@kk-forge/artel-collector 0.4.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -23
- 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/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 +31 -15
- 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 +33 -6
- package/dist/web.d.ts +4 -4
- package/dist/web.js +30 -17
- package/package.json +4 -3
package/dist/installState.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Period, formatDay, localDateAt, parseDay, periodKey } from
|
|
2
|
-
import { LifecycleEvent } from
|
|
3
|
-
import { newRandomId } from
|
|
1
|
+
import { Period, formatDay, localDateAt, parseDay, periodKey, } from "./calendar.js";
|
|
2
|
+
import { LifecycleEvent } from "./envelope.js";
|
|
3
|
+
import { newRandomId } from "./queue.js";
|
|
4
4
|
const SESSION_ID_LENGTH = 12;
|
|
5
5
|
/**
|
|
6
6
|
* The most active days the collector stores. It reports the count in buckets, and the last bucket is `21+`, so the
|
|
@@ -11,23 +11,23 @@ const MAX_ACTIVE_DAYS = 21;
|
|
|
11
11
|
* The last id after the host forgets the user. It is longer than the 64 characters of any id the collector takes, so
|
|
12
12
|
* the next id reads as another user's.
|
|
13
13
|
*/
|
|
14
|
-
const FORGOTTEN_ID =
|
|
14
|
+
const FORGOTTEN_ID = "<forgotten>".repeat(6);
|
|
15
15
|
/** The install id's form: 16 random bytes as lowercase hex, as the intake expects it. */
|
|
16
16
|
const INSTALL_ID_FORMAT = /^[\da-f]{32}$/;
|
|
17
17
|
const INSTALL_ID_BYTES = 16;
|
|
18
18
|
const StorageKey = {
|
|
19
|
-
InstallDay:
|
|
20
|
-
Installed:
|
|
21
|
-
Version:
|
|
22
|
-
State:
|
|
19
|
+
InstallDay: "install_day",
|
|
20
|
+
Installed: "installed",
|
|
21
|
+
Version: "version",
|
|
22
|
+
State: "state",
|
|
23
23
|
/** The random id of the pseudonymous state, `''` once the user left that state. */
|
|
24
|
-
InstallId:
|
|
24
|
+
InstallId: "install_id",
|
|
25
25
|
/** The last id an envelope named the user by, `''` when none does, or `FORGOTTEN_ID` after the host forgot it. */
|
|
26
|
-
LastId:
|
|
27
|
-
Session:
|
|
28
|
-
SessionSeen:
|
|
26
|
+
LastId: "last_id",
|
|
27
|
+
Session: "session",
|
|
28
|
+
SessionSeen: "session_seen",
|
|
29
29
|
/** The local days with a queued or sent event, as a JSON list of `YYYY-MM-DD`. */
|
|
30
|
-
ActiveDays:
|
|
30
|
+
ActiveDays: "active_days",
|
|
31
31
|
firstOf: (period) => `first.${period}`,
|
|
32
32
|
};
|
|
33
33
|
export function newInstallState({ storage, sessionIdleMs, }) {
|
|
@@ -53,12 +53,12 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
53
53
|
async function readActiveDays() {
|
|
54
54
|
let days;
|
|
55
55
|
try {
|
|
56
|
-
days = JSON.parse((await storage.get(StorageKey.ActiveDays)) ??
|
|
56
|
+
days = JSON.parse((await storage.get(StorageKey.ActiveDays)) ?? "[]");
|
|
57
57
|
}
|
|
58
58
|
catch {
|
|
59
59
|
return [];
|
|
60
60
|
}
|
|
61
|
-
return Array.isArray(days) ? days.filter((day) => typeof day ===
|
|
61
|
+
return Array.isArray(days) ? days.filter((day) => typeof day === "string") : [];
|
|
62
62
|
}
|
|
63
63
|
async function countActiveDay(day) {
|
|
64
64
|
const days = await readActiveDays();
|
|
@@ -73,7 +73,7 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
73
73
|
}
|
|
74
74
|
async function giveBackMark(period, day) {
|
|
75
75
|
if ((await storage.get(StorageKey.firstOf(period))) === periodKey(period, day)) {
|
|
76
|
-
await storage.set(StorageKey.firstOf(period),
|
|
76
|
+
await storage.set(StorageKey.firstOf(period), "");
|
|
77
77
|
}
|
|
78
78
|
}
|
|
79
79
|
async function giveBackFirstMarks(day, first) {
|
|
@@ -91,11 +91,12 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
91
91
|
await giveBackFirstMarks(day, event.first ?? []);
|
|
92
92
|
}
|
|
93
93
|
if (event.name === LifecycleEvent.Installed) {
|
|
94
|
-
await storage.set(StorageKey.Installed,
|
|
94
|
+
await storage.set(StorageKey.Installed, "");
|
|
95
95
|
}
|
|
96
96
|
// A later `updated` of another version stored its own version, which stays.
|
|
97
|
-
if (event.name === LifecycleEvent.Updated &&
|
|
98
|
-
await storage.
|
|
97
|
+
if (event.name === LifecycleEvent.Updated &&
|
|
98
|
+
(await storage.get(StorageKey.Version)) === version) {
|
|
99
|
+
await storage.set(StorageKey.Version, "");
|
|
99
100
|
}
|
|
100
101
|
}
|
|
101
102
|
/**
|
|
@@ -106,7 +107,7 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
106
107
|
const stored = await storage.get(StorageKey.Session);
|
|
107
108
|
const lastSeen = Number(await storage.get(StorageKey.SessionSeen));
|
|
108
109
|
const isIdle = !(timestamp - lastSeen < sessionIdleMs);
|
|
109
|
-
const session = stored === undefined || stored ===
|
|
110
|
+
const session = stored === undefined || stored === "" || isIdle || isNewDay ? newSessionId() : stored;
|
|
110
111
|
await storage.set(StorageKey.Session, session);
|
|
111
112
|
await storage.set(StorageKey.SessionSeen, String(timestamp));
|
|
112
113
|
return session;
|
|
@@ -115,7 +116,7 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
115
116
|
state: () => storage.get(StorageKey.State),
|
|
116
117
|
lastId: async () => {
|
|
117
118
|
const id = await storage.get(StorageKey.LastId);
|
|
118
|
-
return id ===
|
|
119
|
+
return id === "" ? undefined : id;
|
|
119
120
|
},
|
|
120
121
|
setLastId: (id) => storage.set(StorageKey.LastId, id),
|
|
121
122
|
forgetLastId: () => storage.set(StorageKey.LastId, FORGOTTEN_ID),
|
|
@@ -128,7 +129,7 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
128
129
|
await storage.set(StorageKey.InstallId, id);
|
|
129
130
|
return id;
|
|
130
131
|
},
|
|
131
|
-
dropInstallId: () => storage.set(StorageKey.InstallId,
|
|
132
|
+
dropInstallId: () => storage.set(StorageKey.InstallId, ""),
|
|
132
133
|
giveBack: async (envelopes) => {
|
|
133
134
|
for (const { version, events } of envelopes) {
|
|
134
135
|
for (const event of events) {
|
|
@@ -138,15 +139,15 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
138
139
|
},
|
|
139
140
|
setState: (state) => storage.set(StorageKey.State, state),
|
|
140
141
|
// An empty session reads as none, so the next event takes a new one. The storage has no remove.
|
|
141
|
-
endSession: () => storage.set(StorageKey.Session,
|
|
142
|
+
endSession: () => storage.set(StorageKey.Session, ""),
|
|
142
143
|
takeInstall: async (version) => {
|
|
143
144
|
const mark = await storage.get(StorageKey.Installed);
|
|
144
|
-
if (mark !== undefined && mark !==
|
|
145
|
+
if (mark !== undefined && mark !== "") {
|
|
145
146
|
return false;
|
|
146
147
|
}
|
|
147
148
|
// The version goes first, so a failed write leaves the install mark untaken.
|
|
148
149
|
await storage.set(StorageKey.Version, version);
|
|
149
|
-
await storage.set(StorageKey.Installed,
|
|
150
|
+
await storage.set(StorageKey.Installed, "1");
|
|
150
151
|
return true;
|
|
151
152
|
},
|
|
152
153
|
takeVersion: async (version) => {
|
|
@@ -180,7 +181,7 @@ export function newInstallState({ storage, sessionIdleMs, }) {
|
|
|
180
181
|
};
|
|
181
182
|
}
|
|
182
183
|
function newSessionId() {
|
|
183
|
-
const alphabet =
|
|
184
|
+
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyz";
|
|
184
185
|
const bytes = crypto.getRandomValues(new Uint8Array(SESSION_ID_LENGTH));
|
|
185
|
-
return Array.from(bytes, (byte) => alphabet[byte % alphabet.length]).join(
|
|
186
|
+
return Array.from(bytes, (byte) => alphabet[byte % alphabet.length]).join("");
|
|
186
187
|
}
|
package/dist/outbox.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import type { Clock } from
|
|
2
|
-
import type { Envelope, UsageEvent } from
|
|
3
|
-
import type { Lock } from
|
|
4
|
-
import { type Identity, type QueuedEnvelope } from
|
|
5
|
-
import type { StorageAdapter } from
|
|
6
|
-
import type { Transport } from
|
|
1
|
+
import type { Clock } from "./clock.js";
|
|
2
|
+
import type { Envelope, UsageEvent } from "./envelope.js";
|
|
3
|
+
import type { Lock } from "./lock.js";
|
|
4
|
+
import { type Identity, type QueuedEnvelope } from "./queue.js";
|
|
5
|
+
import type { StorageAdapter } from "./storage.js";
|
|
6
|
+
import type { Transport } from "./transport.js";
|
|
7
7
|
/**
|
|
8
8
|
* Holds the envelopes and the forget requests on their way to the intake. The forget requests leave first, then the
|
|
9
9
|
* envelopes, one at a time, in the order they were made. A request the intake cannot take now goes again later, and
|
|
@@ -15,7 +15,7 @@ interface Outbox {
|
|
|
15
15
|
* Queues the event and sends it within the send delay, at once when its envelope is full, or with the pending retry.
|
|
16
16
|
* Resolves to what the queue dropped to take it, whose marks may go back.
|
|
17
17
|
*/
|
|
18
|
-
add(fields: Omit<Envelope,
|
|
18
|
+
add(fields: Omit<Envelope, "events">, event: UsageEvent, options?: {
|
|
19
19
|
awaitsId?: boolean;
|
|
20
20
|
}): Promise<QueuedEnvelope[]>;
|
|
21
21
|
/** Sends what is queued within the send delay, such as what an earlier run of the host left. */
|
|
@@ -37,10 +37,12 @@ interface Outbox {
|
|
|
37
37
|
forget(id: string): Promise<QueuedEnvelope[]>;
|
|
38
38
|
/** Drops the envelopes that name a user or that await an id. Resolves to those whose marks may go back. */
|
|
39
39
|
discardIdentified(): Promise<QueuedEnvelope[]>;
|
|
40
|
+
/** Resolves to whether the storage holds an envelope or a forget request to send. */
|
|
41
|
+
holdsRequests(): Promise<boolean>;
|
|
40
42
|
}
|
|
41
43
|
/**
|
|
42
|
-
* Expects the caller to run `add`, `discard`, `forget` and `
|
|
43
|
-
* for the whole recording of an event. The sends take the lock themselves.
|
|
44
|
+
* Expects the caller to run `add`, `discard`, `forget`, `discardIdentified` and `holdsRequests` inside its own `lock`,
|
|
45
|
+
* which it holds for the whole recording of an event. The sends take the lock themselves.
|
|
44
46
|
*/
|
|
45
47
|
export declare function newOutbox({ key, storage, lock, transport, forgetTransport, identify, giveBack, sendDelayMs, clock, reportError, }: {
|
|
46
48
|
/** The channel key, which a forget request names. */
|
package/dist/outbox.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { daysBetween, parseDay, utcDateAt } from
|
|
2
|
-
import { isTestKey, isUsableId, quoted } from
|
|
3
|
-
import { newQueue, newRandomId, } from
|
|
1
|
+
import { daysBetween, parseDay, utcDateAt } from "./calendar.js";
|
|
2
|
+
import { isTestKey, isUsableId, quoted } from "./hostInput.js";
|
|
3
|
+
import { newQueue, newRandomId, } from "./queue.js";
|
|
4
4
|
const RETRY_DELAY_MS = 1_000;
|
|
5
5
|
const MAX_RETRY_DELAY_MS = 5 * 60_000;
|
|
6
6
|
/** Names the stored time, in epoch milliseconds, before which no context that shares the storage starts a send. */
|
|
7
|
-
const RETRY_AT_KEY =
|
|
7
|
+
const RETRY_AT_KEY = "retry_at";
|
|
8
8
|
/**
|
|
9
9
|
* The time one send holds the lease on a queued envelope, twice the 30 s request limit of `newHttpTransport` in
|
|
10
10
|
* `src/transport.ts`. The send renews the lease before each request. A host that stops mid-send blocks the envelope
|
|
@@ -18,8 +18,8 @@ const LEASE_MS = 60_000;
|
|
|
18
18
|
const TRANSPORT_LIMIT_MS = 35_000;
|
|
19
19
|
const MAX_HTTP_STATUS = 599;
|
|
20
20
|
/**
|
|
21
|
-
* Expects the caller to run `add`, `discard`, `forget` and `
|
|
22
|
-
* for the whole recording of an event. The sends take the lock themselves.
|
|
21
|
+
* Expects the caller to run `add`, `discard`, `forget`, `discardIdentified` and `holdsRequests` inside its own `lock`,
|
|
22
|
+
* which it holds for the whole recording of an event. The sends take the lock themselves.
|
|
23
23
|
*/
|
|
24
24
|
export function newOutbox({ key, storage, lock, transport, forgetTransport, identify, giveBack, sendDelayMs, clock, reportError, }) {
|
|
25
25
|
const queue = newQueue({ storage, reportError });
|
|
@@ -71,7 +71,9 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
71
71
|
*/
|
|
72
72
|
function sendUnlessRetryPending() {
|
|
73
73
|
cancelSend();
|
|
74
|
-
sending = sending
|
|
74
|
+
sending = sending
|
|
75
|
+
.then(async () => (retryTimer === undefined ? sendLeased() : undefined))
|
|
76
|
+
.catch(reportError);
|
|
75
77
|
return sending;
|
|
76
78
|
}
|
|
77
79
|
/**
|
|
@@ -80,7 +82,7 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
80
82
|
* now, so it holds no send for longer. The caller holds `lock`.
|
|
81
83
|
*/
|
|
82
84
|
async function retryWaitMs() {
|
|
83
|
-
const stored = (await storage.get(RETRY_AT_KEY)) ??
|
|
85
|
+
const stored = (await storage.get(RETRY_AT_KEY)) ?? "";
|
|
84
86
|
const waitMs = Math.max(0, Number(stored) - clock.now());
|
|
85
87
|
if (waitMs <= MAX_RETRY_DELAY_MS) {
|
|
86
88
|
return waitMs;
|
|
@@ -103,7 +105,9 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
103
105
|
const wait = await retryWaitMs();
|
|
104
106
|
return {
|
|
105
107
|
waitMs: wait,
|
|
106
|
-
taken: wait > 0
|
|
108
|
+
taken: wait > 0
|
|
109
|
+
? undefined
|
|
110
|
+
: { forgets: await queue.forgets(), leased: await queue.lease(leaseTerms()) },
|
|
107
111
|
};
|
|
108
112
|
});
|
|
109
113
|
if (taken === undefined) {
|
|
@@ -166,7 +170,7 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
166
170
|
const { isSettled, askedWaitMs } = await deliver({
|
|
167
171
|
body: JSON.stringify({ key, id }),
|
|
168
172
|
transport: forgetTransport,
|
|
169
|
-
what:
|
|
173
|
+
what: "a forget",
|
|
170
174
|
reportError,
|
|
171
175
|
clock,
|
|
172
176
|
});
|
|
@@ -201,7 +205,13 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
201
205
|
unsettled.delete(item.qid);
|
|
202
206
|
continue;
|
|
203
207
|
}
|
|
204
|
-
const { isSettled, askedWaitMs } = await deliver({
|
|
208
|
+
const { isSettled, askedWaitMs } = await deliver({
|
|
209
|
+
body,
|
|
210
|
+
transport,
|
|
211
|
+
what: "an envelope",
|
|
212
|
+
reportError,
|
|
213
|
+
clock,
|
|
214
|
+
});
|
|
205
215
|
if (!isSettled) {
|
|
206
216
|
await waitForRetry(askedWaitMs);
|
|
207
217
|
return;
|
|
@@ -232,6 +242,7 @@ export function newOutbox({ key, storage, lock, transport, forgetTransport, iden
|
|
|
232
242
|
return queue.removeId(id);
|
|
233
243
|
},
|
|
234
244
|
discardIdentified: () => queue.removeIdentified(),
|
|
245
|
+
holdsRequests: () => queue.holdsRequests(),
|
|
235
246
|
};
|
|
236
247
|
}
|
|
237
248
|
/**
|
|
@@ -259,10 +270,13 @@ async function deliver({ body, transport, what, reportError, clock, }) {
|
|
|
259
270
|
* Only a product's own transport, outside TypeScript or with a bug, gives such a value.
|
|
260
271
|
*/
|
|
261
272
|
function httpStatus(status, reportError) {
|
|
262
|
-
if (typeof status ===
|
|
273
|
+
if (typeof status === "number" &&
|
|
274
|
+
Number.isInteger(status) &&
|
|
275
|
+
status >= 0 &&
|
|
276
|
+
status <= MAX_HTTP_STATUS) {
|
|
263
277
|
return status;
|
|
264
278
|
}
|
|
265
|
-
reportError(new Error(
|
|
279
|
+
reportError(new Error("artel: the transport answered a status that is no whole number from 0 to 599, read as 0"));
|
|
266
280
|
return 0;
|
|
267
281
|
}
|
|
268
282
|
/**
|
|
@@ -277,7 +291,9 @@ async function answerOf(transport, body, clock) {
|
|
|
277
291
|
try {
|
|
278
292
|
const answer = await Promise.race([transport(body), late]);
|
|
279
293
|
// A null or undefined answer throws here, and reads as status 0.
|
|
280
|
-
return typeof answer ===
|
|
294
|
+
return typeof answer === "number"
|
|
295
|
+
? { status: answer }
|
|
296
|
+
: { status: answer.status, retryAfter: answer.retryAfter };
|
|
281
297
|
}
|
|
282
298
|
catch {
|
|
283
299
|
return { status: 0 };
|
|
@@ -292,7 +308,7 @@ async function answerOf(transport, body, clock) {
|
|
|
292
308
|
* only a product's own transport outside TypeScript gives.
|
|
293
309
|
*/
|
|
294
310
|
function retryAfterMs(value, now) {
|
|
295
|
-
if (typeof value !==
|
|
311
|
+
if (typeof value !== "string") {
|
|
296
312
|
return undefined;
|
|
297
313
|
}
|
|
298
314
|
if (/^\d+$/.test(value)) {
|
package/dist/page.d.ts
CHANGED
package/dist/page.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { PAGE_VIEW } from
|
|
2
|
-
import { pagePath, referrerHost } from
|
|
1
|
+
import { PAGE_VIEW } from "./envelope.js";
|
|
2
|
+
import { pagePath, referrerHost } from "./pagePath.js";
|
|
3
3
|
/**
|
|
4
4
|
* Returns the reader of an event's page fields from `getPage`. It sends the referrer only with the first recorded
|
|
5
5
|
* `page_view`, as the referrer belongs to the page load. It sends nothing for a `page_view` that repeats the last page.
|
|
@@ -12,8 +12,10 @@ export function newPageReader({ getPage, reportError, }) {
|
|
|
12
12
|
// A host outside TypeScript can return any value, or fields whose getters throw.
|
|
13
13
|
try {
|
|
14
14
|
const fields = getPage?.(name);
|
|
15
|
-
const page = stringField(
|
|
16
|
-
const referrer = mayCarryReferrer
|
|
15
|
+
const page = stringField("page", fields?.page, reportError);
|
|
16
|
+
const referrer = mayCarryReferrer
|
|
17
|
+
? stringField("referrer", fields?.referrer, reportError)
|
|
18
|
+
: undefined;
|
|
17
19
|
const path = page === undefined ? undefined : checkedPath(page, reportError);
|
|
18
20
|
const host = referrer === undefined ? undefined : referrerHost(referrer);
|
|
19
21
|
const isPageHost = page !== undefined && host === referrerHost(page);
|
|
@@ -50,7 +52,7 @@ export function newPageReader({ getPage, reportError, }) {
|
|
|
50
52
|
}
|
|
51
53
|
/** Returns a page field that is a string, or reports and leaves out one that is not. */
|
|
52
54
|
function stringField(name, value, reportError) {
|
|
53
|
-
if (value === undefined || typeof value ===
|
|
55
|
+
if (value === undefined || typeof value === "string") {
|
|
54
56
|
return value;
|
|
55
57
|
}
|
|
56
58
|
reportError(new TypeError(`artel: the ${name} getPage gave is a ${typeof value}, not a string, left out`));
|
|
@@ -63,7 +65,7 @@ function stringField(name, value, reportError) {
|
|
|
63
65
|
function checkedPath(page, reportError) {
|
|
64
66
|
const path = pagePath(page);
|
|
65
67
|
if (path === undefined) {
|
|
66
|
-
reportError(new Error(
|
|
68
|
+
reportError(new Error("artel: a page that is neither a path nor a URL with a path was left out"));
|
|
67
69
|
}
|
|
68
70
|
return path;
|
|
69
71
|
}
|
package/dist/pagePath.js
CHANGED
|
@@ -6,9 +6,9 @@ const MAX_PAGE_LENGTH = 256;
|
|
|
6
6
|
/** The length of a referrer host the intake keeps. */
|
|
7
7
|
const MAX_REFERRER_LENGTH = 128;
|
|
8
8
|
/** What the collector sends in place of a segment that holds an address. */
|
|
9
|
-
const ADDRESS_SEGMENT =
|
|
9
|
+
const ADDRESS_SEGMENT = ":address";
|
|
10
10
|
/** The base `URL` reads a page against, so a page given as a path reads too. */
|
|
11
|
-
const PAGE_BASE =
|
|
11
|
+
const PAGE_BASE = "https://page.invalid";
|
|
12
12
|
/** The most times the collector decodes a segment, so an address escaped twice, as `%2540`, still shows. */
|
|
13
13
|
const MAX_DECODING_PASSES = 2;
|
|
14
14
|
/** The at sign and its look-alikes U+FF20 and U+FE6B. */
|
|
@@ -44,15 +44,15 @@ export function pagePath(page) {
|
|
|
44
44
|
catch {
|
|
45
45
|
return undefined;
|
|
46
46
|
}
|
|
47
|
-
return path.startsWith(
|
|
47
|
+
return path.startsWith("/") ? cut(withoutAddresses(path)) : undefined;
|
|
48
48
|
}
|
|
49
49
|
/** Returns the path cut to 256 characters, never inside an escape or inside the escapes of one UTF-8 character. */
|
|
50
50
|
function cut(path) {
|
|
51
51
|
if (path.length <= MAX_PAGE_LENGTH) {
|
|
52
52
|
return path;
|
|
53
53
|
}
|
|
54
|
-
const kept = path.slice(0, MAX_PAGE_LENGTH).replace(CUT_ESCAPE,
|
|
55
|
-
const lastCharacter = LAST_ENCODED_CHARACTER.exec(kept)?.[0] ??
|
|
54
|
+
const kept = path.slice(0, MAX_PAGE_LENGTH).replace(CUT_ESCAPE, "");
|
|
55
|
+
const lastCharacter = LAST_ENCODED_CHARACTER.exec(kept)?.[0] ?? "";
|
|
56
56
|
return isWholeCharacter(lastCharacter) ? kept : kept.slice(0, kept.length - lastCharacter.length);
|
|
57
57
|
}
|
|
58
58
|
/** Tells whether escapes spell one whole UTF-8 character, or are none. */
|
|
@@ -78,18 +78,18 @@ export function referrerHost(referrer) {
|
|
|
78
78
|
catch {
|
|
79
79
|
return undefined;
|
|
80
80
|
}
|
|
81
|
-
const isIp = host.startsWith(
|
|
81
|
+
const isIp = host.startsWith("[") || /^\d+$/.test(host.slice(host.lastIndexOf(".") + 1));
|
|
82
82
|
// The check decodes the host, since `URL` leaves an at sign or a look-alike escaped in the host of a scheme other
|
|
83
83
|
// than http or https.
|
|
84
84
|
const isAddress = isIp || AT_SIGN.test(decodedOrSame(host));
|
|
85
|
-
return host ===
|
|
85
|
+
return host === "" || host.length > MAX_REFERRER_LENGTH || isAddress ? undefined : host;
|
|
86
86
|
}
|
|
87
87
|
/**
|
|
88
88
|
* Returns the path with `:address` for each segment that holds an address, and one `:address` for the rest of the path
|
|
89
89
|
* from a segment that starts a URL.
|
|
90
90
|
*/
|
|
91
91
|
function withoutAddresses(path) {
|
|
92
|
-
const segments = path.split(
|
|
92
|
+
const segments = path.split("/");
|
|
93
93
|
const kept = [];
|
|
94
94
|
let length = 0;
|
|
95
95
|
for (const [index, whole] of segments.entries()) {
|
|
@@ -97,25 +97,25 @@ function withoutAddresses(path) {
|
|
|
97
97
|
if (length > MAX_PAGE_LENGTH) {
|
|
98
98
|
break;
|
|
99
99
|
}
|
|
100
|
-
const segment = whole.replace(PATH_PARAMETER,
|
|
100
|
+
const segment = whole.replace(PATH_PARAMETER, "");
|
|
101
101
|
const texts = decodings(segment);
|
|
102
102
|
if (startsUrl(texts, segments[index + 1])) {
|
|
103
|
-
return [...kept, ADDRESS_SEGMENT].join(
|
|
103
|
+
return [...kept, ADDRESS_SEGMENT].join("/");
|
|
104
104
|
}
|
|
105
105
|
const sent = texts.some(holdsAddress) ? ADDRESS_SEGMENT : segment;
|
|
106
106
|
kept.push(sent);
|
|
107
107
|
length += sent.length + 1;
|
|
108
108
|
}
|
|
109
|
-
return kept.join(
|
|
109
|
+
return kept.join("/");
|
|
110
110
|
}
|
|
111
111
|
/**
|
|
112
112
|
* Tells whether a segment, given as written and decoded, starts a URL: it holds a scheme and `://` or a special scheme,
|
|
113
113
|
* or it ends in a scheme's colon before an empty segment.
|
|
114
114
|
*/
|
|
115
115
|
function startsUrl(texts, next) {
|
|
116
|
-
const [written =
|
|
116
|
+
const [written = ""] = texts;
|
|
117
117
|
return (texts.some((text) => SCHEME_SLASHES.test(text) || SPECIAL_SCHEME.test(text)) ||
|
|
118
|
-
(next ===
|
|
118
|
+
(next === "" && SCHEME_END.test(written)));
|
|
119
119
|
}
|
|
120
120
|
/** Returns the segment as written and after each decoding pass, until a pass changes nothing or the passes run out. */
|
|
121
121
|
function decodings(segment) {
|
|
@@ -159,5 +159,5 @@ function holdsAddress(text) {
|
|
|
159
159
|
* `::1`.
|
|
160
160
|
*/
|
|
161
161
|
function holdsShortIpv6(text) {
|
|
162
|
-
return text.split(NON_WORD).some((word) => word.includes(
|
|
162
|
+
return text.split(NON_WORD).some((word) => word.includes("::") && HEX_AND_COLONS.test(word));
|
|
163
163
|
}
|
package/dist/queue.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { type Envelope, type IdKind, type UsageEvent } from
|
|
2
|
-
import type { StorageAdapter } from
|
|
1
|
+
import { type Envelope, type IdKind, type UsageEvent } from "./envelope.js";
|
|
2
|
+
import type { StorageAdapter } from "./storage.js";
|
|
3
3
|
export declare const QUEUE_KEY = "queue";
|
|
4
4
|
export interface QueuedEnvelope {
|
|
5
5
|
qid: string;
|
|
@@ -22,7 +22,7 @@ export interface QueuedEnvelope {
|
|
|
22
22
|
export interface Identity {
|
|
23
23
|
id: string;
|
|
24
24
|
id_kind: IdKind;
|
|
25
|
-
browser?: Envelope[
|
|
25
|
+
browser?: Envelope["browser"];
|
|
26
26
|
}
|
|
27
27
|
/** Holds a sealed envelope and the body each send attempt carries. */
|
|
28
28
|
export interface SealedEnvelope {
|
|
@@ -49,7 +49,7 @@ interface Queue {
|
|
|
49
49
|
* kB, else to a new one. An `opted_out` takes an envelope of its own. Resolves to whether that envelope holds 100
|
|
50
50
|
* events, and to what the queue dropped: the oldest envelope past 20.
|
|
51
51
|
*/
|
|
52
|
-
add(fields: Omit<Envelope,
|
|
52
|
+
add(fields: Omit<Envelope, "events">, event: UsageEvent, options?: {
|
|
53
53
|
awaitsId?: boolean;
|
|
54
54
|
}): Promise<{
|
|
55
55
|
isFull: boolean;
|
|
@@ -83,6 +83,8 @@ interface Queue {
|
|
|
83
83
|
/** Resolves to the ids of the stored forget requests, oldest first. */
|
|
84
84
|
forgets(): Promise<string[]>;
|
|
85
85
|
removeForget(id: string): Promise<void>;
|
|
86
|
+
/** Resolves to whether the storage holds an envelope or a forget request. Writes and reports nothing. */
|
|
87
|
+
holdsRequests(): Promise<boolean>;
|
|
86
88
|
}
|
|
87
89
|
/** Returns a queue in `storage`. The caller holds a lock around each call. */
|
|
88
90
|
export declare function newQueue({ storage, reportError, }: {
|
package/dist/queue.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { LifecycleEvent } from
|
|
2
|
-
export const QUEUE_KEY =
|
|
1
|
+
import { LifecycleEvent } from "./envelope.js";
|
|
2
|
+
export const QUEUE_KEY = "queue";
|
|
3
3
|
/** Names the ids of the stored forget requests, a JSON list. */
|
|
4
|
-
const FORGETS_KEY =
|
|
4
|
+
const FORGETS_KEY = "forgets";
|
|
5
5
|
const MAX_ENVELOPE_EVENTS = 100;
|
|
6
6
|
/**
|
|
7
7
|
* The largest request body, under 64 KiB with some margin. A keepalive request and the intake both refuse a larger
|
|
@@ -24,7 +24,7 @@ export function newQueue({ storage, reportError, }) {
|
|
|
24
24
|
async function read() {
|
|
25
25
|
const queued = parseQueue(await storage.get(QUEUE_KEY));
|
|
26
26
|
if (queued === undefined) {
|
|
27
|
-
reportError(new Error(
|
|
27
|
+
reportError(new Error("artel: the stored queue is not a JSON list, so it was dropped"));
|
|
28
28
|
await write([]);
|
|
29
29
|
return [];
|
|
30
30
|
}
|
|
@@ -57,12 +57,14 @@ export function newQueue({ storage, reportError, }) {
|
|
|
57
57
|
async function readForgets() {
|
|
58
58
|
let bodies;
|
|
59
59
|
try {
|
|
60
|
-
bodies = JSON.parse((await storage.get(FORGETS_KEY)) ??
|
|
60
|
+
bodies = JSON.parse((await storage.get(FORGETS_KEY)) ?? "[]");
|
|
61
61
|
}
|
|
62
62
|
catch {
|
|
63
63
|
return [];
|
|
64
64
|
}
|
|
65
|
-
return Array.isArray(bodies)
|
|
65
|
+
return Array.isArray(bodies)
|
|
66
|
+
? bodies.filter((body) => typeof body === "string")
|
|
67
|
+
: [];
|
|
66
68
|
}
|
|
67
69
|
async function writeForgets(ids) {
|
|
68
70
|
await storage.set(FORGETS_KEY, JSON.stringify(ids));
|
|
@@ -123,7 +125,9 @@ export function newQueue({ storage, reportError, }) {
|
|
|
123
125
|
seal: async (qid, terms, identity) => {
|
|
124
126
|
const items = await read();
|
|
125
127
|
const item = items.find((candidate) => candidate.qid === qid);
|
|
126
|
-
if (item === undefined ||
|
|
128
|
+
if (item === undefined ||
|
|
129
|
+
!isFree(item, terms) ||
|
|
130
|
+
(item.awaitsId === true && identity === undefined)) {
|
|
127
131
|
return undefined;
|
|
128
132
|
}
|
|
129
133
|
if (item.awaitsId === true && identity !== undefined) {
|
|
@@ -165,6 +169,8 @@ export function newQueue({ storage, reportError, }) {
|
|
|
165
169
|
}
|
|
166
170
|
},
|
|
167
171
|
forgets: readForgets,
|
|
172
|
+
holdsRequests: async () => (parseQueue(await storage.get(QUEUE_KEY))?.length ?? 0) > 0 ||
|
|
173
|
+
(await readForgets()).length > 0,
|
|
168
174
|
removeForget: async (id) => writeForgets((await readForgets()).filter((stored) => stored !== id)),
|
|
169
175
|
};
|
|
170
176
|
}
|
|
@@ -175,7 +181,7 @@ export function newQueue({ storage, reportError, }) {
|
|
|
175
181
|
export function parseQueue(stored) {
|
|
176
182
|
let queued;
|
|
177
183
|
try {
|
|
178
|
-
queued = JSON.parse(stored ??
|
|
184
|
+
queued = JSON.parse(stored ?? "[]");
|
|
179
185
|
}
|
|
180
186
|
catch {
|
|
181
187
|
// The caller reports a queue that is no list. The parser's message quotes the stored text, which may hold an id or
|
|
@@ -193,7 +199,10 @@ function unsent(items) {
|
|
|
193
199
|
*/
|
|
194
200
|
function isFree(item, { holder, now, until }) {
|
|
195
201
|
const { leasedUntil } = item;
|
|
196
|
-
return leasedUntil === undefined ||
|
|
202
|
+
return (leasedUntil === undefined ||
|
|
203
|
+
item.leasedBy === holder ||
|
|
204
|
+
leasedUntil <= now ||
|
|
205
|
+
leasedUntil > until);
|
|
197
206
|
}
|
|
198
207
|
function sameFields(envelope, fields) {
|
|
199
208
|
const { events: _, ...envelopeFields } = envelope;
|
|
@@ -209,12 +218,16 @@ function fits(envelope, event) {
|
|
|
209
218
|
/** Returns `byteCount` random bytes, 8 by default, as lowercase hex. */
|
|
210
219
|
export function newRandomId(byteCount = 8) {
|
|
211
220
|
const bytes = crypto.getRandomValues(new Uint8Array(byteCount));
|
|
212
|
-
return Array.from(bytes, (byte) => byte.toString(16).padStart(2,
|
|
221
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
213
222
|
}
|
|
214
223
|
function isQueuedEnvelope(value) {
|
|
215
|
-
if (typeof value !==
|
|
224
|
+
if (typeof value !== "object" ||
|
|
225
|
+
value === null ||
|
|
226
|
+
typeof Reflect.get(value, "qid") !== "string") {
|
|
216
227
|
return false;
|
|
217
228
|
}
|
|
218
|
-
const envelope = Reflect.get(value,
|
|
219
|
-
return typeof envelope ===
|
|
229
|
+
const envelope = Reflect.get(value, "envelope");
|
|
230
|
+
return (typeof envelope === "object" &&
|
|
231
|
+
envelope !== null &&
|
|
232
|
+
Array.isArray(Reflect.get(envelope, "events")));
|
|
220
233
|
}
|
package/dist/stateFields.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { AnalyticsState, Mode } from
|
|
2
|
-
import { Platform, type Envelope, type IdKind } from
|
|
1
|
+
import { AnalyticsState, Mode } from "./collectorTypes.js";
|
|
2
|
+
import { Platform, type Envelope, type IdKind } from "./envelope.js";
|
|
3
3
|
export interface Build {
|
|
4
4
|
platform: Platform;
|
|
5
5
|
version: string;
|
|
6
6
|
}
|
|
7
7
|
/** The fields that name the product build, as an envelope and the uninstall page carry them. */
|
|
8
|
-
export type ProductFields = Pick<Envelope,
|
|
8
|
+
export type ProductFields = Pick<Envelope, "platform" | "version" | "browser_language" | "ui_language">;
|
|
9
9
|
/** Everything the collector shapes by the user's state. */
|
|
10
10
|
export interface StateFields {
|
|
11
11
|
/** Whether the state records the user's events. Only `opted_out` records none. */
|
|
@@ -23,7 +23,7 @@ export declare function isAnalyticsState(value: unknown): value is AnalyticsStat
|
|
|
23
23
|
/** Tells whether a channel of `mode` takes `state`: a state up to its mode. A mode that does not exist is anonymous. */
|
|
24
24
|
export declare function channelTakes(mode: Mode, state: unknown): state is AnalyticsState;
|
|
25
25
|
/** Returns whether events of this build may carry a page, which the intake keeps only from a site channel. */
|
|
26
|
-
export declare function carriesPage(build: Pick<Build,
|
|
26
|
+
export declare function carriesPage(build: Pick<Build, "platform">): boolean;
|
|
27
27
|
/**
|
|
28
28
|
* Returns what the collector sends in `state` for this build and these languages. Only a state with an id carries the
|
|
29
29
|
* full languages and the exact ages: with the platform and version they can single out a user, so they go only with the
|
package/dist/stateFields.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { AnalyticsState, Mode } from
|
|
2
|
-
import { Platform } from
|
|
3
|
-
import { primaryLanguage } from
|
|
1
|
+
import { AnalyticsState, Mode } from "./collectorTypes.js";
|
|
2
|
+
import { Platform } from "./envelope.js";
|
|
3
|
+
import { primaryLanguage } from "./fields.js";
|
|
4
4
|
/** Ranks the modes and the states by what they reveal of a user. A mode takes the states of a rank up to its own. */
|
|
5
5
|
const MODE_RANKS = new Map([
|
|
6
6
|
[Mode.Anonymous, 0],
|
|
@@ -30,7 +30,9 @@ export function carriesPage(build) {
|
|
|
30
30
|
* consent the id needs.
|
|
31
31
|
*/
|
|
32
32
|
export function fieldsForState({ state, build, browserLanguage, uiLanguage, }) {
|
|
33
|
-
const idKind = state === AnalyticsState.Pseudonymous || state === AnalyticsState.Identified
|
|
33
|
+
const idKind = state === AnalyticsState.Pseudonymous || state === AnalyticsState.Identified
|
|
34
|
+
? state
|
|
35
|
+
: undefined;
|
|
34
36
|
const isNamed = idKind !== undefined;
|
|
35
37
|
const shape = (tag) => tag === undefined || isNamed ? tag : primaryLanguage(tag);
|
|
36
38
|
const shapedBrowserLanguage = shape(browserLanguage);
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import type
|
|
3
|
-
import {
|
|
1
|
+
import { type Clock } from "./clock.js";
|
|
2
|
+
import { Mode, type Collector } from "./collectorTypes.js";
|
|
3
|
+
import type { EventParams } from "./envelope.js";
|
|
4
|
+
import { type StorageAdapter } from "./storage.js";
|
|
4
5
|
/** One event as a product tracked it. */
|
|
5
6
|
export interface RecordedEvent {
|
|
6
7
|
name: string;
|
|
@@ -16,10 +17,12 @@ export type RecordingCollector<M extends Mode = Mode> = Collector<M> & {
|
|
|
16
17
|
* real collector would send. Its user starts in the anonymous state. It refuses an event `track` refuses, a state above
|
|
17
18
|
* the mode and an id `forget` refuses, with the same report to `onError`. It records `opted_out` at the opt-out, and
|
|
18
19
|
* nothing in the opted_out state. It keeps one version: `installed` records once, and `updated` only while neither of
|
|
19
|
-
* them recorded. `uninstallParams` resolves to undefined.
|
|
20
|
+
* them recorded. It drops a call with `throttleMs` as `track` does, by `clock`. `uninstallParams` resolves to undefined.
|
|
20
21
|
*/
|
|
21
|
-
export declare function newRecordingCollector<M extends Mode = typeof Mode.Anonymous>(mode?: M, { onError }?: {
|
|
22
|
+
export declare function newRecordingCollector<M extends Mode = typeof Mode.Anonymous>(mode?: M, { onError, clock, }?: {
|
|
22
23
|
onError?: (error: Error) => void;
|
|
24
|
+
/** The clock of the `throttleMs` windows of `track`, the system's by default. */
|
|
25
|
+
clock?: Clock;
|
|
23
26
|
}): RecordingCollector<M>;
|
|
24
27
|
/**
|
|
25
28
|
* Resolves to the events a collector of channel `key` holds queued in `storage`, oldest first, so a product's test reads
|