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.
@@ -3,8 +3,11 @@
3
3
  // Licensed under the MIT License: https://github.com/getsentry/sentry-javascript/blob/develop/LICENSE
4
4
 
5
5
  import { ErrorTracking as CoreErrorTracking } from '@posthog/core'
6
+ import type { ContextData } from '../context/types'
6
7
 
7
- type ErrorHandler = { _posthogErrorHandler: boolean } & NodeJS.UncaughtExceptionListener
8
+ type PostHogListener = { _posthogErrorHandler: boolean }
9
+ type ErrorHandler = PostHogListener & NodeJS.UncaughtExceptionListener
10
+ type RejectionHandler = PostHogListener & NodeJS.UnhandledRejectionListener
8
11
  type UnhandledRejectionMode = 'throw' | 'strict' | 'warn' | 'warn-with-error-code' | 'none'
9
12
 
10
13
  const UNHANDLED_REJECTION_OPTION_NAMES = ['--unhandled-rejections', '--unhandled_rejections']
@@ -80,83 +83,602 @@ export function getUnhandledRejectionMode(
80
83
 
81
84
  const STARTUP_UNHANDLED_REJECTION_MODE = getUnhandledRejectionMode()
82
85
 
86
+ /** A client that captures exceptions through the shared process listeners. */
87
+ export type AutocaptureClient = {
88
+ // Clients with the same project token and host send to the same project, so only one of them captures.
89
+ key: string
90
+ capture: (exception: unknown, hint: CoreErrorTracking.EventHint) => void
91
+ // Each client keeps its own request context, set with withContext.
92
+ getContext: () => ContextData | undefined
93
+ // Sends what the client holds, for a flush or shutdown of another client of the project.
94
+ flush: () => Promise<void>
95
+ // Sends what the client still holds. Called before a fatal exit.
96
+ shutdown: () => Promise<void>
97
+ }
98
+
99
+ type ContextRunner = <T>(run: () => T) => T
100
+
101
+ type AsyncHooksModule = { AsyncLocalStorage?: { snapshot?: () => ContextRunner } }
102
+
103
+ // The async context an exception was reported in: every AsyncLocalStorage, so each client's request context and the
104
+ // active OpenTelemetry span. A capture that a flush or shutdown elsewhere forces early still reports that request.
105
+ function snapshotAsyncContext(): ContextRunner {
106
+ try {
107
+ const process = globalThis.process as { getBuiltinModule?: (id: string) => unknown } | undefined
108
+ const asyncHooks = process?.getBuiltinModule?.('node:async_hooks') as AsyncHooksModule | undefined
109
+ const snapshot = asyncHooks?.AsyncLocalStorage?.snapshot?.()
110
+ if (snapshot) {
111
+ return snapshot
112
+ }
113
+ } catch {
114
+ // A runtime without AsyncLocalStorage.snapshot has nothing to restore.
115
+ }
116
+ return (run) => run()
117
+ }
118
+
119
+ const UNHANDLED_REJECTION_HINT: CoreErrorTracking.EventHint = {
120
+ mechanism: { type: 'onunhandledrejection', handled: false },
121
+ }
122
+ const UNCAUGHT_EXCEPTION_HINT: CoreErrorTracking.EventHint = {
123
+ mechanism: { type: 'onuncaughtexception', handled: false },
124
+ }
125
+
126
+ // Next.js and React pass these through rejections and throws as control flow. @sentry/nextjs drops the same set.
127
+ const CONTROL_FLOW_DIGESTS = new Set([
128
+ 'HANGING_PROMISE_REJECTION',
129
+ 'NEXT_PRERENDER_INTERRUPTED',
130
+ 'DYNAMIC_SERVER_USAGE',
131
+ 'BAILOUT_TO_CLIENT_SIDE_RENDERING',
132
+ ])
133
+ const REACT_POSTPONE = Symbol.for('react.postpone')
134
+ const NEXT_REJECTION_FILTER = Symbol.for('next.unhandledRejectionFilter')
135
+
136
+ // Next.js 16's patched process.on announces an unhandledRejection listener through this event instead.
137
+ const NEXT_LISTENER_EVENT = 'Next.UnhandledRejectionFilter.MacguffinEvent'
138
+
139
+ // Shared through globalThis, so that every client and every copy of this module in the process (bundlers can load
140
+ // posthog-node more than once, for example in Next.js's separate server layers) use one set of process listeners.
141
+ // Bump the version in this key whenever the shape of what it holds changes.
142
+ const STATE_KEY = Symbol.for('posthog-node.exception-autocapture.v1')
143
+
144
+ type CaptureSource = 'autocapture' | 'app'
145
+
146
+ // A capture waiting for the end of the current turn of the event loop.
147
+ type DeferredCapture = {
148
+ exception: unknown
149
+ hint: CoreErrorTracking.EventHint
150
+ // The projects the app captured the exception for itself, which autocapture skips.
151
+ skipKeys: Set<string>
152
+ runInContext: ContextRunner
153
+ }
154
+
155
+ type AutocaptureState = {
156
+ mode: UnhandledRejectionMode
157
+ clients: Set<AutocaptureClient>
158
+ // The last client of each project that shut down. It keeps capturing until another client of the project starts,
159
+ // as the listeners of a shut-down client always did, so that a client per request still captures between requests.
160
+ retired: Map<string, AutocaptureClient>
161
+ // Who captured each exception for each project during this turn: autocapture, or the app through captureException.
162
+ // A host that rethrows a rejection, a runtime that reports one twice, and an app that captures an error and rethrows
163
+ // it all hand over the same exception again before the turn ends. Primitives compare by value. The same error object
164
+ // in a later turn is a new occurrence.
165
+ capturedThisTurn: Map<unknown, Map<string, CaptureSource>>
166
+ // Captures waiting for the end of the turn, by exception.
167
+ deferred: Map<unknown, DeferredCapture>
168
+ turnResetScheduled: boolean
169
+ calledFatalError: boolean
170
+ listeners: InstalledListeners
171
+ }
172
+
173
+ type InstalledListeners = {
174
+ remove: () => void
175
+ // False once the app has removed them, for example with process.removeAllListeners().
176
+ areInstalled: () => boolean
177
+ }
178
+
179
+ type PostHogGlobal = typeof globalThis & {
180
+ [STATE_KEY]?: AutocaptureState
181
+ [NEXT_REJECTION_FILTER]?: boolean
182
+ }
183
+
184
+ const posthogGlobal = globalThis as PostHogGlobal
185
+
186
+ function isPostHogListener(listener: unknown): boolean {
187
+ return typeof listener === 'function' && (listener as Partial<PostHogListener>)._posthogErrorHandler === true
188
+ }
189
+
190
+ function isWeakKey(value: unknown): value is object {
191
+ return (typeof value === 'object' && value !== null) || typeof value === 'function'
192
+ }
193
+
194
+ function markListener<T extends (...args: any[]) => unknown>(listener: T): T & PostHogListener {
195
+ return Object.assign(listener, { _posthogErrorHandler: true })
196
+ }
197
+
198
+ function hasHostUnhandledRejectionListener(process: NodeJS.Process): boolean {
199
+ return process.listeners('unhandledRejection').some((listener) => !isPostHogListener(listener))
200
+ }
201
+
202
+ function isFrameworkControlFlow(reason: unknown, depth = 0): boolean {
203
+ try {
204
+ if (!isWeakKey(reason)) {
205
+ return false
206
+ }
207
+ const candidate = reason as { $$typeof?: unknown; digest?: unknown; cause?: unknown }
208
+ if (candidate.$$typeof === REACT_POSTPONE) {
209
+ return true
210
+ }
211
+ if (typeof candidate.digest === 'string' && CONTROL_FLOW_DIGESTS.has(candidate.digest)) {
212
+ return true
213
+ }
214
+ return depth < 5 && isFrameworkControlFlow(candidate.cause, depth + 1)
215
+ } catch {
216
+ // A throwing getter or a revoked proxy is not a framework signal.
217
+ return false
218
+ }
219
+ }
220
+
221
+ // An abort the app started itself and never awaited, for example a cancelled fetch. Sentry ignores these too.
222
+ function isAbortError(reason: unknown): boolean {
223
+ try {
224
+ return isWeakKey(reason) && (reason as { name?: unknown }).name === 'AbortError'
225
+ } catch {
226
+ return false
227
+ }
228
+ }
229
+
230
+ function isIgnored(exception: unknown, origin: NodeJS.UncaughtExceptionOrigin | 'unhandledRejection'): boolean {
231
+ return isFrameworkControlFlow(exception) || (origin === 'unhandledRejection' && isAbortError(exception))
232
+ }
233
+
234
+ // One client per project: a running one if there is one, otherwise the last one that shut down. Among running
235
+ // clients, the one whose request context is active here, since no other client of the project can see it.
236
+ function captureTargets(state: AutocaptureState): AutocaptureClient[] {
237
+ const targets = new Map<string, AutocaptureClient>()
238
+ for (const client of state.clients) {
239
+ const chosen = targets.get(client.key)
240
+ if (!chosen || (chosen.getContext() === undefined && client.getContext() !== undefined)) {
241
+ targets.set(client.key, client)
242
+ }
243
+ }
244
+ for (const [key, client] of state.retired) {
245
+ if (!targets.has(key)) {
246
+ targets.set(key, client)
247
+ }
248
+ }
249
+ return [...targets.values()]
250
+ }
251
+
252
+ // Runs after the microtasks the current callback queued. A runtime without setImmediate gets the next timer, which also
253
+ // runs after them: a throw from our listener would turn every rejection into a crash. Not unref'd: an unref'd immediate
254
+ // does not wake an idle event loop, which would stretch the turn until the next I/O or timer, and drop an occurrence
255
+ // that comes in the meantime.
256
+ function nextTurn(callback: () => void): void {
257
+ if (typeof globalThis.setImmediate === 'function') {
258
+ setImmediate(callback)
259
+ } else {
260
+ setTimeout(callback, 0)
261
+ }
262
+ }
263
+
264
+ function scheduleTurnReset(state: AutocaptureState): void {
265
+ if (state.turnResetScheduled) {
266
+ return
267
+ }
268
+ state.turnResetScheduled = true
269
+ // Two immediates: a capture at the end of the turn runs in an immediate, and a host can rethrow the error from an
270
+ // immediate of its own (Next.js 16's filter does) or one more hop later. A real second occurrence of the same error
271
+ // object within that window counts once.
272
+ nextTurn(() => {
273
+ nextTurn(() => {
274
+ state.capturedThisTurn.clear()
275
+ state.turnResetScheduled = false
276
+ })
277
+ })
278
+ }
279
+
280
+ function recordCapture(state: AutocaptureState, exception: unknown, key: string, source: CaptureSource): void {
281
+ const captured = state.capturedThisTurn.get(exception) ?? new Map<string, CaptureSource>()
282
+ if (!captured.has(key)) {
283
+ captured.set(key, source)
284
+ }
285
+ state.capturedThisTurn.set(exception, captured)
286
+ scheduleTurnReset(state)
287
+ }
288
+
289
+ function wasCapturedThisTurn(state: AutocaptureState, exception: unknown): boolean {
290
+ const captured = state.capturedThisTurn.get(exception)
291
+ return captured !== undefined && captureTargets(state).every((client) => captured.has(client.key))
292
+ }
293
+
294
+ // Sends the exception to every project that has not received it in this turn.
295
+ function dispatch(
296
+ state: AutocaptureState,
297
+ exception: unknown,
298
+ hint: CoreErrorTracking.EventHint,
299
+ skipKeys?: Set<string>
300
+ ): AutocaptureClient[] {
301
+ const captured = state.capturedThisTurn.get(exception)
302
+ const owners: AutocaptureClient[] = []
303
+ for (const client of captureTargets(state)) {
304
+ if (captured?.has(client.key) || skipKeys?.has(client.key)) {
305
+ continue
306
+ }
307
+ recordCapture(state, exception, client.key, 'autocapture')
308
+ client.capture(exception, hint)
309
+ owners.push(client)
310
+ }
311
+ return owners
312
+ }
313
+
314
+ // Returns the clients that captured it.
315
+ function captureDeferred(state: AutocaptureState, deferred: DeferredCapture): AutocaptureClient[] {
316
+ if (state.deferred.get(deferred.exception) !== deferred) {
317
+ return []
318
+ }
319
+ state.deferred.delete(deferred.exception)
320
+ return deferred.runInContext(() => dispatch(state, deferred.exception, deferred.hint, deferred.skipKeys))
321
+ }
322
+
323
+ // Used when the process survives the exception. The host's listeners run after ours, and a framework's error hook a
324
+ // microtask later, so capturing at the end of the turn lets the app's own capture win, with the identity and
325
+ // properties it passes.
326
+ function deferCapture(state: AutocaptureState, exception: unknown, hint: CoreErrorTracking.EventHint): void {
327
+ if (wasCapturedThisTurn(state, exception) || state.deferred.has(exception)) {
328
+ return
329
+ }
330
+ const deferred: DeferredCapture = {
331
+ exception,
332
+ hint,
333
+ skipKeys: new Set(state.capturedThisTurn.get(exception)?.keys()),
334
+ runInContext: snapshotAsyncContext(),
335
+ }
336
+ state.deferred.set(exception, deferred)
337
+ nextTurn(() => captureDeferred(state, deferred))
338
+ }
339
+
340
+ async function exitAfterFatalError(state: AutocaptureState, error: unknown): Promise<void> {
341
+ try {
342
+ console.error(error)
343
+ } catch {
344
+ // An error whose inspection throws must not stop the exit.
345
+ }
346
+ // Captures waiting for the end of the turn would go down with the process.
347
+ capturePendingExceptions()
348
+ const clients = new Set([...state.clients, ...state.retired.values()])
349
+ await Promise.all([...clients].map((client) => client.shutdown().catch(() => undefined)))
350
+ globalThis.process.exit(1)
351
+ }
352
+
83
353
  function captureUncaughtException(
84
- captureFn: (exception: Error, hint: CoreErrorTracking.EventHint) => void,
85
- error: Error,
86
- origin: NodeJS.UncaughtExceptionOrigin
354
+ state: AutocaptureState,
355
+ error: unknown,
356
+ origin: NodeJS.UncaughtExceptionOrigin,
357
+ fatal: boolean
87
358
  ): void {
88
- captureFn(error, {
89
- mechanism: {
90
- type: origin === 'unhandledRejection' ? 'onunhandledrejection' : 'onuncaughtexception',
91
- handled: false,
92
- },
359
+ const hint = origin === 'unhandledRejection' ? UNHANDLED_REJECTION_HINT : UNCAUGHT_EXCEPTION_HINT
360
+ if (!fatal) {
361
+ // The app handles uncaught exceptions itself, and its listener may capture this one.
362
+ if (!isIgnored(error, origin)) {
363
+ deferCapture(state, error, hint)
364
+ }
365
+ return
366
+ }
367
+ // A crash is captured whatever the error, an abort or a framework's control flow included.
368
+ // A host listener that rethrew a rejection: one occurrence, reported as the rejection it was.
369
+ const deferred = state.deferred.get(error)
370
+ if (deferred) {
371
+ captureDeferred(state, deferred)
372
+ } else {
373
+ dispatch(state, error, hint)
374
+ }
375
+ }
376
+
377
+ function makeUncaughtExceptionHandler(state: AutocaptureState): ErrorHandler {
378
+ return markListener((error: Error, origin: NodeJS.UncaughtExceptionOrigin): void => {
379
+ const process = globalThis.process
380
+ // Like Sentry, we only consider listeners that are currently registered. We intentionally do not reconstruct
381
+ // participation by once listeners or listeners added or removed during dispatch.
382
+ const userProvidedListenersCount = process.listeners('uncaughtException').filter((listener) => {
383
+ return listener.name !== 'domainUncaughtExceptionClear' && !isPostHogListener(listener)
384
+ }).length
385
+ const fatal = userProvidedListenersCount === 0
386
+
387
+ captureUncaughtException(state, error, origin, fatal)
388
+
389
+ if (fatal && !state.calledFatalError) {
390
+ state.calledFatalError = true
391
+ void exitAfterFatalError(state, error)
392
+ }
93
393
  })
94
394
  }
95
395
 
96
- function makeUncaughtExceptionHandler(
97
- captureFn: (exception: Error, hint: CoreErrorTracking.EventHint) => void,
98
- onFatalFn: (exception: Error) => void
99
- ): ErrorHandler {
100
- let calledFatalError: boolean = false
101
-
102
- return Object.assign(
103
- (error: Error, origin: NodeJS.UncaughtExceptionOrigin): void => {
104
- // Like Sentry, we only consider listeners that are currently registered. We intentionally do not reconstruct
105
- // participation by once listeners or listeners added or removed during dispatch.
106
- const userProvidedListenersCount = global.process.listeners('uncaughtException').filter((listener) => {
107
- return (
108
- listener.name !== 'domainUncaughtExceptionClear' &&
109
- (listener as Partial<ErrorHandler>)._posthogErrorHandler !== true
110
- )
111
- }).length
112
-
113
- captureUncaughtException(captureFn, error, origin)
114
-
115
- if (!calledFatalError && userProvidedListenersCount === 0) {
116
- calledFatalError = true
117
- onFatalFn(error)
118
- }
119
- },
120
- { _posthogErrorHandler: true }
396
+ // String() throws for a null-prototype object or a revoked proxy.
397
+ function describeReason(reason: unknown): string {
398
+ try {
399
+ return String(reason)
400
+ } catch {
401
+ return typeof reason
402
+ }
403
+ }
404
+
405
+ // The error Node raises in throw mode for a rejection whose reason is not an Error.
406
+ function toUnhandledRejectionError(reason: unknown): Error {
407
+ if (reason instanceof Error) {
408
+ return reason
409
+ }
410
+ const error = new Error(
411
+ `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)}".`
121
412
  )
413
+ return Object.assign(error, { name: 'UnhandledPromiseRejection', code: 'ERR_UNHANDLED_REJECTION' })
122
414
  }
123
415
 
124
- export function addUncaughtExceptionListener(
125
- captureFn: (exception: Error, hint: CoreErrorTracking.EventHint) => void,
126
- onFatalFn: (exception: Error) => void,
127
- mode: UnhandledRejectionMode = STARTUP_UNHANDLED_REJECTION_MODE
128
- ): void {
416
+ // No host listener is left, but ours still runs: the host's listener went away without a removeListener event (Bun
417
+ // never emits one), or the runtime does not escalate rejections at all (Bun again). Our listener has stopped the
418
+ // runtime's default handling, so do what the runtime would have done without it.
419
+ function applyDefaultRejectionHandling(state: AutocaptureState, reason: unknown): void {
129
420
  const process = globalThis.process
130
- if (!process) {
421
+ if (state.mode === 'warn-with-error-code') {
422
+ process.emitWarning(`Unhandled promise rejection: ${describeReason(reason)}`, 'UnhandledPromiseRejectionWarning')
423
+ process.exitCode = 1
424
+ if (!isIgnored(reason, 'unhandledRejection')) {
425
+ dispatch(state, reason, UNHANDLED_REJECTION_HINT)
426
+ }
131
427
  return
132
428
  }
133
429
 
134
- if (mode === 'strict') {
135
- process.on('uncaughtExceptionMonitor', (error, origin) => captureUncaughtException(captureFn, error, origin))
430
+ if (process.versions?.bun) {
431
+ // Bun exits on an unhandled rejection without emitting uncaughtException. When nothing else is pending, it also
432
+ // ends the process right after this listener, without running anything the listener started, so set the exit code
433
+ // now. A crash is captured whatever the error.
434
+ process.exitCode = 1
435
+ dispatch(state, reason, UNHANDLED_REJECTION_HINT)
436
+ if (!state.calledFatalError) {
437
+ state.calledFatalError = true
438
+ void exitAfterFatalError(state, reason)
439
+ }
136
440
  return
137
441
  }
138
442
 
139
- process.on('uncaughtException', makeUncaughtExceptionHandler(captureFn, onFatalFn))
443
+ // Node escalates the rejection to the uncaught-exception listeners, with the origin 'unhandledRejection'. Ours is one
444
+ // of them: it captures the rejection, and exits unless the app handles uncaught exceptions itself.
445
+ const escalated = toUnhandledRejectionError(reason)
446
+ const emit = process.emit as (event: string, ...args: unknown[]) => boolean
447
+ emit.call(process, 'uncaughtExceptionMonitor', escalated, 'unhandledRejection')
448
+ emit.call(process, 'uncaughtException', escalated, 'unhandledRejection')
140
449
  }
141
450
 
142
- export function addUnhandledRejectionListener(
143
- captureFn: (exception: unknown, hint: CoreErrorTracking.EventHint) => void,
144
- mode: UnhandledRejectionMode = STARTUP_UNHANDLED_REJECTION_MODE
145
- ): void {
146
- const process = globalThis.process
451
+ // replacesDefaultHandling: in throw and warn-with-error-code modes, an unhandledRejection listener replaces the
452
+ // runtime's default handling, so ours must reproduce it when it is the only one left.
453
+ function makeUnhandledRejectionHandler(
454
+ state: AutocaptureState,
455
+ replacesDefaultHandling: boolean,
456
+ isInstalled: () => boolean
457
+ ): RejectionHandler {
458
+ return markListener((reason: unknown): void => {
459
+ // Our listener runs first, so a host listener that is gone now was not there when the rejection was emitted, unless
460
+ // ours went with it: a once listener, or one that removes itself, takes ours along through the removeListener
461
+ // handler, and the emit still calls ours from its copy of the list.
462
+ if (replacesDefaultHandling && !hasHostUnhandledRejectionListener(globalThis.process) && isInstalled()) {
463
+ applyDefaultRejectionHandling(state, reason)
464
+ return
465
+ }
466
+ if (!isIgnored(reason, 'unhandledRejection')) {
467
+ deferCapture(state, reason, UNHANDLED_REJECTION_HINT)
468
+ }
469
+ })
470
+ }
147
471
 
148
- // Installing an unhandledRejection listener changes Node's behavior in these modes. We intentionally skip capture
149
- // rather than reproducing Node's fatal handling or warn-with-error-code warning and exit-code semantics in the SDK.
150
- if (!process || mode === 'throw' || mode === 'strict' || mode === 'warn-with-error-code') {
472
+ // Next.js 16 moves every unhandledRejection listener into a queue behind one filtering listener, and patches
473
+ // process.on and process.listeners so that later listeners join that queue too. The filter drops rejections from
474
+ // prerenders Next has aborted on purpose. A listener left on the process in front of the filter would capture those,
475
+ // and one in both places would capture everything twice, so move ours into the queue once the filter is in place.
476
+ function joinHostRejectionQueue(listener: RejectionHandler): void {
477
+ const process = globalThis.process
478
+ if (!posthogGlobal[NEXT_REJECTION_FILTER] || typeof process.rawListeners !== 'function') {
479
+ return
480
+ }
481
+ if (!process.rawListeners('unhandledRejection').includes(listener)) {
151
482
  return
152
483
  }
484
+ // Next patches the methods on the process object itself, so the prototype's removeListener still reaches the
485
+ // process's real listener list.
486
+ const removeListener = Object.getPrototypeOf(process).removeListener as NodeJS.Process['removeListener']
487
+ removeListener.call(process, 'unhandledRejection', listener)
488
+ if (!process.listeners('unhandledRejection').includes(listener)) {
489
+ process.prependListener('unhandledRejection', listener)
490
+ }
491
+ }
153
492
 
154
- process.on('unhandledRejection', (reason: unknown) => {
155
- captureFn(reason, {
156
- mechanism: {
157
- type: 'onunhandledrejection',
158
- handled: false,
159
- },
493
+ function installListeners(state: AutocaptureState): InstalledListeners {
494
+ const process = globalThis.process
495
+ const removals: (() => void)[] = []
496
+ const listen = (event: string, listener: (...args: any[]) => void): void => {
497
+ process.on(event, listener)
498
+ removals.push(() => process.removeListener(event, listener))
499
+ }
500
+ const remove = (): void => removals.forEach((removal) => removal())
501
+
502
+ if (state.mode === 'strict') {
503
+ // Strict mode raises the rejection as an uncaught exception before any unhandledRejection listener runs, and the
504
+ // process exits right after.
505
+ const monitor = (error: Error, origin: NodeJS.UncaughtExceptionOrigin): void =>
506
+ captureUncaughtException(state, error, origin, true)
507
+ listen('uncaughtExceptionMonitor', monitor)
508
+ return { remove, areInstalled: () => process.listeners('uncaughtExceptionMonitor').includes(monitor) }
509
+ }
510
+
511
+ const uncaughtExceptionHandler = makeUncaughtExceptionHandler(state)
512
+ listen('uncaughtException', uncaughtExceptionHandler)
513
+
514
+ // In throw and warn-with-error-code modes, any unhandledRejection listener stops Node's default handling (the
515
+ // escalation to uncaughtException, or the warning and exit code). We listen only while the host has a listener of
516
+ // its own, which has already stopped that handling, so the SDK never changes what Node does with the rejection.
517
+ // Bun never escalates a rejection, so there we always listen and reproduce its exit when no host listener is left.
518
+ const replacesDefaultHandling = state.mode === 'throw' || state.mode === 'warn-with-error-code'
519
+ const followsHostListeners = replacesDefaultHandling && !process.versions?.bun
520
+ const isInstalled = (): boolean => process.listeners('unhandledRejection').includes(listener)
521
+ const listener = makeUnhandledRejectionHandler(state, replacesDefaultHandling, isInstalled)
522
+
523
+ // Ours runs before the host's listeners, so that it sees them as they were when the rejection was emitted.
524
+ const keepFirst = (): void => {
525
+ const raw = typeof process.rawListeners === 'function' ? process.rawListeners('unhandledRejection') : []
526
+ if (raw.includes(listener) && raw[0] !== listener) {
527
+ process.removeListener('unhandledRejection', listener)
528
+ process.prependListener('unhandledRejection', listener)
529
+ }
530
+ }
531
+
532
+ // newListener is emitted before the host listener is added, so ours is in place for the next rejection. Adding ours
533
+ // back here also recovers from a host that cleared every listener with removeAllListeners.
534
+ listen(
535
+ 'newListener',
536
+ markListener((event: string | symbol, added: unknown) => {
537
+ if (isPostHogListener(added)) {
538
+ return
539
+ }
540
+ if (event === 'unhandledRejection') {
541
+ if (!isInstalled()) {
542
+ process.prependListener('unhandledRejection', listener)
543
+ }
544
+ queueMicrotask(() => {
545
+ keepFirst()
546
+ joinHostRejectionQueue(listener)
547
+ })
548
+ } else if (event === NEXT_LISTENER_EVENT) {
549
+ // Once Next's process.on has queued the host listener, ours joins the same queue if it is not there.
550
+ queueMicrotask(() => {
551
+ if (!isInstalled()) {
552
+ process.prependListener('unhandledRejection', listener)
553
+ }
554
+ })
555
+ }
160
556
  })
557
+ )
558
+
559
+ if (!followsHostListeners) {
560
+ process.prependListener('unhandledRejection', listener)
561
+ } else {
562
+ // removeListener is emitted after the removal. Without a host listener, ours would stop Node's default handling.
563
+ listen(
564
+ 'removeListener',
565
+ markListener((event: string | symbol) => {
566
+ if (event === 'unhandledRejection' && isInstalled() && !hasHostUnhandledRejectionListener(process)) {
567
+ process.removeListener('unhandledRejection', listener)
568
+ }
569
+ })
570
+ )
571
+ if (hasHostUnhandledRejectionListener(process)) {
572
+ process.prependListener('unhandledRejection', listener)
573
+ }
574
+ }
575
+ joinHostRejectionQueue(listener)
576
+ removals.push(() => {
577
+ process.removeListener('unhandledRejection', listener)
578
+ if (typeof process.rawListeners === 'function' && process.rawListeners('unhandledRejection').includes(listener)) {
579
+ const removeListener = Object.getPrototypeOf(process).removeListener as NodeJS.Process['removeListener']
580
+ removeListener.call(process, 'unhandledRejection', listener)
581
+ }
161
582
  })
583
+ return {
584
+ remove,
585
+ // In warn and none modes, and on Bun, the rejection listener is always installed.
586
+ areInstalled: () =>
587
+ process.listeners('uncaughtException').includes(uncaughtExceptionHandler) &&
588
+ (followsHostListeners || isInstalled()),
589
+ }
590
+ }
591
+
592
+ /**
593
+ * Captures uncaught exceptions and unhandled rejections for a client, through one set of process listeners shared by
594
+ * every client in the process. Returns a function the client calls on shutdown. The listeners stay for the life of
595
+ * the process, as they always have, and the last client of a project keeps capturing after it shuts down until
596
+ * another client of the project starts.
597
+ */
598
+ export function startExceptionAutocapture(
599
+ client: AutocaptureClient,
600
+ mode: UnhandledRejectionMode = STARTUP_UNHANDLED_REJECTION_MODE
601
+ ): () => void {
602
+ if (!globalThis.process?.on) {
603
+ return () => undefined
604
+ }
605
+
606
+ let state = posthogGlobal[STATE_KEY]
607
+ if (!state) {
608
+ const created: AutocaptureState = {
609
+ mode,
610
+ clients: new Set(),
611
+ retired: new Map(),
612
+ capturedThisTurn: new Map(),
613
+ deferred: new Map(),
614
+ turnResetScheduled: false,
615
+ calledFatalError: false,
616
+ listeners: { remove: () => undefined, areInstalled: () => true },
617
+ }
618
+ created.listeners = installListeners(created)
619
+ posthogGlobal[STATE_KEY] = created
620
+ state = created
621
+ } else if (!state.listeners.areInstalled()) {
622
+ // The app removed them, for example with process.removeAllListeners(). A new client always added its own.
623
+ state.listeners.remove()
624
+ state.listeners = installListeners(state)
625
+ }
626
+ state.clients.add(client)
627
+ state.retired.delete(client.key)
628
+
629
+ const activeState = state
630
+ return () => {
631
+ if (!activeState.clients.delete(client)) {
632
+ return
633
+ }
634
+ if (![...activeState.clients].some((other) => other.key === client.key)) {
635
+ activeState.retired.set(client.key, client)
636
+ }
637
+ }
638
+ }
639
+
640
+ /**
641
+ * Records an error passed to captureException, and reports whether to capture it: false when autocapture already sent
642
+ * this error to the project during this turn. Otherwise the app's capture wins, and autocapture skips the error for the
643
+ * project for the rest of the turn. The same occurrence comes both ways when a framework hands an error from its own
644
+ * process listener to an error hook that calls captureException (Nitro's error hook, which @posthog/nuxt captures),
645
+ * and when an app captures an error and rethrows it. A capture of the same error object in a later turn is a new
646
+ * occurrence.
647
+ */
648
+ export function claimExplicitCapture(error: unknown, key: string): boolean {
649
+ const state = posthogGlobal[STATE_KEY]
650
+ if (!state) {
651
+ return true
652
+ }
653
+ if (state.capturedThisTurn.get(error)?.get(key) === 'autocapture') {
654
+ return false
655
+ }
656
+ recordCapture(state, error, key, 'app')
657
+ state.deferred.get(error)?.skipKeys.add(key)
658
+ return true
659
+ }
660
+
661
+ /**
662
+ * Captures at once the exceptions waiting for the end of the turn. A flush or shutdown calls this first: an app's
663
+ * crash handler often flushes or shuts the client down and exits before the turn ends.
664
+ */
665
+ export function capturePendingExceptions(): Set<AutocaptureClient> {
666
+ const owners = new Set<AutocaptureClient>()
667
+ const state = posthogGlobal[STATE_KEY]
668
+ if (state) {
669
+ for (const deferred of [...state.deferred.values()]) {
670
+ captureDeferred(state, deferred).forEach((owner) => owners.add(owner))
671
+ }
672
+ }
673
+ return owners
674
+ }
675
+
676
+ /** @internal Removes the shared listeners and forgets every client, for tests. */
677
+ export function resetExceptionAutocapture(): void {
678
+ const state = posthogGlobal[STATE_KEY]
679
+ if (state) {
680
+ state.deferred.clear()
681
+ state.listeners.remove()
682
+ delete posthogGlobal[STATE_KEY]
683
+ }
162
684
  }