@kk-forge/artel-collector 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -24
- package/dist/browser.d.ts +8 -8
- package/dist/browser.js +23 -21
- package/dist/calendar.d.ts +5 -5
- package/dist/calendar.js +7 -7
- package/dist/clock.d.ts +4 -4
- package/dist/clock.js +4 -2
- package/dist/collector.d.ts +7 -2
- package/dist/collector.js +85 -49
- package/dist/collectorTypes.d.ts +30 -21
- package/dist/collectorTypes.js +12 -12
- package/dist/desktop.d.ts +4 -4
- package/dist/desktop.js +2 -2
- package/dist/envelope.d.ts +11 -11
- package/dist/envelope.js +12 -12
- package/dist/eventCheck.d.ts +14 -5
- package/dist/eventCheck.js +50 -29
- package/dist/exports.d.ts +10 -10
- package/dist/exports.js +9 -9
- package/dist/extension.d.ts +15 -11
- package/dist/extension.js +120 -61
- package/dist/fields.d.ts +3 -3
- package/dist/fields.js +7 -7
- package/dist/hostInput.d.ts +5 -5
- package/dist/hostInput.js +26 -20
- package/dist/installState.d.ts +4 -4
- package/dist/installState.js +28 -27
- package/dist/outbox.d.ts +11 -9
- package/dist/outbox.js +45 -27
- package/dist/page.d.ts +1 -1
- package/dist/page.js +8 -6
- package/dist/pagePath.js +14 -14
- package/dist/queue.d.ts +6 -4
- package/dist/queue.js +26 -13
- package/dist/stateFields.d.ts +4 -4
- package/dist/stateFields.js +6 -4
- package/dist/testing.d.ts +8 -5
- package/dist/testing.js +27 -17
- package/dist/throttle.d.ts +30 -0
- package/dist/throttle.js +41 -0
- package/dist/transport.d.ts +10 -1
- package/dist/transport.js +35 -8
- package/dist/web.d.ts +4 -4
- package/dist/web.js +30 -17
- package/package.json +6 -4
package/README.md
CHANGED
|
@@ -53,13 +53,13 @@ One line per context makes its collector. `key`, `version`, `endpoint` and `unin
|
|
|
53
53
|
|
|
54
54
|
```ts
|
|
55
55
|
// a website or a web app
|
|
56
|
-
const analytics = newWebCollector({ key, version, endpoint, mode:
|
|
56
|
+
const analytics = newWebCollector({ key, version, endpoint, mode: "anonymous" });
|
|
57
57
|
// a Chrome extension: the service worker, at its top level, and each of its pages, such as the popup
|
|
58
|
-
const analytics = newExtensionCollector({ key, endpoint, mode:
|
|
58
|
+
const analytics = newExtensionCollector({ key, endpoint, mode: "anonymous", uninstallPage });
|
|
59
59
|
// a content script of that extension, which hands its events to the service worker
|
|
60
60
|
const analytics = newContentScriptCollector();
|
|
61
61
|
// a window of a desktop app, such as a Tauri webview, where `platform` is 'macos', 'windows' or 'linux'
|
|
62
|
-
const analytics = newDesktopCollector({ key, version, endpoint, platform, mode:
|
|
62
|
+
const analytics = newDesktopCollector({ key, version, endpoint, platform, mode: "anonymous" });
|
|
63
63
|
```
|
|
64
64
|
|
|
65
65
|
A channel of another mode passes it, and `getId` in the identified mode, such as `mode: 'identified', getId`. A site whose paths carry a secret or a person passes `getPage: () => ({ page: route.pattern, referrer: document.referrer })` to send the route pattern instead.
|
|
@@ -67,10 +67,10 @@ A channel of another mode passes it, and `getId` in the identified mode, such as
|
|
|
67
67
|
Then the product tracks what the user does, and sets the analytics state when the user picks one, here in a pseudonymous channel:
|
|
68
68
|
|
|
69
69
|
```ts
|
|
70
|
-
const analytics = newWebCollector({ key, version, endpoint, mode:
|
|
71
|
-
void analytics.track(
|
|
72
|
-
void analytics.setState(consented ?
|
|
73
|
-
void analytics.setState(
|
|
70
|
+
const analytics = newWebCollector({ key, version, endpoint, mode: "pseudonymous" });
|
|
71
|
+
void analytics.track("report_exported", { format: "pdf", pages: 12, with_images: true });
|
|
72
|
+
void analytics.setState(consented ? "pseudonymous" : "anonymous");
|
|
73
|
+
void analytics.setState("opted_out"); // the user turned analytics off
|
|
74
74
|
```
|
|
75
75
|
|
|
76
76
|
The collectors do the rest themselves:
|
|
@@ -110,7 +110,7 @@ Each constructor throws a `TypeError` that names the option when the options wou
|
|
|
110
110
|
- An extension channel without a Chrome Web Store id takes no live request.
|
|
111
111
|
- 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`.
|
|
112
112
|
- `mode`: `'anonymous'`, `'pseudonymous'` or `'identified'`, as "Modes and states" describes. `Mode.Anonymous`, `Mode.Pseudonymous` and `Mode.Identified` name the same values. Another value, which only untyped code can pass, works as `'anonymous'`.
|
|
113
|
-
- `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. It posts a forget request the same way to the endpoint
|
|
113
|
+
- `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. It posts a forget request the same way to the endpoint with `forget` in place of the path's last segment, `relay`, so to `/v1/public/forget`. A slash after `relay` goes with it, and the endpoint's query stays, as on the envelopes' address. 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`.
|
|
114
114
|
- `transport`, in place of `endpoint`: a function that delivers a request 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`. The collector also hands the transport each forget request, a body `{"key":…,"id":…}` with no `events`, which goes to the intake's `/v1/public/forget`, and reads its answer the same way. A transport written for 0.3.0 posts every body to the relay, so it must now post a body without `events` to `/v1/public/forget`.
|
|
115
115
|
- `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.
|
|
116
116
|
- `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.
|
|
@@ -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;
|
|
@@ -147,7 +147,7 @@ Each constructor throws a `TypeError` that names the option when the options wou
|
|
|
147
147
|
|
|
148
148
|
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.
|
|
149
149
|
|
|
150
|
-
- `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:
|
|
150
|
+
- `track(name, params?, { throttleMs }?)` 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:
|
|
151
151
|
|
|
152
152
|
| Event | Params |
|
|
153
153
|
| ----------------------------- | --------------------------------------------------------------------------------------------- |
|
|
@@ -157,7 +157,9 @@ Every method returns a promise that resolves and never rejects. A failure goes t
|
|
|
157
157
|
|
|
158
158
|
The intake keeps `welcome_opened` and `uninstalled` without an id at most once an hour per source, and drops the rest.
|
|
159
159
|
|
|
160
|
-
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,
|
|
160
|
+
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, are refused, and the report names them as params that could not be read. 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.
|
|
161
|
+
|
|
162
|
+
`track(name, params?, { throttleMs })` takes a throttle for one intent that fires in a quick burst, such as key autorepeat on a held arrow that moves a slider, or a held undo key. The throttle is leading-edge. The first call of a name with `throttleMs` goes as usual. A later call of the same name with `throttleMs` is dropped while less than its `throttleMs` milliseconds have passed since the last call of that name with `throttleMs` that went. A call without `throttleMs`, a forwarded event of a content script included, opens no window and is never dropped. The window belongs to the event name alone, not to its params. The collector keeps it in its own memory, so each collector, each page and each content script keeps its own, and a restart starts it again. A dropped call is the caller's intent, so it reaches no `onError`. Only a call with `throttleMs` whose event the collector records opens a window: a refused event and an event in the `opted_out` state do not. A content script does not know the state, so there a call with `throttleMs` opens a window when its event passes the worker's check, in any state, as `newContentScriptCollector()` describes. A `throttleMs` that is not a finite number from 0 refuses the event and reports it to `onError`. A `throttleMs` of 0 drops nothing.
|
|
161
163
|
|
|
162
164
|
- `installed()` sends `installed` once per install. A later call sends no event. The extension's service worker and `newDesktopCollector` call it and `updated()` themselves, and a website calls it where its product counts an install. In the `opted_out` state it sends nothing and marks nothing, so a user who turns analytics back on still sends it.
|
|
163
165
|
- `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.
|
|
@@ -168,7 +170,7 @@ Every method returns a promise that resolves and never rejects. A failure goes t
|
|
|
168
170
|
- `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, a stored state above the channel's mode becomes `anonymous`, as `setState('anonymous')` would make it, as after the admin lowered the mode.
|
|
169
171
|
- `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. The collector sends within `sendDelaySeconds` without it, as "Sending" describes, so `flush()` is only for a product that wants to send sooner.
|
|
170
172
|
- `forget(id)` drops the queued events of this id and asks the intake to delete the id's events, with `{ key, id }` to its `/v1/public/forget`. The product calls it for an account id the collector does not hold, such as one `getId` no longer gives. Leaving a state with an id does the same for the last id by itself. An `id` that is not a string of 1 to 64 characters, which the intake refuses, is reported and 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. The collector stores the request until the intake answers it, and sends it after this collector's request in flight, which may carry the id, and before the queued envelopes. It resolves once that send ends. A forget answered 0, 429 or 5xx goes again under the wait rules of "Sending", and any other status outside 2xx drops it and reports it. The intake checks the request's `Origin` as it checks a relay request. With a test key the collector forgets the id and drops its events here but sends no request and reports nothing: the intake answers a test key's forget 403, since it would delete the user's live events too, and test events go when the channel's test data is cleared. The collector stores only the ids of its forget requests, and sends each with its own key. It drops a stored id that is not 1 to 64 characters unsent. The intake deletes the id's events in every channel of the product within a minute, and those that arrive up to a minute after the forget. A request another context sent arrives within its 30-second limit.
|
|
171
|
-
- `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`. The uninstall page that `uninstallPage` sets carries the values of its last refresh
|
|
173
|
+
- `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`. The uninstall page that `uninstallPage` sets carries the values of its last refresh. The extension's collector refreshes it after it queues the first event of a local day, such as `installed` on the install day, so `active_days` includes that day. 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.
|
|
172
174
|
|
|
173
175
|
### Other exports
|
|
174
176
|
|
|
@@ -180,7 +182,7 @@ The main module also exports the checks of "Testing", `newHttpTransport(endpoint
|
|
|
180
182
|
|
|
181
183
|
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.
|
|
182
184
|
|
|
183
|
-
The queue lives in storage, so every event outlives the page that recorded it. A page or a window that closes within the send delay after its last events leaves them queued.
|
|
185
|
+
The queue lives in storage, so every event outlives the page that recorded it. A page or a window that closes within the send delay after its last events leaves them queued. A later visit or launch sends them. A collector that finds events or forget requests stored when it is built sends them within the send delay, or after any retry wait, without waiting for a call. In the `opted_out` state it drops the stored events but a queued `opted_out`, and sends that and the forget requests. The collector does not send when a page is hidden: a send reads the storage and takes the lock before its request, and a closing page is gone by then. In an extension, the service worker sends what its pages queue, even after a page closed. It listens to `chrome.storage.onChanged` for the channel's queue and sends within the send delay of the page's write. A page still sends on its own as well, and the leases keep an envelope from going twice.
|
|
184
186
|
|
|
185
187
|
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.
|
|
186
188
|
|
|
@@ -219,9 +221,9 @@ For a website or a web app. The desktop module builds on its storage and lock.
|
|
|
219
221
|
A site sets up page views in two lines:
|
|
220
222
|
|
|
221
223
|
```ts
|
|
222
|
-
import { newWebCollector, trackPageViews } from
|
|
224
|
+
import { newWebCollector, trackPageViews } from "@kk-forge/artel-collector/web";
|
|
223
225
|
|
|
224
|
-
const analytics = newWebCollector({ key, version, endpoint, mode:
|
|
226
|
+
const analytics = newWebCollector({ key, version, endpoint, mode: "anonymous" });
|
|
225
227
|
trackPageViews(analytics);
|
|
226
228
|
```
|
|
227
229
|
|
|
@@ -231,28 +233,28 @@ For a Chrome extension. Its service worker and its pages each make a collector w
|
|
|
231
233
|
|
|
232
234
|
- `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.
|
|
233
235
|
- `newChromeStorageAdapter()` returns a `storage` over `chrome.storage.local`.
|
|
234
|
-
- `newContentScriptCollector()` returns the collector of a content script, typed `ContentScriptCollector`: `track` only. Its `track`
|
|
236
|
+
- `newContentScriptCollector()` returns the collector of a content script, typed `ContentScriptCollector`: `track` only. Its `track` hands the event to `forwardTrack`, so the worker's collector checks, queues and sends the event under the user's analytics state. It applies a call's `throttleMs` in the content script's own memory before it forwards the event. A call with `throttleMs` opens a window when its event passes the worker's check, in any analytics state, since only the worker knows the state. It drops a call with a bad `throttleMs` without a report, since it has no `onError`. `newContentScriptCollector({ clock })` takes the clock of those windows, the system's by default. The state 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.
|
|
235
237
|
- `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.
|
|
236
238
|
- The service worker's collector tracks the events content scripts forward. 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, a guard against a flood, and drops the rest. It reports the first event it drops in a minute to `onError`. It keeps the count in memory, so a restart of the worker starts it again.
|
|
237
239
|
- The service worker's collector sends `installed` at Chrome's `onInstalled` with reason `install`, and `updated` with reason `update`. It also adds an empty `onStartup` listener, so Chrome starts the worker with the browser and the worker closes the storage again before content scripts run. Chrome needs these listeners registered synchronously at the worker's top level on every start of the worker, so build the collector there. A product may add `onInstalled` listeners of its own, such as one that opens a welcome page.
|
|
238
|
-
- `uninstallPage`, an option of `newExtensionCollector`: the address Chrome opens when the user removes the extension. The collector sets it with the fields of `uninstallParams()` added to its query, or alone when `uninstallParams()` resolves to `undefined
|
|
240
|
+
- `uninstallPage`, an option of `newExtensionCollector`: the address Chrome opens when the user removes the extension. The collector sets it with the fields of `uninstallParams()` added to the end of its query, before any `#` fragment, or alone when `uninstallParams()` resolves to `undefined`. The address's own query stays as written, and a name it shares with a field appears twice. The collector sets the page at construction, after each `setState` and after it queues the first event of a local day. It does so in the worker and in each page, since Chrome keeps the address as it was set. Before a change to `anonymous` or `opted_out` it sets the page alone, so the earlier state's fields are gone while the change runs. A write that began before the latest `setState` is dropped. Left out, the collector sets no uninstall page.
|
|
239
241
|
|
|
240
242
|
```ts
|
|
241
243
|
// service worker
|
|
242
|
-
import { newExtensionCollector } from
|
|
244
|
+
import { newExtensionCollector } from "@kk-forge/artel-collector/extension";
|
|
243
245
|
|
|
244
246
|
const analytics = newExtensionCollector({
|
|
245
247
|
key,
|
|
246
248
|
endpoint,
|
|
247
|
-
mode:
|
|
248
|
-
uninstallPage:
|
|
249
|
+
mode: "anonymous",
|
|
250
|
+
uninstallPage: "https://example.com/uninstall",
|
|
249
251
|
});
|
|
250
252
|
|
|
251
253
|
// content script
|
|
252
|
-
import { newContentScriptCollector } from
|
|
254
|
+
import { newContentScriptCollector } from "@kk-forge/artel-collector/extension";
|
|
253
255
|
|
|
254
256
|
const analytics = newContentScriptCollector();
|
|
255
|
-
void analytics.track(
|
|
257
|
+
void analytics.track("link_shared", { target: "clipboard" });
|
|
256
258
|
```
|
|
257
259
|
|
|
258
260
|
### `@kk-forge/artel-collector/desktop`
|
|
@@ -323,14 +325,14 @@ The core reads no page, URL or user input. `params`, the account `id` and the pa
|
|
|
323
325
|
|
|
324
326
|
`@kk-forge/artel-collector/testing` serves a product's own tests:
|
|
325
327
|
|
|
326
|
-
- `newRecordingCollector(mode?, { onError }?)` 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. `uninstallParams()` resolves to `undefined`.
|
|
328
|
+
- `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`.
|
|
327
329
|
- `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.
|
|
328
330
|
|
|
329
331
|
The main module exports three checks that read no `chrome`, `navigator` or storage, so a build script or a test can call them:
|
|
330
332
|
|
|
331
333
|
- `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.
|
|
332
334
|
- `isTestKey(key)` tells whether `key` is a channel's test key, `<kind>-test-<10 characters>`.
|
|
333
|
-
- `checkEvent(name, params)` returns the problem `track` would report for the event, or `undefined` when it takes it.
|
|
335
|
+
- `checkEvent(name, params)` returns the problem `track` would report for the event, or `undefined` when it takes it. It never throws: for params whose reading throws, it returns `has params that could not be read`.
|
|
334
336
|
|
|
335
337
|
## Development
|
|
336
338
|
|
package/dist/browser.d.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
/** The browsers the intake tells apart. Any other browser is `other`. */
|
|
2
2
|
export declare const BrowserName: {
|
|
3
|
-
readonly Chrome:
|
|
4
|
-
readonly Edge:
|
|
5
|
-
readonly Opera:
|
|
6
|
-
readonly Yandex:
|
|
7
|
-
readonly Brave:
|
|
8
|
-
readonly Firefox:
|
|
9
|
-
readonly Safari:
|
|
10
|
-
readonly Other:
|
|
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
11
|
};
|
|
12
12
|
export type BrowserName = (typeof BrowserName)[keyof typeof BrowserName];
|
|
13
13
|
type VersionedBrowserName = Exclude<BrowserName, typeof BrowserName.Other>;
|
package/dist/browser.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
/** The browsers the intake tells apart. Any other browser is `other`. */
|
|
2
2
|
export const BrowserName = {
|
|
3
|
-
Chrome:
|
|
4
|
-
Edge:
|
|
5
|
-
Opera:
|
|
6
|
-
Yandex:
|
|
7
|
-
Brave:
|
|
8
|
-
Firefox:
|
|
9
|
-
Safari:
|
|
10
|
-
Other:
|
|
3
|
+
Chrome: "chrome",
|
|
4
|
+
Edge: "edge",
|
|
5
|
+
Opera: "opera",
|
|
6
|
+
Yandex: "yandex",
|
|
7
|
+
Brave: "brave",
|
|
8
|
+
Firefox: "firefox",
|
|
9
|
+
Safari: "safari",
|
|
10
|
+
Other: "other",
|
|
11
11
|
};
|
|
12
12
|
/**
|
|
13
13
|
* The brands of a Chromium browser, each browser's own ahead of Google Chrome. A browser that lists both goes by its
|
|
14
14
|
* own.
|
|
15
15
|
*/
|
|
16
16
|
const BRANDS = [
|
|
17
|
-
[
|
|
18
|
-
[
|
|
19
|
-
[
|
|
20
|
-
[
|
|
21
|
-
[
|
|
17
|
+
["Microsoft Edge", BrowserName.Edge],
|
|
18
|
+
["Opera", BrowserName.Opera],
|
|
19
|
+
["YaBrowser", BrowserName.Yandex],
|
|
20
|
+
["Brave", BrowserName.Brave],
|
|
21
|
+
["Google Chrome", BrowserName.Chrome],
|
|
22
22
|
];
|
|
23
23
|
/**
|
|
24
24
|
* User-Agent tokens of the browsers that name themselves there. Chrome goes by its brands: every Chromium browser's
|
|
@@ -43,11 +43,11 @@ export function detectBrowser(nav) {
|
|
|
43
43
|
}
|
|
44
44
|
// This check names a Chromium browser with no brand of its own `other`, and skips its User-Agent string. Such a
|
|
45
45
|
// browser copies Chrome's User-Agent string, so that string names no browser.
|
|
46
|
-
const chromiumBrands = new Set([
|
|
46
|
+
const chromiumBrands = new Set(["Chromium", ...BRANDS.map(([brand]) => brand)]);
|
|
47
47
|
if (nav.userAgentData?.brands?.some((entry) => chromiumBrands.has(entry.brand)) === true) {
|
|
48
48
|
return { name: BrowserName.Other };
|
|
49
49
|
}
|
|
50
|
-
if (nav.userAgent === undefined || nav.userAgent ===
|
|
50
|
+
if (nav.userAgent === undefined || nav.userAgent === "") {
|
|
51
51
|
return undefined;
|
|
52
52
|
}
|
|
53
53
|
return fromUserAgent(nav.userAgent);
|
|
@@ -62,7 +62,9 @@ function fromUserAgent(userAgent) {
|
|
|
62
62
|
// The check names Safari only without a Chrome or Chromium token. A Chromium browser's User-Agent string carries
|
|
63
63
|
// Safari's tokens too. One regular expression per token keeps a long User-Agent string free of backtracking.
|
|
64
64
|
const version = /\bVersion\/(\d+)/.exec(userAgent)?.[1];
|
|
65
|
-
if (version !== undefined &&
|
|
65
|
+
if (version !== undefined &&
|
|
66
|
+
/\bSafari\//.test(userAgent) &&
|
|
67
|
+
!/\b(?:Chrome|Chromium)\//.test(userAgent)) {
|
|
66
68
|
return withMajor(BrowserName.Safari, version);
|
|
67
69
|
}
|
|
68
70
|
return { name: BrowserName.Other };
|
|
@@ -72,11 +74,11 @@ function fromUserAgent(userAgent) {
|
|
|
72
74
|
* 1 to 999 left out. Returns undefined for a value that is not an object, which only a host outside TypeScript passes.
|
|
73
75
|
*/
|
|
74
76
|
export function copyBrowser(value) {
|
|
75
|
-
if (typeof value !==
|
|
77
|
+
if (typeof value !== "object" || value === null) {
|
|
76
78
|
return undefined;
|
|
77
79
|
}
|
|
78
|
-
const name = Reflect.get(value,
|
|
79
|
-
const major = Reflect.get(value,
|
|
80
|
+
const name = Reflect.get(value, "name");
|
|
81
|
+
const major = Reflect.get(value, "major");
|
|
80
82
|
const known = Object.values(BrowserName).find((candidate) => candidate === name && candidate !== BrowserName.Other);
|
|
81
83
|
if (known === undefined) {
|
|
82
84
|
return { name: BrowserName.Other };
|
|
@@ -90,10 +92,10 @@ function withMajor(name, version) {
|
|
|
90
92
|
}
|
|
91
93
|
/** Returns the major version, or undefined when the string has none from 1 to 999, the range the intake takes. */
|
|
92
94
|
function majorOf(version) {
|
|
93
|
-
const major = Number.parseInt(version ??
|
|
95
|
+
const major = Number.parseInt(version ?? "", 10);
|
|
94
96
|
return isMajor(major) ? major : undefined;
|
|
95
97
|
}
|
|
96
98
|
/** Checks for a whole number from 1 to 999, the range the intake takes. */
|
|
97
99
|
function isMajor(value) {
|
|
98
|
-
return typeof value ===
|
|
100
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 999;
|
|
99
101
|
}
|
package/dist/calendar.d.ts
CHANGED
|
@@ -6,11 +6,11 @@ export interface CalendarDate {
|
|
|
6
6
|
}
|
|
7
7
|
/** The periods an event can be the first of, in the order the intake lists them. */
|
|
8
8
|
export declare const Period: {
|
|
9
|
-
readonly Day:
|
|
10
|
-
readonly Week:
|
|
11
|
-
readonly Month:
|
|
12
|
-
readonly Quarter:
|
|
13
|
-
readonly Year:
|
|
9
|
+
readonly Day: "day";
|
|
10
|
+
readonly Week: "week";
|
|
11
|
+
readonly Month: "month";
|
|
12
|
+
readonly Quarter: "quarter";
|
|
13
|
+
readonly Year: "year";
|
|
14
14
|
};
|
|
15
15
|
export type Period = (typeof Period)[keyof typeof Period];
|
|
16
16
|
/**
|
package/dist/calendar.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/** The periods an event can be the first of, in the order the intake lists them. */
|
|
2
2
|
export const Period = {
|
|
3
|
-
Day:
|
|
4
|
-
Week:
|
|
5
|
-
Month:
|
|
6
|
-
Quarter:
|
|
7
|
-
Year:
|
|
3
|
+
Day: "day",
|
|
4
|
+
Week: "week",
|
|
5
|
+
Month: "month",
|
|
6
|
+
Quarter: "quarter",
|
|
7
|
+
Year: "year",
|
|
8
8
|
};
|
|
9
9
|
const DAY_MS = 86_400_000;
|
|
10
10
|
/**
|
|
@@ -26,7 +26,7 @@ export function formatDay(date) {
|
|
|
26
26
|
}
|
|
27
27
|
/** Parses a `YYYY-MM-DD` day, or returns undefined when the text is missing or has another form. */
|
|
28
28
|
export function parseDay(text) {
|
|
29
|
-
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text ??
|
|
29
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text ?? "");
|
|
30
30
|
if (!match) {
|
|
31
31
|
return undefined;
|
|
32
32
|
}
|
|
@@ -71,5 +71,5 @@ function utcMidnight(date) {
|
|
|
71
71
|
return Date.UTC(date.year, date.month - 1, date.day);
|
|
72
72
|
}
|
|
73
73
|
function pad(value) {
|
|
74
|
-
return String(value).padStart(2,
|
|
74
|
+
return String(value).padStart(2, "0");
|
|
75
75
|
}
|
package/dist/clock.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
export type TimerHandle = ReturnType<typeof setTimeout>;
|
|
2
1
|
/**
|
|
3
2
|
* 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.
|
|
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
5
|
*/
|
|
6
6
|
export interface Clock {
|
|
7
7
|
/** Returns milliseconds since the epoch. */
|
|
8
8
|
now(): number;
|
|
9
|
-
|
|
10
|
-
|
|
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
11
|
}
|
|
12
12
|
export declare const systemClock: Clock;
|
package/dist/clock.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export const systemClock = {
|
|
2
2
|
now: () => Date.now(),
|
|
3
|
-
setTimeout: (callback, delayMs) =>
|
|
4
|
-
|
|
3
|
+
setTimeout: (callback, delayMs) => {
|
|
4
|
+
const handle = setTimeout(callback, delayMs);
|
|
5
|
+
return () => clearTimeout(handle);
|
|
6
|
+
},
|
|
5
7
|
};
|
package/dist/collector.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Mode, type Collector, type CollectorOptions } from
|
|
1
|
+
import { Mode, type Collector, type CollectorOptions } from "./collectorTypes.js";
|
|
2
2
|
/**
|
|
3
3
|
* Returns a collector. Throws a `TypeError` that names the option for options that would make the intake refuse every
|
|
4
4
|
* envelope, such as a bad key, version or endpoint, and for options only a host outside TypeScript passes. A language
|
|
@@ -7,5 +7,10 @@ import { Mode, type Collector, type CollectorOptions } from './collectorTypes.js
|
|
|
7
7
|
export declare function newCollector<M extends Mode>(options: CollectorOptions & {
|
|
8
8
|
mode: M;
|
|
9
9
|
}): Collector<M>;
|
|
10
|
+
/**
|
|
11
|
+
* Returns a collector, as `newCollector` does, that calls `onNewDay` inside its lock each time it queues the first
|
|
12
|
+
* event of a local day. That event adds the day to the active days.
|
|
13
|
+
*/
|
|
14
|
+
export declare function newCollectorNotingDays(options: CollectorOptions, onNewDay: () => void): Collector;
|
|
10
15
|
/** Returns the longest an event waits in the queue before a send starts, as the options set it. */
|
|
11
|
-
export declare function sendDelayMsOf({ sendDelaySeconds }: Pick<CollectorOptions,
|
|
16
|
+
export declare function sendDelayMsOf({ sendDelaySeconds, }: Pick<CollectorOptions, "sendDelaySeconds">): number;
|
package/dist/collector.js
CHANGED
|
@@ -1,20 +1,28 @@
|
|
|
1
|
-
import { daysBetween, formatDay, localDateAt } from
|
|
2
|
-
import { LifecycleEvent, UNINSTALLED } from
|
|
3
|
-
import { activeDaysBucket, ageInDays, isLanguage, languageTag, newEvent, uninstalledParams } from
|
|
4
|
-
import { accepted, checkedBuild, isUsableId, newBrowserReader, newStringStorage, quoted, reportTo, usableId, } from
|
|
5
|
-
import { systemClock } from
|
|
6
|
-
import { newChannelStorage } from
|
|
7
|
-
import { AnalyticsState, Mode } from
|
|
8
|
-
import { acceptedEvent } from
|
|
9
|
-
import { newInstallState } from
|
|
10
|
-
import { exclusive } from
|
|
11
|
-
import { newOutbox } from
|
|
12
|
-
import { newPageReader } from
|
|
13
|
-
import { carriesPage, channelTakes, fieldsForState, isAnalyticsState } from
|
|
14
|
-
import {
|
|
1
|
+
import { daysBetween, formatDay, localDateAt, Period } from "./calendar.js";
|
|
2
|
+
import { LifecycleEvent, UNINSTALLED } from "./envelope.js";
|
|
3
|
+
import { activeDaysBucket, ageInDays, isLanguage, languageTag, newEvent, uninstalledParams, } from "./fields.js";
|
|
4
|
+
import { accepted, checkedBuild, isUsableId, newBrowserReader, newStringStorage, quoted, reportTo, usableId, } from "./hostInput.js";
|
|
5
|
+
import { systemClock } from "./clock.js";
|
|
6
|
+
import { newChannelStorage } from "./storage.js";
|
|
7
|
+
import { AnalyticsState, Mode } from "./collectorTypes.js";
|
|
8
|
+
import { acceptedEvent } from "./eventCheck.js";
|
|
9
|
+
import { newInstallState } from "./installState.js";
|
|
10
|
+
import { exclusive } from "./lock.js";
|
|
11
|
+
import { newOutbox } from "./outbox.js";
|
|
12
|
+
import { newPageReader } from "./page.js";
|
|
13
|
+
import { carriesPage, channelTakes, fieldsForState, isAnalyticsState, } from "./stateFields.js";
|
|
14
|
+
import { newThrottle } from "./throttle.js";
|
|
15
|
+
import { transportsOf } from "./transport.js";
|
|
15
16
|
const SESSION_IDLE_MINUTES = 10;
|
|
16
17
|
const SEND_DELAY_SECONDS = 5;
|
|
17
18
|
export function newCollector(options) {
|
|
19
|
+
return newCollectorNotingDays(options, () => undefined);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Returns a collector, as `newCollector` does, that calls `onNewDay` inside its lock each time it queues the first
|
|
23
|
+
* event of a local day. That event adds the day to the active days.
|
|
24
|
+
*/
|
|
25
|
+
export function newCollectorNotingDays(options, onNewDay) {
|
|
18
26
|
const product = checkedBuild(options);
|
|
19
27
|
const { mode } = options;
|
|
20
28
|
const transports = transportsOf(options);
|
|
@@ -24,8 +32,8 @@ export function newCollector(options) {
|
|
|
24
32
|
const lock = exclusive(options.lock);
|
|
25
33
|
const getId = options.mode === Mode.Identified ? usableId(options.getId, reportError) : undefined;
|
|
26
34
|
const readBrowser = options.mode === Mode.Anonymous ? undefined : newBrowserReader(options.browser, reportError);
|
|
27
|
-
const browserLanguage = accepted(
|
|
28
|
-
const uiLanguage = accepted(
|
|
35
|
+
const browserLanguage = accepted("browserLanguage", languageTag(options.browserLanguage), isLanguage, reportError);
|
|
36
|
+
const uiLanguage = accepted("uiLanguage", languageTag(options.uiLanguage), isLanguage, reportError);
|
|
29
37
|
const install = newInstallState({
|
|
30
38
|
storage,
|
|
31
39
|
sessionIdleMs: durationOr(options.sessionIdleMinutes, SESSION_IDLE_MINUTES) * 60_000,
|
|
@@ -49,23 +57,31 @@ export function newCollector(options) {
|
|
|
49
57
|
? newPageReader({ getPage: options.getPage, reportError })
|
|
50
58
|
: undefined;
|
|
51
59
|
const pageOf = (name) => pages?.read(name);
|
|
60
|
+
const throttle = newThrottle();
|
|
52
61
|
// The install day is the local date of the first call of any method, so it waits on no particular event.
|
|
53
62
|
let isInstallDayKnown = false;
|
|
63
|
+
/**
|
|
64
|
+
* Stores the install day, settles the stored state and schedules the first send, once per collector. The caller
|
|
65
|
+
* holds the lock.
|
|
66
|
+
*/
|
|
67
|
+
async function startOnce() {
|
|
68
|
+
if (isInstallDayKnown) {
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
await install.installDayOr(localDateAt(clock.now()));
|
|
72
|
+
await settleStoredState();
|
|
73
|
+
isInstallDayKnown = true;
|
|
74
|
+
// The first send carries what an earlier run of the host left queued. A run stopped mid-send holds a lease, and its
|
|
75
|
+
// events go with the first send after the lease runs out.
|
|
76
|
+
outbox.sendSoon();
|
|
77
|
+
}
|
|
54
78
|
function serialize(operation, fallback) {
|
|
55
|
-
const withInstallDay = async () => {
|
|
56
|
-
if (!isInstallDayKnown) {
|
|
57
|
-
await install.installDayOr(localDateAt(clock.now()));
|
|
58
|
-
await settleStoredState();
|
|
59
|
-
isInstallDayKnown = true;
|
|
60
|
-
// The first send carries what an earlier run of the host left queued. A run stopped mid-send holds a lease, and
|
|
61
|
-
// its events go with the first send after the lease runs out.
|
|
62
|
-
outbox.sendSoon();
|
|
63
|
-
}
|
|
64
|
-
return operation();
|
|
65
|
-
};
|
|
66
79
|
// Each operation reads and writes several storage keys. The lock keeps two events from both taking the same
|
|
67
80
|
// first-of-day mark.
|
|
68
|
-
return lock(
|
|
81
|
+
return lock(async () => {
|
|
82
|
+
await startOnce();
|
|
83
|
+
return operation();
|
|
84
|
+
}).catch((error) => {
|
|
69
85
|
reportError(error);
|
|
70
86
|
return fallback;
|
|
71
87
|
});
|
|
@@ -120,7 +136,7 @@ export function newCollector(options) {
|
|
|
120
136
|
// The install id goes before the last id. A run that stops between them then keeps the last id, and the next run
|
|
121
137
|
// leaves it again.
|
|
122
138
|
await install.dropInstallId();
|
|
123
|
-
await install.setLastId(
|
|
139
|
+
await install.setLastId("");
|
|
124
140
|
}
|
|
125
141
|
/**
|
|
126
142
|
* Stores `next` and leaves the id of `previous`, and resolves to whether `previous` had one. A change between the two
|
|
@@ -200,8 +216,10 @@ export function newCollector(options) {
|
|
|
200
216
|
}
|
|
201
217
|
let event;
|
|
202
218
|
let dropped;
|
|
219
|
+
let isNewDay = false;
|
|
203
220
|
try {
|
|
204
221
|
const stamp = await install.stamp(clock.now());
|
|
222
|
+
isNewDay = stamp.first.includes(Period.Day);
|
|
205
223
|
event = newEvent({
|
|
206
224
|
name,
|
|
207
225
|
// The `uninstalled` age gets the precision of the envelope's ages, so a state that sends no exact age does not
|
|
@@ -224,11 +242,17 @@ export function newCollector(options) {
|
|
|
224
242
|
// A failure before the queue holds the event loses it. Its marks go back, so the next event takes them and the
|
|
225
243
|
// day still counts. A failed stamp gave back its own first-of-period marks.
|
|
226
244
|
await install.giveBack([
|
|
227
|
-
{
|
|
245
|
+
{
|
|
246
|
+
version: productVersion,
|
|
247
|
+
events: [event ?? { name, day: formatDay(localDateAt(clock.now())) }],
|
|
248
|
+
},
|
|
228
249
|
]);
|
|
229
250
|
throw error;
|
|
230
251
|
}
|
|
231
252
|
view?.recorded();
|
|
253
|
+
if (isNewDay) {
|
|
254
|
+
onNewDay();
|
|
255
|
+
}
|
|
232
256
|
// The queue holds the event by now, so a failure here keeps its marks.
|
|
233
257
|
await giveBack(dropped);
|
|
234
258
|
return true;
|
|
@@ -249,14 +273,38 @@ export function newCollector(options) {
|
|
|
249
273
|
await serialize(async () => undefined, undefined);
|
|
250
274
|
await outbox.send();
|
|
251
275
|
}
|
|
276
|
+
/**
|
|
277
|
+
* Schedules a send at construction when the storage holds requests, such as the events of a page or a window that
|
|
278
|
+
* closed before its send. It runs `startOnce`, which settles the stored state before it schedules the send.
|
|
279
|
+
*/
|
|
280
|
+
async function sendWhatIsLeft() {
|
|
281
|
+
await lock(async () => {
|
|
282
|
+
// A storage that fails here fails the next call too, and that call reports it once.
|
|
283
|
+
if (await outbox.holdsRequests().catch(() => false)) {
|
|
284
|
+
await startOnce();
|
|
285
|
+
}
|
|
286
|
+
}).catch(reportError);
|
|
287
|
+
}
|
|
252
288
|
const collector = {
|
|
253
|
-
track: async (name, given) => {
|
|
254
|
-
const
|
|
289
|
+
track: async (name, given, trackOptions) => {
|
|
290
|
+
const calledAt = clock.now();
|
|
291
|
+
const event = acceptedEvent({ name, given, options: trackOptions, reportError });
|
|
255
292
|
if (event === undefined) {
|
|
256
293
|
return;
|
|
257
294
|
}
|
|
258
295
|
const page = pageOf(name);
|
|
259
|
-
await serialize(async () =>
|
|
296
|
+
await serialize(async () => {
|
|
297
|
+
// The check and the mark run in the lock, so of two calls in quick turn only the first goes.
|
|
298
|
+
const call = { name, throttleMs: event.throttleMs, now: calledAt };
|
|
299
|
+
if (throttle.isDropped(call)) {
|
|
300
|
+
return false;
|
|
301
|
+
}
|
|
302
|
+
const isRecorded = await record({ name, params: event.params, page });
|
|
303
|
+
if (isRecorded) {
|
|
304
|
+
throttle.went(call);
|
|
305
|
+
}
|
|
306
|
+
return isRecorded;
|
|
307
|
+
}, false);
|
|
260
308
|
},
|
|
261
309
|
// The opted_out state takes no install mark. A user who turns analytics back on still sends `installed`.
|
|
262
310
|
installed: async () => {
|
|
@@ -299,7 +347,7 @@ export function newCollector(options) {
|
|
|
299
347
|
forget: async (id) => {
|
|
300
348
|
// The intake refuses a forget of any other value, which no envelope carries as its id.
|
|
301
349
|
if (!isUsableId(id)) {
|
|
302
|
-
reportError(new TypeError(
|
|
350
|
+
reportError(new TypeError("artel: forget takes an id of 1 to 64 characters"));
|
|
303
351
|
return;
|
|
304
352
|
}
|
|
305
353
|
await serialize(async () => {
|
|
@@ -328,26 +376,14 @@ export function newCollector(options) {
|
|
|
328
376
|
};
|
|
329
377
|
}, undefined),
|
|
330
378
|
};
|
|
379
|
+
void sendWhatIsLeft();
|
|
331
380
|
return collector;
|
|
332
381
|
}
|
|
333
|
-
/**
|
|
334
|
-
* Returns the transport of the envelopes and that of the forget requests. The intake's forget address replaces the last
|
|
335
|
-
* segment of the relay path, `/v1/public/relay`. A product's own transport takes both kinds of request.
|
|
336
|
-
*/
|
|
337
|
-
function transportsOf(options) {
|
|
338
|
-
if (options.transport !== undefined) {
|
|
339
|
-
return { transport: options.transport, forgetTransport: options.transport };
|
|
340
|
-
}
|
|
341
|
-
return {
|
|
342
|
-
transport: newHttpTransport(options.endpoint),
|
|
343
|
-
forgetTransport: newHttpTransport(new URL('forget', options.endpoint).href),
|
|
344
|
-
};
|
|
345
|
-
}
|
|
346
382
|
/** Returns the longest an event waits in the queue before a send starts, as the options set it. */
|
|
347
|
-
export function sendDelayMsOf({ sendDelaySeconds }) {
|
|
383
|
+
export function sendDelayMsOf({ sendDelaySeconds, }) {
|
|
348
384
|
return durationOr(sendDelaySeconds, SEND_DELAY_SECONDS) * 1_000;
|
|
349
385
|
}
|
|
350
386
|
/** Returns `value`, or `fallback` for a duration that is no finite number from 0. */
|
|
351
387
|
function durationOr(value, fallback) {
|
|
352
|
-
return typeof value ===
|
|
388
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fallback;
|
|
353
389
|
}
|