tallymark 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.
Files changed (68) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +234 -2
  3. package/SECURITY.md +37 -0
  4. package/dist/cli.d.ts +2 -0
  5. package/dist/cli.js +124 -0
  6. package/dist/cloudflare.d.ts +9 -0
  7. package/dist/cloudflare.js +53 -0
  8. package/dist/hit.d.ts +83 -0
  9. package/dist/hit.js +301 -0
  10. package/dist/http.d.ts +36 -0
  11. package/dist/http.js +393 -0
  12. package/dist/index.d.ts +7 -0
  13. package/dist/index.js +4 -0
  14. package/dist/node.d.ts +40 -0
  15. package/dist/node.js +66 -0
  16. package/dist/query.d.ts +31 -0
  17. package/dist/query.js +699 -0
  18. package/dist/react.d.ts +27 -0
  19. package/dist/react.js +34 -0
  20. package/dist/script.d.ts +17 -0
  21. package/dist/script.js +147 -0
  22. package/dist/stores.d.ts +129 -0
  23. package/dist/stores.js +393 -0
  24. package/dist/tallymark.d.ts +49 -0
  25. package/dist/tallymark.js +265 -0
  26. package/dist/types.d.ts +306 -0
  27. package/dist/types.js +1 -0
  28. package/dist/vercel.d.ts +33 -0
  29. package/dist/vercel.js +36 -0
  30. package/dist/webhook.d.ts +27 -0
  31. package/dist/webhook.js +61 -0
  32. package/docs/DEPLOYMENT.md +155 -0
  33. package/docs/HOW_IT_WORKS.md +106 -0
  34. package/docs/USAGE.md +237 -0
  35. package/examples/README.md +39 -0
  36. package/examples/browser/index.html +32 -0
  37. package/examples/browser/server.ts +34 -0
  38. package/examples/events/index.html +89 -0
  39. package/examples/events/server.ts +101 -0
  40. package/examples/frameworks/astro/[...path].ts +21 -0
  41. package/examples/frameworks/bun.ts +23 -0
  42. package/examples/frameworks/cloudflare.ts +37 -0
  43. package/examples/frameworks/deno.ts +26 -0
  44. package/examples/frameworks/express.ts +57 -0
  45. package/examples/frameworks/hono.ts +38 -0
  46. package/examples/frameworks/nextjs/app/api/analytics/[...route]/route.ts +7 -0
  47. package/examples/frameworks/nextjs/app/api/analytics-cron/route.ts +6 -0
  48. package/examples/frameworks/nextjs/app/layout.tsx +15 -0
  49. package/examples/frameworks/nextjs/app/page.tsx +21 -0
  50. package/examples/frameworks/nextjs/lib/analytics.ts +14 -0
  51. package/examples/frameworks/nextjs/vercel.json +3 -0
  52. package/examples/frameworks/react/main.tsx +32 -0
  53. package/examples/frameworks/sveltekit/+server.ts +26 -0
  54. package/examples/frameworks/vercel/api/analytics-cron.ts +9 -0
  55. package/examples/frameworks/vercel/api/analytics.ts +22 -0
  56. package/examples/frameworks/vercel/vercel.json +4 -0
  57. package/examples/http/Java.java +74 -0
  58. package/examples/http/curl.sh +46 -0
  59. package/examples/http/go.go +93 -0
  60. package/examples/http/php.php +74 -0
  61. package/examples/http/python.py +62 -0
  62. package/examples/http/ruby.rb +60 -0
  63. package/examples/library/basic.ts +95 -0
  64. package/examples/library/reports.ts +136 -0
  65. package/examples/library/stores.ts +57 -0
  66. package/examples/library/webhook-receiver.ts +30 -0
  67. package/llms.txt +235 -0
  68. package/package.json +116 -4
package/dist/query.js ADDED
@@ -0,0 +1,699 @@
1
+ import { continentOf } from './hit.js';
2
+ /**
3
+ * Pure aggregation. Takes events, returns typed answers. No I/O, no database,
4
+ * so it runs anywhere and is trivial to test.
5
+ */
6
+ const HOUR = 3_600_000;
7
+ const DAY = 86_400_000;
8
+ const MAX_BUCKETS = 2000;
9
+ const round = (n, places) => Math.round(n * 10 ** places) / 10 ** places;
10
+ const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));
11
+ // ── Dimensions ────────────────────────────────────────────────────────────
12
+ export const DIMENSIONS = [
13
+ 'path',
14
+ 'referrer',
15
+ 'source',
16
+ 'channel',
17
+ 'country',
18
+ 'continent',
19
+ 'region',
20
+ 'city',
21
+ 'timezone',
22
+ 'language',
23
+ 'browser',
24
+ 'browser_version',
25
+ 'os',
26
+ 'os_version',
27
+ 'device',
28
+ 'screen',
29
+ 'utm_source',
30
+ 'utm_medium',
31
+ 'utm_campaign',
32
+ 'utm_term',
33
+ 'utm_content',
34
+ 'event',
35
+ 'hostname',
36
+ 'weekday',
37
+ 'hour',
38
+ ];
39
+ /** Everything `top()` accepts: the dimensions, plus entry/exit pages derived from sessions. */
40
+ export const TOP_DIMENSIONS = [...DIMENSIONS, 'entry_page', 'exit_page'];
41
+ const PROP = /^prop:[A-Za-z0-9_.-]{1,40}$/;
42
+ /** A built-in dimension or a `prop:<name>` custom property. */
43
+ export const isDimension = (d) => DIMENSIONS.includes(d) || PROP.test(d);
44
+ const SEARCH = [
45
+ 'google',
46
+ 'bing',
47
+ 'duckduckgo',
48
+ 'yahoo',
49
+ 'baidu',
50
+ 'yandex',
51
+ 'ecosia',
52
+ 'brave',
53
+ 'startpage',
54
+ 'qwant',
55
+ 'kagi',
56
+ 'naver',
57
+ 'seznam',
58
+ ];
59
+ const SOCIAL = [
60
+ 'facebook',
61
+ 'instagram',
62
+ 'twitter',
63
+ 'x.com',
64
+ 't.co',
65
+ 'linkedin',
66
+ 'lnkd.in',
67
+ 'reddit',
68
+ 'youtube',
69
+ 'pinterest',
70
+ 'tiktok',
71
+ 'threads',
72
+ 'mastodon',
73
+ 'bsky',
74
+ 'whatsapp',
75
+ 'telegram',
76
+ 'discord',
77
+ 'news.ycombinator.com',
78
+ ];
79
+ /**
80
+ * `google` matches google.com and www.google.co.uk, where the only labels after
81
+ * the brand are a TLD. `google.evil.com` does not: `evil` is someone else's site.
82
+ * `x.com` matches that host and its subdomains.
83
+ */
84
+ const hostIs = (host, names) => {
85
+ const h = host.toLowerCase();
86
+ return names.some((n) => {
87
+ if (n.includes('.'))
88
+ return h === n || h.endsWith(`.${n}`);
89
+ const labels = h.split('.');
90
+ for (let i = labels.length - 1; i >= 0; i--) {
91
+ if (labels[i] !== n)
92
+ continue;
93
+ const rest = labels.slice(i + 1);
94
+ const head = rest[0];
95
+ if (rest.length === 1 || (rest.length === 2 && head !== undefined && head.length <= 3))
96
+ return true;
97
+ }
98
+ return false;
99
+ });
100
+ };
101
+ /** Where a visit came from, in the usual marketing buckets. */
102
+ function channelOf(e) {
103
+ const medium = e.utm.medium?.toLowerCase() ?? '';
104
+ const host = e.referrerHost;
105
+ if (/^(cpc|ppc|paid|paidsearch|paid-social|display|cpm|banner|retargeting)/.test(medium))
106
+ return 'Paid';
107
+ if (/^(e-?mail|newsletter)/.test(medium) || /^(e-?mail|newsletter)$/i.test(e.utm.source ?? ''))
108
+ return 'Email';
109
+ if (medium === 'social' || (host && hostIs(host, SOCIAL)))
110
+ return 'Social';
111
+ if (host && hostIs(host, SEARCH))
112
+ return 'Organic Search';
113
+ if (host)
114
+ return 'Referral';
115
+ if (e.utm.source || e.utm.campaign || e.utm.medium)
116
+ return 'Campaign';
117
+ return 'Direct';
118
+ }
119
+ const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
120
+ function dimensionValue(e, d) {
121
+ switch (d) {
122
+ case 'path':
123
+ return e.path;
124
+ case 'referrer':
125
+ return e.referrerHost;
126
+ case 'source':
127
+ return e.utm.source ?? e.referrerHost ?? 'Direct';
128
+ case 'channel':
129
+ return channelOf(e);
130
+ case 'country':
131
+ return e.country;
132
+ case 'continent':
133
+ return continentOf(e.country);
134
+ case 'region':
135
+ return e.region;
136
+ case 'city':
137
+ return e.city;
138
+ case 'timezone':
139
+ return e.timezone;
140
+ case 'language':
141
+ return e.language;
142
+ case 'browser':
143
+ return e.browser;
144
+ case 'browser_version':
145
+ return e.browser && e.browserVersion ? `${e.browser} ${e.browserVersion}` : null;
146
+ case 'os':
147
+ return e.os;
148
+ case 'os_version':
149
+ return e.os && e.osVersion ? `${e.os} ${e.osVersion}` : null;
150
+ case 'device':
151
+ return e.device === 'unknown' ? null : e.device;
152
+ case 'screen':
153
+ return e.screen;
154
+ case 'utm_source':
155
+ return e.utm.source;
156
+ case 'utm_medium':
157
+ return e.utm.medium;
158
+ case 'utm_campaign':
159
+ return e.utm.campaign;
160
+ case 'utm_term':
161
+ return e.utm.term;
162
+ case 'utm_content':
163
+ return e.utm.content;
164
+ case 'event':
165
+ return e.type === 'event' ? e.name : null;
166
+ case 'hostname':
167
+ return e.hostname || null;
168
+ case 'weekday':
169
+ return WEEKDAYS[new Date(e.ts).getUTCDay()] ?? null;
170
+ case 'hour':
171
+ return String(new Date(e.ts).getUTCHours()).padStart(2, '0');
172
+ default: {
173
+ // prop:<name>
174
+ const v = e.props[d.slice(5)];
175
+ return v === undefined ? null : String(v);
176
+ }
177
+ }
178
+ }
179
+ export function applyFilters(events, filters) {
180
+ const entries = Object.entries(filters).filter(([, v]) => v !== undefined && v !== '');
181
+ if (entries.length === 0)
182
+ return events;
183
+ return events.filter((e) => entries.every(([d, v]) => dimensionValue(e, d) === v));
184
+ }
185
+ /**
186
+ * Only a session's entry pageview carries a referrer or campaign. Let every later hit
187
+ * (pages, custom events, engagement beacons) inherit it, so a visitor who arrived from
188
+ * Google counts as Google for the whole visit, and "revenue by source" works.
189
+ * A hit that brings its own source (a new campaign landing) replaces the inherited one,
190
+ * and a new session starts after `gapMs` of inactivity.
191
+ */
192
+ export function inheritAttribution(events, gapMs = 30 * 60_000) {
193
+ const byVisitor = new Map();
194
+ for (const e of events) {
195
+ const list = byVisitor.get(e.visitor);
196
+ if (list)
197
+ list.push(e);
198
+ else
199
+ byVisitor.set(e.visitor, [e]);
200
+ }
201
+ const resolved = new Map();
202
+ for (const list of byVisitor.values()) {
203
+ list.sort((a, b) => a.ts - b.ts);
204
+ let source = null;
205
+ let last = -Infinity;
206
+ for (const e of list) {
207
+ if (e.ts - last > gapMs)
208
+ source = null;
209
+ last = e.ts;
210
+ const own = e.referrerHost ||
211
+ e.utm.source ||
212
+ e.utm.medium ||
213
+ e.utm.campaign ||
214
+ e.utm.term ||
215
+ e.utm.content;
216
+ if (own)
217
+ source = { referrer: e.referrer, referrerHost: e.referrerHost, utm: e.utm };
218
+ else if (source)
219
+ resolved.set(e, { ...e, ...source });
220
+ }
221
+ }
222
+ return events.map((e) => resolved.get(e) ?? e);
223
+ }
224
+ /** Latest pageview of the same path. A later beacon replaces an earlier one. */
225
+ function attachEngagement(cur, e) {
226
+ for (let i = cur.hits.length - 1; i >= 0; i--) {
227
+ const h = cur.hits[i];
228
+ if (h.type === 'pageview' && h.path === e.path) {
229
+ const prev = cur.engaged.get(h);
230
+ cur.engaged.set(h, {
231
+ ms: Math.max(prev?.ms ?? 0, e.duration ?? 0),
232
+ scroll: e.scroll ?? prev?.scroll ?? null,
233
+ });
234
+ return true;
235
+ }
236
+ }
237
+ return false;
238
+ }
239
+ /** Group a visitor's hits into sessions split by an inactivity gap. */
240
+ function sessionize(events, gapMs) {
241
+ const byVisitor = new Map();
242
+ for (const e of events) {
243
+ const list = byVisitor.get(e.visitor);
244
+ if (list)
245
+ list.push(e);
246
+ else
247
+ byVisitor.set(e.visitor, [e]);
248
+ }
249
+ const sessions = [];
250
+ for (const list of byVisitor.values()) {
251
+ list.sort((a, b) => a.ts - b.ts);
252
+ let cur = null;
253
+ for (const e of list) {
254
+ if (e.type === 'engagement') {
255
+ // The beacon is the delayed end of a page, sent when the reader leaves.
256
+ // It must not open a session of its own: a 45 minute article would
257
+ // otherwise look like 30 minutes of silence and lose its reading time.
258
+ if (cur && attachEngagement(cur, e))
259
+ cur.end = Math.max(cur.end, e.ts);
260
+ continue;
261
+ }
262
+ if (!cur || e.ts - cur.end > gapMs) {
263
+ if (cur)
264
+ sessions.push(cur);
265
+ cur = { hits: [], engaged: new Map(), end: e.ts };
266
+ }
267
+ cur.end = Math.max(cur.end, e.ts);
268
+ cur.hits.push(e);
269
+ }
270
+ if (cur)
271
+ sessions.push(cur);
272
+ }
273
+ // An engagement beacon whose pageview is outside the range leaves an empty session.
274
+ return sessions.filter((s) => s.hits.length > 0);
275
+ }
276
+ /** Seconds on a pageview: engaged time when the tracker reported it, else the time to the next hit. */
277
+ function pageSeconds(s, i) {
278
+ const h = s.hits[i];
279
+ const eng = s.engaged.get(h);
280
+ if (eng)
281
+ return eng.ms / 1000;
282
+ const next = s.hits[i + 1];
283
+ return next ? (next.ts - h.ts) / 1000 : null;
284
+ }
285
+ export function summary(events, range, sessionMinutes = 30) {
286
+ const sessions = sessionize(events, sessionMinutes * 60_000);
287
+ let pageviews = 0;
288
+ let customEvents = 0;
289
+ let revenue = 0;
290
+ for (const e of events) {
291
+ if (e.type === 'pageview')
292
+ pageviews++;
293
+ else if (e.type === 'event') {
294
+ customEvents++;
295
+ revenue += e.value ?? 0;
296
+ }
297
+ }
298
+ let bounces = 0;
299
+ let lengthSum = 0;
300
+ let lengthN = 0;
301
+ let pageSum = 0;
302
+ let pageN = 0;
303
+ for (const s of sessions) {
304
+ if (s.hits.length === 1 && s.hits[0].type === 'pageview')
305
+ bounces++;
306
+ const length = (s.end - s.hits[0].ts) / 1000;
307
+ if (length > 0) {
308
+ lengthSum += length;
309
+ lengthN++;
310
+ }
311
+ s.hits.forEach((h, i) => {
312
+ if (h.type !== 'pageview')
313
+ return;
314
+ const sec = pageSeconds(s, i);
315
+ if (sec !== null) {
316
+ pageSum += sec;
317
+ pageN++;
318
+ }
319
+ });
320
+ }
321
+ return {
322
+ range,
323
+ pageviews,
324
+ // A beacon is not a visit. Counting it would report a visitor with no pageview and no session.
325
+ visitors: new Set(events.filter((e) => e.type !== 'engagement').map((e) => e.visitor)).size,
326
+ sessions: sessions.length,
327
+ events: customEvents,
328
+ revenue: round(revenue, 2),
329
+ bounceRate: sessions.length ? round(bounces / sessions.length, 4) : 0,
330
+ avgSessionSeconds: lengthN ? Math.round(lengthSum / lengthN) : 0,
331
+ avgTimeOnPageSeconds: pageN ? Math.round(pageSum / pageN) : 0,
332
+ viewsPerSession: sessions.length ? round(pageviews / sessions.length, 2) : 0,
333
+ };
334
+ }
335
+ // ── Time series ───────────────────────────────────────────────────────────
336
+ const STEP = { hour: HOUR, day: DAY, week: 7 * DAY, month: 30 * DAY };
337
+ const COARSER = {
338
+ hour: 'day',
339
+ day: 'week',
340
+ week: 'month',
341
+ month: 'month',
342
+ };
343
+ /** UTC bucket start. Weeks begin on Monday. */
344
+ function bucketStart(t, interval) {
345
+ if (interval === 'hour')
346
+ return Math.floor(t / HOUR) * HOUR;
347
+ const day = Math.floor(t / DAY);
348
+ if (interval === 'day')
349
+ return day * DAY;
350
+ if (interval === 'week')
351
+ return (day - ((day + 3) % 7)) * DAY; // 1970-01-01 was a Thursday
352
+ const d = new Date(t);
353
+ return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1);
354
+ }
355
+ function nextBucket(t, interval) {
356
+ if (interval === 'month') {
357
+ const d = new Date(t);
358
+ return Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1);
359
+ }
360
+ return t + STEP[interval];
361
+ }
362
+ export const autoInterval = (r) => {
363
+ const span = r.to - r.from;
364
+ return span <= 2 * DAY ? 'hour' : span <= 120 * DAY ? 'day' : 'week';
365
+ };
366
+ export function timeseries(events, range, interval = autoInterval(range)) {
367
+ // Never allocate an unbounded number of buckets: coarsen, then clamp the start.
368
+ while (interval !== 'month' && (range.to - range.from) / STEP[interval] > MAX_BUCKETS)
369
+ interval = COARSER[interval];
370
+ const from = Math.max(range.from, range.to - MAX_BUCKETS * STEP[interval]);
371
+ const buckets = new Map();
372
+ for (let t = bucketStart(from, interval); t < range.to; t = nextBucket(t, interval)) {
373
+ buckets.set(t, { pv: 0, ev: 0, v: new Set() });
374
+ }
375
+ for (const e of events) {
376
+ if (e.type === 'engagement')
377
+ continue;
378
+ const b = buckets.get(bucketStart(e.ts, interval));
379
+ if (!b)
380
+ continue;
381
+ if (e.type === 'pageview')
382
+ b.pv++;
383
+ else
384
+ b.ev++;
385
+ b.v.add(e.visitor);
386
+ }
387
+ return [...buckets.entries()].map(([t, b]) => ({
388
+ t,
389
+ pageviews: b.pv,
390
+ events: b.ev,
391
+ visitors: b.v.size,
392
+ }));
393
+ }
394
+ // ── Top lists ─────────────────────────────────────────────────────────────
395
+ export function top(events, by, limit = 10, sessionMinutes = 30) {
396
+ const max = clamp(limit, 1, 100);
397
+ if (by === 'entry_page' || by === 'exit_page')
398
+ return topPages(events, by, max, sessionMinutes);
399
+ // Custom events, and any `prop:<name>` (properties live on events), are counted as events
400
+ // and their values summed. Everything else counts pageviews.
401
+ const isEvent = by === 'event' || by.startsWith('prop:');
402
+ const rows = new Map();
403
+ const row = (key) => {
404
+ let r = rows.get(key);
405
+ if (!r) {
406
+ r = { count: 0, value: 0, v: new Set(), secSum: 0, secN: 0, scrollSum: 0, scrollN: 0 };
407
+ rows.set(key, r);
408
+ }
409
+ return r;
410
+ };
411
+ for (const e of events) {
412
+ if (e.type === 'engagement' || e.type !== (isEvent ? 'event' : 'pageview'))
413
+ continue;
414
+ const key = dimensionValue(e, by);
415
+ if (!key)
416
+ continue;
417
+ const r = row(key);
418
+ r.count++;
419
+ r.value += e.value ?? 0;
420
+ r.v.add(e.visitor);
421
+ }
422
+ // Time on page and scroll depth per path.
423
+ if (by === 'path') {
424
+ for (const s of sessionize(events, sessionMinutes * 60_000)) {
425
+ s.hits.forEach((h, i) => {
426
+ if (h.type !== 'pageview')
427
+ return;
428
+ const r = rows.get(h.path);
429
+ if (!r)
430
+ return;
431
+ const sec = pageSeconds(s, i);
432
+ if (sec !== null) {
433
+ r.secSum += sec;
434
+ r.secN++;
435
+ }
436
+ const scroll = s.engaged.get(h)?.scroll;
437
+ if (scroll !== null && scroll !== undefined) {
438
+ r.scrollSum += scroll;
439
+ r.scrollN++;
440
+ }
441
+ });
442
+ }
443
+ }
444
+ return [...rows.entries()]
445
+ .map(([key, r]) => {
446
+ const out = { key, visitors: r.v.size, count: r.count };
447
+ if (isEvent)
448
+ out.value = round(r.value, 2);
449
+ if (by === 'path') {
450
+ if (r.secN)
451
+ out.seconds = Math.round(r.secSum / r.secN);
452
+ if (r.scrollN)
453
+ out.scroll = Math.round(r.scrollSum / r.scrollN);
454
+ }
455
+ return out;
456
+ })
457
+ .sort((a, b) => b.count - a.count || a.key.localeCompare(b.key))
458
+ .slice(0, max);
459
+ }
460
+ /** Entry / exit pages: the first / last pageview of each session. */
461
+ function topPages(events, by, limit, sessionMinutes) {
462
+ const rows = new Map();
463
+ for (const s of sessionize(events, sessionMinutes * 60_000)) {
464
+ const views = s.hits.filter((e) => e.type === 'pageview');
465
+ const page = by === 'entry_page' ? views[0] : views[views.length - 1];
466
+ if (!page)
467
+ continue;
468
+ let r = rows.get(page.path);
469
+ if (!r) {
470
+ r = { count: 0, v: new Set() };
471
+ rows.set(page.path, r);
472
+ }
473
+ r.count++;
474
+ r.v.add(page.visitor);
475
+ }
476
+ return [...rows.entries()]
477
+ .map(([key, r]) => ({ key, visitors: r.v.size, count: r.count }))
478
+ .sort((a, b) => b.count - a.count || a.key.localeCompare(b.key))
479
+ .slice(0, limit);
480
+ }
481
+ // ── Paths travelled ───────────────────────────────────────────────────────
482
+ /** Recent sessions, newest first, each with the ordered steps the visitor took. */
483
+ export function sessionTraces(events, sessionMinutes = 30, limit = 50) {
484
+ const recent = sessionize(events, sessionMinutes * 60_000)
485
+ .sort((a, b) => b.hits[0].ts - a.hits[0].ts)
486
+ .slice(0, clamp(limit, 1, 500));
487
+ return recent.map((s) => {
488
+ const first = s.hits[0];
489
+ const views = s.hits.filter((h) => h.type === 'pageview');
490
+ const steps = s.hits.map((h, i) => {
491
+ if (h.type === 'event') {
492
+ return {
493
+ t: h.ts,
494
+ type: 'event',
495
+ path: h.path,
496
+ name: h.name,
497
+ ...(h.value !== null && { value: h.value }),
498
+ };
499
+ }
500
+ const seconds = pageSeconds(s, i);
501
+ const scroll = s.engaged.get(h)?.scroll;
502
+ return {
503
+ t: h.ts,
504
+ type: 'pageview',
505
+ path: h.path,
506
+ ...(seconds !== null && { seconds: round(seconds, 1) }),
507
+ ...(scroll !== null && scroll !== undefined && { scroll }),
508
+ };
509
+ });
510
+ return {
511
+ id: `${first.visitor.slice(0, 8)}-${first.ts.toString(36)}`,
512
+ start: first.ts,
513
+ end: s.end,
514
+ seconds: Math.round((s.end - first.ts) / 1000),
515
+ pages: views.length,
516
+ entry: views[0]?.path ?? null,
517
+ exit: views[views.length - 1]?.path ?? null,
518
+ source: dimensionValue(first, 'source') ?? 'Direct',
519
+ channel: channelOf(first),
520
+ country: first.country,
521
+ device: first.device,
522
+ browser: first.browser,
523
+ os: first.os,
524
+ language: first.language,
525
+ screen: first.screen,
526
+ revenue: round(s.hits.reduce((n, h) => n + (h.type === 'event' ? (h.value ?? 0) : 0), 0), 2),
527
+ steps,
528
+ };
529
+ });
530
+ }
531
+ /** The most common routes through the site: each session's first `depth` pages, in order. */
532
+ export function journeys(events, sessionMinutes = 30, depth = 3, limit = 10) {
533
+ const counts = new Map();
534
+ let total = 0;
535
+ for (const s of sessionize(events, sessionMinutes * 60_000)) {
536
+ const path = [];
537
+ for (const h of s.hits) {
538
+ if (h.type === 'pageview' && path[path.length - 1] !== h.path)
539
+ path.push(h.path); // a reload is not a step
540
+ }
541
+ if (path.length === 0)
542
+ continue;
543
+ total++;
544
+ const steps = path.slice(0, clamp(depth, 1, 10));
545
+ const key = steps.join('\n');
546
+ const c = counts.get(key);
547
+ if (c)
548
+ c.n++;
549
+ else
550
+ counts.set(key, { steps, n: 1 });
551
+ }
552
+ return [...counts.values()]
553
+ .sort((a, b) => b.n - a.n || a.steps.join().localeCompare(b.steps.join()))
554
+ .slice(0, clamp(limit, 1, 100))
555
+ .map((c) => ({ steps: c.steps, sessions: c.n, share: round(c.n / total, 4) }));
556
+ }
557
+ // ── Comparison, funnel, realtime, CSV ─────────────────────────────────────
558
+ const delta = (current, previous) => ({
559
+ current,
560
+ previous,
561
+ change: previous === 0 ? null : round((current - previous) / previous, 4),
562
+ });
563
+ export function compare(current, previous) {
564
+ return {
565
+ current,
566
+ previous,
567
+ delta: {
568
+ pageviews: delta(current.pageviews, previous.pageviews),
569
+ visitors: delta(current.visitors, previous.visitors),
570
+ sessions: delta(current.sessions, previous.sessions),
571
+ events: delta(current.events, previous.events),
572
+ revenue: delta(current.revenue, previous.revenue),
573
+ bounceRate: delta(current.bounceRate, previous.bounceRate),
574
+ avgSessionSeconds: delta(current.avgSessionSeconds, previous.avgSessionSeconds),
575
+ },
576
+ };
577
+ }
578
+ const stepLabel = (s) => ('path' in s ? s.path : `event:${s.event}`);
579
+ function stepMatches(e, s) {
580
+ if ('event' in s)
581
+ return e.type === 'event' && e.name === s.event;
582
+ if (e.type !== 'pageview')
583
+ return false;
584
+ // A trailing `*` is a prefix match: `/docs/*`.
585
+ return s.path.endsWith('*') ? e.path.startsWith(s.path.slice(0, -1)) : e.path === s.path;
586
+ }
587
+ /**
588
+ * Ordered funnel. A visitor counts for step N only if they hit steps 1..N in
589
+ * order. Visitor ids rotate daily by design, so a funnel measures within-day journeys.
590
+ */
591
+ export function funnel(events, steps) {
592
+ if (steps.length === 0)
593
+ return [];
594
+ const byVisitor = new Map();
595
+ for (const e of events) {
596
+ const l = byVisitor.get(e.visitor);
597
+ if (l)
598
+ l.push(e);
599
+ else
600
+ byVisitor.set(e.visitor, [e]);
601
+ }
602
+ const reached = new Array(steps.length).fill(0);
603
+ for (const list of byVisitor.values()) {
604
+ list.sort((a, b) => a.ts - b.ts);
605
+ let i = 0;
606
+ for (const e of list) {
607
+ if (i < steps.length && stepMatches(e, steps[i]))
608
+ i++;
609
+ }
610
+ for (let k = 0; k < i; k++)
611
+ reached[k]++;
612
+ }
613
+ return steps.map((s, k) => ({
614
+ step: k + 1,
615
+ label: stepLabel(s),
616
+ visitors: reached[k],
617
+ rate: reached[0] ? round(reached[k] / reached[0], 4) : 0,
618
+ dropoff: k === 0 || !reached[k - 1] ? 0 : round(1 - reached[k] / reached[k - 1], 4),
619
+ }));
620
+ }
621
+ export function realtime(events, now, windowMinutes = 5) {
622
+ const live = events.filter((e) => e.ts >= now - windowMinutes * 60_000 && e.type !== 'engagement');
623
+ return {
624
+ windowMinutes,
625
+ visitors: new Set(live.map((e) => e.visitor)).size,
626
+ pageviews: live.filter((e) => e.type === 'pageview').length,
627
+ topPaths: top(live, 'path', 5),
628
+ };
629
+ }
630
+ const csvCell = (v) => {
631
+ let s = v === null || v === undefined ? '' : String(v);
632
+ // Neutralise spreadsheet formula injection.
633
+ if (/^[=+\-@\t\r]/.test(s))
634
+ s = `'${s}`;
635
+ return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
636
+ };
637
+ export function toCsv(events) {
638
+ const head = [
639
+ 'time',
640
+ 'type',
641
+ 'name',
642
+ 'path',
643
+ 'hostname',
644
+ 'referrer',
645
+ 'utm_source',
646
+ 'utm_medium',
647
+ 'utm_campaign',
648
+ 'utm_term',
649
+ 'utm_content',
650
+ 'browser',
651
+ 'browser_version',
652
+ 'os',
653
+ 'os_version',
654
+ 'device',
655
+ 'screen',
656
+ 'country',
657
+ 'region',
658
+ 'city',
659
+ 'timezone',
660
+ 'language',
661
+ 'value',
662
+ 'duration_ms',
663
+ 'scroll',
664
+ 'props',
665
+ 'visitor',
666
+ ];
667
+ const lines = events.map((e) => [
668
+ new Date(e.ts).toISOString(),
669
+ e.type,
670
+ e.name,
671
+ e.path,
672
+ e.hostname,
673
+ e.referrerHost,
674
+ e.utm.source,
675
+ e.utm.medium,
676
+ e.utm.campaign,
677
+ e.utm.term,
678
+ e.utm.content,
679
+ e.browser,
680
+ e.browserVersion,
681
+ e.os,
682
+ e.osVersion,
683
+ e.device,
684
+ e.screen,
685
+ e.country,
686
+ e.region,
687
+ e.city,
688
+ e.timezone,
689
+ e.language,
690
+ e.value,
691
+ e.duration,
692
+ e.scroll,
693
+ Object.keys(e.props).length ? JSON.stringify(e.props) : '',
694
+ e.visitor,
695
+ ]
696
+ .map(csvCell)
697
+ .join(','));
698
+ return `${[head.join(','), ...lines].join('\n')}\n`;
699
+ }