bugstack-sdk 1.0.0 → 2.0.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.
@@ -0,0 +1,622 @@
1
+ import { NextRequest } from 'next/server';
2
+
3
+ /**
4
+ * Configuration options for the BugStack error capture SDK
5
+ */
6
+ interface ErrorCaptureConfig {
7
+ /**
8
+ * API key for authenticating with the BugStack error service
9
+ */
10
+ apiKey: string;
11
+ /**
12
+ * URL of the BugStack error service endpoint
13
+ * @default process.env.BUGSTACK_ENDPOINT || "http://localhost:3001/api/capture"
14
+ */
15
+ endpoint?: string;
16
+ /**
17
+ * Unique identifier for your project
18
+ */
19
+ projectId?: string;
20
+ /**
21
+ * Environment name (e.g., "production", "staging", "development")
22
+ * @default process.env.NODE_ENV || "development"
23
+ */
24
+ environment?: string;
25
+ /**
26
+ * Enable autonomous error fixing
27
+ * When true, BugStack will automatically fix errors and deploy fixes
28
+ * When false, BugStack will only create PRs for manual review
29
+ * @default false
30
+ */
31
+ autoFix?: boolean;
32
+ /**
33
+ * Enable or disable error capture
34
+ * Useful for disabling in certain environments
35
+ * @default true
36
+ */
37
+ enabled?: boolean;
38
+ /**
39
+ * Whether to capture request body in error reports
40
+ * @default true
41
+ */
42
+ captureRequestBody?: boolean;
43
+ /**
44
+ * Whether to capture query parameters in error reports
45
+ * @default true
46
+ */
47
+ captureQueryParams?: boolean;
48
+ /**
49
+ * Whether to capture request headers in error reports
50
+ * @default true
51
+ */
52
+ captureHeaders?: boolean;
53
+ /**
54
+ * Maximum size of request body to capture (in bytes)
55
+ * Bodies larger than this will be truncated
56
+ * @default 10000 (10KB)
57
+ */
58
+ maxBodySize?: number;
59
+ /**
60
+ * Additional fields to redact from request body and headers
61
+ * Common sensitive fields are redacted by default
62
+ */
63
+ redactFields?: string[];
64
+ /**
65
+ * Custom metadata to include with every error report
66
+ */
67
+ metadata?: Record<string, unknown>;
68
+ /**
69
+ * Timeout for sending error reports (in milliseconds)
70
+ * @default 5000
71
+ */
72
+ timeout?: number;
73
+ /**
74
+ * Time window for client-side deduplication (in milliseconds)
75
+ * If the same error (by fingerprint) is captured within this window,
76
+ * it won't be sent again to avoid flooding the service
77
+ * @default 300000 (5 minutes)
78
+ */
79
+ deduplicationWindow?: number;
80
+ /**
81
+ * Whether to log SDK errors to console
82
+ * @default true in development, false in production
83
+ */
84
+ debug?: boolean;
85
+ /**
86
+ * Custom error filter function
87
+ * Return false to skip reporting certain errors
88
+ */
89
+ shouldCapture?: (error: Error, request: NextRequest) => boolean;
90
+ /**
91
+ * Hook called before sending error report
92
+ * Can be used to modify or enrich error data
93
+ */
94
+ beforeSend?: (error: CapturedError) => CapturedError | null;
95
+ }
96
+ /**
97
+ * Resolved configuration with all defaults applied
98
+ */
99
+ interface ResolvedConfig {
100
+ apiKey: string;
101
+ endpoint: string;
102
+ projectId: string;
103
+ environment: string;
104
+ autoFix: boolean;
105
+ enabled: boolean;
106
+ captureRequestBody: boolean;
107
+ captureQueryParams: boolean;
108
+ captureHeaders: boolean;
109
+ maxBodySize: number;
110
+ redactFields: string[];
111
+ metadata: Record<string, unknown>;
112
+ timeout: number;
113
+ deduplicationWindow: number;
114
+ debug: boolean;
115
+ shouldCapture?: (error: Error, request: NextRequest) => boolean;
116
+ beforeSend?: (error: CapturedError) => CapturedError | null;
117
+ }
118
+ /**
119
+ * Captured error data sent to the error service
120
+ */
121
+ interface CapturedError {
122
+ /**
123
+ * Unique identifier for this error instance
124
+ */
125
+ id: string;
126
+ /**
127
+ * Error fingerprint for deduplication
128
+ * Stable hash based on error type, route, and stack trace
129
+ */
130
+ fingerprint?: string;
131
+ /**
132
+ * Error message
133
+ */
134
+ message: string;
135
+ /**
136
+ * Error name/type (e.g., "TypeError", "ReferenceError")
137
+ */
138
+ name: string;
139
+ /**
140
+ * Full stack trace
141
+ */
142
+ stack?: string;
143
+ /**
144
+ * Parsed stack frames for easier analysis
145
+ */
146
+ stackFrames?: StackFrame[];
147
+ /**
148
+ * ISO 8601 timestamp when the error occurred
149
+ */
150
+ timestamp: string;
151
+ /**
152
+ * API route path (e.g., "/api/users/[id]")
153
+ */
154
+ route: string;
155
+ /**
156
+ * HTTP method (GET, POST, etc.)
157
+ */
158
+ method: string;
159
+ /**
160
+ * HTTP status code
161
+ * @default 500
162
+ */
163
+ statusCode: number;
164
+ /**
165
+ * Full request URL
166
+ */
167
+ url: string;
168
+ /**
169
+ * Query parameters (sanitized)
170
+ */
171
+ queryParams?: Record<string, string>;
172
+ /**
173
+ * Request body (sanitized and truncated)
174
+ */
175
+ requestBody?: unknown;
176
+ /**
177
+ * Request headers (sanitized)
178
+ */
179
+ requestHeaders?: Record<string, string>;
180
+ /**
181
+ * Environment (production, staging, development)
182
+ */
183
+ environment: string;
184
+ /**
185
+ * Project identifier
186
+ */
187
+ projectId?: string;
188
+ /**
189
+ * Route parameters (e.g., { id: "123" })
190
+ */
191
+ routeParams?: Record<string, string>;
192
+ /**
193
+ * Additional custom metadata
194
+ */
195
+ metadata?: Record<string, unknown>;
196
+ /**
197
+ * SDK version that captured this error
198
+ */
199
+ sdkVersion: string;
200
+ /**
201
+ * Node.js version
202
+ */
203
+ nodeVersion: string;
204
+ /**
205
+ * Next.js version (if available)
206
+ */
207
+ nextVersion?: string;
208
+ }
209
+ /**
210
+ * Parsed stack frame for easier debugging
211
+ */
212
+ interface StackFrame {
213
+ /**
214
+ * Function name
215
+ */
216
+ function?: string;
217
+ /**
218
+ * File path
219
+ */
220
+ file?: string;
221
+ /**
222
+ * Line number
223
+ */
224
+ line?: number;
225
+ /**
226
+ * Column number
227
+ */
228
+ column?: number;
229
+ /**
230
+ * Whether this frame is from node_modules
231
+ */
232
+ isNodeModule?: boolean;
233
+ /**
234
+ * Whether this frame is from internal Node.js code
235
+ */
236
+ isInternal?: boolean;
237
+ }
238
+ /**
239
+ * Payload sent to the error service
240
+ */
241
+ interface ErrorReportPayload {
242
+ /**
243
+ * The captured error data
244
+ */
245
+ error: CapturedError;
246
+ /**
247
+ * Source code context around the error (if available)
248
+ */
249
+ sourceContext?: SourceContext;
250
+ }
251
+ /**
252
+ * Source code context around the error location
253
+ */
254
+ interface SourceContext {
255
+ /**
256
+ * File path
257
+ */
258
+ filePath: string;
259
+ /**
260
+ * Line number where error occurred
261
+ */
262
+ lineNumber: number;
263
+ /**
264
+ * Lines of code before the error line
265
+ */
266
+ preContext: string[];
267
+ /**
268
+ * The line where the error occurred
269
+ */
270
+ contextLine: string;
271
+ /**
272
+ * Lines of code after the error line
273
+ */
274
+ postContext: string[];
275
+ }
276
+ /**
277
+ * Next.js App Router route handler type
278
+ */
279
+ type NextRouteHandler<T = unknown> = (request: NextRequest, context: RouteContext<T>) => Response | Promise<Response>;
280
+ /**
281
+ * Route context passed to Next.js handlers
282
+ */
283
+ interface RouteContext<T = unknown> {
284
+ params: T extends Record<string, string> ? T : Record<string, string>;
285
+ }
286
+ /**
287
+ * Options that can be passed to withErrorCapture per-route
288
+ */
289
+ interface RouteOptions {
290
+ /**
291
+ * Override the status code reported for errors in this route
292
+ */
293
+ statusCode?: number;
294
+ /**
295
+ * Additional metadata specific to this route
296
+ */
297
+ metadata?: Record<string, unknown>;
298
+ /**
299
+ * Custom error filter for this route
300
+ */
301
+ shouldCapture?: (error: Error) => boolean;
302
+ }
303
+ type BugStackConfig = ErrorCaptureConfig;
304
+
305
+ /**
306
+ * Client-side error deduplicator
307
+ *
308
+ * Prevents the same error (identified by fingerprint) from being sent
309
+ * multiple times within a configurable time window. This helps avoid
310
+ * flooding the BugStack service with duplicate errors.
311
+ */
312
+ declare class ErrorDeduplicator {
313
+ /**
314
+ * Cache of fingerprint → timestamp mapping
315
+ * Key: error fingerprint (hex string)
316
+ * Value: timestamp (ms) when error was last sent
317
+ */
318
+ private cache;
319
+ /**
320
+ * Time window in milliseconds
321
+ * Errors with the same fingerprint within this window are considered duplicates
322
+ */
323
+ private window;
324
+ /**
325
+ * Interval ID for cleanup task
326
+ */
327
+ private cleanupIntervalId?;
328
+ /**
329
+ * Create a new deduplicator
330
+ *
331
+ * @param window - Deduplication window in milliseconds (default: 5 minutes)
332
+ */
333
+ constructor(window?: number);
334
+ /**
335
+ * Check if an error should be sent
336
+ *
337
+ * @param fingerprint - Error fingerprint
338
+ * @returns true if error should be sent, false if it's a duplicate
339
+ */
340
+ shouldSend(fingerprint: string): boolean;
341
+ /**
342
+ * Mark an error as sent (manually)
343
+ *
344
+ * This can be used to pre-populate the cache or update the timestamp
345
+ * after a successful send.
346
+ *
347
+ * @param fingerprint - Error fingerprint
348
+ */
349
+ markSent(fingerprint: string): void;
350
+ /**
351
+ * Check if an error fingerprint is in the cache
352
+ *
353
+ * @param fingerprint - Error fingerprint
354
+ * @returns true if fingerprint exists and is within the window
355
+ */
356
+ has(fingerprint: string): boolean;
357
+ /**
358
+ * Get the number of entries in the cache
359
+ */
360
+ get size(): number;
361
+ /**
362
+ * Clear all entries from the cache
363
+ */
364
+ clear(): void;
365
+ /**
366
+ * Remove expired entries from the cache
367
+ *
368
+ * This is called automatically every minute, but can also be
369
+ * called manually to free up memory.
370
+ */
371
+ cleanup(): void;
372
+ /**
373
+ * Start automatic cleanup task
374
+ *
375
+ * Runs cleanup every minute to remove expired entries
376
+ */
377
+ private startCleanup;
378
+ /**
379
+ * Stop automatic cleanup task
380
+ *
381
+ * This should be called when shutting down to prevent memory leaks
382
+ */
383
+ destroy(): void;
384
+ /**
385
+ * Get cache statistics (for debugging)
386
+ */
387
+ getStats(): {
388
+ size: number;
389
+ window: number;
390
+ entries: Array<{
391
+ fingerprint: string;
392
+ age: number;
393
+ }>;
394
+ };
395
+ }
396
+
397
+ /**
398
+ * Function that sends an error to the service
399
+ */
400
+ type SendFunction = (error: CapturedError, sourceContext?: SourceContext) => Promise<boolean>;
401
+ /**
402
+ * Retry queue with exponential backoff
403
+ *
404
+ * Handles failed error reports by queuing them and retrying with
405
+ * exponentially increasing delays. Never blocks the host application.
406
+ */
407
+ declare class RetryQueue {
408
+ /**
409
+ * Queue of errors waiting to be sent
410
+ */
411
+ private queue;
412
+ /**
413
+ * Whether the queue is currently processing
414
+ */
415
+ private processing;
416
+ /**
417
+ * Maximum number of retry attempts
418
+ */
419
+ private maxRetries;
420
+ /**
421
+ * Base backoff delay in milliseconds
422
+ */
423
+ private baseDelay;
424
+ /**
425
+ * Maximum backoff delay in milliseconds
426
+ */
427
+ private maxDelay;
428
+ /**
429
+ * Function to send errors
430
+ */
431
+ private sendFn;
432
+ /**
433
+ * Debug mode
434
+ */
435
+ private debug;
436
+ /**
437
+ * Processing interval ID
438
+ */
439
+ private intervalId?;
440
+ /**
441
+ * Create a new retry queue
442
+ *
443
+ * @param sendFn - Function to send errors
444
+ * @param options - Configuration options
445
+ */
446
+ constructor(sendFn: SendFunction, options?: {
447
+ maxRetries?: number;
448
+ baseDelay?: number;
449
+ maxDelay?: number;
450
+ debug?: boolean;
451
+ });
452
+ /**
453
+ * Enqueue an error for sending
454
+ *
455
+ * This is non-blocking and returns immediately.
456
+ *
457
+ * @param error - The error to send
458
+ * @param sourceContext - Source context (optional)
459
+ */
460
+ enqueue(error: CapturedError, sourceContext?: SourceContext): void;
461
+ /**
462
+ * Get the current queue size
463
+ */
464
+ get size(): number;
465
+ /**
466
+ * Clear all items from the queue
467
+ */
468
+ clear(): void;
469
+ /**
470
+ * Destroy the queue and stop processing
471
+ */
472
+ destroy(): void;
473
+ /**
474
+ * Start periodic queue processing
475
+ */
476
+ private startProcessing;
477
+ /**
478
+ * Process the queue
479
+ *
480
+ * This is called periodically and also immediately after enqueue.
481
+ * Non-blocking - errors are caught and logged.
482
+ */
483
+ private processQueue;
484
+ /**
485
+ * Process a single queued error
486
+ *
487
+ * @param item - The queued error item
488
+ */
489
+ private processItem;
490
+ /**
491
+ * Handle a failed send attempt
492
+ *
493
+ * @param item - The queued error item
494
+ */
495
+ private handleFailure;
496
+ /**
497
+ * Calculate exponential backoff delay
498
+ *
499
+ * Backoff formula: min(baseDelay * 2^(attempts - 1), maxDelay)
500
+ * - Attempt 1: 1s
501
+ * - Attempt 2: 2s
502
+ * - Attempt 3: 4s
503
+ * - Attempt 4: 8s
504
+ * - Attempt 5: 16s
505
+ *
506
+ * @param attempts - Number of attempts
507
+ * @returns Delay in milliseconds
508
+ */
509
+ private calculateBackoff;
510
+ /**
511
+ * Remove an item from the queue
512
+ *
513
+ * @param item - The item to remove
514
+ */
515
+ private removeFromQueue;
516
+ /**
517
+ * Log a message (if debug mode is enabled)
518
+ *
519
+ * @param message - Message to log
520
+ */
521
+ private log;
522
+ /**
523
+ * Log an error (if debug mode is enabled)
524
+ *
525
+ * @param message - Message to log
526
+ * @param error - Error object (optional)
527
+ */
528
+ private logError;
529
+ /**
530
+ * Get queue statistics (for debugging)
531
+ */
532
+ getStats(): {
533
+ size: number;
534
+ processing: boolean;
535
+ items: Array<{
536
+ errorId: string;
537
+ attempts: number;
538
+ nextRetry: number;
539
+ timeUntilRetry: number;
540
+ }>;
541
+ };
542
+ }
543
+
544
+ /**
545
+ * BugStack Error Capture Client
546
+ *
547
+ * Singleton client for capturing and reporting errors to the BugStack service.
548
+ * Now includes client-side deduplication and retry queue with exponential backoff.
549
+ */
550
+ declare class ErrorCaptureClient {
551
+ private config;
552
+ private static instance;
553
+ private deduplicator;
554
+ private retryQueue;
555
+ constructor(config: ErrorCaptureConfig);
556
+ /**
557
+ * Initialize the singleton client instance
558
+ */
559
+ static init(config: ErrorCaptureConfig): ErrorCaptureClient;
560
+ /**
561
+ * Get the singleton client instance
562
+ */
563
+ static getInstance(): ErrorCaptureClient | null;
564
+ /**
565
+ * Check if the client has been initialized
566
+ */
567
+ static isInitialized(): boolean;
568
+ /**
569
+ * Reset the client (mainly for testing)
570
+ */
571
+ static reset(): void;
572
+ /**
573
+ * Report an error to the BugStack service
574
+ *
575
+ * This method includes deduplication and queuing for resilience.
576
+ *
577
+ * @param error - The captured error
578
+ * @param sourceContext - Source code context (optional)
579
+ * @returns Promise that resolves to true if error was accepted (not deduplicated)
580
+ */
581
+ reportError(error: CapturedError, sourceContext?: SourceContext): Promise<boolean>;
582
+ /**
583
+ * Send an error to the service (internal method)
584
+ *
585
+ * This is used by the retry queue. Returns true on success, false on failure.
586
+ *
587
+ * @param error - The error to send
588
+ * @param sourceContext - Source context (optional)
589
+ * @returns Promise that resolves to true on success
590
+ */
591
+ private sendErrorToService;
592
+ /**
593
+ * Get the resolved configuration
594
+ */
595
+ getConfig(): ResolvedConfig;
596
+ /**
597
+ * Check if a field should be redacted
598
+ */
599
+ shouldRedact(fieldName: string): boolean;
600
+ /**
601
+ * Get the SDK version
602
+ */
603
+ static getVersion(): string;
604
+ /**
605
+ * Get client statistics (for debugging)
606
+ */
607
+ getStats(): {
608
+ deduplicator: ReturnType<ErrorDeduplicator["getStats"]>;
609
+ retryQueue: ReturnType<RetryQueue["getStats"]>;
610
+ };
611
+ /**
612
+ * Clean up resources
613
+ *
614
+ * Should be called when shutting down to prevent memory leaks
615
+ */
616
+ destroy(): void;
617
+ private log;
618
+ private logError;
619
+ }
620
+ declare const BugStackClient: typeof ErrorCaptureClient;
621
+
622
+ export { BugStackClient as B, type CapturedError as C, ErrorCaptureClient as E, type NextRouteHandler as N, type ResolvedConfig as R, type StackFrame as S, type BugStackConfig as a, type ErrorCaptureConfig as b, ErrorDeduplicator as c, type ErrorReportPayload as d, RetryQueue as e, type RouteContext as f, type RouteOptions as g, type SourceContext as h };