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