bugstack-sdk 1.0.0 → 2.0.1
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 +212 -183
- package/dist/adapters/express/index.d.mts +80 -0
- package/dist/adapters/express/index.d.ts +80 -0
- package/dist/adapters/express/index.js +887 -0
- package/dist/adapters/express/index.js.map +1 -0
- package/dist/adapters/express/index.mjs +881 -0
- package/dist/adapters/express/index.mjs.map +1 -0
- package/dist/adapters/generic/index.d.mts +127 -0
- package/dist/adapters/generic/index.d.ts +127 -0
- package/dist/adapters/generic/index.js +833 -0
- package/dist/adapters/generic/index.js.map +1 -0
- package/dist/adapters/generic/index.mjs +824 -0
- package/dist/adapters/generic/index.mjs.map +1 -0
- package/dist/adapters/nextjs/index.d.mts +50 -0
- package/dist/adapters/nextjs/index.d.ts +50 -0
- package/dist/adapters/nextjs/index.js +1003 -0
- package/dist/adapters/nextjs/index.js.map +1 -0
- package/dist/adapters/nextjs/index.mjs +998 -0
- package/dist/adapters/nextjs/index.mjs.map +1 -0
- package/dist/client-9EMqVMOl.d.mts +622 -0
- package/dist/client-9EMqVMOl.d.ts +622 -0
- package/dist/index.d.mts +44 -360
- package/dist/index.d.ts +44 -360
- package/dist/index.js +535 -150
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +529 -149
- package/dist/index.mjs.map +1 -1
- package/package.json +90 -71
|
@@ -0,0 +1,833 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/core/fingerprint.ts
|
|
4
|
+
function generateErrorFingerprint(error) {
|
|
5
|
+
const errorType = error.name || "Error";
|
|
6
|
+
const route = error.route || "unknown";
|
|
7
|
+
const stackFirstLine = getStackFirstLine(error.stack);
|
|
8
|
+
const key = `${errorType}:${route}:${stackFirstLine}`;
|
|
9
|
+
return simpleHash(key);
|
|
10
|
+
}
|
|
11
|
+
function getStackFirstLine(stack) {
|
|
12
|
+
if (!stack) return "unknown";
|
|
13
|
+
const lines = stack.split("\n");
|
|
14
|
+
for (const line of lines) {
|
|
15
|
+
const trimmed = line.trim();
|
|
16
|
+
if (trimmed.startsWith("at ")) {
|
|
17
|
+
return trimmed;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
for (const line of lines) {
|
|
21
|
+
const trimmed = line.trim();
|
|
22
|
+
if (trimmed) {
|
|
23
|
+
return trimmed;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return "unknown";
|
|
27
|
+
}
|
|
28
|
+
function simpleHash(str) {
|
|
29
|
+
let hash = 5381;
|
|
30
|
+
for (let i = 0; i < str.length; i++) {
|
|
31
|
+
hash = (hash << 5) + hash + str.charCodeAt(i);
|
|
32
|
+
hash = hash & hash;
|
|
33
|
+
}
|
|
34
|
+
const unsignedHash = hash >>> 0;
|
|
35
|
+
return unsignedHash.toString(16).padStart(8, "0");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// src/core/deduplicator.ts
|
|
39
|
+
var ErrorDeduplicator = class {
|
|
40
|
+
/**
|
|
41
|
+
* Cache of fingerprint → timestamp mapping
|
|
42
|
+
* Key: error fingerprint (hex string)
|
|
43
|
+
* Value: timestamp (ms) when error was last sent
|
|
44
|
+
*/
|
|
45
|
+
cache;
|
|
46
|
+
/**
|
|
47
|
+
* Time window in milliseconds
|
|
48
|
+
* Errors with the same fingerprint within this window are considered duplicates
|
|
49
|
+
*/
|
|
50
|
+
window;
|
|
51
|
+
/**
|
|
52
|
+
* Interval ID for cleanup task
|
|
53
|
+
*/
|
|
54
|
+
cleanupIntervalId;
|
|
55
|
+
/**
|
|
56
|
+
* Create a new deduplicator
|
|
57
|
+
*
|
|
58
|
+
* @param window - Deduplication window in milliseconds (default: 5 minutes)
|
|
59
|
+
*/
|
|
60
|
+
constructor(window = 5 * 60 * 1e3) {
|
|
61
|
+
this.cache = /* @__PURE__ */ new Map();
|
|
62
|
+
this.window = window;
|
|
63
|
+
this.startCleanup();
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Check if an error should be sent
|
|
67
|
+
*
|
|
68
|
+
* @param fingerprint - Error fingerprint
|
|
69
|
+
* @returns true if error should be sent, false if it's a duplicate
|
|
70
|
+
*/
|
|
71
|
+
shouldSend(fingerprint) {
|
|
72
|
+
const now = Date.now();
|
|
73
|
+
const lastSent = this.cache.get(fingerprint);
|
|
74
|
+
if (lastSent !== void 0) {
|
|
75
|
+
const elapsed = now - lastSent;
|
|
76
|
+
if (elapsed < this.window) {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
this.cache.set(fingerprint, now);
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Mark an error as sent (manually)
|
|
85
|
+
*
|
|
86
|
+
* This can be used to pre-populate the cache or update the timestamp
|
|
87
|
+
* after a successful send.
|
|
88
|
+
*
|
|
89
|
+
* @param fingerprint - Error fingerprint
|
|
90
|
+
*/
|
|
91
|
+
markSent(fingerprint) {
|
|
92
|
+
this.cache.set(fingerprint, Date.now());
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Check if an error fingerprint is in the cache
|
|
96
|
+
*
|
|
97
|
+
* @param fingerprint - Error fingerprint
|
|
98
|
+
* @returns true if fingerprint exists and is within the window
|
|
99
|
+
*/
|
|
100
|
+
has(fingerprint) {
|
|
101
|
+
const lastSent = this.cache.get(fingerprint);
|
|
102
|
+
if (lastSent === void 0) {
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
const elapsed = Date.now() - lastSent;
|
|
106
|
+
return elapsed < this.window;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Get the number of entries in the cache
|
|
110
|
+
*/
|
|
111
|
+
get size() {
|
|
112
|
+
return this.cache.size;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Clear all entries from the cache
|
|
116
|
+
*/
|
|
117
|
+
clear() {
|
|
118
|
+
this.cache.clear();
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Remove expired entries from the cache
|
|
122
|
+
*
|
|
123
|
+
* This is called automatically every minute, but can also be
|
|
124
|
+
* called manually to free up memory.
|
|
125
|
+
*/
|
|
126
|
+
cleanup() {
|
|
127
|
+
const now = Date.now();
|
|
128
|
+
const toDelete = [];
|
|
129
|
+
for (const [fingerprint, timestamp] of this.cache.entries()) {
|
|
130
|
+
const elapsed = now - timestamp;
|
|
131
|
+
if (elapsed >= this.window) {
|
|
132
|
+
toDelete.push(fingerprint);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
for (const fingerprint of toDelete) {
|
|
136
|
+
this.cache.delete(fingerprint);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Start automatic cleanup task
|
|
141
|
+
*
|
|
142
|
+
* Runs cleanup every minute to remove expired entries
|
|
143
|
+
*/
|
|
144
|
+
startCleanup() {
|
|
145
|
+
this.cleanupIntervalId = setInterval(() => {
|
|
146
|
+
this.cleanup();
|
|
147
|
+
}, 60 * 1e3);
|
|
148
|
+
if (this.cleanupIntervalId.unref) {
|
|
149
|
+
this.cleanupIntervalId.unref();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Stop automatic cleanup task
|
|
154
|
+
*
|
|
155
|
+
* This should be called when shutting down to prevent memory leaks
|
|
156
|
+
*/
|
|
157
|
+
destroy() {
|
|
158
|
+
if (this.cleanupIntervalId) {
|
|
159
|
+
clearInterval(this.cleanupIntervalId);
|
|
160
|
+
this.cleanupIntervalId = void 0;
|
|
161
|
+
}
|
|
162
|
+
this.cache.clear();
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Get cache statistics (for debugging)
|
|
166
|
+
*/
|
|
167
|
+
getStats() {
|
|
168
|
+
const now = Date.now();
|
|
169
|
+
const entries = Array.from(this.cache.entries()).map(([fingerprint, timestamp]) => ({
|
|
170
|
+
fingerprint,
|
|
171
|
+
age: now - timestamp
|
|
172
|
+
}));
|
|
173
|
+
return {
|
|
174
|
+
size: this.cache.size,
|
|
175
|
+
window: this.window,
|
|
176
|
+
entries
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
// src/core/queue.ts
|
|
182
|
+
var RetryQueue = class {
|
|
183
|
+
/**
|
|
184
|
+
* Queue of errors waiting to be sent
|
|
185
|
+
*/
|
|
186
|
+
queue = [];
|
|
187
|
+
/**
|
|
188
|
+
* Whether the queue is currently processing
|
|
189
|
+
*/
|
|
190
|
+
processing = false;
|
|
191
|
+
/**
|
|
192
|
+
* Maximum number of retry attempts
|
|
193
|
+
*/
|
|
194
|
+
maxRetries = 5;
|
|
195
|
+
/**
|
|
196
|
+
* Base backoff delay in milliseconds
|
|
197
|
+
*/
|
|
198
|
+
baseDelay = 1e3;
|
|
199
|
+
// 1 second
|
|
200
|
+
/**
|
|
201
|
+
* Maximum backoff delay in milliseconds
|
|
202
|
+
*/
|
|
203
|
+
maxDelay = 16e3;
|
|
204
|
+
// 16 seconds
|
|
205
|
+
/**
|
|
206
|
+
* Function to send errors
|
|
207
|
+
*/
|
|
208
|
+
sendFn;
|
|
209
|
+
/**
|
|
210
|
+
* Debug mode
|
|
211
|
+
*/
|
|
212
|
+
debug;
|
|
213
|
+
/**
|
|
214
|
+
* Processing interval ID
|
|
215
|
+
*/
|
|
216
|
+
intervalId;
|
|
217
|
+
/**
|
|
218
|
+
* Create a new retry queue
|
|
219
|
+
*
|
|
220
|
+
* @param sendFn - Function to send errors
|
|
221
|
+
* @param options - Configuration options
|
|
222
|
+
*/
|
|
223
|
+
constructor(sendFn, options) {
|
|
224
|
+
this.sendFn = sendFn;
|
|
225
|
+
this.maxRetries = options?.maxRetries ?? 5;
|
|
226
|
+
this.baseDelay = options?.baseDelay ?? 1e3;
|
|
227
|
+
this.maxDelay = options?.maxDelay ?? 16e3;
|
|
228
|
+
this.debug = options?.debug ?? false;
|
|
229
|
+
this.startProcessing();
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Enqueue an error for sending
|
|
233
|
+
*
|
|
234
|
+
* This is non-blocking and returns immediately.
|
|
235
|
+
*
|
|
236
|
+
* @param error - The error to send
|
|
237
|
+
* @param sourceContext - Source context (optional)
|
|
238
|
+
*/
|
|
239
|
+
enqueue(error, sourceContext) {
|
|
240
|
+
const queuedError = {
|
|
241
|
+
error,
|
|
242
|
+
sourceContext,
|
|
243
|
+
attempts: 0,
|
|
244
|
+
nextRetry: Date.now()
|
|
245
|
+
// Send immediately on first attempt
|
|
246
|
+
};
|
|
247
|
+
this.queue.push(queuedError);
|
|
248
|
+
this.log(`Enqueued error: ${error.id} (queue size: ${this.queue.length})`);
|
|
249
|
+
this.processQueue();
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Get the current queue size
|
|
253
|
+
*/
|
|
254
|
+
get size() {
|
|
255
|
+
return this.queue.length;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Clear all items from the queue
|
|
259
|
+
*/
|
|
260
|
+
clear() {
|
|
261
|
+
this.queue = [];
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Destroy the queue and stop processing
|
|
265
|
+
*/
|
|
266
|
+
destroy() {
|
|
267
|
+
if (this.intervalId) {
|
|
268
|
+
clearInterval(this.intervalId);
|
|
269
|
+
this.intervalId = void 0;
|
|
270
|
+
}
|
|
271
|
+
this.queue = [];
|
|
272
|
+
this.processing = false;
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Start periodic queue processing
|
|
276
|
+
*/
|
|
277
|
+
startProcessing() {
|
|
278
|
+
this.intervalId = setInterval(() => {
|
|
279
|
+
this.processQueue();
|
|
280
|
+
}, 500);
|
|
281
|
+
if (this.intervalId.unref) {
|
|
282
|
+
this.intervalId.unref();
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Process the queue
|
|
287
|
+
*
|
|
288
|
+
* This is called periodically and also immediately after enqueue.
|
|
289
|
+
* Non-blocking - errors are caught and logged.
|
|
290
|
+
*/
|
|
291
|
+
async processQueue() {
|
|
292
|
+
if (this.processing || this.queue.length === 0) {
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
this.processing = true;
|
|
296
|
+
try {
|
|
297
|
+
const now = Date.now();
|
|
298
|
+
const readyErrors = this.queue.filter((item) => item.nextRetry <= now);
|
|
299
|
+
if (readyErrors.length === 0) {
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
this.log(`Processing ${readyErrors.length} ready errors`);
|
|
303
|
+
for (const item of readyErrors) {
|
|
304
|
+
await this.processItem(item);
|
|
305
|
+
}
|
|
306
|
+
} catch (err) {
|
|
307
|
+
this.logError("Queue processing error:", err);
|
|
308
|
+
} finally {
|
|
309
|
+
this.processing = false;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Process a single queued error
|
|
314
|
+
*
|
|
315
|
+
* @param item - The queued error item
|
|
316
|
+
*/
|
|
317
|
+
async processItem(item) {
|
|
318
|
+
try {
|
|
319
|
+
item.attempts++;
|
|
320
|
+
item.lastAttempt = Date.now();
|
|
321
|
+
this.log(
|
|
322
|
+
`Sending error ${item.error.id} (attempt ${item.attempts}/${this.maxRetries})`
|
|
323
|
+
);
|
|
324
|
+
const success = await this.sendFn(item.error, item.sourceContext);
|
|
325
|
+
if (success) {
|
|
326
|
+
this.log(`Successfully sent error: ${item.error.id}`);
|
|
327
|
+
this.removeFromQueue(item);
|
|
328
|
+
} else {
|
|
329
|
+
this.handleFailure(item);
|
|
330
|
+
}
|
|
331
|
+
} catch (err) {
|
|
332
|
+
this.logError(`Error sending ${item.error.id}:`, err);
|
|
333
|
+
this.handleFailure(item);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Handle a failed send attempt
|
|
338
|
+
*
|
|
339
|
+
* @param item - The queued error item
|
|
340
|
+
*/
|
|
341
|
+
handleFailure(item) {
|
|
342
|
+
if (item.attempts >= this.maxRetries) {
|
|
343
|
+
this.logError(
|
|
344
|
+
`Max retries exceeded for error ${item.error.id}, dropping`
|
|
345
|
+
);
|
|
346
|
+
this.removeFromQueue(item);
|
|
347
|
+
} else {
|
|
348
|
+
const delay = this.calculateBackoff(item.attempts);
|
|
349
|
+
item.nextRetry = Date.now() + delay;
|
|
350
|
+
this.log(
|
|
351
|
+
`Scheduling retry for error ${item.error.id} in ${delay}ms (attempt ${item.attempts}/${this.maxRetries})`
|
|
352
|
+
);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Calculate exponential backoff delay
|
|
357
|
+
*
|
|
358
|
+
* Backoff formula: min(baseDelay * 2^(attempts - 1), maxDelay)
|
|
359
|
+
* - Attempt 1: 1s
|
|
360
|
+
* - Attempt 2: 2s
|
|
361
|
+
* - Attempt 3: 4s
|
|
362
|
+
* - Attempt 4: 8s
|
|
363
|
+
* - Attempt 5: 16s
|
|
364
|
+
*
|
|
365
|
+
* @param attempts - Number of attempts
|
|
366
|
+
* @returns Delay in milliseconds
|
|
367
|
+
*/
|
|
368
|
+
calculateBackoff(attempts) {
|
|
369
|
+
const delay = this.baseDelay * Math.pow(2, attempts - 1);
|
|
370
|
+
return Math.min(delay, this.maxDelay);
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Remove an item from the queue
|
|
374
|
+
*
|
|
375
|
+
* @param item - The item to remove
|
|
376
|
+
*/
|
|
377
|
+
removeFromQueue(item) {
|
|
378
|
+
const index = this.queue.indexOf(item);
|
|
379
|
+
if (index !== -1) {
|
|
380
|
+
this.queue.splice(index, 1);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Log a message (if debug mode is enabled)
|
|
385
|
+
*
|
|
386
|
+
* @param message - Message to log
|
|
387
|
+
*/
|
|
388
|
+
log(message) {
|
|
389
|
+
if (this.debug) {
|
|
390
|
+
console.log(`[BugStack Queue] ${message}`);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Log an error (if debug mode is enabled)
|
|
395
|
+
*
|
|
396
|
+
* @param message - Message to log
|
|
397
|
+
* @param error - Error object (optional)
|
|
398
|
+
*/
|
|
399
|
+
logError(message, error) {
|
|
400
|
+
if (this.debug) {
|
|
401
|
+
if (error) {
|
|
402
|
+
console.error(`[BugStack Queue] ${message}`, error);
|
|
403
|
+
} else {
|
|
404
|
+
console.error(`[BugStack Queue] ${message}`);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Get queue statistics (for debugging)
|
|
410
|
+
*/
|
|
411
|
+
getStats() {
|
|
412
|
+
const now = Date.now();
|
|
413
|
+
return {
|
|
414
|
+
size: this.queue.length,
|
|
415
|
+
processing: this.processing,
|
|
416
|
+
items: this.queue.map((item) => ({
|
|
417
|
+
errorId: item.error.id,
|
|
418
|
+
attempts: item.attempts,
|
|
419
|
+
nextRetry: item.nextRetry,
|
|
420
|
+
timeUntilRetry: Math.max(0, item.nextRetry - now)
|
|
421
|
+
}))
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
};
|
|
425
|
+
|
|
426
|
+
// src/core/client.ts
|
|
427
|
+
var SDK_VERSION = "0.2.0";
|
|
428
|
+
var DEFAULT_ENDPOINT = "http://localhost:3001/api/capture";
|
|
429
|
+
var DEFAULT_TIMEOUT = 5e3;
|
|
430
|
+
var DEFAULT_MAX_BODY_SIZE = 1e4;
|
|
431
|
+
var DEFAULT_DEDUPLICATION_WINDOW = 5 * 60 * 1e3;
|
|
432
|
+
var DEFAULT_REDACT_FIELDS = [
|
|
433
|
+
"password",
|
|
434
|
+
"secret",
|
|
435
|
+
"token",
|
|
436
|
+
"apikey",
|
|
437
|
+
"api_key",
|
|
438
|
+
"apiKey",
|
|
439
|
+
"authorization",
|
|
440
|
+
"auth",
|
|
441
|
+
"credential",
|
|
442
|
+
"private",
|
|
443
|
+
"credit_card",
|
|
444
|
+
"creditcard",
|
|
445
|
+
"card_number",
|
|
446
|
+
"cvv",
|
|
447
|
+
"ssn",
|
|
448
|
+
"social_security"
|
|
449
|
+
];
|
|
450
|
+
var ErrorCaptureClient = class _ErrorCaptureClient {
|
|
451
|
+
config;
|
|
452
|
+
static instance = null;
|
|
453
|
+
deduplicator;
|
|
454
|
+
retryQueue;
|
|
455
|
+
constructor(config) {
|
|
456
|
+
const isProduction = process.env.NODE_ENV === "production";
|
|
457
|
+
this.config = {
|
|
458
|
+
apiKey: config.apiKey,
|
|
459
|
+
endpoint: config.endpoint ?? process.env.BUGSTACK_ENDPOINT ?? DEFAULT_ENDPOINT,
|
|
460
|
+
projectId: config.projectId ?? process.env.BUGSTACK_PROJECT_ID ?? "",
|
|
461
|
+
environment: config.environment ?? process.env.NODE_ENV ?? "development",
|
|
462
|
+
autoFix: config.autoFix ?? false,
|
|
463
|
+
enabled: config.enabled ?? true,
|
|
464
|
+
captureRequestBody: config.captureRequestBody ?? true,
|
|
465
|
+
captureQueryParams: config.captureQueryParams ?? true,
|
|
466
|
+
captureHeaders: config.captureHeaders ?? true,
|
|
467
|
+
maxBodySize: config.maxBodySize ?? DEFAULT_MAX_BODY_SIZE,
|
|
468
|
+
redactFields: [
|
|
469
|
+
...DEFAULT_REDACT_FIELDS,
|
|
470
|
+
...config.redactFields ?? []
|
|
471
|
+
],
|
|
472
|
+
metadata: config.metadata ?? {},
|
|
473
|
+
timeout: config.timeout ?? DEFAULT_TIMEOUT,
|
|
474
|
+
deduplicationWindow: config.deduplicationWindow ?? DEFAULT_DEDUPLICATION_WINDOW,
|
|
475
|
+
debug: config.debug ?? !isProduction,
|
|
476
|
+
shouldCapture: config.shouldCapture,
|
|
477
|
+
beforeSend: config.beforeSend
|
|
478
|
+
};
|
|
479
|
+
this.deduplicator = new ErrorDeduplicator(this.config.deduplicationWindow);
|
|
480
|
+
this.retryQueue = new RetryQueue(
|
|
481
|
+
(error, sourceContext) => this.sendErrorToService(error, sourceContext),
|
|
482
|
+
{
|
|
483
|
+
maxRetries: 5,
|
|
484
|
+
baseDelay: 1e3,
|
|
485
|
+
maxDelay: 16e3,
|
|
486
|
+
debug: this.config.debug
|
|
487
|
+
}
|
|
488
|
+
);
|
|
489
|
+
this.log("BugStack client initialized", {
|
|
490
|
+
endpoint: this.config.endpoint,
|
|
491
|
+
projectId: this.config.projectId,
|
|
492
|
+
environment: this.config.environment,
|
|
493
|
+
autoFix: this.config.autoFix,
|
|
494
|
+
deduplicationWindow: this.config.deduplicationWindow
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* Initialize the singleton client instance
|
|
499
|
+
*/
|
|
500
|
+
static init(config) {
|
|
501
|
+
if (_ErrorCaptureClient.instance) {
|
|
502
|
+
_ErrorCaptureClient.instance.destroy();
|
|
503
|
+
}
|
|
504
|
+
_ErrorCaptureClient.instance = new _ErrorCaptureClient(config);
|
|
505
|
+
return _ErrorCaptureClient.instance;
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Get the singleton client instance
|
|
509
|
+
*/
|
|
510
|
+
static getInstance() {
|
|
511
|
+
return _ErrorCaptureClient.instance;
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Check if the client has been initialized
|
|
515
|
+
*/
|
|
516
|
+
static isInitialized() {
|
|
517
|
+
return _ErrorCaptureClient.instance !== null;
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* Reset the client (mainly for testing)
|
|
521
|
+
*/
|
|
522
|
+
static reset() {
|
|
523
|
+
if (_ErrorCaptureClient.instance) {
|
|
524
|
+
_ErrorCaptureClient.instance.destroy();
|
|
525
|
+
}
|
|
526
|
+
_ErrorCaptureClient.instance = null;
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Report an error to the BugStack service
|
|
530
|
+
*
|
|
531
|
+
* This method includes deduplication and queuing for resilience.
|
|
532
|
+
*
|
|
533
|
+
* @param error - The captured error
|
|
534
|
+
* @param sourceContext - Source code context (optional)
|
|
535
|
+
* @returns Promise that resolves to true if error was accepted (not deduplicated)
|
|
536
|
+
*/
|
|
537
|
+
async reportError(error, sourceContext) {
|
|
538
|
+
if (!this.config.enabled) {
|
|
539
|
+
this.log("Error capture is disabled, skipping report");
|
|
540
|
+
return false;
|
|
541
|
+
}
|
|
542
|
+
let errorToSend = error;
|
|
543
|
+
if (this.config.beforeSend) {
|
|
544
|
+
const modified = this.config.beforeSend(error);
|
|
545
|
+
if (modified === null) {
|
|
546
|
+
this.log("Error filtered by beforeSend hook");
|
|
547
|
+
return false;
|
|
548
|
+
}
|
|
549
|
+
errorToSend = modified;
|
|
550
|
+
}
|
|
551
|
+
const fingerprint = generateErrorFingerprint(errorToSend);
|
|
552
|
+
errorToSend.fingerprint = fingerprint;
|
|
553
|
+
if (!this.deduplicator.shouldSend(fingerprint)) {
|
|
554
|
+
this.log(`Error deduplicated: ${error.id} (fingerprint: ${fingerprint})`);
|
|
555
|
+
return false;
|
|
556
|
+
}
|
|
557
|
+
this.log(`Reporting error: ${error.id} (fingerprint: ${fingerprint})`);
|
|
558
|
+
errorToSend.projectId = this.config.projectId || errorToSend.projectId;
|
|
559
|
+
errorToSend.environment = this.config.environment;
|
|
560
|
+
errorToSend.metadata = {
|
|
561
|
+
...this.config.metadata,
|
|
562
|
+
...errorToSend.metadata,
|
|
563
|
+
autoFix: this.config.autoFix
|
|
564
|
+
};
|
|
565
|
+
this.retryQueue.enqueue(errorToSend, sourceContext);
|
|
566
|
+
return true;
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Send an error to the service (internal method)
|
|
570
|
+
*
|
|
571
|
+
* This is used by the retry queue. Returns true on success, false on failure.
|
|
572
|
+
*
|
|
573
|
+
* @param error - The error to send
|
|
574
|
+
* @param sourceContext - Source context (optional)
|
|
575
|
+
* @returns Promise that resolves to true on success
|
|
576
|
+
*/
|
|
577
|
+
async sendErrorToService(error, sourceContext) {
|
|
578
|
+
const payload = {
|
|
579
|
+
error,
|
|
580
|
+
sourceContext
|
|
581
|
+
};
|
|
582
|
+
try {
|
|
583
|
+
const controller = new AbortController();
|
|
584
|
+
const timeoutId = setTimeout(
|
|
585
|
+
() => controller.abort(),
|
|
586
|
+
this.config.timeout
|
|
587
|
+
);
|
|
588
|
+
const response = await fetch(this.config.endpoint, {
|
|
589
|
+
method: "POST",
|
|
590
|
+
headers: {
|
|
591
|
+
"Content-Type": "application/json",
|
|
592
|
+
"X-BugStack-API-Key": this.config.apiKey,
|
|
593
|
+
"X-BugStack-SDK-Version": SDK_VERSION
|
|
594
|
+
},
|
|
595
|
+
body: JSON.stringify(payload),
|
|
596
|
+
signal: controller.signal
|
|
597
|
+
});
|
|
598
|
+
clearTimeout(timeoutId);
|
|
599
|
+
if (!response.ok) {
|
|
600
|
+
this.logError(
|
|
601
|
+
`Failed to send error: HTTP ${response.status} ${response.statusText}`
|
|
602
|
+
);
|
|
603
|
+
return false;
|
|
604
|
+
}
|
|
605
|
+
this.log(`Error sent successfully: ${error.id}`);
|
|
606
|
+
return true;
|
|
607
|
+
} catch (err) {
|
|
608
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
609
|
+
this.logError(`Error send timed out after ${this.config.timeout}ms`);
|
|
610
|
+
} else {
|
|
611
|
+
this.logError("Failed to send error:", err);
|
|
612
|
+
}
|
|
613
|
+
return false;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
/**
|
|
617
|
+
* Get the resolved configuration
|
|
618
|
+
*/
|
|
619
|
+
getConfig() {
|
|
620
|
+
return { ...this.config };
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* Check if a field should be redacted
|
|
624
|
+
*/
|
|
625
|
+
shouldRedact(fieldName) {
|
|
626
|
+
const lowerField = fieldName.toLowerCase();
|
|
627
|
+
return this.config.redactFields.some(
|
|
628
|
+
(redact) => lowerField.includes(redact.toLowerCase()) || redact.toLowerCase().includes(lowerField)
|
|
629
|
+
);
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* Get the SDK version
|
|
633
|
+
*/
|
|
634
|
+
static getVersion() {
|
|
635
|
+
return SDK_VERSION;
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* Get client statistics (for debugging)
|
|
639
|
+
*/
|
|
640
|
+
getStats() {
|
|
641
|
+
return {
|
|
642
|
+
deduplicator: this.deduplicator.getStats(),
|
|
643
|
+
retryQueue: this.retryQueue.getStats()
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* Clean up resources
|
|
648
|
+
*
|
|
649
|
+
* Should be called when shutting down to prevent memory leaks
|
|
650
|
+
*/
|
|
651
|
+
destroy() {
|
|
652
|
+
this.deduplicator.destroy();
|
|
653
|
+
this.retryQueue.destroy();
|
|
654
|
+
}
|
|
655
|
+
log(message, data) {
|
|
656
|
+
if (this.config.debug) {
|
|
657
|
+
if (data) {
|
|
658
|
+
console.log(`[BugStack] ${message}`, data);
|
|
659
|
+
} else {
|
|
660
|
+
console.log(`[BugStack] ${message}`);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
logError(message, error) {
|
|
665
|
+
if (this.config.debug) {
|
|
666
|
+
if (error) {
|
|
667
|
+
console.error(`[BugStack] ${message}`, error);
|
|
668
|
+
} else {
|
|
669
|
+
console.error(`[BugStack] ${message}`);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
};
|
|
674
|
+
var BugStackClient = ErrorCaptureClient;
|
|
675
|
+
|
|
676
|
+
// src/core/utils/stack-parser.ts
|
|
677
|
+
var V8_STACK_FRAME_REGEX = /^\s*at\s+(?:async\s+)?(?:(.+?)\s+\()?(?:(.+?):(\d+):(\d+))\)?$/;
|
|
678
|
+
function isNodeModule(filePath) {
|
|
679
|
+
return filePath.includes("node_modules");
|
|
680
|
+
}
|
|
681
|
+
function isInternalCode(filePath) {
|
|
682
|
+
return filePath.startsWith("node:") || filePath.startsWith("internal/") || !filePath.includes("/");
|
|
683
|
+
}
|
|
684
|
+
function cleanFunctionName(name) {
|
|
685
|
+
if (!name) return void 0;
|
|
686
|
+
return name.replace(/^Object\./, "").replace(/^Module\./, "").replace(/^__webpack_require__\./, "").replace(/^webpack_require\./, "").trim();
|
|
687
|
+
}
|
|
688
|
+
function parseStackTrace(stack) {
|
|
689
|
+
if (!stack) return [];
|
|
690
|
+
const lines = stack.split("\n");
|
|
691
|
+
const frames = [];
|
|
692
|
+
for (const line of lines) {
|
|
693
|
+
const match = V8_STACK_FRAME_REGEX.exec(line);
|
|
694
|
+
if (match) {
|
|
695
|
+
const [, functionName, file, lineStr, columnStr] = match;
|
|
696
|
+
const frame = {
|
|
697
|
+
function: cleanFunctionName(functionName),
|
|
698
|
+
file: file ?? void 0,
|
|
699
|
+
line: lineStr ? parseInt(lineStr, 10) : void 0,
|
|
700
|
+
column: columnStr ? parseInt(columnStr, 10) : void 0
|
|
701
|
+
};
|
|
702
|
+
if (frame.file) {
|
|
703
|
+
frame.isNodeModule = isNodeModule(frame.file);
|
|
704
|
+
frame.isInternal = isInternalCode(frame.file);
|
|
705
|
+
}
|
|
706
|
+
frames.push(frame);
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
return frames;
|
|
710
|
+
}
|
|
711
|
+
function getFirstAppFrame(frames) {
|
|
712
|
+
return frames.find((frame) => !frame.isNodeModule && !frame.isInternal);
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// src/adapters/generic/index.ts
|
|
716
|
+
var SDK_VERSION2 = "0.2.0";
|
|
717
|
+
function generateErrorId() {
|
|
718
|
+
const timestamp = Date.now().toString(36);
|
|
719
|
+
const random = Math.random().toString(36).substring(2, 9);
|
|
720
|
+
return `err_${timestamp}_${random}`;
|
|
721
|
+
}
|
|
722
|
+
function getNodeVersion() {
|
|
723
|
+
try {
|
|
724
|
+
return process.version;
|
|
725
|
+
} catch {
|
|
726
|
+
return "unknown";
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
function buildCapturedError(error, client, metadata) {
|
|
730
|
+
const config = client.getConfig();
|
|
731
|
+
const stackFrames = parseStackTrace(error.stack);
|
|
732
|
+
const firstAppFrame = getFirstAppFrame(stackFrames);
|
|
733
|
+
const capturedError = {
|
|
734
|
+
id: generateErrorId(),
|
|
735
|
+
name: error.name || "Error",
|
|
736
|
+
message: error.message,
|
|
737
|
+
stack: error.stack,
|
|
738
|
+
stackFrames,
|
|
739
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
740
|
+
route: "generic",
|
|
741
|
+
method: "N/A",
|
|
742
|
+
statusCode: 500,
|
|
743
|
+
url: "N/A",
|
|
744
|
+
environment: config.environment,
|
|
745
|
+
projectId: config.projectId,
|
|
746
|
+
sdkVersion: SDK_VERSION2,
|
|
747
|
+
nodeVersion: getNodeVersion()
|
|
748
|
+
};
|
|
749
|
+
if (firstAppFrame) {
|
|
750
|
+
capturedError.metadata = {
|
|
751
|
+
...capturedError.metadata,
|
|
752
|
+
sourceLocation: {
|
|
753
|
+
file: firstAppFrame.file,
|
|
754
|
+
line: firstAppFrame.line,
|
|
755
|
+
column: firstAppFrame.column,
|
|
756
|
+
function: firstAppFrame.function
|
|
757
|
+
}
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
if (metadata) {
|
|
761
|
+
capturedError.metadata = {
|
|
762
|
+
...capturedError.metadata,
|
|
763
|
+
...metadata
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
return capturedError;
|
|
767
|
+
}
|
|
768
|
+
function initBugStack(config) {
|
|
769
|
+
return ErrorCaptureClient.init(config);
|
|
770
|
+
}
|
|
771
|
+
async function captureError(error, metadata) {
|
|
772
|
+
const client = ErrorCaptureClient.getInstance();
|
|
773
|
+
if (!client) {
|
|
774
|
+
console.warn(
|
|
775
|
+
"[BugStack] Client not initialized. Call initBugStack() first."
|
|
776
|
+
);
|
|
777
|
+
return false;
|
|
778
|
+
}
|
|
779
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
780
|
+
const capturedError = buildCapturedError(err, client, metadata);
|
|
781
|
+
return client.reportError(capturedError);
|
|
782
|
+
}
|
|
783
|
+
var captureException = captureError;
|
|
784
|
+
function wrapFunction(fn, metadata) {
|
|
785
|
+
return ((...args) => {
|
|
786
|
+
try {
|
|
787
|
+
const result = fn(...args);
|
|
788
|
+
if (result instanceof Promise) {
|
|
789
|
+
return result.catch((error) => {
|
|
790
|
+
captureError(error, metadata);
|
|
791
|
+
throw error;
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
return result;
|
|
795
|
+
} catch (error) {
|
|
796
|
+
captureError(error, metadata);
|
|
797
|
+
throw error;
|
|
798
|
+
}
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
function installGlobalHandlers() {
|
|
802
|
+
process.on("uncaughtException", (error) => {
|
|
803
|
+
captureError(error, { type: "uncaughtException" }).then(() => {
|
|
804
|
+
setTimeout(() => {
|
|
805
|
+
process.exit(1);
|
|
806
|
+
}, 1e3);
|
|
807
|
+
});
|
|
808
|
+
});
|
|
809
|
+
process.on("unhandledRejection", (reason) => {
|
|
810
|
+
const error = reason instanceof Error ? reason : new Error(String(reason));
|
|
811
|
+
captureError(error, { type: "unhandledRejection" }).catch(() => {
|
|
812
|
+
});
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
function createErrorCapture(baseMetadata) {
|
|
816
|
+
return (error, additionalMetadata) => {
|
|
817
|
+
return captureError(error, {
|
|
818
|
+
...baseMetadata,
|
|
819
|
+
...additionalMetadata
|
|
820
|
+
});
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
exports.BugStackClient = BugStackClient;
|
|
825
|
+
exports.ErrorCaptureClient = ErrorCaptureClient;
|
|
826
|
+
exports.captureError = captureError;
|
|
827
|
+
exports.captureException = captureException;
|
|
828
|
+
exports.createErrorCapture = createErrorCapture;
|
|
829
|
+
exports.initBugStack = initBugStack;
|
|
830
|
+
exports.installGlobalHandlers = installGlobalHandlers;
|
|
831
|
+
exports.wrapFunction = wrapFunction;
|
|
832
|
+
//# sourceMappingURL=index.js.map
|
|
833
|
+
//# sourceMappingURL=index.js.map
|