Skip to content

Commit 2c91a94

Browse files
committed
Bound native matcher reentry in jsdom
1 parent f6a0bf1 commit 2c91a94

2 files changed

Lines changed: 49 additions & 0 deletions

File tree

‎src/nwsapi.mts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -782,16 +782,23 @@
782782
// installed itself, _matches retains the native implementation
783783
matchesNative =
784784
function(node, selector) {
785+
// A host such as jsdom can delegate matches() back to this engine.
786+
if (matchingNative) return false;
785787
var matcher = _matches || node.matches || node.webkitMatchesSelector ||
786788
node.mozMatchesSelector || node.msMatchesSelector;
787789
if (!matcher) return false;
788790
try {
791+
matchingNative = true;
789792
return matcher.call(node, selector);
790793
} catch (e) {
791794
return false;
795+
} finally {
796+
matchingNative = false;
792797
}
793798
},
794799

800+
matchingNative = false,
801+
795802
// :open and :closed have a portable DOM state for details and dialog.
796803
// Native matching extends support to host-language states such as pickers.
797804
isOpen =

‎test/native-reentry.test.mts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { test, expect } from 'vitest'
2+
import { createRequire } from 'node:module'
3+
import { JSDOM } from 'jsdom'
4+
5+
const require = createRequire(import.meta.url)
6+
const factory = require('../src/nwsapi.js')
7+
8+
test('host matcher delegation stays bounded', t => {
9+
const { window } = new JSDOM('<div></div>')
10+
t.onTestFinished(() => window.close())
11+
const engine = factory(window)
12+
const node = window.document.body.firstElementChild
13+
for (const selector of [
14+
':open',
15+
':closed',
16+
':modal',
17+
':fullscreen',
18+
':picture-in-picture',
19+
]) {
20+
let calls = 0
21+
node.matches = value => {
22+
if (++calls > 4) throw new Error('recursive host matcher')
23+
return engine.match(value, node)
24+
}
25+
expect(engine.match(selector, node), selector).toBe(false)
26+
expect(calls).toBeLessThanOrEqual(2)
27+
expect(calls).toBeGreaterThan(0)
28+
}
29+
})
30+
31+
test('native matching recovers after exceptions and keeps host state', t => {
32+
const { window } = new JSDOM('<div></div>')
33+
t.onTestFinished(() => window.close())
34+
const engine = factory(window)
35+
const node = window.document.body.firstElementChild
36+
node.matches = () => {
37+
throw new Error('unsupported')
38+
}
39+
expect(engine.match(':open', node)).toBe(false)
40+
node.matches = () => true
41+
expect(engine.match(':open', node)).toBe(true)
42+
})

0 commit comments

Comments
 (0)