@kk-forge/artel-collector 0.1.1 → 0.3.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 CHANGED
@@ -1,8 +1,8 @@
1
1
  # @kk-forge/artel-collector
2
2
 
3
- Sends a product's usage events to the intake service. It runs in a website, a web app, a browser extension or a desktop window, and has no runtime dependencies.
3
+ Sends a product's usage events to the intake service. It runs in a website, a web app, a Chrome extension or a desktop window, and has no runtime dependencies.
4
4
 
5
- The collector marks the first event of each local day, week, month, quarter and year, and adds the install age to those events. From these marks the intake counts daily, weekly and monthly active users without a user id. The collector also keeps a session, holds every event in a queue in storage until the intake takes it, and carries an on/off switch for the user.
5
+ The collector marks the first event of each local day, week, month, quarter and year, and adds the install age to those events, so the intake counts active users per period without a user id. The collector also keeps a session, holds every event in a queue in storage until the intake takes it, and keeps the user's analytics choice.
6
6
 
7
7
  ## Install
8
8
 
@@ -10,126 +10,231 @@ The collector marks the first event of each local day, week, month, quarter and
10
10
  npm install @kk-forge/artel-collector
11
11
  ```
12
12
 
13
+ ## Choose a mode and a state
14
+
15
+ A channel in the intake's admin is anonymous or identified, and its collector takes the same `mode`. The mode sets which states the channel takes. The user's state sets what the collector sends, and the collector stores it. Every user starts in `anonymous`.
16
+
17
+ | State | What the collector sends | Channel |
18
+ | ------------ | ----------------------------------------------------------------------------------------- | --------------- |
19
+ | `opted_out` | one `opted_out` when the user enters the state, then nothing | either |
20
+ | `anonymous` | events with no user id and no browser, the primary languages only, ages in coarse buckets | either |
21
+ | `identified` | events with the user's id, the browser, the full languages and exact ages | identified only |
22
+
23
+ - An anonymous channel needs no consent. Its options take neither `getId` nor `browser`, and its `setState` takes `opted_out` and `anonymous`.
24
+ - An identified channel needs the user's consent before the product calls `setState('identified')`. Its options take `getId`, and `browser` on the web and in an extension.
25
+
26
+ On a site, the events of both sending states also carry their page path, and the first `page_view` the referring host, as `getPage` describes.
27
+
28
+ Any site can read the browser and the full language tags. With the exact install age, and with the `platform` and `version` every envelope carries, these fields can single out a user, so only the `identified` state, which needs the user's consent, sends them. Every envelope of that state carries the id. The uninstall query of that state carries the full languages and an exact age up to 31, with no id.
29
+
30
+ A product with its own analytics switch calls `setState('opted_out')` once for each user who turned it off, then deletes the switch's stored value.
31
+
32
+ ### Languages
33
+
34
+ - `browserLanguage` is the user's language: the one the browser asks sites for, `navigator.language` by default on the web and in an extension.
35
+ - `uiLanguage` is the language the user picked in the product, when the product offers that choice. Only the product's option sets it, on every platform. A product without that choice passes none, and its envelopes carry no `ui_language`.
36
+
37
+ In the `anonymous` state both are cut to the primary language: `pt-BR` goes as `pt`, `zh-Hant-TW` as `zh`.
38
+
13
39
  ## Usage
14
40
 
41
+ Each `const usage` line makes a collector. `key`, `version` and `endpoint` are variables of the build, and `getId` returns the user's id in the identified state.
42
+
15
43
  ```ts
16
- import { newCollector, newHttpTransport, Platform } from '@kk-forge/artel-collector';
17
-
18
- const usage = newCollector({
19
- key, // the channel key, a variable of the build
20
- platform: Platform.Extension,
21
- version: '4.2.0',
22
- lang: 'en',
23
- storage, // see "Storage"
24
- transport: newHttpTransport('https://intake.example.com/v1/public/relay'),
44
+ // a website or a web app
45
+ const usage = newWebCollector({ key, version, endpoint, mode: 'anonymous' });
46
+ const usage = newWebCollector({ key, version, endpoint, mode: 'identified', getId, uiLanguage: settings.language });
47
+ // a site whose paths carry a secret or a person sends the route pattern instead
48
+ const usage = newWebCollector({
49
+ key,
50
+ version,
51
+ endpoint,
52
+ mode: 'anonymous',
53
+ getPage: () => ({ page: route.pattern, referrer: document.referrer }),
25
54
  });
26
55
 
56
+ // a Chrome extension, in the service worker and in each page
57
+ const usage = newExtensionCollector({ key, endpoint, mode: 'anonymous' });
58
+ const usage = newExtensionCollector({ key, endpoint, mode: 'identified', getId });
59
+ // a content script of that extension, which hands its events to the service worker
60
+ const usage = newContentScriptCollector();
61
+
62
+ // a window of a desktop app, such as a Tauri webview, where `platform` is 'macos', 'windows' or 'linux'
63
+ const usage = newDesktopCollector({ key, version, endpoint, platform, mode: 'anonymous' });
64
+ const usage = newDesktopCollector({ key, version, endpoint, platform, mode: 'identified', getId });
65
+ ```
66
+
67
+ Then track what the user does, and store their choice when they make it, here in an identified channel:
68
+
69
+ ```ts
27
70
  void usage.track('report_exported', { format: 'pdf', pages: 12, with_images: true });
71
+ void usage.setState(consented ? 'identified' : 'anonymous');
72
+ void usage.setState('opted_out'); // the user turned usage statistics off
28
73
  ```
29
74
 
75
+ `newWebCollector` comes from `@kk-forge/artel-collector/web`, `newExtensionCollector` and `newContentScriptCollector` from `@kk-forge/artel-collector/extension`, `newDesktopCollector` from `@kk-forge/artel-collector/desktop`, and `newCollector` from the main module. 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'` 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 "`@kk-forge/artel-collector/extension`" describes.
76
+
77
+ 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.
78
+
79
+ | Option | `newWebCollector` | `newExtensionCollector` | `newDesktopCollector` |
80
+ | -------------------------- | -------------------------------- | -------------------------------- | ------------------------------------- |
81
+ | `platform` | `web` | `extension` | required: `macos`, `windows`, `linux` |
82
+ | `version` | required | the manifest's | required |
83
+ | `storage` | `newLocalStorageAdapter()` | `newChromeStorageAdapter()` | `newLocalStorageAdapter()` |
84
+ | `lock` | `newWebLock()` | `newWebLock()` | `newWebLock()` |
85
+ | `browserLanguage` | `navigator.language` | `navigator.language` | `navigator.language` |
86
+ | `uiLanguage` | none | none | none |
87
+ | `getPage` | `pageFields`, see below | not taken | not taken |
88
+ | `browser`, identified only | `() => detectBrowser(navigator)` | `() => detectBrowser(navigator)` | not taken |
89
+
30
90
  ### Options
31
91
 
32
- - `key`: the channel key. It comes in as a variable at build time, so the code holds no key and one commit builds every target. A channel has a live key, `<kind>-<10 characters>`, for the build for the store and a test key, `<kind>-test-<10 characters>`, for any other build. The intake marks test events and keeps them out of the product's analytics. The live key is no secret. The test key stays out of the build for the store, since anyone who has it can read the channel's test events.
33
- - `platform`: `Platform.Extension`, `MacOs`, `Windows`, `Linux` or `Web`.
34
- - `version`: the product version, such as `1.2.3` or `1.2.3-beta.1`, up to 32 characters.
35
- - `lang`: the interface language as a BCP 47 code, such as `en` or `pt-BR`. Optional.
92
+ - `key`: the channel key. It comes in as a variable at build time, so the code holds no key and one commit builds every target. A channel has a live key, `<kind>-<10 characters>`, for the build for the store and a test key, `<kind>-test-<10 characters>`, for any other build. The kind is `extension`, `desktop` or `site`, and the 10 characters are lowercase letters and digits. The intake marks test events and keeps them out of the product's analytics. The live key is no secret. The test key stays out of the build for the store, since anyone who has it can read the channel's test events. A key that breaks this form, or whose kind does not take `platform`, makes the constructor throw, since the intake would refuse every envelope.
93
+ - The origins the intake takes a request from, per channel kind. A test key of any kind also takes the origins of a developer build: the `chrome-extension://` origin of any real Chrome id, 32 letters from `a` to `p`, and `http://localhost` and `http://127.0.0.1` on any port. Any other origin, and a request with no `Origin`, gets 403, which drops the envelope and reports it.
94
+
95
+ | Kind | Origins |
96
+ | ----------- | ------------------------------------------------------------- |
97
+ | `site` | the one origin the channel sets |
98
+ | `extension` | `chrome-extension://<id>` for the Chrome Web Store id it sets |
99
+ | `desktop` | `tauri://localhost` and `http://tauri.localhost` |
100
+
101
+ - An extension channel without a Chrome Web Store id takes no live request.
102
+ - These get 403 with either key: a Tauri 2 window on Windows with `useHttpsScheme`, whose origin is `https://tauri.localhost`; a dev server over `https://localhost`; a Firefox extension, whose origin is `moz-extension://`; and a `transport` that sends from Rust, as Tauri's HTTP plugin does, with no browser `Origin`.
103
+ - `mode`: `'anonymous'` or `'identified'`, as "Choose a mode and a state" describes. `Mode.Anonymous` and `Mode.Identified` name the same values. Another value, which only untyped code can pass, works as `'anonymous'`.
104
+ - `endpoint`: the intake's relay address, whose path is `/v1/public/relay`. The channel's admin gives the address. The collector posts each envelope there with `keepalive`, without cookies or a referrer. An `endpoint` that is not `https`, or that names a user or a password, which `fetch` refuses, makes the constructor throw. Plain `http` is taken only for development, to `localhost`, `127.0.0.1`, `[::1]`, a host under `.localhost` or one under `.test`.
105
+ - `transport`, in place of `endpoint`: a function that delivers the envelope body. It must resolve within 30 seconds to `{ status, retryAfter }`, the intake's HTTP status and the raw value of its `Retry-After` header, or to the status alone. The status is `0` when the request did not reach the intake. A transport that rejects counts as `0`. So does a transport that has not resolved after 35 seconds, and an answer whose status is no whole number from 0 to 599, an answer with no status included. A `retryAfter` that is not a string counts as none, and an answer of `null` or `undefined` as `0`. `newHttpTransport` resolves to the object. A `transport` that is not a function, which only untyped code can pass, makes the constructor throw. With a `transport`, the collector never reads `endpoint`.
106
+ - `platform`: the platform of the envelope, `'web'`, `'extension'`, `'macos'`, `'windows'` or `'linux'`, also `Platform.Web` and so on. It is not the kind of the channel in the intake's admin, `site`, `extension` or `desktop`. A `site` channel takes `web`, an `extension` channel `extension`, and a `desktop` channel `macos`, `windows` or `linux`, and `key` names the kind. Another platform, which only untyped code can pass, makes the constructor throw.
107
+ - `version`: the product version, required on every platform, up to 32 characters: one to four dot-separated numbers, then an optional `-` prerelease and `+` build of letters, digits and dots, such as `1.2.3` or `1.2.3-beta.1`. The intake refuses an envelope without one, so a version that is missing or breaks this format makes the constructor throw. Chrome's own manifest versions all fit it.
108
+ - `browserLanguage` and `uiLanguage`: as "Languages" describes. Each is a language tag of up to 16 characters: two or three lowercase letters, then up to two `-` parts of 2 to 8 letters or digits, such as `en`, `pt-BR` or `zh-Hant-TW`. The collector reads `_` as `-`, so `en_US` goes as `en-US`. The intake refuses a whole envelope whose language breaks this format, so the collector leaves such a language out and reports it to `onError`.
36
109
  - `storage`: where the collector keeps its state. See "Storage".
37
- - `transport`: `newHttpTransport(endpoint)`, which posts without cookies or a referrer, or a function that delivers the envelope body. It resolves within 30 seconds to the intake's HTTP status, or to `0` when the request did not reach the intake.
38
- - `getId`: returns the user's id in a `full` channel once they consented, or `undefined`. The collector never creates an id.
39
- - `getPage`: returns `{ page, referrer }` for an event of a site channel, the path without the query string and the referring host. The collector reads no page itself, and cuts the two to 256 and 128 characters.
40
- - `lock`: runs an operation while no other context that shares `storage` runs one, such as `newWebLock()` from the web module. Without it, two contexts recording at once may both mark the first event of a day, or overwrite each other's queued events.
41
- - `sessionIdleMinutes`: minutes without events that end a session, 10 by default.
110
+ - `getId`, identified only: returns the user's id, up to 64 characters, or `undefined` while the product does not know it yet, as before sign-in loads. It may return a promise of either. The collector calls it only in the `identified` state, and never creates an id. Events of the identified state wait in the queue until `getId` returns an id. A longer id is reported and counts as not known yet. An empty string, or a value that is not a string, such as the `null` of untyped code, also counts as not known yet, without a report. A `getId` that throws loses the event being recorded, or stops the send that called it, and the queue waits for the next send. Both go to `onError`. Events that wait go under the next id only when it is the last id `getId` gave, or when it gave none before. When `getId` gives another id, as after a sign-out and another user's sign-in, the collector drops the unsent events of the last user and those that waited after them, and starts a new session. So no event goes under another user's id. Two contexts that see different users at once each drop the other's unsent events. `getId` runs while the collector holds its lock. So `getId` must resolve, and must call no method of the collector, or every later call waits forever.
111
+ - `browser`, identified only, web and extension only: the browser the product runs in, `{ name, major }`, or a function that returns it or `undefined`. The function runs under the lock too, with the same rule as `getId`. The collector calls the function once, for the first event with an id, so the anonymous state never reads the browser. The collector sends a copy. A name the intake does not list goes as `other`, and a major version outside 1 to 999 is left out. A browser on a desktop platform, which only untyped code can pass, makes the constructor throw.
112
+ - `getPage(name)`: returns `{ page, referrer }` for an event named `name`. `page` is the page's path or its full URL, and `referrer` a URL. Only platform `web` takes it and sends the two fields, since the intake keeps them only for a `site` channel. Another platform never calls it. The collector calls it when the method is called, so a navigation right after `track` does not move the event. `newWebCollector` takes `pageFields` by default. The collector shapes whatever `getPage` returns by the rules below. The intake masks the page by wider rules of its own and stores the event without such a referrer, so a stored page may hold an `:address` the collector did not send.
113
+ - The page goes as its path only, as the platform `URL` reads it, so the query and the fragment go nowhere. Each segment is cut at its first `;`, so a path parameter such as `/cart;jsessionid=…` goes as `/cart`. The path is cut to 256 characters, never inside an escape.
114
+ - Each segment that holds an e-mail address or an IP address goes as `:address`, so `/u/alice@example.com` goes as `/u/:address`. An `@` counts, and so do `@` (U+FF20) and `﹫` (U+FE6B), which a browser shows alike. So do four dotted numbers, as in `10.0.0.1`, and an IPv6 address, as in `fe80::1`. A four-part version counts too, so `/docs/1.2.3.4` goes as `/docs/:address`. The collector reads the segment as written and decoded up to twice, so `%40` and `%2540` count as `@`. An escape that does not decode as UTF-8 stays as written, and the ASCII escapes around it still decode, so `/u/caf%E9%40mail.com%` goes as `/u/:address`.
115
+ - A segment that starts a URL goes with the rest of the path as one `:address`. It holds a scheme and `://`, as in `/login/next=https%3A%2F%2Fsite.com`, or ends in a scheme's `:` before an empty segment, as in `/open/myapp://item`. It also holds `http:`, `https:`, `ws:`, `wss:`, `ftp:` or `file:` in any case, at its start or after a character that is not a letter or a digit, as in `/go/https:site.com`.
116
+ - The collector leaves out a page that `URL` cannot read, or whose path does not start with `/`, such as `mailto:alice@example.com`. The report names no part of the page. It also leaves out and reports a field that is not a string.
117
+ - The referrer goes as the lowercased host of a URL. The collector sends no referrer for text that is no URL, such as a bare `www.google.com`. It also sends none for a host longer than 128 characters, the most the intake keeps, or a host that is an IP address or holds an `@`. `URL` writes every IPv4 form a browser reads as four decimal numbers, so a host whose last label is a number counts as one. The referrer goes only with the first `page_view` the collector records, which on a site is the first of a page load. A referrer of the same host as a page given as a full URL goes nowhere.
118
+ - The collector sends no `page_view` of the page the last recorded `page_view` sent, so two in a row for one page send one. A recorded `page_view` without a page ends that run. A `page_view` the collector does not record, as in the `opted_out` state, counts for neither rule.
119
+
120
+ A site whose paths carry another secret or person, such as `/share/<token>` or `/u/<name>`, passes its own `getPage` that returns the route pattern, such as `/share/:token`.
121
+
122
+ - `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.
123
+ - `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`.
42
124
  - `sendDelaySeconds`: the longest an event waits in the queue before a send starts, 5 by default.
43
125
  - `clock`: time and timers, the host's own by default. Tests pass a fake.
44
- - `onError`: receives every failure the collector swallows.
126
+ - `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:
127
+ - an event `track` refuses;
128
+ - an event or envelope dropped by a limit, by its age or by the intake's refusal;
129
+ - a stored queue that is no JSON list, which the collector reads as empty;
130
+ - a stored retry wait more than 5 minutes ahead or that is no time;
131
+ - a language the collector leaves out, a state `setState` refuses, an id past 64 characters, an id `forget` refuses, a transport status that is no HTTP status, a page the collector leaves out, and a page field that is not a string;
132
+ - a storage, lock, `getId`, `browser` or `getPage` error, and an extension worker's `setAccessLevel` that fails.
133
+
134
+ A request that goes again later, after a network failure, 429 or 5xx, does not reach it. Its envelope reaches it only when a drop rule removes it. These reach no `onError` of the collector: a forwarded event the extension worker refuses or drops, a `forwardTrack` or a content script's `track` that fails, and a failure of `refreshUninstallUrl` outside `uninstallParams()`, which goes to that function's own `onError`.
45
135
 
46
136
  ### Methods
47
137
 
48
138
  Every method returns a promise that resolves and never rejects. A failure goes to `onError`. So a call whose result you do not wait for is marked `void`, as in the examples.
49
139
 
50
- - `track(name, params?)` records an event. The name and each param name must be on the product's allowlist and match this form: a lowercase letter, then lowercase letters, digits and `_`, up to 40 characters. A param value is a string up to 64 characters, a number or a boolean.
51
- - `installed()` sends `installed` once per install. A later call sends no event.
52
- - `updated()` sends `updated` when `version` differs from the last version seen. Call it after `installed()`, so that a fresh install does not also count as an update.
53
- - `setEnabled(on)` with `false` drops the events not sent yet, sends `usage_counts_off` and stops sending. With `true` it sends `usage_counts_on`. The choice persists.
54
- - `isEnabled()` resolves to the stored choice, on by default.
55
- - `flush()` sends what is queued now.
56
- - `forget(id)` drops the queued events of this id, and resolves once this collector's request in flight has ended. To forget a user, make `getId` stop returning the id, call `forget(id)`, then ask the intake to forget the user. A request another context sent arrives within its 30 seconds, and the intake deletes events that arrive up to a minute after the forget. The intake forgets by the live key only. Test events go when the channel's test data is cleared.
57
- - `uninstallParams()` resolves to `{ platform, version, lang, age, days }` for an uninstall page. `age` is days since install, and `days` is the bucket of active days: `0`, `1`, `2-5`, `6-20` or `21+`.
140
+ - `track(name, params?)` records an event. It records nothing in the `opted_out` state. The name and each param name must be on the product's allowlist and match this form: a lowercase letter, then lowercase letters, digits and `_`, up to 40 characters. An event takes up to 16 params. A param value is a string up to 64 characters, a finite number or a boolean. The intake also drops an event whose string param looks like an address, a domain or an IP, a four-part version such as `1.0.0.1` included. The collector does not check this rule, so `onError` does not hear of such a drop. A system event takes only its own params:
141
+
142
+ | Event | Params |
143
+ | ----------------------------- | --------------------------------------------------------------------------------------------- |
144
+ | `page_view`, `welcome_opened` | none |
145
+ | `install_click` | `product`, a string |
146
+ | `uninstalled` | `age_days`, a whole number from 0, and `active_days`, one of `0`, `1`, `2-5`, `6-20` or `21+` |
147
+
148
+ The intake keeps `welcome_opened` and `uninstalled` without an id at most once an hour per source, and drops the rest.
149
+
150
+ The collector refuses an event that breaks one of these rules, and `installed`, `updated` and `opted_out`, which only its own methods send. It reports a refused event to `onError`, naming the rule it breaks, and queues none of it. `track` copies the params once, when it is called, so a later change to the object reaches neither the check nor the event. Params whose reading throws, as a getter or a proxy may, go to `onError`, and nothing is recorded. The intake also drops the whole event when a param is off the allowlist or an enum param's value is off its list. The collector does not know the allowlist, so it cannot refuse these.
58
151
 
59
- ### Types
152
+ - `installed()` sends `installed` once per install. A later call sends no event. In the `opted_out` state it sends nothing and marks nothing, so a user who turns analytics back on still sends it.
153
+ - `updated()` sends `updated` when `version` differs from the last version `installed()` or `updated()` stored, or when none is stored. Call it after `installed()`, so that a fresh install does not also count as an update. In the `opted_out` state it sends nothing and marks nothing. A desktop app calls both methods on every start.
154
+ - `setState(state)` stores the user's choice and starts a new session, so events from before and after the change share no session. The same state again does nothing.
155
+ - To `opted_out`: stores the state first, then drops the events not sent yet and the last id `getId` gave, and sends one `opted_out`. It goes at once, or at the end of a retry wait that is running. An `opted_out` from an earlier opt-out that has not gone yet stays queued. The `opted_out` goes in an envelope of its own, with no id, no browser, no first-of-period mark and no age, so no count of active users takes it. Its session is new and no other event shares it. A run that stops after storing the state drops the queue on the first call of its next run. If that run stopped before it queued the `opted_out`, none is sent.
156
+ - From `identified`: drops the queued events of the identified state, those waiting for an id included, and the last id `getId` gave.
157
+ - An anonymous channel refuses `identified`: a type error, and `onError` in untyped code.
158
+ - `getState()` resolves to the stored state, `anonymous` until the user chose. It also resolves to `anonymous` when the storage fails, whatever the user chose, and reports the failure. On the first call of any method, an `identified` state that an anonymous channel finds stored becomes `anonymous`, as `setState('anonymous')` would make it.
159
+ - `flush()` sends what is queued now and resolves once that send ends. While the wait after a failed request runs, it schedules the send for the end of the wait instead.
160
+ - `forget(id)` drops the queued events of this id. An `id` that is no string, from untyped code, drops nothing. When this id is the last one `getId` gave, it also drops the events that wait for an id. The next id `getId` gives then counts as another user, so the events that waited after the forget never go under it. It resolves once this collector's request in flight has ended. To forget a user, leave the `identified` state or make `getId` stop returning the id, call `forget(id)`, then ask the intake to forget the user with `POST /v1/public/forget` and `{ key, id }`. The intake checks the request's `Origin` as it checks a relay request, so the product sends it from its own page, extension or window, and a request from its server gets 403. The intake takes up to 60 forget requests a minute per channel and answers 429 with `Retry-After` past that. A forget answered 429 or 503 did not happen, so the product sends it again after the wait. The intake deletes the user's events in every channel of the product, and those that arrive up to a minute after the forget. A request another context sent arrives within its 30-second limit. The intake forgets by the live key only. Test events go when the channel's test data is cleared.
161
+ - `uninstallParams()` resolves to the query of an uninstall page. It resolves to `undefined` in the `opted_out` state, and when the storage fails. The query is `{ platform, version, browser_language, ui_language, age_days, active_days }`, each shaped by the state as an envelope is. `age_days` is days since install, and `active_days` the bucket of active days, the local days whose first event is queued or sent: `0`, `1`, `2-5`, `6-20` or `21+`, the values of `ActiveDaysBucket`. A day leaves the count when the event that took its first-of-day mark gives its marks back, as "Sending" describes. The next event of that day counts it again. The uninstall page is a page of the product's site. It sends `uninstalled` from its own `site` channel, with the params `age_days`, as a JSON number, and `active_days`. `track('uninstalled')` sends `age_days` shaped by the state as `uninstallParams()` gives it. The `platform`, `version` and languages in the query are for the page itself and are not params of the event.
60
162
 
61
- The main module also exports `systemClock`, the host's own `clock`, and the types `Collector`, `CollectorOptions`, `PageFields`, `UninstallParams`, `ActiveDaysBucket` (the values of `days`), `EventParams`, `StorageAdapter`, `Transport`, `Lock`, `Clock` and `TimerHandle`. `ActiveDaysBucket` is also a value: `ActiveDaysBucket.None` through `ActiveDaysBucket.TwentyOneOrMore`.
163
+ ### Other exports
164
+
165
+ `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.
166
+
167
+ The main module also exports `newHttpTransport(endpoint, { fetch, clock }?)`, the transport behind `endpoint`, `newMemoryStorage()`, `systemClock`, `Mode`, `AnalyticsState`, `Platform`, `ActiveDaysBucket` and `BrowserName`, and the types of every option, method and value above. `WebCollectorOptions`, `ExtensionCollectorOptions` and `DesktopCollectorOptions` come from their own modules.
62
168
 
63
169
  ## Sending
64
170
 
65
- The collector writes each event to the queue in storage at once. A send starts at most `sendDelaySeconds` after the first event waiting, so the events of those seconds share one request. An envelope of 100 events goes at once. An event that would take an envelope past 60 kB starts a new one, and an event that alone passes 60 kB is dropped and reported.
171
+ The collector writes each event to the queue in storage at once. A send starts at most `sendDelaySeconds` after the first event waiting, so the events of those seconds share one request. An envelope of 100 events goes at once. An event that would take an envelope past 60 kB starts a new one.
172
+
173
+ An envelope leaves the queue once the intake answered it, or by a drop rule, so a host stopped at any point keeps its queued events. Its next run sends the queue. A context that sends an envelope holds a one-minute lease on it and renews the lease before each request, so no other context sends it at the same time. An envelope whose sender stopped goes with the first send after that lease runs out. A lease that ends more than a minute ahead, as after the clock was set back, counts as run out. A failed request ends the lease, so the first send of any context after the retry wait below takes the envelope. Each envelope carries a `batch` key, and every attempt sends the body of the first attempt byte for byte. Events tracked after the first attempt go into a new envelope. The intake drops a repeat of an envelope it stored in the last 72 hours. The collector stops repeating an envelope within that time, by the rule for old events below. A 503 can also come back after the intake wrote part of an envelope. The intake catches the repeat of such an envelope only while it remembers that write among its last 10 000 inserts. Past that, part of the envelope is stored twice.
66
174
 
67
- An envelope leaves the queue once the intake answered it, or by a drop rule, so a host stopped at any point keeps its queued events. Its next run sends the queue. A context that sends an envelope holds a one-minute lease on it and renews the lease before each request, so no other context sends it at the same time. An envelope whose sender stopped goes with the first send after that lease runs out. A failed request ends the lease, so the next send of any context may take the envelope before its sender's own retry. Each envelope carries a `batch` key, and every attempt sends the body of the first attempt byte for byte. So the intake keeps the envelope once, even when an answer never came back. Events tracked after the first attempt go into a new envelope, and an envelope that may no longer go is dropped whole.
175
+ When the request fails or the intake answers 429 or 5xx, the envelope keeps its place. It goes again after 1 second, then after 2, 4 and so on, up to 5 minutes. The intake sends `Retry-After` with a 429, in seconds or as an HTTP date, and the collector reads it from a 503 too. The collector reads a date with `Date.parse`, which also takes other forms of a date. It then waits that long instead if it is longer, up to the same 5 minutes. The collector stores the end of the wait, so every context that shares the storage keeps it, and so does `flush()`. A shorter wait never replaces a longer one stored. A stored end more than 5 minutes ahead, as after the clock was set back, or one that is no time, counts as 5 minutes from now. New events wait for that retry. At most 20 envelopes wait, those waiting for an id included. Past 20 the oldest is dropped and reported, but never an `opted_out`. At most 2 `opted_out` envelopes wait, and a third drops and reports the oldest of them. Any other status outside 2xx, such as a 3xx, 400, 403 or 413, drops the envelope and reports it.
68
176
 
69
- When the request fails or the intake answers 429 or 5xx, the envelope keeps its place. It goes again after 1 second, then after 2, 4 and so on, up to 5 minutes. New events wait for that retry. At most 20 envelopes wait, and the oldest is dropped and reported. Any other 4xx drops the envelope and reports it.
177
+ Just before its request, the collector drops an envelope that holds an event dated before yesterday in UTC, and reports it. The intake would move such an event to its own today, and a sent envelope goes whole or not at all. An envelope of the identified state stays queued while `getId` returns `undefined`, and the envelopes after it go. Once `getId` returns an id, the envelope goes with that id, and with the browser, under the same rule for old events.
70
178
 
71
- Before a send, the collector drops queued events dated before yesterday in UTC, which the intake would move to its own today. It also drops an envelope whose id `getId` no longer returns, as after a user withdrew consent. A sealed envelope whose stored body no longer matches its events is dropped and reported.
179
+ Any script that can write the storage can also write the queue. Such a script can already call `track` and post to the intake with the public key, so the collector checks a stored queue only for the shape it reads. It reads a stored queue that is no JSON list as empty and reports it once, and skips an item without a queue id and an envelope with a list of events. The intake applies every rule of its own to whatever arrives.
180
+
181
+ The marks an event takes go back when the collector drops it before any request carried it. The drops that give them back are a change of state, another id, the 20-envelope cap, the rule for old events, and a failure while the event was recorded. So the next event takes the first-of-period marks and counts its day again, and `installed()` and `updated()` send again. An envelope a request carried keeps its marks whatever drops it later, since the intake may have stored it. `forget` gives back the marks of the id's queued envelopes, those a request carried included, since the intake deletes their events. Leaving the `identified` state first drops those envelopes, so then only the ones no request carried give back their marks.
72
182
 
73
183
  ## Storage
74
184
 
75
- `storage` is any `{ get(key), set(key, value) }` that returns promises. Every key starts with `artel.`. `newMemoryStorage()` keeps the state only while the page or worker lives. The platform modules below bring adapters over `localStorage` and `chrome.storage.local`.
185
+ `storage` is any `{ get(key), set(key, value) }` over strings that returns promises. `get` resolves to the stored string, or to `undefined` for a missing key. The collector reads any other value, such as the `null` of some stores, as a missing key. A `get` must see every `set` that resolved before it, in every context that shares the storage. The collector never removes a key. Every key is `artel.<key>.<name>`, where `<key>` is the channel key, such as `artel.site-aa131n3j11.queue`. Collectors of different keys over one storage share no stored value, so a live and a test build, or two products on one origin, keep their own state and queues. The storage holds the state, the install day, the install mark and the last version. It also holds the session and the time of its last event, the first-of-period marks, the active days and the end of the retry wait. It holds the queue, whose envelopes of the identified state carry the user's id, and the last id `getId` gave. The queue is one value: up to 20 envelopes of up to 60 kB each, and the request body of each sealed one.
186
+
187
+ 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.
188
+
189
+ `newMemoryStorage()` keeps the state only while the page or worker lives. The platform modules below bring adapters over `localStorage` and `chrome.storage.local`.
76
190
 
77
191
  ## Platform modules
78
192
 
79
- The core touches no platform API. Two optional modules hold the code a website or an extension would otherwise write for itself.
193
+ The core touches no platform API. Three optional modules hold the code a website, an extension or a desktop app would otherwise write for itself.
80
194
 
81
195
  ### `@kk-forge/artel-collector/web`
82
196
 
83
- For a website, a web app, or a window of a desktop app such as Tauri or Electron.
197
+ For a website or a web app. The desktop module builds on its storage and lock.
84
198
 
85
- - `newLocalStorageAdapter()` returns a `storage` over `localStorage`. Every script of the origin can read it, the queued events with their `id` included, and no other storage of the origin hides them from its scripts. A site that runs untrusted scripts sends no `id`.
86
- - `newWebLock()` returns a `lock` over Web Locks, so that the tabs and workers of one origin do not send one envelope at the same time. Without Web Locks, operations run unguarded.
87
- - `pageFields()` is a `getPage` for a site channel: the path without the query string, and the referring host when it is another site. A site whose paths carry a secret or a person, such as `/share/<token>`, passes its own `getPage` with the route pattern instead.
88
- - `flushWhenHidden(collector)` sends the queue when the page is hidden, since the user may not come back. `newHttpTransport` posts with `keepalive`, so a request started before the tab closes still finishes. A send that has not started by then stays queued for the next visit. It returns the function that stops it.
199
+ - `newWebCollector(options)` makes a collector for a website or a web app, as in "Usage".
200
+ - `newLocalStorageAdapter()` returns a `storage` over `localStorage`. Every script of the origin can read it, the queued events with their `id` and the last id `getId` gave included, and no other storage of the origin hides them from its scripts. A site that runs untrusted scripts uses an anonymous channel.
201
+ - `newWebLock()` returns a `lock` over the Web Lock named `artel`, shared by the tabs and workers of one origin. Without Web Locks, operations run unguarded.
202
+ - `pageFields()` gives the page's address without its query string and fragment, and `document.referrer`. `newWebCollector`'s default `getPage` takes it, and the collector shapes both as "Options" describes under `getPage`.
203
+ - `trackPageViews(collector)` sends `page_view` for the page now and for each later navigation: `history.pushState` and `replaceState`, `popstate`, and the Navigation API's `currententrychange` where the browser has it. A navigation that keeps `location.pathname` sends none. So a change of the query or the hash alone sends none, and a router that keeps its routes in the hash gets one `page_view` per page load. A navigation that both `pushState` and the Navigation API report sends one. Two trackers of one collector each send their own, which the collector of platform `web` takes as one, since it sends no `page_view` of the page its last one sent. A tracker counts a path whether or not the collector records its `page_view`, so a page loaded in the `opted_out` state sends a `page_view` at the first navigation to another path after the user leaves that state. Leaving `opted_out` sends none by itself. `page_view` is a system event, which the intake counts without the product's allowlist. It returns the function that stops it. Once every tracker stopped, in any order, `history` is as they found it: a method the page inherited from `History.prototype` is inherited again. A product that wraps a method after the tracker keeps its wrapper, and the stopped tracker's wrapper under it stays and only passes calls on.
204
+ - `flushWhenHidden(collector)` sends the queue when the page is hidden, since the user may not come back. A request to `endpoint` that started before the tab closes still finishes. A send that has not started by then stays queued for the next visit. It returns the function that stops it.
89
205
 
90
- ```ts
91
- import { newCollector, newHttpTransport, Platform } from '@kk-forge/artel-collector';
92
- import { flushWhenHidden, newLocalStorageAdapter, newWebLock, pageFields } from '@kk-forge/artel-collector/web';
206
+ `newWebCollector` needs `localStorage`, which a Web Worker lacks, so a worker passes its own `storage`. Its default `getPage` sends no page where there is no `document` or `location`.
93
207
 
94
- const usage = newCollector({
95
- key,
96
- platform: Platform.Web,
97
- version,
98
- lang: navigator.language,
99
- storage: newLocalStorageAdapter(),
100
- lock: newWebLock(),
101
- transport: newHttpTransport(endpoint),
102
- getPage: pageFields,
103
- });
208
+ A site sets up page views in three lines:
104
209
 
105
- void usage.track('page_view');
210
+ ```ts
211
+ import { flushWhenHidden, newWebCollector, trackPageViews } from '@kk-forge/artel-collector/web';
212
+
213
+ const usage = newWebCollector({ key, version, endpoint, mode: 'anonymous' });
214
+ trackPageViews(usage);
106
215
  flushWhenHidden(usage);
107
216
  ```
108
217
 
109
- A desktop app calls both lifecycle methods on every start. `installed()` sends once, and `updated()` sends only after a version change.
110
-
111
218
  ### `@kk-forge/artel-collector/extension`
112
219
 
113
- For a Chrome extension. Its service worker and its pages each create a collector over `newChromeStorageAdapter()`, the shared `chrome.storage.local`, with `lock: newWebLock()` from the web module.
220
+ For a Chrome extension. Its 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.
114
221
 
115
- - `newChromeStorageAdapter()` returns a `storage` over `chrome.storage.local`. It needs the `storage` permission.
116
- - `forwardTrack(name, params?)` hands an event from a content script to the service worker. A content script's own requests carry the page's origin, which the intake refuses. The worker refuses a name or a param name past 40 characters, more than 16 params and a param string past 64 characters, the limits of a product's event list.
117
- - `acceptForwarded(collector, { clock }?)` tracks, in the service worker, the events content scripts forward, and returns the function that stops it. It takes them only from this extension, and never the collector's own lifecycle events. It tracks at most 60 forwarded events, or 60 kB of their names and params, a minute from all tabs and frames together and drops the rest, since a page can open any number of frames that run the content script. The budget outlasts a restart of the worker in `chrome.storage.session`, under the `storage` permission. `clock` is the time source, as in Options.
118
- - `refreshUninstallUrl(collector, pageUrl)` sets the uninstall page with `uninstallParams()` in its query. Chrome keeps the address as it was set, so call it on each start of the worker.
222
+ - `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 choice, 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.
223
+ - `newChromeStorageAdapter()` returns a `storage` over `chrome.storage.local`.
224
+ - `newContentScriptCollector()` returns the collector of a content script, typed `ContentScriptCollector`: `track` and `flush` only. Its `track` is `forwardTrack`, so the worker's collector checks, queues and sends the event under the user's choice, and `flush` does nothing. The user's choice lives in the service worker and the extension pages, so a content script can neither read nor change it, and its types say so. It reads no storage, needs no key, version or endpoint, and never throws.
225
+ - `forwardTrack(name, params?)` hands an event from a content script to the service worker. A content script's own requests carry the page's origin, which the intake refuses. It never rejects. While the worker cannot take the message, as during an update, the event is lost.
226
+ - `acceptForwarded(collector, { clock }?)` tracks, in the service worker, the events content scripts forward, and returns the function that stops it. It takes them only from this extension, and only the product's own events. It refuses every system event of the intake, which the intake counts from any product without its allowlist: `installed`, `updated`, `opted_out`, `uninstalled`, `welcome_opened`, `page_view` and `install_click`. It also refuses each event `track` refuses. A page can open any number of frames that run the content script. So the worker tracks at most 60 forwarded events a minute from all tabs and frames together, and drops the rest. It keeps the count in memory, so a restart of the worker starts it again. `clock` is the time source, as in Options.
227
+ - `refreshUninstallUrl(collector, pageUrl, { onError }?)` sets the uninstall page to `pageUrl` with the fields of `uninstallParams()` added to its query, or to `pageUrl` alone when `uninstallParams()` resolves to `undefined`. Chrome keeps the address as it was set, so call it on each start of the worker and after each `setState`. It never rejects. A failure of `uninstallParams()` goes to the collector's `onError`, and any other failure to the function's own `onError`.
119
228
 
120
229
  ```ts
121
230
  // service worker
122
- const usage = newCollector({
123
- key,
124
- platform: Platform.Extension,
125
- version: chrome.runtime.getManifest().version,
126
- storage: newChromeStorageAdapter(),
127
- lock: newWebLock(),
128
- transport: newHttpTransport(endpoint),
129
- });
231
+ import type { AnalyticsState } from '@kk-forge/artel-collector';
232
+ import { acceptForwarded, newExtensionCollector, refreshUninstallUrl } from '@kk-forge/artel-collector/extension';
130
233
 
234
+ const usage = newExtensionCollector({ key, endpoint, mode: 'identified', getId });
131
235
  acceptForwarded(usage);
132
- void refreshUninstallUrl(usage, 'https://example.com/uninstall');
236
+ const uninstallPage = 'https://example.com/uninstall';
237
+ void refreshUninstallUrl(usage, uninstallPage, { onError: console.error });
133
238
  chrome.runtime.onInstalled.addListener(async ({ reason }) => {
134
239
  if (reason === 'install') {
135
240
  await usage.installed();
@@ -138,42 +243,79 @@ chrome.runtime.onInstalled.addListener(async ({ reason }) => {
138
243
  }
139
244
  });
140
245
 
246
+ // wherever the worker stores the user's choice
247
+ async function storeChoice(choice: AnalyticsState): Promise<void> {
248
+ await usage.setState(choice);
249
+ await refreshUninstallUrl(usage, uninstallPage, { onError: console.error });
250
+ }
251
+
141
252
  // content script
142
- void forwardTrack('link_shared', { target: 'clipboard' });
253
+ import { newContentScriptCollector } from '@kk-forge/artel-collector/extension';
254
+
255
+ const usage = newContentScriptCollector();
256
+ void usage.track('link_shared', { target: 'clipboard' });
143
257
  ```
144
258
 
259
+ ### `@kk-forge/artel-collector/desktop`
260
+
261
+ For a window of a desktop app, such as a Tauri webview.
262
+
263
+ - `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 names no browser and sends no page.
264
+
145
265
  ## What is sent
146
266
 
147
- One envelope per request:
267
+ One envelope per request. An envelope in the `anonymous` state, in either channel:
148
268
 
149
269
  ```json
150
270
  {
151
271
  "key": "extension-aa131n3j11",
152
272
  "platform": "extension",
153
273
  "version": "4.2.0",
154
- "lang": "en",
274
+ "browser_language": "pt",
275
+ "ui_language": "en",
155
276
  "session": "k3j9x2m1qa0b",
156
- "batch": "9f2c41d07ab35e18",
157
277
  "events": [
158
278
  {
159
279
  "name": "report_exported",
160
280
  "day": "2026-10-29",
161
281
  "first": ["day", "week"],
162
- "age_days": 3,
282
+ "age_days": 2,
163
283
  "params": { "format": "pdf", "pages": 12, "with_images": true }
164
284
  }
165
- ]
285
+ ],
286
+ "batch": "9f2c41d07ab35e18"
166
287
  }
167
288
  ```
168
289
 
290
+ - `browser_language` and `ui_language` are the two languages "Languages" describes, each present when the collector has it.
169
291
  - `day` is the local calendar date. `first` lists the periods this event is the first of, in local time. Weeks are ISO weeks and start on Monday.
170
- - `age_days` comes with the `day` mark. It counts days since install from 0 to 30, and 31 stands for 31 or more. `age_months` comes with the `month` mark, which a `quarter` or `year` mark always comes with. It counts months from 0 to 24, and 25 stands for more than 24. The install date is the local date of the collector's first use.
171
- - `session` is 12 random characters from `[0-9a-z]`, a window of activity. A new one starts after `sessionIdleMinutes` without events, and at local midnight.
292
+ - `age_days` comes with the `day` mark, and counts days since install. `age_months` comes with the `month` mark, which a `quarter` or `year` mark always comes with, and counts months since install. The install date is the local date of the collector's first use. In the `anonymous` state each age is the lowest value of its bucket:
293
+ - `age_days`: `0`, `1`, `2` for 2 to 6 days, `7` for 7 to 13, `14` for 14 to 29, and `30` for 30 or more.
294
+ - `age_months`: `0`, `1`, `2`, `3` for 3 to 5 months, `6` for 6 to 11, `12` for 12 to 23, and `24` for 24 or more.
295
+ - `session` is 12 random characters from `[0-9a-z]`, a window of activity. A new one starts after `sessionIdleMinutes` without events, with the event that takes the `day` mark, at each change of state and when `getId` gives another id.
172
296
  - `batch` is 16 random hex characters per envelope, the same on every attempt to send it.
173
- - `id` is present only when `getId` returns one.
174
- - `page` and `referrer` are present only when `getPage` returns them.
297
+ - `key`, `platform` and `version` name the channel and the build, as "Options" describes.
298
+ - `params` holds what the product passed to `track`.
299
+ - `page` and `referrer` are present only on platform `web`, when `getPage` returns them, as it does by default.
300
+
301
+ In the `identified` state the ages are exact: `age_days` from 0 to 30, where 31 stands for 31 or more, and `age_months` from 0 to 24, where 25 stands for more than 24. The languages are whole, and the envelope adds `browser`, the browser on the web and in an extension, and `id`, the user's id from `getId`:
302
+
303
+ ```json
304
+ {
305
+ "browser_language": "pt-BR",
306
+ "ui_language": "en",
307
+ "browser": { "name": "chrome", "major": 131 },
308
+ "id": "c0ffee12"
309
+ }
310
+ ```
311
+
312
+ The `opted_out` event that `setState('opted_out')` sends:
313
+
314
+ ```json
315
+ { "name": "opted_out", "day": "2026-10-29" }
316
+ ```
175
317
 
176
- The collector reads no page, URL or user input. `params`, `id` and the page fields carry only what the product passes.
318
+ The core reads no page, URL or user input. `params`, `id` and the page fields carry only what the product passes, and the page fields only as the collector shapes them.
177
319
 
178
320
  ## Development
179
321
 
@@ -186,7 +328,7 @@ mise run check:ci # the same with coverage, as CI runs it
186
328
 
187
329
  ## Release
188
330
 
189
- Versions follow semver: a breaking change to the API this README describes raises the major version, or the minor one before 1.0.0. `src/exports.unit.test.ts` holds the names of that API's values and types. Raise `version` in `package.json` in a PR. Once it merges to `main`, `.github/workflows/release.yml` checks the package, publishes it to npm with provenance and tags `v<version>`. npm trusts that workflow as the package's Trusted Publisher, so the repository keeps no npm token. A merge that keeps the version publishes no new release. When the tag job fails after the publish, rerun that run's failed jobs, so the tag lands on the published commit. Until the tag exists, a later merge that keeps the version fails at the publish.
331
+ Versions follow semver: a breaking change to the API this README describes raises the major version, or the minor one before 1.0.0. `src/exports.unit.test.ts` holds the names of that API's values and types. Raise `version` in `package.json` in a PR, as `X.Y.Z`: the release workflow takes no prerelease version. Once it merges to `main`, `.github/workflows/release.yml` runs the shared [Release npm](https://github.com/kk-forge-engineering/gh-actions/blob/main/.github/workflows/release-npm.yml) workflow. It checks the package and waits for a reviewer of the `production` environment to approve the publish. It then publishes the package to npm with provenance and tags `v<version>`. npm trusts `release.yml` as the package's Trusted Publisher, so the repository keeps no npm token. A merge that keeps the version publishes no new release.
190
332
 
191
333
  ## License
192
334
 
@@ -0,0 +1,41 @@
1
+ /** The browsers the intake tells apart. Any other browser is `other`. */
2
+ export declare const BrowserName: {
3
+ readonly Chrome: 'chrome';
4
+ readonly Edge: 'edge';
5
+ readonly Opera: 'opera';
6
+ readonly Yandex: 'yandex';
7
+ readonly Brave: 'brave';
8
+ readonly Firefox: 'firefox';
9
+ readonly Safari: 'safari';
10
+ readonly Other: 'other';
11
+ };
12
+ export type BrowserName = (typeof BrowserName)[keyof typeof BrowserName];
13
+ type VersionedBrowserName = Exclude<BrowserName, typeof BrowserName.Other>;
14
+ /** The browser and its major version, when it is known. `other` carries no version. */
15
+ export type Browser = {
16
+ name: VersionedBrowserName;
17
+ major?: number;
18
+ } | {
19
+ name: typeof BrowserName.Other;
20
+ };
21
+ /** The part of `navigator` the detection reads. */
22
+ export interface NavigatorFields {
23
+ userAgent?: string;
24
+ userAgentData?: {
25
+ brands?: readonly {
26
+ brand: string;
27
+ version: string;
28
+ }[];
29
+ };
30
+ }
31
+ /**
32
+ * Names the browser from what `navigator` gives any site: the Client Hints brands of a Chromium browser, or else the
33
+ * User-Agent string. Returns undefined when it has neither, as outside a browser.
34
+ */
35
+ export declare function detectBrowser(nav: NavigatorFields): Browser | undefined;
36
+ /**
37
+ * Returns a fresh copy of a browser as the intake keeps it: a name off the list as `other`, and a major version outside
38
+ * 1 to 999 left out. Returns undefined for a value that is not an object, which only a host outside TypeScript passes.
39
+ */
40
+ export declare function copyBrowser(value: unknown): Browser | undefined;
41
+ export {};