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
package/dist/index.js ADDED
@@ -0,0 +1,3317 @@
1
+ import { randomBytes, createHash } from 'crypto';
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
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
+ var __esm = (fn, res) => function __init() {
12
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
13
+ };
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+
19
+ // src/configuration.ts
20
+ function configuration() {
21
+ const g = globalThis;
22
+ if (!g[GLOBAL_CONFIG_KEY]) {
23
+ g[GLOBAL_CONFIG_KEY] = new Configuration();
24
+ }
25
+ return g[GLOBAL_CONFIG_KEY];
26
+ }
27
+ var DEFAULT_EXCLUDED_PATHS, DEFAULT_EXCLUDED_EXTENSIONS, DEFAULT_EXCLUDED_TABLES, DEFAULT_EXCLUDED_JOB_CLASSES, DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, DEFAULT_SERVER_URL, Configuration, GLOBAL_CONFIG_KEY;
28
+ var init_configuration = __esm({
29
+ "src/configuration.ts"() {
30
+ DEFAULT_EXCLUDED_PATHS = Object.freeze([
31
+ // Next.js / Vercel infrastructure noise
32
+ "/_next/*",
33
+ "/_vercel/*",
34
+ "/__nextjs_*",
35
+ // NextAuth.js / Auth.js — skip session-refresh polls and CSRF/provider
36
+ // metadata GETs (high-frequency, no business meaning), but CAPTURE
37
+ // POSTs (callbacks, signin, signout, register). The POSTs are the
38
+ // actual auth events users care about; the GETs are pure plumbing.
39
+ Object.freeze({ path: "/api/auth/*", methods: ["GET", "HEAD"] }),
40
+ // Generic infrastructure
41
+ "/health*",
42
+ "/api/health",
43
+ "/up",
44
+ "/alive",
45
+ "/ready",
46
+ "/metrics",
47
+ "/favicon.ico",
48
+ "/.well-known*",
49
+ "/robots.txt",
50
+ "/sitemap.xml",
51
+ "/*.hot-update.*",
52
+ // Auth routes (common patterns across Clerk, NextAuth, custom auth)
53
+ "*/login*",
54
+ "*/logout*",
55
+ "*/sign-in*",
56
+ "*/sign-out*",
57
+ "*/signin*",
58
+ "*/signout*",
59
+ "/session*"
60
+ ]);
61
+ DEFAULT_EXCLUDED_EXTENSIONS = Object.freeze([
62
+ ".js",
63
+ ".css",
64
+ ".map",
65
+ ".png",
66
+ ".jpg",
67
+ ".jpeg",
68
+ ".gif",
69
+ ".svg",
70
+ ".ico",
71
+ ".webp",
72
+ ".woff",
73
+ ".woff2",
74
+ ".ttf",
75
+ ".eot",
76
+ ".otf"
77
+ ]);
78
+ DEFAULT_EXCLUDED_TABLES = Object.freeze([
79
+ // Prisma migration ledger
80
+ "_prisma_migrations",
81
+ // Auth.js / NextAuth Prisma adapter — session/verification-token churn
82
+ // is auth machinery, not business activity. Account/User stay captured.
83
+ "Session",
84
+ "VerificationToken",
85
+ // Common cross-stack convention names for the same things
86
+ "sessions",
87
+ "session",
88
+ "verification_tokens"
89
+ ]);
90
+ DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
91
+ DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
92
+ DEFAULT_SERVER_URL = "https://app.ezlogs.io";
93
+ Configuration = class {
94
+ serverUrl = DEFAULT_SERVER_URL;
95
+ projectToken = null;
96
+ captureHttp = true;
97
+ captureDb = true;
98
+ captureJobs = true;
99
+ bufferSize = 1e4;
100
+ /** Default 3000 ms — equivalent to Ruby's 3 seconds. */
101
+ sendInterval = 3e3;
102
+ retryAttempts = 3;
103
+ logLevel = "warn";
104
+ patchGlobalFetch = true;
105
+ actorFromSupabase = true;
106
+ excludedPaths = [];
107
+ excludedTables = [];
108
+ excludedJobClasses = [];
109
+ excludedGraphqlOperations = [];
110
+ excludedGraphqlVariableKeys = [];
111
+ actorFromRequest = null;
112
+ displayNameFor = {};
113
+ isServerActionError = null;
114
+ databaseReader = null;
115
+ databaseSnapshotMode = false;
116
+ databaseUrl = null;
117
+ /**
118
+ * Tables that have the `ezlogs_audit` trigger attached. Detected once
119
+ * at agent startup by reading `information_schema.triggers`. The
120
+ * supabase / drizzle / prisma adapters use this to decide whether
121
+ * their per-mutation emit is redundant: if the table is trigger-
122
+ * tracked the audit-log reader will surface the same write with full
123
+ * old/new state, so the adapter's emit is suppressed. Tables NOT in
124
+ * this set fall through to the adapter so they're still captured.
125
+ *
126
+ * `null` means "detection hasn't run yet or failed" — in that state
127
+ * `databaseReader`-wired apps suppress every adapter emit (the
128
+ * original Phase 5 behavior). After detection completes the agent
129
+ * gives the more accurate per-table answer.
130
+ */
131
+ triggerTrackedTables = null;
132
+ apply(options) {
133
+ if (options.serverUrl !== void 0) this.serverUrl = options.serverUrl;
134
+ this.projectToken = options.projectToken;
135
+ if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
136
+ if (options.captureDb !== void 0) this.captureDb = options.captureDb;
137
+ if (options.captureJobs !== void 0) this.captureJobs = options.captureJobs;
138
+ if (options.bufferSize !== void 0) this.bufferSize = options.bufferSize;
139
+ if (options.sendInterval !== void 0) this.sendInterval = options.sendInterval;
140
+ if (options.retryAttempts !== void 0) this.retryAttempts = options.retryAttempts;
141
+ if (options.excludedPaths) this.excludedPaths = [...options.excludedPaths];
142
+ if (options.excludedTables) this.excludedTables = [...options.excludedTables];
143
+ if (options.excludedJobClasses) {
144
+ this.excludedJobClasses = [...options.excludedJobClasses];
145
+ }
146
+ if (options.excludedGraphqlOperations) {
147
+ this.excludedGraphqlOperations = [...options.excludedGraphqlOperations];
148
+ }
149
+ if (options.excludedGraphqlVariableKeys) {
150
+ this.excludedGraphqlVariableKeys = [...options.excludedGraphqlVariableKeys];
151
+ }
152
+ if (options.actorFromRequest) this.actorFromRequest = options.actorFromRequest;
153
+ if (options.displayNameFor) this.displayNameFor = { ...options.displayNameFor };
154
+ if (options.isServerActionError) this.isServerActionError = options.isServerActionError;
155
+ if (options.patchGlobalFetch !== void 0) {
156
+ this.patchGlobalFetch = options.patchGlobalFetch;
157
+ }
158
+ if (options.actorFromSupabase !== void 0) {
159
+ this.actorFromSupabase = options.actorFromSupabase;
160
+ }
161
+ if (options.databaseReader !== void 0) {
162
+ this.databaseReader = options.databaseReader;
163
+ }
164
+ if (options.databaseSnapshotMode !== void 0) {
165
+ this.databaseSnapshotMode = options.databaseSnapshotMode;
166
+ }
167
+ if (options.databaseUrl !== void 0) {
168
+ this.databaseUrl = options.databaseUrl;
169
+ }
170
+ if (options.logLevel) this.logLevel = options.logLevel;
171
+ }
172
+ allExcludedPaths() {
173
+ return [...DEFAULT_EXCLUDED_PATHS, ...this.excludedPaths];
174
+ }
175
+ allExcludedTables() {
176
+ return [...DEFAULT_EXCLUDED_TABLES, ...this.excludedTables];
177
+ }
178
+ allExcludedJobClasses() {
179
+ return [...DEFAULT_EXCLUDED_JOB_CLASSES, ...this.excludedJobClasses];
180
+ }
181
+ allExcludedGraphqlOperations() {
182
+ return [...DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, ...this.excludedGraphqlOperations];
183
+ }
184
+ };
185
+ GLOBAL_CONFIG_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:configuration");
186
+ }
187
+ });
188
+
189
+ // src/logger.ts
190
+ function readLevel() {
191
+ const g = globalThis;
192
+ return g[LEVEL_KEY] ?? "warn";
193
+ }
194
+ function setLogLevel(level) {
195
+ globalThis[LEVEL_KEY] = level;
196
+ }
197
+ function shouldLog(level) {
198
+ return LEVEL_RANK[level] >= LEVEL_RANK[readLevel()];
199
+ }
200
+ function safeWrite(level, message) {
201
+ try {
202
+ if (!shouldLog(level)) return;
203
+ const line = `[ezlogs] ${message}`;
204
+ if (level === "error" || level === "warn") {
205
+ console.error(line);
206
+ } else {
207
+ console.log(line);
208
+ }
209
+ } catch {
210
+ }
211
+ }
212
+ var LEVEL_RANK, LEVEL_KEY, logger;
213
+ var init_logger = __esm({
214
+ "src/logger.ts"() {
215
+ LEVEL_RANK = {
216
+ debug: 10,
217
+ info: 20,
218
+ warn: 30,
219
+ error: 40,
220
+ silent: 100
221
+ };
222
+ LEVEL_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:log-level");
223
+ logger = {
224
+ debug: (message) => safeWrite("debug", message),
225
+ info: (message) => safeWrite("info", message),
226
+ warn: (message) => safeWrite("warn", message),
227
+ error: (message) => safeWrite("error", message)
228
+ };
229
+ }
230
+ });
231
+
232
+ // src/pipeline/buffer.ts
233
+ var buffer_exports = {};
234
+ __export(buffer_exports, {
235
+ bufferSize: () => bufferSize,
236
+ clearBuffer: () => clearBuffer,
237
+ drainEvents: () => drainEvents,
238
+ pushEvent: () => pushEvent
239
+ });
240
+ function getQueue() {
241
+ const g = globalThis;
242
+ if (!g[GLOBAL_QUEUE_KEY]) g[GLOBAL_QUEUE_KEY] = [];
243
+ return g[GLOBAL_QUEUE_KEY];
244
+ }
245
+ function pushEvent(event) {
246
+ try {
247
+ const queue = getQueue();
248
+ const max = maxSize();
249
+ if (queue.length >= max) {
250
+ queue.shift();
251
+ logger.warn(`Buffer full (${max}), dropped oldest event`);
252
+ }
253
+ queue.push(event);
254
+ } catch (error) {
255
+ logger.error(`pushEvent failed: ${describe(error)}`);
256
+ }
257
+ }
258
+ function drainEvents() {
259
+ try {
260
+ const queue = getQueue();
261
+ if (queue.length === 0) return [];
262
+ return queue.splice(0, queue.length);
263
+ } catch (error) {
264
+ logger.error(`drainEvents failed: ${describe(error)}`);
265
+ return [];
266
+ }
267
+ }
268
+ function bufferSize() {
269
+ return getQueue().length;
270
+ }
271
+ function clearBuffer() {
272
+ const queue = getQueue();
273
+ queue.length = 0;
274
+ }
275
+ function maxSize() {
276
+ try {
277
+ return configuration().bufferSize;
278
+ } catch {
279
+ return 1e4;
280
+ }
281
+ }
282
+ function describe(error) {
283
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
284
+ return String(error);
285
+ }
286
+ var GLOBAL_QUEUE_KEY;
287
+ var init_buffer = __esm({
288
+ "src/pipeline/buffer.ts"() {
289
+ init_configuration();
290
+ init_logger();
291
+ GLOBAL_QUEUE_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:buffer-queue");
292
+ }
293
+ });
294
+
295
+ // src/edge-fallback.ts
296
+ function loadAsyncLocalStorage() {
297
+ const fromGlobal = globalThis.AsyncLocalStorage;
298
+ if (typeof fromGlobal === "function") return fromGlobal;
299
+ try {
300
+ const req = typeof __require !== "undefined" ? __require : (
301
+ // In ESM, `createRequire` is the official escape hatch.
302
+ // We pull it via globalThis to avoid a static `import`
303
+ // that would itself be browser-bundled.
304
+ void 0
305
+ );
306
+ if (typeof req === "function") {
307
+ const moduleName = ["async", "hooks"].join("_");
308
+ const mod = req("node:" + moduleName);
309
+ if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
310
+ }
311
+ } catch {
312
+ }
313
+ return null;
314
+ }
315
+ function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
316
+ const globalStore = globalThis;
317
+ let entry = globalStore[key];
318
+ if (!entry) {
319
+ const als2 = (() => {
320
+ if (!ALS_CTOR) return null;
321
+ try {
322
+ return new ALS_CTOR();
323
+ } catch {
324
+ return null;
325
+ }
326
+ })();
327
+ entry = { als: als2, edgeFallback: null };
328
+ globalStore[key] = entry;
329
+ }
330
+ const als = entry.als;
331
+ const stateRef = entry;
332
+ return {
333
+ read() {
334
+ if (als) return als.getStore()?.value ?? null;
335
+ return stateRef.edgeFallback?.value ?? null;
336
+ },
337
+ run(value, callback) {
338
+ if (als) return als.run({ value }, callback);
339
+ const previous = stateRef.edgeFallback;
340
+ stateRef.edgeFallback = { value };
341
+ try {
342
+ return callback();
343
+ } finally {
344
+ stateRef.edgeFallback = previous;
345
+ }
346
+ },
347
+ update(value) {
348
+ if (als) {
349
+ const store = als.getStore();
350
+ if (store) store.value = value;
351
+ return;
352
+ }
353
+ stateRef.edgeFallback = { value };
354
+ },
355
+ _resetForTests() {
356
+ stateRef.edgeFallback = null;
357
+ },
358
+ _isAsyncLocalStorage() {
359
+ return als !== null;
360
+ }
361
+ };
362
+ }
363
+ var ALS_CTOR;
364
+ var init_edge_fallback = __esm({
365
+ "src/edge-fallback.ts"() {
366
+ ALS_CTOR = loadAsyncLocalStorage();
367
+ }
368
+ });
369
+ function generate() {
370
+ const ts = Date.now();
371
+ const hex = randomBytes(4).toString("hex");
372
+ return `ezl_${ts}_${hex}`;
373
+ }
374
+ function resolveCorrelation(headers) {
375
+ if (!headers) return generate();
376
+ const ezlogs2 = safeRead(headers, CORRELATION_HEADER);
377
+ if (ezlogs2) return ezlogs2;
378
+ for (const name of PLATFORM_REQUEST_ID_HEADERS) {
379
+ const platformId = safeRead(headers, name);
380
+ if (platformId) return wrapPlatformId(platformId);
381
+ }
382
+ return generate();
383
+ }
384
+ function safeRead(headers, name) {
385
+ try {
386
+ const value = headers.get(name);
387
+ return typeof value === "string" && value.length > 0 ? value : null;
388
+ } catch {
389
+ return null;
390
+ }
391
+ }
392
+ function wrapPlatformId(platformId) {
393
+ const ts = Date.now();
394
+ const hex = createHash("sha1").update(platformId).digest("hex").slice(0, 8);
395
+ return `ezl_${ts}_${hex}`;
396
+ }
397
+ function current() {
398
+ return storage.read();
399
+ }
400
+ function runWithCorrelation(correlationId, callback) {
401
+ return storage.run(correlationId, callback);
402
+ }
403
+ var CORRELATION_HEADER, PLATFORM_REQUEST_ID_HEADERS, storage;
404
+ var init_correlation = __esm({
405
+ "src/correlation.ts"() {
406
+ init_edge_fallback();
407
+ CORRELATION_HEADER = "x-ezlogs-correlation-id";
408
+ PLATFORM_REQUEST_ID_HEADERS = [
409
+ "x-vercel-id",
410
+ "cf-ray",
411
+ "x-request-id"
412
+ ];
413
+ storage = createScopedStorage(
414
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
415
+ );
416
+ }
417
+ });
418
+
419
+ // src/actor.ts
420
+ function getCurrentActor() {
421
+ return storage2.read();
422
+ }
423
+ function setActor(input) {
424
+ const sanitized = validateActor(input);
425
+ if (input != null && sanitized === null) {
426
+ logger.debug(`Actor: invalid actor structure ignored: ${describe2(input)}`);
427
+ }
428
+ storage2.update(sanitized);
429
+ return sanitized;
430
+ }
431
+ function runWithActorScope(callback) {
432
+ return storage2.run(null, callback);
433
+ }
434
+ function validateActor(input) {
435
+ if (input === null || input === void 0) return null;
436
+ if (typeof input !== "object") return null;
437
+ if (Array.isArray(input)) return null;
438
+ const obj = input;
439
+ const rawId = obj.id;
440
+ if (rawId === null || rawId === void 0) return null;
441
+ const id = String(rawId);
442
+ if (id === "") return null;
443
+ const result = { id };
444
+ if (obj.label !== void 0 && obj.label !== null) {
445
+ result.label = String(obj.label);
446
+ }
447
+ return result;
448
+ }
449
+ function describe2(value) {
450
+ try {
451
+ return JSON.stringify(value);
452
+ } catch {
453
+ return Object.prototype.toString.call(value);
454
+ }
455
+ }
456
+ var storage2;
457
+ var init_actor = __esm({
458
+ "src/actor.ts"() {
459
+ init_logger();
460
+ init_edge_fallback();
461
+ storage2 = createScopedStorage(
462
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-storage")
463
+ );
464
+ }
465
+ });
466
+
467
+ // src/event-builder.ts
468
+ function build(input) {
469
+ const source_type = validateSourceType(input.source_type);
470
+ const source_data_raw = validateSourceData(input.source_data);
471
+ const outcome = validateOutcome(input.outcome);
472
+ const timestamp = validateTimestamp(input.timestamp ?? null);
473
+ const resource_ids = validateResourceIds(input.resource_ids ?? []);
474
+ const context_raw = validateContext(input.context ?? null);
475
+ const duration_ms = validateDurationMs(input.duration_ms ?? null);
476
+ const error_message = input.error_message ?? null;
477
+ validateOutcomeErrorConsistency(outcome, error_message);
478
+ const source_data = sanitizeRecord(source_data_raw);
479
+ const context = context_raw === null ? null : sanitizeRecord(context_raw);
480
+ const correlation_id = input.correlation_id ?? null;
481
+ const event = {
482
+ timestamp,
483
+ source_type,
484
+ source_data,
485
+ outcome,
486
+ correlation_id,
487
+ resource_ids,
488
+ context,
489
+ duration_ms,
490
+ error_message
491
+ };
492
+ return event;
493
+ }
494
+ function validateSourceType(value) {
495
+ if (value === null || value === void 0) {
496
+ throw new ArgError("source_type is required");
497
+ }
498
+ const normalized = String(value);
499
+ if (!VALID_SOURCE_TYPES.includes(normalized)) {
500
+ throw new ArgError(
501
+ `source_type must be one of ${VALID_SOURCE_TYPES.join(", ")}, got: ${normalized}`
502
+ );
503
+ }
504
+ return normalized;
505
+ }
506
+ function validateSourceData(value) {
507
+ if (value === null || value === void 0) {
508
+ throw new ArgError("source_data is required");
509
+ }
510
+ if (!isPlainObject(value)) {
511
+ throw new ArgError(
512
+ `source_data must be an object, got: ${describe3(value)}`
513
+ );
514
+ }
515
+ return value;
516
+ }
517
+ function validateOutcome(value) {
518
+ if (value === null || value === void 0) {
519
+ throw new ArgError("outcome is required");
520
+ }
521
+ const normalized = String(value);
522
+ if (!VALID_OUTCOMES.includes(normalized)) {
523
+ throw new ArgError(
524
+ `outcome must be one of ${VALID_OUTCOMES.join(", ")}, got: ${normalized}`
525
+ );
526
+ }
527
+ return normalized;
528
+ }
529
+ function validateTimestamp(value) {
530
+ if (value === null) {
531
+ return (/* @__PURE__ */ new Date()).toISOString();
532
+ }
533
+ if (typeof value === "string") {
534
+ const parsed = new Date(value);
535
+ if (Number.isNaN(parsed.getTime())) {
536
+ throw new ArgError(
537
+ `timestamp must be valid ISO 8601 format, got: ${value}`
538
+ );
539
+ }
540
+ return value;
541
+ }
542
+ if (value instanceof Date) {
543
+ if (Number.isNaN(value.getTime())) {
544
+ throw new ArgError("timestamp must be a valid Date");
545
+ }
546
+ return value.toISOString();
547
+ }
548
+ throw new ArgError(
549
+ `timestamp must be a string or Date, got: ${describe3(value)}`
550
+ );
551
+ }
552
+ function validateResourceIds(value) {
553
+ if (!Array.isArray(value)) {
554
+ throw new ArgError(`resource_ids must be an array, got: ${describe3(value)}`);
555
+ }
556
+ value.forEach((entry, index) => {
557
+ if (!isPlainObject(entry)) {
558
+ throw new ArgError(
559
+ `resource_ids[${index}] must be an object, got: ${describe3(entry)}`
560
+ );
561
+ }
562
+ const e = entry;
563
+ if (!("resource_type" in e) || !("resource_id" in e)) {
564
+ throw new ArgError(
565
+ `resource_ids[${index}] must have resource_type and resource_id keys, got: ${Object.keys(e).join(", ")}`
566
+ );
567
+ }
568
+ if (typeof e.resource_type !== "string") {
569
+ throw new ArgError(
570
+ `resource_ids[${index}].resource_type must be a string, got: ${describe3(e.resource_type)}`
571
+ );
572
+ }
573
+ if (typeof e.resource_id !== "string") {
574
+ throw new ArgError(
575
+ `resource_ids[${index}].resource_id must be a string, got: ${describe3(e.resource_id)}`
576
+ );
577
+ }
578
+ });
579
+ return value;
580
+ }
581
+ function validateContext(value) {
582
+ if (value === null) return null;
583
+ if (!isPlainObject(value)) {
584
+ throw new ArgError(
585
+ `context must be an object or null, got: ${describe3(value)}`
586
+ );
587
+ }
588
+ return value;
589
+ }
590
+ function validateDurationMs(value) {
591
+ if (value === null || value === void 0) return null;
592
+ if (typeof value !== "number" || !Number.isFinite(value)) {
593
+ throw new ArgError(`duration_ms must be a number, got: ${describe3(value)}`);
594
+ }
595
+ if (!Number.isInteger(value)) {
596
+ throw new ArgError(`duration_ms must be an integer, got: ${value}`);
597
+ }
598
+ if (value < 0) {
599
+ throw new ArgError(`duration_ms must be >= 0, got: ${value}`);
600
+ }
601
+ return value;
602
+ }
603
+ function validateOutcomeErrorConsistency(outcome, error_message) {
604
+ if (outcome === "failure") {
605
+ if (error_message === null || error_message === "") {
606
+ throw new ArgError("error_message is required when outcome is 'failure'");
607
+ }
608
+ } else if (outcome === "success") {
609
+ if (error_message !== null) {
610
+ throw new ArgError("error_message must be null when outcome is 'success'");
611
+ }
612
+ }
613
+ }
614
+ function sanitizeRecord(input) {
615
+ const result = {};
616
+ for (const key of Object.keys(input)) {
617
+ const value = input[key];
618
+ if (isSensitiveKey(key)) {
619
+ result[key] = "[FILTERED]";
620
+ } else if (isPlainObject(value)) {
621
+ result[key] = sanitizeRecord(value);
622
+ } else if (Array.isArray(value)) {
623
+ result[key] = value.map(
624
+ (item) => isPlainObject(item) ? sanitizeRecord(item) : item
625
+ );
626
+ } else {
627
+ result[key] = value;
628
+ }
629
+ }
630
+ return result;
631
+ }
632
+ function isSensitiveKey(key) {
633
+ const lower = key.toLowerCase();
634
+ return SENSITIVE_KEYS.some((p) => lower.includes(p));
635
+ }
636
+ function isPlainObject(value) {
637
+ if (value === null || typeof value !== "object") return false;
638
+ const proto = Object.getPrototypeOf(value);
639
+ return proto === Object.prototype || proto === null;
640
+ }
641
+ function describe3(value) {
642
+ if (value === null) return "null";
643
+ if (Array.isArray(value)) return "Array";
644
+ return typeof value;
645
+ }
646
+ var SENSITIVE_KEYS, VALID_SOURCE_TYPES, VALID_OUTCOMES, ArgError;
647
+ var init_event_builder = __esm({
648
+ "src/event-builder.ts"() {
649
+ SENSITIVE_KEYS = Object.freeze([
650
+ "password",
651
+ "token",
652
+ "secret",
653
+ "api_key",
654
+ "credit_card"
655
+ ]);
656
+ VALID_SOURCE_TYPES = [
657
+ "http_request",
658
+ "background_job",
659
+ "database_callback"
660
+ ];
661
+ VALID_OUTCOMES = ["success", "failure"];
662
+ ArgError = class extends Error {
663
+ constructor(message) {
664
+ super(message);
665
+ this.name = "ArgError";
666
+ }
667
+ };
668
+ }
669
+ });
670
+
671
+ // src/db/shared.ts
672
+ function emitDbEvent(input) {
673
+ try {
674
+ const config = configuration();
675
+ if (!config.captureDb) return;
676
+ if (config.allExcludedTables().includes(input.modelClass)) return;
677
+ if (config.databaseReader && !input._fromTrigger) {
678
+ const tracked = config.triggerTrackedTables;
679
+ if (tracked === null || tracked.has(input.modelClass)) return;
680
+ }
681
+ if (input.operation === "update") {
682
+ const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
683
+ if (meaningful.length === 0) return;
684
+ }
685
+ const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
686
+ const context = buildContext(input);
687
+ const event = build({
688
+ source_type: "database_callback",
689
+ source_data: {
690
+ model_class: input.modelClass,
691
+ operation: input.operation
692
+ },
693
+ outcome: "success",
694
+ correlation_id: current(),
695
+ resource_ids: resourceIdStr === null ? [] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
696
+ context,
697
+ duration_ms: null
698
+ });
699
+ pushEvent(event);
700
+ } catch (error) {
701
+ logger.debug(`db emit failed: ${describeError5(error)}`);
702
+ }
703
+ }
704
+ function buildContext(input) {
705
+ const context = {};
706
+ const actor = getCurrentActor();
707
+ if (actor) context.actor = actor;
708
+ if ((input.operation === "create" || input.operation === "destroy") && input.initialAttributes) {
709
+ const filtered = filterMeaningfulAttributes(input.initialAttributes);
710
+ if (filtered !== null) context.initial_attributes = filtered;
711
+ }
712
+ if (input.operation === "update" && input.changes) {
713
+ const filtered = filterMeaningfulChanges(input.changes);
714
+ if (filtered.length > 0) {
715
+ context.changes = filtered.map((c) => {
716
+ const out = {
717
+ attribute: c.attribute,
718
+ to: formatForJson(c.to)
719
+ };
720
+ if (c.from !== void 0) out.from = formatForJson(c.from);
721
+ return out;
722
+ });
723
+ }
724
+ }
725
+ const displayName = input.displayName ?? (input.modelInstance ? resolveDisplayName(input.modelClass, input.modelInstance) : null);
726
+ if (displayName !== null) context.display_name = displayName;
727
+ return Object.keys(context).length === 0 ? null : context;
728
+ }
729
+ function filterMeaningfulAttributes(attrs) {
730
+ const out = {};
731
+ for (const key of Object.keys(attrs)) {
732
+ if (!isMeaningfulAttribute(key)) continue;
733
+ const value = attrs[key];
734
+ if (value === null || value === void 0) continue;
735
+ if (!isScalar(value)) continue;
736
+ out[key] = formatForJson(value);
737
+ }
738
+ return Object.keys(out).length === 0 ? null : out;
739
+ }
740
+ function filterMeaningfulChanges(changes) {
741
+ return changes.filter((c) => {
742
+ if (!isMeaningfulAttribute(c.attribute)) return false;
743
+ if (!isScalar(c.to)) return false;
744
+ if (c.from === void 0) return true;
745
+ if (!isScalar(c.from)) return false;
746
+ return valuesActuallyChanged(c.from, c.to);
747
+ });
748
+ }
749
+ function isMeaningfulAttribute(name) {
750
+ if (IGNORED_ATTRIBUTES.includes(name)) return false;
751
+ if (isDbSensitive(name)) return false;
752
+ return true;
753
+ }
754
+ function isDbSensitive(name) {
755
+ const lower = name.toLowerCase();
756
+ return DB_SENSITIVE_PATTERNS.some((p) => lower.includes(p));
757
+ }
758
+ function isScalar(value) {
759
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
760
+ return true;
761
+ }
762
+ if (isPrismaDecimal(value)) return true;
763
+ if (Buffer.isBuffer?.(value)) return false;
764
+ if (Array.isArray(value)) return value.every((v) => isScalar(v));
765
+ return false;
766
+ }
767
+ function valuesActuallyChanged(from, to) {
768
+ if (from === null && to === null) return false;
769
+ if (from instanceof Date && to instanceof Date) {
770
+ return from.getTime() !== to.getTime();
771
+ }
772
+ return from !== to;
773
+ }
774
+ function formatForJson(value) {
775
+ if (value === null || value === void 0) return value;
776
+ if (value instanceof Date) return value.toISOString();
777
+ if (typeof value === "bigint") return value.toString();
778
+ if (isPrismaDecimal(value)) return Number(value.toString());
779
+ if (Array.isArray(value)) return value.map(formatForJson);
780
+ return value;
781
+ }
782
+ function isPrismaDecimal(value) {
783
+ if (value === null || typeof value !== "object") return false;
784
+ const obj = value;
785
+ return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
786
+ }
787
+ function resolveDisplayName(modelClass, instance) {
788
+ try {
789
+ const config = configuration();
790
+ const resolver = config.displayNameFor[modelClass];
791
+ const resolved = applyResolver(resolver, instance);
792
+ if (resolved !== null) return resolved;
793
+ for (const field of ["name", "title", "number"]) {
794
+ const value = instance[field];
795
+ if (value !== null && value !== void 0 && String(value).length > 0) {
796
+ return String(value);
797
+ }
798
+ }
799
+ } catch {
800
+ }
801
+ return null;
802
+ }
803
+ function applyResolver(resolver, instance) {
804
+ if (typeof resolver === "string") {
805
+ const value = instance[resolver];
806
+ if (value !== null && value !== void 0 && String(value).length > 0) {
807
+ return String(value);
808
+ }
809
+ return null;
810
+ }
811
+ if (typeof resolver === "function") {
812
+ try {
813
+ const value = resolver(instance);
814
+ if (typeof value === "string" && value.length > 0) return value;
815
+ if (value !== null && value !== void 0 && String(value).length > 0) {
816
+ return String(value);
817
+ }
818
+ } catch {
819
+ }
820
+ }
821
+ return null;
822
+ }
823
+ function describeError5(error) {
824
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
825
+ return String(error);
826
+ }
827
+ var IGNORED_ATTRIBUTES, DB_SENSITIVE_PATTERNS;
828
+ var init_shared = __esm({
829
+ "src/db/shared.ts"() {
830
+ init_configuration();
831
+ init_logger();
832
+ init_event_builder();
833
+ init_buffer();
834
+ init_correlation();
835
+ init_actor();
836
+ IGNORED_ATTRIBUTES = Object.freeze([
837
+ "id",
838
+ "createdAt",
839
+ "created_at",
840
+ "updatedAt",
841
+ "updated_at",
842
+ "deletedAt",
843
+ "deleted_at",
844
+ // Auth.js / NextAuth standard columns
845
+ "emailVerified",
846
+ "expires"
847
+ ]);
848
+ DB_SENSITIVE_PATTERNS = Object.freeze([
849
+ "password",
850
+ "token",
851
+ "secret",
852
+ "api_key",
853
+ "credit_card",
854
+ "ssn",
855
+ "social_security",
856
+ "encrypted"
857
+ ]);
858
+ }
859
+ });
860
+
861
+ // src/db/supabase.ts
862
+ var supabase_exports = {};
863
+ __export(supabase_exports, {
864
+ tryExtractSupabaseActor: () => tryExtractSupabaseActor,
865
+ wrapSupabase: () => wrapSupabase
866
+ });
867
+ function triggerPathWillCapture(table) {
868
+ const config = configuration();
869
+ if (!config.databaseReader) return false;
870
+ const tracked = config.triggerTrackedTables;
871
+ if (tracked === null) return false;
872
+ return tracked.has(table);
873
+ }
874
+ function wrapSupabase(client) {
875
+ if (client === null || typeof client !== "object") return client;
876
+ const obj = client;
877
+ if (obj.__ezlogsWrapped) return client;
878
+ if (typeof obj.from !== "function") return client;
879
+ const originalFrom = obj.from.bind(obj);
880
+ const prereadRow = async (table, filters) => {
881
+ try {
882
+ const queryBuilder = originalFrom(table);
883
+ if (typeof queryBuilder.select !== "function") return null;
884
+ let chain = queryBuilder.select("*");
885
+ for (const f of filters) {
886
+ if (typeof chain.eq !== "function") return null;
887
+ chain = chain.eq(
888
+ f.column,
889
+ f.value
890
+ );
891
+ }
892
+ if (typeof chain.maybeSingle === "function") {
893
+ chain = chain.maybeSingle();
894
+ } else if (typeof chain.limit === "function") {
895
+ chain = chain.limit(
896
+ 1
897
+ );
898
+ }
899
+ const result = await chain;
900
+ if (!result || result.error) return null;
901
+ if (Array.isArray(result.data)) {
902
+ const first = result.data[0];
903
+ return isPlainObject4(first) ? first : null;
904
+ }
905
+ return isPlainObject4(result.data) ? result.data : null;
906
+ } catch {
907
+ return null;
908
+ }
909
+ };
910
+ obj.from = ((table) => {
911
+ const builder = originalFrom(table);
912
+ return wrapBuilder(builder, table, prereadRow);
913
+ });
914
+ Object.defineProperty(obj, "__ezlogsWrapped", {
915
+ value: true,
916
+ enumerable: false,
917
+ configurable: false
918
+ });
919
+ registerActorSource(obj);
920
+ return client;
921
+ }
922
+ function registerActorSource(client) {
923
+ try {
924
+ const g = globalThis;
925
+ g[GLOBAL_CLIENT_KEY] = client;
926
+ } catch {
927
+ }
928
+ }
929
+ async function tryExtractSupabaseActor() {
930
+ const g = globalThis;
931
+ const client = g[GLOBAL_CLIENT_KEY];
932
+ if (!client || typeof client.auth?.getUser !== "function") return null;
933
+ try {
934
+ const { data } = await client.auth.getUser();
935
+ const user = data?.user;
936
+ if (!user || typeof user.id !== "string" || !user.id) return null;
937
+ const label = user.user_metadata?.full_name ?? user.user_metadata?.name ?? user.email ?? void 0;
938
+ return label ? { id: user.id, label } : { id: user.id };
939
+ } catch {
940
+ return null;
941
+ }
942
+ }
943
+ function wrapBuilder(builder, table, preread) {
944
+ if (typeof builder.insert === "function") {
945
+ builder.insert = wrapMutation(
946
+ builder.insert.bind(builder),
947
+ { table, operation: "create" },
948
+ preread
949
+ );
950
+ }
951
+ if (typeof builder.upsert === "function") {
952
+ builder.upsert = wrapMutation(
953
+ builder.upsert.bind(builder),
954
+ { table, operation: "update" },
955
+ // supabase upsert is conceptually update-with-fallback
956
+ preread
957
+ );
958
+ }
959
+ if (typeof builder.update === "function") {
960
+ builder.update = wrapMutation(
961
+ builder.update.bind(builder),
962
+ { table, operation: "update" },
963
+ preread
964
+ );
965
+ }
966
+ if (typeof builder.delete === "function") {
967
+ builder.delete = wrapDeleteMutation(
968
+ builder.delete.bind(builder),
969
+ table,
970
+ preread
971
+ );
972
+ }
973
+ return builder;
974
+ }
975
+ function wrapMutation(original, ctx, preread) {
976
+ return (values, options) => {
977
+ const filterBuilder = original(values, options);
978
+ const filters = trackFilterChain(filterBuilder);
979
+ const beforeRowRef = { row: null };
980
+ return instrumentFilterBuilder(
981
+ filterBuilder,
982
+ (result) => emitFromMutation(ctx, values, result, filters, beforeRowRef.row),
983
+ async () => {
984
+ if (ctx.operation !== "update") return;
985
+ if (triggerPathWillCapture(ctx.table)) return;
986
+ const prereadFilters = prereadFiltersFromCaptured(filters);
987
+ if (prereadFilters !== null) {
988
+ beforeRowRef.row = await preread(ctx.table, prereadFilters);
989
+ }
990
+ }
991
+ );
992
+ };
993
+ }
994
+ function wrapDeleteMutation(original, table, preread) {
995
+ return (options) => {
996
+ const filterBuilder = original(options);
997
+ const filters = trackFilterChain(filterBuilder);
998
+ const beforeRowRef = { row: null };
999
+ return instrumentFilterBuilder(
1000
+ filterBuilder,
1001
+ (result) => emitFromDelete(table, result, filters, beforeRowRef.row),
1002
+ async () => {
1003
+ if (triggerPathWillCapture(table)) return;
1004
+ const prereadFilters = prereadFiltersFromCaptured(filters);
1005
+ if (prereadFilters !== null) {
1006
+ beforeRowRef.row = await preread(table, prereadFilters);
1007
+ }
1008
+ }
1009
+ );
1010
+ };
1011
+ }
1012
+ function trackFilterChain(builder) {
1013
+ const captured = { equals: {}, inLists: {} };
1014
+ if (!builder || typeof builder !== "object") return captured;
1015
+ const builderObj = builder;
1016
+ const wrapEq = (orig) => {
1017
+ if (typeof orig !== "function") return orig;
1018
+ return function patchedEq(column, value) {
1019
+ try {
1020
+ if (typeof column === "string") captured.equals[column] = value;
1021
+ } catch {
1022
+ }
1023
+ return orig.call(this, column, value);
1024
+ };
1025
+ };
1026
+ const wrapIn = (orig) => {
1027
+ if (typeof orig !== "function") return orig;
1028
+ return function patchedIn(column, values) {
1029
+ try {
1030
+ if (typeof column === "string" && Array.isArray(values)) {
1031
+ captured.inLists[column] = values;
1032
+ }
1033
+ } catch {
1034
+ }
1035
+ return orig.call(this, column, values);
1036
+ };
1037
+ };
1038
+ const wrapMatch = (orig) => {
1039
+ if (typeof orig !== "function") return orig;
1040
+ return function patchedMatch(query) {
1041
+ try {
1042
+ if (isPlainObject4(query)) {
1043
+ for (const [k, v] of Object.entries(query)) {
1044
+ captured.equals[k] = v;
1045
+ }
1046
+ }
1047
+ } catch {
1048
+ }
1049
+ return orig.call(this, query);
1050
+ };
1051
+ };
1052
+ if ("eq" in builderObj) builderObj.eq = wrapEq(builderObj.eq);
1053
+ if ("in" in builderObj) builderObj.in = wrapIn(builderObj.in);
1054
+ if ("match" in builderObj) builderObj.match = wrapMatch(builderObj.match);
1055
+ return captured;
1056
+ }
1057
+ function instrumentFilterBuilder(builder, onResolved, beforeFire) {
1058
+ if (!builder || typeof builder !== "object") return builder;
1059
+ const originalThen = builder.then?.bind(builder);
1060
+ if (typeof originalThen !== "function") return builder;
1061
+ const wrappedThen = function ezlogsThen(onfulfilled, onrejected) {
1062
+ return new Promise((resolve, reject) => {
1063
+ const proceed = () => {
1064
+ originalThen(
1065
+ (raw) => {
1066
+ const result = raw;
1067
+ try {
1068
+ if (!result?.error) onResolved(result);
1069
+ } catch (error) {
1070
+ logger.debug(`supabase capture failed: ${describeError6(error)}`);
1071
+ }
1072
+ try {
1073
+ const passthrough = onfulfilled ? onfulfilled(raw) : raw;
1074
+ resolve(passthrough);
1075
+ } catch (e) {
1076
+ reject(e);
1077
+ }
1078
+ },
1079
+ (reason) => {
1080
+ try {
1081
+ const passthrough = onrejected ? onrejected(reason) : Promise.reject(reason);
1082
+ resolve(passthrough);
1083
+ } catch (e) {
1084
+ reject(e);
1085
+ }
1086
+ }
1087
+ );
1088
+ };
1089
+ if (beforeFire) {
1090
+ beforeFire().then(proceed, () => proceed());
1091
+ } else {
1092
+ proceed();
1093
+ }
1094
+ });
1095
+ };
1096
+ builder.then = wrappedThen;
1097
+ return builder;
1098
+ }
1099
+ function emitFromMutation(ctx, values, result, filters, beforeRow) {
1100
+ if (Array.isArray(values)) {
1101
+ const resultRows = pickResultRows(result);
1102
+ values.forEach((row, index) => {
1103
+ if (!isPlainObject4(row)) return;
1104
+ emitOneRow(ctx, row, resultRows[index] ?? null, filters, null);
1105
+ });
1106
+ return;
1107
+ }
1108
+ if (!isPlainObject4(values)) {
1109
+ emitDbEvent({
1110
+ modelClass: ctx.table,
1111
+ operation: ctx.operation,
1112
+ resourceId: idFromFilters(filters)
1113
+ });
1114
+ return;
1115
+ }
1116
+ const valueObj = values;
1117
+ const resultRow = pickFirstResultRow(result);
1118
+ emitOneRow(ctx, valueObj, resultRow, filters, beforeRow);
1119
+ }
1120
+ function emitOneRow(ctx, values, resultRow, filters, beforeRow) {
1121
+ const resourceId = resultRow?.id ?? values.id ?? idFromFilters(filters) ?? null;
1122
+ const merged = beforeRow ?? resultRow ?? values;
1123
+ const displayName = resolveDisplayName(ctx.table, merged);
1124
+ if (ctx.operation === "create") {
1125
+ emitDbEvent({
1126
+ modelClass: ctx.table,
1127
+ operation: "create",
1128
+ resourceId,
1129
+ initialAttributes: values,
1130
+ displayName,
1131
+ modelInstance: merged
1132
+ });
1133
+ return;
1134
+ }
1135
+ if (ctx.operation === "update") {
1136
+ const changes = buildUpdateChanges(values, beforeRow);
1137
+ emitDbEvent({
1138
+ modelClass: ctx.table,
1139
+ operation: "update",
1140
+ resourceId,
1141
+ changes,
1142
+ displayName,
1143
+ modelInstance: merged
1144
+ });
1145
+ }
1146
+ }
1147
+ function emitFromDelete(table, result, filters, beforeRow) {
1148
+ const resultRow = pickFirstResultRow(result);
1149
+ const resourceId = resultRow?.id ?? beforeRow?.id ?? idFromFilters(filters) ?? null;
1150
+ const richestRow = resultRow ?? beforeRow;
1151
+ const displayName = richestRow ? resolveDisplayName(table, richestRow) : null;
1152
+ emitDbEvent({
1153
+ modelClass: table,
1154
+ operation: "destroy",
1155
+ resourceId,
1156
+ displayName,
1157
+ modelInstance: richestRow
1158
+ });
1159
+ }
1160
+ function prereadFiltersFromCaptured(filters) {
1161
+ const idValue = filters.equals["id"];
1162
+ if (!isScalarFilterValue(idValue)) return null;
1163
+ const out = [];
1164
+ for (const column of Object.keys(filters.equals)) {
1165
+ const value = filters.equals[column];
1166
+ if (!isScalarFilterValue(value)) continue;
1167
+ out.push({ column, value });
1168
+ }
1169
+ return out;
1170
+ }
1171
+ function idFromFilters(filters) {
1172
+ const value = filters.equals["id"];
1173
+ return isScalarFilterValue(value) ? value : null;
1174
+ }
1175
+ function isScalarFilterValue(value) {
1176
+ return typeof value === "string" || typeof value === "number" || typeof value === "bigint";
1177
+ }
1178
+ function buildUpdateChanges(values, beforeRow) {
1179
+ return Object.keys(values).map((attribute) => {
1180
+ const change = {
1181
+ attribute,
1182
+ to: values[attribute]
1183
+ };
1184
+ if (beforeRow && Object.prototype.hasOwnProperty.call(beforeRow, attribute)) {
1185
+ change.from = beforeRow[attribute];
1186
+ }
1187
+ return change;
1188
+ });
1189
+ }
1190
+ function pickFirstResultRow(result) {
1191
+ if (!result || result.error) return null;
1192
+ if (Array.isArray(result.data)) {
1193
+ const first = result.data[0];
1194
+ return isPlainObject4(first) ? first : null;
1195
+ }
1196
+ if (isPlainObject4(result.data)) return result.data;
1197
+ return null;
1198
+ }
1199
+ function pickResultRows(result) {
1200
+ if (!result || result.error || !Array.isArray(result.data)) return [];
1201
+ return result.data.map(
1202
+ (row) => isPlainObject4(row) ? row : void 0
1203
+ );
1204
+ }
1205
+ function isPlainObject4(value) {
1206
+ if (value === null || typeof value !== "object") return false;
1207
+ if (Array.isArray(value)) return false;
1208
+ if (value instanceof Date) return false;
1209
+ return true;
1210
+ }
1211
+ function describeError6(error) {
1212
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
1213
+ return String(error);
1214
+ }
1215
+ var GLOBAL_CLIENT_KEY;
1216
+ var init_supabase = __esm({
1217
+ "src/db/supabase.ts"() {
1218
+ init_logger();
1219
+ init_configuration();
1220
+ init_shared();
1221
+ GLOBAL_CLIENT_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:supabase-current-client");
1222
+ }
1223
+ });
1224
+
1225
+ // src/index.ts
1226
+ init_configuration();
1227
+ init_logger();
1228
+ init_buffer();
1229
+
1230
+ // src/pipeline/flush-scheduler.ts
1231
+ init_configuration();
1232
+ init_logger();
1233
+ init_buffer();
1234
+
1235
+ // src/pipeline/retry-sender.ts
1236
+ init_configuration();
1237
+ init_logger();
1238
+
1239
+ // src/pipeline/transport.ts
1240
+ init_configuration();
1241
+ init_logger();
1242
+ var REQUEST_TIMEOUT_MS = 1e4;
1243
+ var transport = {
1244
+ async send(events) {
1245
+ if (!events || events.length === 0) return "success";
1246
+ const config = configuration();
1247
+ const serverUrl = config.serverUrl;
1248
+ if (!serverUrl) {
1249
+ logger.error("Transport: serverUrl not configured");
1250
+ return "failure";
1251
+ }
1252
+ const url = `${stripTrailingSlash(serverUrl)}/api/events`;
1253
+ const controller = new AbortController();
1254
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
1255
+ try {
1256
+ const headers = {
1257
+ "Content-Type": "application/json"
1258
+ };
1259
+ if (config.projectToken) {
1260
+ headers["Authorization"] = `Bearer ${config.projectToken}`;
1261
+ }
1262
+ const response = await fetch(url, {
1263
+ method: "POST",
1264
+ headers,
1265
+ body: JSON.stringify({ events }),
1266
+ signal: controller.signal
1267
+ });
1268
+ if (response.status >= 200 && response.status < 300) {
1269
+ logger.debug(`Transport send succeeded (${response.status})`);
1270
+ return "success";
1271
+ }
1272
+ logger.error(`Transport send failed (${response.status})`);
1273
+ return "failure";
1274
+ } catch (error) {
1275
+ const desc = describeError(error);
1276
+ logger.error(`Transport send failed: ${desc}`);
1277
+ return "failure";
1278
+ } finally {
1279
+ clearTimeout(timer);
1280
+ }
1281
+ }
1282
+ };
1283
+ function stripTrailingSlash(url) {
1284
+ return url.endsWith("/") ? url.slice(0, -1) : url;
1285
+ }
1286
+ function describeError(error) {
1287
+ if (error instanceof Error) {
1288
+ if (error.name === "AbortError") return "request timed out";
1289
+ return `${error.name}: ${error.message}`;
1290
+ }
1291
+ return String(error);
1292
+ }
1293
+
1294
+ // src/pipeline/retry-sender.ts
1295
+ var MAX_SLEEP_MS = 5e3;
1296
+ var BASE_DELAY_MS = 500;
1297
+ var JITTER_FRACTION = 0.2;
1298
+ var randomFn = Math.random;
1299
+ var retrySender = {
1300
+ async send(events) {
1301
+ if (!events || events.length === 0) return "success";
1302
+ const maxAttempts = retryAttempts() + 1;
1303
+ let attempt = 1;
1304
+ while (attempt <= maxAttempts) {
1305
+ const result = await attemptSend(events, attempt, maxAttempts);
1306
+ if (result === "success") return "success";
1307
+ if (attempt >= maxAttempts) break;
1308
+ await sleepBeforeRetry(attempt);
1309
+ attempt += 1;
1310
+ }
1311
+ logger.error(
1312
+ `RetrySender: failed after ${maxAttempts} attempts, dropping ${events.length} events`
1313
+ );
1314
+ return "failure";
1315
+ }
1316
+ };
1317
+ async function attemptSend(events, attempt, maxAttempts) {
1318
+ try {
1319
+ return await transport.send(events);
1320
+ } catch (error) {
1321
+ logger.error(
1322
+ `RetrySender: transport raised (attempt ${attempt}/${maxAttempts}): ${describeError2(error)}`
1323
+ );
1324
+ return "failure";
1325
+ }
1326
+ }
1327
+ function sleepBeforeRetry(attempt) {
1328
+ const base = Math.min(BASE_DELAY_MS * 2 ** (attempt - 1), MAX_SLEEP_MS);
1329
+ const delay = applyJitter(base) ;
1330
+ return new Promise((resolve) => setTimeout(resolve, delay));
1331
+ }
1332
+ function applyJitter(base) {
1333
+ const span = base * JITTER_FRACTION;
1334
+ return base - span + randomFn() * 2 * span;
1335
+ }
1336
+ function retryAttempts() {
1337
+ try {
1338
+ const value = configuration().retryAttempts;
1339
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
1340
+ return 3;
1341
+ }
1342
+ return value;
1343
+ } catch {
1344
+ return 3;
1345
+ }
1346
+ }
1347
+ function describeError2(error) {
1348
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
1349
+ return String(error);
1350
+ }
1351
+
1352
+ // src/pipeline/flush-scheduler.ts
1353
+ var GLOBAL_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:flush-scheduler-state");
1354
+ function state() {
1355
+ const g = globalThis;
1356
+ if (!g[GLOBAL_KEY]) {
1357
+ g[GLOBAL_KEY] = { timer: null, inFlight: false };
1358
+ }
1359
+ return g[GLOBAL_KEY];
1360
+ }
1361
+ var flushScheduler = {
1362
+ start() {
1363
+ const s = state();
1364
+ if (s.timer !== null) return;
1365
+ const interval = sendInterval();
1366
+ s.timer = setInterval(() => {
1367
+ void tick();
1368
+ }, interval);
1369
+ if (typeof s.timer === "object" && s.timer !== null && "unref" in s.timer) {
1370
+ s.timer.unref();
1371
+ }
1372
+ logger.debug(`FlushScheduler started (interval ${interval}ms)`);
1373
+ },
1374
+ async stop() {
1375
+ const s = state();
1376
+ if (s.timer === null) return;
1377
+ clearInterval(s.timer);
1378
+ s.timer = null;
1379
+ await tick();
1380
+ logger.debug("FlushScheduler stopped");
1381
+ },
1382
+ isRunning() {
1383
+ return state().timer !== null;
1384
+ },
1385
+ /** Force a single drain-and-send cycle. Used by serverless flush + tests. */
1386
+ async flushNow() {
1387
+ await tick();
1388
+ }
1389
+ };
1390
+ async function tick() {
1391
+ const s = state();
1392
+ if (s.inFlight) return;
1393
+ s.inFlight = true;
1394
+ try {
1395
+ const events = drainEvents();
1396
+ if (events.length === 0) return;
1397
+ await retrySender.send(events);
1398
+ } catch (error) {
1399
+ logger.error(`FlushScheduler tick failed: ${describeError3(error)}`);
1400
+ } finally {
1401
+ s.inFlight = false;
1402
+ }
1403
+ }
1404
+ function sendInterval() {
1405
+ try {
1406
+ const value = configuration().sendInterval;
1407
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
1408
+ return 5e3;
1409
+ }
1410
+ return value;
1411
+ } catch {
1412
+ return 5e3;
1413
+ }
1414
+ }
1415
+ function describeError3(error) {
1416
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
1417
+ return String(error);
1418
+ }
1419
+
1420
+ // src/http/outgoing-fetch.ts
1421
+ init_correlation();
1422
+ init_logger();
1423
+ var HEADER = "x-correlation-id";
1424
+ var originalFetch = null;
1425
+ var patched = false;
1426
+ function patchGlobalFetch() {
1427
+ if (patched) return;
1428
+ if (typeof globalThis.fetch !== "function") return;
1429
+ originalFetch = globalThis.fetch;
1430
+ const wrapped = (input, init) => {
1431
+ const id = current();
1432
+ if (!id) return originalFetch.call(globalThis, input, init);
1433
+ try {
1434
+ const enriched = injectHeader(input, init, id);
1435
+ return originalFetch.call(globalThis, enriched.input, enriched.init);
1436
+ } catch (error) {
1437
+ logger.debug(`outgoing-fetch injection failed: ${describeError4(error)}`);
1438
+ return originalFetch.call(globalThis, input, init);
1439
+ }
1440
+ };
1441
+ globalThis.fetch = wrapped;
1442
+ patched = true;
1443
+ }
1444
+ function unpatchGlobalFetch() {
1445
+ if (!patched || originalFetch === null) return;
1446
+ globalThis.fetch = originalFetch;
1447
+ originalFetch = null;
1448
+ patched = false;
1449
+ }
1450
+ function injectHeader(input, init, correlationId) {
1451
+ if (input instanceof Request && !init) {
1452
+ if (input.headers.has(HEADER)) return { input, init };
1453
+ const merged = new Headers(input.headers);
1454
+ merged.set(HEADER, correlationId);
1455
+ return {
1456
+ input: new Request(input, { headers: merged }),
1457
+ init: void 0
1458
+ };
1459
+ }
1460
+ const headers = new Headers(init && init.headers || (input instanceof Request ? input.headers : void 0));
1461
+ if (headers.has(HEADER)) return { input, init };
1462
+ headers.set(HEADER, correlationId);
1463
+ return {
1464
+ input,
1465
+ init: { ...init, headers }
1466
+ };
1467
+ }
1468
+ function describeError4(error) {
1469
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
1470
+ return String(error);
1471
+ }
1472
+
1473
+ // src/triggers/patch-pg.ts
1474
+ init_actor();
1475
+ init_correlation();
1476
+ init_logger();
1477
+ var txState = /* @__PURE__ */ new WeakMap();
1478
+ function patchPgClient(pgModule) {
1479
+ if (!pgModule || !pgModule.Client || !pgModule.Client.prototype) {
1480
+ logger.debug("patchPgClient: not a recognized pg module shape, skipping");
1481
+ return;
1482
+ }
1483
+ const proto = pgModule.Client.prototype;
1484
+ if (proto._ezlogsPatched) return;
1485
+ const originalQuery = proto.query;
1486
+ proto.query = function patchedQuery(config, values, callback) {
1487
+ return runPatchedQuery(
1488
+ this,
1489
+ originalQuery,
1490
+ config,
1491
+ values,
1492
+ callback
1493
+ );
1494
+ };
1495
+ proto._ezlogsPatched = true;
1496
+ }
1497
+ function runPatchedQuery(client, original, config, values, callback) {
1498
+ const state2 = ensureState(client);
1499
+ const text = extractQueryText(config);
1500
+ const verb = leadingVerb(text);
1501
+ if (verb === "BEGIN" || verb === "START") {
1502
+ state2.inTx = true;
1503
+ state2.injected = false;
1504
+ return original.call(client, config, values, callback);
1505
+ }
1506
+ if (verb === "COMMIT" || verb === "ROLLBACK" || verb === "END") {
1507
+ const result = original.call(client, config, values, callback);
1508
+ state2.inTx = false;
1509
+ state2.injected = false;
1510
+ return result;
1511
+ }
1512
+ if (state2.inTx) {
1513
+ if (state2.injected) {
1514
+ return original.call(client, config, values, callback);
1515
+ }
1516
+ const ctx2 = snapshotContext();
1517
+ if (!ctx2.actorId && !ctx2.correlationId) {
1518
+ state2.injected = true;
1519
+ return original.call(client, config, values, callback);
1520
+ }
1521
+ state2.injected = true;
1522
+ return injectAndRun(client, original, config, values, callback, ctx2);
1523
+ }
1524
+ const ctx = snapshotContext();
1525
+ if (!ctx.actorId && !ctx.correlationId) {
1526
+ return original.call(client, config, values, callback);
1527
+ }
1528
+ return wrapInTx(client, original, config, values, callback, ctx);
1529
+ }
1530
+ function snapshotContext() {
1531
+ const actor = getCurrentActor();
1532
+ return {
1533
+ actorId: actor && actor.id ? actor.id : null,
1534
+ correlationId: current()
1535
+ };
1536
+ }
1537
+ async function injectAndRun(client, original, config, values, callback, ctx) {
1538
+ if (ctx.actorId) {
1539
+ await safeSet(client, original, {
1540
+ text: "SELECT set_config('ezlogs.actor_id', $1, true)",
1541
+ values: [ctx.actorId]
1542
+ });
1543
+ }
1544
+ if (ctx.correlationId) {
1545
+ await safeSet(client, original, {
1546
+ text: "SELECT set_config('ezlogs.correlation_id', $1, true)",
1547
+ values: [ctx.correlationId]
1548
+ });
1549
+ }
1550
+ return original.call(client, config, values, callback);
1551
+ }
1552
+ async function safeSet(client, original, cfg) {
1553
+ try {
1554
+ const result = original.call(client, cfg);
1555
+ if (result && typeof result.then === "function") {
1556
+ await result;
1557
+ }
1558
+ } catch (err) {
1559
+ logger.debug(
1560
+ `patchPgClient: SET LOCAL failed (continuing): ${err instanceof Error ? err.message : String(err)}`
1561
+ );
1562
+ }
1563
+ }
1564
+ function wrapInTx(client, original, config, values, callback, ctx) {
1565
+ const state2 = ensureState(client);
1566
+ let userCb = null;
1567
+ let realValues = values;
1568
+ if (typeof callback === "function") {
1569
+ userCb = callback;
1570
+ } else if (typeof values === "function") {
1571
+ userCb = values;
1572
+ realValues = void 0;
1573
+ }
1574
+ const begin = original.call(client, "BEGIN");
1575
+ if (!begin || typeof begin.then !== "function") {
1576
+ return original.call(client, config, values, callback);
1577
+ }
1578
+ const wrapped = begin.then(async () => {
1579
+ state2.inTx = true;
1580
+ state2.injected = true;
1581
+ if (ctx.actorId) {
1582
+ await original.call(client, {
1583
+ text: "SELECT set_config('ezlogs.actor_id', $1, true)",
1584
+ values: [ctx.actorId]
1585
+ });
1586
+ }
1587
+ if (ctx.correlationId) {
1588
+ await original.call(client, {
1589
+ text: "SELECT set_config('ezlogs.correlation_id', $1, true)",
1590
+ values: [ctx.correlationId]
1591
+ });
1592
+ }
1593
+ }).then(
1594
+ () => (
1595
+ // Run the user's actual query in promise mode — DO NOT forward
1596
+ // the caller's callback. See comment above.
1597
+ original.call(client, config, realValues)
1598
+ )
1599
+ ).then(
1600
+ async (result) => {
1601
+ await original.call(client, "COMMIT");
1602
+ state2.inTx = false;
1603
+ state2.injected = false;
1604
+ return result;
1605
+ },
1606
+ async (err) => {
1607
+ try {
1608
+ await original.call(client, "ROLLBACK");
1609
+ } catch {
1610
+ }
1611
+ state2.inTx = false;
1612
+ state2.injected = false;
1613
+ throw err;
1614
+ }
1615
+ );
1616
+ if (userCb) {
1617
+ wrapped.then(
1618
+ (result) => userCb(null, result),
1619
+ (err) => userCb(err instanceof Error ? err : new Error(String(err)))
1620
+ );
1621
+ return void 0;
1622
+ }
1623
+ return wrapped;
1624
+ }
1625
+ function ensureState(client) {
1626
+ let s = txState.get(client);
1627
+ if (!s) {
1628
+ s = { inTx: false, injected: false };
1629
+ txState.set(client, s);
1630
+ }
1631
+ return s;
1632
+ }
1633
+ function extractQueryText(config) {
1634
+ if (typeof config === "string") return config;
1635
+ if (config && typeof config === "object" && typeof config.text === "string") {
1636
+ return config.text;
1637
+ }
1638
+ return "";
1639
+ }
1640
+ function leadingVerb(text) {
1641
+ let s = text;
1642
+ while (true) {
1643
+ const before = s.length;
1644
+ s = s.replace(/^\s+/, "");
1645
+ s = s.replace(/^--[^\n]*\n?/, "");
1646
+ if (s.length === before) break;
1647
+ }
1648
+ const m = /^[A-Za-z]+/.exec(s);
1649
+ return m ? m[0].toUpperCase() : "";
1650
+ }
1651
+
1652
+ // src/triggers/reader.ts
1653
+ init_logger();
1654
+ init_shared();
1655
+ init_correlation();
1656
+
1657
+ // src/triggers/audit-snapshot.ts
1658
+ init_edge_fallback();
1659
+ var storage3 = createScopedStorage(
1660
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-snapshot-storage")
1661
+ );
1662
+ function currentAuditSnapshot() {
1663
+ return storage3.read();
1664
+ }
1665
+ function setAuditSnapshot(value) {
1666
+ storage3.update(value);
1667
+ }
1668
+ function runWithAuditSnapshotScope(callback) {
1669
+ return storage3.run(0n, callback);
1670
+ }
1671
+
1672
+ // src/triggers/reader.ts
1673
+ async function readAuditRows(exec, correlationId, snapshotMaxId = null) {
1674
+ try {
1675
+ const sql = snapshotMaxId === null ? `SELECT table_name, op, old_row, new_row, resource_id
1676
+ FROM ezlogs_audit_log
1677
+ WHERE correlation_id = $1
1678
+ ORDER BY id ASC` : `SELECT table_name, op, old_row, new_row, resource_id
1679
+ FROM ezlogs_audit_log
1680
+ WHERE correlation_id = $1
1681
+ OR (correlation_id IS NULL AND id > $2)
1682
+ ORDER BY id ASC`;
1683
+ const params = snapshotMaxId === null ? [correlationId] : [correlationId, snapshotMaxId.toString()];
1684
+ const result = await exec(sql, params);
1685
+ const rows = extractRows(result);
1686
+ return rows.map((r) => normalizeAuditRow(r));
1687
+ } catch (err) {
1688
+ logger.debug(
1689
+ `readAuditRows failed: ${err instanceof Error ? err.message : String(err)}`
1690
+ );
1691
+ return [];
1692
+ }
1693
+ }
1694
+ async function takeAuditSnapshot(exec) {
1695
+ try {
1696
+ const result = await exec(
1697
+ `SELECT COALESCE(MAX(id), 0) AS max_id FROM ezlogs_audit_log`,
1698
+ []
1699
+ );
1700
+ const rows = extractRows(result);
1701
+ if (rows.length === 0) return;
1702
+ const raw = rows[0] ?? {};
1703
+ const value = typeof raw.max_id === "bigint" ? raw.max_id : typeof raw.max_id === "number" ? BigInt(raw.max_id) : typeof raw.max_id === "string" && /^\d+$/.test(raw.max_id) ? BigInt(raw.max_id) : null;
1704
+ if (value === null) return;
1705
+ setAuditSnapshot(value);
1706
+ } catch (err) {
1707
+ logger.debug(
1708
+ `takeAuditSnapshot failed: ${err instanceof Error ? err.message : String(err)}`
1709
+ );
1710
+ }
1711
+ }
1712
+ async function detectTriggerTrackedTables(exec) {
1713
+ try {
1714
+ const result = await exec(
1715
+ `SELECT event_object_table AS table_name
1716
+ FROM information_schema.triggers
1717
+ WHERE trigger_name = 'ezlogs_audit'
1718
+ AND trigger_schema = 'public'`,
1719
+ []
1720
+ );
1721
+ const rows = extractRows(result);
1722
+ const tables = /* @__PURE__ */ new Set();
1723
+ for (const row of rows) {
1724
+ const r = row ?? {};
1725
+ if (typeof r.table_name === "string" && r.table_name.length > 0) {
1726
+ tables.add(r.table_name);
1727
+ }
1728
+ }
1729
+ return tables;
1730
+ } catch (err) {
1731
+ logger.debug(
1732
+ `detectTriggerTrackedTables failed: ${err instanceof Error ? err.message : String(err)}`
1733
+ );
1734
+ return null;
1735
+ }
1736
+ }
1737
+ function emitAuditRows(rows) {
1738
+ for (const row of rows) {
1739
+ emitOne(row);
1740
+ }
1741
+ }
1742
+ async function flushAuditLog(exec) {
1743
+ if (!exec) return;
1744
+ const correlationId = current();
1745
+ if (!correlationId) return;
1746
+ const snapshot = currentAuditSnapshot();
1747
+ const rows = await readAuditRows(exec, correlationId, snapshot);
1748
+ if (rows.length === 0) return;
1749
+ emitAuditRows(rows);
1750
+ }
1751
+ function emitOne(row) {
1752
+ const op = mapOp(row.op);
1753
+ if (!op) return;
1754
+ const oldRow = coerceJsonb(row.old_row);
1755
+ const newRow = coerceJsonb(row.new_row);
1756
+ if (op === "create" && newRow) {
1757
+ emitDbEvent({
1758
+ modelClass: row.table_name,
1759
+ operation: "create",
1760
+ resourceId: row.resource_id,
1761
+ initialAttributes: newRow,
1762
+ modelInstance: newRow,
1763
+ displayName: null,
1764
+ _fromTrigger: true
1765
+ });
1766
+ return;
1767
+ }
1768
+ if (op === "update" && oldRow && newRow) {
1769
+ const changes = computeChanges(oldRow, newRow);
1770
+ if (changes.length === 0) {
1771
+ return;
1772
+ }
1773
+ emitDbEvent({
1774
+ modelClass: row.table_name,
1775
+ operation: "update",
1776
+ resourceId: row.resource_id,
1777
+ changes,
1778
+ // Prefer the post-state for the display name — that's what the
1779
+ // user just told the system to call this row.
1780
+ modelInstance: newRow,
1781
+ displayName: null,
1782
+ _fromTrigger: true
1783
+ });
1784
+ return;
1785
+ }
1786
+ if (op === "destroy" && oldRow) {
1787
+ emitDbEvent({
1788
+ modelClass: row.table_name,
1789
+ operation: "destroy",
1790
+ resourceId: row.resource_id,
1791
+ initialAttributes: oldRow,
1792
+ modelInstance: oldRow,
1793
+ displayName: null,
1794
+ _fromTrigger: true
1795
+ });
1796
+ return;
1797
+ }
1798
+ }
1799
+ function mapOp(op) {
1800
+ if (op === "INSERT") return "create";
1801
+ if (op === "UPDATE") return "update";
1802
+ if (op === "DELETE") return "destroy";
1803
+ return null;
1804
+ }
1805
+ function computeChanges(oldRow, newRow) {
1806
+ const out = [];
1807
+ for (const key of Object.keys(newRow)) {
1808
+ const before = oldRow[key];
1809
+ const after = newRow[key];
1810
+ if (deepEqual(before, after)) continue;
1811
+ out.push({ attribute: key, from: before, to: after });
1812
+ }
1813
+ return out;
1814
+ }
1815
+ function deepEqual(a, b) {
1816
+ if (a === b) return true;
1817
+ if (a === null || b === null) return false;
1818
+ if (typeof a !== typeof b) return false;
1819
+ if (typeof a !== "object") return false;
1820
+ try {
1821
+ return stableStringify(a) === stableStringify(b);
1822
+ } catch {
1823
+ return false;
1824
+ }
1825
+ }
1826
+ function stableStringify(value) {
1827
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
1828
+ if (Array.isArray(value)) {
1829
+ return "[" + value.map((v) => stableStringify(v)).join(",") + "]";
1830
+ }
1831
+ const entries = Object.keys(value).sort().map((k) => JSON.stringify(k) + ":" + stableStringify(value[k]));
1832
+ return "{" + entries.join(",") + "}";
1833
+ }
1834
+ function extractRows(result) {
1835
+ if (!result) return [];
1836
+ if (Array.isArray(result)) return result;
1837
+ if (typeof result === "object" && Array.isArray(result.rows)) {
1838
+ return result.rows;
1839
+ }
1840
+ return [];
1841
+ }
1842
+ function normalizeAuditRow(raw) {
1843
+ const r = raw ?? {};
1844
+ return {
1845
+ table_name: String(r.table_name ?? ""),
1846
+ op: r.op,
1847
+ old_row: r.old_row ?? null,
1848
+ new_row: r.new_row ?? null,
1849
+ resource_id: r.resource_id == null ? null : String(r.resource_id)
1850
+ };
1851
+ }
1852
+ function coerceJsonb(value) {
1853
+ if (value === null || value === void 0) return null;
1854
+ if (typeof value === "string") {
1855
+ try {
1856
+ const parsed = JSON.parse(value);
1857
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
1858
+ } catch {
1859
+ return null;
1860
+ }
1861
+ }
1862
+ if (typeof value === "object" && !Array.isArray(value)) return value;
1863
+ return null;
1864
+ }
1865
+
1866
+ // src/index.ts
1867
+ init_logger();
1868
+ init_event_builder();
1869
+
1870
+ // src/http/capture.ts
1871
+ init_configuration();
1872
+ init_logger();
1873
+ init_event_builder();
1874
+ init_buffer();
1875
+
1876
+ // src/pipeline/serverless.ts
1877
+ var cachedFlag = null;
1878
+ function isServerless() {
1879
+ if (cachedFlag !== null) return cachedFlag;
1880
+ cachedFlag = detect();
1881
+ return cachedFlag;
1882
+ }
1883
+ function detect() {
1884
+ if (typeof process === "undefined" || !process.env) return false;
1885
+ const env = process.env;
1886
+ if (env.VERCEL === "1") return true;
1887
+ if (typeof env.AWS_LAMBDA_FUNCTION_NAME === "string" && env.AWS_LAMBDA_FUNCTION_NAME) {
1888
+ return true;
1889
+ }
1890
+ if (env.NETLIFY === "true") return true;
1891
+ if (env.CF_PAGES === "1") return true;
1892
+ return false;
1893
+ }
1894
+
1895
+ // src/http/capture.ts
1896
+ init_actor();
1897
+ init_correlation();
1898
+
1899
+ // src/http/path-matcher.ts
1900
+ function pathMatches(path, pattern) {
1901
+ const startsWithStar = pattern.startsWith("*");
1902
+ const endsWithStar = pattern.endsWith("*");
1903
+ if (startsWithStar && endsWithStar) {
1904
+ const middle = pattern.slice(1, -1);
1905
+ return path.includes(middle);
1906
+ }
1907
+ if (startsWithStar) {
1908
+ const suffix = pattern.slice(1);
1909
+ return path.endsWith(suffix);
1910
+ }
1911
+ if (endsWithStar) {
1912
+ const prefix = pattern.slice(0, -1);
1913
+ return path.startsWith(prefix);
1914
+ }
1915
+ return path === pattern;
1916
+ }
1917
+ function hasExcludedExtension(path, extensions) {
1918
+ if (!path) return false;
1919
+ return extensions.some((ext) => path.endsWith(ext));
1920
+ }
1921
+
1922
+ // src/http/capture.ts
1923
+ init_configuration();
1924
+
1925
+ // src/http/sanitize.ts
1926
+ var SENSITIVE_VARIABLE_PATTERNS = Object.freeze([
1927
+ "password",
1928
+ "passwd",
1929
+ "pwd",
1930
+ "token",
1931
+ "access_token",
1932
+ "refresh_token",
1933
+ "api_token",
1934
+ "auth_token",
1935
+ "secret",
1936
+ "api_secret",
1937
+ "client_secret",
1938
+ "api_key",
1939
+ "apikey",
1940
+ "private_key",
1941
+ "privatekey",
1942
+ "secret_key",
1943
+ "secretkey",
1944
+ "credential",
1945
+ "auth",
1946
+ "authorization",
1947
+ "encrypted",
1948
+ "encrypted_data",
1949
+ "ssn",
1950
+ "social_security",
1951
+ "credit_card",
1952
+ "card_number",
1953
+ "cvv",
1954
+ "cvc"
1955
+ ]);
1956
+ var MAX_NESTING_DEPTH = 3;
1957
+ var MAX_ARRAY_DISPLAY_SIZE = 5;
1958
+ function sanitizeRequestParams(params, userPatterns = []) {
1959
+ if (params === null || params === void 0) return null;
1960
+ if (!isPlainObject2(params)) return null;
1961
+ const obj = params;
1962
+ const cleaned = {};
1963
+ for (const key of Object.keys(obj)) {
1964
+ if (FRAMEWORK_INTERNAL_KEYS.has(key)) continue;
1965
+ cleaned[key] = obj[key];
1966
+ }
1967
+ if (Object.keys(cleaned).length === 0) return null;
1968
+ const out = {};
1969
+ for (const key of Object.keys(cleaned)) {
1970
+ out[key] = sanitizeValue(key, cleaned[key], 0, userPatterns);
1971
+ }
1972
+ return out;
1973
+ }
1974
+ var FRAMEWORK_INTERNAL_KEYS = /* @__PURE__ */ new Set([
1975
+ // Rails leftovers — kept for parity since users may funnel through a
1976
+ // proxy that adds them, e.g. via a NextAuth credentials provider that
1977
+ // forwards CSRF tokens.
1978
+ "controller",
1979
+ "action",
1980
+ "format",
1981
+ "authenticity_token",
1982
+ "_method",
1983
+ // Next.js / common JS conventions
1984
+ "csrfToken",
1985
+ "_csrf",
1986
+ "_next"
1987
+ ]);
1988
+ function sanitizeValue(key, value, depth, userPatterns) {
1989
+ if (isSensitiveKey2(key, userPatterns)) return "[FILTERED]";
1990
+ if (isPlainObject2(value)) {
1991
+ return sanitizeNestedObject(value, depth, userPatterns);
1992
+ }
1993
+ if (Array.isArray(value)) {
1994
+ return sanitizeArrayValue(value, depth, userPatterns);
1995
+ }
1996
+ return value;
1997
+ }
1998
+ function sanitizeNestedObject(hash, depth, userPatterns) {
1999
+ if (depth >= MAX_NESTING_DEPTH) return "[Object]";
2000
+ if (Object.keys(hash).length === 0) return {};
2001
+ const out = {};
2002
+ for (const k of Object.keys(hash)) {
2003
+ out[k] = sanitizeValue(k, hash[k], depth + 1, userPatterns);
2004
+ }
2005
+ return out;
2006
+ }
2007
+ function sanitizeArrayValue(array, depth, userPatterns) {
2008
+ if (array.length === 0) return [];
2009
+ const allPrimitive = array.every(isPrimitive);
2010
+ if (allPrimitive) {
2011
+ if (array.length <= MAX_ARRAY_DISPLAY_SIZE) return array;
2012
+ const preview = array.slice(0, MAX_ARRAY_DISPLAY_SIZE);
2013
+ return `${JSON.stringify(preview)}... (${array.length} total)`;
2014
+ }
2015
+ if (array.length <= MAX_ARRAY_DISPLAY_SIZE) {
2016
+ return array.map((item) => sanitizeArrayItem(item, depth, userPatterns));
2017
+ }
2018
+ return {
2019
+ _truncated: true,
2020
+ _count: array.length,
2021
+ _preview: array.slice(0, MAX_ARRAY_DISPLAY_SIZE).map((item) => sanitizeArrayItem(item, depth, userPatterns))
2022
+ };
2023
+ }
2024
+ function sanitizeArrayItem(item, depth, userPatterns) {
2025
+ if (isPrimitive(item)) return item;
2026
+ if (isPlainObject2(item)) {
2027
+ return sanitizeNestedObject(item, depth + 1, userPatterns);
2028
+ }
2029
+ if (Array.isArray(item)) return sanitizeArrayValue(item, depth + 1, userPatterns);
2030
+ return "[Object]";
2031
+ }
2032
+ function isSensitiveKey2(key, userPatterns) {
2033
+ const lower = key.toLowerCase();
2034
+ if (SENSITIVE_VARIABLE_PATTERNS.some((p) => lower.includes(p))) return true;
2035
+ return userPatterns.some((p) => lower.includes(p.toLowerCase()));
2036
+ }
2037
+ function isPrimitive(value) {
2038
+ return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
2039
+ }
2040
+ function isPlainObject2(value) {
2041
+ if (value === null || typeof value !== "object") return false;
2042
+ const proto = Object.getPrototypeOf(value);
2043
+ return proto === Object.prototype || proto === null;
2044
+ }
2045
+
2046
+ // src/http/source-data.ts
2047
+ function buildHttpSourceData(input) {
2048
+ const { controller, action } = resolveControllerAction(input);
2049
+ const source = {
2050
+ method: input.method,
2051
+ path: input.url.pathname,
2052
+ status_code: input.statusCode,
2053
+ controller,
2054
+ action,
2055
+ format: deriveFormat(input.contentType),
2056
+ user_agent: input.userAgent,
2057
+ remote_ip: input.remoteIp
2058
+ };
2059
+ if (input.serverActionName) {
2060
+ const parsed = parseServerActionName(input.serverActionName);
2061
+ if (parsed.verb) source.verb = parsed.verb;
2062
+ if (parsed.entity) source.entity = parsed.entity;
2063
+ }
2064
+ if (input.graphql) {
2065
+ if (input.graphql.graphql_operation) {
2066
+ source.graphql_operation = input.graphql.graphql_operation;
2067
+ }
2068
+ if (input.graphql.graphql_type) {
2069
+ source.graphql_type = input.graphql.graphql_type;
2070
+ }
2071
+ if (input.graphql.graphql_variables) {
2072
+ source.graphql_variables = input.graphql.graphql_variables;
2073
+ }
2074
+ } else {
2075
+ const params = sanitizeRequestParams(input.rawParams, input.excludedVariableKeys);
2076
+ if (params !== null) source.request_params = params;
2077
+ }
2078
+ return compact(source);
2079
+ }
2080
+ function resolveControllerAction(input) {
2081
+ if (input.serverActionName) {
2082
+ return { controller: "server-action", action: input.serverActionName };
2083
+ }
2084
+ return {
2085
+ controller: input.routeModulePath ?? null,
2086
+ action: input.method
2087
+ };
2088
+ }
2089
+ var KNOWN_VERBS = /* @__PURE__ */ new Map([
2090
+ ["create", "create"],
2091
+ ["add", "create"],
2092
+ ["new", "create"],
2093
+ ["update", "update"],
2094
+ ["edit", "update"],
2095
+ ["save", "update"],
2096
+ ["modify", "update"],
2097
+ ["change", "update"],
2098
+ ["set", "update"],
2099
+ ["rename", "update"],
2100
+ ["delete", "destroy"],
2101
+ ["remove", "destroy"],
2102
+ ["destroy", "destroy"],
2103
+ ["archive", "destroy"],
2104
+ ["bulk", null],
2105
+ // handled below
2106
+ ["mark", null],
2107
+ ["assign", "update"],
2108
+ ["unassign", "update"],
2109
+ ["report", "update"],
2110
+ ["put", "update"],
2111
+ ["list", "read"],
2112
+ ["get", "read"],
2113
+ ["fetch", "read"],
2114
+ ["read", "read"],
2115
+ ["view", "read"],
2116
+ ["search", "read"],
2117
+ ["import", "create"],
2118
+ ["export", "read"],
2119
+ ["upload", "create"],
2120
+ ["download", "read"],
2121
+ ["send", "create"],
2122
+ ["invite", "create"],
2123
+ ["accept", "update"],
2124
+ ["reject", "update"],
2125
+ ["approve", "update"],
2126
+ ["enable", "update"],
2127
+ ["disable", "update"],
2128
+ ["activate", "update"],
2129
+ ["deactivate", "update"],
2130
+ ["start", "update"],
2131
+ ["stop", "update"],
2132
+ ["cancel", "update"],
2133
+ ["complete", "update"],
2134
+ ["sync", "update"],
2135
+ ["refresh", "update"],
2136
+ ["regenerate", "update"],
2137
+ ["resend", "update"],
2138
+ ["restore", "update"],
2139
+ ["duplicate", "create"],
2140
+ ["clone", "create"],
2141
+ ["move", "update"],
2142
+ ["copy", "create"],
2143
+ ["link", "update"],
2144
+ ["unlink", "update"],
2145
+ ["attach", "update"],
2146
+ ["detach", "update"],
2147
+ ["confirm", "update"],
2148
+ ["dismiss", "update"],
2149
+ ["publish", "update"],
2150
+ ["unpublish", "update"]
2151
+ ]);
2152
+ function parseServerActionName(name) {
2153
+ const withoutSuffix = name.replace(/Action$/, "");
2154
+ if (!withoutSuffix) return { verb: null, entity: null };
2155
+ const tokens = withoutSuffix.split(/(?=[A-Z])/).map((t) => t.trim()).filter(Boolean);
2156
+ if (tokens.length === 0) return { verb: null, entity: null };
2157
+ let leading = tokens[0].toLowerCase();
2158
+ let entityStart = 1;
2159
+ if (leading === "bulk" && tokens.length > 1) {
2160
+ leading = tokens[1].toLowerCase();
2161
+ entityStart = 2;
2162
+ }
2163
+ if (leading === "mark") {
2164
+ const asIdx = tokens.findIndex(
2165
+ (t, i) => i > 0 && t.toLowerCase() === "as"
2166
+ );
2167
+ if (asIdx > 1) {
2168
+ const entity2 = tokens.slice(1, asIdx).join("");
2169
+ return { verb: "update", entity: stripTrailingS(entity2) || entity2 };
2170
+ }
2171
+ return { verb: "update", entity: null };
2172
+ }
2173
+ const canonical = KNOWN_VERBS.get(leading);
2174
+ if (!canonical) return { verb: null, entity: null };
2175
+ const entityTokens = tokens.slice(entityStart);
2176
+ if (entityTokens.length === 0) return { verb: canonical, entity: null };
2177
+ const entity = entityTokens.join("");
2178
+ return { verb: canonical, entity: stripTrailingS(entity) || entity };
2179
+ }
2180
+ function stripTrailingS(entity) {
2181
+ if (entity.length <= 1) return entity;
2182
+ if (entity.endsWith("ies")) return `${entity.slice(0, -3)}y`;
2183
+ if (entity.endsWith("s") && !entity.endsWith("ss")) return entity.slice(0, -1);
2184
+ return entity;
2185
+ }
2186
+ function deriveFormat(contentType) {
2187
+ if (!contentType) return null;
2188
+ if (contentType.includes("json")) return "json";
2189
+ if (contentType.includes("xml")) return "xml";
2190
+ if (contentType.includes("form-urlencoded") || contentType.includes("multipart"))
2191
+ return "form";
2192
+ if (contentType.includes("text/html")) return "html";
2193
+ return null;
2194
+ }
2195
+ function compact(obj) {
2196
+ const out = {};
2197
+ for (const key of Object.keys(obj)) {
2198
+ const value = obj[key];
2199
+ if (value !== null && value !== void 0) out[key] = value;
2200
+ }
2201
+ return out;
2202
+ }
2203
+ function determineOutcome(statusCode, exception, graphqlResponseErrors) {
2204
+ if (exception) {
2205
+ return {
2206
+ outcome: "failure",
2207
+ error_message: `${exception.name}: ${exception.message}`
2208
+ };
2209
+ }
2210
+ if (statusCode !== null && statusCode >= 400) {
2211
+ return { outcome: "failure", error_message: `HTTP ${statusCode}` };
2212
+ }
2213
+ if (graphqlResponseErrors) {
2214
+ return { outcome: "failure", error_message: graphqlResponseErrors };
2215
+ }
2216
+ return { outcome: "success", error_message: null };
2217
+ }
2218
+
2219
+ // src/http/graphql.ts
2220
+ var QUERY_PREFIXES = ["Get", "Fetch", "List", "Find", "Load", "Search", "Query"];
2221
+ var MUTATION_PREFIXES = ["Create", "Update", "Delete", "Remove", "Add", "Set", "Upsert"];
2222
+ function isGraphqlPath(path) {
2223
+ return path === "/graphql" || path.startsWith("/graphql/");
2224
+ }
2225
+ function parseGraphqlBody(body, excludedOperations, excludedVariableKeys) {
2226
+ if (!isPlainObject3(body)) return { metadata: null };
2227
+ const obj = body;
2228
+ const queryString = typeof obj.query === "string" ? obj.query : null;
2229
+ let operationName = typeof obj.operationName === "string" ? obj.operationName : null;
2230
+ if (!operationName && queryString) {
2231
+ operationName = extractOperationNameFromQuery(queryString);
2232
+ }
2233
+ if (operationName && isExcludedOperation(operationName, excludedOperations)) {
2234
+ return { metadata: "skip" };
2235
+ }
2236
+ const operationType = inferOperationTypeFromQuery(queryString) ?? inferOperationTypeFromName(operationName);
2237
+ const sanitizedVariables = sanitizeRequestParams(obj.variables, excludedVariableKeys);
2238
+ return {
2239
+ metadata: {
2240
+ graphql_operation: operationName ?? "anonymous",
2241
+ graphql_type: operationType,
2242
+ graphql_variables: sanitizedVariables
2243
+ }
2244
+ };
2245
+ }
2246
+ function inferOperationTypeFromQuery(query) {
2247
+ if (!query) return null;
2248
+ const trimmed = query.trimStart();
2249
+ if (/^mutation/i.test(trimmed)) return "mutation";
2250
+ if (/^subscription/i.test(trimmed)) return "subscription";
2251
+ if (/^query/i.test(trimmed) || trimmed.startsWith("{")) return "query";
2252
+ return null;
2253
+ }
2254
+ function inferOperationTypeFromName(name) {
2255
+ if (!name) return null;
2256
+ if (QUERY_PREFIXES.some((p) => name.startsWith(p))) return "query";
2257
+ if (MUTATION_PREFIXES.some((p) => name.startsWith(p))) return "mutation";
2258
+ return null;
2259
+ }
2260
+ function extractOperationNameFromQuery(query) {
2261
+ const match = query.match(
2262
+ /^\s*(?:query|mutation|subscription)\s+([_A-Za-z][_0-9A-Za-z]*)/i
2263
+ );
2264
+ return match ? match[1] : null;
2265
+ }
2266
+ function isExcludedOperation(name, patterns) {
2267
+ return patterns.some((pattern) => {
2268
+ if (pattern.endsWith("*")) return name.startsWith(pattern.slice(0, -1));
2269
+ return name === pattern;
2270
+ });
2271
+ }
2272
+ function extractGraphqlErrorsFromBody(parsed) {
2273
+ if (!isPlainObject3(parsed)) return null;
2274
+ const errors = parsed.errors;
2275
+ if (!Array.isArray(errors) || errors.length === 0) return null;
2276
+ const messages = errors.map((err) => isPlainObject3(err) ? err.message : null).filter((m) => typeof m === "string" && m.length > 0);
2277
+ if (messages.length === 0) return null;
2278
+ return messages.length === 1 ? messages[0] : messages.join("; ");
2279
+ }
2280
+ function isPlainObject3(value) {
2281
+ if (value === null || typeof value !== "object") return false;
2282
+ const proto = Object.getPrototypeOf(value);
2283
+ return proto === Object.prototype || proto === null;
2284
+ }
2285
+
2286
+ // src/http/capture.ts
2287
+ function captureRoute(handler, context = {}) {
2288
+ return async (...args) => {
2289
+ if (!configuration().captureHttp) {
2290
+ return Promise.resolve(handler(...args));
2291
+ }
2292
+ const request = args[0];
2293
+ if (!request || typeof request !== "object" || !("url" in request)) {
2294
+ return Promise.resolve(handler(...args));
2295
+ }
2296
+ const snapshot = await snapshotRequest(request);
2297
+ if (snapshot === null) return Promise.resolve(handler(...args));
2298
+ const correlationId = resolveCorrelation(request.headers ?? null);
2299
+ return runWithCorrelation(
2300
+ correlationId,
2301
+ () => runWithActorAndAuditScope(async () => {
2302
+ await maybeRunActorHook(request);
2303
+ const startMs = Date.now();
2304
+ let statusCode = null;
2305
+ let response = null;
2306
+ let exception = null;
2307
+ let graphqlErrorMessage = null;
2308
+ try {
2309
+ response = await Promise.resolve(handler(...args));
2310
+ statusCode = response.status;
2311
+ if (snapshot.graphqlBody !== null && response.status === 200) {
2312
+ graphqlErrorMessage = await readGraphqlErrors(response);
2313
+ }
2314
+ return response;
2315
+ } catch (e) {
2316
+ exception = e instanceof Error ? e : new Error(String(e));
2317
+ throw e;
2318
+ } finally {
2319
+ await maybeExtractSupabaseActor();
2320
+ await emitEvent({
2321
+ snapshot,
2322
+ context,
2323
+ statusCode,
2324
+ exception,
2325
+ graphqlErrorMessage,
2326
+ durationMs: Date.now() - startMs,
2327
+ startedAt: new Date(startMs)
2328
+ });
2329
+ if (isServerless()) {
2330
+ await flushScheduler.flushNow().catch(() => {
2331
+ });
2332
+ }
2333
+ }
2334
+ })
2335
+ );
2336
+ };
2337
+ }
2338
+ var CORRELATION_HEADER2 = "x-ezlogs-correlation-id";
2339
+ function withMiddlewareCapture(middleware) {
2340
+ return async (request, ...rest) => {
2341
+ const correlationId = resolveCorrelation(request.headers);
2342
+ try {
2343
+ request.headers.set(CORRELATION_HEADER2, correlationId);
2344
+ } catch {
2345
+ }
2346
+ return runWithCorrelation(
2347
+ correlationId,
2348
+ () => runWithActorAndAuditScope(async () => {
2349
+ const startMs = Date.now();
2350
+ const startedAt = new Date(startMs);
2351
+ const response = await Promise.resolve(middleware(request, ...rest));
2352
+ try {
2353
+ if (response?.headers && typeof response.headers.set === "function") {
2354
+ response.headers.set(CORRELATION_HEADER2, correlationId);
2355
+ }
2356
+ } catch {
2357
+ }
2358
+ try {
2359
+ if (shouldEmitPageNavigation(request)) {
2360
+ await maybeRunActorHook(request);
2361
+ await maybeExtractSupabaseActor();
2362
+ await emitPageNavigationEvent({
2363
+ request,
2364
+ statusCode: typeof response?.status === "number" ? response.status : null,
2365
+ durationMs: Date.now() - startMs,
2366
+ startedAt
2367
+ });
2368
+ }
2369
+ } catch (error) {
2370
+ logger.debug(`page navigation capture failed: ${describeError7(error)}`);
2371
+ }
2372
+ return response;
2373
+ })
2374
+ );
2375
+ };
2376
+ }
2377
+ function shouldEmitPageNavigation(request) {
2378
+ if (request.method !== "GET") return false;
2379
+ if (request.headers.get("next-action")) return false;
2380
+ if (request.headers.get("rsc")) return false;
2381
+ if (request.headers.get("next-router-prefetch")) return false;
2382
+ let url;
2383
+ try {
2384
+ url = new URL(request.url);
2385
+ } catch {
2386
+ return false;
2387
+ }
2388
+ if (url.searchParams.has("_rsc")) return false;
2389
+ if (isExcludedPath(url.pathname, request.method)) return false;
2390
+ if (url.pathname.startsWith("/api/")) return false;
2391
+ return true;
2392
+ }
2393
+ async function emitPageNavigationEvent(input) {
2394
+ try {
2395
+ await flushTriggerAuditLog();
2396
+ const url = new URL(input.request.url);
2397
+ const userAgent = input.request.headers.get("user-agent");
2398
+ const remoteIp = extractRemoteIp(input.request.headers);
2399
+ const sourceData = buildHttpSourceData({
2400
+ method: "GET",
2401
+ url,
2402
+ statusCode: input.statusCode,
2403
+ rawParams: null,
2404
+ // Synthesize a Rails-like controller name from the path so the
2405
+ // dashboard's NLP can produce "Viewed <page>" titles consistent
2406
+ // with the Ruby agent's output.
2407
+ routeModulePath: pageControllerFromPath(url.pathname),
2408
+ userAgent,
2409
+ remoteIp,
2410
+ contentType: null,
2411
+ excludedVariableKeys: configuration().excludedGraphqlVariableKeys
2412
+ });
2413
+ const { outcome, error_message } = determineOutcome(
2414
+ input.statusCode,
2415
+ null,
2416
+ null
2417
+ );
2418
+ const event = build({
2419
+ source_type: "http_request",
2420
+ source_data: sourceData,
2421
+ outcome,
2422
+ correlation_id: current(),
2423
+ resource_ids: [],
2424
+ context: getCurrentActor() ? { actor: getCurrentActor() } : null,
2425
+ duration_ms: input.durationMs,
2426
+ error_message,
2427
+ timestamp: input.startedAt
2428
+ });
2429
+ pushEvent(event);
2430
+ } catch (error) {
2431
+ logger.error(`page navigation emit failed: ${describeError7(error)}`);
2432
+ }
2433
+ }
2434
+ function pageControllerFromPath(pathname) {
2435
+ const stripped = pathname.replace(/^\/+|\/+$/g, "");
2436
+ if (!stripped) return "page:home";
2437
+ const segments = stripped.split("/").map((segment) => {
2438
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(segment)) {
2439
+ return "[id]";
2440
+ }
2441
+ if (/^\d+$/.test(segment)) return "[id]";
2442
+ return segment;
2443
+ });
2444
+ return `page:${segments.join("/")}`;
2445
+ }
2446
+ function capturePagesApi(handler, context = {}) {
2447
+ return async (...args) => {
2448
+ if (!configuration().captureHttp) {
2449
+ return Promise.resolve(handler(...args));
2450
+ }
2451
+ const req = args[0];
2452
+ const res = args[1];
2453
+ if (!req || !res) return Promise.resolve(handler(...args));
2454
+ const snapshot = snapshotPagesRequest(req);
2455
+ if (snapshot === null) return Promise.resolve(handler(...args));
2456
+ const correlationId = resolveCorrelation({
2457
+ get: (name) => readPagesHeader(req, name)
2458
+ });
2459
+ return runWithCorrelation(
2460
+ correlationId,
2461
+ () => runWithActorAndAuditScope(async () => {
2462
+ await maybeRunActorHookFromPages(req);
2463
+ const startMs = Date.now();
2464
+ let exception = null;
2465
+ try {
2466
+ const result = await Promise.resolve(handler(...args));
2467
+ return result;
2468
+ } catch (e) {
2469
+ exception = e instanceof Error ? e : new Error(String(e));
2470
+ throw e;
2471
+ } finally {
2472
+ await maybeExtractSupabaseActor();
2473
+ await emitEvent({
2474
+ snapshot,
2475
+ context,
2476
+ statusCode: typeof res.statusCode === "number" ? res.statusCode : null,
2477
+ exception,
2478
+ graphqlErrorMessage: null,
2479
+ durationMs: Date.now() - startMs,
2480
+ startedAt: new Date(startMs)
2481
+ });
2482
+ if (isServerless()) {
2483
+ await flushScheduler.flushNow().catch(() => void 0);
2484
+ }
2485
+ }
2486
+ })
2487
+ );
2488
+ };
2489
+ }
2490
+ function captureServerAction(action, actionName) {
2491
+ return async (...args) => {
2492
+ if (!configuration().captureHttp) {
2493
+ return Promise.resolve(action(...args));
2494
+ }
2495
+ const headersAdapter = await readNextHeadersAsAdapter();
2496
+ const correlationId = resolveCorrelation(headersAdapter);
2497
+ return runWithCorrelation(
2498
+ correlationId,
2499
+ () => runWithActorAndAuditScope(async () => {
2500
+ const startMs = Date.now();
2501
+ const startedAt = new Date(startMs);
2502
+ let exception = null;
2503
+ await maybeRunActorHookFromServerAction();
2504
+ try {
2505
+ const result = await Promise.resolve(action(...args));
2506
+ await maybeExtractSupabaseActor();
2507
+ const failure = classifyServerActionResult(result);
2508
+ await emitServerActionEvent({
2509
+ actionName,
2510
+ statusCode: failure ? 500 : 200,
2511
+ exception: failure ? new Error(failure.errorMessage) : null,
2512
+ durationMs: Date.now() - startMs,
2513
+ startedAt,
2514
+ args
2515
+ });
2516
+ return result;
2517
+ } catch (e) {
2518
+ if (isNextControlFlowError(e)) {
2519
+ await maybeExtractSupabaseActor();
2520
+ await emitServerActionEvent({
2521
+ actionName,
2522
+ statusCode: 200,
2523
+ exception: null,
2524
+ durationMs: Date.now() - startMs,
2525
+ startedAt,
2526
+ args
2527
+ });
2528
+ throw e;
2529
+ }
2530
+ exception = e instanceof Error ? e : new Error(String(e));
2531
+ await maybeExtractSupabaseActor();
2532
+ await emitServerActionEvent({
2533
+ actionName,
2534
+ statusCode: 500,
2535
+ exception,
2536
+ durationMs: Date.now() - startMs,
2537
+ startedAt,
2538
+ args
2539
+ });
2540
+ throw e;
2541
+ } finally {
2542
+ if (isServerless()) {
2543
+ await flushScheduler.flushNow().catch(() => void 0);
2544
+ }
2545
+ }
2546
+ })
2547
+ );
2548
+ };
2549
+ }
2550
+ function captureServerActionExport(value, actionName) {
2551
+ if (typeof value !== "function") return value;
2552
+ return captureServerAction(
2553
+ value,
2554
+ actionName
2555
+ );
2556
+ }
2557
+ async function __ezlogs_run_inline_server_action(actionName, body) {
2558
+ const wrapped = captureServerAction(
2559
+ async () => Promise.resolve(body()),
2560
+ actionName
2561
+ );
2562
+ return wrapped();
2563
+ }
2564
+ function classifyServerActionResult(result) {
2565
+ const classifier = configuration().isServerActionError;
2566
+ if (classifier) {
2567
+ try {
2568
+ const verdict = classifier(result);
2569
+ if (verdict === true) {
2570
+ return { errorMessage: defaultErrorMessage(result) };
2571
+ }
2572
+ if (verdict && typeof verdict === "object" && typeof verdict.errorMessage === "string") {
2573
+ return verdict;
2574
+ }
2575
+ } catch (error) {
2576
+ logger.debug(`isServerActionError classifier threw: ${describeError7(error)}`);
2577
+ }
2578
+ }
2579
+ if (Array.isArray(result) && result.length === 2 && result[0] === null && isZsaError(result[1])) {
2580
+ const err = result[1];
2581
+ return { errorMessage: truncate(err.message) };
2582
+ }
2583
+ if (result && typeof result === "object") {
2584
+ const r = result;
2585
+ if (typeof r.serverError === "string" && r.serverError.length > 0) {
2586
+ return { errorMessage: truncate(r.serverError) };
2587
+ }
2588
+ if (r.validationErrors && typeof r.validationErrors === "object" && !Array.isArray(r.validationErrors) && hasNonEmptyValidationError(r.validationErrors)) {
2589
+ return {
2590
+ errorMessage: formatValidationErrors(
2591
+ r.validationErrors
2592
+ )
2593
+ };
2594
+ }
2595
+ if (r.data === null && isZsaError(r.error)) {
2596
+ const err = r.error;
2597
+ return { errorMessage: truncate(err.message) };
2598
+ }
2599
+ if (r.status === "error" && "intent" in r) {
2600
+ return { errorMessage: conformErrorMessage(r) };
2601
+ }
2602
+ if (r.success === false && isZodErrorLike(r.error)) {
2603
+ return {
2604
+ errorMessage: formatZodIssues(
2605
+ r.error.issues
2606
+ )
2607
+ };
2608
+ }
2609
+ if (r.success === false && typeof r.error === "string" && r.error.length > 0) {
2610
+ return { errorMessage: truncate(r.error) };
2611
+ }
2612
+ }
2613
+ return null;
2614
+ }
2615
+ function defaultErrorMessage(result) {
2616
+ if (result && typeof result === "object" && !Array.isArray(result)) {
2617
+ const r = result;
2618
+ if (typeof r.serverError === "string" && r.serverError.length > 0) {
2619
+ return truncate(r.serverError);
2620
+ }
2621
+ const err = r.error;
2622
+ if (typeof err === "string" && err.length > 0) return truncate(err);
2623
+ if (isZsaError(err)) return truncate(err.message);
2624
+ if (isZodErrorLike(err)) {
2625
+ return formatZodIssues(err.issues);
2626
+ }
2627
+ }
2628
+ if (Array.isArray(result) && result.length === 2 && result[0] === null && isZsaError(result[1])) {
2629
+ return truncate(result[1].message);
2630
+ }
2631
+ return "Server Action returned a failure result";
2632
+ }
2633
+ var MAX_ERROR_MESSAGE_LENGTH = 200;
2634
+ function truncate(value) {
2635
+ if (value.length <= MAX_ERROR_MESSAGE_LENGTH) return value;
2636
+ return value.slice(0, MAX_ERROR_MESSAGE_LENGTH - 1) + "\u2026";
2637
+ }
2638
+ function isZsaError(value) {
2639
+ if (!value || typeof value !== "object") return false;
2640
+ const v = value;
2641
+ return typeof v.code === "string" && typeof v.message === "string" && v.message.length > 0;
2642
+ }
2643
+ function isZodErrorLike(value) {
2644
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2645
+ const issues = value.issues;
2646
+ return Array.isArray(issues) && issues.length > 0;
2647
+ }
2648
+ function formatZodIssues(issues) {
2649
+ const messages = [];
2650
+ for (const issue of issues) {
2651
+ if (issue && typeof issue === "object") {
2652
+ const m = issue.message;
2653
+ if (typeof m === "string" && m.length > 0) messages.push(m);
2654
+ }
2655
+ if (messages.length >= 3) break;
2656
+ }
2657
+ if (messages.length === 0) return "Validation failed";
2658
+ return truncate(messages.join("; "));
2659
+ }
2660
+ function hasNonEmptyValidationError(errors) {
2661
+ for (const value of Object.values(errors)) {
2662
+ if (Array.isArray(value) && value.length > 0) return true;
2663
+ if (typeof value === "string" && value.length > 0) return true;
2664
+ if (value && typeof value === "object" && Object.keys(value).length > 0) {
2665
+ return true;
2666
+ }
2667
+ }
2668
+ return false;
2669
+ }
2670
+ function formatValidationErrors(errors) {
2671
+ const parts = [];
2672
+ for (const [field, value] of Object.entries(errors)) {
2673
+ if (Array.isArray(value) && value.length > 0 && typeof value[0] === "string") {
2674
+ parts.push(`${field}: ${value[0]}`);
2675
+ } else if (typeof value === "string" && value.length > 0) {
2676
+ parts.push(`${field}: ${value}`);
2677
+ }
2678
+ if (parts.length >= 3) break;
2679
+ }
2680
+ if (parts.length === 0) return "Validation failed";
2681
+ return truncate(parts.join("; "));
2682
+ }
2683
+ function conformErrorMessage(result) {
2684
+ const candidates = [
2685
+ result.error,
2686
+ result.submission?.error
2687
+ ];
2688
+ for (const c of candidates) {
2689
+ if (c && typeof c === "object" && !Array.isArray(c)) {
2690
+ const formatted = formatValidationErrors(c);
2691
+ if (formatted !== "Validation failed") return formatted;
2692
+ }
2693
+ }
2694
+ return "Form submission failed";
2695
+ }
2696
+ function isNextControlFlowError(error) {
2697
+ if (!error || typeof error !== "object") return false;
2698
+ const digest = error.digest;
2699
+ if (typeof digest !== "string") return false;
2700
+ return digest.startsWith("NEXT_REDIRECT") || digest.startsWith("NEXT_NOT_FOUND");
2701
+ }
2702
+ async function emitServerActionEvent(input) {
2703
+ try {
2704
+ await flushTriggerAuditLog();
2705
+ const referer = await readNextHeader("referer");
2706
+ const nextUrl = await readNextHeader("next-url");
2707
+ const userAgent = await readNextHeader("user-agent");
2708
+ const fromPage = referer ?? nextUrl ?? null;
2709
+ const argParams = extractServerActionArgs(input.args);
2710
+ const requestParams = argParams !== null || fromPage !== null ? { ...argParams ?? {}, ...fromPage !== null ? { from_page: fromPage } : {} } : null;
2711
+ const syntheticUrl = new URL(
2712
+ `http://localhost/__server-action/${encodeURIComponent(input.actionName)}`
2713
+ );
2714
+ const sourceData = buildHttpSourceData({
2715
+ method: "POST",
2716
+ // Server Actions are always POST under the hood.
2717
+ url: syntheticUrl,
2718
+ statusCode: input.statusCode,
2719
+ rawParams: requestParams,
2720
+ serverActionName: input.actionName,
2721
+ userAgent,
2722
+ remoteIp: null,
2723
+ contentType: null,
2724
+ excludedVariableKeys: configuration().excludedGraphqlVariableKeys
2725
+ });
2726
+ const { outcome, error_message } = determineOutcome(
2727
+ input.statusCode,
2728
+ input.exception,
2729
+ null
2730
+ );
2731
+ const event = build({
2732
+ source_type: "http_request",
2733
+ source_data: sourceData,
2734
+ outcome,
2735
+ correlation_id: current(),
2736
+ resource_ids: [],
2737
+ context: getCurrentActor() ? { actor: getCurrentActor() } : null,
2738
+ duration_ms: input.durationMs,
2739
+ error_message,
2740
+ timestamp: input.startedAt
2741
+ });
2742
+ pushEvent(event);
2743
+ } catch (error) {
2744
+ logger.error(`server-action capture emit failed: ${describeError7(error)}`);
2745
+ }
2746
+ }
2747
+ function extractServerActionArgs(args) {
2748
+ if (!args || args.length === 0) return null;
2749
+ const payloadIndex = findPayloadIndex(args);
2750
+ if (payloadIndex !== -1) {
2751
+ const payload = args[payloadIndex];
2752
+ const out2 = {};
2753
+ if (typeof FormData !== "undefined" && payload instanceof FormData) {
2754
+ Object.assign(out2, formDataToObject(payload));
2755
+ } else if (isPlainParamObject(payload)) {
2756
+ Object.assign(out2, payload);
2757
+ }
2758
+ return Object.keys(out2).length === 0 ? null : out2;
2759
+ }
2760
+ const out = {};
2761
+ args.forEach((a, i) => {
2762
+ if (isInsignificantArg(a)) return;
2763
+ const v = serializeArgValue(a);
2764
+ if (v !== void 0) out[`arg${i}`] = v;
2765
+ });
2766
+ return Object.keys(out).length === 0 ? null : out;
2767
+ }
2768
+ function findPayloadIndex(args) {
2769
+ for (let i = args.length - 1; i >= 0; i -= 1) {
2770
+ if (typeof FormData !== "undefined" && args[i] instanceof FormData) {
2771
+ return i;
2772
+ }
2773
+ }
2774
+ for (let i = 0; i < args.length; i += 1) {
2775
+ const a = args[i];
2776
+ if (isPlainParamObject(a) && Object.keys(a).length > 0) {
2777
+ return i;
2778
+ }
2779
+ }
2780
+ for (let i = 0; i < args.length; i += 1) {
2781
+ if (isPlainParamObject(args[i])) return i;
2782
+ }
2783
+ return -1;
2784
+ }
2785
+ function isInsignificantArg(value) {
2786
+ if (value === void 0) return true;
2787
+ if (typeof value === "function") return true;
2788
+ if (isPlainParamObject(value) && Object.keys(value).length === 0) {
2789
+ return true;
2790
+ }
2791
+ return false;
2792
+ }
2793
+ function formDataToObject(fd) {
2794
+ const out = {};
2795
+ const seen = /* @__PURE__ */ new Set();
2796
+ for (const key of fd.keys()) {
2797
+ if (seen.has(key)) continue;
2798
+ seen.add(key);
2799
+ if (key.startsWith("$") || key.startsWith("_")) continue;
2800
+ const value = fd.get(key);
2801
+ if (value === null) continue;
2802
+ if (typeof value === "string") {
2803
+ out[key] = value;
2804
+ } else {
2805
+ const file = value;
2806
+ out[key] = {
2807
+ _file: typeof file.name === "string" ? file.name : "<file>",
2808
+ size: typeof file.size === "number" ? file.size : null,
2809
+ type: typeof file.type === "string" ? file.type : null
2810
+ };
2811
+ }
2812
+ }
2813
+ return out;
2814
+ }
2815
+ function isPlainParamObject(value) {
2816
+ if (value === null || typeof value !== "object") return false;
2817
+ if (Array.isArray(value)) return false;
2818
+ if (typeof FormData !== "undefined" && value instanceof FormData) return false;
2819
+ const proto = Object.getPrototypeOf(value);
2820
+ return proto === Object.prototype || proto === null;
2821
+ }
2822
+ function serializeArgValue(value) {
2823
+ if (value === void 0) return void 0;
2824
+ if (typeof value === "function") return void 0;
2825
+ if (typeof FormData !== "undefined" && value instanceof FormData) {
2826
+ return formDataToObject(value);
2827
+ }
2828
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
2829
+ return value;
2830
+ }
2831
+ if (typeof value === "bigint") return value.toString();
2832
+ if (Array.isArray(value)) return value.map(serializeArgValue);
2833
+ if (isPlainParamObject(value)) {
2834
+ const out = {};
2835
+ for (const [k, v] of Object.entries(value)) out[k] = serializeArgValue(v);
2836
+ return out;
2837
+ }
2838
+ return void 0;
2839
+ }
2840
+ async function captureHttpEvent(input) {
2841
+ if (!configuration().captureHttp) return;
2842
+ const snapshot = await snapshotRequest(input.request);
2843
+ if (snapshot === null) return;
2844
+ let graphqlErrorMessage = null;
2845
+ if (snapshot.graphqlBody !== null && input.response && input.response.status === 200) {
2846
+ graphqlErrorMessage = await readGraphqlErrors(input.response);
2847
+ }
2848
+ await emitEvent({
2849
+ snapshot,
2850
+ context: input.context ?? {},
2851
+ statusCode: input.response?.status ?? null,
2852
+ exception: input.error,
2853
+ graphqlErrorMessage,
2854
+ durationMs: input.durationMs,
2855
+ startedAt: input.startedAt ?? /* @__PURE__ */ new Date()
2856
+ });
2857
+ }
2858
+ async function snapshotRequest(request) {
2859
+ let url;
2860
+ try {
2861
+ url = new URL(request.url);
2862
+ } catch {
2863
+ return null;
2864
+ }
2865
+ if (isExcludedPath(url.pathname, request.method)) return null;
2866
+ const method = request.method;
2867
+ const headers = request.headers;
2868
+ const userAgent = headers.get("user-agent");
2869
+ const remoteIp = extractRemoteIp(headers);
2870
+ const contentType = headers.get("content-type");
2871
+ const serverActionId = headers.get("next-action");
2872
+ let rawParams = null;
2873
+ let graphqlBody = null;
2874
+ if (method === "GET" || method === "HEAD") {
2875
+ const params = Object.fromEntries(url.searchParams.entries());
2876
+ rawParams = Object.keys(params).length === 0 ? null : params;
2877
+ return { method, url, userAgent, remoteIp, contentType, rawParams, graphqlBody, serverActionId };
2878
+ }
2879
+ const cloned = safeClone(request);
2880
+ if (!cloned) {
2881
+ return { method, url, userAgent, remoteIp, contentType, rawParams, graphqlBody, serverActionId };
2882
+ }
2883
+ const isGraphql = method === "POST" && isGraphqlPath(url.pathname);
2884
+ try {
2885
+ if (contentType?.includes("application/json")) {
2886
+ const text = await cloned.text();
2887
+ const parsed = text ? safeJsonParse(text) : null;
2888
+ if (isGraphql) graphqlBody = parsed;
2889
+ else rawParams = parsed;
2890
+ } else if (contentType?.includes("application/x-www-form-urlencoded")) {
2891
+ const text = await cloned.text();
2892
+ if (text) {
2893
+ const params = new URLSearchParams(text);
2894
+ const obj = {};
2895
+ params.forEach((value, key) => {
2896
+ obj[key] = value;
2897
+ });
2898
+ rawParams = Object.keys(obj).length === 0 ? null : obj;
2899
+ }
2900
+ }
2901
+ } catch (error) {
2902
+ logger.debug(`http snapshot body-parse failed: ${describeError7(error)}`);
2903
+ }
2904
+ return { method, url, userAgent, remoteIp, contentType, rawParams, graphqlBody, serverActionId };
2905
+ }
2906
+ async function maybeRunActorHook(request) {
2907
+ const hook = configuration().actorFromRequest;
2908
+ if (!hook) return;
2909
+ try {
2910
+ const result = await Promise.resolve(hook(request));
2911
+ setActor(result ?? null);
2912
+ } catch (error) {
2913
+ logger.debug(`actorFromRequest hook failed: ${describeError7(error)}`);
2914
+ }
2915
+ }
2916
+ async function maybeRunActorHookFromPages(req) {
2917
+ const hook = configuration().actorFromRequest;
2918
+ if (!hook) return;
2919
+ try {
2920
+ const result = await Promise.resolve(hook(req));
2921
+ setActor(result ?? null);
2922
+ } catch (error) {
2923
+ logger.debug(`actorFromRequest hook (pages) failed: ${describeError7(error)}`);
2924
+ }
2925
+ }
2926
+ async function maybeRunActorHookFromServerAction() {
2927
+ const hook = configuration().actorFromRequest;
2928
+ if (!hook) {
2929
+ logger.debug("actorFromRequest hook (server action): no hook configured");
2930
+ return;
2931
+ }
2932
+ const headers = await loadNextHeaders();
2933
+ if (!headers) {
2934
+ logger.debug(
2935
+ "actorFromRequest hook (server action): skipped, no next/headers available"
2936
+ );
2937
+ return;
2938
+ }
2939
+ const facade = {
2940
+ headers,
2941
+ method: "POST",
2942
+ url: ""
2943
+ };
2944
+ try {
2945
+ const result = await Promise.resolve(hook(facade));
2946
+ if (result) {
2947
+ logger.debug(
2948
+ `actorFromRequest hook (server action): set actor id=${result.id ?? "?"}`
2949
+ );
2950
+ } else {
2951
+ logger.debug(
2952
+ "actorFromRequest hook (server action): returned null/undefined"
2953
+ );
2954
+ }
2955
+ setActor(result ?? null);
2956
+ } catch (error) {
2957
+ logger.debug(
2958
+ `actorFromRequest hook (server action) failed: ${describeError7(error)}`
2959
+ );
2960
+ }
2961
+ }
2962
+ async function maybeExtractSupabaseActor() {
2963
+ const config = configuration();
2964
+ if (!config.actorFromSupabase) return;
2965
+ if (getCurrentActor()) return;
2966
+ try {
2967
+ const mod = await Promise.resolve().then(() => (init_supabase(), supabase_exports));
2968
+ const actor = await mod.tryExtractSupabaseActor();
2969
+ if (actor) setActor(actor);
2970
+ } catch (error) {
2971
+ logger.debug(`actorFromSupabase failed: ${describeError7(error)}`);
2972
+ }
2973
+ }
2974
+ function snapshotPagesRequest(req) {
2975
+ let url;
2976
+ try {
2977
+ url = new URL(req.url ?? "/", "http://internal.localhost");
2978
+ } catch {
2979
+ return null;
2980
+ }
2981
+ if (isExcludedPath(url.pathname, req.method)) return null;
2982
+ const method = (req.method ?? "GET").toUpperCase();
2983
+ const headers = pagesHeaders(req.headers);
2984
+ const userAgent = headers.get("user-agent");
2985
+ const remoteIp = extractRemoteIp(headers) ?? req.socket?.remoteAddress ?? null;
2986
+ const contentType = headers.get("content-type");
2987
+ let rawParams = null;
2988
+ let graphqlBody = null;
2989
+ if (method === "GET" || method === "HEAD") {
2990
+ const params = {};
2991
+ if (req.query) {
2992
+ for (const key of Object.keys(req.query)) {
2993
+ params[key] = req.query[key] ?? null;
2994
+ }
2995
+ }
2996
+ rawParams = Object.keys(params).length === 0 ? null : params;
2997
+ } else {
2998
+ const isGraphql = method === "POST" && isGraphqlPath(url.pathname);
2999
+ if (req.body && typeof req.body === "object" && !Array.isArray(req.body)) {
3000
+ if (isGraphql) graphqlBody = req.body;
3001
+ else rawParams = req.body;
3002
+ }
3003
+ }
3004
+ return { method, url, userAgent, remoteIp, contentType, rawParams, graphqlBody, serverActionId: null };
3005
+ }
3006
+ function pagesHeaders(raw) {
3007
+ if (raw instanceof Headers) return raw;
3008
+ const out = new Headers();
3009
+ for (const key of Object.keys(raw)) {
3010
+ const value = raw[key];
3011
+ if (value === void 0) continue;
3012
+ if (Array.isArray(value)) {
3013
+ out.set(key, value.join(", "));
3014
+ } else {
3015
+ out.set(key, value);
3016
+ }
3017
+ }
3018
+ return out;
3019
+ }
3020
+ async function readNextHeader(name) {
3021
+ const headers = await loadNextHeaders();
3022
+ if (!headers) return null;
3023
+ try {
3024
+ return headers.get(name);
3025
+ } catch {
3026
+ return null;
3027
+ }
3028
+ }
3029
+ async function readNextHeadersAsAdapter() {
3030
+ const headers = await loadNextHeaders();
3031
+ if (!headers) return { get: () => null };
3032
+ return {
3033
+ get(name) {
3034
+ try {
3035
+ return headers.get(name);
3036
+ } catch {
3037
+ return null;
3038
+ }
3039
+ }
3040
+ };
3041
+ }
3042
+ async function loadNextHeaders() {
3043
+ try {
3044
+ const mod = await import('next/headers');
3045
+ return await Promise.resolve(mod.headers());
3046
+ } catch (error) {
3047
+ logger.debug(`loadNextHeaders failed: ${describeError7(error)}`);
3048
+ return null;
3049
+ }
3050
+ }
3051
+ function readPagesHeader(req, name) {
3052
+ const raw = req.headers;
3053
+ if (raw instanceof Headers) return raw.get(name);
3054
+ const lower = name.toLowerCase();
3055
+ const value = raw?.[lower] ?? raw?.[name];
3056
+ if (typeof value === "string") return value;
3057
+ if (Array.isArray(value)) return value[0] ?? null;
3058
+ return null;
3059
+ }
3060
+ async function emitEvent(input) {
3061
+ try {
3062
+ await flushTriggerAuditLog();
3063
+ const config = configuration();
3064
+ let graphql = null;
3065
+ if (input.snapshot.graphqlBody !== null) {
3066
+ const parsed = parseGraphqlBody(
3067
+ input.snapshot.graphqlBody,
3068
+ config.allExcludedGraphqlOperations(),
3069
+ config.excludedGraphqlVariableKeys
3070
+ );
3071
+ if (parsed.metadata === "skip") return;
3072
+ graphql = parsed.metadata;
3073
+ }
3074
+ const serverActionName = input.context.serverActionName ?? (input.snapshot.serverActionId ? `server-action:${input.snapshot.serverActionId.slice(0, 12)}` : null);
3075
+ const sourceDataInput = {
3076
+ method: input.snapshot.method,
3077
+ url: input.snapshot.url,
3078
+ statusCode: input.statusCode,
3079
+ rawParams: input.snapshot.rawParams,
3080
+ routeModulePath: input.context.routeModulePath ?? null,
3081
+ serverActionName,
3082
+ userAgent: input.snapshot.userAgent,
3083
+ remoteIp: input.snapshot.remoteIp,
3084
+ contentType: input.snapshot.contentType,
3085
+ excludedVariableKeys: config.excludedGraphqlVariableKeys,
3086
+ ...graphql !== null ? { graphql } : {}
3087
+ };
3088
+ const sourceData = buildHttpSourceData(sourceDataInput);
3089
+ const { outcome, error_message } = determineOutcome(
3090
+ input.statusCode,
3091
+ input.exception,
3092
+ input.graphqlErrorMessage
3093
+ );
3094
+ const contextValue = buildContext2();
3095
+ const event = build({
3096
+ source_type: "http_request",
3097
+ source_data: sourceData,
3098
+ outcome,
3099
+ correlation_id: current(),
3100
+ resource_ids: [],
3101
+ context: contextValue,
3102
+ duration_ms: input.durationMs,
3103
+ error_message,
3104
+ timestamp: input.startedAt
3105
+ });
3106
+ pushEvent(event);
3107
+ } catch (error) {
3108
+ logger.error(`http capture emit failed: ${describeError7(error)}`);
3109
+ }
3110
+ }
3111
+ function buildContext2() {
3112
+ const currentActor = getCurrentActor();
3113
+ if (!currentActor) return null;
3114
+ return { actor: currentActor };
3115
+ }
3116
+ async function flushTriggerAuditLog() {
3117
+ const reader = configuration().databaseReader;
3118
+ if (!reader) return;
3119
+ await flushAuditLog(reader);
3120
+ }
3121
+ async function takeTriggerAuditSnapshotIfEnabled() {
3122
+ const config = configuration();
3123
+ if (!config.databaseSnapshotMode) return;
3124
+ if (!config.databaseReader) return;
3125
+ await takeAuditSnapshot(config.databaseReader);
3126
+ }
3127
+ function runWithActorAndAuditScope(callback) {
3128
+ if (!configuration().databaseSnapshotMode) {
3129
+ return runWithActorScope(callback);
3130
+ }
3131
+ return runWithActorScope(
3132
+ () => runWithAuditSnapshotScope(async () => {
3133
+ await takeTriggerAuditSnapshotIfEnabled();
3134
+ return callback();
3135
+ })
3136
+ );
3137
+ }
3138
+ function isExcludedPath(path, method) {
3139
+ const config = configuration();
3140
+ const normalizedMethod = (method ?? "").toUpperCase();
3141
+ for (const pattern of config.allExcludedPaths()) {
3142
+ if (typeof pattern === "string") {
3143
+ if (pathMatches(path, pattern)) return true;
3144
+ continue;
3145
+ }
3146
+ if (!pathMatches(path, pattern.path)) continue;
3147
+ if (pattern.methods.some((m) => m.toUpperCase() === normalizedMethod)) {
3148
+ return true;
3149
+ }
3150
+ }
3151
+ if (hasExcludedExtension(path, DEFAULT_EXCLUDED_EXTENSIONS)) return true;
3152
+ return false;
3153
+ }
3154
+ function extractRemoteIp(headers) {
3155
+ const xff = headers.get("x-forwarded-for");
3156
+ if (xff) return xff.split(",")[0]?.trim() ?? null;
3157
+ return headers.get("x-real-ip") ?? null;
3158
+ }
3159
+ function safeClone(request) {
3160
+ try {
3161
+ return request.clone();
3162
+ } catch {
3163
+ return null;
3164
+ }
3165
+ }
3166
+ function safeJsonParse(text) {
3167
+ try {
3168
+ return JSON.parse(text);
3169
+ } catch {
3170
+ return null;
3171
+ }
3172
+ }
3173
+ async function readGraphqlErrors(response) {
3174
+ try {
3175
+ const cloned = response.clone();
3176
+ const text = await cloned.text();
3177
+ if (!text) return null;
3178
+ const parsed = safeJsonParse(text);
3179
+ return extractGraphqlErrorsFromBody(parsed);
3180
+ } catch {
3181
+ return null;
3182
+ }
3183
+ }
3184
+ function describeError7(error) {
3185
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
3186
+ return String(error);
3187
+ }
3188
+
3189
+ // src/index.ts
3190
+ var initialized = false;
3191
+ var beforeExitInstalled = false;
3192
+ var ezlogs = {
3193
+ init(options) {
3194
+ const config = configuration();
3195
+ config.apply(options);
3196
+ if (options.logLevel) setLogLevel(options.logLevel);
3197
+ flushScheduler.start();
3198
+ if (config.patchGlobalFetch) patchGlobalFetch();
3199
+ const resolvedDbUrl = options.databaseUrl ?? detectDatabaseUrlFromEnv();
3200
+ if (resolvedDbUrl && !options.databaseReader) {
3201
+ autoWireTriggerPathFromDatabaseUrl(
3202
+ { ...options, databaseUrl: resolvedDbUrl }
3203
+ ).catch((err) => {
3204
+ if (process.env.NODE_ENV !== "production") {
3205
+ console.warn(
3206
+ `[ezlogs] auto-wire from databaseUrl failed: ${err instanceof Error ? err.message : String(err)}`
3207
+ );
3208
+ }
3209
+ });
3210
+ } else if (options.patchDatabaseClient) {
3211
+ patchPgClient(
3212
+ options.patchDatabaseClient
3213
+ );
3214
+ }
3215
+ applyDatabaseReaderDefaults(options);
3216
+ installBeforeExitHook();
3217
+ initialized = true;
3218
+ },
3219
+ /**
3220
+ * Drain the buffer and ship its contents now. Always call this before
3221
+ * a serverless handler returns — Vercel/Lambda will freeze the
3222
+ * process and the periodic flush timer will never fire.
3223
+ */
3224
+ async flush() {
3225
+ if (!initialized) return;
3226
+ await flushScheduler.flushNow();
3227
+ },
3228
+ /** Stop the periodic scheduler and flush remaining events. */
3229
+ async shutdown() {
3230
+ if (!initialized) return;
3231
+ await flushScheduler.stop();
3232
+ unpatchGlobalFetch();
3233
+ initialized = false;
3234
+ }
3235
+ };
3236
+ function _detectDatabaseUrlFromEnvForTests() {
3237
+ return detectDatabaseUrlFromEnv();
3238
+ }
3239
+ function detectDatabaseUrlFromEnv() {
3240
+ if (typeof process === "undefined" || !process.env) return null;
3241
+ const candidates = [
3242
+ "DATABASE_URL",
3243
+ "POSTGRES_URL",
3244
+ "POSTGRES_PRISMA_URL",
3245
+ "POSTGRES_URL_NON_POOLING",
3246
+ "DIRECT_URL",
3247
+ "SUPABASE_DB_URL"
3248
+ ];
3249
+ for (const name of candidates) {
3250
+ const value = process.env[name];
3251
+ if (typeof value === "string" && /^postgres(?:ql)?:\/\//i.test(value)) {
3252
+ return value;
3253
+ }
3254
+ }
3255
+ return null;
3256
+ }
3257
+ async function autoWireTriggerPathFromDatabaseUrl(options) {
3258
+ const config = configuration();
3259
+ let pg;
3260
+ try {
3261
+ const dynImport = new Function(
3262
+ "s",
3263
+ "return import(s)"
3264
+ );
3265
+ pg = await dynImport("pg");
3266
+ } catch (err) {
3267
+ return;
3268
+ }
3269
+ const pool = new pg.Pool({
3270
+ connectionString: options.databaseUrl,
3271
+ max: 4
3272
+ });
3273
+ if (config.databaseReader === null) {
3274
+ config.databaseReader = (sql, params) => pool.query(sql, params);
3275
+ }
3276
+ patchPgClient(pg);
3277
+ applyDatabaseReaderDefaults(options);
3278
+ }
3279
+ function applyDatabaseReaderDefaults(options) {
3280
+ const config = configuration();
3281
+ if (!config.databaseReader) return;
3282
+ if (options.databaseSnapshotMode === void 0) {
3283
+ config.databaseSnapshotMode = true;
3284
+ }
3285
+ runTriggerTrackedTablesDetection();
3286
+ }
3287
+ function runTriggerTrackedTablesDetection() {
3288
+ const config = configuration();
3289
+ if (!config.databaseReader) return;
3290
+ if (config.triggerTrackedTables !== null) return;
3291
+ detectTriggerTrackedTables(config.databaseReader).then((tables) => {
3292
+ if (tables === null) {
3293
+ logger.debug(
3294
+ "[ezlogs] trigger-tracked-table detection failed; falling back to suppress-all on `databaseReader` paths. Untracked tables will not appear in the dashboard until detection succeeds or the table is added with `SELECT ezlogs_track('table_name')`."
3295
+ );
3296
+ return;
3297
+ }
3298
+ config.triggerTrackedTables = tables;
3299
+ logger.debug(
3300
+ `[ezlogs] trigger-tracked tables: ${tables.size === 0 ? "(none)" : Array.from(tables).sort().join(", ")}`
3301
+ );
3302
+ }).catch(() => {
3303
+ });
3304
+ }
3305
+ function installBeforeExitHook() {
3306
+ if (beforeExitInstalled) return;
3307
+ if (typeof process === "undefined" || !process.on) return;
3308
+ process.on("beforeExit", () => {
3309
+ void flushScheduler.flushNow();
3310
+ });
3311
+ beforeExitInstalled = true;
3312
+ }
3313
+ function _internalsForTests() {
3314
+ return { buffer: buffer_exports, flushScheduler };
3315
+ }
3316
+
3317
+ export { ArgError, __ezlogs_run_inline_server_action, _detectDatabaseUrlFromEnvForTests, _internalsForTests, build as buildEvent, captureHttpEvent, capturePagesApi, captureRoute, captureServerAction, captureServerActionExport, ezlogs, withMiddlewareCapture };