ezlogs-nextjs 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +15 -2
  2. package/bin/install-triggers.cjs +33 -5
  3. package/dist/actors/index.cjs +5 -37
  4. package/dist/actors/index.js +2 -34
  5. package/dist/chunk-C5OSM557.js +39 -0
  6. package/dist/chunk-CE3R7DVB.js +1127 -0
  7. package/dist/chunk-CU45I2WR.js +498 -0
  8. package/dist/chunk-DKRNNI4I.js +180 -0
  9. package/dist/chunk-SIAA4J6H.js +17 -0
  10. package/dist/chunk-UQHEW6ER.js +119 -0
  11. package/dist/chunk-UWHYJH4M.cjs +126 -0
  12. package/dist/chunk-V5YNKKTG.cjs +42 -0
  13. package/dist/chunk-WASXTDLW.cjs +1151 -0
  14. package/dist/chunk-Y5NSHKWQ.cjs +182 -0
  15. package/dist/chunk-YX2XPLOA.cjs +508 -0
  16. package/dist/chunk-ZDSQYCYV.cjs +21 -0
  17. package/dist/db/drizzle.cjs +6 -821
  18. package/dist/db/drizzle.js +5 -820
  19. package/dist/db/prisma.cjs +28 -853
  20. package/dist/db/prisma.js +14 -839
  21. package/dist/db/supabase.cjs +21 -836
  22. package/dist/db/supabase.js +14 -829
  23. package/dist/index.cjs +132 -2362
  24. package/dist/index.js +34 -2270
  25. package/dist/jobs/bullmq.cjs +13 -1465
  26. package/dist/jobs/bullmq.js +7 -1459
  27. package/dist/jobs/inngest.cjs +14 -1422
  28. package/dist/jobs/inngest.js +8 -1416
  29. package/dist/jobs/supabase-queues.cjs +15 -1467
  30. package/dist/jobs/supabase-queues.js +10 -1462
  31. package/dist/jobs/trigger.cjs +9 -1454
  32. package/dist/jobs/trigger.js +5 -1450
  33. package/dist/jobs/upstash-workflow.cjs +30 -1456
  34. package/dist/jobs/upstash-workflow.d.cts +2 -1
  35. package/dist/jobs/upstash-workflow.d.ts +2 -1
  36. package/dist/jobs/upstash-workflow.js +27 -1453
  37. package/dist/nextjs-plugin/index.cjs +1 -1
  38. package/dist/nextjs-plugin/index.js +1 -1
  39. package/dist/nextjs-plugin/loader.cjs +21 -25
  40. package/dist/nextjs-plugin/loader.js +1 -5
  41. package/dist/triggers/index.cjs +40 -1434
  42. package/dist/triggers/index.js +6 -1421
  43. package/package.json +2 -1
@@ -1,200 +1,15 @@
1
1
  'use strict';
2
2
 
3
+ var chunkY5NSHKWQ_cjs = require('../chunk-Y5NSHKWQ.cjs');
4
+ var chunkYX2XPLOA_cjs = require('../chunk-YX2XPLOA.cjs');
5
+ var chunkWASXTDLW_cjs = require('../chunk-WASXTDLW.cjs');
6
+ var chunkV5YNKKTG_cjs = require('../chunk-V5YNKKTG.cjs');
7
+ require('../chunk-ZDSQYCYV.cjs');
3
8
  var promises = require('fs/promises');
4
9
  var path = require('path');
5
10
  var url = require('url');
6
11
 
7
12
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
8
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
- }) : x)(function(x) {
11
- if (typeof require !== "undefined") return require.apply(this, arguments);
12
- throw Error('Dynamic require of "' + x + '" is not supported');
13
- });
14
-
15
- // src/logger.ts
16
- var LEVEL_RANK = {
17
- debug: 10,
18
- info: 20,
19
- warn: 30,
20
- error: 40,
21
- silent: 100
22
- };
23
- var LEVEL_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:log-level");
24
- function readLevel() {
25
- const g = globalThis;
26
- return g[LEVEL_KEY] ?? "warn";
27
- }
28
- function shouldLog(level) {
29
- return LEVEL_RANK[level] >= LEVEL_RANK[readLevel()];
30
- }
31
- function safeWrite(level, message) {
32
- try {
33
- if (!shouldLog(level)) return;
34
- const line = `[ezlogs] ${message}`;
35
- if (level === "error" || level === "warn") {
36
- console.error(line);
37
- } else {
38
- console.log(line);
39
- }
40
- } catch {
41
- }
42
- }
43
- var logger = {
44
- debug: (message) => safeWrite("debug", message),
45
- info: (message) => safeWrite("info", message),
46
- warn: (message) => safeWrite("warn", message),
47
- error: (message) => safeWrite("error", message)
48
- };
49
-
50
- // src/configuration.ts
51
- var DEFAULT_EXCLUDED_PATHS = Object.freeze([
52
- // Next.js / Vercel infrastructure noise
53
- "/_next/*",
54
- "/_vercel/*",
55
- "/__nextjs_*",
56
- // NextAuth.js / Auth.js — skip session-refresh polls and CSRF/provider
57
- // metadata GETs (high-frequency, no business meaning), but CAPTURE
58
- // POSTs (callbacks, signin, signout, register). The POSTs are the
59
- // actual auth events users care about; the GETs are pure plumbing.
60
- Object.freeze({ path: "/api/auth/*", methods: ["GET", "HEAD"] }),
61
- // Generic infrastructure
62
- "/health*",
63
- "/api/health",
64
- "/up",
65
- "/alive",
66
- "/ready",
67
- "/metrics",
68
- "/favicon.ico",
69
- "/.well-known*",
70
- "/robots.txt",
71
- "/sitemap.xml",
72
- "/*.hot-update.*",
73
- // Auth routes (common patterns across Clerk, NextAuth, custom auth)
74
- "*/login*",
75
- "*/logout*",
76
- "*/sign-in*",
77
- "*/sign-out*",
78
- "*/signin*",
79
- "*/signout*",
80
- "/session*"
81
- ]);
82
- var DEFAULT_EXCLUDED_TABLES = Object.freeze([
83
- // Prisma migration ledger
84
- "_prisma_migrations",
85
- // Auth.js / NextAuth Prisma adapter — session/verification-token churn
86
- // is auth machinery, not business activity. Account/User stay captured.
87
- "Session",
88
- "VerificationToken",
89
- // Common cross-stack convention names for the same things
90
- "sessions",
91
- "session",
92
- "verification_tokens"
93
- ]);
94
- var DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
95
- var DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
96
- var Configuration = class {
97
- serverUrl = null;
98
- projectToken = null;
99
- captureHttp = true;
100
- captureDb = true;
101
- captureJobs = true;
102
- bufferSize = 1e4;
103
- /** Default 3000 ms — equivalent to Ruby's 3 seconds. */
104
- sendInterval = 3e3;
105
- retryAttempts = 3;
106
- logLevel = "warn";
107
- patchGlobalFetch = true;
108
- actorFromSupabase = true;
109
- allowInsecureTransport = false;
110
- excludedPaths = [];
111
- excludedTables = [];
112
- excludedJobClasses = [];
113
- excludedGraphqlOperations = [];
114
- excludedGraphqlVariableKeys = [];
115
- actorFromRequest = null;
116
- displayNameFor = {};
117
- isServerActionError = null;
118
- databaseReader = null;
119
- databaseUrl = null;
120
- /**
121
- * Tables that have the `ezlogs_audit` trigger attached. Detected once
122
- * at agent startup by reading `information_schema.triggers`. The
123
- * supabase / drizzle / prisma adapters use this to decide whether
124
- * their per-mutation emit is redundant: if the table is trigger-
125
- * tracked the audit-log reader will surface the same write with full
126
- * old/new state, so the adapter's emit is suppressed. Tables NOT in
127
- * this set fall through to the adapter so they're still captured.
128
- *
129
- * `null` means "detection hasn't run yet or failed" — in that state
130
- * `databaseReader`-wired apps suppress every adapter emit (the
131
- * original Phase 5 behavior). After detection completes the agent
132
- * gives the more accurate per-table answer.
133
- */
134
- triggerTrackedTables = null;
135
- apply(options) {
136
- this.serverUrl = options.serverUrl;
137
- this.projectToken = options.projectToken;
138
- if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
139
- if (options.captureDb !== void 0) this.captureDb = options.captureDb;
140
- if (options.captureJobs !== void 0) this.captureJobs = options.captureJobs;
141
- if (options.bufferSize !== void 0) this.bufferSize = options.bufferSize;
142
- if (options.sendInterval !== void 0) this.sendInterval = options.sendInterval;
143
- if (options.retryAttempts !== void 0) this.retryAttempts = options.retryAttempts;
144
- if (options.excludedPaths) this.excludedPaths = [...options.excludedPaths];
145
- if (options.excludedTables) this.excludedTables = [...options.excludedTables];
146
- if (options.excludedJobClasses) {
147
- this.excludedJobClasses = [...options.excludedJobClasses];
148
- }
149
- if (options.excludedGraphqlOperations) {
150
- this.excludedGraphqlOperations = [...options.excludedGraphqlOperations];
151
- }
152
- if (options.excludedGraphqlVariableKeys) {
153
- this.excludedGraphqlVariableKeys = [...options.excludedGraphqlVariableKeys];
154
- }
155
- if (options.actorFromRequest) this.actorFromRequest = options.actorFromRequest;
156
- if (options.displayNameFor) this.displayNameFor = { ...options.displayNameFor };
157
- if (options.isServerActionError) this.isServerActionError = options.isServerActionError;
158
- if (options.patchGlobalFetch !== void 0) {
159
- this.patchGlobalFetch = options.patchGlobalFetch;
160
- }
161
- if (options.allowInsecureTransport !== void 0) {
162
- this.allowInsecureTransport = options.allowInsecureTransport;
163
- }
164
- if (options.actorFromSupabase !== void 0) {
165
- this.actorFromSupabase = options.actorFromSupabase;
166
- }
167
- if (options.databaseReader !== void 0) {
168
- this.databaseReader = options.databaseReader;
169
- }
170
- if (options.databaseUrl !== void 0) {
171
- this.databaseUrl = options.databaseUrl;
172
- }
173
- if (options.logLevel) this.logLevel = options.logLevel;
174
- }
175
- allExcludedPaths() {
176
- return [...DEFAULT_EXCLUDED_PATHS, ...this.excludedPaths];
177
- }
178
- allExcludedTables() {
179
- return [...DEFAULT_EXCLUDED_TABLES, ...this.excludedTables];
180
- }
181
- allExcludedJobClasses() {
182
- return [...DEFAULT_EXCLUDED_JOB_CLASSES, ...this.excludedJobClasses];
183
- }
184
- allExcludedGraphqlOperations() {
185
- return [...DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, ...this.excludedGraphqlOperations];
186
- }
187
- };
188
- var GLOBAL_CONFIG_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:configuration");
189
- function configuration() {
190
- const g = globalThis;
191
- if (!g[GLOBAL_CONFIG_KEY]) {
192
- g[GLOBAL_CONFIG_KEY] = new Configuration();
193
- }
194
- return g[GLOBAL_CONFIG_KEY];
195
- }
196
-
197
- // src/triggers/install.ts
198
13
  var HERE = path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
199
14
  function parseArgs(argv) {
200
15
  const out = {
@@ -288,7 +103,7 @@ function escapeSqlIdentifier(name) {
288
103
  return name;
289
104
  }
290
105
  var TRIGGER_INSTALL_SKIP_PATTERNS = [
291
- ...DEFAULT_EXCLUDED_TABLES,
106
+ ...chunkWASXTDLW_cjs.DEFAULT_EXCLUDED_TABLES,
292
107
  // Our own audit table — trigger on the audit table would be a loop.
293
108
  "ezlogs_audit_log",
294
109
  // Postgres internals (won't be in public schema, but defensive).
@@ -421,130 +236,24 @@ ${trackingSql}
421
236
  }
422
237
  return 0;
423
238
  } catch (error) {
424
- logger.error(
239
+ chunkV5YNKKTG_cjs.logger.error(
425
240
  `install-triggers failed: ${error instanceof Error ? error.message : String(error)}`
426
241
  );
427
242
  return 1;
428
243
  }
429
244
  }
430
245
 
431
- // src/edge-fallback.ts
432
- var ALS_CTOR = loadAsyncLocalStorage();
433
- function loadAsyncLocalStorage() {
434
- const fromGlobal = globalThis.AsyncLocalStorage;
435
- if (typeof fromGlobal === "function") return fromGlobal;
436
- try {
437
- const req = typeof __require !== "undefined" ? __require : (
438
- // In ESM, `createRequire` is the official escape hatch.
439
- // We pull it via globalThis to avoid a static `import`
440
- // that would itself be browser-bundled.
441
- void 0
442
- );
443
- if (typeof req === "function") {
444
- const moduleName = ["async", "hooks"].join("_");
445
- const mod = req("node:" + moduleName);
446
- if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
447
- }
448
- } catch {
449
- }
450
- return null;
451
- }
452
- function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
453
- const globalStore = globalThis;
454
- let entry = globalStore[key];
455
- if (!entry) {
456
- const als2 = (() => {
457
- if (!ALS_CTOR) return null;
458
- try {
459
- return new ALS_CTOR();
460
- } catch {
461
- return null;
462
- }
463
- })();
464
- entry = { als: als2, edgeFallback: null };
465
- globalStore[key] = entry;
466
- }
467
- const als = entry.als;
468
- const stateRef = entry;
469
- return {
470
- read() {
471
- if (als) return als.getStore()?.value ?? null;
472
- return stateRef.edgeFallback?.value ?? null;
473
- },
474
- run(value, callback) {
475
- if (als) return als.run({ value }, callback);
476
- const previous = stateRef.edgeFallback;
477
- stateRef.edgeFallback = { value };
478
- try {
479
- return callback();
480
- } finally {
481
- stateRef.edgeFallback = previous;
482
- }
483
- },
484
- update(value) {
485
- if (als) {
486
- const store = als.getStore();
487
- if (store) store.value = value;
488
- return;
489
- }
490
- stateRef.edgeFallback = { value };
491
- },
492
- _resetForTests() {
493
- stateRef.edgeFallback = null;
494
- },
495
- _isAsyncLocalStorage() {
496
- return als !== null;
497
- }
498
- };
499
- }
500
-
501
- // src/actor.ts
502
- var storage = createScopedStorage(
503
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-storage")
504
- );
505
- function getCurrentActor() {
506
- return storage.read();
507
- }
508
- function runWithActorScope(callback) {
509
- return storage.run(null, callback);
510
- }
511
-
512
- // src/correlation.ts
513
- var storage2 = createScopedStorage(
514
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
515
- );
516
- function generate() {
517
- const ts = Date.now();
518
- const hex = randomHexBytes(4);
519
- return `ezl_${ts}_${hex}`;
520
- }
521
- function randomHexBytes(byteCount) {
522
- const buf = new Uint8Array(byteCount);
523
- globalThis.crypto.getRandomValues(buf);
524
- let out = "";
525
- for (let i = 0; i < buf.length; i++) {
526
- out += buf[i].toString(16).padStart(2, "0");
527
- }
528
- return out;
529
- }
530
- function current() {
531
- return storage2.read();
532
- }
533
- function runWithCorrelation(correlationId, callback) {
534
- return storage2.run(correlationId, callback);
535
- }
536
-
537
246
  // src/triggers/context.ts
538
247
  function getDatabaseContext() {
539
- const actor = getCurrentActor();
248
+ const actor = chunkWASXTDLW_cjs.getCurrentActor();
540
249
  return {
541
250
  actorId: actor && actor.id ? actor.id : null,
542
- correlationId: current()
251
+ correlationId: chunkWASXTDLW_cjs.current()
543
252
  };
544
253
  }
545
254
  async function applyDatabaseContext(exec) {
546
- const actor = getCurrentActor();
547
- const correlationId = current();
255
+ const actor = chunkWASXTDLW_cjs.getCurrentActor();
256
+ const correlationId = chunkWASXTDLW_cjs.current();
548
257
  if (!actor && !correlationId) return;
549
258
  try {
550
259
  if (actor && actor.id) {
@@ -557,7 +266,7 @@ async function applyDatabaseContext(exec) {
557
266
  );
558
267
  }
559
268
  } catch (err) {
560
- logger.debug(
269
+ chunkV5YNKKTG_cjs.logger.debug(
561
270
  `applyDatabaseContext: set_config failed, continuing without context: ${err instanceof Error ? err.message : String(err)}`
562
271
  );
563
272
  }
@@ -578,1141 +287,38 @@ async function withDatabaseContext(client, callback) {
578
287
  }
579
288
  }
580
289
 
581
- // src/event-builder.ts
582
- var SENSITIVE_KEYS = Object.freeze([
583
- "password",
584
- "token",
585
- "secret",
586
- "api_key",
587
- "credit_card"
588
- ]);
589
- var VALID_SOURCE_TYPES = [
590
- "http_request",
591
- "background_job",
592
- "database_callback"
593
- ];
594
- var VALID_OUTCOMES = ["success", "failure"];
595
- function build(input) {
596
- const source_type = validateSourceType(input.source_type);
597
- const source_data_raw = validateSourceData(input.source_data);
598
- const outcome = validateOutcome(input.outcome);
599
- const timestamp = validateTimestamp(input.timestamp ?? null);
600
- const resource_ids = validateResourceIds(input.resource_ids ?? []);
601
- const context_raw = validateContext(input.context ?? null);
602
- const duration_ms = validateDurationMs();
603
- const error_message = input.error_message ?? null;
604
- validateOutcomeErrorConsistency(outcome, error_message);
605
- const source_data = sanitizeRecord(source_data_raw);
606
- const context = context_raw === null ? null : sanitizeRecord(context_raw);
607
- const correlation_id = input.correlation_id ?? null;
608
- const event = {
609
- timestamp,
610
- source_type,
611
- source_data,
612
- outcome,
613
- correlation_id,
614
- resource_ids,
615
- context,
616
- duration_ms,
617
- error_message
618
- };
619
- return event;
620
- }
621
- function validateSourceType(value) {
622
- const normalized = String(value);
623
- if (!VALID_SOURCE_TYPES.includes(normalized)) {
624
- throw new ArgError(
625
- `source_type must be one of ${VALID_SOURCE_TYPES.join(", ")}, got: ${normalized}`
626
- );
627
- }
628
- return normalized;
629
- }
630
- function validateSourceData(value) {
631
- if (value === null || value === void 0) {
632
- throw new ArgError("source_data is required");
633
- }
634
- if (!isPlainObject(value)) {
635
- throw new ArgError(
636
- `source_data must be an object, got: ${describe(value)}`
637
- );
638
- }
639
- return value;
640
- }
641
- function validateOutcome(value) {
642
- const normalized = String(value);
643
- if (!VALID_OUTCOMES.includes(normalized)) {
644
- throw new ArgError(
645
- `outcome must be one of ${VALID_OUTCOMES.join(", ")}, got: ${normalized}`
646
- );
647
- }
648
- return normalized;
649
- }
650
- function validateTimestamp(value) {
651
- if (value === null) {
652
- return (/* @__PURE__ */ new Date()).toISOString();
653
- }
654
- if (typeof value === "string") {
655
- const parsed = new Date(value);
656
- if (Number.isNaN(parsed.getTime())) {
657
- throw new ArgError(
658
- `timestamp must be valid ISO 8601 format, got: ${value}`
659
- );
660
- }
661
- return value;
662
- }
663
- if (value instanceof Date) {
664
- if (Number.isNaN(value.getTime())) {
665
- throw new ArgError("timestamp must be a valid Date");
666
- }
667
- return value.toISOString();
668
- }
669
- throw new ArgError(
670
- `timestamp must be a string or Date, got: ${describe(value)}`
671
- );
672
- }
673
- function validateResourceIds(value) {
674
- if (!Array.isArray(value)) {
675
- throw new ArgError(`resource_ids must be an array, got: ${describe(value)}`);
676
- }
677
- value.forEach((entry, index) => {
678
- if (!isPlainObject(entry)) {
679
- throw new ArgError(
680
- `resource_ids[${index}] must be an object, got: ${describe(entry)}`
681
- );
682
- }
683
- const e = entry;
684
- if (!("resource_type" in e) || !("resource_id" in e)) {
685
- throw new ArgError(
686
- `resource_ids[${index}] must have resource_type and resource_id keys, got: ${Object.keys(e).join(", ")}`
687
- );
688
- }
689
- if (typeof e.resource_type !== "string") {
690
- throw new ArgError(
691
- `resource_ids[${index}].resource_type must be a string, got: ${describe(e.resource_type)}`
692
- );
693
- }
694
- if (typeof e.resource_id !== "string") {
695
- throw new ArgError(
696
- `resource_ids[${index}].resource_id must be a string, got: ${describe(e.resource_id)}`
697
- );
698
- }
699
- });
700
- return value;
701
- }
702
- function validateContext(value) {
703
- if (value === null) return null;
704
- if (!isPlainObject(value)) {
705
- throw new ArgError(
706
- `context must be an object or null, got: ${describe(value)}`
707
- );
708
- }
709
- return value;
710
- }
711
- function validateDurationMs(value) {
712
- return null;
713
- }
714
- function validateOutcomeErrorConsistency(outcome, error_message) {
715
- if (outcome === "failure") {
716
- if (error_message === null || error_message === "") {
717
- throw new ArgError("error_message is required when outcome is 'failure'");
718
- }
719
- } else if (outcome === "success") {
720
- if (error_message !== null) {
721
- throw new ArgError("error_message must be null when outcome is 'success'");
722
- }
723
- }
724
- }
725
- function sanitizeRecord(input) {
726
- const result = {};
727
- for (const key of Object.keys(input)) {
728
- const value = input[key];
729
- if (isSensitiveKey(key)) {
730
- result[key] = "[FILTERED]";
731
- } else if (isPlainObject(value)) {
732
- result[key] = sanitizeRecord(value);
733
- } else if (Array.isArray(value)) {
734
- result[key] = value.map(
735
- (item) => isPlainObject(item) ? sanitizeRecord(item) : item
736
- );
737
- } else {
738
- result[key] = value;
739
- }
740
- }
741
- return result;
742
- }
743
- function isSensitiveKey(key) {
744
- const lower = key.toLowerCase();
745
- return SENSITIVE_KEYS.some((p) => lower.includes(p));
746
- }
747
- function isPlainObject(value) {
748
- if (value === null || typeof value !== "object") return false;
749
- const proto = Object.getPrototypeOf(value);
750
- return proto === Object.prototype || proto === null;
751
- }
752
- function describe(value) {
753
- if (value === null) return "null";
754
- if (Array.isArray(value)) return "Array";
755
- return typeof value;
756
- }
757
- var ArgError = class extends Error {
758
- constructor(message) {
759
- super(message);
760
- this.name = "ArgError";
761
- }
762
- };
763
-
764
- // src/pipeline/buffer.ts
765
- var GLOBAL_QUEUE_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:buffer-queue");
766
- function getQueue() {
767
- const g = globalThis;
768
- if (!g[GLOBAL_QUEUE_KEY]) g[GLOBAL_QUEUE_KEY] = [];
769
- return g[GLOBAL_QUEUE_KEY];
770
- }
771
- function pushEvent(event) {
772
- try {
773
- const queue = getQueue();
774
- const max = maxSize();
775
- if (queue.length >= max) {
776
- queue.shift();
777
- logger.warn(`Buffer full (${max}), dropped oldest event`);
778
- }
779
- queue.push(event);
780
- } catch (error) {
781
- logger.error(`pushEvent failed: ${describe2(error)}`);
782
- }
783
- }
784
- function maxSize() {
785
- try {
786
- return configuration().bufferSize;
787
- } catch {
788
- return 1e4;
789
- }
790
- }
791
- function describe2(error) {
792
- if (error instanceof Error) return `${error.name}: ${error.message}`;
793
- return String(error);
794
- }
795
- var SENSITIVE_WORD_PATTERNS = Object.freeze([
796
- "pin",
797
- "otp",
798
- "totp",
799
- "iban",
800
- "mfa",
801
- "passphrase"
802
- ]);
803
- function snakeLower(key) {
804
- return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
805
- }
806
- function matchesSensitiveKey(key, substringPatterns) {
807
- const lower = key.toLowerCase();
808
- const snake = snakeLower(key);
809
- if (substringPatterns.some((p) => lower.includes(p) || snake.includes(p))) {
810
- return true;
811
- }
812
- const words = snake.split(/[^a-z0-9]+/);
813
- return SENSITIVE_WORD_PATTERNS.some((w) => words.includes(w));
814
- }
815
- function passesLuhn(digits) {
816
- let sum = 0;
817
- for (let i = 0; i < digits.length; i += 1) {
818
- let d = Number(digits[digits.length - 1 - i]);
819
- if (i % 2 === 1) {
820
- d *= 2;
821
- if (d > 9) d -= 9;
822
- }
823
- sum += d;
824
- }
825
- return sum % 10 === 0;
826
- }
827
- var SECRET_TEXT_PATTERNS = [
828
- /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
829
- /\beyJ[\w-]+\.[\w-]+\.[\w-]+/g,
830
- /\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]+/g,
831
- /\bsk-[A-Za-z0-9_-]{16,}/g,
832
- /\bgh[pousr]_[A-Za-z0-9]{20,}/g,
833
- /\bxox[abposr]-[A-Za-z0-9-]+/g,
834
- /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g
835
- ];
836
- var EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
837
- function scrubSecretsInText(text, options = {}) {
838
- let out = text;
839
- for (const pattern of SECRET_TEXT_PATTERNS) out = out.replace(pattern, "[FILTERED]");
840
- out = out.replace(/\b(Bearer|Basic)\s+[\w.~+/=-]+/gi, "$1 [FILTERED]").replace(/\b\d(?:[ -]?\d){12,18}\b/g, (match) => {
841
- const digits = match.replace(/[ -]/g, "");
842
- return (digits.length === 15 || digits.length === 16) && passesLuhn(digits) ? "[FILTERED]" : match;
843
- });
844
- return options.emails ? out.replace(EMAIL, "[FILTERED]") : out;
845
- }
846
-
847
- // src/db/shared.ts
848
- var IGNORED_ATTRIBUTES = Object.freeze([
849
- "id",
850
- "createdAt",
851
- "created_at",
852
- "updatedAt",
853
- "updated_at",
854
- // Auth.js / NextAuth standard columns
855
- "emailVerified",
856
- "expires"
857
- ]);
858
- var DB_SENSITIVE_PATTERNS = Object.freeze([
859
- "password",
860
- "token",
861
- "secret",
862
- "api_key",
863
- "credit_card",
864
- "ssn",
865
- "social_security",
866
- "encrypted",
867
- "private_key",
868
- "public_key",
869
- "signing_key",
870
- "pem",
871
- "cipher",
872
- "nonce",
873
- "salt",
874
- "digest",
875
- "signature",
876
- "hmac",
877
- // 0.2.0 additions. `credential` / `passwd` / `apikey` were already in
878
- // the HTTP list; `passcode` / `card_number` / `cardnumber` / `cvv` /
879
- // `cvc` are new. Whole-word `pin` / `otp` / `totp` / `iban` come from
880
- // SENSITIVE_WORD_PATTERNS. The SQL trigger mirrors this list.
881
- "credential",
882
- "passwd",
883
- "passcode",
884
- "apikey",
885
- "card_number",
886
- "cardnumber",
887
- "cvv",
888
- "cvc"
889
- ]);
890
- function emitDbEvent(input) {
891
- try {
892
- const config = configuration();
893
- if (!config.captureDb) return;
894
- if (config.allExcludedTables().includes(input.modelClass)) return;
895
- if (config.databaseReader && !input._fromTrigger) {
896
- const tracked = config.triggerTrackedTables;
897
- if (tracked === null || tracked.has(input.table ?? input.modelClass)) return;
898
- }
899
- if (input.operation === "update") {
900
- const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
901
- if (meaningful.length === 0) return;
902
- }
903
- const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
904
- const related = resourceIdStr === null ? input.relatedResourceIds ?? [] : [];
905
- const context = buildContext(
906
- related.length > 0 ? { ...input, displayName: null, modelInstance: null } : input
907
- );
908
- const event = build({
909
- source_type: "database_callback",
910
- source_data: {
911
- model_class: input.modelClass,
912
- operation: input.operation
913
- },
914
- outcome: "success",
915
- correlation_id: current(),
916
- resource_ids: resourceIdStr === null ? [...related] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
917
- context,
918
- duration_ms: null,
919
- timestamp: input.timestamp ?? null
920
- });
921
- pushEvent(event);
922
- } catch (error) {
923
- logger.debug(`db emit failed: ${describeError(error)}`);
924
- }
925
- }
926
- function buildContext(input) {
927
- const context = {};
928
- const actor = getCurrentActor();
929
- if (actor) context.actor = actor;
930
- if ((input.operation === "create" || input.operation === "destroy") && input.initialAttributes) {
931
- const filtered = filterMeaningfulAttributes(input.initialAttributes);
932
- if (filtered !== null) context.initial_attributes = filtered;
933
- }
934
- if (input.operation === "update" && input.changes) {
935
- const filtered = filterMeaningfulChanges(input.changes);
936
- if (filtered.length > 0) {
937
- context.changes = filtered.map((c) => {
938
- const out = {
939
- attribute: c.attribute,
940
- to: formatForJson(c.to)
941
- };
942
- if (c.from !== void 0) out.from = formatForJson(c.from);
943
- return out;
944
- });
945
- }
946
- }
947
- const displayName = input.displayName ?? (input.modelInstance ? resolveDisplayName(input.modelClass, input.modelInstance) : null);
948
- if (displayName !== null) context.display_name = displayName;
949
- return Object.keys(context).length === 0 ? null : context;
950
- }
951
- function filterMeaningfulAttributes(attrs) {
952
- const out = {};
953
- for (const key of Object.keys(attrs)) {
954
- if (!isMeaningfulAttribute(key)) continue;
955
- const value = attrs[key];
956
- if (value === null || value === void 0) continue;
957
- if (!isScalar(value)) continue;
958
- out[key] = formatForJson(value);
959
- }
960
- return Object.keys(out).length === 0 ? null : out;
961
- }
962
- function filterMeaningfulChanges(changes) {
963
- return flattenNestedChanges(changes).filter((c) => {
964
- if (!isMeaningfulAttribute(c.attribute)) return false;
965
- if (!isScalar(c.to)) return false;
966
- if (c.from === void 0) return true;
967
- if (!isScalar(c.from)) return false;
968
- return valuesActuallyChanged(c.from, c.to);
969
- });
970
- }
971
- var MAX_NESTED_DEPTH = 3;
972
- var MAX_NESTED_LEAVES = 20;
973
- var MAX_UNKNOWN_FROM_LEAVES = 5;
974
- function flattenNestedChanges(changes) {
975
- if (!changes.some((c) => isPlainRecord(c.to) || isPlainRecord(c.from))) return changes;
976
- const out = [];
977
- for (const c of changes) {
978
- if (!isPlainRecord(c.to) && !isPlainRecord(c.from)) {
979
- out.push(c);
980
- continue;
981
- }
982
- if (!isMeaningfulAttribute(c.attribute)) continue;
983
- const leaves = [];
984
- collectLeafChanges(c.attribute, c.from, c.to, 1, leaves);
985
- const cap = c.from === void 0 ? MAX_UNKNOWN_FROM_LEAVES : MAX_NESTED_LEAVES;
986
- out.push(...leaves.slice(0, cap).map(scrubLeaf));
987
- }
988
- return out;
989
- }
990
- function collectLeafChanges(path, from, to, depth, out) {
991
- if (out.length > MAX_NESTED_LEAVES) return;
992
- const fromObj = isPlainRecord(from);
993
- const toObj = isPlainRecord(to);
994
- if ((fromObj || toObj) && depth <= MAX_NESTED_DEPTH && (fromObj || from == null) && (toObj || to == null)) {
995
- const f = fromObj ? from : {};
996
- const t = toObj ? to : {};
997
- for (const key of /* @__PURE__ */ new Set([...Object.keys(f), ...Object.keys(t)])) {
998
- const before = from === void 0 ? void 0 : f[key] ?? null;
999
- collectLeafChanges(`${path}.${key}`, before, t[key] ?? null, depth + 1, out);
1000
- }
1001
- return;
1002
- }
1003
- if (from !== void 0 && sameJson(from, to)) return;
1004
- out.push(from === void 0 ? { attribute: path, to } : { attribute: path, from, to });
1005
- }
1006
- function scrubLeaf(change) {
1007
- const scrub = (v) => typeof v === "string" ? scrubSecretsInText(v) : v;
1008
- const out = { attribute: change.attribute, to: scrub(change.to) };
1009
- if (change.from !== void 0) out.from = scrub(change.from);
1010
- return out;
1011
- }
1012
- function isPlainRecord(value) {
1013
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1014
- const proto = Object.getPrototypeOf(value);
1015
- return proto === Object.prototype || proto === null;
1016
- }
1017
- function sameJson(a, b) {
1018
- if (a === b) return true;
1019
- try {
1020
- return JSON.stringify(a) === JSON.stringify(b);
1021
- } catch {
1022
- return false;
1023
- }
1024
- }
1025
- function isMeaningfulAttribute(name) {
1026
- if (IGNORED_ATTRIBUTES.includes(name)) return false;
1027
- if (isDbSensitive(name)) return false;
1028
- return true;
1029
- }
1030
- function isDbSensitive(name) {
1031
- return matchesSensitiveKey(name, DB_SENSITIVE_PATTERNS);
1032
- }
1033
- function isScalar(value) {
1034
- if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
1035
- return true;
1036
- }
1037
- if (isPrismaDecimal(value)) return true;
1038
- if (Buffer.isBuffer?.(value)) return false;
1039
- if (Array.isArray(value)) return value.every((v) => isScalar(v));
1040
- return false;
1041
- }
1042
- function valuesActuallyChanged(from, to) {
1043
- if (from === null && to === null) return false;
1044
- if (from instanceof Date && to instanceof Date) {
1045
- return from.getTime() !== to.getTime();
1046
- }
1047
- return from !== to;
1048
- }
1049
- function formatForJson(value) {
1050
- if (value === null || value === void 0) return value;
1051
- if (value instanceof Date) return value.toISOString();
1052
- if (typeof value === "bigint") return value.toString();
1053
- if (isPrismaDecimal(value)) return Number(value.toString());
1054
- if (Array.isArray(value)) return value.map(formatForJson);
1055
- return value;
1056
- }
1057
- function isPrismaDecimal(value) {
1058
- if (value === null || typeof value !== "object") return false;
1059
- const obj = value;
1060
- return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
1061
- }
1062
- var DISPLAY_NAME_COLUMNS = ["name", "title", "number", "label"];
1063
- var MAX_DISPLAY_NAME_LENGTH = 120;
1064
- function resolveDisplayName(modelClass, instance) {
1065
- try {
1066
- const config = configuration();
1067
- const resolver = config.displayNameFor[modelClass];
1068
- const resolved = applyResolver(resolver, instance);
1069
- if (resolved !== null) return resolved;
1070
- const columns = /* @__PURE__ */ new Map();
1071
- for (const key of Object.keys(instance)) {
1072
- if (isDbSensitive(key)) continue;
1073
- const norm = key.toLowerCase().replace(/_/g, "");
1074
- if (!columns.has(norm)) columns.set(norm, instance[key]);
1075
- }
1076
- const text = (norm) => {
1077
- const value = columns.get(norm);
1078
- if (typeof value !== "string" && typeof value !== "number" && typeof value !== "bigint") {
1079
- return null;
1080
- }
1081
- const str = String(value).trim();
1082
- return str.length > 0 ? str.slice(0, MAX_DISPLAY_NAME_LENGTH) : null;
1083
- };
1084
- for (const column of DISPLAY_NAME_COLUMNS) {
1085
- const value = text(column);
1086
- if (value !== null) return value;
1087
- }
1088
- return text(`${singularNorm(modelClass)}number`);
1089
- } catch {
1090
- }
1091
- return null;
1092
- }
1093
- function singularNorm(modelClass) {
1094
- const norm = modelClass.toLowerCase().replace(/_/g, "");
1095
- if (norm.endsWith("ies")) return norm.slice(0, -3) + "y";
1096
- if (/(ss|us|is)$/.test(norm)) return norm;
1097
- if (/(xes|ches|shes|sses)$/.test(norm)) return norm.slice(0, -2);
1098
- return norm.endsWith("s") ? norm.slice(0, -1) : norm;
1099
- }
1100
- function applyResolver(resolver, instance) {
1101
- if (typeof resolver === "string") {
1102
- const value = instance[resolver];
1103
- if (value !== null && value !== void 0 && String(value).length > 0) {
1104
- return String(value);
1105
- }
1106
- return null;
1107
- }
1108
- if (typeof resolver === "function") {
1109
- try {
1110
- const value = resolver(instance);
1111
- if (typeof value === "string" && value.length > 0) return value;
1112
- if (value !== null && value !== void 0 && String(value).length > 0) {
1113
- return String(value);
1114
- }
1115
- } catch {
1116
- }
1117
- }
1118
- return null;
1119
- }
1120
- function describeError(error) {
1121
- if (error instanceof Error) return `${error.name}: ${error.message}`;
1122
- return String(error);
1123
- }
1124
-
1125
- // src/triggers/emit-dedup.ts
1126
- var storage3 = createScopedStorage(
1127
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-emitted-ids-storage")
1128
- );
1129
- function currentEmittedAuditIds() {
1130
- return storage3.read();
1131
- }
1132
-
1133
- // src/triggers/reader.ts
1134
- var COLUMNS = "id, table_name, op, old_row, new_row, resource_id, correlation_id, txid, captured_at";
1135
- var ORPHAN_AGE = "5 minutes";
1136
- var PRUNE_AGE = "24 hours";
1137
- var SWEEP_BATCH = 100;
1138
- var PRUNE_BATCH = 2e3;
1139
- var SWEEP_INTERVAL_MS = 1e4;
1140
- var PRUNE_INTERVAL_MS = 10 * 6e4;
1141
- var lastSweepAt = 0;
1142
- var lastPruneAt = 0;
1143
- var deleteDenied = false;
1144
- var txCorrelation = /* @__PURE__ */ new Map();
1145
- async function readAuditRows(exec, correlationId, since = null) {
1146
- const where = since ? "correlation_id = $1 AND captured_at >= $2" : "correlation_id = $1";
1147
- const params = since ? [correlationId, since.toISOString()] : [correlationId];
1148
- try {
1149
- if (!deleteDenied) {
1150
- try {
1151
- return sortById(
1152
- extractRows(
1153
- await exec(
1154
- `DELETE FROM ezlogs_audit_log WHERE ${where} RETURNING ${COLUMNS}`,
1155
- params
1156
- )
1157
- ).map(normalizeAuditRow)
1158
- );
1159
- } catch (err) {
1160
- if (!isPermissionDenied(err)) throw err;
1161
- deleteDenied = true;
1162
- logger.warn(
1163
- "the database role used by the agent cannot DELETE from ezlogs_audit_log. Rows will not be cleaned up after they are sent; grant DELETE or schedule `DELETE FROM ezlogs_audit_log WHERE captured_at < now() - interval '24 hours'`."
1164
- );
1165
- }
1166
- }
1167
- const result = await exec(
1168
- `SELECT ${COLUMNS} FROM ezlogs_audit_log WHERE ${where} ORDER BY id ASC`,
1169
- params
1170
- );
1171
- return extractRows(result).map(normalizeAuditRow);
1172
- } catch (err) {
1173
- logger.debug(
1174
- `readAuditRows failed: ${err instanceof Error ? err.message : String(err)}`
1175
- );
1176
- return [];
1177
- }
1178
- }
1179
- async function sweepAuditLog(exec) {
1180
- if (deleteDenied) return 0;
1181
- try {
1182
- const rows = sortById(
1183
- extractRows(
1184
- await exec(
1185
- `DELETE FROM ezlogs_audit_log
1186
- WHERE id IN (
1187
- SELECT id FROM ezlogs_audit_log
1188
- WHERE (correlation_id IS NULL
1189
- OR captured_at < now() - interval '${ORPHAN_AGE}')
1190
- -- Never resurface history: past the retention cap a
1191
- -- row is pruned, not sent as new activity.
1192
- AND captured_at > now() - interval '${PRUNE_AGE}'
1193
- ORDER BY id
1194
- LIMIT ${SWEEP_BATCH}
1195
- FOR UPDATE SKIP LOCKED)
1196
- RETURNING ${COLUMNS}`,
1197
- []
1198
- )
1199
- ).map(normalizeAuditRow)
1200
- );
1201
- await loadTableMeta(exec, rows);
1202
- for (const row of rows) {
1203
- const correlationId = row.correlation_id ?? correlationForTx(row.txid);
1204
- runWithCorrelation(
1205
- correlationId,
1206
- () => runWithActorScope(() => emitOne(row))
1207
- );
1208
- }
1209
- return rows.length;
1210
- } catch (err) {
1211
- logger.debug(
1212
- `sweepAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
1213
- );
1214
- return 0;
1215
- }
1216
- }
1217
- async function pruneAuditLog(exec) {
1218
- if (deleteDenied) return;
1219
- try {
1220
- await exec(
1221
- `DELETE FROM ezlogs_audit_log
1222
- WHERE id IN (
1223
- SELECT id FROM ezlogs_audit_log
1224
- WHERE captured_at < now() - interval '${PRUNE_AGE}'
1225
- LIMIT ${PRUNE_BATCH})`,
1226
- []
1227
- );
1228
- } catch (err) {
1229
- logger.debug(
1230
- `pruneAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
1231
- );
1232
- }
1233
- }
1234
- async function detectTriggerTrackedTables(exec) {
1235
- try {
1236
- const result = await exec(
1237
- `SELECT event_object_table AS table_name
1238
- FROM information_schema.triggers
1239
- WHERE trigger_name = 'ezlogs_audit'
1240
- AND trigger_schema = 'public'`,
1241
- []
1242
- );
1243
- const rows = extractRows(result);
1244
- const tables = /* @__PURE__ */ new Set();
1245
- for (const row of rows) {
1246
- const r = row ?? {};
1247
- if (typeof r.table_name === "string" && r.table_name.length > 0) {
1248
- tables.add(r.table_name);
1249
- }
1250
- }
1251
- return tables;
1252
- } catch (err) {
1253
- logger.debug(
1254
- `detectTriggerTrackedTables failed: ${err instanceof Error ? err.message : String(err)}`
1255
- );
1256
- return null;
1257
- }
1258
- }
1259
- function emitAuditRows(rows) {
1260
- for (const row of rows) {
1261
- emitOne(row);
1262
- }
1263
- }
1264
- async function flushAuditLog(exec, options = {}) {
1265
- if (!exec) return;
1266
- const correlationId = current();
1267
- if (!correlationId) return;
1268
- const rows = await readAuditRows(exec, correlationId, options.since ?? null);
1269
- await loadTableMeta(exec, rows);
1270
- emitFresh(rows);
1271
- const now = Date.now();
1272
- if (now - lastPruneAt >= PRUNE_INTERVAL_MS) {
1273
- lastPruneAt = now;
1274
- await pruneAuditLog(exec);
1275
- }
1276
- if (now - lastSweepAt >= SWEEP_INTERVAL_MS) {
1277
- lastSweepAt = now;
1278
- await sweepAuditLog(exec);
1279
- }
1280
- }
1281
- var tableMeta = /* @__PURE__ */ new Map();
1282
- var META_RETRY_MS = 6e4;
1283
- var metaRetryAt = 0;
1284
- async function loadTableMeta(exec, rows) {
1285
- if (Date.now() < metaRetryAt) return;
1286
- const tables = [
1287
- ...new Set(rows.map((r) => r.table_name).filter((t) => t !== "" && !t.includes(",") && !tableMeta.has(t)))
1288
- ];
1289
- if (tables.length === 0) return;
1290
- const list = tables.join(",");
1291
- try {
1292
- const fkRows = extractRows(
1293
- await exec(
1294
- `SELECT cl.relname AS table_name, a.attname AS column_name, rf.relname AS ref_table
1295
- FROM pg_constraint c
1296
- JOIN pg_class cl ON cl.oid = c.conrelid
1297
- JOIN pg_namespace n ON n.oid = cl.relnamespace
1298
- JOIN pg_class rf ON rf.oid = c.confrelid
1299
- JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
1300
- WHERE c.contype = 'f'
1301
- AND n.nspname = 'public'
1302
- AND array_length(c.conkey, 1) = 1
1303
- AND cl.relname = ANY(string_to_array($1, ','))
1304
- ORDER BY cl.relname, a.attnum`,
1305
- [list]
1306
- )
1307
- );
1308
- const tsRows = extractRows(
1309
- await exec(
1310
- `SELECT cl.relname AS table_name, a.attname AS column_name
1311
- FROM pg_attribute a
1312
- JOIN pg_class cl ON cl.oid = a.attrelid
1313
- JOIN pg_namespace n ON n.oid = cl.relnamespace
1314
- WHERE n.nspname = 'public'
1315
- AND cl.relname = ANY(string_to_array($1, ','))
1316
- AND a.attnum > 0
1317
- AND NOT a.attisdropped
1318
- AND a.atttypid = 'timestamp'::regtype`,
1319
- [list]
1320
- )
1321
- );
1322
- const fks = /* @__PURE__ */ new Map();
1323
- for (const raw of fkRows) {
1324
- const r = raw ?? {};
1325
- if (typeof r.table_name !== "string" || typeof r.column_name !== "string" || typeof r.ref_table !== "string") {
1326
- continue;
1327
- }
1328
- fks.set(r.table_name, [...fks.get(r.table_name) ?? [], { column: r.column_name, refTable: r.ref_table }]);
1329
- }
1330
- const timestamps = /* @__PURE__ */ new Map();
1331
- for (const raw of tsRows) {
1332
- const r = raw ?? {};
1333
- if (typeof r.table_name !== "string" || typeof r.column_name !== "string") continue;
1334
- timestamps.set(r.table_name, (timestamps.get(r.table_name) ?? /* @__PURE__ */ new Set()).add(r.column_name));
1335
- }
1336
- for (const table of tables) {
1337
- tableMeta.set(table, { fks: fks.get(table) ?? [], naiveTimestamps: timestamps.get(table) ?? /* @__PURE__ */ new Set() });
1338
- }
1339
- } catch (err) {
1340
- metaRetryAt = Date.now() + META_RETRY_MS;
1341
- logger.debug(`table metadata lookup failed: ${err instanceof Error ? err.message : String(err)}`);
1342
- }
1343
- }
1344
- function relatedResourceIds(table, row) {
1345
- const out = [];
1346
- for (const fk of tableMeta.get(table)?.fks ?? []) {
1347
- const value = row[fk.column];
1348
- if (typeof value === "string" || typeof value === "number") {
1349
- out.push({ resource_type: fk.refTable, resource_id: String(value) });
1350
- }
1351
- }
1352
- return out;
1353
- }
1354
- function emitFresh(rows) {
1355
- if (rows.length === 0) return;
1356
- const emitted = currentEmittedAuditIds();
1357
- if (emitted === null) {
1358
- emitAuditRows(rows);
1359
- return;
1360
- }
1361
- const fresh = [];
1362
- for (const row of rows) {
1363
- if (row.id === "" || emitted.has(row.id)) continue;
1364
- emitted.add(row.id);
1365
- fresh.push(row);
1366
- }
1367
- emitAuditRows(fresh);
1368
- }
1369
- function correlationForTx(txid) {
1370
- if (!txid) return generate();
1371
- let id = txCorrelation.get(txid);
1372
- if (!id) {
1373
- if (txCorrelation.size >= 1e3) txCorrelation.clear();
1374
- id = generate();
1375
- txCorrelation.set(txid, id);
1376
- }
1377
- return id;
1378
- }
1379
- function isPermissionDenied(err) {
1380
- return err?.code === "42501";
1381
- }
1382
- function sortById(rows) {
1383
- return rows.sort(
1384
- (a, b) => a.id.length !== b.id.length ? a.id.length - b.id.length : a.id < b.id ? -1 : a.id > b.id ? 1 : 0
1385
- );
1386
- }
1387
- function emitOne(row) {
1388
- const op = mapOp(row.op);
1389
- if (!op) return;
1390
- const naive = tableMeta.get(row.table_name)?.naiveTimestamps ?? null;
1391
- const oldRow = withUtcTimestamps(coerceJsonb(row.old_row), naive);
1392
- const newRow = withUtcTimestamps(coerceJsonb(row.new_row), naive);
1393
- const related = row.resource_id === null ? relatedResourceIds(row.table_name, newRow ?? oldRow ?? {}) : null;
1394
- if (op === "create" && newRow) {
1395
- emitDbEvent({
1396
- modelClass: row.table_name,
1397
- operation: "create",
1398
- resourceId: row.resource_id,
1399
- initialAttributes: newRow,
1400
- modelInstance: newRow,
1401
- displayName: null,
1402
- timestamp: row.captured_at ?? null,
1403
- relatedResourceIds: related,
1404
- _fromTrigger: true
1405
- });
1406
- return;
1407
- }
1408
- if (op === "update" && oldRow && newRow) {
1409
- const changes = computeChanges(oldRow, newRow);
1410
- if (changes.length === 0) {
1411
- return;
1412
- }
1413
- emitDbEvent({
1414
- modelClass: row.table_name,
1415
- operation: "update",
1416
- resourceId: row.resource_id,
1417
- changes,
1418
- // Prefer the post-state for the display name — that's what the
1419
- // user just told the system to call this row.
1420
- modelInstance: newRow,
1421
- displayName: null,
1422
- timestamp: row.captured_at ?? null,
1423
- relatedResourceIds: related,
1424
- _fromTrigger: true
1425
- });
1426
- return;
1427
- }
1428
- if (op === "destroy" && oldRow) {
1429
- emitDbEvent({
1430
- modelClass: row.table_name,
1431
- operation: "destroy",
1432
- resourceId: row.resource_id,
1433
- initialAttributes: oldRow,
1434
- modelInstance: oldRow,
1435
- displayName: null,
1436
- timestamp: row.captured_at ?? null,
1437
- relatedResourceIds: related,
1438
- _fromTrigger: true
1439
- });
1440
- return;
1441
- }
1442
- }
1443
- var NAIVE_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;
1444
- function withUtcTimestamps(row, naiveColumns) {
1445
- if (!row) return row;
1446
- const out = {};
1447
- for (const [key, value] of Object.entries(row)) {
1448
- const isNaiveColumn = naiveColumns ? naiveColumns.has(key) : /(_at|At)$/.test(key);
1449
- out[key] = isNaiveColumn && typeof value === "string" && NAIVE_TIMESTAMP.test(value) ? `${value}Z` : value;
1450
- }
1451
- return out;
1452
- }
1453
- function mapOp(op) {
1454
- if (op === "INSERT") return "create";
1455
- if (op === "UPDATE") return "update";
1456
- if (op === "DELETE") return "destroy";
1457
- return null;
1458
- }
1459
- function computeChanges(oldRow, newRow) {
1460
- const out = [];
1461
- for (const key of Object.keys(newRow)) {
1462
- const before = oldRow[key];
1463
- const after = newRow[key];
1464
- if (deepEqual(before, after)) continue;
1465
- out.push({ attribute: key, from: before, to: after });
1466
- }
1467
- return out;
1468
- }
1469
- function deepEqual(a, b) {
1470
- if (a === b) return true;
1471
- if (a === null || b === null) return false;
1472
- if (typeof a !== typeof b) return false;
1473
- if (typeof a !== "object") return false;
1474
- try {
1475
- return stableStringify(a) === stableStringify(b);
1476
- } catch {
1477
- return false;
1478
- }
1479
- }
1480
- function stableStringify(value) {
1481
- if (value === null || typeof value !== "object") return JSON.stringify(value);
1482
- if (Array.isArray(value)) {
1483
- return "[" + value.map((v) => stableStringify(v)).join(",") + "]";
1484
- }
1485
- const entries = Object.keys(value).sort().map((k) => JSON.stringify(k) + ":" + stableStringify(value[k]));
1486
- return "{" + entries.join(",") + "}";
1487
- }
1488
- function extractRows(result) {
1489
- if (!result) return [];
1490
- if (Array.isArray(result)) return result;
1491
- if (typeof result === "object" && Array.isArray(result.rows)) {
1492
- return result.rows;
1493
- }
1494
- return [];
1495
- }
1496
- function toDate(value) {
1497
- if (value == null) return null;
1498
- const d = value instanceof Date ? value : new Date(String(value));
1499
- return Number.isNaN(d.getTime()) ? null : d;
1500
- }
1501
- function normalizeAuditRow(raw) {
1502
- const r = raw ?? {};
1503
- return {
1504
- id: r.id == null ? "" : String(r.id),
1505
- table_name: String(r.table_name ?? ""),
1506
- op: r.op,
1507
- old_row: r.old_row ?? null,
1508
- new_row: r.new_row ?? null,
1509
- resource_id: r.resource_id == null ? null : String(r.resource_id),
1510
- correlation_id: r.correlation_id == null ? null : String(r.correlation_id),
1511
- txid: r.txid == null ? null : String(r.txid),
1512
- captured_at: toDate(r.captured_at)
1513
- };
1514
- }
1515
- function coerceJsonb(value) {
1516
- if (value === null || value === void 0) return null;
1517
- if (typeof value === "string") {
1518
- try {
1519
- const parsed = JSON.parse(value);
1520
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
1521
- } catch {
1522
- return null;
1523
- }
1524
- }
1525
- if (typeof value === "object" && !Array.isArray(value)) return value;
1526
- return null;
1527
- }
1528
-
1529
- // src/triggers/patch-pg.ts
1530
- var txState = /* @__PURE__ */ new WeakMap();
1531
- function patchPgClient(pgModule) {
1532
- if (!pgModule || !pgModule.Client || !pgModule.Client.prototype) {
1533
- logger.debug("patchPgClient: not a recognized pg module shape, skipping");
1534
- return;
1535
- }
1536
- const proto = pgModule.Client.prototype;
1537
- if (proto._ezlogsPatched) return;
1538
- const originalQuery = proto.query;
1539
- proto.query = function patchedQuery(config, values, callback) {
1540
- return runPatchedQuery(
1541
- this,
1542
- originalQuery,
1543
- config,
1544
- values,
1545
- callback
1546
- );
1547
- };
1548
- proto._ezlogsPatched = true;
1549
- }
1550
- function runPatchedQuery(client, original, config, values, callback) {
1551
- const state = ensureState(client);
1552
- const text = extractQueryText(config);
1553
- const verb = leadingVerb(text);
1554
- if (verb === "BEGIN" || verb === "START") {
1555
- state.inTx = true;
1556
- state.injected = false;
1557
- return original.call(client, config, values, callback);
1558
- }
1559
- if (verb === "COMMIT" || verb === "ROLLBACK" || verb === "END") {
1560
- const result = original.call(client, config, values, callback);
1561
- state.inTx = false;
1562
- state.injected = false;
1563
- return result;
1564
- }
1565
- if (state.inTx) {
1566
- if (state.injected) {
1567
- return original.call(client, config, values, callback);
1568
- }
1569
- const ctx2 = snapshotContext();
1570
- if (!ctx2.actorId && !ctx2.correlationId) {
1571
- state.injected = true;
1572
- return original.call(client, config, values, callback);
1573
- }
1574
- state.injected = true;
1575
- return injectAndRun(client, original, config, values, callback, ctx2);
1576
- }
1577
- const ctx = snapshotContext();
1578
- if (!ctx.actorId && !ctx.correlationId) {
1579
- return original.call(client, config, values, callback);
1580
- }
1581
- return wrapInTx(client, original, config, values, callback, ctx);
1582
- }
1583
- function snapshotContext() {
1584
- const actor = getCurrentActor();
1585
- return {
1586
- actorId: actor && actor.id ? actor.id : null,
1587
- correlationId: current()
1588
- };
1589
- }
1590
- async function injectAndRun(client, original, config, values, callback, ctx) {
1591
- if (ctx.actorId) {
1592
- await safeSet(client, original, {
1593
- text: "SELECT set_config('ezlogs.actor_id', $1, true)",
1594
- values: [ctx.actorId]
1595
- });
1596
- }
1597
- if (ctx.correlationId) {
1598
- await safeSet(client, original, {
1599
- text: "SELECT set_config('ezlogs.correlation_id', $1, true)",
1600
- values: [ctx.correlationId]
1601
- });
1602
- }
1603
- return original.call(client, config, values, callback);
1604
- }
1605
- async function safeSet(client, original, cfg) {
1606
- try {
1607
- const result = original.call(client, cfg);
1608
- if (result && typeof result.then === "function") {
1609
- await result;
1610
- }
1611
- } catch (err) {
1612
- logger.debug(
1613
- `patchPgClient: SET LOCAL failed (continuing): ${err instanceof Error ? err.message : String(err)}`
1614
- );
1615
- }
1616
- }
1617
- function wrapInTx(client, original, config, values, callback, ctx) {
1618
- const state = ensureState(client);
1619
- let userCb = null;
1620
- let realValues = values;
1621
- if (typeof callback === "function") {
1622
- userCb = callback;
1623
- } else if (typeof values === "function") {
1624
- userCb = values;
1625
- realValues = void 0;
1626
- }
1627
- const begin = original.call(client, "BEGIN");
1628
- if (!begin || typeof begin.then !== "function") {
1629
- return original.call(client, config, values, callback);
1630
- }
1631
- const wrapped = begin.then(async () => {
1632
- state.inTx = true;
1633
- state.injected = true;
1634
- if (ctx.actorId) {
1635
- await original.call(client, {
1636
- text: "SELECT set_config('ezlogs.actor_id', $1, true)",
1637
- values: [ctx.actorId]
1638
- });
1639
- }
1640
- if (ctx.correlationId) {
1641
- await original.call(client, {
1642
- text: "SELECT set_config('ezlogs.correlation_id', $1, true)",
1643
- values: [ctx.correlationId]
1644
- });
1645
- }
1646
- }).then(
1647
- () => (
1648
- // Run the user's actual query in promise mode — DO NOT forward
1649
- // the caller's callback. See comment above.
1650
- original.call(client, config, realValues)
1651
- )
1652
- ).then(
1653
- async (result) => {
1654
- await original.call(client, "COMMIT");
1655
- state.inTx = false;
1656
- state.injected = false;
1657
- return result;
1658
- },
1659
- async (err) => {
1660
- try {
1661
- await original.call(client, "ROLLBACK");
1662
- } catch {
1663
- }
1664
- state.inTx = false;
1665
- state.injected = false;
1666
- throw err;
1667
- }
1668
- );
1669
- if (userCb) {
1670
- wrapped.then(
1671
- (result) => userCb(null, result),
1672
- (err) => userCb(err instanceof Error ? err : new Error(String(err)))
1673
- );
1674
- return void 0;
1675
- }
1676
- return wrapped;
1677
- }
1678
- function ensureState(client) {
1679
- let s = txState.get(client);
1680
- if (!s) {
1681
- s = { inTx: false, injected: false };
1682
- txState.set(client, s);
1683
- }
1684
- return s;
1685
- }
1686
- function extractQueryText(config) {
1687
- if (typeof config === "string") return config;
1688
- if (config && typeof config === "object" && typeof config.text === "string") {
1689
- return config.text;
1690
- }
1691
- return "";
1692
- }
1693
- function leadingVerb(text) {
1694
- let s = text;
1695
- while (true) {
1696
- const before = s.length;
1697
- s = s.replace(/^\s+/, "");
1698
- s = s.replace(/^--[^\n]*\n?/, "");
1699
- if (s.length === before) break;
1700
- }
1701
- const m = /^[A-Za-z]+/.exec(s);
1702
- return m ? m[0].toUpperCase() : "";
1703
- }
1704
-
290
+ Object.defineProperty(exports, "patchPgClient", {
291
+ enumerable: true,
292
+ get: function () { return chunkY5NSHKWQ_cjs.patchPgClient; }
293
+ });
294
+ Object.defineProperty(exports, "detectTriggerTrackedTables", {
295
+ enumerable: true,
296
+ get: function () { return chunkYX2XPLOA_cjs.detectTriggerTrackedTables; }
297
+ });
298
+ Object.defineProperty(exports, "emitAuditRows", {
299
+ enumerable: true,
300
+ get: function () { return chunkYX2XPLOA_cjs.emitAuditRows; }
301
+ });
302
+ Object.defineProperty(exports, "flushAuditLog", {
303
+ enumerable: true,
304
+ get: function () { return chunkYX2XPLOA_cjs.flushAuditLog; }
305
+ });
306
+ Object.defineProperty(exports, "pruneAuditLog", {
307
+ enumerable: true,
308
+ get: function () { return chunkYX2XPLOA_cjs.pruneAuditLog; }
309
+ });
310
+ Object.defineProperty(exports, "readAuditRows", {
311
+ enumerable: true,
312
+ get: function () { return chunkYX2XPLOA_cjs.readAuditRows; }
313
+ });
314
+ Object.defineProperty(exports, "sweepAuditLog", {
315
+ enumerable: true,
316
+ get: function () { return chunkYX2XPLOA_cjs.sweepAuditLog; }
317
+ });
1705
318
  exports.applyDatabaseContext = applyDatabaseContext;
1706
319
  exports.buildTrackingSql = buildTrackingSql;
1707
320
  exports.detectEngine = detectEngine;
1708
- exports.detectTriggerTrackedTables = detectTriggerTrackedTables;
1709
- exports.emitAuditRows = emitAuditRows;
1710
- exports.flushAuditLog = flushAuditLog;
1711
321
  exports.getDatabaseContext = getDatabaseContext;
1712
322
  exports.parseArgs = parseArgs;
1713
- exports.patchPgClient = patchPgClient;
1714
- exports.pruneAuditLog = pruneAuditLog;
1715
- exports.readAuditRows = readAuditRows;
1716
323
  exports.runInstall = runInstall;
1717
- exports.sweepAuditLog = sweepAuditLog;
1718
324
  exports.withDatabaseContext = withDatabaseContext;