posthog-node 5.61.0 → 5.61.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.
@@ -45,43 +45,339 @@ function getUnhandledRejectionMode(execArgv = STARTUP_EXEC_ARGV, nodeOptions = S
45
45
  return findUnhandledRejectionMode(execArgv) ?? findUnhandledRejectionMode(splitNodeOptions(nodeOptions ?? '')) ?? 'throw';
46
46
  }
47
47
  const STARTUP_UNHANDLED_REJECTION_MODE = getUnhandledRejectionMode();
48
- function captureUncaughtException(captureFn, error, origin) {
49
- captureFn(error, {
50
- mechanism: {
51
- type: 'unhandledRejection' === origin ? 'onunhandledrejection' : 'onuncaughtexception',
52
- handled: false
48
+ function snapshotAsyncContext() {
49
+ try {
50
+ const process = globalThis.process;
51
+ const asyncHooks = process?.getBuiltinModule?.('node:async_hooks');
52
+ const snapshot = asyncHooks?.AsyncLocalStorage?.snapshot?.();
53
+ if (snapshot) return snapshot;
54
+ } catch {}
55
+ return (run)=>run();
56
+ }
57
+ const UNHANDLED_REJECTION_HINT = {
58
+ mechanism: {
59
+ type: 'onunhandledrejection',
60
+ handled: false
61
+ }
62
+ };
63
+ const UNCAUGHT_EXCEPTION_HINT = {
64
+ mechanism: {
65
+ type: 'onuncaughtexception',
66
+ handled: false
67
+ }
68
+ };
69
+ const CONTROL_FLOW_DIGESTS = new Set([
70
+ 'HANGING_PROMISE_REJECTION',
71
+ 'NEXT_PRERENDER_INTERRUPTED',
72
+ 'DYNAMIC_SERVER_USAGE',
73
+ 'BAILOUT_TO_CLIENT_SIDE_RENDERING'
74
+ ]);
75
+ const REACT_POSTPONE = Symbol.for('react.postpone');
76
+ const NEXT_REJECTION_FILTER = Symbol.for('next.unhandledRejectionFilter');
77
+ const NEXT_LISTENER_EVENT = 'Next.UnhandledRejectionFilter.MacguffinEvent';
78
+ const STATE_KEY = Symbol.for('posthog-node.exception-autocapture.v1');
79
+ const posthogGlobal = globalThis;
80
+ function isPostHogListener(listener) {
81
+ return 'function' == typeof listener && true === listener._posthogErrorHandler;
82
+ }
83
+ function isWeakKey(value) {
84
+ return 'object' == typeof value && null !== value || 'function' == typeof value;
85
+ }
86
+ function markListener(listener) {
87
+ return Object.assign(listener, {
88
+ _posthogErrorHandler: true
89
+ });
90
+ }
91
+ function hasHostUnhandledRejectionListener(process) {
92
+ return process.listeners('unhandledRejection').some((listener)=>!isPostHogListener(listener));
93
+ }
94
+ function isFrameworkControlFlow(reason, depth = 0) {
95
+ try {
96
+ if (!isWeakKey(reason)) return false;
97
+ const candidate = reason;
98
+ if (candidate.$$typeof === REACT_POSTPONE) return true;
99
+ if ('string' == typeof candidate.digest && CONTROL_FLOW_DIGESTS.has(candidate.digest)) return true;
100
+ return depth < 5 && isFrameworkControlFlow(candidate.cause, depth + 1);
101
+ } catch {
102
+ return false;
103
+ }
104
+ }
105
+ function isAbortError(reason) {
106
+ try {
107
+ return isWeakKey(reason) && 'AbortError' === reason.name;
108
+ } catch {
109
+ return false;
110
+ }
111
+ }
112
+ function isIgnored(exception, origin) {
113
+ return isFrameworkControlFlow(exception) || 'unhandledRejection' === origin && isAbortError(exception);
114
+ }
115
+ function captureTargets(state) {
116
+ const targets = new Map();
117
+ for (const client of state.clients){
118
+ const chosen = targets.get(client.key);
119
+ if (!chosen || void 0 === chosen.getContext() && void 0 !== client.getContext()) targets.set(client.key, client);
120
+ }
121
+ for (const [key, client] of state.retired)if (!targets.has(key)) targets.set(key, client);
122
+ return [
123
+ ...targets.values()
124
+ ];
125
+ }
126
+ function nextTurn(callback) {
127
+ if ('function' == typeof globalThis.setImmediate) setImmediate(callback);
128
+ else setTimeout(callback, 0);
129
+ }
130
+ function scheduleTurnReset(state) {
131
+ if (state.turnResetScheduled) return;
132
+ state.turnResetScheduled = true;
133
+ nextTurn(()=>{
134
+ nextTurn(()=>{
135
+ state.capturedThisTurn.clear();
136
+ state.turnResetScheduled = false;
137
+ });
138
+ });
139
+ }
140
+ function recordCapture(state, exception, key, source) {
141
+ const captured = state.capturedThisTurn.get(exception) ?? new Map();
142
+ if (!captured.has(key)) captured.set(key, source);
143
+ state.capturedThisTurn.set(exception, captured);
144
+ scheduleTurnReset(state);
145
+ }
146
+ function wasCapturedThisTurn(state, exception) {
147
+ const captured = state.capturedThisTurn.get(exception);
148
+ return void 0 !== captured && captureTargets(state).every((client)=>captured.has(client.key));
149
+ }
150
+ function dispatch(state, exception, hint, skipKeys) {
151
+ const captured = state.capturedThisTurn.get(exception);
152
+ const owners = [];
153
+ for (const client of captureTargets(state))if (!(captured?.has(client.key) || skipKeys?.has(client.key))) {
154
+ recordCapture(state, exception, client.key, 'autocapture');
155
+ client.capture(exception, hint);
156
+ owners.push(client);
157
+ }
158
+ return owners;
159
+ }
160
+ function captureDeferred(state, deferred) {
161
+ if (state.deferred.get(deferred.exception) !== deferred) return [];
162
+ state.deferred.delete(deferred.exception);
163
+ return deferred.runInContext(()=>dispatch(state, deferred.exception, deferred.hint, deferred.skipKeys));
164
+ }
165
+ function deferCapture(state, exception, hint) {
166
+ if (wasCapturedThisTurn(state, exception) || state.deferred.has(exception)) return;
167
+ const deferred = {
168
+ exception,
169
+ hint,
170
+ skipKeys: new Set(state.capturedThisTurn.get(exception)?.keys()),
171
+ runInContext: snapshotAsyncContext()
172
+ };
173
+ state.deferred.set(exception, deferred);
174
+ nextTurn(()=>captureDeferred(state, deferred));
175
+ }
176
+ async function exitAfterFatalError(state, error) {
177
+ try {
178
+ console.error(error);
179
+ } catch {}
180
+ capturePendingExceptions();
181
+ const clients = new Set([
182
+ ...state.clients,
183
+ ...state.retired.values()
184
+ ]);
185
+ await Promise.all([
186
+ ...clients
187
+ ].map((client)=>client.shutdown().catch(()=>void 0)));
188
+ globalThis.process.exit(1);
189
+ }
190
+ function captureUncaughtException(state, error, origin, fatal) {
191
+ const hint = 'unhandledRejection' === origin ? UNHANDLED_REJECTION_HINT : UNCAUGHT_EXCEPTION_HINT;
192
+ if (!fatal) {
193
+ if (!isIgnored(error, origin)) deferCapture(state, error, hint);
194
+ return;
195
+ }
196
+ const deferred = state.deferred.get(error);
197
+ if (deferred) captureDeferred(state, deferred);
198
+ else dispatch(state, error, hint);
199
+ }
200
+ function makeUncaughtExceptionHandler(state) {
201
+ return markListener((error, origin)=>{
202
+ const process = globalThis.process;
203
+ const userProvidedListenersCount = process.listeners('uncaughtException').filter((listener)=>'domainUncaughtExceptionClear' !== listener.name && !isPostHogListener(listener)).length;
204
+ const fatal = 0 === userProvidedListenersCount;
205
+ captureUncaughtException(state, error, origin, fatal);
206
+ if (fatal && !state.calledFatalError) {
207
+ state.calledFatalError = true;
208
+ exitAfterFatalError(state, error);
53
209
  }
54
210
  });
55
211
  }
56
- function makeUncaughtExceptionHandler(captureFn, onFatalFn) {
57
- let calledFatalError = false;
58
- return Object.assign((error, origin)=>{
59
- const userProvidedListenersCount = global.process.listeners('uncaughtException').filter((listener)=>'domainUncaughtExceptionClear' !== listener.name && true !== listener._posthogErrorHandler).length;
60
- captureUncaughtException(captureFn, error, origin);
61
- if (!calledFatalError && 0 === userProvidedListenersCount) {
62
- calledFatalError = true;
63
- onFatalFn(error);
212
+ function describeReason(reason) {
213
+ try {
214
+ return String(reason);
215
+ } catch {
216
+ return typeof reason;
217
+ }
218
+ }
219
+ function toUnhandledRejectionError(reason) {
220
+ if (reason instanceof Error) return reason;
221
+ const error = new Error(`This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "${describeReason(reason)}".`);
222
+ return Object.assign(error, {
223
+ name: 'UnhandledPromiseRejection',
224
+ code: 'ERR_UNHANDLED_REJECTION'
225
+ });
226
+ }
227
+ function applyDefaultRejectionHandling(state, reason) {
228
+ const process = globalThis.process;
229
+ if ('warn-with-error-code' === state.mode) {
230
+ process.emitWarning(`Unhandled promise rejection: ${describeReason(reason)}`, 'UnhandledPromiseRejectionWarning');
231
+ process.exitCode = 1;
232
+ if (!isIgnored(reason, 'unhandledRejection')) dispatch(state, reason, UNHANDLED_REJECTION_HINT);
233
+ return;
234
+ }
235
+ if (process.versions?.bun) {
236
+ process.exitCode = 1;
237
+ dispatch(state, reason, UNHANDLED_REJECTION_HINT);
238
+ if (!state.calledFatalError) {
239
+ state.calledFatalError = true;
240
+ exitAfterFatalError(state, reason);
64
241
  }
65
- }, {
66
- _posthogErrorHandler: true
242
+ return;
243
+ }
244
+ const escalated = toUnhandledRejectionError(reason);
245
+ const emit = process.emit;
246
+ emit.call(process, 'uncaughtExceptionMonitor', escalated, 'unhandledRejection');
247
+ emit.call(process, 'uncaughtException', escalated, 'unhandledRejection');
248
+ }
249
+ function makeUnhandledRejectionHandler(state, replacesDefaultHandling, isInstalled) {
250
+ return markListener((reason)=>{
251
+ if (replacesDefaultHandling && !hasHostUnhandledRejectionListener(globalThis.process) && isInstalled()) return void applyDefaultRejectionHandling(state, reason);
252
+ if (!isIgnored(reason, 'unhandledRejection')) deferCapture(state, reason, UNHANDLED_REJECTION_HINT);
67
253
  });
68
254
  }
69
- function addUncaughtExceptionListener(captureFn, onFatalFn, mode = STARTUP_UNHANDLED_REJECTION_MODE) {
255
+ function joinHostRejectionQueue(listener) {
70
256
  const process = globalThis.process;
71
- if (!process) return;
72
- if ('strict' === mode) return void process.on('uncaughtExceptionMonitor', (error, origin)=>captureUncaughtException(captureFn, error, origin));
73
- process.on('uncaughtException', makeUncaughtExceptionHandler(captureFn, onFatalFn));
257
+ if (!posthogGlobal[NEXT_REJECTION_FILTER] || 'function' != typeof process.rawListeners) return;
258
+ if (!process.rawListeners('unhandledRejection').includes(listener)) return;
259
+ const removeListener = Object.getPrototypeOf(process).removeListener;
260
+ removeListener.call(process, 'unhandledRejection', listener);
261
+ if (!process.listeners('unhandledRejection').includes(listener)) process.prependListener('unhandledRejection', listener);
74
262
  }
75
- function addUnhandledRejectionListener(captureFn, mode = STARTUP_UNHANDLED_REJECTION_MODE) {
263
+ function installListeners(state) {
76
264
  const process = globalThis.process;
77
- if (!process || 'throw' === mode || 'strict' === mode || 'warn-with-error-code' === mode) return;
78
- process.on('unhandledRejection', (reason)=>{
79
- captureFn(reason, {
80
- mechanism: {
81
- type: 'onunhandledrejection',
82
- handled: false
83
- }
265
+ const removals = [];
266
+ const listen = (event, listener)=>{
267
+ process.on(event, listener);
268
+ removals.push(()=>process.removeListener(event, listener));
269
+ };
270
+ const remove = ()=>removals.forEach((removal)=>removal());
271
+ if ('strict' === state.mode) {
272
+ const monitor = (error, origin)=>captureUncaughtException(state, error, origin, true);
273
+ listen('uncaughtExceptionMonitor', monitor);
274
+ return {
275
+ remove,
276
+ areInstalled: ()=>process.listeners('uncaughtExceptionMonitor').includes(monitor)
277
+ };
278
+ }
279
+ const uncaughtExceptionHandler = makeUncaughtExceptionHandler(state);
280
+ listen('uncaughtException', uncaughtExceptionHandler);
281
+ const replacesDefaultHandling = 'throw' === state.mode || 'warn-with-error-code' === state.mode;
282
+ const followsHostListeners = replacesDefaultHandling && !process.versions?.bun;
283
+ const isInstalled = ()=>process.listeners('unhandledRejection').includes(listener);
284
+ const listener = makeUnhandledRejectionHandler(state, replacesDefaultHandling, isInstalled);
285
+ const keepFirst = ()=>{
286
+ const raw = 'function' == typeof process.rawListeners ? process.rawListeners('unhandledRejection') : [];
287
+ if (raw.includes(listener) && raw[0] !== listener) {
288
+ process.removeListener('unhandledRejection', listener);
289
+ process.prependListener('unhandledRejection', listener);
290
+ }
291
+ };
292
+ listen('newListener', markListener((event, added)=>{
293
+ if (isPostHogListener(added)) return;
294
+ if ('unhandledRejection' === event) {
295
+ if (!isInstalled()) process.prependListener('unhandledRejection', listener);
296
+ queueMicrotask(()=>{
297
+ keepFirst();
298
+ joinHostRejectionQueue(listener);
299
+ });
300
+ } else if (event === NEXT_LISTENER_EVENT) queueMicrotask(()=>{
301
+ if (!isInstalled()) process.prependListener('unhandledRejection', listener);
84
302
  });
303
+ }));
304
+ if (followsHostListeners) {
305
+ listen('removeListener', markListener((event)=>{
306
+ if ('unhandledRejection' === event && isInstalled() && !hasHostUnhandledRejectionListener(process)) process.removeListener('unhandledRejection', listener);
307
+ }));
308
+ if (hasHostUnhandledRejectionListener(process)) process.prependListener('unhandledRejection', listener);
309
+ } else process.prependListener('unhandledRejection', listener);
310
+ joinHostRejectionQueue(listener);
311
+ removals.push(()=>{
312
+ process.removeListener('unhandledRejection', listener);
313
+ if ('function' == typeof process.rawListeners && process.rawListeners('unhandledRejection').includes(listener)) {
314
+ const removeListener = Object.getPrototypeOf(process).removeListener;
315
+ removeListener.call(process, 'unhandledRejection', listener);
316
+ }
85
317
  });
318
+ return {
319
+ remove,
320
+ areInstalled: ()=>process.listeners('uncaughtException').includes(uncaughtExceptionHandler) && (followsHostListeners || isInstalled())
321
+ };
322
+ }
323
+ function startExceptionAutocapture(client, mode = STARTUP_UNHANDLED_REJECTION_MODE) {
324
+ if (!globalThis.process?.on) return ()=>void 0;
325
+ let state = posthogGlobal[STATE_KEY];
326
+ if (state) {
327
+ if (!state.listeners.areInstalled()) {
328
+ state.listeners.remove();
329
+ state.listeners = installListeners(state);
330
+ }
331
+ } else {
332
+ const created = {
333
+ mode,
334
+ clients: new Set(),
335
+ retired: new Map(),
336
+ capturedThisTurn: new Map(),
337
+ deferred: new Map(),
338
+ turnResetScheduled: false,
339
+ calledFatalError: false,
340
+ listeners: {
341
+ remove: ()=>void 0,
342
+ areInstalled: ()=>true
343
+ }
344
+ };
345
+ created.listeners = installListeners(created);
346
+ posthogGlobal[STATE_KEY] = created;
347
+ state = created;
348
+ }
349
+ state.clients.add(client);
350
+ state.retired.delete(client.key);
351
+ const activeState = state;
352
+ return ()=>{
353
+ if (!activeState.clients.delete(client)) return;
354
+ if (![
355
+ ...activeState.clients
356
+ ].some((other)=>other.key === client.key)) activeState.retired.set(client.key, client);
357
+ };
358
+ }
359
+ function claimExplicitCapture(error, key) {
360
+ const state = posthogGlobal[STATE_KEY];
361
+ if (!state) return true;
362
+ if (state.capturedThisTurn.get(error)?.get(key) === 'autocapture') return false;
363
+ recordCapture(state, error, key, 'app');
364
+ state.deferred.get(error)?.skipKeys.add(key);
365
+ return true;
366
+ }
367
+ function capturePendingExceptions() {
368
+ const owners = new Set();
369
+ const state = posthogGlobal[STATE_KEY];
370
+ if (state) for (const deferred of [
371
+ ...state.deferred.values()
372
+ ])captureDeferred(state, deferred).forEach((owner)=>owners.add(owner));
373
+ return owners;
374
+ }
375
+ function resetExceptionAutocapture() {
376
+ const state = posthogGlobal[STATE_KEY];
377
+ if (state) {
378
+ state.deferred.clear();
379
+ state.listeners.remove();
380
+ delete posthogGlobal[STATE_KEY];
381
+ }
86
382
  }
87
- export { addUncaughtExceptionListener, addUnhandledRejectionListener, getUnhandledRejectionMode };
383
+ export { capturePendingExceptions, claimExplicitCapture, getUnhandledRejectionMode, resetExceptionAutocapture, startExceptionAutocapture };
@@ -8,12 +8,27 @@ export default class ErrorTracking {
8
8
  private _exceptionAutocaptureEnabled;
9
9
  private _rateLimiter;
10
10
  private _logger;
11
+ private _autocaptureClient?;
12
+ private _stopAutocapture?;
11
13
  constructor(client: PostHogBackendClient, options: PostHogOptions, _logger: Logger);
12
14
  static isPreviouslyCapturedError(x: unknown): boolean;
13
15
  static buildEventMessage(builder: CoreErrorTracking.ErrorPropertiesBuilder, error: unknown, hint: CoreErrorTracking.EventHint, distinctId?: string, additionalProperties?: Record<string | number, any>, context?: ContextData): Promise<EventMessage>;
16
+ private get destinationKey();
14
17
  private startAutocaptureIfEnabled;
18
+ /**
19
+ * Whether captureException should capture this error. False when exception autocapture already sent the same error
20
+ * object to this project in this turn of the event loop, for example when a framework passes an error from its own
21
+ * process listener to an error hook that calls captureException.
22
+ */
23
+ claimExplicitCapture(error: unknown): boolean;
24
+ /**
25
+ * Captures at once the exceptions autocapture holds until the end of the turn, so that this client's flush or
26
+ * shutdown sends them: an app's crash handler often flushes or shuts the client down and exits before the turn ends.
27
+ * The capture can land in another client of the project, the one whose request context is active, so this client
28
+ * waits for that client's flush too.
29
+ */
30
+ capturePendingExceptions(): void;
15
31
  private onException;
16
- private onFatalError;
17
32
  isEnabled(): boolean;
18
33
  shutdown(): void;
19
34
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/extensions/error-tracking/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAA;AAC/C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AAGnD,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AACtD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAA;AAE3C,OAAO,EAAE,aAAa,IAAI,iBAAiB,EAAE,MAAM,eAAe,CAAA;AAIlE,MAAM,CAAC,OAAO,OAAO,aAAa;IAChC,OAAO,CAAC,MAAM,CAAsB;IACpC,OAAO,CAAC,4BAA4B,CAAS;IAC7C,OAAO,CAAC,YAAY,CAA6B;IACjD,OAAO,CAAC,OAAO,CAAQ;IAEvB,YAAY,MAAM,EAAE,oBAAoB,EAAE,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAsBjF;IAED,MAAM,CAAC,yBAAyB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAEpD;IAED,OAAa,iBAAiB,CAC5B,OAAO,EAAE,iBAAiB,CAAC,sBAAsB,EACjD,KAAK,EAAE,OAAO,EACd,IAAI,EAAE,iBAAiB,CAAC,SAAS,EACjC,UAAU,CAAC,EAAE,MAAM,EACnB,oBAAoB,CAAC,EAAE,MAAM,CAAC,MAAM,GAAG,MAAM,EAAE,GAAG,CAAC,EACnD,OAAO,CAAC,EAAE,WAAW,GACpB,OAAO,CAAC,YAAY,CAAC,CAuBvB;IAED,OAAO,CAAC,yBAAyB;IAOjC,OAAO,CAAC,WAAW;YA2BL,YAAY;IAM1B,SAAS,IAAI,OAAO,CAEnB;IAED,QAAQ,IAAI,IAAI,CAEf;CACF"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/extensions/error-tracking/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAA;AAC/C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AAGnD,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AACtD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAA;AAE3C,OAAO,EAAE,aAAa,IAAI,iBAAiB,EAAE,MAAM,eAAe,CAAA;AAIlE,MAAM,CAAC,OAAO,OAAO,aAAa;IAChC,OAAO,CAAC,MAAM,CAAsB;IACpC,OAAO,CAAC,4BAA4B,CAAS;IAC7C,OAAO,CAAC,YAAY,CAA6B;IACjD,OAAO,CAAC,OAAO,CAAQ;IACvB,OAAO,CAAC,kBAAkB,CAAC,CAAmB;IAC9C,OAAO,CAAC,gBAAgB,CAAC,CAAY;IAErC,YAAY,MAAM,EAAE,oBAAoB,EAAE,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAsBjF;IAED,MAAM,CAAC,yBAAyB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAEpD;IAED,OAAa,iBAAiB,CAC5B,OAAO,EAAE,iBAAiB,CAAC,sBAAsB,EACjD,KAAK,EAAE,OAAO,EACd,IAAI,EAAE,iBAAiB,CAAC,SAAS,EACjC,UAAU,CAAC,EAAE,MAAM,EACnB,oBAAoB,CAAC,EAAE,MAAM,CAAC,MAAM,GAAG,MAAM,EAAE,GAAG,CAAC,EACnD,OAAO,CAAC,EAAE,WAAW,GACpB,OAAO,CAAC,YAAY,CAAC,CAuBvB;IAGD,OAAO,KAAK,cAAc,GAEzB;IAED,OAAO,CAAC,yBAAyB;IAajC;;;;OAIG;IACH,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAE5C;IAED;;;;;OAKG;IACH,wBAAwB,IAAI,IAAI,CAM/B;IAED,OAAO,CAAC,WAAW;IA+BnB,SAAS,IAAI,OAAO,CAEnB;IAED,QAAQ,IAAI,IAAI,CAKf;CACF"}
@@ -68,12 +68,27 @@ class ErrorTracking {
68
68
  _originatedFromCaptureException: true
69
69
  });
70
70
  }
71
+ get destinationKey() {
72
+ return `${this.client.apiKey}@${this.client.host}`;
73
+ }
71
74
  startAutocaptureIfEnabled() {
72
75
  if (this.isEnabled()) {
73
- (0, external_autocapture_js_namespaceObject.addUncaughtExceptionListener)(this.onException.bind(this), this.onFatalError.bind(this));
74
- (0, external_autocapture_js_namespaceObject.addUnhandledRejectionListener)(this.onException.bind(this));
76
+ this._autocaptureClient = {
77
+ key: this.destinationKey,
78
+ capture: (exception, hint)=>this.onException(exception, hint),
79
+ getContext: ()=>this.client.getContext(),
80
+ flush: ()=>this.client.flush(),
81
+ shutdown: ()=>this.client.shutdown(SHUTDOWN_TIMEOUT)
82
+ };
83
+ this._stopAutocapture = (0, external_autocapture_js_namespaceObject.startExceptionAutocapture)(this._autocaptureClient);
75
84
  }
76
85
  }
86
+ claimExplicitCapture(error) {
87
+ return (0, external_autocapture_js_namespaceObject.claimExplicitCapture)(error, this.destinationKey);
88
+ }
89
+ capturePendingExceptions() {
90
+ for (const owner of (0, external_autocapture_js_namespaceObject.capturePendingExceptions)())if (owner !== this._autocaptureClient) this.client.addPendingPromise(owner.flush().catch(()=>void 0));
91
+ }
77
92
  onException(exception, hint) {
78
93
  this.client.addPendingPromise((async ()=>{
79
94
  if (!ErrorTracking.isPreviouslyCapturedError(exception)) {
@@ -86,18 +101,18 @@ class ErrorTracking {
86
101
  });
87
102
  return this.client._capturePreparedEvent(eventMessage, false);
88
103
  }
89
- })());
90
- }
91
- async onFatalError(exception) {
92
- console.error(exception);
93
- await this.client.shutdown(SHUTDOWN_TIMEOUT);
94
- globalThis.process.exit(1);
104
+ })().catch((error)=>{
105
+ this._logger.error('Failed to capture an exception:', error);
106
+ }));
95
107
  }
96
108
  isEnabled() {
97
109
  return !this.client.isDisabled && this._exceptionAutocaptureEnabled;
98
110
  }
99
111
  shutdown() {
100
112
  this._rateLimiter.stop();
113
+ this.capturePendingExceptions();
114
+ this._stopAutocapture?.();
115
+ this._stopAutocapture = void 0;
101
116
  }
102
117
  }
103
118
  exports["default"] = __webpack_exports__["default"];
@@ -1,4 +1,4 @@
1
- import { addUncaughtExceptionListener, addUnhandledRejectionListener } from "./autocapture.mjs";
1
+ import { capturePendingExceptions, claimExplicitCapture, startExceptionAutocapture } from "./autocapture.mjs";
2
2
  import { snapshotEventContext } from "../context/event-context.mjs";
3
3
  import { BucketedRateLimiter, ErrorTracking, isObject, resolveExceptionRateLimiterConfig } from "@posthog/core";
4
4
  const SHUTDOWN_TIMEOUT = 2000;
@@ -36,12 +36,27 @@ class error_tracking_ErrorTracking {
36
36
  _originatedFromCaptureException: true
37
37
  });
38
38
  }
39
+ get destinationKey() {
40
+ return `${this.client.apiKey}@${this.client.host}`;
41
+ }
39
42
  startAutocaptureIfEnabled() {
40
43
  if (this.isEnabled()) {
41
- addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this));
42
- addUnhandledRejectionListener(this.onException.bind(this));
44
+ this._autocaptureClient = {
45
+ key: this.destinationKey,
46
+ capture: (exception, hint)=>this.onException(exception, hint),
47
+ getContext: ()=>this.client.getContext(),
48
+ flush: ()=>this.client.flush(),
49
+ shutdown: ()=>this.client.shutdown(SHUTDOWN_TIMEOUT)
50
+ };
51
+ this._stopAutocapture = startExceptionAutocapture(this._autocaptureClient);
43
52
  }
44
53
  }
54
+ claimExplicitCapture(error) {
55
+ return claimExplicitCapture(error, this.destinationKey);
56
+ }
57
+ capturePendingExceptions() {
58
+ for (const owner of capturePendingExceptions())if (owner !== this._autocaptureClient) this.client.addPendingPromise(owner.flush().catch(()=>void 0));
59
+ }
45
60
  onException(exception, hint) {
46
61
  this.client.addPendingPromise((async ()=>{
47
62
  if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(exception)) {
@@ -54,18 +69,18 @@ class error_tracking_ErrorTracking {
54
69
  });
55
70
  return this.client._capturePreparedEvent(eventMessage, false);
56
71
  }
57
- })());
58
- }
59
- async onFatalError(exception) {
60
- console.error(exception);
61
- await this.client.shutdown(SHUTDOWN_TIMEOUT);
62
- globalThis.process.exit(1);
72
+ })().catch((error)=>{
73
+ this._logger.error('Failed to capture an exception:', error);
74
+ }));
63
75
  }
64
76
  isEnabled() {
65
77
  return !this.client.isDisabled && this._exceptionAutocaptureEnabled;
66
78
  }
67
79
  shutdown() {
68
80
  this._rateLimiter.stop();
81
+ this.capturePendingExceptions();
82
+ this._stopAutocapture?.();
83
+ this._stopAutocapture = void 0;
69
84
  }
70
85
  }
71
86
  export default error_tracking_ErrorTracking;
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export declare const version = "5.61.0";
1
+ export declare const version = "5.61.1";
2
2
  //# sourceMappingURL=version.d.ts.map
package/dist/version.js CHANGED
@@ -27,7 +27,7 @@ var __webpack_require__ = {};
27
27
  })();
28
28
  var __webpack_exports__ = {};
29
29
  __webpack_require__.r(__webpack_exports__);
30
- const version = "5.61.0";
30
+ const version = "5.61.1";
31
31
  __webpack_require__.d(__webpack_exports__, {}, {
32
32
  version: version
33
33
  });
package/dist/version.mjs CHANGED
@@ -1,2 +1,2 @@
1
- const version = "5.61.0";
1
+ const version = "5.61.1";
2
2
  export { version };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "posthog-node",
3
- "version": "5.61.0",
3
+ "version": "5.61.1",
4
4
  "bugs": {
5
5
  "url": "https://github.com/PostHog/posthog-js/issues"
6
6
  },
package/src/client.ts CHANGED
@@ -362,6 +362,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
362
362
  }
363
363
 
364
364
  override async flush(): Promise<void> {
365
+ // An app's crash handler often flushes and exits before the end of the turn, when autocapture would capture.
366
+ this.errorTracking.capturePendingExceptions()
365
367
  return this._flushKeepingRuntimeAlive(false)
366
368
  }
367
369
 
@@ -3266,7 +3268,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3266
3268
  uuid?: EventMessage['uuid'],
3267
3269
  flags?: FeatureFlagEvaluations
3268
3270
  ): void {
3269
- if (!ErrorTracking.isPreviouslyCapturedError(error)) {
3271
+ if (!ErrorTracking.isPreviouslyCapturedError(error) && this.errorTracking.claimExplicitCapture(error)) {
3270
3272
  const syntheticException = new Error('PostHog syntheticException')
3271
3273
  this.addPendingPromise(
3272
3274
  ErrorTracking.buildEventMessage(
@@ -3323,7 +3325,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3323
3325
  additionalProperties?: Record<string | number, any>,
3324
3326
  flags?: FeatureFlagEvaluations
3325
3327
  ): Promise<void> {
3326
- if (!ErrorTracking.isPreviouslyCapturedError(error)) {
3328
+ if (!ErrorTracking.isPreviouslyCapturedError(error) && this.errorTracking.claimExplicitCapture(error)) {
3327
3329
  const syntheticException = new Error('PostHog syntheticException')
3328
3330
  return this.addPendingPromise(
3329
3331
  ErrorTracking.buildEventMessage(