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,673 @@
1
+ 'use strict';
2
+
3
+ var crypto = 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 generate() {
492
+ const ts = Date.now();
493
+ const hex = crypto.randomBytes(4).toString("hex");
494
+ return `ezl_${ts}_${hex}`;
495
+ }
496
+ function current() {
497
+ return storage.read();
498
+ }
499
+ function runWithCorrelation(correlationId, callback) {
500
+ return storage.run(correlationId, callback);
501
+ }
502
+
503
+ // src/jobs/shared.ts
504
+ function emitJobEvent(input) {
505
+ try {
506
+ const config = configuration();
507
+ if (!config.captureJobs) return;
508
+ if (config.allExcludedJobClasses().includes(input.jobClass)) return;
509
+ const sourceData = compactJobSourceData({
510
+ job_class: input.jobClass,
511
+ job_id: input.jobId ?? null,
512
+ queue: input.queue ?? null,
513
+ retry_count: input.retryCount ?? null
514
+ });
515
+ const event = build({
516
+ source_type: "background_job",
517
+ source_data: sourceData,
518
+ outcome: input.outcome,
519
+ correlation_id: input.correlationId ?? current(),
520
+ resource_ids: [],
521
+ context: null,
522
+ duration_ms: input.durationMs ?? null,
523
+ error_message: input.errorMessage ?? null,
524
+ timestamp: input.startedAt
525
+ });
526
+ pushEvent(event);
527
+ } catch (error) {
528
+ logger.debug(`job emit failed: ${describeError(error)}`);
529
+ }
530
+ }
531
+ async function runJobWithCapture(meta, work) {
532
+ const correlationId = meta.correlationId ?? generate();
533
+ return runWithCorrelation(correlationId, async () => {
534
+ const startedAt = /* @__PURE__ */ new Date();
535
+ const startMs = startedAt.getTime();
536
+ const baseMeta = {
537
+ jobClass: meta.jobClass,
538
+ jobId: meta.jobId ?? null,
539
+ queue: meta.queue ?? null,
540
+ retryCount: meta.retryCount ?? null,
541
+ correlationId,
542
+ startedAt
543
+ };
544
+ try {
545
+ const result = await work();
546
+ emitJobEvent({
547
+ ...baseMeta,
548
+ outcome: "success",
549
+ durationMs: Date.now() - startMs
550
+ });
551
+ return result;
552
+ } catch (error) {
553
+ const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
554
+ emitJobEvent({
555
+ ...baseMeta,
556
+ outcome: "failure",
557
+ errorMessage: message,
558
+ durationMs: Date.now() - startMs
559
+ });
560
+ throw error;
561
+ }
562
+ });
563
+ }
564
+ function compactJobSourceData(data) {
565
+ const out = {};
566
+ for (const key of Object.keys(data)) {
567
+ const value = data[key];
568
+ if (value !== null && value !== void 0) out[key] = value;
569
+ }
570
+ return out;
571
+ }
572
+ function describeError(error) {
573
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
574
+ return String(error);
575
+ }
576
+
577
+ // src/jobs/upstash-workflow.ts
578
+ var FORWARD_PREFIX = "upstash-forward-";
579
+ var WRAPPED_FLAG = "__ezlogsUpstashQStashWrapped";
580
+ function wrapQStashClient(client) {
581
+ if (client[WRAPPED_FLAG]) return client;
582
+ if (typeof client.publishJSON === "function") {
583
+ const original = client.publishJSON.bind(client);
584
+ const wrapped = (request) => original(stampPublishRequest(request));
585
+ client.publishJSON = wrapped;
586
+ }
587
+ if (typeof client.publish === "function") {
588
+ const original = client.publish.bind(client);
589
+ const wrapped = (request) => original(stampPublishRequest(request));
590
+ client.publish = wrapped;
591
+ }
592
+ Object.defineProperty(client, WRAPPED_FLAG, {
593
+ value: true,
594
+ enumerable: false,
595
+ configurable: false
596
+ });
597
+ return client;
598
+ }
599
+ function stampPublishRequest(request) {
600
+ const id = current();
601
+ if (!id) return request;
602
+ const headerKey = `${FORWARD_PREFIX}x-correlation-id`;
603
+ const headers = { ...request.headers ?? {} };
604
+ const lower = Object.keys(headers).reduce(
605
+ (acc, key) => {
606
+ acc[key.toLowerCase()] = key;
607
+ return acc;
608
+ },
609
+ {}
610
+ );
611
+ if (lower[headerKey]) return request;
612
+ headers[headerKey] = id;
613
+ return { ...request, headers };
614
+ }
615
+ async function captureWorkflowRequest(meta, work) {
616
+ const headers = meta.request.headers;
617
+ const correlationId = readCorrelationFromHeaders(headers);
618
+ const runId = readHeader(headers, "upstash-workflow-runid");
619
+ const retried = parseRetried(readHeader(headers, "upstash-retried"));
620
+ return runJobWithCapture(
621
+ {
622
+ jobClass: meta.workflowName,
623
+ jobId: runId,
624
+ queue: meta.stepName ?? meta.workflowName,
625
+ retryCount: retried,
626
+ correlationId
627
+ },
628
+ work
629
+ );
630
+ }
631
+ function emitUpstashWorkflowEvent(input) {
632
+ try {
633
+ const headers = input.request.headers;
634
+ emitJobEvent({
635
+ jobClass: input.workflowName,
636
+ jobId: readHeader(headers, "upstash-workflow-runid"),
637
+ queue: input.workflowName,
638
+ retryCount: parseRetried(readHeader(headers, "upstash-retried")),
639
+ correlationId: readCorrelationFromHeaders(headers),
640
+ outcome: input.outcome,
641
+ errorMessage: input.errorMessage ?? null,
642
+ durationMs: input.durationMs ?? null,
643
+ startedAt: input.startedAt ?? /* @__PURE__ */ new Date()
644
+ });
645
+ } catch (error) {
646
+ logger.debug(`upstash workflow capture failed: ${describeError2(error)}`);
647
+ }
648
+ }
649
+ function readHeader(headers, name) {
650
+ try {
651
+ const value = headers.get(name);
652
+ return typeof value === "string" && value.length > 0 ? value : null;
653
+ } catch {
654
+ return null;
655
+ }
656
+ }
657
+ function readCorrelationFromHeaders(headers) {
658
+ return readHeader(headers, "x-correlation-id") ?? readHeader(headers, "upstash-forward-x-correlation-id");
659
+ }
660
+ function parseRetried(value) {
661
+ if (value === null) return null;
662
+ const parsed = Number(value);
663
+ if (!Number.isFinite(parsed) || parsed < 0) return null;
664
+ return parsed;
665
+ }
666
+ function describeError2(error) {
667
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
668
+ return String(error);
669
+ }
670
+
671
+ exports.captureWorkflowRequest = captureWorkflowRequest;
672
+ exports.emitUpstashWorkflowEvent = emitUpstashWorkflowEvent;
673
+ exports.wrapQStashClient = wrapQStashClient;