From c58e5c29e1a7f96d5163383b08b4cae4f05987d4 Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Thu, 3 Dec 2026 00:16:58 -0600 Subject: [PATCH] Add WPT URL variants and document lifecycle events --- packages/ui/src/dom.ts | 18 ++- packages/ui/src/events.ts | 33 +++--- packages/ui/src/window.ts | 26 +++++ packages/ui/wpt.config.ts | 24 +++- packages/web-platform-tests/README.md | 47 +++++--- packages/web-platform-tests/src/config.ts | 13 ++- .../web-platform-tests/src/node/isolated.ts | 11 +- .../web-platform-tests/src/node/location.ts | 35 ++++++ packages/web-platform-tests/src/node/run.ts | 107 +++++++++++------- .../web-platform-tests/src/node/source.ts | 35 +++++- .../web-platform-tests/src/node/window.ts | 65 ----------- .../web-platform-tests/src/node/worker.ts | 4 +- packages/web-platform-tests/src/vitest.ts | 4 +- .../web-platform-tests/src/vitest/runner.ts | 78 +++++++++---- 14 files changed, 316 insertions(+), 184 deletions(-) create mode 100644 packages/ui/src/window.ts create mode 100644 packages/web-platform-tests/src/node/location.ts delete mode 100644 packages/web-platform-tests/src/node/window.ts diff --git a/packages/ui/src/dom.ts b/packages/ui/src/dom.ts index 8684d28b..c4d9feff 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -1,10 +1,12 @@ /* oxlint-disable bombshell-dev/no-generic-error -- Web IDL requires TypeError for missing arguments. */ +/* oxlint-disable bombshell-dev/exported-function-async -- DOM apis are synchronous. */ import { findElement, findElements, querySelector } from './css-select.ts'; import { asciiUppercase, asciiLowercase } from './ascii.ts'; import { exposeAttributes, NamedNodeMap } from './named-node-map.ts'; import { HTMLCollection } from './html-collection.ts'; import { StyleDeclaration } from './style.ts'; +import type { Window } from './window.ts'; import { addEventListener, removeEventListener, @@ -101,11 +103,7 @@ export abstract class Node implements EventTarget { } dispatchEvent(this: EventTarget, event: Event): boolean { - return dispatch(this, { - event, - isTrusted: false, - path: this instanceof Node ? lineage(this) : [this], - }); + return dispatch(this, { event, isTrusted: false }); } hasChildNodes(): boolean { @@ -295,6 +293,10 @@ export class Document extends Node { readonly implementation: DOMImplementation; + get defaultView(): Window | null { + return null; + } + readonly #notify: () => void; #factory: (...params: ConstructorParameters) => Element; @@ -878,12 +880,6 @@ export class HTMLUnknownElement extends HTMLElement {} export class XMLDocument extends Document {} -function* lineage(node: Node): Iterable { - for (let current: Node | null = node; current; current = current.parentNode) { - yield current; - } -} - /** internal helpers **/ function getTextContent(node: Element | DocumentFragment): string { diff --git a/packages/ui/src/events.ts b/packages/ui/src/events.ts index c63023c2..dfb1a4da 100644 --- a/packages/ui/src/events.ts +++ b/packages/ui/src/events.ts @@ -1,6 +1,7 @@ /* oxlint-disable bombshell-dev/no-generic-error -- Web IDL requires TypeError for missing arguments. */ import { asciiLowercase } from './ascii.ts'; +import { Document, Node } from './dom.ts'; const NONE = 0; const CAPTURING_PHASE = 1; @@ -19,7 +20,6 @@ export function addEventListener( options?: ListenerOptions | boolean; }, ): void { - assertEventTarget(target); type = `${type}`; if (listener != null && typeof listener !== 'function' && typeof listener !== 'object') { throw new TypeError('Event listener must be a function or an object'); @@ -85,7 +85,6 @@ export function removeEventListener( options?: EventListenerOptions | boolean; }, ): void { - assertEventTarget(target); type = `${type}`; if (listener != null && typeof listener !== 'function' && typeof listener !== 'object') { throw new TypeError('Event listener must be a function or an object'); @@ -117,13 +116,8 @@ export function createEvent(eventInterface: string): Event { export function dispatch( node: EventTarget, - { - event, - isTrusted, - path = [node], - }: { event: Event; isTrusted: boolean; path?: Iterable }, + { event, isTrusted, target = node }: { event: Event; isTrusted: boolean; target?: EventTarget }, ): boolean { - assertEventTarget(node); if (!(event instanceof Event)) { throw new TypeError('dispatchEvent requires an Event'); } @@ -134,10 +128,23 @@ export function dispatch( if (!state.initialized) { throw new DOMException('Event is not initialized', 'InvalidStateError'); } + const path: EventTarget[] = [node]; + if (node instanceof Node) { + let root = node; + while (root.parentNode) { + root = root.parentNode; + path.push(root); + } + // A document's event parent is null for "load", so its path stops at the document. + // https://dom.spec.whatwg.org/#interface-document + if (root instanceof Document && root.defaultView && event.type !== 'load') { + path.push(root.defaultView); + } + } state.dispatching = true; - state.target = node; + state.target = target; state.isTrusted = isTrusted; - state.path = [...path]; + state.path = path; const invoke = (currentTarget: EventTarget, capture: boolean): void => { if (state.stopped) { @@ -206,12 +213,6 @@ export function dispatch( } } -function assertEventTarget(target: EventTarget): void { - if (!(target instanceof EventTarget)) { - throw new TypeError('Event listener methods require an EventTarget'); - } -} - function stateFor(event: Event): DispatchState { const existing = eventStates.get(event); if (existing) { diff --git a/packages/ui/src/window.ts b/packages/ui/src/window.ts new file mode 100644 index 00000000..4f25faa0 --- /dev/null +++ b/packages/ui/src/window.ts @@ -0,0 +1,26 @@ +/* oxlint-disable bombshell-dev/exported-function-async -- DOM apis are synchronous. */ + +import { Node, type Document } from './dom.ts'; + +export function createWindow(document: Document): Window { + const window = new Window(); + return Window.init(window, document); +} + +export class Window extends EventTarget { + declare readonly document: Document; + + static init(window: Window, document: Document): Window { + Object.defineProperty(window, 'document', { get: () => document }); + Object.defineProperty(document, 'defaultView', { get: () => window }); + return window; + } +} + +for (const name of ['addEventListener', 'removeEventListener', 'dispatchEvent'] as const) { + Object.defineProperty( + Window.prototype, + name, + Object.getOwnPropertyDescriptor(Node.prototype, name)!, + ); +} diff --git a/packages/ui/wpt.config.ts b/packages/ui/wpt.config.ts index fe1dd412..f8b477df 100644 --- a/packages/ui/wpt.config.ts +++ b/packages/ui/wpt.config.ts @@ -23,9 +23,18 @@ import { import { NamedNodeMap } from './src/named-node-map.ts'; import { HTMLCollection } from './src/html-collection.ts'; import { StyleDeclaration } from './src/style.ts'; +import { dispatch } from './src/events.ts'; +import { Window } from './src/window.ts'; -const config: WPTConfig = { - createDocument: () => createHTMLDocument(() => {}), +const config: WPTConfig = { + createWindow(scope) { + const window = Object.setPrototypeOf(scope, Window.prototype) as Window; + return Window.init( + window, + createHTMLDocument(() => {}), + ); + }, + dispatchEvent: dispatch, globals: { AbortController: globalThis.AbortController, Attr, @@ -52,9 +61,18 @@ const config: WPTConfig = { NamedNodeMap, Node, Text, + Window, XMLDocument, }, include: { + 'html/syntax/parsing/the-end.html': ['DOMContentLoaded', 'load'], + 'html/browsers/the-window-object/Document-defaultView.html': [ + 'Document in a browsing context', + 'Document created with the Document constructor', + 'Document created with createDocument', + 'Document created with createHTMLDocument', + // DOMParser remains unsupported. + ], 'html/dom/elements/global-attributes/id-name.html': true, 'html/dom/elements/global-attributes/id-attribute.html': [ 'After setting id via id attribute, getElementById find the element by the new id.', @@ -400,6 +418,8 @@ const config: WPTConfig = { exclude: { '**': true }, // excluded cases that run for their shared state, but we don't wait for forceTimeout: { + // PageTransitionEvent and pageshow remain unsupported. + 'html/syntax/parsing/the-end.html': ['pageshow', 'order'], // Waits on an iframe load the fixture cannot deliver. 'dom/nodes/Node-parentNode.html': ['Removed iframe'], }, diff --git a/packages/web-platform-tests/README.md b/packages/web-platform-tests/README.md index da59f512..ffeb97c6 100644 --- a/packages/web-platform-tests/README.md +++ b/packages/web-platform-tests/README.md @@ -45,16 +45,20 @@ implementation tests, and run the configured WPT cases. ## Configuration -A consumer needs only a `wpt.config.ts`. It supplies a document factory and the +A consumer needs only a `wpt.config.ts`. It supplies a window factory and the implementation's global bindings, then selects upstream source paths and original case names. See the [UI configuration](../ui/wpt.config.ts). ```ts import type { WPTConfig } from "@bomb.sh/web-platform-tests/config"; import { createHTMLDocument, Node, Document, Element } from "./dom.ts"; +import { Window } from "./window.ts"; export default { - createDocument: () => createHTMLDocument(), + createWindow(scope) { + Object.setPrototypeOf(scope, Window.prototype); + return Window.init(scope as Window, createHTMLDocument()); + }, globals: { Node, Document, Element }, include: { "dom/nodes/Node-parentNode.html": ["Document", "Root element"], @@ -68,10 +72,22 @@ export default { } satisfies WPTConfig; ``` -`createDocument()` returns a fresh document for each upstream file. The harness -populates it with that file's HTML and installs `document.defaultView`. +`createWindow(scope)` initializes the supplied worker global as the implementation's +window and returns that same object, with a fresh `document` for each upstream file +and URL variant. The factory establishes `window.document` and +`document.defaultView`; the harness preserves those associations. This keeps +`globalThis === window` and `window === document.defaultView` in upstream scripts. +The harness binds the window's event methods to support bare `addEventListener`, +`removeEventListener`, and `dispatchEvent` calls. +It populates the document with that file's HTML and installs `document.location`, +`document.URL`, and `document.documentURI`. Window and document +share the fixture's location. URL reads are supported; navigation fails explicitly. +Optional `dispatchEvent(target, options)` +dispatches trusted host events; options contain `event`, `isTrusted`, and an optional +legacy `target` override used for window load. The UI configuration supplies this +hook using its shared event dispatcher. `globals` supplies the constructors and other bindings the tests use. `timeout` -sets the maximum execution time per file in milliseconds; the default is 15,000. +sets the maximum execution time per variant in milliseconds; the default is 15,000. Source keys support `*` within a path segment and `**` across directories. Values are `true` for every subtest in a source or arrays of exact names and regular @@ -88,14 +104,14 @@ whose unfinished work isn't needed by the selected tests. `framework()` returns selectors for the DOM features used by React, Preact, Vue, Solid, or Svelte. Pass them to `include` with `exclude: { '**': true }` to run -that profile against the consumer's document factory and globals: +that profile against the consumer's window factory and globals: ```ts import { framework, type WPTConfig } from "@bomb.sh/web-platform-tests"; -import { createDocument, globals } from "./dom.ts"; +import { createWindow, globals } from "./fixture.ts"; export default { - createDocument, + createWindow, globals, include: framework("preact"), exclude: { "**": true }, @@ -127,17 +143,23 @@ fail the checks. These tests run with `pnpm test` and in CI. The harness parses HTML with parse5, populates the implementation's document, and executes the original inline scripts and static local helpers in source -order within one fresh Node worker per file. It loads upstream `testharness.js` in -its shell environment and delivers window `load` after the scripts finish. +order within one fresh Node worker per URL variant. HTML `meta name="variant"` +and JavaScript `META: variant` declarations select query/fragment variants; each +gets a separate result group while selectors continue to match original case names. +It loads upstream `testharness.js` in its Window environment with rendering and +cross-window reporting disabled. After the scripts +finish, document readiness changes from `loading` to `interactive`, the harness +dispatches bubbling `DOMContentLoaded` at the document, readiness becomes +`complete`, and window `load` follows with the legacy document target. Script elements are fixture nodes; parsing them does not execute their contents. The worker loads the consumer configuration before installing its fixture globals, then executes the harness and test scripts in that same JavaScript realm. Consumer methods, native Node APIs, and fixture scripts therefore share the built-in error constructors and prototypes; no error-prototype patches or error-constructor -bindings in `globals` are needed. Each worker is terminated after its file, so +bindings in `globals` are needed. Each worker is terminated after its variant, so script globals, top-level lexical declarations, and module state cannot leak into -the next file. The file's `timeout` includes worker startup and configuration +the next variant. The variant's `timeout` includes worker startup and configuration loading. The harness reports ordinary timeouts at that shared deadline; a parent watchdog allows 250 ms for those results to arrive before terminating an unresponsive worker, including one blocked in an asynchronous callback. @@ -155,7 +177,6 @@ the runner waits for it normally. The UI lists `Removed iframe` in The runner supports HTML sources and window `.any.js`/`.window.js` sources with static helpers. It does not implement iframe navigation, parser-driven script timing, module/async/defer scripts, server substitutions, or remote helpers. -Window event delegation currently requires extensible event objects. Unsupported source features fail explicitly. Selecting part of a file does not claim coverage of its remaining subtests or complete standards conformance. diff --git a/packages/web-platform-tests/src/config.ts b/packages/web-platform-tests/src/config.ts index fa80a568..74c87f19 100644 --- a/packages/web-platform-tests/src/config.ts +++ b/packages/web-platform-tests/src/config.ts @@ -1,9 +1,14 @@ /** Source globs select files; arrays select original WPT names within each file. */ export type WPTSelectors = Readonly>; -export interface WPTConfig { - /** Create a fresh implementation document for each upstream source file. */ - createDocument(): unknown; +export interface WPTConfig { + /** Initialize and return the supplied worker global with a fresh associated document. */ + createWindow(scope: object): EventTarget & { readonly document: TDocument }; + /** Dispatch host events, including trusted lifecycle events and load's document target. */ + dispatchEvent?( + target: EventTarget, + options: { event: Event; isTrusted: boolean; target?: EventTarget }, + ): boolean; /** DOM constructors and other implementation bindings exposed to upstream scripts. */ globals?: Record; include?: WPTSelectors; @@ -13,7 +18,7 @@ export interface WPTConfig { * Maps exact source paths to arrays of original case names. */ forceTimeout?: Readonly>; - /** Maximum execution time per source file, in milliseconds. Defaults to 15 seconds. */ + /** Maximum execution time per source variant, in milliseconds. Defaults to 15 seconds. */ timeout?: number; } diff --git a/packages/web-platform-tests/src/node/isolated.ts b/packages/web-platform-tests/src/node/isolated.ts index dc05bb3b..e52f017a 100644 --- a/packages/web-platform-tests/src/node/isolated.ts +++ b/packages/web-platform-tests/src/node/isolated.ts @@ -1,27 +1,32 @@ import { clearTimeout, setTimeout } from 'node:timers'; import { Worker } from 'node:worker_threads'; import type { WPTFileResult } from './run.ts'; +import type { SourceFile } from './source.ts'; interface WPTFileRequest { file: string; sourceRoot: string; configFile: string; + source: SourceFile; + variant: string; } export interface WPTWorkerData extends WPTFileRequest { deadline: number; } -/** Give each source file a fresh realm for both its implementation and scripts. */ +/** Give each source variant a fresh realm for both its implementation and scripts. */ export async function runWPTFile({ file, sourceRoot, configFile, + source, + variant, timeout = 15_000, }: WPTFileRequest & { timeout?: number }): Promise { const deadline = Date.now() + timeout; const worker = new Worker(new URL('./worker.mjs', import.meta.url), { - workerData: { file, sourceRoot, configFile, deadline } satisfies WPTWorkerData, + workerData: { file, sourceRoot, configFile, source, variant, deadline } satisfies WPTWorkerData, }); const completion = Promise.withResolvers(); // Let an ordinary upstream timeout report its subtests before terminating a blocked worker. @@ -31,7 +36,7 @@ export async function runWPTFile({ tests: [], status: { status: 2, - message: `WPT worker did not complete within ${timeout}ms: ${file}`, + message: `WPT worker did not complete within ${timeout}ms: ${file}${variant}`, }, }); }, diff --git a/packages/web-platform-tests/src/node/location.ts b/packages/web-platform-tests/src/node/location.ts new file mode 100644 index 00000000..59c1a423 --- /dev/null +++ b/packages/web-platform-tests/src/node/location.ts @@ -0,0 +1,35 @@ +/* oxlint-disable bombshell-dev/exported-function-async -- Fixture location setup is synchronous. */ + +class UnsupportedNavigationError extends Error {} + +/** Expose the current fixture URL without pretending to navigate between documents. */ +export function createLocation(url: URL): object { + const navigate = (): never => { + throw new UnsupportedNavigationError('WPT document navigation is not supported'); + }; + const location = { + assign: navigate, + replace: navigate, + reload: navigate, + toString: () => url.href, + [Symbol.toStringTag]: 'Location', + }; + for (const name of [ + 'href', + 'origin', + 'protocol', + 'host', + 'hostname', + 'port', + 'pathname', + 'search', + 'hash', + ] as const) { + Object.defineProperty(location, name, { + get: () => url[name], + set: navigate, + enumerable: true, + }); + } + return location; +} diff --git a/packages/web-platform-tests/src/node/run.ts b/packages/web-platform-tests/src/node/run.ts index 62008109..d7075c42 100644 --- a/packages/web-platform-tests/src/node/run.ts +++ b/packages/web-platform-tests/src/node/run.ts @@ -7,8 +7,8 @@ import type { WPTConfig } from '../config.ts'; import { selectsTest } from '../vitest/selection.ts'; import { populateDocument } from './document.ts'; import { installNamedProperties } from './named-properties.ts'; -import { loadSource, type SourceScript } from './source.ts'; -import { Window } from './window.ts'; +import { loadSource, type SourceFile, type SourceScript } from './source.ts'; +import { createLocation } from './location.ts'; export interface WPTTestResult { name: string; @@ -49,11 +49,15 @@ export async function runWPTFile({ file, sourceRoot, config, + source: providedSource, + variant = '', deadline = Date.now() + (config.timeout ?? 15_000), }: { file: string; sourceRoot: string; config: WPTConfig; + source?: SourceFile; + variant?: string; deadline?: number; }): Promise { const results: WPTTestResult[] = []; @@ -78,13 +82,21 @@ export async function runWPTFile({ if (!Number.isFinite(timeout) || timeout <= 0) { throw new WPTExecutionError('The WPT timeout must be a positive number of milliseconds'); } - const source = await loadSource(file, sourceRoot); + const source = providedSource ?? (await loadSource(file, sourceRoot)); const rootURL = pathToFileURL(sourceRoot.endsWith('/') ? sourceRoot : `${sourceRoot}/`); const sourcePath = decodeURIComponent(pathToFileURL(file).href.slice(rootURL.href.length)); + const wrapperPath = sourcePath.replace(/\.(any|window)\.js$/, '.$1.html'); + const url = new URL(variant, new URL(wrapperPath, 'https://web-platform.test/')); + const location = createLocation(url); const harnessFile = fileURLToPath(new URL('resources/testharness.js', rootURL)); const harnessCode = await readFile(harnessFile, 'utf8'); const scope = globalThis as unknown as Record; - const window = new Window(scope); + const window = config.createWindow(scope); + if (window !== (scope as object)) { + throw new WPTExecutionError( + 'createWindow() must initialize and return the supplied global scope', + ); + } const execute = (script: SourceScript): unknown => new Script(script.code, { filename: script.file, @@ -94,7 +106,7 @@ export async function runWPTFile({ const invoke = (callback: (...args: unknown[]) => void, args: unknown[]): void => { if (!finished) { try { - callback.apply(scope, args); + callback.apply(window, args); } catch (error) { onError(error); } @@ -102,13 +114,15 @@ export async function runWPTFile({ }; const globals = { ...config.globals, - window: scope, - self: scope, - console, - // Delegate events to the fixture window while exposing the worker global to listeners. addEventListener: window.addEventListener.bind(window), removeEventListener: window.removeEventListener.bind(window), dispatchEvent: window.dispatchEvent.bind(window), + window, + self: window, + parent: window, + top: window, + opener: null, + console, setTimeout(callback: (...args: unknown[]) => void, delay = 0, ...args: unknown[]) { const timer = setTimeout(() => { timers.delete(timer); @@ -140,21 +154,44 @@ export async function runWPTFile({ }); } scope.clearInterval = scope.clearTimeout; - // Upstream supplies its shell environment, assertions, scheduling, and cleanup. - // Keep its environment view in shell mode, including later title/stack lookups. - // Test scripts still see the actual window and document through self. - scope.self = new Proxy( - {}, - { - get: (_, key) => Reflect.get(scope, key), - set: (_, key, value) => Reflect.set(scope, key, value), - has: (_, key) => key !== 'document' && Reflect.has(scope, key), + const document = window.document as Document; + const locationDescriptor = { + get: () => location, + set: () => { + throw new WPTExecutionError('WPT document navigation is not supported'); }, - ); + enumerable: true, + configurable: true, + }; + Object.defineProperty(scope, 'location', locationDescriptor); + Object.defineProperties(document, { + location: locationDescriptor, + URL: { get: () => url.href, enumerable: true, configurable: true }, + documentURI: { get: () => url.href, enumerable: true, configurable: true }, + }); + const fire = ( + target: EventTarget, + { event, target: legacyTarget }: { event: Event; target?: EventTarget }, + ): void => { + if (config.dispatchEvent) { + config.dispatchEvent(target, { event, isTrusted: true, target: legacyTarget }); + } else { + Object.defineProperty(event, 'isTrusted', { value: true, configurable: true }); + if (legacyTarget) { + Object.defineProperty(event, 'target', { value: legacyTarget, configurable: true }); + } + target.dispatchEvent(event); + } + }; + let readyState: DocumentReadyState = 'loading'; + Object.defineProperty(document, 'readyState', { + get: () => readyState, + enumerable: true, + configurable: true, + }); execute({ file: harnessFile, code: harnessCode }); - scope.self = scope; const harness = scope as unknown as Harness; - harness.setup({ output: false }); + harness.setup({ output: false, message_events: [], explicit_timeout: true }); onError = (error): void => { const event = new Event('error', { cancelable: true }); Object.defineProperties(event, { @@ -163,12 +200,12 @@ export async function runWPTFile({ }); // Let upstream's error handler honor allow_uncaught_exception and let // EventWatcher observe native listener errors just as window errors. - window.dispatchEvent(event); + fire(window, { event }); }; onRejection = (reason): void => { const event = new Event('unhandledrejection', { cancelable: true }); Object.defineProperty(event, 'reason', { value: reason }); - window.dispatchEvent(event); + fire(window, { event }); }; process.on('uncaughtException', onError); process.on('unhandledRejection', onRejection); @@ -204,13 +241,6 @@ export async function runWPTFile({ status: { status: status.status, message: status.message, stack: status.stack }, }); }); - const document = config.createDocument() as Document; - Object.defineProperty(scope, 'document', { value: document, enumerable: true }); - Object.defineProperty(document, 'defaultView', { - get: () => scope, - enumerable: true, - configurable: true, - }); if (source.title !== undefined) { scope.META_TITLE = source.title; } @@ -232,15 +262,16 @@ export async function runWPTFile({ ); for (const script of source.scripts) { execute(script); + await Promise.resolve(); } - execute({ - file: 'wpt:load', - code: `{ - const event = new Event('load'); - Object.defineProperty(event, 'target', { value: document, configurable: true }); - window.dispatchEvent(event); - }`, - }); + readyState = 'interactive'; + fire(document, { event: new Event('readystatechange') }); + await setImmediate(); + fire(document, { event: new Event('DOMContentLoaded', { bubbles: true }) }); + await setImmediate(); + readyState = 'complete'; + fire(document, { event: new Event('readystatechange') }); + fire(window, { event: new Event('load'), target: document }); loaded = true; finishUnselected(); const result = await completion.promise; diff --git a/packages/web-platform-tests/src/node/source.ts b/packages/web-platform-tests/src/node/source.ts index 8fee5b39..6f77163a 100644 --- a/packages/web-platform-tests/src/node/source.ts +++ b/packages/web-platform-tests/src/node/source.ts @@ -12,6 +12,7 @@ export interface SourceScript { export interface SourceFile { html: string; scripts: SourceScript[]; + variants: string[]; title?: string; } @@ -51,10 +52,13 @@ export async function loadSource(file: string, sourceRoot: string): Promise name.trim() === 'window')) { throw new UnsupportedSourceError( `Only the window variant of JavaScript WPT files is supported: ${path}`, @@ -71,7 +75,7 @@ export async function loadSource(file: string, sourceRoot: string): Promise child.value) .join(''); + } else if ( + node.tagName === 'meta' && + node.namespaceURI === 'http://www.w3.org/1999/xhtml' && + node.attrs.some(({ name, value }) => name === 'name' && value === 'variant') + ) { + const content = node.attrs.find(({ name }) => name === 'content'); + if (content) { + variants.push(content.value); + } } } if ('childNodes' in node) { @@ -133,7 +146,21 @@ export async function loadSource(file: string, sourceRoot: string): Promise(); - - constructor(scope: object) { - super(); - this.#scope = scope; - // Whole WPT files register hundreds of load listeners on the same window. - setMaxListeners(0, this); - } - - override addEventListener( - type: string, - callback: EventListenerOrEventListenerObject | null, - options?: AddEventListenerOptions | boolean, - ): void { - if (typeof callback === 'function') { - let listener = this.#listeners.get(callback); - if (!listener) { - listener = (event) => Reflect.apply(callback, this.#scope, [event]); - this.#listeners.set(callback, listener); - } - super.addEventListener(type, listener, options); - } else { - super.addEventListener(type, callback, options); - } - } - - override removeEventListener( - type: string, - callback: EventListenerOrEventListenerObject | null, - options?: EventListenerOptions | boolean, - ): void { - super.removeEventListener( - type, - typeof callback === 'function' ? (this.#listeners.get(callback) ?? callback) : callback, - options, - ); - } - - override dispatchEvent(event: Event): boolean { - const retarget = (target: EventTarget | null): object | null => - target === this ? this.#scope : target; - const descriptors: PropertyDescriptorMap = { - target: { get: () => retarget(getTarget.call(event)) }, - currentTarget: { get: () => retarget(getCurrentTarget.call(event)) }, - srcElement: { get: () => event.target }, - composedPath: { value: () => composedPath.call(event).map(retarget), writable: true }, - }; - for (const [name, descriptor] of Object.entries(descriptors)) { - // Preserve explicit targets, including document on the window load event. - if (!Object.hasOwn(event, name)) { - Object.defineProperty(event, name, { ...descriptor, configurable: true }); - } - } - return super.dispatchEvent(event); - } -} diff --git a/packages/web-platform-tests/src/node/worker.ts b/packages/web-platform-tests/src/node/worker.ts index 54fefae3..7b87ce34 100644 --- a/packages/web-platform-tests/src/node/worker.ts +++ b/packages/web-platform-tests/src/node/worker.ts @@ -6,7 +6,7 @@ import { runWPTFile } from './run.ts'; class WPTWorkerError extends Error {} -const { file, sourceRoot, configFile, deadline } = workerData as WPTWorkerData; +const { file, sourceRoot, configFile, source, variant, deadline } = workerData as WPTWorkerData; // Import the consumer here so its functions and native errors belong to this realm. const loaded = await loadConfigFromFile({ command: 'serve', mode: 'test' }, configFile); if (!loaded) { @@ -14,4 +14,4 @@ if (!loaded) { } const config = loaded.config as unknown as WPTConfig; // oxlint-disable-next-line unicorn/require-post-message-target-origin -- Node worker ports have no origin. -parentPort!.postMessage(await runWPTFile({ file, sourceRoot, config, deadline })); +parentPort!.postMessage(await runWPTFile({ file, sourceRoot, config, source, variant, deadline })); diff --git a/packages/web-platform-tests/src/vitest.ts b/packages/web-platform-tests/src/vitest.ts index 8d9895b4..9c3c0f00 100644 --- a/packages/web-platform-tests/src/vitest.ts +++ b/packages/web-platform-tests/src/vitest.ts @@ -114,8 +114,8 @@ async function startWPT( } onDependencies?.(loaded.dependencies); const config = loaded.config as unknown as WPTConfig; - if (typeof config.createDocument !== 'function') { - throw new WPTConfigurationError('WPT configuration must provide createDocument().'); + if (typeof config.createWindow !== 'function') { + throw new WPTConfigurationError('WPT configuration must provide createWindow().'); } if (config.timeout !== undefined && (!Number.isFinite(config.timeout) || config.timeout <= 0)) { throw new WPTConfigurationError('WPT timeout must be a positive number of milliseconds.'); diff --git a/packages/web-platform-tests/src/vitest/runner.ts b/packages/web-platform-tests/src/vitest/runner.ts index aa03b881..1e8d3e14 100644 --- a/packages/web-platform-tests/src/vitest/runner.ts +++ b/packages/web-platform-tests/src/vitest/runner.ts @@ -1,7 +1,9 @@ import { pathToFileURL } from 'node:url'; -import { inject, test } from 'vitest'; +import { describe, inject, test } from 'vitest'; import type { WPTConfig } from '../config.ts'; import { runWPTFile } from '../node/isolated.ts'; +import type { WPTFileResult } from '../node/run.ts'; +import { loadSource, type SourceFile } from '../node/source.ts'; import { matchesName, matchesSource, selectsTest } from './selection.ts'; declare module 'vitest' { @@ -24,15 +26,60 @@ class WPTFailure extends Error { } } -/** Execute upstream once during collection, then register only selected results. */ +/** Execute every upstream variant during collection, then register only selected results. */ export async function registerWPTFile(file: string): Promise { const { configFile, sourceRoot, namePattern } = inject('wpt'); const { default: config } = (await import(configFile)) as { default: WPTConfig }; const source = decodeURIComponent( pathToFileURL(file).href.slice(pathToFileURL(`${sourceRoot}/`).href.length), ); - const result = await runWPTFile({ file, sourceRoot, configFile, timeout: config.timeout }); + let loadedSource: SourceFile; + try { + loadedSource = await loadSource(file, sourceRoot); + } catch (error) { + test('WPT harness completion', () => { + throw error; + }); + return; + } const expression = namePattern === undefined ? undefined : new RegExp(namePattern); + const results: WPTFileResult[] = []; + for (const variant of loadedSource.variants) { + const result = await runWPTFile({ + file, + sourceRoot, + configFile, + source: loadedSource, + variant, + timeout: config.timeout, + }); + results.push(result); + const register = (): void => { + for (const entry of result.tests) { + if (!selectsTest({ source, name: entry.name }, config)) { + continue; + } + if (expression && !expression.test(entry.name)) { + continue; + } + test(entry.name, () => { + if (entry.status !== 0) { + throw new WPTFailure(entry.message || `WPT status ${entry.status}`, entry.stack); + } + }); + } + if (result.status.status !== 0) { + test('WPT harness completion', () => { + throw new WPTFailure(result.status.message || 'WPT harness failed', result.status.stack); + }); + } + }; + if (loadedSource.variants.length === 1 && variant === '') { + register(); + } else { + describe(variant || '(default URL)', register); + } + } // Exact file selectors can be checked here without executing unrelated files. for (const [kind, selectors] of Object.entries({ @@ -42,7 +89,7 @@ export async function registerWPTFile(file: string): Promise { })) { for (const [pattern, cases] of Object.entries(selectors ?? {})) { if ( - (result.status.status !== 0 && kind !== 'forceTimeout') || + (results.some((result) => result.status.status !== 0) && kind !== 'forceTimeout') || pattern.includes('*') || !matchesSource(source, pattern) || cases === true @@ -50,7 +97,9 @@ export async function registerWPTFile(file: string): Promise { continue; } for (const selector of cases) { - if (!result.tests.some((entry) => matchesName(entry.name, selector))) { + if ( + !results.some((result) => result.tests.some((entry) => matchesName(entry.name, selector))) + ) { test(`WPT configuration: ${kind} case ${String(selector)}`, () => { throw new WPTFailure( `${kind} case ${String(selector)} in ${source} matched no WPT tests`, @@ -60,23 +109,4 @@ export async function registerWPTFile(file: string): Promise { } } } - - for (const entry of result.tests) { - if (!selectsTest({ source, name: entry.name }, config)) { - continue; - } - if (expression && !expression.test(entry.name)) { - continue; - } - test(entry.name, () => { - if (entry.status !== 0) { - throw new WPTFailure(entry.message || `WPT status ${entry.status}`, entry.stack); - } - }); - } - if (result.status.status !== 0) { - test('WPT harness completion', () => { - throw new WPTFailure(result.status.message || 'WPT harness failed', result.status.stack); - }); - } }