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.
- package/CHANGELOG.md +30 -0
- package/README.md +75 -2
- package/dist/adapters/express/index.d.mts +2 -2
- package/dist/adapters/express/index.d.ts +2 -2
- package/dist/adapters/express/index.js +408 -42
- package/dist/adapters/express/index.js.map +1 -1
- package/dist/adapters/express/index.mjs +408 -42
- package/dist/adapters/express/index.mjs.map +1 -1
- package/dist/adapters/generic/index.d.mts +2 -2
- package/dist/adapters/generic/index.d.ts +2 -2
- package/dist/adapters/generic/index.js +456 -42
- package/dist/adapters/generic/index.js.map +1 -1
- package/dist/adapters/generic/index.mjs +453 -43
- package/dist/adapters/generic/index.mjs.map +1 -1
- package/dist/adapters/nextjs/index.d.mts +2 -2
- package/dist/adapters/nextjs/index.d.ts +2 -2
- package/dist/adapters/nextjs/index.js +408 -42
- package/dist/adapters/nextjs/index.js.map +1 -1
- package/dist/adapters/nextjs/index.mjs +408 -42
- package/dist/adapters/nextjs/index.mjs.map +1 -1
- package/dist/{client-DK_ItP55.d.mts → client-B9WaTEYj.d.mts} +148 -1
- package/dist/{client-DK_ItP55.d.ts → client-B9WaTEYj.d.ts} +148 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +468 -54
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +465 -55
- package/dist/index.mjs.map +1 -1
- package/package.json +8 -4
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,36 @@
|
|
|
3
3
|
All notable changes to `bugstack-sdk` are documented here.
|
|
4
4
|
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
5
5
|
|
|
6
|
+
## [2.3.0] — 2026-11-23
|
|
7
|
+
|
|
8
|
+
### Added
|
|
9
|
+
- **Caught-and-logged errors reach Bugstack.** A `catch` block that logs
|
|
10
|
+
an error with `console.error` and carries on was invisible: only uncaught
|
|
11
|
+
exceptions and the adapters' own wrappers reported anything. Once the
|
|
12
|
+
client is initialised, a `console.error` call carrying an `Error` (or a
|
|
13
|
+
string holding a stack trace) is now reported, anchored at the line that
|
|
14
|
+
logged it, with the original error as `metadata.causeName` /
|
|
15
|
+
`metadata.causeStack`. On by default; `captureConsoleErrors: false` turns
|
|
16
|
+
it off, and an options object tunes it (`messages`, `maxPerMinute`,
|
|
17
|
+
`repeatWindowMs`, `ignore`). The console line is written exactly as before.
|
|
18
|
+
Plain message lines, Node's process warnings and the SDK's own lines stay
|
|
19
|
+
console lines; forwards are capped at 20 a minute and once per site and
|
|
20
|
+
message per 5 minutes, then deduplicated by fingerprint as usual; logged
|
|
21
|
+
text is redacted with `redactFields`; forwarding never throws.
|
|
22
|
+
- **pino and winston.** `bugstackPinoHooks()` (pino `hooks`) and
|
|
23
|
+
`bugstackWinstonFormat()` (first in a winston format chain) forward
|
|
24
|
+
error-level logs under the same rules.
|
|
25
|
+
- **`markErrorReported(error)`** says an error was already sent, so the
|
|
26
|
+
console line for it is not sent again. The Next.js, Express and generic
|
|
27
|
+
adapters call it, so an error they report is not reported a second time
|
|
28
|
+
when the framework logs it. **`loggedErrorStats()`** returns forwarded and
|
|
29
|
+
dropped counts per rule.
|
|
30
|
+
|
|
31
|
+
### Fixed
|
|
32
|
+
- **Windows paths are app frames.** The stack parser treated any file path
|
|
33
|
+
without a `/` as Node-internal, so on Windows no frame was an app frame and
|
|
34
|
+
`metadata.sourceLocation` was never set.
|
|
35
|
+
|
|
6
36
|
## [2.2.2] — 2026-10-29
|
|
7
37
|
|
|
8
38
|
### Fixed
|
package/README.md
CHANGED
|
@@ -2,13 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
The [Bugstack](https://bugstack.ai) SDK for Node.js: Next.js, Express and any Node process.
|
|
4
4
|
|
|
5
|
-
Bugstack is autonomous software maintenance. It watches your app and your repository, fixes what breaks, and sends every change as a pull request you control. This SDK is how your app tells Bugstack about an uncaught
|
|
5
|
+
Bugstack is autonomous software maintenance. It watches your app and your repository, fixes what breaks, and sends every change as a pull request you control. This SDK is how your app tells Bugstack about a server error: an uncaught one, or one your code caught and logged with `console.error`. It sends the error, its stack trace and where it happened, and Bugstack takes it from there.
|
|
6
6
|
|
|
7
7
|
**Get your API key at:** [dashboard.bugstack.ai](https://dashboard.bugstack.ai)
|
|
8
8
|
|
|
9
9
|
## Features
|
|
10
10
|
|
|
11
11
|
- **Multiple frameworks** — First-class support for Next.js, Express, and generic Node.js
|
|
12
|
+
- **Caught-and-logged errors** — A `console.error(err)` in a `catch` block reaches Bugstack too, on by default; pino and winston with one line each
|
|
12
13
|
- **Full error context** — Captures stack traces, request body, headers, query params, route params
|
|
13
14
|
- **Automatic sanitization** — Sensitive data (passwords, tokens, API keys) is redacted automatically
|
|
14
15
|
- **Non-blocking** — Error reporting is async and never slows down your responses
|
|
@@ -178,6 +179,74 @@ try {
|
|
|
178
179
|
|
|
179
180
|
---
|
|
180
181
|
|
|
182
|
+
## Caught-and-Logged Errors
|
|
183
|
+
|
|
184
|
+
Most failures never reach an uncaught-exception handler. A `catch` block logs them and the app carries on:
|
|
185
|
+
|
|
186
|
+
```typescript
|
|
187
|
+
try {
|
|
188
|
+
await grantCredits(order);
|
|
189
|
+
} catch (err) {
|
|
190
|
+
console.error("[billing] grant failed", err); // a log line nobody reads
|
|
191
|
+
}
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
Once the client is initialised, the SDK forwards these to Bugstack. It is on by default, and the console line is written exactly as before.
|
|
195
|
+
|
|
196
|
+
**What is forwarded:** a `console.error` call that carries an `Error` (as an argument, or as the `err` / `error` field of an object argument), or a string holding a stack trace (`console.error("failed", err.stack)`). The report is anchored at the line that logged it, so each logging site is its own issue; the original error's name and stack ride along in `metadata.causeName` / `metadata.causeStack`. A `[billing]` style tag at the start of the line becomes the route (`log:billing`).
|
|
197
|
+
|
|
198
|
+
**What stays a console line:** a plain message with no error and no stack (unless you set `messages: true`), Node's own process warnings (`(node:1) [DEP0169] DeprecationWarning: …`), the SDK's own `[BugStack]` lines, and lines matching `ignore`. An error the SDK already reported (through `withErrorCapture`, `bugstackErrorHandler` or `captureError`) is not sent again when your framework logs it.
|
|
199
|
+
|
|
200
|
+
**Bounded:** at most 20 forwards a minute per process, the same site and message at most once per 5 minutes, then the usual fingerprint dedup. Logged text goes through the same `redactFields` as request data (`password=…`, `token: …`), and bearer tokens are masked. Only the message and stacks are sent, never the other log arguments. Forwarding never throws into your code.
|
|
201
|
+
|
|
202
|
+
```typescript
|
|
203
|
+
ErrorCaptureClient.init({
|
|
204
|
+
apiKey: "your-api-key",
|
|
205
|
+
|
|
206
|
+
// captureConsoleErrors: false turns it off. To tune it instead
|
|
207
|
+
// (every field optional, defaults shown):
|
|
208
|
+
captureConsoleErrors: {
|
|
209
|
+
messages: false, // also forward console.error lines that carry only a message
|
|
210
|
+
maxPerMinute: 20,
|
|
211
|
+
repeatWindowMs: 5 * 60 * 1000,
|
|
212
|
+
ignore: [/ECONNRESET/], // strings or RegExps; matching lines stay console lines
|
|
213
|
+
},
|
|
214
|
+
});
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
### pino
|
|
218
|
+
|
|
219
|
+
```typescript
|
|
220
|
+
import pino from "pino";
|
|
221
|
+
import { bugstackPinoHooks } from "bugstack-sdk";
|
|
222
|
+
|
|
223
|
+
const logger = pino({ hooks: bugstackPinoHooks() });
|
|
224
|
+
|
|
225
|
+
logger.error({ err, orderId }, "[checkout] charge failed"); // forwarded
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
`error` and `fatal` logs are forwarded under the same rules. If you already use `hooks.logMethod`, call the returned `logMethod` from yours.
|
|
229
|
+
|
|
230
|
+
### winston
|
|
231
|
+
|
|
232
|
+
```typescript
|
|
233
|
+
import winston from "winston";
|
|
234
|
+
import { bugstackWinstonFormat } from "bugstack-sdk";
|
|
235
|
+
|
|
236
|
+
const logger = winston.createLogger({
|
|
237
|
+
format: winston.format.combine(bugstackWinstonFormat(), winston.format.json()),
|
|
238
|
+
transports: [new winston.transports.Console()],
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
logger.error("[upload] write failed", err); // forwarded
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
Put `bugstackWinstonFormat()` first in the chain. `error` and higher levels are forwarded, and the log entry passes through unchanged.
|
|
245
|
+
|
|
246
|
+
`loggedErrorStats()` returns how many logged errors were forwarded and how many were left as log lines, counted per rule.
|
|
247
|
+
|
|
248
|
+
---
|
|
249
|
+
|
|
181
250
|
## Source Maps for Production (Next.js)
|
|
182
251
|
|
|
183
252
|
By default, server-side errors in a Next.js production build come back with stack frames that point at compiled chunks like `.next/server/chunks/8393.js:1:8734`. The Bugstack orchestrator can't fix what it can't locate — so without source maps, those errors land in your dashboard as "Could not identify primary file from error" and never auto-fix.
|
|
@@ -309,6 +378,9 @@ ErrorCaptureClient.init({
|
|
|
309
378
|
return true;
|
|
310
379
|
},
|
|
311
380
|
|
|
381
|
+
// Caught-and-logged errors (console.error); see "Caught-and-Logged Errors"
|
|
382
|
+
captureConsoleErrors: true, // false to turn off, or an options object
|
|
383
|
+
|
|
312
384
|
// Transform errors before sending
|
|
313
385
|
beforeSend: (capturedError) => {
|
|
314
386
|
capturedError.metadata = { ...capturedError.metadata, custom: "value" };
|
|
@@ -346,7 +418,7 @@ export const POST = withErrorCapture(
|
|
|
346
418
|
|
|
347
419
|
## Automatic Sanitization
|
|
348
420
|
|
|
349
|
-
The SDK redacts sensitive data from headers, request bodies, and query params.
|
|
421
|
+
The SDK redacts sensitive data from headers, request bodies, and query params, and from the text of caught-and-logged errors.
|
|
350
422
|
|
|
351
423
|
**Built-in redacted fields:**
|
|
352
424
|
`password`, `secret`, `token`, `apikey`, `api_key`, `apiKey`, `authorization`, `auth`, `credential`, `private`, `credit_card`, `creditcard`, `card_number`, `cvv`, `ssn`, `social_security`
|
|
@@ -365,6 +437,7 @@ The SDK never interferes with your application:
|
|
|
365
437
|
- **Network failures** — Silently retried (up to 5 times with exponential backoff)
|
|
366
438
|
- **Timeouts** — Configurable, defaults to 5 seconds
|
|
367
439
|
- **SDK errors** — Caught and logged in debug mode, never thrown to your app
|
|
440
|
+
- **Console behaviour preserved** — `console.error` writes exactly what it wrote before; forwarding happens after, one tick later
|
|
368
441
|
- **Original error preserved** — The wrapper re-throws the original error so your framework handles the response normally
|
|
369
442
|
|
|
370
443
|
---
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ErrorRequestHandler, Request, Response, NextFunction } from 'express';
|
|
2
|
-
import { E as ErrorCaptureConfig } from '../../client-
|
|
3
|
-
export { B as BugStackClient, C as CapturedError, a as ErrorCaptureClient } from '../../client-
|
|
2
|
+
import { E as ErrorCaptureConfig } from '../../client-B9WaTEYj.mjs';
|
|
3
|
+
export { B as BugStackClient, C as CapturedError, a as ErrorCaptureClient } from '../../client-B9WaTEYj.mjs';
|
|
4
4
|
import 'next/server';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ErrorRequestHandler, Request, Response, NextFunction } from 'express';
|
|
2
|
-
import { E as ErrorCaptureConfig } from '../../client-
|
|
3
|
-
export { B as BugStackClient, C as CapturedError, a as ErrorCaptureClient } from '../../client-
|
|
2
|
+
import { E as ErrorCaptureConfig } from '../../client-B9WaTEYj.js';
|
|
3
|
+
export { B as BugStackClient, C as CapturedError, a as ErrorCaptureClient } from '../../client-B9WaTEYj.js';
|
|
4
4
|
import 'next/server';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -430,8 +430,395 @@ var RetryQueue = class {
|
|
|
430
430
|
}
|
|
431
431
|
};
|
|
432
432
|
|
|
433
|
+
// src/core/utils/stack-parser.ts
|
|
434
|
+
var V8_STACK_FRAME_REGEX = /^\s*at\s+(?:async\s+)?(?:(.+?)\s+\()?(?:(.+?):(\d+):(\d+))\)?$/;
|
|
435
|
+
function isNodeModule(filePath) {
|
|
436
|
+
return filePath.includes("node_modules");
|
|
437
|
+
}
|
|
438
|
+
function isInternalCode(filePath) {
|
|
439
|
+
return filePath.startsWith("node:") || filePath.startsWith("internal/") || // A bare name ("native", "<anonymous>") has no directory. A Windows
|
|
440
|
+
// path has backslashes and is app code.
|
|
441
|
+
!filePath.includes("/") && !filePath.includes("\\");
|
|
442
|
+
}
|
|
443
|
+
function cleanFunctionName(name) {
|
|
444
|
+
if (!name) return void 0;
|
|
445
|
+
return name.replace(/^Object\./, "").replace(/^Module\./, "").replace(/^__webpack_require__\./, "").replace(/^webpack_require\./, "").trim();
|
|
446
|
+
}
|
|
447
|
+
function parseStackTrace(stack) {
|
|
448
|
+
if (!stack) return [];
|
|
449
|
+
const lines = stack.split("\n");
|
|
450
|
+
const frames = [];
|
|
451
|
+
for (const line of lines) {
|
|
452
|
+
const match = V8_STACK_FRAME_REGEX.exec(line);
|
|
453
|
+
if (match) {
|
|
454
|
+
const [, functionName, file, lineStr, columnStr] = match;
|
|
455
|
+
const frame = {
|
|
456
|
+
function: cleanFunctionName(functionName),
|
|
457
|
+
file: file ?? void 0,
|
|
458
|
+
line: lineStr ? parseInt(lineStr, 10) : void 0,
|
|
459
|
+
column: columnStr ? parseInt(columnStr, 10) : void 0
|
|
460
|
+
};
|
|
461
|
+
if (frame.file) {
|
|
462
|
+
frame.isNodeModule = isNodeModule(frame.file);
|
|
463
|
+
frame.isInternal = isInternalCode(frame.file);
|
|
464
|
+
}
|
|
465
|
+
frames.push(frame);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
return frames;
|
|
469
|
+
}
|
|
470
|
+
function getFirstAppFrame(frames) {
|
|
471
|
+
return frames.find((frame) => !frame.isNodeModule && !frame.isInternal);
|
|
472
|
+
}
|
|
473
|
+
|
|
433
474
|
// src/core/sdk-version.ts
|
|
434
|
-
var SDK_VERSION = "2.
|
|
475
|
+
var SDK_VERSION = "2.3.0" ;
|
|
476
|
+
|
|
477
|
+
// src/core/logged-errors.ts
|
|
478
|
+
var DEFAULT_MAX_PER_MINUTE = 20;
|
|
479
|
+
var DEFAULT_REPEAT_WINDOW_MS = 5 * 6e4;
|
|
480
|
+
var MAX_REMEMBERED = 500;
|
|
481
|
+
var MESSAGE_MAX = 300;
|
|
482
|
+
var ANCHORED_MESSAGE_MAX = 500;
|
|
483
|
+
var CAUSE_STACK_MAX = 2e3;
|
|
484
|
+
function resolveLoggedErrorOptions(value) {
|
|
485
|
+
const opts = typeof value === "object" && value !== null ? value : {};
|
|
486
|
+
return {
|
|
487
|
+
console: value !== false,
|
|
488
|
+
messages: opts.messages ?? false,
|
|
489
|
+
maxPerMinute: opts.maxPerMinute ?? DEFAULT_MAX_PER_MINUTE,
|
|
490
|
+
repeatWindowMs: opts.repeatWindowMs ?? DEFAULT_REPEAT_WINDOW_MS,
|
|
491
|
+
ignore: opts.ignore ?? []
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
var SHARED_KEY = /* @__PURE__ */ Symbol.for("bugstack-sdk.logged-errors");
|
|
495
|
+
function emptyStats() {
|
|
496
|
+
return {
|
|
497
|
+
forwarded: 0,
|
|
498
|
+
messageOnly: 0,
|
|
499
|
+
dropped: {
|
|
500
|
+
no_error_argument: 0,
|
|
501
|
+
sdk_line: 0,
|
|
502
|
+
node_warning: 0,
|
|
503
|
+
ignored: 0,
|
|
504
|
+
already_reported: 0,
|
|
505
|
+
repeat: 0,
|
|
506
|
+
rate_limited: 0,
|
|
507
|
+
no_client: 0
|
|
508
|
+
}
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
function shared() {
|
|
512
|
+
const g = globalThis;
|
|
513
|
+
let s = g[SHARED_KEY];
|
|
514
|
+
if (!s) {
|
|
515
|
+
s = {
|
|
516
|
+
reported: /* @__PURE__ */ new WeakSet(),
|
|
517
|
+
sink: null,
|
|
518
|
+
consoleOriginal: null,
|
|
519
|
+
consoleWrapper: null,
|
|
520
|
+
busy: false,
|
|
521
|
+
windowStart: 0,
|
|
522
|
+
inWindow: 0,
|
|
523
|
+
lastSent: /* @__PURE__ */ new Map(),
|
|
524
|
+
stats: emptyStats(),
|
|
525
|
+
now: Date.now
|
|
526
|
+
};
|
|
527
|
+
g[SHARED_KEY] = s;
|
|
528
|
+
}
|
|
529
|
+
return s;
|
|
530
|
+
}
|
|
531
|
+
var defer = typeof setImmediate === "function" ? (fn) => void setImmediate(fn) : (fn) => void setTimeout(fn, 0);
|
|
532
|
+
function markErrorReported(error) {
|
|
533
|
+
try {
|
|
534
|
+
if (error !== null && typeof error === "object") shared().reported.add(error);
|
|
535
|
+
} catch {
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
function isError(value) {
|
|
539
|
+
if (value instanceof Error) return true;
|
|
540
|
+
if (value === null || typeof value !== "object") return false;
|
|
541
|
+
try {
|
|
542
|
+
const v = value;
|
|
543
|
+
return typeof v.message === "string" && typeof v.stack === "string";
|
|
544
|
+
} catch {
|
|
545
|
+
return false;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
function findError(args) {
|
|
549
|
+
for (const a of args) if (isError(a)) return a;
|
|
550
|
+
for (const a of args) {
|
|
551
|
+
if (a === null || typeof a !== "object" || Array.isArray(a)) continue;
|
|
552
|
+
try {
|
|
553
|
+
const o = a;
|
|
554
|
+
for (const k of ["err", "error", "cause"]) if (isError(o[k])) return o[k];
|
|
555
|
+
} catch {
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
return void 0;
|
|
559
|
+
}
|
|
560
|
+
var STACK_TEXT = /(^|\n)\s*([A-Za-z_$][\w$.]*(?:Error|Exception)\b[^\n]*)\n\s+at \S/;
|
|
561
|
+
function findStackText(args) {
|
|
562
|
+
for (const a of args) {
|
|
563
|
+
if (typeof a !== "string") continue;
|
|
564
|
+
const m = STACK_TEXT.exec(a);
|
|
565
|
+
if (!m) continue;
|
|
566
|
+
const header = m[2].trim();
|
|
567
|
+
const colon = header.indexOf(":");
|
|
568
|
+
const err = new Error(colon > 0 ? header.slice(colon + 1).trim() : header);
|
|
569
|
+
err.name = colon > 0 ? header.slice(0, colon).trim() : "Error";
|
|
570
|
+
err.stack = a.slice(m.index + m[1].length).trim();
|
|
571
|
+
return err;
|
|
572
|
+
}
|
|
573
|
+
return void 0;
|
|
574
|
+
}
|
|
575
|
+
function messageOfArgs(args) {
|
|
576
|
+
const parts = [];
|
|
577
|
+
for (const a of args) {
|
|
578
|
+
if (typeof a === "string") parts.push(a);
|
|
579
|
+
else if (typeof a === "number" || typeof a === "boolean") parts.push(String(a));
|
|
580
|
+
else if (a !== null && typeof a === "object" && !Array.isArray(a) && !isError(a)) {
|
|
581
|
+
try {
|
|
582
|
+
const o = a;
|
|
583
|
+
for (const k of ["error", "message", "reason", "err", "msg"]) {
|
|
584
|
+
if (typeof o[k] === "string" && o[k].length > 0) {
|
|
585
|
+
parts.push(o[k]);
|
|
586
|
+
break;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
} catch {
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
return parts.join(" ").replace(/\s+/g, " ").trim().slice(0, MESSAGE_MAX);
|
|
594
|
+
}
|
|
595
|
+
function logRoute(label) {
|
|
596
|
+
const tag = label?.match(/^\s*\[([A-Za-z0-9_.:/-]{1,60})\]/)?.[1];
|
|
597
|
+
return tag ? `log:${tag}` : "log";
|
|
598
|
+
}
|
|
599
|
+
var SDK_LINE = /^\s*\[bugstack[^\]]*\]/i;
|
|
600
|
+
var NODE_WARNING_LINE = /^\s*\(node:\d+\)\s+(?:\[[A-Z0-9_]+\]\s+)?\w*Warning:/;
|
|
601
|
+
function escapeRegExp(s) {
|
|
602
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
603
|
+
}
|
|
604
|
+
function redactText(text, redactFields) {
|
|
605
|
+
let out = text.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "$1 [REDACTED]");
|
|
606
|
+
if (redactFields.length > 0) {
|
|
607
|
+
const names = redactFields.filter((f) => f.length > 0).map(escapeRegExp).join("|");
|
|
608
|
+
if (names) {
|
|
609
|
+
const re = new RegExp(
|
|
610
|
+
`(["']?\\b\\w*(?:${names})\\w*["']?\\s*[=:]\\s*)("[^"]*"|'[^']*'|[^\\s,;&)}\\]]+)`,
|
|
611
|
+
"gi"
|
|
612
|
+
);
|
|
613
|
+
out = out.replace(re, "$1[REDACTED]");
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
return out;
|
|
617
|
+
}
|
|
618
|
+
function firstFrame(stack) {
|
|
619
|
+
return (stack ?? "").split("\n").find((l) => /^\s+at /.test(l))?.trim() ?? "";
|
|
620
|
+
}
|
|
621
|
+
function trimLibraryFrames(stack) {
|
|
622
|
+
const lines = stack.split("\n");
|
|
623
|
+
const header = [];
|
|
624
|
+
let i = 0;
|
|
625
|
+
while (i < lines.length && !/^\s+at /.test(lines[i])) header.push(lines[i++]);
|
|
626
|
+
let j = i;
|
|
627
|
+
while (j < lines.length && /node_modules|[/\\]bugstack-sdk[/\\]|\(node:internal|^\s+at node:internal/.test(lines[j])) j++;
|
|
628
|
+
if (j >= lines.length) return stack;
|
|
629
|
+
return [...header, ...lines.slice(j)].join("\n");
|
|
630
|
+
}
|
|
631
|
+
function siteOf(label, cause) {
|
|
632
|
+
if (label === void 0) return "";
|
|
633
|
+
const first = label.split("\n")[0].trim();
|
|
634
|
+
if (!first || first === cause.message || first === `${cause.name}: ${cause.message}`) return "";
|
|
635
|
+
return first.slice(0, 200);
|
|
636
|
+
}
|
|
637
|
+
function matchesIgnore(text, ignore) {
|
|
638
|
+
for (const p of ignore) {
|
|
639
|
+
try {
|
|
640
|
+
if (typeof p === "string" ? text.includes(p) : p.test(text)) return true;
|
|
641
|
+
} catch {
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
return false;
|
|
645
|
+
}
|
|
646
|
+
function captureLoggedCall(args, source, boundary) {
|
|
647
|
+
const s = shared();
|
|
648
|
+
if (s.busy) return;
|
|
649
|
+
try {
|
|
650
|
+
const sink = s.sink;
|
|
651
|
+
if (!sink) {
|
|
652
|
+
s.stats.dropped.no_client += 1;
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
const label = args.find((a) => typeof a === "string");
|
|
656
|
+
if (label !== void 0 && SDK_LINE.test(label)) {
|
|
657
|
+
s.stats.dropped.sdk_line += 1;
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
if (label !== void 0 && NODE_WARNING_LINE.test(label)) {
|
|
661
|
+
s.stats.dropped.node_warning += 1;
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
const cause = findError(args) ?? findStackText(args) ?? null;
|
|
665
|
+
if (sink.options.ignore.length > 0 && matchesIgnore(`${messageOfArgs(args)} ${cause ? `${cause.name}: ${cause.message}` : ""}`, sink.options.ignore)) {
|
|
666
|
+
s.stats.dropped.ignored += 1;
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
let message;
|
|
670
|
+
if (cause) {
|
|
671
|
+
message = `${siteOf(label, cause) || source}: ${cause.message}`;
|
|
672
|
+
} else {
|
|
673
|
+
message = sink.options.messages ? messageOfArgs(args) : "";
|
|
674
|
+
if (!message) {
|
|
675
|
+
s.stats.dropped.no_error_argument += 1;
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
const anchored = new Error(redactText(message, sink.redactFields).slice(0, ANCHORED_MESSAGE_MAX));
|
|
680
|
+
anchored.name = "LoggedError";
|
|
681
|
+
const capture = Error.captureStackTrace;
|
|
682
|
+
if (capture) capture(anchored, boundary);
|
|
683
|
+
if (anchored.stack) anchored.stack = trimLibraryFrames(anchored.stack);
|
|
684
|
+
if (cause) anchored.cause = cause;
|
|
685
|
+
const pending = { anchored, cause, label, source, messageOnly: !cause };
|
|
686
|
+
defer(() => forward(pending));
|
|
687
|
+
} catch {
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
function forward(p) {
|
|
691
|
+
const s = shared();
|
|
692
|
+
const sink = s.sink;
|
|
693
|
+
if (!sink) {
|
|
694
|
+
s.stats.dropped.no_client += 1;
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
try {
|
|
698
|
+
if (p.cause && s.reported.has(p.cause)) {
|
|
699
|
+
s.stats.dropped.already_reported += 1;
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
const now = s.now();
|
|
703
|
+
const key = p.messageOnly ? `${firstFrame(p.anchored.stack)}|message-only` : `${firstFrame(p.anchored.stack)}|${p.anchored.message}`;
|
|
704
|
+
const last = s.lastSent.get(key);
|
|
705
|
+
if (last !== void 0 && now - last < sink.options.repeatWindowMs) {
|
|
706
|
+
s.stats.dropped.repeat += 1;
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
if (now - s.windowStart >= 6e4) {
|
|
710
|
+
s.windowStart = now;
|
|
711
|
+
s.inWindow = 0;
|
|
712
|
+
}
|
|
713
|
+
if (s.inWindow >= sink.options.maxPerMinute) {
|
|
714
|
+
s.stats.dropped.rate_limited += 1;
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
s.inWindow += 1;
|
|
718
|
+
s.lastSent.set(key, now);
|
|
719
|
+
if (s.lastSent.size > MAX_REMEMBERED) {
|
|
720
|
+
const oldest = s.lastSent.keys().next().value;
|
|
721
|
+
if (oldest !== void 0) s.lastSent.delete(oldest);
|
|
722
|
+
}
|
|
723
|
+
if (p.cause) s.reported.add(p.cause);
|
|
724
|
+
const captured = buildLoggedCapturedError(p, sink);
|
|
725
|
+
s.busy = true;
|
|
726
|
+
try {
|
|
727
|
+
const result = sink.report(captured);
|
|
728
|
+
if (result && typeof result.catch === "function") {
|
|
729
|
+
result.catch(() => {
|
|
730
|
+
});
|
|
731
|
+
}
|
|
732
|
+
s.stats.forwarded += 1;
|
|
733
|
+
if (p.messageOnly) s.stats.messageOnly += 1;
|
|
734
|
+
} finally {
|
|
735
|
+
s.busy = false;
|
|
736
|
+
}
|
|
737
|
+
} catch {
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
function nodeVersion() {
|
|
741
|
+
try {
|
|
742
|
+
return typeof process !== "undefined" && process.version ? process.version : "unknown";
|
|
743
|
+
} catch {
|
|
744
|
+
return "unknown";
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
function buildLoggedCapturedError(p, sink) {
|
|
748
|
+
const stackFrames = parseStackTrace(p.anchored.stack);
|
|
749
|
+
const firstAppFrame = getFirstAppFrame(stackFrames);
|
|
750
|
+
const route = logRoute(p.label);
|
|
751
|
+
const metadata = {
|
|
752
|
+
source: p.source,
|
|
753
|
+
handled: true,
|
|
754
|
+
...firstAppFrame && {
|
|
755
|
+
sourceLocation: {
|
|
756
|
+
file: firstAppFrame.file,
|
|
757
|
+
line: firstAppFrame.line,
|
|
758
|
+
column: firstAppFrame.column,
|
|
759
|
+
function: firstAppFrame.function
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
};
|
|
763
|
+
if (p.cause) {
|
|
764
|
+
metadata.causeName = p.cause.name;
|
|
765
|
+
if (p.cause.stack) metadata.causeStack = redactText(p.cause.stack, sink.redactFields).slice(0, CAUSE_STACK_MAX);
|
|
766
|
+
} else {
|
|
767
|
+
metadata.messageOnly = true;
|
|
768
|
+
}
|
|
769
|
+
return {
|
|
770
|
+
id: `err_${Date.now().toString(36)}_${Math.random().toString(36).substring(2, 9)}`,
|
|
771
|
+
name: p.anchored.name,
|
|
772
|
+
message: p.anchored.message,
|
|
773
|
+
stack: p.anchored.stack,
|
|
774
|
+
stackFrames,
|
|
775
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
776
|
+
route,
|
|
777
|
+
method: "LOG",
|
|
778
|
+
statusCode: 500,
|
|
779
|
+
url: route,
|
|
780
|
+
environment: sink.environment,
|
|
781
|
+
projectId: sink.projectId,
|
|
782
|
+
sdkVersion: SDK_VERSION,
|
|
783
|
+
nodeVersion: nodeVersion(),
|
|
784
|
+
metadata
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
function attachLoggedErrorSink(sink) {
|
|
788
|
+
try {
|
|
789
|
+
const s = shared();
|
|
790
|
+
s.sink = sink;
|
|
791
|
+
if (sink.options.console) installConsoleWrapper(s);
|
|
792
|
+
} catch {
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
function detachLoggedErrorSink(sink) {
|
|
796
|
+
try {
|
|
797
|
+
const s = shared();
|
|
798
|
+
if (s.sink !== sink) return;
|
|
799
|
+
s.sink = null;
|
|
800
|
+
if (s.consoleWrapper && typeof console !== "undefined" && console.error === s.consoleWrapper && s.consoleOriginal) {
|
|
801
|
+
console.error = s.consoleOriginal;
|
|
802
|
+
s.consoleWrapper = null;
|
|
803
|
+
s.consoleOriginal = null;
|
|
804
|
+
}
|
|
805
|
+
} catch {
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
function installConsoleWrapper(s) {
|
|
809
|
+
if (typeof console === "undefined" || typeof console.error !== "function") return;
|
|
810
|
+
if (s.consoleWrapper && console.error === s.consoleWrapper) return;
|
|
811
|
+
const original = console.error;
|
|
812
|
+
const wrapper = function consoleErrorCapturedByBugstack(...args) {
|
|
813
|
+
original.apply(this === void 0 ? console : this, args);
|
|
814
|
+
const st = shared();
|
|
815
|
+
if (!st.sink || !st.sink.options.console) return;
|
|
816
|
+
captureLoggedCall(args, "console-error", wrapper);
|
|
817
|
+
};
|
|
818
|
+
s.consoleOriginal = original;
|
|
819
|
+
s.consoleWrapper = wrapper;
|
|
820
|
+
console.error = wrapper;
|
|
821
|
+
}
|
|
435
822
|
|
|
436
823
|
// src/core/client.ts
|
|
437
824
|
var DEFAULT_ENDPOINT = "https://dashboard.bugstack.ai/api/ingest/sdk";
|
|
@@ -461,6 +848,7 @@ var ErrorCaptureClient = class _ErrorCaptureClient {
|
|
|
461
848
|
static instance = null;
|
|
462
849
|
deduplicator;
|
|
463
850
|
retryQueue;
|
|
851
|
+
loggedErrorSink = null;
|
|
464
852
|
constructor(config) {
|
|
465
853
|
const isProduction = process.env.NODE_ENV === "production";
|
|
466
854
|
this.config = {
|
|
@@ -487,7 +875,8 @@ var ErrorCaptureClient = class _ErrorCaptureClient {
|
|
|
487
875
|
dropChunkErrors: config.dropChunkErrors ?? false,
|
|
488
876
|
chunkErrorsEndpoint: config.chunkErrorsEndpoint ?? deriveChunkErrorsEndpoint(
|
|
489
877
|
config.endpoint ?? process.env.BUGSTACK_ENDPOINT ?? DEFAULT_ENDPOINT
|
|
490
|
-
)
|
|
878
|
+
),
|
|
879
|
+
captureConsoleErrors: resolveLoggedErrorOptions(config.captureConsoleErrors)
|
|
491
880
|
};
|
|
492
881
|
this.deduplicator = new ErrorDeduplicator(this.config.deduplicationWindow);
|
|
493
882
|
this.retryQueue = new RetryQueue(
|
|
@@ -499,12 +888,23 @@ var ErrorCaptureClient = class _ErrorCaptureClient {
|
|
|
499
888
|
debug: this.config.debug
|
|
500
889
|
}
|
|
501
890
|
);
|
|
891
|
+
if (this.config.enabled) {
|
|
892
|
+
this.loggedErrorSink = {
|
|
893
|
+
options: this.config.captureConsoleErrors,
|
|
894
|
+
environment: this.config.environment,
|
|
895
|
+
projectId: this.config.projectId,
|
|
896
|
+
redactFields: this.config.redactFields,
|
|
897
|
+
report: (error) => this.reportError(error)
|
|
898
|
+
};
|
|
899
|
+
attachLoggedErrorSink(this.loggedErrorSink);
|
|
900
|
+
}
|
|
502
901
|
this.log("BugStack client initialized", {
|
|
503
902
|
endpoint: this.config.endpoint,
|
|
504
903
|
projectId: this.config.projectId,
|
|
505
904
|
environment: this.config.environment,
|
|
506
905
|
autoFix: this.config.autoFix,
|
|
507
|
-
deduplicationWindow: this.config.deduplicationWindow
|
|
906
|
+
deduplicationWindow: this.config.deduplicationWindow,
|
|
907
|
+
captureConsoleErrors: this.config.captureConsoleErrors.console
|
|
508
908
|
});
|
|
509
909
|
}
|
|
510
910
|
/**
|
|
@@ -703,6 +1103,10 @@ var ErrorCaptureClient = class _ErrorCaptureClient {
|
|
|
703
1103
|
* Should be called when shutting down to prevent memory leaks
|
|
704
1104
|
*/
|
|
705
1105
|
destroy() {
|
|
1106
|
+
if (this.loggedErrorSink) {
|
|
1107
|
+
detachLoggedErrorSink(this.loggedErrorSink);
|
|
1108
|
+
this.loggedErrorSink = null;
|
|
1109
|
+
}
|
|
706
1110
|
this.deduplicator.destroy();
|
|
707
1111
|
this.retryQueue.destroy();
|
|
708
1112
|
}
|
|
@@ -742,45 +1146,6 @@ function deriveChunkErrorsEndpoint(captureEndpoint) {
|
|
|
742
1146
|
return captureEndpoint.replace(/\/?$/, "/chunk-errors");
|
|
743
1147
|
}
|
|
744
1148
|
|
|
745
|
-
// src/core/utils/stack-parser.ts
|
|
746
|
-
var V8_STACK_FRAME_REGEX = /^\s*at\s+(?:async\s+)?(?:(.+?)\s+\()?(?:(.+?):(\d+):(\d+))\)?$/;
|
|
747
|
-
function isNodeModule(filePath) {
|
|
748
|
-
return filePath.includes("node_modules");
|
|
749
|
-
}
|
|
750
|
-
function isInternalCode(filePath) {
|
|
751
|
-
return filePath.startsWith("node:") || filePath.startsWith("internal/") || !filePath.includes("/");
|
|
752
|
-
}
|
|
753
|
-
function cleanFunctionName(name) {
|
|
754
|
-
if (!name) return void 0;
|
|
755
|
-
return name.replace(/^Object\./, "").replace(/^Module\./, "").replace(/^__webpack_require__\./, "").replace(/^webpack_require\./, "").trim();
|
|
756
|
-
}
|
|
757
|
-
function parseStackTrace(stack) {
|
|
758
|
-
if (!stack) return [];
|
|
759
|
-
const lines = stack.split("\n");
|
|
760
|
-
const frames = [];
|
|
761
|
-
for (const line of lines) {
|
|
762
|
-
const match = V8_STACK_FRAME_REGEX.exec(line);
|
|
763
|
-
if (match) {
|
|
764
|
-
const [, functionName, file, lineStr, columnStr] = match;
|
|
765
|
-
const frame = {
|
|
766
|
-
function: cleanFunctionName(functionName),
|
|
767
|
-
file: file ?? void 0,
|
|
768
|
-
line: lineStr ? parseInt(lineStr, 10) : void 0,
|
|
769
|
-
column: columnStr ? parseInt(columnStr, 10) : void 0
|
|
770
|
-
};
|
|
771
|
-
if (frame.file) {
|
|
772
|
-
frame.isNodeModule = isNodeModule(frame.file);
|
|
773
|
-
frame.isInternal = isInternalCode(frame.file);
|
|
774
|
-
}
|
|
775
|
-
frames.push(frame);
|
|
776
|
-
}
|
|
777
|
-
}
|
|
778
|
-
return frames;
|
|
779
|
-
}
|
|
780
|
-
function getFirstAppFrame(frames) {
|
|
781
|
-
return frames.find((frame) => !frame.isNodeModule && !frame.isInternal);
|
|
782
|
-
}
|
|
783
|
-
|
|
784
1149
|
// src/core/utils/sanitize.ts
|
|
785
1150
|
var REDACT_PLACEHOLDER = "[REDACTED]";
|
|
786
1151
|
var TRUNCATE_PLACEHOLDER = "[TRUNCATED]";
|
|
@@ -967,6 +1332,7 @@ function bugstackErrorHandler(config) {
|
|
|
967
1332
|
}
|
|
968
1333
|
return (err, req, _res, next) => {
|
|
969
1334
|
const client = ErrorCaptureClient.getInstance();
|
|
1335
|
+
markErrorReported(err);
|
|
970
1336
|
if (client && client.getConfig().enabled) {
|
|
971
1337
|
const capturedError = buildCapturedError(err, req, client);
|
|
972
1338
|
client.reportError(capturedError).catch(() => {
|