bugstack-sdk 2.0.1 → 2.1.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/README.md CHANGED
@@ -1,346 +1,346 @@
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
- ## Other Languages
180
-
181
- BugStack also provides SDKs for:
182
-
183
- | Language | Package | Install |
184
- |----------|---------|---------|
185
- | Python | [bugstack](https://pypi.org/project/bugstack/) | `pip install bugstack` |
186
- | Ruby | [bugstack](https://rubygems.org/gems/bugstack) | `gem install bugstack` |
187
- | Go | [bugstack-go](https://github.com/MasonBachmann7/Bugstack-SDK-Go) | `go get github.com/MasonBachmann7/bugstack-go` |
188
-
189
- ---
190
-
191
- ## Configuration
192
-
193
- ### Full Options
194
-
195
- ```typescript
196
- import { ErrorCaptureClient } from "bugstack-sdk";
197
-
198
- ErrorCaptureClient.init({
199
- // Required
200
- apiKey: "your-api-key",
201
-
202
- // Endpoint (defaults to localhost for local dev)
203
- endpoint: "https://bugstack-error-service.onrender.com/api/capture",
204
-
205
- // Optional — defaults shown
206
- projectId: "",
207
- environment: process.env.NODE_ENV, // "development", "production", etc.
208
- enabled: true, // set false to disable capture entirely
209
-
210
- // Request capture
211
- captureRequestBody: true,
212
- captureQueryParams: true,
213
- captureHeaders: true,
214
- maxBodySize: 10000, // 10KB max body capture
215
-
216
- // Additional fields to redact (added to built-in defaults)
217
- redactFields: ["customSecret", "internalToken"],
218
-
219
- // Custom metadata included with every error
220
- metadata: { service: "api", version: "1.0.0" },
221
-
222
- // Network
223
- timeout: 5000, // 5s timeout for error reporting
224
- deduplicationWindow: 5 * 60 * 1000, // 5 min window for dedup
225
-
226
- // Debug logging (defaults to true in development)
227
- debug: false,
228
-
229
- // Custom filter — return false to skip certain errors
230
- shouldCapture: (error, request) => {
231
- if (error.message.includes("not found")) return false;
232
- return true;
233
- },
234
-
235
- // Transform errors before sending
236
- beforeSend: (capturedError) => {
237
- capturedError.metadata = { ...capturedError.metadata, custom: "value" };
238
- return capturedError; // return null to skip
239
- },
240
- });
241
- ```
242
-
243
- ### Environment Variables
244
-
245
- The SDK reads these automatically:
246
-
247
- ```bash
248
- BUGSTACK_API_KEY=your-api-key # Required
249
- BUGSTACK_ENDPOINT=https://bugstack-error-service.onrender.com/api/capture # Optional
250
- BUGSTACK_PROJECT_ID=my-project # Optional
251
- NODE_ENV=production # Optional
252
- ```
253
-
254
- ### Per-Route Options (Next.js)
255
-
256
- ```typescript
257
- export const POST = withErrorCapture(
258
- async (request) => { /* ... */ },
259
- undefined, // use existing client config
260
- {
261
- statusCode: 400,
262
- metadata: { operation: "createUser" },
263
- shouldCapture: (error) => error.name !== "ValidationError",
264
- }
265
- );
266
- ```
267
-
268
- ---
269
-
270
- ## Automatic Sanitization
271
-
272
- The SDK redacts sensitive data from headers, request bodies, and query params.
273
-
274
- **Built-in redacted fields:**
275
- `password`, `secret`, `token`, `apikey`, `api_key`, `apiKey`, `authorization`, `auth`, `credential`, `private`, `credit_card`, `creditcard`, `card_number`, `cvv`, `ssn`, `social_security`
276
-
277
- **Always-redacted headers:**
278
- `authorization`, `cookie`, `set-cookie`, `x-api-key`, `x-auth-token`, `proxy-authorization`
279
-
280
- Add custom fields via the `redactFields` config option.
281
-
282
- ---
283
-
284
- ## Error Resilience
285
-
286
- The SDK never interferes with your application:
287
-
288
- - **Network failures** — Silently retried (up to 5 times with exponential backoff)
289
- - **Timeouts** — Configurable, defaults to 5 seconds
290
- - **SDK errors** — Caught and logged in debug mode, never thrown to your app
291
- - **Original error preserved** — The wrapper re-throws the original error so your framework handles the response normally
292
-
293
- ---
294
-
295
- ## Captured Data
296
-
297
- Each error report includes:
298
-
299
- | Field | Description |
300
- |-------|-------------|
301
- | `id` | Unique error ID |
302
- | `fingerprint` | Stable hash for deduplication |
303
- | `name` | Error type (TypeError, etc.) |
304
- | `message` | Error message |
305
- | `stack` | Full stack trace |
306
- | `stackFrames` | Parsed stack frames with file, line, column |
307
- | `route` | API route path |
308
- | `method` | HTTP method |
309
- | `statusCode` | HTTP status code |
310
- | `url` | Full request URL |
311
- | `queryParams` | Sanitized query parameters |
312
- | `requestBody` | Sanitized request body |
313
- | `requestHeaders` | Sanitized headers |
314
- | `routeParams` | Dynamic route parameters |
315
- | `environment` | Environment name |
316
- | `projectId` | Project identifier |
317
- | `metadata` | Custom metadata |
318
-
319
- ---
320
-
321
- ## TypeScript
322
-
323
- All types are exported:
324
-
325
- ```typescript
326
- import type {
327
- ErrorCaptureConfig,
328
- CapturedError,
329
- StackFrame,
330
- RouteOptions,
331
- RouteContext,
332
- ErrorReportPayload,
333
- SourceContext,
334
- } from "bugstack-sdk";
335
- ```
336
-
337
- ## Compatibility
338
-
339
- - **Next.js**: 14.0.0+
340
- - **Express**: 4.x or 5.x
341
- - **Node.js**: 18.0.0+
342
- - **TypeScript**: 5.0.0+ (optional)
343
-
344
- ## License
345
-
346
- MIT
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
+ ## Other Languages
180
+
181
+ BugStack also provides SDKs for:
182
+
183
+ | Language | Package | Install |
184
+ |----------|---------|---------|
185
+ | Python | [bugstack](https://pypi.org/project/bugstack/) | `pip install bugstack` |
186
+ | Ruby | [bugstack](https://rubygems.org/gems/bugstack) | `gem install bugstack` |
187
+ | Go | [bugstack-go](https://github.com/MasonBachmann7/Bugstack-SDK-Go) | `go get github.com/MasonBachmann7/bugstack-go` |
188
+
189
+ ---
190
+
191
+ ## Configuration
192
+
193
+ ### Full Options
194
+
195
+ ```typescript
196
+ import { ErrorCaptureClient } from "bugstack-sdk";
197
+
198
+ ErrorCaptureClient.init({
199
+ // Required
200
+ apiKey: "your-api-key",
201
+
202
+ // Endpoint (defaults to localhost for local dev)
203
+ endpoint: "https://bugstack-error-service.onrender.com/api/capture",
204
+
205
+ // Optional — defaults shown
206
+ projectId: "",
207
+ environment: process.env.NODE_ENV, // "development", "production", etc.
208
+ enabled: true, // set false to disable capture entirely
209
+
210
+ // Request capture
211
+ captureRequestBody: true,
212
+ captureQueryParams: true,
213
+ captureHeaders: true,
214
+ maxBodySize: 10000, // 10KB max body capture
215
+
216
+ // Additional fields to redact (added to built-in defaults)
217
+ redactFields: ["customSecret", "internalToken"],
218
+
219
+ // Custom metadata included with every error
220
+ metadata: { service: "api", version: "1.0.0" },
221
+
222
+ // Network
223
+ timeout: 5000, // 5s timeout for error reporting
224
+ deduplicationWindow: 5 * 60 * 1000, // 5 min window for dedup
225
+
226
+ // Debug logging (defaults to true in development)
227
+ debug: false,
228
+
229
+ // Custom filter — return false to skip certain errors
230
+ shouldCapture: (error, request) => {
231
+ if (error.message.includes("not found")) return false;
232
+ return true;
233
+ },
234
+
235
+ // Transform errors before sending
236
+ beforeSend: (capturedError) => {
237
+ capturedError.metadata = { ...capturedError.metadata, custom: "value" };
238
+ return capturedError; // return null to skip
239
+ },
240
+ });
241
+ ```
242
+
243
+ ### Environment Variables
244
+
245
+ The SDK reads these automatically:
246
+
247
+ ```bash
248
+ BUGSTACK_API_KEY=your-api-key # Required
249
+ BUGSTACK_ENDPOINT=https://bugstack-error-service.onrender.com/api/capture # Optional
250
+ BUGSTACK_PROJECT_ID=my-project # Optional
251
+ NODE_ENV=production # Optional
252
+ ```
253
+
254
+ ### Per-Route Options (Next.js)
255
+
256
+ ```typescript
257
+ export const POST = withErrorCapture(
258
+ async (request) => { /* ... */ },
259
+ undefined, // use existing client config
260
+ {
261
+ statusCode: 400,
262
+ metadata: { operation: "createUser" },
263
+ shouldCapture: (error) => error.name !== "ValidationError",
264
+ }
265
+ );
266
+ ```
267
+
268
+ ---
269
+
270
+ ## Automatic Sanitization
271
+
272
+ The SDK redacts sensitive data from headers, request bodies, and query params.
273
+
274
+ **Built-in redacted fields:**
275
+ `password`, `secret`, `token`, `apikey`, `api_key`, `apiKey`, `authorization`, `auth`, `credential`, `private`, `credit_card`, `creditcard`, `card_number`, `cvv`, `ssn`, `social_security`
276
+
277
+ **Always-redacted headers:**
278
+ `authorization`, `cookie`, `set-cookie`, `x-api-key`, `x-auth-token`, `proxy-authorization`
279
+
280
+ Add custom fields via the `redactFields` config option.
281
+
282
+ ---
283
+
284
+ ## Error Resilience
285
+
286
+ The SDK never interferes with your application:
287
+
288
+ - **Network failures** — Silently retried (up to 5 times with exponential backoff)
289
+ - **Timeouts** — Configurable, defaults to 5 seconds
290
+ - **SDK errors** — Caught and logged in debug mode, never thrown to your app
291
+ - **Original error preserved** — The wrapper re-throws the original error so your framework handles the response normally
292
+
293
+ ---
294
+
295
+ ## Captured Data
296
+
297
+ Each error report includes:
298
+
299
+ | Field | Description |
300
+ |-------|-------------|
301
+ | `id` | Unique error ID |
302
+ | `fingerprint` | Stable hash for deduplication |
303
+ | `name` | Error type (TypeError, etc.) |
304
+ | `message` | Error message |
305
+ | `stack` | Full stack trace |
306
+ | `stackFrames` | Parsed stack frames with file, line, column |
307
+ | `route` | API route path |
308
+ | `method` | HTTP method |
309
+ | `statusCode` | HTTP status code |
310
+ | `url` | Full request URL |
311
+ | `queryParams` | Sanitized query parameters |
312
+ | `requestBody` | Sanitized request body |
313
+ | `requestHeaders` | Sanitized headers |
314
+ | `routeParams` | Dynamic route parameters |
315
+ | `environment` | Environment name |
316
+ | `projectId` | Project identifier |
317
+ | `metadata` | Custom metadata |
318
+
319
+ ---
320
+
321
+ ## TypeScript
322
+
323
+ All types are exported:
324
+
325
+ ```typescript
326
+ import type {
327
+ ErrorCaptureConfig,
328
+ CapturedError,
329
+ StackFrame,
330
+ RouteOptions,
331
+ RouteContext,
332
+ ErrorReportPayload,
333
+ SourceContext,
334
+ } from "bugstack-sdk";
335
+ ```
336
+
337
+ ## Compatibility
338
+
339
+ - **Next.js**: 14.0.0+
340
+ - **Express**: 4.x or 5.x
341
+ - **Node.js**: 18.0.0+
342
+ - **TypeScript**: 5.0.0+ (optional)
343
+
344
+ ## License
345
+
346
+ MIT