@kk-forge/artel-collector 0.4.1 → 0.6.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/README.md +25 -16
- package/dist/infra/chrome/exports.d.ts +1 -0
- package/dist/infra/chrome/exports.js +1 -0
- package/dist/{extension.d.ts → infra/chrome/extension.d.ts} +4 -4
- package/dist/{extension.js → infra/chrome/extension.js} +11 -10
- package/dist/{desktop.d.ts → infra/desktop.d.ts} +3 -3
- package/dist/{desktop.js → infra/desktop.js} +1 -1
- package/dist/infra/exports.d.ts +4 -0
- package/dist/infra/exports.js +4 -0
- package/dist/infra/system.d.ts +9 -0
- package/dist/infra/system.js +14 -0
- package/dist/{collector.d.ts → infra/systemCollector.d.ts} +12 -3
- package/dist/infra/systemCollector.js +27 -0
- package/dist/{web.d.ts → infra/web.d.ts} +3 -3
- package/dist/{web.js → infra/web.js} +4 -4
- package/dist/shared/clock.d.ts +11 -0
- package/dist/shared/clock.js +1 -0
- package/dist/shared/collector.d.ts +23 -0
- package/dist/{collector.js → shared/collector.js} +8 -9
- package/dist/{exports.d.ts → shared/exports.d.ts} +2 -3
- package/dist/{exports.js → shared/exports.js} +0 -3
- package/dist/{installState.d.ts → shared/installState.d.ts} +4 -1
- package/dist/{installState.js → shared/installState.js} +6 -6
- package/dist/{outbox.d.ts → shared/outbox.d.ts} +6 -3
- package/dist/{outbox.js → shared/outbox.js} +23 -20
- package/dist/{queue.d.ts → shared/queue.d.ts} +4 -3
- package/dist/{queue.js → shared/queue.js} +3 -7
- package/dist/shared/random.d.ts +10 -0
- package/dist/shared/random.js +4 -0
- package/dist/{transport.d.ts → shared/transport.d.ts} +9 -8
- package/dist/{transport.js → shared/transport.js} +8 -12
- package/dist/testing/exports.d.ts +1 -0
- package/dist/testing/exports.js +1 -0
- package/dist/{testing.d.ts → testing/recordingCollector.d.ts} +4 -4
- package/dist/{testing.js → testing/recordingCollector.js} +8 -8
- package/package.json +23 -23
- package/dist/clock.d.ts +0 -12
- package/dist/clock.js +0 -5
- /package/dist/{browser.d.ts → shared/browser.d.ts} +0 -0
- /package/dist/{browser.js → shared/browser.js} +0 -0
- /package/dist/{calendar.d.ts → shared/calendar.d.ts} +0 -0
- /package/dist/{calendar.js → shared/calendar.js} +0 -0
- /package/dist/{collectorTypes.d.ts → shared/collectorTypes.d.ts} +0 -0
- /package/dist/{collectorTypes.js → shared/collectorTypes.js} +0 -0
- /package/dist/{envelope.d.ts → shared/envelope.d.ts} +0 -0
- /package/dist/{envelope.js → shared/envelope.js} +0 -0
- /package/dist/{eventCheck.d.ts → shared/eventCheck.d.ts} +0 -0
- /package/dist/{eventCheck.js → shared/eventCheck.js} +0 -0
- /package/dist/{fields.d.ts → shared/fields.d.ts} +0 -0
- /package/dist/{fields.js → shared/fields.js} +0 -0
- /package/dist/{hostInput.d.ts → shared/hostInput.d.ts} +0 -0
- /package/dist/{hostInput.js → shared/hostInput.js} +0 -0
- /package/dist/{lock.d.ts → shared/lock.d.ts} +0 -0
- /package/dist/{lock.js → shared/lock.js} +0 -0
- /package/dist/{page.d.ts → shared/page.d.ts} +0 -0
- /package/dist/{page.js → shared/page.js} +0 -0
- /package/dist/{pagePath.d.ts → shared/pagePath.d.ts} +0 -0
- /package/dist/{pagePath.js → shared/pagePath.js} +0 -0
- /package/dist/{stateFields.d.ts → shared/stateFields.d.ts} +0 -0
- /package/dist/{stateFields.js → shared/stateFields.js} +0 -0
- /package/dist/{storage.d.ts → shared/storage.d.ts} +0 -0
- /package/dist/{storage.js → shared/storage.js} +0 -0
- /package/dist/{throttle.d.ts → shared/throttle.d.ts} +0 -0
- /package/dist/{throttle.js → shared/throttle.js} +0 -0
package/README.md
CHANGED
|
@@ -80,7 +80,7 @@ The collectors do the rest themselves:
|
|
|
80
80
|
- An extension collector with `uninstallPage` keeps Chrome's uninstall page up to date with the user's state.
|
|
81
81
|
- A desktop window sends `installed` and `updated` when they are due.
|
|
82
82
|
|
|
83
|
-
`newWebCollector`
|
|
83
|
+
`newWebCollector`, `newDesktopCollector` and `newCollector` come from `@kk-forge/artel-collector/infra`, and `newExtensionCollector` and `newContentScriptCollector` from `@kk-forge/artel-collector/infra/chrome`, as "Entry points" describes. Each platform constructor fills in the defaults in the table below and passes the result to `newCollector`. The web and extension constructors set `platform`, and the desktop one takes it. An option left out or `undefined` takes its default. Each constructor takes `mode` as the literal `'anonymous'`, `'pseudonymous'` or `'identified'`, and returns a collector whose `setState` takes only that channel's states. A `mode` known only at run time goes in options typed `CollectorOptions`, `WebCollectorOptions`, `ExtensionCollectorOptions` or `DesktopCollectorOptions` and built per mode, and gives a collector whose `setState` takes every state. `newContentScriptCollector` takes no channel options, as "Chrome extension" describes.
|
|
84
84
|
|
|
85
85
|
Each constructor throws a `TypeError` that names the option when the options would make the intake refuse every envelope. A mistake in the build then fails its first run and its tests. That is a `key`, `platform` or `version` the intake does not take, an `endpoint` that is not `https`, or a `transport` that is not a function, as "Options" describes. It also throws for a `browser` on a desktop platform, which only untyped code passes and whose envelopes the intake refuses. The message never quotes the endpoint, so it carries no password. `newWebCollector`, `newExtensionCollector` and `newDesktopCollector` also throw where `navigator` is missing, unless the options pass `browserLanguage`. Node 21.2 and later define `navigator.language`, so server rendering there builds a collector with the server's language. `newExtensionCollector` also throws outside an extension context unless the options pass `version`. `newContentScriptCollector` never throws. A `browserLanguage` or `uiLanguage` that breaks the format throws nothing: the collector leaves it out and reports it to `onError`, since it often comes from the browser.
|
|
86
86
|
|
|
@@ -131,7 +131,7 @@ Each constructor throws a `TypeError` that names the option when the options wou
|
|
|
131
131
|
- `lock`: a function that takes an async operation, runs it while no other context that shares `storage` runs one, and resolves or rejects as the operation does. It must run the operation exactly once and hold the lock until the operation's promise settles, as `navigator.locks.request` does. The collector never asks for it while it holds it. The collector runs each method, and each queue change of a send, under it. Without it, two contexts recording at once may both mark the first event of a day, overwrite each other's queued events or send one envelope twice. The rule that no event goes under another user's id then holds only within one context, and so does the opt-out: an event another context records during `setState('opted_out')` may still leave. Each collector runs one of its own operations at a time with or without a lock.
|
|
132
132
|
- `sessionIdleMinutes`: minutes without events that end a session, 10 by default. A value that is not a finite number from 0 takes the default, and so does one of `sendDelaySeconds`.
|
|
133
133
|
- `sendDelaySeconds`: the longest an event waits in the queue before a send starts, 5 by default.
|
|
134
|
-
- `clock`: time and timers, the host's own by default. Tests pass a fake.
|
|
134
|
+
- `clock`: time and timers, the host's own by default. Tests pass a fake. A `Clock` has `now()`, which returns milliseconds since the epoch, and `setTimeout(callback, delayMs)`, which returns the function that cancels that timer. A cancel after the timer ran does nothing. The port names no timer handle, whose type is a number in the DOM typings and an object in the Node ones. A clock written for 0.4 drops `clearTimeout` and returns the cancel from `setTimeout` instead, and `TimerHandle` is no longer exported.
|
|
135
135
|
- `onError`: receives each failure the collector does not retry. An `onError` that throws is ignored. A report quotes at most 64 characters of host or stored text, and never a page. It receives:
|
|
136
136
|
- an event `track` refuses;
|
|
137
137
|
- an event or envelope dropped by a limit, by its age or by the intake's refusal;
|
|
@@ -176,7 +176,7 @@ Every method returns a promise that resolves and never rejects. A failure goes t
|
|
|
176
176
|
|
|
177
177
|
`detectBrowser(nav)` names the browser from the `userAgentData.brands` and `userAgent` of the `navigator` it is given. It returns `{ name, major }`, where `name` is `chrome`, `edge`, `opera`, `yandex`, `brave`, `firefox` or `safari`, and leaves out a major version outside 1 to 999. Any other browser is `{ name: 'other' }`. Chrome is named only by its brands, since every Chromium browser carries Chrome's User-Agent token. It returns `undefined` when `nav` has neither a Chromium brand nor a User-Agent.
|
|
178
178
|
|
|
179
|
-
|
|
179
|
+
`@kk-forge/artel-collector` also exports the checks of "Testing", `newMemoryStorage()`, `Mode`, `AnalyticsState`, `Platform`, `ActiveDaysBucket` and `BrowserName`, and the types of every option, method and value above. `@kk-forge/artel-collector/infra` also exports `systemClock`, `WebCollectorOptions`, `DesktopCollectorOptions` and `newHttpTransport(endpoint, { fetch, clock }?)`, the transport behind `endpoint`. `@kk-forge/artel-collector/infra/chrome` also exports `ExtensionCollectorOptions` and `ContentScriptCollector`.
|
|
180
180
|
|
|
181
181
|
## Sending
|
|
182
182
|
|
|
@@ -200,15 +200,24 @@ The marks an event takes go back when the collector drops it before any request
|
|
|
200
200
|
|
|
201
201
|
A `get` or `set` that fails goes to `onError`, and the method that called it stops there. A `set` that fails while an event is recorded loses the event, and the event gives back its marks.
|
|
202
202
|
|
|
203
|
-
`newMemoryStorage()` keeps the state only while the page or worker lives.
|
|
203
|
+
`newMemoryStorage()` keeps the state only while the page or worker lives. `@kk-forge/artel-collector/infra` brings an adapter over `localStorage`, and `@kk-forge/artel-collector/infra/chrome` one over `chrome.storage.local`.
|
|
204
204
|
|
|
205
|
-
##
|
|
205
|
+
## Entry points
|
|
206
206
|
|
|
207
|
-
The
|
|
207
|
+
The package publishes one entry point for each layer of its code:
|
|
208
208
|
|
|
209
|
-
|
|
209
|
+
| Entry point | Holds |
|
|
210
|
+
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
|
|
211
|
+
| `@kk-forge/artel-collector` | what reads no host: the types, the enums, `detectBrowser`, the checks of "Testing" and `newMemoryStorage()` |
|
|
212
|
+
| `@kk-forge/artel-collector/infra` | what reads the host: `newCollector`, `newHttpTransport`, `systemClock`, and the code of "Website or web app" and "Desktop app" |
|
|
213
|
+
| `@kk-forge/artel-collector/infra/chrome` | the code of "Chrome extension", the only code of the package that calls `chrome` |
|
|
214
|
+
| `@kk-forge/artel-collector/testing` | the helpers of "Testing" |
|
|
210
215
|
|
|
211
|
-
|
|
216
|
+
An extension imports `infra/chrome` only in its entrypoints, the scripts that start its service worker, its pages and its content scripts.
|
|
217
|
+
|
|
218
|
+
### Website or web app
|
|
219
|
+
|
|
220
|
+
`@kk-forge/artel-collector/infra` exports the code for a website or a web app. The desktop collector uses the same storage adapter and lock.
|
|
212
221
|
|
|
213
222
|
- `newWebCollector(options)` makes a collector for a website or a web app, as in "Usage".
|
|
214
223
|
- `newLocalStorageAdapter()` returns a `storage` over `localStorage`. Every script of the origin can read it, the queued events with their `id`, the last id and the install id included, and no other storage of the origin hides them from its scripts. A site that runs untrusted scripts uses an anonymous channel.
|
|
@@ -221,15 +230,15 @@ For a website or a web app. The desktop module builds on its storage and lock.
|
|
|
221
230
|
A site sets up page views in two lines:
|
|
222
231
|
|
|
223
232
|
```ts
|
|
224
|
-
import { newWebCollector, trackPageViews } from "@kk-forge/artel-collector/
|
|
233
|
+
import { newWebCollector, trackPageViews } from "@kk-forge/artel-collector/infra";
|
|
225
234
|
|
|
226
235
|
const analytics = newWebCollector({ key, version, endpoint, mode: "anonymous" });
|
|
227
236
|
trackPageViews(analytics);
|
|
228
237
|
```
|
|
229
238
|
|
|
230
|
-
###
|
|
239
|
+
### Chrome extension
|
|
231
240
|
|
|
232
|
-
|
|
241
|
+
`@kk-forge/artel-collector/infra/chrome` exports the code for a Chrome extension. The extension's service worker and its pages each make a collector with `newExtensionCollector`. They share `chrome.storage.local` and Web Locks, so they keep one queue and one state.
|
|
233
242
|
|
|
234
243
|
- `newExtensionCollector(options)` makes a collector for the service worker or a page, as in "Usage". It needs the `storage` permission. In the service worker it closes `chrome.storage.local` to content scripts with `setAccessLevel({ accessLevel: 'TRUSTED_CONTEXTS' })`, since a content script that could write the user's analytics state, the queue and the last id `getId` gave could send events the user refused. The collector reads and writes no storage until Chrome answers the call, and a failure of the call goes to `onError`. The call runs only in the service worker, so build the collector at the top level of the worker: until it runs, content scripts keep access to `chrome.storage.local`. The call closes the whole `chrome.storage.local` area, every key and not only the collector's, even when the product passes its own `storage`. So a content script of the product that reads its own settings there must get them from the worker instead. `setAccessLevel` needs Chrome 102 or later. The collector calls it again on each start of the service worker.
|
|
235
244
|
- `newChromeStorageAdapter()` returns a `storage` over `chrome.storage.local`.
|
|
@@ -241,7 +250,7 @@ For a Chrome extension. Its service worker and its pages each make a collector w
|
|
|
241
250
|
|
|
242
251
|
```ts
|
|
243
252
|
// service worker
|
|
244
|
-
import { newExtensionCollector } from "@kk-forge/artel-collector/
|
|
253
|
+
import { newExtensionCollector } from "@kk-forge/artel-collector/infra/chrome";
|
|
245
254
|
|
|
246
255
|
const analytics = newExtensionCollector({
|
|
247
256
|
key,
|
|
@@ -251,15 +260,15 @@ const analytics = newExtensionCollector({
|
|
|
251
260
|
});
|
|
252
261
|
|
|
253
262
|
// content script
|
|
254
|
-
import { newContentScriptCollector } from "@kk-forge/artel-collector/
|
|
263
|
+
import { newContentScriptCollector } from "@kk-forge/artel-collector/infra/chrome";
|
|
255
264
|
|
|
256
265
|
const analytics = newContentScriptCollector();
|
|
257
266
|
void analytics.track("link_shared", { target: "clipboard" });
|
|
258
267
|
```
|
|
259
268
|
|
|
260
|
-
###
|
|
269
|
+
### Desktop app
|
|
261
270
|
|
|
262
|
-
|
|
271
|
+
`@kk-forge/artel-collector/infra` exports the code for a window of a desktop app, such as a Tauri webview.
|
|
263
272
|
|
|
264
273
|
- `newDesktopCollector(options)` makes a collector for a desktop window, as in "Usage". It takes `platform` as `'macos'`, `'windows'` or `'linux'`, the platforms a `desktop` channel takes. Its windows share the webview's `localStorage` through `newLocalStorageAdapter()` and its Web Locks through `newWebLock()`, so they keep one queue and one state. It sends `installed` and `updated` when it is built, each only when due, so every window may build one. Events of the last seconds before the app closes go at its next launch, as "Sending" describes. It names no browser and sends no page.
|
|
265
274
|
|
|
@@ -328,7 +337,7 @@ The core reads no page, URL or user input. `params`, the account `id` and the pa
|
|
|
328
337
|
- `newRecordingCollector(mode?, { onError, clock }?)` returns a `Collector` that sends nothing and records each event it takes in `events`, as `{ name, params }`. `mode` is the channel mode, `anonymous` by default. The user starts in `anonymous`. It refuses an event `track` refuses, a state above the mode and an id `forget` refuses, with the same report to `onError`, so a test catches a bad event name or param. It records what the real collector sends: `opted_out` once at the opt-out and nothing after it in that state, `installed` once, and `updated` only when neither was recorded before, as for one version. It drops a call by `throttleMs` as `track` does. `clock` times the windows, the system's by default, so a test can pass a fake one. `uninstallParams()` resolves to `undefined`.
|
|
329
338
|
- `queuedEvents(storage, key)` resolves to the `{ name, params }` of the events a real collector of channel `key` holds queued in `storage`, oldest first. It writes nothing, and reads a stored queue that is no JSON list as empty.
|
|
330
339
|
|
|
331
|
-
|
|
340
|
+
`@kk-forge/artel-collector` exports three checks that read no `chrome`, `navigator` or storage, so a build script or a test can call them:
|
|
332
341
|
|
|
333
342
|
- `checkOptions({ key, version, platform, endpoint })` throws the `TypeError` a constructor throws for these options, and returns otherwise. It takes `transport` in place of `endpoint` too.
|
|
334
343
|
- `isTestKey(key)` tells whether `key` is a channel's test key, `<kind>-test-<10 characters>`.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { forwardTrack, newChromeStorageAdapter, newContentScriptCollector, newExtensionCollector, type ContentScriptCollector, type ExtensionCollectorOptions, } from "./extension.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { forwardTrack, newChromeStorageAdapter, newContentScriptCollector, newExtensionCollector, } from "./extension.js";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { Mode, type Collector, type CommonOptions, type Delivery, type ModeOptions } from "
|
|
3
|
-
import { type EventParams } from "
|
|
4
|
-
import type { StorageAdapter } from "
|
|
1
|
+
import type { Clock } from "../../shared/clock.js";
|
|
2
|
+
import { Mode, type Collector, type CommonOptions, type Delivery, type ModeOptions } from "../../shared/collectorTypes.js";
|
|
3
|
+
import { type EventParams } from "../../shared/envelope.js";
|
|
4
|
+
import type { StorageAdapter } from "../../shared/storage.js";
|
|
5
5
|
/**
|
|
6
6
|
* The options of `newExtensionCollector`: those of `newCollector` without `platform`, with `storage` and `version`
|
|
7
7
|
* optional. An option left out or `undefined` takes its default.
|
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import { detectBrowser } from "
|
|
2
|
-
import { systemClock } from "
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
1
|
+
import { detectBrowser } from "../../shared/browser.js";
|
|
2
|
+
import { systemClock } from "../system.js";
|
|
3
|
+
import { sendDelayMsOf } from "../../shared/collector.js";
|
|
4
|
+
import { newCollectorNotingDays } from "../systemCollector.js";
|
|
5
|
+
import { AnalyticsState, Mode, } from "../../shared/collectorTypes.js";
|
|
6
|
+
import { Platform, SYSTEM_EVENTS } from "../../shared/envelope.js";
|
|
7
|
+
import { checkEvent } from "../../shared/eventCheck.js";
|
|
8
|
+
import { reportTo } from "../../shared/hostInput.js";
|
|
9
|
+
import { parseQueue, QUEUE_KEY } from "../../shared/queue.js";
|
|
10
|
+
import { newThrottle, throttleOf } from "../../shared/throttle.js";
|
|
11
|
+
import { newWebLock } from "../web.js";
|
|
11
12
|
const FORWARD_TYPE = "artel.track";
|
|
12
13
|
/**
|
|
13
14
|
* The event names the worker refuses from a content script: every system event, which the intake counts from any page
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import type { Collector, CommonOptions, Delivery, Mode, ModeOptions } from "
|
|
2
|
-
import type { Platform } from "
|
|
3
|
-
import type { StorageAdapter } from "
|
|
1
|
+
import type { Collector, CommonOptions, Delivery, Mode, ModeOptions } from "../shared/collectorTypes.js";
|
|
2
|
+
import type { Platform } from "../shared/envelope.js";
|
|
3
|
+
import type { StorageAdapter } from "../shared/storage.js";
|
|
4
4
|
/**
|
|
5
5
|
* The options of `newDesktopCollector`: those of `newCollector` with `storage` optional and a desktop `platform`. An
|
|
6
6
|
* option left out or `undefined` takes its default.
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { newCollector, newHttpTransport } from "./systemCollector.js";
|
|
2
|
+
export { systemClock } from "./system.js";
|
|
3
|
+
export { newLocalStorageAdapter, newWebCollector, newWebLock, pageFields, trackPageViews, type WebCollectorOptions, } from "./web.js";
|
|
4
|
+
export { newDesktopCollector, type DesktopCollectorOptions } from "./desktop.js";
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { newCollector, newHttpTransport } from "./systemCollector.js";
|
|
2
|
+
export { systemClock } from "./system.js";
|
|
3
|
+
export { newLocalStorageAdapter, newWebCollector, newWebLock, pageFields, trackPageViews, } from "./web.js";
|
|
4
|
+
export { newDesktopCollector } from "./desktop.js";
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Clock } from "../shared/clock.js";
|
|
2
|
+
import type { Random } from "../shared/random.js";
|
|
3
|
+
import type { Fetch } from "../shared/transport.js";
|
|
4
|
+
/** The host's clock and timers. */
|
|
5
|
+
export declare const systemClock: Clock;
|
|
6
|
+
/** The host's cryptographic random bytes. */
|
|
7
|
+
export declare const systemRandom: Random;
|
|
8
|
+
/** The host's `fetch`, called through its global, since a browser refuses a `fetch` called apart from its global. */
|
|
9
|
+
export declare const systemFetch: Fetch;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** The host's clock and timers. */
|
|
2
|
+
export const systemClock = {
|
|
3
|
+
now: () => Date.now(),
|
|
4
|
+
setTimeout: (callback, delayMs) => {
|
|
5
|
+
const handle = setTimeout(callback, delayMs);
|
|
6
|
+
return () => clearTimeout(handle);
|
|
7
|
+
},
|
|
8
|
+
};
|
|
9
|
+
/** The host's cryptographic random bytes. */
|
|
10
|
+
export const systemRandom = {
|
|
11
|
+
bytes: (count) => crypto.getRandomValues(new Uint8Array(count)),
|
|
12
|
+
};
|
|
13
|
+
/** The host's `fetch`, called through its global, since a browser refuses a `fetch` called apart from its global. */
|
|
14
|
+
export const systemFetch = (input, init) => globalThis.fetch(input, init);
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import
|
|
1
|
+
import type { Clock } from "../shared/clock.js";
|
|
2
|
+
import type { Collector, CollectorOptions, Mode } from "../shared/collectorTypes.js";
|
|
3
|
+
import { type Fetch, type Transport } from "../shared/transport.js";
|
|
2
4
|
/**
|
|
3
5
|
* Returns a collector. Throws a `TypeError` that names the option for options that would make the intake refuse every
|
|
4
6
|
* envelope, such as a bad key, version or endpoint, and for options only a host outside TypeScript passes. A language
|
|
@@ -12,5 +14,12 @@ export declare function newCollector<M extends Mode>(options: CollectorOptions &
|
|
|
12
14
|
* event of a local day. That event adds the day to the active days.
|
|
13
15
|
*/
|
|
14
16
|
export declare function newCollectorNotingDays(options: CollectorOptions, onNewDay: () => void): Collector;
|
|
15
|
-
/**
|
|
16
|
-
|
|
17
|
+
/**
|
|
18
|
+
* Returns a transport that posts each body to `endpoint` with `fetch`, the host's own by default. The transport
|
|
19
|
+
* resolves to the status and the raw `Retry-After` header, or to status 0 when a request fails or takes over 30
|
|
20
|
+
* seconds.
|
|
21
|
+
*/
|
|
22
|
+
export declare function newHttpTransport(endpoint: string, { fetch, clock }?: {
|
|
23
|
+
fetch?: Fetch;
|
|
24
|
+
clock?: Clock;
|
|
25
|
+
}): Transport;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { newCollectorOn } from "../shared/collector.js";
|
|
2
|
+
import { systemClock, systemFetch, systemRandom } from "./system.js";
|
|
3
|
+
import { newFetchTransport } from "../shared/transport.js";
|
|
4
|
+
export function newCollector(options) {
|
|
5
|
+
return newCollectorNotingDays(options, () => undefined);
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Returns a collector, as `newCollector` does, that calls `onNewDay` inside its lock each time it queues the first
|
|
9
|
+
* event of a local day. That event adds the day to the active days.
|
|
10
|
+
*/
|
|
11
|
+
export function newCollectorNotingDays(options, onNewDay) {
|
|
12
|
+
// The transport's timeout runs on the system clock even when the product passes its own.
|
|
13
|
+
const host = {
|
|
14
|
+
clock: options.clock ?? systemClock,
|
|
15
|
+
random: systemRandom,
|
|
16
|
+
newTransport: newHttpTransport,
|
|
17
|
+
};
|
|
18
|
+
return newCollectorOn({ host, options, onNewDay });
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Returns a transport that posts each body to `endpoint` with `fetch`, the host's own by default. The transport
|
|
22
|
+
* resolves to the status and the raw `Retry-After` header, or to status 0 when a request fails or takes over 30
|
|
23
|
+
* seconds.
|
|
24
|
+
*/
|
|
25
|
+
export function newHttpTransport(endpoint, { fetch = systemFetch, clock = systemClock } = {}) {
|
|
26
|
+
return newFetchTransport(endpoint, { fetch, clock });
|
|
27
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Mode, type Collector, type CommonOptions, type Delivery, type ModeOptions, type PageFields, type PageOptions } from "
|
|
2
|
-
import type { Lock } from "
|
|
3
|
-
import type { StorageAdapter } from "
|
|
1
|
+
import { Mode, type Collector, type CommonOptions, type Delivery, type ModeOptions, type PageFields, type PageOptions } from "../shared/collectorTypes.js";
|
|
2
|
+
import type { Lock } from "../shared/lock.js";
|
|
3
|
+
import type { StorageAdapter } from "../shared/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.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { detectBrowser } from "
|
|
2
|
-
import { newCollector } from "./
|
|
3
|
-
import { Mode, } from "
|
|
4
|
-
import { PAGE_VIEW, Platform } from "
|
|
1
|
+
import { detectBrowser } from "../shared/browser.js";
|
|
2
|
+
import { newCollector } from "./systemCollector.js";
|
|
3
|
+
import { Mode, } from "../shared/collectorTypes.js";
|
|
4
|
+
import { PAGE_VIEW, Platform } from "../shared/envelope.js";
|
|
5
5
|
export function newWebCollector(options) {
|
|
6
6
|
const defaults = {
|
|
7
7
|
platform: Platform.Web,
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gives the time and the timers. The collector and the transport read both through this port, so that a test can move
|
|
3
|
+
* them by hand. A timer hands back its own cancel, so the port names no timer handle, whose type differs between
|
|
4
|
+
* hosts.
|
|
5
|
+
*/
|
|
6
|
+
export interface Clock {
|
|
7
|
+
/** Returns milliseconds since the epoch. */
|
|
8
|
+
now(): number;
|
|
9
|
+
/** Runs `callback` after `delayMs` and returns the function that cancels it. A cancel after the run does nothing. */
|
|
10
|
+
setTimeout(callback: () => void, delayMs: number): () => void;
|
|
11
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Clock } from "./clock.js";
|
|
2
|
+
import { type Collector, type CollectorOptions } from "./collectorTypes.js";
|
|
3
|
+
import type { Random } from "./random.js";
|
|
4
|
+
import { type Transport } from "./transport.js";
|
|
5
|
+
/** What the collector reads from its host: the time and timers, random bytes, and a transport to an address. */
|
|
6
|
+
export interface Host {
|
|
7
|
+
clock: Clock;
|
|
8
|
+
random: Random;
|
|
9
|
+
/** Returns the transport that posts to `endpoint`, for a product that passes `endpoint` and no `transport`. */
|
|
10
|
+
newTransport: (endpoint: string) => Transport;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Returns a collector that throws as `newCollector` in `src/infra/systemCollector.ts` describes. It calls `onNewDay`
|
|
14
|
+
* inside its lock each time it queues the first event of a local day, which adds the day to the active days. It ignores
|
|
15
|
+
* `options.clock`, so the caller puts that clock into `host`.
|
|
16
|
+
*/
|
|
17
|
+
export declare function newCollectorOn({ host, options, onNewDay, }: {
|
|
18
|
+
host: Host;
|
|
19
|
+
options: CollectorOptions;
|
|
20
|
+
onNewDay: () => void;
|
|
21
|
+
}): Collector;
|
|
22
|
+
/** Returns the longest an event waits in the queue before a send starts, as the options set it. */
|
|
23
|
+
export declare function sendDelayMsOf({ sendDelaySeconds, }: Pick<CollectorOptions, "sendDelaySeconds">): number;
|
|
@@ -2,7 +2,6 @@ import { daysBetween, formatDay, localDateAt, Period } from "./calendar.js";
|
|
|
2
2
|
import { LifecycleEvent, UNINSTALLED } from "./envelope.js";
|
|
3
3
|
import { activeDaysBucket, ageInDays, isLanguage, languageTag, newEvent, uninstalledParams, } from "./fields.js";
|
|
4
4
|
import { accepted, checkedBuild, isUsableId, newBrowserReader, newStringStorage, quoted, reportTo, usableId, } from "./hostInput.js";
|
|
5
|
-
import { systemClock } from "./clock.js";
|
|
6
5
|
import { newChannelStorage } from "./storage.js";
|
|
7
6
|
import { AnalyticsState, Mode } from "./collectorTypes.js";
|
|
8
7
|
import { acceptedEvent } from "./eventCheck.js";
|
|
@@ -15,19 +14,17 @@ import { newThrottle } from "./throttle.js";
|
|
|
15
14
|
import { transportsOf } from "./transport.js";
|
|
16
15
|
const SESSION_IDLE_MINUTES = 10;
|
|
17
16
|
const SEND_DELAY_SECONDS = 5;
|
|
18
|
-
export function newCollector(options) {
|
|
19
|
-
return newCollectorNotingDays(options, () => undefined);
|
|
20
|
-
}
|
|
21
17
|
/**
|
|
22
|
-
* Returns a collector
|
|
23
|
-
* event of a local day
|
|
18
|
+
* Returns a collector that throws as `newCollector` in `src/infra/systemCollector.ts` describes. It calls `onNewDay`
|
|
19
|
+
* inside its lock each time it queues the first event of a local day, which adds the day to the active days. It ignores
|
|
20
|
+
* `options.clock`, so the caller puts that clock into `host`.
|
|
24
21
|
*/
|
|
25
|
-
export function
|
|
22
|
+
export function newCollectorOn({ host, options, onNewDay, }) {
|
|
26
23
|
const product = checkedBuild(options);
|
|
27
24
|
const { mode } = options;
|
|
28
|
-
const
|
|
25
|
+
const { clock, random } = host;
|
|
26
|
+
const transports = transportsOf(options, host.newTransport);
|
|
29
27
|
const storage = newChannelStorage(newStringStorage(options.storage), options.key);
|
|
30
|
-
const clock = options.clock ?? systemClock;
|
|
31
28
|
const reportError = (error) => reportTo(options.onError, error);
|
|
32
29
|
const lock = exclusive(options.lock);
|
|
33
30
|
const getId = options.mode === Mode.Identified ? usableId(options.getId, reportError) : undefined;
|
|
@@ -37,6 +34,7 @@ export function newCollectorNotingDays(options, onNewDay) {
|
|
|
37
34
|
const install = newInstallState({
|
|
38
35
|
storage,
|
|
39
36
|
sessionIdleMs: durationOr(options.sessionIdleMinutes, SESSION_IDLE_MINUTES) * 60_000,
|
|
37
|
+
random,
|
|
40
38
|
});
|
|
41
39
|
const outbox = newOutbox({
|
|
42
40
|
key: options.key,
|
|
@@ -49,6 +47,7 @@ export function newCollectorNotingDays(options, onNewDay) {
|
|
|
49
47
|
giveBack: (items) => giveBack(items),
|
|
50
48
|
sendDelayMs: sendDelayMsOf(options),
|
|
51
49
|
clock,
|
|
50
|
+
random,
|
|
52
51
|
reportError,
|
|
53
52
|
});
|
|
54
53
|
// The collector takes the page when a method is called, so a navigation before the event is recorded does not move
|
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
export { detectBrowser, BrowserName, type Browser, type NavigatorFields } from "./browser.js";
|
|
2
|
-
export { newCollector } from "./collector.js";
|
|
3
2
|
export { ActiveDaysBucket, AnalyticsState, Mode, type Collector, type CollectorOptions, type CommonOptions, type Delivery, type GetId, type ModeOptions, type PageFields, type PageOptions, type StateOf, type TrackOptions, type UninstallParams, } from "./collectorTypes.js";
|
|
4
3
|
export { Platform, type EventParams } from "./envelope.js";
|
|
5
4
|
export { checkEvent } from "./eventCheck.js";
|
|
6
5
|
export { checkOptions, isTestKey } from "./hostInput.js";
|
|
7
6
|
export { newMemoryStorage, type StorageAdapter } from "./storage.js";
|
|
8
|
-
export {
|
|
7
|
+
export type { Transport, TransportResult } from "./transport.js";
|
|
9
8
|
export type { Lock } from "./lock.js";
|
|
10
|
-
export {
|
|
9
|
+
export type { Clock } from "./clock.js";
|
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
export { detectBrowser, BrowserName } from "./browser.js";
|
|
2
|
-
export { newCollector } from "./collector.js";
|
|
3
2
|
export { ActiveDaysBucket, AnalyticsState, Mode, } from "./collectorTypes.js";
|
|
4
3
|
export { Platform } from "./envelope.js";
|
|
5
4
|
export { checkEvent } from "./eventCheck.js";
|
|
6
5
|
export { checkOptions, isTestKey } from "./hostInput.js";
|
|
7
6
|
export { newMemoryStorage } from "./storage.js";
|
|
8
|
-
export { newHttpTransport } from "./transport.js";
|
|
9
|
-
export { systemClock } from "./clock.js";
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Period, type CalendarDate } from "./calendar.js";
|
|
2
2
|
import { type Envelope } from "./envelope.js";
|
|
3
|
+
import { type Random } from "./random.js";
|
|
3
4
|
import type { StorageAdapter } from "./storage.js";
|
|
4
5
|
/** What the collector knows about one event when it records it. */
|
|
5
6
|
export interface EventStamp {
|
|
@@ -54,9 +55,11 @@ interface InstallState {
|
|
|
54
55
|
/** Returns the number of local days with a queued or sent event. */
|
|
55
56
|
activeDays(): Promise<number>;
|
|
56
57
|
}
|
|
57
|
-
export declare function newInstallState({ storage, sessionIdleMs, }: {
|
|
58
|
+
export declare function newInstallState({ storage, sessionIdleMs, random, }: {
|
|
58
59
|
storage: StorageAdapter;
|
|
59
60
|
/** Time without events that ends a session. */
|
|
60
61
|
sessionIdleMs: number;
|
|
62
|
+
/** Makes the session and install ids. */
|
|
63
|
+
random: Random;
|
|
61
64
|
}): InstallState;
|
|
62
65
|
export {};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Period, formatDay, localDateAt, parseDay, periodKey, } from "./calendar.js";
|
|
2
2
|
import { LifecycleEvent } from "./envelope.js";
|
|
3
|
-
import { newRandomId } from "./
|
|
3
|
+
import { newRandomId } from "./random.js";
|
|
4
4
|
const SESSION_ID_LENGTH = 12;
|
|
5
5
|
/**
|
|
6
6
|
* The most active days the collector stores. It reports the count in buckets, and the last bucket is `21+`, so the
|
|
@@ -30,7 +30,7 @@ const StorageKey = {
|
|
|
30
30
|
ActiveDays: "active_days",
|
|
31
31
|
firstOf: (period) => `first.${period}`,
|
|
32
32
|
};
|
|
33
|
-
export function newInstallState({ storage, sessionIdleMs, }) {
|
|
33
|
+
export function newInstallState({ storage, sessionIdleMs, random, }) {
|
|
34
34
|
async function installDayOr(today) {
|
|
35
35
|
const stored = parseDay(await storage.get(StorageKey.InstallDay));
|
|
36
36
|
if (stored) {
|
|
@@ -107,7 +107,7 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
107
107
|
const stored = await storage.get(StorageKey.Session);
|
|
108
108
|
const lastSeen = Number(await storage.get(StorageKey.SessionSeen));
|
|
109
109
|
const isIdle = !(timestamp - lastSeen < sessionIdleMs);
|
|
110
|
-
const session = stored === undefined || stored === "" || isIdle || isNewDay ? newSessionId() : stored;
|
|
110
|
+
const session = stored === undefined || stored === "" || isIdle || isNewDay ? newSessionId(random) : stored;
|
|
111
111
|
await storage.set(StorageKey.Session, session);
|
|
112
112
|
await storage.set(StorageKey.SessionSeen, String(timestamp));
|
|
113
113
|
return session;
|
|
@@ -125,7 +125,7 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
125
125
|
if (stored !== undefined && INSTALL_ID_FORMAT.test(stored)) {
|
|
126
126
|
return stored;
|
|
127
127
|
}
|
|
128
|
-
const id = newRandomId(INSTALL_ID_BYTES);
|
|
128
|
+
const id = newRandomId(random, INSTALL_ID_BYTES);
|
|
129
129
|
await storage.set(StorageKey.InstallId, id);
|
|
130
130
|
return id;
|
|
131
131
|
},
|
|
@@ -180,8 +180,8 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
180
180
|
activeDays: async () => (await readActiveDays()).length,
|
|
181
181
|
};
|
|
182
182
|
}
|
|
183
|
-
function newSessionId() {
|
|
183
|
+
function newSessionId(random) {
|
|
184
184
|
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyz";
|
|
185
|
-
const bytes =
|
|
185
|
+
const bytes = random.bytes(SESSION_ID_LENGTH);
|
|
186
186
|
return Array.from(bytes, (byte) => alphabet[byte % alphabet.length]).join("");
|
|
187
187
|
}
|
|
@@ -2,6 +2,7 @@ import type { Clock } from "./clock.js";
|
|
|
2
2
|
import type { Envelope, UsageEvent } from "./envelope.js";
|
|
3
3
|
import type { Lock } from "./lock.js";
|
|
4
4
|
import { type Identity, type QueuedEnvelope } from "./queue.js";
|
|
5
|
+
import { type Random } from "./random.js";
|
|
5
6
|
import type { StorageAdapter } from "./storage.js";
|
|
6
7
|
import type { Transport } from "./transport.js";
|
|
7
8
|
/**
|
|
@@ -26,8 +27,8 @@ interface Outbox {
|
|
|
26
27
|
*/
|
|
27
28
|
send(): Promise<void>;
|
|
28
29
|
/**
|
|
29
|
-
* Drops every envelope not sent yet
|
|
30
|
-
* `src/queue.ts` describes.
|
|
30
|
+
* Drops every envelope not sent yet, except those that carry an `opted_out` event. Resolves to the dropped
|
|
31
|
+
* envelopes whose marks may go back, as `src/shared/queue.ts` describes.
|
|
31
32
|
*/
|
|
32
33
|
discard(): Promise<QueuedEnvelope[]>;
|
|
33
34
|
/**
|
|
@@ -44,7 +45,7 @@ interface Outbox {
|
|
|
44
45
|
* Expects the caller to run `add`, `discard`, `forget`, `discardIdentified` and `holdsRequests` inside its own `lock`,
|
|
45
46
|
* which it holds for the whole recording of an event. The sends take the lock themselves.
|
|
46
47
|
*/
|
|
47
|
-
export declare function newOutbox({ key, storage, lock, transport, forgetTransport, identify, giveBack, sendDelayMs, clock, reportError, }: {
|
|
48
|
+
export declare function newOutbox({ key, storage, lock, transport, forgetTransport, identify, giveBack, sendDelayMs, clock, random, reportError, }: {
|
|
48
49
|
/** The channel key, which a forget request names. */
|
|
49
50
|
key: string;
|
|
50
51
|
storage: StorageAdapter;
|
|
@@ -64,6 +65,8 @@ export declare function newOutbox({ key, storage, lock, transport, forgetTranspo
|
|
|
64
65
|
*/
|
|
65
66
|
giveBack: (items: readonly QueuedEnvelope[]) => Promise<void>;
|
|
66
67
|
clock: Clock;
|
|
68
|
+
/** Makes the queue ids and names this outbox's leases. */
|
|
69
|
+
random: Random;
|
|
67
70
|
reportError: (error: unknown) => void;
|
|
68
71
|
}): Outbox;
|
|
69
72
|
export {};
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import { daysBetween, parseDay, utcDateAt } from "./calendar.js";
|
|
2
2
|
import { isTestKey, isUsableId, quoted } from "./hostInput.js";
|
|
3
|
-
import { newQueue,
|
|
3
|
+
import { newQueue, } from "./queue.js";
|
|
4
|
+
import { newRandomId } from "./random.js";
|
|
4
5
|
const RETRY_DELAY_MS = 1_000;
|
|
5
6
|
const MAX_RETRY_DELAY_MS = 5 * 60_000;
|
|
6
7
|
/** Names the stored time, in epoch milliseconds, before which no context that shares the storage starts a send. */
|
|
7
8
|
const RETRY_AT_KEY = "retry_at";
|
|
8
9
|
/**
|
|
9
|
-
* The time one send holds the lease on a queued envelope, twice the 30 s request limit of `
|
|
10
|
-
* `src/transport.ts`. The send renews the lease before each request. A host that stops mid-send blocks the
|
|
11
|
-
* only until its lease ends.
|
|
10
|
+
* The time one send holds the lease on a queued envelope, twice the 30 s request limit of `newFetchTransport` in
|
|
11
|
+
* `src/shared/transport.ts`. The send renews the lease before each request. A host that stops mid-send blocks the
|
|
12
|
+
* envelope only until its lease ends.
|
|
12
13
|
*/
|
|
13
14
|
const LEASE_MS = 60_000;
|
|
14
15
|
/**
|
|
@@ -21,13 +22,14 @@ const MAX_HTTP_STATUS = 599;
|
|
|
21
22
|
* Expects the caller to run `add`, `discard`, `forget`, `discardIdentified` and `holdsRequests` inside its own `lock`,
|
|
22
23
|
* which it holds for the whole recording of an event. The sends take the lock themselves.
|
|
23
24
|
*/
|
|
24
|
-
export function newOutbox({ key, storage, lock, transport, forgetTransport, identify, giveBack, sendDelayMs, clock, reportError, }) {
|
|
25
|
-
const queue = newQueue({ storage, reportError });
|
|
25
|
+
export function newOutbox({ key, storage, lock, transport, forgetTransport, identify, giveBack, sendDelayMs, clock, random, reportError, }) {
|
|
26
|
+
const queue = newQueue({ storage, random, reportError });
|
|
26
27
|
/** Names this outbox's leases, apart from those of other contexts that share the storage. */
|
|
27
|
-
const holder = newRandomId();
|
|
28
|
-
let
|
|
28
|
+
const holder = newRandomId(random);
|
|
29
|
+
let cancelSendTimer;
|
|
29
30
|
let sendDue = Number.POSITIVE_INFINITY;
|
|
30
|
-
|
|
31
|
+
/** Cancels the timer of the pending retry. Set only while a retry is pending. */
|
|
32
|
+
let cancelRetryTimer;
|
|
31
33
|
let retryDelay = RETRY_DELAY_MS;
|
|
32
34
|
/** Chains the sends, so that one runs at a time and queued envelopes leave in the order they were made. */
|
|
33
35
|
let sending = Promise.resolve();
|
|
@@ -40,23 +42,24 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
40
42
|
return { holder, now: clock.now(), until: clock.now() + LEASE_MS };
|
|
41
43
|
}
|
|
42
44
|
function cancelSend() {
|
|
43
|
-
|
|
45
|
+
cancelSendTimer?.();
|
|
46
|
+
cancelSendTimer = undefined;
|
|
44
47
|
sendDue = Number.POSITIVE_INFINITY;
|
|
45
48
|
}
|
|
46
49
|
function cancelRetry() {
|
|
47
|
-
|
|
48
|
-
|
|
50
|
+
cancelRetryTimer?.();
|
|
51
|
+
cancelRetryTimer = undefined;
|
|
49
52
|
}
|
|
50
53
|
/** Starts a send within `delayMs`, unless a send is due sooner or a retry is pending. */
|
|
51
54
|
function sendWithin(delayMs) {
|
|
52
55
|
// The pending retry carries the new events too. An earlier send would reach an intake that asked the outbox to
|
|
53
56
|
// wait.
|
|
54
|
-
if (
|
|
57
|
+
if (cancelRetryTimer !== undefined || sendDue <= clock.now() + delayMs) {
|
|
55
58
|
return;
|
|
56
59
|
}
|
|
57
|
-
|
|
60
|
+
cancelSendTimer?.();
|
|
58
61
|
sendDue = clock.now() + delayMs;
|
|
59
|
-
|
|
62
|
+
cancelSendTimer = clock.setTimeout(() => void sendUnlessRetryPending(), delayMs);
|
|
60
63
|
}
|
|
61
64
|
/** Sends at once, cancelling a pending retry, as `flush` and a retry timer do. */
|
|
62
65
|
function send() {
|
|
@@ -72,7 +75,7 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
72
75
|
function sendUnlessRetryPending() {
|
|
73
76
|
cancelSend();
|
|
74
77
|
sending = sending
|
|
75
|
-
.then(async () => (
|
|
78
|
+
.then(async () => (cancelRetryTimer === undefined ? sendLeased() : undefined))
|
|
76
79
|
.catch(reportError);
|
|
77
80
|
return sending;
|
|
78
81
|
}
|
|
@@ -152,7 +155,7 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
152
155
|
cancelSend();
|
|
153
156
|
cancelRetry();
|
|
154
157
|
const waitMs = Math.min(Math.max(retryDelay, askedWaitMs ?? 0), MAX_RETRY_DELAY_MS);
|
|
155
|
-
|
|
158
|
+
cancelRetryTimer = clock.setTimeout(() => void send(), waitMs);
|
|
156
159
|
retryDelay = Math.min(retryDelay * 2, MAX_RETRY_DELAY_MS);
|
|
157
160
|
await lock(async () => keepRetryWait(waitMs));
|
|
158
161
|
}
|
|
@@ -284,9 +287,9 @@ function httpStatus(status, reportError) {
|
|
|
284
287
|
* answers null or undefined, as only a product's own transport outside TypeScript does.
|
|
285
288
|
*/
|
|
286
289
|
async function answerOf(transport, body, clock) {
|
|
287
|
-
let
|
|
290
|
+
let cancelLate;
|
|
288
291
|
const late = new Promise((resolve) => {
|
|
289
|
-
|
|
292
|
+
cancelLate = clock.setTimeout(() => resolve({ status: 0 }), TRANSPORT_LIMIT_MS);
|
|
290
293
|
});
|
|
291
294
|
try {
|
|
292
295
|
const answer = await Promise.race([transport(body), late]);
|
|
@@ -299,7 +302,7 @@ async function answerOf(transport, body, clock) {
|
|
|
299
302
|
return { status: 0 };
|
|
300
303
|
}
|
|
301
304
|
finally {
|
|
302
|
-
|
|
305
|
+
cancelLate?.();
|
|
303
306
|
}
|
|
304
307
|
}
|
|
305
308
|
/**
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type Envelope, type IdKind, type UsageEvent } from "./envelope.js";
|
|
2
|
+
import { type Random } from "./random.js";
|
|
2
3
|
import type { StorageAdapter } from "./storage.js";
|
|
3
4
|
export declare const QUEUE_KEY = "queue";
|
|
4
5
|
export interface QueuedEnvelope {
|
|
@@ -87,8 +88,10 @@ interface Queue {
|
|
|
87
88
|
holdsRequests(): Promise<boolean>;
|
|
88
89
|
}
|
|
89
90
|
/** Returns a queue in `storage`. The caller holds a lock around each call. */
|
|
90
|
-
export declare function newQueue({ storage, reportError, }: {
|
|
91
|
+
export declare function newQueue({ storage, random, reportError, }: {
|
|
91
92
|
storage: StorageAdapter;
|
|
93
|
+
/** Makes the queue ids. */
|
|
94
|
+
random: Random;
|
|
92
95
|
reportError: (error: unknown) => void;
|
|
93
96
|
}): Queue;
|
|
94
97
|
/**
|
|
@@ -96,6 +99,4 @@ export declare function newQueue({ storage, reportError, }: {
|
|
|
96
99
|
* without a queue id and an envelope with a list of events.
|
|
97
100
|
*/
|
|
98
101
|
export declare function parseQueue(stored: string | undefined): QueuedEnvelope[] | undefined;
|
|
99
|
-
/** Returns `byteCount` random bytes, 8 by default, as lowercase hex. */
|
|
100
|
-
export declare function newRandomId(byteCount?: number): string;
|
|
101
102
|
export {};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { LifecycleEvent } from "./envelope.js";
|
|
2
|
+
import { newRandomId } from "./random.js";
|
|
2
3
|
export const QUEUE_KEY = "queue";
|
|
3
4
|
/** Names the ids of the stored forget requests, a JSON list. */
|
|
4
5
|
const FORGETS_KEY = "forgets";
|
|
@@ -15,7 +16,7 @@ const MAX_QUEUED_ENVELOPES = 20;
|
|
|
15
16
|
*/
|
|
16
17
|
const MAX_QUEUED_OPT_OUTS = 2;
|
|
17
18
|
/** Returns a queue in `storage`. The caller holds a lock around each call. */
|
|
18
|
-
export function newQueue({ storage, reportError, }) {
|
|
19
|
+
export function newQueue({ storage, random, reportError, }) {
|
|
19
20
|
/**
|
|
20
21
|
* Returns the stored envelopes. A stored queue that is no JSON list is reported once and dropped. An item without a
|
|
21
22
|
* queue id and an envelope with a list of events is skipped, so a value another script wrote never makes a method
|
|
@@ -85,7 +86,7 @@ export function newQueue({ storage, reportError, }) {
|
|
|
85
86
|
add: async (fields, event, { awaitsId = false } = {}) => {
|
|
86
87
|
const isOptOut = event.name === LifecycleEvent.OptedOut;
|
|
87
88
|
const newItem = () => ({
|
|
88
|
-
qid: newRandomId(),
|
|
89
|
+
qid: newRandomId(random),
|
|
89
90
|
...(awaitsId && { awaitsId: true }),
|
|
90
91
|
...(isOptOut && { isOptOut: true }),
|
|
91
92
|
envelope: { ...fields, events: [event] },
|
|
@@ -215,11 +216,6 @@ function fits(envelope, event) {
|
|
|
215
216
|
const withEvent = { ...envelope, events: [...envelope.events, event] };
|
|
216
217
|
return new TextEncoder().encode(JSON.stringify(withEvent)).length <= MAX_ENVELOPE_BYTES;
|
|
217
218
|
}
|
|
218
|
-
/** Returns `byteCount` random bytes, 8 by default, as lowercase hex. */
|
|
219
|
-
export function newRandomId(byteCount = 8) {
|
|
220
|
-
const bytes = crypto.getRandomValues(new Uint8Array(byteCount));
|
|
221
|
-
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
222
|
-
}
|
|
223
219
|
function isQueuedEnvelope(value) {
|
|
224
220
|
if (typeof value !== "object" ||
|
|
225
221
|
value === null ||
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gives random bytes. The collector makes its queue, lease, session and install ids through this port, so that it reads
|
|
3
|
+
* no host API itself.
|
|
4
|
+
*/
|
|
5
|
+
export interface Random {
|
|
6
|
+
/** Returns `count` random bytes. */
|
|
7
|
+
bytes(count: number): Uint8Array;
|
|
8
|
+
}
|
|
9
|
+
/** Returns `byteCount` random bytes, 8 by default, as lowercase hex. */
|
|
10
|
+
export declare function newRandomId(random: Random, byteCount?: number): string;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { Clock } from "./clock.js";
|
|
2
2
|
import type { CollectorOptions } from "./collectorTypes.js";
|
|
3
3
|
/** What the intake answered: its HTTP status, 0 when the request did not reach it, and its `Retry-After` header. */
|
|
4
4
|
export interface TransportResult {
|
|
@@ -12,20 +12,21 @@ export interface TransportResult {
|
|
|
12
12
|
* keeps a forgotten user's events from a request that arrives over a minute after the forget.
|
|
13
13
|
*/
|
|
14
14
|
export type Transport = (body: string) => Promise<number | TransportResult>;
|
|
15
|
+
/** The `fetch` a transport posts with. */
|
|
16
|
+
export type Fetch = typeof globalThis.fetch;
|
|
15
17
|
/**
|
|
16
|
-
* Returns a transport that posts each body to `endpoint` with `fetch
|
|
17
|
-
*
|
|
18
|
-
* seconds.
|
|
18
|
+
* Returns a transport that posts each body to `endpoint` with `fetch`. The transport resolves to the status and the raw
|
|
19
|
+
* `Retry-After` header, or to status 0 when a request fails or takes over 30 seconds.
|
|
19
20
|
*/
|
|
20
|
-
export declare function
|
|
21
|
-
fetch
|
|
22
|
-
clock
|
|
21
|
+
export declare function newFetchTransport(endpoint: string, { fetch, clock }: {
|
|
22
|
+
fetch: Fetch;
|
|
23
|
+
clock: Clock;
|
|
23
24
|
}): Transport;
|
|
24
25
|
/**
|
|
25
26
|
* Returns the transport of the envelopes and that of the forget requests. A product's own transport takes both kinds
|
|
26
27
|
* of request.
|
|
27
28
|
*/
|
|
28
|
-
export declare function transportsOf(options: CollectorOptions): {
|
|
29
|
+
export declare function transportsOf(options: CollectorOptions, newTransport: (endpoint: string) => Transport): {
|
|
29
30
|
transport: Transport;
|
|
30
31
|
forgetTransport: Transport;
|
|
31
32
|
};
|
|
@@ -1,16 +1,12 @@
|
|
|
1
|
-
import { systemClock } from "./clock.js";
|
|
2
1
|
const TIMEOUT_MS = 30_000;
|
|
3
2
|
/**
|
|
4
|
-
* Returns a transport that posts each body to `endpoint` with `fetch
|
|
5
|
-
*
|
|
6
|
-
* seconds.
|
|
3
|
+
* Returns a transport that posts each body to `endpoint` with `fetch`. The transport resolves to the status and the raw
|
|
4
|
+
* `Retry-After` header, or to status 0 when a request fails or takes over 30 seconds.
|
|
7
5
|
*/
|
|
8
|
-
export function
|
|
9
|
-
// The default calls `fetch` through its global. A browser refuses a `fetch` called apart from its global.
|
|
10
|
-
fetch = (input, init) => globalThis.fetch(input, init), clock = systemClock, } = {}) {
|
|
6
|
+
export function newFetchTransport(endpoint, { fetch, clock }) {
|
|
11
7
|
return async (body) => {
|
|
12
8
|
const timeout = new AbortController();
|
|
13
|
-
const
|
|
9
|
+
const cancelTimeout = clock.setTimeout(() => timeout.abort(), TIMEOUT_MS);
|
|
14
10
|
try {
|
|
15
11
|
const response = await fetch(endpoint, {
|
|
16
12
|
method: "POST",
|
|
@@ -32,7 +28,7 @@ fetch = (input, init) => globalThis.fetch(input, init), clock = systemClock, } =
|
|
|
32
28
|
return { status: 0 };
|
|
33
29
|
}
|
|
34
30
|
finally {
|
|
35
|
-
|
|
31
|
+
cancelTimeout();
|
|
36
32
|
}
|
|
37
33
|
};
|
|
38
34
|
}
|
|
@@ -40,13 +36,13 @@ fetch = (input, init) => globalThis.fetch(input, init), clock = systemClock, } =
|
|
|
40
36
|
* Returns the transport of the envelopes and that of the forget requests. A product's own transport takes both kinds
|
|
41
37
|
* of request.
|
|
42
38
|
*/
|
|
43
|
-
export function transportsOf(options) {
|
|
39
|
+
export function transportsOf(options, newTransport) {
|
|
44
40
|
if (options.transport !== undefined) {
|
|
45
41
|
return { transport: options.transport, forgetTransport: options.transport };
|
|
46
42
|
}
|
|
47
43
|
return {
|
|
48
|
-
transport:
|
|
49
|
-
forgetTransport:
|
|
44
|
+
transport: newTransport(options.endpoint),
|
|
45
|
+
forgetTransport: newTransport(forgetUrlOf(options.endpoint)),
|
|
50
46
|
};
|
|
51
47
|
}
|
|
52
48
|
/**
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { newRecordingCollector, queuedEvents, type RecordedEvent, type RecordingCollector, } from "./recordingCollector.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { newRecordingCollector, queuedEvents, } from "./recordingCollector.js";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { Mode, type Collector } from "
|
|
3
|
-
import type { EventParams } from "
|
|
4
|
-
import { type StorageAdapter } from "
|
|
1
|
+
import type { Clock } from "../shared/clock.js";
|
|
2
|
+
import { Mode, type Collector } from "../shared/collectorTypes.js";
|
|
3
|
+
import type { EventParams } from "../shared/envelope.js";
|
|
4
|
+
import { type StorageAdapter } from "../shared/storage.js";
|
|
5
5
|
/** One event as a product tracked it. */
|
|
6
6
|
export interface RecordedEvent {
|
|
7
7
|
name: string;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { systemClock } from "
|
|
2
|
-
import { AnalyticsState, Mode } from "
|
|
3
|
-
import { acceptedEvent } from "
|
|
4
|
-
import { isUsableId, quoted, reportTo } from "
|
|
5
|
-
import { parseQueue, QUEUE_KEY } from "
|
|
6
|
-
import { channelTakes } from "
|
|
7
|
-
import { newChannelStorage } from "
|
|
8
|
-
import { newThrottle } from "
|
|
1
|
+
import { systemClock } from "../infra/system.js";
|
|
2
|
+
import { AnalyticsState, Mode } from "../shared/collectorTypes.js";
|
|
3
|
+
import { acceptedEvent } from "../shared/eventCheck.js";
|
|
4
|
+
import { isUsableId, quoted, reportTo } from "../shared/hostInput.js";
|
|
5
|
+
import { parseQueue, QUEUE_KEY } from "../shared/queue.js";
|
|
6
|
+
import { channelTakes } from "../shared/stateFields.js";
|
|
7
|
+
import { newChannelStorage } from "../shared/storage.js";
|
|
8
|
+
import { newThrottle } from "../shared/throttle.js";
|
|
9
9
|
/**
|
|
10
10
|
* Returns a collector of channel mode `mode`, `anonymous` by default, that sends nothing and records each event the
|
|
11
11
|
* real collector would send. Its user starts in the anonymous state. It refuses an event `track` refuses, a state above
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kk-forge/artel-collector",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Sends a product's analytics events to the intake service",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "KK Forge",
|
|
@@ -13,28 +13,24 @@
|
|
|
13
13
|
],
|
|
14
14
|
"type": "module",
|
|
15
15
|
"sideEffects": false,
|
|
16
|
-
"main": "./dist/exports.js",
|
|
17
|
-
"types": "./dist/exports.d.ts",
|
|
16
|
+
"main": "./dist/shared/exports.js",
|
|
17
|
+
"types": "./dist/shared/exports.d.ts",
|
|
18
18
|
"exports": {
|
|
19
19
|
".": {
|
|
20
|
-
"types": "./dist/exports.d.ts",
|
|
21
|
-
"default": "./dist/exports.js"
|
|
20
|
+
"types": "./dist/shared/exports.d.ts",
|
|
21
|
+
"default": "./dist/shared/exports.js"
|
|
22
22
|
},
|
|
23
|
-
"./
|
|
24
|
-
"types": "./dist/
|
|
25
|
-
"default": "./dist/
|
|
23
|
+
"./infra": {
|
|
24
|
+
"types": "./dist/infra/exports.d.ts",
|
|
25
|
+
"default": "./dist/infra/exports.js"
|
|
26
26
|
},
|
|
27
|
-
"./
|
|
28
|
-
"types": "./dist/
|
|
29
|
-
"default": "./dist/
|
|
30
|
-
},
|
|
31
|
-
"./desktop": {
|
|
32
|
-
"types": "./dist/desktop.d.ts",
|
|
33
|
-
"default": "./dist/desktop.js"
|
|
27
|
+
"./infra/chrome": {
|
|
28
|
+
"types": "./dist/infra/chrome/exports.d.ts",
|
|
29
|
+
"default": "./dist/infra/chrome/exports.js"
|
|
34
30
|
},
|
|
35
31
|
"./testing": {
|
|
36
|
-
"types": "./dist/testing.d.ts",
|
|
37
|
-
"default": "./dist/testing.js"
|
|
32
|
+
"types": "./dist/testing/exports.d.ts",
|
|
33
|
+
"default": "./dist/testing/exports.js"
|
|
38
34
|
}
|
|
39
35
|
},
|
|
40
36
|
"publishConfig": {
|
|
@@ -45,9 +41,9 @@
|
|
|
45
41
|
"build": "node --eval \"process.getBuiltinModule('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json",
|
|
46
42
|
"lint": "npm run lint:tsc && npm run lint:oxlint && npm run lint:format",
|
|
47
43
|
"lint:fix": "npm run lint:oxlint:fix && npm run lint:format:fix",
|
|
48
|
-
"lint:tsc": "tsc",
|
|
49
|
-
"lint:oxlint": "oxlint
|
|
50
|
-
"lint:oxlint:fix": "oxlint --fix
|
|
44
|
+
"lint:tsc": "tsc && tsc -p tsconfig.dom.json && tsc -p tsconfig.node.json",
|
|
45
|
+
"lint:oxlint": "oxlint",
|
|
46
|
+
"lint:oxlint:fix": "oxlint --fix",
|
|
51
47
|
"lint:format": "oxfmt --check .",
|
|
52
48
|
"lint:format:fix": "oxfmt .",
|
|
53
49
|
"test": "npm run test:unit",
|
|
@@ -55,13 +51,17 @@
|
|
|
55
51
|
"test:ci": "vitest run --coverage"
|
|
56
52
|
},
|
|
57
53
|
"devDependencies": {
|
|
58
|
-
"@kk-forge/oxlint-config": "^
|
|
54
|
+
"@kk-forge/oxlint-config": "^11.0.0",
|
|
55
|
+
"@types/node": "^26.6.6",
|
|
59
56
|
"@vitest/coverage-v8": "^5.0.5",
|
|
60
57
|
"oxfmt": "^0.73.0",
|
|
61
|
-
"oxlint": "^1.
|
|
62
|
-
"oxlint-tsgolint": "^7.0.
|
|
58
|
+
"oxlint": "^1.93.0",
|
|
59
|
+
"oxlint-tsgolint": "^7.0.2007",
|
|
63
60
|
"typescript": "^7.0.2",
|
|
64
61
|
"vitest": "^5.0.5",
|
|
65
62
|
"vitest-sonar-reporter": "^3.0.0"
|
|
63
|
+
},
|
|
64
|
+
"allowScripts": {
|
|
65
|
+
"fsevents": false
|
|
66
66
|
}
|
|
67
67
|
}
|
package/dist/clock.d.ts
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
export type TimerHandle = ReturnType<typeof setTimeout>;
|
|
2
|
-
/**
|
|
3
|
-
* Gives the time and the timers. The collector and the transport read both through this port, so that a test can move
|
|
4
|
-
* them by hand.
|
|
5
|
-
*/
|
|
6
|
-
export interface Clock {
|
|
7
|
-
/** Returns milliseconds since the epoch. */
|
|
8
|
-
now(): number;
|
|
9
|
-
setTimeout(callback: () => void, delayMs: number): TimerHandle;
|
|
10
|
-
clearTimeout(handle: TimerHandle | undefined): void;
|
|
11
|
-
}
|
|
12
|
-
export declare const systemClock: Clock;
|
package/dist/clock.js
DELETED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|