ezlogs-nextjs 0.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.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +779 -0
  3. package/bin/install-triggers.cjs +75 -0
  4. package/dist/actors/index.cjs +111 -0
  5. package/dist/actors/index.d.cts +52 -0
  6. package/dist/actors/index.d.ts +52 -0
  7. package/dist/actors/index.js +107 -0
  8. package/dist/configuration-D9x9Gvds.d.cts +190 -0
  9. package/dist/configuration-D9x9Gvds.d.ts +190 -0
  10. package/dist/db/drizzle.cjs +898 -0
  11. package/dist/db/drizzle.d.cts +68 -0
  12. package/dist/db/drizzle.d.ts +68 -0
  13. package/dist/db/drizzle.js +893 -0
  14. package/dist/db/prisma.cjs +826 -0
  15. package/dist/db/prisma.d.cts +3 -0
  16. package/dist/db/prisma.d.ts +3 -0
  17. package/dist/db/prisma.js +824 -0
  18. package/dist/db/supabase.cjs +1027 -0
  19. package/dist/db/supabase.d.cts +32 -0
  20. package/dist/db/supabase.d.ts +32 -0
  21. package/dist/db/supabase.js +1024 -0
  22. package/dist/index.cjs +3329 -0
  23. package/dist/index.d.cts +305 -0
  24. package/dist/index.d.ts +305 -0
  25. package/dist/index.js +3317 -0
  26. package/dist/jobs/bullmq.cjs +624 -0
  27. package/dist/jobs/bullmq.d.cts +33 -0
  28. package/dist/jobs/bullmq.d.ts +33 -0
  29. package/dist/jobs/bullmq.js +621 -0
  30. package/dist/jobs/inngest.cjs +645 -0
  31. package/dist/jobs/inngest.d.cts +21 -0
  32. package/dist/jobs/inngest.d.ts +21 -0
  33. package/dist/jobs/inngest.js +642 -0
  34. package/dist/jobs/supabase-queues.cjs +661 -0
  35. package/dist/jobs/supabase-queues.d.cts +37 -0
  36. package/dist/jobs/supabase-queues.d.ts +37 -0
  37. package/dist/jobs/supabase-queues.js +657 -0
  38. package/dist/jobs/trigger.cjs +622 -0
  39. package/dist/jobs/trigger.d.cts +46 -0
  40. package/dist/jobs/trigger.d.ts +46 -0
  41. package/dist/jobs/trigger.js +619 -0
  42. package/dist/jobs/upstash-workflow.cjs +673 -0
  43. package/dist/jobs/upstash-workflow.d.cts +57 -0
  44. package/dist/jobs/upstash-workflow.d.ts +57 -0
  45. package/dist/jobs/upstash-workflow.js +669 -0
  46. package/dist/nextjs-plugin/index.cjs +232 -0
  47. package/dist/nextjs-plugin/index.d.cts +68 -0
  48. package/dist/nextjs-plugin/index.d.ts +68 -0
  49. package/dist/nextjs-plugin/index.js +229 -0
  50. package/dist/nextjs-plugin/loader.cjs +16248 -0
  51. package/dist/nextjs-plugin/loader.d.cts +61 -0
  52. package/dist/nextjs-plugin/loader.d.ts +61 -0
  53. package/dist/nextjs-plugin/loader.js +16242 -0
  54. package/dist/triggers/index.cjs +1354 -0
  55. package/dist/triggers/index.d.cts +243 -0
  56. package/dist/triggers/index.d.ts +243 -0
  57. package/dist/triggers/index.js +1337 -0
  58. package/package.json +150 -0
  59. package/sql/postgres/00_install.sql +205 -0
@@ -0,0 +1,624 @@
1
+ 'use strict';
2
+
3
+ require('crypto');
4
+
5
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
6
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
7
+ }) : x)(function(x) {
8
+ if (typeof require !== "undefined") return require.apply(this, arguments);
9
+ throw Error('Dynamic require of "' + x + '" is not supported');
10
+ });
11
+
12
+ // src/logger.ts
13
+ var LEVEL_RANK = {
14
+ debug: 10,
15
+ info: 20,
16
+ warn: 30,
17
+ error: 40,
18
+ silent: 100
19
+ };
20
+ var LEVEL_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:log-level");
21
+ function readLevel() {
22
+ const g = globalThis;
23
+ return g[LEVEL_KEY] ?? "warn";
24
+ }
25
+ function shouldLog(level) {
26
+ return LEVEL_RANK[level] >= LEVEL_RANK[readLevel()];
27
+ }
28
+ function safeWrite(level, message) {
29
+ try {
30
+ if (!shouldLog(level)) return;
31
+ const line = `[ezlogs] ${message}`;
32
+ if (level === "error" || level === "warn") {
33
+ console.error(line);
34
+ } else {
35
+ console.log(line);
36
+ }
37
+ } catch {
38
+ }
39
+ }
40
+ var logger = {
41
+ debug: (message) => safeWrite("debug", message),
42
+ info: (message) => safeWrite("info", message),
43
+ warn: (message) => safeWrite("warn", message),
44
+ error: (message) => safeWrite("error", message)
45
+ };
46
+
47
+ // src/event-builder.ts
48
+ var SENSITIVE_KEYS = Object.freeze([
49
+ "password",
50
+ "token",
51
+ "secret",
52
+ "api_key",
53
+ "credit_card"
54
+ ]);
55
+ var VALID_SOURCE_TYPES = [
56
+ "http_request",
57
+ "background_job",
58
+ "database_callback"
59
+ ];
60
+ var VALID_OUTCOMES = ["success", "failure"];
61
+ function build(input) {
62
+ const source_type = validateSourceType(input.source_type);
63
+ const source_data_raw = validateSourceData(input.source_data);
64
+ const outcome = validateOutcome(input.outcome);
65
+ const timestamp = validateTimestamp(input.timestamp ?? null);
66
+ const resource_ids = validateResourceIds(input.resource_ids ?? []);
67
+ const context_raw = validateContext();
68
+ const duration_ms = validateDurationMs(input.duration_ms ?? null);
69
+ const error_message = input.error_message ?? null;
70
+ validateOutcomeErrorConsistency(outcome, error_message);
71
+ const source_data = sanitizeRecord(source_data_raw);
72
+ const context = context_raw === null ? null : sanitizeRecord(context_raw);
73
+ const correlation_id = input.correlation_id ?? null;
74
+ const event = {
75
+ timestamp,
76
+ source_type,
77
+ source_data,
78
+ outcome,
79
+ correlation_id,
80
+ resource_ids,
81
+ context,
82
+ duration_ms,
83
+ error_message
84
+ };
85
+ return event;
86
+ }
87
+ function validateSourceType(value) {
88
+ const normalized = String(value);
89
+ if (!VALID_SOURCE_TYPES.includes(normalized)) {
90
+ throw new ArgError(
91
+ `source_type must be one of ${VALID_SOURCE_TYPES.join(", ")}, got: ${normalized}`
92
+ );
93
+ }
94
+ return normalized;
95
+ }
96
+ function validateSourceData(value) {
97
+ if (value === null || value === void 0) {
98
+ throw new ArgError("source_data is required");
99
+ }
100
+ if (!isPlainObject(value)) {
101
+ throw new ArgError(
102
+ `source_data must be an object, got: ${describe(value)}`
103
+ );
104
+ }
105
+ return value;
106
+ }
107
+ function validateOutcome(value) {
108
+ if (value === null || value === void 0) {
109
+ throw new ArgError("outcome is required");
110
+ }
111
+ const normalized = String(value);
112
+ if (!VALID_OUTCOMES.includes(normalized)) {
113
+ throw new ArgError(
114
+ `outcome must be one of ${VALID_OUTCOMES.join(", ")}, got: ${normalized}`
115
+ );
116
+ }
117
+ return normalized;
118
+ }
119
+ function validateTimestamp(value) {
120
+ if (value === null) {
121
+ return (/* @__PURE__ */ new Date()).toISOString();
122
+ }
123
+ if (typeof value === "string") {
124
+ const parsed = new Date(value);
125
+ if (Number.isNaN(parsed.getTime())) {
126
+ throw new ArgError(
127
+ `timestamp must be valid ISO 8601 format, got: ${value}`
128
+ );
129
+ }
130
+ return value;
131
+ }
132
+ if (value instanceof Date) {
133
+ if (Number.isNaN(value.getTime())) {
134
+ throw new ArgError("timestamp must be a valid Date");
135
+ }
136
+ return value.toISOString();
137
+ }
138
+ throw new ArgError(
139
+ `timestamp must be a string or Date, got: ${describe(value)}`
140
+ );
141
+ }
142
+ function validateResourceIds(value) {
143
+ if (!Array.isArray(value)) {
144
+ throw new ArgError(`resource_ids must be an array, got: ${describe(value)}`);
145
+ }
146
+ value.forEach((entry, index) => {
147
+ if (!isPlainObject(entry)) {
148
+ throw new ArgError(
149
+ `resource_ids[${index}] must be an object, got: ${describe(entry)}`
150
+ );
151
+ }
152
+ const e = entry;
153
+ if (!("resource_type" in e) || !("resource_id" in e)) {
154
+ throw new ArgError(
155
+ `resource_ids[${index}] must have resource_type and resource_id keys, got: ${Object.keys(e).join(", ")}`
156
+ );
157
+ }
158
+ if (typeof e.resource_type !== "string") {
159
+ throw new ArgError(
160
+ `resource_ids[${index}].resource_type must be a string, got: ${describe(e.resource_type)}`
161
+ );
162
+ }
163
+ if (typeof e.resource_id !== "string") {
164
+ throw new ArgError(
165
+ `resource_ids[${index}].resource_id must be a string, got: ${describe(e.resource_id)}`
166
+ );
167
+ }
168
+ });
169
+ return value;
170
+ }
171
+ function validateContext(value) {
172
+ return null;
173
+ }
174
+ function validateDurationMs(value) {
175
+ if (value === null || value === void 0) return null;
176
+ if (typeof value !== "number" || !Number.isFinite(value)) {
177
+ throw new ArgError(`duration_ms must be a number, got: ${describe(value)}`);
178
+ }
179
+ if (!Number.isInteger(value)) {
180
+ throw new ArgError(`duration_ms must be an integer, got: ${value}`);
181
+ }
182
+ if (value < 0) {
183
+ throw new ArgError(`duration_ms must be >= 0, got: ${value}`);
184
+ }
185
+ return value;
186
+ }
187
+ function validateOutcomeErrorConsistency(outcome, error_message) {
188
+ if (outcome === "failure") {
189
+ if (error_message === null || error_message === "") {
190
+ throw new ArgError("error_message is required when outcome is 'failure'");
191
+ }
192
+ } else if (outcome === "success") {
193
+ if (error_message !== null) {
194
+ throw new ArgError("error_message must be null when outcome is 'success'");
195
+ }
196
+ }
197
+ }
198
+ function sanitizeRecord(input) {
199
+ const result = {};
200
+ for (const key of Object.keys(input)) {
201
+ const value = input[key];
202
+ if (isSensitiveKey(key)) {
203
+ result[key] = "[FILTERED]";
204
+ } else if (isPlainObject(value)) {
205
+ result[key] = sanitizeRecord(value);
206
+ } else if (Array.isArray(value)) {
207
+ result[key] = value.map(
208
+ (item) => isPlainObject(item) ? sanitizeRecord(item) : item
209
+ );
210
+ } else {
211
+ result[key] = value;
212
+ }
213
+ }
214
+ return result;
215
+ }
216
+ function isSensitiveKey(key) {
217
+ const lower = key.toLowerCase();
218
+ return SENSITIVE_KEYS.some((p) => lower.includes(p));
219
+ }
220
+ function isPlainObject(value) {
221
+ if (value === null || typeof value !== "object") return false;
222
+ const proto = Object.getPrototypeOf(value);
223
+ return proto === Object.prototype || proto === null;
224
+ }
225
+ function describe(value) {
226
+ if (value === null) return "null";
227
+ if (Array.isArray(value)) return "Array";
228
+ return typeof value;
229
+ }
230
+ var ArgError = class extends Error {
231
+ constructor(message) {
232
+ super(message);
233
+ this.name = "ArgError";
234
+ }
235
+ };
236
+
237
+ // src/configuration.ts
238
+ var DEFAULT_EXCLUDED_PATHS = Object.freeze([
239
+ // Next.js / Vercel infrastructure noise
240
+ "/_next/*",
241
+ "/_vercel/*",
242
+ "/__nextjs_*",
243
+ // NextAuth.js / Auth.js — skip session-refresh polls and CSRF/provider
244
+ // metadata GETs (high-frequency, no business meaning), but CAPTURE
245
+ // POSTs (callbacks, signin, signout, register). The POSTs are the
246
+ // actual auth events users care about; the GETs are pure plumbing.
247
+ Object.freeze({ path: "/api/auth/*", methods: ["GET", "HEAD"] }),
248
+ // Generic infrastructure
249
+ "/health*",
250
+ "/api/health",
251
+ "/up",
252
+ "/alive",
253
+ "/ready",
254
+ "/metrics",
255
+ "/favicon.ico",
256
+ "/.well-known*",
257
+ "/robots.txt",
258
+ "/sitemap.xml",
259
+ "/*.hot-update.*",
260
+ // Auth routes (common patterns across Clerk, NextAuth, custom auth)
261
+ "*/login*",
262
+ "*/logout*",
263
+ "*/sign-in*",
264
+ "*/sign-out*",
265
+ "*/signin*",
266
+ "*/signout*",
267
+ "/session*"
268
+ ]);
269
+ var DEFAULT_EXCLUDED_TABLES = Object.freeze([
270
+ // Prisma migration ledger
271
+ "_prisma_migrations",
272
+ // Auth.js / NextAuth Prisma adapter — session/verification-token churn
273
+ // is auth machinery, not business activity. Account/User stay captured.
274
+ "Session",
275
+ "VerificationToken",
276
+ // Common cross-stack convention names for the same things
277
+ "sessions",
278
+ "session",
279
+ "verification_tokens"
280
+ ]);
281
+ var DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
282
+ var DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
283
+ var DEFAULT_SERVER_URL = "https://app.ezlogs.io";
284
+ var Configuration = class {
285
+ serverUrl = DEFAULT_SERVER_URL;
286
+ projectToken = null;
287
+ captureHttp = true;
288
+ captureDb = true;
289
+ captureJobs = true;
290
+ bufferSize = 1e4;
291
+ /** Default 3000 ms — equivalent to Ruby's 3 seconds. */
292
+ sendInterval = 3e3;
293
+ retryAttempts = 3;
294
+ logLevel = "warn";
295
+ patchGlobalFetch = true;
296
+ actorFromSupabase = true;
297
+ excludedPaths = [];
298
+ excludedTables = [];
299
+ excludedJobClasses = [];
300
+ excludedGraphqlOperations = [];
301
+ excludedGraphqlVariableKeys = [];
302
+ actorFromRequest = null;
303
+ displayNameFor = {};
304
+ isServerActionError = null;
305
+ databaseReader = null;
306
+ databaseSnapshotMode = false;
307
+ databaseUrl = null;
308
+ /**
309
+ * Tables that have the `ezlogs_audit` trigger attached. Detected once
310
+ * at agent startup by reading `information_schema.triggers`. The
311
+ * supabase / drizzle / prisma adapters use this to decide whether
312
+ * their per-mutation emit is redundant: if the table is trigger-
313
+ * tracked the audit-log reader will surface the same write with full
314
+ * old/new state, so the adapter's emit is suppressed. Tables NOT in
315
+ * this set fall through to the adapter so they're still captured.
316
+ *
317
+ * `null` means "detection hasn't run yet or failed" — in that state
318
+ * `databaseReader`-wired apps suppress every adapter emit (the
319
+ * original Phase 5 behavior). After detection completes the agent
320
+ * gives the more accurate per-table answer.
321
+ */
322
+ triggerTrackedTables = null;
323
+ apply(options) {
324
+ if (options.serverUrl !== void 0) this.serverUrl = options.serverUrl;
325
+ this.projectToken = options.projectToken;
326
+ if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
327
+ if (options.captureDb !== void 0) this.captureDb = options.captureDb;
328
+ if (options.captureJobs !== void 0) this.captureJobs = options.captureJobs;
329
+ if (options.bufferSize !== void 0) this.bufferSize = options.bufferSize;
330
+ if (options.sendInterval !== void 0) this.sendInterval = options.sendInterval;
331
+ if (options.retryAttempts !== void 0) this.retryAttempts = options.retryAttempts;
332
+ if (options.excludedPaths) this.excludedPaths = [...options.excludedPaths];
333
+ if (options.excludedTables) this.excludedTables = [...options.excludedTables];
334
+ if (options.excludedJobClasses) {
335
+ this.excludedJobClasses = [...options.excludedJobClasses];
336
+ }
337
+ if (options.excludedGraphqlOperations) {
338
+ this.excludedGraphqlOperations = [...options.excludedGraphqlOperations];
339
+ }
340
+ if (options.excludedGraphqlVariableKeys) {
341
+ this.excludedGraphqlVariableKeys = [...options.excludedGraphqlVariableKeys];
342
+ }
343
+ if (options.actorFromRequest) this.actorFromRequest = options.actorFromRequest;
344
+ if (options.displayNameFor) this.displayNameFor = { ...options.displayNameFor };
345
+ if (options.isServerActionError) this.isServerActionError = options.isServerActionError;
346
+ if (options.patchGlobalFetch !== void 0) {
347
+ this.patchGlobalFetch = options.patchGlobalFetch;
348
+ }
349
+ if (options.actorFromSupabase !== void 0) {
350
+ this.actorFromSupabase = options.actorFromSupabase;
351
+ }
352
+ if (options.databaseReader !== void 0) {
353
+ this.databaseReader = options.databaseReader;
354
+ }
355
+ if (options.databaseSnapshotMode !== void 0) {
356
+ this.databaseSnapshotMode = options.databaseSnapshotMode;
357
+ }
358
+ if (options.databaseUrl !== void 0) {
359
+ this.databaseUrl = options.databaseUrl;
360
+ }
361
+ if (options.logLevel) this.logLevel = options.logLevel;
362
+ }
363
+ allExcludedPaths() {
364
+ return [...DEFAULT_EXCLUDED_PATHS, ...this.excludedPaths];
365
+ }
366
+ allExcludedTables() {
367
+ return [...DEFAULT_EXCLUDED_TABLES, ...this.excludedTables];
368
+ }
369
+ allExcludedJobClasses() {
370
+ return [...DEFAULT_EXCLUDED_JOB_CLASSES, ...this.excludedJobClasses];
371
+ }
372
+ allExcludedGraphqlOperations() {
373
+ return [...DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, ...this.excludedGraphqlOperations];
374
+ }
375
+ };
376
+ var GLOBAL_CONFIG_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:configuration");
377
+ function configuration() {
378
+ const g = globalThis;
379
+ if (!g[GLOBAL_CONFIG_KEY]) {
380
+ g[GLOBAL_CONFIG_KEY] = new Configuration();
381
+ }
382
+ return g[GLOBAL_CONFIG_KEY];
383
+ }
384
+
385
+ // src/pipeline/buffer.ts
386
+ var GLOBAL_QUEUE_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:buffer-queue");
387
+ function getQueue() {
388
+ const g = globalThis;
389
+ if (!g[GLOBAL_QUEUE_KEY]) g[GLOBAL_QUEUE_KEY] = [];
390
+ return g[GLOBAL_QUEUE_KEY];
391
+ }
392
+ function pushEvent(event) {
393
+ try {
394
+ const queue = getQueue();
395
+ const max = maxSize();
396
+ if (queue.length >= max) {
397
+ queue.shift();
398
+ logger.warn(`Buffer full (${max}), dropped oldest event`);
399
+ }
400
+ queue.push(event);
401
+ } catch (error) {
402
+ logger.error(`pushEvent failed: ${describe2(error)}`);
403
+ }
404
+ }
405
+ function maxSize() {
406
+ try {
407
+ return configuration().bufferSize;
408
+ } catch {
409
+ return 1e4;
410
+ }
411
+ }
412
+ function describe2(error) {
413
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
414
+ return String(error);
415
+ }
416
+
417
+ // src/edge-fallback.ts
418
+ var ALS_CTOR = loadAsyncLocalStorage();
419
+ function loadAsyncLocalStorage() {
420
+ const fromGlobal = globalThis.AsyncLocalStorage;
421
+ if (typeof fromGlobal === "function") return fromGlobal;
422
+ try {
423
+ const req = typeof __require !== "undefined" ? __require : (
424
+ // In ESM, `createRequire` is the official escape hatch.
425
+ // We pull it via globalThis to avoid a static `import`
426
+ // that would itself be browser-bundled.
427
+ void 0
428
+ );
429
+ if (typeof req === "function") {
430
+ const moduleName = ["async", "hooks"].join("_");
431
+ const mod = req("node:" + moduleName);
432
+ if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
433
+ }
434
+ } catch {
435
+ }
436
+ return null;
437
+ }
438
+ function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
439
+ const globalStore = globalThis;
440
+ let entry = globalStore[key];
441
+ if (!entry) {
442
+ const als2 = (() => {
443
+ if (!ALS_CTOR) return null;
444
+ try {
445
+ return new ALS_CTOR();
446
+ } catch {
447
+ return null;
448
+ }
449
+ })();
450
+ entry = { als: als2, edgeFallback: null };
451
+ globalStore[key] = entry;
452
+ }
453
+ const als = entry.als;
454
+ const stateRef = entry;
455
+ return {
456
+ read() {
457
+ if (als) return als.getStore()?.value ?? null;
458
+ return stateRef.edgeFallback?.value ?? null;
459
+ },
460
+ run(value, callback) {
461
+ if (als) return als.run({ value }, callback);
462
+ const previous = stateRef.edgeFallback;
463
+ stateRef.edgeFallback = { value };
464
+ try {
465
+ return callback();
466
+ } finally {
467
+ stateRef.edgeFallback = previous;
468
+ }
469
+ },
470
+ update(value) {
471
+ if (als) {
472
+ const store = als.getStore();
473
+ if (store) store.value = value;
474
+ return;
475
+ }
476
+ stateRef.edgeFallback = { value };
477
+ },
478
+ _resetForTests() {
479
+ stateRef.edgeFallback = null;
480
+ },
481
+ _isAsyncLocalStorage() {
482
+ return als !== null;
483
+ }
484
+ };
485
+ }
486
+
487
+ // src/correlation.ts
488
+ var storage = createScopedStorage(
489
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
490
+ );
491
+ function current() {
492
+ return storage.read();
493
+ }
494
+
495
+ // src/jobs/shared.ts
496
+ var CORRELATION_PAYLOAD_KEY = "ezlogs_correlation_id";
497
+ function emitJobEvent(input) {
498
+ try {
499
+ const config = configuration();
500
+ if (!config.captureJobs) return;
501
+ if (config.allExcludedJobClasses().includes(input.jobClass)) return;
502
+ const sourceData = compactJobSourceData({
503
+ job_class: input.jobClass,
504
+ job_id: input.jobId ?? null,
505
+ queue: input.queue ?? null,
506
+ retry_count: input.retryCount ?? null
507
+ });
508
+ const event = build({
509
+ source_type: "background_job",
510
+ source_data: sourceData,
511
+ outcome: input.outcome,
512
+ correlation_id: input.correlationId ?? current(),
513
+ resource_ids: [],
514
+ context: null,
515
+ duration_ms: input.durationMs ?? null,
516
+ error_message: input.errorMessage ?? null,
517
+ timestamp: input.startedAt
518
+ });
519
+ pushEvent(event);
520
+ } catch (error) {
521
+ logger.debug(`job emit failed: ${describeError(error)}`);
522
+ }
523
+ }
524
+ function extractCorrelationFromPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
525
+ if (payload === null || typeof payload !== "object") return null;
526
+ const value = payload[key];
527
+ return typeof value === "string" && value.length > 0 ? value : null;
528
+ }
529
+ function stampCorrelationOnPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
530
+ if (!payload || typeof payload !== "object") return;
531
+ if (typeof payload[key] === "string" && payload[key]) return;
532
+ const id = current();
533
+ if (!id) return;
534
+ payload[key] = id;
535
+ }
536
+ function compactJobSourceData(data) {
537
+ const out = {};
538
+ for (const key of Object.keys(data)) {
539
+ const value = data[key];
540
+ if (value !== null && value !== void 0) out[key] = value;
541
+ }
542
+ return out;
543
+ }
544
+ function describeError(error) {
545
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
546
+ return String(error);
547
+ }
548
+
549
+ // src/jobs/bullmq.ts
550
+ var WRAPPED_FLAG = "__ezlogsBullWrapped";
551
+ function wrapBullQueue(queue) {
552
+ if (queue[WRAPPED_FLAG]) return queue;
553
+ const originalAdd = queue.add.bind(queue);
554
+ queue.add = ((name, data, opts) => {
555
+ return originalAdd(name, stampPayload(data), opts);
556
+ });
557
+ if (typeof queue.addBulk === "function") {
558
+ const originalAddBulk = queue.addBulk.bind(queue);
559
+ const wrappedAddBulk = (jobs) => originalAddBulk(jobs.map((j) => ({ ...j, data: stampPayload(j.data) })));
560
+ queue.addBulk = wrappedAddBulk;
561
+ }
562
+ Object.defineProperty(queue, WRAPPED_FLAG, {
563
+ value: true,
564
+ enumerable: false,
565
+ configurable: false
566
+ });
567
+ return queue;
568
+ }
569
+ function wrapBullWorker(worker) {
570
+ if (worker[WRAPPED_FLAG]) return worker;
571
+ worker.on("completed", (...args) => {
572
+ const job = args[0];
573
+ if (!job) return;
574
+ captureJob(job, worker, "success", null);
575
+ });
576
+ worker.on("failed", (...args) => {
577
+ const job = args[0];
578
+ const error = args[1];
579
+ if (!job) return;
580
+ const message = error ? `${error.name ?? "Error"}: ${error.message ?? String(error)}` : "Error: job failed";
581
+ captureJob(job, worker, "failure", message);
582
+ });
583
+ Object.defineProperty(worker, WRAPPED_FLAG, {
584
+ value: true,
585
+ enumerable: false,
586
+ configurable: false
587
+ });
588
+ return worker;
589
+ }
590
+ function captureJob(job, worker, outcome, errorMessage) {
591
+ try {
592
+ const correlationId = extractCorrelationFromPayload(job.data);
593
+ const startedAt = typeof job.timestamp === "number" ? new Date(job.timestamp) : /* @__PURE__ */ new Date();
594
+ const durationMs = job.timestamp ? Date.now() - job.timestamp : null;
595
+ emitJobEvent({
596
+ jobClass: job.name ?? worker.name ?? "BullMQJob",
597
+ jobId: job.id !== void 0 && job.id !== null ? String(job.id) : null,
598
+ queue: job.queueName ?? worker.name ?? null,
599
+ retryCount: typeof job.attemptsMade === "number" ? Math.max(0, job.attemptsMade - 1) : null,
600
+ correlationId,
601
+ outcome,
602
+ errorMessage,
603
+ durationMs,
604
+ startedAt
605
+ });
606
+ } catch (error) {
607
+ logger.debug(`bullmq capture failed: ${describeError2(error)}`);
608
+ }
609
+ }
610
+ function stampPayload(data) {
611
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
612
+ return data;
613
+ }
614
+ const obj = data;
615
+ stampCorrelationOnPayload(obj, CORRELATION_PAYLOAD_KEY);
616
+ return obj;
617
+ }
618
+ function describeError2(error) {
619
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
620
+ return String(error);
621
+ }
622
+
623
+ exports.wrapBullQueue = wrapBullQueue;
624
+ exports.wrapBullWorker = wrapBullWorker;
@@ -0,0 +1,33 @@
1
+ interface BullQueueLike {
2
+ add: (name: string, data: unknown, opts?: unknown) => Promise<unknown>;
3
+ addBulk?: (jobs: Array<{
4
+ name: string;
5
+ data: unknown;
6
+ opts?: unknown;
7
+ }>) => Promise<unknown>;
8
+ name?: string;
9
+ }
10
+ interface BullWorkerLike {
11
+ on: (event: string, listener: (...args: unknown[]) => void) => unknown;
12
+ off?: (event: string, listener: (...args: unknown[]) => void) => unknown;
13
+ name?: string;
14
+ }
15
+ /**
16
+ * Patches `queue.add` (and `queue.addBulk` when present) so each
17
+ * enqueued job carries the current correlation id on its `data`.
18
+ * If `data` isn't a plain object, we stamp by wrapping it under a
19
+ * `payload` key — but adapters typically expect to read straight
20
+ * from `data`, so callers should pass plain objects when they want
21
+ * propagation to work. Documented in the README.
22
+ */
23
+ declare function wrapBullQueue<T extends BullQueueLike>(queue: T): T;
24
+ /**
25
+ * Subscribes capture listeners to a BullMQ Worker. Each completed /
26
+ * failed job emits one event. We use `attemptsMade` for retry_count
27
+ * (parity with Sidekiq's `retry_count`).
28
+ *
29
+ * Idempotent — calling on the same worker twice is a no-op.
30
+ */
31
+ declare function wrapBullWorker<T extends BullWorkerLike>(worker: T): T;
32
+
33
+ export { wrapBullQueue, wrapBullWorker };
@@ -0,0 +1,33 @@
1
+ interface BullQueueLike {
2
+ add: (name: string, data: unknown, opts?: unknown) => Promise<unknown>;
3
+ addBulk?: (jobs: Array<{
4
+ name: string;
5
+ data: unknown;
6
+ opts?: unknown;
7
+ }>) => Promise<unknown>;
8
+ name?: string;
9
+ }
10
+ interface BullWorkerLike {
11
+ on: (event: string, listener: (...args: unknown[]) => void) => unknown;
12
+ off?: (event: string, listener: (...args: unknown[]) => void) => unknown;
13
+ name?: string;
14
+ }
15
+ /**
16
+ * Patches `queue.add` (and `queue.addBulk` when present) so each
17
+ * enqueued job carries the current correlation id on its `data`.
18
+ * If `data` isn't a plain object, we stamp by wrapping it under a
19
+ * `payload` key — but adapters typically expect to read straight
20
+ * from `data`, so callers should pass plain objects when they want
21
+ * propagation to work. Documented in the README.
22
+ */
23
+ declare function wrapBullQueue<T extends BullQueueLike>(queue: T): T;
24
+ /**
25
+ * Subscribes capture listeners to a BullMQ Worker. Each completed /
26
+ * failed job emits one event. We use `attemptsMade` for retry_count
27
+ * (parity with Sidekiq's `retry_count`).
28
+ *
29
+ * Idempotent — calling on the same worker twice is a no-op.
30
+ */
31
+ declare function wrapBullWorker<T extends BullWorkerLike>(worker: T): T;
32
+
33
+ export { wrapBullQueue, wrapBullWorker };