@amplitude/amp-semantic 0.0.1 → 0.2.0-codexsemantic-review-integration.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 (100) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +246 -0
  3. package/lib/cjs/capture.d.ts +13 -0
  4. package/lib/cjs/capture.d.ts.map +1 -0
  5. package/lib/cjs/capture.js +229 -0
  6. package/lib/cjs/capture.js.map +1 -0
  7. package/lib/cjs/helpers.d.ts +9 -0
  8. package/lib/cjs/helpers.d.ts.map +1 -0
  9. package/lib/cjs/helpers.js +469 -0
  10. package/lib/cjs/helpers.js.map +1 -0
  11. package/lib/cjs/identity.d.ts +4 -0
  12. package/lib/cjs/identity.d.ts.map +1 -0
  13. package/lib/cjs/identity.js +27 -0
  14. package/lib/cjs/identity.js.map +1 -0
  15. package/lib/cjs/index.d.ts +17 -0
  16. package/lib/cjs/index.d.ts.map +1 -0
  17. package/lib/cjs/index.js +43 -0
  18. package/lib/cjs/index.js.map +1 -0
  19. package/lib/cjs/recorders/analytics.d.ts +7 -0
  20. package/lib/cjs/recorders/analytics.d.ts.map +1 -0
  21. package/lib/cjs/recorders/analytics.js +95 -0
  22. package/lib/cjs/recorders/analytics.js.map +1 -0
  23. package/lib/cjs/recorders/feedback.d.ts +4 -0
  24. package/lib/cjs/recorders/feedback.d.ts.map +1 -0
  25. package/lib/cjs/recorders/feedback.js +611 -0
  26. package/lib/cjs/recorders/feedback.js.map +1 -0
  27. package/lib/cjs/recorders/interactions.d.ts +4 -0
  28. package/lib/cjs/recorders/interactions.d.ts.map +1 -0
  29. package/lib/cjs/recorders/interactions.js +320 -0
  30. package/lib/cjs/recorders/interactions.js.map +1 -0
  31. package/lib/cjs/recorders/keys.d.ts +4 -0
  32. package/lib/cjs/recorders/keys.d.ts.map +1 -0
  33. package/lib/cjs/recorders/keys.js +64 -0
  34. package/lib/cjs/recorders/keys.js.map +1 -0
  35. package/lib/cjs/recorders/lifecycle.d.ts +4 -0
  36. package/lib/cjs/recorders/lifecycle.d.ts.map +1 -0
  37. package/lib/cjs/recorders/lifecycle.js +86 -0
  38. package/lib/cjs/recorders/lifecycle.js.map +1 -0
  39. package/lib/cjs/recorders/navigation.d.ts +4 -0
  40. package/lib/cjs/recorders/navigation.d.ts.map +1 -0
  41. package/lib/cjs/recorders/navigation.js +18 -0
  42. package/lib/cjs/recorders/navigation.js.map +1 -0
  43. package/lib/cjs/recorders/resource-error.d.ts +4 -0
  44. package/lib/cjs/recorders/resource-error.d.ts.map +1 -0
  45. package/lib/cjs/recorders/resource-error.js +159 -0
  46. package/lib/cjs/recorders/resource-error.js.map +1 -0
  47. package/lib/cjs/types.d.ts +263 -0
  48. package/lib/cjs/types.d.ts.map +1 -0
  49. package/lib/cjs/types.js +5 -0
  50. package/lib/cjs/types.js.map +1 -0
  51. package/lib/esm/capture.d.ts +13 -0
  52. package/lib/esm/capture.d.ts.map +1 -0
  53. package/lib/esm/capture.js +225 -0
  54. package/lib/esm/capture.js.map +1 -0
  55. package/lib/esm/helpers.d.ts +9 -0
  56. package/lib/esm/helpers.d.ts.map +1 -0
  57. package/lib/esm/helpers.js +461 -0
  58. package/lib/esm/helpers.js.map +1 -0
  59. package/lib/esm/identity.d.ts +4 -0
  60. package/lib/esm/identity.d.ts.map +1 -0
  61. package/lib/esm/identity.js +23 -0
  62. package/lib/esm/identity.js.map +1 -0
  63. package/lib/esm/index.d.ts +17 -0
  64. package/lib/esm/index.d.ts.map +1 -0
  65. package/lib/esm/index.js +27 -0
  66. package/lib/esm/index.js.map +1 -0
  67. package/lib/esm/recorders/analytics.d.ts +7 -0
  68. package/lib/esm/recorders/analytics.d.ts.map +1 -0
  69. package/lib/esm/recorders/analytics.js +92 -0
  70. package/lib/esm/recorders/analytics.js.map +1 -0
  71. package/lib/esm/recorders/feedback.d.ts +4 -0
  72. package/lib/esm/recorders/feedback.d.ts.map +1 -0
  73. package/lib/esm/recorders/feedback.js +608 -0
  74. package/lib/esm/recorders/feedback.js.map +1 -0
  75. package/lib/esm/recorders/interactions.d.ts +4 -0
  76. package/lib/esm/recorders/interactions.d.ts.map +1 -0
  77. package/lib/esm/recorders/interactions.js +317 -0
  78. package/lib/esm/recorders/interactions.js.map +1 -0
  79. package/lib/esm/recorders/keys.d.ts +4 -0
  80. package/lib/esm/recorders/keys.d.ts.map +1 -0
  81. package/lib/esm/recorders/keys.js +61 -0
  82. package/lib/esm/recorders/keys.js.map +1 -0
  83. package/lib/esm/recorders/lifecycle.d.ts +4 -0
  84. package/lib/esm/recorders/lifecycle.d.ts.map +1 -0
  85. package/lib/esm/recorders/lifecycle.js +83 -0
  86. package/lib/esm/recorders/lifecycle.js.map +1 -0
  87. package/lib/esm/recorders/navigation.d.ts +4 -0
  88. package/lib/esm/recorders/navigation.d.ts.map +1 -0
  89. package/lib/esm/recorders/navigation.js +15 -0
  90. package/lib/esm/recorders/navigation.js.map +1 -0
  91. package/lib/esm/recorders/resource-error.d.ts +4 -0
  92. package/lib/esm/recorders/resource-error.d.ts.map +1 -0
  93. package/lib/esm/recorders/resource-error.js +156 -0
  94. package/lib/esm/recorders/resource-error.js.map +1 -0
  95. package/lib/esm/types.d.ts +263 -0
  96. package/lib/esm/types.d.ts.map +1 -0
  97. package/lib/esm/types.js +2 -0
  98. package/lib/esm/types.js.map +1 -0
  99. package/package.json +33 -4
  100. package/schema.json +1110 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Amplitude Analytics
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,246 @@
1
+ # @amplitude/amp-semantic
2
+
3
+ Experimental browser semantic capture for Amplitude Session Replay. The package emits versioned captured facts; it does not classify user intent or upload data.
4
+
5
+ ## Package boundary
6
+
7
+ `amp-semantic` depends on the shared DOM privacy package, not rrweb, the analytics client, or Session Replay. A `SemanticHost` supplies the DOM, replay node IDs, current privacy/URL configuration, analytics capability information, and a synchronous event sink. The Session Replay adapter translates these events into `amp-semantic/<family>` rrweb custom events.
8
+
9
+ Capture is disabled by default. The runtime owns sampling, per-session caps, family switches, subscriptions, error containment, and teardown. Each recorder owns its signal subscriptions, DOM listeners, and timers. Stopping capture preserves session caps and the sampling decision; `resetSession()` starts a new accounting period. Hosts should forward `snapshot` only after the corresponding full snapshot has entered the recording stream.
10
+
11
+ ## Session Replay integration
12
+
13
+ ```ts
14
+ sessionReplay.init(API_KEY, {
15
+ deviceId,
16
+ sessionId,
17
+ semanticCapture: {
18
+ enabled: true,
19
+ sampleRate: 1,
20
+ families: { keys: false },
21
+ },
22
+ });
23
+ ```
24
+
25
+ The analytics Session Replay plugin accepts the same `semanticCapture` option. The remote `sr_semantic_config` object can override enabled, sample rate, and individual families. The standalone capture runtime also supports immediate `updateConfig()` calls; SDK remote settings follow the existing SDK config-refresh/restart lifecycle.
26
+
27
+ The adapter emits synchronously through `recordFunction.addCustomEvent`, avoiding debug metadata and asynchronous size lookups. It queues initial snapshot notifications until rrweb returns its cancellation callback and emits terminal recording state before cancellation.
28
+
29
+ Notice/dialog capture consumes the accepted rrweb full snapshots and mutation batches through
30
+ `notify('dom', change)`, resolving relevant elements with `host.getNode(id)`. It does not install a
31
+ MutationObserver or perform an initial dialog selector query. Standalone hosts must provide both
32
+ this signal and resolver for these two families; there is no independent observation fallback.
33
+ Full snapshots seed existing dialogs silently, while later changes produce the same wire payloads.
34
+ The adapter queues startup input until capture starts and ignores custom events to prevent feedback.
35
+
36
+ ## Semantic identity and visibility
37
+
38
+ Click `states` includes `mixed` (native checkbox indeterminate or ARIA checked/pressed mixed),
39
+ `busy` (the target's aria-busy), and `open` (native details/dialog), alongside existing states.
40
+ Mixed observations omit the checked token. Field events include optional `checked: true | false`
41
+ for native checkbox/radio controls, including masked controls; blocked controls remain excluded.
42
+ Other field types omit it, and older events without it mean unknown. These reads use existing
43
+ event handlers, with no extra observers, scans, or layout checks. Radio peers and silent programmatic
44
+ state changes are not continuously tracked. `value_state` is not checkbox selection state.
45
+
46
+ Every new semantic payload includes `tab_id` and `document_id`. The capture runtime stamps these
47
+ fields centrally, including when the context family is disabled. The host can inject `getIdentity()`;
48
+ without it, the package uses shared in-memory IDs for its host document, with no storage or listeners.
49
+
50
+ The Session Replay host lazily creates identity only when a semantic event is accepted. In a top-level
51
+ page it stores an opaque tab ID and document owner in sessionStorage (`AMP_semantic_tab_v1`).
52
+ Actual `pagehide` releases ownership so normal same-origin reloads/navigation reuse the tab ID;
53
+ each newly loaded document gets a new document ID. A copied record with a live owner gets a fresh
54
+ tab ID. A bfcache restore preserves the original document identity and reclaims ownership.
55
+ SPA navigation, stop/resume, and session resets preserve both IDs within the current document.
56
+ These IDs are unrelated to the replay event store's internal ownership ID.
57
+
58
+ Storage unavailable, corrupt, or a missing navigation boundary can break tab continuity. Capture
59
+ falls back to document-scoped in-memory IDs when storage is blocked; it never requires storage to
60
+ emit. Child-frame hosts use document-scoped IDs without modifying top-level tab storage; they are
61
+ not correlated to the parent's tab. The lightweight identity ownership listeners last for the
62
+ page lifetime once initialized, while recorder listeners are removed on stop. Disabled or
63
+ sampled-out capture does not initialize identity storage or listeners.
64
+
65
+ Context includes `visibility_state`, `focused` (`document.hasFocus()`), and `user_agent`.
66
+ Visibility emits `{ state }` plus the shared version and identity fields only when the document changes
67
+ between hidden and visible. Both transitions emit immediately, with no settling timer. Duplicate
68
+ visibility notifications and standalone window/element focus or blur events emit nothing.
69
+ Visibility payloads omit `focused`: focus may arrive after the visibility boundary, and a one-time
70
+ snapshot would be misleading as the focus state for the visible interval. Initial visibility is
71
+ included in context. The visibility listener is removed on stop or family disabling. Visibility
72
+ is an observation, not proof of attention or a reason for leaving the page.
73
+ The redundant `trigger` field is no longer emitted. The wire schema still accepts legacy
74
+ `focused` and `trigger` fields (`visibilitychange`, `focus`, or `blur`) from earlier recordings.
75
+ Context retains its observation-time `focused` snapshot; local diagnostics also show
76
+ raw focus notifications, but neither is continuous semantic focus tracking.
77
+
78
+ The local replay inspector displays millisecond timestamps and separate visibility diagnostics for
79
+ browser event creation, handler execution, and batch decoding. These diagnostics stay local and
80
+ are not semantic payload fields. A reported embedded-browser switch produced hidden/visible
81
+ observations only 4 ms apart despite several seconds away; the cause is still under investigation.
82
+ Do not treat that pair as a measured absence interval. Synthetic visibility tests do not establish
83
+ native browser tab-switch behavior.
84
+
85
+ The wire version remains `v: 1`; the schema accepts legacy payloads without these fields. Missing
86
+ identity/focus/visibility means unknown. These additions only identify semantic events. They do not
87
+ attribute interleaved raw rrweb events, link an opener to its child, or implement multi-tab DOM replay.
88
+
89
+ ## Host API and extensions
90
+
91
+ ```ts
92
+ const capture = createSemanticCapture(config, host);
93
+ capture.start();
94
+ capture.notify('recording', { state: 'start', reason: 'init' });
95
+ capture.notify('snapshot', undefined);
96
+ // Forward a URL observation after applying the host URL privacy rules:
97
+ // This also invalidates cached interaction headings.
98
+ capture.notify('url', { url: filteredUrl, timestamp: Date.now() });
99
+ capture.notify('recording', { state: 'stop', reason: 'customer_stop' });
100
+ capture.stop();
101
+ ```
102
+
103
+ Pass a third argument containing recorder factories to replace the default recorder set. Built-in factories and `defaultRecorders` are exported so hosts can compose a subset. A `SemanticRecorder` declares its families and implements `setup(context)`, returning complete cleanup. Call `context.onCleanup()` immediately after acquiring a resource when setup could subsequently fail; the runtime unwinds those resources if setup throws. Context signal subscriptions are automatically scoped to their recorder. Cleanup should be idempotent.
104
+
105
+ To add an event family, add its payload to `SemanticPayloads`, its session limit to `SEMANTIC_CAPS`, its wire variant to `schema.json`, and its factory to the desired recorder set. Wire tags and payload `v` are stable contracts. Breaking payload changes require a new version; avoid encoding application classification into capture facts.
106
+
107
+ `SemanticHost.externalClicks` lets hosts reuse existing native click hooks. Session Replay routes primary clicks through its existing heatmap `ClickHandler` and rrweb's `mouseInteraction` hook, including when heatmaps are disabled. The hook receives the original event in memory, preserving modifiers, keyboard activation, trust and composed-path targeting. Native events are never added to recorded rrweb data. Selector lookup is shared for the same element within one click; an actionable ancestor gets its own lookup when it differs from the raw target. Consumer failures are isolated.
108
+
109
+ The published `@amplitude/rrweb-record@2.1.5` provides the optional native-event hook argument and `record.supportsNativeMouseInteraction`; no workspace patch is required. Older recorders retain the independent native listener as a compatibility fallback. `externalAuxClicks: false` keeps the middle-button `auxclick` listener because rrweb does not forward auxiliary clicks. Standalone semantic capture still installs its own native listeners.
110
+
111
+ Recorder processing timestamps are supplied to generic hosts. rrweb's `addCustomEvent` controls its own wire timestamp, so exact ±1 ms alignment with MouseInteraction remains a browser integration requirement.
112
+
113
+ ## Privacy and limits
114
+
115
+ All captured text uses the replay privacy policy, including referenced labels and nested text sources. Blocked elements are skipped, masked text is `null`, and browser validation messages are never included. Field events include an optional `value` for native inputs and textareas only when the input policy permits it, with no length limit or whitespace normalization. Passwords (including `data-rr-is-password`), hidden fields and blocked fields emit nothing. Files, checkbox/radio submitted values, selects and contenteditable contents are excluded from `value`; selection labels and checked state retain their existing contracts. Text traversal is bounded and fails closed when its budget is exceeded. Unsupported URL schemes are discarded; HTTP(S) paths and hash routes are templated without queries or secondary fragments. Detached dialog names are cleared because their former masking ancestry cannot safely be reconstructed.
116
+
117
+ The page event and its title observer, scheduled checks, and page-wide scans remain deferred.
118
+ `amp-semantic/navigation` emits `{ url }` plus shared version/identity fields from accepted
119
+ `amplitude/url-tracking@1` plugin events. This covers the initial URL, history/hash changes (or the
120
+ plugin's configured polling), and the current URL when recording resumes. No second URL listener,
121
+ history wrapper, polling timer, title observer, or page scan is added. Plugin observations also
122
+ invalidate cached interaction headings even when the navigation family is disabled.
123
+
124
+ The existing URL plugin applies configured UGC URL rules first. Semantic normalization then removes
125
+ origins and query values and templates ID-shaped path segments, preserving hash routes. Literal path
126
+ segments remain: sensitive path content still requires appropriate UGC rules. No title or navigation
127
+ reason is emitted. Separate navigations may produce the same template; consumers should retain the
128
+ boundaries. The limit is 200 events per session. Set `families: { navigation: false }` to disable it.
129
+ Standalone hosts can provide accepted input using `capture.notify('url', { url, timestamp })`.
130
+
131
+ Recorders include context, clicks, keys, resource load failures, field state, form submissions, notices, dialogs, navigation, recording state, visibility, lifecycle, and an accepted-analytics-event mirror.
132
+
133
+ Field events and key targets include the same event-time `states` as clicks, including native disabled fieldset inheritance (with the first-legend exception) and native/ARIA invalid state. Reading native validity does not dispatch validation events. Fields, key targets and dialogs include `name_source`; excluded editable names and detached dialog names report `masked`. These additive v1 fields remain optional in the wire schema for older recordings. No new listeners, observers, scans or timers are introduced; states describe the observation, not a post-action outcome.
134
+
135
+ ## Work limits
136
+
137
+ Recorders call `context.canEmit(family)` before expensive payload construction when possible.
138
+ A cap-rejected candidate increments the dropped count without resolving its text, selector, or
139
+ layout; `emit()` still enforces the cap independently. This is not a reservation. Recorders retain
140
+ shared subscriptions while another family still has capacity. `hasCapacity()` checks capacity without
141
+ incrementing dropped counts; feedback disconnects once both families are exhausted, including on
142
+ same-session resume, and reattaches after a session reset.
143
+ Field candidates rejected before deduplication can contribute to the dropped count.
144
+
145
+ Notice/dialog processing retains at most 128 replay batches, 256 notice candidates (ready plus
146
+ trailing timers), 256 dialog candidates, and 256 tracked dialogs (including closed/hidden dialogs).
147
+ Serialized trees are traversed incrementally without building a second tree or walking live DOM
148
+ subtrees. Ordinary serialized elements need no live-node lookup; repeated parent lookups in a
149
+ mutation batch are deduplicated with a bounded set. References to queued serialized batches retain
150
+ their source data until consumed. Overflow drops excess work and reports a payload-free diagnostic
151
+ through `host.onError`, once per limit per recorder setup; these are not exact dropped-event counts.
152
+
153
+ Each frame gives ready events the first 2 ms, alternating notices and dialogs, before inspecting
154
+ recorded changes. It processes at most 1,000 work items and 50 payload candidates within a cooperative
155
+ 4 ms frame budget. Trailing notice timers only enqueue work. Detached notice work is discarded;
156
+ removal checks the bounded dialog registry without traversing removed subtrees. Privacy helpers
157
+ still recheck live text, names and blocking before emission; detached dialog names stay null.
158
+
159
+ State and timestamps reflect processing time. rrweb batching and deferred enrichment can coalesce
160
+ or omit transient states, including nodes removed before discovery. Masked/blocked or otherwise
161
+ unrecorded DOM changes cannot be recovered from this input. Snapshot baseline processing is also
162
+ incremental. CSS-only visibility and full-page visibility tracking remain out of scope. These are
163
+ cooperative limits, not hard deadlines for individual DOM or host callbacks. No production CPU
164
+ improvement is claimed without a representative browser benchmark.
165
+
166
+ Heading discovery traverses at most 2,000 elements with a cooperative 2 ms budget and reuses only the
167
+ DOM candidate for up to 250 ms. Text, masking and visibility are re-read when emitted; no private text
168
+ is cached. Navigation, snapshots, disconnected candidates and hidden candidates invalidate discovery.
169
+ New higher-priority headings may take up to 250 ms to be selected, and over-budget discovery can omit
170
+ a heading. These budgets are checked between DOM operations, not hard deadlines for browser calls.
171
+
172
+ The SDK still has separate autocapture/replay observers; this package does not introduce a shared observer across those packages.
173
+
174
+ ## Remaining integration and release work
175
+
176
+ - The analytics mirror requires a host signal after analytics enrichment/filtering accepts an event for delivery. The existing Session Replay plugin `execute()` runs too early; SDK forwarding is intentionally not wired there.
177
+ - Coordinated cross-origin child iframe capture bypasses the ordinary snapshot callback and needs an additional rrweb lifecycle bridge. Semantic recorders currently operate on their host document, not a shadow-root/iframe forest.
178
+ - Within-frame dialog open/close transitions can coalesce in the observer batch.
179
+ - The inherited 100% unit-coverage threshold is retained and is not yet met. Do not treat passing tests with coverage disabled as a passing release gate.
180
+ - The real-browser smoke fixture checks shapes, privacy, teardown, reconfiguration, and click dispatch overhead. It does not establish the ≤5% replay-byte budget or exact rrweb timestamp/ID alignment on production journeys. Actionable-ancestor click IDs can differ from rrweb's raw target IDs; that spec tension needs explicit resolution before release.
181
+
182
+ ## Validation
183
+
184
+ Build dependencies first, then run the package's build, test, and lint scripts. `schema.json` validates complete rrweb custom-event envelopes and is shipped with the package for downstream consumers. Fixture tests cover each specified family and reject extra raw-value fields.
185
+
186
+ ### Local Session Replay inspector
187
+
188
+ From the repository root, run:
189
+
190
+ ```sh
191
+ pnpm dev:semantic
192
+ ```
193
+
194
+ This builds Session Replay and its workspace dependencies, then opens `http://127.0.0.1:5174/session-replay-browser/sr-semantic-test.html` in the existing Vite test server. After package source changes, run `pnpm build:semantic` again and reload. The page also works with the repository's normal `pnpm dev` watch workflow.
195
+
196
+ Interact with the checkout form, dialog, notice, navigation, and privacy fixtures. The inspector decodes actual Session Replay transport batches, validates every `amp-semantic/*` rrweb envelope against `schema.json`, and displays its payload. Use **Flush batches** to inspect the current recording immediately, filter by family, or **Export semantic JSON** to save the captured envelopes.
197
+
198
+ Controls let you change replay masking, semantic sampling, family switches, and worker transport. **Stop recording** and **Resume recording** exercise the public SDK lifecycle. Disabled or sampled-out semantic capture should leave ordinary replay events flowing. The inspector lives in a blocked shadow tree to keep its own controls and log updates outside recorded content.
199
+
200
+ No real API key is needed. Custom config and transport callbacks handle data locally in memory; the fixture does not upload to Amplitude. Reloading clears its log, which retains up to 10,000 replay events. The analytics mirror is not connected to this SDK path yet.
201
+
202
+ ### Browser integration tests
203
+
204
+ ```sh
205
+ pnpm test:semantic
206
+ ```
207
+
208
+ This builds the dependencies and runs the package's Chromium Playwright suite, starting the local Vite server automatically. If Chromium is not installed, run `pnpm exec playwright install chromium` first. After a build, use `pnpm --filter @amplitude/amp-semantic test:playwright --ui` for interactive debugging.
209
+
210
+ The suite covers real SDK → rrweb → serialized transport delivery, schema validation, direct-button click node ID matching, fields/submits, notices/dialogs, post-navigation click context, masking, disabled capture, sampling, the remote kill switch, individual family switches, stop/resume, JSON export, and worker transport. It also checks ordinary clicks without a page change. These fixture checks do not establish production byte budgets or exact timestamp alignment.
211
+
212
+ For an isolated Chromium recorder smoke check, from the repository root:
213
+
214
+ ```sh
215
+ node packages/amp-semantic/test/e2e/smoke.cjs
216
+ ```
217
+
218
+ The smoke check uses the workspace's Vite and Playwright installations. It validates actual emitted events against the schema and reports measured click-dispatch p95 for its fixture.
219
+
220
+
221
+ ## Keys and resource errors
222
+
223
+ `keys` emits `{ key, target: { id, role, name } }` with common identity/version fields. It allows
224
+ Escape, Enter, Tab, arrows, Home/End, PageUp/PageDown, F1–F12 and Ctrl/Meta+K/P/F (optionally Shift).
225
+ Modifier prefixes are canonical. Ordinary typing, Backspace/Delete, repeat, IME/composition,
226
+ AltGraph, password/hidden inputs, and blocked targets are excluded. Names use shared masking;
227
+ control values and editable text are never names. Browser/OS-intercepted shortcuts are unavailable.
228
+ The target is the actual DOM key target, not an inferred cause of a dialog transition.
229
+
230
+ `resource-error` emits `{ rt, count, container?, path? }`, where `rt` is img/css/font/script. Only
231
+ observed load failures are captured, not runtime exceptions or fetch/XHR. Identical resource type,
232
+ templated path, and container are aggregated over 500 ms; 100 pending groups force an early flush.
233
+ Counts saturate at 65,535. Hidden/pagehide flushes immediately; stop/disable discards pending groups.
234
+ The rrweb timestamp is batch emission time. Do not infer exact click attribution from that timestamp.
235
+ Paths omit origins, queries and fragments; data/blob/invalid/over-200-character paths are omitted.
236
+ Detached/blocked elements are dropped and container masking is checked again at emission.
237
+
238
+ FontFaceSet loadingerror supplies a failed-face count; font URLs and affected containers are not
239
+ available, so those fields are omitted. Font family names are never sent. Document-level font counts
240
+ cannot attribute or exclude a failure specific to a blocked region. Element errors in shadow roots
241
+ and other frame documents, and failures before capture starts, are outside this recorder's coverage.
242
+ There are no retrospective requests, polling, or DOM/CSS scans.
243
+
244
+ Caps are 1,000 keys and 200 resource-error groups per session. Disable either independently with
245
+ `families: { keys: false, 'resource-error': false }`. The local playground has a command palette
246
+ (Ctrl/Cmd+K, Escape) and a button that triggers real missing local image/CSS/script/font requests.
@@ -0,0 +1,13 @@
1
+ import { HostSignals, SemanticCaptureConfig, SemanticFamily, SemanticHost, SemanticRecorder } from './types';
2
+ export declare const SEMANTIC_CAPS: Record<SemanticFamily, number>;
3
+ export interface SemanticCapture {
4
+ isActive: () => boolean;
5
+ start: () => void;
6
+ stop: () => void;
7
+ updateConfig: (config: SemanticCaptureConfig) => void;
8
+ resetSession: () => void;
9
+ notify: <K extends keyof HostSignals>(signal: K, value: HostSignals[K]) => void;
10
+ }
11
+ /** Composable runtime. Sampling and caps belong to a session, listeners to a recording. */
12
+ export declare function createCapture(config: SemanticCaptureConfig, host: SemanticHost, recorders: readonly SemanticRecorder[]): SemanticCapture;
13
+ //# sourceMappingURL=capture.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"capture.d.ts","sourceRoot":"","sources":["../../src/capture.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,WAAW,EAEX,qBAAqB,EAErB,cAAc,EACd,YAAY,EAEZ,gBAAgB,EACjB,MAAM,SAAS,CAAC;AAEjB,eAAO,MAAM,aAAa,EAAE,MAAM,CAAC,cAAc,EAAE,MAAM,CAcxD,CAAC;AAEF,MAAM,WAAW,eAAe;IAC9B,QAAQ,EAAE,MAAM,OAAO,CAAC;IACxB,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB,IAAI,EAAE,MAAM,IAAI,CAAC;IACjB,YAAY,EAAE,CAAC,MAAM,EAAE,qBAAqB,KAAK,IAAI,CAAC;IACtD,YAAY,EAAE,MAAM,IAAI,CAAC;IACzB,MAAM,EAAE,CAAC,CAAC,SAAS,MAAM,WAAW,EAAE,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC;CACjF;AAED,2FAA2F;AAC3F,wBAAgB,aAAa,CAC3B,MAAM,EAAE,qBAAqB,EAC7B,IAAI,EAAE,YAAY,EAClB,SAAS,EAAE,SAAS,gBAAgB,EAAE,GACrC,eAAe,CAyKjB"}
@@ -0,0 +1,229 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createCapture = exports.SEMANTIC_CAPS = void 0;
4
+ var tslib_1 = require("tslib");
5
+ var helpers_1 = require("./helpers");
6
+ var identity_1 = require("./identity");
7
+ exports.SEMANTIC_CAPS = {
8
+ click: 2000,
9
+ keys: 1000,
10
+ 'resource-error': 200,
11
+ field: 1000,
12
+ submit: 300,
13
+ notice: 300,
14
+ dialog: 300,
15
+ 'amp-event': 500,
16
+ context: 200,
17
+ recording: 200,
18
+ navigation: 200,
19
+ visibility: 200,
20
+ lifecycle: 200,
21
+ };
22
+ /** Composable runtime. Sampling and caps belong to a session, listeners to a recording. */
23
+ function createCapture(config, host, recorders) {
24
+ var _a;
25
+ var settings = copyConfig(config);
26
+ var active = false;
27
+ var requested = false;
28
+ var snapshotSeen = false;
29
+ var sample;
30
+ var cleanups = [];
31
+ var counts = {};
32
+ var dropped = {};
33
+ var signals = new Map();
34
+ var subscribers = new Set();
35
+ var now = (_a = host.now) !== null && _a !== void 0 ? _a : Date.now;
36
+ var report = function (error) {
37
+ var _a;
38
+ try {
39
+ (_a = host.onError) === null || _a === void 0 ? void 0 : _a.call(host, error);
40
+ }
41
+ catch (_b) {
42
+ /* Diagnostics must not affect the host. */
43
+ }
44
+ };
45
+ var safely = function (fn) {
46
+ try {
47
+ fn();
48
+ }
49
+ catch (error) {
50
+ report(error);
51
+ }
52
+ };
53
+ var enabled = function (family) { var _a; return active && ((_a = settings.families) === null || _a === void 0 ? void 0 : _a[family]) !== false; };
54
+ var hasCapacity = function (family) { var _a; return enabled(family) && ((_a = counts[family]) !== null && _a !== void 0 ? _a : 0) < exports.SEMANTIC_CAPS[family]; };
55
+ var canEmit = function (family) {
56
+ var _a;
57
+ if (!enabled(family))
58
+ return false;
59
+ if (hasCapacity(family))
60
+ return true;
61
+ dropped[family] = ((_a = dropped[family]) !== null && _a !== void 0 ? _a : 0) + 1;
62
+ return false;
63
+ };
64
+ var context = {
65
+ host: host,
66
+ helpers: (0, helpers_1.createHelpers)(host),
67
+ now: now,
68
+ enabled: enabled,
69
+ canEmit: canEmit,
70
+ hasCapacity: hasCapacity,
71
+ dropped: function () { return (tslib_1.__assign({}, dropped)); },
72
+ hasSnapshot: function () { return snapshotSeen; },
73
+ emit: function (family, payload, timestamp) {
74
+ var _a, _b;
75
+ if (timestamp === void 0) { timestamp = now(); }
76
+ if (!canEmit(family))
77
+ return false;
78
+ var identity;
79
+ try {
80
+ identity = (_a = host.getIdentity) === null || _a === void 0 ? void 0 : _a.call(host);
81
+ }
82
+ catch (error) {
83
+ report(error);
84
+ }
85
+ identity !== null && identity !== void 0 ? identity : (identity = (0, identity_1.getDocumentIdentity)(host.document, host.window));
86
+ var event = {
87
+ name: family,
88
+ payload: tslib_1.__assign(tslib_1.__assign({}, payload), { v: 1, tab_id: identity.tab_id, document_id: identity.document_id }),
89
+ timestamp: timestamp,
90
+ };
91
+ counts[family] = ((_b = counts[family]) !== null && _b !== void 0 ? _b : 0) + 1;
92
+ try {
93
+ host.emit(event);
94
+ }
95
+ catch (error) {
96
+ report(error);
97
+ return false;
98
+ }
99
+ if (family === 'context')
100
+ dropped = {};
101
+ subscribers.forEach(function (subscriber) { return safely(function () { return subscriber(event); }); });
102
+ return true;
103
+ },
104
+ on: function (signal, callback) {
105
+ var listeners = signals.get(signal);
106
+ if (!listeners) {
107
+ listeners = new Set();
108
+ signals.set(signal, listeners);
109
+ }
110
+ var listener = function (value) { return safely(function () { return callback(value); }); };
111
+ listeners.add(listener);
112
+ var registered = listeners;
113
+ return function () {
114
+ registered.delete(listener);
115
+ };
116
+ },
117
+ subscribe: function (callback) {
118
+ subscribers.add(callback);
119
+ return function () {
120
+ subscribers.delete(callback);
121
+ };
122
+ },
123
+ };
124
+ var detach = function () {
125
+ active = false;
126
+ var previous = cleanups;
127
+ cleanups = [];
128
+ previous.reverse().forEach(function (cleanup) { return safely(cleanup); });
129
+ signals.clear();
130
+ subscribers.clear();
131
+ };
132
+ var attach = function () {
133
+ var e_1, _a;
134
+ var _b, _c;
135
+ if (active || !requested || !settings.enabled)
136
+ return;
137
+ var rate = (_b = settings.sampleRate) !== null && _b !== void 0 ? _b : 1;
138
+ if (!Number.isFinite(rate) || rate <= 0 || rate > 1)
139
+ return;
140
+ if (sample === undefined)
141
+ sample = ((_c = host.random) !== null && _c !== void 0 ? _c : Math.random)();
142
+ if (sample >= rate)
143
+ return;
144
+ active = true;
145
+ var _loop_1 = function (recorder) {
146
+ if (recorder.families.some(enabled)) {
147
+ var acquired_1 = [];
148
+ var scoped = tslib_1.__assign(tslib_1.__assign({}, context), { onCleanup: function (cleanup) {
149
+ acquired_1.push(cleanup);
150
+ }, on: function (signal, callback) {
151
+ var cleanup = context.on(signal, callback);
152
+ acquired_1.push(cleanup);
153
+ return cleanup;
154
+ }, subscribe: function (callback) {
155
+ var cleanup = context.subscribe(callback);
156
+ acquired_1.push(cleanup);
157
+ return cleanup;
158
+ } });
159
+ var rollback = function () {
160
+ acquired_1
161
+ .splice(0)
162
+ .reverse()
163
+ .forEach(function (cleanup) { return safely(cleanup); });
164
+ };
165
+ try {
166
+ acquired_1.push(recorder.setup(scoped));
167
+ cleanups.push(rollback);
168
+ }
169
+ catch (error) {
170
+ rollback();
171
+ report(error);
172
+ }
173
+ }
174
+ };
175
+ try {
176
+ for (var recorders_1 = tslib_1.__values(recorders), recorders_1_1 = recorders_1.next(); !recorders_1_1.done; recorders_1_1 = recorders_1.next()) {
177
+ var recorder = recorders_1_1.value;
178
+ _loop_1(recorder);
179
+ }
180
+ }
181
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
182
+ finally {
183
+ try {
184
+ if (recorders_1_1 && !recorders_1_1.done && (_a = recorders_1.return)) _a.call(recorders_1);
185
+ }
186
+ finally { if (e_1) throw e_1.error; }
187
+ }
188
+ };
189
+ return {
190
+ isActive: function () { return active; },
191
+ start: function () {
192
+ requested = true;
193
+ attach();
194
+ },
195
+ stop: function () {
196
+ requested = false;
197
+ snapshotSeen = false;
198
+ detach();
199
+ },
200
+ updateConfig: function (next) {
201
+ detach();
202
+ settings = copyConfig(next);
203
+ attach();
204
+ },
205
+ resetSession: function () {
206
+ detach();
207
+ sample = undefined;
208
+ snapshotSeen = false;
209
+ counts = {};
210
+ dropped = {};
211
+ attach();
212
+ },
213
+ notify: function (signal, value) {
214
+ var _a, _b, _c;
215
+ if (signal === 'snapshot')
216
+ snapshotSeen = true;
217
+ if (signal === 'snapshot' || signal === 'navigation' || signal === 'url')
218
+ (_b = (_a = context.helpers).invalidateHeading) === null || _b === void 0 ? void 0 : _b.call(_a);
219
+ if (!active)
220
+ return;
221
+ (_c = signals.get(signal)) === null || _c === void 0 ? void 0 : _c.forEach(function (callback) { return callback(value); });
222
+ },
223
+ };
224
+ }
225
+ exports.createCapture = createCapture;
226
+ function copyConfig(config) {
227
+ return tslib_1.__assign(tslib_1.__assign({}, config), { families: config.families ? tslib_1.__assign({}, config.families) : undefined });
228
+ }
229
+ //# sourceMappingURL=capture.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"capture.js","sourceRoot":"","sources":["../../src/capture.ts"],"names":[],"mappings":";;;;AAAA,qCAA0C;AAC1C,uCAAiD;AAapC,QAAA,aAAa,GAAmC;IAC3D,KAAK,EAAE,IAAI;IACX,IAAI,EAAE,IAAI;IACV,gBAAgB,EAAE,GAAG;IACrB,KAAK,EAAE,IAAI;IACX,MAAM,EAAE,GAAG;IACX,MAAM,EAAE,GAAG;IACX,MAAM,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AC;YACrB,MAAM,EAAE,CAAC;QACX,CAAC;QACD,YAAY,EAAE,UAAC,IAAI;YACjB,MAAM,EAAE,CAAC;YACT,QAAQ,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC;YAC5B,MAAM,EAAE,CAAC;QACX,CAAC;QACD,YAAY,EAAE;YACZ,MAAM,EAAE,CAAC;YACT,MAAM,GAAG,SAAS,CAAC;YACnB,YAAY,GAAG,KAAK,CAAC;YACrB,MAAM,GAAG,EAAE,CAAC;YACZ,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,EAAE,CAAC;QACX,CAAC;QACD,MAAM,EAAE,UAAC,MAAM,EAAE,KAAK;;YACpB,IAAI,MAAM,KAAK,UAAU;gBAAE,YAAY,GAAG,IAAI,CAAC;YAC/C,IAAI,MAAM,KAAK,UAAU,IAAI,MAAM,KAAK,YAAY,IAAI,MAAM,KAAK,KAAK;gBAAE,MAAA,MAAA,OAAO,CAAC,OAAO,EAAC,iBAAiB,kDAAI,CAAC;YAChH,IAAI,CAAC,MAAM;gBAAE,OAAO;YACpB,MAAA,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,0CAAE,OAAO,CAAC,UAAC,QAAQ,IAAK,OAAA,QAAQ,CAAC,KAAc,CAAC,EAAxB,CAAwB,CAAC,CAAC;QACvE,CAAC;KACF,CAAC;AACJ,CAAC;AA7KD,sCA6KC;AAED,SAAS,UAAU,CAAC,MAA6B;IAC/C,6CAAY,MAAM,KAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC,sBAAM,MAAM,CAAC,QAAQ,EAAG,CAAC,CAAC,SAAS,IAAG;AACvF,CAAC","sourcesContent":["import { createHelpers } from './helpers';\nimport { getDocumentIdentity } from './identity';\nimport {\n Cleanup,\n HostSignals,\n RecorderContext,\n SemanticCaptureConfig,\n SemanticEvent,\n SemanticFamily,\n SemanticHost,\n SemanticPayloads,\n SemanticRecorder,\n} from './types';\n\nexport const SEMANTIC_CAPS: Record<SemanticFamily, number> = {\n click: 2000,\n keys: 1000,\n 'resource-error': 200,\n field: 1000,\n submit: 300,\n notice: 300,\n dialog: 300,\n 'amp-event': 500,\n context: 200,\n recording: 200,\n navigation: 200,\n visibility: 200,\n lifecycle: 200,\n};\n\nexport interface SemanticCapture {\n isActive: () => boolean;\n start: () => void;\n stop: () => void;\n updateConfig: (config: SemanticCaptureConfig) => void;\n resetSession: () => void;\n notify: <K extends keyof HostSignals>(signal: K, value: HostSignals[K]) => void;\n}\n\n/** Composable runtime. Sampling and caps belong to a session, listeners to a recording. */\nexport function createCapture(\n config: SemanticCaptureConfig,\n host: SemanticHost,\n recorders: readonly SemanticRecorder[],\n): SemanticCapture {\n let settings = copyConfig(config);\n let active = false;\n let requested = false;\n let snapshotSeen = false;\n let sample: number | undefined;\n let cleanups: Cleanup[] = [];\n let counts: Partial<Record<SemanticFamily, number>> = {};\n let dropped: Partial<Record<SemanticFamily, number>> = {};\n const signals = new Map<keyof HostSignals, Set<(value: never) => void>>();\n const subscribers = new Set<(event: SemanticEvent) => void>();\n const now = host.now ?? Date.now;\n const report = (error: unknown) => {\n try {\n host.onError?.(error);\n } catch {\n /* Diagnostics must not affect the host. */\n }\n };\n const safely = (fn: () => void) => {\n try {\n fn();\n } catch (error) {\n report(error);\n }\n };\n const enabled = (family: SemanticFamily) => active && settings.families?.[family] !== false;\n const hasCapacity = (family: SemanticFamily) => enabled(family) && (counts[family] ?? 0) < SEMANTIC_CAPS[family];\n const canEmit = (family: SemanticFamily): boolean => {\n if (!enabled(family)) return false;\n if (hasCapacity(family)) return true;\n dropped[family] = (dropped[family] ?? 0) + 1;\n return false;\n };\n const context: Omit<RecorderContext, 'onCleanup'> = {\n host,\n helpers: createHelpers(host),\n now,\n enabled,\n canEmit,\n hasCapacity,\n dropped: () => ({ ...dropped }),\n hasSnapshot: () => snapshotSeen,\n emit: <K extends SemanticFamily>(family: K, payload: SemanticPayloads[K], timestamp = now()): boolean => {\n if (!canEmit(family)) return false;\n let identity;\n try {\n identity = host.getIdentity?.();\n } catch (error) {\n report(error);\n }\n identity ??= getDocumentIdentity(host.document, host.window);\n const event = {\n name: family,\n payload: { ...payload, v: 1, tab_id: identity.tab_id, document_id: identity.document_id },\n timestamp,\n } as SemanticEvent;\n counts[family] = (counts[family] ?? 0) + 1;\n try {\n host.emit(event);\n } catch (error) {\n report(error);\n return false;\n }\n if (family === 'context') dropped = {};\n subscribers.forEach((subscriber) => safely(() => subscriber(event)));\n return true;\n },\n on: (signal, callback) => {\n let listeners = signals.get(signal);\n if (!listeners) {\n listeners = new Set();\n signals.set(signal, listeners);\n }\n const listener = (value: never) => safely(() => callback(value));\n listeners.add(listener);\n const registered = listeners;\n return () => {\n registered.delete(listener);\n };\n },\n subscribe: (callback) => {\n subscribers.add(callback);\n return () => {\n subscribers.delete(callback);\n };\n },\n };\n const detach = () => {\n active = false;\n const previous = cleanups;\n cleanups = [];\n previous.reverse().forEach((cleanup) => safely(cleanup));\n signals.clear();\n subscribers.clear();\n };\n const attach = () => {\n if (active || !requested || !settings.enabled) return;\n const rate = settings.sampleRate ?? 1;\n if (!Number.isFinite(rate) || rate <= 0 || rate > 1) return;\n if (sample === undefined) sample = (host.random ?? Math.random)();\n if (sample >= rate) return;\n active = true;\n for (const recorder of recorders) {\n if (recorder.families.some(enabled)) {\n const acquired: Cleanup[] = [];\n const scoped: RecorderContext = {\n ...context,\n onCleanup: (cleanup) => {\n acquired.push(cleanup);\n },\n on: (signal, callback) => {\n const cleanup = context.on(signal, callback);\n acquired.push(cleanup);\n return cleanup;\n },\n subscribe: (callback) => {\n const cleanup = context.subscribe(callback);\n acquired.push(cleanup);\n return cleanup;\n },\n };\n const rollback = () => {\n acquired\n .splice(0)\n .reverse()\n .forEach((cleanup) => safely(cleanup));\n };\n try {\n acquired.push(recorder.setup(scoped));\n cleanups.push(rollback);\n } catch (error) {\n rollback();\n report(error);\n }\n }\n }\n };\n return {\n isActive: () => active,\n start: () => {\n requested = true;\n attach();\n },\n stop: () => {\n requested = false;\n snapshotSeen = false;\n detach();\n },\n updateConfig: (next) => {\n detach();\n settings = copyConfig(next);\n attach();\n },\n resetSession: () => {\n detach();\n sample = undefined;\n snapshotSeen = false;\n counts = {};\n dropped = {};\n attach();\n },\n notify: (signal, value) => {\n if (signal === 'snapshot') snapshotSeen = true;\n if (signal === 'snapshot' || signal === 'navigation' || signal === 'url') context.helpers.invalidateHeading?.();\n if (!active) return;\n signals.get(signal)?.forEach((callback) => callback(value as never));\n },\n };\n}\n\nfunction copyConfig(config: SemanticCaptureConfig): SemanticCaptureConfig {\n return { ...config, families: config.families ? { ...config.families } : undefined };\n}\n"]}
@@ -0,0 +1,9 @@
1
+ import { SemanticHelpers, SemanticHost } from './types';
2
+ export declare function truncate(value: string, limit: number): string;
3
+ /** Only path-shaped information leaves the browser, including hash router paths. */
4
+ export declare function urlTemplate(value: string, base?: string): string;
5
+ export declare function roleOf(element: Element): string;
6
+ /** ARIA treats unknown nonempty tokens as true, alongside grammar and spelling. */
7
+ export declare function isAriaInvalid(element: Element): boolean;
8
+ export declare function createHelpers(host: SemanticHost): SemanticHelpers;
9
+ //# sourceMappingURL=helpers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/helpers.ts"],"names":[],"mappings":"AACA,OAAO,EAAc,eAAe,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AA+DpE,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAG7D;AAED,oFAAoF;AACpF,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,SAA8B,GAAG,MAAM,CA2BrF;AAED,wBAAgB,MAAM,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAuD/C;AAED,mFAAmF;AACnF,wBAAgB,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAGvD;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,YAAY,GAAG,eAAe,CAyPjE"}