@qoretechnologies/reqraft 0.10.56 → 0.10.57-pr.127.g0a792ea
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/.claude/CLAUDE.md +1 -0
- package/README.md +20 -0
- package/design/TRACKING.md +290 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/tracking/browser/attach.d.ts +8 -0
- package/dist/tracking/browser/attach.d.ts.map +1 -0
- package/dist/tracking/browser/attach.js +182 -0
- package/dist/tracking/browser/attach.js.map +1 -0
- package/dist/tracking/browser/env.d.ts +14 -0
- package/dist/tracking/browser/env.d.ts.map +1 -0
- package/dist/tracking/browser/env.js +150 -0
- package/dist/tracking/browser/env.js.map +1 -0
- package/dist/tracking/core/consent.d.ts +21 -0
- package/dist/tracking/core/consent.d.ts.map +1 -0
- package/dist/tracking/core/consent.js +39 -0
- package/dist/tracking/core/consent.js.map +1 -0
- package/dist/tracking/core/engagement.d.ts +20 -0
- package/dist/tracking/core/engagement.d.ts.map +1 -0
- package/dist/tracking/core/engagement.js +52 -0
- package/dist/tracking/core/engagement.js.map +1 -0
- package/dist/tracking/core/experiments.d.ts +109 -0
- package/dist/tracking/core/experiments.d.ts.map +1 -0
- package/dist/tracking/core/experiments.js +294 -0
- package/dist/tracking/core/experiments.js.map +1 -0
- package/dist/tracking/core/hash.d.ts +16 -0
- package/dist/tracking/core/hash.d.ts.map +1 -0
- package/dist/tracking/core/hash.js +31 -0
- package/dist/tracking/core/hash.js.map +1 -0
- package/dist/tracking/core/ids.d.ts +6 -0
- package/dist/tracking/core/ids.d.ts.map +1 -0
- package/dist/tracking/core/ids.js +31 -0
- package/dist/tracking/core/ids.js.map +1 -0
- package/dist/tracking/core/observable.d.ts +12 -0
- package/dist/tracking/core/observable.d.ts.map +1 -0
- package/dist/tracking/core/observable.js +32 -0
- package/dist/tracking/core/observable.js.map +1 -0
- package/dist/tracking/core/queue.d.ts +47 -0
- package/dist/tracking/core/queue.d.ts.map +1 -0
- package/dist/tracking/core/queue.js +205 -0
- package/dist/tracking/core/queue.js.map +1 -0
- package/dist/tracking/core/sections.d.ts +54 -0
- package/dist/tracking/core/sections.d.ts.map +1 -0
- package/dist/tracking/core/sections.js +156 -0
- package/dist/tracking/core/sections.js.map +1 -0
- package/dist/tracking/core/storage.d.ts +15 -0
- package/dist/tracking/core/storage.d.ts.map +1 -0
- package/dist/tracking/core/storage.js +72 -0
- package/dist/tracking/core/storage.js.map +1 -0
- package/dist/tracking/core/tracker.d.ts +122 -0
- package/dist/tracking/core/tracker.d.ts.map +1 -0
- package/dist/tracking/core/tracker.js +390 -0
- package/dist/tracking/core/tracker.js.map +1 -0
- package/dist/tracking/core/types.d.ts +130 -0
- package/dist/tracking/core/types.d.ts.map +1 -0
- package/dist/tracking/core/types.js +69 -0
- package/dist/tracking/core/types.js.map +1 -0
- package/dist/tracking/core/utm.d.ts +6 -0
- package/dist/tracking/core/utm.d.ts.map +1 -0
- package/dist/tracking/core/utm.js +30 -0
- package/dist/tracking/core/utm.js.map +1 -0
- package/dist/tracking/index.d.ts +46 -0
- package/dist/tracking/index.d.ts.map +1 -0
- package/dist/tracking/index.js +91 -0
- package/dist/tracking/index.js.map +1 -0
- package/dist/tracking/markup.d.ts +12 -0
- package/dist/tracking/markup.d.ts.map +1 -0
- package/dist/tracking/markup.js +19 -0
- package/dist/tracking/markup.js.map +1 -0
- package/dist/tracking/react/Experiment.d.ts +23 -0
- package/dist/tracking/react/Experiment.d.ts.map +1 -0
- package/dist/tracking/react/Experiment.js +28 -0
- package/dist/tracking/react/Experiment.js.map +1 -0
- package/dist/tracking/react/TrackingProvider.d.ts +26 -0
- package/dist/tracking/react/TrackingProvider.d.ts.map +1 -0
- package/dist/tracking/react/TrackingProvider.js +45 -0
- package/dist/tracking/react/TrackingProvider.js.map +1 -0
- package/dist/tracking/react/hooks.d.ts +39 -0
- package/dist/tracking/react/hooks.d.ts.map +1 -0
- package/dist/tracking/react/hooks.js +96 -0
- package/dist/tracking/react/hooks.js.map +1 -0
- package/dist/tracking/react/index.d.ts +7 -0
- package/dist/tracking/react/index.d.ts.map +1 -0
- package/dist/tracking/react/index.js +17 -0
- package/dist/tracking/react/index.js.map +1 -0
- package/dist/tracking/testing.d.ts +40 -0
- package/dist/tracking/testing.d.ts.map +1 -0
- package/dist/tracking/testing.js +140 -0
- package/dist/tracking/testing.js.map +1 -0
- package/dist/tracking/ui/ExperimentCard.d.ts +55 -0
- package/dist/tracking/ui/ExperimentCard.d.ts.map +1 -0
- package/dist/tracking/ui/ExperimentCard.js +340 -0
- package/dist/tracking/ui/ExperimentCard.js.map +1 -0
- package/dist/tracking/ui/ExperimentsOverlay.d.ts +59 -0
- package/dist/tracking/ui/ExperimentsOverlay.d.ts.map +1 -0
- package/dist/tracking/ui/ExperimentsOverlay.js +359 -0
- package/dist/tracking/ui/ExperimentsOverlay.js.map +1 -0
- package/dist/tracking/ui/anchor.d.ts +107 -0
- package/dist/tracking/ui/anchor.d.ts.map +1 -0
- package/dist/tracking/ui/anchor.js +108 -0
- package/dist/tracking/ui/anchor.js.map +1 -0
- package/dist/tracking/ui/card.d.ts +121 -0
- package/dist/tracking/ui/card.d.ts.map +1 -0
- package/dist/tracking/ui/card.js +417 -0
- package/dist/tracking/ui/card.js.map +1 -0
- package/dist/tracking/ui/client.d.ts +42 -0
- package/dist/tracking/ui/client.d.ts.map +1 -0
- package/dist/tracking/ui/client.js +123 -0
- package/dist/tracking/ui/client.js.map +1 -0
- package/dist/tracking/ui/index.d.ts +20 -0
- package/dist/tracking/ui/index.d.ts.map +1 -0
- package/dist/tracking/ui/index.js +60 -0
- package/dist/tracking/ui/index.js.map +1 -0
- package/dist/tracking/ui/types.d.ts +120 -0
- package/dist/tracking/ui/types.d.ts.map +1 -0
- package/dist/tracking/ui/types.js +8 -0
- package/dist/tracking/ui/types.js.map +1 -0
- package/dist/tracking/ui/useExperimentsAdmin.d.ts +31 -0
- package/dist/tracking/ui/useExperimentsAdmin.d.ts.map +1 -0
- package/dist/tracking/ui/useExperimentsAdmin.js +136 -0
- package/dist/tracking/ui/useExperimentsAdmin.js.map +1 -0
- package/package.json +1 -1
- package/src/index.tsx +5 -0
- package/src/stories/tracking.tsx +206 -0
- package/src/tracking/browser/attach.ts +186 -0
- package/src/tracking/browser/env.ts +78 -0
- package/src/tracking/core/consent.ts +37 -0
- package/src/tracking/core/engagement.ts +47 -0
- package/src/tracking/core/experiments.ts +258 -0
- package/src/tracking/core/hash.ts +26 -0
- package/src/tracking/core/ids.ts +25 -0
- package/src/tracking/core/observable.ts +23 -0
- package/src/tracking/core/queue.ts +131 -0
- package/src/tracking/core/sections.ts +166 -0
- package/src/tracking/core/storage.ts +69 -0
- package/src/tracking/core/tracker.ts +417 -0
- package/src/tracking/core/types.ts +162 -0
- package/src/tracking/core/utm.ts +23 -0
- package/src/tracking/index.ts +72 -0
- package/src/tracking/markup.ts +17 -0
- package/src/tracking/react/Experiment.tsx +44 -0
- package/src/tracking/react/TrackingProvider.tsx +56 -0
- package/src/tracking/react/hooks.ts +106 -0
- package/src/tracking/react/index.ts +13 -0
- package/src/tracking/testing.ts +108 -0
- package/src/tracking/ui/ExperimentCard.stories.tsx +290 -0
- package/src/tracking/ui/ExperimentCard.tsx +581 -0
- package/src/tracking/ui/ExperimentsOverlay.stories.tsx +155 -0
- package/src/tracking/ui/ExperimentsOverlay.tsx +437 -0
- package/src/tracking/ui/anchor.ts +180 -0
- package/src/tracking/ui/card.ts +464 -0
- package/src/tracking/ui/client.ts +117 -0
- package/src/tracking/ui/index.ts +77 -0
- package/src/tracking/ui/types.ts +110 -0
- package/src/tracking/ui/useExperimentsAdmin.ts +103 -0
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { effectiveRatio } from '../core/sections';
|
|
2
|
+
import type { Tracker } from '../core/tracker';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Connects a `Tracker` to the page: tab visibility, page leave, interactions,
|
|
6
|
+
* scroll depth, the heartbeat, section visibility (IntersectionObserver on every
|
|
7
|
+
* `[data-track-section]`) and clicks (one delegated listener for
|
|
8
|
+
* `[data-track-click]`). Returns a function that removes all of it.
|
|
9
|
+
*
|
|
10
|
+
* Markup contract (see design/TRACKING.md):
|
|
11
|
+
* data-track-section="<id>" a section: visible time, seen, exit section
|
|
12
|
+
* data-track-click="<target>" a tracked click (`get-started`, `contact`, …)
|
|
13
|
+
* data-track-placement="<where>" optional; defaults to the enclosing section id
|
|
14
|
+
* data-track-label="<text>" optional; defaults to the element's text
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const SECTION_SELECTOR = '[data-track-section]';
|
|
18
|
+
const THRESHOLDS = Array.from({ length: 21 }, (_, i) => i / 20);
|
|
19
|
+
const TICK_MS = 250;
|
|
20
|
+
const ACTIVITY_EVENTS = ['pointerdown', 'keydown', 'wheel', 'touchstart', 'mousemove', 'scroll'] as const;
|
|
21
|
+
|
|
22
|
+
export interface IAttached {
|
|
23
|
+
detach: () => void;
|
|
24
|
+
/** Observes an element under a synthetic id (an experiment's wrapped element); not in the page summary. */
|
|
25
|
+
observeElement: (el: Element, id: string) => () => void;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const clean = (s: string | null | undefined, max = 80) => {
|
|
29
|
+
const t = (s ?? '').replace(/\s+/g, ' ').trim();
|
|
30
|
+
return t ? t.slice(0, max) : null;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export const attachToPage = (tracker: Tracker, heartbeatMs: number): IAttached => {
|
|
34
|
+
const cleanup: (() => void)[] = [];
|
|
35
|
+
const on = (target: EventTarget, type: string, fn: EventListener, opts?: AddEventListenerOptions) => {
|
|
36
|
+
target.addEventListener(type, fn, opts);
|
|
37
|
+
cleanup.push(() => target.removeEventListener(type, fn, opts));
|
|
38
|
+
};
|
|
39
|
+
const safe = (fn: () => void) => () => {
|
|
40
|
+
try {
|
|
41
|
+
fn();
|
|
42
|
+
} catch {
|
|
43
|
+
/* never into the page */
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
// ── tab visibility and page leave
|
|
48
|
+
on(document, 'visibilitychange', safe(() => tracker.setTabVisible(document.visibilityState === 'visible')));
|
|
49
|
+
on(window, 'pagehide', safe(() => tracker.leave()));
|
|
50
|
+
if (document.visibilityState !== 'visible') tracker.setTabVisible(false);
|
|
51
|
+
|
|
52
|
+
// ── engagement (throttled to one signal per second)
|
|
53
|
+
let lastActivity = 0;
|
|
54
|
+
const activity = safe(() => {
|
|
55
|
+
const now = Date.now();
|
|
56
|
+
if (now - lastActivity < 1000) return;
|
|
57
|
+
lastActivity = now;
|
|
58
|
+
tracker.activity();
|
|
59
|
+
});
|
|
60
|
+
ACTIVITY_EVENTS.forEach((t) => on(window, t, activity, { passive: true, capture: true }));
|
|
61
|
+
|
|
62
|
+
// ── scroll depth (once per frame)
|
|
63
|
+
let scrollQueued = false;
|
|
64
|
+
const measureScroll = safe(() => {
|
|
65
|
+
scrollQueued = false;
|
|
66
|
+
const doc = document.documentElement;
|
|
67
|
+
const scrollable = Math.max(doc.scrollHeight, document.body?.scrollHeight ?? 0);
|
|
68
|
+
const seen = window.scrollY + window.innerHeight;
|
|
69
|
+
tracker.scrolled(scrollable > 0 ? (seen / scrollable) * 100 : 100);
|
|
70
|
+
});
|
|
71
|
+
on(window, 'scroll', () => {
|
|
72
|
+
if (scrollQueued) return;
|
|
73
|
+
scrollQueued = true;
|
|
74
|
+
requestAnimationFrame(measureScroll);
|
|
75
|
+
}, { passive: true });
|
|
76
|
+
|
|
77
|
+
// ── heartbeat while visible, and the section clock
|
|
78
|
+
const heartbeat = setInterval(safe(() => document.visibilityState === 'visible' && tracker.heartbeat()), heartbeatMs);
|
|
79
|
+
const tick = setInterval(safe(() => tracker.sections.tick(tracker.now())), TICK_MS);
|
|
80
|
+
cleanup.push(() => clearInterval(heartbeat), () => clearInterval(tick));
|
|
81
|
+
|
|
82
|
+
// ── sections
|
|
83
|
+
const ratios = new Map<Element, number>();
|
|
84
|
+
const ids = new Map<Element, string>();
|
|
85
|
+
const report = new Map<string, boolean>();
|
|
86
|
+
const apply = (id: string) => {
|
|
87
|
+
let best = 0;
|
|
88
|
+
ids.forEach((other, el) => other === id && (best = Math.max(best, ratios.get(el) ?? 0)));
|
|
89
|
+
tracker.sections.update(id, best, tracker.now());
|
|
90
|
+
};
|
|
91
|
+
const io =
|
|
92
|
+
typeof IntersectionObserver !== 'undefined'
|
|
93
|
+
? new IntersectionObserver(
|
|
94
|
+
(entries) =>
|
|
95
|
+
safe(() => {
|
|
96
|
+
const vh = window.innerHeight || document.documentElement.clientHeight;
|
|
97
|
+
entries.forEach((e) => {
|
|
98
|
+
const id = ids.get(e.target);
|
|
99
|
+
if (!id) return;
|
|
100
|
+
ratios.set(e.target, effectiveRatio(e.intersectionRatio, e.intersectionRect.height, e.rootBounds?.height ?? vh));
|
|
101
|
+
apply(id);
|
|
102
|
+
});
|
|
103
|
+
})(),
|
|
104
|
+
{ threshold: THRESHOLDS },
|
|
105
|
+
)
|
|
106
|
+
: null;
|
|
107
|
+
|
|
108
|
+
const track = (el: Element, id: string, inSummary: boolean) => {
|
|
109
|
+
if (ids.get(el) === id) return;
|
|
110
|
+
ids.set(el, id);
|
|
111
|
+
report.set(id, (report.get(id) ?? false) || inSummary);
|
|
112
|
+
tracker.sections.register(id, inSummary);
|
|
113
|
+
io?.observe(el);
|
|
114
|
+
};
|
|
115
|
+
const untrack = (el: Element) => {
|
|
116
|
+
const id = ids.get(el);
|
|
117
|
+
if (!id) return;
|
|
118
|
+
io?.unobserve(el);
|
|
119
|
+
ids.delete(el);
|
|
120
|
+
ratios.delete(el);
|
|
121
|
+
apply(id);
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const scan = safe(() => {
|
|
125
|
+
const present = new Set<Element>(Array.from(document.querySelectorAll(SECTION_SELECTOR)));
|
|
126
|
+
ids.forEach((id, el) => report.get(id) && !present.has(el) && !el.isConnected && untrack(el));
|
|
127
|
+
present.forEach((el) => {
|
|
128
|
+
const id = (el as HTMLElement).dataset.trackSection;
|
|
129
|
+
if (id) track(el, id, true);
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
// Re-measure everything at a new page view: the section clock starts from zero,
|
|
134
|
+
// and re-observing makes the observer report every element's current state.
|
|
135
|
+
const remeasure = safe(() => {
|
|
136
|
+
scan();
|
|
137
|
+
ids.forEach((_id, el) => {
|
|
138
|
+
io?.unobserve(el);
|
|
139
|
+
io?.observe(el);
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
cleanup.push(tracker.pageViewId.subscribe(remeasure));
|
|
143
|
+
|
|
144
|
+
let scanTimer: ReturnType<typeof setTimeout> | null = null;
|
|
145
|
+
const mo =
|
|
146
|
+
typeof MutationObserver !== 'undefined'
|
|
147
|
+
? new MutationObserver(() => {
|
|
148
|
+
if (scanTimer) return;
|
|
149
|
+
scanTimer = setTimeout(() => {
|
|
150
|
+
scanTimer = null;
|
|
151
|
+
scan();
|
|
152
|
+
}, 150);
|
|
153
|
+
})
|
|
154
|
+
: null;
|
|
155
|
+
mo?.observe(document.body, { childList: true, subtree: true });
|
|
156
|
+
scan();
|
|
157
|
+
cleanup.push(() => {
|
|
158
|
+
mo?.disconnect();
|
|
159
|
+
io?.disconnect();
|
|
160
|
+
if (scanTimer) clearTimeout(scanTimer);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
// ── clicks: one delegated listener
|
|
164
|
+
const onClick = (e: Event) =>
|
|
165
|
+
safe(() => {
|
|
166
|
+
const el = (e.target as Element | null)?.closest?.('[data-track-click]') as HTMLElement | null;
|
|
167
|
+
if (!el) return;
|
|
168
|
+
const d = el.dataset;
|
|
169
|
+
const link = el.closest('a');
|
|
170
|
+
tracker.click({
|
|
171
|
+
target: d.trackClick || 'unknown',
|
|
172
|
+
placement: d.trackPlacement || (el.closest(SECTION_SELECTOR) as HTMLElement | null)?.dataset.trackSection || null,
|
|
173
|
+
label: clean(d.trackLabel) ?? clean(el.innerText) ?? clean(el.getAttribute('aria-label')),
|
|
174
|
+
href: d.trackHref || link?.href || null,
|
|
175
|
+
});
|
|
176
|
+
})();
|
|
177
|
+
on(document, 'click', onClick, { capture: true });
|
|
178
|
+
|
|
179
|
+
return {
|
|
180
|
+
detach: () => cleanup.forEach((fn) => fn()),
|
|
181
|
+
observeElement: (el, id) => {
|
|
182
|
+
track(el, id, false);
|
|
183
|
+
return () => untrack(el);
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { ITransport } from '../core/queue';
|
|
2
|
+
import { safeStorage } from '../core/storage';
|
|
3
|
+
import type { IPageInfo, ITrackerEnv } from '../core/tracker';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Sends a batch. `beacon` (page going away): `navigator.sendBeacon`, falling back
|
|
7
|
+
* to `fetch(…, { keepalive: true })` when the beacon is refused (too big, or the
|
|
8
|
+
* browser has none). Any HTTP answer counts as delivered — the collector always
|
|
9
|
+
* answers 204, and a 404 (collector not installed) must not turn into a retry loop;
|
|
10
|
+
* only a network error keeps the batch for the next flush.
|
|
11
|
+
*/
|
|
12
|
+
export const browserTransport = (endpoint: string): ITransport => ({
|
|
13
|
+
async send(body, mode) {
|
|
14
|
+
if (mode === 'beacon' && typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
|
|
15
|
+
try {
|
|
16
|
+
if (navigator.sendBeacon(endpoint, new Blob([body], { type: 'application/json' }))) return true;
|
|
17
|
+
} catch {
|
|
18
|
+
/* fall through to fetch */
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
await fetch(endpoint, {
|
|
23
|
+
method: 'POST',
|
|
24
|
+
body,
|
|
25
|
+
headers: { 'Content-Type': 'application/json' },
|
|
26
|
+
// Batches stay under 60 KB (queue.ts), inside keepalive's 64 KB budget.
|
|
27
|
+
keepalive: true,
|
|
28
|
+
credentials: 'same-origin',
|
|
29
|
+
});
|
|
30
|
+
return true;
|
|
31
|
+
} catch {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const fetchJson = async (url: string, timeoutMs: number): Promise<unknown> => {
|
|
38
|
+
const ctrl = typeof AbortController !== 'undefined' ? new AbortController() : undefined;
|
|
39
|
+
const timer = setTimeout(() => ctrl?.abort(), timeoutMs);
|
|
40
|
+
try {
|
|
41
|
+
const res = await fetch(url, { headers: { Accept: 'application/json' }, signal: ctrl?.signal, credentials: 'same-origin' });
|
|
42
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
43
|
+
return await res.json();
|
|
44
|
+
} finally {
|
|
45
|
+
clearTimeout(timer);
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** desktop / tablet / mobile from the user agent (targeting only; the server classifies for reports). */
|
|
50
|
+
export const deviceOf = (ua: string): IPageInfo['device'] => {
|
|
51
|
+
if (/iPad|Tablet|PlayBook|Silk|Android(?!.*Mobile)/i.test(ua)) return 'tablet';
|
|
52
|
+
if (/Mobi|iPhone|iPod|Android.*Mobile|Opera Mini|IEMobile/i.test(ua)) return 'mobile';
|
|
53
|
+
return 'desktop';
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const readPage = (): IPageInfo => ({
|
|
57
|
+
origin: window.location.origin,
|
|
58
|
+
path: window.location.pathname,
|
|
59
|
+
search: window.location.search,
|
|
60
|
+
title: document.title,
|
|
61
|
+
referrer: document.referrer,
|
|
62
|
+
lang: navigator.language || 'en',
|
|
63
|
+
viewport: [window.innerWidth, window.innerHeight],
|
|
64
|
+
device: deviceOf(navigator.userAgent || ''),
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
export const browserEnv = (endpoint: string): ITrackerEnv => ({
|
|
68
|
+
local: safeStorage(() => window.localStorage),
|
|
69
|
+
session: safeStorage(() => window.sessionStorage),
|
|
70
|
+
transport: browserTransport(endpoint),
|
|
71
|
+
now: () => Date.now(),
|
|
72
|
+
setTimer: (fn, ms) => setTimeout(fn, ms),
|
|
73
|
+
clearTimer: (h) => clearTimeout(h as ReturnType<typeof setTimeout>),
|
|
74
|
+
page: readPage,
|
|
75
|
+
fetchJson,
|
|
76
|
+
// eslint-disable-next-line no-console
|
|
77
|
+
log: (...args) => console.info(...args),
|
|
78
|
+
});
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { IStorage } from './storage';
|
|
2
|
+
import { Observable } from './observable';
|
|
3
|
+
import { KEYS, type TConsentState, type TStorageKeys } from './types';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The visitor's answer (§3 of the contract): `localStorage["<prefix>consent"]` is
|
|
7
|
+
* `granted` | `denied`, `<prefix>consent.v` the version of the text they answered
|
|
8
|
+
* (prefix `qa.` by default). An answer to an older version counts as no answer, so
|
|
9
|
+
* the consent prompt asks again.
|
|
10
|
+
*/
|
|
11
|
+
export class ConsentStore {
|
|
12
|
+
readonly state: Observable<TConsentState>;
|
|
13
|
+
|
|
14
|
+
constructor(
|
|
15
|
+
private readonly storage: IStorage,
|
|
16
|
+
private readonly version: number,
|
|
17
|
+
private readonly keys: TStorageKeys = KEYS,
|
|
18
|
+
) {
|
|
19
|
+
this.state = new Observable<TConsentState>(this.read());
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
private read(): TConsentState {
|
|
23
|
+
const answer = this.storage.get(this.keys.consent);
|
|
24
|
+
const version = Number(this.storage.get(this.keys.consentVersion) ?? 0);
|
|
25
|
+
if ((answer === 'granted' || answer === 'denied') && version >= this.version) return answer;
|
|
26
|
+
return 'unknown';
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
get = (): TConsentState => this.state.get();
|
|
30
|
+
granted = (): boolean => this.state.get() === 'granted';
|
|
31
|
+
|
|
32
|
+
answer(state: 'granted' | 'denied') {
|
|
33
|
+
this.storage.set(this.keys.consent, state);
|
|
34
|
+
this.storage.set(this.keys.consentVersion, String(this.version));
|
|
35
|
+
this.state.set(state);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Engaged time: the tab is visible AND the visitor did something (scroll, pointer,
|
|
3
|
+
* key, touch) within the last `windowMs`. Each interaction extends the engaged
|
|
4
|
+
* stretch to `interaction + windowMs`; hiding the tab ends it at once.
|
|
5
|
+
*/
|
|
6
|
+
export class EngagementClock {
|
|
7
|
+
private engagedMs = 0;
|
|
8
|
+
/** Start and end of the current engaged stretch (end is in the future while active). */
|
|
9
|
+
private from: number | null = null;
|
|
10
|
+
private until = 0;
|
|
11
|
+
private tabVisible = true;
|
|
12
|
+
|
|
13
|
+
constructor(private readonly windowMs: number) {}
|
|
14
|
+
|
|
15
|
+
reset() {
|
|
16
|
+
this.engagedMs = 0;
|
|
17
|
+
this.from = null;
|
|
18
|
+
this.until = 0;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
activity(now: number) {
|
|
22
|
+
if (!this.tabVisible) return;
|
|
23
|
+
if (this.from != null && now <= this.until) {
|
|
24
|
+
this.until = now + this.windowMs;
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
this.close(now);
|
|
28
|
+
this.from = now;
|
|
29
|
+
this.until = now + this.windowMs;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
setTabVisible(visible: boolean, now: number) {
|
|
33
|
+
if (!visible) this.close(now);
|
|
34
|
+
this.tabVisible = visible;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
private close(now: number) {
|
|
38
|
+
if (this.from == null) return;
|
|
39
|
+
this.engagedMs += Math.max(0, Math.min(now, this.until) - this.from);
|
|
40
|
+
this.from = null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
total(now: number): number {
|
|
44
|
+
const open = this.from != null ? Math.max(0, Math.min(now, this.until) - this.from) : 0;
|
|
45
|
+
return Math.round(this.engagedMs + open);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { hashV2 } from './hash';
|
|
2
|
+
import { Observable } from './observable';
|
|
3
|
+
import { readJson, writeJson, type IStorage } from './storage';
|
|
4
|
+
import { KEYS, type IExperimentDefinition, type IExperimentVariant, type TStorageKeys } from './types';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Client-side assignment (§5 of the contract). No round trip: the running
|
|
8
|
+
* experiments are fetched once (public fields only) and every visitor is bucketed
|
|
9
|
+
* locally from their `vid`, the same way every time, on any page.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export type TAssignmentReason =
|
|
13
|
+
/** Bucketed into a variant: an exposure is logged when the trigger is seen. */
|
|
14
|
+
| 'assigned'
|
|
15
|
+
/** Outside the experiment's traffic share: control, no exposure. */
|
|
16
|
+
| 'not-enrolled'
|
|
17
|
+
/** Targeting (path, device, language) does not match: control, no exposure. */
|
|
18
|
+
| 'not-targeted'
|
|
19
|
+
/** No consent (no vid) or tracking disabled: control, no exposure. */
|
|
20
|
+
| 'no-consent'
|
|
21
|
+
/** Definitions not loaded (yet, or the endpoint is missing) or experiment not running: control. */
|
|
22
|
+
| 'not-running'
|
|
23
|
+
/** A preview link (`?qa_variant=`) or the in-app version switch: that variant, never logged. */
|
|
24
|
+
| 'preview'
|
|
25
|
+
/** The experiment ended: everybody sees the winner, nothing is logged. */
|
|
26
|
+
| 'concluded';
|
|
27
|
+
|
|
28
|
+
export interface IAssignment {
|
|
29
|
+
key: string;
|
|
30
|
+
variant: string;
|
|
31
|
+
/** Whether this visitor counts for the experiment (exposure is logged). */
|
|
32
|
+
enrolled: boolean;
|
|
33
|
+
reason: TAssignmentReason;
|
|
34
|
+
/** The section whose being seen logs the exposure; null → on render. */
|
|
35
|
+
trigger: string | null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface IAssignContext {
|
|
39
|
+
path: string;
|
|
40
|
+
device?: 'desktop' | 'tablet' | 'mobile';
|
|
41
|
+
lang?: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export const controlOf = (variants: IExperimentVariant[], fallback = 'a'): string =>
|
|
45
|
+
(variants.find((v) => v.control) ?? variants[0])?.key ?? fallback;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* GrowthBook's bucket ranges: variant i owns `[c_i, c_i + traffic * w_i)` where
|
|
49
|
+
* `c_i` is the sum of the weights before it. The enrolled share equals `traffic`,
|
|
50
|
+
* and raising `traffic` later never moves an enrolled visitor to another variant.
|
|
51
|
+
* Weights that do not add up to 1 are normalised.
|
|
52
|
+
*/
|
|
53
|
+
export const bucketRanges = (weights: number[], traffic: number): [number, number][] => {
|
|
54
|
+
const cover = Math.min(1, Math.max(0, Number.isFinite(traffic) ? traffic : 0));
|
|
55
|
+
const clean = weights.map((w) => (Number.isFinite(w) && w > 0 ? w : 0));
|
|
56
|
+
const sum = clean.reduce((a, b) => a + b, 0);
|
|
57
|
+
const norm = sum > 0 ? clean.map((w) => w / sum) : clean.map(() => 1 / clean.length);
|
|
58
|
+
let cumulative = 0;
|
|
59
|
+
return norm.map((w) => {
|
|
60
|
+
const start = cumulative;
|
|
61
|
+
cumulative += w;
|
|
62
|
+
return [start, start + cover * w];
|
|
63
|
+
});
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/** `/` matches `/` only; `/blog/*` matches `/blog/` and everything under it. */
|
|
67
|
+
export const pathMatches = (patterns: string[] | null | undefined, path: string): boolean => {
|
|
68
|
+
if (!patterns || !patterns.length) return true;
|
|
69
|
+
const clean = path.split(/[?#]/)[0] || '/';
|
|
70
|
+
return patterns.some((p) => (p.endsWith('*') ? clean.startsWith(p.slice(0, -1)) : clean === p || clean === `${p}/`));
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const targeted = (def: IExperimentDefinition, ctx: IAssignContext): boolean => {
|
|
74
|
+
const t = def.targeting;
|
|
75
|
+
if (!t) return true;
|
|
76
|
+
if (!pathMatches(t.paths, ctx.path)) return false;
|
|
77
|
+
if (t.device && ctx.device && t.device !== ctx.device) return false;
|
|
78
|
+
if (t.lang && ctx.lang && !ctx.lang.toLowerCase().startsWith(t.lang.toLowerCase())) return false;
|
|
79
|
+
return true;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/** Pure assignment of one visitor to one experiment. */
|
|
83
|
+
export const assign = (def: IExperimentDefinition, vid: string | null, ctx: IAssignContext): IAssignment => {
|
|
84
|
+
const control = controlOf(def.variants);
|
|
85
|
+
const trigger = def.trigger?.section ?? null;
|
|
86
|
+
const base = { key: def.key, variant: control, enrolled: false, trigger };
|
|
87
|
+
if (def.status === 'concluded') return { ...base, variant: def.winner || control, reason: 'concluded' };
|
|
88
|
+
if (!vid) return { ...base, reason: 'no-consent' };
|
|
89
|
+
if (!def.variants.length) return { ...base, reason: 'not-running' };
|
|
90
|
+
if (!targeted(def, ctx)) return { ...base, reason: 'not-targeted' };
|
|
91
|
+
const n = hashV2(def.key, vid);
|
|
92
|
+
const ranges = bucketRanges(
|
|
93
|
+
def.variants.map((v) => v.weight),
|
|
94
|
+
def.traffic,
|
|
95
|
+
);
|
|
96
|
+
const i = ranges.findIndex(([from, to]) => n >= from && n < to);
|
|
97
|
+
if (i < 0) return { ...base, reason: 'not-enrolled' };
|
|
98
|
+
return { ...base, variant: def.variants[i].key, enrolled: true, reason: 'assigned' };
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/** The default preview query parameter. */
|
|
102
|
+
export const DEFAULT_PREVIEW_PARAM = 'qa_variant';
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* `?qa_variant=signup-cta:b,other:a` → `{ 'signup-cta': 'b', other: 'a' }`.
|
|
106
|
+
* `?qa_variant=clear` (or `off`) → `{}` and clears the saved preview.
|
|
107
|
+
* Returns null when the parameter is absent. `param` names the query parameter.
|
|
108
|
+
*/
|
|
109
|
+
export const parsePreview = (search: string, param: string = DEFAULT_PREVIEW_PARAM): Record<string, string> | null => {
|
|
110
|
+
let raw: string | null = null;
|
|
111
|
+
try {
|
|
112
|
+
raw = new URLSearchParams(search).get(param);
|
|
113
|
+
} catch {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
if (raw == null) return null;
|
|
117
|
+
const out: Record<string, string> = {};
|
|
118
|
+
if (raw === 'clear' || raw === 'off') return out;
|
|
119
|
+
raw.split(',').forEach((pair) => {
|
|
120
|
+
const [k, v] = pair.split(':').map((s) => s?.trim());
|
|
121
|
+
if (k && v && /^[\w.-]{1,80}$/.test(k) && /^[\w.-]{1,40}$/.test(v)) out[k] = v;
|
|
122
|
+
});
|
|
123
|
+
return out;
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
export type TExperimentsStatus = 'idle' | 'loading' | 'ready' | 'failed';
|
|
127
|
+
|
|
128
|
+
interface ICache {
|
|
129
|
+
at: number;
|
|
130
|
+
property: string;
|
|
131
|
+
experiments: IExperimentDefinition[];
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Cached definitions are used for a flicker-free first render for up to a day, then refreshed. */
|
|
135
|
+
const CACHE_MAX_AGE_MS = 24 * 60 * 60 * 1000;
|
|
136
|
+
const FETCH_TIMEOUT_MS = 4000;
|
|
137
|
+
|
|
138
|
+
/** A usable entry, normalised (a concluded entry gets `variants: []`); null for junk. */
|
|
139
|
+
export const normaliseDefinition = (x: unknown): IExperimentDefinition | null => {
|
|
140
|
+
const d = x as IExperimentDefinition;
|
|
141
|
+
if (!d || typeof d.key !== 'string') return null;
|
|
142
|
+
if (d.status === 'concluded') return typeof d.winner === 'string' && d.winner ? { ...d, variants: d.variants ?? [] } : null;
|
|
143
|
+
if (d.status && d.status !== 'running') return null;
|
|
144
|
+
const ok = Array.isArray(d.variants) && d.variants.every((v) => v && typeof v.key === 'string' && typeof v.weight === 'number');
|
|
145
|
+
return ok ? d : null;
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
export interface IExperimentsDeps {
|
|
149
|
+
property: string;
|
|
150
|
+
endpoint: string;
|
|
151
|
+
local: IStorage;
|
|
152
|
+
session: IStorage;
|
|
153
|
+
now: () => number;
|
|
154
|
+
fetchJson: (url: string, timeoutMs: number) => Promise<unknown>;
|
|
155
|
+
/** Storage keys (default prefix `qa.`). */
|
|
156
|
+
keys?: TStorageKeys;
|
|
157
|
+
/** The preview query parameter (default `qa_variant`). */
|
|
158
|
+
previewParam?: string;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Holds the running experiments and the preview overrides. */
|
|
162
|
+
export class ExperimentStore {
|
|
163
|
+
readonly status = new Observable<TExperimentsStatus>('idle');
|
|
164
|
+
/**
|
|
165
|
+
* An in-app version switch, per experiment (`{ key: variant }`), in this browser's
|
|
166
|
+
* localStorage (an editor lets its user see each version). A preview: never logged.
|
|
167
|
+
* Rendered variants follow it live.
|
|
168
|
+
*/
|
|
169
|
+
readonly editorOverrides: Observable<Record<string, string>>;
|
|
170
|
+
/**
|
|
171
|
+
* Bumped by `refresh()` (an editor, after it accepted a winner or removed a version): mounted
|
|
172
|
+
* experiments decide again, so an accepted test shows its winner at once. Visitors never
|
|
173
|
+
* trigger it, so their variant stays fixed for the page view.
|
|
174
|
+
*/
|
|
175
|
+
readonly revision = new Observable<number>(0);
|
|
176
|
+
private definitions = new Map<string, IExperimentDefinition>();
|
|
177
|
+
private preview: Record<string, string>;
|
|
178
|
+
private readonly keys: TStorageKeys;
|
|
179
|
+
|
|
180
|
+
constructor(private readonly d: IExperimentsDeps) {
|
|
181
|
+
this.keys = d.keys ?? KEYS;
|
|
182
|
+
this.preview = readJson<Record<string, string>>(d.session, this.keys.preview) ?? {};
|
|
183
|
+
this.editorOverrides = new Observable<Record<string, string>>(readJson<Record<string, string>>(d.local, this.keys.editorVariants) ?? {});
|
|
184
|
+
const cache = readJson<ICache>(d.local, this.keys.experimentsCache);
|
|
185
|
+
if (cache && cache.property === d.property && d.now() - cache.at < CACHE_MAX_AGE_MS && Array.isArray(cache.experiments)) {
|
|
186
|
+
this.setDefinitions(cache.experiments);
|
|
187
|
+
this.status.set('ready');
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Reads the preview parameter (`?qa_variant=`) from the URL; the preview sticks for the browser session. */
|
|
192
|
+
applyPreviewFrom(search: string) {
|
|
193
|
+
const parsed = parsePreview(search, this.d.previewParam ?? DEFAULT_PREVIEW_PARAM);
|
|
194
|
+
if (!parsed) return;
|
|
195
|
+
this.preview = Object.keys(parsed).length ? { ...this.preview, ...parsed } : {};
|
|
196
|
+
if (Object.keys(this.preview).length) writeJson(this.d.session, this.keys.preview, this.preview);
|
|
197
|
+
else this.d.session.remove(this.keys.preview);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** The in-app switch first, then a preview link. */
|
|
201
|
+
previewOf = (key: string): string | undefined => this.editorOverrides.get()[key] ?? this.preview[key];
|
|
202
|
+
|
|
203
|
+
editorOverrideOf = (key: string): string | undefined => this.editorOverrides.get()[key];
|
|
204
|
+
|
|
205
|
+
/** The in-app version switch for one experiment; `null` goes back to the visitor's own variant. */
|
|
206
|
+
setEditorOverride(key: string, variant: string | null) {
|
|
207
|
+
const next = { ...this.editorOverrides.get() };
|
|
208
|
+
if (variant) next[key] = variant;
|
|
209
|
+
else delete next[key];
|
|
210
|
+
if (Object.keys(next).length) writeJson(this.d.local, this.keys.editorVariants, next);
|
|
211
|
+
else this.d.local.remove(this.keys.editorVariants);
|
|
212
|
+
this.editorOverrides.set(next);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Re-reads the switches (another window of the same app changed them). */
|
|
216
|
+
reloadEditorOverrides() {
|
|
217
|
+
const stored = readJson<Record<string, string>>(this.d.local, this.keys.editorVariants) ?? {};
|
|
218
|
+
if (JSON.stringify(stored) !== JSON.stringify(this.editorOverrides.get())) this.editorOverrides.set(stored);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Loads the definitions again and makes mounted experiments decide again (for an editor, never for visitors). */
|
|
222
|
+
async refresh(): Promise<void> {
|
|
223
|
+
await this.load(true);
|
|
224
|
+
this.revision.set(this.revision.get() + 1);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
private setDefinitions(list: unknown[]) {
|
|
228
|
+
this.definitions = new Map(
|
|
229
|
+
list.map(normaliseDefinition).filter((d): d is IExperimentDefinition => !!d).map((d) => [d.key, d]),
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
get(key: string) {
|
|
234
|
+
return this.definitions.get(key);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Fetches the running experiments; a missing endpoint leaves everyone on the control. */
|
|
238
|
+
async load(force = false): Promise<void> {
|
|
239
|
+
if (this.status.get() === 'loading' && !force) return;
|
|
240
|
+
const hadCache = this.status.get() === 'ready';
|
|
241
|
+
if (!hadCache) this.status.set('loading');
|
|
242
|
+
try {
|
|
243
|
+
const sep = this.d.endpoint.includes('?') ? '&' : '?';
|
|
244
|
+
const body = await this.d.fetchJson(`${this.d.endpoint}${sep}property=${encodeURIComponent(this.d.property)}`, FETCH_TIMEOUT_MS);
|
|
245
|
+
const list = Array.isArray(body) ? body : ((body as { experiments?: unknown[] } | null)?.experiments ?? null);
|
|
246
|
+
if (!Array.isArray(list)) throw new Error('unexpected experiments payload');
|
|
247
|
+
this.setDefinitions(list);
|
|
248
|
+
writeJson(this.d.local, this.keys.experimentsCache, {
|
|
249
|
+
at: this.d.now(),
|
|
250
|
+
property: this.d.property,
|
|
251
|
+
experiments: Array.from(this.definitions.values()),
|
|
252
|
+
} satisfies ICache);
|
|
253
|
+
this.status.set('ready');
|
|
254
|
+
} catch {
|
|
255
|
+
if (!hadCache) this.status.set('failed');
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic bucketing: GrowthBook's hash v2 (MIT), so assignments match what
|
|
3
|
+
* GrowthBook-compatible tooling (and the server, if it ever recomputes) gets.
|
|
4
|
+
*
|
|
5
|
+
* n = (fnv1a32(String(fnv1a32(seed + value))) % 10000) / 10000
|
|
6
|
+
*
|
|
7
|
+
* The inner hash is turned into its *decimal string* before it is hashed again —
|
|
8
|
+
* that is GrowthBook's definition (`hashFnv32a(hashFnv32a(seed + value) + "")`).
|
|
9
|
+
* Characters are hashed as UTF-16 code units (`charCodeAt`), like GrowthBook; for
|
|
10
|
+
* the ASCII ids and keys we use that equals FNV-1a over the bytes.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** FNV-1a, 32 bit. `fnv1a32('a') === 0xe40c292c` (the reference test vector). */
|
|
14
|
+
export const fnv1a32 = (input: string): number => {
|
|
15
|
+
let h = 0x811c9dc5;
|
|
16
|
+
for (let i = 0; i < input.length; i++) {
|
|
17
|
+
h ^= input.charCodeAt(i);
|
|
18
|
+
// h *= 16777619 (the FNV prime) in 32-bit arithmetic, as shifts and adds.
|
|
19
|
+
h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);
|
|
20
|
+
}
|
|
21
|
+
return h >>> 0;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** A number in [0, 1) with 4 decimals; the same inputs always give the same number. */
|
|
25
|
+
export const hashV2 = (seed: string, value: string): number =>
|
|
26
|
+
(fnv1a32(String(fnv1a32(seed + value))) % 10000) / 10000;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Random ids from the platform CSPRNG (never Math.random: ids must not collide or be guessable). */
|
|
2
|
+
|
|
3
|
+
const toBase64Url = (bytes: Uint8Array): string => {
|
|
4
|
+
let bin = '';
|
|
5
|
+
bytes.forEach((b) => (bin += String.fromCharCode(b)));
|
|
6
|
+
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
/** `bytes` random bytes as base64url: 16 bytes = 128 bits = 22 characters. */
|
|
10
|
+
export const randomId = (bytes = 16): string => {
|
|
11
|
+
const buf = new Uint8Array(bytes);
|
|
12
|
+
globalThis.crypto.getRandomValues(buf);
|
|
13
|
+
return toBase64Url(buf);
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** Event id (a UUID v4). */
|
|
17
|
+
export const eventId = (): string => {
|
|
18
|
+
if (typeof globalThis.crypto?.randomUUID === 'function') return globalThis.crypto.randomUUID();
|
|
19
|
+
const b = new Uint8Array(16);
|
|
20
|
+
globalThis.crypto.getRandomValues(b);
|
|
21
|
+
b[6] = (b[6] & 0x0f) | 0x40;
|
|
22
|
+
b[8] = (b[8] & 0x3f) | 0x80;
|
|
23
|
+
const h = Array.from(b).map((x) => x.toString(16).padStart(2, '0')).join('');
|
|
24
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
|
|
25
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
type TListener = () => void;
|
|
2
|
+
|
|
3
|
+
/** A tiny observable value (what React's `useSyncExternalStore` wants). */
|
|
4
|
+
export class Observable<T> {
|
|
5
|
+
private listeners = new Set<TListener>();
|
|
6
|
+
constructor(private value: T) {}
|
|
7
|
+
get = (): T => this.value;
|
|
8
|
+
set(next: T) {
|
|
9
|
+
if (Object.is(next, this.value)) return;
|
|
10
|
+
this.value = next;
|
|
11
|
+
this.listeners.forEach((l) => {
|
|
12
|
+
try {
|
|
13
|
+
l();
|
|
14
|
+
} catch {
|
|
15
|
+
/* a listener never breaks the tracker */
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
subscribe = (listener: TListener) => {
|
|
20
|
+
this.listeners.add(listener);
|
|
21
|
+
return () => void this.listeners.delete(listener);
|
|
22
|
+
};
|
|
23
|
+
}
|