@veroxm/sdk 1.9.0 → 1.10.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.
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ export { ProcessesResource } from './processes.js';
10
10
  export { FormsResource } from './forms.js';
11
11
  // Showing forms in a page: inline, popup, full page or toast.
12
12
  export { embedForm, embedFormsFromPage } from './embed.js';
13
- export { VeroXMApiError, VeroXMNotAuthenticatedError, VeroXMTwoStepRequiredError } from './errors.js';
13
+ export { VeroXMApiError, VeroXMNotAuthenticatedError, VeroXMTimeoutError, VeroXMTwoStepRequiredError } from './errors.js';
14
14
  export { MemoryTokenStorage, BrowserLocalStorageTokenStorage } from './token-storage.js';
15
15
  // Experience OS visitor tracking (page views, actions, consent, identify).
16
16
  export { VeroxmTracker, createTracker } from './tracker.js';
@@ -0,0 +1,27 @@
1
+ /** The part of posthog-js the tracker uses (the snippet's stub queues these calls until PostHog has loaded). */
2
+ export interface PostHogLike {
3
+ capture(event: string, properties?: Record<string, unknown>): unknown;
4
+ register(properties: Record<string, unknown>): unknown;
5
+ }
6
+ /** What VeroXM says to send for an exposure (`posthog` on a decision). */
7
+ export interface PosthogExposureHint {
8
+ /** `$feature_flag`: veroxm-<experience id>. */
9
+ flag: string;
10
+ /** `$feature_flag_response`: "control", or the variant's label as a key. */
11
+ variant: string;
12
+ }
13
+ export declare const POSTHOG_EXPOSURE_EVENT = "$feature_flag_called";
14
+ /** The PostHog instance to send to: the one given, else the page's window.posthog; null when there is none. */
15
+ export declare function findPosthog(given?: PostHogLike | false | null): PostHogLike | null;
16
+ /** A hint as the API sends it, or null when it isn't one. */
17
+ export declare function readHint(raw: unknown): PosthogExposureHint | null;
18
+ /**
19
+ * Sends one exposure to PostHog, at most once per test for this `sent` set (one per page load). Returns whether it
20
+ * sent. Never throws: PostHog's problems never break the page.
21
+ */
22
+ export declare function sendPosthogExposure(ph: PostHogLike | null, exposure: {
23
+ hint: PosthogExposureHint;
24
+ experienceId: number;
25
+ variantId: number;
26
+ placement: string;
27
+ }, sent: Set<number>): boolean;
@@ -0,0 +1,54 @@
1
+ // Insights I1 (docs/INSIGHTS-SCOPE.md, D5): experiment exposures in the site's own PostHog.
2
+ //
3
+ // When the project's "Send test exposures to PostHog" is on, VeroXM's answers (GET /decide, and /slots for the
4
+ // script tag) carry `posthog: { flag, variant }`. If the page has PostHog (window.posthog, or the instance passed as
5
+ // the tracker's `posthog` option), the tracker sends the exposure there, so it lands on the visitor's own PostHog
6
+ // distinct id:
7
+ //
8
+ // posthog.capture('$feature_flag_called', { $feature_flag: 'veroxm-12', $feature_flag_response: 'b', ... })
9
+ // posthog.register({ '$feature/veroxm-12': 'b', veroxm_12: 'b' })
10
+ //
11
+ // `$feature_flag_called` (not `$exposure`) because it is the exposure event PostHog's own SDKs send for a flag, the
12
+ // default exposure event of PostHog experiments, and what its flag breakdowns read. The super properties make every
13
+ // later PostHog event of the visitor carry the variant: `$feature/<flag>` is how PostHog attributes events to a flag
14
+ // variant; `veroxm_<id>` is a plain property that is easy to find in any breakdown. Once per test per page load,
15
+ // only after VeroXM's analytics consent, and nothing about the person: test and variant ids and keys, the placement.
16
+ export const POSTHOG_EXPOSURE_EVENT = '$feature_flag_called';
17
+ /** The PostHog instance to send to: the one given, else the page's window.posthog; null when there is none. */
18
+ export function findPosthog(given) {
19
+ if (given === false || given === null)
20
+ return null;
21
+ const candidate = given ?? (typeof window !== 'undefined' ? window.posthog : undefined);
22
+ const ph = candidate;
23
+ return ph && typeof ph.capture === 'function' && typeof ph.register === 'function' ? ph : null;
24
+ }
25
+ /** A hint as the API sends it, or null when it isn't one. */
26
+ export function readHint(raw) {
27
+ const h = raw;
28
+ return h && typeof h.flag === 'string' && typeof h.variant === 'string' && h.flag && h.variant ? { flag: h.flag, variant: h.variant } : null;
29
+ }
30
+ /**
31
+ * Sends one exposure to PostHog, at most once per test for this `sent` set (one per page load). Returns whether it
32
+ * sent. Never throws: PostHog's problems never break the page.
33
+ */
34
+ export function sendPosthogExposure(ph, exposure, sent) {
35
+ if (!ph || sent.has(exposure.experienceId))
36
+ return false;
37
+ sent.add(exposure.experienceId);
38
+ const { flag, variant } = exposure.hint;
39
+ try {
40
+ ph.capture(POSTHOG_EXPOSURE_EVENT, {
41
+ $feature_flag: flag,
42
+ $feature_flag_response: variant,
43
+ [`$feature/${flag}`]: variant,
44
+ veroxm_experience_id: exposure.experienceId,
45
+ veroxm_variant_id: exposure.variantId,
46
+ veroxm_placement: exposure.placement,
47
+ });
48
+ ph.register({ [`$feature/${flag}`]: variant, [`veroxm_${exposure.experienceId}`]: variant });
49
+ return true;
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ }
package/dist/tracker.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import type { Schemas } from './schemas.js';
2
+ import { type Vitals } from './autocapture.js';
3
+ import { type PostHogLike, type PosthogExposureHint } from './posthog.js';
2
4
  export interface TrackerStorage {
3
5
  get(key: string): string | null;
4
6
  set(key: string, value: string): void;
@@ -19,6 +21,43 @@ export interface TrackerOptions {
19
21
  storage?: TrackerStorage;
20
22
  /** Called when a request fails for good (a rejected batch, a bad key). Defaults to console.warn. */
21
23
  onError?: (error: Error) => void;
24
+ /**
25
+ * Record clicks, rage clicks, form submits, scroll depth and page speed automatically (browsers only; default
26
+ * false). Held until analytics consent like every other event.
27
+ * @since 1.9.0
28
+ */
29
+ autocapture?: boolean;
30
+ /**
31
+ * For autocapture: the A/B test a clicked element is part of (e.g. a slot under test), so clicks can be split by
32
+ * variant. Return null when it isn't in one.
33
+ * @since 1.9.0
34
+ */
35
+ slotTest?: (element: Element) => {
36
+ experienceId: number;
37
+ variantId: number;
38
+ } | null;
39
+ /**
40
+ * Where test exposures go when the project sends them to PostHog: your posthog-js instance. By default the page's
41
+ * `window.posthog`; pass `false` to never send them from this tracker.
42
+ * @since 1.9.0
43
+ */
44
+ posthog?: PostHogLike | false;
45
+ }
46
+ /** What an automatic capture or page-end report carries (sent as `interaction`). */
47
+ export interface InteractionData {
48
+ path: string;
49
+ selector?: string;
50
+ label?: string;
51
+ href?: string;
52
+ x?: number;
53
+ y?: number;
54
+ pageY?: number;
55
+ depth?: number;
56
+ viewportW?: number;
57
+ experienceId?: number;
58
+ variantId?: number;
59
+ engagedMs?: number;
60
+ metrics?: Vitals;
22
61
  }
23
62
  export interface ConsentChoices {
24
63
  analytics?: boolean;
@@ -53,6 +92,12 @@ export interface ExperienceDecision<TContent = Record<string, unknown>, TConfig
53
92
  config: TConfig | null;
54
93
  /** True when no request was made because analytics consent isn't granted yet. */
55
94
  waitingForConsent?: boolean;
95
+ /**
96
+ * When the project sends test exposures to PostHog: the flag and variant the tracker sent there (`$feature_flag`,
97
+ * `$feature_flag_response`). Only on a test's answer.
98
+ * @since 1.9.0
99
+ */
100
+ posthog?: PosthogExposureHint;
56
101
  /** Set when the request failed or timed out (the decision is then "none"). */
57
102
  error?: string;
58
103
  }
@@ -76,6 +121,17 @@ export declare class VeroxmTracker {
76
121
  private readonly memory;
77
122
  private readonly onError;
78
123
  private readonly keys;
124
+ private readonly autocapture;
125
+ private readonly slotTest;
126
+ private readonly posthogOption;
127
+ /** Tests whose exposure went to PostHog on this page load. */
128
+ private readonly posthogSent;
129
+ private session;
130
+ private pageState;
131
+ private pagesSeen;
132
+ private readonly vitals;
133
+ private scrollCheckedAt;
134
+ private scrollTimer;
79
135
  private visitorId;
80
136
  private consentState;
81
137
  private queue;
@@ -145,6 +201,8 @@ export declare class VeroxmTracker {
145
201
  * `config.newCheckout` of this visitor's variant, else the fallback.
146
202
  */
147
203
  getFlag<T>(placement: string, key: string, fallback: T): Promise<T>;
204
+ /** A test's exposure to the page's PostHog, once per test per page load (see posthog.ts). Consent is checked by getExperience. */
205
+ private sendToPosthog;
148
206
  /** Called when consent, identity or the visitor changes -- ask for experiences again. Returns an unsubscribe function. */
149
207
  subscribe(listener: () => void): () => void;
150
208
  /** Sends queued events now. Resolves when done (or deferred by a backoff). */
@@ -155,7 +213,24 @@ export declare class VeroxmTracker {
155
213
  shutdown(): void;
156
214
  private changed;
157
215
  private sendAll;
216
+ /**
217
+ * Queues an event; returns its session id. Reports (page end, scroll, vitals) pass their page's fixed id, time and
218
+ * session: an unsent copy in the queue is replaced, and a re-sent one replaces the stored one (same id and time).
219
+ */
158
220
  private enqueue;
221
+ /** The session an event now belongs to (D4), kept on the device only when allowed. */
222
+ private sessionFor;
223
+ private saveSession;
224
+ /** Stops the page's visible-time clock (the tab was hidden or left). */
225
+ private pausePage;
226
+ /** The page's reports: engaged time, and with autocapture its scroll depth and page speed. Safe to call repeatedly. */
227
+ private reportPage;
228
+ /** Updates the page's deepest scroll bucket (at most every 250 ms unless forced). */
229
+ private checkScroll;
230
+ private startAutocapture;
231
+ private clickData;
232
+ /** LCP, INP (approximated by the longest interaction), CLS -- where the browser measures them. */
233
+ private observeVitals;
159
234
  private post;
160
235
  private canSend;
161
236
  /** Whether anything may be written to the device. */
package/dist/tracker.js CHANGED
@@ -36,6 +36,22 @@
36
36
  // when the page is hidden), retried with backoff on network/server errors
37
37
  // with the same eventId and occurredAt (so the server counts them once),
38
38
  // and -- with consent -- kept in storage across page loads until sent.
39
+ //
40
+ // Insights (docs/INSIGHTS-SCOPE.md, I0): every event carries a session id
41
+ // (a new one after 30 minutes without an event, at midnight UTC, or when a
42
+ // page view is a new campaign touch), kept on the device only with consent,
43
+ // like the visitor id. In a browser, each page also sends a page-end report
44
+ // (visible time on it, engaged_ms) when it is hidden or left. With
45
+ // `autocapture: true` it also records clicks on links, buttons and marked
46
+ // elements, rage clicks, form submits (the form's id or name, never what was
47
+ // typed), how far down each page was scrolled and its Core Web Vitals.
48
+ // data-veroxm-ignore on an element (or an ancestor) leaves it out;
49
+ // data-veroxm-mask keeps its text out. Held until consent like everything else.
50
+ //
51
+ // PostHog (Insights I1): when the project sends test exposures to PostHog, a decision carries `posthog` and the
52
+ // tracker sends the exposure to the page's PostHog (window.posthog, or the `posthog` option) -- see posthog.ts.
53
+ import { ClsWindow, MAX_PATH, RageDetector, campaignKey, clickTarget, fraction, hrefFor, isIgnored, labelFor, nextSession, parseSession, scrollBucket, selectorFor, shortText, vitalsReport, } from './autocapture.js';
54
+ import { findPosthog, readHint, sendPosthogExposure } from './posthog.js';
39
55
  const BATCH_SIZE = 20;
40
56
  const MAX_QUEUE = 1000;
41
57
  const MAX_BACKOFF_MS = 5 * 60 * 1000;
@@ -106,6 +122,14 @@ function uuid() {
106
122
  export class VeroxmTracker {
107
123
  constructor(options) {
108
124
  this.memory = new MemoryStorage();
125
+ /** Tests whose exposure went to PostHog on this page load. */
126
+ this.posthogSent = new Set();
127
+ this.session = null;
128
+ this.pageState = null;
129
+ this.pagesSeen = 0;
130
+ this.vitals = {};
131
+ this.scrollCheckedAt = 0;
132
+ this.scrollTimer = null;
109
133
  this.queue = [];
110
134
  this.timer = null;
111
135
  this.sending = null;
@@ -124,9 +148,15 @@ export class VeroxmTracker {
124
148
  visitor: `veroxm:${options.projectId}:visitor`,
125
149
  consent: `veroxm:${options.projectId}:consent`,
126
150
  queue: `veroxm:${options.projectId}:queue`,
151
+ session: `veroxm:${options.projectId}:session`,
127
152
  };
153
+ const browser = typeof document !== 'undefined' && typeof window !== 'undefined';
154
+ this.autocapture = !!options.autocapture && browser;
155
+ this.slotTest = options.slotTest;
156
+ this.posthogOption = options.posthog;
128
157
  this.consentState = this.readConsent();
129
158
  this.visitorId = this.store().get(this.keys.visitor) ?? uuid();
159
+ this.session = parseSession(this.store().get(this.keys.session));
130
160
  // Campaign attribution: in a browser, the page the visitor arrived on (with its utm tags and ad click ids) and the
131
161
  // page that linked to it. Kept in memory for this page load only; a single-page app keeps it as people move around.
132
162
  if (typeof window !== 'undefined' && window.location) {
@@ -142,13 +172,25 @@ export class VeroxmTracker {
142
172
  this.timer = setInterval(() => void this.flush(), interval);
143
173
  this.timer.unref?.();
144
174
  }
145
- if (typeof document !== 'undefined' && typeof window !== 'undefined') {
146
- // The last chance to send before the tab goes away.
175
+ if (browser) {
176
+ // The last chance to send before the tab goes away: the page-end report first, then everything queued.
147
177
  document.addEventListener('visibilitychange', () => {
148
- if (document.visibilityState === 'hidden')
178
+ if (document.visibilityState === 'hidden') {
179
+ this.pausePage();
180
+ this.reportPage();
149
181
  void this.flush({ keepalive: true });
182
+ }
183
+ else if (this.pageState && this.pageState.visibleSince === null) {
184
+ this.pageState.visibleSince = Date.now();
185
+ }
150
186
  });
151
- window.addEventListener('pagehide', () => void this.flush({ keepalive: true }));
187
+ window.addEventListener('pagehide', () => {
188
+ this.pausePage();
189
+ this.reportPage();
190
+ void this.flush({ keepalive: true });
191
+ });
192
+ if (this.autocapture)
193
+ this.startAutocapture();
152
194
  }
153
195
  }
154
196
  /** The anonymous id for this browser/app install. */
@@ -176,7 +218,28 @@ export class VeroxmTracker {
176
218
  auto.referrer = document.referrer;
177
219
  }
178
220
  }
179
- this.enqueue({ type: 'page', properties: { ...auto, ...properties } });
221
+ // A single-page app moving on: the page before it is done.
222
+ if (this.pageState) {
223
+ this.pausePage();
224
+ this.reportPage();
225
+ this.pageState = null;
226
+ }
227
+ // Only the page this load started on can be a campaign touch (later pages of a single-page app keep the referrer).
228
+ const first = this.pagesSeen++ === 0;
229
+ const touch = first && this.landing ? campaignKey(this.landing.url, this.landing.referrer) : '';
230
+ const sessionId = this.enqueue({ type: 'page', properties: { ...auto, ...properties } }, { touch });
231
+ if (typeof window !== 'undefined' && window.location && typeof document !== 'undefined') {
232
+ this.pageState = {
233
+ path: window.location.pathname.slice(0, MAX_PATH),
234
+ startedAt: new Date().toISOString(),
235
+ sessionId,
236
+ // Page speed is measured for the page the browser loaded, not for a single-page app's later views.
237
+ ids: { end: uuid(), scroll: uuid(), vitals: first ? uuid() : null },
238
+ engagedMs: 0,
239
+ visibleSince: document.visibilityState === 'hidden' ? null : Date.now(),
240
+ depth: 0, // measured on scroll and when the page ends (not now: the page may still be loading)
241
+ };
242
+ }
180
243
  }
181
244
  /** Saves the visitor's consent answers (true = granted, false = denied, omitted = unchanged). */
182
245
  async consent(choices) {
@@ -194,14 +257,18 @@ export class VeroxmTracker {
194
257
  this.storage.set(this.keys.consent, JSON.stringify(next));
195
258
  this.storage.set(this.keys.visitor, this.visitorId);
196
259
  setVisitorCookie(this.visitorId);
197
- if (!wasPersisting)
260
+ if (!wasPersisting) {
198
261
  this.saveQueue();
262
+ this.saveSession();
263
+ }
199
264
  }
200
265
  else if (next.analytics === 'denied') {
201
266
  // Denied: forget everything this tracker kept about the visitor.
202
267
  this.queue = [];
268
+ this.session = null;
203
269
  this.storage.remove(this.keys.queue);
204
270
  this.storage.remove(this.keys.visitor);
271
+ this.storage.remove(this.keys.session);
205
272
  setVisitorCookie(null);
206
273
  this.storage.set(this.keys.consent, JSON.stringify(next)); // remember the answer itself
207
274
  }
@@ -241,10 +308,14 @@ export class VeroxmTracker {
241
308
  reset() {
242
309
  this.queue = [];
243
310
  this.visitorId = uuid();
311
+ this.session = null; // a new person: a new session too
312
+ if (this.pageState)
313
+ this.pageState.sessionId = undefined;
244
314
  if (this.canPersist()) {
245
315
  this.storage.set(this.keys.visitor, this.visitorId);
246
316
  setVisitorCookie(this.visitorId);
247
317
  this.storage.remove(this.keys.queue);
318
+ this.storage.remove(this.keys.session);
248
319
  }
249
320
  this.changed();
250
321
  }
@@ -288,6 +359,9 @@ export class VeroxmTracker {
288
359
  qs += `&url=${encodeURIComponent(this.landing.url.slice(0, 2000))}`;
289
360
  if (this.landing?.referrer)
290
361
  qs += `&referrer=${encodeURIComponent(this.landing.referrer.slice(0, 2000))}`;
362
+ // This page sends exposures to PostHog itself, so VeroXM's server doesn't (it would for a signed-in person).
363
+ if (findPosthog(this.posthogOption))
364
+ qs += '&posthog=browser';
291
365
  const request = fetch(`${this.apiBase}/decide?${qs}`, {
292
366
  headers: { Authorization: `Bearer ${this.key}` },
293
367
  ...(controller ? { signal: controller.signal } : {}),
@@ -295,7 +369,9 @@ export class VeroxmTracker {
295
369
  .then(async (res) => {
296
370
  if (!res.ok)
297
371
  throw new Error(`VeroXM /decide failed with ${res.status}`);
298
- return (await res.json());
372
+ const decision = (await res.json());
373
+ this.sendToPosthog(decision);
374
+ return decision;
299
375
  })
300
376
  .catch((err) => {
301
377
  this.decisions.delete(placement); // try again next time
@@ -357,6 +433,13 @@ export class VeroxmTracker {
357
433
  const value = decision.config?.[key];
358
434
  return value === undefined ? fallback : value;
359
435
  }
436
+ /** A test's exposure to the page's PostHog, once per test per page load (see posthog.ts). Consent is checked by getExperience. */
437
+ sendToPosthog(decision) {
438
+ const hint = readHint(decision.posthog);
439
+ if (!hint || !decision.experienceId || !decision.variantId || !this.canSend())
440
+ return;
441
+ sendPosthogExposure(findPosthog(this.posthogOption), { hint, experienceId: decision.experienceId, variantId: decision.variantId, placement: decision.placement }, this.posthogSent);
442
+ }
360
443
  /** Called when consent, identity or the visitor changes -- ask for experiences again. Returns an unsubscribe function. */
361
444
  subscribe(listener) {
362
445
  this.listeners.add(listener);
@@ -407,28 +490,198 @@ export class VeroxmTracker {
407
490
  // 4xx: this batch will never be accepted (bad key, invalid events) -- drop it.
408
491
  this.onError(err);
409
492
  }
410
- this.queue = this.queue.slice(batch.length);
493
+ // By identity, not position: a report re-queued while this batch was in flight (same id, newer values) stays.
494
+ const done = new Set(batch);
495
+ this.queue = this.queue.filter((e) => !done.has(e));
411
496
  this.saveQueue();
412
497
  this.backoffMs = 0;
413
498
  this.retryAt = 0;
414
499
  }
415
500
  }
416
- enqueue(e) {
501
+ /**
502
+ * Queues an event; returns its session id. Reports (page end, scroll, vitals) pass their page's fixed id, time and
503
+ * session: an unsent copy in the queue is replaced, and a re-sent one replaces the stored one (same id and time).
504
+ */
505
+ enqueue(e, opts = {}) {
417
506
  if (this.requireConsent && this.consentState.analytics === 'denied')
418
- return;
419
- this.queue.push({
420
- eventId: uuid(),
507
+ return undefined;
508
+ const now = Date.now();
509
+ const sessionId = opts.eventId ? opts.sessionId ?? this.session?.id : this.sessionFor(now, opts.touch ?? '');
510
+ const event = {
511
+ eventId: opts.eventId ?? uuid(),
421
512
  visitorId: this.visitorId,
513
+ ...(sessionId ? { sessionId } : {}),
422
514
  type: e.type,
423
515
  ...(e.name ? { name: e.name } : {}),
424
516
  ...(e.properties && Object.keys(e.properties).length ? { properties: e.properties } : {}),
425
- occurredAt: new Date().toISOString(),
426
- });
517
+ ...(e.interaction ? { interaction: e.interaction } : {}),
518
+ occurredAt: opts.occurredAt ?? new Date(now).toISOString(),
519
+ };
520
+ const at = opts.eventId ? this.queue.findIndex((q) => q.eventId === opts.eventId) : -1;
521
+ if (at >= 0)
522
+ this.queue[at] = event;
523
+ else
524
+ this.queue.push(event);
427
525
  if (this.queue.length > MAX_QUEUE)
428
526
  this.queue = this.queue.slice(-MAX_QUEUE);
429
527
  this.saveQueue();
430
528
  if (this.queue.length >= BATCH_SIZE)
431
529
  void this.flush();
530
+ return sessionId;
531
+ }
532
+ /** The session an event now belongs to (D4), kept on the device only when allowed. */
533
+ sessionFor(now, touch) {
534
+ this.session = nextSession(this.session, now, touch, uuid);
535
+ this.saveSession();
536
+ return this.session.id;
537
+ }
538
+ saveSession() {
539
+ if (!this.canPersist() || !this.session)
540
+ return;
541
+ try {
542
+ this.storage.set(this.keys.session, JSON.stringify(this.session));
543
+ }
544
+ catch {
545
+ // storage full -- the session lives in memory for this page
546
+ }
547
+ }
548
+ // ------------------------------------------------------------ page end and autocapture (Insights I0)
549
+ /** Stops the page's visible-time clock (the tab was hidden or left). */
550
+ pausePage() {
551
+ const p = this.pageState;
552
+ if (p && p.visibleSince !== null) {
553
+ p.engagedMs += Math.max(0, Date.now() - p.visibleSince);
554
+ p.visibleSince = null;
555
+ }
556
+ }
557
+ /** The page's reports: engaged time, and with autocapture its scroll depth and page speed. Safe to call repeatedly. */
558
+ reportPage() {
559
+ const p = this.pageState;
560
+ if (!p)
561
+ return;
562
+ const report = { occurredAt: p.startedAt, sessionId: p.sessionId };
563
+ const running = p.visibleSince !== null ? Date.now() - p.visibleSince : 0;
564
+ this.enqueue({ type: 'page_end', interaction: { path: p.path, engagedMs: Math.round(p.engagedMs + running) } }, { ...report, eventId: p.ids.end });
565
+ if (!this.autocapture)
566
+ return;
567
+ this.checkScroll(true);
568
+ const viewportW = Math.round(window.innerWidth || 0);
569
+ this.enqueue({ type: 'scroll', interaction: { path: p.path, depth: p.depth, viewportW } }, { ...report, eventId: p.ids.scroll });
570
+ if (p.ids.vitals) {
571
+ if (this.vitals.ttfb === undefined)
572
+ this.vitals.ttfb = navigationTtfb();
573
+ const metrics = vitalsReport(this.vitals);
574
+ if (metrics)
575
+ this.enqueue({ type: 'vitals', interaction: { path: p.path, metrics, viewportW } }, { ...report, eventId: p.ids.vitals });
576
+ }
577
+ }
578
+ /** Updates the page's deepest scroll bucket (at most every 250 ms unless forced). */
579
+ checkScroll(force = false) {
580
+ const p = this.pageState;
581
+ if (!p)
582
+ return;
583
+ const now = Date.now();
584
+ if (!force && now - this.scrollCheckedAt < 250) {
585
+ // Throttled: look once more when the burst is over, so the deepest point isn't missed.
586
+ this.scrollTimer ?? (this.scrollTimer = setTimeout(() => {
587
+ this.scrollTimer = null;
588
+ this.checkScroll(true);
589
+ }, 250));
590
+ return;
591
+ }
592
+ this.scrollCheckedAt = now;
593
+ const doc = document.documentElement;
594
+ const height = Math.max(doc?.scrollHeight ?? 0, document.body?.scrollHeight ?? 0);
595
+ p.depth = Math.max(p.depth, scrollBucket((window.scrollY || 0) + (window.innerHeight || 0), height));
596
+ }
597
+ startAutocapture() {
598
+ const rage = new RageDetector();
599
+ document.addEventListener('click', (e) => {
600
+ const t = e.target instanceof Element ? e.target : null;
601
+ if (!t || isIgnored(t))
602
+ return;
603
+ const target = clickTarget(t);
604
+ const isRage = rage.hit(e.clientX, e.clientY, Date.now());
605
+ if (!target && !isRage)
606
+ return;
607
+ const data = this.clickData((target ?? t), e);
608
+ if (target)
609
+ this.enqueue({ type: 'click', interaction: data });
610
+ if (isRage)
611
+ this.enqueue({ type: 'rage', interaction: data });
612
+ }, { capture: true, passive: true });
613
+ document.addEventListener('submit', (e) => {
614
+ const form = e.target instanceof Element ? e.target : null;
615
+ if (!form || isIgnored(form))
616
+ return;
617
+ // The form's own id or name only -- never a field or what was typed.
618
+ this.enqueue({
619
+ type: 'submit',
620
+ interaction: {
621
+ path: location.pathname.slice(0, MAX_PATH),
622
+ selector: selectorFor(form),
623
+ label: shortText(form.getAttribute('id') || form.getAttribute('name')),
624
+ viewportW: Math.round(window.innerWidth || 0),
625
+ },
626
+ });
627
+ }, { capture: true, passive: true });
628
+ window.addEventListener('scroll', () => this.checkScroll(), { passive: true });
629
+ this.observeVitals();
630
+ }
631
+ clickData(el, e) {
632
+ const rect = el.getBoundingClientRect();
633
+ const doc = document.documentElement;
634
+ const height = Math.max(doc?.scrollHeight ?? 0, document.body?.scrollHeight ?? 0);
635
+ let test = null;
636
+ try {
637
+ test = this.slotTest?.(el) ?? null;
638
+ }
639
+ catch {
640
+ // the hook's problem; the click still counts
641
+ }
642
+ const href = el.tagName === 'A' ? hrefFor(el.getAttribute('href'), location.href) : '';
643
+ return {
644
+ path: location.pathname.slice(0, MAX_PATH),
645
+ selector: selectorFor(el),
646
+ label: labelFor(el),
647
+ ...(href ? { href } : {}),
648
+ x: fraction(e.clientX - rect.left, rect.width),
649
+ y: fraction(e.clientY - rect.top, rect.height),
650
+ pageY: fraction(e.clientY + (window.scrollY || 0), height),
651
+ viewportW: Math.round(window.innerWidth || 0),
652
+ ...(test ? { experienceId: test.experienceId, variantId: test.variantId } : {}),
653
+ };
654
+ }
655
+ /** LCP, INP (approximated by the longest interaction), CLS -- where the browser measures them. */
656
+ observeVitals() {
657
+ if (typeof PerformanceObserver === 'undefined')
658
+ return;
659
+ const supported = PerformanceObserver.supportedEntryTypes ?? [];
660
+ const observe = (type, onEntry, extra = {}) => {
661
+ if (!supported.includes(type))
662
+ return;
663
+ try {
664
+ new PerformanceObserver((list) => list.getEntries().forEach(onEntry)).observe({ type, buffered: true, ...extra });
665
+ }
666
+ catch {
667
+ // an older browser that lists the type but not these options
668
+ }
669
+ };
670
+ const cls = new ClsWindow();
671
+ if (supported.includes('layout-shift'))
672
+ this.vitals.cls = 0;
673
+ observe('largest-contentful-paint', (e) => (this.vitals.lcp = e.startTime));
674
+ observe('layout-shift', (e) => {
675
+ cls.add(e);
676
+ this.vitals.cls = cls.value;
677
+ });
678
+ const interaction = (e) => {
679
+ if (e.interactionId === 0)
680
+ return;
681
+ this.vitals.inp = Math.max(this.vitals.inp ?? 0, e.duration);
682
+ };
683
+ observe('event', interaction, { durationThreshold: 16 });
684
+ observe('first-input', interaction);
432
685
  }
433
686
  async post(path, body, keepalive = false) {
434
687
  const res = await fetch(`${this.apiBase}${path}`, {
@@ -489,6 +742,16 @@ export class VeroxmTracker {
489
742
  }
490
743
  }
491
744
  }
745
+ /** Time to first byte of the page load, where the browser reports it. */
746
+ function navigationTtfb() {
747
+ try {
748
+ const nav = performance.getEntriesByType('navigation')[0];
749
+ return nav && nav.responseStart > 0 ? nav.responseStart : undefined;
750
+ }
751
+ catch {
752
+ return undefined;
753
+ }
754
+ }
492
755
  /** Creates a tracker. One per page/app; see VeroxmTracker for the API. */
493
756
  export function createTracker(options) {
494
757
  return new VeroxmTracker(options);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@veroxm/sdk",
3
- "version": "1.9.0",
3
+ "version": "1.10.0",
4
4
  "description": "VeroXM client for JavaScript and TypeScript: content, media, experiences, events and the visitor tracker.",
5
5
  "keywords": [
6
6
  "veroxm",