@amplitude/element-selector 0.3.1 → 0.3.3-sr-bfcache-pageshow-snapshot.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/helpers/shadow.d.ts +7 -1
- package/lib/cjs/helpers/shadow.d.ts.map +1 -1
- package/lib/cjs/helpers/shadow.js +14 -2
- package/lib/cjs/helpers/shadow.js.map +1 -1
- package/lib/esm/helpers/shadow.d.ts +7 -1
- package/lib/esm/helpers/shadow.d.ts.map +1 -1
- package/lib/esm/helpers/shadow.js +14 -2
- package/lib/esm/helpers/shadow.js.map +1 -1
- package/package.json +2 -2
|
@@ -58,7 +58,13 @@ export declare const SHADOW_BOUNDARY_DELIMITER = " >>> ";
|
|
|
58
58
|
* syntactically legal string; its meaning here is purely the descent signal.
|
|
59
59
|
*/
|
|
60
60
|
export declare const SHADOW_CHILD_CHAIN_PREFIX = ":scope > ";
|
|
61
|
-
/**
|
|
61
|
+
/**
|
|
62
|
+
* Narrowing guard for shadow roots. Tries `instanceof` first, then falls back
|
|
63
|
+
* to a structural check so shadow roots from another realm (e.g. a same-origin
|
|
64
|
+
* iframe, as in a replay mirror) are recognized too: there the calling page's
|
|
65
|
+
* `ShadowRoot` constructor does not match. Safe in environments without a
|
|
66
|
+
* `ShadowRoot` global, and `null`/`undefined` return `false`.
|
|
67
|
+
*/
|
|
62
68
|
export declare function isShadowRoot(node: Node): node is ShadowRoot;
|
|
63
69
|
/**
|
|
64
70
|
* Anchor a per-tree segment so it re-resolves within a `ShadowRoot`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shadow.d.ts","sourceRoot":"","sources":["../../../src/helpers/shadow.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,yBAAyB,UAAU,CAAC;AAEjD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,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K,EAAE,MAAM,CAAC;CACf;AAED;;;;;GAKG;AACH,wBAAiB,qBAAqB,CAAC,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,GAAG,SAAS,CAAC,OAAO,CAAC,CAuBjG;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,GAAG,mBAAmB,EAAE,CAwBnG;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,WAAW,CAAC,EAAE,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,GAAG,iBAAiB,CAgClF;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,GAAG,IAAI,CA0BlF;AAyCD;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,EAAE,EAAE,OAAO,EAAE,WAAW,EAAE,OAAO,GAAG,MAAM,CAgBxE"}
|
|
@@ -62,9 +62,21 @@ exports.SHADOW_BOUNDARY_DELIMITER = ' >>> ';
|
|
|
62
62
|
* syntactically legal string; its meaning here is purely the descent signal.
|
|
63
63
|
*/
|
|
64
64
|
exports.SHADOW_CHILD_CHAIN_PREFIX = ':scope > ';
|
|
65
|
-
/**
|
|
65
|
+
/**
|
|
66
|
+
* Narrowing guard for shadow roots. Tries `instanceof` first, then falls back
|
|
67
|
+
* to a structural check so shadow roots from another realm (e.g. a same-origin
|
|
68
|
+
* iframe, as in a replay mirror) are recognized too: there the calling page's
|
|
69
|
+
* `ShadowRoot` constructor does not match. Safe in environments without a
|
|
70
|
+
* `ShadowRoot` global, and `null`/`undefined` return `false`.
|
|
71
|
+
*/
|
|
66
72
|
function isShadowRoot(node) {
|
|
67
|
-
|
|
73
|
+
var _a;
|
|
74
|
+
if (typeof ShadowRoot !== 'undefined' && node instanceof ShadowRoot) {
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
return (node != null &&
|
|
78
|
+
node.nodeType === 11 /* DOCUMENT_FRAGMENT_NODE */ &&
|
|
79
|
+
((_a = node.host) === null || _a === void 0 ? void 0 : _a.nodeType) === 1 /* ELEMENT_NODE */);
|
|
68
80
|
}
|
|
69
81
|
exports.isShadowRoot = isShadowRoot;
|
|
70
82
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shadow.js","sourceRoot":"","sources":["../../../src/helpers/shadow.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;;;;AAEH;;;;;;;;;;;GAWG;AACU,QAAA,yBAAyB,GAAG,OAAO,CAAC;AAEjD;;;;;;;;;;;;;;GAcG;AACU,QAAA,yBAAyB,GAAG,WAAW,CAAC;AAErD,iFAAiF;AACjF,SAAgB,YAAY,CAAC,IAAU;IACrC,OAAO,OAAO,UAAU,KAAK,WAAW,IAAI,IAAI,YAAY,UAAU,CAAC;AACzE,CAAC;AAFD,oCAEC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,SAAgB,0BAA0B,CAAC,OAAe,EAAE,KAAiB,EAAE,cAAuB;IACpG,IAAI,OAAO,IAAI,cAAc,IAAI,YAAY,CAAC,KAAa,CAAC,EAAE;QAC5D,OAAO,UAAG,iCAAyB,SAAG,OAAO,CAAE,CAAC;KACjD;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AALD,gEAKC;AAED;;;;;;;;;;;GAWG;AACH,SAAgB,wBAAwB,CAAC,EAAW;IAClD,KAAK,IAAI,IAAI,GAAmB,EAAE,EAAE,IAAI,KAAK,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC,aAAa,EAAE;QAC5E,IAAI,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,EAAE;YAC3B,OAAO,KAAK,CAAC;SACd;KACF;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAPD,4DAOC;AAED;;;;;;;GAOG;AACH,SAAgB,MAAM,CAAC,EAAW;;IAChC,IAAM,IAAI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,CAAC,MAAG,CAAC;AAC1E,CAAC;AAhBD,wCAgBC;AAED;;;;;GAKG;AACH,SAAS,kBAAkB,CAAC,EAAW,EAAE,QAAwB;IAC/D,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACxC,IAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;QAC5B,IAAI,OAAO,CAAC,OAAO,KAAK,EAAE,CAAC,OAAO,EAAE;YAClC,KAAK,IAAI,CAAC,CAAC;YACX,IAAI,OAAO,KAAK,EAAE,EAAE;gBAClB,OAAO,KAAK,CAAC;aACd;SACF;KACF;IACD,6EAA6E;IAC7E,sDAAsD;IACtD,OAAO,CAAC,CAAC;AACX,CAAC","sourcesContent":["/**\n * Shadow-DOM traversal + re-resolution helpers.\n *\n * CSS selectors cannot pierce shadow boundaries: `document.querySelector` never\n * matches an element that lives inside a shadow root. So a selector that needs\n * to reach into shadow DOM can't be a single flat string — it has to be a\n * sequence of per-tree selectors, one per shadow tree, each resolvable within\n * its own root. We join those segments with `SHADOW_BOUNDARY_DELIMITER` and\n * re-resolve them with `resolveSelector`, descending one `shadowRoot` per\n * boundary.\n *\n * This module owns the primitives that knowledge lives in:\n *\n * - `composedParent` / `rootOf` — walk *out* of a shadow tree (the light-DOM\n * `parentElement` chain dead-ends at a shadow root; `getRootNode().host`\n * crosses the boundary).\n * - `segmentWalk` — split the outward walk into per-tree segments, honoring\n * the configured max shadow depth.\n * - `resolveSelector` — the symmetric inverse of the engine's output: split\n * on the delimiter and pierce open shadow roots to re-find the element.\n * - `walkComposedAncestors` — yield ancestors up the composed tree, honoring a\n * shadow-boundary crossing budget (shared by capture and selector layers).\n * - `collectOpenShadowRoots` — DFS collection of open shadow roots for\n * observer fan-out and deep `querySelectorAll`.\n * - `positionalStep` — a shadow-aware `tag:nth-of-type(n)` builder shared by\n * the orchestrator's descent and the fallback walker, so a shadow-root-top\n * element is still disambiguated against its `ShadowRoot` siblings.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\n/**\n * Delimiter that separates per-shadow-tree segments in a generated selector.\n *\n * Chosen to be visually distinct and trivially splittable, and to be invalid as\n * a real CSS combinator so it can never be confused with a `>` child combinator\n * the engine emits inside a single tree. Example output:\n *\n * `div#host >>> button:nth-of-type(1)`\n *\n * which `resolveSelector` re-resolves as\n * `document.querySelector('div#host').shadowRoot.querySelector('button:nth-of-type(1)')`.\n */\nexport const SHADOW_BOUNDARY_DELIMITER = ' >>> ';\n\n/**\n * Marker prefix for a \"direct child from the root\" chain inside a shadow tree.\n *\n * A positional chain scoped to a `ShadowRoot` (e.g. `div:nth-of-type(2)`) is not\n * anchored: `querySelector` matches it tree-wide, and `:scope` matches nothing\n * on a `ShadowRoot` (it isn't an element), so there is no CSS way to express\n * \"direct child of the root.\" The generator therefore prefixes such chains with\n * this marker and `resolveSelector` resolves them by strict direct-child descent\n * instead of `querySelector`. Keying off this explicit marker — rather than\n * sniffing a segment for the absence of `#`/`[` — keeps the round-trip correct\n * no matter what the steps contain (tag, `:nth-of-type`, classes, …).\n *\n * `:scope > ` is deliberately valid CSS syntax so a generated selector stays a\n * syntactically legal string; its meaning here is purely the descent signal.\n */\nexport const SHADOW_CHILD_CHAIN_PREFIX = ':scope > ';\n\n/** Narrowing guard that tolerates environments without a `ShadowRoot` global. */\nexport function isShadowRoot(node: Node): node is ShadowRoot {\n return typeof ShadowRoot !== 'undefined' && node instanceof ShadowRoot;\n}\n\n/**\n * Anchor a per-tree segment so it re-resolves within a `ShadowRoot`.\n *\n * Both selector algorithms (the strategy-chain fallback and the legacy Chromium\n * `cssPath`) can emit a segment that is only *positionally* specified — a chain\n * of `tag:nth-*` / class steps with no id or attribute to pin it. In the light\n * DOM the chain is implicitly anchored by the unique `<html>` root; inside a\n * shadow root there is no such root element, so `querySelector` matches the\n * chain tree-wide and can resolve to the wrong element (or none).\n *\n * When `segment` is such a root-anchored positional chain inside a shadow root,\n * we prefix it with {@link SHADOW_CHILD_CHAIN_PREFIX} so `resolveSelector`\n * descends by strict direct-child matching instead of `querySelector`. An\n * id/attribute-anchored segment is already resolvable tree-wide and is returned\n * untouched. `isRootAnchored` is the caller's decision (each generator knows\n * whether its own output reached the tree top vs. short-circuited on an id), so\n * this stays correct regardless of what the steps contain.\n */\nexport function anchorSegmentToShadowScope(segment: string, scope: ParentNode, isRootAnchored: boolean): string {\n if (segment && isRootAnchored && isShadowRoot(scope as Node)) {\n return `${SHADOW_CHILD_CHAIN_PREFIX}${segment}`;\n }\n return segment;\n}\n\n/**\n * Whether the legacy `cssPath` output for `el` is a root-anchored positional\n * chain rather than one anchored by an id.\n *\n * `legacyCssPath` short-circuits at the first element — inclusive of `el` —\n * that carries an `id`, emitting `tag#id > …` from there. If some element in\n * `el`'s ancestor chain has an id the emitted selector is id-anchored (a plain,\n * tree-wide-resolvable `querySelector`); if none does, the chain spans the tree\n * top down to `el` via positional steps and must be marked for direct-child\n * descent inside a shadow root. This walks the same `parentElement` chain the\n * legacy walker does, so the two stay in lockstep.\n */\nexport function legacyPathIsRootAnchored(el: Element): boolean {\n for (let node: Element | null = el; node !== null; node = node.parentElement) {\n if (node.getAttribute('id')) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * The queryable root for `el`'s own tree: the enclosing `ShadowRoot` when `el`\n * lives inside shadow DOM, otherwise the owner document. Both support\n * `querySelectorAll`, so uniqueness checks can be scoped to the correct tree.\n *\n * Preserves the legacy default for non-shadow elements (`ownerDocument`), so\n * nothing changes for the common flat-document case.\n */\nexport function rootOf(el: Element): ParentNode {\n const root = el.getRootNode();\n if (isShadowRoot(root)) {\n return root;\n }\n return el.ownerDocument ?? document;\n}\n\n/**\n * The next element up, crossing shadow boundaries: `parentElement` within a\n * tree, or the shadow host when `el` is at the top of a shadow tree. Returns\n * `null` only at the document root (or a detached non-shadow root).\n */\nexport function composedParent(el: Element): Element | null {\n if (el.parentElement) {\n return el.parentElement;\n }\n const root = el.getRootNode();\n if (isShadowRoot(root)) {\n return root.host;\n }\n return null;\n}\n\n/** One tree's contribution to a piercing selector. */\nexport interface TreeSegment {\n /** Queryable root for this tree — a `Document` or `ShadowRoot`. */\n root: ParentNode;\n /** Element to locate within `root`: the host of the next inner tree, or the original target. */\n target: Element;\n}\n\nexport interface SegmentWalkResult {\n /** Tree segments, outermost (document) first — the order they're joined for output. */\n segments: TreeSegment[];\n /**\n * True when the target sat deeper than `maxShadowDepth` allowed, so inner\n * trees were dropped and the innermost emitted segment targets the shadow\n * host at the depth limit rather than the original target.\n */\n truncated: boolean;\n}\n\n/**\n * Defensive bound on composed-ancestor walks (host-chain iteration in\n * `walkComposedAncestors` and `segmentWalk`). Far above any real shadow nesting\n * (the resolver caps effective depth at `MAX_SHADOW_DOM_DEPTH`). See also\n * {@link MAX_SHADOW_DOM_TRAVERSAL_NODES} for the DFS collection cap.\n */\nexport const MAX_SHADOW_COMPOSED_WALK_ITERATIONS = 1024;\n\n/**\n * Defensive bound on node visits when collecting open shadow roots via DFS.\n * Caps synchronous work inside MutationObserver callbacks on pathologically\n * large trees. See also {@link MAX_SHADOW_COMPOSED_WALK_ITERATIONS} for the\n * ancestor-walk cap.\n */\nexport const MAX_SHADOW_DOM_TRAVERSAL_NODES = 50000;\n\nexport interface OpenShadowRootEntry {\n root: ShadowRoot;\n /** 1-based shadow-boundary depth relative to the collection `root`. */\n depth: number;\n}\n\n/**\n * Yield `start` and each ancestor up the composed tree. Within a tree the walk\n * follows `parentElement`; at the top of a shadow tree it crosses to the host\n * when `crossings < maxShadowDepth`. Yields every element including detached\n * nodes at the top of their tree (where `parentElement` is null).\n */\nexport function* walkComposedAncestors(start: Element, maxShadowDepth: number): Generator<Element> {\n let node: Element | null = start;\n let crossings = 0;\n let iterations = 0;\n\n while (node !== null && iterations < MAX_SHADOW_COMPOSED_WALK_ITERATIONS) {\n iterations += 1;\n yield node;\n\n if (node.parentElement) {\n node = node.parentElement;\n continue;\n }\n if (crossings < maxShadowDepth && typeof node.getRootNode === 'function') {\n const host = composedParent(node);\n if (host && host !== node) {\n crossings += 1;\n node = host;\n continue;\n }\n }\n break;\n }\n}\n\n/**\n * Collect the OPEN shadow roots within `root`'s composed subtree (its own light\n * children and any nested shadow trees), each paired with how many shadow\n * boundary crossings deep it sits relative to `root` (1-based). Bounded by\n * `maxShadowDepth` crossings and by {@link MAX_SHADOW_DOM_TRAVERSAL_NODES}\n * total nodes. Closed roots are invisible (`el.shadowRoot` is null) and skipped.\n */\nexport function collectOpenShadowRoots(root: Element, maxShadowDepth: number): OpenShadowRootEntry[] {\n const found: OpenShadowRootEntry[] = [];\n if (maxShadowDepth <= 0) {\n return found;\n }\n const stack: Array<[Element, number]> = [[root, 0]];\n let visited = 0;\n while (stack.length && visited < MAX_SHADOW_DOM_TRAVERSAL_NODES) {\n visited += 1;\n const [el, depth] = stack.pop() as [Element, number];\n const shadowRoot = el.shadowRoot;\n if (shadowRoot && depth + 1 <= maxShadowDepth) {\n found.push({ root: shadowRoot, depth: depth + 1 });\n const shadowChildren = shadowRoot.children;\n for (let i = 0; i < shadowChildren.length; i++) {\n stack.push([shadowChildren[i], depth + 1]);\n }\n }\n const children = el.children;\n for (let i = 0; i < children.length; i++) {\n stack.push([children[i], depth]);\n }\n }\n return found;\n}\n\n/**\n * Split the outward composed walk from `el` into per-tree segments.\n *\n * Always walks fully out to the document so the outermost segment is\n * document-rooted and therefore re-resolvable. `maxShadowDepth` caps how many\n * shadow boundaries the *emitted* selector descends through: when the target is\n * nested deeper than the budget, the innermost (over-budget) trees are dropped\n * and the result is flagged `truncated` — the innermost kept segment then\n * targets the shadow host at the depth limit (a best-effort, still-resolvable\n * selector for an ancestor of the true target).\n */\nexport function segmentWalk(el: Element, maxShadowDepth: number): SegmentWalkResult {\n // Build innermost-first: one segment per tree, each `target` being the\n // element to locate within that tree (the inner tree's host, or `el`).\n const innermostFirst: TreeSegment[] = [];\n let node: Element | null = el;\n let iterations = 0;\n\n while (node !== null && iterations < MAX_SHADOW_COMPOSED_WALK_ITERATIONS) {\n iterations += 1;\n const root = rootOf(node);\n innermostFirst.push({ root, target: node });\n const actualRoot = node.getRootNode();\n if (!isShadowRoot(actualRoot)) {\n break; // reached the document (or a detached non-shadow root)\n }\n node = actualRoot.host; // cross the boundary outward\n }\n\n const totalCrossings = innermostFirst.length - 1;\n let truncated = false;\n let kept = innermostFirst;\n\n if (totalCrossings > maxShadowDepth) {\n // Drop the innermost over-budget trees, keeping the outermost\n // (maxShadowDepth + 1) trees. The new innermost kept segment's `target` is\n // already the shadow host of the first dropped tree.\n kept = innermostFirst.slice(totalCrossings - maxShadowDepth);\n truncated = true;\n }\n\n // Reverse to outermost-first so the engine joins document → target order.\n return { segments: kept.reverse(), truncated };\n}\n\n/**\n * Re-resolve a generated selector back to its element, piercing open shadow\n * roots at each boundary. The symmetric inverse of `engine.generate`.\n *\n * Returns `null` when any segment fails to match, or when a boundary crossing\n * hits a *closed* shadow root (`host.shadowRoot === null`) — closed roots are\n * opaque from outside, so such selectors cannot round-trip (a documented\n * limitation). Never throws on a malformed segment.\n *\n * @param root Root to resolve against — almost always `document`.\n * @param selector A selector produced by the engine (may contain boundary delimiters).\n */\nexport function resolveSelector(root: ParentNode, selector: string): Element | null {\n const segments = selector.split(SHADOW_BOUNDARY_DELIMITER);\n let scope: ParentNode | null = root;\n let found: Element | null = null;\n\n for (let i = 0; i < segments.length; i++) {\n if (scope === null) {\n return null; // previous segment's host had no (open) shadow root\n }\n const segment = segments[i].trim();\n try {\n found = resolveSegment(scope, segment);\n } catch {\n return null; // malformed segment — never throw out of the resolver\n }\n if (found === null) {\n return null;\n }\n if (i < segments.length - 1) {\n // Descend into this host's shadow root for the next segment. `null` for a\n // closed root ends resolution gracefully on the next iteration.\n scope = found.shadowRoot;\n }\n }\n\n return found;\n}\n\n/**\n * Resolve a single (non-delimited) segment within `scope`.\n *\n * A segment marked with {@link SHADOW_CHILD_CHAIN_PREFIX} is a root-anchored\n * \"direct child from the root\" chain (emitted by the fallback for a shadow-root\n * scope, where `querySelector` can't express that anchoring). We strip the\n * marker and resolve by strict direct-child descent. The marker is set\n * explicitly by the generator, so this stays correct regardless of what the\n * steps contain (tag, `:nth-of-type`, classes, …). Every other segment —\n * id/attribute-anchored, or any document-scope segment — resolves via a plain\n * `querySelector`.\n */\nfunction resolveSegment(scope: ParentNode, segment: string): Element | null {\n if (segment.startsWith(SHADOW_CHILD_CHAIN_PREFIX)) {\n return resolveChildChain(scope, segment.slice(SHADOW_CHILD_CHAIN_PREFIX.length));\n }\n return scope.querySelector(segment);\n}\n\n/**\n * Resolve a `>`-joined chain as a strict direct-child descent from `scope`. At\n * each level exactly one child matches the step (positional or otherwise via\n * `matches()`), so the walk is deterministic. Returns `null` if any step matches\n * no child.\n */\nfunction resolveChildChain(scope: ParentNode, chain: string): Element | null {\n const steps = chain.split('>').map((s) => s.trim());\n let children: Element[] = Array.from(scope.children);\n let el: Element | null = null;\n for (const step of steps) {\n el = children.find((child) => child.matches(step)) ?? null;\n if (el === null) {\n return null;\n }\n children = Array.from(el.children);\n }\n return el;\n}\n\n/**\n * Build a single positional step for `el`: `tag:nth-of-type(n)`, indexed among\n * its same-tag siblings. A parentless element emits the bare tag.\n *\n * `shadowAware` extends the parentless case: an element at the top of a shadow\n * tree has a null `parentElement` but can still have same-tag peers among the\n * `ShadowRoot`'s children, so it is indexed against those instead. When\n * `shadowAware` is false every parentless element emits the bare tag.\n */\nexport function positionalStep(el: Element, shadowAware: boolean): string {\n const tag = el.tagName.toLowerCase();\n const parent = el.parentElement;\n\n if (parent === null) {\n // Parentless means the document root (`<html>`), a detached element, or the\n // top of a shadow tree. Only the last has siblings worth indexing, and only\n // when the caller asks for shadow-aware stepping.\n const root = el.getRootNode();\n if (shadowAware && isShadowRoot(root)) {\n return `${tag}:nth-of-type(${sameTypeIndexAmong(el, root.children)})`;\n }\n return tag;\n }\n\n return `${tag}:nth-of-type(${sameTypeIndexAmong(el, parent.children)})`;\n}\n\n/**\n * 1-based index of `el` among same-tag siblings in `siblings`, mirroring\n * `:nth-of-type`. Takes an `HTMLCollection` rather than a parent `Element` so a\n * `ShadowRoot`'s children can be counted too — a `ShadowRoot` is not an\n * `Element` but does expose `children`.\n */\nfunction sameTypeIndexAmong(el: Element, siblings: HTMLCollection): number {\n let count = 0;\n for (let i = 0; i < siblings.length; i++) {\n const sibling = siblings[i];\n if (sibling.tagName === el.tagName) {\n count += 1;\n if (sibling === el) {\n return count;\n }\n }\n }\n // Defensive: element not found among its parent's children (shouldn't happen\n // for a live element). Return 1 rather than throwing.\n return 1;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"shadow.js","sourceRoot":"","sources":["../../../src/helpers/shadow.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;;;;AAEH;;;;;;;;;;;GAWG;AACU,QAAA,yBAAyB,GAAG,OAAO,CAAC;AAEjD;;;;;;;;;;;;;;GAcG;AACU,QAAA,yBAAyB,GAAG,WAAW,CAAC;AAErD;;;;;;GAMG;AACH,SAAgB,YAAY,CAAC,IAAU;;IACrC,IAAI,OAAO,UAAU,KAAK,WAAW,IAAI,IAAI,YAAY,UAAU,EAAE;QACnE,OAAO,IAAI,CAAC;KACb;IACD,OAAO,CACL,IAAI,IAAI,IAAI;QACZ,IAAI,CAAC,QAAQ,KAAK,EAAE,CAAC,4BAA4B;QACjD,CAAA,MAAC,IAAmB,CAAC,IAAI,0CAAE,QAAQ,MAAK,CAAC,CAAC,kBAAkB,CAC7D,CAAC;AACJ,CAAC;AATD,oCASC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,SAAgB,0BAA0B,CAAC,OAAe,EAAE,KAAiB,EAAE,cAAuB;IACpG,IAAI,OAAO,IAAI,cAAc,IAAI,YAAY,CAAC,KAAa,CAAC,EAAE;QAC5D,OAAO,UAAG,iCAAyB,SAAG,OAAO,CAAE,CAAC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AAC,aAAa,CAAC;IAEhC,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,4EAA4E;QAC5E,4EAA4E;QAC5E,kDAAkD;QAClD,IAAM,IAAI,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC;QAC9B,IAAI,WAAW,IAAI,YAAY,CAAC,IAAI,CAAC,EAAE;YACrC,OAAO,UAAG,GAAG,0BAAgB,kBAAkB,CAAC,EAAE,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAG,CAAC;SACvE;QACD,OAAO,GAAG,CAAC;KACZ;IAED,OAAO,UAAG,GAAG,0BAAgB,kBAAkB,CAAC,EAAE,EAAE,MAAM,CAAC,QAAQ,CAAC,MAAG,CAAC;AAC1E,CAAC;AAhBD,wCAgBC;AAED;;;;;GAKG;AACH,SAAS,kBAAkB,CAAC,EAAW,EAAE,QAAwB;IAC/D,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACxC,IAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;QAC5B,IAAI,OAAO,CAAC,OAAO,KAAK,EAAE,CAAC,OAAO,EAAE;YAClC,KAAK,IAAI,CAAC,CAAC;YACX,IAAI,OAAO,KAAK,EAAE,EAAE;gBAClB,OAAO,KAAK,CAAC;aACd;SACF;KACF;IACD,6EAA6E;IAC7E,sDAAsD;IACtD,OAAO,CAAC,CAAC;AACX,CAAC","sourcesContent":["/**\n * Shadow-DOM traversal + re-resolution helpers.\n *\n * CSS selectors cannot pierce shadow boundaries: `document.querySelector` never\n * matches an element that lives inside a shadow root. So a selector that needs\n * to reach into shadow DOM can't be a single flat string — it has to be a\n * sequence of per-tree selectors, one per shadow tree, each resolvable within\n * its own root. We join those segments with `SHADOW_BOUNDARY_DELIMITER` and\n * re-resolve them with `resolveSelector`, descending one `shadowRoot` per\n * boundary.\n *\n * This module owns the primitives that knowledge lives in:\n *\n * - `composedParent` / `rootOf` — walk *out* of a shadow tree (the light-DOM\n * `parentElement` chain dead-ends at a shadow root; `getRootNode().host`\n * crosses the boundary).\n * - `segmentWalk` — split the outward walk into per-tree segments, honoring\n * the configured max shadow depth.\n * - `resolveSelector` — the symmetric inverse of the engine's output: split\n * on the delimiter and pierce open shadow roots to re-find the element.\n * - `walkComposedAncestors` — yield ancestors up the composed tree, honoring a\n * shadow-boundary crossing budget (shared by capture and selector layers).\n * - `collectOpenShadowRoots` — DFS collection of open shadow roots for\n * observer fan-out and deep `querySelectorAll`.\n * - `positionalStep` — a shadow-aware `tag:nth-of-type(n)` builder shared by\n * the orchestrator's descent and the fallback walker, so a shadow-root-top\n * element is still disambiguated against its `ShadowRoot` siblings.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\n/**\n * Delimiter that separates per-shadow-tree segments in a generated selector.\n *\n * Chosen to be visually distinct and trivially splittable, and to be invalid as\n * a real CSS combinator so it can never be confused with a `>` child combinator\n * the engine emits inside a single tree. Example output:\n *\n * `div#host >>> button:nth-of-type(1)`\n *\n * which `resolveSelector` re-resolves as\n * `document.querySelector('div#host').shadowRoot.querySelector('button:nth-of-type(1)')`.\n */\nexport const SHADOW_BOUNDARY_DELIMITER = ' >>> ';\n\n/**\n * Marker prefix for a \"direct child from the root\" chain inside a shadow tree.\n *\n * A positional chain scoped to a `ShadowRoot` (e.g. `div:nth-of-type(2)`) is not\n * anchored: `querySelector` matches it tree-wide, and `:scope` matches nothing\n * on a `ShadowRoot` (it isn't an element), so there is no CSS way to express\n * \"direct child of the root.\" The generator therefore prefixes such chains with\n * this marker and `resolveSelector` resolves them by strict direct-child descent\n * instead of `querySelector`. Keying off this explicit marker — rather than\n * sniffing a segment for the absence of `#`/`[` — keeps the round-trip correct\n * no matter what the steps contain (tag, `:nth-of-type`, classes, …).\n *\n * `:scope > ` is deliberately valid CSS syntax so a generated selector stays a\n * syntactically legal string; its meaning here is purely the descent signal.\n */\nexport const SHADOW_CHILD_CHAIN_PREFIX = ':scope > ';\n\n/**\n * Narrowing guard for shadow roots. Tries `instanceof` first, then falls back\n * to a structural check so shadow roots from another realm (e.g. a same-origin\n * iframe, as in a replay mirror) are recognized too: there the calling page's\n * `ShadowRoot` constructor does not match. Safe in environments without a\n * `ShadowRoot` global, and `null`/`undefined` return `false`.\n */\nexport function isShadowRoot(node: Node): node is ShadowRoot {\n if (typeof ShadowRoot !== 'undefined' && node instanceof ShadowRoot) {\n return true;\n }\n return (\n node != null &&\n node.nodeType === 11 /* DOCUMENT_FRAGMENT_NODE */ &&\n (node as ShadowRoot).host?.nodeType === 1 /* ELEMENT_NODE */\n );\n}\n\n/**\n * Anchor a per-tree segment so it re-resolves within a `ShadowRoot`.\n *\n * Both selector algorithms (the strategy-chain fallback and the legacy Chromium\n * `cssPath`) can emit a segment that is only *positionally* specified — a chain\n * of `tag:nth-*` / class steps with no id or attribute to pin it. In the light\n * DOM the chain is implicitly anchored by the unique `<html>` root; inside a\n * shadow root there is no such root element, so `querySelector` matches the\n * chain tree-wide and can resolve to the wrong element (or none).\n *\n * When `segment` is such a root-anchored positional chain inside a shadow root,\n * we prefix it with {@link SHADOW_CHILD_CHAIN_PREFIX} so `resolveSelector`\n * descends by strict direct-child matching instead of `querySelector`. An\n * id/attribute-anchored segment is already resolvable tree-wide and is returned\n * untouched. `isRootAnchored` is the caller's decision (each generator knows\n * whether its own output reached the tree top vs. short-circuited on an id), so\n * this stays correct regardless of what the steps contain.\n */\nexport function anchorSegmentToShadowScope(segment: string, scope: ParentNode, isRootAnchored: boolean): string {\n if (segment && isRootAnchored && isShadowRoot(scope as Node)) {\n return `${SHADOW_CHILD_CHAIN_PREFIX}${segment}`;\n }\n return segment;\n}\n\n/**\n * Whether the legacy `cssPath` output for `el` is a root-anchored positional\n * chain rather than one anchored by an id.\n *\n * `legacyCssPath` short-circuits at the first element — inclusive of `el` —\n * that carries an `id`, emitting `tag#id > …` from there. If some element in\n * `el`'s ancestor chain has an id the emitted selector is id-anchored (a plain,\n * tree-wide-resolvable `querySelector`); if none does, the chain spans the tree\n * top down to `el` via positional steps and must be marked for direct-child\n * descent inside a shadow root. This walks the same `parentElement` chain the\n * legacy walker does, so the two stay in lockstep.\n */\nexport function legacyPathIsRootAnchored(el: Element): boolean {\n for (let node: Element | null = el; node !== null; node = node.parentElement) {\n if (node.getAttribute('id')) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * The queryable root for `el`'s own tree: the enclosing `ShadowRoot` when `el`\n * lives inside shadow DOM, otherwise the owner document. Both support\n * `querySelectorAll`, so uniqueness checks can be scoped to the correct tree.\n *\n * Preserves the legacy default for non-shadow elements (`ownerDocument`), so\n * nothing changes for the common flat-document case.\n */\nexport function rootOf(el: Element): ParentNode {\n const root = el.getRootNode();\n if (isShadowRoot(root)) {\n return root;\n }\n return el.ownerDocument ?? document;\n}\n\n/**\n * The next element up, crossing shadow boundaries: `parentElement` within a\n * tree, or the shadow host when `el` is at the top of a shadow tree. Returns\n * `null` only at the document root (or a detached non-shadow root).\n */\nexport function composedParent(el: Element): Element | null {\n if (el.parentElement) {\n return el.parentElement;\n }\n const root = el.getRootNode();\n if (isShadowRoot(root)) {\n return root.host;\n }\n return null;\n}\n\n/** One tree's contribution to a piercing selector. */\nexport interface TreeSegment {\n /** Queryable root for this tree — a `Document` or `ShadowRoot`. */\n root: ParentNode;\n /** Element to locate within `root`: the host of the next inner tree, or the original target. */\n target: Element;\n}\n\nexport interface SegmentWalkResult {\n /** Tree segments, outermost (document) first — the order they're joined for output. */\n segments: TreeSegment[];\n /**\n * True when the target sat deeper than `maxShadowDepth` allowed, so inner\n * trees were dropped and the innermost emitted segment targets the shadow\n * host at the depth limit rather than the original target.\n */\n truncated: boolean;\n}\n\n/**\n * Defensive bound on composed-ancestor walks (host-chain iteration in\n * `walkComposedAncestors` and `segmentWalk`). Far above any real shadow nesting\n * (the resolver caps effective depth at `MAX_SHADOW_DOM_DEPTH`). See also\n * {@link MAX_SHADOW_DOM_TRAVERSAL_NODES} for the DFS collection cap.\n */\nexport const MAX_SHADOW_COMPOSED_WALK_ITERATIONS = 1024;\n\n/**\n * Defensive bound on node visits when collecting open shadow roots via DFS.\n * Caps synchronous work inside MutationObserver callbacks on pathologically\n * large trees. See also {@link MAX_SHADOW_COMPOSED_WALK_ITERATIONS} for the\n * ancestor-walk cap.\n */\nexport const MAX_SHADOW_DOM_TRAVERSAL_NODES = 50000;\n\nexport interface OpenShadowRootEntry {\n root: ShadowRoot;\n /** 1-based shadow-boundary depth relative to the collection `root`. */\n depth: number;\n}\n\n/**\n * Yield `start` and each ancestor up the composed tree. Within a tree the walk\n * follows `parentElement`; at the top of a shadow tree it crosses to the host\n * when `crossings < maxShadowDepth`. Yields every element including detached\n * nodes at the top of their tree (where `parentElement` is null).\n */\nexport function* walkComposedAncestors(start: Element, maxShadowDepth: number): Generator<Element> {\n let node: Element | null = start;\n let crossings = 0;\n let iterations = 0;\n\n while (node !== null && iterations < MAX_SHADOW_COMPOSED_WALK_ITERATIONS) {\n iterations += 1;\n yield node;\n\n if (node.parentElement) {\n node = node.parentElement;\n continue;\n }\n if (crossings < maxShadowDepth && typeof node.getRootNode === 'function') {\n const host = composedParent(node);\n if (host && host !== node) {\n crossings += 1;\n node = host;\n continue;\n }\n }\n break;\n }\n}\n\n/**\n * Collect the OPEN shadow roots within `root`'s composed subtree (its own light\n * children and any nested shadow trees), each paired with how many shadow\n * boundary crossings deep it sits relative to `root` (1-based). Bounded by\n * `maxShadowDepth` crossings and by {@link MAX_SHADOW_DOM_TRAVERSAL_NODES}\n * total nodes. Closed roots are invisible (`el.shadowRoot` is null) and skipped.\n */\nexport function collectOpenShadowRoots(root: Element, maxShadowDepth: number): OpenShadowRootEntry[] {\n const found: OpenShadowRootEntry[] = [];\n if (maxShadowDepth <= 0) {\n return found;\n }\n const stack: Array<[Element, number]> = [[root, 0]];\n let visited = 0;\n while (stack.length && visited < MAX_SHADOW_DOM_TRAVERSAL_NODES) {\n visited += 1;\n const [el, depth] = stack.pop() as [Element, number];\n const shadowRoot = el.shadowRoot;\n if (shadowRoot && depth + 1 <= maxShadowDepth) {\n found.push({ root: shadowRoot, depth: depth + 1 });\n const shadowChildren = shadowRoot.children;\n for (let i = 0; i < shadowChildren.length; i++) {\n stack.push([shadowChildren[i], depth + 1]);\n }\n }\n const children = el.children;\n for (let i = 0; i < children.length; i++) {\n stack.push([children[i], depth]);\n }\n }\n return found;\n}\n\n/**\n * Split the outward composed walk from `el` into per-tree segments.\n *\n * Always walks fully out to the document so the outermost segment is\n * document-rooted and therefore re-resolvable. `maxShadowDepth` caps how many\n * shadow boundaries the *emitted* selector descends through: when the target is\n * nested deeper than the budget, the innermost (over-budget) trees are dropped\n * and the result is flagged `truncated` — the innermost kept segment then\n * targets the shadow host at the depth limit (a best-effort, still-resolvable\n * selector for an ancestor of the true target).\n */\nexport function segmentWalk(el: Element, maxShadowDepth: number): SegmentWalkResult {\n // Build innermost-first: one segment per tree, each `target` being the\n // element to locate within that tree (the inner tree's host, or `el`).\n const innermostFirst: TreeSegment[] = [];\n let node: Element | null = el;\n let iterations = 0;\n\n while (node !== null && iterations < MAX_SHADOW_COMPOSED_WALK_ITERATIONS) {\n iterations += 1;\n const root = rootOf(node);\n innermostFirst.push({ root, target: node });\n const actualRoot = node.getRootNode();\n if (!isShadowRoot(actualRoot)) {\n break; // reached the document (or a detached non-shadow root)\n }\n node = actualRoot.host; // cross the boundary outward\n }\n\n const totalCrossings = innermostFirst.length - 1;\n let truncated = false;\n let kept = innermostFirst;\n\n if (totalCrossings > maxShadowDepth) {\n // Drop the innermost over-budget trees, keeping the outermost\n // (maxShadowDepth + 1) trees. The new innermost kept segment's `target` is\n // already the shadow host of the first dropped tree.\n kept = innermostFirst.slice(totalCrossings - maxShadowDepth);\n truncated = true;\n }\n\n // Reverse to outermost-first so the engine joins document → target order.\n return { segments: kept.reverse(), truncated };\n}\n\n/**\n * Re-resolve a generated selector back to its element, piercing open shadow\n * roots at each boundary. The symmetric inverse of `engine.generate`.\n *\n * Returns `null` when any segment fails to match, or when a boundary crossing\n * hits a *closed* shadow root (`host.shadowRoot === null`) — closed roots are\n * opaque from outside, so such selectors cannot round-trip (a documented\n * limitation). Never throws on a malformed segment.\n *\n * @param root Root to resolve against — almost always `document`.\n * @param selector A selector produced by the engine (may contain boundary delimiters).\n */\nexport function resolveSelector(root: ParentNode, selector: string): Element | null {\n const segments = selector.split(SHADOW_BOUNDARY_DELIMITER);\n let scope: ParentNode | null = root;\n let found: Element | null = null;\n\n for (let i = 0; i < segments.length; i++) {\n if (scope === null) {\n return null; // previous segment's host had no (open) shadow root\n }\n const segment = segments[i].trim();\n try {\n found = resolveSegment(scope, segment);\n } catch {\n return null; // malformed segment — never throw out of the resolver\n }\n if (found === null) {\n return null;\n }\n if (i < segments.length - 1) {\n // Descend into this host's shadow root for the next segment. `null` for a\n // closed root ends resolution gracefully on the next iteration.\n scope = found.shadowRoot;\n }\n }\n\n return found;\n}\n\n/**\n * Resolve a single (non-delimited) segment within `scope`.\n *\n * A segment marked with {@link SHADOW_CHILD_CHAIN_PREFIX} is a root-anchored\n * \"direct child from the root\" chain (emitted by the fallback for a shadow-root\n * scope, where `querySelector` can't express that anchoring). We strip the\n * marker and resolve by strict direct-child descent. The marker is set\n * explicitly by the generator, so this stays correct regardless of what the\n * steps contain (tag, `:nth-of-type`, classes, …). Every other segment —\n * id/attribute-anchored, or any document-scope segment — resolves via a plain\n * `querySelector`.\n */\nfunction resolveSegment(scope: ParentNode, segment: string): Element | null {\n if (segment.startsWith(SHADOW_CHILD_CHAIN_PREFIX)) {\n return resolveChildChain(scope, segment.slice(SHADOW_CHILD_CHAIN_PREFIX.length));\n }\n return scope.querySelector(segment);\n}\n\n/**\n * Resolve a `>`-joined chain as a strict direct-child descent from `scope`. At\n * each level exactly one child matches the step (positional or otherwise via\n * `matches()`), so the walk is deterministic. Returns `null` if any step matches\n * no child.\n */\nfunction resolveChildChain(scope: ParentNode, chain: string): Element | null {\n const steps = chain.split('>').map((s) => s.trim());\n let children: Element[] = Array.from(scope.children);\n let el: Element | null = null;\n for (const step of steps) {\n el = children.find((child) => child.matches(step)) ?? null;\n if (el === null) {\n return null;\n }\n children = Array.from(el.children);\n }\n return el;\n}\n\n/**\n * Build a single positional step for `el`: `tag:nth-of-type(n)`, indexed among\n * its same-tag siblings. A parentless element emits the bare tag.\n *\n * `shadowAware` extends the parentless case: an element at the top of a shadow\n * tree has a null `parentElement` but can still have same-tag peers among the\n * `ShadowRoot`'s children, so it is indexed against those instead. When\n * `shadowAware` is false every parentless element emits the bare tag.\n */\nexport function positionalStep(el: Element, shadowAware: boolean): string {\n const tag = el.tagName.toLowerCase();\n const parent = el.parentElement;\n\n if (parent === null) {\n // Parentless means the document root (`<html>`), a detached element, or the\n // top of a shadow tree. Only the last has siblings worth indexing, and only\n // when the caller asks for shadow-aware stepping.\n const root = el.getRootNode();\n if (shadowAware && isShadowRoot(root)) {\n return `${tag}:nth-of-type(${sameTypeIndexAmong(el, root.children)})`;\n }\n return tag;\n }\n\n return `${tag}:nth-of-type(${sameTypeIndexAmong(el, parent.children)})`;\n}\n\n/**\n * 1-based index of `el` among same-tag siblings in `siblings`, mirroring\n * `:nth-of-type`. Takes an `HTMLCollection` rather than a parent `Element` so a\n * `ShadowRoot`'s children can be counted too — a `ShadowRoot` is not an\n * `Element` but does expose `children`.\n */\nfunction sameTypeIndexAmong(el: Element, siblings: HTMLCollection): number {\n let count = 0;\n for (let i = 0; i < siblings.length; i++) {\n const sibling = siblings[i];\n if (sibling.tagName === el.tagName) {\n count += 1;\n if (sibling === el) {\n return count;\n }\n }\n }\n // Defensive: element not found among its parent's children (shouldn't happen\n // for a live element). Return 1 rather than throwing.\n return 1;\n}\n"]}
|
|
@@ -58,7 +58,13 @@ export declare const SHADOW_BOUNDARY_DELIMITER = " >>> ";
|
|
|
58
58
|
* syntactically legal string; its meaning here is purely the descent signal.
|
|
59
59
|
*/
|
|
60
60
|
export declare const SHADOW_CHILD_CHAIN_PREFIX = ":scope > ";
|
|
61
|
-
/**
|
|
61
|
+
/**
|
|
62
|
+
* Narrowing guard for shadow roots. Tries `instanceof` first, then falls back
|
|
63
|
+
* to a structural check so shadow roots from another realm (e.g. a same-origin
|
|
64
|
+
* iframe, as in a replay mirror) are recognized too: there the calling page's
|
|
65
|
+
* `ShadowRoot` constructor does not match. Safe in environments without a
|
|
66
|
+
* `ShadowRoot` global, and `null`/`undefined` return `false`.
|
|
67
|
+
*/
|
|
62
68
|
export declare function isShadowRoot(node: Node): node is ShadowRoot;
|
|
63
69
|
/**
|
|
64
70
|
* Anchor a per-tree segment so it re-resolves within a `ShadowRoot`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shadow.d.ts","sourceRoot":"","sources":["../../../src/helpers/shadow.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,yBAAyB,UAAU,CAAC;AAEjD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,yBAAyB,cAAc,CAAC;AAErD
|
|
1
|
+
{"version":3,"file":"shadow.d.ts","sourceRoot":"","sources":["../../../src/helpers/shadow.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,yBAAyB,UAAU,CAAC;AAEjD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,yBAAyB,cAAc,CAAC;AAErD;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,UAAU,CAS3D;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,OAAO,GAAG,MAAM,CAK9G;AAED;;;;;;;;;;;GA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AC,EAAE,EAAE,OAAO,EAAE,WAAW,EAAE,OAAO,GAAG,MAAM,CAgBxE"}
|
|
@@ -59,9 +59,21 @@ export var SHADOW_BOUNDARY_DELIMITER = ' >>> ';
|
|
|
59
59
|
* syntactically legal string; its meaning here is purely the descent signal.
|
|
60
60
|
*/
|
|
61
61
|
export var SHADOW_CHILD_CHAIN_PREFIX = ':scope > ';
|
|
62
|
-
/**
|
|
62
|
+
/**
|
|
63
|
+
* Narrowing guard for shadow roots. Tries `instanceof` first, then falls back
|
|
64
|
+
* to a structural check so shadow roots from another realm (e.g. a same-origin
|
|
65
|
+
* iframe, as in a replay mirror) are recognized too: there the calling page's
|
|
66
|
+
* `ShadowRoot` constructor does not match. Safe in environments without a
|
|
67
|
+
* `ShadowRoot` global, and `null`/`undefined` return `false`.
|
|
68
|
+
*/
|
|
63
69
|
export function isShadowRoot(node) {
|
|
64
|
-
|
|
70
|
+
var _a;
|
|
71
|
+
if (typeof ShadowRoot !== 'undefined' && node instanceof ShadowRoot) {
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
return (node != null &&
|
|
75
|
+
node.nodeType === 11 /* DOCUMENT_FRAGMENT_NODE */ &&
|
|
76
|
+
((_a = node.host) === null || _a === void 0 ? void 0 : _a.nodeType) === 1 /* ELEMENT_NODE */);
|
|
65
77
|
}
|
|
66
78
|
/**
|
|
67
79
|
* Anchor a per-tree segment so it re-resolves within a `ShadowRoot`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shadow.js","sourceRoot":"","sources":["../../../src/helpers/shadow.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;;AAEH;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,IAAM,yBAAyB,GAAG,OAAO,CAAC;AAEjD;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,IAAM,yBAAyB,GAAG,WAAW,CAAC;AAErD,iFAAiF;AACjF,MAAM,UAAU,YAA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SS selectors cannot pierce shadow boundaries: `document.querySelector` never\n * matches an element that lives inside a shadow root. So a selector that needs\n * to reach into shadow DOM can't be a single flat string — it has to be a\n * sequence of per-tree selectors, one per shadow tree, each resolvable within\n * its own root. We join those segments with `SHADOW_BOUNDARY_DELIMITER` and\n * re-resolve them with `resolveSelector`, descending one `shadowRoot` per\n * boundary.\n *\n * This module owns the primitives that knowledge lives in:\n *\n * - `composedParent` / `rootOf` — walk *out* of a shadow tree (the light-DOM\n * `parentElement` chain dead-ends at a shadow root; `getRootNode().host`\n * crosses the boundary).\n * - `segmentWalk` — split the outward walk into per-tree segments, honoring\n * the configured max shadow depth.\n * - `resolveSelector` — the symmetric inverse of the engine's output: split\n * on the delimiter and pierce open shadow roots to re-find the element.\n * - `walkComposedAncestors` — yield ancestors up the composed tree, honoring a\n * shadow-boundary crossing budget (shared by capture and selector layers).\n * - `collectOpenShadowRoots` — DFS collection of open shadow roots for\n * observer fan-out and deep `querySelectorAll`.\n * - `positionalStep` — a shadow-aware `tag:nth-of-type(n)` builder shared by\n * the orchestrator's descent and the fallback walker, so a shadow-root-top\n * element is still disambiguated against its `ShadowRoot` siblings.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\n/**\n * Delimiter that separates per-shadow-tree segments in a generated selector.\n *\n * Chosen to be visually distinct and trivially splittable, and to be invalid as\n * a real CSS combinator so it can never be confused with a `>` child combinator\n * the engine emits inside a single tree. Example output:\n *\n * `div#host >>> button:nth-of-type(1)`\n *\n * which `resolveSelector` re-resolves as\n * `document.querySelector('div#host').shadowRoot.querySelector('button:nth-of-type(1)')`.\n */\nexport const SHADOW_BOUNDARY_DELIMITER = ' >>> ';\n\n/**\n * Marker prefix for a \"direct child from the root\" chain inside a shadow tree.\n *\n * A positional chain scoped to a `ShadowRoot` (e.g. `div:nth-of-type(2)`) is not\n * anchored: `querySelector` matches it tree-wide, and `:scope` matches nothing\n * on a `ShadowRoot` (it isn't an element), so there is no CSS way to express\n * \"direct child of the root.\" The generator therefore prefixes such chains with\n * this marker and `resolveSelector` resolves them by strict direct-child descent\n * instead of `querySelector`. Keying off this explicit marker — rather than\n * sniffing a segment for the absence of `#`/`[` — keeps the round-trip correct\n * no matter what the steps contain (tag, `:nth-of-type`, classes, …).\n *\n * `:scope > ` is deliberately valid CSS syntax so a generated selector stays a\n * syntactically legal string; its meaning here is purely the descent signal.\n */\nexport const SHADOW_CHILD_CHAIN_PREFIX = ':scope > ';\n\n/** Narrowing guard that tolerates environments without a `ShadowRoot` global. */\nexport function isShadowRoot(node: Node): node is ShadowRoot {\n return typeof ShadowRoot !== 'undefined' && node instanceof ShadowRoot;\n}\n\n/**\n * Anchor a per-tree segment so it re-resolves within a `ShadowRoot`.\n *\n * Both selector algorithms (the strategy-chain fallback and the legacy Chromium\n * `cssPath`) can emit a segment that is only *positionally* specified — a chain\n * of `tag:nth-*` / class steps with no id or attribute to pin it. In the light\n * DOM the chain is implicitly anchored by the unique `<html>` root; inside a\n * shadow root there is no such root element, so `querySelector` matches the\n * chain tree-wide and can resolve to the wrong element (or none).\n *\n * When `segment` is such a root-anchored positional chain inside a shadow root,\n * we prefix it with {@link SHADOW_CHILD_CHAIN_PREFIX} so `resolveSelector`\n * descends by strict direct-child matching instead of `querySelector`. An\n * id/attribute-anchored segment is already resolvable tree-wide and is returned\n * untouched. `isRootAnchored` is the caller's decision (each generator knows\n * whether its own output reached the tree top vs. short-circuited on an id), so\n * this stays correct regardless of what the steps contain.\n */\nexport function anchorSegmentToShadowScope(segment: string, scope: ParentNode, isRootAnchored: boolean): string {\n if (segment && isRootAnchored && isShadowRoot(scope as Node)) {\n return `${SHADOW_CHILD_CHAIN_PREFIX}${segment}`;\n }\n return segment;\n}\n\n/**\n * Whether the legacy `cssPath` output for `el` is a root-anchored positional\n * chain rather than one anchored by an id.\n *\n * `legacyCssPath` short-circuits at the first element — inclusive of `el` —\n * that carries an `id`, emitting `tag#id > …` from there. If some element in\n * `el`'s ancestor chain has an id the emitted selector is id-anchored (a plain,\n * tree-wide-resolvable `querySelector`); if none does, the chain spans the tree\n * top down to `el` via positional steps and must be marked for direct-child\n * descent inside a shadow root. This walks the same `parentElement` chain the\n * legacy walker does, so the two stay in lockstep.\n */\nexport function legacyPathIsRootAnchored(el: Element): boolean {\n for (let node: Element | null = el; node !== null; node = node.parentElement) {\n if (node.getAttribute('id')) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * The queryable root for `el`'s own tree: the enclosing `ShadowRoot` when `el`\n * lives inside shadow DOM, otherwise the owner document. Both support\n * `querySelectorAll`, so uniqueness checks can be scoped to the correct tree.\n *\n * Preserves the legacy default for non-shadow elements (`ownerDocument`), so\n * nothing changes for the common flat-document case.\n */\nexport function rootOf(el: Element): ParentNode {\n const root = el.getRootNode();\n if (isShadowRoot(root)) {\n return root;\n }\n return el.ownerDocument ?? document;\n}\n\n/**\n * The next element up, crossing shadow boundaries: `parentElement` within a\n * tree, or the shadow host when `el` is at the top of a shadow tree. Returns\n * `null` only at the document root (or a detached non-shadow root).\n */\nexport function composedParent(el: Element): Element | null {\n if (el.parentElement) {\n return el.parentElement;\n }\n const root = el.getRootNode();\n if (isShadowRoot(root)) {\n return root.host;\n }\n return null;\n}\n\n/** One tree's contribution to a piercing selector. */\nexport interface TreeSegment {\n /** Queryable root for this tree — a `Document` or `ShadowRoot`. */\n root: ParentNode;\n /** Element to locate within `root`: the host of the next inner tree, or the original target. */\n target: Element;\n}\n\nexport interface SegmentWalkResult {\n /** Tree segments, outermost (document) first — the order they're joined for output. */\n segments: TreeSegment[];\n /**\n * True when the target sat deeper than `maxShadowDepth` allowed, so inner\n * trees were dropped and the innermost emitted segment targets the shadow\n * host at the depth limit rather than the original target.\n */\n truncated: boolean;\n}\n\n/**\n * Defensive bound on composed-ancestor walks (host-chain iteration in\n * `walkComposedAncestors` and `segmentWalk`). Far above any real shadow nesting\n * (the resolver caps effective depth at `MAX_SHADOW_DOM_DEPTH`). See also\n * {@link MAX_SHADOW_DOM_TRAVERSAL_NODES} for the DFS collection cap.\n */\nexport const MAX_SHADOW_COMPOSED_WALK_ITERATIONS = 1024;\n\n/**\n * Defensive bound on node visits when collecting open shadow roots via DFS.\n * Caps synchronous work inside MutationObserver callbacks on pathologically\n * large trees. See also {@link MAX_SHADOW_COMPOSED_WALK_ITERATIONS} for the\n * ancestor-walk cap.\n */\nexport const MAX_SHADOW_DOM_TRAVERSAL_NODES = 50000;\n\nexport interface OpenShadowRootEntry {\n root: ShadowRoot;\n /** 1-based shadow-boundary depth relative to the collection `root`. */\n depth: number;\n}\n\n/**\n * Yield `start` and each ancestor up the composed tree. Within a tree the walk\n * follows `parentElement`; at the top of a shadow tree it crosses to the host\n * when `crossings < maxShadowDepth`. Yields every element including detached\n * nodes at the top of their tree (where `parentElement` is null).\n */\nexport function* walkComposedAncestors(start: Element, maxShadowDepth: number): Generator<Element> {\n let node: Element | null = start;\n let crossings = 0;\n let iterations = 0;\n\n while (node !== null && iterations < MAX_SHADOW_COMPOSED_WALK_ITERATIONS) {\n iterations += 1;\n yield node;\n\n if (node.parentElement) {\n node = node.parentElement;\n continue;\n }\n if (crossings < maxShadowDepth && typeof node.getRootNode === 'function') {\n const host = composedParent(node);\n if (host && host !== node) {\n crossings += 1;\n node = host;\n continue;\n }\n }\n break;\n }\n}\n\n/**\n * Collect the OPEN shadow roots within `root`'s composed subtree (its own light\n * children and any nested shadow trees), each paired with how many shadow\n * boundary crossings deep it sits relative to `root` (1-based). Bounded by\n * `maxShadowDepth` crossings and by {@link MAX_SHADOW_DOM_TRAVERSAL_NODES}\n * total nodes. Closed roots are invisible (`el.shadowRoot` is null) and skipped.\n */\nexport function collectOpenShadowRoots(root: Element, maxShadowDepth: number): OpenShadowRootEntry[] {\n const found: OpenShadowRootEntry[] = [];\n if (maxShadowDepth <= 0) {\n return found;\n }\n const stack: Array<[Element, number]> = [[root, 0]];\n let visited = 0;\n while (stack.length && visited < MAX_SHADOW_DOM_TRAVERSAL_NODES) {\n visited += 1;\n const [el, depth] = stack.pop() as [Element, number];\n const shadowRoot = el.shadowRoot;\n if (shadowRoot && depth + 1 <= maxShadowDepth) {\n found.push({ root: shadowRoot, depth: depth + 1 });\n const shadowChildren = shadowRoot.children;\n for (let i = 0; i < shadowChildren.length; i++) {\n stack.push([shadowChildren[i], depth + 1]);\n }\n }\n const children = el.children;\n for (let i = 0; i < children.length; i++) {\n stack.push([children[i], depth]);\n }\n }\n return found;\n}\n\n/**\n * Split the outward composed walk from `el` into per-tree segments.\n *\n * Always walks fully out to the document so the outermost segment is\n * document-rooted and therefore re-resolvable. `maxShadowDepth` caps how many\n * shadow boundaries the *emitted* selector descends through: when the target is\n * nested deeper than the budget, the innermost (over-budget) trees are dropped\n * and the result is flagged `truncated` — the innermost kept segment then\n * targets the shadow host at the depth limit (a best-effort, still-resolvable\n * selector for an ancestor of the true target).\n */\nexport function segmentWalk(el: Element, maxShadowDepth: number): SegmentWalkResult {\n // Build innermost-first: one segment per tree, each `target` being the\n // element to locate within that tree (the inner tree's host, or `el`).\n const innermostFirst: TreeSegment[] = [];\n let node: Element | null = el;\n let iterations = 0;\n\n while (node !== null && iterations < MAX_SHADOW_COMPOSED_WALK_ITERATIONS) {\n iterations += 1;\n const root = rootOf(node);\n innermostFirst.push({ root, target: node });\n const actualRoot = node.getRootNode();\n if (!isShadowRoot(actualRoot)) {\n break; // reached the document (or a detached non-shadow root)\n }\n node = actualRoot.host; // cross the boundary outward\n }\n\n const totalCrossings = innermostFirst.length - 1;\n let truncated = false;\n let kept = innermostFirst;\n\n if (totalCrossings > maxShadowDepth) {\n // Drop the innermost over-budget trees, keeping the outermost\n // (maxShadowDepth + 1) trees. The new innermost kept segment's `target` is\n // already the shadow host of the first dropped tree.\n kept = innermostFirst.slice(totalCrossings - maxShadowDepth);\n truncated = true;\n }\n\n // Reverse to outermost-first so the engine joins document → target order.\n return { segments: kept.reverse(), truncated };\n}\n\n/**\n * Re-resolve a generated selector back to its element, piercing open shadow\n * roots at each boundary. The symmetric inverse of `engine.generate`.\n *\n * Returns `null` when any segment fails to match, or when a boundary crossing\n * hits a *closed* shadow root (`host.shadowRoot === null`) — closed roots are\n * opaque from outside, so such selectors cannot round-trip (a documented\n * limitation). Never throws on a malformed segment.\n *\n * @param root Root to resolve against — almost always `document`.\n * @param selector A selector produced by the engine (may contain boundary delimiters).\n */\nexport function resolveSelector(root: ParentNode, selector: string): Element | null {\n const segments = selector.split(SHADOW_BOUNDARY_DELIMITER);\n let scope: ParentNode | null = root;\n let found: Element | null = null;\n\n for (let i = 0; i < segments.length; i++) {\n if (scope === null) {\n return null; // previous segment's host had no (open) shadow root\n }\n const segment = segments[i].trim();\n try {\n found = resolveSegment(scope, segment);\n } catch {\n return null; // malformed segment — never throw out of the resolver\n }\n if (found === null) {\n return null;\n }\n if (i < segments.length - 1) {\n // Descend into this host's shadow root for the next segment. `null` for a\n // closed root ends resolution gracefully on the next iteration.\n scope = found.shadowRoot;\n }\n }\n\n return found;\n}\n\n/**\n * Resolve a single (non-delimited) segment within `scope`.\n *\n * A segment marked with {@link SHADOW_CHILD_CHAIN_PREFIX} is a root-anchored\n * \"direct child from the root\" chain (emitted by the fallback for a shadow-root\n * scope, where `querySelector` can't express that anchoring). We strip the\n * marker and resolve by strict direct-child descent. The marker is set\n * explicitly by the generator, so this stays correct regardless of what the\n * steps contain (tag, `:nth-of-type`, classes, …). Every other segment —\n * id/attribute-anchored, or any document-scope segment — resolves via a plain\n * `querySelector`.\n */\nfunction resolveSegment(scope: ParentNode, segment: string): Element | null {\n if (segment.startsWith(SHADOW_CHILD_CHAIN_PREFIX)) {\n return resolveChildChain(scope, segment.slice(SHADOW_CHILD_CHAIN_PREFIX.length));\n }\n return scope.querySelector(segment);\n}\n\n/**\n * Resolve a `>`-joined chain as a strict direct-child descent from `scope`. At\n * each level exactly one child matches the step (positional or otherwise via\n * `matches()`), so the walk is deterministic. Returns `null` if any step matches\n * no child.\n */\nfunction resolveChildChain(scope: ParentNode, chain: string): Element | null {\n const steps = chain.split('>').map((s) => s.trim());\n let children: Element[] = Array.from(scope.children);\n let el: Element | null = null;\n for (const step of steps) {\n el = children.find((child) => child.matches(step)) ?? null;\n if (el === null) {\n return null;\n }\n children = Array.from(el.children);\n }\n return el;\n}\n\n/**\n * Build a single positional step for `el`: `tag:nth-of-type(n)`, indexed among\n * its same-tag siblings. A parentless element emits the bare tag.\n *\n * `shadowAware` extends the parentless case: an element at the top of a shadow\n * tree has a null `parentElement` but can still have same-tag peers among the\n * `ShadowRoot`'s children, so it is indexed against those instead. When\n * `shadowAware` is false every parentless element emits the bare tag.\n */\nexport function positionalStep(el: Element, shadowAware: boolean): string {\n const tag = el.tagName.toLowerCase();\n const parent = el.parentElement;\n\n if (parent === null) {\n // Parentless means the document root (`<html>`), a detached element, or the\n // top of a shadow tree. Only the last has siblings worth indexing, and only\n // when the caller asks for shadow-aware stepping.\n const root = el.getRootNode();\n if (shadowAware && isShadowRoot(root)) {\n return `${tag}:nth-of-type(${sameTypeIndexAmong(el, root.children)})`;\n }\n return tag;\n }\n\n return `${tag}:nth-of-type(${sameTypeIndexAmong(el, parent.children)})`;\n}\n\n/**\n * 1-based index of `el` among same-tag siblings in `siblings`, mirroring\n * `:nth-of-type`. Takes an `HTMLCollection` rather than a parent `Element` so a\n * `ShadowRoot`'s children can be counted too — a `ShadowRoot` is not an\n * `Element` but does expose `children`.\n */\nfunction sameTypeIndexAmong(el: Element, siblings: HTMLCollection): number {\n let count = 0;\n for (let i = 0; i < siblings.length; i++) {\n const sibling = siblings[i];\n if (sibling.tagName === el.tagName) {\n count += 1;\n if (sibling === el) {\n return count;\n }\n }\n }\n // Defensive: element not found among its parent's children (shouldn't happen\n // for a live element). Return 1 rather than throwing.\n return 1;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"shadow.js","sourceRoot":"","sources":["../../../src/helpers/shadow.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;;AAEH;;;;;;;;;;;GAWG;A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,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACxC,IAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;QAC5B,IAAI,OAAO,CAAC,OAAO,KAAK,EAAE,CAAC,OAAO,EAAE;YAClC,KAAK,IAAI,CAAC,CAAC;YACX,IAAI,OAAO,KAAK,EAAE,EAAE;gBAClB,OAAO,KAAK,CAAC;aACd;SACF;KACF;IACD,6EAA6E;IAC7E,sDAAsD;IACtD,OAAO,CAAC,CAAC;AACX,CAAC","sourcesContent":["/**\n * Shadow-DOM traversal + re-resolution helpers.\n *\n * CSS selectors cannot pierce shadow boundaries: `document.querySelector` never\n * matches an element that lives inside a shadow root. So a selector that needs\n * to reach into shadow DOM can't be a single flat string — it has to be a\n * sequence of per-tree selectors, one per shadow tree, each resolvable within\n * its own root. We join those segments with `SHADOW_BOUNDARY_DELIMITER` and\n * re-resolve them with `resolveSelector`, descending one `shadowRoot` per\n * boundary.\n *\n * This module owns the primitives that knowledge lives in:\n *\n * - `composedParent` / `rootOf` — walk *out* of a shadow tree (the light-DOM\n * `parentElement` chain dead-ends at a shadow root; `getRootNode().host`\n * crosses the boundary).\n * - `segmentWalk` — split the outward walk into per-tree segments, honoring\n * the configured max shadow depth.\n * - `resolveSelector` — the symmetric inverse of the engine's output: split\n * on the delimiter and pierce open shadow roots to re-find the element.\n * - `walkComposedAncestors` — yield ancestors up the composed tree, honoring a\n * shadow-boundary crossing budget (shared by capture and selector layers).\n * - `collectOpenShadowRoots` — DFS collection of open shadow roots for\n * observer fan-out and deep `querySelectorAll`.\n * - `positionalStep` — a shadow-aware `tag:nth-of-type(n)` builder shared by\n * the orchestrator's descent and the fallback walker, so a shadow-root-top\n * element is still disambiguated against its `ShadowRoot` siblings.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\n/**\n * Delimiter that separates per-shadow-tree segments in a generated selector.\n *\n * Chosen to be visually distinct and trivially splittable, and to be invalid as\n * a real CSS combinator so it can never be confused with a `>` child combinator\n * the engine emits inside a single tree. Example output:\n *\n * `div#host >>> button:nth-of-type(1)`\n *\n * which `resolveSelector` re-resolves as\n * `document.querySelector('div#host').shadowRoot.querySelector('button:nth-of-type(1)')`.\n */\nexport const SHADOW_BOUNDARY_DELIMITER = ' >>> ';\n\n/**\n * Marker prefix for a \"direct child from the root\" chain inside a shadow tree.\n *\n * A positional chain scoped to a `ShadowRoot` (e.g. `div:nth-of-type(2)`) is not\n * anchored: `querySelector` matches it tree-wide, and `:scope` matches nothing\n * on a `ShadowRoot` (it isn't an element), so there is no CSS way to express\n * \"direct child of the root.\" The generator therefore prefixes such chains with\n * this marker and `resolveSelector` resolves them by strict direct-child descent\n * instead of `querySelector`. Keying off this explicit marker — rather than\n * sniffing a segment for the absence of `#`/`[` — keeps the round-trip correct\n * no matter what the steps contain (tag, `:nth-of-type`, classes, …).\n *\n * `:scope > ` is deliberately valid CSS syntax so a generated selector stays a\n * syntactically legal string; its meaning here is purely the descent signal.\n */\nexport const SHADOW_CHILD_CHAIN_PREFIX = ':scope > ';\n\n/**\n * Narrowing guard for shadow roots. Tries `instanceof` first, then falls back\n * to a structural check so shadow roots from another realm (e.g. a same-origin\n * iframe, as in a replay mirror) are recognized too: there the calling page's\n * `ShadowRoot` constructor does not match. Safe in environments without a\n * `ShadowRoot` global, and `null`/`undefined` return `false`.\n */\nexport function isShadowRoot(node: Node): node is ShadowRoot {\n if (typeof ShadowRoot !== 'undefined' && node instanceof ShadowRoot) {\n return true;\n }\n return (\n node != null &&\n node.nodeType === 11 /* DOCUMENT_FRAGMENT_NODE */ &&\n (node as ShadowRoot).host?.nodeType === 1 /* ELEMENT_NODE */\n );\n}\n\n/**\n * Anchor a per-tree segment so it re-resolves within a `ShadowRoot`.\n *\n * Both selector algorithms (the strategy-chain fallback and the legacy Chromium\n * `cssPath`) can emit a segment that is only *positionally* specified — a chain\n * of `tag:nth-*` / class steps with no id or attribute to pin it. In the light\n * DOM the chain is implicitly anchored by the unique `<html>` root; inside a\n * shadow root there is no such root element, so `querySelector` matches the\n * chain tree-wide and can resolve to the wrong element (or none).\n *\n * When `segment` is such a root-anchored positional chain inside a shadow root,\n * we prefix it with {@link SHADOW_CHILD_CHAIN_PREFIX} so `resolveSelector`\n * descends by strict direct-child matching instead of `querySelector`. An\n * id/attribute-anchored segment is already resolvable tree-wide and is returned\n * untouched. `isRootAnchored` is the caller's decision (each generator knows\n * whether its own output reached the tree top vs. short-circuited on an id), so\n * this stays correct regardless of what the steps contain.\n */\nexport function anchorSegmentToShadowScope(segment: string, scope: ParentNode, isRootAnchored: boolean): string {\n if (segment && isRootAnchored && isShadowRoot(scope as Node)) {\n return `${SHADOW_CHILD_CHAIN_PREFIX}${segment}`;\n }\n return segment;\n}\n\n/**\n * Whether the legacy `cssPath` output for `el` is a root-anchored positional\n * chain rather than one anchored by an id.\n *\n * `legacyCssPath` short-circuits at the first element — inclusive of `el` —\n * that carries an `id`, emitting `tag#id > …` from there. If some element in\n * `el`'s ancestor chain has an id the emitted selector is id-anchored (a plain,\n * tree-wide-resolvable `querySelector`); if none does, the chain spans the tree\n * top down to `el` via positional steps and must be marked for direct-child\n * descent inside a shadow root. This walks the same `parentElement` chain the\n * legacy walker does, so the two stay in lockstep.\n */\nexport function legacyPathIsRootAnchored(el: Element): boolean {\n for (let node: Element | null = el; node !== null; node = node.parentElement) {\n if (node.getAttribute('id')) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * The queryable root for `el`'s own tree: the enclosing `ShadowRoot` when `el`\n * lives inside shadow DOM, otherwise the owner document. Both support\n * `querySelectorAll`, so uniqueness checks can be scoped to the correct tree.\n *\n * Preserves the legacy default for non-shadow elements (`ownerDocument`), so\n * nothing changes for the common flat-document case.\n */\nexport function rootOf(el: Element): ParentNode {\n const root = el.getRootNode();\n if (isShadowRoot(root)) {\n return root;\n }\n return el.ownerDocument ?? document;\n}\n\n/**\n * The next element up, crossing shadow boundaries: `parentElement` within a\n * tree, or the shadow host when `el` is at the top of a shadow tree. Returns\n * `null` only at the document root (or a detached non-shadow root).\n */\nexport function composedParent(el: Element): Element | null {\n if (el.parentElement) {\n return el.parentElement;\n }\n const root = el.getRootNode();\n if (isShadowRoot(root)) {\n return root.host;\n }\n return null;\n}\n\n/** One tree's contribution to a piercing selector. */\nexport interface TreeSegment {\n /** Queryable root for this tree — a `Document` or `ShadowRoot`. */\n root: ParentNode;\n /** Element to locate within `root`: the host of the next inner tree, or the original target. */\n target: Element;\n}\n\nexport interface SegmentWalkResult {\n /** Tree segments, outermost (document) first — the order they're joined for output. */\n segments: TreeSegment[];\n /**\n * True when the target sat deeper than `maxShadowDepth` allowed, so inner\n * trees were dropped and the innermost emitted segment targets the shadow\n * host at the depth limit rather than the original target.\n */\n truncated: boolean;\n}\n\n/**\n * Defensive bound on composed-ancestor walks (host-chain iteration in\n * `walkComposedAncestors` and `segmentWalk`). Far above any real shadow nesting\n * (the resolver caps effective depth at `MAX_SHADOW_DOM_DEPTH`). See also\n * {@link MAX_SHADOW_DOM_TRAVERSAL_NODES} for the DFS collection cap.\n */\nexport const MAX_SHADOW_COMPOSED_WALK_ITERATIONS = 1024;\n\n/**\n * Defensive bound on node visits when collecting open shadow roots via DFS.\n * Caps synchronous work inside MutationObserver callbacks on pathologically\n * large trees. See also {@link MAX_SHADOW_COMPOSED_WALK_ITERATIONS} for the\n * ancestor-walk cap.\n */\nexport const MAX_SHADOW_DOM_TRAVERSAL_NODES = 50000;\n\nexport interface OpenShadowRootEntry {\n root: ShadowRoot;\n /** 1-based shadow-boundary depth relative to the collection `root`. */\n depth: number;\n}\n\n/**\n * Yield `start` and each ancestor up the composed tree. Within a tree the walk\n * follows `parentElement`; at the top of a shadow tree it crosses to the host\n * when `crossings < maxShadowDepth`. Yields every element including detached\n * nodes at the top of their tree (where `parentElement` is null).\n */\nexport function* walkComposedAncestors(start: Element, maxShadowDepth: number): Generator<Element> {\n let node: Element | null = start;\n let crossings = 0;\n let iterations = 0;\n\n while (node !== null && iterations < MAX_SHADOW_COMPOSED_WALK_ITERATIONS) {\n iterations += 1;\n yield node;\n\n if (node.parentElement) {\n node = node.parentElement;\n continue;\n }\n if (crossings < maxShadowDepth && typeof node.getRootNode === 'function') {\n const host = composedParent(node);\n if (host && host !== node) {\n crossings += 1;\n node = host;\n continue;\n }\n }\n break;\n }\n}\n\n/**\n * Collect the OPEN shadow roots within `root`'s composed subtree (its own light\n * children and any nested shadow trees), each paired with how many shadow\n * boundary crossings deep it sits relative to `root` (1-based). Bounded by\n * `maxShadowDepth` crossings and by {@link MAX_SHADOW_DOM_TRAVERSAL_NODES}\n * total nodes. Closed roots are invisible (`el.shadowRoot` is null) and skipped.\n */\nexport function collectOpenShadowRoots(root: Element, maxShadowDepth: number): OpenShadowRootEntry[] {\n const found: OpenShadowRootEntry[] = [];\n if (maxShadowDepth <= 0) {\n return found;\n }\n const stack: Array<[Element, number]> = [[root, 0]];\n let visited = 0;\n while (stack.length && visited < MAX_SHADOW_DOM_TRAVERSAL_NODES) {\n visited += 1;\n const [el, depth] = stack.pop() as [Element, number];\n const shadowRoot = el.shadowRoot;\n if (shadowRoot && depth + 1 <= maxShadowDepth) {\n found.push({ root: shadowRoot, depth: depth + 1 });\n const shadowChildren = shadowRoot.children;\n for (let i = 0; i < shadowChildren.length; i++) {\n stack.push([shadowChildren[i], depth + 1]);\n }\n }\n const children = el.children;\n for (let i = 0; i < children.length; i++) {\n stack.push([children[i], depth]);\n }\n }\n return found;\n}\n\n/**\n * Split the outward composed walk from `el` into per-tree segments.\n *\n * Always walks fully out to the document so the outermost segment is\n * document-rooted and therefore re-resolvable. `maxShadowDepth` caps how many\n * shadow boundaries the *emitted* selector descends through: when the target is\n * nested deeper than the budget, the innermost (over-budget) trees are dropped\n * and the result is flagged `truncated` — the innermost kept segment then\n * targets the shadow host at the depth limit (a best-effort, still-resolvable\n * selector for an ancestor of the true target).\n */\nexport function segmentWalk(el: Element, maxShadowDepth: number): SegmentWalkResult {\n // Build innermost-first: one segment per tree, each `target` being the\n // element to locate within that tree (the inner tree's host, or `el`).\n const innermostFirst: TreeSegment[] = [];\n let node: Element | null = el;\n let iterations = 0;\n\n while (node !== null && iterations < MAX_SHADOW_COMPOSED_WALK_ITERATIONS) {\n iterations += 1;\n const root = rootOf(node);\n innermostFirst.push({ root, target: node });\n const actualRoot = node.getRootNode();\n if (!isShadowRoot(actualRoot)) {\n break; // reached the document (or a detached non-shadow root)\n }\n node = actualRoot.host; // cross the boundary outward\n }\n\n const totalCrossings = innermostFirst.length - 1;\n let truncated = false;\n let kept = innermostFirst;\n\n if (totalCrossings > maxShadowDepth) {\n // Drop the innermost over-budget trees, keeping the outermost\n // (maxShadowDepth + 1) trees. The new innermost kept segment's `target` is\n // already the shadow host of the first dropped tree.\n kept = innermostFirst.slice(totalCrossings - maxShadowDepth);\n truncated = true;\n }\n\n // Reverse to outermost-first so the engine joins document → target order.\n return { segments: kept.reverse(), truncated };\n}\n\n/**\n * Re-resolve a generated selector back to its element, piercing open shadow\n * roots at each boundary. The symmetric inverse of `engine.generate`.\n *\n * Returns `null` when any segment fails to match, or when a boundary crossing\n * hits a *closed* shadow root (`host.shadowRoot === null`) — closed roots are\n * opaque from outside, so such selectors cannot round-trip (a documented\n * limitation). Never throws on a malformed segment.\n *\n * @param root Root to resolve against — almost always `document`.\n * @param selector A selector produced by the engine (may contain boundary delimiters).\n */\nexport function resolveSelector(root: ParentNode, selector: string): Element | null {\n const segments = selector.split(SHADOW_BOUNDARY_DELIMITER);\n let scope: ParentNode | null = root;\n let found: Element | null = null;\n\n for (let i = 0; i < segments.length; i++) {\n if (scope === null) {\n return null; // previous segment's host had no (open) shadow root\n }\n const segment = segments[i].trim();\n try {\n found = resolveSegment(scope, segment);\n } catch {\n return null; // malformed segment — never throw out of the resolver\n }\n if (found === null) {\n return null;\n }\n if (i < segments.length - 1) {\n // Descend into this host's shadow root for the next segment. `null` for a\n // closed root ends resolution gracefully on the next iteration.\n scope = found.shadowRoot;\n }\n }\n\n return found;\n}\n\n/**\n * Resolve a single (non-delimited) segment within `scope`.\n *\n * A segment marked with {@link SHADOW_CHILD_CHAIN_PREFIX} is a root-anchored\n * \"direct child from the root\" chain (emitted by the fallback for a shadow-root\n * scope, where `querySelector` can't express that anchoring). We strip the\n * marker and resolve by strict direct-child descent. The marker is set\n * explicitly by the generator, so this stays correct regardless of what the\n * steps contain (tag, `:nth-of-type`, classes, …). Every other segment —\n * id/attribute-anchored, or any document-scope segment — resolves via a plain\n * `querySelector`.\n */\nfunction resolveSegment(scope: ParentNode, segment: string): Element | null {\n if (segment.startsWith(SHADOW_CHILD_CHAIN_PREFIX)) {\n return resolveChildChain(scope, segment.slice(SHADOW_CHILD_CHAIN_PREFIX.length));\n }\n return scope.querySelector(segment);\n}\n\n/**\n * Resolve a `>`-joined chain as a strict direct-child descent from `scope`. At\n * each level exactly one child matches the step (positional or otherwise via\n * `matches()`), so the walk is deterministic. Returns `null` if any step matches\n * no child.\n */\nfunction resolveChildChain(scope: ParentNode, chain: string): Element | null {\n const steps = chain.split('>').map((s) => s.trim());\n let children: Element[] = Array.from(scope.children);\n let el: Element | null = null;\n for (const step of steps) {\n el = children.find((child) => child.matches(step)) ?? null;\n if (el === null) {\n return null;\n }\n children = Array.from(el.children);\n }\n return el;\n}\n\n/**\n * Build a single positional step for `el`: `tag:nth-of-type(n)`, indexed among\n * its same-tag siblings. A parentless element emits the bare tag.\n *\n * `shadowAware` extends the parentless case: an element at the top of a shadow\n * tree has a null `parentElement` but can still have same-tag peers among the\n * `ShadowRoot`'s children, so it is indexed against those instead. When\n * `shadowAware` is false every parentless element emits the bare tag.\n */\nexport function positionalStep(el: Element, shadowAware: boolean): string {\n const tag = el.tagName.toLowerCase();\n const parent = el.parentElement;\n\n if (parent === null) {\n // Parentless means the document root (`<html>`), a detached element, or the\n // top of a shadow tree. Only the last has siblings worth indexing, and only\n // when the caller asks for shadow-aware stepping.\n const root = el.getRootNode();\n if (shadowAware && isShadowRoot(root)) {\n return `${tag}:nth-of-type(${sameTypeIndexAmong(el, root.children)})`;\n }\n return tag;\n }\n\n return `${tag}:nth-of-type(${sameTypeIndexAmong(el, parent.children)})`;\n}\n\n/**\n * 1-based index of `el` among same-tag siblings in `siblings`, mirroring\n * `:nth-of-type`. Takes an `HTMLCollection` rather than a parent `Element` so a\n * `ShadowRoot`'s children can be counted too — a `ShadowRoot` is not an\n * `Element` but does expose `children`.\n */\nfunction sameTypeIndexAmong(el: Element, siblings: HTMLCollection): number {\n let count = 0;\n for (let i = 0; i < siblings.length; i++) {\n const sibling = siblings[i];\n if (sibling.tagName === el.tagName) {\n count += 1;\n if (sibling === el) {\n return count;\n }\n }\n }\n // Defensive: element not found among its parent's children (shouldn't happen\n // for a live element). Return 1 rather than throwing.\n return 1;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amplitude/element-selector",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.3-sr-bfcache-pageshow-snapshot.0",
|
|
4
4
|
"description": "Shared element-selector algorithm consumed by autocapture, the Amplitude dashboard, and the Chrome extension visual tagger.",
|
|
5
5
|
"author": "Amplitude Inc",
|
|
6
6
|
"homepage": "https://github.com/amplitude/Amplitude-TypeScript",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"lib"
|
|
31
31
|
],
|
|
32
32
|
"scripts": {
|
|
33
|
-
"build": "pnpm build:es5
|
|
33
|
+
"build": "pnpm build:es5 && pnpm build:esm",
|
|
34
34
|
"build:es5": "tsc -p ./tsconfig.es5.json",
|
|
35
35
|
"build:esm": "tsc -p ./tsconfig.esm.json",
|
|
36
36
|
"watch": "tsc -p ./tsconfig.esm.json --watch",
|