@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.
@@ -0,0 +1,99 @@
1
+ /** The browsers the intake tells apart. Any other browser is `other`. */
2
+ export const BrowserName = {
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
+ };
12
+ /**
13
+ * The brands of a Chromium browser, each browser's own ahead of Google Chrome. A browser that lists both goes by its
14
+ * own.
15
+ */
16
+ const BRANDS = [
17
+ ['Microsoft Edge', BrowserName.Edge],
18
+ ['Opera', BrowserName.Opera],
19
+ ['YaBrowser', BrowserName.Yandex],
20
+ ['Brave', BrowserName.Brave],
21
+ ['Google Chrome', BrowserName.Chrome],
22
+ ];
23
+ /**
24
+ * User-Agent tokens of the browsers that name themselves there. Chrome goes by its brands: every Chromium browser's
25
+ * User-Agent has its token, so that token alone names no browser.
26
+ */
27
+ const USER_AGENT_TOKENS = [
28
+ [/\bEdg\/(\d+)/, BrowserName.Edge],
29
+ [/\bOPR\/(\d+)/, BrowserName.Opera],
30
+ [/\bYaBrowser\/(\d+)/, BrowserName.Yandex],
31
+ [/\bFirefox\/(\d+)/, BrowserName.Firefox],
32
+ ];
33
+ /**
34
+ * Names the browser from what `navigator` gives any site: the Client Hints brands of a Chromium browser, or else the
35
+ * User-Agent string. Returns undefined when it has neither, as outside a browser.
36
+ */
37
+ export function detectBrowser(nav) {
38
+ for (const [brand, name] of BRANDS) {
39
+ const entry = nav.userAgentData?.brands?.find((candidate) => candidate.brand === brand);
40
+ if (entry !== undefined) {
41
+ return withMajor(name, entry.version);
42
+ }
43
+ }
44
+ // This check names a Chromium browser with no brand of its own `other`, and skips its User-Agent string. Such a
45
+ // browser copies Chrome's User-Agent string, so that string names no browser.
46
+ const chromiumBrands = new Set(['Chromium', ...BRANDS.map(([brand]) => brand)]);
47
+ if (nav.userAgentData?.brands?.some((entry) => chromiumBrands.has(entry.brand)) === true) {
48
+ return { name: BrowserName.Other };
49
+ }
50
+ if (nav.userAgent === undefined || nav.userAgent === '') {
51
+ return undefined;
52
+ }
53
+ return fromUserAgent(nav.userAgent);
54
+ }
55
+ function fromUserAgent(userAgent) {
56
+ for (const [pattern, name] of USER_AGENT_TOKENS) {
57
+ const match = pattern.exec(userAgent);
58
+ if (match !== null) {
59
+ return withMajor(name, match[1]);
60
+ }
61
+ }
62
+ // The check names Safari only without a Chrome or Chromium token. A Chromium browser's User-Agent string carries
63
+ // Safari's tokens too. One regular expression per token keeps a long User-Agent string free of backtracking.
64
+ const version = /\bVersion\/(\d+)/.exec(userAgent)?.[1];
65
+ if (version !== undefined && /\bSafari\//.test(userAgent) && !/\b(?:Chrome|Chromium)\//.test(userAgent)) {
66
+ return withMajor(BrowserName.Safari, version);
67
+ }
68
+ return { name: BrowserName.Other };
69
+ }
70
+ /**
71
+ * Returns a fresh copy of a browser as the intake keeps it: a name off the list as `other`, and a major version outside
72
+ * 1 to 999 left out. Returns undefined for a value that is not an object, which only a host outside TypeScript passes.
73
+ */
74
+ export function copyBrowser(value) {
75
+ if (typeof value !== 'object' || value === null) {
76
+ return undefined;
77
+ }
78
+ const name = Reflect.get(value, 'name');
79
+ const major = Reflect.get(value, 'major');
80
+ const known = Object.values(BrowserName).find((candidate) => candidate === name && candidate !== BrowserName.Other);
81
+ if (known === undefined) {
82
+ return { name: BrowserName.Other };
83
+ }
84
+ return isMajor(major) ? { name: known, major } : { name: known };
85
+ }
86
+ /** Returns the browser with its major version, or without one outside 1 to 999, which the intake does not take. */
87
+ function withMajor(name, version) {
88
+ const major = majorOf(version);
89
+ return major === undefined ? { name } : { name, major };
90
+ }
91
+ /** Returns the major version, or undefined when the string has none from 1 to 999, the range the intake takes. */
92
+ function majorOf(version) {
93
+ const major = Number.parseInt(version ?? '', 10);
94
+ return isMajor(major) ? major : undefined;
95
+ }
96
+ /** Checks for a whole number from 1 to 999, the range the intake takes. */
97
+ function isMajor(value) {
98
+ return typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= 999;
99
+ }
@@ -1,82 +1,13 @@
1
- import { Platform, type EventParams } from './envelope.js';
2
- import { type Clock } from './clock.js';
3
- import type { Lock } from './lock.js';
4
- import type { StorageAdapter } from './storage.js';
5
- import type { Transport } from './transport.js';
6
- export interface CollectorOptions {
7
- /** The live channel key in the build for the store, the test key in any other build. */
8
- key: string;
9
- platform: Platform;
10
- /** Product version, up to 32 characters. */
11
- version: string;
12
- /** Interface language, such as `en` or `pt-BR`. */
13
- lang?: string | undefined;
14
- storage: StorageAdapter;
15
- /** How an envelope reaches the intake: `newHttpTransport(endpoint)`, or the product's own. */
16
- transport: Transport;
17
- /** The user's id in a `full` channel, once they consented. The collector never makes one up. */
18
- getId?: (() => string | undefined | Promise<string | undefined>) | undefined;
19
- /** Minutes without events that end a session, 10 by default. */
20
- sessionIdleMinutes?: number | undefined;
21
- /** The longest an event waits in the queue before a send starts, 5 seconds by default. */
22
- sendDelaySeconds?: number | undefined;
23
- /** Time and timers, the host's own by default. */
24
- clock?: Clock | undefined;
25
- /** The page an event happened on, for a site channel. The collector reads no page itself. */
26
- getPage?: (() => PageFields | undefined) | undefined;
27
- /**
28
- * Runs an operation while no other context that shares `storage` runs one. Without it, two contexts recording at once
29
- * may both mark the first event of a day, or both send one envelope.
30
- */
31
- lock?: Lock | undefined;
32
- /** Hears every failure the collector swallows, such as a dropped envelope or a storage error. */
33
- onError?: ((error: Error) => void) | undefined;
34
- }
35
- /** What a site channel's event says about its page. The intake keeps only the path and the referring host. */
36
- export interface PageFields {
37
- /** The page's path without the query string. */
38
- page?: string;
39
- /** The host of the referring page, when it is another site. */
40
- referrer?: string;
41
- }
42
- /** Bucket for the number of days with at least one event. */
43
- export declare const ActiveDaysBucket: {
44
- readonly None: '0';
45
- readonly One: '1';
46
- readonly TwoToFive: '2-5';
47
- readonly SixToTwenty: '6-20';
48
- readonly TwentyOneOrMore: '21+';
49
- };
50
- export type ActiveDaysBucket = (typeof ActiveDaysBucket)[keyof typeof ActiveDaysBucket];
51
- /** What an uninstall page gets in its query string. */
52
- export interface UninstallParams {
53
- platform: Platform;
54
- version: string;
55
- lang?: string;
56
- /** Days since install. */
57
- age: number;
58
- days: ActiveDaysBucket;
59
- }
60
- /** Every method resolves, never rejects: a failure goes to `onError` and nowhere else. */
61
- export interface Collector {
62
- track(name: string, params?: EventParams): Promise<void>;
63
- /** Sends `installed` once per install. Later calls do nothing. */
64
- installed(): Promise<void>;
65
- /** Sends `updated` when the version differs from the last one seen. Call it after `installed()`. */
66
- updated(): Promise<void>;
67
- /**
68
- * Off sends `usage_counts_off` at once and then nothing. On sends `usage_counts_on`. The collector stores the choice.
69
- */
70
- setEnabled(on: boolean): Promise<void>;
71
- isEnabled(): Promise<boolean>;
72
- /** Sends what is queued now. A page calls it when it is hidden, since the user may not come back. */
73
- flush(): Promise<void>;
74
- /**
75
- * Drops this id's queued events and resolves once this collector's request in progress ends. The host calls it after
76
- * `getId` stops returning the id, then asks the intake to forget the user. The intake keeps a forget for a minute,
77
- * and drops a request from another context, which arrives within 30 seconds.
78
- */
79
- forget(id: string): Promise<void>;
80
- uninstallParams(): Promise<UninstallParams>;
81
- }
1
+ import { Mode, type Collector, type CollectorOptions } from './collectorTypes.js';
2
+ /**
3
+ * Returns a collector. Throws a `TypeError` that names the option for options that would make the intake refuse every
4
+ * envelope, such as a bad key, version or endpoint, and for options only a host outside TypeScript passes. A language
5
+ * that breaks the intake's format is left out and goes to `onError`, since it often comes from the browser.
6
+ */
7
+ export declare function newCollector(options: CollectorOptions & {
8
+ mode: typeof Mode.Identified;
9
+ }): Collector<'identified'>;
10
+ export declare function newCollector(options: CollectorOptions & {
11
+ mode: typeof Mode.Anonymous;
12
+ }): Collector<'anonymous'>;
82
13
  export declare function newCollector(options: CollectorOptions): Collector;
package/dist/collector.js CHANGED
@@ -1,61 +1,75 @@
1
- import { Period, daysBetween, formatDay, localDateAt, monthsBetween } from './calendar.js';
2
- import { LifecycleEvent, Platform } from './envelope.js';
1
+ import { daysBetween, formatDay, localDateAt } 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, newBrowserReader, newStringStorage, quoted, reportTo, usableId } from './hostInput.js';
3
5
  import { systemClock } from './clock.js';
6
+ import { newChannelStorage } from './storage.js';
7
+ import { AnalyticsState, Mode } from './collectorTypes.js';
8
+ import { copyOfParams, eventProblem } from './eventCheck.js';
4
9
  import { newInstallState } from './installState.js';
10
+ import { exclusive } from './lock.js';
5
11
  import { newOutbox } from './outbox.js';
6
- /** Bucket for the number of days with at least one event. */
7
- export const ActiveDaysBucket = {
8
- None: '0',
9
- One: '1',
10
- TwoToFive: '2-5',
11
- SixToTwenty: '6-20',
12
- TwentyOneOrMore: '21+',
13
- };
12
+ import { newPageReader } from './page.js';
13
+ import { carriesPage, channelTakes, fieldsForState } from './stateFields.js';
14
+ import { newHttpTransport } from './transport.js';
14
15
  const SESSION_IDLE_MINUTES = 10;
15
16
  const SEND_DELAY_SECONDS = 5;
16
- /** The length of a page path the intake keeps. */
17
- const MAX_PAGE_LENGTH = 256;
18
- /** The length of a referring host the intake keeps. */
19
- const MAX_REFERRER_LENGTH = 128;
20
- const MAX_AGE_DAYS = 31;
21
- const MAX_AGE_MONTHS = 25;
22
17
  export function newCollector(options) {
23
- const { storage } = options;
18
+ const product = checkedBuild(options);
19
+ const { mode } = options;
20
+ const transport = options.transport ?? newHttpTransport(options.endpoint);
21
+ const storage = newChannelStorage(newStringStorage(options.storage), options.key);
24
22
  const clock = options.clock ?? systemClock;
25
- const reportError = (error) => {
26
- try {
27
- options.onError?.(toError(error));
28
- }
29
- catch {
30
- // The host's own handler failing must not reach the host either.
31
- }
32
- };
23
+ const reportError = (error) => reportTo(options.onError, error);
33
24
  const lock = exclusive(options.lock);
34
- /** Names the product build. Every envelope and the uninstall page carry these fields. */
35
- const product = {
36
- platform: options.platform,
37
- version: options.version,
38
- ...(options.lang !== undefined && { lang: options.lang }),
39
- };
25
+ const getId = options.mode === Mode.Identified ? usableId(options.getId, reportError) : undefined;
26
+ const readBrowser = options.mode === Mode.Identified ? newBrowserReader(options.browser, reportError) : undefined;
27
+ const browserLanguage = accepted('browserLanguage', languageTag(options.browserLanguage), isLanguage, reportError);
28
+ const uiLanguage = accepted('uiLanguage', languageTag(options.uiLanguage), isLanguage, reportError);
40
29
  const install = newInstallState({
41
30
  storage,
42
- sessionIdleMs: (options.sessionIdleMinutes ?? SESSION_IDLE_MINUTES) * 60_000,
31
+ sessionIdleMs: durationOr(options.sessionIdleMinutes, SESSION_IDLE_MINUTES) * 60_000,
43
32
  });
44
33
  const outbox = newOutbox({
45
34
  storage,
46
35
  lock,
47
- transport: options.transport,
48
- getId: options.getId,
49
- sendDelayMs: (options.sendDelaySeconds ?? SEND_DELAY_SECONDS) * 1_000,
36
+ transport,
37
+ identify: () => lock(async () => {
38
+ // The check names no user once the state has left identified. The state can change in this or another context
39
+ // after the lease.
40
+ if (!(await currentFields()).mayName) {
41
+ return undefined;
42
+ }
43
+ const id = await getId?.();
44
+ if (id === undefined) {
45
+ return undefined;
46
+ }
47
+ await noteId(id);
48
+ const browser = readBrowser?.();
49
+ return { id, ...(browser !== undefined && { browser }) };
50
+ }),
51
+ giveBack: (items) => giveBack(items),
52
+ sendDelayMs: durationOr(options.sendDelaySeconds, SEND_DELAY_SECONDS) * 1_000,
50
53
  clock,
51
54
  reportError,
52
55
  });
56
+ // The collector takes the page when a method is called, so a navigation before the event is recorded does not move
57
+ // it. Only platform web asks `getPage`.
58
+ const pages = carriesPage(product)
59
+ ? newPageReader({ getPage: options.getPage, reportError })
60
+ : undefined;
61
+ const pageOf = (name) => pages?.read(name);
53
62
  // The install day is the local date of the first call of any method, so it waits on no particular event.
54
63
  let isInstallDayKnown = false;
55
64
  function serialize(operation, fallback) {
56
65
  const withInstallDay = async () => {
57
66
  if (!isInstallDayKnown) {
58
67
  await install.installDayOr(localDateAt(clock.now()));
68
+ await dropStateTheChannelNoLongerTakes();
69
+ if ((await currentState()) === AnalyticsState.OptedOut) {
70
+ // A run stopped between storing the opted_out state and dropping the queue left events that must not go.
71
+ await discardForOptOut();
72
+ }
59
73
  isInstallDayKnown = true;
60
74
  // The first send carries what an earlier run of the host left queued. A run stopped mid-send holds a lease, and
61
75
  // its events go with the first send after the lease runs out.
@@ -70,121 +84,236 @@ export function newCollector(options) {
70
84
  return fallback;
71
85
  });
72
86
  }
73
- /** Records the event, unless the user switched usage counts off. */
74
- async function record(name, params) {
75
- if (!(await install.isEnabled())) {
87
+ /** Gives back the marks of the dropped envelopes. */
88
+ async function giveBack(items) {
89
+ await install.giveBack(items.map((item) => item.envelope));
90
+ }
91
+ /**
92
+ * Stores the id `getId` gave. An id other than the last one means another user: the events of the last one, and
93
+ * those that waited for an id after it, are dropped, so none goes under another user's id. The session ends, so no
94
+ * session holds the events of two users.
95
+ */
96
+ async function noteId(id) {
97
+ const last = await install.lastId();
98
+ if (last === id) {
76
99
  return;
77
100
  }
78
- const stamp = await install.stamp(clock.now());
79
- const id = await options.getId?.();
80
- await outbox.add({ key: options.key, ...product, session: stamp.session, ...(id !== undefined && { id }) }, newEvent({ name, params, stamp, page: options.getPage?.() }));
101
+ if (last !== undefined) {
102
+ await giveBack(await outbox.discardIdentified());
103
+ await install.endSession();
104
+ }
105
+ await install.setLastId(id);
106
+ }
107
+ /** Drops the queued events that name the user or wait for an id, and the last id with them. */
108
+ async function leaveIdentity() {
109
+ await giveBack(await outbox.discardIdentified());
110
+ await install.setLastId('');
111
+ }
112
+ /** Drops what was not sent, except an `opted_out`, and the last id with it. */
113
+ async function discardForOptOut() {
114
+ await giveBack(await outbox.discard());
115
+ await install.setLastId('');
116
+ }
117
+ /**
118
+ * Stores an identified state as anonymous when this channel is anonymous, as after the product changed its mode.
119
+ * Drops the queued events that name the user or wait for an id, which this channel can never send.
120
+ */
121
+ async function dropStateTheChannelNoLongerTakes() {
122
+ const stored = await install.state();
123
+ if (stored === AnalyticsState.Identified && !takes(stored)) {
124
+ await leaveIdentity();
125
+ await install.setState(AnalyticsState.Anonymous);
126
+ await install.endSession();
127
+ }
128
+ }
129
+ async function currentState() {
130
+ const stored = await install.state();
131
+ // The function reads an identified state this channel does not take as anonymous. Such a state stays after the
132
+ // product changes its mode.
133
+ return takes(stored) ? stored : AnalyticsState.Anonymous;
134
+ }
135
+ function takes(state) {
136
+ return channelTakes(mode, state);
137
+ }
138
+ /** Resolves to what the current state, or `state`, sends. */
139
+ async function currentFields(state) {
140
+ return fieldsIn(state ?? (await currentState()));
141
+ }
142
+ function fieldsIn(state) {
143
+ return fieldsForState({ state, build: product, browserLanguage, uiLanguage });
144
+ }
145
+ /**
146
+ * Queues the event for the current state, and resolves to whether it did. Does nothing in the opted_out state, or
147
+ * when `takeMark` finds its install or version mark taken.
148
+ */
149
+ async function record({ name, params, page, takeMark, }) {
150
+ const fields = await currentFields();
151
+ if (!fields.recordsEvents) {
152
+ return false;
153
+ }
154
+ const view = page === undefined ? undefined : pages?.view(page);
155
+ // A second `page_view` of the same page in a row, as from two trackers or a change of the query, sends nothing.
156
+ if (view?.isRepeatedView === true) {
157
+ return false;
158
+ }
159
+ // The identified state names the user once the product knows the id. Another user's id gives back the marks of the
160
+ // last user's dropped events, the install and version marks included, before this event takes its own.
161
+ const id = fields.mayName ? await getId?.() : undefined;
162
+ if (id !== undefined) {
163
+ await noteId(id);
164
+ }
165
+ const productVersion = fields.product.version;
166
+ // A `takeMark` that fails took no mark, so nothing goes back.
167
+ if (takeMark !== undefined && !(await takeMark(productVersion))) {
168
+ return false;
169
+ }
170
+ let event;
171
+ let dropped;
172
+ try {
173
+ const stamp = await install.stamp(clock.now());
174
+ event = newEvent({
175
+ name,
176
+ // The `uninstalled` age gets the precision of the envelope's ages, so a state that sends no exact age does not
177
+ // send one here.
178
+ params: name === UNINSTALLED ? uninstalledParams(params, { isExact: fields.isAgeExact }) : params,
179
+ stamp,
180
+ page: fields.mayCarryPage ? view?.fields : undefined,
181
+ isAgeExact: fields.isAgeExact,
182
+ });
183
+ const browser = id === undefined ? undefined : readBrowser?.();
184
+ dropped = await outbox.add({
185
+ key: options.key,
186
+ ...fields.product,
187
+ ...(browser !== undefined && { browser }),
188
+ session: stamp.session,
189
+ ...(id !== undefined && { id }),
190
+ }, event, { awaitsId: fields.mayName && id === undefined });
191
+ }
192
+ catch (error) {
193
+ // A failure before the queue holds the event loses it. Its marks go back, so the next event takes them and the
194
+ // day still counts. A failed stamp gave back its own first-of-period marks.
195
+ await install.giveBack([
196
+ { version: productVersion, events: [event ?? { name, day: formatDay(localDateAt(clock.now())) }] },
197
+ ]);
198
+ throw error;
199
+ }
200
+ view?.recorded();
201
+ // The queue holds the event by now, so a failure here keeps its marks.
202
+ await giveBack(dropped);
203
+ return true;
204
+ }
205
+ /**
206
+ * Queues one `opted_out` with no id, no browser, no first-of-period mark and no age, so that no count of active users
207
+ * takes it.
208
+ */
209
+ async function recordOptOut() {
210
+ await install.endSession();
211
+ const fields = await currentFields(AnalyticsState.OptedOut);
212
+ const session = await install.session(clock.now());
213
+ const dropped = await outbox.add({ key: options.key, ...fields.product, session }, { name: LifecycleEvent.OptedOut, day: formatDay(localDateAt(clock.now())) });
214
+ await giveBack(dropped);
81
215
  }
82
216
  async function flush() {
83
217
  // Waiting for the queue of operations first lets an event tracked just before flush join this send.
84
218
  await serialize(async () => undefined, undefined);
85
219
  await outbox.send();
86
220
  }
87
- return {
88
- track: (name, params) => serialize(async () => record(name, params), undefined),
89
- installed: () => serialize(async () => {
90
- if (await install.takeInstall(options.version)) {
91
- await record(LifecycleEvent.Installed);
221
+ const collector = {
222
+ track: async (name, given) => {
223
+ let params;
224
+ try {
225
+ params = copyOfParams(given);
92
226
  }
93
- }, undefined),
94
- updated: () => serialize(async () => {
95
- if (await install.takeVersion(options.version)) {
96
- await record(LifecycleEvent.Updated);
227
+ catch (error) {
228
+ reportError(error);
229
+ return;
97
230
  }
98
- }, undefined),
99
- setEnabled: async (on) => {
100
- const wasChanged = await serialize(async () => {
101
- if ((await install.isEnabled()) === on) {
231
+ const problem = eventProblem(name, params);
232
+ if (problem !== undefined) {
233
+ reportError(new Error(`artel: event ${quoted(name)} ${problem}, so it was not tracked`));
234
+ return;
235
+ }
236
+ const page = pageOf(name);
237
+ await serialize(async () => record({ name, params, page }), false);
238
+ },
239
+ // The opted_out state takes no install mark. A user who turns analytics back on still sends `installed`.
240
+ installed: async () => {
241
+ const page = pageOf(LifecycleEvent.Installed);
242
+ const takeMark = (productVersion) => install.takeInstall(productVersion);
243
+ await serialize(async () => record({ name: LifecycleEvent.Installed, page, takeMark }), false);
244
+ },
245
+ updated: async () => {
246
+ const page = pageOf(LifecycleEvent.Updated);
247
+ const takeMark = (productVersion) => install.takeVersion(productVersion);
248
+ await serialize(async () => record({ name: LifecycleEvent.Updated, page, takeMark }), false);
249
+ },
250
+ setState: async (next) => {
251
+ const isOptedOut = await serialize(async () => {
252
+ if (!takes(next)) {
253
+ reportError(new TypeError(`artel: a channel of mode ${quoted(mode)} takes no state ${quoted(next)}`));
102
254
  return false;
103
255
  }
104
- // The collector records nothing while it is off. It records the off event before the switch and the on event
105
- // after it, so both events go out.
106
- if (on) {
107
- await install.setEnabled(true);
108
- await record(LifecycleEvent.UsageCountsOn);
256
+ const previous = await currentState();
257
+ if (previous === next) {
258
+ return false;
109
259
  }
110
- else {
260
+ // The state goes first. A failure after it leaves the user opted out, and the next run drops what is queued.
261
+ await install.setState(next);
262
+ if (next === AnalyticsState.OptedOut) {
111
263
  // Events from before the opt-out that have not gone yet never go.
112
- await outbox.discard();
113
- await record(LifecycleEvent.UsageCountsOff);
114
- await install.setEnabled(false);
264
+ await discardForOptOut();
265
+ await recordOptOut();
266
+ }
267
+ else if (previous === AnalyticsState.Identified) {
268
+ await leaveIdentity();
115
269
  }
116
- return true;
270
+ // A new session keeps the intake from tying together events from before and after the change.
271
+ await install.endSession();
272
+ return next === AnalyticsState.OptedOut;
117
273
  }, false);
118
- if (wasChanged && !on) {
274
+ if (isOptedOut) {
119
275
  await flush();
120
276
  }
121
277
  },
122
- isEnabled: () => serialize(async () => install.isEnabled(), true),
278
+ getState: () => serialize(currentState, AnalyticsState.Anonymous),
123
279
  flush,
124
280
  forget: async (id) => {
125
- await serialize(async () => outbox.forget(id), undefined);
281
+ // A host outside TypeScript can pass any value, which no envelope carries as its id.
282
+ if (typeof id !== 'string') {
283
+ reportError(new TypeError('artel: forget takes the id getId gave, a string'));
284
+ return;
285
+ }
286
+ await serialize(async () => {
287
+ // The intake deletes the user's events, so each envelope of the id gives back its marks, sent or not.
288
+ await giveBack(await outbox.forget(id));
289
+ // The events that wait for an id after the last user are that user's, so they go with it. The next id counts
290
+ // as another user, so the events that wait after the forget never go under it.
291
+ if ((await install.lastId()) === id) {
292
+ await giveBack(await outbox.discardIdentified());
293
+ await install.forgetLastId();
294
+ }
295
+ }, undefined);
126
296
  // A request already on its way may carry the id. It must reach the intake before the host asks the intake to
127
297
  // forget the user.
128
298
  await outbox.settled();
129
299
  },
130
300
  uninstallParams: () => serialize(async () => {
301
+ const fields = await currentFields();
302
+ if (!fields.recordsEvents) {
303
+ return undefined;
304
+ }
131
305
  const today = localDateAt(clock.now());
132
- const age = daysBetween(await install.installDayOr(today), today);
133
- return { ...product, age: Math.max(0, age), days: activeDaysBucket(await install.activeDays()) };
134
- }, { ...product, age: 0, days: ActiveDaysBucket.None }),
135
- };
136
- }
137
- /**
138
- * Returns the event to queue. It carries install ages only on the first event of a day or a month, and cuts page fields
139
- * to the lengths the intake keeps.
140
- */
141
- function newEvent({ name, params, stamp: { today, installDay, first }, page, }) {
142
- const event = { name, day: formatDay(today), ...(first.length > 0 && { first }) };
143
- if (first.includes(Period.Day)) {
144
- event.age_days = clamp(daysBetween(installDay, today), MAX_AGE_DAYS);
145
- }
146
- if (first.includes(Period.Month)) {
147
- event.age_months = clamp(monthsBetween(installDay, today), MAX_AGE_MONTHS);
148
- }
149
- if (params !== undefined) {
150
- event.params = params;
151
- }
152
- if (page?.page !== undefined) {
153
- event.page = page.page.slice(0, MAX_PAGE_LENGTH);
154
- }
155
- if (page?.referrer !== undefined) {
156
- event.referrer = page.referrer.slice(0, MAX_REFERRER_LENGTH);
157
- }
158
- return event;
159
- }
160
- function activeDaysBucket(days) {
161
- if (days <= 0) {
162
- return ActiveDaysBucket.None;
163
- }
164
- if (days === 1) {
165
- return ActiveDaysBucket.One;
166
- }
167
- if (days <= 5) {
168
- return ActiveDaysBucket.TwoToFive;
169
- }
170
- return days <= 20 ? ActiveDaysBucket.SixToTwenty : ActiveDaysBucket.TwentyOneOrMore;
171
- }
172
- /** Returns the value held between 0 and `max`. The intake reads the top value of an age as that age or more. */
173
- function clamp(value, max) {
174
- return Math.min(Math.max(0, value), max);
175
- }
176
- /**
177
- * Returns a lock that runs one operation at a time within this collector, inside the host's lock when there is one.
178
- * Without it, two operations over an asynchronous storage could interleave reads and writes and lose an event.
179
- */
180
- function exclusive(hostLock) {
181
- let tail = Promise.resolve();
182
- return (operation) => {
183
- const run = tail.then(async () => (hostLock === undefined ? operation() : hostLock(operation)));
184
- tail = run.catch(() => undefined);
185
- return run;
306
+ const age = Math.max(0, daysBetween(await install.installDayOr(today), today));
307
+ return {
308
+ ...fields.product,
309
+ age_days: ageInDays(age, { isExact: fields.isAgeExact }),
310
+ active_days: activeDaysBucket(await install.activeDays()),
311
+ };
312
+ }, undefined),
186
313
  };
314
+ return collector;
187
315
  }
188
- function toError(error) {
189
- return error instanceof Error ? error : new Error(String(error));
316
+ /** Returns `value`, or `fallback` for a duration that is no finite number from 0. */
317
+ function durationOr(value, fallback) {
318
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback;
190
319
  }