@baukit/analytics-core 0.7.2 → 0.7.4
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/package.json +2 -1
- package/src/client.test.ts +324 -0
- package/src/client.ts +585 -0
- package/src/index.ts +34 -0
- package/src/scrubber.test.ts +195 -0
- package/src/scrubber.ts +216 -0
- package/src/storage.ts +45 -0
- package/src/transports.ts +25 -0
- package/src/types.ts +114 -0
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { REDACTED_VALUE, scrubErrorEvent, scrubProperties } from './scrubber.js';
|
|
4
|
+
|
|
5
|
+
describe('scrubProperties', () => {
|
|
6
|
+
it('redacts built-in blocked keys at every nesting level', () => {
|
|
7
|
+
const input = {
|
|
8
|
+
email: 'person@example.com',
|
|
9
|
+
displayName: 'Ada',
|
|
10
|
+
nested: {
|
|
11
|
+
auth_token: 'short-token',
|
|
12
|
+
phoneNumber: '+49 123',
|
|
13
|
+
},
|
|
14
|
+
items: [{ shipping_address: 'Main Street' }],
|
|
15
|
+
safe_count: 3,
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
expect(scrubProperties(input)).toEqual({
|
|
19
|
+
email: REDACTED_VALUE,
|
|
20
|
+
displayName: REDACTED_VALUE,
|
|
21
|
+
nested: {
|
|
22
|
+
auth_token: REDACTED_VALUE,
|
|
23
|
+
phoneNumber: REDACTED_VALUE,
|
|
24
|
+
},
|
|
25
|
+
items: [{ shipping_address: REDACTED_VALUE }],
|
|
26
|
+
safe_count: 3,
|
|
27
|
+
});
|
|
28
|
+
expect(input.email).toBe('person@example.com');
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('redacts email-shaped, JWT-shaped, long hex, and long base64 values', () => {
|
|
32
|
+
const scrubbed = scrubProperties({
|
|
33
|
+
contact: 'Please contact person@example.com today',
|
|
34
|
+
credential: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.signature123',
|
|
35
|
+
hexadecimal: '0123456789abcdef0123456789abcdef',
|
|
36
|
+
encoded: 'VGhpcy1pc19hX3ZlcnlfbG9uZ19zZWNyZXQ',
|
|
37
|
+
ordinary: 'onboarding_completed',
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
expect(scrubbed).toEqual({
|
|
41
|
+
contact: REDACTED_VALUE,
|
|
42
|
+
credential: REDACTED_VALUE,
|
|
43
|
+
hexadecimal: REDACTED_VALUE,
|
|
44
|
+
encoded: REDACTED_VALUE,
|
|
45
|
+
ordinary: 'onboarding_completed',
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('supports product-specific blocked-key extensions', () => {
|
|
50
|
+
expect(
|
|
51
|
+
scrubProperties(
|
|
52
|
+
{
|
|
53
|
+
patientIdentifier: 'short-but-sensitive',
|
|
54
|
+
safe: true,
|
|
55
|
+
},
|
|
56
|
+
{ blockedKeys: ['patient_identifier'] },
|
|
57
|
+
),
|
|
58
|
+
).toEqual({ patientIdentifier: REDACTED_VALUE, safe: true });
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('fails closed for cycles and non-serializable object values', () => {
|
|
62
|
+
const cyclic: Record<string, unknown> = {};
|
|
63
|
+
cyclic['self'] = cyclic;
|
|
64
|
+
|
|
65
|
+
expect(scrubProperties({ cyclic, date: new Date(0) })).toEqual({
|
|
66
|
+
cyclic: { self: REDACTED_VALUE },
|
|
67
|
+
date: REDACTED_VALUE,
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('redacts exact keys without matching longer keys that contain them', () => {
|
|
72
|
+
expect(
|
|
73
|
+
scrubProperties(
|
|
74
|
+
{
|
|
75
|
+
ip: '203.0.113.7',
|
|
76
|
+
ipAddress: '203.0.113.7',
|
|
77
|
+
'X-Forwarded-For': '203.0.113.7',
|
|
78
|
+
zip_code_count: 1,
|
|
79
|
+
description_length: 12,
|
|
80
|
+
q: 'free text',
|
|
81
|
+
query_count: 2,
|
|
82
|
+
},
|
|
83
|
+
{ exactBlockedKeys: ['q'] },
|
|
84
|
+
),
|
|
85
|
+
).toEqual({
|
|
86
|
+
ip: REDACTED_VALUE,
|
|
87
|
+
ipAddress: REDACTED_VALUE,
|
|
88
|
+
'X-Forwarded-For': REDACTED_VALUE,
|
|
89
|
+
zip_code_count: 1,
|
|
90
|
+
description_length: 12,
|
|
91
|
+
q: REDACTED_VALUE,
|
|
92
|
+
query_count: 2,
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
describe('scrubErrorEvent', () => {
|
|
98
|
+
const eventId = '0123456789abcdef0123456789abcdef';
|
|
99
|
+
const traceId = 'fedcba9876543210fedcba9876543210';
|
|
100
|
+
|
|
101
|
+
function crashEvent() {
|
|
102
|
+
return {
|
|
103
|
+
event_id: eventId,
|
|
104
|
+
message: 'Sync failed for person@example.com',
|
|
105
|
+
contexts: { trace: { trace_id: traceId, span_id: '0123456789abcdef' } },
|
|
106
|
+
exception: {
|
|
107
|
+
values: [
|
|
108
|
+
{
|
|
109
|
+
type: 'TypeError',
|
|
110
|
+
value: 'x is undefined',
|
|
111
|
+
stacktrace: {
|
|
112
|
+
frames: [
|
|
113
|
+
{
|
|
114
|
+
filename: 'app:///index.bundle',
|
|
115
|
+
function: 'renderScreen',
|
|
116
|
+
lineno: 12,
|
|
117
|
+
vars: { password: 'secret' },
|
|
118
|
+
},
|
|
119
|
+
],
|
|
120
|
+
},
|
|
121
|
+
},
|
|
122
|
+
],
|
|
123
|
+
},
|
|
124
|
+
request: {
|
|
125
|
+
url: 'https://api.example.test/items',
|
|
126
|
+
headers: { Authorization: 'Bearer abc' },
|
|
127
|
+
cookies: 'session=abc',
|
|
128
|
+
query_string: 'q=secret',
|
|
129
|
+
data: { note: 'free text' },
|
|
130
|
+
},
|
|
131
|
+
user: { id: 'user-1', email: 'person@example.com', ip_address: '203.0.113.7' },
|
|
132
|
+
breadcrumbs: [{ category: 'fetch', data: { url: '/items?q=secret' } }],
|
|
133
|
+
sdk: { name: 'sentry.javascript.react-native', packages: [{ name: 'npm:@sentry/core' }] },
|
|
134
|
+
extra: { accessToken: 'abc', attempt: 2 },
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
it('keeps crash identifiers and stack frames while redacting request payloads', () => {
|
|
139
|
+
const input = crashEvent();
|
|
140
|
+
|
|
141
|
+
expect(scrubErrorEvent(input)).toEqual({
|
|
142
|
+
event_id: eventId,
|
|
143
|
+
message: REDACTED_VALUE,
|
|
144
|
+
contexts: { trace: { trace_id: traceId, span_id: '0123456789abcdef' } },
|
|
145
|
+
exception: {
|
|
146
|
+
values: [
|
|
147
|
+
{
|
|
148
|
+
type: 'TypeError',
|
|
149
|
+
value: 'x is undefined',
|
|
150
|
+
stacktrace: {
|
|
151
|
+
frames: [
|
|
152
|
+
{
|
|
153
|
+
filename: 'app:///index.bundle',
|
|
154
|
+
function: 'renderScreen',
|
|
155
|
+
lineno: 12,
|
|
156
|
+
vars: REDACTED_VALUE,
|
|
157
|
+
},
|
|
158
|
+
],
|
|
159
|
+
},
|
|
160
|
+
},
|
|
161
|
+
],
|
|
162
|
+
},
|
|
163
|
+
request: {
|
|
164
|
+
url: 'https://api.example.test/items',
|
|
165
|
+
headers: REDACTED_VALUE,
|
|
166
|
+
cookies: REDACTED_VALUE,
|
|
167
|
+
query_string: REDACTED_VALUE,
|
|
168
|
+
data: REDACTED_VALUE,
|
|
169
|
+
},
|
|
170
|
+
user: { id: 'user-1', email: REDACTED_VALUE, ip_address: REDACTED_VALUE },
|
|
171
|
+
breadcrumbs: [{ category: 'fetch', data: REDACTED_VALUE }],
|
|
172
|
+
sdk: { name: 'sentry.javascript.react-native', packages: [{ name: 'npm:@sentry/core' }] },
|
|
173
|
+
extra: { accessToken: REDACTED_VALUE, attempt: 2 },
|
|
174
|
+
});
|
|
175
|
+
expect(input).toEqual(crashEvent());
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it('still redacts non-string values under preserved keys', () => {
|
|
179
|
+
expect(scrubErrorEvent({ function: { password: 'secret' } })).toEqual({
|
|
180
|
+
function: { password: REDACTED_VALUE },
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it('applies product key extensions', () => {
|
|
185
|
+
expect(
|
|
186
|
+
scrubErrorEvent(
|
|
187
|
+
{ extra: { mealNotes: 'text', q: 'text' } },
|
|
188
|
+
{
|
|
189
|
+
blockedKeys: ['notes'],
|
|
190
|
+
exactBlockedKeys: ['q'],
|
|
191
|
+
},
|
|
192
|
+
),
|
|
193
|
+
).toEqual({ extra: { mealNotes: REDACTED_VALUE, q: REDACTED_VALUE } });
|
|
194
|
+
});
|
|
195
|
+
});
|
package/src/scrubber.ts
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
export const REDACTED_VALUE = '[redacted]' as const;
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_BLOCKED_KEYS = [
|
|
4
|
+
'email',
|
|
5
|
+
'name',
|
|
6
|
+
'token',
|
|
7
|
+
'password',
|
|
8
|
+
'authorization',
|
|
9
|
+
'cookie',
|
|
10
|
+
'phone',
|
|
11
|
+
'address',
|
|
12
|
+
] as const;
|
|
13
|
+
|
|
14
|
+
export const DEFAULT_EXACT_BLOCKED_KEYS = [
|
|
15
|
+
'ip',
|
|
16
|
+
'ip_address',
|
|
17
|
+
'remote_addr',
|
|
18
|
+
'x_forwarded_for',
|
|
19
|
+
'x_real_ip',
|
|
20
|
+
] as const;
|
|
21
|
+
|
|
22
|
+
export const ERROR_EVENT_BLOCKED_KEYS = [
|
|
23
|
+
'headers',
|
|
24
|
+
'data',
|
|
25
|
+
'query_string',
|
|
26
|
+
'body',
|
|
27
|
+
'vars',
|
|
28
|
+
'geo',
|
|
29
|
+
'env',
|
|
30
|
+
] as const;
|
|
31
|
+
|
|
32
|
+
export const ERROR_EVENT_PRESERVED_KEYS = [
|
|
33
|
+
'event_id',
|
|
34
|
+
'trace_id',
|
|
35
|
+
'span_id',
|
|
36
|
+
'parent_span_id',
|
|
37
|
+
'debug_id',
|
|
38
|
+
'code_id',
|
|
39
|
+
'filename',
|
|
40
|
+
'abs_path',
|
|
41
|
+
'function',
|
|
42
|
+
'module',
|
|
43
|
+
] as const;
|
|
44
|
+
|
|
45
|
+
export interface ScrubberOptions {
|
|
46
|
+
/** Terms redacted when a normalized key contains them. */
|
|
47
|
+
readonly blockedKeys?: readonly string[];
|
|
48
|
+
/** Keys redacted only when the normalized key equals them. */
|
|
49
|
+
readonly exactBlockedKeys?: readonly string[];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
interface ScrubRules {
|
|
53
|
+
readonly blockedKeys: readonly string[];
|
|
54
|
+
readonly exactBlockedKeys: ReadonlySet<string>;
|
|
55
|
+
readonly preservedKeys: ReadonlySet<string>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const VALUE_ONLY_RULES: ScrubRules = {
|
|
59
|
+
blockedKeys: [],
|
|
60
|
+
exactBlockedKeys: new Set(),
|
|
61
|
+
preservedKeys: new Set(),
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const EMAIL_PATTERN = /(?:^|\s|[<(])[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+(?:$|\s|[>),.;:!?])/i;
|
|
65
|
+
const JWT_PATTERN = /^[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}$/;
|
|
66
|
+
const LONG_HEX_PATTERN = /^[A-Fa-f0-9]{32,}$/;
|
|
67
|
+
const LONG_BASE64_PATTERN = /^[A-Za-z0-9+/_-]{32,}={0,2}$/;
|
|
68
|
+
|
|
69
|
+
function normalizeKey(key: string): string {
|
|
70
|
+
return key.toLowerCase().replaceAll(/[^a-z0-9]/g, '');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function normalizeKeys(keys: readonly string[]): string[] {
|
|
74
|
+
return keys.map(normalizeKey).filter((key) => key.length > 0);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function createRules(
|
|
78
|
+
options: ScrubberOptions,
|
|
79
|
+
extraExactKeys: readonly string[] = [],
|
|
80
|
+
preservedKeys: readonly string[] = [],
|
|
81
|
+
): ScrubRules {
|
|
82
|
+
return {
|
|
83
|
+
blockedKeys: normalizeKeys([...DEFAULT_BLOCKED_KEYS, ...(options.blockedKeys ?? [])]),
|
|
84
|
+
exactBlockedKeys: new Set(
|
|
85
|
+
normalizeKeys([
|
|
86
|
+
...DEFAULT_EXACT_BLOCKED_KEYS,
|
|
87
|
+
...extraExactKeys,
|
|
88
|
+
...(options.exactBlockedKeys ?? []),
|
|
89
|
+
]),
|
|
90
|
+
),
|
|
91
|
+
preservedKeys: new Set(normalizeKeys(preservedKeys)),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function isBlockedKey(normalizedKey: string, rules: ScrubRules): boolean {
|
|
96
|
+
return (
|
|
97
|
+
rules.exactBlockedKeys.has(normalizedKey) ||
|
|
98
|
+
rules.blockedKeys.some((blockedKey) => normalizedKey.includes(blockedKey))
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function isSensitiveString(value: string): boolean {
|
|
103
|
+
const candidate = value.trim();
|
|
104
|
+
return (
|
|
105
|
+
EMAIL_PATTERN.test(candidate) ||
|
|
106
|
+
JWT_PATTERN.test(candidate) ||
|
|
107
|
+
LONG_HEX_PATTERN.test(candidate) ||
|
|
108
|
+
LONG_BASE64_PATTERN.test(candidate)
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function scrubValue(value: unknown, rules: ScrubRules, ancestors: WeakSet<object>): unknown {
|
|
113
|
+
if (typeof value === 'string') {
|
|
114
|
+
return isSensitiveString(value) ? REDACTED_VALUE : value;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (
|
|
118
|
+
value === null ||
|
|
119
|
+
typeof value === 'number' ||
|
|
120
|
+
typeof value === 'boolean' ||
|
|
121
|
+
typeof value === 'undefined'
|
|
122
|
+
) {
|
|
123
|
+
return value;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (typeof value !== 'object') {
|
|
127
|
+
return REDACTED_VALUE;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (ancestors.has(value)) {
|
|
131
|
+
return REDACTED_VALUE;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
ancestors.add(value);
|
|
135
|
+
let result: unknown;
|
|
136
|
+
|
|
137
|
+
if (Array.isArray(value)) {
|
|
138
|
+
result = value.map((item) => scrubValue(item, rules, ancestors));
|
|
139
|
+
} else if (
|
|
140
|
+
Object.getPrototypeOf(value) === Object.prototype ||
|
|
141
|
+
Object.getPrototypeOf(value) === null
|
|
142
|
+
) {
|
|
143
|
+
result = scrubRecord(value as Readonly<Record<string, unknown>>, rules, ancestors);
|
|
144
|
+
} else {
|
|
145
|
+
result = REDACTED_VALUE;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
ancestors.delete(value);
|
|
149
|
+
return result;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function scrubEntry(
|
|
153
|
+
key: string,
|
|
154
|
+
value: unknown,
|
|
155
|
+
rules: ScrubRules,
|
|
156
|
+
ancestors: WeakSet<object>,
|
|
157
|
+
): unknown {
|
|
158
|
+
const normalizedKey = normalizeKey(key);
|
|
159
|
+
if (typeof value === 'string' && rules.preservedKeys.has(normalizedKey)) {
|
|
160
|
+
return value;
|
|
161
|
+
}
|
|
162
|
+
return isBlockedKey(normalizedKey, rules) ? REDACTED_VALUE : scrubValue(value, rules, ancestors);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function scrubRecord(
|
|
166
|
+
properties: Readonly<Record<string, unknown>>,
|
|
167
|
+
rules: ScrubRules,
|
|
168
|
+
ancestors: WeakSet<object>,
|
|
169
|
+
): Record<string, unknown> {
|
|
170
|
+
const scrubbed: Record<string, unknown> = {};
|
|
171
|
+
|
|
172
|
+
for (const [key, value] of Object.entries(properties)) {
|
|
173
|
+
scrubbed[key] = scrubEntry(key, value, rules, ancestors);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
return scrubbed;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Returns a new object with blocked keys and sensitive string values redacted.
|
|
181
|
+
* Nested objects and arrays are traversed; the input is never mutated.
|
|
182
|
+
*/
|
|
183
|
+
export function scrubProperties(
|
|
184
|
+
properties: Readonly<Record<string, unknown>>,
|
|
185
|
+
options: ScrubberOptions = {},
|
|
186
|
+
): Readonly<Record<string, unknown>> {
|
|
187
|
+
return scrubRoot(properties, createRules(options));
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function scrubRoot(
|
|
191
|
+
record: Readonly<Record<string, unknown>>,
|
|
192
|
+
rules: ScrubRules,
|
|
193
|
+
): Record<string, unknown> {
|
|
194
|
+
const ancestors = new WeakSet();
|
|
195
|
+
ancestors.add(record);
|
|
196
|
+
return scrubRecord(record, rules, ancestors);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Scrubs a crash-report event, such as the object a Sentry `beforeSend` hook receives.
|
|
201
|
+
*
|
|
202
|
+
* Applies the property rules plus {@link ERROR_EVENT_BLOCKED_KEYS}. String values under
|
|
203
|
+
* {@link ERROR_EVENT_PRESERVED_KEYS} stay intact so event and trace IDs and stack frames survive.
|
|
204
|
+
* The top-level `sdk` object keeps its keys and only has its values checked.
|
|
205
|
+
*/
|
|
206
|
+
export function scrubErrorEvent<T extends object>(event: T, options: ScrubberOptions = {}): T {
|
|
207
|
+
const record = event as Readonly<Record<string, unknown>>;
|
|
208
|
+
const scrubbed = scrubRoot(
|
|
209
|
+
record,
|
|
210
|
+
createRules(options, ERROR_EVENT_BLOCKED_KEYS, ERROR_EVENT_PRESERVED_KEYS),
|
|
211
|
+
);
|
|
212
|
+
if ('sdk' in record) {
|
|
213
|
+
scrubbed['sdk'] = scrubValue(record['sdk'], VALUE_ONLY_RULES, new WeakSet([record]));
|
|
214
|
+
}
|
|
215
|
+
return scrubbed as T;
|
|
216
|
+
}
|
package/src/storage.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { AnalyticsStorage } from './types.js';
|
|
2
|
+
|
|
3
|
+
export interface AnalyticsStorageKeys {
|
|
4
|
+
readonly consent: string;
|
|
5
|
+
readonly anonymousId: string;
|
|
6
|
+
readonly userId: string;
|
|
7
|
+
readonly aliasedUserId: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Keys `AnalyticsClient` reads and writes for a `storageKeyPrefix`. */
|
|
11
|
+
export function analyticsStorageKeys(prefix: string): AnalyticsStorageKeys {
|
|
12
|
+
return {
|
|
13
|
+
consent: `${prefix}:consent`,
|
|
14
|
+
anonymousId: `${prefix}:anonymous-id`,
|
|
15
|
+
userId: `${prefix}:user-id`,
|
|
16
|
+
aliasedUserId: `${prefix}:aliased-user-id`,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Small dependency-free storage useful as the default and in tests. */
|
|
21
|
+
export class InMemoryAnalyticsStorage implements AnalyticsStorage {
|
|
22
|
+
readonly #values = new Map<string, string>();
|
|
23
|
+
|
|
24
|
+
public constructor(initialValues: Readonly<Record<string, string>> = {}) {
|
|
25
|
+
for (const [key, value] of Object.entries(initialValues)) {
|
|
26
|
+
this.#values.set(key, value);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
public getItem(key: string): string | undefined {
|
|
31
|
+
return this.#values.get(key);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
public setItem(key: string, value: string): void {
|
|
35
|
+
this.#values.set(key, value);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
public removeItem(key: string): void {
|
|
39
|
+
this.#values.delete(key);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
public snapshot(): Readonly<Record<string, string>> {
|
|
43
|
+
return Object.fromEntries(this.#values);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { AnalyticsEnvelope, AnalyticsEvent, Transport } from './types.js';
|
|
2
|
+
|
|
3
|
+
/** A production-safe transport that intentionally discards every command. */
|
|
4
|
+
export class NoopTransport<E extends AnalyticsEvent = AnalyticsEvent> implements Transport<E> {
|
|
5
|
+
public send(_envelopes: readonly AnalyticsEnvelope<E>[]): void {
|
|
6
|
+
// Discards every envelope.
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** An inspectable transport intended for unit tests and local development. */
|
|
11
|
+
export class InMemoryTransport<E extends AnalyticsEvent = AnalyticsEvent> implements Transport<E> {
|
|
12
|
+
readonly #envelopes: AnalyticsEnvelope<E>[] = [];
|
|
13
|
+
|
|
14
|
+
public get envelopes(): readonly AnalyticsEnvelope<E>[] {
|
|
15
|
+
return [...this.#envelopes];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
public send(envelopes: readonly AnalyticsEnvelope<E>[]): void {
|
|
19
|
+
this.#envelopes.push(...envelopes);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
public clear(): void {
|
|
23
|
+
this.#envelopes.length = 0;
|
|
24
|
+
}
|
|
25
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/** A product-owned, statically typed analytics event. */
|
|
2
|
+
export interface AnalyticsEvent {
|
|
3
|
+
readonly name: string;
|
|
4
|
+
readonly properties: object;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export type ConsentState = 'granted' | 'denied' | 'unknown';
|
|
8
|
+
|
|
9
|
+
/** Traits must be bounded product metadata, never user-provided free text or PII. */
|
|
10
|
+
export type SafeTraits = Readonly<Record<string, unknown>>;
|
|
11
|
+
|
|
12
|
+
export interface AnalyticsPort<E extends AnalyticsEvent> {
|
|
13
|
+
capture(event: E): void;
|
|
14
|
+
identify(userId: string, traits?: SafeTraits): void;
|
|
15
|
+
alias(anonymousId: string, userId: string): void;
|
|
16
|
+
reset(): void;
|
|
17
|
+
setConsent(value: ConsentState): void;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Required metadata stamped onto every captured event. */
|
|
21
|
+
export interface AnalyticsContext {
|
|
22
|
+
readonly schema_version: number;
|
|
23
|
+
readonly app: string;
|
|
24
|
+
readonly app_version: string;
|
|
25
|
+
readonly platform: string;
|
|
26
|
+
readonly environment: string;
|
|
27
|
+
readonly locale: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
type EventPropertyName<Event extends AnalyticsEvent> = Extract<keyof Event['properties'], string>;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* A complete per-event allowlist. Adding an event to a product union makes its
|
|
34
|
+
* allowlist entry a compile-time requirement.
|
|
35
|
+
*/
|
|
36
|
+
export type EventAllowlist<E extends AnalyticsEvent> = {
|
|
37
|
+
readonly [Name in E['name']]: readonly EventPropertyName<Extract<E, { name: Name }>>[];
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
interface BaseEnvelope {
|
|
41
|
+
readonly captured_at: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface CaptureEnvelope<E extends AnalyticsEvent = AnalyticsEvent> extends BaseEnvelope {
|
|
45
|
+
readonly type: 'capture';
|
|
46
|
+
readonly anonymous_id: string;
|
|
47
|
+
readonly user_id?: string;
|
|
48
|
+
readonly event: AnalyticsContext & {
|
|
49
|
+
readonly name: E['name'];
|
|
50
|
+
readonly properties: Readonly<Record<string, unknown>>;
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface IdentifyEnvelope extends BaseEnvelope {
|
|
55
|
+
readonly type: 'identify';
|
|
56
|
+
readonly anonymous_id: string;
|
|
57
|
+
readonly user_id: string;
|
|
58
|
+
readonly traits?: SafeTraits;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface AliasEnvelope extends BaseEnvelope {
|
|
62
|
+
readonly type: 'alias';
|
|
63
|
+
readonly anonymous_id: string;
|
|
64
|
+
readonly user_id: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface ResetEnvelope extends BaseEnvelope {
|
|
68
|
+
readonly type: 'reset';
|
|
69
|
+
readonly previous_anonymous_id: string;
|
|
70
|
+
readonly previous_user_id?: string;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Provider-neutral commands delivered in ordering-preserving batches. */
|
|
74
|
+
export type AnalyticsEnvelope<E extends AnalyticsEvent = AnalyticsEvent> =
|
|
75
|
+
CaptureEnvelope<E> | IdentifyEnvelope | AliasEnvelope | ResetEnvelope;
|
|
76
|
+
|
|
77
|
+
export interface Transport<E extends AnalyticsEvent = AnalyticsEvent> {
|
|
78
|
+
send(envelopes: readonly AnalyticsEnvelope<E>[]): Promise<void> | void;
|
|
79
|
+
/** Purges provider-owned queued commands after consent is denied. */
|
|
80
|
+
clearPending?(): Promise<void> | void;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Synchronous by design so consent can be applied before the first capture call. */
|
|
84
|
+
export interface AnalyticsStorage {
|
|
85
|
+
getItem(key: string): string | undefined;
|
|
86
|
+
setItem(key: string, value: string): void;
|
|
87
|
+
removeItem(key: string): void;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface TransportFailure<E extends AnalyticsEvent = AnalyticsEvent> {
|
|
91
|
+
readonly error: unknown;
|
|
92
|
+
readonly envelopes: readonly AnalyticsEnvelope<E>[];
|
|
93
|
+
readonly attempts: number;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface AnalyticsClientOptions<E extends AnalyticsEvent> {
|
|
97
|
+
readonly context: AnalyticsContext;
|
|
98
|
+
readonly allowlist: EventAllowlist<E>;
|
|
99
|
+
readonly transport?: Transport<E>;
|
|
100
|
+
readonly storage?: AnalyticsStorage;
|
|
101
|
+
readonly storageKeyPrefix?: string;
|
|
102
|
+
readonly uuidFactory?: () => string;
|
|
103
|
+
readonly blockedKeys?: readonly string[];
|
|
104
|
+
readonly exactBlockedKeys?: readonly string[];
|
|
105
|
+
readonly maxQueueSize?: number;
|
|
106
|
+
readonly flushBatchSize?: number;
|
|
107
|
+
readonly flushIntervalMs?: number;
|
|
108
|
+
readonly maxRetries?: number;
|
|
109
|
+
readonly retryDelayMs?: number;
|
|
110
|
+
readonly development?: boolean;
|
|
111
|
+
readonly now?: () => Date;
|
|
112
|
+
readonly onWarning?: (message: string) => void;
|
|
113
|
+
readonly onTransportFailure?: (failure: TransportFailure<E>) => void;
|
|
114
|
+
}
|