@kk-forge/artel-collector 0.4.0 → 0.5.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.
@@ -1,11 +1,11 @@
1
- import { AnalyticsState, Mode } from './collectorTypes.js';
2
- import { Platform, type Envelope, type IdKind } from './envelope.js';
1
+ import { AnalyticsState, Mode } from "./collectorTypes.js";
2
+ import { Platform, type Envelope, type IdKind } from "./envelope.js";
3
3
  export interface Build {
4
4
  platform: Platform;
5
5
  version: string;
6
6
  }
7
7
  /** The fields that name the product build, as an envelope and the uninstall page carry them. */
8
- export type ProductFields = Pick<Envelope, 'platform' | 'version' | 'browser_language' | 'ui_language'>;
8
+ export type ProductFields = Pick<Envelope, "platform" | "version" | "browser_language" | "ui_language">;
9
9
  /** Everything the collector shapes by the user's state. */
10
10
  export interface StateFields {
11
11
  /** Whether the state records the user's events. Only `opted_out` records none. */
@@ -23,7 +23,7 @@ export declare function isAnalyticsState(value: unknown): value is AnalyticsStat
23
23
  /** Tells whether a channel of `mode` takes `state`: a state up to its mode. A mode that does not exist is anonymous. */
24
24
  export declare function channelTakes(mode: Mode, state: unknown): state is AnalyticsState;
25
25
  /** Returns whether events of this build may carry a page, which the intake keeps only from a site channel. */
26
- export declare function carriesPage(build: Pick<Build, 'platform'>): boolean;
26
+ export declare function carriesPage(build: Pick<Build, "platform">): boolean;
27
27
  /**
28
28
  * Returns what the collector sends in `state` for this build and these languages. Only a state with an id carries the
29
29
  * full languages and the exact ages: with the platform and version they can single out a user, so they go only with the
@@ -1,6 +1,6 @@
1
- import { AnalyticsState, Mode } from './collectorTypes.js';
2
- import { Platform } from './envelope.js';
3
- import { primaryLanguage } from './fields.js';
1
+ import { AnalyticsState, Mode } from "./collectorTypes.js";
2
+ import { Platform } from "./envelope.js";
3
+ import { primaryLanguage } from "./fields.js";
4
4
  /** Ranks the modes and the states by what they reveal of a user. A mode takes the states of a rank up to its own. */
5
5
  const MODE_RANKS = new Map([
6
6
  [Mode.Anonymous, 0],
@@ -30,7 +30,9 @@ export function carriesPage(build) {
30
30
  * consent the id needs.
31
31
  */
32
32
  export function fieldsForState({ state, build, browserLanguage, uiLanguage, }) {
33
- const idKind = state === AnalyticsState.Pseudonymous || state === AnalyticsState.Identified ? state : undefined;
33
+ const idKind = state === AnalyticsState.Pseudonymous || state === AnalyticsState.Identified
34
+ ? state
35
+ : undefined;
34
36
  const isNamed = idKind !== undefined;
35
37
  const shape = (tag) => tag === undefined || isNamed ? tag : primaryLanguage(tag);
36
38
  const shapedBrowserLanguage = shape(browserLanguage);
package/dist/testing.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { Mode, type Collector } from './collectorTypes.js';
2
- import type { EventParams } from './envelope.js';
3
- import { type StorageAdapter } from './storage.js';
1
+ import { type Clock } from "./clock.js";
2
+ import { Mode, type Collector } from "./collectorTypes.js";
3
+ import type { EventParams } from "./envelope.js";
4
+ import { type StorageAdapter } from "./storage.js";
4
5
  /** One event as a product tracked it. */
5
6
  export interface RecordedEvent {
6
7
  name: string;
@@ -16,10 +17,12 @@ export type RecordingCollector<M extends Mode = Mode> = Collector<M> & {
16
17
  * real collector would send. Its user starts in the anonymous state. It refuses an event `track` refuses, a state above
17
18
  * the mode and an id `forget` refuses, with the same report to `onError`. It records `opted_out` at the opt-out, and
18
19
  * nothing in the opted_out state. It keeps one version: `installed` records once, and `updated` only while neither of
19
- * them recorded. `uninstallParams` resolves to undefined.
20
+ * them recorded. It drops a call with `throttleMs` as `track` does, by `clock`. `uninstallParams` resolves to undefined.
20
21
  */
21
- export declare function newRecordingCollector<M extends Mode = typeof Mode.Anonymous>(mode?: M, { onError }?: {
22
+ export declare function newRecordingCollector<M extends Mode = typeof Mode.Anonymous>(mode?: M, { onError, clock, }?: {
22
23
  onError?: (error: Error) => void;
24
+ /** The clock of the `throttleMs` windows of `track`, the system's by default. */
25
+ clock?: Clock;
23
26
  }): RecordingCollector<M>;
24
27
  /**
25
28
  * Resolves to the events a collector of channel `key` holds queued in `storage`, oldest first, so a product's test reads
package/dist/testing.js CHANGED
@@ -1,47 +1,57 @@
1
- import { AnalyticsState, Mode } from './collectorTypes.js';
2
- import { acceptedEvent } from './eventCheck.js';
3
- import { isUsableId, quoted, reportTo } from './hostInput.js';
4
- import { parseQueue, QUEUE_KEY } from './queue.js';
5
- import { channelTakes } from './stateFields.js';
6
- import { newChannelStorage } from './storage.js';
1
+ import { systemClock } from "./clock.js";
2
+ import { AnalyticsState, Mode } from "./collectorTypes.js";
3
+ import { acceptedEvent } from "./eventCheck.js";
4
+ import { isUsableId, quoted, reportTo } from "./hostInput.js";
5
+ import { parseQueue, QUEUE_KEY } from "./queue.js";
6
+ import { channelTakes } from "./stateFields.js";
7
+ import { newChannelStorage } from "./storage.js";
8
+ import { newThrottle } from "./throttle.js";
7
9
  /**
8
10
  * Returns a collector of channel mode `mode`, `anonymous` by default, that sends nothing and records each event the
9
11
  * real collector would send. Its user starts in the anonymous state. It refuses an event `track` refuses, a state above
10
12
  * the mode and an id `forget` refuses, with the same report to `onError`. It records `opted_out` at the opt-out, and
11
13
  * nothing in the opted_out state. It keeps one version: `installed` records once, and `updated` only while neither of
12
- * them recorded. `uninstallParams` resolves to undefined.
14
+ * them recorded. It drops a call with `throttleMs` as `track` does, by `clock`. `uninstallParams` resolves to undefined.
13
15
  */
14
- export function newRecordingCollector(mode, { onError } = {}) {
16
+ export function newRecordingCollector(mode, { onError, clock = systemClock, } = {}) {
15
17
  const channelMode = mode ?? Mode.Anonymous;
16
18
  const reportError = (error) => reportTo(onError, error);
17
19
  const events = [];
18
20
  let state = AnalyticsState.Anonymous;
19
21
  let isInstalled = false;
20
22
  let isVersionMarked = false;
23
+ const throttle = newThrottle();
21
24
  const record = (name, params) => {
22
- if (state !== AnalyticsState.OptedOut) {
23
- events.push({ name, ...(params !== undefined && { params }) });
25
+ if (state === AnalyticsState.OptedOut) {
26
+ return false;
24
27
  }
28
+ events.push({ name, ...(params !== undefined && { params }) });
29
+ return true;
25
30
  };
26
31
  return {
27
32
  events,
28
- track: async (name, given) => {
29
- const event = acceptedEvent(name, given, reportError);
30
- if (event !== undefined) {
31
- record(name, event.params);
33
+ track: async (name, given, options) => {
34
+ const now = clock.now();
35
+ const event = acceptedEvent({ name, given, options, reportError });
36
+ if (event === undefined) {
37
+ return;
38
+ }
39
+ const call = { name, throttleMs: event.throttleMs, now };
40
+ if (!throttle.isDropped(call) && record(name, event.params)) {
41
+ throttle.went(call);
32
42
  }
33
43
  },
34
44
  installed: async () => {
35
45
  if (!isInstalled && state !== AnalyticsState.OptedOut) {
36
46
  isInstalled = true;
37
47
  isVersionMarked = true;
38
- record('installed');
48
+ record("installed");
39
49
  }
40
50
  },
41
51
  updated: async () => {
42
52
  if (!isVersionMarked && state !== AnalyticsState.OptedOut) {
43
53
  isVersionMarked = true;
44
- record('updated');
54
+ record("updated");
45
55
  }
46
56
  },
47
57
  setState: async (next) => {
@@ -59,7 +69,7 @@ export function newRecordingCollector(mode, { onError } = {}) {
59
69
  flush: async () => undefined,
60
70
  forget: async (id) => {
61
71
  if (!isUsableId(id)) {
62
- reportError(new TypeError('artel: forget takes an id of 1 to 64 characters'));
72
+ reportError(new TypeError("artel: forget takes an id of 1 to 64 characters"));
63
73
  }
64
74
  },
65
75
  uninstallParams: async () => undefined,
@@ -0,0 +1,30 @@
1
+ import type { TrackOptions } from "./collectorTypes.js";
2
+ /**
3
+ * Remembers in memory when each event name last went from a call with `throttleMs`. The window is leading-edge: the
4
+ * first such call goes, and a later one of the name goes only once its `throttleMs` passed since the last one that
5
+ * went. A call without `throttleMs` opens no window and is never dropped.
6
+ */
7
+ export interface Throttle {
8
+ /**
9
+ * Tells whether a call of `name` at `now` falls inside the window of the name. False while `throttleMs` is
10
+ * undefined.
11
+ */
12
+ isDropped(call: ThrottledCall): boolean;
13
+ /** Opens the window of `name` at `now` for a call with `throttleMs` that went. */
14
+ went(call: ThrottledCall): void;
15
+ }
16
+ /** One `track` call as the throttle reads it. */
17
+ interface ThrottledCall {
18
+ name: string;
19
+ throttleMs: number | undefined;
20
+ now: number;
21
+ }
22
+ export declare function newThrottle(): Throttle;
23
+ /**
24
+ * Returns `{ throttleMs }` from `track`'s options, with `throttleMs` undefined when they name none. Returns undefined
25
+ * when `throttleMs` is no finite number from 0, when the options are no object, or when reading them throws.
26
+ */
27
+ export declare function throttleOf(options: TrackOptions | undefined): {
28
+ throttleMs: number | undefined;
29
+ } | undefined;
30
+ export {};
@@ -0,0 +1,41 @@
1
+ export function newThrottle() {
2
+ const lastWent = new Map();
3
+ return {
4
+ isDropped: ({ name, throttleMs, now }) => {
5
+ const last = lastWent.get(name);
6
+ // The window spans `throttleMs` on either side of the last time, so a clock set back never holds it open until
7
+ // the clock catches up.
8
+ return throttleMs !== undefined && last !== undefined && Math.abs(now - last) < throttleMs;
9
+ },
10
+ went: ({ name, throttleMs, now }) => {
11
+ if (throttleMs !== undefined) {
12
+ lastWent.set(name, now);
13
+ }
14
+ },
15
+ };
16
+ }
17
+ /**
18
+ * Returns `{ throttleMs }` from `track`'s options, with `throttleMs` undefined when they name none. Returns undefined
19
+ * when `throttleMs` is no finite number from 0, when the options are no object, or when reading them throws.
20
+ */
21
+ export function throttleOf(options) {
22
+ const value = options;
23
+ if (value === undefined) {
24
+ return { throttleMs: undefined };
25
+ }
26
+ let throttleMs;
27
+ try {
28
+ // An untyped host can pass options of any kind, such as ones with a getter that throws.
29
+ throttleMs =
30
+ typeof value === "object" && value !== null ? Reflect.get(value, "throttleMs") : Number.NaN;
31
+ }
32
+ catch {
33
+ return undefined;
34
+ }
35
+ if (throttleMs === undefined) {
36
+ return { throttleMs: undefined };
37
+ }
38
+ return typeof throttleMs === "number" && Number.isFinite(throttleMs) && throttleMs >= 0
39
+ ? { throttleMs }
40
+ : undefined;
41
+ }
@@ -1,4 +1,5 @@
1
- import { type Clock } from './clock.js';
1
+ import { type Clock } from "./clock.js";
2
+ import type { CollectorOptions } from "./collectorTypes.js";
2
3
  /** What the intake answered: its HTTP status, 0 when the request did not reach it, and its `Retry-After` header. */
3
4
  export interface TransportResult {
4
5
  status: number;
@@ -20,3 +21,11 @@ export declare function newHttpTransport(endpoint: string, { fetch, clock, }?: {
20
21
  fetch?: typeof globalThis.fetch;
21
22
  clock?: Clock;
22
23
  }): Transport;
24
+ /**
25
+ * Returns the transport of the envelopes and that of the forget requests. A product's own transport takes both kinds
26
+ * of request.
27
+ */
28
+ export declare function transportsOf(options: CollectorOptions): {
29
+ transport: Transport;
30
+ forgetTransport: Transport;
31
+ };
package/dist/transport.js CHANGED
@@ -1,4 +1,4 @@
1
- import { systemClock } from './clock.js';
1
+ import { systemClock } from "./clock.js";
2
2
  const TIMEOUT_MS = 30_000;
3
3
  /**
4
4
  * Returns a transport that posts each body to `endpoint` with `fetch`, the host's own by default. The transport
@@ -10,29 +10,56 @@ export function newHttpTransport(endpoint, {
10
10
  fetch = (input, init) => globalThis.fetch(input, init), clock = systemClock, } = {}) {
11
11
  return async (body) => {
12
12
  const timeout = new AbortController();
13
- const timer = clock.setTimeout(() => timeout.abort(), TIMEOUT_MS);
13
+ const cancelTimeout = clock.setTimeout(() => timeout.abort(), TIMEOUT_MS);
14
14
  try {
15
15
  const response = await fetch(endpoint, {
16
- method: 'POST',
16
+ method: "POST",
17
17
  // This type skips a CORS preflight. The intake reads the body as JSON.
18
- headers: { 'content-type': 'text/plain;charset=UTF-8' },
18
+ headers: { "content-type": "text/plain;charset=UTF-8" },
19
19
  body,
20
20
  // An extension with host access, or a page on the intake's own origin, would otherwise send the user's cookies
21
21
  // for that host. The intake reads none.
22
- credentials: 'omit',
22
+ credentials: "omit",
23
23
  // A page's own policy could otherwise send its full address, which `getPage` exists to keep out.
24
- referrerPolicy: 'no-referrer',
24
+ referrerPolicy: "no-referrer",
25
25
  keepalive: true,
26
26
  signal: timeout.signal,
27
27
  });
28
- const retryAfter = response.headers.get('Retry-After');
28
+ const retryAfter = response.headers.get("Retry-After");
29
29
  return { status: response.status, ...(retryAfter !== null && { retryAfter }) };
30
30
  }
31
31
  catch {
32
32
  return { status: 0 };
33
33
  }
34
34
  finally {
35
- clock.clearTimeout(timer);
35
+ cancelTimeout();
36
36
  }
37
37
  };
38
38
  }
39
+ /**
40
+ * Returns the transport of the envelopes and that of the forget requests. A product's own transport takes both kinds
41
+ * of request.
42
+ */
43
+ export function transportsOf(options) {
44
+ if (options.transport !== undefined) {
45
+ return { transport: options.transport, forgetTransport: options.transport };
46
+ }
47
+ return {
48
+ transport: newHttpTransport(options.endpoint),
49
+ forgetTransport: newHttpTransport(forgetUrlOf(options.endpoint)),
50
+ };
51
+ }
52
+ /**
53
+ * Returns the intake's forget address: `endpoint` with `forget` in place of the last segment of its path, which is
54
+ * `relay`. A trailing slash goes with that segment. The query stays, as on the envelopes' address.
55
+ */
56
+ function forgetUrlOf(endpoint) {
57
+ const url = new URL(endpoint);
58
+ const path = url.pathname;
59
+ let end = path.length;
60
+ while (end > 0 && path[end - 1] === "/") {
61
+ end--;
62
+ }
63
+ url.pathname = `${path.slice(0, path.lastIndexOf("/", end - 1) + 1)}forget`;
64
+ return url.href;
65
+ }
package/dist/web.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- import { Mode, type Collector, type CommonOptions, type Delivery, type ModeOptions, type PageFields, type PageOptions } from './collectorTypes.js';
2
- import type { Lock } from './lock.js';
3
- import type { StorageAdapter } from './storage.js';
1
+ import { Mode, type Collector, type CommonOptions, type Delivery, type ModeOptions, type PageFields, type PageOptions } from "./collectorTypes.js";
2
+ import type { Lock } from "./lock.js";
3
+ import type { StorageAdapter } from "./storage.js";
4
4
  /**
5
5
  * The options of `newWebCollector`: those of `newCollector` without `platform`, with `storage` optional. An option left
6
6
  * out or `undefined` takes its default.
7
7
  */
8
- export type WebCollectorOptions = Omit<CommonOptions, 'storage'> & {
8
+ export type WebCollectorOptions = Omit<CommonOptions, "storage"> & {
9
9
  storage?: StorageAdapter | undefined;
10
10
  } & PageOptions & Delivery & ModeOptions;
11
11
  /**
package/dist/web.js CHANGED
@@ -1,7 +1,7 @@
1
- import { detectBrowser } from './browser.js';
2
- import { newCollector } from './collector.js';
3
- import { Mode, } from './collectorTypes.js';
4
- import { PAGE_VIEW, Platform } from './envelope.js';
1
+ import { detectBrowser } from "./browser.js";
2
+ import { newCollector } from "./collector.js";
3
+ import { Mode, } from "./collectorTypes.js";
4
+ import { PAGE_VIEW, Platform } from "./envelope.js";
5
5
  export function newWebCollector(options) {
6
6
  const defaults = {
7
7
  platform: Platform.Web,
@@ -12,7 +12,11 @@ export function newWebCollector(options) {
12
12
  };
13
13
  return options.mode === Mode.Anonymous
14
14
  ? newCollector({ ...options, ...defaults })
15
- : newCollector({ ...options, ...defaults, browser: options.browser ?? (() => detectBrowser(navigator)) });
15
+ : newCollector({
16
+ ...options,
17
+ ...defaults,
18
+ browser: options.browser ?? (() => detectBrowser(navigator)),
19
+ });
16
20
  }
17
21
  /**
18
22
  * Returns a storage adapter over `localStorage`, which every tab of the origin shares. A Web Worker has no
@@ -33,8 +37,8 @@ export function newLocalStorageAdapter() {
33
37
  export function newWebLock() {
34
38
  return (operation) => {
35
39
  // A test DOM such as happy-dom sets `navigator.locks` to null, so the check asks for the method itself.
36
- const locks = typeof navigator === 'undefined' ? undefined : navigator.locks;
37
- return typeof locks?.request === 'function' ? locks.request('artel', operation) : operation();
40
+ const locks = typeof navigator === "undefined" ? undefined : navigator.locks;
41
+ return typeof locks?.request === "function" ? locks.request("artel", operation) : operation();
38
42
  };
39
43
  }
40
44
  /**
@@ -43,11 +47,16 @@ export function newWebLock() {
43
47
  * `getPage` that returns the route pattern instead.
44
48
  */
45
49
  export function pageFields() {
46
- return { page: `${location.protocol}//${location.host}${location.pathname}`, referrer: document.referrer };
50
+ return {
51
+ page: `${location.protocol}//${location.host}${location.pathname}`,
52
+ referrer: document.referrer,
53
+ };
47
54
  }
48
55
  /** Returns `pageFields`, or undefined in a Web Worker, which has no page. */
49
56
  function pageFieldsWherePageIs() {
50
- return typeof document === 'undefined' || typeof location === 'undefined' ? undefined : pageFields();
57
+ return typeof document === "undefined" || typeof location === "undefined"
58
+ ? undefined
59
+ : pageFields();
51
60
  }
52
61
  /**
53
62
  * Sends `page_view` for the current page and after each navigation that changes `location.pathname`, and returns the
@@ -63,17 +72,17 @@ export function trackPageViews(collector) {
63
72
  lastPath = location.pathname;
64
73
  void collector.track(PAGE_VIEW);
65
74
  };
66
- const unwrapPushState = callAfter('pushState', onNavigation);
67
- const unwrapReplaceState = callAfter('replaceState', onNavigation);
68
- window.addEventListener('popstate', onNavigation);
75
+ const unwrapPushState = callAfter("pushState", onNavigation);
76
+ const unwrapReplaceState = callAfter("replaceState", onNavigation);
77
+ window.addEventListener("popstate", onNavigation);
69
78
  const navigation = navigationApi();
70
- navigation?.addEventListener('currententrychange', onNavigation);
79
+ navigation?.addEventListener("currententrychange", onNavigation);
71
80
  onNavigation();
72
81
  return () => {
73
82
  unwrapPushState();
74
83
  unwrapReplaceState();
75
- window.removeEventListener('popstate', onNavigation);
76
- navigation?.removeEventListener('currententrychange', onNavigation);
84
+ window.removeEventListener("popstate", onNavigation);
85
+ navigation?.removeEventListener("currententrychange", onNavigation);
77
86
  };
78
87
  }
79
88
  /** The wrappers `callAfter` installed, by the wrapper function. */
@@ -84,7 +93,11 @@ const wrappings = new WeakMap();
84
93
  * active one or under a product's own wrapper stays and passes calls on.
85
94
  */
86
95
  function callAfter(method, listener) {
87
- const wrapping = { found: history[method], wasOwn: Object.hasOwn(history, method), isActive: true };
96
+ const wrapping = {
97
+ found: history[method],
98
+ wasOwn: Object.hasOwn(history, method),
99
+ isActive: true,
100
+ };
88
101
  const wrapper = function (...args) {
89
102
  wrapping.found.apply(this, args);
90
103
  if (wrapping.isActive) {
@@ -107,6 +120,6 @@ function callAfter(method, listener) {
107
120
  }
108
121
  /** Returns the Navigation API, or undefined where the browser lacks it. */
109
122
  function navigationApi() {
110
- const navigation = Reflect.get(globalThis, 'navigation');
123
+ const navigation = Reflect.get(globalThis, "navigation");
111
124
  return navigation instanceof EventTarget ? navigation : undefined;
112
125
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kk-forge/artel-collector",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Sends a product's analytics events to the intake service",
5
5
  "license": "MIT",
6
6
  "author": "KK Forge",
@@ -45,9 +45,9 @@
45
45
  "build": "node --eval \"process.getBuiltinModule('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json",
46
46
  "lint": "npm run lint:tsc && npm run lint:oxlint && npm run lint:format",
47
47
  "lint:fix": "npm run lint:oxlint:fix && npm run lint:format:fix",
48
- "lint:tsc": "tsc",
49
- "lint:oxlint": "oxlint --type-aware src tests",
50
- "lint:oxlint:fix": "oxlint --type-aware --fix src tests",
48
+ "lint:tsc": "tsc && tsc -p tsconfig.dom.json && tsc -p tsconfig.node.json",
49
+ "lint:oxlint": "oxlint src tests",
50
+ "lint:oxlint:fix": "oxlint --fix src tests",
51
51
  "lint:format": "oxfmt --check .",
52
52
  "lint:format:fix": "oxfmt .",
53
53
  "test": "npm run test:unit",
@@ -55,6 +55,8 @@
55
55
  "test:ci": "vitest run --coverage"
56
56
  },
57
57
  "devDependencies": {
58
+ "@kk-forge/oxlint-config": "^4.0.0",
59
+ "@types/node": "^26.6.6",
58
60
  "@vitest/coverage-v8": "^5.0.5",
59
61
  "oxfmt": "^0.73.0",
60
62
  "oxlint": "^1.90.0",