ezlogs-nextjs 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +53 -16
  2. package/bin/install-triggers.cjs +73 -11
  3. package/dist/actors/index.cjs +5 -37
  4. package/dist/actors/index.js +2 -34
  5. package/dist/chunk-C5OSM557.js +39 -0
  6. package/dist/chunk-CE3R7DVB.js +1127 -0
  7. package/dist/chunk-CU45I2WR.js +498 -0
  8. package/dist/chunk-DKRNNI4I.js +180 -0
  9. package/dist/chunk-SIAA4J6H.js +17 -0
  10. package/dist/chunk-UQHEW6ER.js +119 -0
  11. package/dist/chunk-UWHYJH4M.cjs +126 -0
  12. package/dist/chunk-V5YNKKTG.cjs +42 -0
  13. package/dist/chunk-WASXTDLW.cjs +1151 -0
  14. package/dist/chunk-Y5NSHKWQ.cjs +182 -0
  15. package/dist/chunk-YX2XPLOA.cjs +508 -0
  16. package/dist/chunk-ZDSQYCYV.cjs +21 -0
  17. package/dist/db/drizzle.cjs +6 -713
  18. package/dist/db/drizzle.js +5 -712
  19. package/dist/db/prisma.cjs +52 -763
  20. package/dist/db/prisma.d.cts +3 -1
  21. package/dist/db/prisma.d.ts +3 -1
  22. package/dist/db/prisma.js +38 -749
  23. package/dist/db/supabase.cjs +21 -728
  24. package/dist/db/supabase.js +14 -721
  25. package/dist/index.cjs +204 -2181
  26. package/dist/index.js +107 -2090
  27. package/dist/jobs/bullmq.cjs +61 -552
  28. package/dist/jobs/bullmq.d.cts +8 -3
  29. package/dist/jobs/bullmq.d.ts +8 -3
  30. package/dist/jobs/bullmq.js +58 -549
  31. package/dist/jobs/inngest.cjs +23 -561
  32. package/dist/jobs/inngest.d.cts +7 -5
  33. package/dist/jobs/inngest.d.ts +7 -5
  34. package/dist/jobs/inngest.js +19 -557
  35. package/dist/jobs/supabase-queues.cjs +17 -603
  36. package/dist/jobs/supabase-queues.js +12 -598
  37. package/dist/jobs/trigger.cjs +18 -587
  38. package/dist/jobs/trigger.js +16 -585
  39. package/dist/jobs/upstash-workflow.cjs +62 -584
  40. package/dist/jobs/upstash-workflow.d.cts +17 -2
  41. package/dist/jobs/upstash-workflow.d.ts +17 -2
  42. package/dist/jobs/upstash-workflow.js +59 -582
  43. package/dist/nextjs-plugin/index.cjs +1 -1
  44. package/dist/nextjs-plugin/index.js +1 -1
  45. package/dist/nextjs-plugin/loader.cjs +21 -25
  46. package/dist/nextjs-plugin/loader.js +1 -5
  47. package/dist/triggers/index.cjs +40 -1234
  48. package/dist/triggers/index.d.cts +7 -2
  49. package/dist/triggers/index.d.ts +7 -2
  50. package/dist/triggers/index.js +6 -1221
  51. package/package.json +4 -1
@@ -1,197 +1,12 @@
1
+ export { patchPgClient } from '../chunk-DKRNNI4I.js';
2
+ export { detectTriggerTrackedTables, emitAuditRows, flushAuditLog, pruneAuditLog, readAuditRows, sweepAuditLog } from '../chunk-CU45I2WR.js';
3
+ import { DEFAULT_EXCLUDED_TABLES, getCurrentActor, current } from '../chunk-CE3R7DVB.js';
4
+ import { logger } from '../chunk-C5OSM557.js';
5
+ import '../chunk-SIAA4J6H.js';
1
6
  import { readFile } from 'fs/promises';
2
7
  import { dirname, join } from 'path';
3
8
  import { fileURLToPath } from 'url';
4
9
 
5
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
6
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
7
- }) : x)(function(x) {
8
- if (typeof require !== "undefined") return require.apply(this, arguments);
9
- throw Error('Dynamic require of "' + x + '" is not supported');
10
- });
11
-
12
- // src/logger.ts
13
- var LEVEL_RANK = {
14
- debug: 10,
15
- info: 20,
16
- warn: 30,
17
- error: 40,
18
- silent: 100
19
- };
20
- var LEVEL_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:log-level");
21
- function readLevel() {
22
- const g = globalThis;
23
- return g[LEVEL_KEY] ?? "warn";
24
- }
25
- function shouldLog(level) {
26
- return LEVEL_RANK[level] >= LEVEL_RANK[readLevel()];
27
- }
28
- function safeWrite(level, message) {
29
- try {
30
- if (!shouldLog(level)) return;
31
- const line = `[ezlogs] ${message}`;
32
- if (level === "error" || level === "warn") {
33
- console.error(line);
34
- } else {
35
- console.log(line);
36
- }
37
- } catch {
38
- }
39
- }
40
- var logger = {
41
- debug: (message) => safeWrite("debug", message),
42
- info: (message) => safeWrite("info", message),
43
- warn: (message) => safeWrite("warn", message),
44
- error: (message) => safeWrite("error", message)
45
- };
46
-
47
- // src/configuration.ts
48
- var DEFAULT_EXCLUDED_PATHS = Object.freeze([
49
- // Next.js / Vercel infrastructure noise
50
- "/_next/*",
51
- "/_vercel/*",
52
- "/__nextjs_*",
53
- // NextAuth.js / Auth.js — skip session-refresh polls and CSRF/provider
54
- // metadata GETs (high-frequency, no business meaning), but CAPTURE
55
- // POSTs (callbacks, signin, signout, register). The POSTs are the
56
- // actual auth events users care about; the GETs are pure plumbing.
57
- Object.freeze({ path: "/api/auth/*", methods: ["GET", "HEAD"] }),
58
- // Generic infrastructure
59
- "/health*",
60
- "/api/health",
61
- "/up",
62
- "/alive",
63
- "/ready",
64
- "/metrics",
65
- "/favicon.ico",
66
- "/.well-known*",
67
- "/robots.txt",
68
- "/sitemap.xml",
69
- "/*.hot-update.*",
70
- // Auth routes (common patterns across Clerk, NextAuth, custom auth)
71
- "*/login*",
72
- "*/logout*",
73
- "*/sign-in*",
74
- "*/sign-out*",
75
- "*/signin*",
76
- "*/signout*",
77
- "/session*"
78
- ]);
79
- var DEFAULT_EXCLUDED_TABLES = Object.freeze([
80
- // Prisma migration ledger
81
- "_prisma_migrations",
82
- // Auth.js / NextAuth Prisma adapter — session/verification-token churn
83
- // is auth machinery, not business activity. Account/User stay captured.
84
- "Session",
85
- "VerificationToken",
86
- // Common cross-stack convention names for the same things
87
- "sessions",
88
- "session",
89
- "verification_tokens"
90
- ]);
91
- var DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
92
- var DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
93
- var Configuration = class {
94
- serverUrl = null;
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
- allowInsecureTransport = false;
107
- excludedPaths = [];
108
- excludedTables = [];
109
- excludedJobClasses = [];
110
- excludedGraphqlOperations = [];
111
- excludedGraphqlVariableKeys = [];
112
- actorFromRequest = null;
113
- displayNameFor = {};
114
- isServerActionError = null;
115
- databaseReader = null;
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
- 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.allowInsecureTransport !== void 0) {
159
- this.allowInsecureTransport = options.allowInsecureTransport;
160
- }
161
- if (options.actorFromSupabase !== void 0) {
162
- this.actorFromSupabase = options.actorFromSupabase;
163
- }
164
- if (options.databaseReader !== void 0) {
165
- this.databaseReader = options.databaseReader;
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
- var GLOBAL_CONFIG_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:configuration");
186
- function configuration() {
187
- const g = globalThis;
188
- if (!g[GLOBAL_CONFIG_KEY]) {
189
- g[GLOBAL_CONFIG_KEY] = new Configuration();
190
- }
191
- return g[GLOBAL_CONFIG_KEY];
192
- }
193
-
194
- // src/triggers/install.ts
195
10
  var HERE = dirname(fileURLToPath(import.meta.url));
196
11
  function parseArgs(argv) {
197
12
  const out = {
@@ -425,112 +240,6 @@ ${trackingSql}
425
240
  }
426
241
  }
427
242
 
428
- // src/edge-fallback.ts
429
- var ALS_CTOR = loadAsyncLocalStorage();
430
- function loadAsyncLocalStorage() {
431
- const fromGlobal = globalThis.AsyncLocalStorage;
432
- if (typeof fromGlobal === "function") return fromGlobal;
433
- try {
434
- const req = typeof __require !== "undefined" ? __require : (
435
- // In ESM, `createRequire` is the official escape hatch.
436
- // We pull it via globalThis to avoid a static `import`
437
- // that would itself be browser-bundled.
438
- void 0
439
- );
440
- if (typeof req === "function") {
441
- const moduleName = ["async", "hooks"].join("_");
442
- const mod = req("node:" + moduleName);
443
- if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
444
- }
445
- } catch {
446
- }
447
- return null;
448
- }
449
- function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
450
- const globalStore = globalThis;
451
- let entry = globalStore[key];
452
- if (!entry) {
453
- const als2 = (() => {
454
- if (!ALS_CTOR) return null;
455
- try {
456
- return new ALS_CTOR();
457
- } catch {
458
- return null;
459
- }
460
- })();
461
- entry = { als: als2, edgeFallback: null };
462
- globalStore[key] = entry;
463
- }
464
- const als = entry.als;
465
- const stateRef = entry;
466
- return {
467
- read() {
468
- if (als) return als.getStore()?.value ?? null;
469
- return stateRef.edgeFallback?.value ?? null;
470
- },
471
- run(value, callback) {
472
- if (als) return als.run({ value }, callback);
473
- const previous = stateRef.edgeFallback;
474
- stateRef.edgeFallback = { value };
475
- try {
476
- return callback();
477
- } finally {
478
- stateRef.edgeFallback = previous;
479
- }
480
- },
481
- update(value) {
482
- if (als) {
483
- const store = als.getStore();
484
- if (store) store.value = value;
485
- return;
486
- }
487
- stateRef.edgeFallback = { value };
488
- },
489
- _resetForTests() {
490
- stateRef.edgeFallback = null;
491
- },
492
- _isAsyncLocalStorage() {
493
- return als !== null;
494
- }
495
- };
496
- }
497
-
498
- // src/actor.ts
499
- var storage = createScopedStorage(
500
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-storage")
501
- );
502
- function getCurrentActor() {
503
- return storage.read();
504
- }
505
- function runWithActorScope(callback) {
506
- return storage.run(null, callback);
507
- }
508
-
509
- // src/correlation.ts
510
- var storage2 = createScopedStorage(
511
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
512
- );
513
- function generate() {
514
- const ts = Date.now();
515
- const hex = randomHexBytes(4);
516
- return `ezl_${ts}_${hex}`;
517
- }
518
- function randomHexBytes(byteCount) {
519
- const buf = new Uint8Array(byteCount);
520
- globalThis.crypto.getRandomValues(buf);
521
- let out = "";
522
- for (let i = 0; i < buf.length; i++) {
523
- out += buf[i].toString(16).padStart(2, "0");
524
- }
525
- return out;
526
- }
527
- function current() {
528
- return storage2.read();
529
- }
530
- function runWithCorrelation(correlationId, callback) {
531
- return storage2.run(correlationId, callback);
532
- }
533
-
534
243
  // src/triggers/context.ts
535
244
  function getDatabaseContext() {
536
245
  const actor = getCurrentActor();
@@ -575,928 +284,4 @@ async function withDatabaseContext(client, callback) {
575
284
  }
576
285
  }
577
286
 
578
- // src/event-builder.ts
579
- var SENSITIVE_KEYS = Object.freeze([
580
- "password",
581
- "token",
582
- "secret",
583
- "api_key",
584
- "credit_card"
585
- ]);
586
- var VALID_SOURCE_TYPES = [
587
- "http_request",
588
- "background_job",
589
- "database_callback"
590
- ];
591
- var VALID_OUTCOMES = ["success", "failure"];
592
- function build(input) {
593
- const source_type = validateSourceType(input.source_type);
594
- const source_data_raw = validateSourceData(input.source_data);
595
- const outcome = validateOutcome(input.outcome);
596
- const timestamp = validateTimestamp(input.timestamp ?? null);
597
- const resource_ids = validateResourceIds(input.resource_ids ?? []);
598
- const context_raw = validateContext(input.context ?? null);
599
- const duration_ms = validateDurationMs();
600
- const error_message = input.error_message ?? null;
601
- validateOutcomeErrorConsistency(outcome, error_message);
602
- const source_data = sanitizeRecord(source_data_raw);
603
- const context = context_raw === null ? null : sanitizeRecord(context_raw);
604
- const correlation_id = input.correlation_id ?? null;
605
- const event = {
606
- timestamp,
607
- source_type,
608
- source_data,
609
- outcome,
610
- correlation_id,
611
- resource_ids,
612
- context,
613
- duration_ms,
614
- error_message
615
- };
616
- return event;
617
- }
618
- function validateSourceType(value) {
619
- const normalized = String(value);
620
- if (!VALID_SOURCE_TYPES.includes(normalized)) {
621
- throw new ArgError(
622
- `source_type must be one of ${VALID_SOURCE_TYPES.join(", ")}, got: ${normalized}`
623
- );
624
- }
625
- return normalized;
626
- }
627
- function validateSourceData(value) {
628
- if (value === null || value === void 0) {
629
- throw new ArgError("source_data is required");
630
- }
631
- if (!isPlainObject(value)) {
632
- throw new ArgError(
633
- `source_data must be an object, got: ${describe(value)}`
634
- );
635
- }
636
- return value;
637
- }
638
- function validateOutcome(value) {
639
- const normalized = String(value);
640
- if (!VALID_OUTCOMES.includes(normalized)) {
641
- throw new ArgError(
642
- `outcome must be one of ${VALID_OUTCOMES.join(", ")}, got: ${normalized}`
643
- );
644
- }
645
- return normalized;
646
- }
647
- function validateTimestamp(value) {
648
- if (value === null) {
649
- return (/* @__PURE__ */ new Date()).toISOString();
650
- }
651
- if (typeof value === "string") {
652
- const parsed = new Date(value);
653
- if (Number.isNaN(parsed.getTime())) {
654
- throw new ArgError(
655
- `timestamp must be valid ISO 8601 format, got: ${value}`
656
- );
657
- }
658
- return value;
659
- }
660
- if (value instanceof Date) {
661
- if (Number.isNaN(value.getTime())) {
662
- throw new ArgError("timestamp must be a valid Date");
663
- }
664
- return value.toISOString();
665
- }
666
- throw new ArgError(
667
- `timestamp must be a string or Date, got: ${describe(value)}`
668
- );
669
- }
670
- function validateResourceIds(value) {
671
- if (!Array.isArray(value)) {
672
- throw new ArgError(`resource_ids must be an array, got: ${describe(value)}`);
673
- }
674
- value.forEach((entry, index) => {
675
- if (!isPlainObject(entry)) {
676
- throw new ArgError(
677
- `resource_ids[${index}] must be an object, got: ${describe(entry)}`
678
- );
679
- }
680
- const e = entry;
681
- if (!("resource_type" in e) || !("resource_id" in e)) {
682
- throw new ArgError(
683
- `resource_ids[${index}] must have resource_type and resource_id keys, got: ${Object.keys(e).join(", ")}`
684
- );
685
- }
686
- if (typeof e.resource_type !== "string") {
687
- throw new ArgError(
688
- `resource_ids[${index}].resource_type must be a string, got: ${describe(e.resource_type)}`
689
- );
690
- }
691
- if (typeof e.resource_id !== "string") {
692
- throw new ArgError(
693
- `resource_ids[${index}].resource_id must be a string, got: ${describe(e.resource_id)}`
694
- );
695
- }
696
- });
697
- return value;
698
- }
699
- function validateContext(value) {
700
- if (value === null) return null;
701
- if (!isPlainObject(value)) {
702
- throw new ArgError(
703
- `context must be an object or null, got: ${describe(value)}`
704
- );
705
- }
706
- return value;
707
- }
708
- function validateDurationMs(value) {
709
- return null;
710
- }
711
- function validateOutcomeErrorConsistency(outcome, error_message) {
712
- if (outcome === "failure") {
713
- if (error_message === null || error_message === "") {
714
- throw new ArgError("error_message is required when outcome is 'failure'");
715
- }
716
- } else if (outcome === "success") {
717
- if (error_message !== null) {
718
- throw new ArgError("error_message must be null when outcome is 'success'");
719
- }
720
- }
721
- }
722
- function sanitizeRecord(input) {
723
- const result = {};
724
- for (const key of Object.keys(input)) {
725
- const value = input[key];
726
- if (isSensitiveKey(key)) {
727
- result[key] = "[FILTERED]";
728
- } else if (isPlainObject(value)) {
729
- result[key] = sanitizeRecord(value);
730
- } else if (Array.isArray(value)) {
731
- result[key] = value.map(
732
- (item) => isPlainObject(item) ? sanitizeRecord(item) : item
733
- );
734
- } else {
735
- result[key] = value;
736
- }
737
- }
738
- return result;
739
- }
740
- function isSensitiveKey(key) {
741
- const lower = key.toLowerCase();
742
- return SENSITIVE_KEYS.some((p) => lower.includes(p));
743
- }
744
- function isPlainObject(value) {
745
- if (value === null || typeof value !== "object") return false;
746
- const proto = Object.getPrototypeOf(value);
747
- return proto === Object.prototype || proto === null;
748
- }
749
- function describe(value) {
750
- if (value === null) return "null";
751
- if (Array.isArray(value)) return "Array";
752
- return typeof value;
753
- }
754
- var ArgError = class extends Error {
755
- constructor(message) {
756
- super(message);
757
- this.name = "ArgError";
758
- }
759
- };
760
-
761
- // src/pipeline/buffer.ts
762
- var GLOBAL_QUEUE_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:buffer-queue");
763
- function getQueue() {
764
- const g = globalThis;
765
- if (!g[GLOBAL_QUEUE_KEY]) g[GLOBAL_QUEUE_KEY] = [];
766
- return g[GLOBAL_QUEUE_KEY];
767
- }
768
- function pushEvent(event) {
769
- try {
770
- const queue = getQueue();
771
- const max = maxSize();
772
- if (queue.length >= max) {
773
- queue.shift();
774
- logger.warn(`Buffer full (${max}), dropped oldest event`);
775
- }
776
- queue.push(event);
777
- } catch (error) {
778
- logger.error(`pushEvent failed: ${describe2(error)}`);
779
- }
780
- }
781
- function maxSize() {
782
- try {
783
- return configuration().bufferSize;
784
- } catch {
785
- return 1e4;
786
- }
787
- }
788
- function describe2(error) {
789
- if (error instanceof Error) return `${error.name}: ${error.message}`;
790
- return String(error);
791
- }
792
- var SENSITIVE_WORD_PATTERNS = Object.freeze([
793
- "pin",
794
- "otp",
795
- "totp",
796
- "iban",
797
- "mfa",
798
- "passphrase"
799
- ]);
800
- function snakeLower(key) {
801
- return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
802
- }
803
- function matchesSensitiveKey(key, substringPatterns) {
804
- const lower = key.toLowerCase();
805
- const snake = snakeLower(key);
806
- if (substringPatterns.some((p) => lower.includes(p) || snake.includes(p))) {
807
- return true;
808
- }
809
- const words = snake.split(/[^a-z0-9]+/);
810
- return SENSITIVE_WORD_PATTERNS.some((w) => words.includes(w));
811
- }
812
-
813
- // src/db/shared.ts
814
- var IGNORED_ATTRIBUTES = Object.freeze([
815
- "id",
816
- "createdAt",
817
- "created_at",
818
- "updatedAt",
819
- "updated_at",
820
- "deletedAt",
821
- "deleted_at",
822
- // Auth.js / NextAuth standard columns
823
- "emailVerified",
824
- "expires"
825
- ]);
826
- var DB_SENSITIVE_PATTERNS = Object.freeze([
827
- "password",
828
- "token",
829
- "secret",
830
- "api_key",
831
- "credit_card",
832
- "ssn",
833
- "social_security",
834
- "encrypted",
835
- "private_key",
836
- "public_key",
837
- "signing_key",
838
- "pem",
839
- "cipher",
840
- "nonce",
841
- "salt",
842
- "digest",
843
- "signature",
844
- "hmac",
845
- // 0.2.0 additions. `credential` / `passwd` / `apikey` were already in
846
- // the HTTP list; `passcode` / `card_number` / `cardnumber` / `cvv` /
847
- // `cvc` are new. Whole-word `pin` / `otp` / `totp` / `iban` come from
848
- // SENSITIVE_WORD_PATTERNS. The SQL trigger mirrors this list.
849
- "credential",
850
- "passwd",
851
- "passcode",
852
- "apikey",
853
- "card_number",
854
- "cardnumber",
855
- "cvv",
856
- "cvc"
857
- ]);
858
- function emitDbEvent(input) {
859
- try {
860
- const config = configuration();
861
- if (!config.captureDb) return;
862
- if (config.allExcludedTables().includes(input.modelClass)) return;
863
- if (config.databaseReader && !input._fromTrigger) {
864
- const tracked = config.triggerTrackedTables;
865
- if (tracked === null || tracked.has(input.modelClass)) return;
866
- }
867
- if (input.operation === "update") {
868
- const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
869
- if (meaningful.length === 0) return;
870
- }
871
- const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
872
- const context = buildContext(input);
873
- const event = build({
874
- source_type: "database_callback",
875
- source_data: {
876
- model_class: input.modelClass,
877
- operation: input.operation
878
- },
879
- outcome: "success",
880
- correlation_id: current(),
881
- resource_ids: resourceIdStr === null ? [] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
882
- context,
883
- duration_ms: null,
884
- timestamp: input.timestamp ?? null
885
- });
886
- pushEvent(event);
887
- } catch (error) {
888
- logger.debug(`db emit failed: ${describeError(error)}`);
889
- }
890
- }
891
- function buildContext(input) {
892
- const context = {};
893
- const actor = getCurrentActor();
894
- if (actor) context.actor = actor;
895
- if ((input.operation === "create" || input.operation === "destroy") && input.initialAttributes) {
896
- const filtered = filterMeaningfulAttributes(input.initialAttributes);
897
- if (filtered !== null) context.initial_attributes = filtered;
898
- }
899
- if (input.operation === "update" && input.changes) {
900
- const filtered = filterMeaningfulChanges(input.changes);
901
- if (filtered.length > 0) {
902
- context.changes = filtered.map((c) => {
903
- const out = {
904
- attribute: c.attribute,
905
- to: formatForJson(c.to)
906
- };
907
- if (c.from !== void 0) out.from = formatForJson(c.from);
908
- return out;
909
- });
910
- }
911
- }
912
- const displayName = input.displayName ?? (input.modelInstance ? resolveDisplayName(input.modelClass, input.modelInstance) : null);
913
- if (displayName !== null) context.display_name = displayName;
914
- return Object.keys(context).length === 0 ? null : context;
915
- }
916
- function filterMeaningfulAttributes(attrs) {
917
- const out = {};
918
- for (const key of Object.keys(attrs)) {
919
- if (!isMeaningfulAttribute(key)) continue;
920
- const value = attrs[key];
921
- if (value === null || value === void 0) continue;
922
- if (!isScalar(value)) continue;
923
- out[key] = formatForJson(value);
924
- }
925
- return Object.keys(out).length === 0 ? null : out;
926
- }
927
- function filterMeaningfulChanges(changes) {
928
- return changes.filter((c) => {
929
- if (!isMeaningfulAttribute(c.attribute)) return false;
930
- if (!isScalar(c.to)) return false;
931
- if (c.from === void 0) return true;
932
- if (!isScalar(c.from)) return false;
933
- return valuesActuallyChanged(c.from, c.to);
934
- });
935
- }
936
- function isMeaningfulAttribute(name) {
937
- if (IGNORED_ATTRIBUTES.includes(name)) return false;
938
- if (isDbSensitive(name)) return false;
939
- return true;
940
- }
941
- function isDbSensitive(name) {
942
- return matchesSensitiveKey(name, DB_SENSITIVE_PATTERNS);
943
- }
944
- function isScalar(value) {
945
- if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
946
- return true;
947
- }
948
- if (isPrismaDecimal(value)) return true;
949
- if (Buffer.isBuffer?.(value)) return false;
950
- if (Array.isArray(value)) return value.every((v) => isScalar(v));
951
- return false;
952
- }
953
- function valuesActuallyChanged(from, to) {
954
- if (from === null && to === null) return false;
955
- if (from instanceof Date && to instanceof Date) {
956
- return from.getTime() !== to.getTime();
957
- }
958
- return from !== to;
959
- }
960
- function formatForJson(value) {
961
- if (value === null || value === void 0) return value;
962
- if (value instanceof Date) return value.toISOString();
963
- if (typeof value === "bigint") return value.toString();
964
- if (isPrismaDecimal(value)) return Number(value.toString());
965
- if (Array.isArray(value)) return value.map(formatForJson);
966
- return value;
967
- }
968
- function isPrismaDecimal(value) {
969
- if (value === null || typeof value !== "object") return false;
970
- const obj = value;
971
- return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
972
- }
973
- function resolveDisplayName(modelClass, instance) {
974
- try {
975
- const config = configuration();
976
- const resolver = config.displayNameFor[modelClass];
977
- const resolved = applyResolver(resolver, instance);
978
- if (resolved !== null) return resolved;
979
- for (const field of ["name", "title", "number"]) {
980
- const value = instance[field];
981
- if (value !== null && value !== void 0 && String(value).length > 0) {
982
- return String(value);
983
- }
984
- }
985
- } catch {
986
- }
987
- return null;
988
- }
989
- function applyResolver(resolver, instance) {
990
- if (typeof resolver === "string") {
991
- const value = instance[resolver];
992
- if (value !== null && value !== void 0 && String(value).length > 0) {
993
- return String(value);
994
- }
995
- return null;
996
- }
997
- if (typeof resolver === "function") {
998
- try {
999
- const value = resolver(instance);
1000
- if (typeof value === "string" && value.length > 0) return value;
1001
- if (value !== null && value !== void 0 && String(value).length > 0) {
1002
- return String(value);
1003
- }
1004
- } catch {
1005
- }
1006
- }
1007
- return null;
1008
- }
1009
- function describeError(error) {
1010
- if (error instanceof Error) return `${error.name}: ${error.message}`;
1011
- return String(error);
1012
- }
1013
-
1014
- // src/triggers/emit-dedup.ts
1015
- var storage3 = createScopedStorage(
1016
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-emitted-ids-storage")
1017
- );
1018
- function currentEmittedAuditIds() {
1019
- return storage3.read();
1020
- }
1021
-
1022
- // src/triggers/reader.ts
1023
- var COLUMNS = "id, table_name, op, old_row, new_row, resource_id, correlation_id, txid, captured_at";
1024
- var ORPHAN_AGE = "5 minutes";
1025
- var PRUNE_AGE = "24 hours";
1026
- var SWEEP_BATCH = 100;
1027
- var PRUNE_BATCH = 2e3;
1028
- var SWEEP_INTERVAL_MS = 1e4;
1029
- var PRUNE_INTERVAL_MS = 10 * 6e4;
1030
- var lastSweepAt = 0;
1031
- var lastPruneAt = 0;
1032
- var deleteDenied = false;
1033
- var txCorrelation = /* @__PURE__ */ new Map();
1034
- async function readAuditRows(exec, correlationId) {
1035
- try {
1036
- if (!deleteDenied) {
1037
- try {
1038
- return sortById(
1039
- extractRows(
1040
- await exec(
1041
- `DELETE FROM ezlogs_audit_log WHERE correlation_id = $1 RETURNING ${COLUMNS}`,
1042
- [correlationId]
1043
- )
1044
- ).map(normalizeAuditRow)
1045
- );
1046
- } catch (err) {
1047
- if (!isPermissionDenied(err)) throw err;
1048
- deleteDenied = true;
1049
- logger.warn(
1050
- "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'`."
1051
- );
1052
- }
1053
- }
1054
- const result = await exec(
1055
- `SELECT ${COLUMNS} FROM ezlogs_audit_log WHERE correlation_id = $1 ORDER BY id ASC`,
1056
- [correlationId]
1057
- );
1058
- return extractRows(result).map(normalizeAuditRow);
1059
- } catch (err) {
1060
- logger.debug(
1061
- `readAuditRows failed: ${err instanceof Error ? err.message : String(err)}`
1062
- );
1063
- return [];
1064
- }
1065
- }
1066
- async function sweepAuditLog(exec) {
1067
- if (deleteDenied) return 0;
1068
- try {
1069
- const rows = sortById(
1070
- extractRows(
1071
- await exec(
1072
- `DELETE FROM ezlogs_audit_log
1073
- WHERE id IN (
1074
- SELECT id FROM ezlogs_audit_log
1075
- WHERE (correlation_id IS NULL
1076
- OR captured_at < now() - interval '${ORPHAN_AGE}')
1077
- -- Never resurface history: past the retention cap a
1078
- -- row is pruned, not sent as new activity.
1079
- AND captured_at > now() - interval '${PRUNE_AGE}'
1080
- ORDER BY id
1081
- LIMIT ${SWEEP_BATCH}
1082
- FOR UPDATE SKIP LOCKED)
1083
- RETURNING ${COLUMNS}`,
1084
- []
1085
- )
1086
- ).map(normalizeAuditRow)
1087
- );
1088
- for (const row of rows) {
1089
- const correlationId = row.correlation_id ?? correlationForTx(row.txid);
1090
- runWithCorrelation(
1091
- correlationId,
1092
- () => runWithActorScope(() => emitOne(row))
1093
- );
1094
- }
1095
- return rows.length;
1096
- } catch (err) {
1097
- logger.debug(
1098
- `sweepAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
1099
- );
1100
- return 0;
1101
- }
1102
- }
1103
- async function pruneAuditLog(exec) {
1104
- if (deleteDenied) return;
1105
- try {
1106
- await exec(
1107
- `DELETE FROM ezlogs_audit_log
1108
- WHERE id IN (
1109
- SELECT id FROM ezlogs_audit_log
1110
- WHERE captured_at < now() - interval '${PRUNE_AGE}'
1111
- LIMIT ${PRUNE_BATCH})`,
1112
- []
1113
- );
1114
- } catch (err) {
1115
- logger.debug(
1116
- `pruneAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
1117
- );
1118
- }
1119
- }
1120
- async function detectTriggerTrackedTables(exec) {
1121
- try {
1122
- const result = await exec(
1123
- `SELECT event_object_table AS table_name
1124
- FROM information_schema.triggers
1125
- WHERE trigger_name = 'ezlogs_audit'
1126
- AND trigger_schema = 'public'`,
1127
- []
1128
- );
1129
- const rows = extractRows(result);
1130
- const tables = /* @__PURE__ */ new Set();
1131
- for (const row of rows) {
1132
- const r = row ?? {};
1133
- if (typeof r.table_name === "string" && r.table_name.length > 0) {
1134
- tables.add(r.table_name);
1135
- }
1136
- }
1137
- return tables;
1138
- } catch (err) {
1139
- logger.debug(
1140
- `detectTriggerTrackedTables failed: ${err instanceof Error ? err.message : String(err)}`
1141
- );
1142
- return null;
1143
- }
1144
- }
1145
- function emitAuditRows(rows) {
1146
- for (const row of rows) {
1147
- emitOne(row);
1148
- }
1149
- }
1150
- async function flushAuditLog(exec) {
1151
- if (!exec) return;
1152
- const correlationId = current();
1153
- if (!correlationId) return;
1154
- const rows = await readAuditRows(exec, correlationId);
1155
- emitFresh(rows);
1156
- const now = Date.now();
1157
- if (now - lastPruneAt >= PRUNE_INTERVAL_MS) {
1158
- lastPruneAt = now;
1159
- await pruneAuditLog(exec);
1160
- }
1161
- if (now - lastSweepAt >= SWEEP_INTERVAL_MS) {
1162
- lastSweepAt = now;
1163
- await sweepAuditLog(exec);
1164
- }
1165
- }
1166
- function emitFresh(rows) {
1167
- if (rows.length === 0) return;
1168
- const emitted = currentEmittedAuditIds();
1169
- if (emitted === null) {
1170
- emitAuditRows(rows);
1171
- return;
1172
- }
1173
- const fresh = [];
1174
- for (const row of rows) {
1175
- if (row.id === "" || emitted.has(row.id)) continue;
1176
- emitted.add(row.id);
1177
- fresh.push(row);
1178
- }
1179
- emitAuditRows(fresh);
1180
- }
1181
- function correlationForTx(txid) {
1182
- if (!txid) return generate();
1183
- let id = txCorrelation.get(txid);
1184
- if (!id) {
1185
- if (txCorrelation.size >= 1e3) txCorrelation.clear();
1186
- id = generate();
1187
- txCorrelation.set(txid, id);
1188
- }
1189
- return id;
1190
- }
1191
- function isPermissionDenied(err) {
1192
- return err?.code === "42501";
1193
- }
1194
- function sortById(rows) {
1195
- return rows.sort(
1196
- (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
1197
- );
1198
- }
1199
- function emitOne(row) {
1200
- const op = mapOp(row.op);
1201
- if (!op) return;
1202
- const oldRow = coerceJsonb(row.old_row);
1203
- const newRow = coerceJsonb(row.new_row);
1204
- if (op === "create" && newRow) {
1205
- emitDbEvent({
1206
- modelClass: row.table_name,
1207
- operation: "create",
1208
- resourceId: row.resource_id,
1209
- initialAttributes: newRow,
1210
- modelInstance: newRow,
1211
- displayName: null,
1212
- timestamp: row.captured_at ?? null,
1213
- _fromTrigger: true
1214
- });
1215
- return;
1216
- }
1217
- if (op === "update" && oldRow && newRow) {
1218
- const changes = computeChanges(oldRow, newRow);
1219
- if (changes.length === 0) {
1220
- return;
1221
- }
1222
- emitDbEvent({
1223
- modelClass: row.table_name,
1224
- operation: "update",
1225
- resourceId: row.resource_id,
1226
- changes,
1227
- // Prefer the post-state for the display name — that's what the
1228
- // user just told the system to call this row.
1229
- modelInstance: newRow,
1230
- displayName: null,
1231
- timestamp: row.captured_at ?? null,
1232
- _fromTrigger: true
1233
- });
1234
- return;
1235
- }
1236
- if (op === "destroy" && oldRow) {
1237
- emitDbEvent({
1238
- modelClass: row.table_name,
1239
- operation: "destroy",
1240
- resourceId: row.resource_id,
1241
- initialAttributes: oldRow,
1242
- modelInstance: oldRow,
1243
- displayName: null,
1244
- timestamp: row.captured_at ?? null,
1245
- _fromTrigger: true
1246
- });
1247
- return;
1248
- }
1249
- }
1250
- function mapOp(op) {
1251
- if (op === "INSERT") return "create";
1252
- if (op === "UPDATE") return "update";
1253
- if (op === "DELETE") return "destroy";
1254
- return null;
1255
- }
1256
- function computeChanges(oldRow, newRow) {
1257
- const out = [];
1258
- for (const key of Object.keys(newRow)) {
1259
- const before = oldRow[key];
1260
- const after = newRow[key];
1261
- if (deepEqual(before, after)) continue;
1262
- out.push({ attribute: key, from: before, to: after });
1263
- }
1264
- return out;
1265
- }
1266
- function deepEqual(a, b) {
1267
- if (a === b) return true;
1268
- if (a === null || b === null) return false;
1269
- if (typeof a !== typeof b) return false;
1270
- if (typeof a !== "object") return false;
1271
- try {
1272
- return stableStringify(a) === stableStringify(b);
1273
- } catch {
1274
- return false;
1275
- }
1276
- }
1277
- function stableStringify(value) {
1278
- if (value === null || typeof value !== "object") return JSON.stringify(value);
1279
- if (Array.isArray(value)) {
1280
- return "[" + value.map((v) => stableStringify(v)).join(",") + "]";
1281
- }
1282
- const entries = Object.keys(value).sort().map((k) => JSON.stringify(k) + ":" + stableStringify(value[k]));
1283
- return "{" + entries.join(",") + "}";
1284
- }
1285
- function extractRows(result) {
1286
- if (!result) return [];
1287
- if (Array.isArray(result)) return result;
1288
- if (typeof result === "object" && Array.isArray(result.rows)) {
1289
- return result.rows;
1290
- }
1291
- return [];
1292
- }
1293
- function toDate(value) {
1294
- if (value == null) return null;
1295
- const d = value instanceof Date ? value : new Date(String(value));
1296
- return Number.isNaN(d.getTime()) ? null : d;
1297
- }
1298
- function normalizeAuditRow(raw) {
1299
- const r = raw ?? {};
1300
- return {
1301
- id: r.id == null ? "" : String(r.id),
1302
- table_name: String(r.table_name ?? ""),
1303
- op: r.op,
1304
- old_row: r.old_row ?? null,
1305
- new_row: r.new_row ?? null,
1306
- resource_id: r.resource_id == null ? null : String(r.resource_id),
1307
- correlation_id: r.correlation_id == null ? null : String(r.correlation_id),
1308
- txid: r.txid == null ? null : String(r.txid),
1309
- captured_at: toDate(r.captured_at)
1310
- };
1311
- }
1312
- function coerceJsonb(value) {
1313
- if (value === null || value === void 0) return null;
1314
- if (typeof value === "string") {
1315
- try {
1316
- const parsed = JSON.parse(value);
1317
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
1318
- } catch {
1319
- return null;
1320
- }
1321
- }
1322
- if (typeof value === "object" && !Array.isArray(value)) return value;
1323
- return null;
1324
- }
1325
-
1326
- // src/triggers/patch-pg.ts
1327
- var txState = /* @__PURE__ */ new WeakMap();
1328
- function patchPgClient(pgModule) {
1329
- if (!pgModule || !pgModule.Client || !pgModule.Client.prototype) {
1330
- logger.debug("patchPgClient: not a recognized pg module shape, skipping");
1331
- return;
1332
- }
1333
- const proto = pgModule.Client.prototype;
1334
- if (proto._ezlogsPatched) return;
1335
- const originalQuery = proto.query;
1336
- proto.query = function patchedQuery(config, values, callback) {
1337
- return runPatchedQuery(
1338
- this,
1339
- originalQuery,
1340
- config,
1341
- values,
1342
- callback
1343
- );
1344
- };
1345
- proto._ezlogsPatched = true;
1346
- }
1347
- function runPatchedQuery(client, original, config, values, callback) {
1348
- const state = ensureState(client);
1349
- const text = extractQueryText(config);
1350
- const verb = leadingVerb(text);
1351
- if (verb === "BEGIN" || verb === "START") {
1352
- state.inTx = true;
1353
- state.injected = false;
1354
- return original.call(client, config, values, callback);
1355
- }
1356
- if (verb === "COMMIT" || verb === "ROLLBACK" || verb === "END") {
1357
- const result = original.call(client, config, values, callback);
1358
- state.inTx = false;
1359
- state.injected = false;
1360
- return result;
1361
- }
1362
- if (state.inTx) {
1363
- if (state.injected) {
1364
- return original.call(client, config, values, callback);
1365
- }
1366
- const ctx2 = snapshotContext();
1367
- if (!ctx2.actorId && !ctx2.correlationId) {
1368
- state.injected = true;
1369
- return original.call(client, config, values, callback);
1370
- }
1371
- state.injected = true;
1372
- return injectAndRun(client, original, config, values, callback, ctx2);
1373
- }
1374
- const ctx = snapshotContext();
1375
- if (!ctx.actorId && !ctx.correlationId) {
1376
- return original.call(client, config, values, callback);
1377
- }
1378
- return wrapInTx(client, original, config, values, callback, ctx);
1379
- }
1380
- function snapshotContext() {
1381
- const actor = getCurrentActor();
1382
- return {
1383
- actorId: actor && actor.id ? actor.id : null,
1384
- correlationId: current()
1385
- };
1386
- }
1387
- async function injectAndRun(client, original, config, values, callback, ctx) {
1388
- if (ctx.actorId) {
1389
- await safeSet(client, original, {
1390
- text: "SELECT set_config('ezlogs.actor_id', $1, true)",
1391
- values: [ctx.actorId]
1392
- });
1393
- }
1394
- if (ctx.correlationId) {
1395
- await safeSet(client, original, {
1396
- text: "SELECT set_config('ezlogs.correlation_id', $1, true)",
1397
- values: [ctx.correlationId]
1398
- });
1399
- }
1400
- return original.call(client, config, values, callback);
1401
- }
1402
- async function safeSet(client, original, cfg) {
1403
- try {
1404
- const result = original.call(client, cfg);
1405
- if (result && typeof result.then === "function") {
1406
- await result;
1407
- }
1408
- } catch (err) {
1409
- logger.debug(
1410
- `patchPgClient: SET LOCAL failed (continuing): ${err instanceof Error ? err.message : String(err)}`
1411
- );
1412
- }
1413
- }
1414
- function wrapInTx(client, original, config, values, callback, ctx) {
1415
- const state = ensureState(client);
1416
- let userCb = null;
1417
- let realValues = values;
1418
- if (typeof callback === "function") {
1419
- userCb = callback;
1420
- } else if (typeof values === "function") {
1421
- userCb = values;
1422
- realValues = void 0;
1423
- }
1424
- const begin = original.call(client, "BEGIN");
1425
- if (!begin || typeof begin.then !== "function") {
1426
- return original.call(client, config, values, callback);
1427
- }
1428
- const wrapped = begin.then(async () => {
1429
- state.inTx = true;
1430
- state.injected = true;
1431
- if (ctx.actorId) {
1432
- await original.call(client, {
1433
- text: "SELECT set_config('ezlogs.actor_id', $1, true)",
1434
- values: [ctx.actorId]
1435
- });
1436
- }
1437
- if (ctx.correlationId) {
1438
- await original.call(client, {
1439
- text: "SELECT set_config('ezlogs.correlation_id', $1, true)",
1440
- values: [ctx.correlationId]
1441
- });
1442
- }
1443
- }).then(
1444
- () => (
1445
- // Run the user's actual query in promise mode — DO NOT forward
1446
- // the caller's callback. See comment above.
1447
- original.call(client, config, realValues)
1448
- )
1449
- ).then(
1450
- async (result) => {
1451
- await original.call(client, "COMMIT");
1452
- state.inTx = false;
1453
- state.injected = false;
1454
- return result;
1455
- },
1456
- async (err) => {
1457
- try {
1458
- await original.call(client, "ROLLBACK");
1459
- } catch {
1460
- }
1461
- state.inTx = false;
1462
- state.injected = false;
1463
- throw err;
1464
- }
1465
- );
1466
- if (userCb) {
1467
- wrapped.then(
1468
- (result) => userCb(null, result),
1469
- (err) => userCb(err instanceof Error ? err : new Error(String(err)))
1470
- );
1471
- return void 0;
1472
- }
1473
- return wrapped;
1474
- }
1475
- function ensureState(client) {
1476
- let s = txState.get(client);
1477
- if (!s) {
1478
- s = { inTx: false, injected: false };
1479
- txState.set(client, s);
1480
- }
1481
- return s;
1482
- }
1483
- function extractQueryText(config) {
1484
- if (typeof config === "string") return config;
1485
- if (config && typeof config === "object" && typeof config.text === "string") {
1486
- return config.text;
1487
- }
1488
- return "";
1489
- }
1490
- function leadingVerb(text) {
1491
- let s = text;
1492
- while (true) {
1493
- const before = s.length;
1494
- s = s.replace(/^\s+/, "");
1495
- s = s.replace(/^--[^\n]*\n?/, "");
1496
- if (s.length === before) break;
1497
- }
1498
- const m = /^[A-Za-z]+/.exec(s);
1499
- return m ? m[0].toUpperCase() : "";
1500
- }
1501
-
1502
- export { applyDatabaseContext, buildTrackingSql, detectEngine, detectTriggerTrackedTables, emitAuditRows, flushAuditLog, getDatabaseContext, parseArgs, patchPgClient, pruneAuditLog, readAuditRows, runInstall, sweepAuditLog, withDatabaseContext };
287
+ export { applyDatabaseContext, buildTrackingSql, detectEngine, getDatabaseContext, parseArgs, runInstall, withDatabaseContext };