@byline/analytics 4.16.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 (41) hide show
  1. package/LICENSE +373 -0
  2. package/README.md +41 -0
  3. package/dist/analytics.d.ts +40 -0
  4. package/dist/analytics.js +221 -0
  5. package/dist/analytics.test.node.d.ts +8 -0
  6. package/dist/analytics.test.node.js +216 -0
  7. package/dist/browser-boundary.test.node.d.ts +8 -0
  8. package/dist/browser-boundary.test.node.js +26 -0
  9. package/dist/config.d.ts +52 -0
  10. package/dist/config.js +92 -0
  11. package/dist/config.test.node.d.ts +8 -0
  12. package/dist/config.test.node.js +30 -0
  13. package/dist/crawler-user-agents.d.ts +8 -0
  14. package/dist/crawler-user-agents.js +11 -0
  15. package/dist/date.d.ts +13 -0
  16. package/dist/date.js +31 -0
  17. package/dist/dedupe.d.ts +18 -0
  18. package/dist/dedupe.js +37 -0
  19. package/dist/index.d.ts +16 -0
  20. package/dist/index.js +15 -0
  21. package/dist/maintenance.d.ts +29 -0
  22. package/dist/maintenance.js +68 -0
  23. package/dist/maintenance.test.node.d.ts +8 -0
  24. package/dist/maintenance.test.node.js +46 -0
  25. package/dist/metrics.d.ts +18 -0
  26. package/dist/metrics.js +67 -0
  27. package/dist/normalize.d.ts +21 -0
  28. package/dist/normalize.js +90 -0
  29. package/dist/privacy-statement.d.ts +29 -0
  30. package/dist/privacy-statement.js +43 -0
  31. package/dist/privacy-statement.test.node.d.ts +8 -0
  32. package/dist/privacy-statement.test.node.js +32 -0
  33. package/dist/runtime.d.ts +15 -0
  34. package/dist/runtime.js +33 -0
  35. package/dist/types.d.ts +166 -0
  36. package/dist/types.js +8 -0
  37. package/dist/visitor.d.ts +10 -0
  38. package/dist/visitor.js +24 -0
  39. package/dist/visitor.test.node.d.ts +8 -0
  40. package/dist/visitor.test.node.js +19 -0
  41. package/package.json +74 -0
@@ -0,0 +1,68 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ import { defineRecurringTask } from '@byline/core';
9
+ import { ANALYTICS_EVENT_RETENTION_DAYS } from './config.js';
10
+ import { addAnalyticsDays, analyticsDay, compareAnalyticsDays, startOfAnalyticsDay, } from './date.js';
11
+ export async function runAnalyticsMaintenance(options, context) {
12
+ const now = (options.now ?? (() => new Date()))();
13
+ // The recurring task also acts as the daily metrics flush when ingest is idle.
14
+ options.analytics.metrics.snapshot(now);
15
+ const yesterday = addAnalyticsDays(analyticsDay(now), -1);
16
+ const maxDays = validateMaxDays(options.maxDaysPerRun ?? 7);
17
+ const store = options.analytics.store;
18
+ const cursor = await store.getRollupCursor();
19
+ const earliest = cursor == null ? await store.getEarliestEventDay() : null;
20
+ let nextDay = cursor == null ? (earliest ?? yesterday) : addAnalyticsDays(cursor, 1);
21
+ const processedDays = [];
22
+ while (compareAnalyticsDays(nextDay, yesterday) <= 0 &&
23
+ processedDays.length < maxDays &&
24
+ context?.signal?.aborted !== true) {
25
+ await store.rebuildDay({
26
+ day: nextDay,
27
+ pathCardinalityCap: options.analytics.config.pathCardinalityCap,
28
+ referrerCardinalityCap: options.analytics.config.referrerCardinalityCap,
29
+ advanceCursor: true,
30
+ });
31
+ processedDays.push(nextDay);
32
+ nextDay = addAnalyticsDays(nextDay, 1);
33
+ await context?.heartbeat?.();
34
+ }
35
+ const workRemaining = compareAnalyticsDays(nextDay, yesterday) <= 0;
36
+ if (!workRemaining) {
37
+ const today = analyticsDay(now);
38
+ await store.prune({
39
+ eventsBefore: startOfAnalyticsDay(addAnalyticsDays(today, -ANALYTICS_EVENT_RETENTION_DAYS)),
40
+ saltsBefore: addAnalyticsDays(today, -1),
41
+ pathAggregatesBefore: options.analytics.config.pathRetentionDays == null
42
+ ? null
43
+ : addAnalyticsDays(today, -options.analytics.config.pathRetentionDays),
44
+ referrerAggregatesBefore: options.analytics.config.referrerRetentionDays == null
45
+ ? null
46
+ : addAnalyticsDays(today, -options.analytics.config.referrerRetentionDays),
47
+ });
48
+ }
49
+ return { processedDays, workRemaining };
50
+ }
51
+ export function defineAnalyticsRollupTask(options) {
52
+ return defineRecurringTask({
53
+ name: 'analytics.rollup',
54
+ intervalMs: options.intervalMs ?? 60 * 60_000,
55
+ leaseMs: options.leaseMs ?? 5 * 60_000,
56
+ async run(context) {
57
+ const result = await runAnalyticsMaintenance(options, context);
58
+ context.logger.info({ processedDays: result.processedDays.length, workRemaining: result.workRemaining }, '[analytics] rollup maintenance completed');
59
+ return { workRemaining: result.workRemaining };
60
+ },
61
+ });
62
+ }
63
+ function validateMaxDays(value) {
64
+ if (!Number.isSafeInteger(value) || value < 1) {
65
+ throw new Error('analytics maxDaysPerRun must be a positive integer');
66
+ }
67
+ return value;
68
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ export {};
@@ -0,0 +1,46 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ import { describe, expect, it, vi } from 'vitest';
9
+ import { createAnalytics } from './analytics.js';
10
+ import { runAnalyticsMaintenance } from './maintenance.js';
11
+ describe('runAnalyticsMaintenance', () => {
12
+ it('catches up complete days in bounded batches and prunes only after catch-up', async () => {
13
+ const rebuildDay = vi.fn(async () => { });
14
+ const prune = vi.fn(async () => ({
15
+ events: 0,
16
+ salts: 0,
17
+ pathAggregates: 0,
18
+ referrerAggregates: 0,
19
+ }));
20
+ const store = {
21
+ getRollupCursor: async () => '2026-08-18',
22
+ getEarliestEventDay: async () => null,
23
+ getEarliestReportDay: async () => null,
24
+ rebuildDay,
25
+ prune,
26
+ };
27
+ const analytics = createAnalytics({ store, publicDomains: ['example.com'] });
28
+ const heartbeat = vi.fn(async () => { });
29
+ const first = await runAnalyticsMaintenance({ analytics, maxDaysPerRun: 2, now: () => new Date('2026-08-23T12:00:00.000Z') }, { heartbeat });
30
+ expect(first).toEqual({
31
+ processedDays: ['2026-08-19', '2026-08-20'],
32
+ workRemaining: true,
33
+ });
34
+ expect(prune).not.toHaveBeenCalled();
35
+ store.getRollupCursor = async () => '2026-08-20';
36
+ const second = await runAnalyticsMaintenance({ analytics, maxDaysPerRun: 5, now: () => new Date('2026-08-23T12:00:00.000Z') }, { heartbeat });
37
+ expect(second).toEqual({ processedDays: ['2026-08-21', '2026-08-22'], workRemaining: false });
38
+ expect(prune).toHaveBeenCalledWith({
39
+ eventsBefore: new Date('2026-05-25T00:00:00.000Z'),
40
+ saltsBefore: '2026-08-22',
41
+ pathAggregatesBefore: null,
42
+ referrerAggregatesBefore: null,
43
+ });
44
+ expect(heartbeat).toHaveBeenCalledTimes(4);
45
+ });
46
+ });
@@ -0,0 +1,18 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ import type { BylineLogger } from '@byline/core';
9
+ import type { AnalyticsIngestResult, AnalyticsMetricsSnapshot } from './types.js';
10
+ export declare class AnalyticsMetrics {
11
+ #private;
12
+ private logger?;
13
+ constructor(now: Date, logger?: BylineLogger | undefined);
14
+ setLogger(logger: BylineLogger): void;
15
+ record(result: AnalyticsIngestResult, now: Date): void;
16
+ snapshot(now?: Date): AnalyticsMetricsSnapshot;
17
+ private rotate;
18
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ import { analyticsDay } from './date.js';
9
+ const OUTCOMES = [
10
+ 'origin',
11
+ 'admin-path',
12
+ 'bot',
13
+ 'prefetch',
14
+ 'client-ip',
15
+ 'dedupe',
16
+ 'method',
17
+ 'body-size',
18
+ 'malformed',
19
+ ];
20
+ export class AnalyticsMetrics {
21
+ logger;
22
+ #day;
23
+ #accepted = 0;
24
+ #drops = emptyDrops();
25
+ #previousAccepted = null;
26
+ constructor(now, logger) {
27
+ this.logger = logger;
28
+ this.#day = analyticsDay(now);
29
+ }
30
+ setLogger(logger) {
31
+ this.logger = logger;
32
+ }
33
+ record(result, now) {
34
+ this.rotate(now);
35
+ if (result.accepted)
36
+ this.#accepted += 1;
37
+ else
38
+ this.#drops[result.reason] += 1;
39
+ }
40
+ snapshot(now = new Date()) {
41
+ this.rotate(now);
42
+ return {
43
+ day: this.#day,
44
+ accepted: this.#accepted,
45
+ drops: { ...this.#drops },
46
+ };
47
+ }
48
+ rotate(now) {
49
+ const nextDay = analyticsDay(now);
50
+ if (nextDay === this.#day)
51
+ return;
52
+ const snapshot = { day: this.#day, accepted: this.#accepted, drops: { ...this.#drops } };
53
+ this.logger?.info({ analytics: snapshot }, '[analytics] daily ingest counters');
54
+ if (this.#previousAccepted != null &&
55
+ this.#previousAccepted > 0 &&
56
+ this.#accepted > this.#previousAccepted * 5) {
57
+ this.logger?.warn({ day: this.#day, accepted: this.#accepted, previousAccepted: this.#previousAccepted }, '[analytics] accepted events increased by more than 5x day over day');
58
+ }
59
+ this.#previousAccepted = this.#accepted;
60
+ this.#day = nextDay;
61
+ this.#accepted = 0;
62
+ this.#drops = emptyDrops();
63
+ }
64
+ }
65
+ function emptyDrops() {
66
+ return Object.fromEntries(OUTCOMES.map((outcome) => [outcome, 0]));
67
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ import type { AnalyticsEventKind } from './types.js';
9
+ interface BeaconPayload {
10
+ v: 1;
11
+ kind: AnalyticsEventKind;
12
+ path: string;
13
+ ref: string;
14
+ }
15
+ export declare function parseBeaconPayload(body: string): BeaconPayload | null;
16
+ export declare function normalizeAnalyticsPath(value: string): string | null;
17
+ export declare function isIgnoredAnalyticsPath(path: string, prefixes: readonly string[]): boolean;
18
+ export declare function requestHost(origin: string | null | undefined, referer: string | null | undefined): string | null;
19
+ export declare function normalizeReferrerHost(referrer: string, publicDomains: ReadonlySet<string>): string | null;
20
+ export declare function normalizeCountry(value: string | null | undefined): string | null;
21
+ export {};
@@ -0,0 +1,90 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ import { ANALYTICS_MAX_PATH_LENGTH, ANALYTICS_OVERFLOW_KEY } from './config.js';
9
+ const PAYLOAD_KEYS = ['kind', 'path', 'ref', 'v'];
10
+ export function parseBeaconPayload(body) {
11
+ let value;
12
+ try {
13
+ value = JSON.parse(body);
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ if (value == null || typeof value !== 'object' || Array.isArray(value))
19
+ return null;
20
+ const record = value;
21
+ const keys = Object.keys(record).sort();
22
+ if (keys.length !== PAYLOAD_KEYS.length ||
23
+ keys.some((key, index) => key !== PAYLOAD_KEYS[index])) {
24
+ return null;
25
+ }
26
+ if (record.v !== 1 || (record.kind !== 'page' && record.kind !== 'download'))
27
+ return null;
28
+ if (typeof record.path !== 'string' || typeof record.ref !== 'string')
29
+ return null;
30
+ return { v: 1, kind: record.kind, path: record.path, ref: record.ref };
31
+ }
32
+ export function normalizeAnalyticsPath(value) {
33
+ if (!value.startsWith('/') || hasUnpairedSurrogate(value))
34
+ return null;
35
+ const withoutQuery = value.split(/[?#]/u, 1)[0] ?? '';
36
+ const collapsed = withoutQuery.replace(/\/{2,}/gu, '/');
37
+ const codePoints = [...collapsed];
38
+ const capped = codePoints.slice(0, ANALYTICS_MAX_PATH_LENGTH).join('');
39
+ return capped.length === 0 ? '/' : capped;
40
+ }
41
+ export function isIgnoredAnalyticsPath(path, prefixes) {
42
+ return prefixes.some((prefix) => {
43
+ if (prefix === '/')
44
+ return true;
45
+ return path === prefix || path.startsWith(`${prefix}/`);
46
+ });
47
+ }
48
+ export function requestHost(origin, referer) {
49
+ const source = origin?.trim() || referer?.trim();
50
+ if (!source || source === 'null')
51
+ return null;
52
+ try {
53
+ return new URL(source).host.toLowerCase().replace(/\.$/, '');
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
59
+ export function normalizeReferrerHost(referrer, publicDomains) {
60
+ if (referrer.trim().length === 0)
61
+ return null;
62
+ try {
63
+ const host = new URL(referrer).host.toLowerCase().replace(/\.$/, '');
64
+ if (host.length === 0 || host === ANALYTICS_OVERFLOW_KEY || publicDomains.has(host))
65
+ return null;
66
+ return [...host].slice(0, 255).join('');
67
+ }
68
+ catch {
69
+ return null;
70
+ }
71
+ }
72
+ export function normalizeCountry(value) {
73
+ const country = value?.trim().toUpperCase();
74
+ return country != null && /^[A-Z]{2}$/u.test(country) ? country : null;
75
+ }
76
+ function hasUnpairedSurrogate(value) {
77
+ for (let index = 0; index < value.length; index += 1) {
78
+ const unit = value.charCodeAt(index);
79
+ if (unit >= 0xd800 && unit <= 0xdbff) {
80
+ const next = value.charCodeAt(index + 1);
81
+ if (next < 0xdc00 || next > 0xdfff)
82
+ return true;
83
+ index += 1;
84
+ }
85
+ else if (unit >= 0xdc00 && unit <= 0xdfff) {
86
+ return true;
87
+ }
88
+ }
89
+ return false;
90
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ export interface AnalyticsPrivacyStatementOptions {
9
+ /** Public name of the site or organization operating this installation. */
10
+ operatorName: string;
11
+ /** Deployment-specific instructions for setting the browser-local exclusion flag. */
12
+ exclusionInstructions: string;
13
+ /** Match the configured aggregate retention; `null` means indefinite. */
14
+ pathRetentionDays?: number | null;
15
+ /** Match the configured aggregate retention; `null` means indefinite. */
16
+ referrerRetentionDays?: number | null;
17
+ title?: string;
18
+ }
19
+ export interface AnalyticsPrivacyStatement {
20
+ title: string;
21
+ paragraphs: readonly string[];
22
+ /** This reminder is intentionally separate from public-facing copy. */
23
+ operatorNotice: string;
24
+ }
25
+ /**
26
+ * Build editable, plain-text privacy copy that stays aligned with the v1 data
27
+ * model. Deployments must review and publish it as part of their own notice.
28
+ */
29
+ export declare function createAnalyticsPrivacyStatement(options: AnalyticsPrivacyStatementOptions): AnalyticsPrivacyStatement;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ import { ANALYTICS_EVENT_RETENTION_DAYS } from './config.js';
9
+ /**
10
+ * Build editable, plain-text privacy copy that stays aligned with the v1 data
11
+ * model. Deployments must review and publish it as part of their own notice.
12
+ */
13
+ export function createAnalyticsPrivacyStatement(options) {
14
+ const operatorName = requiredText(options.operatorName, 'operatorName');
15
+ const exclusionInstructions = requiredText(options.exclusionInstructions, 'exclusionInstructions');
16
+ const pathRetention = retentionText(options.pathRetentionDays);
17
+ const referrerRetention = retentionText(options.referrerRetentionDays);
18
+ return {
19
+ title: options.title?.trim() || `${operatorName} analytics privacy`,
20
+ paragraphs: [
21
+ `${operatorName} uses first-party analytics to count page views, daily unique visitors, and download clicks. The analytics feature sets no cookies and does not create an identifier that follows a visitor across days.`,
22
+ `For each event, the server uses the request IP address and browser user agent to derive a pseudonymous identifier under a random salt that changes every UTC day. The raw IP address is not stored or logged by the analytics feature.`,
23
+ `Raw analytics events are retained for up to ${ANALYTICS_EVENT_RETENTION_DAYS} days. Daily site and country totals are retained indefinitely. Daily page totals are ${pathRetention}, and daily referrer totals are ${referrerRetention}. Daily aggregates contain no visitor identifier.`,
24
+ `The analytics feature does not sell or share event data with third parties and does not use it for cross-context targeted advertising.`,
25
+ exclusionInstructions,
26
+ ],
27
+ operatorNotice: 'Template only, not legal advice. Review the final notice for the deployment and update it before changing collection, retention, sharing, or identification behavior.',
28
+ };
29
+ }
30
+ function requiredText(value, label) {
31
+ const text = value.trim();
32
+ if (text === '')
33
+ throw new Error(`analytics privacy ${label} must not be blank`);
34
+ return text;
35
+ }
36
+ function retentionText(days) {
37
+ if (days == null)
38
+ return 'retained indefinitely';
39
+ if (!Number.isSafeInteger(days) || days < 1) {
40
+ throw new Error('analytics privacy retention days must be positive integers or null');
41
+ }
42
+ return `retained for up to ${days} days`;
43
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ export {};
@@ -0,0 +1,32 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ import { describe, expect, it } from 'vitest';
9
+ import { createAnalyticsPrivacyStatement } from './privacy-statement.js';
10
+ describe('createAnalyticsPrivacyStatement', () => {
11
+ it('renders deployment-specific retention and exclusion copy', () => {
12
+ const statement = createAnalyticsPrivacyStatement({
13
+ operatorName: 'Example News',
14
+ exclusionInstructions: 'Use the Exclude my visits control on this site.',
15
+ pathRetentionDays: 365,
16
+ referrerRetentionDays: null,
17
+ });
18
+ expect(statement.title).toBe('Example News analytics privacy');
19
+ expect(statement.paragraphs.join(' ')).toContain('up to 90 days');
20
+ expect(statement.paragraphs.join(' ')).toContain('up to 365 days');
21
+ expect(statement.paragraphs.join(' ')).toContain('referrer totals are retained indefinitely');
22
+ expect(statement.paragraphs.at(-1)).toBe('Use the Exclude my visits control on this site.');
23
+ });
24
+ it('rejects blank deployment copy and invalid retention', () => {
25
+ expect(() => createAnalyticsPrivacyStatement({ operatorName: '', exclusionInstructions: 'Use opt-out.' })).toThrow('operatorName');
26
+ expect(() => createAnalyticsPrivacyStatement({
27
+ operatorName: 'Example',
28
+ exclusionInstructions: 'Use opt-out.',
29
+ pathRetentionDays: 0,
30
+ })).toThrow('retention');
31
+ });
32
+ });
@@ -0,0 +1,15 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ import type { Analytics } from './analytics.js';
9
+ /** Register the installation-scoped analytics runtime for host integrations. */
10
+ export declare function registerAnalytics(analytics: Analytics): Analytics;
11
+ /** Return the registered runtime, or `null` when analytics is not enabled. */
12
+ export declare function tryGetAnalytics(): Analytics | null;
13
+ /** Return the registered runtime and fail loudly when the subsystem is disabled. */
14
+ export declare function getAnalytics(): Analytics;
15
+ export declare function isAnalyticsRegistered(): boolean;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ const BYLINE_ANALYTICS_RUNTIME = Symbol.for('__byline_analytics_runtime__');
9
+ function runtimeSlot() {
10
+ return globalThis;
11
+ }
12
+ /** Register the installation-scoped analytics runtime for host integrations. */
13
+ export function registerAnalytics(analytics) {
14
+ runtimeSlot()[BYLINE_ANALYTICS_RUNTIME] = analytics;
15
+ return analytics;
16
+ }
17
+ /** Return the registered runtime, or `null` when analytics is not enabled. */
18
+ export function tryGetAnalytics() {
19
+ if ('window' in globalThis)
20
+ return null;
21
+ return runtimeSlot()[BYLINE_ANALYTICS_RUNTIME] ?? null;
22
+ }
23
+ /** Return the registered runtime and fail loudly when the subsystem is disabled. */
24
+ export function getAnalytics() {
25
+ const analytics = tryGetAnalytics();
26
+ if (analytics == null) {
27
+ throw new Error('Byline analytics has not been registered. Call registerAnalytics() during server startup.');
28
+ }
29
+ return analytics;
30
+ }
31
+ export function isAnalyticsRegistered() {
32
+ return tryGetAnalytics() != null;
33
+ }
@@ -0,0 +1,166 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ /** A UTC calendar day in `YYYY-MM-DD` form. */
9
+ export type AnalyticsDay = string;
10
+ export type AnalyticsEventKind = 'page' | 'download';
11
+ export type AnalyticsEventSource = 'beacon' | 'redirect' | 'cdnlog';
12
+ /** The only event shape a storage driver receives. Raw IP is deliberately absent. */
13
+ export interface AnalyticsEvent {
14
+ occurredAt: Date;
15
+ kind: AnalyticsEventKind;
16
+ source: AnalyticsEventSource;
17
+ path: string;
18
+ visitorHash: string;
19
+ referrerHost: string | null;
20
+ country: string | null;
21
+ }
22
+ export interface AnalyticsSummaryDay {
23
+ day: AnalyticsDay;
24
+ views: number;
25
+ visitors: number;
26
+ downloads: number;
27
+ }
28
+ export interface AnalyticsSummary {
29
+ views: number;
30
+ visitors: number;
31
+ downloads: number;
32
+ /** Visitor totals are sums of daily uniques; hashes never link UTC days. */
33
+ timeseries: AnalyticsSummaryDay[];
34
+ }
35
+ export interface AnalyticsPathTotal {
36
+ path: string;
37
+ views: number;
38
+ /** Sum of per-day unique visitors, not a cross-day distinct count. */
39
+ visitors: number;
40
+ }
41
+ export interface AnalyticsReferrerTotal {
42
+ referrerHost: string;
43
+ views: number;
44
+ /** Sum of per-day unique visitors, not a cross-day distinct count. */
45
+ visitors: number;
46
+ }
47
+ export interface AnalyticsCountryTotal {
48
+ country: string;
49
+ views: number;
50
+ /** Sum of per-day unique visitors, not a cross-day distinct count. */
51
+ visitors: number;
52
+ }
53
+ /**
54
+ * A ranked list plus the size of the set it was drawn from.
55
+ *
56
+ * `total` is the number of distinct keys in the period *before* the top-N limit,
57
+ * so the interface can say "top 20 of 143" instead of presenting a truncated
58
+ * list as though it were the whole one. It is bounded by the rollup's
59
+ * cardinality cap for days already processed: paths past that cap were folded
60
+ * into the reserved overflow row, which counts as one key, not many.
61
+ */
62
+ export interface AnalyticsRankedTotals<Row> {
63
+ rows: Row[];
64
+ total: number;
65
+ }
66
+ export interface AnalyticsDateRange {
67
+ from: AnalyticsDay;
68
+ to: AnalyticsDay;
69
+ }
70
+ /**
71
+ * Earliest UTC days for which each report dimension is complete under the
72
+ * current retention configuration. Headline totals and countries are retained
73
+ * indefinitely. Paths (including downloads) and referrers may begin later when
74
+ * their configured aggregate retention is finite.
75
+ */
76
+ export interface AnalyticsReportCoverage {
77
+ summaryFrom: AnalyticsDay | null;
78
+ pathsFrom: AnalyticsDay | null;
79
+ referrersFrom: AnalyticsDay | null;
80
+ }
81
+ export interface AnalyticsTopQuery extends AnalyticsDateRange {
82
+ kind: AnalyticsEventKind;
83
+ limit?: number;
84
+ }
85
+ export interface AnalyticsLimitQuery extends AnalyticsDateRange {
86
+ limit?: number;
87
+ }
88
+ export interface AnalyticsRollupDayOptions {
89
+ day: AnalyticsDay;
90
+ pathCardinalityCap: number;
91
+ referrerCardinalityCap: number;
92
+ /** Manual repair rebuilds a day without moving the sequential cursor. */
93
+ advanceCursor: boolean;
94
+ }
95
+ export interface AnalyticsPruneOptions {
96
+ eventsBefore: Date;
97
+ saltsBefore: AnalyticsDay;
98
+ pathAggregatesBefore: AnalyticsDay | null;
99
+ referrerAggregatesBefore: AnalyticsDay | null;
100
+ }
101
+ export interface AnalyticsPruneResult {
102
+ events: number;
103
+ salts: number;
104
+ pathAggregates: number;
105
+ referrerAggregates: number;
106
+ }
107
+ export interface AnalyticsDeleteEventsOptions {
108
+ from: Date;
109
+ to: Date;
110
+ visitorHash?: string;
111
+ }
112
+ /**
113
+ * Database-neutral storage contract. SQL drivers own schemas, migrations, and
114
+ * transaction boundaries; analytics owns behavior and orchestration.
115
+ */
116
+ export interface AnalyticsStore {
117
+ /** Insert the candidate salt if absent, then return the row that won. */
118
+ getOrCreateDailySalt(day: AnalyticsDay, candidate: Uint8Array): Promise<Uint8Array>;
119
+ insertEvent(event: AnalyticsEvent): Promise<void>;
120
+ getRollupCursor(): Promise<AnalyticsDay | null>;
121
+ getEarliestEventDay(): Promise<AnalyticsDay | null>;
122
+ /** Earliest day present in either retained headline aggregates or raw events. */
123
+ getEarliestReportDay(): Promise<AnalyticsDay | null>;
124
+ rebuildDay(options: AnalyticsRollupDayOptions): Promise<void>;
125
+ prune(options: AnalyticsPruneOptions): Promise<AnalyticsPruneResult>;
126
+ getSummary(range: AnalyticsDateRange): Promise<AnalyticsSummaryDay[]>;
127
+ getTopPaths(query: Required<AnalyticsTopQuery>): Promise<AnalyticsRankedTotals<AnalyticsPathTotal>>;
128
+ getReferrers(query: Required<AnalyticsLimitQuery>): Promise<AnalyticsRankedTotals<AnalyticsReferrerTotal>>;
129
+ getCountries(range: AnalyticsDateRange): Promise<AnalyticsCountryTotal[]>;
130
+ deleteEvents(options: AnalyticsDeleteEventsOptions): Promise<number>;
131
+ }
132
+ export type AnalyticsDropReason = 'origin' | 'admin-path' | 'bot' | 'prefetch' | 'client-ip' | 'dedupe';
133
+ export type AnalyticsRejectReason = 'method' | 'body-size' | 'malformed';
134
+ export type AnalyticsIngestResult = {
135
+ status: 202;
136
+ accepted: true;
137
+ } | {
138
+ status: 204;
139
+ accepted: false;
140
+ reason: AnalyticsDropReason;
141
+ } | {
142
+ status: 400;
143
+ accepted: false;
144
+ reason: AnalyticsRejectReason;
145
+ };
146
+ /**
147
+ * Host-normalized request data. The trusted bridge supplies `clientIp` and
148
+ * `country`; analytics never reads forwarding headers and never persists or
149
+ * logs `clientIp`.
150
+ */
151
+ export interface AnalyticsIngestRequest {
152
+ method: string;
153
+ body: string | Uint8Array;
154
+ origin?: string | null;
155
+ referer?: string | null;
156
+ userAgent?: string | null;
157
+ secPurpose?: string | null;
158
+ xPurpose?: string | null;
159
+ clientIp?: string | null;
160
+ country?: string | null;
161
+ }
162
+ export interface AnalyticsMetricsSnapshot {
163
+ day: AnalyticsDay;
164
+ accepted: number;
165
+ drops: Record<AnalyticsDropReason | AnalyticsRejectReason, number>;
166
+ }
package/dist/types.js ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ export {};