|
| 1 | +const HTML_NS = 'http://www.w3.org/1999/xhtml'; |
| 2 | +const namedElements = new Set(['embed', 'form', 'img', 'object']); |
| 3 | + |
| 4 | +class UnsupportedNamedAccessError extends Error {} |
| 5 | + |
| 6 | +/** Resolve fixture names through the worker global without changing its realm. */ |
| 7 | +export function installNamedProperties(scope: object, document: Document): () => void { |
| 8 | + const prototype = Object.getPrototypeOf(scope); |
| 9 | + const namedProperties = Object.create(prototype) as object; |
| 10 | + Object.setPrototypeOf( |
| 11 | + scope, |
| 12 | + new Proxy(namedProperties, { |
| 13 | + get(target, key, receiver) { |
| 14 | + return Reflect.has(target, key) |
| 15 | + ? Reflect.get(target, key, receiver) |
| 16 | + : namedElement(document, key); |
| 17 | + }, |
| 18 | + has(target, key) { |
| 19 | + return Reflect.has(target, key) || namedElement(document, key) !== undefined; |
| 20 | + }, |
| 21 | + }), |
| 22 | + ); |
| 23 | + // Names are never own properties, so enumeration omits them and assignments |
| 24 | + // create ordinary globals that shadow subsequent named lookups. |
| 25 | + return () => Object.setPrototypeOf(scope, prototype); |
| 26 | +} |
| 27 | + |
| 28 | +function namedElement(document: Document, key: PropertyKey): Element | undefined { |
| 29 | + if (typeof key !== 'string' || key === '') { |
| 30 | + return undefined; |
| 31 | + } |
| 32 | + let match: Element | undefined; |
| 33 | + const pending: Node[] = Array.from(document.childNodes); |
| 34 | + while (pending.length > 0) { |
| 35 | + const node = pending.pop()!; |
| 36 | + pending.push(...node.childNodes); |
| 37 | + if (node.nodeType !== 1) { |
| 38 | + continue; |
| 39 | + } |
| 40 | + const element = node as Element; |
| 41 | + const isHTML = element.namespaceURI === HTML_NS; |
| 42 | + const nameMatches = isHTML && element.getAttributeNS(null, 'name') === key; |
| 43 | + if (nameMatches && (element.localName === 'iframe' || element.localName === 'frame')) { |
| 44 | + throw new UnsupportedNamedAccessError( |
| 45 | + `Window named access to child browsing contexts is not supported: ${JSON.stringify(key)}`, |
| 46 | + ); |
| 47 | + } |
| 48 | + if ( |
| 49 | + element.getAttributeNS(null, 'id') === key || |
| 50 | + (nameMatches && namedElements.has(element.localName)) |
| 51 | + ) { |
| 52 | + if (match) { |
| 53 | + throw new UnsupportedNamedAccessError( |
| 54 | + `Window named access with multiple matching elements is not supported: ${JSON.stringify(key)}`, |
| 55 | + ); |
| 56 | + } |
| 57 | + match = element; |
| 58 | + } |
| 59 | + } |
| 60 | + return match; |
| 61 | +} |
0 commit comments