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,622 @@
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
+ var CORRELATION_PAYLOAD_KEY = "ezlogs_correlation_id";
505
+ function emitJobEvent(input) {
506
+ try {
507
+ const config = configuration();
508
+ if (!config.captureJobs) return;
509
+ if (config.allExcludedJobClasses().includes(input.jobClass)) return;
510
+ const sourceData = compactJobSourceData({
511
+ job_class: input.jobClass,
512
+ job_id: input.jobId ?? null,
513
+ queue: input.queue ?? null,
514
+ retry_count: input.retryCount ?? null
515
+ });
516
+ const event = build({
517
+ source_type: "background_job",
518
+ source_data: sourceData,
519
+ outcome: input.outcome,
520
+ correlation_id: input.correlationId ?? current(),
521
+ resource_ids: [],
522
+ context: null,
523
+ duration_ms: input.durationMs ?? null,
524
+ error_message: input.errorMessage ?? null,
525
+ timestamp: input.startedAt
526
+ });
527
+ pushEvent(event);
528
+ } catch (error) {
529
+ logger.debug(`job emit failed: ${describeError(error)}`);
530
+ }
531
+ }
532
+ function extractCorrelationFromPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
533
+ if (payload === null || typeof payload !== "object") return null;
534
+ const value = payload[key];
535
+ return typeof value === "string" && value.length > 0 ? value : null;
536
+ }
537
+ function compactJobSourceData(data) {
538
+ const out = {};
539
+ for (const key of Object.keys(data)) {
540
+ const value = data[key];
541
+ if (value !== null && value !== void 0) out[key] = value;
542
+ }
543
+ return out;
544
+ }
545
+ function describeError(error) {
546
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
547
+ return String(error);
548
+ }
549
+
550
+ // src/jobs/trigger.ts
551
+ var REGISTERED_FLAG = "__ezlogsTriggerRegistered";
552
+ function registerTriggerHooks(tasks) {
553
+ if (tasks[REGISTERED_FLAG]) return;
554
+ if (typeof tasks.middleware !== "function") {
555
+ logger.debug("trigger.dev tasks.middleware not available \u2014 adapter not registered");
556
+ return;
557
+ }
558
+ tasks.middleware("ezlogs", async (params) => {
559
+ return runWithEzlogsCapture(params);
560
+ });
561
+ Object.defineProperty(tasks, REGISTERED_FLAG, {
562
+ value: true,
563
+ enumerable: false,
564
+ configurable: false
565
+ });
566
+ }
567
+ async function runWithEzlogsCapture(params) {
568
+ const ctx = params.ctx ?? {};
569
+ const taskId = ctx.task?.id ?? "trigger-task";
570
+ const runId = ctx.run?.id ?? null;
571
+ const queueName = ctx.run?.queue?.name ?? null;
572
+ const attemptNumber = ctx.attempt?.number ?? 1;
573
+ const retryCount = Math.max(0, attemptNumber - 1);
574
+ const correlationId = extractCorrelationFromPayload(params.payload) ?? generate();
575
+ return runWithCorrelation(correlationId, async () => {
576
+ const startedAt = /* @__PURE__ */ new Date();
577
+ const startMs = startedAt.getTime();
578
+ try {
579
+ const result = await params.next();
580
+ emitJobEvent({
581
+ jobClass: taskId,
582
+ jobId: runId,
583
+ queue: queueName,
584
+ retryCount,
585
+ correlationId,
586
+ outcome: "success",
587
+ durationMs: Date.now() - startMs,
588
+ startedAt
589
+ });
590
+ return result;
591
+ } catch (error) {
592
+ const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
593
+ emitJobEvent({
594
+ jobClass: taskId,
595
+ jobId: runId,
596
+ queue: queueName,
597
+ retryCount,
598
+ correlationId,
599
+ outcome: "failure",
600
+ errorMessage: message,
601
+ durationMs: Date.now() - startMs,
602
+ startedAt
603
+ });
604
+ throw error;
605
+ }
606
+ });
607
+ }
608
+ function stampPayloadForTrigger(payload) {
609
+ const id = current();
610
+ if (!id) return payload;
611
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
612
+ return payload;
613
+ }
614
+ const obj = payload;
615
+ if (typeof obj.ezlogs_correlation_id !== "string" || !obj.ezlogs_correlation_id) {
616
+ obj.ezlogs_correlation_id = id;
617
+ }
618
+ return obj;
619
+ }
620
+
621
+ exports.registerTriggerHooks = registerTriggerHooks;
622
+ exports.stampPayloadForTrigger = stampPayloadForTrigger;
@@ -0,0 +1,46 @@
1
+ interface TriggerTasksLike {
2
+ middleware?: (name: string, handler: (params: TriggerMiddlewareParams) => Promise<unknown>) => unknown;
3
+ }
4
+ interface TriggerMiddlewareParams {
5
+ payload: unknown;
6
+ ctx?: TriggerCtx;
7
+ next: () => Promise<unknown>;
8
+ }
9
+ interface TriggerCtx {
10
+ run?: {
11
+ id?: string;
12
+ queue?: {
13
+ name?: string;
14
+ };
15
+ };
16
+ task?: {
17
+ id?: string;
18
+ };
19
+ attempt?: {
20
+ number?: number;
21
+ };
22
+ }
23
+ /**
24
+ * Registers the EZLogs lifecycle hook on the user's `tasks` object.
25
+ *
26
+ * Pass the `tasks` import from `@trigger.dev/sdk/v3`. Idempotent.
27
+ */
28
+ declare function registerTriggerHooks(tasks: TriggerTasksLike): void;
29
+ /**
30
+ * Imperatively stamp the current correlation id onto a payload before
31
+ * calling tasks.trigger / batchTrigger. Trigger.dev doesn't expose a
32
+ * send-side middleware hook the way Inngest does, so users that want
33
+ * the upstream correlation propagated to a triggered task either:
34
+ * 1. Pass a payload that's a plain object (the agent's outgoing-
35
+ * fetch patch already injects X-Correlation-ID on the HTTP
36
+ * call to the Trigger.dev API server, but only the receiving
37
+ * task's middleware sees that — not the payload's data slot),
38
+ * OR
39
+ * 2. Call `stampPayloadForTrigger(payload)` themselves before
40
+ * invoking trigger().
41
+ *
42
+ * This helper exists for case 2.
43
+ */
44
+ declare function stampPayloadForTrigger(payload: unknown): unknown;
45
+
46
+ export { registerTriggerHooks, stampPayloadForTrigger };
@@ -0,0 +1,46 @@
1
+ interface TriggerTasksLike {
2
+ middleware?: (name: string, handler: (params: TriggerMiddlewareParams) => Promise<unknown>) => unknown;
3
+ }
4
+ interface TriggerMiddlewareParams {
5
+ payload: unknown;
6
+ ctx?: TriggerCtx;
7
+ next: () => Promise<unknown>;
8
+ }
9
+ interface TriggerCtx {
10
+ run?: {
11
+ id?: string;
12
+ queue?: {
13
+ name?: string;
14
+ };
15
+ };
16
+ task?: {
17
+ id?: string;
18
+ };
19
+ attempt?: {
20
+ number?: number;
21
+ };
22
+ }
23
+ /**
24
+ * Registers the EZLogs lifecycle hook on the user's `tasks` object.
25
+ *
26
+ * Pass the `tasks` import from `@trigger.dev/sdk/v3`. Idempotent.
27
+ */
28
+ declare function registerTriggerHooks(tasks: TriggerTasksLike): void;
29
+ /**
30
+ * Imperatively stamp the current correlation id onto a payload before
31
+ * calling tasks.trigger / batchTrigger. Trigger.dev doesn't expose a
32
+ * send-side middleware hook the way Inngest does, so users that want
33
+ * the upstream correlation propagated to a triggered task either:
34
+ * 1. Pass a payload that's a plain object (the agent's outgoing-
35
+ * fetch patch already injects X-Correlation-ID on the HTTP
36
+ * call to the Trigger.dev API server, but only the receiving
37
+ * task's middleware sees that — not the payload's data slot),
38
+ * OR
39
+ * 2. Call `stampPayloadForTrigger(payload)` themselves before
40
+ * invoking trigger().
41
+ *
42
+ * This helper exists for case 2.
43
+ */
44
+ declare function stampPayloadForTrigger(payload: unknown): unknown;
45
+
46
+ export { registerTriggerHooks, stampPayloadForTrigger };