bugstack-sdk 2.2.2 → 2.3.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.
@@ -1,5 +1,138 @@
1
1
  import { NextRequest } from 'next/server';
2
2
 
3
+ /**
4
+ * Caught-and-logged errors reach Bugstack.
5
+ *
6
+ * A `catch` that writes `console.error("[billing] grant failed", err)` and
7
+ * carries on is the commonest way an application handles a failure, and a log
8
+ * line is something nobody reads. Uncaught-exception handlers never see these
9
+ * errors because nothing re-throws them. On Bugstack's own repository, 12 of 16
10
+ * loud bugs it missed in one month were errors caught, logged and carried on
11
+ * from.
12
+ *
13
+ * This module forwards them through the same client every other capture path
14
+ * uses (`ErrorCaptureClient.reportError`), so they get the same `beforeSend`,
15
+ * the same fingerprint dedup and the same transport. Three sources feed it:
16
+ *
17
+ * - `console.error`, wrapped once per process when a client is initialised
18
+ * (on by default; `captureConsoleErrors: false` turns it off);
19
+ * - pino, through `bugstackPinoHooks()` (error and fatal);
20
+ * - winston, through `bugstackWinstonFormat()` (error and above).
21
+ *
22
+ * Rules, each tested in test/logged-errors.test.ts:
23
+ *
24
+ * - THE CONSOLE LINE IS WRITTEN EXACTLY AS BEFORE, first, with the same
25
+ * arguments and `this`. Forwarding happens after, and never throws.
26
+ * - WHAT IS FORWARDED: a call carrying an Error (as an argument, or as the
27
+ * `err` / `error` field of an object argument, the pino shape), or a string
28
+ * holding a stack trace (`console.error("failed", err.stack)`). A plain
29
+ * message with neither is noise by default and stays a console line;
30
+ * `{ messages: true }` forwards it too, as its text.
31
+ * - NOT FORWARDED, counted per rule in `loggedErrorStats()`: the SDK's own
32
+ * `[BugStack…]` lines, Node's process warnings (`(node:1) [DEP0169]
33
+ * DeprecationWarning: …`, which Node writes through console.error), lines
34
+ * matching `ignore`, an error an adapter already reported
35
+ * (`markErrorReported`), the same site and message again within
36
+ * `repeatWindowMs`, and anything past `maxPerMinute`.
37
+ * - ANCHORED AT THE LOGGING SITE. The fingerprint is error type + route +
38
+ * first stack frame. A driver error has the same first frame wherever it
39
+ * was caught, so the report is a new `LoggedError` whose stack starts at
40
+ * the line that logged it. The original rides along as `cause` and, as
41
+ * `causeName` / `causeStack`, in metadata.
42
+ * - NEVER TWICE. Forwarding is deferred one macrotask, so a catch that logs
43
+ * and then calls `captureError` in the same tick sends once.
44
+ * - NEVER LOOPS. A console.error raised while reporting (by `beforeSend`, or
45
+ * by the SDK's own debug logging) is written and not forwarded.
46
+ * - REDACTED. The text of a logged line goes through the client's
47
+ * `redactFields` (`password=…`, `token: …`) and `Bearer …` is masked.
48
+ * Only message text and stacks are sent, never the other log arguments.
49
+ *
50
+ * State lives on `globalThis` under a registered symbol: each package entry
51
+ * point (`bugstack-sdk`, `bugstack-sdk/generic`, …) is bundled on its own, and
52
+ * there must still be one console wrap and one "already reported" set per
53
+ * process.
54
+ */
55
+
56
+ /** Options for `captureConsoleErrors`. Every field is optional. */
57
+ interface LoggedErrorOptions {
58
+ /**
59
+ * Also forward a console.error (or logger error) that carries no Error and
60
+ * no stack trace, as its message text. Off by default: many libraries write
61
+ * plain lines through console.error that are not failures of your app.
62
+ * @default false
63
+ */
64
+ messages?: boolean;
65
+ /**
66
+ * At most this many logged errors are forwarded per minute, per process.
67
+ * @default 20
68
+ */
69
+ maxPerMinute?: number;
70
+ /**
71
+ * The same logging site with the same message is forwarded at most once per
72
+ * this window (milliseconds). A message-only line repeats per site alone,
73
+ * because its text usually carries ids.
74
+ * @default 300000 (5 minutes)
75
+ */
76
+ repeatWindowMs?: number;
77
+ /**
78
+ * Lines whose text matches any of these stay console lines.
79
+ */
80
+ ignore?: Array<string | RegExp>;
81
+ }
82
+ /** Where a logged error came from. */
83
+ type LoggedErrorSource = "console-error" | "pino" | "winston";
84
+ /** Why a logged error was not forwarded, counted per rule. */
85
+ type LoggedErrorDropRule = "no_error_argument" | "sdk_line" | "node_warning" | "ignored" | "already_reported" | "repeat" | "rate_limited" | "no_client";
86
+ interface ResolvedLoggedErrorOptions {
87
+ console: boolean;
88
+ messages: boolean;
89
+ maxPerMinute: number;
90
+ repeatWindowMs: number;
91
+ ignore: Array<string | RegExp>;
92
+ }
93
+ /**
94
+ * Say this error was already sent to Bugstack, so a console line or logger
95
+ * call for the same error object is not sent again. The SDK's adapters call
96
+ * it; call it yourself if you report an error through your own wrapper.
97
+ */
98
+ declare function markErrorReported(error: unknown): void;
99
+ /** Forwarded and dropped counts since the process started, dropped counted per rule. */
100
+ declare function loggedErrorStats(): {
101
+ consoleInstalled: boolean;
102
+ forwarded: number;
103
+ messageOnly: number;
104
+ dropped: Record<LoggedErrorDropRule, number>;
105
+ };
106
+ /**
107
+ * pino `hooks` that forward error and fatal logs. Pass to pino:
108
+ *
109
+ * ```ts
110
+ * const logger = pino({ hooks: bugstackPinoHooks() });
111
+ * ```
112
+ *
113
+ * If you already use `hooks.logMethod`, call the returned `logMethod` from
114
+ * yours. The log line is written exactly as before.
115
+ */
116
+ declare function bugstackPinoHooks(): {
117
+ logMethod: (this: unknown, inputArgs: unknown[], method: (...a: unknown[]) => unknown, level: number) => unknown;
118
+ };
119
+ /**
120
+ * A winston format that forwards error-level logs. Put it first in your
121
+ * format chain:
122
+ *
123
+ * ```ts
124
+ * const logger = winston.createLogger({
125
+ * format: winston.format.combine(bugstackWinstonFormat(), winston.format.json()),
126
+ * transports: [new winston.transports.Console()],
127
+ * });
128
+ * ```
129
+ *
130
+ * It returns the log entry unchanged.
131
+ */
132
+ declare function bugstackWinstonFormat(): {
133
+ transform: (info: Record<string | symbol, unknown>) => Record<string | symbol, unknown>;
134
+ };
135
+
3
136
  /**
4
137
  * Configuration options for the BugStack error capture SDK
5
138
  */
@@ -114,6 +247,18 @@ interface ErrorCaptureConfig {
114
247
  * lives behind a different host/path for telemetry vs. main capture.
115
248
  */
116
249
  chunkErrorsEndpoint?: string;
250
+ /**
251
+ * Forward caught-and-logged errors: a `console.error` call that carries an
252
+ * Error (or a stack trace) is reported, anchored at the line that logged it.
253
+ * The console line is written exactly as before. On by default; `false`
254
+ * turns it off. Pass options to tune it, e.g. `{ messages: true }` to also
255
+ * forward console.error lines that carry only a message.
256
+ *
257
+ * pino and winston are covered through `bugstackPinoHooks()` and
258
+ * `bugstackWinstonFormat()`, which follow the same rules.
259
+ * @default true
260
+ */
261
+ captureConsoleErrors?: boolean | LoggedErrorOptions;
117
262
  }
118
263
  /**
119
264
  * Resolved configuration with all defaults applied
@@ -138,6 +283,7 @@ interface ResolvedConfig {
138
283
  beforeSend?: (error: CapturedError) => CapturedError | null;
139
284
  dropChunkErrors: boolean;
140
285
  chunkErrorsEndpoint: string;
286
+ captureConsoleErrors: ResolvedLoggedErrorOptions;
141
287
  }
142
288
  /**
143
289
  * Captured error data sent to the error service
@@ -576,6 +722,7 @@ declare class ErrorCaptureClient {
576
722
  private static instance;
577
723
  private deduplicator;
578
724
  private retryQueue;
725
+ private loggedErrorSink;
579
726
  constructor(config: ErrorCaptureConfig);
580
727
  /**
581
728
  * Initialize the singleton client instance
@@ -660,4 +807,4 @@ declare function isChunkLoadError(error: {
660
807
  message?: string;
661
808
  }): boolean;
662
809
 
663
- export { BugStackClient as B, type CapturedError as C, type ErrorCaptureConfig as E, type NextRouteHandler as N, type RouteContext as R, type StackFrame as S, ErrorCaptureClient as a, type RouteOptions as b, type BugStackConfig as c, ErrorDeduplicator as d, type ErrorReportPayload as e, type ResolvedConfig as f, RetryQueue as g, type SourceContext as h, isChunkLoadError as i };
810
+ export { BugStackClient as B, type CapturedError as C, type ErrorCaptureConfig as E, type LoggedErrorOptions as L, type NextRouteHandler as N, type RouteContext as R, type StackFrame as S, ErrorCaptureClient as a, bugstackPinoHooks as b, bugstackWinstonFormat as c, type RouteOptions as d, type BugStackConfig as e, ErrorDeduplicator as f, type ErrorReportPayload as g, type LoggedErrorDropRule as h, type LoggedErrorSource as i, type ResolvedConfig as j, RetryQueue as k, loggedErrorStats as l, markErrorReported as m, type SourceContext as n, isChunkLoadError as o };
@@ -1,5 +1,138 @@
1
1
  import { NextRequest } from 'next/server';
2
2
 
3
+ /**
4
+ * Caught-and-logged errors reach Bugstack.
5
+ *
6
+ * A `catch` that writes `console.error("[billing] grant failed", err)` and
7
+ * carries on is the commonest way an application handles a failure, and a log
8
+ * line is something nobody reads. Uncaught-exception handlers never see these
9
+ * errors because nothing re-throws them. On Bugstack's own repository, 12 of 16
10
+ * loud bugs it missed in one month were errors caught, logged and carried on
11
+ * from.
12
+ *
13
+ * This module forwards them through the same client every other capture path
14
+ * uses (`ErrorCaptureClient.reportError`), so they get the same `beforeSend`,
15
+ * the same fingerprint dedup and the same transport. Three sources feed it:
16
+ *
17
+ * - `console.error`, wrapped once per process when a client is initialised
18
+ * (on by default; `captureConsoleErrors: false` turns it off);
19
+ * - pino, through `bugstackPinoHooks()` (error and fatal);
20
+ * - winston, through `bugstackWinstonFormat()` (error and above).
21
+ *
22
+ * Rules, each tested in test/logged-errors.test.ts:
23
+ *
24
+ * - THE CONSOLE LINE IS WRITTEN EXACTLY AS BEFORE, first, with the same
25
+ * arguments and `this`. Forwarding happens after, and never throws.
26
+ * - WHAT IS FORWARDED: a call carrying an Error (as an argument, or as the
27
+ * `err` / `error` field of an object argument, the pino shape), or a string
28
+ * holding a stack trace (`console.error("failed", err.stack)`). A plain
29
+ * message with neither is noise by default and stays a console line;
30
+ * `{ messages: true }` forwards it too, as its text.
31
+ * - NOT FORWARDED, counted per rule in `loggedErrorStats()`: the SDK's own
32
+ * `[BugStack…]` lines, Node's process warnings (`(node:1) [DEP0169]
33
+ * DeprecationWarning: …`, which Node writes through console.error), lines
34
+ * matching `ignore`, an error an adapter already reported
35
+ * (`markErrorReported`), the same site and message again within
36
+ * `repeatWindowMs`, and anything past `maxPerMinute`.
37
+ * - ANCHORED AT THE LOGGING SITE. The fingerprint is error type + route +
38
+ * first stack frame. A driver error has the same first frame wherever it
39
+ * was caught, so the report is a new `LoggedError` whose stack starts at
40
+ * the line that logged it. The original rides along as `cause` and, as
41
+ * `causeName` / `causeStack`, in metadata.
42
+ * - NEVER TWICE. Forwarding is deferred one macrotask, so a catch that logs
43
+ * and then calls `captureError` in the same tick sends once.
44
+ * - NEVER LOOPS. A console.error raised while reporting (by `beforeSend`, or
45
+ * by the SDK's own debug logging) is written and not forwarded.
46
+ * - REDACTED. The text of a logged line goes through the client's
47
+ * `redactFields` (`password=…`, `token: …`) and `Bearer …` is masked.
48
+ * Only message text and stacks are sent, never the other log arguments.
49
+ *
50
+ * State lives on `globalThis` under a registered symbol: each package entry
51
+ * point (`bugstack-sdk`, `bugstack-sdk/generic`, …) is bundled on its own, and
52
+ * there must still be one console wrap and one "already reported" set per
53
+ * process.
54
+ */
55
+
56
+ /** Options for `captureConsoleErrors`. Every field is optional. */
57
+ interface LoggedErrorOptions {
58
+ /**
59
+ * Also forward a console.error (or logger error) that carries no Error and
60
+ * no stack trace, as its message text. Off by default: many libraries write
61
+ * plain lines through console.error that are not failures of your app.
62
+ * @default false
63
+ */
64
+ messages?: boolean;
65
+ /**
66
+ * At most this many logged errors are forwarded per minute, per process.
67
+ * @default 20
68
+ */
69
+ maxPerMinute?: number;
70
+ /**
71
+ * The same logging site with the same message is forwarded at most once per
72
+ * this window (milliseconds). A message-only line repeats per site alone,
73
+ * because its text usually carries ids.
74
+ * @default 300000 (5 minutes)
75
+ */
76
+ repeatWindowMs?: number;
77
+ /**
78
+ * Lines whose text matches any of these stay console lines.
79
+ */
80
+ ignore?: Array<string | RegExp>;
81
+ }
82
+ /** Where a logged error came from. */
83
+ type LoggedErrorSource = "console-error" | "pino" | "winston";
84
+ /** Why a logged error was not forwarded, counted per rule. */
85
+ type LoggedErrorDropRule = "no_error_argument" | "sdk_line" | "node_warning" | "ignored" | "already_reported" | "repeat" | "rate_limited" | "no_client";
86
+ interface ResolvedLoggedErrorOptions {
87
+ console: boolean;
88
+ messages: boolean;
89
+ maxPerMinute: number;
90
+ repeatWindowMs: number;
91
+ ignore: Array<string | RegExp>;
92
+ }
93
+ /**
94
+ * Say this error was already sent to Bugstack, so a console line or logger
95
+ * call for the same error object is not sent again. The SDK's adapters call
96
+ * it; call it yourself if you report an error through your own wrapper.
97
+ */
98
+ declare function markErrorReported(error: unknown): void;
99
+ /** Forwarded and dropped counts since the process started, dropped counted per rule. */
100
+ declare function loggedErrorStats(): {
101
+ consoleInstalled: boolean;
102
+ forwarded: number;
103
+ messageOnly: number;
104
+ dropped: Record<LoggedErrorDropRule, number>;
105
+ };
106
+ /**
107
+ * pino `hooks` that forward error and fatal logs. Pass to pino:
108
+ *
109
+ * ```ts
110
+ * const logger = pino({ hooks: bugstackPinoHooks() });
111
+ * ```
112
+ *
113
+ * If you already use `hooks.logMethod`, call the returned `logMethod` from
114
+ * yours. The log line is written exactly as before.
115
+ */
116
+ declare function bugstackPinoHooks(): {
117
+ logMethod: (this: unknown, inputArgs: unknown[], method: (...a: unknown[]) => unknown, level: number) => unknown;
118
+ };
119
+ /**
120
+ * A winston format that forwards error-level logs. Put it first in your
121
+ * format chain:
122
+ *
123
+ * ```ts
124
+ * const logger = winston.createLogger({
125
+ * format: winston.format.combine(bugstackWinstonFormat(), winston.format.json()),
126
+ * transports: [new winston.transports.Console()],
127
+ * });
128
+ * ```
129
+ *
130
+ * It returns the log entry unchanged.
131
+ */
132
+ declare function bugstackWinstonFormat(): {
133
+ transform: (info: Record<string | symbol, unknown>) => Record<string | symbol, unknown>;
134
+ };
135
+
3
136
  /**
4
137
  * Configuration options for the BugStack error capture SDK
5
138
  */
@@ -114,6 +247,18 @@ interface ErrorCaptureConfig {
114
247
  * lives behind a different host/path for telemetry vs. main capture.
115
248
  */
116
249
  chunkErrorsEndpoint?: string;
250
+ /**
251
+ * Forward caught-and-logged errors: a `console.error` call that carries an
252
+ * Error (or a stack trace) is reported, anchored at the line that logged it.
253
+ * The console line is written exactly as before. On by default; `false`
254
+ * turns it off. Pass options to tune it, e.g. `{ messages: true }` to also
255
+ * forward console.error lines that carry only a message.
256
+ *
257
+ * pino and winston are covered through `bugstackPinoHooks()` and
258
+ * `bugstackWinstonFormat()`, which follow the same rules.
259
+ * @default true
260
+ */
261
+ captureConsoleErrors?: boolean | LoggedErrorOptions;
117
262
  }
118
263
  /**
119
264
  * Resolved configuration with all defaults applied
@@ -138,6 +283,7 @@ interface ResolvedConfig {
138
283
  beforeSend?: (error: CapturedError) => CapturedError | null;
139
284
  dropChunkErrors: boolean;
140
285
  chunkErrorsEndpoint: string;
286
+ captureConsoleErrors: ResolvedLoggedErrorOptions;
141
287
  }
142
288
  /**
143
289
  * Captured error data sent to the error service
@@ -576,6 +722,7 @@ declare class ErrorCaptureClient {
576
722
  private static instance;
577
723
  private deduplicator;
578
724
  private retryQueue;
725
+ private loggedErrorSink;
579
726
  constructor(config: ErrorCaptureConfig);
580
727
  /**
581
728
  * Initialize the singleton client instance
@@ -660,4 +807,4 @@ declare function isChunkLoadError(error: {
660
807
  message?: string;
661
808
  }): boolean;
662
809
 
663
- export { BugStackClient as B, type CapturedError as C, type ErrorCaptureConfig as E, type NextRouteHandler as N, type RouteContext as R, type StackFrame as S, ErrorCaptureClient as a, type RouteOptions as b, type BugStackConfig as c, ErrorDeduplicator as d, type ErrorReportPayload as e, type ResolvedConfig as f, RetryQueue as g, type SourceContext as h, isChunkLoadError as i };
810
+ export { BugStackClient as B, type CapturedError as C, type ErrorCaptureConfig as E, type LoggedErrorOptions as L, type NextRouteHandler as N, type RouteContext as R, type StackFrame as S, ErrorCaptureClient as a, bugstackPinoHooks as b, bugstackWinstonFormat as c, type RouteOptions as d, type BugStackConfig as e, ErrorDeduplicator as f, type ErrorReportPayload as g, type LoggedErrorDropRule as h, type LoggedErrorSource as i, type ResolvedConfig as j, RetryQueue as k, loggedErrorStats as l, markErrorReported as m, type SourceContext as n, isChunkLoadError as o };
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as CapturedError, a as ErrorCaptureClient, S as StackFrame } from './client-DK_ItP55.mjs';
2
- export { B as BugStackClient, c as BugStackConfig, E as ErrorCaptureConfig, d as ErrorDeduplicator, e as ErrorReportPayload, N as NextRouteHandler, f as ResolvedConfig, g as RetryQueue, R as RouteContext, b as RouteOptions, h as SourceContext, i as isChunkLoadError } from './client-DK_ItP55.mjs';
1
+ import { C as CapturedError, a as ErrorCaptureClient, S as StackFrame } from './client-B9WaTEYj.mjs';
2
+ export { B as BugStackClient, e as BugStackConfig, E as ErrorCaptureConfig, f as ErrorDeduplicator, g as ErrorReportPayload, h as LoggedErrorDropRule, L as LoggedErrorOptions, i as LoggedErrorSource, N as NextRouteHandler, j as ResolvedConfig, k as RetryQueue, R as RouteContext, d as RouteOptions, n as SourceContext, b as bugstackPinoHooks, c as bugstackWinstonFormat, o as isChunkLoadError, l as loggedErrorStats, m as markErrorReported } from './client-B9WaTEYj.mjs';
3
3
  export { withBugStack, withErrorCapture } from './adapters/nextjs/index.mjs';
4
4
  import 'next/server';
5
5
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as CapturedError, a as ErrorCaptureClient, S as StackFrame } from './client-DK_ItP55.js';
2
- export { B as BugStackClient, c as BugStackConfig, E as ErrorCaptureConfig, d as ErrorDeduplicator, e as ErrorReportPayload, N as NextRouteHandler, f as ResolvedConfig, g as RetryQueue, R as RouteContext, b as RouteOptions, h as SourceContext, i as isChunkLoadError } from './client-DK_ItP55.js';
1
+ import { C as CapturedError, a as ErrorCaptureClient, S as StackFrame } from './client-B9WaTEYj.js';
2
+ export { B as BugStackClient, e as BugStackConfig, E as ErrorCaptureConfig, f as ErrorDeduplicator, g as ErrorReportPayload, h as LoggedErrorDropRule, L as LoggedErrorOptions, i as LoggedErrorSource, N as NextRouteHandler, j as ResolvedConfig, k as RetryQueue, R as RouteContext, d as RouteOptions, n as SourceContext, b as bugstackPinoHooks, c as bugstackWinstonFormat, o as isChunkLoadError, l as loggedErrorStats, m as markErrorReported } from './client-B9WaTEYj.js';
3
3
  export { withBugStack, withErrorCapture } from './adapters/nextjs/index.js';
4
4
  import 'next/server';
5
5