|
| 1 | +import { test } from 'node:test'; |
| 2 | +import assert from 'node:assert/strict'; |
| 3 | +import { fileURLToPath } from 'node:url'; |
| 4 | +import { build } from 'esbuild'; |
| 5 | +import { DOMParser } from '@xmldom/xmldom'; |
| 6 | + |
| 7 | +// As undom-ng installs under DOMiNATIVE (solid-js): a document whose elements have no |
| 8 | +// getElementsByTagName, which query-selector's import-time probe calls. |
| 9 | +function installForeignDocument() { |
| 10 | + const foreign = { |
| 11 | + createElement: (tag) => ({ nodeName: tag.toUpperCase(), childNodes: [], appendChild(node) { this.childNodes.push(node); return node; } }), |
| 12 | + createComment: (data) => ({ nodeType: 8, data }), |
| 13 | + }; |
| 14 | + globalThis.document = foreign; |
| 15 | + return foreign; |
| 16 | +} |
| 17 | + |
| 18 | +const packageDir = fileURLToPath(new URL('..', import.meta.url)); |
| 19 | + |
| 20 | +/** `source` bundled the way an app bundler would, from this package. */ |
| 21 | +async function load(source) { |
| 22 | + const { outputFiles } = await build({ |
| 23 | + stdin: { contents: source, resolveDir: packageDir, loader: 'ts' }, |
| 24 | + bundle: true, |
| 25 | + format: 'esm', |
| 26 | + write: false, |
| 27 | + platform: 'neutral', |
| 28 | + mainFields: ['module', 'main'], |
| 29 | + }); |
| 30 | + return import('data:text/javascript;base64,' + Buffer.from(outputFiles[0].text).toString('base64') + '#' + Math.random()); |
| 31 | +} |
| 32 | + |
| 33 | +const svg = new DOMParser().parseFromString('<svg xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="g"/></defs><rect class="a"/><rect/></svg>', 'image/svg+xml'); |
| 34 | + |
| 35 | +test('query-selector on its own fails beside a foreign document', async () => { |
| 36 | + installForeignDocument(); |
| 37 | + await assert.rejects(load("export { default } from 'query-selector';"), /getElementsByTagName/); |
| 38 | + delete globalThis.document; |
| 39 | +}); |
| 40 | + |
| 41 | +test('the polyfill loads query-selector beside a foreign document and puts it back', async () => { |
| 42 | + const foreign = installForeignDocument(); |
| 43 | + const { default: querySelector } = await load("export { default } from './DOM/querySelector';"); |
| 44 | + assert.equal(globalThis.document, foreign); |
| 45 | + assert.deepEqual(querySelector('#g', svg.documentElement).map((node) => node.nodeName), ['linearGradient']); |
| 46 | + assert.equal(querySelector('rect', svg.documentElement).length, 2); |
| 47 | + assert.equal(querySelector('rect.a', svg.documentElement).length, 1); |
| 48 | + delete globalThis.document; |
| 49 | +}); |
| 50 | + |
| 51 | +test('without a document nothing is installed', async () => { |
| 52 | + delete globalThis.document; |
| 53 | + await load("export { default } from './DOM/querySelector';"); |
| 54 | + assert.equal('document' in globalThis, false); |
| 55 | +}); |
0 commit comments