@amplitude/element-selector 0.2.0 → 0.3.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.
Files changed (52) hide show
  1. package/README.md +29 -3
  2. package/lib/cjs/config/resolve-config.d.ts +21 -3
  3. package/lib/cjs/config/resolve-config.d.ts.map +1 -1
  4. package/lib/cjs/config/resolve-config.js +47 -2
  5. package/lib/cjs/config/resolve-config.js.map +1 -1
  6. package/lib/cjs/engine.d.ts.map +1 -1
  7. package/lib/cjs/engine.js +61 -27
  8. package/lib/cjs/engine.js.map +1 -1
  9. package/lib/cjs/fallback-css-path.d.ts +6 -1
  10. package/lib/cjs/fallback-css-path.d.ts.map +1 -1
  11. package/lib/cjs/fallback-css-path.js +38 -37
  12. package/lib/cjs/fallback-css-path.js.map +1 -1
  13. package/lib/cjs/helpers/shadow.d.ts +196 -0
  14. package/lib/cjs/helpers/shadow.d.ts.map +1 -0
  15. package/lib/cjs/helpers/shadow.js +415 -0
  16. package/lib/cjs/helpers/shadow.js.map +1 -0
  17. package/lib/cjs/index.d.ts +4 -2
  18. package/lib/cjs/index.d.ts.map +1 -1
  19. package/lib/cjs/index.js +19 -1
  20. package/lib/cjs/index.js.map +1 -1
  21. package/lib/cjs/orchestrator.d.ts.map +1 -1
  22. package/lib/cjs/orchestrator.js +4 -2
  23. package/lib/cjs/orchestrator.js.map +1 -1
  24. package/lib/cjs/types.d.ts +36 -1
  25. package/lib/cjs/types.d.ts.map +1 -1
  26. package/lib/cjs/types.js.map +1 -1
  27. package/lib/esm/config/resolve-config.d.ts +21 -3
  28. package/lib/esm/config/resolve-config.d.ts.map +1 -1
  29. package/lib/esm/config/resolve-config.js +46 -2
  30. package/lib/esm/config/resolve-config.js.map +1 -1
  31. package/lib/esm/engine.d.ts.map +1 -1
  32. package/lib/esm/engine.js +61 -27
  33. package/lib/esm/engine.js.map +1 -1
  34. package/lib/esm/fallback-css-path.d.ts +6 -1
  35. package/lib/esm/fallback-css-path.d.ts.map +1 -1
  36. package/lib/esm/fallback-css-path.js +37 -36
  37. package/lib/esm/fallback-css-path.js.map +1 -1
  38. package/lib/esm/helpers/shadow.d.ts +196 -0
  39. package/lib/esm/helpers/shadow.d.ts.map +1 -0
  40. package/lib/esm/helpers/shadow.js +402 -0
  41. package/lib/esm/helpers/shadow.js.map +1 -0
  42. package/lib/esm/index.d.ts +4 -2
  43. package/lib/esm/index.d.ts.map +1 -1
  44. package/lib/esm/index.js +9 -1
  45. package/lib/esm/index.js.map +1 -1
  46. package/lib/esm/orchestrator.d.ts.map +1 -1
  47. package/lib/esm/orchestrator.js +4 -2
  48. package/lib/esm/orchestrator.js.map +1 -1
  49. package/lib/esm/types.d.ts +36 -1
  50. package/lib/esm/types.d.ts.map +1 -1
  51. package/lib/esm/types.js.map +1 -1
  52. package/package.json +1 -1
package/lib/esm/engine.js CHANGED
@@ -26,9 +26,11 @@
26
26
  * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
27
27
  */
28
28
  import { __values } from "tslib";
29
+ import { normalizeResolvedConfig } from './config/resolve-config';
29
30
  import { runOrchestrator } from './orchestrator';
30
31
  import { fallbackCssPath } from './fallback-css-path';
31
32
  import { safeLegacyCssPath } from './legacy-css-path';
33
+ import { anchorSegmentToShadowScope, legacyPathIsRootAnchored, segmentWalk, SHADOW_BOUNDARY_DELIMITER, } from './helpers/shadow';
32
34
  /**
33
35
  * Build a `SelectorEngine` bound to the supplied config.
34
36
  *
@@ -40,42 +42,74 @@ import { safeLegacyCssPath } from './legacy-css-path';
40
42
  */
41
43
  export function createSelectorEngine(initialConfig, options) {
42
44
  if (options === void 0) { options = {}; }
43
- var config = initialConfig;
45
+ var config = normalizeResolvedConfig(initialConfig);
44
46
  var subscribers = new Set();
45
47
  var logger = options.logger;
46
- var orchestratorOptions = {
47
- strategies: options.strategies,
48
- scope: options.scope,
49
- logger: logger,
48
+ // ── Per-tree algorithms: the `config.enabled` axis ────────────────────────
49
+ /**
50
+ * LEGACY algorithm
51
+ * The algorithm has no notion of scope.
52
+ */
53
+ var legacyTree = function (target) { return safeLegacyCssPath(target, logger); };
54
+ /**
55
+ * ENGINE algorithm: the strategy chain, then the hardened fallback, both
56
+ * scoped to the tree's own root.
57
+ */
58
+ var engineTree = function (target, scope) {
59
+ var _a;
60
+ return (_a = runOrchestrator(target, config, { strategies: options.strategies, scope: scope, logger: logger })) !== null && _a !== void 0 ? _a : fallbackCssPath(target, config, { scope: scope });
50
61
  };
62
+ // ── Shadow-aware variant: reachable ONLY from `pierce` ────────────────────
63
+ /**
64
+ * `legacyCssPath` ignores scope, so for a shadow-tree element with no id
65
+ * ancestor it emits an unanchored positional chain that `querySelector` would
66
+ * match tree-wide. Anchor such a chain so `resolveSelector` descends by direct
67
+ * child instead. `engineTree` needs no counterpart — `fallbackCssPath` anchors
68
+ * its own output from the scope it is handed.
69
+ */
70
+ var legacyTreeInShadow = function (target, scope) {
71
+ return anchorSegmentToShadowScope(legacyTree(target, scope), scope, legacyPathIsRootAnchored(target));
72
+ };
73
+ /**
74
+ * Split the outward walk into per-tree segments (capped at `maxShadowDomDepth`
75
+ * boundary crossings), run `perTree` for each segment scoped to that tree's
76
+ * root, and join the results with the boundary delimiter. Passing the per-tree
77
+ * generator as a callback keeps "how to select within one tree" in one place
78
+ * and lets both the legacy and engine algorithms reuse the same walk.
79
+ */
80
+ function pierce(el, perTree) {
81
+ var _a = segmentWalk(el, config.maxShadowDomDepth), segments = _a.segments, truncated = _a.truncated;
82
+ if (truncated) {
83
+ logger === null || logger === void 0 ? void 0 : logger.debug("@amplitude/element-selector: target is nested deeper than maxShadowDomDepth (".concat(config.maxShadowDomDepth, ") \u2014 emitting a best-effort selector for the outermost in-budget shadow host"));
84
+ }
85
+ return segments.map(function (_a) {
86
+ var target = _a.target, root = _a.root;
87
+ return perTree(target, root);
88
+ }).join(SHADOW_BOUNDARY_DELIMITER);
89
+ }
51
90
  return {
52
91
  generate: function (el) {
53
92
  var _a, _b;
54
- // Kill switch: when the customer's remote config has the engine
55
- // disabled (the default for orgs that haven't opted in), emit the same
56
- // Chromium-derived selector autocapture has shipped since before the
57
- // strategy chain existed. This is what makes "flip enabled back to
58
- // false" a one-config-fetch revert for both the SDK and the dashboard —
59
- // they both go through this entry point now.
60
- if (!config.enabled) {
61
- return safeLegacyCssPath(el, logger);
62
- }
63
- // Engine path: try the strategy chain, then the hardened fallback. Both
64
- // are wrapped so a runtime exception (malformed config slipped past the
65
- // resolver, browser API quirks, a bad scope) still produces a usable
66
- // selector. Without this, an autocapture click handler could throw
67
- // mid-flow and the customer would silently lose the event — a worse
68
- // outcome than emitting a less-stable selector.
93
+ // Two independent switches:
94
+ //
95
+ // config.enabled → which per-tree algorithm runs (engine vs legacy)
96
+ // config.shadowDomEnabled → whether we pierce boundaries or stay in one tree
97
+ //
98
+ // One try/catch covers all four corners. It is the safety net: a runtime
99
+ // exception (malformed config slipped past the resolver, browser API
100
+ // quirks, a bad scope, a pathological host chain) still produces a usable
101
+ // selector rather than throwing mid-capture and silently dropping the
102
+ // customer's event.
69
103
  try {
70
- var composed = runOrchestrator(el, config, orchestratorOptions);
71
- if (composed !== null) {
72
- return composed;
104
+ if (!config.shadowDomEnabled) {
105
+ var perTree = config.enabled ? engineTree : legacyTree;
106
+ return perTree(el, (_b = (_a = options.scope) !== null && _a !== void 0 ? _a : el.ownerDocument) !== null && _b !== void 0 ? _b : document);
73
107
  }
74
- return fallbackCssPath(el, config, { scope: (_b = (_a = options.scope) !== null && _a !== void 0 ? _a : el.ownerDocument) !== null && _b !== void 0 ? _b : document });
108
+ return pierce(el, config.enabled ? engineTree : legacyTreeInShadow);
75
109
  }
76
110
  catch (e) {
77
111
  var message = e instanceof Error ? e.message : String(e);
78
- logger === null || logger === void 0 ? void 0 : logger.warn("@amplitude/element-selector: strategy chain threw \u2014 falling back to legacy cssPath: ".concat(message));
112
+ logger === null || logger === void 0 ? void 0 : logger.warn("@amplitude/element-selector: selector generation threw \u2014 falling back to legacy cssPath: ".concat(message));
79
113
  return safeLegacyCssPath(el, logger);
80
114
  }
81
115
  },
@@ -84,7 +118,7 @@ export function createSelectorEngine(initialConfig, options) {
84
118
  },
85
119
  updateConfig: function (next) {
86
120
  var e_1, _a;
87
- config = next;
121
+ config = normalizeResolvedConfig(next);
88
122
  try {
89
123
  // Notify subscribers in insertion order. Errors thrown by individual
90
124
  // subscribers are isolated so one bad listener can't break the others —
@@ -93,7 +127,7 @@ export function createSelectorEngine(initialConfig, options) {
93
127
  for (var subscribers_1 = __values(subscribers), subscribers_1_1 = subscribers_1.next(); !subscribers_1_1.done; subscribers_1_1 = subscribers_1.next()) {
94
128
  var cb = subscribers_1_1.value;
95
129
  try {
96
- cb(next);
130
+ cb(config);
97
131
  }
98
132
  catch (e) {
99
133
  var message = e instanceof Error ? e.message : String(e);
@@ -1 +1 @@
1
- {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../src/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;;AAGH,OAAO,EAAE,eAAe,EAAuB,MAAM,gBAAgB,CAAC;AACtE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAiBtD;;;;;;;;GAQG;AACH,MAAM,UAAU,oBAAoB,CAClC,aAAqC,EACrC,OAAyC;IAAzC,wBAAA,EAAA,YAAyC;IAEzC,IAAI,MAAM,GAA2B,aAAa,CAAC;IACnD,IAAM,WAAW,GAAG,IAAI,GAAG,EAA4C,CAAC;IACxE,IAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAE9B,IAAM,mBAAmB,GAAwB;QAC/C,UAAU,EAAE,OAAO,CAAC,UAAU;QAC9B,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,MAAM,QAAA;KACP,CAAC;IAEF,OAAO;QACL,QAAQ,YAAC,EAAW;;YAClB,gEAAgE;YAChE,uEAAuE;YACvE,qEAAqE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AG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;wBAC3D,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,IAAI,CAAC,8EAAkE,OAAO,CAAE,CAAC,CAAC;qBAC3F;iBACF;;;;;;;;;QACH,CAAC;QAED,cAAc,YAAC,EAA4C;YACzD,WAAW,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YACpB,OAAO;gBACL,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACzB,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Engine factory — composes the strategy chain (via `runOrchestrator`) with\n * the safety-net fallback (`fallbackCssPath`) behind a single `SelectorEngine`\n * interface.\n *\n * This is the surface every consumer talks to:\n *\n * - autocapture SDK plugin → instantiates one engine per init() call,\n * wires it into the click handler, and forwards remote-config updates\n * via `updateConfig`.\n * - app.amplitude.com tagging UI → fetches the customer's remote config\n * out-of-band and stands up a transient engine to compute selectors for\n * elements the user clicks in the iframe.\n * - Chrome extension visual tagger → reads the customer's already-live\n * engine off `window.amplitude.elementSelector` (when present) and\n * subscribes to `onConfigChange` so the extension's preview stays in\n * sync with the customer's runtime config.\n *\n * The factory deliberately takes a pre-resolved `ResolvedSelectorConfig` rather\n * than the raw remote payload — config resolution is a separate concern handled\n * by `resolveSelectorConfig`, and keeping it out of the engine constructor lets\n * dashboard / extension consumers stand up an engine from a static snapshot\n * without re-running the full resolver.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nimport { ElementSelectorLogger, ResolvedSelectorConfig, SelectorEngine } from './types';\nimport { runOrchestrator, OrchestratorOptions } from './orchestrator';\nimport { fallbackCssPath } from './fallback-css-path';\nimport { safeLegacyCssPath } from './legacy-css-path';\n\nexport interface CreateSelectorEngineOptions {\n /** Optional document or shadow root for uniqueness checks. Defaults per-call to the target's owner document. */\n scope?: ParentNode;\n /** Optional override of the strategy chain. Primarily for testing / dashboard ad-hoc runs. */\n strategies?: OrchestratorOptions['strategies'];\n /**\n * Optional logger threaded through the orchestrator and the subscriber-fan-out\n * inside `updateConfig`. When provided, the engine surfaces malformed\n * selectors (`debug`) and listener exceptions (`warn`); when absent it stays\n * silent — preserving the legacy \"fire-and-forget\" semantics existing\n * consumers may rely on.\n */\n logger?: ElementSelectorLogger;\n}\n\n/**\n * Build a `SelectorEngine` bound to the supplied config.\n *\n * The returned engine is independent — calling the factory twice yields two\n * engines with separate config state and separate subscriber lists. This is the\n * shape the autocapture plugin wants (one engine per SDK instance) and the\n * shape the Chrome extension consumes off the page (the extension reads, never\n * writes).\n */\nexport function createSelectorEngine(\n initialConfig: ResolvedSelectorConfig,\n options: CreateSelectorEngineOptions = {},\n): SelectorEngine {\n let config: ResolvedSelectorConfig = initialConfig;\n const subscribers = new Set<(config: ResolvedSelectorConfig) => void>();\n const logger = options.logger;\n\n const orchestratorOptions: OrchestratorOptions = {\n strategies: options.strategies,\n scope: options.scope,\n logger,\n };\n\n return {\n generate(el: Element): string {\n // Kill switch: when the customer's remote config has the engine\n // disabled (the default for orgs that haven't opted in), emit the same\n // Chromium-derived selector autocapture has shipped since before the\n // strategy chain existed. This is what makes \"flip enabled back to\n // false\" a one-config-fetch revert for both the SDK and the dashboard —\n // they both go through this entry point now.\n if (!config.enabled) {\n return safeLegacyCssPath(el, logger);\n }\n\n // Engine path: try the strategy chain, then the hardened fallback. Both\n // are wrapped so a runtime exception (malformed config slipped past the\n // resolver, browser API quirks, a bad scope) still produces a usable\n // selector. Without this, an autocapture click handler could throw\n // mid-flow and the customer would silently lose the event — a worse\n // outcome than emitting a less-stable selector.\n try {\n const composed = runOrchestrator(el, config, orchestratorOptions);\n if (composed !== null) {\n return composed;\n }\n return fallbackCssPath(el, config, { scope: options.scope ?? el.ownerDocument ?? document });\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(`@amplitude/element-selector: strategy chain threw — falling back to legacy cssPath: ${message}`);\n return safeLegacyCssPath(el, logger);\n }\n },\n\n getConfig(): Readonly<ResolvedSelectorConfig> {\n return config;\n },\n\n updateConfig(next: ResolvedSelectorConfig): void {\n config = next;\n // Notify subscribers in insertion order. Errors thrown by individual\n // subscribers are isolated so one bad listener can't break the others —\n // the extension's listener is the canonical consumer here and we don't\n // want SDK-side changes to cascade-fail because of an extension bug.\n for (const cb of subscribers) {\n try {\n cb(next);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(`@amplitude/element-selector: onConfigChange subscriber threw — ${message}`);\n }\n }\n },\n\n onConfigChange(cb: (config: ResolvedSelectorConfig) => void): () => void {\n subscribers.add(cb);\n return () => {\n subscribers.delete(cb);\n };\n },\n };\n}\n"]}
1
+ {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../src/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAElE,OAAO,EAAE,eAAe,EAAuB,MAAM,gBAAgB,CAAC;AACtE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EACL,0BAA0B,EAC1B,wBAAwB,EACxB,WAAW,EACX,yBAAyB,GAC1B,MAAM,kBAAkB,CAAC;AAyB1B;;;;;;;;GAQG;AACH,MAAM,UAAU,oBAAoB,CAClC,aAAqC,EACrC,OAAyC;IAAzC,wBAAA,EAAA,YAAyC;IAEzC,IAAI,MAAM,GAA6B,uBAAuB,CAAC,aAAa,CAAC,CAAC;IAC9E,IAAM,WAAW,GAAG,IAAI,GAAG,EAA8C,CAAC;IAC1E,IAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAE9B,6EAA6E;IAE7E;;;OAGG;IACH,IAAM,UAAU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C,MAAM,CAAC,CAAC,CAAC,CAAC;wBAC3D,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,IAAI,CAAC,8EAAkE,OAAO,CAAE,CAAC,CAAC;qBAC3F;iBACF;;;;;;;;;QACH,CAAC;QAED,cAAc,YAAC,EAA8C;YAC3D,WAAW,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YACpB,OAAO;gBACL,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACzB,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Engine factory — composes the strategy chain (via `runOrchestrator`) with\n * the safety-net fallback (`fallbackCssPath`) behind a single `SelectorEngine`\n * interface.\n *\n * This is the surface every consumer talks to:\n *\n * - autocapture SDK plugin → instantiates one engine per init() call,\n * wires it into the click handler, and forwards remote-config updates\n * via `updateConfig`.\n * - app.amplitude.com tagging UI → fetches the customer's remote config\n * out-of-band and stands up a transient engine to compute selectors for\n * elements the user clicks in the iframe.\n * - Chrome extension visual tagger → reads the customer's already-live\n * engine off `window.amplitude.elementSelector` (when present) and\n * subscribes to `onConfigChange` so the extension's preview stays in\n * sync with the customer's runtime config.\n *\n * The factory deliberately takes a pre-resolved `ResolvedSelectorConfig` rather\n * than the raw remote payload — config resolution is a separate concern handled\n * by `resolveSelectorConfig`, and keeping it out of the engine constructor lets\n * dashboard / extension consumers stand up an engine from a static snapshot\n * without re-running the full resolver.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nimport { normalizeResolvedConfig } from './config/resolve-config';\nimport { ElementSelectorLogger, NormalizedSelectorConfig, ResolvedSelectorConfig, SelectorEngine } from './types';\nimport { runOrchestrator, OrchestratorOptions } from './orchestrator';\nimport { fallbackCssPath } from './fallback-css-path';\nimport { safeLegacyCssPath } from './legacy-css-path';\nimport {\n anchorSegmentToShadowScope,\n legacyPathIsRootAnchored,\n segmentWalk,\n SHADOW_BOUNDARY_DELIMITER,\n} from './helpers/shadow';\n\n/**\n * Produce a selector for `target` that is resolvable **within a single tree**,\n * using `scope` (a `Document` or `ShadowRoot`) for uniqueness checks. The two\n * implementations below are the `config.enabled` axis; `pierce` composes one of\n * them across shadow boundaries for the `config.shadowDomEnabled` axis.\n */\ntype TreeSelector = (target: Element, scope: ParentNode) => string;\n\nexport interface CreateSelectorEngineOptions {\n /** Optional document or shadow root for uniqueness checks. Defaults per-call to the target's owner document. */\n scope?: ParentNode;\n /** Optional override of the strategy chain. Primarily for testing / dashboard ad-hoc runs. */\n strategies?: OrchestratorOptions['strategies'];\n /**\n * Optional logger threaded through the orchestrator and the subscriber-fan-out\n * inside `updateConfig`. When provided, the engine surfaces malformed\n * selectors (`debug`) and listener exceptions (`warn`); when absent it stays\n * silent — preserving the legacy \"fire-and-forget\" semantics existing\n * consumers may rely on.\n */\n logger?: ElementSelectorLogger;\n}\n\n/**\n * Build a `SelectorEngine` bound to the supplied config.\n *\n * The returned engine is independent — calling the factory twice yields two\n * engines with separate config state and separate subscriber lists. This is the\n * shape the autocapture plugin wants (one engine per SDK instance) and the\n * shape the Chrome extension consumes off the page (the extension reads, never\n * writes).\n */\nexport function createSelectorEngine(\n initialConfig: ResolvedSelectorConfig,\n options: CreateSelectorEngineOptions = {},\n): SelectorEngine {\n let config: NormalizedSelectorConfig = normalizeResolvedConfig(initialConfig);\n const subscribers = new Set<(config: NormalizedSelectorConfig) => void>();\n const logger = options.logger;\n\n // ── Per-tree algorithms: the `config.enabled` axis ────────────────────────\n\n /**\n * LEGACY algorithm\n * The algorithm has no notion of scope.\n */\n const legacyTree: TreeSelector = (target) => safeLegacyCssPath(target, logger);\n\n /**\n * ENGINE algorithm: the strategy chain, then the hardened fallback, both\n * scoped to the tree's own root.\n */\n const engineTree: TreeSelector = (target, scope) =>\n runOrchestrator(target, config, { strategies: options.strategies, scope, logger }) ??\n fallbackCssPath(target, config, { scope });\n\n // ── Shadow-aware variant: reachable ONLY from `pierce` ────────────────────\n\n /**\n * `legacyCssPath` ignores scope, so for a shadow-tree element with no id\n * ancestor it emits an unanchored positional chain that `querySelector` would\n * match tree-wide. Anchor such a chain so `resolveSelector` descends by direct\n * child instead. `engineTree` needs no counterpart — `fallbackCssPath` anchors\n * its own output from the scope it is handed.\n */\n const legacyTreeInShadow: TreeSelector = (target, scope) =>\n anchorSegmentToShadowScope(legacyTree(target, scope), scope, legacyPathIsRootAnchored(target));\n\n /**\n * Split the outward walk into per-tree segments (capped at `maxShadowDomDepth`\n * boundary crossings), run `perTree` for each segment scoped to that tree's\n * root, and join the results with the boundary delimiter. Passing the per-tree\n * generator as a callback keeps \"how to select within one tree\" in one place\n * and lets both the legacy and engine algorithms reuse the same walk.\n */\n function pierce(el: Element, perTree: TreeSelector): string {\n const { segments, truncated } = segmentWalk(el, config.maxShadowDomDepth);\n if (truncated) {\n logger?.debug(\n `@amplitude/element-selector: target is nested deeper than maxShadowDomDepth (${config.maxShadowDomDepth}) — emitting a best-effort selector for the outermost in-budget shadow host`,\n );\n }\n return segments.map(({ target, root }) => perTree(target, root)).join(SHADOW_BOUNDARY_DELIMITER);\n }\n\n return {\n generate(el: Element): string {\n // Two independent switches:\n //\n // config.enabled → which per-tree algorithm runs (engine vs legacy)\n // config.shadowDomEnabled → whether we pierce boundaries or stay in one tree\n //\n // One try/catch covers all four corners. It is the safety net: a runtime\n // exception (malformed config slipped past the resolver, browser API\n // quirks, a bad scope, a pathological host chain) still produces a usable\n // selector rather than throwing mid-capture and silently dropping the\n // customer's event.\n try {\n if (!config.shadowDomEnabled) {\n const perTree = config.enabled ? engineTree : legacyTree;\n return perTree(el, options.scope ?? el.ownerDocument ?? document);\n }\n return pierce(el, config.enabled ? engineTree : legacyTreeInShadow);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(\n `@amplitude/element-selector: selector generation threw — falling back to legacy cssPath: ${message}`,\n );\n return safeLegacyCssPath(el, logger);\n }\n },\n\n getConfig(): Readonly<NormalizedSelectorConfig> {\n return config;\n },\n\n updateConfig(next: ResolvedSelectorConfig): void {\n config = normalizeResolvedConfig(next);\n // Notify subscribers in insertion order. Errors thrown by individual\n // subscribers are isolated so one bad listener can't break the others —\n // the extension's listener is the canonical consumer here and we don't\n // want SDK-side changes to cascade-fail because of an extension bug.\n for (const cb of subscribers) {\n try {\n cb(config);\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n logger?.warn(`@amplitude/element-selector: onConfigChange subscriber threw — ${message}`);\n }\n }\n },\n\n onConfigChange(cb: (config: NormalizedSelectorConfig) => void): () => void {\n subscribers.add(cb);\n return () => {\n subscribers.delete(cb);\n };\n },\n };\n}\n"]}
@@ -47,7 +47,12 @@ export interface FallbackCssPathOptions {
47
47
  *
48
48
  * Honors `config.maxAncestorWalkDepth` defensively — once the depth limit is
49
49
  * reached, the walker stops and returns whatever it has built so far rooted at
50
- * the deepest reached ancestor.
50
+ * the deepest reached ancestor. Exception: a shadow-root scope always walks to
51
+ * the tree root (see `honorDepthCap`).
52
+ *
53
+ * A depth-capped light-DOM chain is relative and may match more than one
54
+ * element — `resolveSelector` returns the first match, not necessarily the
55
+ * target. Treat capped paths as locators, not identities.
51
56
  */
52
57
  export declare function fallbackCssPath(el: Element, config: ResolvedSelectorConfig, options?: FallbackCssPathOptions): string;
53
58
  //# sourceMappingURL=fallback-css-path.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"fallback-css-path.d.ts","sourceRoot":"","sources":["../../src/fallback-css-path.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,OAAO,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAIjD,MAAM,WAAW,sBAAsB;IACrC,mGAAmG;IACnG,KAAK,CAAC,EAAE,UAAU,CAAC;CACpB;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAC7B,EAAE,EAAE,OAAO,EACX,MAAM,EAAE,sBAAsB,EAC9B,OAAO,GAAE,sBAA2B,GACnC,MAAM,CAgCR"}
1
+ {"version":3,"file":"fallback-css-path.d.ts","sourceRoot":"","sources":["../../src/fallback-css-path.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,OAAO,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAMjD,MAAM,WAAW,sBAAsB;IACrC,mGAAmG;IACnG,KAAK,CAAC,EAAE,UAAU,CAAC;CACpB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,eAAe,CAC7B,EAAE,EAAE,OAAO,EACX,MAAM,EAAE,sBAAsB,EAC9B,OAAO,GAAE,sBAA2B,GACnC,MAAM,CA0DR"}
@@ -37,28 +37,43 @@
37
37
  * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
38
38
  */
39
39
  import { __read, __spreadArray } from "tslib";
40
+ import { normalizeResolvedConfig } from './config/resolve-config';
40
41
  import { getStableId } from './helpers/get-stable-id';
41
42
  import { escapeIdForCss } from './helpers/escape-id';
43
+ import { isShadowRoot, positionalStep, SHADOW_CHILD_CHAIN_PREFIX } from './helpers/shadow';
42
44
  /**
43
45
  * Build a positional CSS selector for `el`, using stable ids as anchors when
44
46
  * available and falling back to `tag:nth-of-type(n)` for disambiguation.
45
47
  *
46
48
  * Honors `config.maxAncestorWalkDepth` defensively — once the depth limit is
47
49
  * reached, the walker stops and returns whatever it has built so far rooted at
48
- * the deepest reached ancestor.
50
+ * the deepest reached ancestor. Exception: a shadow-root scope always walks to
51
+ * the tree root (see `honorDepthCap`).
52
+ *
53
+ * A depth-capped light-DOM chain is relative and may match more than one
54
+ * element — `resolveSelector` returns the first match, not necessarily the
55
+ * target. Treat capped paths as locators, not identities.
49
56
  */
50
57
  export function fallbackCssPath(el, config, options) {
51
58
  var _a, _b;
52
59
  if (options === void 0) { options = {}; }
60
+ var resolved = normalizeResolvedConfig(config);
53
61
  var scope = (_b = (_a = options.scope) !== null && _a !== void 0 ? _a : el.ownerDocument) !== null && _b !== void 0 ? _b : document;
62
+ var scopeIsShadowRoot = isShadowRoot(scope);
54
63
  var segments = [];
55
64
  var cursor = el;
56
65
  var depth = 0;
66
+ // The `SHADOW_CHILD_CHAIN_PREFIX` marker below is only emitted when the walk
67
+ // terminates naturally, and it's the only thing anchoring a positional chain
68
+ // inside a shadow root. Capping the walk there drops the marker, so
69
+ // `resolveSelector` matches the first same-shaped subtree instead of the
70
+ // target. The cap targets deep light DOMs; skipping it here is cheap.
71
+ var honorDepthCap = !(resolved.shadowDomEnabled && scopeIsShadowRoot);
57
72
  while (cursor !== null) {
58
- if (config.maxAncestorWalkDepth !== undefined && depth > config.maxAncestorWalkDepth) {
73
+ if (honorDepthCap && resolved.maxAncestorWalkDepth !== undefined && depth > resolved.maxAncestorWalkDepth) {
59
74
  break;
60
75
  }
61
- var id = getStableId(cursor, config);
76
+ var id = getStableId(cursor, resolved);
62
77
  if (id !== null) {
63
78
  // Anchor format mirrors the stableId strategy: `tag#id` with the id
64
79
  // CSS-escaped. Only terminate if the composed selector uniquely resolves
@@ -69,43 +84,29 @@ export function fallbackCssPath(el, config, options) {
69
84
  return candidate;
70
85
  }
71
86
  }
72
- segments.unshift(stepFor(cursor));
87
+ // `positionalStep` emits `tag:nth-of-type(n)` for an element with a parent
88
+ // and the bare `tag` for the document root. `config.shadowDomEnabled` also
89
+ // lets it index a shadow-root-top element against its `ShadowRoot` siblings —
90
+ // its `parentElement` is null, but it can have same-tag peers.
91
+ segments.unshift(positionalStep(cursor, resolved.shadowDomEnabled));
73
92
  cursor = cursor.parentElement;
74
93
  depth += 1;
75
94
  }
76
- // Walked all the way to the document root without finding an id. The first
77
- // segment is whatever `<html>` produced (which is just `html` since it has
78
- // no parent and no same-tag siblings).
79
- return segments.join(' > ');
80
- }
81
- /**
82
- * Build a single step. For an element with a parent: `tag:nth-of-type(n)`.
83
- * For a root element (no parent — i.e. <html>): just `tag`.
84
- *
85
- * Class-based disambiguation is intentionally not emitted in v1 — see the
86
- * design doc, "Why we don't use classes for sibling disambiguation". The
87
- * `filterClasses` helper is imported in the package for future iterations.
88
- */
89
- function stepFor(el) {
90
- var tag = el.tagName.toLowerCase();
91
- var parent = el.parentElement;
92
- if (parent === null) {
93
- return tag;
94
- }
95
- var index = sameTypeIndex(el, parent);
96
- return "".concat(tag, ":nth-of-type(").concat(index, ")");
97
- }
98
- function sameTypeIndex(el, parent) {
99
- var count = 0;
100
- for (var i = 0; i < parent.children.length; i++) {
101
- var sibling = parent.children[i];
102
- if (sibling.tagName === el.tagName) {
103
- count += 1;
104
- if (sibling === el)
105
- return count;
106
- }
95
+ var path = segments.join(' > ');
96
+ // In the light DOM the chain's first segment is `<html>` (unique), which
97
+ // anchors it. Inside a shadow root there is no anchoring root element, so a
98
+ // bare positional chain would match tree-wide. When we reached the top of the
99
+ // tree naturally (`cursor === null`, not a depth-limit break), the chain spans
100
+ // root → target via direct children — mark it so `resolveSelector` resolves it
101
+ // by direct-child descent. The marker is explicit (not inferred from the step
102
+ // syntax), so it stays correct even if steps later include classes.
103
+ //
104
+ // Requires `shadowDomEnabled`: the marker is only meaningful to a resolver that
105
+ // is descending shadow roots, so a `ShadowRoot` scope alone doesn't produce it.
106
+ if (resolved.shadowDomEnabled && scopeIsShadowRoot && cursor === null) {
107
+ return "".concat(SHADOW_CHILD_CHAIN_PREFIX).concat(path);
107
108
  }
108
- return 1;
109
+ return path;
109
110
  }
110
111
  function isUniqueMatch(scope, selector, el) {
111
112
  var matches;
@@ -1 +1 @@
1
- {"version":3,"file":"fallback-css-path.js","sourceRoot":"","sources":["../../src/fallback-css-path.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;;AAGH,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAOrD;;;;;;;GAOG;AACH,MAAM,UAAU,eAAe,CAC7B,EAAW,EACX,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AAM,GAAG,EAAE,CAAC,aAAa,CAAC;IAChC,IAAI,MAAM,KAAK,IAAI,EAAE;QACnB,OAAO,GAAG,CAAC;KACZ;IACD,IAAM,KAAK,GAAG,aAAa,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;IACxC,OAAO,UAAG,GAAG,0BAAgB,KAAK,MAAG,CAAC;AACxC,CAAC;AAED,SAAS,aAAa,CAAC,EAAW,EAAE,MAAe;IACjD,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QAC/C,IAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QACnC,IAAI,OAAO,CAAC,OAAO,KAAK,EAAE,CAAC,OAAO,EAAE;YAClC,KAAK,IAAI,CAAC,CAAC;YACX,IAAI,OAAO,KAAK,EAAE;gBAAE,OAAO,KAAK,CAAC;SAClC;KACF;IACD,OAAO,CAAC,CAAC;AACX,CAAC;AAED,SAAS,aAAa,CAAC,KAAiB,EAAE,QAAgB,EAAE,EAAW;IACrE,IAAI,OAA4B,CAAC;IACjC,IAAI;QACF,OAAO,GAAG,KAAK,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC;KAC5C;IAAC,OAAO,EAAE,EAAE;QACX,OAAO,KAAK,CAAC;KACd;IACD,OAAO,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;AACnD,CAAC","sourcesContent":["/**\n * Fallback CSS-path walker — the safety net for the v1 element-selector\n * algorithm.\n *\n * When the orchestrator's strategy chain finds nothing usable across the full\n * ancestor walk, the engine invokes this fallback. It produces a positional\n * selector by walking up from the target to <html>, expressing each step as\n * either an id anchor (when one survives the autogen filter) or a\n * `tag:nth-of-type(n)` step.\n *\n * Key differences from the legacy autocapture `cssPath`:\n *\n * 1. Ids are filtered through `getStableId`, which honors the\n * explicit-tracking-attribute suppression signal AND the autogenerated-id\n * pattern pack. The legacy `cssPath` would happily anchor on `id=\":r5:\"`\n * and produce selectors that never match across page loads.\n *\n * 2. Classes — when they're used at all for sibling disambiguation — are\n * filtered through `filterClasses` against the unstable-class pattern\n * pack. The current v1 implementation here doesn't emit classes (we lean\n * entirely on `:nth-of-type` for sibling disambiguation), but the\n * filtering helper is wired through so future iterations can opt back in\n * surgically without re-deriving the policy.\n *\n * 3. A unique anchor id terminates the walk early — once we hit `body#main`,\n * we don't need to keep walking up to `<html>`.\n *\n * 4. Ambiguous id anchors are skipped. Duplicate ids are invalid HTML but\n * common enough in the wild that fallback must not emit selectors that\n * resolve to the wrong target.\n *\n * Output format mirrors the orchestrator's output: `<anchor> > <descent>`.\n * When no usable id is found anywhere on the walk, the fallback emits a\n * pure-positional selector rooted at `html`.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nimport { ResolvedSelectorConfig } from './types';\nimport { getStableId } from './helpers/get-stable-id';\nimport { escapeIdForCss } from './helpers/escape-id';\n\nexport interface FallbackCssPathOptions {\n /** Document or shadow root used for uniqueness checks. Defaults to the target's owner document. */\n scope?: ParentNode;\n}\n\n/**\n * Build a positional CSS selector for `el`, using stable ids as anchors when\n * available and falling back to `tag:nth-of-type(n)` for disambiguation.\n *\n * Honors `config.maxAncestorWalkDepth` defensively — once the depth limit is\n * reached, the walker stops and returns whatever it has built so far rooted at\n * the deepest reached ancestor.\n */\nexport function fallbackCssPath(\n el: Element,\n config: ResolvedSelectorConfig,\n options: FallbackCssPathOptions = {},\n): string {\n const scope: ParentNode = options.scope ?? el.ownerDocument ?? document;\n const segments: string[] = [];\n let cursor: Element | null = el;\n let depth = 0;\n\n while (cursor !== null) {\n if (config.maxAncestorWalkDepth !== undefined && depth > config.maxAncestorWalkDepth) {\n break;\n }\n\n const id = getStableId(cursor, config);\n if (id !== null) {\n // Anchor format mirrors the stableId strategy: `tag#id` with the id\n // CSS-escaped. Only terminate if the composed selector uniquely resolves\n // to the target; duplicate ids should fall through to positional steps.\n const anchorSegment = `${cursor.tagName.toLowerCase()}#${escapeIdForCss(id)}`;\n const candidate = [anchorSegment, ...segments].join(' > ');\n if (isUniqueMatch(scope, candidate, el)) {\n return candidate;\n }\n }\n\n segments.unshift(stepFor(cursor));\n cursor = cursor.parentElement;\n depth += 1;\n }\n\n // Walked all the way to the document root without finding an id. The first\n // segment is whatever `<html>` produced (which is just `html` since it has\n // no parent and no same-tag siblings).\n return segments.join(' > ');\n}\n\n/**\n * Build a single step. For an element with a parent: `tag:nth-of-type(n)`.\n * For a root element (no parent — i.e. <html>): just `tag`.\n *\n * Class-based disambiguation is intentionally not emitted in v1 — see the\n * design doc, \"Why we don't use classes for sibling disambiguation\". The\n * `filterClasses` helper is imported in the package for future iterations.\n */\nfunction stepFor(el: Element): string {\n const tag = el.tagName.toLowerCase();\n const parent = el.parentElement;\n if (parent === null) {\n return tag;\n }\n const index = sameTypeIndex(el, parent);\n return `${tag}:nth-of-type(${index})`;\n}\n\nfunction sameTypeIndex(el: Element, parent: Element): number {\n let count = 0;\n for (let i = 0; i < parent.children.length; i++) {\n const sibling = parent.children[i];\n if (sibling.tagName === el.tagName) {\n count += 1;\n if (sibling === el) return count;\n }\n }\n return 1;\n}\n\nfunction isUniqueMatch(scope: ParentNode, selector: string, el: Element): boolean {\n let matches: NodeListOf<Element>;\n try {\n matches = scope.querySelectorAll(selector);\n } catch (_e) {\n return false;\n }\n return matches.length === 1 && matches[0] === el;\n}\n"]}
1
+ {"version":3,"file":"fallback-css-path.js","sourceRoot":"","sources":["../../src/fallback-css-path.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;;AAGH,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,E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CAAC,KAAK,EAAE,SAAS,EAAE,EAAE,CAAC,EAAE;gBACvC,OAAO,SAAS,CAAC;aAClB;SACF;QAED,2EAA2E;QAC3E,2EAA2E;QAC3E,8EAA8E;QAC9E,+DAA+D;QAC/D,QAAQ,CAAC,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,QAAQ,CAAC,gBAAgB,CAAC,CAAC,CAAC;QACpE,MAAM,GAAG,MAAM,CAAC,aAAa,CAAC;QAC9B,KAAK,IAAI,CAAC,CAAC;KACZ;IAED,IAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAElC,yEAAyE;IACzE,4EAA4E;IAC5E,8EAA8E;IAC9E,+EAA+E;IAC/E,+EAA+E;IAC/E,8EAA8E;IAC9E,oEAAoE;IACpE,EAAE;IACF,gFAAgF;IAChF,gFAAgF;IAChF,IAAI,QAAQ,CAAC,gBAAgB,IAAI,iBAAiB,IAAI,MAAM,KAAK,IAAI,EAAE;QACrE,OAAO,UAAG,yBAAyB,SAAG,IAAI,CAAE,CAAC;KAC9C;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,aAAa,CAAC,KAAiB,EAAE,QAAgB,EAAE,EAAW;IACrE,IAAI,OAA4B,CAAC;IACjC,IAAI;QACF,OAAO,GAAG,KAAK,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC;KAC5C;IAAC,OAAO,EAAE,EAAE;QACX,OAAO,KAAK,CAAC;KACd;IACD,OAAO,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;AACnD,CAAC","sourcesContent":["/**\n * Fallback CSS-path walker — the safety net for the v1 element-selector\n * algorithm.\n *\n * When the orchestrator's strategy chain finds nothing usable across the full\n * ancestor walk, the engine invokes this fallback. It produces a positional\n * selector by walking up from the target to <html>, expressing each step as\n * either an id anchor (when one survives the autogen filter) or a\n * `tag:nth-of-type(n)` step.\n *\n * Key differences from the legacy autocapture `cssPath`:\n *\n * 1. Ids are filtered through `getStableId`, which honors the\n * explicit-tracking-attribute suppression signal AND the autogenerated-id\n * pattern pack. The legacy `cssPath` would happily anchor on `id=\":r5:\"`\n * and produce selectors that never match across page loads.\n *\n * 2. Classes — when they're used at all for sibling disambiguation — are\n * filtered through `filterClasses` against the unstable-class pattern\n * pack. The current v1 implementation here doesn't emit classes (we lean\n * entirely on `:nth-of-type` for sibling disambiguation), but the\n * filtering helper is wired through so future iterations can opt back in\n * surgically without re-deriving the policy.\n *\n * 3. A unique anchor id terminates the walk early — once we hit `body#main`,\n * we don't need to keep walking up to `<html>`.\n *\n * 4. Ambiguous id anchors are skipped. Duplicate ids are invalid HTML but\n * common enough in the wild that fallback must not emit selectors that\n * resolve to the wrong target.\n *\n * Output format mirrors the orchestrator's output: `<anchor> > <descent>`.\n * When no usable id is found anywhere on the walk, the fallback emits a\n * pure-positional selector rooted at `html`.\n *\n * See the design doc:\n * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md\n */\n\nimport { ResolvedSelectorConfig } from './types';\nimport { normalizeResolvedConfig } from './config/resolve-config';\nimport { getStableId } from './helpers/get-stable-id';\nimport { escapeIdForCss } from './helpers/escape-id';\nimport { isShadowRoot, positionalStep, SHADOW_CHILD_CHAIN_PREFIX } from './helpers/shadow';\n\nexport interface FallbackCssPathOptions {\n /** Document or shadow root used for uniqueness checks. Defaults to the target's owner document. */\n scope?: ParentNode;\n}\n\n/**\n * Build a positional CSS selector for `el`, using stable ids as anchors when\n * available and falling back to `tag:nth-of-type(n)` for disambiguation.\n *\n * Honors `config.maxAncestorWalkDepth` defensively — once the depth limit is\n * reached, the walker stops and returns whatever it has built so far rooted at\n * the deepest reached ancestor. Exception: a shadow-root scope always walks to\n * the tree root (see `honorDepthCap`).\n *\n * A depth-capped light-DOM chain is relative and may match more than one\n * element — `resolveSelector` returns the first match, not necessarily the\n * target. Treat capped paths as locators, not identities.\n */\nexport function fallbackCssPath(\n el: Element,\n config: ResolvedSelectorConfig,\n options: FallbackCssPathOptions = {},\n): string {\n const resolved = normalizeResolvedConfig(config);\n const scope: ParentNode = options.scope ?? el.ownerDocument ?? document;\n const scopeIsShadowRoot = isShadowRoot(scope as Node);\n const segments: string[] = [];\n let cursor: Element | null = el;\n let depth = 0;\n\n // The `SHADOW_CHILD_CHAIN_PREFIX` marker below is only emitted when the walk\n // terminates naturally, and it's the only thing anchoring a positional chain\n // inside a shadow root. Capping the walk there drops the marker, so\n // `resolveSelector` matches the first same-shaped subtree instead of the\n // target. The cap targets deep light DOMs; skipping it here is cheap.\n const honorDepthCap = !(resolved.shadowDomEnabled && scopeIsShadowRoot);\n\n while (cursor !== null) {\n if (honorDepthCap && resolved.maxAncestorWalkDepth !== undefined && depth > resolved.maxAncestorWalkDepth) {\n break;\n }\n\n const id = getStableId(cursor, resolved);\n if (id !== null) {\n // Anchor format mirrors the stableId strategy: `tag#id` with the id\n // CSS-escaped. Only terminate if the composed selector uniquely resolves\n // to the target; duplicate ids should fall through to positional steps.\n const anchorSegment = `${cursor.tagName.toLowerCase()}#${escapeIdForCss(id)}`;\n const candidate = [anchorSegment, ...segments].join(' > ');\n if (isUniqueMatch(scope, candidate, el)) {\n return candidate;\n }\n }\n\n // `positionalStep` emits `tag:nth-of-type(n)` for an element with a parent\n // and the bare `tag` for the document root. `config.shadowDomEnabled` also\n // lets it index a shadow-root-top element against its `ShadowRoot` siblings —\n // its `parentElement` is null, but it can have same-tag peers.\n segments.unshift(positionalStep(cursor, resolved.shadowDomEnabled));\n cursor = cursor.parentElement;\n depth += 1;\n }\n\n const path = segments.join(' > ');\n\n // In the light DOM the chain's first segment is `<html>` (unique), which\n // anchors it. Inside a shadow root there is no anchoring root element, so a\n // bare positional chain would match tree-wide. When we reached the top of the\n // tree naturally (`cursor === null`, not a depth-limit break), the chain spans\n // root → target via direct children — mark it so `resolveSelector` resolves it\n // by direct-child descent. The marker is explicit (not inferred from the step\n // syntax), so it stays correct even if steps later include classes.\n //\n // Requires `shadowDomEnabled`: the marker is only meaningful to a resolver that\n // is descending shadow roots, so a `ShadowRoot` scope alone doesn't produce it.\n if (resolved.shadowDomEnabled && scopeIsShadowRoot && cursor === null) {\n return `${SHADOW_CHILD_CHAIN_PREFIX}${path}`;\n }\n\n return path;\n}\n\nfunction isUniqueMatch(scope: ParentNode, selector: string, el: Element): boolean {\n let matches: NodeListOf<Element>;\n try {\n matches = scope.querySelectorAll(selector);\n } catch (_e) {\n return false;\n }\n return matches.length === 1 && matches[0] === el;\n}\n"]}
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Shadow-DOM traversal + re-resolution helpers.
3
+ *
4
+ * CSS selectors cannot pierce shadow boundaries: `document.querySelector` never
5
+ * matches an element that lives inside a shadow root. So a selector that needs
6
+ * to reach into shadow DOM can't be a single flat string — it has to be a
7
+ * sequence of per-tree selectors, one per shadow tree, each resolvable within
8
+ * its own root. We join those segments with `SHADOW_BOUNDARY_DELIMITER` and
9
+ * re-resolve them with `resolveSelector`, descending one `shadowRoot` per
10
+ * boundary.
11
+ *
12
+ * This module owns the primitives that knowledge lives in:
13
+ *
14
+ * - `composedParent` / `rootOf` — walk *out* of a shadow tree (the light-DOM
15
+ * `parentElement` chain dead-ends at a shadow root; `getRootNode().host`
16
+ * crosses the boundary).
17
+ * - `segmentWalk` — split the outward walk into per-tree segments, honoring
18
+ * the configured max shadow depth.
19
+ * - `resolveSelector` — the symmetric inverse of the engine's output: split
20
+ * on the delimiter and pierce open shadow roots to re-find the element.
21
+ * - `walkComposedAncestors` — yield ancestors up the composed tree, honoring a
22
+ * shadow-boundary crossing budget (shared by capture and selector layers).
23
+ * - `collectOpenShadowRoots` — DFS collection of open shadow roots for
24
+ * observer fan-out and deep `querySelectorAll`.
25
+ * - `positionalStep` — a shadow-aware `tag:nth-of-type(n)` builder shared by
26
+ * the orchestrator's descent and the fallback walker, so a shadow-root-top
27
+ * element is still disambiguated against its `ShadowRoot` siblings.
28
+ *
29
+ * See the design doc:
30
+ * packages/plugin-autocapture-browser/element-selector-strategy-v1-no-classes.md
31
+ */
32
+ /**
33
+ * Delimiter that separates per-shadow-tree segments in a generated selector.
34
+ *
35
+ * Chosen to be visually distinct and trivially splittable, and to be invalid as
36
+ * a real CSS combinator so it can never be confused with a `>` child combinator
37
+ * the engine emits inside a single tree. Example output:
38
+ *
39
+ * `div#host >>> button:nth-of-type(1)`
40
+ *
41
+ * which `resolveSelector` re-resolves as
42
+ * `document.querySelector('div#host').shadowRoot.querySelector('button:nth-of-type(1)')`.
43
+ */
44
+ export declare const SHADOW_BOUNDARY_DELIMITER = " >>> ";
45
+ /**
46
+ * Marker prefix for a "direct child from the root" chain inside a shadow tree.
47
+ *
48
+ * A positional chain scoped to a `ShadowRoot` (e.g. `div:nth-of-type(2)`) is not
49
+ * anchored: `querySelector` matches it tree-wide, and `:scope` matches nothing
50
+ * on a `ShadowRoot` (it isn't an element), so there is no CSS way to express
51
+ * "direct child of the root." The generator therefore prefixes such chains with
52
+ * this marker and `resolveSelector` resolves them by strict direct-child descent
53
+ * instead of `querySelector`. Keying off this explicit marker — rather than
54
+ * sniffing a segment for the absence of `#`/`[` — keeps the round-trip correct
55
+ * no matter what the steps contain (tag, `:nth-of-type`, classes, …).
56
+ *
57
+ * `:scope > ` is deliberately valid CSS syntax so a generated selector stays a
58
+ * syntactically legal string; its meaning here is purely the descent signal.
59
+ */
60
+ export declare const SHADOW_CHILD_CHAIN_PREFIX = ":scope > ";
61
+ /** Narrowing guard that tolerates environments without a `ShadowRoot` global. */
62
+ export declare function isShadowRoot(node: Node): node is ShadowRoot;
63
+ /**
64
+ * Anchor a per-tree segment so it re-resolves within a `ShadowRoot`.
65
+ *
66
+ * Both selector algorithms (the strategy-chain fallback and the legacy Chromium
67
+ * `cssPath`) can emit a segment that is only *positionally* specified — a chain
68
+ * of `tag:nth-*` / class steps with no id or attribute to pin it. In the light
69
+ * DOM the chain is implicitly anchored by the unique `<html>` root; inside a
70
+ * shadow root there is no such root element, so `querySelector` matches the
71
+ * chain tree-wide and can resolve to the wrong element (or none).
72
+ *
73
+ * When `segment` is such a root-anchored positional chain inside a shadow root,
74
+ * we prefix it with {@link SHADOW_CHILD_CHAIN_PREFIX} so `resolveSelector`
75
+ * descends by strict direct-child matching instead of `querySelector`. An
76
+ * id/attribute-anchored segment is already resolvable tree-wide and is returned
77
+ * untouched. `isRootAnchored` is the caller's decision (each generator knows
78
+ * whether its own output reached the tree top vs. short-circuited on an id), so
79
+ * this stays correct regardless of what the steps contain.
80
+ */
81
+ export declare function anchorSegmentToShadowScope(segment: string, scope: ParentNode, isRootAnchored: boolean): string;
82
+ /**
83
+ * Whether the legacy `cssPath` output for `el` is a root-anchored positional
84
+ * chain rather than one anchored by an id.
85
+ *
86
+ * `legacyCssPath` short-circuits at the first element — inclusive of `el` —
87
+ * that carries an `id`, emitting `tag#id > …` from there. If some element in
88
+ * `el`'s ancestor chain has an id the emitted selector is id-anchored (a plain,
89
+ * tree-wide-resolvable `querySelector`); if none does, the chain spans the tree
90
+ * top down to `el` via positional steps and must be marked for direct-child
91
+ * descent inside a shadow root. This walks the same `parentElement` chain the
92
+ * legacy walker does, so the two stay in lockstep.
93
+ */
94
+ export declare function legacyPathIsRootAnchored(el: Element): boolean;
95
+ /**
96
+ * The queryable root for `el`'s own tree: the enclosing `ShadowRoot` when `el`
97
+ * lives inside shadow DOM, otherwise the owner document. Both support
98
+ * `querySelectorAll`, so uniqueness checks can be scoped to the correct tree.
99
+ *
100
+ * Preserves the legacy default for non-shadow elements (`ownerDocument`), so
101
+ * nothing changes for the common flat-document case.
102
+ */
103
+ export declare function rootOf(el: Element): ParentNode;
104
+ /**
105
+ * The next element up, crossing shadow boundaries: `parentElement` within a
106
+ * tree, or the shadow host when `el` is at the top of a shadow tree. Returns
107
+ * `null` only at the document root (or a detached non-shadow root).
108
+ */
109
+ export declare function composedParent(el: Element): Element | null;
110
+ /** One tree's contribution to a piercing selector. */
111
+ export interface TreeSegment {
112
+ /** Queryable root for this tree — a `Document` or `ShadowRoot`. */
113
+ root: ParentNode;
114
+ /** Element to locate within `root`: the host of the next inner tree, or the original target. */
115
+ target: Element;
116
+ }
117
+ export interface SegmentWalkResult {
118
+ /** Tree segments, outermost (document) first — the order they're joined for output. */
119
+ segments: TreeSegment[];
120
+ /**
121
+ * True when the target sat deeper than `maxShadowDepth` allowed, so inner
122
+ * trees were dropped and the innermost emitted segment targets the shadow
123
+ * host at the depth limit rather than the original target.
124
+ */
125
+ truncated: boolean;
126
+ }
127
+ /**
128
+ * Defensive bound on composed-ancestor walks (host-chain iteration in
129
+ * `walkComposedAncestors` and `segmentWalk`). Far above any real shadow nesting
130
+ * (the resolver caps effective depth at `MAX_SHADOW_DOM_DEPTH`). See also
131
+ * {@link MAX_SHADOW_DOM_TRAVERSAL_NODES} for the DFS collection cap.
132
+ */
133
+ export declare const MAX_SHADOW_COMPOSED_WALK_ITERATIONS = 1024;
134
+ /**
135
+ * Defensive bound on node visits when collecting open shadow roots via DFS.
136
+ * Caps synchronous work inside MutationObserver callbacks on pathologically
137
+ * large trees. See also {@link MAX_SHADOW_COMPOSED_WALK_ITERATIONS} for the
138
+ * ancestor-walk cap.
139
+ */
140
+ export declare const MAX_SHADOW_DOM_TRAVERSAL_NODES = 50000;
141
+ export interface OpenShadowRootEntry {
142
+ root: ShadowRoot;
143
+ /** 1-based shadow-boundary depth relative to the collection `root`. */
144
+ depth: number;
145
+ }
146
+ /**
147
+ * Yield `start` and each ancestor up the composed tree. Within a tree the walk
148
+ * follows `parentElement`; at the top of a shadow tree it crosses to the host
149
+ * when `crossings < maxShadowDepth`. Yields every element including detached
150
+ * nodes at the top of their tree (where `parentElement` is null).
151
+ */
152
+ export declare function walkComposedAncestors(start: Element, maxShadowDepth: number): Generator<Element>;
153
+ /**
154
+ * Collect the OPEN shadow roots within `root`'s composed subtree (its own light
155
+ * children and any nested shadow trees), each paired with how many shadow
156
+ * boundary crossings deep it sits relative to `root` (1-based). Bounded by
157
+ * `maxShadowDepth` crossings and by {@link MAX_SHADOW_DOM_TRAVERSAL_NODES}
158
+ * total nodes. Closed roots are invisible (`el.shadowRoot` is null) and skipped.
159
+ */
160
+ export declare function collectOpenShadowRoots(root: Element, maxShadowDepth: number): OpenShadowRootEntry[];
161
+ /**
162
+ * Split the outward composed walk from `el` into per-tree segments.
163
+ *
164
+ * Always walks fully out to the document so the outermost segment is
165
+ * document-rooted and therefore re-resolvable. `maxShadowDepth` caps how many
166
+ * shadow boundaries the *emitted* selector descends through: when the target is
167
+ * nested deeper than the budget, the innermost (over-budget) trees are dropped
168
+ * and the result is flagged `truncated` — the innermost kept segment then
169
+ * targets the shadow host at the depth limit (a best-effort, still-resolvable
170
+ * selector for an ancestor of the true target).
171
+ */
172
+ export declare function segmentWalk(el: Element, maxShadowDepth: number): SegmentWalkResult;
173
+ /**
174
+ * Re-resolve a generated selector back to its element, piercing open shadow
175
+ * roots at each boundary. The symmetric inverse of `engine.generate`.
176
+ *
177
+ * Returns `null` when any segment fails to match, or when a boundary crossing
178
+ * hits a *closed* shadow root (`host.shadowRoot === null`) — closed roots are
179
+ * opaque from outside, so such selectors cannot round-trip (a documented
180
+ * limitation). Never throws on a malformed segment.
181
+ *
182
+ * @param root Root to resolve against — almost always `document`.
183
+ * @param selector A selector produced by the engine (may contain boundary delimiters).
184
+ */
185
+ export declare function resolveSelector(root: ParentNode, selector: string): Element | null;
186
+ /**
187
+ * Build a single positional step for `el`: `tag:nth-of-type(n)`, indexed among
188
+ * its same-tag siblings. A parentless element emits the bare tag.
189
+ *
190
+ * `shadowAware` extends the parentless case: an element at the top of a shadow
191
+ * tree has a null `parentElement` but can still have same-tag peers among the
192
+ * `ShadowRoot`'s children, so it is indexed against those instead. When
193
+ * `shadowAware` is false every parentless element emits the bare tag.
194
+ */
195
+ export declare function positionalStep(el: Element, shadowAware: boolean): string;
196
+ //# sourceMappingURL=shadow.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shadow.d.ts","sourceRoot":"","sources":["../../../src/help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