Skip to content

Commit 5ff4409

Browse files
committed
Stop state pseudo-classes from re-entering the engine
1 parent eaf4233 commit 5ff4409

7 files changed

Lines changed: 457 additions & 4 deletions

File tree

‎.github/workflows/node.js.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,5 @@ jobs:
2424
- run: npm run upstream:clone
2525
- run: npm run upstream:verify
2626
- run: npx playwright install --with-deps chromium
27+
- run: npm run test:browser
2728
- run: npm run test:upstream

‎package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@
9898
"test:package": "node test/jsdom-adapter-package.mts",
9999
"test:upstream": "node scripts/build.mts && playwright test --config playwright.config.mts",
100100
"upstream:clone": "node scripts/git-partial-submodule.mts clone",
101-
"upstream:verify": "node scripts/git-partial-submodule.mts verify"
101+
"upstream:verify": "node scripts/git-partial-submodule.mts verify",
102+
"test:browser": "NWSAPI_BROWSER=1 vitest run --config .config/vitest.config.mts"
102103
}
103104
}

‎src/nwsapi.mts‎

Lines changed: 51 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,10 @@
3939
root = doc.documentElement,
4040
slice = Array.prototype.slice,
4141

42+
// Factory fallback for documents without a window.
43+
ELEMENT_PROTO = global.Element && global.Element.prototype,
44+
FACTORY_MATCHES = ELEMENT_PROTO && ELEMENT_PROTO.matches,
45+
4246
HSP = '\\x20\\t',
4347
VSP = '\\r\\n\\f',
4448
WSP = '[' + HSP + VSP + ']',
@@ -778,20 +782,64 @@
778782
return false;
779783
},
780784

785+
// Called during document setup only when legacy mode needs an alias.
786+
legacyMatcher =
787+
function(proto) {
788+
return proto && (proto.webkitMatchesSelector ||
789+
proto.mozMatchesSelector || proto.msMatchesSelector);
790+
},
791+
781792
// use the native selector state when it is available; when NWSAPI has
782793
// installed itself, _matches retains the native implementation
783794
matchesNative =
784795
function(node, selector) {
785-
var matcher = _matches || node.matches || node.webkitMatchesSelector ||
786-
node.mozMatchesSelector || node.msMatchesSelector;
787-
if (!matcher) return false;
796+
var view, proto, matcher, ownerDoc = node.ownerDocument || doc;
797+
// Record delegation before doing any lookup. Nested calls must not
798+
// replace the document record belonging to the outer matcher.
799+
if (matchingNative) { matchingNative.delegates = true; return false; }
800+
if (ownerDoc !== matcherDoc) {
801+
if (matcherCache === null) { matcherCache = createWeakMap(); }
802+
matcherDoc = ownerDoc;
803+
matcherRecord = matcherCache && matcherCache.get(ownerDoc);
804+
if (!matcherRecord) {
805+
view = ownerDoc.defaultView;
806+
proto = view && view.Element && view.Element.prototype;
807+
matcherRecord = {
808+
matcher: _matches || (proto && (proto.matches ||
809+
(Config.LEGACY && legacyMatcher(proto)))) || FACTORY_MATCHES ||
810+
(Config.LEGACY && proto !== ELEMENT_PROTO ? legacyMatcher(ELEMENT_PROTO) : undefined),
811+
delegates: false
812+
};
813+
if (matcherCache) { matcherCache.set(ownerDoc, matcherRecord); }
814+
}
815+
}
816+
// install() may supply a saved matcher after this document was cached.
817+
if (_matches && _matches !== matcherRecord.matcher) {
818+
matcherRecord.matcher = _matches;
819+
matcherRecord.delegates = false;
820+
}
821+
matcher = matcherRecord.matcher;
822+
if (!matcher || matcherRecord.delegates) { return false; }
788823
try {
824+
matchingNative = matcherRecord;
789825
return matcher.call(node, selector);
790826
} catch (e) {
791827
return false;
828+
} finally {
829+
matchingNative = null;
792830
}
793831
},
794832

833+
// The active record is marked directly on re-entry, even if the host throws.
834+
matchingNative = null,
835+
836+
// Consecutive queries avoid a WeakMap lookup. Retain other documents weakly
837+
// so switching realms does not repeat delegation detection. Allocate after
838+
// legacy configuration, on first use; undefined selects the bounded fallback.
839+
matcherDoc = null,
840+
matcherRecord = null,
841+
matcherCache = null,
842+
795843
// :open and :closed have a portable DOM state for details and dialog.
796844
// Native matching extends support to host-language states such as pickers.
797845
isOpen =
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
const __dirname = import.meta.dirname
2+
import { createRequire } from 'node:module'
3+
const require = createRequire(import.meta.url)
4+
const assert = require('node:assert/strict')
5+
const { readFileSync } = require('node:fs')
6+
const { resolve } = require('node:path')
7+
import { test } from 'vitest'
8+
const { chromium } = require('@playwright/test')
9+
const source = readFileSync(resolve(__dirname, '../src/nwsapi.js'), 'utf8')
10+
11+
test.skipIf(!process.env.NWSAPI_BROWSER)(
12+
'browser state stays live across factory shapes, documents, and install()',
13+
async t => {
14+
const browser = await chromium.launch()
15+
t.onTestFinished(() => browser.close())
16+
for (const mode of [
17+
'script',
18+
'document',
19+
'window',
20+
'install-before',
21+
'install-after',
22+
]) {
23+
await (async () => {
24+
const page = await browser.newPage()
25+
try {
26+
await page.setContent(
27+
'<!doctype html><dialog></dialog><div popover></div><iframe></iframe>',
28+
)
29+
const results = await page.evaluate(
30+
({ source, mode }) => {
31+
const native = Element.prototype.matches
32+
let nw
33+
if (mode === 'document' || mode === 'window') {
34+
const module = { exports: {} }
35+
new Function('module', 'exports', source)(
36+
module,
37+
module.exports,
38+
)
39+
nw = module.exports(
40+
mode === 'window' ? window : { document, DOMException },
41+
)
42+
} else {
43+
// eslint-disable-next-line no-eval -- Exercise the built browser-global bootstrap.
44+
;(0, eval)(source)
45+
nw = NW.Dom
46+
}
47+
const other = document.querySelector('iframe').contentDocument
48+
other.body.innerHTML = '<dialog></dialog><div popover></div>'
49+
const pairs = [document, other].map(doc => [
50+
doc.querySelector('dialog'),
51+
doc.querySelector('[popover]'),
52+
])
53+
if (mode === 'install-before') nw.install()
54+
const results = []
55+
function check() {
56+
for (let i = 0; i < 3; i++)
57+
for (const [dialog, popover] of pairs) {
58+
results.push([
59+
nw.match(':modal', dialog),
60+
native.call(dialog, ':modal'),
61+
])
62+
results.push([
63+
nw.match(':popover-open', popover),
64+
native.call(popover, ':popover-open'),
65+
])
66+
}
67+
}
68+
check()
69+
if (mode === 'install-after') nw.install()
70+
for (const [dialog, popover] of pairs) {
71+
dialog.showModal()
72+
popover.showPopover()
73+
}
74+
check()
75+
for (const [dialog, popover] of pairs) {
76+
dialog.close()
77+
popover.hidePopover()
78+
}
79+
check()
80+
return results
81+
},
82+
{ source, mode },
83+
)
84+
assert.ok(results.some(([, expected]) => expected === true))
85+
for (const [actual, expected] of results)
86+
assert.equal(actual, expected)
87+
} finally {
88+
await page.close()
89+
}
90+
})()
91+
}
92+
},
93+
)
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
const __dirname = import.meta.dirname
2+
import { createRequire } from 'node:module'
3+
const require = createRequire(import.meta.url)
4+
const assert = require('node:assert/strict')
5+
const { readFileSync } = require('node:fs')
6+
const { resolve } = require('node:path')
7+
import { test } from 'vitest'
8+
const vm = require('node:vm')
9+
const source = readFileSync(resolve(__dirname, '../src/nwsapi.js'), 'utf8')
10+
const createNwsapi = require('../src/nwsapi.js')
11+
// Route jsdom through the adapter from this checkout. Count actual adapter
12+
// instances so the reentry test cannot silently exercise jsdom's default engine.
13+
const { DOMSelector } = createNwsapi
14+
const resolved = require.resolve('@asamuzakjp/dom-selector', {
15+
paths: [require.resolve('jsdom')],
16+
})
17+
const previous = require(resolved)
18+
let creations = 0,
19+
matchCalls = 0,
20+
depth = 0,
21+
peakDepth = 0
22+
require.cache[resolved].exports = {
23+
DOMSelector: class extends DOMSelector {
24+
constructor(...args) {
25+
super(...args)
26+
creations++
27+
const match = this.engine.match
28+
this.engine.match = function (...args) {
29+
matchCalls++
30+
peakDepth = Math.max(peakDepth, ++depth)
31+
try {
32+
if (depth > 20) throw new Error('Reentry safety limit')
33+
return match.apply(this, args)
34+
} finally {
35+
depth--
36+
}
37+
}
38+
}
39+
},
40+
}
41+
const { JSDOM } = (() => {
42+
try {
43+
return require('jsdom')
44+
} finally {
45+
require.cache[resolved].exports = previous
46+
}
47+
})()
48+
const pseudos = [
49+
':modal',
50+
':fullscreen',
51+
':picture-in-picture',
52+
':open',
53+
':closed',
54+
':popover-open',
55+
]
56+
57+
function host(t) {
58+
const dom = new JSDOM('<!doctype html><div popover></div>')
59+
t.onTestFinished(() => dom.window.close())
60+
return dom.window
61+
}
62+
63+
for (const legacy of [false, true])
64+
test(`delegating matchers are called once per document (LEGACY=${legacy})`, t => {
65+
const windows = [host(t), host(t)]
66+
const nw = createNwsapi({ document: windows[0].document })
67+
nw.configure({ LEGACY: legacy })
68+
const calls = [0, 0]
69+
const nodes = windows.map(w => w.document.querySelector('div'))
70+
windows.forEach((w, i) => {
71+
w.Element.prototype.matches = function (selector) {
72+
assert.ok(++calls[i] < 10, 'unbounded recursion')
73+
return nw.match(selector, this)
74+
}
75+
})
76+
for (let i = 0; i < 50; i++) {
77+
for (const node of nodes)
78+
for (const pseudo of pseudos)
79+
assert.equal(nw.match(pseudo, node), false)
80+
}
81+
assert.deepEqual(calls, [1, 1])
82+
})
83+
84+
test('browser bootstrap safely captures an already-delegating prototype', t => {
85+
const window = host(t)
86+
let nw,
87+
calls = 0
88+
window.Element.prototype.matches = function (selector) {
89+
assert.ok(++calls < 10, 'unbounded recursion')
90+
return nw.match(selector, this)
91+
}
92+
const context = { document: window.document, Element: window.Element }
93+
vm.runInNewContext(source, context)
94+
nw = context.NW.Dom
95+
const node = window.document.querySelector('div')
96+
for (let i = 0; i < 50; i++)
97+
assert.equal(nw.match(':popover-open', node), false)
98+
assert.equal(calls, 1)
99+
})
100+
101+
test('the original jsdom Element.matches route uses this engine without recursion', t => {
102+
const window = host(t)
103+
const before = creations
104+
const beforeCalls = matchCalls
105+
peakDepth = 0
106+
const node = window.document.body.firstElementChild
107+
for (let i = 0; i < 50; i++)
108+
for (const pseudo of pseudos) assert.equal(node.matches(pseudo), false)
109+
assert.equal(
110+
creations - before,
111+
1,
112+
'jsdom must exercise the source under test',
113+
)
114+
assert.ok(
115+
matchCalls - beforeCalls <= 301,
116+
'300 calls allow only one delegation probe',
117+
)
118+
assert.ok(peakDepth <= 2, 'the adapter must not hide repeated reentry')
119+
})
120+
121+
test('delegation remains cached when a re-entering matcher subsequently throws', t => {
122+
const window = host(t)
123+
const nw = createNwsapi({ document: window.document })
124+
const node = window.document.querySelector('div')
125+
let calls = 0
126+
window.Element.prototype.matches = function (selector) {
127+
calls++
128+
nw.match(selector, this)
129+
throw new Error('host failed after re-entry')
130+
}
131+
for (let i = 0; i < 10; i++)
132+
assert.equal(nw.match(':popover-open', node), false)
133+
assert.equal(calls, 1)
134+
})
135+
136+
test('an unsupported selector does not disable other host state queries', t => {
137+
const window = host(t)
138+
window.Element.prototype.matches = function (selector) {
139+
if (selector === ':fullscreen') throw new Error('unsupported')
140+
return selector === ':popover-open'
141+
}
142+
const nw = createNwsapi({ document: window.document })
143+
const node = window.document.querySelector('div')
144+
assert.equal(nw.match(':fullscreen', node), false)
145+
assert.equal(nw.match(':popover-open', node), true)
146+
})
147+
148+
test('re-entry involving another document marks the outer record', t => {
149+
const a = host(t),
150+
b = host(t)
151+
const nw = createNwsapi({ document: a.document })
152+
const first = a.document.querySelector('div'),
153+
second = b.document.querySelector('div')
154+
let calls = 0
155+
a.Element.prototype.matches = function (selector) {
156+
calls++
157+
return nw.match(selector, second)
158+
}
159+
b.Element.prototype.matches = () => true
160+
assert.equal(nw.match(':popover-open', first), false)
161+
assert.equal(nw.match(':popover-open', second), true)
162+
assert.equal(nw.match(':popover-open', first), false)
163+
assert.equal(calls, 1)
164+
})
165+
166+
test('hosts without WeakMap retain bounded recursion and the single-document fast path', t => {
167+
const window = host(t)
168+
const context = { module: { exports: {} }, exports: {}, WeakMap: undefined }
169+
vm.runInNewContext(source, context)
170+
const nw = context.module.exports({ document: window.document })
171+
nw.configure({ LEGACY: true })
172+
let calls = 0
173+
window.Element.prototype.matches = function (selector) {
174+
calls++
175+
return nw.match(selector, this)
176+
}
177+
const node = window.document.querySelector('div')
178+
for (let i = 0; i < 50; i++)
179+
assert.equal(nw.match(':popover-open', node), false)
180+
assert.equal(calls, 1)
181+
})

‎test/display-state-testing.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Display-state regression tests
2+
3+
Use Node.js ≥ 22 for the development test runner. Runtime compatibility is unchanged.
4+
5+
```sh
6+
pnpm install
7+
pnpm test
8+
pnpm exec playwright install chromium
9+
pnpm run test:browser
10+
```
11+
12+
The Node suite uses jsdom 30.0.1 and routes its selector-engine import through this checkout's adapter. It also covers alternating documents in modern and legacy mode, browser bootstrap with a delegating prototype, exceptions, nested document changes, and the legacy fallback without WeakMap. Configure legacy mode before the first query when the runtime lacks WeakMap.
13+
14+
The Chromium suite compares modal and popover state with the browser before opening, while open, and after closing. It exercises browser scripts, both CommonJS factory shapes, iframe documents, and installation before and after caching.
15+
16+
Alias tests cover document and factory prototypes. Modern mode reads no prefixed methods; legacy mode caches the selected alias or its absence.

0 commit comments

Comments
 (0)