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,645 @@
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/inngest.ts
551
+ function ezlogsInngestMiddleware() {
552
+ return {
553
+ name: "ezlogs-nextjs",
554
+ init() {
555
+ return {
556
+ // Hook called once per function run (e.g. one trigger fires
557
+ // one function). Returns per-run hooks that fire as the run
558
+ // proceeds. We track the run via closure-scoped state.
559
+ onFunctionRun(args) {
560
+ const fnId = args.fn?.id ?? "inngest-function";
561
+ const runId = args.ctx?.runId ?? null;
562
+ const attempt = typeof args.ctx?.attempt === "number" ? args.ctx.attempt : 0;
563
+ const eventName = args.ctx?.event?.name ?? null;
564
+ const correlationId = extractCorrelationFromPayload(args.ctx?.event?.data) ?? generate();
565
+ const startedAt = /* @__PURE__ */ new Date();
566
+ const startMs = startedAt.getTime();
567
+ return {
568
+ // Inngest calls this once after the function body returns
569
+ // (success) or throws (failure surfaces via result.error).
570
+ transformOutput(args2) {
571
+ try {
572
+ const result = args2.result;
573
+ const error = result?.error;
574
+ const outcome = error ? "failure" : "success";
575
+ const errorMessage = error ? formatError(error) : null;
576
+ emitJobEvent({
577
+ jobClass: fnId,
578
+ jobId: runId,
579
+ queue: eventName,
580
+ retryCount: attempt,
581
+ correlationId,
582
+ outcome,
583
+ errorMessage,
584
+ durationMs: Date.now() - startMs,
585
+ startedAt
586
+ });
587
+ } catch (error) {
588
+ logger.debug(`inngest capture failed: ${describeError2(error)}`);
589
+ }
590
+ }
591
+ };
592
+ },
593
+ // Hook called when a user calls inngest.send(...). Stamp the
594
+ // current correlation id on the event payload so the
595
+ // downstream function's onFunctionRun can read it back.
596
+ onSendEvent() {
597
+ return {
598
+ transformInput(args) {
599
+ try {
600
+ const id = current();
601
+ if (!id) return;
602
+ if (!Array.isArray(args.payloads)) return;
603
+ for (const payload of args.payloads) {
604
+ if (!payload || typeof payload !== "object") continue;
605
+ const data = payload.data ?? {};
606
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
607
+ continue;
608
+ }
609
+ if (typeof data.ezlogs_correlation_id === "string") {
610
+ continue;
611
+ }
612
+ data.ezlogs_correlation_id = id;
613
+ payload.data = data;
614
+ }
615
+ } catch (error) {
616
+ logger.debug(`inngest send-stamp failed: ${describeError2(error)}`);
617
+ }
618
+ }
619
+ };
620
+ }
621
+ };
622
+ }
623
+ };
624
+ }
625
+ async function runInsideInngestCorrelation(event, callback) {
626
+ const id = extractCorrelationFromPayload(event?.data) ?? generate();
627
+ return runWithCorrelation(id, callback);
628
+ }
629
+ function formatError(error) {
630
+ if (error instanceof Error) {
631
+ return `${error.name ?? "Error"}: ${error.message ?? String(error)}`;
632
+ }
633
+ if (typeof error === "object" && error !== null) {
634
+ const err = error;
635
+ return `${err.name ?? "Error"}: ${err.message ?? JSON.stringify(error)}`;
636
+ }
637
+ return String(error);
638
+ }
639
+ function describeError2(error) {
640
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
641
+ return String(error);
642
+ }
643
+
644
+ exports.ezlogsInngestMiddleware = ezlogsInngestMiddleware;
645
+ exports.runInsideInngestCorrelation = runInsideInngestCorrelation;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Returns an Inngest middleware object. Pass it via:
3
+ * new Inngest({ middleware: [ezlogsInngestMiddleware()] })
4
+ *
5
+ * Returned `unknown` because Inngest's `Middleware` type is parameterized
6
+ * over the client and we don't want to take a hard type dep.
7
+ */
8
+ declare function ezlogsInngestMiddleware(): unknown;
9
+ /**
10
+ * Helper for users who need to run downstream code inside the
11
+ * correlation scope of an Inngest run (e.g. arbitrary work outside
12
+ * the agent's automatic capture). Wraps a callback in
13
+ * runWithCorrelation using the id extracted from an event's data.
14
+ *
15
+ * Most users won't need this — the middleware handles the common case.
16
+ */
17
+ declare function runInsideInngestCorrelation<T>(event: {
18
+ data?: unknown;
19
+ } | undefined, callback: () => Promise<T>): Promise<T>;
20
+
21
+ export { ezlogsInngestMiddleware, runInsideInngestCorrelation };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Returns an Inngest middleware object. Pass it via:
3
+ * new Inngest({ middleware: [ezlogsInngestMiddleware()] })
4
+ *
5
+ * Returned `unknown` because Inngest's `Middleware` type is parameterized
6
+ * over the client and we don't want to take a hard type dep.
7
+ */
8
+ declare function ezlogsInngestMiddleware(): unknown;
9
+ /**
10
+ * Helper for users who need to run downstream code inside the
11
+ * correlation scope of an Inngest run (e.g. arbitrary work outside
12
+ * the agent's automatic capture). Wraps a callback in
13
+ * runWithCorrelation using the id extracted from an event's data.
14
+ *
15
+ * Most users won't need this — the middleware handles the common case.
16
+ */
17
+ declare function runInsideInngestCorrelation<T>(event: {
18
+ data?: unknown;
19
+ } | undefined, callback: () => Promise<T>): Promise<T>;
20
+
21
+ export { ezlogsInngestMiddleware, runInsideInngestCorrelation };