posthog-node 6.4.0 → 6.4.2
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/dist/capture-lane/lane.d.ts +4 -4
- package/dist/capture-lane/lane.d.ts.map +1 -1
- package/dist/capture-lane/lane.js +8 -9
- package/dist/capture-lane/lane.mjs +1 -2
- package/dist/capture-lane/settings.d.ts +1 -1
- package/dist/capture-lane/settings.d.ts.map +1 -1
- package/dist/capture-lane/settings.js +3 -3
- package/dist/capture-lane/settings.mjs +1 -1
- package/dist/client.d.ts +3 -3
- package/dist/client.js +16 -20
- package/dist/client.mjs +2 -6
- package/dist/compression.node.d.ts +1 -1
- package/dist/entrypoints/index.node.d.ts +1 -1
- package/dist/entrypoints/index.node.d.ts.map +1 -1
- package/dist/exports.d.ts +3 -3
- package/dist/exports.d.ts.map +1 -1
- package/dist/exports.js +5 -5
- package/dist/exports.mjs +1 -1
- package/dist/extensions/nestjs.d.ts.map +1 -1
- package/dist/extensions/nestjs.js +1 -0
- package/dist/extensions/nestjs.mjs +1 -0
- package/dist/types.d.ts +3 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.mjs +1 -1
- package/package.json +4 -4
- package/src/capture-lane/lane.ts +4 -4
- package/src/capture-lane/settings.ts +1 -1
- package/src/client.ts +9 -9
- package/src/compression.node.ts +1 -1
- package/src/entrypoints/index.node.ts +1 -1
- package/src/exports.ts +3 -3
- package/src/extensions/nestjs.ts +12 -0
- package/src/types.ts +3 -3
- package/src/version.ts +1 -1
- package/dist/capture-v1/compression.d.ts +0 -18
- package/dist/capture-v1/compression.d.ts.map +0 -1
- package/dist/capture-v1/compression.js +0 -70
- package/dist/capture-v1/compression.mjs +0 -26
- package/dist/capture-v1/errors.d.ts +0 -48
- package/dist/capture-v1/errors.d.ts.map +0 -1
- package/dist/capture-v1/errors.js +0 -82
- package/dist/capture-v1/errors.mjs +0 -38
- package/dist/capture-v1/sender.d.ts +0 -110
- package/dist/capture-v1/sender.d.ts.map +0 -1
- package/dist/capture-v1/sender.js +0 -481
- package/dist/capture-v1/sender.mjs +0 -434
- package/dist/capture-v1/serialize.d.ts +0 -28
- package/dist/capture-v1/serialize.d.ts.map +0 -1
- package/dist/capture-v1/serialize.js +0 -82
- package/dist/capture-v1/serialize.mjs +0 -38
- package/dist/capture-v1/transform.d.ts +0 -19
- package/dist/capture-v1/transform.d.ts.map +0 -1
- package/dist/capture-v1/transform.js +0 -118
- package/dist/capture-v1/transform.mjs +0 -77
- package/dist/capture-v1/types.d.ts +0 -52
- package/dist/capture-v1/types.d.ts.map +0 -1
- package/dist/capture-v1/types.js +0 -44
- package/dist/capture-v1/types.mjs +0 -3
- package/dist/capture-v1/uuid.d.ts +0 -9
- package/dist/capture-v1/uuid.d.ts.map +0 -1
- package/dist/capture-v1/uuid.js +0 -75
- package/dist/capture-v1/uuid.mjs +0 -34
- package/src/capture-v1/compression.ts +0 -50
- package/src/capture-v1/errors.ts +0 -91
- package/src/capture-v1/sender.ts +0 -668
- package/src/capture-v1/serialize.ts +0 -77
- package/src/capture-v1/transform.ts +0 -134
- package/src/capture-v1/types.ts +0 -59
- package/src/capture-v1/uuid.ts +0 -53
|
@@ -1,434 +0,0 @@
|
|
|
1
|
-
import { uuidv7 } from "@posthog/core";
|
|
2
|
-
import { webCompressor } from "./compression.mjs";
|
|
3
|
-
import { CaptureError, CaptureLossTally, describeCaptureLoss } from "./errors.mjs";
|
|
4
|
-
import { buildV1Body } from "./serialize.mjs";
|
|
5
|
-
import { canonicalizeUuid } from "./uuid.mjs";
|
|
6
|
-
const RETRY_BASE_DELAY_MS = 100;
|
|
7
|
-
const MAX_RETRY_DELAY_MS = 30000;
|
|
8
|
-
async function raceAbort(work, signal) {
|
|
9
|
-
if (!signal) return work;
|
|
10
|
-
let onAbort;
|
|
11
|
-
const aborted = new Promise((_resolve, reject)=>{
|
|
12
|
-
onAbort = ()=>{
|
|
13
|
-
const abortError = new Error('Capture V1 request aborted while compressing the body');
|
|
14
|
-
abortError.name = 'AbortError';
|
|
15
|
-
abortError.cause = signal.reason;
|
|
16
|
-
reject(abortError);
|
|
17
|
-
};
|
|
18
|
-
if (signal.aborted) onAbort();
|
|
19
|
-
else signal.addEventListener('abort', onAbort, {
|
|
20
|
-
once: true
|
|
21
|
-
});
|
|
22
|
-
});
|
|
23
|
-
try {
|
|
24
|
-
return await Promise.race([
|
|
25
|
-
work,
|
|
26
|
-
aborted
|
|
27
|
-
]);
|
|
28
|
-
} finally{
|
|
29
|
-
signal.removeEventListener('abort', onAbort);
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
function abortableSleep(ms, signal) {
|
|
33
|
-
return new Promise((resolve)=>{
|
|
34
|
-
const onAbort = ()=>{
|
|
35
|
-
clearTimeout(timer);
|
|
36
|
-
resolve();
|
|
37
|
-
};
|
|
38
|
-
const timer = setTimeout(()=>{
|
|
39
|
-
signal?.removeEventListener('abort', onAbort);
|
|
40
|
-
resolve();
|
|
41
|
-
}, ms);
|
|
42
|
-
signal?.addEventListener('abort', onAbort, {
|
|
43
|
-
once: true
|
|
44
|
-
});
|
|
45
|
-
});
|
|
46
|
-
}
|
|
47
|
-
const RETRYABLE_STATUSES = new Set([
|
|
48
|
-
404,
|
|
49
|
-
408,
|
|
50
|
-
429,
|
|
51
|
-
500,
|
|
52
|
-
502,
|
|
53
|
-
503,
|
|
54
|
-
504
|
|
55
|
-
]);
|
|
56
|
-
const FOLLOWED_REDIRECT_STATUSES = new Set([
|
|
57
|
-
307,
|
|
58
|
-
308
|
|
59
|
-
]);
|
|
60
|
-
const MAX_REDIRECTS = 5;
|
|
61
|
-
const timeoutErrors = new WeakSet();
|
|
62
|
-
const DUPLICATE_EVENT_UUID = 'duplicate_event_uuid';
|
|
63
|
-
class V1CaptureSender {
|
|
64
|
-
constructor(config, hooks){
|
|
65
|
-
this.config = config;
|
|
66
|
-
this.hostOrigin = originOf(config.host);
|
|
67
|
-
this.fetchFn = hooks.fetch;
|
|
68
|
-
this.onError = hooks.onError;
|
|
69
|
-
this.now = hooks.now ?? Date.now;
|
|
70
|
-
this.sleep = hooks.sleep ?? abortableSleep;
|
|
71
|
-
this.generateRequestId = hooks.generateRequestId ?? uuidv7;
|
|
72
|
-
this.random = hooks.random ?? Math.random;
|
|
73
|
-
this.compress = hooks.compress ?? webCompressor.compress;
|
|
74
|
-
}
|
|
75
|
-
async send(events, options = {}) {
|
|
76
|
-
if (0 === events.length) return [];
|
|
77
|
-
const { signal, keepUnsent = false } = options;
|
|
78
|
-
const requestId = this.generateRequestId();
|
|
79
|
-
const createdAt = new Date(this.now()).toISOString();
|
|
80
|
-
const url = `${this.config.host}${this.config.path}`;
|
|
81
|
-
const drops = [];
|
|
82
|
-
const loss = new CaptureLossTally();
|
|
83
|
-
let pending = events;
|
|
84
|
-
const unsent = (cause, failure)=>{
|
|
85
|
-
if (keepUnsent) {
|
|
86
|
-
this.surfacePartialDrops(requestId, drops, loss);
|
|
87
|
-
return pending;
|
|
88
|
-
}
|
|
89
|
-
this.surfaceBatchFailure(requestId, drops, pending, cause, loss, failure);
|
|
90
|
-
return [];
|
|
91
|
-
};
|
|
92
|
-
const { maxRetries } = this.config;
|
|
93
|
-
const maxAttempts = (Number.isInteger(maxRetries) && maxRetries > 0 ? maxRetries : 0) + 1;
|
|
94
|
-
for(let attempt = 1; attempt <= maxAttempts; attempt++){
|
|
95
|
-
if (signal?.aborted) return unsent(signal.reason, 'not sent: aborted');
|
|
96
|
-
const isLastAttempt = attempt === maxAttempts;
|
|
97
|
-
const payload = buildV1Body(pending, {
|
|
98
|
-
createdAt,
|
|
99
|
-
historicalMigration: this.config.historicalMigration
|
|
100
|
-
});
|
|
101
|
-
let captureAttempt;
|
|
102
|
-
let retryDelayMs;
|
|
103
|
-
try {
|
|
104
|
-
captureAttempt = await this.sendOnce(url, payload, attempt, requestId, signal);
|
|
105
|
-
const { response, signal: attemptSignal, redirectFailure } = captureAttempt;
|
|
106
|
-
const { status } = response;
|
|
107
|
-
if (void 0 !== redirectFailure) {
|
|
108
|
-
await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(()=>{});
|
|
109
|
-
const failure = `failed on a redirect it does not follow (HTTP ${status})`;
|
|
110
|
-
this.surfaceBatchFailure(requestId, drops, pending, new Error(redirectFailure), loss, failure);
|
|
111
|
-
return [];
|
|
112
|
-
}
|
|
113
|
-
if (status < 200 || status >= 300) if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {
|
|
114
|
-
const retryAfterMs = this.parseRetryAfter(response);
|
|
115
|
-
await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(()=>{});
|
|
116
|
-
retryDelayMs = this.backoffDelay(attempt, retryAfterMs);
|
|
117
|
-
} else {
|
|
118
|
-
const httpError = await this.buildHttpError(response, status, captureAttempt.waitFor);
|
|
119
|
-
this.surfaceBatchFailure(requestId, drops, pending, httpError, loss, `failed with HTTP ${status}`);
|
|
120
|
-
return [];
|
|
121
|
-
}
|
|
122
|
-
else {
|
|
123
|
-
let parsed;
|
|
124
|
-
try {
|
|
125
|
-
parsed = await captureAttempt.waitFor(this.parseResponse(response));
|
|
126
|
-
} catch (error) {
|
|
127
|
-
if (attemptSignal.aborted) throw error;
|
|
128
|
-
this.surfaceBatchFailure(requestId, drops, pending, new Error(`Capture V1 returned an unparseable ${status} response body`), loss, `failed with an unreadable response (HTTP ${status})`);
|
|
129
|
-
return [];
|
|
130
|
-
}
|
|
131
|
-
const dropsBefore = drops.length;
|
|
132
|
-
const retryable = this.classify(pending, parsed, drops);
|
|
133
|
-
for (const drop of drops.slice(dropsBefore)){
|
|
134
|
-
const cause = drop.details === DUPLICATE_EVENT_UUID ? 'dropped as duplicate uuids' : 'dropped by the server';
|
|
135
|
-
loss.add(`${cause} (HTTP ${status})`, 1);
|
|
136
|
-
}
|
|
137
|
-
if (0 === retryable.length) {
|
|
138
|
-
this.surfacePartialDrops(requestId, drops, loss);
|
|
139
|
-
return [];
|
|
140
|
-
}
|
|
141
|
-
if (isLastAttempt) {
|
|
142
|
-
loss.add(`still marked for retry after ${maxAttempts} attempt(s) (HTTP ${status})`, retryable.length);
|
|
143
|
-
this.report(this.captureError({
|
|
144
|
-
requestId,
|
|
145
|
-
drops,
|
|
146
|
-
retryExhausted: retryable.map((event)=>event.uuid)
|
|
147
|
-
}), loss);
|
|
148
|
-
return [];
|
|
149
|
-
}
|
|
150
|
-
pending = retryable;
|
|
151
|
-
const retryAfterMs = this.parseRetryAfter(response);
|
|
152
|
-
retryDelayMs = this.backoffDelay(attempt, retryAfterMs);
|
|
153
|
-
}
|
|
154
|
-
} catch (transportError) {
|
|
155
|
-
if (captureAttempt && !captureAttempt.signal.aborted) throw transportError;
|
|
156
|
-
if (isLastAttempt || signal?.aborted) return unsent(transportError, this.describeTransportFailure(transportError, signal));
|
|
157
|
-
retryDelayMs = this.backoffDelay(attempt);
|
|
158
|
-
} finally{
|
|
159
|
-
captureAttempt?.cleanup();
|
|
160
|
-
}
|
|
161
|
-
if (void 0 !== retryDelayMs) await this.sleepUnlessAborted(retryDelayMs, signal);
|
|
162
|
-
}
|
|
163
|
-
return [];
|
|
164
|
-
}
|
|
165
|
-
async sleepUnlessAborted(ms, signal) {
|
|
166
|
-
if (!signal) return this.sleep(ms);
|
|
167
|
-
if (signal.aborted) return;
|
|
168
|
-
let onAbort;
|
|
169
|
-
const aborted = new Promise((resolve)=>{
|
|
170
|
-
onAbort = resolve;
|
|
171
|
-
signal.addEventListener('abort', onAbort, {
|
|
172
|
-
once: true
|
|
173
|
-
});
|
|
174
|
-
});
|
|
175
|
-
try {
|
|
176
|
-
await Promise.race([
|
|
177
|
-
this.sleep(ms, signal),
|
|
178
|
-
aborted
|
|
179
|
-
]);
|
|
180
|
-
} finally{
|
|
181
|
-
signal.removeEventListener('abort', onAbort);
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
async sendOnce(url, payload, attempt, requestId, externalSignal) {
|
|
185
|
-
const headers = this.buildHeaders(attempt, requestId);
|
|
186
|
-
const body = await raceAbort(this.encodeBody(payload, headers), externalSignal);
|
|
187
|
-
const controller = new AbortController();
|
|
188
|
-
let timeoutPhase = 'waiting for response headers';
|
|
189
|
-
let timer;
|
|
190
|
-
let onExternalAbort;
|
|
191
|
-
const stopListening = ()=>{
|
|
192
|
-
if (onExternalAbort) externalSignal?.removeEventListener('abort', onExternalAbort);
|
|
193
|
-
};
|
|
194
|
-
const deadline = new Promise((_resolve, reject)=>{
|
|
195
|
-
const abortWith = (error)=>{
|
|
196
|
-
reject(error);
|
|
197
|
-
controller.abort(error);
|
|
198
|
-
};
|
|
199
|
-
timer = setTimeout(()=>{
|
|
200
|
-
const timeoutError = new Error(`Capture V1 request timed out ${timeoutPhase} after ${this.config.requestTimeoutMs}ms`);
|
|
201
|
-
timeoutError.name = 'AbortError';
|
|
202
|
-
timeoutErrors.add(timeoutError);
|
|
203
|
-
abortWith(timeoutError);
|
|
204
|
-
}, this.config.requestTimeoutMs);
|
|
205
|
-
if (externalSignal) {
|
|
206
|
-
onExternalAbort = ()=>{
|
|
207
|
-
const abortError = new Error(`Capture V1 request aborted ${timeoutPhase}`);
|
|
208
|
-
abortError.name = 'AbortError';
|
|
209
|
-
abortError.cause = externalSignal.reason;
|
|
210
|
-
abortWith(abortError);
|
|
211
|
-
};
|
|
212
|
-
if (externalSignal.aborted) onExternalAbort();
|
|
213
|
-
else externalSignal.addEventListener('abort', onExternalAbort, {
|
|
214
|
-
once: true
|
|
215
|
-
});
|
|
216
|
-
}
|
|
217
|
-
});
|
|
218
|
-
deadline.catch(()=>{});
|
|
219
|
-
try {
|
|
220
|
-
const fetchPromise = this.fetchFollowingRedirects(url, headers, body, controller.signal);
|
|
221
|
-
let responseAccepted = false;
|
|
222
|
-
fetchPromise.then((late)=>{
|
|
223
|
-
if (controller.signal.aborted && !responseAccepted) this.cancelBody(late.response);
|
|
224
|
-
}).catch(()=>{});
|
|
225
|
-
const { response, redirectFailure } = await Promise.race([
|
|
226
|
-
fetchPromise,
|
|
227
|
-
deadline
|
|
228
|
-
]);
|
|
229
|
-
responseAccepted = true;
|
|
230
|
-
timeoutPhase = 'while reading the response body';
|
|
231
|
-
let cleanedUp = false;
|
|
232
|
-
let cancellation;
|
|
233
|
-
const cancelBody = ()=>cancellation ??= this.cancelBody(response);
|
|
234
|
-
return {
|
|
235
|
-
response,
|
|
236
|
-
redirectFailure,
|
|
237
|
-
signal: controller.signal,
|
|
238
|
-
waitFor: (operation)=>Promise.race([
|
|
239
|
-
operation,
|
|
240
|
-
deadline
|
|
241
|
-
]),
|
|
242
|
-
cancelBody,
|
|
243
|
-
cleanup: ()=>{
|
|
244
|
-
if (cleanedUp) return;
|
|
245
|
-
cleanedUp = true;
|
|
246
|
-
clearTimeout(timer);
|
|
247
|
-
stopListening();
|
|
248
|
-
if (controller.signal.aborted) cancelBody();
|
|
249
|
-
}
|
|
250
|
-
};
|
|
251
|
-
} catch (error) {
|
|
252
|
-
clearTimeout(timer);
|
|
253
|
-
stopListening();
|
|
254
|
-
throw error;
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
async fetchFollowingRedirects(url, headers, body, signal) {
|
|
258
|
-
let target = url;
|
|
259
|
-
for(let redirects = 0;; redirects++){
|
|
260
|
-
const response = await this.fetchFn(target, {
|
|
261
|
-
method: 'POST',
|
|
262
|
-
headers,
|
|
263
|
-
body: 'string' == typeof body ? body : body.slice(),
|
|
264
|
-
signal,
|
|
265
|
-
redirect: 'manual'
|
|
266
|
-
});
|
|
267
|
-
const { status } = response;
|
|
268
|
-
if (status < 300 || status >= 400) return {
|
|
269
|
-
response
|
|
270
|
-
};
|
|
271
|
-
if (!FOLLOWED_REDIRECT_STATUSES.has(status)) return {
|
|
272
|
-
response,
|
|
273
|
-
redirectFailure: `Capture V1 request got an HTTP ${status} redirect, which it does not follow`
|
|
274
|
-
};
|
|
275
|
-
if (redirects === MAX_REDIRECTS) return {
|
|
276
|
-
response,
|
|
277
|
-
redirectFailure: `Capture V1 request was redirected more than ${MAX_REDIRECTS} times`
|
|
278
|
-
};
|
|
279
|
-
const next = resolveLocation(response.headers?.get('Location'), target);
|
|
280
|
-
if (void 0 === next || originOf(next) !== this.hostOrigin) return {
|
|
281
|
-
response,
|
|
282
|
-
redirectFailure: `Capture V1 request got an HTTP ${status} redirect away from the configured host`
|
|
283
|
-
};
|
|
284
|
-
this.cancelBody(response);
|
|
285
|
-
if (signal.aborted) throw signal.reason;
|
|
286
|
-
target = next;
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
async encodeBody(payload, headers) {
|
|
290
|
-
const codec = this.config.compression;
|
|
291
|
-
if ('none' === codec) return payload;
|
|
292
|
-
try {
|
|
293
|
-
const compressed = await this.compress(payload, codec);
|
|
294
|
-
if (null !== compressed) {
|
|
295
|
-
headers['Content-Encoding'] = codec;
|
|
296
|
-
return compressed;
|
|
297
|
-
}
|
|
298
|
-
} catch (error) {
|
|
299
|
-
if (this.config.isDebug) console.error(`Failed to ${codec} compress the capture request body`, error);
|
|
300
|
-
}
|
|
301
|
-
return payload;
|
|
302
|
-
}
|
|
303
|
-
buildHeaders(attempt, requestId) {
|
|
304
|
-
const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`;
|
|
305
|
-
const headers = {
|
|
306
|
-
'Content-Type': 'application/json',
|
|
307
|
-
Authorization: `Bearer ${this.config.apiKey}`,
|
|
308
|
-
'PostHog-Sdk-Info': sdkInfo,
|
|
309
|
-
'PostHog-Attempt': String(attempt),
|
|
310
|
-
'PostHog-Request-Id': requestId,
|
|
311
|
-
'PostHog-Request-Timestamp': new Date(this.now()).toISOString()
|
|
312
|
-
};
|
|
313
|
-
if (this.config.userAgent) headers['User-Agent'] = this.config.userAgent;
|
|
314
|
-
return headers;
|
|
315
|
-
}
|
|
316
|
-
classify(pending, parsed, drops) {
|
|
317
|
-
const results = new Map();
|
|
318
|
-
for (const [uuid, result] of Object.entries(parsed.results))results.set(canonicalizeUuid(uuid) ?? uuid, result);
|
|
319
|
-
const retryable = [];
|
|
320
|
-
let copiesSeen;
|
|
321
|
-
for (const event of pending){
|
|
322
|
-
const result = results.get(event.uuid);
|
|
323
|
-
if (!result) continue;
|
|
324
|
-
const duplicates = result.duplicates_dropped;
|
|
325
|
-
if ('number' == typeof duplicates && Number.isSafeInteger(duplicates) && duplicates > 0) {
|
|
326
|
-
copiesSeen ??= new Map();
|
|
327
|
-
const copy = copiesSeen.get(event.uuid) ?? 0;
|
|
328
|
-
copiesSeen.set(event.uuid, copy + 1);
|
|
329
|
-
if (copy >= 1 && copy <= duplicates) {
|
|
330
|
-
drops.push({
|
|
331
|
-
uuid: event.uuid,
|
|
332
|
-
details: DUPLICATE_EVENT_UUID
|
|
333
|
-
});
|
|
334
|
-
continue;
|
|
335
|
-
}
|
|
336
|
-
}
|
|
337
|
-
if ('drop' === result.result) drops.push({
|
|
338
|
-
uuid: event.uuid,
|
|
339
|
-
details: result.details ?? void 0
|
|
340
|
-
});
|
|
341
|
-
else if ('retry' === result.result) retryable.push(event);
|
|
342
|
-
}
|
|
343
|
-
return retryable;
|
|
344
|
-
}
|
|
345
|
-
backoffDelay(attempt, retryAfterMs) {
|
|
346
|
-
const jitter = 0.75 + 0.5 * this.random();
|
|
347
|
-
const backoff = Math.min(RETRY_BASE_DELAY_MS * 2 ** (attempt - 1) * jitter, MAX_RETRY_DELAY_MS);
|
|
348
|
-
if (void 0 === retryAfterMs) return backoff;
|
|
349
|
-
return Math.max(backoff, Math.min(retryAfterMs, MAX_RETRY_DELAY_MS));
|
|
350
|
-
}
|
|
351
|
-
parseRetryAfter(response) {
|
|
352
|
-
const raw = response.headers?.get('Retry-After');
|
|
353
|
-
if (!raw) return;
|
|
354
|
-
const trimmed = raw.trim();
|
|
355
|
-
if (/^\d+$/.test(trimmed)) {
|
|
356
|
-
const seconds = parseInt(trimmed, 10);
|
|
357
|
-
return Number.isFinite(seconds) && seconds > 0 ? 1000 * seconds : void 0;
|
|
358
|
-
}
|
|
359
|
-
const dateMs = Date.parse(trimmed);
|
|
360
|
-
if (Number.isNaN(dateMs)) return;
|
|
361
|
-
const delta = dateMs - this.now();
|
|
362
|
-
return delta > 0 ? delta : void 0;
|
|
363
|
-
}
|
|
364
|
-
async parseResponse(response) {
|
|
365
|
-
const text = await response.text();
|
|
366
|
-
const parsed = JSON.parse(text);
|
|
367
|
-
if ('object' != typeof parsed || null === parsed || Array.isArray(parsed)) throw new Error('unexpected response shape');
|
|
368
|
-
const results = parsed.results;
|
|
369
|
-
if ('object' != typeof results || null === results || Array.isArray(results)) throw new Error('unexpected results shape');
|
|
370
|
-
return {
|
|
371
|
-
results: results
|
|
372
|
-
};
|
|
373
|
-
}
|
|
374
|
-
async buildHttpError(response, status, waitFor) {
|
|
375
|
-
let bodyText = '';
|
|
376
|
-
try {
|
|
377
|
-
bodyText = (await waitFor(response.text())).slice(0, 512);
|
|
378
|
-
} catch {}
|
|
379
|
-
const suffix = bodyText ? `: ${bodyText}` : '';
|
|
380
|
-
return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`);
|
|
381
|
-
}
|
|
382
|
-
surfaceBatchFailure(requestId, drops, pending, cause, loss, failure) {
|
|
383
|
-
loss.add(failure, pending.length);
|
|
384
|
-
this.report(this.captureError({
|
|
385
|
-
requestId,
|
|
386
|
-
drops,
|
|
387
|
-
retryExhausted: pending.map((event)=>event.uuid),
|
|
388
|
-
cause
|
|
389
|
-
}), loss);
|
|
390
|
-
}
|
|
391
|
-
surfacePartialDrops(requestId, drops, loss) {
|
|
392
|
-
if (drops.length > 0) this.report(this.captureError({
|
|
393
|
-
requestId,
|
|
394
|
-
drops,
|
|
395
|
-
retryExhausted: []
|
|
396
|
-
}), loss);
|
|
397
|
-
}
|
|
398
|
-
report(error, loss) {
|
|
399
|
-
this.onError(error, describeCaptureLoss(this.config.path, loss));
|
|
400
|
-
}
|
|
401
|
-
describeTransportFailure(error, signal) {
|
|
402
|
-
if (error instanceof Error && timeoutErrors.has(error)) return 'failed: request timed out';
|
|
403
|
-
if (signal?.aborted) return 'failed: request aborted';
|
|
404
|
-
const name = error instanceof Error && /^\w{1,64}$/.test(error.name) ? error.name : 'unknown';
|
|
405
|
-
return `failed with a network error (${name})`;
|
|
406
|
-
}
|
|
407
|
-
captureError(params) {
|
|
408
|
-
return new CaptureError({
|
|
409
|
-
endpoint: this.config.path,
|
|
410
|
-
...params
|
|
411
|
-
});
|
|
412
|
-
}
|
|
413
|
-
async cancelBody(response) {
|
|
414
|
-
try {
|
|
415
|
-
await response.body?.cancel();
|
|
416
|
-
} catch {}
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
function originOf(url) {
|
|
420
|
-
try {
|
|
421
|
-
return new URL(url).origin;
|
|
422
|
-
} catch {
|
|
423
|
-
return;
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
function resolveLocation(location, base) {
|
|
427
|
-
if (!location) return;
|
|
428
|
-
try {
|
|
429
|
-
return new URL(location, base).href;
|
|
430
|
-
} catch {
|
|
431
|
-
return;
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
export { DUPLICATE_EVENT_UUID, MAX_RETRY_DELAY_MS, RETRY_BASE_DELAY_MS, V1CaptureSender };
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import { type PostHogEventProperties } from '@posthog/core';
|
|
2
|
-
/** One wire event, serialized once and reused verbatim in every request body that carries it. */
|
|
3
|
-
export interface SerializedV1Event {
|
|
4
|
-
uuid: string;
|
|
5
|
-
json: string;
|
|
6
|
-
/** UTF-8 size of `json`. */
|
|
7
|
-
bytes: number;
|
|
8
|
-
/** UTF-8 size of the serialized `properties` object alone, which is what the AI endpoint limits. */
|
|
9
|
-
propertiesBytes: number;
|
|
10
|
-
}
|
|
11
|
-
/**
|
|
12
|
-
* Why capture would reject this event, or undefined when it can be sent. A name must be a non-empty string, the
|
|
13
|
-
* distinct id a string, and the name and ids well-formed Unicode: a broken id is never repaired, because two broken ids
|
|
14
|
-
* could collapse into one.
|
|
15
|
-
*/
|
|
16
|
-
export declare function wireProblem(message: PostHogEventProperties): string | undefined;
|
|
17
|
-
export declare function serializeV1Event(message: PostHogEventProperties): SerializedV1Event;
|
|
18
|
-
/**
|
|
19
|
-
* The Capture V1 batch envelope, built from already-serialized events. Unlike v0 there is no
|
|
20
|
-
* `api_key` (Bearer auth) and no `sent_at`. `historical_migration` is omitted when false.
|
|
21
|
-
*/
|
|
22
|
-
export declare function buildV1Body(events: readonly {
|
|
23
|
-
json: string;
|
|
24
|
-
}[], { createdAt, historicalMigration }: {
|
|
25
|
-
createdAt: string;
|
|
26
|
-
historicalMigration: boolean;
|
|
27
|
-
}): string;
|
|
28
|
-
//# sourceMappingURL=serialize.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"serialize.d.ts","sourceRoot":"","sources":["../../src/capture-v1/serialize.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,sBAAsB,EAAqB,MAAM,eAAe,CAAA;AAU9E,iGAAiG;AACjG,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;IACZ,4BAA4B;IAC5B,KAAK,EAAE,MAAM,CAAA;IACb,oGAAoG;IACpG,eAAe,EAAE,MAAM,CAAA;CACxB;AAOD;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,sBAAsB,GAAG,MAAM,GAAG,SAAS,CAe/E;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,sBAAsB,GAAG,iBAAiB,CAiBnF;AAED;;;GAGG;AACH,wBAAgB,WAAW,CACzB,MAAM,EAAE,SAAS;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,EACnC,EAAE,SAAS,EAAE,mBAAmB,EAAE,EAAE;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,mBAAmB,EAAE,OAAO,CAAA;CAAE,GACtF,MAAM,CAGR"}
|
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __webpack_require__ = {};
|
|
3
|
-
(()=>{
|
|
4
|
-
__webpack_require__.d = (exports1, getters, values)=>{
|
|
5
|
-
var define = (defs, kind)=>{
|
|
6
|
-
for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
|
|
7
|
-
enumerable: true,
|
|
8
|
-
[kind]: defs[key]
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
|
-
define(getters, "get");
|
|
12
|
-
define(values, "value");
|
|
13
|
-
};
|
|
14
|
-
})();
|
|
15
|
-
(()=>{
|
|
16
|
-
__webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
|
|
17
|
-
})();
|
|
18
|
-
(()=>{
|
|
19
|
-
__webpack_require__.r = (exports1)=>{
|
|
20
|
-
if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
|
|
21
|
-
value: 'Module'
|
|
22
|
-
});
|
|
23
|
-
Object.defineProperty(exports1, '__esModule', {
|
|
24
|
-
value: true
|
|
25
|
-
});
|
|
26
|
-
};
|
|
27
|
-
})();
|
|
28
|
-
var __webpack_exports__ = {};
|
|
29
|
-
__webpack_require__.r(__webpack_exports__);
|
|
30
|
-
__webpack_require__.d(__webpack_exports__, {
|
|
31
|
-
buildV1Body: ()=>buildV1Body,
|
|
32
|
-
serializeV1Event: ()=>serializeV1Event,
|
|
33
|
-
wireProblem: ()=>wireProblem
|
|
34
|
-
});
|
|
35
|
-
const core_namespaceObject = require("@posthog/core");
|
|
36
|
-
const external_transform_js_namespaceObject = require("./transform.js");
|
|
37
|
-
const encoder = new TextEncoder();
|
|
38
|
-
const PROPERTIES_KEY = ',"properties":';
|
|
39
|
-
const PROPERTIES_KEY_BYTES = encoder.encode(PROPERTIES_KEY).length;
|
|
40
|
-
const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
|
|
41
|
-
const LONE_SURROGATE_ESCAPE = /(?<!\\)((?:\\\\)*)\\u[dD][89a-fA-F][0-9a-fA-F]{2}/g;
|
|
42
|
-
function wireProblem(message) {
|
|
43
|
-
const { event, distinct_id: distinctId, properties } = message;
|
|
44
|
-
if ('string' != typeof event || '' === event) return 'event name is missing, empty or not a string';
|
|
45
|
-
if ('string' != typeof distinctId) return 'distinct id is missing or not a string';
|
|
46
|
-
const props = properties ?? {};
|
|
47
|
-
const ids = [
|
|
48
|
-
event,
|
|
49
|
-
distinctId,
|
|
50
|
-
props.$session_id,
|
|
51
|
-
props.$window_id
|
|
52
|
-
];
|
|
53
|
-
if (ids.some((value)=>'string' == typeof value && LONE_SURROGATE.test(value))) return 'event name or id is not well-formed Unicode';
|
|
54
|
-
}
|
|
55
|
-
function serializeV1Event(message) {
|
|
56
|
-
const { properties, ...rest } = (0, external_transform_js_namespaceObject.buildV1Event)(message);
|
|
57
|
-
const restJson = (0, core_namespaceObject.safeJsonStringify)(rest);
|
|
58
|
-
const rawPropertiesJson = (0, core_namespaceObject.safeJsonStringify)(properties);
|
|
59
|
-
const propertiesJson = rawPropertiesJson.includes('\\ud') || rawPropertiesJson.includes('\\uD') ? rawPropertiesJson.replace(LONE_SURROGATE_ESCAPE, '$1\\ufffd') : rawPropertiesJson;
|
|
60
|
-
const propertiesBytes = encoder.encode(propertiesJson).length;
|
|
61
|
-
return {
|
|
62
|
-
uuid: rest.uuid,
|
|
63
|
-
json: `${restJson.slice(0, -1)}${PROPERTIES_KEY}${propertiesJson}}`,
|
|
64
|
-
bytes: encoder.encode(restJson).length + PROPERTIES_KEY_BYTES + propertiesBytes,
|
|
65
|
-
propertiesBytes
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
|
-
function buildV1Body(events, { createdAt, historicalMigration }) {
|
|
69
|
-
const migration = historicalMigration ? ',"historical_migration":true' : '';
|
|
70
|
-
return `{"created_at":${JSON.stringify(createdAt)}${migration},"batch":[${events.map((event)=>event.json).join(',')}]}`;
|
|
71
|
-
}
|
|
72
|
-
exports.buildV1Body = __webpack_exports__.buildV1Body;
|
|
73
|
-
exports.serializeV1Event = __webpack_exports__.serializeV1Event;
|
|
74
|
-
exports.wireProblem = __webpack_exports__.wireProblem;
|
|
75
|
-
for(var __rspack_i in __webpack_exports__)if (-1 === [
|
|
76
|
-
"buildV1Body",
|
|
77
|
-
"serializeV1Event",
|
|
78
|
-
"wireProblem"
|
|
79
|
-
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
|
|
80
|
-
Object.defineProperty(exports, '__esModule', {
|
|
81
|
-
value: true
|
|
82
|
-
});
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
import { safeJsonStringify } from "@posthog/core";
|
|
2
|
-
import { buildV1Event } from "./transform.mjs";
|
|
3
|
-
const encoder = new TextEncoder();
|
|
4
|
-
const PROPERTIES_KEY = ',"properties":';
|
|
5
|
-
const PROPERTIES_KEY_BYTES = encoder.encode(PROPERTIES_KEY).length;
|
|
6
|
-
const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
|
|
7
|
-
const LONE_SURROGATE_ESCAPE = /(?<!\\)((?:\\\\)*)\\u[dD][89a-fA-F][0-9a-fA-F]{2}/g;
|
|
8
|
-
function wireProblem(message) {
|
|
9
|
-
const { event, distinct_id: distinctId, properties } = message;
|
|
10
|
-
if ('string' != typeof event || '' === event) return 'event name is missing, empty or not a string';
|
|
11
|
-
if ('string' != typeof distinctId) return 'distinct id is missing or not a string';
|
|
12
|
-
const props = properties ?? {};
|
|
13
|
-
const ids = [
|
|
14
|
-
event,
|
|
15
|
-
distinctId,
|
|
16
|
-
props.$session_id,
|
|
17
|
-
props.$window_id
|
|
18
|
-
];
|
|
19
|
-
if (ids.some((value)=>'string' == typeof value && LONE_SURROGATE.test(value))) return 'event name or id is not well-formed Unicode';
|
|
20
|
-
}
|
|
21
|
-
function serializeV1Event(message) {
|
|
22
|
-
const { properties, ...rest } = buildV1Event(message);
|
|
23
|
-
const restJson = safeJsonStringify(rest);
|
|
24
|
-
const rawPropertiesJson = safeJsonStringify(properties);
|
|
25
|
-
const propertiesJson = rawPropertiesJson.includes('\\ud') || rawPropertiesJson.includes('\\uD') ? rawPropertiesJson.replace(LONE_SURROGATE_ESCAPE, '$1\\ufffd') : rawPropertiesJson;
|
|
26
|
-
const propertiesBytes = encoder.encode(propertiesJson).length;
|
|
27
|
-
return {
|
|
28
|
-
uuid: rest.uuid,
|
|
29
|
-
json: `${restJson.slice(0, -1)}${PROPERTIES_KEY}${propertiesJson}}`,
|
|
30
|
-
bytes: encoder.encode(restJson).length + PROPERTIES_KEY_BYTES + propertiesBytes,
|
|
31
|
-
propertiesBytes
|
|
32
|
-
};
|
|
33
|
-
}
|
|
34
|
-
function buildV1Body(events, { createdAt, historicalMigration }) {
|
|
35
|
-
const migration = historicalMigration ? ',"historical_migration":true' : '';
|
|
36
|
-
return `{"created_at":${JSON.stringify(createdAt)}${migration},"batch":[${events.map((event)=>event.json).join(',')}]}`;
|
|
37
|
-
}
|
|
38
|
-
export { buildV1Body, serializeV1Event, wireProblem };
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import { type JsonType, type PostHogEventProperties } from '@posthog/core';
|
|
2
|
-
import type { V1Event } from './types';
|
|
3
|
-
/**
|
|
4
|
-
* A copy of the caller's per-event options, or undefined when there are none. Any value that
|
|
5
|
-
* is not an object is reported and ignored, so the event is still sent.
|
|
6
|
-
*/
|
|
7
|
-
export declare function readEventOptions(value: unknown): Record<string, JsonType> | undefined;
|
|
8
|
-
/**
|
|
9
|
-
* Transform one already-normalized queued message into a Capture V1 wire event.
|
|
10
|
-
*
|
|
11
|
-
* The input message is never mutated (events may be retried or handed to
|
|
12
|
-
* callbacks): fresh `options` and `properties` maps are built. Option values are
|
|
13
|
-
* sent unchanged; capture reads them. Each legacy option property is removed from
|
|
14
|
-
* `properties` and fills its option when the caller left that option missing or
|
|
15
|
-
* `null`. `$session_id`/`$window_id` move to the top-level `session_id`/`window_id`
|
|
16
|
-
* fields; top-level `$set`/`$set_once` are relocated into `properties`.
|
|
17
|
-
*/
|
|
18
|
-
export declare function buildV1Event(message: PostHogEventProperties): V1Event;
|
|
19
|
-
//# sourceMappingURL=transform.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"transform.d.ts","sourceRoot":"","sources":["../../src/capture-v1/transform.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkC,KAAK,QAAQ,EAAE,KAAK,sBAAsB,EAAE,MAAM,eAAe,CAAA;AAE1G,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAgBtC;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,GAAG,SAAS,CAYrF;AA6CD;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CA4CrE"}
|