@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,360 @@
1
+ /** Heatmaps: where people click, how far they scroll and where their attention goes, as ONE
2
+ * `$heatmap` event per page view.
3
+ *
4
+ * Each view (a document load, or an SPA route change to a new path) gets a random `view_id`, kept
5
+ * in memory only, so this works at tier 0 with no storage. Every emission is CUMULATIVE for its
6
+ * view -- on `visibilitychange: hidden`, on `pagehide` and on route change -- and the warehouse
7
+ * keeps the last one per view (`argMax(..., ts)`). That makes a lost early beacon harmless and a
8
+ * page that is hidden and shown five times one view, not five.
9
+ *
10
+ * It rides core's flushes, so it never spends a request of its own.
11
+ *
12
+ * Costs on the visitor's main thread, all bounded:
13
+ * - click (capture, passive): one getBoundingClientRect on the anchor, a parent walk with
14
+ * getComputedStyle for the fixed/sticky flag, sibling counts. Read in the CAPTURE phase,
15
+ * before the site's own handlers have mutated anything, so the layout read finds a clean
16
+ * layout instead of forcing one. No serialisation.
17
+ * - scroll (passive): at most one rAF per frame; `scrollHeight` at most once a second.
18
+ * - sections: one IntersectionObserver, callbacks off the input path.
19
+ * Every handler is wrapped: a failure here means "heatmap stopped", never "the page broke".
20
+ *
21
+ * Never sent: text, input values, href/src, classes, coordinates of untrusted events.
22
+ */
23
+ import { anchorOf, rootOf, pathOf, cyrb53, fsRootName } from "../../shared/anchor.ts";
24
+
25
+ window.__dqRegister?.((enqueue, cfg: Record<string, any>, onFinal, onRoute) => {
26
+ const w = window as any,
27
+ d = document,
28
+ now = () => performance.now();
29
+ // Never runs where a visitor types who they are or pays.
30
+ const DENY = /^\/(checkout|account|login)(\/|$)|^\/(api\/io|pvt)\//i;
31
+
32
+ let on = false,
33
+ vid = "",
34
+ path = "",
35
+ t0 = 0,
36
+ last = 0,
37
+ input = 0,
38
+ vis = false,
39
+ raf = 0,
40
+ dhAt = 0;
41
+ let vw = 0,
42
+ vh = 0,
43
+ top = 0,
44
+ dh = 0,
45
+ sd = 0,
46
+ am = 0;
47
+ let roots: Map<string, number>,
48
+ at: number[],
49
+ ss: Map<number, number>,
50
+ seen: Set<number>,
51
+ clicks: any[][];
52
+ let burst: any,
53
+ known: WeakSet<Element>,
54
+ idxOf: WeakMap<Element, number>,
55
+ sent = "",
56
+ sentAm = 0;
57
+ // Clicks awaiting a dead-click verdict. ANY reaction clears all of them: one DOM mutation, a
58
+ // scroll, a route change or focus moving into a text field answers every click before it.
59
+ const pending = new Set<any>();
60
+ const react = () => {
61
+ pending.clear();
62
+ mo.disconnect();
63
+ };
64
+ const mo = new MutationObserver(react);
65
+
66
+ const idx = (id: string) => {
67
+ if (!id) return -1;
68
+ let i = roots.get(id);
69
+ if (i === undefined) {
70
+ if (roots.size >= 32) return -1;
71
+ roots.set(id, (i = roots.size));
72
+ }
73
+ return i;
74
+ };
75
+ const guard =
76
+ (f: (...a: any[]) => void) =>
77
+ (...a: any[]) => {
78
+ try {
79
+ f(...a);
80
+ } catch {
81
+ /* heatmap stops, page lives */
82
+ }
83
+ };
84
+ // Every listener goes through here: guarded, passive unless told otherwise.
85
+ const listen = (
86
+ t: string,
87
+ f: (e: any) => void,
88
+ o: AddEventListenerOptions = { passive: true },
89
+ on: EventTarget = w,
90
+ ) => on.addEventListener(t, guard(f), o);
91
+
92
+ // ---- time: active ms credited to the viewport position it was spent on --------------------
93
+ // Active = tab visible AND some input in the last 30 s, so an idle background tab does not
94
+ // paint the hero red. Time between two ticks is credited to where the viewport WAS.
95
+ const tick = () => {
96
+ const n = now(),
97
+ act = Math.min(n, input + 3e4) - last;
98
+ if (vis && act > 0 && dh) {
99
+ am += act;
100
+ for (
101
+ let i = Math.floor((top * 40) / dh),
102
+ e = Math.min(39, Math.floor(((top + vh - 1) * 40) / dh));
103
+ i <= e;
104
+ i++
105
+ )
106
+ at[i] = (at[i] || 0) + act;
107
+ for (const i of seen) ss.set(i, ss.get(i)! + act);
108
+ }
109
+ last = n;
110
+ vis = d.visibilityState == "visible";
111
+ vw = innerWidth;
112
+ vh = innerHeight;
113
+ top = scrollY;
114
+ if (n - dhAt > 1e3) {
115
+ const h = d.documentElement.scrollHeight;
116
+ dhAt = n;
117
+ if (h > dh) {
118
+ dh = h;
119
+ observe(d.body);
120
+ }
121
+ }
122
+ sd = Math.max(sd, dh ? Math.min(100, Math.round(((top + vh) * 100) / dh)) : 100);
123
+ };
124
+ const poke = () => {
125
+ const n = now();
126
+ if (on && n - input > 3e4) tick();
127
+ input = n;
128
+ };
129
+
130
+ // ---- sections: Deco sections and FastStore component roots, the same roots clicks use -----
131
+ const io = new IntersectionObserver(
132
+ guard((es: IntersectionObserverEntry[]) => {
133
+ if (!on) return;
134
+ tick();
135
+ for (const e of es) {
136
+ const i = idxOf.get(e.target)!;
137
+ if (i < 0) continue;
138
+ if (e.intersectionRatio >= 0.5 || e.intersectionRect.height >= 300) {
139
+ seen.add(i);
140
+ ss.set(i, ss.get(i) || 0);
141
+ } else seen.delete(i);
142
+ }
143
+ }),
144
+ { threshold: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1] },
145
+ );
146
+ // Top-down to the first root on each branch: visits the page scaffolding, not the inside of
147
+ // every component. Re-run when the document grows, which is when lazy sections appear.
148
+ const observe = (p: Element, k = 0) => {
149
+ for (const c of p?.children ?? []) {
150
+ if (k++ > 3e3) return;
151
+ if (c.matches("section[data-manifest-key]") || fsRootName(c)) {
152
+ if (!known.has(c)) {
153
+ known.add(c);
154
+ idxOf.set(c, idx(rootOf(c)[1]));
155
+ io.observe(c);
156
+ }
157
+ } else observe(c, k);
158
+ }
159
+ };
160
+
161
+ // ---- view lifecycle -----------------------------------------------------------------------
162
+ const start = () => {
163
+ path = location.pathname;
164
+ // Sampled ONCE per view: per-event sampling overcounts visitors (2026-08-19).
165
+ on = cfg.h !== 0 && !DENY.test(path) && Math.random() < (cfg.hr ?? 1);
166
+ const r = crypto.getRandomValues(new Uint32Array(2));
167
+ vid = ((r[0] & 0x1fffff) * 4294967296 + r[1]).toString(36);
168
+ cfg.hv = on ? vid : ""; // read by vitals, for the INP A/B by view
169
+ t0 = last = input = now();
170
+ dhAt = -1e4;
171
+ dh = sd = am = 0;
172
+ burst = 0;
173
+ sent = "";
174
+ notes = [];
175
+ roots = new Map();
176
+ at = [];
177
+ ss = new Map();
178
+ seen = new Set();
179
+ clicks = [];
180
+ // Root indices are per view: an SPA view re-observes from scratch with a fresh dictionary.
181
+ io.disconnect();
182
+ known = new WeakSet();
183
+ idxOf = new WeakMap();
184
+ if (!on) return;
185
+ tick();
186
+ // An SPA view starts before its new DOM exists; look again once it has rendered.
187
+ setTimeout(
188
+ guard(() => {
189
+ if (on) {
190
+ tick();
191
+ dh = 0;
192
+ dhAt = -1e4;
193
+ tick();
194
+ }
195
+ }),
196
+ 2e3,
197
+ );
198
+ };
199
+
200
+ const emit = () => {
201
+ if (!on || cfg.h === 0) return;
202
+ drain();
203
+ tick();
204
+ const a: number[] = [];
205
+ for (let i = 0; i < at.length; i++) a.push(Math.round((at[i] || 0) / 100));
206
+ const hm: any = {
207
+ v: 1,
208
+ id: vid,
209
+ vw,
210
+ vh,
211
+ dh,
212
+ sd,
213
+ am: Math.round(am),
214
+ at: a,
215
+ s: [...roots.keys()].map((k) => k.slice(0, 120)),
216
+ ss: [...ss].map(([i, ms]) => [i, Math.round(ms / 100)]),
217
+ // Copies: the queue serialises later, and a dead flag set after this must not edit a
218
+ // record already queued.
219
+ c: clicks.map((c) => c.slice()),
220
+ };
221
+ // Never over the contract's 4 KB for this event: shed the newest clicks first.
222
+ let j;
223
+ while ((j = JSON.stringify(hm)).length > 3800 && hm.c.length) hm.c.pop();
224
+ // Unchanged since the last emission -- `hidden` then `pagehide` on the way out -- is not
225
+ // sent again: core drains on each, and a second copy would cost a second beacon. "Unchanged"
226
+ // ignores the few ms of attention that tick between the two; a second of it is a change.
227
+ const { am: a0, at: a1, ss: a2, ...rest } = hm;
228
+ const sig = JSON.stringify(rest);
229
+ if (sig == sent && hm.am - sentAm < 1e3) return;
230
+ sent = sig;
231
+ sentAm = hm.am;
232
+ enqueue("$heatmap", undefined, { path, heatmap: hm });
233
+ };
234
+
235
+ // ---- clicks -------------------------------------------------------------------------------
236
+ // The listener only takes notes: target, coordinates, scroll, time. The hashing and the layout
237
+ // reads happen AFTER THE NEXT PAINT (rAF, then a task), so none of it is inside the interaction
238
+ // INP measures -- and a layout read there would force the layout the click's own :active
239
+ // styles just invalidated. A route change or the end of the view drains the notes first, so a
240
+ // click is never attributed to the next view.
241
+ const clamp = (v: number) => (v > 255 ? 255 : v > 0 ? v | 0 : 0);
242
+ let notes: any[] = [];
243
+ const drain = () => {
244
+ for (const r of notes.splice(0)) record(r);
245
+ };
246
+ const record = ([t, cx, cy, sy, n, kb, tok]: any[]) => {
247
+ if (!t.isConnected) return; // gone before we looked: no anchor to hash
248
+ const [a, inter] = anchorOf(t),
249
+ [root, id] = rootOf(a);
250
+ const el = cyrb53(id + "|" + pathOf(root, a)).toString(36);
251
+ const r = a.getBoundingClientRect(),
252
+ ds = scrollY - sy;
253
+ let f = (inter ? 16 : 0) | (kb ? 32 : 0);
254
+ for (let p: Element | null = a; p && p != d.body; p = p.parentElement) {
255
+ const pos = getComputedStyle(p).position;
256
+ if (pos == "fixed" || pos == "sticky") {
257
+ f |= 8;
258
+ break;
259
+ }
260
+ }
261
+ // Where the element was AT THE CLICK: a fixed one does not move with scroll, the rest moved
262
+ // up by however far the page scrolled since.
263
+ const top = f & 8 ? r.top : r.top + ds,
264
+ left = r.left;
265
+ // A keyboard "click" has no coordinates; it happened on the element, so use its centre.
266
+ const x = kb ? left + r.width / 2 : cx,
267
+ y = kb ? top + r.height / 2 : cy;
268
+ // Rage: 3+ clicks within 1 s, each within 30 px of the first. One record, n = count.
269
+ if (
270
+ burst &&
271
+ burst[0] == el &&
272
+ n - burst[1] < 1e3 &&
273
+ Math.hypot(x - burst[2], y - burst[3]) <= 30
274
+ ) {
275
+ const c = (tok.c = burst[4]);
276
+ if (c[7] < 255) c[7]++;
277
+ if (c[7] > 2) c[8] |= 1;
278
+ return;
279
+ }
280
+ if (clicks.length >= 40) return;
281
+ const c = (tok.c = [
282
+ idx(id),
283
+ el,
284
+ clamp(((x - left) * 256) / r.width),
285
+ clamp(((y - top) * 256) / r.height),
286
+ Math.min(1e3, Math.max(0, Math.round((x * 1e3) / innerWidth))),
287
+ Math.max(0, Math.round(f & 8 ? y : y + sy)),
288
+ Math.round(n - t0),
289
+ 1,
290
+ f | tok.f,
291
+ ]);
292
+ clicks.push(c);
293
+ burst = [el, n, x, y, c];
294
+ };
295
+ listen(
296
+ "click",
297
+ (e: MouseEvent) => {
298
+ const t = e.target as Element;
299
+ // Untrusted clicks are not behaviour; ignored widgets and password fields are never recorded.
300
+ // A target that is not an Element throws in `closest`, which `guard` turns into "not recorded".
301
+ if (!on || cfg.h === 0 || !e.isTrusted || t.closest("[data-dq-ignore],input[type=password]"))
302
+ return;
303
+ const n = now(),
304
+ tok: any = { f: 0 };
305
+ if (!notes.length) requestAnimationFrame(() => setTimeout(guard(drain)));
306
+ notes.push([t, e.clientX, e.clientY, scrollY, n, e.detail === 0, tok]);
307
+ // Dead: nothing reacted within 1 s. Error: the errors module reported something in that second.
308
+ // Armed NOW, since the reaction is what follows the click. Focus moving onto a clicked button
309
+ // is not a reaction -- every button click does that.
310
+ if (!pending.size)
311
+ mo.observe(d, { subtree: true, childList: true, attributes: true, characterData: true });
312
+ pending.add(tok);
313
+ setTimeout(
314
+ guard(() => {
315
+ if (pending.delete(tok)) tok.f |= 2;
316
+ if (!pending.size) mo.disconnect();
317
+ if ((w.__dqLastErrorTs ?? -1) >= n) tok.f |= 4;
318
+ if (tok.c) tok.c[8] |= tok.f;
319
+ }),
320
+ 1e3,
321
+ );
322
+ },
323
+ { capture: true, passive: true },
324
+ );
325
+
326
+ listen("scroll", () => {
327
+ poke();
328
+ react();
329
+ if (on && !raf)
330
+ raf = requestAnimationFrame(
331
+ guard(() => {
332
+ raf = 0;
333
+ on && tick();
334
+ }),
335
+ );
336
+ });
337
+ for (const t of ["pointerdown", "pointermove", "keydown", "touchstart"]) listen(t, poke);
338
+ listen("visibilitychange", () => on && tick(), {}, d);
339
+ // `matches` throws on a non-Element target; `guard` makes that a no-op.
340
+ listen(
341
+ "focusin",
342
+ (e: FocusEvent) =>
343
+ (e.target as Element).matches("input,textarea,select,[contenteditable]") && react(),
344
+ {},
345
+ d,
346
+ );
347
+ // A page restored from the back/forward cache is a new view; the old one was emitted on pagehide.
348
+ listen("pageshow", (e: PageTransitionEvent) => e.persisted && start());
349
+
350
+ onFinal(emit);
351
+ // Core calls this BEFORE the new route's $pageview. A query-string change on the same path
352
+ // (PLP filters) is not a new view, matching core's replaceState rule.
353
+ onRoute?.((prev: string) => {
354
+ if (prev == location.pathname) return;
355
+ react();
356
+ emit();
357
+ start();
358
+ });
359
+ start();
360
+ });
@@ -0,0 +1,128 @@
1
+ /** Core Web Vitals, in one event on the way out.
2
+ *
3
+ * Not five events, and not one per metric as they settle. Every vital is only final when
4
+ * the page is: LCP can be replaced by a later element, CLS accumulates until the visitor
5
+ * leaves, and INP is the worst interaction of the whole visit. Sending them early means
6
+ * sending them wrong, and sending each separately means four extra rows carrying one
7
+ * number each and repeating the same page, path and visitor.
8
+ *
9
+ * Deliberately not the `web-vitals` library. It is ~2 KB for an attribution model we do
10
+ * not use, and this is the part of the payload every visitor downloads.
11
+ */
12
+ window.__dqRegister?.((enqueue, _api: Record<string, unknown>, onFinal) => {
13
+ let lcp: number | null = null;
14
+ let cls = 0;
15
+ let inp = 0;
16
+ let sent = false;
17
+ // The vitals are the DOCUMENT's: LCP, FCP and TTFB belong to the hard load, never to a later
18
+ // SPA route. They are sent on the way out, when `location` and the heatmap's view id already
19
+ // name whatever route the visitor ended on, so both are taken here, for the page being
20
+ // measured. The view id a microtask later, once the heatmap module (after this one in the
21
+ // bundle) has opened its first view.
22
+ const path = location.pathname;
23
+ let hv: unknown;
24
+ queueMicrotask(() => {
25
+ hv = _api.hv;
26
+ });
27
+
28
+ // The first moment the page was hidden. A tab opened in the BACKGROUND — ctrl+click
29
+ // from a listing, "open link in new tab" — keeps accruing largest-contentful-paint
30
+ // until it is first revealed, so its LCP measures how long the visitor took to look at
31
+ // the tab, not how long the content took to appear. Measured on a live storefront:
32
+ // per-page LCP of 152,858 ms and 151,296 ms on product pages (the ones opened from a
33
+ // listing, naturally) against a 936 ms p75 for the whole site — three samples are
34
+ // enough to make the per-page panel unreadable.
35
+ //
36
+ // Paint metrics that land after this point are therefore dropped. TTFB, CLS and INP
37
+ // are kept: none of them is distorted by the tab being hidden.
38
+ let firstHidden = document.visibilityState === "hidden" ? 0 : Infinity;
39
+ addEventListener(
40
+ "visibilitychange",
41
+ () => {
42
+ firstHidden = Math.min(firstHidden, performance.now());
43
+ },
44
+ { once: true },
45
+ );
46
+ const whileVisible = (v: number | null) => (v === null || v > firstHidden ? null : v);
47
+
48
+ const observe = (type: string, cb: (entries: any[]) => void, opts: any = {}) => {
49
+ try {
50
+ const po = new PerformanceObserver((list) => cb(list.getEntries()));
51
+ po.observe({ type, buffered: true, ...opts });
52
+ return po;
53
+ } catch {
54
+ return null;
55
+ } // an unsupported entry type must not break collection
56
+ };
57
+
58
+ // The LAST largest-contentful-paint wins: the browser reports a new one whenever a
59
+ // bigger element arrives, and only the final value is the metric.
60
+ observe("largest-contentful-paint", (es) => {
61
+ const last = es[es.length - 1];
62
+ if (last) lcp = last.startTime;
63
+ });
64
+
65
+ // CLS excludes shifts within 500ms of an interaction — a layout change the visitor
66
+ // asked for is not "unexpected", and counting it punishes responsive UI.
67
+ observe("layout-shift", (es) => {
68
+ for (const e of es) if (!e.hadRecentInput) cls += e.value;
69
+ });
70
+
71
+ // A true INP is the 98th percentile of interaction latencies. Keeping every interaction
72
+ // to compute that costs memory on a page that may run for an hour, so this is the worst
73
+ // one — which is INP exactly whenever a visit has fewer than fifty interactions, and an
74
+ // upper bound otherwise. The direction of the error is knowable, which is what matters.
75
+ observe(
76
+ "event",
77
+ (es) => {
78
+ for (const e of es) if (e.duration > inp) inp = e.duration;
79
+ },
80
+ { durationThreshold: 40 },
81
+ );
82
+
83
+ const paintOnce = (name: string): number | null => {
84
+ try {
85
+ const e = performance.getEntriesByName(name)[0] as PerformanceEntry | undefined;
86
+ return e ? e.startTime : null;
87
+ } catch {
88
+ return null;
89
+ }
90
+ };
91
+
92
+ const ttfb = (): number | null => {
93
+ try {
94
+ const nav = performance.getEntriesByType("navigation")[0] as
95
+ | PerformanceNavigationTiming
96
+ | undefined;
97
+ return nav ? nav.responseStart : null;
98
+ } catch {
99
+ return null;
100
+ }
101
+ };
102
+
103
+ function send() {
104
+ if (sent) return;
105
+ sent = true;
106
+ const fcp = paintOnce("first-contentful-paint");
107
+ const t = ttfb();
108
+ // Nothing observed at all means an unsupported browser, not a fast page. Sending a
109
+ // row of nulls would dilute every average with visits that were never measured.
110
+ if (lcp === null && fcp === null && t === null && cls === 0 && inp === 0) return;
111
+ enqueue("$vitals", undefined, {
112
+ path,
113
+ vital_lcp: whileVisible(lcp),
114
+ vital_inp: inp || null,
115
+ vital_cls: Math.round(cls * 10000) / 10000,
116
+ vital_ttfb: t,
117
+ vital_fcp: whileVisible(fcp),
118
+ // The heatmap module's view id when it sampled this view: the pilot's INP guardrail compares
119
+ // views with and without heatmap capture on the same site and days.
120
+ heatmap: hv ? { id: hv } : undefined,
121
+ });
122
+ }
123
+
124
+ // Every vital is only final when the page is, so this rides out on core's last flush.
125
+ onFinal(send);
126
+ });
127
+
128
+ export {};
@@ -0,0 +1,70 @@
1
+ /** Reasons not to collect at all, evaluated once at boot.
2
+ *
3
+ * Automation detection has a catch: Playwright sets navigator.webdriver, so it would
4
+ * block our own end-to-end tests. `__dqAllowAutomation` is the escape hatch, and it is
5
+ * why 2.8 does not fail for the wrong reason. */
6
+ export function shouldSkip(w: typeof globalThis & Record<string, any>): string | null {
7
+ const nav = w.navigator;
8
+
9
+ if (!w.__dqAllowAutomation) {
10
+ if (nav?.webdriver) return "automation";
11
+ if (w._phantom || w.__nightmare || w.Cypress) return "automation";
12
+ }
13
+
14
+ try {
15
+ if (w.localStorage?.getItem("__dq_ignore") === "true") return "opt-out";
16
+ } catch {
17
+ /* storage can throw in private mode; not a reason to skip */
18
+ }
19
+
20
+ if (isLocal(w) && !w.__dq?.dev) return "local";
21
+
22
+ return null;
23
+ }
24
+
25
+ /** A development host. Not collected unless the site asks for it.
26
+ *
27
+ * This was missing entirely, and on a fleet of storefronts built by agencies that is not
28
+ * a small omission: every `npm run dev` against a client's site was writing into that
29
+ * client's production numbers, indistinguishable from real traffic. Plausible ships a
30
+ * separate script variant for the local case and OneDollarStats has `data-devmode`,
31
+ * because both meet the same problem.
32
+ *
33
+ * Opt in with `window.__dq.dev = true` before the script loads. */
34
+ function isLocal(w: typeof globalThis & Record<string, any>): boolean {
35
+ const l = w.location;
36
+ if (!l) return false;
37
+ if (l.protocol === "file:") return true;
38
+ const h = String(l.hostname ?? "");
39
+ return (
40
+ h === "localhost" ||
41
+ h === "127.0.0.1" ||
42
+ h === "::1" ||
43
+ h === "[::1]" ||
44
+ h.endsWith(".local") ||
45
+ h.endsWith(".localhost") ||
46
+ // The private ranges a dev server binds to when someone tests from a phone.
47
+ /^10\./.test(h) ||
48
+ /^192\.168\./.test(h) ||
49
+ /^172\.(1[6-9]|2\d|3[01])\./.test(h)
50
+ );
51
+ }
52
+
53
+ /** A page prerendered by Chrome must not count until it becomes visible. Without this any
54
+ * site with prefetch overcounts — which is the whole fleet. */
55
+ export function whenVisible(doc: Document, fn: () => void): void {
56
+ if ((doc as any).prerendering) {
57
+ doc.addEventListener("prerenderingchange", () => fn(), { once: true });
58
+ return;
59
+ }
60
+ if ((doc.visibilityState as string) === "prerender") {
61
+ doc.addEventListener("visibilitychange", function onVis() {
62
+ if ((doc.visibilityState as string) !== "prerender") {
63
+ doc.removeEventListener("visibilitychange", onVis);
64
+ fn();
65
+ }
66
+ });
67
+ return;
68
+ }
69
+ fn();
70
+ }