bugstack-sdk 2.2.1 → 2.2.2

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 (36) hide show
  1. package/CHANGELOG.md +109 -96
  2. package/README.md +423 -421
  3. package/bin/bugstack.cjs +6 -6
  4. package/dist/adapters/express/index.d.mts +2 -2
  5. package/dist/adapters/express/index.d.ts +2 -2
  6. package/dist/adapters/express/index.js +2 -2
  7. package/dist/adapters/express/index.js.map +1 -1
  8. package/dist/adapters/express/index.mjs +2 -2
  9. package/dist/adapters/express/index.mjs.map +1 -1
  10. package/dist/adapters/generic/index.d.mts +2 -2
  11. package/dist/adapters/generic/index.d.ts +2 -2
  12. package/dist/adapters/generic/index.js +2 -2
  13. package/dist/adapters/generic/index.js.map +1 -1
  14. package/dist/adapters/generic/index.mjs +2 -2
  15. package/dist/adapters/generic/index.mjs.map +1 -1
  16. package/dist/adapters/nextjs/index.d.mts +2 -2
  17. package/dist/adapters/nextjs/index.d.ts +2 -2
  18. package/dist/adapters/nextjs/index.js +2 -2
  19. package/dist/adapters/nextjs/index.js.map +1 -1
  20. package/dist/adapters/nextjs/index.mjs +2 -2
  21. package/dist/adapters/nextjs/index.mjs.map +1 -1
  22. package/dist/build/cli.js.map +1 -1
  23. package/dist/build/cli.mjs.map +1 -1
  24. package/dist/build/upload.js.map +1 -1
  25. package/dist/build/upload.mjs.map +1 -1
  26. package/dist/{client-DoqE7sNh.d.mts → client-DK_ItP55.d.mts} +1 -1
  27. package/dist/{client-DoqE7sNh.d.ts → client-DK_ItP55.d.ts} +1 -1
  28. package/dist/index.d.mts +2 -2
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.js +2 -2
  31. package/dist/index.js.map +1 -1
  32. package/dist/index.mjs +2 -2
  33. package/dist/index.mjs.map +1 -1
  34. package/dist/next-config/index.js.map +1 -1
  35. package/dist/next-config/index.mjs.map +1 -1
  36. package/package.json +103 -104
package/README.md CHANGED
@@ -1,421 +1,423 @@
1
- # bugstack-sdk
2
-
3
- Framework-agnostic error capture SDK for Node.js. Automatically captures errors with full context and reports them to BugStack for AI-powered fix generation.
4
-
5
- **Get your API key at:** [dashboard.bugstack.ai](https://dashboard.bugstack.ai)
6
-
7
- ## Features
8
-
9
- - **Multiple frameworks** — First-class support for Next.js, Express, and generic Node.js
10
- - **Full error context** — Captures stack traces, request body, headers, query params, route params
11
- - **Automatic sanitization** — Sensitive data (passwords, tokens, API keys) is redacted automatically
12
- - **Non-blocking** — Error reporting is async and never slows down your responses
13
- - **Deduplication** — Same errors are batched within a configurable time window
14
- - **Retry queue** — Failed reports are retried with exponential backoff
15
- - **TypeScript first** — Full type safety with comprehensive type definitions
16
-
17
- ## Installation
18
-
19
- ```bash
20
- npm install bugstack-sdk
21
- ```
22
-
23
- ## Quick Start
24
-
25
- ### Next.js (App Router)
26
-
27
- **1. Initialize the client once:**
28
-
29
- ```typescript
30
- // lib/bugstack.ts
31
- import { ErrorCaptureClient } from "bugstack-sdk";
32
-
33
- ErrorCaptureClient.init({
34
- apiKey: process.env.BUGSTACK_API_KEY!,
35
- endpoint: "https://bugstack-error-service.onrender.com/api/capture",
36
- });
37
- ```
38
-
39
- **2. Wrap your API route handlers:**
40
-
41
- ```typescript
42
- // app/api/users/route.ts
43
- import { NextResponse } from "next/server";
44
- import { withErrorCapture } from "bugstack-sdk/next";
45
- import "@/lib/bugstack"; // ensures client is initialized
46
-
47
- export const GET = withErrorCapture(async (request) => {
48
- const users = await db.users.findMany();
49
- return NextResponse.json({ users });
50
- });
51
-
52
- export const POST = withErrorCapture(async (request) => {
53
- const body = await request.json();
54
- const user = await db.users.create({ data: body });
55
- return NextResponse.json({ user }, { status: 201 });
56
- });
57
- ```
58
-
59
- **3. Dynamic routes with params:**
60
-
61
- ```typescript
62
- // app/api/users/[id]/route.ts
63
- import { NextResponse } from "next/server";
64
- import { withErrorCapture } from "bugstack-sdk/next";
65
- import "@/lib/bugstack";
66
-
67
- export const GET = withErrorCapture<{ id: string }>(
68
- async (request, { params }) => {
69
- const user = await db.users.findUnique({ where: { id: params.id } });
70
- if (!user) throw new Error("User not found");
71
- return NextResponse.json({ user });
72
- }
73
- );
74
- ```
75
-
76
- ---
77
-
78
- ### Express
79
-
80
- **Option A: Error handler middleware (recommended)**
81
-
82
- ```typescript
83
- import express from "express";
84
- import { bugstackErrorHandler } from "bugstack-sdk/express";
85
-
86
- const app = express();
87
-
88
- // Your routes
89
- app.get("/api/users", async (req, res) => {
90
- const users = await db.users.findMany();
91
- res.json({ users });
92
- });
93
-
94
- // Add BugStack error handler AFTER all routes
95
- app.use(
96
- bugstackErrorHandler({
97
- apiKey: process.env.BUGSTACK_API_KEY!,
98
- endpoint: "https://bugstack-error-service.onrender.com/api/capture",
99
- })
100
- );
101
- ```
102
-
103
- **Option B: Wrap individual route handlers**
104
-
105
- ```typescript
106
- import { initBugStack, wrapExpressHandler } from "bugstack-sdk/express";
107
-
108
- // Initialize once
109
- app.use(
110
- initBugStack({
111
- apiKey: process.env.BUGSTACK_API_KEY!,
112
- endpoint: "https://bugstack-error-service.onrender.com/api/capture",
113
- })
114
- );
115
-
116
- // Wrap specific routes
117
- app.get("/api/users/:id", wrapExpressHandler(async (req, res) => {
118
- const user = await getUser(req.params.id);
119
- res.json(user);
120
- }));
121
- ```
122
-
123
- ---
124
-
125
- ### Generic Node.js
126
-
127
- For any Node.js application (scripts, workers, serverless functions, etc.):
128
-
129
- ```typescript
130
- import { initBugStack, captureError, installGlobalHandlers } from "bugstack-sdk/generic";
131
-
132
- // Initialize once
133
- initBugStack({
134
- apiKey: process.env.BUGSTACK_API_KEY!,
135
- endpoint: "https://bugstack-error-service.onrender.com/api/capture",
136
- });
137
-
138
- // Optional: catch uncaught exceptions and unhandled rejections globally
139
- installGlobalHandlers();
140
-
141
- // Capture errors manually in try/catch blocks
142
- try {
143
- await processData();
144
- } catch (error) {
145
- await captureError(error, { operation: "processData" });
146
- }
147
- ```
148
-
149
- **Wrap functions for automatic capture:**
150
-
151
- ```typescript
152
- import { wrapFunction } from "bugstack-sdk/generic";
153
-
154
- const processData = wrapFunction(
155
- async (data: Input) => {
156
- // errors thrown here are automatically captured
157
- return transform(data);
158
- },
159
- { operation: "processData" }
160
- );
161
- ```
162
-
163
- **Create scoped capture functions:**
164
-
165
- ```typescript
166
- import { createErrorCapture } from "bugstack-sdk/generic";
167
-
168
- const captureDbError = createErrorCapture({ component: "database" });
169
-
170
- try {
171
- await db.query("SELECT ...");
172
- } catch (error) {
173
- await captureDbError(error, { query: "SELECT ..." });
174
- }
175
- ```
176
-
177
- ---
178
-
179
- ## Source Maps for Production (Next.js)
180
-
181
- 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.
182
-
183
- Uploading source maps closes that loop. The orchestrator resolves bundled frames back to source-file positions (`app/api/orders/route.ts:42:5`) before deciding which file to patch.
184
-
185
- ### Two-step setup
186
-
187
- **1. Wrap your `next.config.js`:**
188
-
189
- ```js
190
- const { withBugstack } = require('bugstack-sdk/next-config')
191
-
192
- module.exports = withBugstack({
193
- // your existing Next.js config
194
- })
195
- ```
196
-
197
- This enables `webpack.devtool = 'source-map'` for production server builds (no effect on dev or client). Any existing `webpack` hook you have is preserved and runs first.
198
-
199
- **2. Append the upload command to your `build` script:**
200
-
201
- ```json
202
- {
203
- "scripts": {
204
- "build": "next build && bugstack sourcemaps upload"
205
- }
206
- }
207
- ```
208
-
209
- The CLI walks `.next/server/**/*.map`, uploads each to bugstack keyed by the active release, and **never fails the build** — source maps are an optimisation, not a release gate.
210
-
211
- ### Required environment
212
-
213
- The CLI needs two env vars at build time. Set them in your CI / hosting provider:
214
-
215
- | Variable | Purpose |
216
- |---|---|
217
- | `BUGSTACK_PROJECT_API_KEY` | Your project SDK key (find it in your project settings on the bugstack dashboard). |
218
- | `BUGSTACK_ENDPOINT` | Base URL of the bugstack ingest service. The CLI appends `/api/sourcemaps/upload` automatically. |
219
-
220
- Release identifiers are auto-detected from `BUGSTACK_RELEASE`, `RENDER_GIT_COMMIT`, `VERCEL_GIT_COMMIT_SHA`, `GITHUB_SHA`, or `git rev-parse HEAD` — in that order. Override with `--release <id>` if you have a different versioning scheme.
221
-
222
- ### Verifying
223
-
224
- After your next deploy with these env vars set, the build log should print something like:
225
-
226
- ```
227
- [bugstack] Uploading 68 source map(s) to https://… (release=a9ad704)…
228
- [bugstack] Uploaded 68/68 maps (10.0MB) in 4.2s.
229
- ```
230
-
231
- When a server-side error captures next, the row's stack trace and proposed fix will reference real source files (`app/api/.../route.ts`) instead of bundled chunks.
232
-
233
- ### Programmatic API
234
-
235
- If you'd rather drive the upload from a custom script:
236
-
237
- ```ts
238
- import { uploadSourceMaps } from 'bugstack-sdk/build'
239
-
240
- await uploadSourceMaps({
241
- apiKey: process.env.BUGSTACK_PROJECT_API_KEY,
242
- endpoint: process.env.BUGSTACK_ENDPOINT,
243
- release: process.env.GIT_SHA,
244
- serverDir: '.next/server', // override for non-Next builds
245
- })
246
- ```
247
-
248
- ### Other build systems
249
-
250
- The CLI defaults to `.next/server` but accepts `--server-dir <path>` so it works for any directory of compiled `.js` + `.js.map` pairs (e.g. `dist/` for tsc, `build/` for CRA, custom esbuild outputs). The `withBugstack` wrapper is Next.js-specific; for other frameworks, enable source-map emission in your bundler config and run the CLI directly.
251
-
252
- ---
253
-
254
- ## Other Languages
255
-
256
- BugStack also provides SDKs for:
257
-
258
- | Language | Package | Install |
259
- |----------|---------|---------|
260
- | Python | [bugstack](https://pypi.org/project/bugstack/) | `pip install bugstack` |
261
- | Ruby | [bugstack](https://rubygems.org/gems/bugstack) | `gem install bugstack` |
262
- | Go | [bugstack-go](https://github.com/MasonBachmann7/Bugstack-SDK-Go) | `go get github.com/MasonBachmann7/bugstack-go` |
263
-
264
- ---
265
-
266
- ## Configuration
267
-
268
- ### Full Options
269
-
270
- ```typescript
271
- import { ErrorCaptureClient } from "bugstack-sdk";
272
-
273
- ErrorCaptureClient.init({
274
- // Required
275
- apiKey: "your-api-key",
276
-
277
- // Endpoint (defaults to localhost for local dev)
278
- endpoint: "https://bugstack-error-service.onrender.com/api/capture",
279
-
280
- // Optional — defaults shown
281
- projectId: "",
282
- environment: process.env.NODE_ENV, // "development", "production", etc.
283
- enabled: true, // set false to disable capture entirely
284
-
285
- // Request capture
286
- captureRequestBody: true,
287
- captureQueryParams: true,
288
- captureHeaders: true,
289
- maxBodySize: 10000, // 10KB max body capture
290
-
291
- // Additional fields to redact (added to built-in defaults)
292
- redactFields: ["customSecret", "internalToken"],
293
-
294
- // Custom metadata included with every error
295
- metadata: { service: "api", version: "1.0.0" },
296
-
297
- // Network
298
- timeout: 5000, // 5s timeout for error reporting
299
- deduplicationWindow: 5 * 60 * 1000, // 5 min window for dedup
300
-
301
- // Debug logging (defaults to true in development)
302
- debug: false,
303
-
304
- // Custom filter — return false to skip certain errors
305
- shouldCapture: (error, request) => {
306
- if (error.message.includes("not found")) return false;
307
- return true;
308
- },
309
-
310
- // Transform errors before sending
311
- beforeSend: (capturedError) => {
312
- capturedError.metadata = { ...capturedError.metadata, custom: "value" };
313
- return capturedError; // return null to skip
314
- },
315
- });
316
- ```
317
-
318
- ### Environment Variables
319
-
320
- The SDK reads these automatically:
321
-
322
- ```bash
323
- BUGSTACK_API_KEY=your-api-key # Required
324
- BUGSTACK_ENDPOINT=https://bugstack-error-service.onrender.com/api/capture # Optional
325
- BUGSTACK_PROJECT_ID=my-project # Optional
326
- NODE_ENV=production # Optional
327
- ```
328
-
329
- ### Per-Route Options (Next.js)
330
-
331
- ```typescript
332
- export const POST = withErrorCapture(
333
- async (request) => { /* ... */ },
334
- undefined, // use existing client config
335
- {
336
- statusCode: 400,
337
- metadata: { operation: "createUser" },
338
- shouldCapture: (error) => error.name !== "ValidationError",
339
- }
340
- );
341
- ```
342
-
343
- ---
344
-
345
- ## Automatic Sanitization
346
-
347
- The SDK redacts sensitive data from headers, request bodies, and query params.
348
-
349
- **Built-in redacted fields:**
350
- `password`, `secret`, `token`, `apikey`, `api_key`, `apiKey`, `authorization`, `auth`, `credential`, `private`, `credit_card`, `creditcard`, `card_number`, `cvv`, `ssn`, `social_security`
351
-
352
- **Always-redacted headers:**
353
- `authorization`, `cookie`, `set-cookie`, `x-api-key`, `x-auth-token`, `proxy-authorization`
354
-
355
- Add custom fields via the `redactFields` config option.
356
-
357
- ---
358
-
359
- ## Error Resilience
360
-
361
- The SDK never interferes with your application:
362
-
363
- - **Network failures** — Silently retried (up to 5 times with exponential backoff)
364
- - **Timeouts** — Configurable, defaults to 5 seconds
365
- - **SDK errors** — Caught and logged in debug mode, never thrown to your app
366
- - **Original error preserved** — The wrapper re-throws the original error so your framework handles the response normally
367
-
368
- ---
369
-
370
- ## Captured Data
371
-
372
- Each error report includes:
373
-
374
- | Field | Description |
375
- |-------|-------------|
376
- | `id` | Unique error ID |
377
- | `fingerprint` | Stable hash for deduplication |
378
- | `name` | Error type (TypeError, etc.) |
379
- | `message` | Error message |
380
- | `stack` | Full stack trace |
381
- | `stackFrames` | Parsed stack frames with file, line, column |
382
- | `route` | API route path |
383
- | `method` | HTTP method |
384
- | `statusCode` | HTTP status code |
385
- | `url` | Full request URL |
386
- | `queryParams` | Sanitized query parameters |
387
- | `requestBody` | Sanitized request body |
388
- | `requestHeaders` | Sanitized headers |
389
- | `routeParams` | Dynamic route parameters |
390
- | `environment` | Environment name |
391
- | `projectId` | Project identifier |
392
- | `metadata` | Custom metadata |
393
-
394
- ---
395
-
396
- ## TypeScript
397
-
398
- All types are exported:
399
-
400
- ```typescript
401
- import type {
402
- ErrorCaptureConfig,
403
- CapturedError,
404
- StackFrame,
405
- RouteOptions,
406
- RouteContext,
407
- ErrorReportPayload,
408
- SourceContext,
409
- } from "bugstack-sdk";
410
- ```
411
-
412
- ## Compatibility
413
-
414
- - **Next.js**: 14.0.0+
415
- - **Express**: 4.x or 5.x
416
- - **Node.js**: 18.0.0+
417
- - **TypeScript**: 5.0.0+ (optional)
418
-
419
- ## License
420
-
421
- MIT
1
+ # bugstack-sdk
2
+
3
+ The [Bugstack](https://bugstack.ai) SDK for Node.js: Next.js, Express and any Node process.
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 server error: it sends the error, its stack trace and the route, and Bugstack takes it from there.
6
+
7
+ **Get your API key at:** [dashboard.bugstack.ai](https://dashboard.bugstack.ai)
8
+
9
+ ## Features
10
+
11
+ - **Multiple frameworks** — First-class support for Next.js, Express, and generic Node.js
12
+ - **Full error context** — Captures stack traces, request body, headers, query params, route params
13
+ - **Automatic sanitization** — Sensitive data (passwords, tokens, API keys) is redacted automatically
14
+ - **Non-blocking** — Error reporting is async and never slows down your responses
15
+ - **Deduplication** — Same errors are batched within a configurable time window
16
+ - **Retry queue** — Failed reports are retried with exponential backoff
17
+ - **TypeScript first** — Full type safety with comprehensive type definitions
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ npm install --save-exact bugstack-sdk
23
+ ```
24
+
25
+ ## Quick Start
26
+
27
+ ### Next.js (App Router)
28
+
29
+ **1. Initialize the client once:**
30
+
31
+ ```typescript
32
+ // lib/bugstack.ts
33
+ import { ErrorCaptureClient } from "bugstack-sdk";
34
+
35
+ ErrorCaptureClient.init({
36
+ apiKey: process.env.BUGSTACK_API_KEY!,
37
+ endpoint: "https://dashboard.bugstack.ai/api/ingest/sdk",
38
+ });
39
+ ```
40
+
41
+ **2. Wrap your API route handlers:**
42
+
43
+ ```typescript
44
+ // app/api/users/route.ts
45
+ import { NextResponse } from "next/server";
46
+ import { withErrorCapture } from "bugstack-sdk/next";
47
+ import "@/lib/bugstack"; // ensures client is initialized
48
+
49
+ export const GET = withErrorCapture(async (request) => {
50
+ const users = await db.users.findMany();
51
+ return NextResponse.json({ users });
52
+ });
53
+
54
+ export const POST = withErrorCapture(async (request) => {
55
+ const body = await request.json();
56
+ const user = await db.users.create({ data: body });
57
+ return NextResponse.json({ user }, { status: 201 });
58
+ });
59
+ ```
60
+
61
+ **3. Dynamic routes with params:**
62
+
63
+ ```typescript
64
+ // app/api/users/[id]/route.ts
65
+ import { NextResponse } from "next/server";
66
+ import { withErrorCapture } from "bugstack-sdk/next";
67
+ import "@/lib/bugstack";
68
+
69
+ export const GET = withErrorCapture<{ id: string }>(
70
+ async (request, { params }) => {
71
+ const user = await db.users.findUnique({ where: { id: params.id } });
72
+ if (!user) throw new Error("User not found");
73
+ return NextResponse.json({ user });
74
+ }
75
+ );
76
+ ```
77
+
78
+ ---
79
+
80
+ ### Express
81
+
82
+ **Option A: Error handler middleware (recommended)**
83
+
84
+ ```typescript
85
+ import express from "express";
86
+ import { bugstackErrorHandler } from "bugstack-sdk/express";
87
+
88
+ const app = express();
89
+
90
+ // Your routes
91
+ app.get("/api/users", async (req, res) => {
92
+ const users = await db.users.findMany();
93
+ res.json({ users });
94
+ });
95
+
96
+ // Add the Bugstack error handler AFTER all routes
97
+ app.use(
98
+ bugstackErrorHandler({
99
+ apiKey: process.env.BUGSTACK_API_KEY!,
100
+ endpoint: "https://dashboard.bugstack.ai/api/ingest/sdk",
101
+ })
102
+ );
103
+ ```
104
+
105
+ **Option B: Wrap individual route handlers**
106
+
107
+ ```typescript
108
+ import { initBugStack, wrapExpressHandler } from "bugstack-sdk/express";
109
+
110
+ // Initialize once
111
+ app.use(
112
+ initBugStack({
113
+ apiKey: process.env.BUGSTACK_API_KEY!,
114
+ endpoint: "https://dashboard.bugstack.ai/api/ingest/sdk",
115
+ })
116
+ );
117
+
118
+ // Wrap specific routes
119
+ app.get("/api/users/:id", wrapExpressHandler(async (req, res) => {
120
+ const user = await getUser(req.params.id);
121
+ res.json(user);
122
+ }));
123
+ ```
124
+
125
+ ---
126
+
127
+ ### Generic Node.js
128
+
129
+ For any Node.js application (scripts, workers, serverless functions, etc.):
130
+
131
+ ```typescript
132
+ import { initBugStack, captureError, installGlobalHandlers } from "bugstack-sdk/generic";
133
+
134
+ // Initialize once
135
+ initBugStack({
136
+ apiKey: process.env.BUGSTACK_API_KEY!,
137
+ endpoint: "https://dashboard.bugstack.ai/api/ingest/sdk",
138
+ });
139
+
140
+ // Optional: catch uncaught exceptions and unhandled rejections globally
141
+ installGlobalHandlers();
142
+
143
+ // Capture errors manually in try/catch blocks
144
+ try {
145
+ await processData();
146
+ } catch (error) {
147
+ await captureError(error, { operation: "processData" });
148
+ }
149
+ ```
150
+
151
+ **Wrap functions for automatic capture:**
152
+
153
+ ```typescript
154
+ import { wrapFunction } from "bugstack-sdk/generic";
155
+
156
+ const processData = wrapFunction(
157
+ async (data: Input) => {
158
+ // errors thrown here are automatically captured
159
+ return transform(data);
160
+ },
161
+ { operation: "processData" }
162
+ );
163
+ ```
164
+
165
+ **Create scoped capture functions:**
166
+
167
+ ```typescript
168
+ import { createErrorCapture } from "bugstack-sdk/generic";
169
+
170
+ const captureDbError = createErrorCapture({ component: "database" });
171
+
172
+ try {
173
+ await db.query("SELECT ...");
174
+ } catch (error) {
175
+ await captureDbError(error, { query: "SELECT ..." });
176
+ }
177
+ ```
178
+
179
+ ---
180
+
181
+ ## Source Maps for Production (Next.js)
182
+
183
+ 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.
184
+
185
+ Uploading source maps closes that loop. The orchestrator resolves bundled frames back to source-file positions (`app/api/orders/route.ts:42:5`) before deciding which file to patch.
186
+
187
+ ### Two-step setup
188
+
189
+ **1. Wrap your `next.config.js`:**
190
+
191
+ ```js
192
+ const { withBugstack } = require('bugstack-sdk/next-config')
193
+
194
+ module.exports = withBugstack({
195
+ // your existing Next.js config
196
+ })
197
+ ```
198
+
199
+ This enables `webpack.devtool = 'source-map'` for production server builds (no effect on dev or client). Any existing `webpack` hook you have is preserved and runs first.
200
+
201
+ **2. Append the upload command to your `build` script:**
202
+
203
+ ```json
204
+ {
205
+ "scripts": {
206
+ "build": "next build && bugstack sourcemaps upload"
207
+ }
208
+ }
209
+ ```
210
+
211
+ The CLI walks `.next/server/**/*.map`, uploads each to Bugstack keyed by the active release, and **never fails the build** — source maps are an optimisation, not a release gate.
212
+
213
+ ### Required environment
214
+
215
+ The CLI needs two env vars at build time. Set them in your CI / hosting provider:
216
+
217
+ | Variable | Purpose |
218
+ |---|---|
219
+ | `BUGSTACK_PROJECT_API_KEY` | Your project SDK key (find it in your project settings on the Bugstack dashboard). |
220
+ | `BUGSTACK_ENDPOINT` | Base URL of the Bugstack ingest service. The CLI appends `/api/sourcemaps/upload` automatically. |
221
+
222
+ Release identifiers are auto-detected from `BUGSTACK_RELEASE`, `RENDER_GIT_COMMIT`, `VERCEL_GIT_COMMIT_SHA`, `GITHUB_SHA`, or `git rev-parse HEAD` — in that order. Override with `--release <id>` if you have a different versioning scheme.
223
+
224
+ ### Verifying
225
+
226
+ After your next deploy with these env vars set, the build log should print something like:
227
+
228
+ ```
229
+ [bugstack] Uploading 68 source map(s) to https://… (release=a9ad704)…
230
+ [bugstack] Uploaded 68/68 maps (10.0MB) in 4.2s.
231
+ ```
232
+
233
+ When a server-side error captures next, the row's stack trace and proposed fix will reference real source files (`app/api/.../route.ts`) instead of bundled chunks.
234
+
235
+ ### Programmatic API
236
+
237
+ If you'd rather drive the upload from a custom script:
238
+
239
+ ```ts
240
+ import { uploadSourceMaps } from 'bugstack-sdk/build'
241
+
242
+ await uploadSourceMaps({
243
+ apiKey: process.env.BUGSTACK_PROJECT_API_KEY,
244
+ endpoint: process.env.BUGSTACK_ENDPOINT,
245
+ release: process.env.GIT_SHA,
246
+ serverDir: '.next/server', // override for non-Next builds
247
+ })
248
+ ```
249
+
250
+ ### Other build systems
251
+
252
+ The CLI defaults to `.next/server` but accepts `--server-dir <path>` so it works for any directory of compiled `.js` + `.js.map` pairs (e.g. `dist/` for tsc, `build/` for CRA, custom esbuild outputs). The `withBugstack` wrapper is Next.js-specific; for other frameworks, enable source-map emission in your bundler config and run the CLI directly.
253
+
254
+ ---
255
+
256
+ ## Other Languages
257
+
258
+ Bugstack also provides SDKs for:
259
+
260
+ | Language | Package | Install |
261
+ |----------|---------|---------|
262
+ | Python | [bugstack](https://pypi.org/project/bugstack/) | `pip install bugstack` |
263
+ | Ruby | [bugstack](https://rubygems.org/gems/bugstack) | `gem install bugstack` |
264
+ | Go | [bugstack-go](https://github.com/MasonBachmann7/Bugstack-SDK-Go) | `go get github.com/MasonBachmann7/bugstack-go` |
265
+
266
+ ---
267
+
268
+ ## Configuration
269
+
270
+ ### Full Options
271
+
272
+ ```typescript
273
+ import { ErrorCaptureClient } from "bugstack-sdk";
274
+
275
+ ErrorCaptureClient.init({
276
+ // Required
277
+ apiKey: "your-api-key",
278
+
279
+ // Endpoint (defaults to the Bugstack ingest endpoint)
280
+ endpoint: "https://dashboard.bugstack.ai/api/ingest/sdk",
281
+
282
+ // Optional — defaults shown
283
+ projectId: "",
284
+ environment: process.env.NODE_ENV, // "development", "production", etc.
285
+ enabled: true, // set false to disable capture entirely
286
+
287
+ // Request capture
288
+ captureRequestBody: true,
289
+ captureQueryParams: true,
290
+ captureHeaders: true,
291
+ maxBodySize: 10000, // 10KB max body capture
292
+
293
+ // Additional fields to redact (added to built-in defaults)
294
+ redactFields: ["customSecret", "internalToken"],
295
+
296
+ // Custom metadata included with every error
297
+ metadata: { service: "api", version: "1.0.0" },
298
+
299
+ // Network
300
+ timeout: 5000, // 5s timeout for error reporting
301
+ deduplicationWindow: 5 * 60 * 1000, // 5 min window for dedup
302
+
303
+ // Debug logging (defaults to true in development)
304
+ debug: false,
305
+
306
+ // Custom filter — return false to skip certain errors
307
+ shouldCapture: (error, request) => {
308
+ if (error.message.includes("not found")) return false;
309
+ return true;
310
+ },
311
+
312
+ // Transform errors before sending
313
+ beforeSend: (capturedError) => {
314
+ capturedError.metadata = { ...capturedError.metadata, custom: "value" };
315
+ return capturedError; // return null to skip
316
+ },
317
+ });
318
+ ```
319
+
320
+ ### Environment Variables
321
+
322
+ The SDK reads these automatically:
323
+
324
+ ```bash
325
+ BUGSTACK_API_KEY=your-api-key # Required
326
+ BUGSTACK_ENDPOINT=https://dashboard.bugstack.ai/api/ingest/sdk # Optional
327
+ BUGSTACK_PROJECT_ID=my-project # Optional
328
+ NODE_ENV=production # Optional
329
+ ```
330
+
331
+ ### Per-Route Options (Next.js)
332
+
333
+ ```typescript
334
+ export const POST = withErrorCapture(
335
+ async (request) => { /* ... */ },
336
+ undefined, // use existing client config
337
+ {
338
+ statusCode: 400,
339
+ metadata: { operation: "createUser" },
340
+ shouldCapture: (error) => error.name !== "ValidationError",
341
+ }
342
+ );
343
+ ```
344
+
345
+ ---
346
+
347
+ ## Automatic Sanitization
348
+
349
+ The SDK redacts sensitive data from headers, request bodies, and query params.
350
+
351
+ **Built-in redacted fields:**
352
+ `password`, `secret`, `token`, `apikey`, `api_key`, `apiKey`, `authorization`, `auth`, `credential`, `private`, `credit_card`, `creditcard`, `card_number`, `cvv`, `ssn`, `social_security`
353
+
354
+ **Always-redacted headers:**
355
+ `authorization`, `cookie`, `set-cookie`, `x-api-key`, `x-auth-token`, `proxy-authorization`
356
+
357
+ Add custom fields via the `redactFields` config option.
358
+
359
+ ---
360
+
361
+ ## Error Resilience
362
+
363
+ The SDK never interferes with your application:
364
+
365
+ - **Network failures** — Silently retried (up to 5 times with exponential backoff)
366
+ - **Timeouts** — Configurable, defaults to 5 seconds
367
+ - **SDK errors** — Caught and logged in debug mode, never thrown to your app
368
+ - **Original error preserved** — The wrapper re-throws the original error so your framework handles the response normally
369
+
370
+ ---
371
+
372
+ ## Captured Data
373
+
374
+ Each error report includes:
375
+
376
+ | Field | Description |
377
+ |-------|-------------|
378
+ | `id` | Unique error ID |
379
+ | `fingerprint` | Stable hash for deduplication |
380
+ | `name` | Error type (TypeError, etc.) |
381
+ | `message` | Error message |
382
+ | `stack` | Full stack trace |
383
+ | `stackFrames` | Parsed stack frames with file, line, column |
384
+ | `route` | API route path |
385
+ | `method` | HTTP method |
386
+ | `statusCode` | HTTP status code |
387
+ | `url` | Full request URL |
388
+ | `queryParams` | Sanitized query parameters |
389
+ | `requestBody` | Sanitized request body |
390
+ | `requestHeaders` | Sanitized headers |
391
+ | `routeParams` | Dynamic route parameters |
392
+ | `environment` | Environment name |
393
+ | `projectId` | Project identifier |
394
+ | `metadata` | Custom metadata |
395
+
396
+ ---
397
+
398
+ ## TypeScript
399
+
400
+ All types are exported:
401
+
402
+ ```typescript
403
+ import type {
404
+ ErrorCaptureConfig,
405
+ CapturedError,
406
+ StackFrame,
407
+ RouteOptions,
408
+ RouteContext,
409
+ ErrorReportPayload,
410
+ SourceContext,
411
+ } from "bugstack-sdk";
412
+ ```
413
+
414
+ ## Compatibility
415
+
416
+ - **Next.js**: 14.0.0+
417
+ - **Express**: 4.x or 5.x
418
+ - **Node.js**: 18.0.0+
419
+ - **TypeScript**: 5.0.0+ (optional)
420
+
421
+ ## License
422
+
423
+ MIT