@decocms/blocks 8.16.1 → 8.18.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 (112) hide show
  1. package/dist/v8/analytics/client.d.ts +48 -0
  2. package/dist/v8/analytics/client.d.ts.map +1 -0
  3. package/dist/v8/analytics/client.js +71 -0
  4. package/dist/v8/analytics/client.js.map +1 -0
  5. package/dist/v8/analytics/runtime/modules/click.d.ts +2 -0
  6. package/dist/v8/analytics/runtime/modules/click.d.ts.map +1 -0
  7. package/dist/v8/analytics/runtime/modules/click.js +48 -0
  8. package/dist/v8/analytics/runtime/modules/click.js.map +1 -0
  9. package/dist/v8/analytics/runtime/modules/commerce.d.ts +2 -0
  10. package/dist/v8/analytics/runtime/modules/commerce.d.ts.map +1 -0
  11. package/dist/v8/analytics/runtime/modules/commerce.js +41 -0
  12. package/dist/v8/analytics/runtime/modules/commerce.js.map +1 -0
  13. package/dist/v8/analytics/runtime/modules/consent.d.ts +33 -0
  14. package/dist/v8/analytics/runtime/modules/consent.d.ts.map +1 -0
  15. package/dist/v8/analytics/runtime/modules/consent.js +154 -0
  16. package/dist/v8/analytics/runtime/modules/consent.js.map +1 -0
  17. package/dist/v8/analytics/runtime/modules/deco.d.ts +2 -0
  18. package/dist/v8/analytics/runtime/modules/deco.d.ts.map +1 -0
  19. package/dist/v8/analytics/runtime/modules/deco.js +209 -0
  20. package/dist/v8/analytics/runtime/modules/deco.js.map +1 -0
  21. package/dist/v8/analytics/runtime/modules/engagement.d.ts +2 -0
  22. package/dist/v8/analytics/runtime/modules/engagement.d.ts.map +1 -0
  23. package/dist/v8/analytics/runtime/modules/engagement.js +128 -0
  24. package/dist/v8/analytics/runtime/modules/engagement.js.map +1 -0
  25. package/dist/v8/analytics/runtime/modules/errors.d.ts +2 -0
  26. package/dist/v8/analytics/runtime/modules/errors.d.ts.map +1 -0
  27. package/dist/v8/analytics/runtime/modules/errors.js +167 -0
  28. package/dist/v8/analytics/runtime/modules/errors.js.map +1 -0
  29. package/dist/v8/analytics/runtime/modules/heatmap.d.ts +2 -0
  30. package/dist/v8/analytics/runtime/modules/heatmap.d.ts.map +1 -0
  31. package/dist/v8/analytics/runtime/modules/heatmap.js +316 -0
  32. package/dist/v8/analytics/runtime/modules/heatmap.js.map +1 -0
  33. package/dist/v8/analytics/runtime/modules/vitals.d.ts +2 -0
  34. package/dist/v8/analytics/runtime/modules/vitals.d.ts.map +1 -0
  35. package/dist/v8/analytics/runtime/modules/vitals.js +119 -0
  36. package/dist/v8/analytics/runtime/modules/vitals.js.map +1 -0
  37. package/dist/v8/analytics/runtime/src/guards.d.ts +10 -0
  38. package/dist/v8/analytics/runtime/src/guards.d.ts.map +1 -0
  39. package/dist/v8/analytics/runtime/src/guards.js +70 -0
  40. package/dist/v8/analytics/runtime/src/guards.js.map +1 -0
  41. package/dist/v8/analytics/runtime/src/index.d.ts +2 -0
  42. package/dist/v8/analytics/runtime/src/index.d.ts.map +1 -0
  43. package/dist/v8/analytics/runtime/src/index.js +562 -0
  44. package/dist/v8/analytics/runtime/src/index.js.map +1 -0
  45. package/dist/v8/analytics/runtime/src/queue.d.ts +15 -0
  46. package/dist/v8/analytics/runtime/src/queue.d.ts.map +1 -0
  47. package/dist/v8/analytics/runtime/src/queue.js +36 -0
  48. package/dist/v8/analytics/runtime/src/queue.js.map +1 -0
  49. package/dist/v8/analytics/runtime/src/trim.d.ts +13 -0
  50. package/dist/v8/analytics/runtime/src/trim.d.ts.map +1 -0
  51. package/dist/v8/analytics/runtime/src/trim.js +38 -0
  52. package/dist/v8/analytics/runtime/src/trim.js.map +1 -0
  53. package/dist/v8/analytics/runtime/view/heat-core.d.ts +69 -0
  54. package/dist/v8/analytics/runtime/view/heat-core.d.ts.map +1 -0
  55. package/dist/v8/analytics/runtime/view/heat-core.js +314 -0
  56. package/dist/v8/analytics/runtime/view/heat-core.js.map +1 -0
  57. package/dist/v8/analytics/runtime/view/view.d.ts +51 -0
  58. package/dist/v8/analytics/runtime/view/view.d.ts.map +1 -0
  59. package/dist/v8/analytics/runtime/view/view.js +525 -0
  60. package/dist/v8/analytics/runtime/view/view.js.map +1 -0
  61. package/dist/v8/analytics/shared/anchor.d.ts +71 -0
  62. package/dist/v8/analytics/shared/anchor.d.ts.map +1 -0
  63. package/dist/v8/analytics/shared/anchor.js +155 -0
  64. package/dist/v8/analytics/shared/anchor.js.map +1 -0
  65. package/dist/v8/analytics/shared/contract.d.ts +294 -0
  66. package/dist/v8/analytics/shared/contract.d.ts.map +1 -0
  67. package/dist/v8/analytics/shared/contract.js +652 -0
  68. package/dist/v8/analytics/shared/contract.js.map +1 -0
  69. package/dist/v8/builtins/data.d.ts +20 -6
  70. package/dist/v8/builtins/data.d.ts.map +1 -1
  71. package/dist/v8/builtins/data.js +33 -8
  72. package/dist/v8/builtins/data.js.map +1 -1
  73. package/dist/v8/cms.js +2 -2
  74. package/dist/v8/cms.js.map +1 -1
  75. package/dist/v8/settings.d.ts +28 -9
  76. package/dist/v8/settings.d.ts.map +1 -1
  77. package/dist/v8/settings.js +6 -10
  78. package/dist/v8/settings.js.map +1 -1
  79. package/dist/v8/telemetry.d.ts +13 -11
  80. package/dist/v8/telemetry.d.ts.map +1 -1
  81. package/dist/v8/telemetry.js +27 -17
  82. package/dist/v8/telemetry.js.map +1 -1
  83. package/dist/v8/types.d.ts +7 -3
  84. package/dist/v8/types.d.ts.map +1 -1
  85. package/package.json +6 -1
  86. package/skills/deco-storefront-performance/references/render-location.md +3 -2
  87. package/skills/deco-v7-to-v8-migration/references/telemetry.md +1 -1
  88. package/skills/deco-v7-to-v8-migration/scripts/siteSettings.ts +1 -1
  89. package/src/v8/analytics/client.ts +110 -0
  90. package/src/v8/analytics/runtime/globals.d.ts +36 -0
  91. package/src/v8/analytics/runtime/modules/click.ts +54 -0
  92. package/src/v8/analytics/runtime/modules/commerce.ts +73 -0
  93. package/src/v8/analytics/runtime/modules/consent.ts +150 -0
  94. package/src/v8/analytics/runtime/modules/deco.ts +207 -0
  95. package/src/v8/analytics/runtime/modules/engagement.ts +140 -0
  96. package/src/v8/analytics/runtime/modules/errors.ts +217 -0
  97. package/src/v8/analytics/runtime/modules/heatmap.ts +360 -0
  98. package/src/v8/analytics/runtime/modules/vitals.ts +128 -0
  99. package/src/v8/analytics/runtime/src/guards.ts +70 -0
  100. package/src/v8/analytics/runtime/src/index.ts +606 -0
  101. package/src/v8/analytics/runtime/src/queue.ts +40 -0
  102. package/src/v8/analytics/runtime/src/trim.ts +39 -0
  103. package/src/v8/analytics/runtime/view/heat-core.ts +335 -0
  104. package/src/v8/analytics/runtime/view/view.ts +596 -0
  105. package/src/v8/analytics/shared/anchor.ts +171 -0
  106. package/src/v8/analytics/shared/contract.ts +691 -0
  107. package/src/v8/analytics/tsconfig.json +14 -0
  108. package/src/v8/builtins/data.ts +44 -9
  109. package/src/v8/cms.ts +4 -4
  110. package/src/v8/settings.ts +13 -16
  111. package/src/v8/telemetry.ts +33 -29
  112. package/src/v8/types.ts +7 -3
@@ -0,0 +1,207 @@
1
+ /** Adapter for deco storefronts.
2
+ *
3
+ * Two jobs, both about not asking a site to instrument twice: read the experiment
4
+ * assignment the origin already made, and forward the analytics events the framework
5
+ * already dispatches.
6
+ *
7
+ * It reads `deco_segment` rather than the event bus for flags because the cookie is set
8
+ * by the origin before any script runs, so the assignment is on the very first event —
9
+ * including the pageview. Waiting for the bus would attribute the landing pageview to no
10
+ * variant, which is the one event an experiment most needs attributed.
11
+ */
12
+ import { LIMITS, STOREFRONT_EXP } from "../../shared/contract.ts";
13
+
14
+ type Props = Record<string, string | number | boolean>;
15
+
16
+ window.__dqRegister?.((enqueue, api: Record<string, unknown>) => {
17
+ const setExperiment = api.setExperiment as ((k: string, v: string) => void) | undefined;
18
+
19
+ // ---- assignment, from the cookie the origin already set ---------------------
20
+ //
21
+ // deco_segment is base64 of URI-encoded JSON: { active: string[], inactiveDrawn: [] }.
22
+ // It carries flag NAMES and nothing else — see deco/runtime/middleware.ts, which writes
23
+ // it from `flag.value` as a boolean.
24
+ //
25
+ // So both lists matter. `inactiveDrawn` means "evaluated for this visitor and came out
26
+ // false", which IS the control group: recording only the active flags would leave an
27
+ // experiment with a treatment arm and no baseline to compare it against, and a
28
+ // conversion rate with nothing to compare it to is not a result.
29
+ try {
30
+ const raw = document.cookie
31
+ .split(";")
32
+ .map((c) => c.trim())
33
+ .find((c) => c.startsWith("deco_segment="));
34
+ if (raw) {
35
+ const json = JSON.parse(decodeURIComponent(atob(raw.slice("deco_segment=".length))));
36
+ const set = (name: string, variant: string) => {
37
+ // Experiment keys allow hyphens; anything else the Worker normalises and flags.
38
+ if (name && name.length <= LIMITS.expKeyLen) setExperiment?.(name, variant);
39
+ };
40
+ for (const name of json.active ?? []) set(String(name), "on");
41
+ for (const name of json.inactiveDrawn ?? []) set(String(name), "off");
42
+ }
43
+ } catch {
44
+ // A malformed cookie is a site problem, not a reason to stop collecting.
45
+ }
46
+
47
+ // ---- the side of a Fresh x TanStack split ------------------------------------
48
+ //
49
+ // `withABTesting` keeps the side in `_deco_bucket` as `<side>:<percent>` (`worker:50`), set at
50
+ // the edge before the document reaches the browser, so it too is on the first event. Recorded
51
+ // as the `storefront` experiment with the names the store Worker stamps on what it sends
52
+ // through `EdgeIngest` -- the two halves of the funnel only group together if they agree, and
53
+ // `STOREFRONT_EXP` is where they do. An unknown side is skipped rather than recorded raw: a
54
+ // third variant nobody emits at the edge would be a funnel with no ruler.
55
+ try {
56
+ const raw = document.cookie
57
+ .split(";")
58
+ .map((c) => c.trim())
59
+ .find((c) => c.startsWith(`${STOREFRONT_EXP.cookie}=`));
60
+ const side = raw
61
+ ? decodeURIComponent(raw.slice(STOREFRONT_EXP.cookie.length + 1)).split(":")[0]
62
+ : "";
63
+ const variant = STOREFRONT_EXP.variants[side];
64
+ if (variant) setExperiment?.(STOREFRONT_EXP.name, variant);
65
+ } catch {
66
+ // Same as above: a bad cookie costs the arm, never the collection.
67
+ }
68
+
69
+ // ---- events, from the bus the framework already has -------------------------
70
+ //
71
+ // deco dispatches commerce events in the Google Analytics shape. Mapped to our names
72
+ // rather than forwarded verbatim: `add_to_cart` here has a typed value column, and
73
+ // passing GA's nested `ecommerce.items` through as props would put money in a string.
74
+ const NAME_MAP: Record<string, string> = {
75
+ view_item: "view_item",
76
+ view_item_list: "view_item_list",
77
+ select_item: "select_item",
78
+ add_to_cart: "add_to_cart",
79
+ remove_from_cart: "remove_from_cart",
80
+ begin_checkout: "begin_checkout",
81
+ purchase: "purchase",
82
+ search: "$search",
83
+ view_promotion: "view_promotion",
84
+ select_promotion: "select_promotion",
85
+ };
86
+
87
+ /** A storefront can hand the bus its products in one of two shapes, and both are deco's.
88
+ *
89
+ * `items` is the GA4 shape `mapProductToAnalyticsItem` builds. `products` is the schema.org
90
+ * `Product` itself, which the `DECO` adapter of the Azzas tracking SDK expects and builds the
91
+ * GA4 payload from on its own -- the FARM sends every commerce event that way. Reading only
92
+ * `items` stored 94k `add_to_cart` from the FARM in five days with not one item id or value:
93
+ * the event names arrived, so every panel looked instrumented, and nothing said which product.
94
+ *
95
+ * The id follows `mapProductToAnalyticsItem`: `item_id` is `productID` (the SKU), so a site
96
+ * sending either shape lands the same id in `item_ids`. `sku` is the fallback because the
97
+ * lighter Product the FARM puts on shelf cards carries `sku` and no `productID`. */
98
+ const productId = (pr: any) => String(pr?.productID ?? pr?.sku ?? "");
99
+
100
+ /** Price of one unit off a schema.org `AggregateOffer`. `lowPrice` is the price the shopper
101
+ * sees; the first offer is the fallback for the trimmed Product on shelf cards. */
102
+ const unitPrice = (pr: any): number | undefined => {
103
+ const o = pr?.offers;
104
+ const v = o?.lowPrice ?? o?.offers?.[0]?.price;
105
+ return typeof v === "number" ? v : undefined;
106
+ };
107
+
108
+ /** Events where `value` means money that moved. A `view_item_list` of 40 cards has no value:
109
+ * summing the shelf would put a number in a revenue column that no shopper ever paid. */
110
+ const VALUED = new Set(["add_to_cart", "remove_from_cart", "begin_checkout", "purchase"]);
111
+
112
+ const money = (name: string, p: any) => {
113
+ const items = p?.items ?? p?.ecommerce?.items;
114
+ const products = Array.isArray(items) ? undefined : p?.products;
115
+ const out: Record<string, unknown> = {};
116
+ if (typeof p?.value === "number") out.value = p.value;
117
+ if (typeof p?.currency === "string") out.currency = p.currency;
118
+ if (Array.isArray(items)) {
119
+ out.items_count = items.length;
120
+ out.item_ids = items
121
+ .map((i: any) => String(i?.item_id ?? i?.id ?? ""))
122
+ .filter(Boolean)
123
+ .slice(0, LIMITS.itemIds);
124
+ } else if (Array.isArray(products)) {
125
+ out.items_count = products.length;
126
+ out.item_ids = products.map(productId).filter(Boolean).slice(0, LIMITS.itemIds);
127
+ // Only when the site did not say it, and only on events where a value is money.
128
+ if (out.value === undefined && VALUED.has(name)) {
129
+ let sum = 0;
130
+ let priced = 0;
131
+ for (const pr of products) {
132
+ const u = unitPrice(pr);
133
+ if (u === undefined) continue;
134
+ sum += u * (typeof pr?.quantity === "number" && pr.quantity > 0 ? pr.quantity : 1);
135
+ priced++;
136
+ }
137
+ // All or nothing: a cart of three with one unpriced item is not worth the two we
138
+ // could price, and a partial sum would look exactly like a real one.
139
+ if (priced && priced === products.length) out.value = Math.round(sum * 100) / 100;
140
+ }
141
+ const cur = products[0]?.offers?.priceCurrency;
142
+ if (out.currency === undefined && typeof cur === "string" && out.value !== undefined)
143
+ out.currency = cur;
144
+ }
145
+ if (typeof p?.transaction_id === "string") out.transaction_id = p.transaction_id;
146
+ return out;
147
+ };
148
+
149
+ /** Subscribe WHENEVER the bus shows up, not only if it is already there.
150
+ *
151
+ * This was `window?.DECO?.events?.subscribe?.(…)` — one attempt, optional-chained, no retry —
152
+ * and it lost every commerce event on a real site. React hoists `<script async>` into `<head>`
153
+ * regardless of where the component sits in the tree: measured on igor-tanstack.deco.site,
154
+ * our tag is at byte 200 and the inline block that defines `DECO.events` is at byte 1905, in
155
+ * the body. So this ran first, found nothing, and never tried again. Two `view_promotion`
156
+ * events fired and went nowhere, with no error and a page that looked perfectly instrumented.
157
+ *
158
+ * NOTHING IS LOST BY ARRIVING LATE, which is what makes polling the right answer rather than
159
+ * a patch: the bus keeps a `_q` and `subscribe` replays it to a new subscriber. So the only
160
+ * requirement is to subscribe eventually.
161
+ *
162
+ * Bounded at ten seconds. A page that has not defined the bus by then does not have one —
163
+ * a site without the deco runtime is a normal thing, and an interval left running forever
164
+ * would be this module's parting gift to every such page.
165
+ */
166
+ const onBus = (fn: (event: any) => void) => {
167
+ const w = (globalThis as any).window;
168
+ const now = w?.DECO?.events;
169
+ if (typeof now?.subscribe === "function") {
170
+ now.subscribe(fn);
171
+ return;
172
+ }
173
+ let tries = 0;
174
+ const iv = setInterval(() => {
175
+ const bus = (globalThis as any).window?.DECO?.events;
176
+ if (typeof bus?.subscribe === "function") {
177
+ clearInterval(iv);
178
+ bus.subscribe(fn);
179
+ return;
180
+ }
181
+ if (++tries >= 100) clearInterval(iv);
182
+ }, 100);
183
+ };
184
+
185
+ onBus((event: any) => {
186
+ if (!event?.name) return;
187
+
188
+ // The bus replays a synthetic "deco" event on subscribe, carrying the same flags the
189
+ // cookie already gave us. Ignored rather than mapped: it is not something a visitor
190
+ // did, and turning it into an event would put a row in the table for every page load
191
+ // that means nothing.
192
+ if (event.name === "deco") return;
193
+
194
+ const mapped = NAME_MAP[event.name];
195
+ if (!mapped) return; // unknown bus events are not forwarded blind
196
+
197
+ const p = event.params ?? {};
198
+ const props: Props = {};
199
+ // The schema.org shape carries the list on the product, not on the event.
200
+ const list = p.item_list_name ?? p.products?.[0]?.item_list_name;
201
+ if (typeof list === "string") props.list = list.slice(0, 200);
202
+ if (typeof p.search_term === "string")
203
+ props.term = p.search_term.trim().toLowerCase().slice(0, 200);
204
+
205
+ enqueue(mapped, props, money(event.name, p));
206
+ });
207
+ });
@@ -0,0 +1,140 @@
1
+ /** Enhanced measurement: the four things every site wants counted and nobody wants to
2
+ * instrument by hand — how far people scroll, which links take them away, what they
3
+ * download, and what they search for.
4
+ *
5
+ * The reason this is a MODULE and not core: it is automatic, and automatic collection is
6
+ * where an analytics SDK gets expensive without anyone deciding to spend. A blog does not
7
+ * need outbound-click tracking and should not download the code for it.
8
+ *
9
+ * Every counter here is bounded on purpose. GA4 fires a scroll event at each of four
10
+ * thresholds, which is four events per page for one number; it sends an outbound event
11
+ * per click including the same link clicked twice; and none of it is capped. At 400M
12
+ * events a month those choices are the difference between a bill you planned and one you
13
+ * did not.
14
+ */
15
+ import { LIMITS } from "../../shared/contract.ts";
16
+
17
+ window.__dqRegister?.((enqueue, _api: Record<string, unknown>, onFinal, onRoute) => {
18
+ // ---- scroll ---------------------------------------------------------------
19
+ // One event per page load carrying the DEEPEST point reached, not one per threshold
20
+ // crossed. Four events to communicate a single number is the shape GA4 chose, and the
21
+ // extra three carry no information the fourth does not.
22
+ let deepest = 0;
23
+ let scrollSent = false;
24
+
25
+ const depth = () => {
26
+ const doc = document.documentElement;
27
+ const viewport = window.innerHeight || doc.clientHeight || 0;
28
+ const total = Math.max(doc.scrollHeight, document.body?.scrollHeight ?? 0);
29
+ if (total <= viewport) return 100; // nothing to scroll: the page was fully seen
30
+ const seen = (window.scrollY || doc.scrollTop || 0) + viewport;
31
+ return Math.max(0, Math.min(100, Math.round((seen / total) * 100)));
32
+ };
33
+
34
+ // Passive: a scroll listener that can block scrolling is a listener that made the site
35
+ // worse to use, which is the one thing analytics must never do.
36
+ addEventListener(
37
+ "scroll",
38
+ () => {
39
+ const d = depth();
40
+ if (d > deepest) deepest = d;
41
+ },
42
+ { passive: true },
43
+ );
44
+
45
+ // `prev` is set when an SPA route closes the view: the path it was measured on goes with it,
46
+ // and the live document is already the next route's, so only what was tracked counts.
47
+ function sendScroll(prev?: string) {
48
+ if (scrollSent) return;
49
+ const d = prev ? deepest : Math.max(deepest, depth());
50
+ // Rounded to a bucket. The difference between 61% and 62% is noise, and storing it
51
+ // raw would put a hundred distinct values into a LowCardinality dictionary for no
52
+ // question anyone asks.
53
+ const bucket = Math.min(100, Math.round(d / 25) * 25);
54
+ scrollSent = true;
55
+ enqueue("$scroll", { depth: String(bucket) }, prev ? { path: prev } : undefined);
56
+ }
57
+
58
+ // ---- outbound links and downloads -----------------------------------------
59
+ const DOWNLOAD_EXT =
60
+ /\.(pdf|zip|rar|7z|gz|tar|csv|xlsx?|docx?|pptx?|txt|dmg|exe|pkg|apk|mp3|mp4|mov|avi|wav)($|\?)/i;
61
+
62
+ // Same link clicked twice in one page load is one fact, not two. Rage-clicking a slow
63
+ // link is the common case and it is exactly the case that would inflate the number.
64
+ const clicked = new Set<string>();
65
+ const MAX_CLICKS = 20;
66
+
67
+ addEventListener(
68
+ "click",
69
+ (e) => {
70
+ const el = (e.target as Element | null)?.closest?.("a[href]") as HTMLAnchorElement | null;
71
+ if (!el) return;
72
+
73
+ const href = el.href;
74
+ if (!href || href.startsWith("javascript:")) return;
75
+
76
+ let url: URL;
77
+ try {
78
+ url = new URL(href, location.href);
79
+ } catch {
80
+ return;
81
+ }
82
+ if (url.protocol !== "http:" && url.protocol !== "https:") return;
83
+
84
+ if (clicked.size >= MAX_CLICKS || clicked.has(href)) return;
85
+
86
+ const isDownload =
87
+ el.hasAttribute("download") || DOWNLOAD_EXT.test(url.pathname + url.search);
88
+ const isOutbound = url.host !== location.host;
89
+ if (!isDownload && !isOutbound) return;
90
+
91
+ clicked.add(href);
92
+ // The URL is the whole point of the event, so it gets the path budget rather than the
93
+ // value budget — a truncated destination answers nothing.
94
+ const target = (url.host + url.pathname).slice(0, LIMITS.pathLen);
95
+ enqueue(isDownload ? "$download" : "$outbound", { target });
96
+ },
97
+ { capture: true, passive: true },
98
+ );
99
+
100
+ // ---- site search ----------------------------------------------------------
101
+ // A closed list of parameter names, for the same reason the campaign vocabulary is
102
+ // closed: an open one lets any query string mint a dimension value. These are the ones
103
+ // that actually appear on storefronts.
104
+ const SEARCH_PARAMS = ["q", "s", "search", "query", "termo", "busca", "keyword"];
105
+
106
+ (function searchOnce() {
107
+ try {
108
+ const qs = new URLSearchParams(location.search);
109
+ for (const key of SEARCH_PARAMS) {
110
+ const term = qs.get(key);
111
+ if (!term) continue;
112
+ enqueue("$search", {
113
+ // Lowercased and trimmed so "Tenis", "tenis " and "tenis" are one term rather
114
+ // than three rows in a top-searches report.
115
+ term: term.trim().toLowerCase().slice(0, LIMITS.valueLen),
116
+ param: key,
117
+ });
118
+ return;
119
+ }
120
+ } catch {
121
+ /* a malformed query string is not worth breaking collection over */
122
+ }
123
+ })();
124
+
125
+ // ---- flush ----------------------------------------------------------------
126
+ // Scroll depth is only known when the visitor leaves. Core runs this immediately
127
+ // before its own last flush, so the event rides out with everything else instead of
128
+ // buying a request of its own — three modules each flushing cost three requests for
129
+ // what is one visit's worth of data.
130
+ onFinal(() => sendScroll());
131
+ // One `$scroll` per VIEW. Before this, an SPA's route 2 inherited route 1's depth and the
132
+ // whole visit sent a single event at the end, attributed to whichever path was last. A
133
+ // query-string change on the same path is the same view, as it is for core's pageview.
134
+ onRoute?.((prev) => {
135
+ if (prev === location.pathname) return;
136
+ sendScroll(prev);
137
+ deepest = 0;
138
+ scrollSent = false;
139
+ });
140
+ });
@@ -0,0 +1,217 @@
1
+ /** Automatic error capture.
2
+ *
3
+ * `captureException` in core only ever sees what a site already wrapped in try/catch,
4
+ * which is the minority of what breaks. This module attaches the two listeners that
5
+ * see the rest, and does the two things that separate an error product from an error
6
+ * log: it gives every error a stable fingerprint so repeats group, and it collapses a
7
+ * repeating error into one event with a count instead of one event per occurrence.
8
+ *
9
+ * That second part is not an optimisation. A render loop throwing on every frame is
10
+ * the normal shape of a bad deploy; without collapsing, one visitor's broken tab sends
11
+ * thousands of events, the queue drops the rest of their session, and the bill and the
12
+ * data are both wrong.
13
+ */
14
+ import { LIMITS } from "../../shared/contract.ts";
15
+
16
+ type Props = Record<string, string | number | boolean>;
17
+
18
+ window.__dqRegister?.((enqueue, api: Record<string, unknown>, onFinal) => {
19
+ // Volatile parts of a message are what stop repeats grouping: ids, timestamps, URLs
20
+ // and offsets differ per occurrence while the fault is identical. Strip them before
21
+ // hashing, keep the original message on the event as a sample.
22
+ const stable = (msg: string) =>
23
+ msg
24
+ .replace(/https?:\/\/[^\s)'"]+/g, "<url>")
25
+ .replace(/\b[0-9a-f]{8,}\b/gi, "<hex>")
26
+ .replace(/\b\d[\d.,]*\b/g, "<n>")
27
+ .replace(/['"][^'"]{0,80}['"]/g, "<str>")
28
+ .slice(0, 200);
29
+
30
+ // A file path is the same fault whether it arrives absolute, with a cache-busting
31
+ // query, or with a hash fragment.
32
+ const cleanFile = (f: string) => {
33
+ if (!f) return "";
34
+ try {
35
+ const u = new URL(f, location.href);
36
+ return (u.origin === location.origin ? "" : u.origin) + u.pathname;
37
+ } catch {
38
+ return f.split("?")[0].split("#")[0];
39
+ }
40
+ };
41
+
42
+ // A URL in a message or a stack keeps its origin and path and loses its query and fragment:
43
+ // `fetch failed for /api/cart?email=...&token=...` is the fault, the values are a visitor's.
44
+ // A frame's trailing `:line:col` survives, since it is what points at the fault.
45
+ const noQuery = (s: string) =>
46
+ s.replace(
47
+ /([a-z][\w+.-]*:\/\/[^\s?#()'"]*)[?#][^\s()'"]*?(?=:\d+:\d+(?![^\s)])|[\s()'"]|$)/gi,
48
+ "$1",
49
+ );
50
+
51
+ // FNV-1a with a murmur3 finaliser. The finaliser matters: without it the low bits are
52
+ // just an XOR of the input's low bits, and near-identical inputs land in adjacent
53
+ // buckets rather than spread.
54
+ const fingerprint = (parts: string[]) => {
55
+ let h = 2166136261;
56
+ const s = parts.join("|");
57
+ for (let i = 0; i < s.length; i++) {
58
+ h ^= s.charCodeAt(i);
59
+ h = Math.imul(h, 16777619);
60
+ }
61
+ h = Math.imul(h ^ (h >>> 16), 2246822507);
62
+ h = Math.imul(h ^ (h >>> 13), 3266489909);
63
+ return ((h ^ (h >>> 16)) >>> 0).toString(36).padStart(7, "0");
64
+ };
65
+
66
+ // Seen this page load: fingerprint -> how many times since the last send. A repeating
67
+ // error increments rather than enqueues.
68
+ const seen = new Map<string, { n: number; sent: boolean }>();
69
+ // A hard ceiling on DISTINCT errors per page load. A loop that generates a new
70
+ // fingerprint each time (a message with an unstrippable varying part) would otherwise
71
+ // defeat the collapsing entirely, which is the failure mode this guard exists for.
72
+ const MAX_DISTINCT = 20;
73
+
74
+ // OURS = this origin, or a host the site declared as its own in `errorHosts` (served as `er`;
75
+ // a separate asset CDN, say). Everything else on a storefront is a vendor: a GTM tag, a pixel,
76
+ // a chat widget. Measured on FILA, New Balance and Umbro, 96-100% of `$error` was a
77
+ // cross-origin ResourceError -- a dead tag, a 403'd account, an ad blocker -- none of it
78
+ // actionable here, and between them 18-26% of every event those sites sent.
79
+ const ours = (u: string) => {
80
+ try {
81
+ const x = new URL(u, location.href);
82
+ return (
83
+ x.origin === location.origin || ((api.er as string[] | undefined) ?? []).includes(x.host)
84
+ );
85
+ } catch {
86
+ return false;
87
+ }
88
+ };
89
+
90
+ function report(
91
+ type: string,
92
+ message: string,
93
+ file: string,
94
+ line: number,
95
+ stack: string,
96
+ props?: Props,
97
+ ) {
98
+ // Read by the heatmap module: a click followed by an error within a second is an
99
+ // "error click". On the performance timeline, which is what the click is timed on.
100
+ // Only OUR faults flag it. Vendor tags boot on the storefront's first interaction, so their
101
+ // failures land right after the first click -- every header "error click" reproduced on
102
+ // FILA, New Balance and Umbro was one. The source is the file, else the first stack frame
103
+ // (a URL followed by :line:col, which a URL quoted in the message is not). "Script error."
104
+ // and a fault with no source cannot be attributed, so they do not flag.
105
+ const src = file || (/([a-z][\w+.-]*:\/\/[^\s()]+):\d+:\d+/i.exec(String(stack))?.[1] ?? "");
106
+ // Not the site's code at all: a script the BROWSER injected -- an in-app browser's bridge
107
+ // (`iabjs://`, Instagram/Facebook), an extension (`chrome-extension://`, `moz-extension://`,
108
+ // `safari-web-extension://`). Nothing the site ships can fix it, and it was the largest single
109
+ // fault on two storefronts after #27 (newbalance: 130 an hour, "Error invoking postMessage:
110
+ // Java object is gone").
111
+ if (/^[a-z][\w+.-]*:\/\//i.test(src) && !/^https?:/i.test(src)) return;
112
+ if (src && message !== "Script error." && ours(src))
113
+ (window as any).__dqLastErrorTs = performance.now();
114
+ const fp = fingerprint([type, stable(message), cleanFile(file), String(line)]);
115
+ const prev = seen.get(fp);
116
+ if (prev) {
117
+ prev.n++;
118
+ return;
119
+ } // already reported this page load
120
+ if (seen.size >= MAX_DISTINCT) return; // storm guard
121
+ seen.set(fp, { n: 1, sent: true });
122
+
123
+ enqueue("$error", props, {
124
+ error_type: (type || "Error").slice(0, 40),
125
+ error_fingerprint: fp,
126
+ error_message: noQuery(String(message ?? "")).slice(0, LIMITS.valueLen),
127
+ error_file: cleanFile(file).slice(0, LIMITS.pathLen),
128
+ error_line: Number(line) || 0,
129
+ error_count: 1,
130
+ error_stack: noQuery(String(stack ?? "")).slice(0, LIMITS.errorEventBytes),
131
+ });
132
+ }
133
+
134
+ // Repeats accumulated after the first report are sent once, at the end, as a single
135
+ // event carrying the count. One event per thousand occurrences, and the thousand is
136
+ // still visible.
137
+ function flushRepeats() {
138
+ let any = false;
139
+ for (const [fp, rec] of seen) {
140
+ if (rec.n <= 1) continue;
141
+ enqueue("$error", undefined, {
142
+ error_fingerprint: fp,
143
+ error_type: "repeat",
144
+ error_count: rec.n - 1,
145
+ error_message: "",
146
+ });
147
+ rec.n = 1;
148
+ any = true;
149
+ }
150
+ void any;
151
+ }
152
+ // Ordering, not a second request: core runs this BEFORE its final flush, so the
153
+ // repeats are in the queue when that flush happens. Enqueueing after it used to
154
+ // report eight occurrences as one; flushing again to compensate cost a request.
155
+ onFinal(flushRepeats);
156
+
157
+ addEventListener(
158
+ "error",
159
+ (e: any) => {
160
+ // A failed <img>/<script>/<link> also fires "error" on window, with no `error`
161
+ // object and the element as target. It is a real fault worth recording, but it is
162
+ // not an exception and must not be reported as one.
163
+ if (!e?.error && e?.target && e.target !== window) {
164
+ const el = e.target;
165
+ // `.href` on an SVG element is an SVGAnimatedString, NOT a string — so a failing
166
+ // `<use href="/sprite.svg#icon">` used to be reported as
167
+ // `/[object%20SVGAnimatedString]`, which names no resource and masks which sprite
168
+ // actually failed (seen live on a storefront whose icons are one `<use>` sprite).
169
+ // `.src` has the same shape on SVGScriptElement.
170
+ const raw = el.src || el.href || "";
171
+ const src: string = typeof raw === "string" ? raw : (raw.baseVal ?? "");
172
+ // A vendor's asset failing is the vendor's problem (see `ours`): dropped, not reported.
173
+ // Ours -- our chunks, our sprite, a declared `errorHosts` CDN -- is a real fault.
174
+ if (!src || !ours(src)) return;
175
+ report(
176
+ "ResourceError",
177
+ `failed to load ${el.tagName?.toLowerCase?.() ?? "resource"}`,
178
+ src,
179
+ 0,
180
+ "",
181
+ );
182
+ return;
183
+ }
184
+ report(
185
+ e?.error?.name ?? "Error",
186
+ e?.message ?? String(e?.error ?? "error"),
187
+ e?.filename ?? "",
188
+ e?.lineno ?? 0,
189
+ e?.error?.stack ?? "",
190
+ );
191
+ },
192
+ true,
193
+ ); // capture phase: resource errors do not bubble
194
+
195
+ addEventListener("unhandledrejection", (e: any) => {
196
+ const r = e?.reason;
197
+ report(
198
+ r?.name ?? "UnhandledRejection",
199
+ r?.message ?? String(r ?? "rejected"),
200
+ r?.fileName ?? "",
201
+ r?.lineNumber ?? 0,
202
+ r?.stack ?? "",
203
+ );
204
+ });
205
+
206
+ // Same fingerprinting for the manual path, so an error caught by the site and the
207
+ // same error escaping uncaught land in one group rather than two.
208
+ api.captureException = (err: any, props?: Props) =>
209
+ report(
210
+ err?.name ?? "Error",
211
+ err?.message ?? String(err),
212
+ err?.fileName ?? "",
213
+ err?.lineNumber ?? 0,
214
+ err?.stack ?? "",
215
+ props,
216
+ );
217
+ });