ezlogs-nextjs 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -105,22 +105,37 @@ Restart your dev server, hit any route, and watch for
105
105
  `[ezlogs] FlushScheduler started` in the terminal. Events appear in
106
106
  your EZLogs dashboard within a few seconds.
107
107
 
108
- ### 4. (Optional) Full DB diffs on Postgres
108
+ Sending to a local EZLogs server over plain `http://` (development)?
109
+ Events are still sent, but the agent warns on every start; pass
110
+ `allowInsecureTransport: true` to `ezlogs.init` to silence it. Keep
111
+ `https://` in production.
109
112
 
110
- One command installs Postgres triggers that capture every business-
111
- table write with full from→to change diffs:
113
+ ### 4. Database changes
114
+
115
+ Steps 1-3 capture requests, Server Actions and jobs. Database changes
116
+ need one more step, depending on your stack:
117
+
118
+ | Your app writes with | Do this | You get |
119
+ |---|---|---|
120
+ | **Supabase** (supabase-js) | `npm i pg`, set `DATABASE_URL` to the Postgres connection string, run `npx ezlogs-nextjs install-triggers`. Nothing to wrap: the agent tags supabase-js requests and the trigger reads the tag. | Every write (`.from()`, `.rpc()`, bulk) with from→to diffs, linked to its request |
121
+ | **Prisma** on Postgres | triggers (as above) + `new PrismaClient().$extends(ezlogsPrisma())` (below) | Same |
122
+ | **Drizzle** (node-postgres) or raw **`pg`** | triggers (as above). The agent patches `pg` itself. | Same |
123
+ | postgres.js, Neon HTTP, scripts | triggers (as above) | Writes show up as their own actions, not linked to the request |
124
+ | MySQL, SQLite, PlanetScale, no trigger access | a per-ORM adapter: `ezlogsPrisma()`, `ezlogsDrizzleLogger`, `wrapSupabase` ([docs/database.md](./docs/database.md)) | New values only, no before-values |
112
125
 
113
126
  ```bash
127
+ npm i pg # the trigger installer and reader need it
114
128
  npx ezlogs-nextjs install-triggers
115
129
  ```
116
130
 
117
- Migration tables, sessions, and the agent's own audit table are
118
- skipped automatically. The trigger path needs the `pg` package in your
119
- project (`npm i pg`); if `pg` or the audit table is missing, the agent
120
- logs one warning at startup and leaves the trigger path off. Without
121
- triggers, DB writes are captured only if you wire a per-ORM adapter
122
- (`ezlogsPrisma`, `ezlogsDrizzleLogger`, `wrapSupabase`) — see
123
- [docs/database.md](./docs/database.md) for trade-offs.
131
+ Run it from your app's directory with the package installed there
132
+ (with bun: `bunx ezlogs-nextjs install-triggers` or
133
+ `./node_modules/.bin/ezlogs-nextjs install-triggers`); if the package
134
+ isn't installed locally, npx / bunx download whatever version is
135
+ published, and the CLI warns. Migration tables, sessions, and the
136
+ agent's own audit table are skipped automatically. If `pg` or the
137
+ audit table is missing at runtime, the agent logs one warning at
138
+ startup and leaves the trigger path off.
124
139
 
125
140
  **Recommended setup for Prisma** (plain `new PrismaClient()`, no driver
126
141
  adapter): triggers **plus** the extension, which tags each write with
@@ -141,7 +156,13 @@ your own `prisma.$transaction(...)` are not tagged: they still show up,
141
156
  as separate actions without an actor. Without the extension, a plain
142
157
  PrismaClient's writes are never tagged.
143
158
 
144
- **Upgrading from 0.1.x:** run `npx ezlogs-nextjs install-triggers --tables=none`
159
+ Without triggers, the extension still sends Prisma writes itself (new
160
+ values only — Prisma doesn't expose the old row). With triggers it
161
+ sends nothing for tracked tables; the trigger rows are the single
162
+ source, so there are no duplicates (also for `@@map`-ed models).
163
+
164
+ **Upgrading:** from 0.2.x to 0.3.0 there is nothing to re-run (no SQL
165
+ changes). From 0.1.x, run `npx ezlogs-nextjs install-triggers --tables=none`
145
166
  **before** deploying the new agent (functions only, no table locks),
146
167
  deploy right after, and later re-run `npx ezlogs-nextjs install-triggers`
147
168
  at a quiet moment. Details in [CHANGELOG.md](./CHANGELOG.md).
@@ -152,10 +173,10 @@ at a quiet moment. Details in [CHANGELOG.md](./CHANGELOG.md).
152
173
 
153
174
  | Source | What | Where it comes from |
154
175
  |---|---|---|
155
- | HTTP | Method, path, status, duration, sanitized params, GraphQL op | App Router + Pages Router (auto-wrapped) |
156
- | Server Actions | Action name, args, outcome, redirect/notFound handled as success | File-level + inline `"use server"` (auto-wrapped) |
157
- | Database | `model_class`, `operation`, full from→to diffs (trigger path) | Postgres triggers, Prisma, Drizzle, supabase-js |
158
- | Background jobs | `job_class`, `job_id`, `queue`, `retry_count` | BullMQ, Inngest, Trigger.dev, pgmq, Upstash Workflow |
176
+ | HTTP | Method, path, status, duration, sanitized params (incl. route params like `[id]`), GraphQL op, the `error` / `message` of a JSON error response | App Router + Pages Router (auto-wrapped) |
177
+ | Server Actions | Action name, args, caller IP, outcome (a returned `{ success: false, error }` is a failure with that message), redirect/notFound handled as success | File-level + inline `"use server"` (auto-wrapped) |
178
+ | Database | `model_class`, `operation`, full from→to diffs incl. json leaves (trigger path), record name | Postgres triggers, Prisma, Drizzle, supabase-js |
179
+ | Background jobs | `job_class`, `job_id`, `queue`, `retry_count`, sanitized `arguments`, plus the DB writes the job made | BullMQ, Inngest, Trigger.dev, pgmq, Upstash Workflow |
159
180
 
160
181
  Every event in one inbound request shares a `correlation_id` so the
161
182
  server stitches them into a single Action card.
@@ -221,7 +242,10 @@ event. EZLogs is best-effort, not guaranteed delivery.
221
242
  - **Database rows (trigger path).** Columns with sensitive names are
222
243
  removed by the trigger itself, so they are never written to
223
244
  `ezlogs_audit_log`. An update that only touches such columns writes
224
- no audit row.
245
+ no audit row. Sensitive keys inside json/jsonb columns are dropped
246
+ by the agent before sending. DB values are dropped, not sent as
247
+ `"[FILTERED]"` (that placeholder is for request params and job
248
+ arguments).
225
249
  - **Retention of `ezlogs_audit_log`.** Rows are deleted as soon as the
226
250
  agent sends them. Rows nobody claimed (untagged writes, or tagged
227
251
  rows older than 5 minutes) are sent as their own actions by a
@@ -1,21 +1,54 @@
1
1
  #!/usr/bin/env node
2
- // CLI shim for `npx @ezlogs/nextjs install-triggers`.
2
+ // CLI for `npx ezlogs-nextjs install-triggers` (also installed as the
3
+ // `install-triggers` bin).
3
4
  //
4
5
  // Lazy-imports the dist CJS bundle + `pg` so we don't load either when
5
- // the customer is just installing the package. `pg` is a devDependency
6
- // of the agent for tests; in customer projects it's expected to be
7
- // present transitively (drizzle-orm, prisma, etc. all pull it in) or
8
- // the customer can install it explicitly. We don't list it as a peer
9
- // because the only path that needs it is this CLI.
6
+ // the customer is just installing the package. `pg` is resolved from
7
+ // the customer's project first (the directory the command runs in),
8
+ // so it works with npm, pnpm and bun layouts where `pg` isn't hoisted
9
+ // next to this package. We don't list it as a peer because only this
10
+ // CLI and the trigger reader need it.
10
11
  //
11
12
  // Exits non-zero on any install failure so CI scripts can catch it.
12
13
 
14
+ const fs = require("node:fs");
15
+ const path = require("node:path");
16
+
17
+ // The ezlogs-nextjs this project would load (nearest node_modules up
18
+ // from the working directory, so monorepo hoisting counts), or null.
19
+ function installedFromProject() {
20
+ for (let dir = process.cwd(); ; dir = path.dirname(dir)) {
21
+ const candidate = path.join(dir, "node_modules", "ezlogs-nextjs");
22
+ if (fs.existsSync(candidate)) return fs.realpathSync(candidate);
23
+ if (path.dirname(dir) === dir) return null;
24
+ }
25
+ }
26
+
13
27
  (async () => {
14
28
  const { runInstall, parseArgs } = require("../dist/triggers/index.cjs");
29
+ const { version } = require("../package.json");
15
30
 
16
31
  const argv = process.argv.slice(2);
32
+ const command = argv.find((a) => !a.startsWith("-"));
33
+ if (command !== undefined && command !== "install-triggers") {
34
+ console.error(
35
+ `[ezlogs] Unknown command "${command}". Usage: npx ezlogs-nextjs install-triggers [--help]`,
36
+ );
37
+ process.exit(1);
38
+ }
17
39
  const args = parseArgs(argv);
18
40
 
41
+ // `npx` / `bunx` download the package to a temp dir when it isn't
42
+ // installed in this project — a version that may differ from the one
43
+ // your app runs, and a place `pg` can't be found from.
44
+ if (installedFromProject() !== fs.realpathSync(path.join(__dirname, ".."))) {
45
+ console.warn(
46
+ `[ezlogs] Running ezlogs-nextjs ${version} from ${path.dirname(__dirname)}, not from ` +
47
+ "this project's node_modules. Run it from your app's directory after " +
48
+ "`npm install ezlogs-nextjs` (or `./node_modules/.bin/ezlogs-nextjs install-triggers`).",
49
+ );
50
+ }
51
+
19
52
  // For --help / --print / unknown-engine paths the programmatic entry
20
53
  // doesn't need a real exec. Forward without a connection.
21
54
  if (args.help || args.print) {
@@ -25,13 +58,14 @@
25
58
 
26
59
  let pg;
27
60
  try {
28
- pg = require("pg");
61
+ pg = require(require.resolve("pg", { paths: [process.cwd(), __dirname] }));
29
62
  } catch {
30
63
  console.error(
31
- "[ezlogs] install-triggers needs `pg` installed in your project " +
32
- "(it ships as a devDependency of the agent itself, not a peer). " +
33
- "Run `npm install --save-dev pg` and try again, or run with " +
34
- "--print and pipe the SQL into your own tool.",
64
+ `[ezlogs] install-triggers needs the \`pg\` package, and it was not found from ${process.cwd()}.\n` +
65
+ " Install it in your app (the agent also needs it at runtime to read the audit log):\n" +
66
+ " npm install pg (or: pnpm add pg / yarn add pg / bun add pg)\n" +
67
+ " then run this command again from your app's directory.\n" +
68
+ " Or print the SQL and run it with your own tool: npx ezlogs-nextjs install-triggers --print",
35
69
  );
36
70
  process.exit(1);
37
71
  }
@@ -509,6 +509,37 @@ function matchesSensitiveKey(key, substringPatterns) {
509
509
  const words = snake.split(/[^a-z0-9]+/);
510
510
  return SENSITIVE_WORD_PATTERNS.some((w) => words.includes(w));
511
511
  }
512
+ function passesLuhn(digits) {
513
+ let sum = 0;
514
+ for (let i = 0; i < digits.length; i += 1) {
515
+ let d = Number(digits[digits.length - 1 - i]);
516
+ if (i % 2 === 1) {
517
+ d *= 2;
518
+ if (d > 9) d -= 9;
519
+ }
520
+ sum += d;
521
+ }
522
+ return sum % 10 === 0;
523
+ }
524
+ var SECRET_TEXT_PATTERNS = [
525
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
526
+ /\beyJ[\w-]+\.[\w-]+\.[\w-]+/g,
527
+ /\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]+/g,
528
+ /\bsk-[A-Za-z0-9_-]{16,}/g,
529
+ /\bgh[pousr]_[A-Za-z0-9]{20,}/g,
530
+ /\bxox[abposr]-[A-Za-z0-9-]+/g,
531
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g
532
+ ];
533
+ var EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
534
+ function scrubSecretsInText(text, options = {}) {
535
+ let out = text;
536
+ for (const pattern of SECRET_TEXT_PATTERNS) out = out.replace(pattern, "[FILTERED]");
537
+ out = out.replace(/\b(Bearer|Basic)\s+[\w.~+/=-]+/gi, "$1 [FILTERED]").replace(/\b\d(?:[ -]?\d){12,18}\b/g, (match) => {
538
+ const digits = match.replace(/[ -]/g, "");
539
+ return (digits.length === 15 || digits.length === 16) && passesLuhn(digits) ? "[FILTERED]" : match;
540
+ });
541
+ return options.emails ? out.replace(EMAIL, "[FILTERED]") : out;
542
+ }
512
543
 
513
544
  // src/db/shared.ts
514
545
  var IGNORED_ATTRIBUTES = Object.freeze([
@@ -517,8 +548,6 @@ var IGNORED_ATTRIBUTES = Object.freeze([
517
548
  "created_at",
518
549
  "updatedAt",
519
550
  "updated_at",
520
- "deletedAt",
521
- "deleted_at",
522
551
  // Auth.js / NextAuth standard columns
523
552
  "emailVerified",
524
553
  "expires"
@@ -562,14 +591,17 @@ function emitDbEvent(input) {
562
591
  if (config.allExcludedTables().includes(input.modelClass)) return;
563
592
  if (config.databaseReader && !input._fromTrigger) {
564
593
  const tracked = config.triggerTrackedTables;
565
- if (tracked === null || tracked.has(input.modelClass)) return;
594
+ if (tracked === null || tracked.has(input.table ?? input.modelClass)) return;
566
595
  }
567
596
  if (input.operation === "update") {
568
597
  const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
569
598
  if (meaningful.length === 0) return;
570
599
  }
571
600
  const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
572
- const context = buildContext(input);
601
+ const related = resourceIdStr === null ? input.relatedResourceIds ?? [] : [];
602
+ const context = buildContext(
603
+ related.length > 0 ? { ...input, displayName: null, modelInstance: null } : input
604
+ );
573
605
  const event = build({
574
606
  source_type: "database_callback",
575
607
  source_data: {
@@ -578,7 +610,7 @@ function emitDbEvent(input) {
578
610
  },
579
611
  outcome: "success",
580
612
  correlation_id: current(),
581
- resource_ids: resourceIdStr === null ? [] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
613
+ resource_ids: resourceIdStr === null ? [...related] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
582
614
  context,
583
615
  duration_ms: null,
584
616
  timestamp: input.timestamp ?? null
@@ -625,7 +657,7 @@ function filterMeaningfulAttributes(attrs) {
625
657
  return Object.keys(out).length === 0 ? null : out;
626
658
  }
627
659
  function filterMeaningfulChanges(changes) {
628
- return changes.filter((c) => {
660
+ return flattenNestedChanges(changes).filter((c) => {
629
661
  if (!isMeaningfulAttribute(c.attribute)) return false;
630
662
  if (!isScalar(c.to)) return false;
631
663
  if (c.from === void 0) return true;
@@ -633,6 +665,60 @@ function filterMeaningfulChanges(changes) {
633
665
  return valuesActuallyChanged(c.from, c.to);
634
666
  });
635
667
  }
668
+ var MAX_NESTED_DEPTH = 3;
669
+ var MAX_NESTED_LEAVES = 20;
670
+ var MAX_UNKNOWN_FROM_LEAVES = 5;
671
+ function flattenNestedChanges(changes) {
672
+ if (!changes.some((c) => isPlainRecord(c.to) || isPlainRecord(c.from))) return changes;
673
+ const out = [];
674
+ for (const c of changes) {
675
+ if (!isPlainRecord(c.to) && !isPlainRecord(c.from)) {
676
+ out.push(c);
677
+ continue;
678
+ }
679
+ if (!isMeaningfulAttribute(c.attribute)) continue;
680
+ const leaves = [];
681
+ collectLeafChanges(c.attribute, c.from, c.to, 1, leaves);
682
+ const cap = c.from === void 0 ? MAX_UNKNOWN_FROM_LEAVES : MAX_NESTED_LEAVES;
683
+ out.push(...leaves.slice(0, cap).map(scrubLeaf));
684
+ }
685
+ return out;
686
+ }
687
+ function collectLeafChanges(path, from, to, depth, out) {
688
+ if (out.length > MAX_NESTED_LEAVES) return;
689
+ const fromObj = isPlainRecord(from);
690
+ const toObj = isPlainRecord(to);
691
+ if ((fromObj || toObj) && depth <= MAX_NESTED_DEPTH && (fromObj || from == null) && (toObj || to == null)) {
692
+ const f = fromObj ? from : {};
693
+ const t = toObj ? to : {};
694
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(f), ...Object.keys(t)])) {
695
+ const before = from === void 0 ? void 0 : f[key] ?? null;
696
+ collectLeafChanges(`${path}.${key}`, before, t[key] ?? null, depth + 1, out);
697
+ }
698
+ return;
699
+ }
700
+ if (from !== void 0 && sameJson(from, to)) return;
701
+ out.push(from === void 0 ? { attribute: path, to } : { attribute: path, from, to });
702
+ }
703
+ function scrubLeaf(change) {
704
+ const scrub = (v) => typeof v === "string" ? scrubSecretsInText(v) : v;
705
+ const out = { attribute: change.attribute, to: scrub(change.to) };
706
+ if (change.from !== void 0) out.from = scrub(change.from);
707
+ return out;
708
+ }
709
+ function isPlainRecord(value) {
710
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
711
+ const proto = Object.getPrototypeOf(value);
712
+ return proto === Object.prototype || proto === null;
713
+ }
714
+ function sameJson(a, b) {
715
+ if (a === b) return true;
716
+ try {
717
+ return JSON.stringify(a) === JSON.stringify(b);
718
+ } catch {
719
+ return false;
720
+ }
721
+ }
636
722
  function isMeaningfulAttribute(name) {
637
723
  if (IGNORED_ATTRIBUTES.includes(name)) return false;
638
724
  if (isDbSensitive(name)) return false;
@@ -670,22 +756,44 @@ function isPrismaDecimal(value) {
670
756
  const obj = value;
671
757
  return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
672
758
  }
759
+ var DISPLAY_NAME_COLUMNS = ["name", "title", "number", "label"];
760
+ var MAX_DISPLAY_NAME_LENGTH = 120;
673
761
  function resolveDisplayName(modelClass, instance) {
674
762
  try {
675
763
  const config = configuration();
676
764
  const resolver = config.displayNameFor[modelClass];
677
765
  const resolved = applyResolver(resolver, instance);
678
766
  if (resolved !== null) return resolved;
679
- for (const field of ["name", "title", "number"]) {
680
- const value = instance[field];
681
- if (value !== null && value !== void 0 && String(value).length > 0) {
682
- return String(value);
767
+ const columns = /* @__PURE__ */ new Map();
768
+ for (const key of Object.keys(instance)) {
769
+ if (isDbSensitive(key)) continue;
770
+ const norm = key.toLowerCase().replace(/_/g, "");
771
+ if (!columns.has(norm)) columns.set(norm, instance[key]);
772
+ }
773
+ const text = (norm) => {
774
+ const value = columns.get(norm);
775
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "bigint") {
776
+ return null;
683
777
  }
778
+ const str = String(value).trim();
779
+ return str.length > 0 ? str.slice(0, MAX_DISPLAY_NAME_LENGTH) : null;
780
+ };
781
+ for (const column of DISPLAY_NAME_COLUMNS) {
782
+ const value = text(column);
783
+ if (value !== null) return value;
684
784
  }
785
+ return text(`${singularNorm(modelClass)}number`);
685
786
  } catch {
686
787
  }
687
788
  return null;
688
789
  }
790
+ function singularNorm(modelClass) {
791
+ const norm = modelClass.toLowerCase().replace(/_/g, "");
792
+ if (norm.endsWith("ies")) return norm.slice(0, -3) + "y";
793
+ if (/(ss|us|is)$/.test(norm)) return norm;
794
+ if (/(xes|ches|shes|sses)$/.test(norm)) return norm.slice(0, -2);
795
+ return norm.endsWith("s") ? norm.slice(0, -1) : norm;
796
+ }
689
797
  function applyResolver(resolver, instance) {
690
798
  if (typeof resolver === "string") {
691
799
  const value = instance[resolver];
@@ -507,6 +507,37 @@ function matchesSensitiveKey(key, substringPatterns) {
507
507
  const words = snake.split(/[^a-z0-9]+/);
508
508
  return SENSITIVE_WORD_PATTERNS.some((w) => words.includes(w));
509
509
  }
510
+ function passesLuhn(digits) {
511
+ let sum = 0;
512
+ for (let i = 0; i < digits.length; i += 1) {
513
+ let d = Number(digits[digits.length - 1 - i]);
514
+ if (i % 2 === 1) {
515
+ d *= 2;
516
+ if (d > 9) d -= 9;
517
+ }
518
+ sum += d;
519
+ }
520
+ return sum % 10 === 0;
521
+ }
522
+ var SECRET_TEXT_PATTERNS = [
523
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
524
+ /\beyJ[\w-]+\.[\w-]+\.[\w-]+/g,
525
+ /\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]+/g,
526
+ /\bsk-[A-Za-z0-9_-]{16,}/g,
527
+ /\bgh[pousr]_[A-Za-z0-9]{20,}/g,
528
+ /\bxox[abposr]-[A-Za-z0-9-]+/g,
529
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g
530
+ ];
531
+ var EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
532
+ function scrubSecretsInText(text, options = {}) {
533
+ let out = text;
534
+ for (const pattern of SECRET_TEXT_PATTERNS) out = out.replace(pattern, "[FILTERED]");
535
+ out = out.replace(/\b(Bearer|Basic)\s+[\w.~+/=-]+/gi, "$1 [FILTERED]").replace(/\b\d(?:[ -]?\d){12,18}\b/g, (match) => {
536
+ const digits = match.replace(/[ -]/g, "");
537
+ return (digits.length === 15 || digits.length === 16) && passesLuhn(digits) ? "[FILTERED]" : match;
538
+ });
539
+ return options.emails ? out.replace(EMAIL, "[FILTERED]") : out;
540
+ }
510
541
 
511
542
  // src/db/shared.ts
512
543
  var IGNORED_ATTRIBUTES = Object.freeze([
@@ -515,8 +546,6 @@ var IGNORED_ATTRIBUTES = Object.freeze([
515
546
  "created_at",
516
547
  "updatedAt",
517
548
  "updated_at",
518
- "deletedAt",
519
- "deleted_at",
520
549
  // Auth.js / NextAuth standard columns
521
550
  "emailVerified",
522
551
  "expires"
@@ -560,14 +589,17 @@ function emitDbEvent(input) {
560
589
  if (config.allExcludedTables().includes(input.modelClass)) return;
561
590
  if (config.databaseReader && !input._fromTrigger) {
562
591
  const tracked = config.triggerTrackedTables;
563
- if (tracked === null || tracked.has(input.modelClass)) return;
592
+ if (tracked === null || tracked.has(input.table ?? input.modelClass)) return;
564
593
  }
565
594
  if (input.operation === "update") {
566
595
  const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
567
596
  if (meaningful.length === 0) return;
568
597
  }
569
598
  const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
570
- const context = buildContext(input);
599
+ const related = resourceIdStr === null ? input.relatedResourceIds ?? [] : [];
600
+ const context = buildContext(
601
+ related.length > 0 ? { ...input, displayName: null, modelInstance: null } : input
602
+ );
571
603
  const event = build({
572
604
  source_type: "database_callback",
573
605
  source_data: {
@@ -576,7 +608,7 @@ function emitDbEvent(input) {
576
608
  },
577
609
  outcome: "success",
578
610
  correlation_id: current(),
579
- resource_ids: resourceIdStr === null ? [] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
611
+ resource_ids: resourceIdStr === null ? [...related] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
580
612
  context,
581
613
  duration_ms: null,
582
614
  timestamp: input.timestamp ?? null
@@ -623,7 +655,7 @@ function filterMeaningfulAttributes(attrs) {
623
655
  return Object.keys(out).length === 0 ? null : out;
624
656
  }
625
657
  function filterMeaningfulChanges(changes) {
626
- return changes.filter((c) => {
658
+ return flattenNestedChanges(changes).filter((c) => {
627
659
  if (!isMeaningfulAttribute(c.attribute)) return false;
628
660
  if (!isScalar(c.to)) return false;
629
661
  if (c.from === void 0) return true;
@@ -631,6 +663,60 @@ function filterMeaningfulChanges(changes) {
631
663
  return valuesActuallyChanged(c.from, c.to);
632
664
  });
633
665
  }
666
+ var MAX_NESTED_DEPTH = 3;
667
+ var MAX_NESTED_LEAVES = 20;
668
+ var MAX_UNKNOWN_FROM_LEAVES = 5;
669
+ function flattenNestedChanges(changes) {
670
+ if (!changes.some((c) => isPlainRecord(c.to) || isPlainRecord(c.from))) return changes;
671
+ const out = [];
672
+ for (const c of changes) {
673
+ if (!isPlainRecord(c.to) && !isPlainRecord(c.from)) {
674
+ out.push(c);
675
+ continue;
676
+ }
677
+ if (!isMeaningfulAttribute(c.attribute)) continue;
678
+ const leaves = [];
679
+ collectLeafChanges(c.attribute, c.from, c.to, 1, leaves);
680
+ const cap = c.from === void 0 ? MAX_UNKNOWN_FROM_LEAVES : MAX_NESTED_LEAVES;
681
+ out.push(...leaves.slice(0, cap).map(scrubLeaf));
682
+ }
683
+ return out;
684
+ }
685
+ function collectLeafChanges(path, from, to, depth, out) {
686
+ if (out.length > MAX_NESTED_LEAVES) return;
687
+ const fromObj = isPlainRecord(from);
688
+ const toObj = isPlainRecord(to);
689
+ if ((fromObj || toObj) && depth <= MAX_NESTED_DEPTH && (fromObj || from == null) && (toObj || to == null)) {
690
+ const f = fromObj ? from : {};
691
+ const t = toObj ? to : {};
692
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(f), ...Object.keys(t)])) {
693
+ const before = from === void 0 ? void 0 : f[key] ?? null;
694
+ collectLeafChanges(`${path}.${key}`, before, t[key] ?? null, depth + 1, out);
695
+ }
696
+ return;
697
+ }
698
+ if (from !== void 0 && sameJson(from, to)) return;
699
+ out.push(from === void 0 ? { attribute: path, to } : { attribute: path, from, to });
700
+ }
701
+ function scrubLeaf(change) {
702
+ const scrub = (v) => typeof v === "string" ? scrubSecretsInText(v) : v;
703
+ const out = { attribute: change.attribute, to: scrub(change.to) };
704
+ if (change.from !== void 0) out.from = scrub(change.from);
705
+ return out;
706
+ }
707
+ function isPlainRecord(value) {
708
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
709
+ const proto = Object.getPrototypeOf(value);
710
+ return proto === Object.prototype || proto === null;
711
+ }
712
+ function sameJson(a, b) {
713
+ if (a === b) return true;
714
+ try {
715
+ return JSON.stringify(a) === JSON.stringify(b);
716
+ } catch {
717
+ return false;
718
+ }
719
+ }
634
720
  function isMeaningfulAttribute(name) {
635
721
  if (IGNORED_ATTRIBUTES.includes(name)) return false;
636
722
  if (isDbSensitive(name)) return false;
@@ -668,22 +754,44 @@ function isPrismaDecimal(value) {
668
754
  const obj = value;
669
755
  return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
670
756
  }
757
+ var DISPLAY_NAME_COLUMNS = ["name", "title", "number", "label"];
758
+ var MAX_DISPLAY_NAME_LENGTH = 120;
671
759
  function resolveDisplayName(modelClass, instance) {
672
760
  try {
673
761
  const config = configuration();
674
762
  const resolver = config.displayNameFor[modelClass];
675
763
  const resolved = applyResolver(resolver, instance);
676
764
  if (resolved !== null) return resolved;
677
- for (const field of ["name", "title", "number"]) {
678
- const value = instance[field];
679
- if (value !== null && value !== void 0 && String(value).length > 0) {
680
- return String(value);
765
+ const columns = /* @__PURE__ */ new Map();
766
+ for (const key of Object.keys(instance)) {
767
+ if (isDbSensitive(key)) continue;
768
+ const norm = key.toLowerCase().replace(/_/g, "");
769
+ if (!columns.has(norm)) columns.set(norm, instance[key]);
770
+ }
771
+ const text = (norm) => {
772
+ const value = columns.get(norm);
773
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "bigint") {
774
+ return null;
681
775
  }
776
+ const str = String(value).trim();
777
+ return str.length > 0 ? str.slice(0, MAX_DISPLAY_NAME_LENGTH) : null;
778
+ };
779
+ for (const column of DISPLAY_NAME_COLUMNS) {
780
+ const value = text(column);
781
+ if (value !== null) return value;
682
782
  }
783
+ return text(`${singularNorm(modelClass)}number`);
683
784
  } catch {
684
785
  }
685
786
  return null;
686
787
  }
788
+ function singularNorm(modelClass) {
789
+ const norm = modelClass.toLowerCase().replace(/_/g, "");
790
+ if (norm.endsWith("ies")) return norm.slice(0, -3) + "y";
791
+ if (/(ss|us|is)$/.test(norm)) return norm;
792
+ if (/(xes|ches|shes|sses)$/.test(norm)) return norm.slice(0, -2);
793
+ return norm.endsWith("s") ? norm.slice(0, -1) : norm;
794
+ }
687
795
  function applyResolver(resolver, instance) {
688
796
  if (typeof resolver === "string") {
689
797
  const value = instance[resolver];