@buildinams/tracking 0.2.0 → 0.4.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 (69) hide show
  1. package/README.md +86 -208
  2. package/dist/{sources/cart → cart}/index.d.ts +4 -4
  3. package/dist/{sources/cart → cart}/index.js +13 -3
  4. package/dist/cart/index.js.map +1 -0
  5. package/dist/chunk-JZ6HFGVJ.js +163 -0
  6. package/dist/chunk-JZ6HFGVJ.js.map +1 -0
  7. package/dist/{compatibility-Dc1JmTeG.d.ts → compatibility-wHn2I_ws.d.ts} +2 -2
  8. package/dist/{consent/index.d.ts → consent-types-DgKtGapr.d.ts} +5 -1
  9. package/dist/{consent/cookiebot → cookiebot}/index.d.ts +1 -1
  10. package/dist/{consent/cookiebot → cookiebot}/index.js +1 -1
  11. package/dist/cookiebot/index.js.map +1 -0
  12. package/dist/destination-types-DNMBOW_e.d.ts +22 -0
  13. package/dist/devtools/index.d.ts +18 -0
  14. package/dist/devtools/index.js +299 -0
  15. package/dist/devtools/index.js.map +1 -0
  16. package/dist/{sources/dom → dom}/index.d.ts +34 -40
  17. package/dist/{sources/dom → dom}/index.js +149 -247
  18. package/dist/dom/index.js.map +1 -0
  19. package/dist/events/index.d.ts +3 -6
  20. package/dist/events/index.js +5 -4
  21. package/dist/events/index.js.map +1 -1
  22. package/dist/flow/index.d.ts +10 -8
  23. package/dist/flow/index.js +23 -9
  24. package/dist/flow/index.js.map +1 -1
  25. package/dist/google/index.d.ts +32 -0
  26. package/dist/google/index.js +66 -0
  27. package/dist/google/index.js.map +1 -0
  28. package/dist/{page → navigation}/index.d.ts +7 -12
  29. package/dist/{page → navigation}/index.js +4 -10
  30. package/dist/navigation/index.js.map +1 -0
  31. package/dist/{consent/onetrust → onetrust}/index.d.ts +1 -1
  32. package/dist/{consent/onetrust → onetrust}/index.js +1 -1
  33. package/dist/onetrust/index.js.map +1 -0
  34. package/dist/shopify/index.d.ts +45 -0
  35. package/dist/{consent/shopify → shopify}/index.js +48 -20
  36. package/dist/shopify/index.js.map +1 -0
  37. package/dist/{sources/index.d.ts → source-types-fJXZeF2Q.d.ts} +1 -1
  38. package/dist/{types-DfPz7mBl.d.ts → types-CZEg03xW.d.ts} +3 -7
  39. package/docs/annotations.md +104 -0
  40. package/docs/context.md +64 -0
  41. package/docs/decisions/001-vendor-neutral-event-pipeline.md +2 -2
  42. package/docs/decisions/002-data-per-annotation-word.md +34 -0
  43. package/docs/events.md +93 -84
  44. package/docs/setup.md +189 -0
  45. package/package.json +41 -69
  46. package/dist/consent/cookiebot/index.js.map +0 -1
  47. package/dist/consent/index.js +0 -3
  48. package/dist/consent/index.js.map +0 -1
  49. package/dist/consent/onetrust/index.js.map +0 -1
  50. package/dist/consent/shopify/index.d.ts +0 -13
  51. package/dist/consent/shopify/index.js.map +0 -1
  52. package/dist/destinations/ga4/index.d.ts +0 -16
  53. package/dist/destinations/ga4/index.js +0 -15
  54. package/dist/destinations/ga4/index.js.map +0 -1
  55. package/dist/destinations/index.d.ts +0 -9
  56. package/dist/destinations/index.js +0 -17
  57. package/dist/destinations/index.js.map +0 -1
  58. package/dist/destinations/shopify/index.d.ts +0 -12
  59. package/dist/destinations/shopify/index.js +0 -18
  60. package/dist/destinations/shopify/index.js.map +0 -1
  61. package/dist/page/index.js.map +0 -1
  62. package/dist/sources/cart/index.js.map +0 -1
  63. package/dist/sources/cart/shopify/index.d.ts +0 -28
  64. package/dist/sources/cart/shopify/index.js +0 -16
  65. package/dist/sources/cart/shopify/index.js.map +0 -1
  66. package/dist/sources/dom/index.js.map +0 -1
  67. package/dist/sources/index.js +0 -3
  68. package/dist/sources/index.js.map +0 -1
  69. package/dist/types-BfJsv8AV.d.ts +0 -30
package/README.md CHANGED
@@ -1,187 +1,86 @@
1
1
  # @buildinams/tracking
2
2
 
3
- Vendor-neutral storefront events: Sources publish them to a Broker, and each Destination receives them through its own Mapping, behind consent. Behavior rules and glossary: [docs/events.md](docs/events.md).
3
+ Vendor-neutral storefront events. Sources publish Events to a Broker; each Destination, like GTM or Shopify, receives them through its own Mapping, once the shopper consented.
4
4
 
5
- ```tsx
6
- import { cookiebot } from "@buildinams/tracking/consent/cookiebot";
7
- import { shopifyCustomerPrivacy } from "@buildinams/tracking/consent/shopify";
8
- import {
9
- createDestinations,
10
- map,
11
- withConsent,
12
- } from "@buildinams/tracking/destinations";
13
- import { ga4 } from "@buildinams/tracking/destinations/ga4";
14
- import { shopify } from "@buildinams/tracking/destinations/shopify";
15
- import { createEventBroker, shape } from "@buildinams/tracking/events";
16
- import { startTracking } from "@buildinams/tracking/flow";
17
- import { createCurrentPage } from "@buildinams/tracking/page";
18
- import { createCartSource } from "@buildinams/tracking/sources/cart";
19
- import { shopifyCart } from "@buildinams/tracking/sources/cart/shopify";
20
- import type {
21
- ButtonClickData,
22
- FormEventData,
23
- FormSubmitData,
24
- ItemSelectData,
25
- LinkClickData,
26
- ListViewData,
27
- VideoEventData,
28
- } from "@buildinams/tracking/sources/dom";
5
+ ```bash
6
+ npm install @buildinams/tracking
7
+ ```
8
+
9
+ ## Setup
10
+
11
+ ```ts
12
+ // src/tracking/index.ts
29
13
  import {
30
- clicks,
31
14
  createDomSource,
32
15
  detailViews,
33
- forms,
34
- impressions,
35
16
  pageViews,
36
- scroll,
37
- selections,
38
- videos,
39
- } from "@buildinams/tracking/sources/dom";
40
-
41
- type Item = { id: string; name?: string; price?: string };
42
- type CartLine = { id: string; quantity: number; merchandise: { id: string } };
43
- type CartFragment = { lines: { nodes: CartLine[] } };
44
- type Named = { id?: string; name?: string };
45
- type Surroundings = { list: Named; promotion: Named; location: Named };
17
+ } from "@buildinams/tracking/dom";
18
+ import { createEventBroker, shape } from "@buildinams/tracking/events";
19
+ import { map } from "@buildinams/tracking/flow";
20
+ import { gtm } from "@buildinams/tracking/google";
46
21
 
47
- // A new Page per pathname; pass `key` to count e.g. `?page=2` as one too.
48
- export const currentPage = createCurrentPage();
22
+ type Item = { id: string; name?: string };
49
23
 
24
+ // The Event Catalog: every Event Name the storefront publishes, with its Data.
50
25
  export const broker = createEventBroker(
51
26
  {
52
- "item:select": {
53
- data: shape<Item & ItemSelectData>(),
54
- composed: shape<Surroundings>(),
55
- },
56
- "item:view": { data: shape<Item>(), composed: shape<Surroundings>() },
57
- "promotion:select": {
58
- data: shape<Named>(),
59
- composed: shape<Surroundings>(),
60
- },
61
- "promotion:view": { data: shape<Named>(), composed: shape<Surroundings>() },
62
- "list:view": {
63
- data: shape<ListViewData>(),
64
- composed: shape<Surroundings>(),
65
- },
66
- "link:click": {
67
- data: shape<LinkClickData>(),
68
- composed: shape<Surroundings>(),
69
- },
70
- "button:click": {
71
- data: shape<ButtonClickData>(),
72
- composed: shape<Surroundings>(),
73
- },
74
- "form:start": {
75
- data: shape<FormEventData>(),
76
- composed: shape<Surroundings>(),
77
- },
78
- "form:submit": {
79
- data: shape<FormSubmitData>(),
80
- composed: shape<Surroundings>(),
81
- },
82
- "video:start": { data: shape<VideoEventData>() },
83
- "video:progress": { data: shape<VideoEventData>() },
84
- "video:complete": { data: shape<VideoEventData>() },
27
+ "item:view": { data: shape<Item>() },
85
28
  "page:view": { data: shape<{ type?: string }>() },
86
- "page:scroll": { data: shape<{ depth: string }>() },
87
- "cart:add": { data: shape<{ line: CartLine; quantity: number }>() },
88
- "cart:remove": { data: shape<{ line: CartLine; quantity: number }>() },
89
29
  },
90
- // Optional; its return type becomes every Event's `context`.
91
- { context: () => ({ ...currentPage.read(), market: "nl" }) },
30
+ {
31
+ context: () => ({
32
+ path: location.pathname,
33
+ referrer: document.referrer,
34
+ }),
35
+ },
92
36
  );
93
37
 
94
- const destinations = createDestinations(broker.events, [
95
- map(withConsent(ga4(), "none"), {
96
- // The Composition decides: an Item in a Promotion but not a List is a promotion selection.
97
- "item:select": ({ data, composed: { list, promotion }, meta: { id } }) =>
98
- promotion && !list
99
- ? {
100
- name: "select_promotion",
101
- payload: {
102
- event_id: id,
103
- promotion_id: promotion.data.id,
104
- items: [{ item_id: data.id }],
105
- },
106
- }
107
- : {
108
- name: "select_item",
109
- payload: {
110
- event_id: id,
111
- items: [
112
- {
113
- item_id: data.id,
114
- item_list_id: list?.data.id,
115
- index: data.index,
116
- },
117
- ],
118
- },
119
- },
120
- }),
121
- map(withConsent(shopify(), ["analytics"]), {
122
- "item:view": ({ data }) => ({ name: "product_viewed", payload: { data } }),
38
+ // One Mapping per Destination, behind the consent it needs.
39
+ export const destinations = [
40
+ map(broker, gtm(), ["analytics"], {
41
+ "item:view": ({ data }) => ({
42
+ name: "view_item",
43
+ payload: { items: [{ item_id: data.id }] },
44
+ }),
123
45
  }),
124
- ]);
125
-
126
- export const domSource = createDomSource(
127
- broker,
128
- [
129
- pageViews(),
130
- selections(),
131
- impressions(),
132
- detailViews(),
133
- clicks(),
134
- forms(),
135
- videos(),
136
- scroll(),
137
- ],
138
- // Flushes Detectors when a Page ends and resets them when the next starts.
139
- { currentPage },
140
- );
141
- // Or your own adapter: { lines: (cart) => …, key: (line) => …, quantity: (line) => … }
142
- export const cartSource = createCartSource(broker, shopifyCart<CartFragment>());
46
+ ];
143
47
 
144
- // In the browser, once, e.g. in instrumentation-client.ts (see Starting the Flow):
145
- startTracking(broker, cookiebot(), destinations, {
146
- sources: [domSource, cartSource],
147
- // Tells Shopify what the shopper answered in Cookiebot
148
- consentSinks: [shopifyCustomerPrivacy()],
149
- });
48
+ export const domSource = createDomSource(broker, [pageViews(), detailViews()]);
150
49
  ```
151
50
 
152
- Use `onetrust()` from `@buildinams/tracking/consent/onetrust` or `shopifyConsent()` from `@buildinams/tracking/consent/shopify` instead of `cookiebot()` for OneTrust or Shopify's privacy banner.
51
+ Start the Flow once, in the browser's entry point, so it runs before hydration. In Next.js that's `instrumentation-client.ts`, and like Hydrogen it also needs [Client-side navigation](#client-side-navigation):
153
52
 
154
- Then:
53
+ ```ts
54
+ import { cookiebot } from "@buildinams/tracking/cookiebot";
55
+ import { startTracking } from "@buildinams/tracking/flow";
155
56
 
156
- - Opt in to clicks and videos per element with a Flag (`data-e="click"`, `data-e="video"`), or per area with `data-e-auto="links buttons forms videos"`, e.g. `<footer data-e-auto="links">`. `data-e-auto="none"` opts an area or a single element out.
157
- - Describe each Page with `data-e="page"`, e.g. `<main data-e="page" data-e-data="type:product">`: `pageViews()` publishes one `page:view` per Page with the Data of every such element, also when there are none. Put it on an element without a Role, e.g. `<div hidden data-e="page" data-e-data="type:product">` inside an Item, or the Role's Data is mixed in. List `pageViews()` first so `page:view` precedes the Page's other Events, and when mapping it to GA4's `page_view`, turn off gtag's own (`send_page_view: false` and Enhanced Measurement's history page views) or Pages count twice.
158
- - Mark the product on its detail page `data-e="item detail"` for `item:view`; clicks inside it, like add to cart, aren't `item:select`. `data-e` takes several words in any order.
159
- - Annotate markup: `data-e="item" data-e-data="id:product1"`, with `data-e-data="name"` on a descendant to use its text. In JSX or templates, spread `annotate()` from `/sources/dom` to write both attributes, e.g. `<div {...annotate(["item", "detail"], { id, title })} />`: it escapes `;` and `\` in values, which hand-written markup writes as `\;` and `\\`.
160
- - Limit a Detector by pathname with `only()` or `except()` from `/sources/dom`, e.g. `except(scroll(), ["/collections/*", "/search", /^\/account\//])` or `only(videos(), ["/lookbook/*"])`.
161
- - Call `currentPage.sync()` after every client-side navigation; in React, from a layout effect (see [New Pages in React](#new-pages-in-react)). Calling it when the Page didn't change does nothing.
162
- - Call `cartSource.setSnapshot(cart)` whenever the cart changes.
57
+ import { broker, destinations, domSource } from "./src/tracking";
58
+
59
+ startTracking(broker, cookiebot(), destinations, { sources: [domSource] });
60
+ ```
163
61
 
164
- ## Starting the Flow
62
+ ### Client-side navigation
165
63
 
166
- Start the Flow once, in the browser's entry point rather than in a component: it then runs before hydration, so clicks and views before React takes over count too. In Next.js, that's `instrumentation-client.ts` at the project root (or in `src/`):
64
+ Next.js, Hydrogen, or a theme that swaps pages with `pushState`, change Pages without a page load. Follow them with a Client Navigation: it gives the DOM Source each new Page and keeps the referrer right.
167
65
 
168
66
  ```ts
169
- // instrumentation-client.ts
170
- import { startTracking } from "@buildinams/tracking/flow";
67
+ import { createClientNavigation } from "@buildinams/tracking/navigation";
171
68
 
172
- import { broker, cartSource, destinations, domSource } from "./src/tracking";
69
+ export const clientNavigation = createClientNavigation();
173
70
 
174
- startTracking(broker, cookiebot(), destinations, {
175
- sources: [domSource, cartSource],
176
- consentSinks: [shopifyCustomerPrivacy()],
71
+ export const broker = createEventBroker(catalog, {
72
+ context: () => ({
73
+ path: location.pathname,
74
+ referrer: clientNavigation.referrer(),
75
+ }),
177
76
  });
178
- ```
179
-
180
- Elsewhere, call it in the module that boots the page. On the server it does nothing, and running it again, e.g. after HMR, replaces the previous Flow.
181
77
 
182
- ## New Pages in React
78
+ export const domSource = createDomSource(broker, detectors, {
79
+ clientNavigation,
80
+ });
81
+ ```
183
82
 
184
- `currentPage.sync()` stays in React: it has to run after the URL changed, which a router's "transition start" hook (like Next's `onRouterTransitionStart`) is too early for. Call it from a layout effect on every navigation:
83
+ Call `clientNavigation.sync()` on every navigation, from a layout effect so it runs before Detectors see the new page:
185
84
 
186
85
  ```tsx
187
86
  "use client";
@@ -189,80 +88,59 @@ Elsewhere, call it in the module that boots the page. On the server it does noth
189
88
  import { usePathname } from "next/navigation";
190
89
  import * as React from "react";
191
90
 
192
- import { currentPage } from "./tracking";
91
+ import { clientNavigation } from "./tracking";
193
92
 
194
93
  export const TrackingPages = () => {
195
94
  const pathname = usePathname();
196
- // With a `key` that reads the query, add `useSearchParams()` here too.
197
- React.useLayoutEffect(() => currentPage.sync(), [pathname]);
198
-
95
+ React.useLayoutEffect(() => clientNavigation.sync(), [pathname]);
199
96
  return null;
200
97
  };
201
98
  ```
202
99
 
203
- It must be a layout effect. React commits the new page's DOM first, then runs layout effects, and only then do Detectors watching the DOM (like `detailViews()`) report what changed. With `useEffect`, a product page's `item:view` is published before `currentPage.sync()` and carries the previous Page's referrer. The first Page is the one `createCurrentPage()` was called on, so the initial render's `sync()` does nothing.
100
+ Sites where every navigation is a full page load don't need it.
204
101
 
205
- ## Custom Context
102
+ The [complete setup](docs/setup.md) has every Event Name, Detector, the Cart Source and consent in one file.
206
103
 
207
- `context` is any function; its return type becomes every Event's `context`, typed in Mappings. Without it, `context` is `undefined`. Spread `currentPage.read()` into your own to add project data, such as the user:
104
+ ## Annotating markup
208
105
 
209
- ```ts
210
- // src/tracking/context.ts
211
- import { createCurrentPage } from "@buildinams/tracking/page";
106
+ Nothing is tracked unless the markup asks for it:
212
107
 
213
- // The one Current Page: also pass it to `createDomSource()` and call its `sync()`.
214
- export const currentPage = createCurrentPage();
108
+ ```html
109
+ <main data-e="item detail" data-e-item="id:product1">
110
+ <div hidden data-e="page" data-e-page="type:product"></div>
111
+ </main>
112
+ ```
215
113
 
216
- type User =
217
- | { loggedIn: true; id: string; tier: "member" | "vip" }
218
- | { loggedIn: false };
114
+ This publishes `page:view` with `{ type: "product" }` and `item:view` with `{ id: "product1" }`. More in [Annotations](docs/annotations.md).
219
115
 
220
- let user: User = { loggedIn: false };
116
+ ## Consent
221
117
 
222
- /** Called by the app whenever the session changes. */
223
- export const setTrackingUser = (next: User) => {
224
- user = next;
225
- };
118
+ Read the shopper's answer with `cookiebot()`, `onetrust()` (`/onetrust`) or `shopifyConsent()` (`/shopify`). Pass it on to platforms that gate their own tracking with `consentSinks`:
226
119
 
227
- export const readContext = () => ({
228
- ...currentPage.read(),
229
- user,
230
- market: document.documentElement.dataset.market ?? "default",
120
+ ```ts
121
+ startTracking(broker, cookiebot(), destinations, {
122
+ sources: [domSource],
123
+ consentSinks: [googleConsentMode(), shopifyCustomerPrivacy()],
231
124
  });
232
125
  ```
233
126
 
127
+ `googleConsentMode()` denies everything when created, so start the Flow before GTM loads. Both sinks take `mapConsent(consent, defaults)` to change how an answer maps:
128
+
234
129
  ```ts
235
- const broker = createEventBroker(catalog, { context: readContext });
236
-
237
- const destinations = createDestinations(broker.events, [
238
- map(withConsent(ga4(), "none"), {
239
- "item:select": ({ data, context: { user } }) => ({
240
- name: "select_item",
241
- payload: {
242
- user_id: user.loggedIn ? user.id : undefined,
243
- items: [{ item_id: data.id }],
244
- },
245
- }),
130
+ googleConsentMode({
131
+ mapConsent: (_consent, google) => ({
132
+ ...google,
133
+ functionality_storage: "granted",
246
134
  }),
247
- ]);
135
+ });
248
136
  ```
249
137
 
250
- ```tsx
251
- // Wherever the session lives
252
- const TrackingUser = () => {
253
- const session = useSession();
254
- useEffect(() => {
255
- setTrackingUser(
256
- session
257
- ? { loggedIn: true, id: session.id, tier: session.tier }
258
- : { loggedIn: false },
259
- );
260
- }, [session]);
261
- return null;
262
- };
263
- ```
138
+ Your own sink is `{ name, apply(consent), clear() }`; `clear()` undoes `apply()` when the answer is withdrawn.
139
+
140
+ ## Docs
264
141
 
265
- - **Read on publish.** Each Event keeps the Context of the moment it happened, also while it waits for consent; a login mid-visit shows from the next Event on.
266
- - **Synchronous.** The reader runs inside `publish()`; keep async data, like a fetched profile, in a variable it returns, as `setTrackingUser` does.
267
- - **Only what Mappings send leaves the page.** Context isn't forwarded by itself: each Mapping picks the fields its Destination gets, behind that Destination's consent, so personal data is decided per Destination.
268
- - **Browser only.** The reader never runs on the server, so it can use `document` and `window`.
142
+ - [Complete setup](docs/setup.md): everything in one file.
143
+ - [Annotations](docs/annotations.md): Items, Lists, Pages, clicks and videos.
144
+ - [Context](docs/context.md): the user or market on every Event.
145
+ - [Events](docs/events.md): glossary, behavior rules and built-in Event Names.
146
+ - [Decisions](docs/decisions/): why it's shaped this way.
@@ -1,12 +1,12 @@
1
- import { R as RequireCompatible } from '../../compatibility-Dc1JmTeG.js';
2
- import { C as Catalog, c as CatalogEntry, E as EventBroker } from '../../types-DfPz7mBl.js';
3
- import { Source } from '../index.js';
1
+ import { C as Catalog, c as CatalogEntry, b as EventBroker } from '../types-CZEg03xW.js';
2
+ import { R as RequireCompatible } from '../compatibility-wHn2I_ws.js';
3
+ import { S as Source } from '../source-types-fJXZeF2Q.js';
4
4
 
5
5
  type CartChange<Line> = {
6
6
  line: Line;
7
7
  quantity: number;
8
8
  };
9
- /** How the Cart Source reads a cart; see `shopifyCart()` in `/sources/cart/shopify`. */
9
+ /** How the Cart Source reads a cart; see `shopifyCart()` in `/shopify`. */
10
10
  type CartAdapter<Cart, Line> = {
11
11
  lines(cart: Cart): readonly Line[];
12
12
  /** Identifies a line across Snapshots; lines sharing a key are summed, and a changed key is a remove plus an add. */
@@ -1,13 +1,23 @@
1
- // src/sources/cart/create-cart-source.ts
1
+ // src/cart/create-cart-source.ts
2
2
  var createCartSource = (broker, {
3
3
  lines,
4
4
  key,
5
5
  quantity
6
6
  }) => {
7
7
  let previous;
8
+ let running = 0;
9
+ let stopped = false;
8
10
  const publish = broker.publish;
9
11
  return {
10
- start: () => () => {
12
+ start() {
13
+ running++;
14
+ let done = false;
15
+ return () => {
16
+ if (done) return;
17
+ done = true;
18
+ running--;
19
+ stopped = true;
20
+ };
11
21
  },
12
22
  setSnapshot(cart) {
13
23
  if (cart == null) return;
@@ -19,7 +29,7 @@ var createCartSource = (broker, {
19
29
  total: (next.get(id)?.total ?? 0) + quantity(line)
20
30
  });
21
31
  }
22
- if (previous) {
32
+ if (previous && (running > 0 || !stopped)) {
23
33
  for (const [id, { line, total }] of previous)
24
34
  if (!next.has(id)) publish("cart:remove", { line, quantity: total });
25
35
  for (const [id, { line, total }] of next) {
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/cart/create-cart-source.ts"],"names":[],"mappings":";AA0BO,IAAM,gBAAA,GAAmB,CAC/B,MAAA,EACA;AAAA,EACC,KAAA;AAAA,EACA,GAAA;AAAA,EACA;AACD,CAAA,KACsB;AACtB,EAAA,IAAI,QAAA;AAEJ,EAAA,IAAI,OAAA,GAAU,CAAA;AACd,EAAA,IAAI,OAAA,GAAU,KAAA;AACd,EAAA,MAAM,UAAU,MAAA,CAAO,OAAA;AAKvB,EAAA,OAAO;AAAA,IACN,KAAA,GAAQ;AACP,MAAA,OAAA,EAAA;AACA,MAAA,IAAI,IAAA,GAAO,KAAA;AACX,MAA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EAAE,IAAA,EAAM,QAAA,EAAU,CAAC,KAAA,EAAO,CAAA;AAAA,QACjE;AAAA,MACD;AACA,MAAA,QAAA,GAAW,IAAA;AAAA,IACZ;AAAA,GACD;AACD","file":"index.js","sourcesContent":["import type { Catalog, CatalogEntry, EventBroker } from \"../events\";\nimport type { RequireCompatible } from \"../events/compatibility\";\nimport type { Source } from \"../flow/source-types\";\n\nexport type CartChange<Line> = { line: Line; quantity: number };\n\n/** How the Cart Source reads a cart; see `shopifyCart()` in `/shopify`. */\nexport type CartAdapter<Cart, Line> = {\n\tlines(cart: Cart): readonly Line[];\n\t/** Identifies a line across Snapshots; lines sharing a key are summed, and a changed key is a remove plus an add. */\n\tkey(line: Line): string;\n\tquantity(line: Line): number;\n};\n\ntype CartPublished<Line> = {\n\t\"cart:add\": CartChange<Line>;\n\t\"cart:remove\": CartChange<Line>;\n};\n\nexport type CartSource<Cart> = Source & {\n\t/** `null` or `undefined` while the cart isn't loaded; ignored. */\n\tsetSnapshot(cart: Cart | null | undefined): void;\n};\n\ntype CartCatalog = Catalog & Record<\"cart:add\" | \"cart:remove\", CatalogEntry>;\n\nexport const createCartSource = <C extends CartCatalog, Cart, Line>(\n\tbroker: EventBroker<C>,\n\t{\n\t\tlines,\n\t\tkey,\n\t\tquantity,\n\t}: CartAdapter<Cart, Line> & RequireCompatible<C, CartPublished<Line>>,\n): CartSource<Cart> => {\n\tlet previous: Map<string, { line: Line; total: number }> | undefined;\n\t// Until the first start, the Broker holds what's published for the Flow; once stopped, nothing is listening.\n\tlet running = 0;\n\tlet stopped = false;\n\tconst publish = broker.publish as (\n\t\tname: \"cart:add\" | \"cart:remove\",\n\t\tdata: CartChange<Line>,\n\t) => void;\n\n\treturn {\n\t\tstart() {\n\t\t\trunning++;\n\t\t\tlet done = false;\n\t\t\treturn () => {\n\t\t\t\tif (done) return;\n\t\t\t\tdone = true;\n\t\t\t\trunning--;\n\t\t\t\tstopped = true;\n\t\t\t};\n\t\t},\n\t\tsetSnapshot(cart) {\n\t\t\tif (cart == null) return;\n\t\t\t// Summed per key: e.g. the same variant can sit on several lines with different attributes.\n\t\t\tconst next = new Map<string, { line: Line; total: number }>();\n\t\t\tfor (const line of lines(cart)) {\n\t\t\t\tconst id = key(line);\n\t\t\t\tnext.set(id, {\n\t\t\t\t\tline,\n\t\t\t\t\ttotal: (next.get(id)?.total ?? 0) + quantity(line),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// The first Snapshot is the cart as loaded, not something the shopper did. Snapshots while stopped still move the baseline, so a restart doesn't report the gap.\n\t\t\tif (previous && (running > 0 || !stopped)) {\n\t\t\t\tfor (const [id, { line, total }] of previous)\n\t\t\t\t\tif (!next.has(id)) publish(\"cart:remove\", { line, quantity: total });\n\t\t\t\tfor (const [id, { line, total }] of next) {\n\t\t\t\t\tconst delta = total - (previous.get(id)?.total ?? 0);\n\t\t\t\t\tif (delta > 0) publish(\"cart:add\", { line, quantity: delta });\n\t\t\t\t\tif (delta < 0) publish(\"cart:remove\", { line, quantity: -delta });\n\t\t\t\t}\n\t\t\t}\n\t\t\tprevious = next;\n\t\t},\n\t};\n};\n"]}
@@ -0,0 +1,163 @@
1
+ import { IS_DEVELOPMENT } from './chunk-KLN5K6PR.js';
2
+
3
+ // src/dom/annotations.ts
4
+ var ANNOTATION_ATTRIBUTE = "data-e";
5
+ var ROLES = ["location", "list", "item", "promotion", "form"];
6
+ var FLAGS = ["click", "video", "detail", "page"];
7
+ var dataAttribute = (word) => `${ANNOTATION_ATTRIBUTE}-${word}`;
8
+ var DATA_WORDS = [...ROLES, ...FLAGS].filter(
9
+ (word) => word !== "detail"
10
+ );
11
+ var DATA_ATTRIBUTES = DATA_WORDS.map(dataAttribute);
12
+ var setSelector = (attribute) => `[${attribute}]:not([${attribute}="false"])`;
13
+ var CLONE_ATTRIBUTE = `${ANNOTATION_ATTRIBUTE}-clone`;
14
+ var IGNORE_ATTRIBUTE = `${ANNOTATION_ATTRIBUTE}-ignore`;
15
+ var IGNORED = setSelector(IGNORE_ATTRIBUTE);
16
+ var isIgnored = (element) => !!element.closest(IGNORED);
17
+ var wordSelector = (word) => `[${ANNOTATION_ATTRIBUTE}~="${word}"]`;
18
+ var roleSelector = (role) => wordSelector(role);
19
+ var flagSelector = (flag) => wordSelector(flag);
20
+ var hasWord = (element, word) => (element.getAttribute(ANNOTATION_ATTRIBUTE) ?? "").split(/\s+/).includes(word);
21
+ var splitParts = (value) => {
22
+ const parts = [];
23
+ let part = "";
24
+ for (let index = 0; index < value.length; index++) {
25
+ const char = value[index];
26
+ const next = value[index + 1];
27
+ if (char === "\\" && (next === ";" || next === "\\")) {
28
+ part += next;
29
+ index++;
30
+ } else if (char === ";") {
31
+ parts.push(part);
32
+ part = "";
33
+ } else part += char;
34
+ }
35
+ parts.push(part);
36
+ return parts;
37
+ };
38
+ var parse = (value) => splitParts(value ?? "").map((part) => part.trim()).filter(Boolean).map((part) => {
39
+ const colon = part.indexOf(":");
40
+ return colon === -1 ? { key: part, value: void 0 } : {
41
+ key: part.slice(0, colon).trim(),
42
+ value: part.slice(colon + 1).trim()
43
+ };
44
+ });
45
+ var isRole = (word) => ROLES.includes(word);
46
+ var cache;
47
+ var memo = (element, key, read) => {
48
+ if (!cache) {
49
+ cache = /* @__PURE__ */ new WeakMap();
50
+ queueMicrotask(() => {
51
+ cache = void 0;
52
+ });
53
+ }
54
+ let entries = cache.get(element);
55
+ if (!entries) cache.set(element, entries = /* @__PURE__ */ new Map());
56
+ if (!entries.has(key)) entries.set(key, read());
57
+ return entries.get(key);
58
+ };
59
+ var readUncached = (element, word) => {
60
+ const attribute = dataAttribute(word);
61
+ const data = {};
62
+ for (const { key, value } of parse(element.getAttribute(attribute)))
63
+ if (value !== void 0) data[key] = value;
64
+ if (!isRole(word)) return data;
65
+ const owner = roleSelector(word);
66
+ const ignored = isIgnored(element);
67
+ for (const field of element.querySelectorAll(`[${attribute}]`)) {
68
+ if (field.closest(owner) !== element || isIgnored(field) !== ignored)
69
+ continue;
70
+ for (const { key, value } of parse(field.getAttribute(attribute)))
71
+ data[key] = value ?? field.textContent?.trim() ?? "";
72
+ }
73
+ return data;
74
+ };
75
+ var readData = (element, word) => ({
76
+ ...memo(element, word, () => readUncached(element, word))
77
+ });
78
+ var surrounding = (element, role) => element.closest(roleSelector(role)) ?? void 0;
79
+ var readAnnotated = (element, word) => {
80
+ const composed = {};
81
+ for (const role of ROLES) {
82
+ if (role === word) continue;
83
+ const container = surrounding(element, role);
84
+ if (container) composed[role] = { data: readData(container, role) };
85
+ }
86
+ return { data: readData(element, word), composed };
87
+ };
88
+ var CLONE = setSelector(CLONE_ATTRIBUTE);
89
+ var isClone = (item, container) => {
90
+ const clone = item.closest(CLONE);
91
+ return !!clone && clone !== container && container.contains(clone);
92
+ };
93
+ var entriesOf = (container, role) => memo(container, `entries:${role}`, () => {
94
+ const candidates = container.matches(roleSelector("item")) ? [container, ...container.querySelectorAll(roleSelector("item"))] : [...container.querySelectorAll(roleSelector("item"))];
95
+ const ignored = isIgnored(container);
96
+ const entries = candidates.filter(
97
+ (item) => !hasWord(item, "detail") && isIgnored(item) === ignored && surrounding(item, role) === container && !isClone(item, container)
98
+ );
99
+ return {
100
+ entries,
101
+ positions: new Map(entries.map((item, index) => [item, index]))
102
+ };
103
+ });
104
+ var entriesByData = (container, role) => memo(container, `data:${role}`, () => {
105
+ const byData = /* @__PURE__ */ new Map();
106
+ for (const entry of entriesOf(container, role).entries) {
107
+ const key = JSON.stringify(readData(entry, "item"));
108
+ if (!byData.has(key)) byData.set(key, entry);
109
+ }
110
+ return byData;
111
+ });
112
+ var entryOf = (item, container, role) => {
113
+ if (entriesOf(container, role).positions.has(item)) return item;
114
+ if (!isClone(item, container)) return void 0;
115
+ return entriesByData(container, role).get(
116
+ JSON.stringify(readData(item, "item"))
117
+ );
118
+ };
119
+ var offsetOf = (list) => {
120
+ const offset = Number.parseInt(readData(list, "list").offset ?? "", 10);
121
+ return Number.isNaN(offset) ? 0 : offset;
122
+ };
123
+ var indexIn = (item, container, role) => {
124
+ const entry = entryOf(item, container, role);
125
+ if (!entry) return void 0;
126
+ const position = entriesOf(container, role).positions.get(entry);
127
+ return role === "list" ? offsetOf(container) + position : position;
128
+ };
129
+ var promotionItems = (promotion) => entriesOf(promotion, "promotion").entries.map((item, index) => ({
130
+ ...readData(item, "item"),
131
+ index
132
+ }));
133
+ var INVALID_KEY = /[\s:;\\]/;
134
+ var escapeValue = (value) => value.replaceAll("\\", "\\\\").replaceAll(";", "\\;");
135
+ var validKey = (key) => {
136
+ if (!INVALID_KEY.test(key)) return true;
137
+ if (IS_DEVELOPMENT)
138
+ console.warn(
139
+ `[tracking] Annotation key "${key}" left out: keys can't contain whitespace, ":", ";" or "\\".`
140
+ );
141
+ return false;
142
+ };
143
+ var encodeData = (data) => Object.entries(data).filter(([key, value]) => value != null && validKey(key)).map(([key, value]) => `${key}:${escapeValue(String(value))}`).join(";");
144
+
145
+ // src/dom/opt-in.ts
146
+ var AUTO_ATTRIBUTE = "data-e-auto";
147
+ var INTERACTIVE = 'a[href], button, [role="button"], input[type="submit"], input[type="button"]';
148
+ var isOptedIn = (element, { flag, kind, fallback }) => {
149
+ if (flag && hasWord(element, flag)) return true;
150
+ const scope = element.closest(`[${AUTO_ATTRIBUTE}]`);
151
+ if (!scope) return fallback;
152
+ return (scope.getAttribute(AUTO_ATTRIBUTE) ?? "").split(/\s+/).includes(kind);
153
+ };
154
+ var readText = (element) => (element.getAttribute("aria-label") ?? (element instanceof HTMLInputElement ? element.value : element.textContent) ?? "").replace(/\s+/g, " ").trim().slice(0, 100);
155
+ var compact = (data) => Object.fromEntries(
156
+ Object.entries(data).filter(
157
+ ([, value]) => value !== void 0 && value !== ""
158
+ )
159
+ );
160
+
161
+ export { ANNOTATION_ATTRIBUTE, AUTO_ATTRIBUTE, CLONE_ATTRIBUTE, DATA_ATTRIBUTES, DATA_WORDS, FLAGS, IGNORED, IGNORE_ATTRIBUTE, INTERACTIVE, ROLES, compact, dataAttribute, encodeData, entryOf, flagSelector, hasWord, indexIn, isIgnored, isOptedIn, isRole, parse, promotionItems, readAnnotated, readData, readText, roleSelector, surrounding };
162
+ //# sourceMappingURL=chunk-JZ6HFGVJ.js.map
163
+ //# sourceMappingURL=chunk-JZ6HFGVJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/dom/annotations.ts","../src/dom/opt-in.ts"],"names":[],"mappings":";;;AAGO,IAAM,oBAAA,GAAuB;AAE7B,IAAM,QAAQ,CAAC,UAAA,EAAY,MAAA,EAAQ,MAAA,EAAQ,aAAa,MAAM;AAC9D,IAAM,KAAA,GAAQ,CAAC,OAAA,EAAS,OAAA,EAAS,UAAU,MAAM;AAOjD,IAAM,gBAAgB,CAAqB,IAAA,KACjD,CAAA,EAAG,oBAAoB,IAAI,IAAI,CAAA;AAEzB,IAAM,aAAa,CAAC,GAAG,KAAA,EAAO,GAAG,KAAK,CAAA,CAAE,MAAA;AAAA,EAC9C,CAAC,SAA2B,IAAA,KAAS;AACtC;AAEO,IAAM,eAAA,GAAkB,UAAA,CAAW,GAAA,CAAI,aAAa;AAG3D,IAAM,cAAc,CAAC,SAAA,KACpB,CAAA,CAAA,EAAI,SAAS,UAAU,SAAS,CAAA,UAAA,CAAA;AAG1B,IAAM,eAAA,GAAkB,GAAG,oBAAoB,CAAA,MAAA;AAG/C,IAAM,gBAAA,GAAmB,GAAG,oBAAoB,CAAA,OAAA;AAEhD,IAAM,OAAA,GAAU,YAAY,gBAAgB;AAG5C,IAAM,YAAY,CAAC,OAAA,KAAqB,CAAC,CAAC,OAAA,CAAQ,QAAQ,OAAO;AAWxE,IAAM,eAAe,CAAC,IAAA,KAAiB,CAAA,CAAA,EAAI,oBAAoB,MAAM,IAAI,CAAA,EAAA,CAAA;AAElE,IAAM,YAAA,GAAe,CAAC,IAAA,KAAe,YAAA,CAAa,IAAI;AACtD,IAAM,YAAA,GAAe,CAAC,IAAA,KAAe,YAAA,CAAa,IAAI;AAEtD,IAAM,OAAA,GAAU,CAAC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EACA,EAAE,IAAA,EAAM,IAAA,EAAM,UAAS,KACnB;AACJ,EAAA,IAAI,IAAA,IAAQ,OAAA,CAAQ,OAAA,EAAS,IAAI,GAAG,OAAO,IAAA;AAC3C,EAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,OAAA,CAAQ,CAAA,CAAA,EAAI,cAAc,CAAA,CAAA,CAAG,CAAA;AACnD,EAAA,IAAI,CAAC,OAAO,OAAO,QAAA;AACnB,EAAA,OAAA,CAAQ,KAAA,CAAM,aAAa,cAAc,CAAA,IAAK,IAAI,KAAA,CAAM,KAAK,CAAA,CAAE,QAAA,CAAS,IAAI,CAAA;AAC7E;AAEO,IAAM,QAAA,GAAW,CAAC,OAAA,KAAA,CAEvB,OAAA,CAAQ,aAAa,YAAY,CAAA,KAChC,OAAA,YAAmB,gBAAA,GACjB,OAAA,CAAQ,KAAA,GACR,QAAQ,WAAA,CAAA,IACX,EAAA,EAEC,QAAQ,MAAA,EAAQ,GAAG,EACnB,IAAA,EAAK,CACL,KAAA,CAAM,CAAA,EAAG,GAAG;AAGR,IAAM,OAAA,GAAU,CAAoC,IAAA,KAC1D,MAAA,CAAO,WAAA;AAAA,EACN,MAAA,CAAO,OAAA,CAAQ,IAAI,CAAA,CAAE,MAAA;AAAA,IACpB,CAAC,GAAG,KAAK,CAAA,KAAM,KAAA,KAAU,UAAa,KAAA,KAAU;AAAA;AAElD","file":"chunk-JZ6HFGVJ.js","sourcesContent":["import { IS_DEVELOPMENT } from \"../config\";\n\n/** Space-separated words: Roles, and Flags that opt the element in to a Detector. */\nexport const ANNOTATION_ATTRIBUTE = \"data-e\";\n\nexport const ROLES = [\"location\", \"list\", \"item\", \"promotion\", \"form\"] as const;\nexport const FLAGS = [\"click\", \"video\", \"detail\", \"page\"] as const;\n\nexport type Role = (typeof ROLES)[number];\nexport type Flag = (typeof FLAGS)[number];\n/** Words with their own Data attribute, `data-e-<word>`. */\nexport type DataWord = Exclude<Role | Flag, \"detail\">;\n\nexport const dataAttribute = <W extends DataWord>(word: W) =>\n\t`${ANNOTATION_ATTRIBUTE}-${word}` as const;\n\nexport const DATA_WORDS = [...ROLES, ...FLAGS].filter(\n\t(word): word is DataWord => word !== \"detail\",\n);\n\nexport const DATA_ATTRIBUTES = DATA_WORDS.map(dataAttribute);\n\n/** Selects a boolean attribute that's set; `\"false\"` isn't, as React renders `attribute={false}` that way. */\nconst setSelector = (attribute: string) =>\n\t`[${attribute}]:not([${attribute}=\"false\"])`;\n\n/** Marks a copy a looping carousel renders, on the Item or a wrapper. */\nexport const CLONE_ATTRIBUTE = `${ANNOTATION_ATTRIBUTE}-clone`;\n\n/** Removes an area from tracking entirely, Annotations included. */\nexport const IGNORE_ATTRIBUTE = `${ANNOTATION_ATTRIBUTE}-ignore`;\n\nexport const IGNORED = setSelector(IGNORE_ATTRIBUTE);\n\n/** Whether the element is in an area the DOM Source doesn't see. */\nexport const isIgnored = (element: Element) => !!element.closest(IGNORED);\n\nexport type AnnotationData = Record<string, string>;\n\nexport type AnnotationValue = string | number | boolean | null | undefined;\n\nexport type Annotated = {\n\tdata: AnnotationData;\n\tcomposed: Partial<Record<Role, { data: AnnotationData }>>;\n};\n\nconst wordSelector = (word: string) => `[${ANNOTATION_ATTRIBUTE}~=\"${word}\"]`;\n\nexport const roleSelector = (role: Role) => wordSelector(role);\nexport const flagSelector = (flag: Flag) => wordSelector(flag);\n\nexport const hasWord = (element: Element, word: Role | Flag) =>\n\t(element.getAttribute(ANNOTATION_ATTRIBUTE) ?? \"\")\n\t\t.split(/\\s+/)\n\t\t.includes(word);\n\n/** Splits a Data attribute on `;`, reading `\\;` and `\\\\` as a literal `;` and `\\`. */\nconst splitParts = (value: string) => {\n\tconst parts: string[] = [];\n\tlet part = \"\";\n\tfor (let index = 0; index < value.length; index++) {\n\t\tconst char = value[index];\n\t\tconst next = value[index + 1];\n\t\tif (char === \"\\\\\" && (next === \";\" || next === \"\\\\\")) {\n\t\t\tpart += next;\n\t\t\tindex++;\n\t\t} else if (char === \";\") {\n\t\t\tparts.push(part);\n\t\t\tpart = \"\";\n\t\t} else part += char;\n\t}\n\tparts.push(part);\n\treturn parts;\n};\n\nexport const parse = (value: string | null) =>\n\tsplitParts(value ?? \"\")\n\t\t.map((part) => part.trim())\n\t\t.filter(Boolean)\n\t\t.map((part) => {\n\t\t\tconst colon = part.indexOf(\":\");\n\t\t\treturn colon === -1\n\t\t\t\t? { key: part, value: undefined }\n\t\t\t\t: {\n\t\t\t\t\t\tkey: part.slice(0, colon).trim(),\n\t\t\t\t\t\tvalue: part.slice(colon + 1).trim(),\n\t\t\t\t\t};\n\t\t});\n\nexport const isRole = (word: string): word is Role =>\n\t(ROLES as readonly string[]).includes(word);\n\nlet cache: WeakMap<Element, Map<string, unknown>> | undefined;\n\n/** `read()`'s result for this element and key until the current callback returns, e.g. across one IntersectionObserver batch. */\nconst memo = <T>(element: Element, key: string, read: () => T): T => {\n\tif (!cache) {\n\t\tcache = new WeakMap();\n\t\tqueueMicrotask(() => {\n\t\t\tcache = undefined;\n\t\t});\n\t}\n\tlet entries = cache.get(element);\n\tif (!entries) cache.set(element, (entries = new Map()));\n\tif (!entries.has(key)) entries.set(key, read());\n\treturn entries.get(key) as T;\n};\n\nconst readUncached = (element: Element, word: DataWord): AnnotationData => {\n\tconst attribute = dataAttribute(word);\n\tconst data: AnnotationData = {};\n\tfor (const { key, value } of parse(element.getAttribute(attribute)))\n\t\tif (value !== undefined) data[key] = value;\n\tif (!isRole(word)) return data;\n\n\tconst owner = roleSelector(word);\n\tconst ignored = isIgnored(element);\n\tfor (const field of element.querySelectorAll(`[${attribute}]`)) {\n\t\tif (field.closest(owner) !== element || isIgnored(field) !== ignored)\n\t\t\tcontinue;\n\t\tfor (const { key, value } of parse(field.getAttribute(attribute)))\n\t\t\tdata[key] = value ?? field.textContent?.trim() ?? \"\";\n\t}\n\treturn data;\n};\n\n/** The element's own `data-e-<word>`, plus, for a Role, the fields it owns: `data-e-<role>` on descendants whose nearest element with that Role is this one. */\nexport const readData = (element: Element, word: DataWord): AnnotationData => ({\n\t...memo(element, word, () => readUncached(element, word)),\n});\n\n/** The nearest element with `role`, the element itself included. */\nexport const surrounding = (element: Element, role: Role) =>\n\telement.closest(roleSelector(role)) ?? undefined;\n\n/** The element's Data as `word`, with the nearest element of every other Role on or above it as its Composition. */\nexport const readAnnotated = (element: Element, word: DataWord): Annotated => {\n\tconst composed: Annotated[\"composed\"] = {};\n\tfor (const role of ROLES) {\n\t\tif (role === word) continue;\n\t\tconst container = surrounding(element, role);\n\t\tif (container) composed[role] = { data: readData(container, role) };\n\t}\n\treturn { data: readData(element, word), composed };\n};\n\n// Not `inert` or `aria-hidden`: carousels also put those on off-screen originals.\nconst CLONE = setSelector(CLONE_ATTRIBUTE);\n\nconst isClone = (item: Element, container: Element) => {\n\tconst clone = item.closest(CLONE);\n\treturn !!clone && clone !== container && container.contains(clone);\n};\n\ntype Container = \"list\" | \"promotion\";\n\n/** A detail view, e.g. a quick view rendered inside a product card, isn't one of a List's or Promotion's Items; nor is a clone. */\nconst entriesOf = (container: Element, role: Container) =>\n\tmemo(container, `entries:${role}`, () => {\n\t\tconst candidates = container.matches(roleSelector(\"item\"))\n\t\t\t? [container, ...container.querySelectorAll(roleSelector(\"item\"))]\n\t\t\t: [...container.querySelectorAll(roleSelector(\"item\"))];\n\t\tconst ignored = isIgnored(container);\n\t\tconst entries = candidates.filter(\n\t\t\t(item) =>\n\t\t\t\t!hasWord(item, \"detail\") &&\n\t\t\t\tisIgnored(item) === ignored &&\n\t\t\t\tsurrounding(item, role) === container &&\n\t\t\t\t!isClone(item, container),\n\t\t);\n\t\treturn {\n\t\t\tentries,\n\t\t\tpositions: new Map(entries.map((item, index) => [item, index])),\n\t\t};\n\t});\n\n/** The first entry per Item Data, which a clone with that Data stands for. */\nconst entriesByData = (container: Element, role: Container) =>\n\tmemo(container, `data:${role}`, () => {\n\t\tconst byData = new Map<string, Element>();\n\t\tfor (const entry of entriesOf(container, role).entries) {\n\t\t\tconst key = JSON.stringify(readData(entry, \"item\"));\n\t\t\tif (!byData.has(key)) byData.set(key, entry);\n\t\t}\n\t\treturn byData;\n\t});\n\n/** The Item an Item element stands for in `container`: itself, the original of a clone with the same Data, or none. */\nexport const entryOf = (item: Element, container: Element, role: Container) => {\n\tif (entriesOf(container, role).positions.has(item)) return item;\n\tif (!isClone(item, container)) return undefined;\n\treturn entriesByData(container, role).get(\n\t\tJSON.stringify(readData(item, \"item\")),\n\t);\n};\n\n/** Where a paginated List's first Item sits in the whole List, from its `offset` Data. */\nconst offsetOf = (list: Element) => {\n\tconst offset = Number.parseInt(readData(list, \"list\").offset ?? \"\", 10);\n\treturn Number.isNaN(offset) ? 0 : offset;\n};\n\n/** An Item's 0-based position among `container`'s Items, after a List's `offset`; a clone takes its original's. */\nexport const indexIn = (item: Element, container: Element, role: Container) => {\n\tconst entry = entryOf(item, container, role);\n\tif (!entry) return undefined;\n\tconst position = entriesOf(container, role).positions.get(entry)!;\n\treturn role === \"list\" ? offsetOf(container) + position : position;\n};\n\n/** The Items whose nearest Promotion is `promotion`, with their Data and 0-based position in it. */\nexport const promotionItems = (promotion: Element) =>\n\tentriesOf(promotion, \"promotion\").entries.map((item, index) => ({\n\t\t...readData(item, \"item\"),\n\t\tindex,\n\t}));\n\nconst INVALID_KEY = /[\\s:;\\\\]/;\n\nconst escapeValue = (value: string) =>\n\tvalue.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\";\", \"\\\\;\");\n\nconst validKey = (key: string) => {\n\tif (!INVALID_KEY.test(key)) return true;\n\tif (IS_DEVELOPMENT)\n\t\tconsole.warn(\n\t\t\t`[tracking] Annotation key \"${key}\" left out: keys can't contain whitespace, \":\", \";\" or \"\\\\\".`,\n\t\t);\n\treturn false;\n};\n\n/** Data typed by the project's own shape, e.g. a `ProductData` type without an index signature. */\nexport type AnnotationFields<D> = { [K in keyof D]: AnnotationValue };\n\n/**\n * Data as a `data-e-<word>` value, the inverse of the DOM Source's reader,\n * e.g. `<div data-e=\"item\" data-e-item={encodeData({ id, title })} />`.\n * `null` and `undefined` values are left out; values may contain `;` and `\\`.\n */\nexport const encodeData = <D extends AnnotationFields<D>>(data: D) =>\n\tObject.entries<AnnotationValue>(data)\n\t\t.filter(([key, value]) => value != null && validKey(key))\n\t\t.map(([key, value]) => `${key}:${escapeValue(String(value))}`)\n\t\t.join(\";\");\n","import type { Flag } from \"./annotations\";\nimport { hasWord } from \"./annotations\";\n\nexport const AUTO_ATTRIBUTE = \"data-e-auto\";\n\n/** What counts as a link or button click. */\nexport const INTERACTIVE =\n\t'a[href], button, [role=\"button\"], input[type=\"submit\"], input[type=\"button\"]';\n\nexport type AutoKind = \"links\" | \"buttons\" | \"forms\" | \"videos\";\n\n/**\n * The element's own Flag opts it in; otherwise the nearest `data-e-auto` on or above it decides,\n * e.g. `\"links buttons\"`, or `\"none\"` to opt out; otherwise `fallback`.\n */\nexport const isOptedIn = (\n\telement: Element,\n\t{ flag, kind, fallback }: { flag?: Flag; kind: AutoKind; fallback: boolean },\n) => {\n\tif (flag && hasWord(element, flag)) return true;\n\tconst scope = element.closest(`[${AUTO_ATTRIBUTE}]`);\n\tif (!scope) return fallback;\n\treturn (scope.getAttribute(AUTO_ATTRIBUTE) ?? \"\").split(/\\s+/).includes(kind);\n};\n\nexport const readText = (element: Element) =>\n\t(\n\t\telement.getAttribute(\"aria-label\") ??\n\t\t(element instanceof HTMLInputElement\n\t\t\t? element.value\n\t\t\t: element.textContent) ??\n\t\t\"\"\n\t)\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim()\n\t\t.slice(0, 100);\n\n/** Leaves out absent fields, so they don't show up as `undefined` in payloads. */\nexport const compact = <T extends Record<string, unknown>>(data: T) =>\n\tObject.fromEntries(\n\t\tObject.entries(data).filter(\n\t\t\t([, value]) => value !== undefined && value !== \"\",\n\t\t),\n\t) as T;\n"]}
@@ -1,6 +1,6 @@
1
- import { C as Catalog, a as EventName, b as EventData } from './types-DfPz7mBl.js';
1
+ import { C as Catalog, E as EventName, a as EventData } from './types-CZEg03xW.js';
2
2
 
3
- /** Keys a type names, without index signatures such as `data-e-data` fields. */
3
+ /** Keys a type names, without index signatures such as Annotation Data. */
4
4
  type KnownKeys<T> = keyof {
5
5
  [K in keyof T as string extends K ? never : K]: T[K];
6
6
  };