@tbdhdev/beacon-sdk 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +586 -2
- package/dist/astro.d.ts +10 -0
- package/dist/astro.js +26 -0
- package/dist/astro.js.map +1 -0
- package/dist/index-t-jJl5-d.d.ts +40 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/nuxt.d.ts +10 -0
- package/dist/nuxt.js +42 -0
- package/dist/nuxt.js.map +1 -0
- package/dist/react.d.ts +6 -0
- package/dist/react.js +15 -0
- package/dist/react.js.map +1 -0
- package/dist/server.d.ts +58 -0
- package/dist/server.js +102 -0
- package/dist/server.js.map +1 -0
- package/dist/solid.d.ts +7 -0
- package/dist/solid.js +44 -0
- package/dist/solid.js.map +1 -0
- package/dist/src-DaAShSXp.js +300 -0
- package/dist/src-DaAShSXp.js.map +1 -0
- package/dist/sveltekit.d.ts +7 -0
- package/dist/sveltekit.js +20 -0
- package/dist/sveltekit.js.map +1 -0
- package/dist/tanstack-router.d.ts +12 -0
- package/dist/tanstack-router.js +18 -0
- package/dist/tanstack-router.js.map +1 -0
- package/dist/vue.d.ts +20 -0
- package/dist/vue.js +31 -0
- package/dist/vue.js.map +1 -0
- package/package.json +113 -3
- package/src/astro.ts +29 -0
- package/src/core.ts +542 -0
- package/src/index.ts +58 -0
- package/src/nuxt.ts +50 -0
- package/src/react.ts +13 -0
- package/src/server.ts +219 -0
- package/src/solid.ts +63 -0
- package/src/sveltekit.ts +16 -0
- package/src/tanstack-router.ts +24 -0
- package/src/vue.ts +55 -0
package/src/core.ts
ADDED
|
@@ -0,0 +1,542 @@
|
|
|
1
|
+
// Beacon browser core, shared by `@tbdhdev/beacon-sdk` and the zero-install script. Cookieless: never
|
|
2
|
+
// writes storage except the operator's own opt-out flag, set with `#beacon-ignore=true`.
|
|
3
|
+
export type BeaconProps = Record<string, string | number | boolean>;
|
|
4
|
+
|
|
5
|
+
export interface BeaconApi {
|
|
6
|
+
/** Track a custom event, e.g. `track("signup_clicked", { plan: "pro" })`. */
|
|
7
|
+
track: (name: string, props?: BeaconProps) => void;
|
|
8
|
+
/** Opt-in identification for your own logged-in apps. Kept in memory only. */
|
|
9
|
+
identify: (id: string, traits?: BeaconProps) => void;
|
|
10
|
+
/** Record a pageview for `url` (default: the current location). Repeats of the last page are ignored. */
|
|
11
|
+
page: (url?: string) => void;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface BeaconConfig {
|
|
15
|
+
/** Website id from the Beacon dashboard. */
|
|
16
|
+
websiteId: string;
|
|
17
|
+
/**
|
|
18
|
+
* Event endpoint: your ingest origin + prefix + event path (Settings → Tracking), e.g.
|
|
19
|
+
* `https://beacon.example.com/x/e`. Relative URLs resolve against the page. Default `/x/e`.
|
|
20
|
+
*/
|
|
21
|
+
endpoint?: string;
|
|
22
|
+
/**
|
|
23
|
+
* Record the first pageview and history navigations (pushState, replaceState to another path,
|
|
24
|
+
* back/forward). Set `false` to call `page()` from your router instead. Default `true`.
|
|
25
|
+
*/
|
|
26
|
+
autoPageviews?: boolean;
|
|
27
|
+
/**
|
|
28
|
+
* The app routes in the URL hash (`/#/pricing`, e.g. Vue's `createWebHashHistory` or React
|
|
29
|
+
* Router's `HashRouter`): record the hash route as the page path. Default `false`.
|
|
30
|
+
*/
|
|
31
|
+
hashRouting?: boolean;
|
|
32
|
+
/** Track clicks on links to other hosts. */
|
|
33
|
+
outbound?: boolean;
|
|
34
|
+
/** Track clicks on file downloads (pdf, zip, csv, ...). */
|
|
35
|
+
downloads?: boolean;
|
|
36
|
+
/** Send LCP, CLS, INP and TTFB when the page is hidden. */
|
|
37
|
+
webVitals?: boolean;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface LayoutShift extends PerformanceEntry {
|
|
41
|
+
value: number;
|
|
42
|
+
hadRecentInput: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
interface EventTiming extends PerformanceEntry {
|
|
46
|
+
interactionId?: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const IGNORE_KEY = "beacon.ignore";
|
|
50
|
+
const DOWNLOAD_RE =
|
|
51
|
+
/\.(pdf|zip|gz|tgz|rar|7z|dmg|pkg|exe|msi|deb|rpm|apk|csv|xlsx?|docx?|pptx?|txt|mp3|mp4|mov|avi|wav|iso|epub)$/i;
|
|
52
|
+
// Campaign and click-id params that sites strip after landing; removing them is not a new page.
|
|
53
|
+
const CAMPAIGN_PARAM_RE = /^(utm_\w+|gclid|fbclid|msclkid)$/i;
|
|
54
|
+
|
|
55
|
+
// Identifies a page for deduplication: path and query, minus campaign params.
|
|
56
|
+
function pageKey(url: URL) {
|
|
57
|
+
const params = new URLSearchParams(url.search);
|
|
58
|
+
|
|
59
|
+
for (const name of [...params.keys()]) {
|
|
60
|
+
if (CAMPAIGN_PARAM_RE.test(name)) {
|
|
61
|
+
params.delete(name);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return `${url.pathname}?${params}`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Starts tracking in the browser. Call once per page load: it patches history and adds listeners. */
|
|
69
|
+
export function createBeacon(config: BeaconConfig): BeaconApi {
|
|
70
|
+
const d = document;
|
|
71
|
+
const loc = location;
|
|
72
|
+
const website = config.websiteId;
|
|
73
|
+
const endpoint = new URL(config.endpoint ?? "/x/e", loc.href).href;
|
|
74
|
+
let ignored = false;
|
|
75
|
+
|
|
76
|
+
try {
|
|
77
|
+
const flag = /beacon-ignore=(true|false)/.exec(loc.hash)?.[1];
|
|
78
|
+
|
|
79
|
+
if (flag === "true") {
|
|
80
|
+
localStorage.setItem(IGNORE_KEY, "1");
|
|
81
|
+
} else if (flag === "false") {
|
|
82
|
+
localStorage.removeItem(IGNORE_KEY);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
ignored = localStorage.getItem(IGNORE_KEY) === "1";
|
|
86
|
+
} catch {
|
|
87
|
+
// Storage blocked: tracking stays enabled.
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Opted out: no history patches, listeners or observers either.
|
|
91
|
+
if (ignored) {
|
|
92
|
+
const noop = () => undefined;
|
|
93
|
+
|
|
94
|
+
return { track: noop, identify: noop, page: noop };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
let distinctId: string | undefined;
|
|
98
|
+
// The last pageview: its dedupe key, path (for replaceState) and URL (for back/forward restores).
|
|
99
|
+
let lastPage: string | undefined;
|
|
100
|
+
let lastPath: string | undefined;
|
|
101
|
+
let lastUrl: string | undefined;
|
|
102
|
+
// The first pageview's URL, which web vitals (a page-load measurement) are filed under.
|
|
103
|
+
let landingUrl: string | undefined;
|
|
104
|
+
let referrer = d.referrer;
|
|
105
|
+
let lastTitle = "";
|
|
106
|
+
// Counts pageviews, so one still waiting for its title can tell a newer page has started.
|
|
107
|
+
let views = 0;
|
|
108
|
+
|
|
109
|
+
// With hash routing, `/app#/pricing?plan=pro` and `/app/index.html#/pricing?plan=pro` are the
|
|
110
|
+
// page `/app/pricing?plan=pro`, and `/app`, `/app#/` and `/app/#section` are its root `/app/`.
|
|
111
|
+
const currentUrl = () => {
|
|
112
|
+
if (!config.hashRouting) {
|
|
113
|
+
return loc.href;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Leading slashes (and backslashes, which URLs read as slashes) are not part of the route.
|
|
117
|
+
const route = /^#!?\//.test(loc.hash)
|
|
118
|
+
? loc.hash.replace(/^#!?[/\\]+/, "")
|
|
119
|
+
: "";
|
|
120
|
+
const base = loc.pathname
|
|
121
|
+
.replace(/\/index\.html?$/, "/")
|
|
122
|
+
.replace(/\/?$/, "/");
|
|
123
|
+
// An absolute URL, so neither `#/\evil.com` nor a `//evil.com/` path can change the host.
|
|
124
|
+
const url = new URL(loc.origin + base + route);
|
|
125
|
+
const own = new URLSearchParams(url.search);
|
|
126
|
+
|
|
127
|
+
// The real query (where UTM tags usually are) still applies; the route's own params win.
|
|
128
|
+
for (const [name, value] of new URLSearchParams(loc.search)) {
|
|
129
|
+
if (!own.has(name)) {
|
|
130
|
+
url.searchParams.append(name, value);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return url.href;
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
const send = (type: string, extra: Record<string, unknown> = {}) => {
|
|
138
|
+
const body = JSON.stringify({
|
|
139
|
+
website,
|
|
140
|
+
type,
|
|
141
|
+
url: currentUrl(),
|
|
142
|
+
title: d.title,
|
|
143
|
+
screen: `${screen.width}x${screen.height}`,
|
|
144
|
+
language: navigator.language,
|
|
145
|
+
id: distinctId,
|
|
146
|
+
...extra,
|
|
147
|
+
});
|
|
148
|
+
// A cors-mode fetch always sends the page's real Origin, which ingest checks; sendBeacon sends
|
|
149
|
+
// "Origin: null" under no-referrer/same-origin referrer policies, so it is only a fallback.
|
|
150
|
+
const transmit = () => {
|
|
151
|
+
if (typeof fetch === "function") {
|
|
152
|
+
fetch(endpoint, {
|
|
153
|
+
method: "POST",
|
|
154
|
+
body,
|
|
155
|
+
keepalive: true,
|
|
156
|
+
credentials: "omit",
|
|
157
|
+
}).catch(() => undefined);
|
|
158
|
+
} else {
|
|
159
|
+
navigator.sendBeacon?.(endpoint, body);
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
// A prerendered page may never be shown: hold its events until the visitor opens it.
|
|
164
|
+
if ((d as Document & { prerendering?: boolean }).prerendering) {
|
|
165
|
+
d.addEventListener("prerenderingchange", transmit, { once: true });
|
|
166
|
+
} else {
|
|
167
|
+
transmit();
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
const page = (path?: string) => {
|
|
172
|
+
const url = new URL(path ?? currentUrl(), loc.href);
|
|
173
|
+
const key = pageKey(url);
|
|
174
|
+
|
|
175
|
+
if (key === lastPage) {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const view = ++views;
|
|
180
|
+
|
|
181
|
+
lastPage = key;
|
|
182
|
+
lastPath = url.pathname;
|
|
183
|
+
lastUrl = url.href;
|
|
184
|
+
landingUrl ??= url.href;
|
|
185
|
+
|
|
186
|
+
const extra = { url: url.href, referrer };
|
|
187
|
+
const route = () => new URL(currentUrl()).pathname;
|
|
188
|
+
const at = route();
|
|
189
|
+
const sendPageview = () => {
|
|
190
|
+
// Waited for a title, but a newer page came first (another page() call, or the location
|
|
191
|
+
// moved on before its own page() call): the title now is that page's.
|
|
192
|
+
if (view !== views || route() !== at) {
|
|
193
|
+
send("pageview", { ...extra, title: "" });
|
|
194
|
+
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
lastTitle = d.title;
|
|
199
|
+
send("pageview", extra);
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
referrer = "";
|
|
203
|
+
|
|
204
|
+
// Next.js empties <title> on client navigation and streams the new one in a moment later.
|
|
205
|
+
if (d.title || !lastTitle) {
|
|
206
|
+
sendPageview();
|
|
207
|
+
} else {
|
|
208
|
+
onTitle(sendPageview);
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
const api: BeaconApi = {
|
|
213
|
+
track: (name, props) => send("event", { name, props }),
|
|
214
|
+
identify: (id, traits) => {
|
|
215
|
+
distinctId = id;
|
|
216
|
+
send("identify", { name: "identify", props: traits });
|
|
217
|
+
},
|
|
218
|
+
page,
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
if (config.autoPageviews ?? true) {
|
|
222
|
+
page();
|
|
223
|
+
|
|
224
|
+
// Deferred so the app can render the new page (and its <title>) first.
|
|
225
|
+
const later = () => setTimeout(() => page(), 0);
|
|
226
|
+
// replaceState on the same path (stripping UTM tags, syncing filters) updates the URL, not the page.
|
|
227
|
+
const replaced = (href: string) => {
|
|
228
|
+
const url = new URL(href);
|
|
229
|
+
|
|
230
|
+
if (url.pathname !== lastPath) {
|
|
231
|
+
page(href);
|
|
232
|
+
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
lastPage = pageKey(url);
|
|
237
|
+
lastUrl = href;
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
// Counts history calls, so a replaceState can tell another one came after it.
|
|
241
|
+
let calls = 0;
|
|
242
|
+
|
|
243
|
+
for (const method of ["pushState", "replaceState"] as const) {
|
|
244
|
+
const original = history[method].bind(history);
|
|
245
|
+
|
|
246
|
+
history[method] = (...args: Parameters<History["pushState"]>) => {
|
|
247
|
+
original(...args);
|
|
248
|
+
// Judge a replaceState by the URL it set: Vue Router's push() replaces the current entry
|
|
249
|
+
// and then pushes the new one in the same tick, so location has moved on by the timeout.
|
|
250
|
+
const href = currentUrl();
|
|
251
|
+
const call = ++calls;
|
|
252
|
+
|
|
253
|
+
setTimeout(() => {
|
|
254
|
+
if (method === "pushState") {
|
|
255
|
+
page();
|
|
256
|
+
} else if (call === calls) {
|
|
257
|
+
// A replaceState followed by another history call (a redirect chain) was never shown.
|
|
258
|
+
replaced(href);
|
|
259
|
+
}
|
|
260
|
+
}, 0);
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
addEventListener("popstate", later);
|
|
265
|
+
|
|
266
|
+
if (config.hashRouting) {
|
|
267
|
+
addEventListener("hashchange", later);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Back/forward cache restores show the page again without reloading it, and no router runs.
|
|
272
|
+
addEventListener("pageshow", (event) => {
|
|
273
|
+
if (event.persisted && lastUrl) {
|
|
274
|
+
const url = lastUrl;
|
|
275
|
+
|
|
276
|
+
// A new page load, which its web vitals are filed under.
|
|
277
|
+
lastPage = landingUrl = undefined;
|
|
278
|
+
page(url);
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
// Left clicks, and middle clicks (auxclick) that open a link in a new tab.
|
|
283
|
+
const onClick = (event: MouseEvent) => {
|
|
284
|
+
if (event.type === "auxclick" && event.button !== 1) {
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// composedPath() reaches into open shadow roots, where event.target stops at the host.
|
|
289
|
+
const elements = event
|
|
290
|
+
.composedPath()
|
|
291
|
+
.filter((node): node is Element => node instanceof Element);
|
|
292
|
+
const tagged =
|
|
293
|
+
event.type === "click"
|
|
294
|
+
? elements.find((el) => el.getAttribute("data-beacon-event"))
|
|
295
|
+
: undefined;
|
|
296
|
+
|
|
297
|
+
if (tagged) {
|
|
298
|
+
// fromEntries keeps a prop named `__proto__` as a prop.
|
|
299
|
+
const props: BeaconProps = Object.fromEntries(
|
|
300
|
+
Array.from(tagged.attributes)
|
|
301
|
+
.filter(({ name }) => name.startsWith("data-beacon-prop-"))
|
|
302
|
+
.map(({ name, value }) => [name.slice(17), value]),
|
|
303
|
+
);
|
|
304
|
+
|
|
305
|
+
api.track(tagged.getAttribute("data-beacon-event") ?? "", props);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const link = elements.find(
|
|
309
|
+
(el): el is HTMLAnchorElement => el instanceof HTMLAnchorElement,
|
|
310
|
+
);
|
|
311
|
+
|
|
312
|
+
if (!link?.href || !/^https?:$/.test(link.protocol)) {
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// Browsers ignore `download` on cross-origin links and navigate instead.
|
|
317
|
+
const isDownload =
|
|
318
|
+
DOWNLOAD_RE.test(link.pathname) ||
|
|
319
|
+
(link.hasAttribute("download") && link.host === loc.host);
|
|
320
|
+
|
|
321
|
+
if (config.downloads && isDownload) {
|
|
322
|
+
send("download", { name: "download", props: { url: link.href } });
|
|
323
|
+
} else if (config.outbound && link.host !== loc.host) {
|
|
324
|
+
send("outbound", { name: "outbound", props: { url: link.href } });
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
d.addEventListener("click", onClick, true);
|
|
329
|
+
d.addEventListener("auxclick", onClick, true);
|
|
330
|
+
|
|
331
|
+
if (config.webVitals) {
|
|
332
|
+
// Vitals describe the page load, so they belong to the first page recorded (after any redirect
|
|
333
|
+
// the router made before its first page() call), not the route open when the tab is hidden.
|
|
334
|
+
observeVitals((vitals, load) =>
|
|
335
|
+
send("vitals", { url: landingUrl ?? currentUrl(), props: vitals, load }),
|
|
336
|
+
);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
return api;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// Calls back once document.title is set, or after 1s.
|
|
343
|
+
function onTitle(callback: () => void) {
|
|
344
|
+
const done = () => {
|
|
345
|
+
observer.disconnect();
|
|
346
|
+
clearTimeout(timer);
|
|
347
|
+
callback();
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
const observer = new MutationObserver(() => {
|
|
351
|
+
if (document.title) {
|
|
352
|
+
done();
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
const timer = setTimeout(done, 1000);
|
|
356
|
+
|
|
357
|
+
observer.observe(document.documentElement, {
|
|
358
|
+
childList: true,
|
|
359
|
+
subtree: true,
|
|
360
|
+
characterData: true,
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function observeVitals(
|
|
365
|
+
report: (vitals: Record<string, number>, load: string) => void,
|
|
366
|
+
) {
|
|
367
|
+
// Every report from one page load carries the same id, so the dashboard counts it once.
|
|
368
|
+
const newLoad = () =>
|
|
369
|
+
Array.from(crypto.getRandomValues(new Uint8Array(8)), (byte) =>
|
|
370
|
+
byte.toString(16).padStart(2, "0"),
|
|
371
|
+
).join("");
|
|
372
|
+
let load = newLoad();
|
|
373
|
+
let vitals: Record<string, number> = {};
|
|
374
|
+
// What the last report sent, per metric.
|
|
375
|
+
let sent: Record<string, number> = {};
|
|
376
|
+
// Entries the browser has queued but not yet delivered, pulled in just before reporting.
|
|
377
|
+
const flushes: (() => void)[] = [];
|
|
378
|
+
const observe = (
|
|
379
|
+
type: string,
|
|
380
|
+
callback: (entries: PerformanceEntry[]) => void,
|
|
381
|
+
extra: Record<string, unknown> = {},
|
|
382
|
+
) => {
|
|
383
|
+
try {
|
|
384
|
+
const observer = new PerformanceObserver((list) =>
|
|
385
|
+
callback(list.getEntries()),
|
|
386
|
+
);
|
|
387
|
+
|
|
388
|
+
observer.observe({ type, buffered: true, ...extra });
|
|
389
|
+
flushes.push(() => callback(observer.takeRecords()));
|
|
390
|
+
} catch {
|
|
391
|
+
// Entry type unsupported in this browser.
|
|
392
|
+
}
|
|
393
|
+
};
|
|
394
|
+
|
|
395
|
+
const navigation = performance.getEntriesByType("navigation")[0] as
|
|
396
|
+
| (PerformanceNavigationTiming & { activationStart?: number })
|
|
397
|
+
| undefined;
|
|
398
|
+
// A prerendered page loads before the visitor opens it: LCP and TTFB count from activation,
|
|
399
|
+
// whose time the entry only has once the page is shown.
|
|
400
|
+
const activation = () => navigation?.activationStart ?? 0;
|
|
401
|
+
const prerendering = (document as Document & { prerendering?: boolean })
|
|
402
|
+
.prerendering;
|
|
403
|
+
|
|
404
|
+
// LCP only counts paints before the page was first hidden (as in the web-vitals library): a page
|
|
405
|
+
// opened in a background tab, or one the visitor comes back to, would report the wait as LCP.
|
|
406
|
+
// The browser's visibility history (Chromium) also covers a hide before Beacon started, e.g. before
|
|
407
|
+
// hydration. A prerendered page is hidden until it is shown, which is not the visitor leaving.
|
|
408
|
+
let firstHidden = prerendering
|
|
409
|
+
? Infinity
|
|
410
|
+
: (performance
|
|
411
|
+
.getEntriesByType("visibility-state")
|
|
412
|
+
.find(
|
|
413
|
+
(entry) => entry.name === "hidden" && entry.startTime >= activation(),
|
|
414
|
+
)?.startTime ?? (document.visibilityState === "hidden" ? 0 : Infinity));
|
|
415
|
+
|
|
416
|
+
// Kept raw: a paint while prerendering comes before activationStart is known, so the report
|
|
417
|
+
// subtracts it instead.
|
|
418
|
+
let lcpStart: number | undefined;
|
|
419
|
+
|
|
420
|
+
observe("largest-contentful-paint", (entries) => {
|
|
421
|
+
for (const entry of entries) {
|
|
422
|
+
if (entry.startTime < firstHidden) {
|
|
423
|
+
lcpStart = entry.startTime;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
});
|
|
427
|
+
|
|
428
|
+
// A page that never shifts has a CLS of 0, which must be reported too, but only where layout
|
|
429
|
+
// shifts can be observed at all (not in Safari or Firefox).
|
|
430
|
+
const shifts =
|
|
431
|
+
globalThis.PerformanceObserver?.supportedEntryTypes?.includes(
|
|
432
|
+
"layout-shift",
|
|
433
|
+
);
|
|
434
|
+
|
|
435
|
+
if (shifts) {
|
|
436
|
+
vitals.CLS = 0;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// CLS: largest session window (shifts < 1s apart, window < 5s).
|
|
440
|
+
let windowValue = 0;
|
|
441
|
+
let windowStart = 0;
|
|
442
|
+
let previous = 0;
|
|
443
|
+
|
|
444
|
+
observe("layout-shift", (entries) => {
|
|
445
|
+
for (const entry of entries as LayoutShift[]) {
|
|
446
|
+
if (entry.hadRecentInput) {
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
const sameWindow =
|
|
451
|
+
windowValue > 0 &&
|
|
452
|
+
entry.startTime - previous < 1000 &&
|
|
453
|
+
entry.startTime - windowStart < 5000;
|
|
454
|
+
|
|
455
|
+
windowValue = sameWindow ? windowValue + entry.value : entry.value;
|
|
456
|
+
windowStart = sameWindow ? windowStart : entry.startTime;
|
|
457
|
+
previous = entry.startTime;
|
|
458
|
+
vitals.CLS = Math.max(vitals.CLS ?? 0, windowValue);
|
|
459
|
+
}
|
|
460
|
+
});
|
|
461
|
+
|
|
462
|
+
// shortcut: INP is the slowest interaction, not the p98; matches web-vitals below ~50 interactions per page.
|
|
463
|
+
// getWebVitals keeps each page load's largest value, so a p98 (which can drop) needs that query changed too.
|
|
464
|
+
observe(
|
|
465
|
+
"event",
|
|
466
|
+
(entries) => {
|
|
467
|
+
for (const entry of entries as EventTiming[]) {
|
|
468
|
+
if (entry.interactionId) {
|
|
469
|
+
vitals.INP = Math.max(vitals.INP ?? 0, entry.duration);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
},
|
|
473
|
+
{ durationThreshold: 40 },
|
|
474
|
+
);
|
|
475
|
+
// "event" entries start at 40ms, so a page whose interactions are all fast would report no INP.
|
|
476
|
+
// The first input is always reported, whatever its duration (as the web-vitals library does).
|
|
477
|
+
observe("first-input", (entries) => {
|
|
478
|
+
for (const entry of entries) {
|
|
479
|
+
vitals.INP = Math.max(vitals.INP ?? 0, entry.duration);
|
|
480
|
+
}
|
|
481
|
+
});
|
|
482
|
+
|
|
483
|
+
// 0 (or a time still to come) when the browser has no real value, e.g. for some cached loads.
|
|
484
|
+
const ttfb = () => {
|
|
485
|
+
if (
|
|
486
|
+
navigation &&
|
|
487
|
+
navigation.responseStart > 0 &&
|
|
488
|
+
navigation.responseStart <= performance.now()
|
|
489
|
+
) {
|
|
490
|
+
vitals.TTFB = Math.max(navigation.responseStart - activation(), 0);
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
|
|
494
|
+
if (prerendering) {
|
|
495
|
+
document.addEventListener("prerenderingchange", ttfb, { once: true });
|
|
496
|
+
} else {
|
|
497
|
+
ttfb();
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// A back/forward cache restore is a new page load without a network load or first paint: it
|
|
501
|
+
// gets its own id, and CLS and INP start over.
|
|
502
|
+
addEventListener("pageshow", (event) => {
|
|
503
|
+
if (event.persisted) {
|
|
504
|
+
load = newLoad();
|
|
505
|
+
vitals = shifts ? { CLS: 0 } : {};
|
|
506
|
+
sent = {};
|
|
507
|
+
windowValue = 0;
|
|
508
|
+
lcpStart = undefined;
|
|
509
|
+
}
|
|
510
|
+
});
|
|
511
|
+
|
|
512
|
+
// CLS and INP keep growing while the page stays open, so each hide reports what changed since the
|
|
513
|
+
// last report. The visitor may never come back, so waiting for a final value would lose it.
|
|
514
|
+
// visibilitychange bubbles up from document; pagehide covers browsers that skip it on unload.
|
|
515
|
+
const onHide = (event: Event) => {
|
|
516
|
+
if (event.type !== "pagehide" && document.visibilityState !== "hidden") {
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
firstHidden = Math.min(firstHidden, performance.now());
|
|
521
|
+
|
|
522
|
+
for (const flush of flushes) {
|
|
523
|
+
flush();
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
if (lcpStart !== undefined) {
|
|
527
|
+
vitals.LCP = Math.max(lcpStart - activation(), 0);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
const changed = Object.fromEntries(
|
|
531
|
+
Object.entries(vitals).filter(([name, value]) => sent[name] !== value),
|
|
532
|
+
);
|
|
533
|
+
|
|
534
|
+
if (Object.keys(changed).length > 0) {
|
|
535
|
+
Object.assign(sent, changed);
|
|
536
|
+
report(changed, load);
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
|
|
540
|
+
addEventListener("visibilitychange", onHide);
|
|
541
|
+
addEventListener("pagehide", onHide);
|
|
542
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type BeaconApi,
|
|
3
|
+
type BeaconConfig,
|
|
4
|
+
type BeaconProps,
|
|
5
|
+
createBeacon,
|
|
6
|
+
} from "./core.js";
|
|
7
|
+
|
|
8
|
+
export type { BeaconApi, BeaconConfig, BeaconProps };
|
|
9
|
+
|
|
10
|
+
let beacon: BeaconApi | undefined;
|
|
11
|
+
// Calls made before init() (e.g. a child component's effect) run right after it. Capped, for an
|
|
12
|
+
// app that never calls init() (e.g. no consent).
|
|
13
|
+
const queue: [keyof BeaconApi, unknown[]][] = [];
|
|
14
|
+
const isBrowser = () =>
|
|
15
|
+
typeof window !== "undefined" && typeof document !== "undefined";
|
|
16
|
+
|
|
17
|
+
function call(method: keyof BeaconApi, args: unknown[]) {
|
|
18
|
+
if (beacon) {
|
|
19
|
+
try {
|
|
20
|
+
(beacon[method] as (...a: unknown[]) => void)(...args);
|
|
21
|
+
} catch {
|
|
22
|
+
// Bad input from the app (an unparsable URL, props JSON can't encode): never break the page.
|
|
23
|
+
}
|
|
24
|
+
} else if (isBrowser() && queue.length < 100) {
|
|
25
|
+
queue.push([method, args]);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Starts Beacon. Safe to call during SSR (no-op) and more than once (later calls are ignored). */
|
|
30
|
+
export function init(config: BeaconConfig): void {
|
|
31
|
+
// Without a website id every event would be refused, e.g. when its env var is missing.
|
|
32
|
+
if (beacon || !isBrowser() || !config.websiteId) {
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
try {
|
|
37
|
+
beacon = createBeacon(config);
|
|
38
|
+
} catch {
|
|
39
|
+
// A malformed endpoint: tracking stays off rather than breaking the page.
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
for (const [method, args] of queue.splice(0)) {
|
|
44
|
+
call(method, args);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function track(name: string, props?: BeaconProps): void {
|
|
49
|
+
call("track", [name, props]);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function identify(id: string, traits?: BeaconProps): void {
|
|
53
|
+
call("identify", [id, traits]);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function page(url?: string): void {
|
|
57
|
+
call("page", [url]);
|
|
58
|
+
}
|
package/src/nuxt.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { addImports, addPluginTemplate, defineNuxtModule } from "nuxt/kit";
|
|
2
|
+
import type { NuxtModule } from "nuxt/schema";
|
|
3
|
+
import type { BeaconConfig } from "./index.js";
|
|
4
|
+
|
|
5
|
+
export type BeaconNuxtOptions = Omit<BeaconConfig, "autoPageviews">;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Nuxt module: add `"@tbdhdev/beacon-sdk/nuxt"` to `modules` and set options under `beacon`. Starts
|
|
9
|
+
* Beacon in the browser, records a pageview once each page has rendered and auto-imports
|
|
10
|
+
* `useBeacon()`.
|
|
11
|
+
*/
|
|
12
|
+
const beaconModule: NuxtModule<BeaconNuxtOptions> =
|
|
13
|
+
defineNuxtModule<BeaconNuxtOptions>({
|
|
14
|
+
meta: { name: "@tbdhdev/beacon-sdk", configKey: "beacon" },
|
|
15
|
+
setup(options, nuxt) {
|
|
16
|
+
const { public: runtime } = nuxt.options.runtimeConfig;
|
|
17
|
+
|
|
18
|
+
// Public runtime config, so NUXT_PUBLIC_BEACON_WEBSITE_ID (and the other options) can be set
|
|
19
|
+
// when the app starts instead of when it is built. Values already set there win.
|
|
20
|
+
runtime.beacon = {
|
|
21
|
+
...options,
|
|
22
|
+
...(runtime.beacon as Partial<BeaconNuxtOptions> | undefined),
|
|
23
|
+
};
|
|
24
|
+
// A generated client plugin: the package ships no runtime file that needs Nuxt's aliases.
|
|
25
|
+
// page:loading:end runs once per navigation (query-only ones included) and on first load.
|
|
26
|
+
// Nuxt writes the new <title> in a microtask after it, hence setTimeout; router.afterEach
|
|
27
|
+
// would be even earlier. A first load that shows error.vue renders no page and has no
|
|
28
|
+
// page:loading:end, hence app:suspense:resolve too, which runs once the first page (or
|
|
29
|
+
// error.vue) has resolved and Nuxt has written its head (page() skips the repeat).
|
|
30
|
+
addPluginTemplate({
|
|
31
|
+
filename: "beacon.client.mjs",
|
|
32
|
+
mode: "client",
|
|
33
|
+
getContents:
|
|
34
|
+
() => `import { defineNuxtPlugin, useRuntimeConfig } from "#app";
|
|
35
|
+
import { init, page } from "@tbdhdev/beacon-sdk";
|
|
36
|
+
|
|
37
|
+
export default defineNuxtPlugin((nuxtApp) => {
|
|
38
|
+
const record = () => setTimeout(() => page(), 0);
|
|
39
|
+
|
|
40
|
+
init({ ...useRuntimeConfig().public.beacon, autoPageviews: false });
|
|
41
|
+
nuxtApp.hook("app:suspense:resolve", record);
|
|
42
|
+
nuxtApp.hook("page:loading:end", record);
|
|
43
|
+
});
|
|
44
|
+
`,
|
|
45
|
+
});
|
|
46
|
+
addImports({ name: "useBeacon", from: "@tbdhdev/beacon-sdk/vue" });
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
export default beaconModule;
|
package/src/react.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useEffect } from "react";
|
|
3
|
+
import { type BeaconConfig, init } from "./index.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Starts Beacon on mount, so a server layout (e.g. Next.js `app/layout.tsx`) can render it
|
|
7
|
+
* without its own client wrapper. Render it once; later prop changes are ignored.
|
|
8
|
+
*/
|
|
9
|
+
export function Beacon(props: BeaconConfig): null {
|
|
10
|
+
useEffect(() => init(props));
|
|
11
|
+
|
|
12
|
+
return null;
|
|
13
|
+
}
|