@veroxm/sdk 1.8.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/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.10.0
4
+
5
+ - Timeouts, retries and cancelling, all off unless you set them. `initializeApp({ timeoutMs, retries })` sets them for
6
+ every request. `list`, `search`, `count`, `get`, `functions.call` and `functions.get` take a `signal` (an
7
+ `AbortSignal`) and their own `timeoutMs`. A request that runs out of time rejects with the new `VeroXMTimeoutError`
8
+ (`code: 'timeout'`). Only GET and HEAD requests are retried, after a network error, a timeout, or 429, 502, 503 or
9
+ 504, with backoff and the API's `Retry-After` (up to 10 s). File uploads don't take the app's time limit.
10
+
11
+ ## 1.9.0
12
+
13
+ - Bot protection (public API 2.12): `auth.getConfig()` says what a sign-in page should show (sign-up, social sign-in,
14
+ passkeys, and `botProtection`: the captcha provider, its site key, which forms need it, the honeypot and timing).
15
+ `signUp`, `signInWithEmail` and `requestPasswordReset` take a `BotCheck`: `botToken` (the Turnstile, hCaptcha or
16
+ reCAPTCHA v3 token), `website` (the hidden honeypot field) and `formStartedAt` (sent as `formElapsedMs`, so the
17
+ device's clock doesn't matter). Refusals are `VeroXMApiError`s with code `bot_check_required`, `bot_check_failed` or
18
+ `bot_check_unavailable`.
19
+
3
20
  ## 1.8.0
4
21
 
5
22
  - Writes to database content models (public API 2.11): `create`, `update` and `delete` work on a model that allows
package/README.md CHANGED
@@ -370,7 +370,8 @@ Every non-2xx response throws `VeroXMApiError` (`.status`, `.body`, a
370
370
  `.message` extracted from whichever error shape the API used, and `.code`
371
371
  when the API gave a reason, such as `email_not_verified`, `invalid_code`,
372
372
  `sign_up_closed` or `too_many_attempts`). A request
373
- made before any sign-in call throws `VeroXMNotAuthenticatedError`.
373
+ made before any sign-in call throws `VeroXMNotAuthenticatedError`. A request that
374
+ runs past its `timeoutMs` throws `VeroXMTimeoutError` (see below).
374
375
 
375
376
  ```ts
376
377
  import { VeroXMApiError } from '@veroxm/sdk';
@@ -384,6 +385,34 @@ try {
384
385
  }
385
386
  ```
386
387
 
388
+ ## Timeouts, retries and cancelling
389
+
390
+ From 1.10. All three are off unless you set them, so a request behaves as before until you do.
391
+
392
+ ```ts
393
+ const app = VeroXMApp.initializeApp({
394
+ baseUrl: 'https://cms.example.com',
395
+ projectId: 'YOUR-PROJECT-UUID',
396
+ timeoutMs: 8000, // give up after 8 s with VeroXMTimeoutError
397
+ retries: 2, // try a failed read twice more
398
+ });
399
+
400
+ // Per call: its own time limit, or cancel it (a React effect's cleanup, a route change).
401
+ const controller = new AbortController();
402
+ const posts = await app.content('posts').list({ limit: 10, signal: controller.signal, timeoutMs: 3000 });
403
+ controller.abort(); // rejects with an AbortError
404
+ ```
405
+
406
+ - **`timeoutMs`** (app or call): rejects with `VeroXMTimeoutError` (`code: 'timeout'`, `timeoutMs`). The API may still
407
+ have received the request. File uploads get no limit from the app setting; pass `timeoutMs` on the call if you want
408
+ one.
409
+ - **`retries`** (0 to 5, app only): only GET and HEAD requests are repeated, after a network error, a timeout, or a
410
+ 429, 502, 503 or 504 answer. The SDK waits 300 ms, 600 ms, 1.2 s and so on, with jitter, or as long as the API's
411
+ `Retry-After` asks, up to 10 s. Writes (`create`, `update`, `delete`, `search`, `functions.call`) are never
412
+ repeated. `functions.get` is, so keep functions that answer GET safe to run twice.
413
+ - **`signal`** (call): taken by `list`, `search`, `count`, `get`, `functions.call` and `functions.get`. A cancelled call
414
+ rejects with the signal's reason and stops any wait for a retry.
415
+
387
416
  ## Stability
388
417
 
389
418
  Follows semantic versioning. From 1.0, breaking changes come only in a major version, after at least one minor release with the
package/dist/auth.d.ts CHANGED
@@ -15,6 +15,22 @@ export type EmailCode = {
15
15
  export type Account = Schemas['Account'];
16
16
  /** A social sign-in option to show a button for. */
17
17
  export type SocialProvider = Schemas['SocialProvider'];
18
+ /** What a sign-in page should show, from `getConfig()`: sign-up, social sign-in, passkeys and the bot check. */
19
+ export type AuthConfig = Schemas['AuthConfig'];
20
+ /** The bot check a project wants on its forms: the captcha provider and site key, the honeypot and timing. */
21
+ export type BotProtectionConfig = Schemas['BotProtectionConfig'];
22
+ /**
23
+ * Bot protection fields for sign-up, email sign-in and password reset, when the project has them on (see
24
+ * `getConfig().botProtection`). All optional.
25
+ */
26
+ export interface BotCheck {
27
+ /** The captcha widget's token (Turnstile, hCaptcha or reCAPTCHA v3). Each token works once: get a new one per try. */
28
+ botToken?: string;
29
+ /** The honeypot: the value of the hidden `website` field, which people leave empty. */
30
+ website?: string;
31
+ /** When the form was shown (`Date.now()` then). Sent as how long it was on screen, so the device's clock doesn't matter. */
32
+ formStartedAt?: number;
33
+ }
18
34
  /** The signed-in person's two-step sign-in and passkeys, from `twoStep()`. */
19
35
  export type TwoStepStatus = Schemas['TwoStepStatus'];
20
36
  /** A passkey on the person's account. */
@@ -77,20 +93,22 @@ export declare class VeroXMAuth {
77
93
  signInWithCredentials(username: string, password: string): Promise<AuthUser | null>;
78
94
  /**
79
95
  * Signs in a built-in account with its email and password. Throws VeroXMApiError with code `email_not_verified` until
80
- * the email is confirmed, and VeroXMTwoStepRequiredError when the person has two-step sign-in on.
96
+ * the email is confirmed, and VeroXMTwoStepRequiredError when the person has two-step sign-in on. Pass `bot` when the
97
+ * project's bot protection covers sign-in (codes `bot_check_required`, `bot_check_failed`, `bot_check_unavailable`).
81
98
  */
82
- signInWithEmail(email: string, password: string): Promise<AuthUser | null>;
99
+ signInWithEmail(email: string, password: string, bot?: BotCheck): Promise<AuthUser | null>;
83
100
  /** Signs out here: the refresh token is revoked on the server too (best effort), and the stored session cleared. */
84
101
  signOut(): Promise<void>;
85
102
  /**
86
103
  * Creates an account. When the project wants emails confirmed, resolves `{ verificationSent: true }` and the person
87
- * gets a 6-digit code (finish with `verifyEmail`); otherwise they're signed in and it resolves `{ user }`.
104
+ * gets a 6-digit code (finish with `verifyEmail`); otherwise they're signed in and it resolves `{ user }`. Add the
105
+ * `BotCheck` fields when the project's bot protection covers sign-up.
88
106
  */
89
107
  signUp(input: {
90
108
  email: string;
91
109
  password: string;
92
110
  name?: string;
93
- }): Promise<{
111
+ } & BotCheck): Promise<{
94
112
  verificationSent: true;
95
113
  } | {
96
114
  user: AuthUser | null;
@@ -99,8 +117,16 @@ export declare class VeroXMAuth {
99
117
  verifyEmail(input: EmailCode): Promise<AuthUser | null>;
100
118
  /** Sends a new confirmation code. Resolves the same whether or not the address has an account. */
101
119
  resendVerification(email: string): Promise<void>;
102
- /** Emails a password reset code. Resolves the same whether or not the address has an account. */
103
- requestPasswordReset(email: string): Promise<void>;
120
+ /**
121
+ * Emails a password reset code. Resolves the same whether or not the address has an account. Pass `bot` when the
122
+ * project's bot protection covers password reset.
123
+ */
124
+ requestPasswordReset(email: string, bot?: BotCheck): Promise<void>;
125
+ /**
126
+ * What a sign-in page should show: whether people can sign up, the social sign-in buttons, passkeys, and the bot
127
+ * check to render (`botProtection`: the provider, its site key, which forms need it, the honeypot and timing).
128
+ */
129
+ getConfig(): Promise<AuthConfig>;
104
130
  /** Sets a new password with the reset code (or the link's token), signs out every other device, and signs in here. */
105
131
  resetPassword(input: EmailCode & {
106
132
  password: string;
package/dist/auth.js CHANGED
@@ -2,6 +2,16 @@ import { rawRequest } from './http.js';
2
2
  import { VeroXMNotAuthenticatedError } from './errors.js';
3
3
  import { createPkce, randomString } from './pkce.js';
4
4
  import { browserPasskeys } from './passkeys.js';
5
+ /** The fields as the API takes them. */
6
+ function botFields(bot) {
7
+ if (!bot)
8
+ return {};
9
+ return {
10
+ ...(bot.botToken ? { botToken: bot.botToken } : {}),
11
+ ...(bot.website !== undefined ? { website: bot.website } : {}),
12
+ ...(typeof bot.formStartedAt === 'number' ? { formElapsedMs: Math.max(0, Date.now() - bot.formStartedAt) } : {}),
13
+ };
14
+ }
5
15
  function defaultPendingStore() {
6
16
  try {
7
17
  if (typeof window !== 'undefined' && window.sessionStorage) {
@@ -69,11 +79,11 @@ export class VeroXMAuth {
69
79
  }
70
80
  /**
71
81
  * Signs in a built-in account with its email and password. Throws VeroXMApiError with code `email_not_verified` until
72
- * the email is confirmed, and VeroXMTwoStepRequiredError when the person has two-step sign-in on.
82
+ * the email is confirmed, and VeroXMTwoStepRequiredError when the person has two-step sign-in on. Pass `bot` when the
83
+ * project's bot protection covers sign-in (codes `bot_check_required`, `bot_check_failed`, `bot_check_unavailable`).
73
84
  */
74
- async signInWithEmail(email, password) {
75
- await this.signInWithCredentials(email, password);
76
- return this.currentUser();
85
+ async signInWithEmail(email, password, bot) {
86
+ return this.signInWith('/auth/token', { username: email, password, ...botFields(bot) });
77
87
  }
78
88
  /** Signs out here: the refresh token is revoked on the server too (best effort), and the stored session cleared. */
79
89
  async signOut() {
@@ -91,10 +101,12 @@ export class VeroXMAuth {
91
101
  // ------------------------------------------------------------------ built-in accounts
92
102
  /**
93
103
  * Creates an account. When the project wants emails confirmed, resolves `{ verificationSent: true }` and the person
94
- * gets a 6-digit code (finish with `verifyEmail`); otherwise they're signed in and it resolves `{ user }`.
104
+ * gets a 6-digit code (finish with `verifyEmail`); otherwise they're signed in and it resolves `{ user }`. Add the
105
+ * `BotCheck` fields when the project's bot protection covers sign-up.
95
106
  */
96
107
  async signUp(input) {
97
- const data = (await this.post('/auth/signup', input));
108
+ const { botToken, website, formStartedAt, ...account } = input;
109
+ const data = (await this.post('/auth/signup', { ...account, ...botFields({ botToken, website, formStartedAt }) }));
98
110
  if ('accessToken' in data) {
99
111
  await this.persistSession(data);
100
112
  return { user: this.currentUser() };
@@ -109,9 +121,19 @@ export class VeroXMAuth {
109
121
  async resendVerification(email) {
110
122
  await this.post('/auth/verify/resend', { email });
111
123
  }
112
- /** Emails a password reset code. Resolves the same whether or not the address has an account. */
113
- async requestPasswordReset(email) {
114
- await this.post('/auth/password/forgot', { email });
124
+ /**
125
+ * Emails a password reset code. Resolves the same whether or not the address has an account. Pass `bot` when the
126
+ * project's bot protection covers password reset.
127
+ */
128
+ async requestPasswordReset(email, bot) {
129
+ await this.post('/auth/password/forgot', { email, ...botFields(bot) });
130
+ }
131
+ /**
132
+ * What a sign-in page should show: whether people can sign up, the social sign-in buttons, passkeys, and the bot
133
+ * check to render (`botProtection`: the provider, its site key, which forms need it, the honeypot and timing).
134
+ */
135
+ async getConfig() {
136
+ return (await rawRequest(this.apiBase, { path: '/auth/config' }));
115
137
  }
116
138
  /** Sets a new password with the reset code (or the link's token), signs out every other device, and signs in here. */
117
139
  async resetPassword(input) {
@@ -0,0 +1,108 @@
1
+ /** The parts of a DOM Element these helpers read (a real Element satisfies it). */
2
+ export interface ElementLike {
3
+ tagName: string;
4
+ id?: string;
5
+ textContent?: string | null;
6
+ parentElement: ElementLike | null;
7
+ getAttribute(name: string): string | null;
8
+ hasAttribute(name: string): boolean;
9
+ /** Space-separated classes (SVG elements have an object here; it is then ignored). */
10
+ className?: unknown;
11
+ }
12
+ /** Clicks count for the closest of these (with the target itself): links, buttons and marked elements. */
13
+ export declare const CLICK_TARGETS = "a, button, [role=button], input[type=submit], input[type=button], [data-veroxm-slot], [data-veroxm-id]";
14
+ /** Longest selector, label and path kept (the api enforces the same caps). */
15
+ export declare const MAX_SELECTOR = 300;
16
+ export declare const MAX_LABEL = 40;
17
+ export declare const MAX_PATH = 500;
18
+ /** True when the element or an ancestor has data-veroxm-ignore. */
19
+ export declare function isIgnored(el: ElementLike | null): boolean;
20
+ /** The link, button or marked element a click on `el` counts for (itself or the closest ancestor), else null. */
21
+ export declare function clickTarget(el: ElementLike | null): ElementLike | null;
22
+ /** Ids that change between page loads or builds (React useId, numbered, hashes) aren't stable enough to select by. */
23
+ export declare function isGeneratedId(id: string): boolean;
24
+ /** Classes worth keeping in a selector: readable names, not hashes (css-1x2y3z, sc-abc, _a1b2c), state or utility variants. */
25
+ export declare function isStableClass(c: string): boolean;
26
+ /**
27
+ * A stable selector for an element (D3): its own anchor if it has one, else a
28
+ * short CSS path (tag, up to two stable classes, :nth-of-type when it has
29
+ * same-tag siblings) of at most 5 levels, starting at the nearest anchored
30
+ * ancestor when one is close. Capped at MAX_SELECTOR characters.
31
+ */
32
+ export declare function selectorFor(el: ElementLike): string;
33
+ /** Whitespace collapsed, trimmed and cut to `max` characters (whole characters, not halves of an emoji). */
34
+ export declare function shortText(text: string | null | undefined, max?: number): string;
35
+ /** True inside data-veroxm-mask, an input, a textarea, a select or an editable region. */
36
+ export declare function isMasked(el: ElementLike | null): boolean;
37
+ /** The text of a link or button (≤ 40 characters), or '' for anything else and anything masked. Never an input's value. */
38
+ export declare function labelFor(el: ElementLike): string;
39
+ /** A link's target for the report: its path on this site, or host + path elsewhere; never the query or hash. */
40
+ export declare function hrefFor(href: string | null, base: string): string;
41
+ /** A value as a fraction 0..1 (non-finite -> 0). */
42
+ export declare function fraction(part: number, whole: number): number;
43
+ /**
44
+ * Rage clicks: 3 or more clicks within 1 second, all within 30 px of the
45
+ * latest. hit() returns true once per burst, on the click that makes it one.
46
+ */
47
+ export declare class RageDetector {
48
+ private readonly count;
49
+ private readonly windowMs;
50
+ private readonly radiusPx;
51
+ private clicks;
52
+ constructor(count?: number, windowMs?: number, radiusPx?: number);
53
+ hit(x: number, y: number, t: number): boolean;
54
+ }
55
+ /**
56
+ * The deepest 25/50/75/100 % bucket of the page seen, from how far down the
57
+ * viewport's bottom edge has been (px) and the page's height. A page that
58
+ * fits in the window counts as 100.
59
+ */
60
+ export declare function scrollBucket(viewportBottom: number, pageHeight: number): 0 | 25 | 50 | 75 | 100;
61
+ export interface SessionState {
62
+ id: string;
63
+ /** When the session last saw an event (ms). */
64
+ last: number;
65
+ /** The campaign touch that started it (campaignKey), or ''. */
66
+ campaign: string;
67
+ }
68
+ /** 30 minutes without an event ends a session. */
69
+ export declare const SESSION_IDLE_MS: number;
70
+ /**
71
+ * What makes a page view a new campaign touch, as a short key: its utm tags,
72
+ * an ad click id, or a link from another site. '' for a direct or internal
73
+ * visit (which never starts a session by itself).
74
+ */
75
+ export declare function campaignKey(url: string, referrer: string): string;
76
+ /**
77
+ * The session an event at `now` belongs to (D4): the current one, unless
78
+ * there is none, it was idle 30 minutes, the UTC day changed, or this page
79
+ * view is a new campaign touch (a non-empty key different from the
80
+ * session's). Returns the state to keep; `newId` makes ids.
81
+ */
82
+ export declare function nextSession(prev: SessionState | null, now: number, touch: string, newId: () => string): SessionState;
83
+ /** A stored session, read leniently (anything unreadable -> null). */
84
+ export declare function parseSession(raw: string | null): SessionState | null;
85
+ /**
86
+ * Cumulative Layout Shift as Google defines it: the largest "session
87
+ * window" of shifts (each less than 1 s after the previous, at most 5 s
88
+ * long), ignoring shifts right after input. Feed it layout-shift entries.
89
+ */
90
+ export declare class ClsWindow {
91
+ value: number;
92
+ private current;
93
+ private first;
94
+ private lastAt;
95
+ add(entry: {
96
+ value: number;
97
+ startTime: number;
98
+ hadRecentInput?: boolean;
99
+ }): void;
100
+ }
101
+ export interface Vitals {
102
+ lcp?: number;
103
+ inp?: number;
104
+ cls?: number;
105
+ ttfb?: number;
106
+ }
107
+ /** Rounded vitals with only what was measured (ms, CLS to 3 decimals); null when nothing was. */
108
+ export declare function vitalsReport(v: Vitals): Vitals | null;
@@ -0,0 +1,323 @@
1
+ // Insights I0 (docs/INSIGHTS-SCOPE.md): the pure parts of automatic capture
2
+ // -- which element a click counts for, its selector (decision D3), its
3
+ // label, rage clicks, scroll depth, sessions (D4) and CLS windows. The
4
+ // tracker wires them to the page (tracker.ts); everything here works on
5
+ // plain values or a minimal element shape, so it is unit-tested without a
6
+ // DOM.
7
+ //
8
+ // Privacy rules kept here (INSIGHTS-SCOPE "Principles"): never an input's
9
+ // value; text only for links and buttons, shortened, and never inside
10
+ // data-veroxm-mask, inputs, textareas or contenteditable; nothing at all
11
+ // for an element inside data-veroxm-ignore.
12
+ /** Clicks count for the closest of these (with the target itself): links, buttons and marked elements. */
13
+ export const CLICK_TARGETS = 'a, button, [role=button], input[type=submit], input[type=button], [data-veroxm-slot], [data-veroxm-id]';
14
+ /** Longest selector, label and path kept (the api enforces the same caps). */
15
+ export const MAX_SELECTOR = 300;
16
+ export const MAX_LABEL = 40;
17
+ export const MAX_PATH = 500;
18
+ const tag = (el) => el.tagName.toLowerCase();
19
+ function isClickTarget(el) {
20
+ const t = tag(el);
21
+ if (t === 'a' || t === 'button')
22
+ return true;
23
+ if (t === 'input') {
24
+ const type = (el.getAttribute('type') ?? '').toLowerCase();
25
+ return type === 'submit' || type === 'button';
26
+ }
27
+ return el.getAttribute('role') === 'button' || el.hasAttribute('data-veroxm-slot') || el.hasAttribute('data-veroxm-id');
28
+ }
29
+ /** True when the element or an ancestor has data-veroxm-ignore. */
30
+ export function isIgnored(el) {
31
+ for (let e = el; e; e = e.parentElement)
32
+ if (e.hasAttribute('data-veroxm-ignore'))
33
+ return true;
34
+ return false;
35
+ }
36
+ /** The link, button or marked element a click on `el` counts for (itself or the closest ancestor), else null. */
37
+ export function clickTarget(el) {
38
+ for (let e = el, depth = 0; e && depth < 25; e = e.parentElement, depth++) {
39
+ if (tag(e) === 'body' || tag(e) === 'html')
40
+ return null;
41
+ if (isClickTarget(e))
42
+ return e;
43
+ }
44
+ return null;
45
+ }
46
+ /** Ids that change between page loads or builds (React useId, numbered, hashes) aren't stable enough to select by. */
47
+ export function isGeneratedId(id) {
48
+ return !id || id.length > 64 || /[:\s]|\d{3,}|^[a-f0-9-]{8,}$|^(ember|react|radix|headlessui|mui|rc-|__next|veroxm-)/i.test(id);
49
+ }
50
+ /** Classes worth keeping in a selector: readable names, not hashes (css-1x2y3z, sc-abc, _a1b2c), state or utility variants. */
51
+ export function isStableClass(c) {
52
+ if (!/^[a-zA-Z][\w-]{0,40}$/.test(c))
53
+ return false; // also drops tailwind variants (hover:..., md:...)
54
+ if (/\d{3,}|^(css|sc|jsx|svelte|emotion|tw)-|__[a-z0-9]{5,}$|^_/.test(c))
55
+ return false;
56
+ if (/^(is|has)-|^(active|hover|focus|focused|open|selected|disabled|visible|hidden|show|current)$/i.test(c))
57
+ return false;
58
+ return !/[A-Z].*\d|\d.*[A-Z]/.test(c) || c.length < 8; // mixed-case hashes like "aB3dE9fG"
59
+ }
60
+ const cssString = (v) => `"${v.replace(/["\\]/g, '\\$&').slice(0, 120)}"`;
61
+ const cssIdent = (v) => v.replace(/[^\w-]/g, (ch) => `\\${ch}`);
62
+ /** The element's own anchor (D3, in order): data-veroxm-id, data-veroxm-slot, a stable id, a data-testid. */
63
+ function anchorOf(el) {
64
+ for (const attr of ['data-veroxm-id', 'data-veroxm-slot']) {
65
+ const v = el.getAttribute(attr);
66
+ if (v)
67
+ return `[${attr}=${cssString(v)}]`;
68
+ }
69
+ const id = el.id || el.getAttribute('id') || '';
70
+ if (id && !isGeneratedId(id))
71
+ return `#${cssIdent(id)}`;
72
+ const testId = el.getAttribute('data-testid');
73
+ if (testId)
74
+ return `[data-testid=${cssString(testId)}]`;
75
+ return null;
76
+ }
77
+ function classesOf(el) {
78
+ const raw = typeof el.className === 'string' ? el.className : el.getAttribute('class') ?? '';
79
+ return raw.split(/\s+/).filter(isStableClass).slice(0, 2);
80
+ }
81
+ /** 1-based position among same-tag siblings, or 0 when it is the only one. Needs `children` on the parent (real DOM). */
82
+ function nthOfType(el) {
83
+ const parent = el.parentElement;
84
+ const kids = parent?.children;
85
+ if (!kids)
86
+ return 0;
87
+ let n = 0;
88
+ let at = 0;
89
+ for (let i = 0; i < kids.length; i++) {
90
+ if (kids[i].tagName === el.tagName) {
91
+ n++;
92
+ if (kids[i] === el)
93
+ at = n;
94
+ }
95
+ }
96
+ return n > 1 ? at : 0;
97
+ }
98
+ /**
99
+ * A stable selector for an element (D3): its own anchor if it has one, else a
100
+ * short CSS path (tag, up to two stable classes, :nth-of-type when it has
101
+ * same-tag siblings) of at most 5 levels, starting at the nearest anchored
102
+ * ancestor when one is close. Capped at MAX_SELECTOR characters.
103
+ */
104
+ export function selectorFor(el) {
105
+ const own = anchorOf(el);
106
+ if (own)
107
+ return own.slice(0, MAX_SELECTOR);
108
+ const parts = [];
109
+ for (let e = el; e && parts.length < 5; e = e.parentElement) {
110
+ const t = tag(e);
111
+ if (t === 'html' || t === 'body')
112
+ break;
113
+ const anchor = e === el ? null : anchorOf(e);
114
+ if (anchor) {
115
+ parts.unshift(anchor);
116
+ break;
117
+ }
118
+ const nth = nthOfType(e);
119
+ parts.unshift(t + classesOf(e).map((c) => `.${c}`).join('') + (nth ? `:nth-of-type(${nth})` : ''));
120
+ }
121
+ let sel = parts.join(' > ');
122
+ // Too long: drop levels from the top (the element's own part is what matters most).
123
+ while (sel.length > MAX_SELECTOR && parts.length > 1) {
124
+ parts.shift();
125
+ sel = parts.join(' > ');
126
+ }
127
+ return sel.slice(0, MAX_SELECTOR);
128
+ }
129
+ /** Whitespace collapsed, trimmed and cut to `max` characters (whole characters, not halves of an emoji). */
130
+ export function shortText(text, max = MAX_LABEL) {
131
+ const t = (text ?? '').replace(/\s+/g, ' ').trim();
132
+ const chars = Array.from(t);
133
+ return chars.length > max ? chars.slice(0, max).join('').trimEnd() : t;
134
+ }
135
+ /** True inside data-veroxm-mask, an input, a textarea, a select or an editable region. */
136
+ export function isMasked(el) {
137
+ for (let e = el; e; e = e.parentElement) {
138
+ if (e.hasAttribute('data-veroxm-mask'))
139
+ return true;
140
+ const t = tag(e);
141
+ if (t === 'input' || t === 'textarea' || t === 'select')
142
+ return true;
143
+ const ce = e.getAttribute('contenteditable');
144
+ if (ce !== null && ce !== 'false')
145
+ return true;
146
+ }
147
+ return false;
148
+ }
149
+ /** The text of a link or button (≤ 40 characters), or '' for anything else and anything masked. Never an input's value. */
150
+ export function labelFor(el) {
151
+ const t = tag(el);
152
+ const isButtonish = t === 'a' || t === 'button' || el.getAttribute('role') === 'button';
153
+ if (!isButtonish || isMasked(el))
154
+ return '';
155
+ return shortText(el.textContent) || shortText(el.getAttribute('aria-label'));
156
+ }
157
+ /** A link's target for the report: its path on this site, or host + path elsewhere; never the query or hash. */
158
+ export function hrefFor(href, base) {
159
+ if (!href)
160
+ return '';
161
+ try {
162
+ const u = new URL(href, base);
163
+ if (u.protocol !== 'http:' && u.protocol !== 'https:')
164
+ return '';
165
+ const own = new URL(base);
166
+ return (u.host === own.host ? u.pathname : `${u.host}${u.pathname}`).slice(0, MAX_PATH);
167
+ }
168
+ catch {
169
+ return '';
170
+ }
171
+ }
172
+ /** A value as a fraction 0..1 (non-finite -> 0). */
173
+ export function fraction(part, whole) {
174
+ if (!(whole > 0) || !Number.isFinite(part))
175
+ return 0;
176
+ return Math.round(Math.min(1, Math.max(0, part / whole)) * 1000) / 1000;
177
+ }
178
+ /**
179
+ * Rage clicks: 3 or more clicks within 1 second, all within 30 px of the
180
+ * latest. hit() returns true once per burst, on the click that makes it one.
181
+ */
182
+ export class RageDetector {
183
+ constructor(count = 3, windowMs = 1000, radiusPx = 30) {
184
+ this.count = count;
185
+ this.windowMs = windowMs;
186
+ this.radiusPx = radiusPx;
187
+ this.clicks = [];
188
+ }
189
+ hit(x, y, t) {
190
+ const r2 = this.radiusPx * this.radiusPx;
191
+ this.clicks = this.clicks.filter((c) => t - c.t <= this.windowMs && (c.x - x) ** 2 + (c.y - y) ** 2 <= r2);
192
+ this.clicks.push({ x, y, t });
193
+ if (this.clicks.length >= this.count) {
194
+ this.clicks = [];
195
+ return true;
196
+ }
197
+ return false;
198
+ }
199
+ }
200
+ /**
201
+ * The deepest 25/50/75/100 % bucket of the page seen, from how far down the
202
+ * viewport's bottom edge has been (px) and the page's height. A page that
203
+ * fits in the window counts as 100.
204
+ */
205
+ export function scrollBucket(viewportBottom, pageHeight) {
206
+ if (!(pageHeight > 0) || viewportBottom >= pageHeight - 2)
207
+ return 100;
208
+ const pct = (viewportBottom / pageHeight) * 100;
209
+ return pct >= 75 ? 75 : pct >= 50 ? 50 : pct >= 25 ? 25 : 0;
210
+ }
211
+ /** 30 minutes without an event ends a session. */
212
+ export const SESSION_IDLE_MS = 30 * 60 * 1000;
213
+ const CLICK_IDS = ['gclid', 'gbraid', 'wbraid', 'msclkid', 'fbclid', 'ttclid', 'li_fat_id', 'twclid', 'dclid'];
214
+ /** Small non-cryptographic hash, so a stored campaign key never keeps a click id itself. */
215
+ function hash(s) {
216
+ let h = 5381;
217
+ for (let i = 0; i < s.length; i++)
218
+ h = ((h << 5) + h + s.charCodeAt(i)) | 0;
219
+ return (h >>> 0).toString(36);
220
+ }
221
+ /**
222
+ * What makes a page view a new campaign touch, as a short key: its utm tags,
223
+ * an ad click id, or a link from another site. '' for a direct or internal
224
+ * visit (which never starts a session by itself).
225
+ */
226
+ export function campaignKey(url, referrer) {
227
+ let u;
228
+ try {
229
+ u = new URL(url);
230
+ }
231
+ catch {
232
+ return '';
233
+ }
234
+ const q = u.searchParams;
235
+ const utm = ['utm_source', 'utm_medium', 'utm_campaign'].map((k) => q.get(k) ?? '');
236
+ if (utm.some(Boolean))
237
+ return `u${hash(utm.join('|'))}`;
238
+ const click = CLICK_IDS.find((k) => q.get(k));
239
+ if (click)
240
+ return `c${hash(`${click}=${q.get(click)}`)}`;
241
+ if (referrer) {
242
+ try {
243
+ const host = new URL(referrer).host;
244
+ if (host && host !== u.host)
245
+ return `r${hash(host)}`;
246
+ }
247
+ catch {
248
+ /* not a URL */
249
+ }
250
+ }
251
+ return '';
252
+ }
253
+ const utcDay = (ms) => Math.floor(ms / 86400000);
254
+ /**
255
+ * The session an event at `now` belongs to (D4): the current one, unless
256
+ * there is none, it was idle 30 minutes, the UTC day changed, or this page
257
+ * view is a new campaign touch (a non-empty key different from the
258
+ * session's). Returns the state to keep; `newId` makes ids.
259
+ */
260
+ export function nextSession(prev, now, touch, newId) {
261
+ const fresh = !prev ||
262
+ !prev.id ||
263
+ now - prev.last > SESSION_IDLE_MS ||
264
+ utcDay(now) !== utcDay(prev.last) ||
265
+ (touch !== '' && touch !== prev.campaign);
266
+ if (fresh)
267
+ return { id: newId(), last: now, campaign: touch };
268
+ return { id: prev.id, last: Math.max(prev.last, now), campaign: prev.campaign };
269
+ }
270
+ /** A stored session, read leniently (anything unreadable -> null). */
271
+ export function parseSession(raw) {
272
+ if (!raw)
273
+ return null;
274
+ try {
275
+ const s = JSON.parse(raw);
276
+ return typeof s.id === 'string' && /^[\w-]{1,64}$/.test(s.id) && typeof s.last === 'number'
277
+ ? { id: s.id, last: s.last, campaign: typeof s.campaign === 'string' ? s.campaign : '' }
278
+ : null;
279
+ }
280
+ catch {
281
+ return null;
282
+ }
283
+ }
284
+ // ---------------------------------------------------------------- page speed
285
+ /**
286
+ * Cumulative Layout Shift as Google defines it: the largest "session
287
+ * window" of shifts (each less than 1 s after the previous, at most 5 s
288
+ * long), ignoring shifts right after input. Feed it layout-shift entries.
289
+ */
290
+ export class ClsWindow {
291
+ constructor() {
292
+ this.value = 0;
293
+ this.current = 0;
294
+ this.first = 0;
295
+ this.lastAt = 0;
296
+ }
297
+ add(entry) {
298
+ if (entry.hadRecentInput)
299
+ return;
300
+ if (this.current && entry.startTime - this.lastAt < 1000 && entry.startTime - this.first < 5000) {
301
+ this.current += entry.value;
302
+ }
303
+ else {
304
+ this.current = entry.value;
305
+ this.first = entry.startTime;
306
+ }
307
+ this.lastAt = entry.startTime;
308
+ this.value = Math.max(this.value, this.current);
309
+ }
310
+ }
311
+ /** Rounded vitals with only what was measured (ms, CLS to 3 decimals); null when nothing was. */
312
+ export function vitalsReport(v) {
313
+ const out = {};
314
+ if (v.lcp !== undefined && v.lcp >= 0)
315
+ out.lcp = Math.round(v.lcp);
316
+ if (v.inp !== undefined && v.inp >= 0)
317
+ out.inp = Math.round(v.inp);
318
+ if (v.cls !== undefined && v.cls >= 0)
319
+ out.cls = Math.round(v.cls * 1000) / 1000;
320
+ if (v.ttfb !== undefined && v.ttfb >= 0)
321
+ out.ttfb = Math.round(v.ttfb);
322
+ return Object.keys(out).length ? out : null;
323
+ }
package/dist/client.d.ts CHANGED
@@ -16,6 +16,17 @@ export interface VeroXMAppOptions {
16
16
  tokenStorage?: TokenStorage;
17
17
  /** Where a social sign-in keeps its verifier while the person is at the provider. Defaults to sessionStorage in a browser. */
18
18
  pendingStore?: PendingStore;
19
+ /**
20
+ * Gives up on a request after this many milliseconds with `VeroXMTimeoutError`. A call can set its own `timeoutMs`.
21
+ * Default: no limit. File uploads aren't limited by this.
22
+ */
23
+ timeoutMs?: number;
24
+ /**
25
+ * Extra attempts (0 to 5) for GET and HEAD requests that fail with a network error, a timeout, or 429, 502, 503 or
26
+ * 504, waiting 300 ms, 600 ms, 1.2 s... (or the API's Retry-After, up to 10 s) in between. Writes are never retried.
27
+ * Default: 0. A function answering GET runs again on a retry, so keep those safe to repeat.
28
+ */
29
+ retries?: number;
19
30
  }
20
31
  /**
21
32
  * The SDK's entry point -- one `initializeApp()` call, Firebase-style,
@@ -33,6 +44,8 @@ export declare class VeroXMApp {
33
44
  /** The project's forms and responses (server keys with forms:read). */
34
45
  readonly forms: FormsResource;
35
46
  private readonly apiBase;
47
+ private readonly timeoutMs;
48
+ private readonly retries;
36
49
  private constructor();
37
50
  static initializeApp(options: VeroXMAppOptions): VeroXMApp;
38
51
  /** Typed access to one content collection's entries (list/get/create/update/delete/search). */