posthog-node 5.74.0 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/MIGRATION.md +556 -0
- package/README.md +3 -1
- package/dist/ai-capture/routing.d.ts +0 -3
- package/dist/ai-capture/routing.d.ts.map +1 -1
- package/dist/ai-capture/routing.js +2 -14
- package/dist/ai-capture/routing.mjs +1 -4
- package/dist/capture-lane/lane.d.ts +109 -0
- package/dist/capture-lane/lane.d.ts.map +1 -0
- package/dist/capture-lane/lane.js +308 -0
- package/dist/capture-lane/lane.mjs +270 -0
- package/dist/capture-lane/limits.d.ts +7 -0
- package/dist/capture-lane/limits.d.ts.map +1 -0
- package/dist/{capture-v1/config.js → capture-lane/limits.js} +13 -11
- package/dist/capture-lane/limits.mjs +4 -0
- package/dist/capture-lane/settings.d.ts +30 -0
- package/dist/capture-lane/settings.d.ts.map +1 -0
- package/dist/capture-lane/settings.js +100 -0
- package/dist/capture-lane/settings.mjs +47 -0
- package/dist/capture-v1/compression.d.ts +18 -0
- package/dist/capture-v1/compression.d.ts.map +1 -0
- package/dist/capture-v1/compression.js +70 -0
- package/dist/capture-v1/compression.mjs +26 -0
- package/dist/capture-v1/errors.d.ts +23 -7
- package/dist/capture-v1/errors.d.ts.map +1 -1
- package/dist/capture-v1/errors.js +37 -8
- package/dist/capture-v1/errors.mjs +29 -6
- package/dist/capture-v1/sender.d.ts +63 -23
- package/dist/capture-v1/sender.d.ts.map +1 -1
- package/dist/capture-v1/sender.js +281 -74
- package/dist/capture-v1/sender.mjs +275 -77
- package/dist/capture-v1/serialize.d.ts +28 -0
- package/dist/capture-v1/serialize.d.ts.map +1 -0
- package/dist/capture-v1/serialize.js +82 -0
- package/dist/capture-v1/serialize.mjs +38 -0
- package/dist/capture-v1/transform.d.ts +10 -25
- package/dist/capture-v1/transform.d.ts.map +1 -1
- package/dist/capture-v1/transform.js +33 -64
- package/dist/capture-v1/transform.mjs +28 -53
- package/dist/capture-v1/types.d.ts +16 -14
- package/dist/capture-v1/types.d.ts.map +1 -1
- package/dist/capture-v1/types.js +27 -1
- package/dist/capture-v1/types.mjs +3 -1
- package/dist/capture-v1/uuid.d.ts +9 -0
- package/dist/capture-v1/uuid.d.ts.map +1 -0
- package/dist/capture-v1/uuid.js +75 -0
- package/dist/capture-v1/uuid.mjs +34 -0
- package/dist/client.d.ts +201 -94
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +456 -228
- package/dist/client.mjs +455 -227
- package/dist/compression.node.d.ts +13 -0
- package/dist/compression.node.d.ts.map +1 -0
- package/dist/{capture-v1/routing.js → compression.node.js} +23 -16
- package/dist/compression.node.mjs +18 -0
- package/dist/entrypoints/index.node.d.ts +2 -0
- package/dist/entrypoints/index.node.d.ts.map +1 -1
- package/dist/entrypoints/index.node.js +11 -4
- package/dist/entrypoints/index.node.mjs +4 -0
- package/dist/event-defaults.d.ts +46 -0
- package/dist/event-defaults.d.ts.map +1 -0
- package/dist/event-defaults.js +141 -0
- package/dist/event-defaults.mjs +79 -0
- package/dist/exports.d.ts +3 -0
- package/dist/exports.d.ts.map +1 -1
- package/dist/exports.js +22 -11
- package/dist/exports.mjs +1 -0
- package/dist/extensions/context/context.d.ts +0 -1
- package/dist/extensions/context/context.d.ts.map +1 -1
- package/dist/extensions/context/context.js +4 -3
- package/dist/extensions/context/context.mjs +4 -3
- package/dist/extensions/context/event-context.d.ts.map +1 -1
- package/dist/extensions/context/event-context.js +3 -0
- package/dist/extensions/context/event-context.mjs +3 -0
- package/dist/extensions/context/types.d.ts +9 -1
- package/dist/extensions/context/types.d.ts.map +1 -1
- package/dist/extensions/error-tracking/index.d.ts +1 -1
- package/dist/extensions/error-tracking/index.d.ts.map +1 -1
- package/dist/extensions/error-tracking/index.js +71 -7
- package/dist/extensions/error-tracking/index.mjs +75 -11
- package/dist/extensions/express.d.ts +8 -0
- package/dist/extensions/express.d.ts.map +1 -1
- package/dist/extensions/express.js +3 -3
- package/dist/extensions/express.mjs +4 -4
- package/dist/extensions/fetch-request.d.ts.map +1 -1
- package/dist/extensions/fetch-request.js +2 -2
- package/dist/extensions/fetch-request.mjs +3 -3
- package/dist/extensions/nestjs.d.ts.map +1 -1
- package/dist/extensions/nestjs.js +7 -4
- package/dist/extensions/nestjs.mjs +8 -5
- package/dist/extensions/tracing-headers.d.ts +7 -0
- package/dist/extensions/tracing-headers.d.ts.map +1 -1
- package/dist/extensions/tracing-headers.js +11 -1
- package/dist/extensions/tracing-headers.mjs +9 -2
- package/dist/flag-events.d.ts +1 -1
- package/dist/flag-events.d.ts.map +1 -1
- package/dist/flag-events.js +2 -2
- package/dist/flag-events.mjs +2 -2
- package/dist/types.d.ts +191 -27
- package/dist/types.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.d.ts.map +1 -1
- package/dist/version.js +1 -1
- package/dist/version.mjs +1 -1
- package/package.json +5 -4
- package/src/ai-capture/routing.ts +0 -6
- package/src/capture-lane/lane.ts +414 -0
- package/src/capture-lane/limits.ts +8 -0
- package/src/capture-lane/settings.ts +119 -0
- package/src/capture-v1/compression.ts +50 -0
- package/src/capture-v1/errors.ts +50 -11
- package/src/capture-v1/sender.ts +405 -111
- package/src/capture-v1/serialize.ts +77 -0
- package/src/capture-v1/transform.ts +59 -92
- package/src/capture-v1/types.ts +19 -15
- package/src/capture-v1/uuid.ts +53 -0
- package/src/client.ts +845 -422
- package/src/compression.node.ts +30 -0
- package/src/entrypoints/index.node.ts +6 -0
- package/src/event-defaults.ts +177 -0
- package/src/exports.ts +3 -0
- package/src/extensions/context/context.ts +4 -4
- package/src/extensions/context/event-context.ts +3 -1
- package/src/extensions/context/types.ts +10 -1
- package/src/extensions/error-tracking/index.ts +51 -7
- package/src/extensions/express.ts +12 -3
- package/src/extensions/fetch-request.ts +7 -3
- package/src/extensions/nestjs.ts +9 -5
- package/src/extensions/tracing-headers.ts +26 -7
- package/src/flag-events.ts +5 -2
- package/src/types.ts +211 -44
- package/src/version.ts +1 -1
- package/dist/ai-capture/batching.d.ts +0 -11
- package/dist/ai-capture/batching.d.ts.map +0 -1
- package/dist/ai-capture/batching.js +0 -77
- package/dist/ai-capture/batching.mjs +0 -36
- package/dist/capture-v1/config.d.ts +0 -11
- package/dist/capture-v1/config.d.ts.map +0 -1
- package/dist/capture-v1/config.mjs +0 -8
- package/dist/capture-v1/routing.d.ts +0 -21
- package/dist/capture-v1/routing.d.ts.map +0 -1
- package/dist/capture-v1/routing.mjs +0 -7
- package/src/ai-capture/batching.ts +0 -47
- package/src/capture-v1/config.ts +0 -18
- package/src/capture-v1/routing.ts +0 -28
|
@@ -1,8 +1,49 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
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
|
+
}
|
|
6
47
|
const RETRYABLE_STATUSES = new Set([
|
|
7
48
|
404,
|
|
8
49
|
408,
|
|
@@ -12,114 +53,176 @@ const RETRYABLE_STATUSES = new Set([
|
|
|
12
53
|
503,
|
|
13
54
|
504
|
|
14
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';
|
|
15
63
|
class V1CaptureSender {
|
|
16
64
|
constructor(config, hooks){
|
|
17
65
|
this.config = config;
|
|
18
|
-
this.
|
|
66
|
+
this.hostOrigin = originOf(config.host);
|
|
19
67
|
this.fetchFn = hooks.fetch;
|
|
20
68
|
this.onError = hooks.onError;
|
|
21
69
|
this.now = hooks.now ?? Date.now;
|
|
22
|
-
this.sleep = hooks.sleep ??
|
|
70
|
+
this.sleep = hooks.sleep ?? abortableSleep;
|
|
23
71
|
this.generateRequestId = hooks.generateRequestId ?? uuidv7;
|
|
24
|
-
this.
|
|
72
|
+
this.random = hooks.random ?? Math.random;
|
|
73
|
+
this.compress = hooks.compress ?? webCompressor.compress;
|
|
25
74
|
}
|
|
26
|
-
async
|
|
27
|
-
if (0 ===
|
|
75
|
+
async send(events, options = {}) {
|
|
76
|
+
if (0 === events.length) return [];
|
|
77
|
+
const { signal, keepUnsent = false } = options;
|
|
28
78
|
const requestId = this.generateRequestId();
|
|
29
79
|
const createdAt = new Date(this.now()).toISOString();
|
|
30
|
-
const
|
|
31
|
-
createdAt,
|
|
32
|
-
historicalMigration: this.config.historicalMigration
|
|
33
|
-
});
|
|
34
|
-
const url = `${this.config.host}${V1_ANALYTICS_PATH}`;
|
|
80
|
+
const url = `${this.config.host}${this.config.path}`;
|
|
35
81
|
const drops = [];
|
|
36
|
-
|
|
37
|
-
|
|
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;
|
|
38
94
|
for(let attempt = 1; attempt <= maxAttempts; attempt++){
|
|
95
|
+
if (signal?.aborted) return unsent(signal.reason, 'not sent: aborted');
|
|
39
96
|
const isLastAttempt = attempt === maxAttempts;
|
|
40
|
-
const payload =
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
historical_migration: true
|
|
44
|
-
} : {},
|
|
45
|
-
batch: pending
|
|
97
|
+
const payload = buildV1Body(pending, {
|
|
98
|
+
createdAt,
|
|
99
|
+
historicalMigration: this.config.historicalMigration
|
|
46
100
|
});
|
|
47
101
|
let captureAttempt;
|
|
48
102
|
let retryDelayMs;
|
|
49
103
|
try {
|
|
50
|
-
captureAttempt = await this.sendOnce(url, payload, attempt, requestId);
|
|
51
|
-
const { response, signal } = captureAttempt;
|
|
104
|
+
captureAttempt = await this.sendOnce(url, payload, attempt, requestId, signal);
|
|
105
|
+
const { response, signal: attemptSignal, redirectFailure } = captureAttempt;
|
|
52
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
|
+
}
|
|
53
113
|
if (status < 200 || status >= 300) if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {
|
|
54
114
|
const retryAfterMs = this.parseRetryAfter(response);
|
|
55
115
|
await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(()=>{});
|
|
56
116
|
retryDelayMs = this.backoffDelay(attempt, retryAfterMs);
|
|
57
117
|
} else {
|
|
58
118
|
const httpError = await this.buildHttpError(response, status, captureAttempt.waitFor);
|
|
59
|
-
|
|
119
|
+
this.surfaceBatchFailure(requestId, drops, pending, httpError, loss, `failed with HTTP ${status}`);
|
|
120
|
+
return [];
|
|
60
121
|
}
|
|
61
122
|
else {
|
|
62
123
|
let parsed;
|
|
63
124
|
try {
|
|
64
125
|
parsed = await captureAttempt.waitFor(this.parseResponse(response));
|
|
65
126
|
} catch (error) {
|
|
66
|
-
if (
|
|
67
|
-
|
|
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 [];
|
|
68
130
|
}
|
|
131
|
+
const dropsBefore = drops.length;
|
|
69
132
|
const retryable = this.classify(pending, parsed, drops);
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
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
|
+
}
|
|
76
150
|
pending = retryable;
|
|
77
151
|
const retryAfterMs = this.parseRetryAfter(response);
|
|
78
152
|
retryDelayMs = this.backoffDelay(attempt, retryAfterMs);
|
|
79
153
|
}
|
|
80
154
|
} catch (transportError) {
|
|
81
155
|
if (captureAttempt && !captureAttempt.signal.aborted) throw transportError;
|
|
82
|
-
if (isLastAttempt) return this.
|
|
156
|
+
if (isLastAttempt || signal?.aborted) return unsent(transportError, this.describeTransportFailure(transportError, signal));
|
|
83
157
|
retryDelayMs = this.backoffDelay(attempt);
|
|
84
158
|
} finally{
|
|
85
159
|
captureAttempt?.cleanup();
|
|
86
160
|
}
|
|
87
|
-
if (void 0 !== retryDelayMs) await this.
|
|
161
|
+
if (void 0 !== retryDelayMs) await this.sleepUnlessAborted(retryDelayMs, signal);
|
|
88
162
|
}
|
|
163
|
+
return [];
|
|
89
164
|
}
|
|
90
|
-
async
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
}
|
|
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);
|
|
99
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);
|
|
100
187
|
const controller = new AbortController();
|
|
101
188
|
let timeoutPhase = 'waiting for response headers';
|
|
102
189
|
let timer;
|
|
190
|
+
let onExternalAbort;
|
|
191
|
+
const stopListening = ()=>{
|
|
192
|
+
if (onExternalAbort) externalSignal?.removeEventListener('abort', onExternalAbort);
|
|
193
|
+
};
|
|
103
194
|
const deadline = new Promise((_resolve, reject)=>{
|
|
104
|
-
|
|
195
|
+
const abortWith = (error)=>{
|
|
196
|
+
reject(error);
|
|
197
|
+
controller.abort(error);
|
|
198
|
+
};
|
|
199
|
+
timer = setTimeout(()=>{
|
|
105
200
|
const timeoutError = new Error(`Capture V1 request timed out ${timeoutPhase} after ${this.config.requestTimeoutMs}ms`);
|
|
106
201
|
timeoutError.name = 'AbortError';
|
|
107
|
-
|
|
108
|
-
|
|
202
|
+
timeoutErrors.add(timeoutError);
|
|
203
|
+
abortWith(timeoutError);
|
|
109
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
|
+
}
|
|
110
217
|
});
|
|
218
|
+
deadline.catch(()=>{});
|
|
111
219
|
try {
|
|
112
|
-
const fetchPromise = this.
|
|
113
|
-
method: 'POST',
|
|
114
|
-
headers,
|
|
115
|
-
body,
|
|
116
|
-
signal: controller.signal
|
|
117
|
-
});
|
|
220
|
+
const fetchPromise = this.fetchFollowingRedirects(url, headers, body, controller.signal);
|
|
118
221
|
let responseAccepted = false;
|
|
119
|
-
fetchPromise.then((
|
|
120
|
-
if (controller.signal.aborted && !responseAccepted) this.cancelBody(
|
|
222
|
+
fetchPromise.then((late)=>{
|
|
223
|
+
if (controller.signal.aborted && !responseAccepted) this.cancelBody(late.response);
|
|
121
224
|
}).catch(()=>{});
|
|
122
|
-
const response = await Promise.race([
|
|
225
|
+
const { response, redirectFailure } = await Promise.race([
|
|
123
226
|
fetchPromise,
|
|
124
227
|
deadline
|
|
125
228
|
]);
|
|
@@ -130,6 +233,7 @@ class V1CaptureSender {
|
|
|
130
233
|
const cancelBody = ()=>cancellation ??= this.cancelBody(response);
|
|
131
234
|
return {
|
|
132
235
|
response,
|
|
236
|
+
redirectFailure,
|
|
133
237
|
signal: controller.signal,
|
|
134
238
|
waitFor: (operation)=>Promise.race([
|
|
135
239
|
operation,
|
|
@@ -140,14 +244,62 @@ class V1CaptureSender {
|
|
|
140
244
|
if (cleanedUp) return;
|
|
141
245
|
cleanedUp = true;
|
|
142
246
|
clearTimeout(timer);
|
|
247
|
+
stopListening();
|
|
143
248
|
if (controller.signal.aborted) cancelBody();
|
|
144
249
|
}
|
|
145
250
|
};
|
|
146
251
|
} catch (error) {
|
|
147
252
|
clearTimeout(timer);
|
|
253
|
+
stopListening();
|
|
148
254
|
throw error;
|
|
149
255
|
}
|
|
150
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
|
+
}
|
|
151
303
|
buildHeaders(attempt, requestId) {
|
|
152
304
|
const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`;
|
|
153
305
|
const headers = {
|
|
@@ -162,24 +314,39 @@ class V1CaptureSender {
|
|
|
162
314
|
return headers;
|
|
163
315
|
}
|
|
164
316
|
classify(pending, parsed, drops) {
|
|
165
|
-
const results =
|
|
317
|
+
const results = new Map();
|
|
318
|
+
for (const [uuid, result] of Object.entries(parsed.results))results.set(canonicalizeUuid(uuid) ?? uuid, result);
|
|
166
319
|
const retryable = [];
|
|
320
|
+
let copiesSeen;
|
|
167
321
|
for (const event of pending){
|
|
168
|
-
const result = results
|
|
169
|
-
if (result)
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
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
|
+
}
|
|
175
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);
|
|
176
342
|
}
|
|
177
343
|
return retryable;
|
|
178
344
|
}
|
|
179
345
|
backoffDelay(attempt, retryAfterMs) {
|
|
180
|
-
const
|
|
181
|
-
|
|
182
|
-
|
|
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));
|
|
183
350
|
}
|
|
184
351
|
parseRetryAfter(response) {
|
|
185
352
|
const raw = response.headers?.get('Retry-After');
|
|
@@ -199,9 +366,9 @@ class V1CaptureSender {
|
|
|
199
366
|
const parsed = JSON.parse(text);
|
|
200
367
|
if ('object' != typeof parsed || null === parsed || Array.isArray(parsed)) throw new Error('unexpected response shape');
|
|
201
368
|
const results = parsed.results;
|
|
202
|
-
if (
|
|
369
|
+
if ('object' != typeof results || null === results || Array.isArray(results)) throw new Error('unexpected results shape');
|
|
203
370
|
return {
|
|
204
|
-
results: results
|
|
371
|
+
results: results
|
|
205
372
|
};
|
|
206
373
|
}
|
|
207
374
|
async buildHttpError(response, status, waitFor) {
|
|
@@ -212,20 +379,36 @@ class V1CaptureSender {
|
|
|
212
379
|
const suffix = bodyText ? `: ${bodyText}` : '';
|
|
213
380
|
return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`);
|
|
214
381
|
}
|
|
215
|
-
surfaceBatchFailure(requestId, drops, pending, cause) {
|
|
216
|
-
|
|
382
|
+
surfaceBatchFailure(requestId, drops, pending, cause, loss, failure) {
|
|
383
|
+
loss.add(failure, pending.length);
|
|
384
|
+
this.report(this.captureError({
|
|
217
385
|
requestId,
|
|
218
386
|
drops,
|
|
219
387
|
retryExhausted: pending.map((event)=>event.uuid),
|
|
220
388
|
cause
|
|
221
|
-
}));
|
|
389
|
+
}), loss);
|
|
222
390
|
}
|
|
223
|
-
surfacePartialDrops(requestId, drops) {
|
|
224
|
-
if (drops.length > 0) this.
|
|
391
|
+
surfacePartialDrops(requestId, drops, loss) {
|
|
392
|
+
if (drops.length > 0) this.report(this.captureError({
|
|
225
393
|
requestId,
|
|
226
394
|
drops,
|
|
227
395
|
retryExhausted: []
|
|
228
|
-
}));
|
|
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
|
+
});
|
|
229
412
|
}
|
|
230
413
|
async cancelBody(response) {
|
|
231
414
|
try {
|
|
@@ -233,4 +416,19 @@ class V1CaptureSender {
|
|
|
233
416
|
} catch {}
|
|
234
417
|
}
|
|
235
418
|
}
|
|
236
|
-
|
|
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 };
|
|
@@ -0,0 +1,28 @@
|
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|
|
@@ -0,0 +1,82 @@
|
|
|
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
|
+
});
|
|
@@ -0,0 +1,38 @@
|
|
|
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 };
|