@kk-forge/artel-collector 0.3.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 +127 -110
- 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 +11 -8
- package/dist/collector.js +176 -106
- package/dist/collectorTypes.d.ts +67 -42
- package/dist/collectorTypes.js +24 -14
- package/dist/desktop.d.ts +9 -12
- package/dist/desktop.js +8 -3
- package/dist/envelope.d.ts +14 -10
- package/dist/envelope.js +12 -12
- package/dist/eventCheck.d.ts +17 -7
- package/dist/eventCheck.js +64 -23
- package/dist/exports.d.ts +10 -8
- package/dist/exports.js +9 -7
- package/dist/extension.d.ts +27 -37
- package/dist/extension.js +200 -51
- package/dist/fields.d.ts +3 -3
- package/dist/fields.js +7 -7
- package/dist/hostInput.d.ts +13 -4
- package/dist/hostInput.js +44 -22
- package/dist/installState.d.ts +11 -7
- package/dist/installState.js +42 -25
- package/dist/outbox.d.ts +28 -17
- package/dist/outbox.js +89 -31
- package/dist/page.d.ts +1 -1
- package/dist/page.js +8 -6
- package/dist/pagePath.js +14 -14
- package/dist/queue.d.ts +26 -10
- package/dist/queue.js +70 -23
- package/dist/stateFields.d.ts +9 -8
- package/dist/stateFields.js +28 -11
- package/dist/testing.d.ts +31 -0
- package/dist/testing.js +85 -0
- package/dist/throttle.d.ts +30 -0
- package/dist/throttle.js +41 -0
- package/dist/transport.d.ts +15 -5
- package/dist/transport.js +34 -7
- package/dist/web.d.ts +8 -18
- package/dist/web.js +32 -33
- package/package.json +10 -5
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,6 @@
|
|
|
1
|
-
import { type Envelope, 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
|
+
export declare const QUEUE_KEY = "queue";
|
|
3
4
|
export interface QueuedEnvelope {
|
|
4
5
|
qid: string;
|
|
5
6
|
/**
|
|
@@ -11,16 +12,17 @@ export interface QueuedEnvelope {
|
|
|
11
12
|
leasedBy?: string;
|
|
12
13
|
/** The time the lease ends, in epoch milliseconds. */
|
|
13
14
|
leasedUntil?: number;
|
|
14
|
-
/** Marks an
|
|
15
|
+
/** Marks an envelope of a state with an id the product does not know yet. It waits for the id and goes with it. */
|
|
15
16
|
awaitsId?: true;
|
|
16
17
|
/** Marks the envelope of an `opted_out`, which the intake takes only alone. No other event joins it. */
|
|
17
18
|
isOptOut?: true;
|
|
18
19
|
envelope: Envelope;
|
|
19
20
|
}
|
|
20
|
-
/** The user that an
|
|
21
|
+
/** The user that an envelope awaiting an id names, known once the product knows the id. */
|
|
21
22
|
export interface Identity {
|
|
22
23
|
id: string;
|
|
23
|
-
|
|
24
|
+
id_kind: IdKind;
|
|
25
|
+
browser?: Envelope["browser"];
|
|
24
26
|
}
|
|
25
27
|
/** Holds a sealed envelope and the body each send attempt carries. */
|
|
26
28
|
export interface SealedEnvelope {
|
|
@@ -36,9 +38,10 @@ export interface LeaseTerms {
|
|
|
36
38
|
until: number;
|
|
37
39
|
}
|
|
38
40
|
/**
|
|
39
|
-
* Keeps envelopes in storage until the intake takes them, so a host that stops, such as an idle
|
|
40
|
-
* worker, loses none. A method that drops envelopes resolves to those whose marks may go back: the
|
|
41
|
-
* a body for, since the intake may keep a request that failed for the sender. `removeId` resolves
|
|
41
|
+
* Keeps envelopes and forget requests in storage until the intake takes them, so a host that stops, such as an idle
|
|
42
|
+
* extension service worker, loses none. A method that drops envelopes resolves to those whose marks may go back: the
|
|
43
|
+
* ones no seal stored a body for, since the intake may keep a request that failed for the sender. `removeId` resolves
|
|
44
|
+
* to all of them.
|
|
42
45
|
*/
|
|
43
46
|
interface Queue {
|
|
44
47
|
/**
|
|
@@ -46,7 +49,7 @@ interface Queue {
|
|
|
46
49
|
* kB, else to a new one. An `opted_out` takes an envelope of its own. Resolves to whether that envelope holds 100
|
|
47
50
|
* events, and to what the queue dropped: the oldest envelope past 20.
|
|
48
51
|
*/
|
|
49
|
-
add(fields: Omit<Envelope,
|
|
52
|
+
add(fields: Omit<Envelope, "events">, event: UsageEvent, options?: {
|
|
50
53
|
awaitsId?: boolean;
|
|
51
54
|
}): Promise<{
|
|
52
55
|
isFull: boolean;
|
|
@@ -75,11 +78,24 @@ interface Queue {
|
|
|
75
78
|
/** Drops the envelopes that name a user or wait to, as when the user stops being identified. */
|
|
76
79
|
removeIdentified(): Promise<QueuedEnvelope[]>;
|
|
77
80
|
removeAllButOptOuts(): Promise<QueuedEnvelope[]>;
|
|
81
|
+
/** Stores the id of a forget request, unless it is stored already. */
|
|
82
|
+
addForget(id: string): Promise<void>;
|
|
83
|
+
/** Resolves to the ids of the stored forget requests, oldest first. */
|
|
84
|
+
forgets(): Promise<string[]>;
|
|
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>;
|
|
78
88
|
}
|
|
79
89
|
/** Returns a queue in `storage`. The caller holds a lock around each call. */
|
|
80
90
|
export declare function newQueue({ storage, reportError, }: {
|
|
81
91
|
storage: StorageAdapter;
|
|
82
92
|
reportError: (error: unknown) => void;
|
|
83
93
|
}): Queue;
|
|
84
|
-
|
|
94
|
+
/**
|
|
95
|
+
* Returns the envelopes of a stored queue, oldest first, or undefined for a value that is no JSON list. It skips an item
|
|
96
|
+
* without a queue id and an envelope with a list of events.
|
|
97
|
+
*/
|
|
98
|
+
export declare function parseQueue(stored: string | undefined): QueuedEnvelope[] | undefined;
|
|
99
|
+
/** Returns `byteCount` random bytes, 8 by default, as lowercase hex. */
|
|
100
|
+
export declare function newRandomId(byteCount?: number): string;
|
|
85
101
|
export {};
|
package/dist/queue.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import { LifecycleEvent } from
|
|
2
|
-
const QUEUE_KEY =
|
|
1
|
+
import { LifecycleEvent } from "./envelope.js";
|
|
2
|
+
export const QUEUE_KEY = "queue";
|
|
3
|
+
/** Names the ids of the stored forget requests, a JSON list. */
|
|
4
|
+
const FORGETS_KEY = "forgets";
|
|
3
5
|
const MAX_ENVELOPE_EVENTS = 100;
|
|
4
6
|
/**
|
|
5
7
|
* The largest request body, under 64 KiB with some margin. A keepalive request and the intake both refuse a larger
|
|
@@ -20,21 +22,13 @@ export function newQueue({ storage, reportError, }) {
|
|
|
20
22
|
* throw.
|
|
21
23
|
*/
|
|
22
24
|
async function read() {
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
queued = JSON.parse(stored);
|
|
27
|
-
}
|
|
28
|
-
catch {
|
|
29
|
-
// The check below reports its own error and drops the parser's error. The parser's message quotes the stored
|
|
30
|
-
// text, which may hold an id or a page.
|
|
31
|
-
}
|
|
32
|
-
if (!Array.isArray(queued)) {
|
|
33
|
-
reportError(new Error('artel: the stored queue is not a JSON list, so it was dropped'));
|
|
25
|
+
const queued = parseQueue(await storage.get(QUEUE_KEY));
|
|
26
|
+
if (queued === undefined) {
|
|
27
|
+
reportError(new Error("artel: the stored queue is not a JSON list, so it was dropped"));
|
|
34
28
|
await write([]);
|
|
35
29
|
return [];
|
|
36
30
|
}
|
|
37
|
-
return queued
|
|
31
|
+
return queued;
|
|
38
32
|
}
|
|
39
33
|
async function write(items) {
|
|
40
34
|
await storage.set(QUEUE_KEY, JSON.stringify(items));
|
|
@@ -59,6 +53,22 @@ export function newQueue({ storage, reportError, }) {
|
|
|
59
53
|
const gone = new Set([...droppedOptOuts, ...dropped]);
|
|
60
54
|
return { kept: items.filter((item) => !gone.has(item)), dropped: unsent(dropped) };
|
|
61
55
|
}
|
|
56
|
+
/** Returns the stored forget requests. A value that is no JSON list reads as none, and only its strings count. */
|
|
57
|
+
async function readForgets() {
|
|
58
|
+
let bodies;
|
|
59
|
+
try {
|
|
60
|
+
bodies = JSON.parse((await storage.get(FORGETS_KEY)) ?? "[]");
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return [];
|
|
64
|
+
}
|
|
65
|
+
return Array.isArray(bodies)
|
|
66
|
+
? bodies.filter((body) => typeof body === "string")
|
|
67
|
+
: [];
|
|
68
|
+
}
|
|
69
|
+
async function writeForgets(ids) {
|
|
70
|
+
await storage.set(FORGETS_KEY, JSON.stringify(ids));
|
|
71
|
+
}
|
|
62
72
|
async function update(change) {
|
|
63
73
|
await write(change(await read()));
|
|
64
74
|
}
|
|
@@ -115,18 +125,21 @@ export function newQueue({ storage, reportError, }) {
|
|
|
115
125
|
seal: async (qid, terms, identity) => {
|
|
116
126
|
const items = await read();
|
|
117
127
|
const item = items.find((candidate) => candidate.qid === qid);
|
|
118
|
-
if (item === undefined ||
|
|
128
|
+
if (item === undefined ||
|
|
129
|
+
!isFree(item, terms) ||
|
|
130
|
+
(item.awaitsId === true && identity === undefined)) {
|
|
119
131
|
return undefined;
|
|
120
132
|
}
|
|
121
133
|
if (item.awaitsId === true && identity !== undefined) {
|
|
122
|
-
// The browser, the session and the id go after the other fields and the events. The body stored
|
|
123
|
-
// keeps that order on every attempt.
|
|
134
|
+
// The browser, the session and the id with its kind go after the other fields and the events. The body stored
|
|
135
|
+
// at this seal keeps that order on every attempt.
|
|
124
136
|
const { session, ...fields } = item.envelope;
|
|
125
137
|
item.envelope = {
|
|
126
138
|
...fields,
|
|
127
139
|
...(identity.browser !== undefined && { browser: identity.browser }),
|
|
128
140
|
session,
|
|
129
141
|
id: identity.id,
|
|
142
|
+
id_kind: identity.id_kind,
|
|
130
143
|
};
|
|
131
144
|
delete item.awaitsId;
|
|
132
145
|
}
|
|
@@ -149,8 +162,33 @@ export function newQueue({ storage, reportError, }) {
|
|
|
149
162
|
removeId: (id) => removeWhere((item) => item.envelope.id === id),
|
|
150
163
|
removeIdentified: async () => unsent(await removeWhere((item) => item.envelope.id !== undefined || item.awaitsId === true)),
|
|
151
164
|
removeAllButOptOuts: async () => unsent(await removeWhere((item) => item.isOptOut !== true)),
|
|
165
|
+
addForget: async (id) => {
|
|
166
|
+
const ids = await readForgets();
|
|
167
|
+
if (!ids.includes(id)) {
|
|
168
|
+
await writeForgets([...ids, id]);
|
|
169
|
+
}
|
|
170
|
+
},
|
|
171
|
+
forgets: readForgets,
|
|
172
|
+
holdsRequests: async () => (parseQueue(await storage.get(QUEUE_KEY))?.length ?? 0) > 0 ||
|
|
173
|
+
(await readForgets()).length > 0,
|
|
174
|
+
removeForget: async (id) => writeForgets((await readForgets()).filter((stored) => stored !== id)),
|
|
152
175
|
};
|
|
153
176
|
}
|
|
177
|
+
/**
|
|
178
|
+
* Returns the envelopes of a stored queue, oldest first, or undefined for a value that is no JSON list. It skips an item
|
|
179
|
+
* without a queue id and an envelope with a list of events.
|
|
180
|
+
*/
|
|
181
|
+
export function parseQueue(stored) {
|
|
182
|
+
let queued;
|
|
183
|
+
try {
|
|
184
|
+
queued = JSON.parse(stored ?? "[]");
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
// The caller reports a queue that is no list. The parser's message quotes the stored text, which may hold an id or
|
|
188
|
+
// a page, so it goes nowhere.
|
|
189
|
+
}
|
|
190
|
+
return Array.isArray(queued) ? queued.filter(isQueuedEnvelope) : undefined;
|
|
191
|
+
}
|
|
154
192
|
/** Returns the envelopes no seal stored a body for, which no request carried to the intake. */
|
|
155
193
|
function unsent(items) {
|
|
156
194
|
return items.filter((item) => item.body === undefined);
|
|
@@ -161,7 +199,10 @@ function unsent(items) {
|
|
|
161
199
|
*/
|
|
162
200
|
function isFree(item, { holder, now, until }) {
|
|
163
201
|
const { leasedUntil } = item;
|
|
164
|
-
return leasedUntil === undefined ||
|
|
202
|
+
return (leasedUntil === undefined ||
|
|
203
|
+
item.leasedBy === holder ||
|
|
204
|
+
leasedUntil <= now ||
|
|
205
|
+
leasedUntil > until);
|
|
165
206
|
}
|
|
166
207
|
function sameFields(envelope, fields) {
|
|
167
208
|
const { events: _, ...envelopeFields } = envelope;
|
|
@@ -174,13 +215,19 @@ function fits(envelope, event) {
|
|
|
174
215
|
const withEvent = { ...envelope, events: [...envelope.events, event] };
|
|
175
216
|
return new TextEncoder().encode(JSON.stringify(withEvent)).length <= MAX_ENVELOPE_BYTES;
|
|
176
217
|
}
|
|
177
|
-
|
|
178
|
-
|
|
218
|
+
/** Returns `byteCount` random bytes, 8 by default, as lowercase hex. */
|
|
219
|
+
export function newRandomId(byteCount = 8) {
|
|
220
|
+
const bytes = crypto.getRandomValues(new Uint8Array(byteCount));
|
|
221
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
179
222
|
}
|
|
180
223
|
function isQueuedEnvelope(value) {
|
|
181
|
-
if (typeof value !==
|
|
224
|
+
if (typeof value !== "object" ||
|
|
225
|
+
value === null ||
|
|
226
|
+
typeof Reflect.get(value, "qid") !== "string") {
|
|
182
227
|
return false;
|
|
183
228
|
}
|
|
184
|
-
const envelope = Reflect.get(value,
|
|
185
|
-
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")));
|
|
186
233
|
}
|
package/dist/stateFields.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { AnalyticsState, Mode } from
|
|
2
|
-
import { Platform, type Envelope } 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. */
|
|
@@ -14,17 +14,18 @@ export interface StateFields {
|
|
|
14
14
|
product: ProductFields;
|
|
15
15
|
/** Whether the install ages go exact, rather than as the lowest value of their bucket. */
|
|
16
16
|
isAgeExact: boolean;
|
|
17
|
-
/**
|
|
18
|
-
|
|
17
|
+
/** The kind of id an envelope carries, with the browser, or undefined for a state that names no user. */
|
|
18
|
+
idKind: IdKind | undefined;
|
|
19
19
|
/** Whether an event may carry its page and referrer. The intake keeps them only from a site channel. */
|
|
20
20
|
mayCarryPage: boolean;
|
|
21
21
|
}
|
|
22
|
-
|
|
22
|
+
export declare function isAnalyticsState(value: unknown): value is AnalyticsState;
|
|
23
|
+
/** Tells whether a channel of `mode` takes `state`: a state up to its mode. A mode that does not exist is anonymous. */
|
|
23
24
|
export declare function channelTakes(mode: Mode, state: unknown): state is AnalyticsState;
|
|
24
25
|
/** Returns whether events of this build may carry a page, which the intake keeps only from a site channel. */
|
|
25
|
-
export declare function carriesPage(build: Pick<Build,
|
|
26
|
+
export declare function carriesPage(build: Pick<Build, "platform">): boolean;
|
|
26
27
|
/**
|
|
27
|
-
* Returns what the collector sends in `state` for this build and these languages. Only
|
|
28
|
+
* Returns what the collector sends in `state` for this build and these languages. Only a state with an id carries the
|
|
28
29
|
* full languages and the exact ages: with the platform and version they can single out a user, so they go only with the
|
|
29
30
|
* consent the id needs.
|
|
30
31
|
*/
|
package/dist/stateFields.js
CHANGED
|
@@ -1,23 +1,40 @@
|
|
|
1
|
-
import { AnalyticsState, Mode } from
|
|
2
|
-
import { Platform } from
|
|
3
|
-
import { primaryLanguage } from
|
|
4
|
-
/**
|
|
1
|
+
import { AnalyticsState, Mode } from "./collectorTypes.js";
|
|
2
|
+
import { Platform } from "./envelope.js";
|
|
3
|
+
import { primaryLanguage } from "./fields.js";
|
|
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
|
+
const MODE_RANKS = new Map([
|
|
6
|
+
[Mode.Anonymous, 0],
|
|
7
|
+
[Mode.Pseudonymous, 1],
|
|
8
|
+
[Mode.Identified, 2],
|
|
9
|
+
]);
|
|
10
|
+
const STATE_RANKS = new Map([
|
|
11
|
+
[AnalyticsState.OptedOut, 0],
|
|
12
|
+
[AnalyticsState.Anonymous, 0],
|
|
13
|
+
[AnalyticsState.Pseudonymous, 1],
|
|
14
|
+
[AnalyticsState.Identified, 2],
|
|
15
|
+
]);
|
|
16
|
+
export function isAnalyticsState(value) {
|
|
17
|
+
return STATE_RANKS.has(value);
|
|
18
|
+
}
|
|
19
|
+
/** Tells whether a channel of `mode` takes `state`: a state up to its mode. A mode that does not exist is anonymous. */
|
|
5
20
|
export function channelTakes(mode, state) {
|
|
6
|
-
return (
|
|
7
|
-
(state !== AnalyticsState.Identified || mode === Mode.Identified));
|
|
21
|
+
return (STATE_RANKS.get(state) ?? Number.POSITIVE_INFINITY) <= (MODE_RANKS.get(mode) ?? 0);
|
|
8
22
|
}
|
|
9
23
|
/** Returns whether events of this build may carry a page, which the intake keeps only from a site channel. */
|
|
10
24
|
export function carriesPage(build) {
|
|
11
25
|
return build.platform === Platform.Web;
|
|
12
26
|
}
|
|
13
27
|
/**
|
|
14
|
-
* Returns what the collector sends in `state` for this build and these languages. Only
|
|
28
|
+
* Returns what the collector sends in `state` for this build and these languages. Only a state with an id carries the
|
|
15
29
|
* full languages and the exact ages: with the platform and version they can single out a user, so they go only with the
|
|
16
30
|
* consent the id needs.
|
|
17
31
|
*/
|
|
18
32
|
export function fieldsForState({ state, build, browserLanguage, uiLanguage, }) {
|
|
19
|
-
const
|
|
20
|
-
|
|
33
|
+
const idKind = state === AnalyticsState.Pseudonymous || state === AnalyticsState.Identified
|
|
34
|
+
? state
|
|
35
|
+
: undefined;
|
|
36
|
+
const isNamed = idKind !== undefined;
|
|
37
|
+
const shape = (tag) => tag === undefined || isNamed ? tag : primaryLanguage(tag);
|
|
21
38
|
const shapedBrowserLanguage = shape(browserLanguage);
|
|
22
39
|
const shapedUiLanguage = shape(uiLanguage);
|
|
23
40
|
const recordsEvents = state !== AnalyticsState.OptedOut;
|
|
@@ -29,8 +46,8 @@ export function fieldsForState({ state, build, browserLanguage, uiLanguage, }) {
|
|
|
29
46
|
...(shapedBrowserLanguage !== undefined && { browser_language: shapedBrowserLanguage }),
|
|
30
47
|
...(shapedUiLanguage !== undefined && { ui_language: shapedUiLanguage }),
|
|
31
48
|
},
|
|
32
|
-
isAgeExact:
|
|
33
|
-
|
|
49
|
+
isAgeExact: isNamed,
|
|
50
|
+
idKind,
|
|
34
51
|
mayCarryPage: recordsEvents && carriesPage(build),
|
|
35
52
|
};
|
|
36
53
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
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";
|
|
5
|
+
/** One event as a product tracked it. */
|
|
6
|
+
export interface RecordedEvent {
|
|
7
|
+
name: string;
|
|
8
|
+
params?: EventParams;
|
|
9
|
+
}
|
|
10
|
+
/** A collector that keeps in memory what it would send, for a product's own tests. */
|
|
11
|
+
export type RecordingCollector<M extends Mode = Mode> = Collector<M> & {
|
|
12
|
+
/** The events it took, oldest first. */
|
|
13
|
+
readonly events: RecordedEvent[];
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Returns a collector of channel mode `mode`, `anonymous` by default, that sends nothing and records each event the
|
|
17
|
+
* real collector would send. Its user starts in the anonymous state. It refuses an event `track` refuses, a state above
|
|
18
|
+
* the mode and an id `forget` refuses, with the same report to `onError`. It records `opted_out` at the opt-out, and
|
|
19
|
+
* nothing in the opted_out state. It keeps one version: `installed` records once, and `updated` only while neither of
|
|
20
|
+
* them recorded. It drops a call with `throttleMs` as `track` does, by `clock`. `uninstallParams` resolves to undefined.
|
|
21
|
+
*/
|
|
22
|
+
export declare function newRecordingCollector<M extends Mode = typeof Mode.Anonymous>(mode?: M, { onError, clock, }?: {
|
|
23
|
+
onError?: (error: Error) => void;
|
|
24
|
+
/** The clock of the `throttleMs` windows of `track`, the system's by default. */
|
|
25
|
+
clock?: Clock;
|
|
26
|
+
}): RecordingCollector<M>;
|
|
27
|
+
/**
|
|
28
|
+
* Resolves to the events a collector of channel `key` holds queued in `storage`, oldest first, so a product's test reads
|
|
29
|
+
* them without the queue's stored form. It writes nothing, and reads a stored queue that is no JSON list as empty.
|
|
30
|
+
*/
|
|
31
|
+
export declare function queuedEvents(storage: StorageAdapter, key: string): Promise<RecordedEvent[]>;
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { systemClock } from "./clock.js";
|
|
2
|
+
import { AnalyticsState, Mode } from "./collectorTypes.js";
|
|
3
|
+
import { acceptedEvent } from "./eventCheck.js";
|
|
4
|
+
import { isUsableId, quoted, reportTo } from "./hostInput.js";
|
|
5
|
+
import { parseQueue, QUEUE_KEY } from "./queue.js";
|
|
6
|
+
import { channelTakes } from "./stateFields.js";
|
|
7
|
+
import { newChannelStorage } from "./storage.js";
|
|
8
|
+
import { newThrottle } from "./throttle.js";
|
|
9
|
+
/**
|
|
10
|
+
* Returns a collector of channel mode `mode`, `anonymous` by default, that sends nothing and records each event the
|
|
11
|
+
* real collector would send. Its user starts in the anonymous state. It refuses an event `track` refuses, a state above
|
|
12
|
+
* the mode and an id `forget` refuses, with the same report to `onError`. It records `opted_out` at the opt-out, and
|
|
13
|
+
* nothing in the opted_out state. It keeps one version: `installed` records once, and `updated` only while neither of
|
|
14
|
+
* them recorded. It drops a call with `throttleMs` as `track` does, by `clock`. `uninstallParams` resolves to undefined.
|
|
15
|
+
*/
|
|
16
|
+
export function newRecordingCollector(mode, { onError, clock = systemClock, } = {}) {
|
|
17
|
+
const channelMode = mode ?? Mode.Anonymous;
|
|
18
|
+
const reportError = (error) => reportTo(onError, error);
|
|
19
|
+
const events = [];
|
|
20
|
+
let state = AnalyticsState.Anonymous;
|
|
21
|
+
let isInstalled = false;
|
|
22
|
+
let isVersionMarked = false;
|
|
23
|
+
const throttle = newThrottle();
|
|
24
|
+
const record = (name, params) => {
|
|
25
|
+
if (state === AnalyticsState.OptedOut) {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
events.push({ name, ...(params !== undefined && { params }) });
|
|
29
|
+
return true;
|
|
30
|
+
};
|
|
31
|
+
return {
|
|
32
|
+
events,
|
|
33
|
+
track: async (name, given, options) => {
|
|
34
|
+
const now = clock.now();
|
|
35
|
+
const event = acceptedEvent({ name, given, options, reportError });
|
|
36
|
+
if (event === undefined) {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
const call = { name, throttleMs: event.throttleMs, now };
|
|
40
|
+
if (!throttle.isDropped(call) && record(name, event.params)) {
|
|
41
|
+
throttle.went(call);
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
installed: async () => {
|
|
45
|
+
if (!isInstalled && state !== AnalyticsState.OptedOut) {
|
|
46
|
+
isInstalled = true;
|
|
47
|
+
isVersionMarked = true;
|
|
48
|
+
record("installed");
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
updated: async () => {
|
|
52
|
+
if (!isVersionMarked && state !== AnalyticsState.OptedOut) {
|
|
53
|
+
isVersionMarked = true;
|
|
54
|
+
record("updated");
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
setState: async (next) => {
|
|
58
|
+
if (channelTakes(channelMode, next)) {
|
|
59
|
+
if (next === AnalyticsState.OptedOut) {
|
|
60
|
+
record(AnalyticsState.OptedOut);
|
|
61
|
+
}
|
|
62
|
+
state = next;
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
reportError(new TypeError(`artel: a channel of mode ${quoted(channelMode)} takes no state ${quoted(next)}`));
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
getState: async () => state,
|
|
69
|
+
flush: async () => undefined,
|
|
70
|
+
forget: async (id) => {
|
|
71
|
+
if (!isUsableId(id)) {
|
|
72
|
+
reportError(new TypeError("artel: forget takes an id of 1 to 64 characters"));
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
uninstallParams: async () => undefined,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Resolves to the events a collector of channel `key` holds queued in `storage`, oldest first, so a product's test reads
|
|
80
|
+
* them without the queue's stored form. It writes nothing, and reads a stored queue that is no JSON list as empty.
|
|
81
|
+
*/
|
|
82
|
+
export async function queuedEvents(storage, key) {
|
|
83
|
+
const queued = parseQueue(await newChannelStorage(storage, key).get(QUEUE_KEY)) ?? [];
|
|
84
|
+
return queued.flatMap(({ envelope }) => envelope.events.map(({ name, params }) => ({ name, ...(params !== undefined && { params }) })));
|
|
85
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { TrackOptions } from "./collectorTypes.js";
|
|
2
|
+
/**
|
|
3
|
+
* Remembers in memory when each event name last went from a call with `throttleMs`. The window is leading-edge: the
|
|
4
|
+
* first such call goes, and a later one of the name goes only once its `throttleMs` passed since the last one that
|
|
5
|
+
* went. A call without `throttleMs` opens no window and is never dropped.
|
|
6
|
+
*/
|
|
7
|
+
export interface Throttle {
|
|
8
|
+
/**
|
|
9
|
+
* Tells whether a call of `name` at `now` falls inside the window of the name. False while `throttleMs` is
|
|
10
|
+
* undefined.
|
|
11
|
+
*/
|
|
12
|
+
isDropped(call: ThrottledCall): boolean;
|
|
13
|
+
/** Opens the window of `name` at `now` for a call with `throttleMs` that went. */
|
|
14
|
+
went(call: ThrottledCall): void;
|
|
15
|
+
}
|
|
16
|
+
/** One `track` call as the throttle reads it. */
|
|
17
|
+
interface ThrottledCall {
|
|
18
|
+
name: string;
|
|
19
|
+
throttleMs: number | undefined;
|
|
20
|
+
now: number;
|
|
21
|
+
}
|
|
22
|
+
export declare function newThrottle(): Throttle;
|
|
23
|
+
/**
|
|
24
|
+
* Returns `{ throttleMs }` from `track`'s options, with `throttleMs` undefined when they name none. Returns undefined
|
|
25
|
+
* when `throttleMs` is no finite number from 0, when the options are no object, or when reading them throws.
|
|
26
|
+
*/
|
|
27
|
+
export declare function throttleOf(options: TrackOptions | undefined): {
|
|
28
|
+
throttleMs: number | undefined;
|
|
29
|
+
} | undefined;
|
|
30
|
+
export {};
|
package/dist/throttle.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export function newThrottle() {
|
|
2
|
+
const lastWent = new Map();
|
|
3
|
+
return {
|
|
4
|
+
isDropped: ({ name, throttleMs, now }) => {
|
|
5
|
+
const last = lastWent.get(name);
|
|
6
|
+
// The window spans `throttleMs` on either side of the last time, so a clock set back never holds it open until
|
|
7
|
+
// the clock catches up.
|
|
8
|
+
return throttleMs !== undefined && last !== undefined && Math.abs(now - last) < throttleMs;
|
|
9
|
+
},
|
|
10
|
+
went: ({ name, throttleMs, now }) => {
|
|
11
|
+
if (throttleMs !== undefined) {
|
|
12
|
+
lastWent.set(name, now);
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Returns `{ throttleMs }` from `track`'s options, with `throttleMs` undefined when they name none. Returns undefined
|
|
19
|
+
* when `throttleMs` is no finite number from 0, when the options are no object, or when reading them throws.
|
|
20
|
+
*/
|
|
21
|
+
export function throttleOf(options) {
|
|
22
|
+
const value = options;
|
|
23
|
+
if (value === undefined) {
|
|
24
|
+
return { throttleMs: undefined };
|
|
25
|
+
}
|
|
26
|
+
let throttleMs;
|
|
27
|
+
try {
|
|
28
|
+
// An untyped host can pass options of any kind, such as ones with a getter that throws.
|
|
29
|
+
throttleMs =
|
|
30
|
+
typeof value === "object" && value !== null ? Reflect.get(value, "throttleMs") : Number.NaN;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
if (throttleMs === undefined) {
|
|
36
|
+
return { throttleMs: undefined };
|
|
37
|
+
}
|
|
38
|
+
return typeof throttleMs === "number" && Number.isFinite(throttleMs) && throttleMs >= 0
|
|
39
|
+
? { throttleMs }
|
|
40
|
+
: undefined;
|
|
41
|
+
}
|