posthog-node 5.60.1 → 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.
Files changed (43) hide show
  1. package/dist/client.d.ts +34 -0
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +33 -4
  4. package/dist/client.mjs +33 -4
  5. package/dist/emails/emails.d.ts +45 -0
  6. package/dist/emails/emails.d.ts.map +1 -0
  7. package/dist/emails/emails.js +360 -0
  8. package/dist/emails/emails.mjs +316 -0
  9. package/dist/emails/errors.d.ts +37 -0
  10. package/dist/emails/errors.d.ts.map +1 -0
  11. package/dist/emails/errors.js +79 -0
  12. package/dist/emails/errors.mjs +41 -0
  13. package/dist/emails/types.d.ts +112 -0
  14. package/dist/emails/types.d.ts.map +1 -0
  15. package/dist/emails/types.js +18 -0
  16. package/dist/emails/types.mjs +1 -0
  17. package/dist/exports.d.ts +3 -0
  18. package/dist/exports.d.ts.map +1 -1
  19. package/dist/exports.js +19 -9
  20. package/dist/exports.mjs +1 -0
  21. package/dist/extensions/error-tracking/autocapture.d.ts +32 -2
  22. package/dist/extensions/error-tracking/autocapture.d.ts.map +1 -1
  23. package/dist/extensions/error-tracking/autocapture.js +337 -35
  24. package/dist/extensions/error-tracking/autocapture.mjs +324 -28
  25. package/dist/extensions/error-tracking/index.d.ts +16 -1
  26. package/dist/extensions/error-tracking/index.d.ts.map +1 -1
  27. package/dist/extensions/error-tracking/index.js +23 -8
  28. package/dist/extensions/error-tracking/index.mjs +24 -9
  29. package/dist/types.d.ts +33 -2
  30. package/dist/types.d.ts.map +1 -1
  31. package/dist/version.d.ts +1 -1
  32. package/dist/version.js +1 -1
  33. package/dist/version.mjs +1 -1
  34. package/package.json +2 -2
  35. package/src/client.ts +76 -3
  36. package/src/emails/emails.ts +459 -0
  37. package/src/emails/errors.ts +90 -0
  38. package/src/emails/types.ts +108 -0
  39. package/src/exports.ts +12 -0
  40. package/src/extensions/error-tracking/autocapture.ts +579 -57
  41. package/src/extensions/error-tracking/index.ts +48 -10
  42. package/src/types.ts +34 -2
  43. package/src/version.ts +1 -1
@@ -74,57 +74,359 @@ function getUnhandledRejectionMode(execArgv = STARTUP_EXEC_ARGV, nodeOptions = S
74
74
  return findUnhandledRejectionMode(execArgv) ?? findUnhandledRejectionMode(splitNodeOptions(nodeOptions ?? '')) ?? 'throw';
75
75
  }
76
76
  const STARTUP_UNHANDLED_REJECTION_MODE = getUnhandledRejectionMode();
77
- function captureUncaughtException(captureFn, error, origin) {
78
- captureFn(error, {
79
- mechanism: {
80
- type: 'unhandledRejection' === origin ? 'onunhandledrejection' : 'onuncaughtexception',
81
- handled: false
77
+ function snapshotAsyncContext() {
78
+ try {
79
+ const process = globalThis.process;
80
+ const asyncHooks = process?.getBuiltinModule?.('node:async_hooks');
81
+ const snapshot = asyncHooks?.AsyncLocalStorage?.snapshot?.();
82
+ if (snapshot) return snapshot;
83
+ } catch {}
84
+ return (run)=>run();
85
+ }
86
+ const UNHANDLED_REJECTION_HINT = {
87
+ mechanism: {
88
+ type: 'onunhandledrejection',
89
+ handled: false
90
+ }
91
+ };
92
+ const UNCAUGHT_EXCEPTION_HINT = {
93
+ mechanism: {
94
+ type: 'onuncaughtexception',
95
+ handled: false
96
+ }
97
+ };
98
+ const CONTROL_FLOW_DIGESTS = new Set([
99
+ 'HANGING_PROMISE_REJECTION',
100
+ 'NEXT_PRERENDER_INTERRUPTED',
101
+ 'DYNAMIC_SERVER_USAGE',
102
+ 'BAILOUT_TO_CLIENT_SIDE_RENDERING'
103
+ ]);
104
+ const REACT_POSTPONE = Symbol.for('react.postpone');
105
+ const NEXT_REJECTION_FILTER = Symbol.for('next.unhandledRejectionFilter');
106
+ const NEXT_LISTENER_EVENT = 'Next.UnhandledRejectionFilter.MacguffinEvent';
107
+ const STATE_KEY = Symbol.for('posthog-node.exception-autocapture.v1');
108
+ const posthogGlobal = globalThis;
109
+ function isPostHogListener(listener) {
110
+ return 'function' == typeof listener && true === listener._posthogErrorHandler;
111
+ }
112
+ function isWeakKey(value) {
113
+ return 'object' == typeof value && null !== value || 'function' == typeof value;
114
+ }
115
+ function markListener(listener) {
116
+ return Object.assign(listener, {
117
+ _posthogErrorHandler: true
118
+ });
119
+ }
120
+ function hasHostUnhandledRejectionListener(process) {
121
+ return process.listeners('unhandledRejection').some((listener)=>!isPostHogListener(listener));
122
+ }
123
+ function isFrameworkControlFlow(reason, depth = 0) {
124
+ try {
125
+ if (!isWeakKey(reason)) return false;
126
+ const candidate = reason;
127
+ if (candidate.$$typeof === REACT_POSTPONE) return true;
128
+ if ('string' == typeof candidate.digest && CONTROL_FLOW_DIGESTS.has(candidate.digest)) return true;
129
+ return depth < 5 && isFrameworkControlFlow(candidate.cause, depth + 1);
130
+ } catch {
131
+ return false;
132
+ }
133
+ }
134
+ function isAbortError(reason) {
135
+ try {
136
+ return isWeakKey(reason) && 'AbortError' === reason.name;
137
+ } catch {
138
+ return false;
139
+ }
140
+ }
141
+ function isIgnored(exception, origin) {
142
+ return isFrameworkControlFlow(exception) || 'unhandledRejection' === origin && isAbortError(exception);
143
+ }
144
+ function captureTargets(state) {
145
+ const targets = new Map();
146
+ for (const client of state.clients){
147
+ const chosen = targets.get(client.key);
148
+ if (!chosen || void 0 === chosen.getContext() && void 0 !== client.getContext()) targets.set(client.key, client);
149
+ }
150
+ for (const [key, client] of state.retired)if (!targets.has(key)) targets.set(key, client);
151
+ return [
152
+ ...targets.values()
153
+ ];
154
+ }
155
+ function nextTurn(callback) {
156
+ if ('function' == typeof globalThis.setImmediate) setImmediate(callback);
157
+ else setTimeout(callback, 0);
158
+ }
159
+ function scheduleTurnReset(state) {
160
+ if (state.turnResetScheduled) return;
161
+ state.turnResetScheduled = true;
162
+ nextTurn(()=>{
163
+ nextTurn(()=>{
164
+ state.capturedThisTurn.clear();
165
+ state.turnResetScheduled = false;
166
+ });
167
+ });
168
+ }
169
+ function recordCapture(state, exception, key, source) {
170
+ const captured = state.capturedThisTurn.get(exception) ?? new Map();
171
+ if (!captured.has(key)) captured.set(key, source);
172
+ state.capturedThisTurn.set(exception, captured);
173
+ scheduleTurnReset(state);
174
+ }
175
+ function wasCapturedThisTurn(state, exception) {
176
+ const captured = state.capturedThisTurn.get(exception);
177
+ return void 0 !== captured && captureTargets(state).every((client)=>captured.has(client.key));
178
+ }
179
+ function dispatch(state, exception, hint, skipKeys) {
180
+ const captured = state.capturedThisTurn.get(exception);
181
+ const owners = [];
182
+ for (const client of captureTargets(state))if (!(captured?.has(client.key) || skipKeys?.has(client.key))) {
183
+ recordCapture(state, exception, client.key, 'autocapture');
184
+ client.capture(exception, hint);
185
+ owners.push(client);
186
+ }
187
+ return owners;
188
+ }
189
+ function captureDeferred(state, deferred) {
190
+ if (state.deferred.get(deferred.exception) !== deferred) return [];
191
+ state.deferred.delete(deferred.exception);
192
+ return deferred.runInContext(()=>dispatch(state, deferred.exception, deferred.hint, deferred.skipKeys));
193
+ }
194
+ function deferCapture(state, exception, hint) {
195
+ if (wasCapturedThisTurn(state, exception) || state.deferred.has(exception)) return;
196
+ const deferred = {
197
+ exception,
198
+ hint,
199
+ skipKeys: new Set(state.capturedThisTurn.get(exception)?.keys()),
200
+ runInContext: snapshotAsyncContext()
201
+ };
202
+ state.deferred.set(exception, deferred);
203
+ nextTurn(()=>captureDeferred(state, deferred));
204
+ }
205
+ async function exitAfterFatalError(state, error) {
206
+ try {
207
+ console.error(error);
208
+ } catch {}
209
+ capturePendingExceptions();
210
+ const clients = new Set([
211
+ ...state.clients,
212
+ ...state.retired.values()
213
+ ]);
214
+ await Promise.all([
215
+ ...clients
216
+ ].map((client)=>client.shutdown().catch(()=>void 0)));
217
+ globalThis.process.exit(1);
218
+ }
219
+ function captureUncaughtException(state, error, origin, fatal) {
220
+ const hint = 'unhandledRejection' === origin ? UNHANDLED_REJECTION_HINT : UNCAUGHT_EXCEPTION_HINT;
221
+ if (!fatal) {
222
+ if (!isIgnored(error, origin)) deferCapture(state, error, hint);
223
+ return;
224
+ }
225
+ const deferred = state.deferred.get(error);
226
+ if (deferred) captureDeferred(state, deferred);
227
+ else dispatch(state, error, hint);
228
+ }
229
+ function makeUncaughtExceptionHandler(state) {
230
+ return markListener((error, origin)=>{
231
+ const process = globalThis.process;
232
+ const userProvidedListenersCount = process.listeners('uncaughtException').filter((listener)=>'domainUncaughtExceptionClear' !== listener.name && !isPostHogListener(listener)).length;
233
+ const fatal = 0 === userProvidedListenersCount;
234
+ captureUncaughtException(state, error, origin, fatal);
235
+ if (fatal && !state.calledFatalError) {
236
+ state.calledFatalError = true;
237
+ exitAfterFatalError(state, error);
82
238
  }
83
239
  });
84
240
  }
85
- function makeUncaughtExceptionHandler(captureFn, onFatalFn) {
86
- let calledFatalError = false;
87
- return Object.assign((error, origin)=>{
88
- const userProvidedListenersCount = global.process.listeners('uncaughtException').filter((listener)=>'domainUncaughtExceptionClear' !== listener.name && true !== listener._posthogErrorHandler).length;
89
- captureUncaughtException(captureFn, error, origin);
90
- if (!calledFatalError && 0 === userProvidedListenersCount) {
91
- calledFatalError = true;
92
- onFatalFn(error);
241
+ function describeReason(reason) {
242
+ try {
243
+ return String(reason);
244
+ } catch {
245
+ return typeof reason;
246
+ }
247
+ }
248
+ function toUnhandledRejectionError(reason) {
249
+ if (reason instanceof Error) return reason;
250
+ 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)}".`);
251
+ return Object.assign(error, {
252
+ name: 'UnhandledPromiseRejection',
253
+ code: 'ERR_UNHANDLED_REJECTION'
254
+ });
255
+ }
256
+ function applyDefaultRejectionHandling(state, reason) {
257
+ const process = globalThis.process;
258
+ if ('warn-with-error-code' === state.mode) {
259
+ process.emitWarning(`Unhandled promise rejection: ${describeReason(reason)}`, 'UnhandledPromiseRejectionWarning');
260
+ process.exitCode = 1;
261
+ if (!isIgnored(reason, 'unhandledRejection')) dispatch(state, reason, UNHANDLED_REJECTION_HINT);
262
+ return;
263
+ }
264
+ if (process.versions?.bun) {
265
+ process.exitCode = 1;
266
+ dispatch(state, reason, UNHANDLED_REJECTION_HINT);
267
+ if (!state.calledFatalError) {
268
+ state.calledFatalError = true;
269
+ exitAfterFatalError(state, reason);
93
270
  }
94
- }, {
95
- _posthogErrorHandler: true
271
+ return;
272
+ }
273
+ const escalated = toUnhandledRejectionError(reason);
274
+ const emit = process.emit;
275
+ emit.call(process, 'uncaughtExceptionMonitor', escalated, 'unhandledRejection');
276
+ emit.call(process, 'uncaughtException', escalated, 'unhandledRejection');
277
+ }
278
+ function makeUnhandledRejectionHandler(state, replacesDefaultHandling, isInstalled) {
279
+ return markListener((reason)=>{
280
+ if (replacesDefaultHandling && !hasHostUnhandledRejectionListener(globalThis.process) && isInstalled()) return void applyDefaultRejectionHandling(state, reason);
281
+ if (!isIgnored(reason, 'unhandledRejection')) deferCapture(state, reason, UNHANDLED_REJECTION_HINT);
96
282
  });
97
283
  }
98
- function addUncaughtExceptionListener(captureFn, onFatalFn, mode = STARTUP_UNHANDLED_REJECTION_MODE) {
284
+ function joinHostRejectionQueue(listener) {
99
285
  const process = globalThis.process;
100
- if (!process) return;
101
- if ('strict' === mode) return void process.on('uncaughtExceptionMonitor', (error, origin)=>captureUncaughtException(captureFn, error, origin));
102
- process.on('uncaughtException', makeUncaughtExceptionHandler(captureFn, onFatalFn));
286
+ if (!posthogGlobal[NEXT_REJECTION_FILTER] || 'function' != typeof process.rawListeners) return;
287
+ if (!process.rawListeners('unhandledRejection').includes(listener)) return;
288
+ const removeListener = Object.getPrototypeOf(process).removeListener;
289
+ removeListener.call(process, 'unhandledRejection', listener);
290
+ if (!process.listeners('unhandledRejection').includes(listener)) process.prependListener('unhandledRejection', listener);
103
291
  }
104
- function addUnhandledRejectionListener(captureFn, mode = STARTUP_UNHANDLED_REJECTION_MODE) {
292
+ function installListeners(state) {
105
293
  const process = globalThis.process;
106
- if (!process || 'throw' === mode || 'strict' === mode || 'warn-with-error-code' === mode) return;
107
- process.on('unhandledRejection', (reason)=>{
108
- captureFn(reason, {
109
- mechanism: {
110
- type: 'onunhandledrejection',
111
- handled: false
112
- }
294
+ const removals = [];
295
+ const listen = (event, listener)=>{
296
+ process.on(event, listener);
297
+ removals.push(()=>process.removeListener(event, listener));
298
+ };
299
+ const remove = ()=>removals.forEach((removal)=>removal());
300
+ if ('strict' === state.mode) {
301
+ const monitor = (error, origin)=>captureUncaughtException(state, error, origin, true);
302
+ listen('uncaughtExceptionMonitor', monitor);
303
+ return {
304
+ remove,
305
+ areInstalled: ()=>process.listeners('uncaughtExceptionMonitor').includes(monitor)
306
+ };
307
+ }
308
+ const uncaughtExceptionHandler = makeUncaughtExceptionHandler(state);
309
+ listen('uncaughtException', uncaughtExceptionHandler);
310
+ const replacesDefaultHandling = 'throw' === state.mode || 'warn-with-error-code' === state.mode;
311
+ const followsHostListeners = replacesDefaultHandling && !process.versions?.bun;
312
+ const isInstalled = ()=>process.listeners('unhandledRejection').includes(listener);
313
+ const listener = makeUnhandledRejectionHandler(state, replacesDefaultHandling, isInstalled);
314
+ const keepFirst = ()=>{
315
+ const raw = 'function' == typeof process.rawListeners ? process.rawListeners('unhandledRejection') : [];
316
+ if (raw.includes(listener) && raw[0] !== listener) {
317
+ process.removeListener('unhandledRejection', listener);
318
+ process.prependListener('unhandledRejection', listener);
319
+ }
320
+ };
321
+ listen('newListener', markListener((event, added)=>{
322
+ if (isPostHogListener(added)) return;
323
+ if ('unhandledRejection' === event) {
324
+ if (!isInstalled()) process.prependListener('unhandledRejection', listener);
325
+ queueMicrotask(()=>{
326
+ keepFirst();
327
+ joinHostRejectionQueue(listener);
328
+ });
329
+ } else if (event === NEXT_LISTENER_EVENT) queueMicrotask(()=>{
330
+ if (!isInstalled()) process.prependListener('unhandledRejection', listener);
113
331
  });
332
+ }));
333
+ if (followsHostListeners) {
334
+ listen('removeListener', markListener((event)=>{
335
+ if ('unhandledRejection' === event && isInstalled() && !hasHostUnhandledRejectionListener(process)) process.removeListener('unhandledRejection', listener);
336
+ }));
337
+ if (hasHostUnhandledRejectionListener(process)) process.prependListener('unhandledRejection', listener);
338
+ } else process.prependListener('unhandledRejection', listener);
339
+ joinHostRejectionQueue(listener);
340
+ removals.push(()=>{
341
+ process.removeListener('unhandledRejection', listener);
342
+ if ('function' == typeof process.rawListeners && process.rawListeners('unhandledRejection').includes(listener)) {
343
+ const removeListener = Object.getPrototypeOf(process).removeListener;
344
+ removeListener.call(process, 'unhandledRejection', listener);
345
+ }
114
346
  });
347
+ return {
348
+ remove,
349
+ areInstalled: ()=>process.listeners('uncaughtException').includes(uncaughtExceptionHandler) && (followsHostListeners || isInstalled())
350
+ };
351
+ }
352
+ function startExceptionAutocapture(client, mode = STARTUP_UNHANDLED_REJECTION_MODE) {
353
+ if (!globalThis.process?.on) return ()=>void 0;
354
+ let state = posthogGlobal[STATE_KEY];
355
+ if (state) {
356
+ if (!state.listeners.areInstalled()) {
357
+ state.listeners.remove();
358
+ state.listeners = installListeners(state);
359
+ }
360
+ } else {
361
+ const created = {
362
+ mode,
363
+ clients: new Set(),
364
+ retired: new Map(),
365
+ capturedThisTurn: new Map(),
366
+ deferred: new Map(),
367
+ turnResetScheduled: false,
368
+ calledFatalError: false,
369
+ listeners: {
370
+ remove: ()=>void 0,
371
+ areInstalled: ()=>true
372
+ }
373
+ };
374
+ created.listeners = installListeners(created);
375
+ posthogGlobal[STATE_KEY] = created;
376
+ state = created;
377
+ }
378
+ state.clients.add(client);
379
+ state.retired.delete(client.key);
380
+ const activeState = state;
381
+ return ()=>{
382
+ if (!activeState.clients.delete(client)) return;
383
+ if (![
384
+ ...activeState.clients
385
+ ].some((other)=>other.key === client.key)) activeState.retired.set(client.key, client);
386
+ };
387
+ }
388
+ function claimExplicitCapture(error, key) {
389
+ const state = posthogGlobal[STATE_KEY];
390
+ if (!state) return true;
391
+ if (state.capturedThisTurn.get(error)?.get(key) === 'autocapture') return false;
392
+ recordCapture(state, error, key, 'app');
393
+ state.deferred.get(error)?.skipKeys.add(key);
394
+ return true;
395
+ }
396
+ function capturePendingExceptions() {
397
+ const owners = new Set();
398
+ const state = posthogGlobal[STATE_KEY];
399
+ if (state) for (const deferred of [
400
+ ...state.deferred.values()
401
+ ])captureDeferred(state, deferred).forEach((owner)=>owners.add(owner));
402
+ return owners;
403
+ }
404
+ function resetExceptionAutocapture() {
405
+ const state = posthogGlobal[STATE_KEY];
406
+ if (state) {
407
+ state.deferred.clear();
408
+ state.listeners.remove();
409
+ delete posthogGlobal[STATE_KEY];
410
+ }
115
411
  }
116
412
  __webpack_require__.d(__webpack_exports__, {
117
- addUncaughtExceptionListener: ()=>addUncaughtExceptionListener,
118
- addUnhandledRejectionListener: ()=>addUnhandledRejectionListener,
119
- getUnhandledRejectionMode: ()=>getUnhandledRejectionMode
413
+ capturePendingExceptions: ()=>capturePendingExceptions,
414
+ claimExplicitCapture: ()=>claimExplicitCapture,
415
+ getUnhandledRejectionMode: ()=>getUnhandledRejectionMode,
416
+ resetExceptionAutocapture: ()=>resetExceptionAutocapture,
417
+ startExceptionAutocapture: ()=>startExceptionAutocapture
120
418
  });
121
- exports.addUncaughtExceptionListener = __webpack_exports__.addUncaughtExceptionListener;
122
- exports.addUnhandledRejectionListener = __webpack_exports__.addUnhandledRejectionListener;
419
+ exports.capturePendingExceptions = __webpack_exports__.capturePendingExceptions;
420
+ exports.claimExplicitCapture = __webpack_exports__.claimExplicitCapture;
123
421
  exports.getUnhandledRejectionMode = __webpack_exports__.getUnhandledRejectionMode;
422
+ exports.resetExceptionAutocapture = __webpack_exports__.resetExceptionAutocapture;
423
+ exports.startExceptionAutocapture = __webpack_exports__.startExceptionAutocapture;
124
424
  for(var __rspack_i in __webpack_exports__)if (-1 === [
125
- "addUncaughtExceptionListener",
126
- "addUnhandledRejectionListener",
127
- "getUnhandledRejectionMode"
425
+ "capturePendingExceptions",
426
+ "claimExplicitCapture",
427
+ "getUnhandledRejectionMode",
428
+ "resetExceptionAutocapture",
429
+ "startExceptionAutocapture"
128
430
  ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
129
431
  Object.defineProperty(exports, '__esModule', {
130
432
  value: true