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
package/dist/db/prisma.js CHANGED
@@ -1,723 +1,6 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined") return require.apply(this, arguments);
5
- throw Error('Dynamic require of "' + x + '" is not supported');
6
- });
7
-
8
- // src/logger.ts
9
- var LEVEL_RANK = {
10
- debug: 10,
11
- info: 20,
12
- warn: 30,
13
- error: 40,
14
- silent: 100
15
- };
16
- var LEVEL_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:log-level");
17
- function readLevel() {
18
- const g = globalThis;
19
- return g[LEVEL_KEY] ?? "warn";
20
- }
21
- function shouldLog(level) {
22
- return LEVEL_RANK[level] >= LEVEL_RANK[readLevel()];
23
- }
24
- function safeWrite(level, message) {
25
- try {
26
- if (!shouldLog(level)) return;
27
- const line = `[ezlogs] ${message}`;
28
- if (level === "error" || level === "warn") {
29
- console.error(line);
30
- } else {
31
- console.log(line);
32
- }
33
- } catch {
34
- }
35
- }
36
- var logger = {
37
- debug: (message) => safeWrite("debug", message),
38
- info: (message) => safeWrite("info", message),
39
- warn: (message) => safeWrite("warn", message),
40
- error: (message) => safeWrite("error", message)
41
- };
42
-
43
- // src/edge-fallback.ts
44
- var ALS_CTOR = loadAsyncLocalStorage();
45
- function loadAsyncLocalStorage() {
46
- const fromGlobal = globalThis.AsyncLocalStorage;
47
- if (typeof fromGlobal === "function") return fromGlobal;
48
- try {
49
- const req = typeof __require !== "undefined" ? __require : (
50
- // In ESM, `createRequire` is the official escape hatch.
51
- // We pull it via globalThis to avoid a static `import`
52
- // that would itself be browser-bundled.
53
- void 0
54
- );
55
- if (typeof req === "function") {
56
- const moduleName = ["async", "hooks"].join("_");
57
- const mod = req("node:" + moduleName);
58
- if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
59
- }
60
- } catch {
61
- }
62
- return null;
63
- }
64
- function makeAsyncContextCapture() {
65
- if (!ALS_CTOR) return null;
66
- const ctor = ALS_CTOR;
67
- if (typeof ctor.snapshot !== "function") return null;
68
- const snapshot = ctor.snapshot.bind(ctor);
69
- return () => {
70
- const runSnapshot = snapshot();
71
- return (fn) => runSnapshot(fn);
72
- };
73
- }
74
- function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
75
- const globalStore = globalThis;
76
- let entry = globalStore[key];
77
- if (!entry) {
78
- const als2 = (() => {
79
- if (!ALS_CTOR) return null;
80
- try {
81
- return new ALS_CTOR();
82
- } catch {
83
- return null;
84
- }
85
- })();
86
- entry = { als: als2, edgeFallback: null };
87
- globalStore[key] = entry;
88
- }
89
- const als = entry.als;
90
- const stateRef = entry;
91
- return {
92
- read() {
93
- if (als) return als.getStore()?.value ?? null;
94
- return stateRef.edgeFallback?.value ?? null;
95
- },
96
- run(value, callback) {
97
- if (als) return als.run({ value }, callback);
98
- const previous = stateRef.edgeFallback;
99
- stateRef.edgeFallback = { value };
100
- try {
101
- return callback();
102
- } finally {
103
- stateRef.edgeFallback = previous;
104
- }
105
- },
106
- update(value) {
107
- if (als) {
108
- const store = als.getStore();
109
- if (store) store.value = value;
110
- return;
111
- }
112
- stateRef.edgeFallback = { value };
113
- },
114
- _resetForTests() {
115
- stateRef.edgeFallback = null;
116
- },
117
- _isAsyncLocalStorage() {
118
- return als !== null;
119
- }
120
- };
121
- }
122
-
123
- // src/correlation.ts
124
- var storage = createScopedStorage(
125
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
126
- );
127
- function current() {
128
- return storage.read();
129
- }
130
-
131
- // src/configuration.ts
132
- var DEFAULT_EXCLUDED_PATHS = Object.freeze([
133
- // Next.js / Vercel infrastructure noise
134
- "/_next/*",
135
- "/_vercel/*",
136
- "/__nextjs_*",
137
- // NextAuth.js / Auth.js — skip session-refresh polls and CSRF/provider
138
- // metadata GETs (high-frequency, no business meaning), but CAPTURE
139
- // POSTs (callbacks, signin, signout, register). The POSTs are the
140
- // actual auth events users care about; the GETs are pure plumbing.
141
- Object.freeze({ path: "/api/auth/*", methods: ["GET", "HEAD"] }),
142
- // Generic infrastructure
143
- "/health*",
144
- "/api/health",
145
- "/up",
146
- "/alive",
147
- "/ready",
148
- "/metrics",
149
- "/favicon.ico",
150
- "/.well-known*",
151
- "/robots.txt",
152
- "/sitemap.xml",
153
- "/*.hot-update.*",
154
- // Auth routes (common patterns across Clerk, NextAuth, custom auth)
155
- "*/login*",
156
- "*/logout*",
157
- "*/sign-in*",
158
- "*/sign-out*",
159
- "*/signin*",
160
- "*/signout*",
161
- "/session*"
162
- ]);
163
- var DEFAULT_EXCLUDED_TABLES = Object.freeze([
164
- // Prisma migration ledger
165
- "_prisma_migrations",
166
- // Auth.js / NextAuth Prisma adapter — session/verification-token churn
167
- // is auth machinery, not business activity. Account/User stay captured.
168
- "Session",
169
- "VerificationToken",
170
- // Common cross-stack convention names for the same things
171
- "sessions",
172
- "session",
173
- "verification_tokens"
174
- ]);
175
- var DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
176
- var DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
177
- var Configuration = class {
178
- serverUrl = null;
179
- projectToken = null;
180
- captureHttp = true;
181
- captureDb = true;
182
- captureJobs = true;
183
- bufferSize = 1e4;
184
- /** Default 3000 ms — equivalent to Ruby's 3 seconds. */
185
- sendInterval = 3e3;
186
- retryAttempts = 3;
187
- logLevel = "warn";
188
- patchGlobalFetch = true;
189
- actorFromSupabase = true;
190
- allowInsecureTransport = false;
191
- excludedPaths = [];
192
- excludedTables = [];
193
- excludedJobClasses = [];
194
- excludedGraphqlOperations = [];
195
- excludedGraphqlVariableKeys = [];
196
- actorFromRequest = null;
197
- displayNameFor = {};
198
- isServerActionError = null;
199
- databaseReader = null;
200
- databaseUrl = null;
201
- /**
202
- * Tables that have the `ezlogs_audit` trigger attached. Detected once
203
- * at agent startup by reading `information_schema.triggers`. The
204
- * supabase / drizzle / prisma adapters use this to decide whether
205
- * their per-mutation emit is redundant: if the table is trigger-
206
- * tracked the audit-log reader will surface the same write with full
207
- * old/new state, so the adapter's emit is suppressed. Tables NOT in
208
- * this set fall through to the adapter so they're still captured.
209
- *
210
- * `null` means "detection hasn't run yet or failed" — in that state
211
- * `databaseReader`-wired apps suppress every adapter emit (the
212
- * original Phase 5 behavior). After detection completes the agent
213
- * gives the more accurate per-table answer.
214
- */
215
- triggerTrackedTables = null;
216
- apply(options) {
217
- this.serverUrl = options.serverUrl;
218
- this.projectToken = options.projectToken;
219
- if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
220
- if (options.captureDb !== void 0) this.captureDb = options.captureDb;
221
- if (options.captureJobs !== void 0) this.captureJobs = options.captureJobs;
222
- if (options.bufferSize !== void 0) this.bufferSize = options.bufferSize;
223
- if (options.sendInterval !== void 0) this.sendInterval = options.sendInterval;
224
- if (options.retryAttempts !== void 0) this.retryAttempts = options.retryAttempts;
225
- if (options.excludedPaths) this.excludedPaths = [...options.excludedPaths];
226
- if (options.excludedTables) this.excludedTables = [...options.excludedTables];
227
- if (options.excludedJobClasses) {
228
- this.excludedJobClasses = [...options.excludedJobClasses];
229
- }
230
- if (options.excludedGraphqlOperations) {
231
- this.excludedGraphqlOperations = [...options.excludedGraphqlOperations];
232
- }
233
- if (options.excludedGraphqlVariableKeys) {
234
- this.excludedGraphqlVariableKeys = [...options.excludedGraphqlVariableKeys];
235
- }
236
- if (options.actorFromRequest) this.actorFromRequest = options.actorFromRequest;
237
- if (options.displayNameFor) this.displayNameFor = { ...options.displayNameFor };
238
- if (options.isServerActionError) this.isServerActionError = options.isServerActionError;
239
- if (options.patchGlobalFetch !== void 0) {
240
- this.patchGlobalFetch = options.patchGlobalFetch;
241
- }
242
- if (options.allowInsecureTransport !== void 0) {
243
- this.allowInsecureTransport = options.allowInsecureTransport;
244
- }
245
- if (options.actorFromSupabase !== void 0) {
246
- this.actorFromSupabase = options.actorFromSupabase;
247
- }
248
- if (options.databaseReader !== void 0) {
249
- this.databaseReader = options.databaseReader;
250
- }
251
- if (options.databaseUrl !== void 0) {
252
- this.databaseUrl = options.databaseUrl;
253
- }
254
- if (options.logLevel) this.logLevel = options.logLevel;
255
- }
256
- allExcludedPaths() {
257
- return [...DEFAULT_EXCLUDED_PATHS, ...this.excludedPaths];
258
- }
259
- allExcludedTables() {
260
- return [...DEFAULT_EXCLUDED_TABLES, ...this.excludedTables];
261
- }
262
- allExcludedJobClasses() {
263
- return [...DEFAULT_EXCLUDED_JOB_CLASSES, ...this.excludedJobClasses];
264
- }
265
- allExcludedGraphqlOperations() {
266
- return [...DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, ...this.excludedGraphqlOperations];
267
- }
268
- };
269
- var GLOBAL_CONFIG_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:configuration");
270
- function configuration() {
271
- const g = globalThis;
272
- if (!g[GLOBAL_CONFIG_KEY]) {
273
- g[GLOBAL_CONFIG_KEY] = new Configuration();
274
- }
275
- return g[GLOBAL_CONFIG_KEY];
276
- }
277
-
278
- // src/event-builder.ts
279
- var SENSITIVE_KEYS = Object.freeze([
280
- "password",
281
- "token",
282
- "secret",
283
- "api_key",
284
- "credit_card"
285
- ]);
286
- var VALID_SOURCE_TYPES = [
287
- "http_request",
288
- "background_job",
289
- "database_callback"
290
- ];
291
- var VALID_OUTCOMES = ["success", "failure"];
292
- function build(input) {
293
- const source_type = validateSourceType(input.source_type);
294
- const source_data_raw = validateSourceData(input.source_data);
295
- const outcome = validateOutcome(input.outcome);
296
- const timestamp = validateTimestamp(input.timestamp ?? null);
297
- const resource_ids = validateResourceIds(input.resource_ids ?? []);
298
- const context_raw = validateContext(input.context ?? null);
299
- const duration_ms = validateDurationMs();
300
- const error_message = input.error_message ?? null;
301
- validateOutcomeErrorConsistency(outcome, error_message);
302
- const source_data = sanitizeRecord(source_data_raw);
303
- const context = context_raw === null ? null : sanitizeRecord(context_raw);
304
- const correlation_id = input.correlation_id ?? null;
305
- const event = {
306
- timestamp,
307
- source_type,
308
- source_data,
309
- outcome,
310
- correlation_id,
311
- resource_ids,
312
- context,
313
- duration_ms,
314
- error_message
315
- };
316
- return event;
317
- }
318
- function validateSourceType(value) {
319
- const normalized = String(value);
320
- if (!VALID_SOURCE_TYPES.includes(normalized)) {
321
- throw new ArgError(
322
- `source_type must be one of ${VALID_SOURCE_TYPES.join(", ")}, got: ${normalized}`
323
- );
324
- }
325
- return normalized;
326
- }
327
- function validateSourceData(value) {
328
- if (value === null || value === void 0) {
329
- throw new ArgError("source_data is required");
330
- }
331
- if (!isPlainObject(value)) {
332
- throw new ArgError(
333
- `source_data must be an object, got: ${describe(value)}`
334
- );
335
- }
336
- return value;
337
- }
338
- function validateOutcome(value) {
339
- const normalized = String(value);
340
- if (!VALID_OUTCOMES.includes(normalized)) {
341
- throw new ArgError(
342
- `outcome must be one of ${VALID_OUTCOMES.join(", ")}, got: ${normalized}`
343
- );
344
- }
345
- return normalized;
346
- }
347
- function validateTimestamp(value) {
348
- if (value === null) {
349
- return (/* @__PURE__ */ new Date()).toISOString();
350
- }
351
- if (typeof value === "string") {
352
- const parsed = new Date(value);
353
- if (Number.isNaN(parsed.getTime())) {
354
- throw new ArgError(
355
- `timestamp must be valid ISO 8601 format, got: ${value}`
356
- );
357
- }
358
- return value;
359
- }
360
- if (value instanceof Date) {
361
- if (Number.isNaN(value.getTime())) {
362
- throw new ArgError("timestamp must be a valid Date");
363
- }
364
- return value.toISOString();
365
- }
366
- throw new ArgError(
367
- `timestamp must be a string or Date, got: ${describe(value)}`
368
- );
369
- }
370
- function validateResourceIds(value) {
371
- if (!Array.isArray(value)) {
372
- throw new ArgError(`resource_ids must be an array, got: ${describe(value)}`);
373
- }
374
- value.forEach((entry, index) => {
375
- if (!isPlainObject(entry)) {
376
- throw new ArgError(
377
- `resource_ids[${index}] must be an object, got: ${describe(entry)}`
378
- );
379
- }
380
- const e = entry;
381
- if (!("resource_type" in e) || !("resource_id" in e)) {
382
- throw new ArgError(
383
- `resource_ids[${index}] must have resource_type and resource_id keys, got: ${Object.keys(e).join(", ")}`
384
- );
385
- }
386
- if (typeof e.resource_type !== "string") {
387
- throw new ArgError(
388
- `resource_ids[${index}].resource_type must be a string, got: ${describe(e.resource_type)}`
389
- );
390
- }
391
- if (typeof e.resource_id !== "string") {
392
- throw new ArgError(
393
- `resource_ids[${index}].resource_id must be a string, got: ${describe(e.resource_id)}`
394
- );
395
- }
396
- });
397
- return value;
398
- }
399
- function validateContext(value) {
400
- if (value === null) return null;
401
- if (!isPlainObject(value)) {
402
- throw new ArgError(
403
- `context must be an object or null, got: ${describe(value)}`
404
- );
405
- }
406
- return value;
407
- }
408
- function validateDurationMs(value) {
409
- return null;
410
- }
411
- function validateOutcomeErrorConsistency(outcome, error_message) {
412
- if (outcome === "failure") {
413
- if (error_message === null || error_message === "") {
414
- throw new ArgError("error_message is required when outcome is 'failure'");
415
- }
416
- } else if (outcome === "success") {
417
- if (error_message !== null) {
418
- throw new ArgError("error_message must be null when outcome is 'success'");
419
- }
420
- }
421
- }
422
- function sanitizeRecord(input) {
423
- const result = {};
424
- for (const key of Object.keys(input)) {
425
- const value = input[key];
426
- if (isSensitiveKey(key)) {
427
- result[key] = "[FILTERED]";
428
- } else if (isPlainObject(value)) {
429
- result[key] = sanitizeRecord(value);
430
- } else if (Array.isArray(value)) {
431
- result[key] = value.map(
432
- (item) => isPlainObject(item) ? sanitizeRecord(item) : item
433
- );
434
- } else {
435
- result[key] = value;
436
- }
437
- }
438
- return result;
439
- }
440
- function isSensitiveKey(key) {
441
- const lower = key.toLowerCase();
442
- return SENSITIVE_KEYS.some((p) => lower.includes(p));
443
- }
444
- function isPlainObject(value) {
445
- if (value === null || typeof value !== "object") return false;
446
- const proto = Object.getPrototypeOf(value);
447
- return proto === Object.prototype || proto === null;
448
- }
449
- function describe(value) {
450
- if (value === null) return "null";
451
- if (Array.isArray(value)) return "Array";
452
- return typeof value;
453
- }
454
- var ArgError = class extends Error {
455
- constructor(message) {
456
- super(message);
457
- this.name = "ArgError";
458
- }
459
- };
460
-
461
- // src/pipeline/buffer.ts
462
- var GLOBAL_QUEUE_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:buffer-queue");
463
- function getQueue() {
464
- const g = globalThis;
465
- if (!g[GLOBAL_QUEUE_KEY]) g[GLOBAL_QUEUE_KEY] = [];
466
- return g[GLOBAL_QUEUE_KEY];
467
- }
468
- function pushEvent(event) {
469
- try {
470
- const queue = getQueue();
471
- const max = maxSize();
472
- if (queue.length >= max) {
473
- queue.shift();
474
- logger.warn(`Buffer full (${max}), dropped oldest event`);
475
- }
476
- queue.push(event);
477
- } catch (error) {
478
- logger.error(`pushEvent failed: ${describe2(error)}`);
479
- }
480
- }
481
- function maxSize() {
482
- try {
483
- return configuration().bufferSize;
484
- } catch {
485
- return 1e4;
486
- }
487
- }
488
- function describe2(error) {
489
- if (error instanceof Error) return `${error.name}: ${error.message}`;
490
- return String(error);
491
- }
492
-
493
- // src/actor.ts
494
- var storage2 = createScopedStorage(
495
- /* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-storage")
496
- );
497
- function getCurrentActor() {
498
- return storage2.read();
499
- }
500
- var SENSITIVE_WORD_PATTERNS = Object.freeze([
501
- "pin",
502
- "otp",
503
- "totp",
504
- "iban",
505
- "mfa",
506
- "passphrase"
507
- ]);
508
- function snakeLower(key) {
509
- return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
510
- }
511
- function matchesSensitiveKey(key, substringPatterns) {
512
- const lower = key.toLowerCase();
513
- const snake = snakeLower(key);
514
- if (substringPatterns.some((p) => lower.includes(p) || snake.includes(p))) {
515
- return true;
516
- }
517
- const words = snake.split(/[^a-z0-9]+/);
518
- return SENSITIVE_WORD_PATTERNS.some((w) => words.includes(w));
519
- }
520
-
521
- // src/db/shared.ts
522
- var IGNORED_ATTRIBUTES = Object.freeze([
523
- "id",
524
- "createdAt",
525
- "created_at",
526
- "updatedAt",
527
- "updated_at",
528
- "deletedAt",
529
- "deleted_at",
530
- // Auth.js / NextAuth standard columns
531
- "emailVerified",
532
- "expires"
533
- ]);
534
- var DB_SENSITIVE_PATTERNS = Object.freeze([
535
- "password",
536
- "token",
537
- "secret",
538
- "api_key",
539
- "credit_card",
540
- "ssn",
541
- "social_security",
542
- "encrypted",
543
- "private_key",
544
- "public_key",
545
- "signing_key",
546
- "pem",
547
- "cipher",
548
- "nonce",
549
- "salt",
550
- "digest",
551
- "signature",
552
- "hmac",
553
- // 0.2.0 additions. `credential` / `passwd` / `apikey` were already in
554
- // the HTTP list; `passcode` / `card_number` / `cardnumber` / `cvv` /
555
- // `cvc` are new. Whole-word `pin` / `otp` / `totp` / `iban` come from
556
- // SENSITIVE_WORD_PATTERNS. The SQL trigger mirrors this list.
557
- "credential",
558
- "passwd",
559
- "passcode",
560
- "apikey",
561
- "card_number",
562
- "cardnumber",
563
- "cvv",
564
- "cvc"
565
- ]);
566
- function emitDbEvent(input) {
567
- try {
568
- const config = configuration();
569
- if (!config.captureDb) return;
570
- if (config.allExcludedTables().includes(input.modelClass)) return;
571
- if (config.databaseReader && !input._fromTrigger) {
572
- const tracked = config.triggerTrackedTables;
573
- if (tracked === null || tracked.has(input.modelClass)) return;
574
- }
575
- if (input.operation === "update") {
576
- const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
577
- if (meaningful.length === 0) return;
578
- }
579
- const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
580
- const context = buildContext(input);
581
- const event = build({
582
- source_type: "database_callback",
583
- source_data: {
584
- model_class: input.modelClass,
585
- operation: input.operation
586
- },
587
- outcome: "success",
588
- correlation_id: current(),
589
- resource_ids: resourceIdStr === null ? [] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
590
- context,
591
- duration_ms: null,
592
- timestamp: input.timestamp ?? null
593
- });
594
- pushEvent(event);
595
- } catch (error) {
596
- logger.debug(`db emit failed: ${describeError(error)}`);
597
- }
598
- }
599
- function buildContext(input) {
600
- const context = {};
601
- const actor = getCurrentActor();
602
- if (actor) context.actor = actor;
603
- if ((input.operation === "create" || input.operation === "destroy") && input.initialAttributes) {
604
- const filtered = filterMeaningfulAttributes(input.initialAttributes);
605
- if (filtered !== null) context.initial_attributes = filtered;
606
- }
607
- if (input.operation === "update" && input.changes) {
608
- const filtered = filterMeaningfulChanges(input.changes);
609
- if (filtered.length > 0) {
610
- context.changes = filtered.map((c) => {
611
- const out = {
612
- attribute: c.attribute,
613
- to: formatForJson(c.to)
614
- };
615
- if (c.from !== void 0) out.from = formatForJson(c.from);
616
- return out;
617
- });
618
- }
619
- }
620
- const displayName = input.displayName ?? (input.modelInstance ? resolveDisplayName(input.modelClass, input.modelInstance) : null);
621
- if (displayName !== null) context.display_name = displayName;
622
- return Object.keys(context).length === 0 ? null : context;
623
- }
624
- function filterMeaningfulAttributes(attrs) {
625
- const out = {};
626
- for (const key of Object.keys(attrs)) {
627
- if (!isMeaningfulAttribute(key)) continue;
628
- const value = attrs[key];
629
- if (value === null || value === void 0) continue;
630
- if (!isScalar(value)) continue;
631
- out[key] = formatForJson(value);
632
- }
633
- return Object.keys(out).length === 0 ? null : out;
634
- }
635
- function filterMeaningfulChanges(changes) {
636
- return changes.filter((c) => {
637
- if (!isMeaningfulAttribute(c.attribute)) return false;
638
- if (!isScalar(c.to)) return false;
639
- if (c.from === void 0) return true;
640
- if (!isScalar(c.from)) return false;
641
- return valuesActuallyChanged(c.from, c.to);
642
- });
643
- }
644
- function isMeaningfulAttribute(name) {
645
- if (IGNORED_ATTRIBUTES.includes(name)) return false;
646
- if (isDbSensitive(name)) return false;
647
- return true;
648
- }
649
- function isDbSensitive(name) {
650
- return matchesSensitiveKey(name, DB_SENSITIVE_PATTERNS);
651
- }
652
- function isScalar(value) {
653
- if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
654
- return true;
655
- }
656
- if (isPrismaDecimal(value)) return true;
657
- if (Buffer.isBuffer?.(value)) return false;
658
- if (Array.isArray(value)) return value.every((v) => isScalar(v));
659
- return false;
660
- }
661
- function valuesActuallyChanged(from, to) {
662
- if (from === null && to === null) return false;
663
- if (from instanceof Date && to instanceof Date) {
664
- return from.getTime() !== to.getTime();
665
- }
666
- return from !== to;
667
- }
668
- function formatForJson(value) {
669
- if (value === null || value === void 0) return value;
670
- if (value instanceof Date) return value.toISOString();
671
- if (typeof value === "bigint") return value.toString();
672
- if (isPrismaDecimal(value)) return Number(value.toString());
673
- if (Array.isArray(value)) return value.map(formatForJson);
674
- return value;
675
- }
676
- function isPrismaDecimal(value) {
677
- if (value === null || typeof value !== "object") return false;
678
- const obj = value;
679
- return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
680
- }
681
- function resolveDisplayName(modelClass, instance) {
682
- try {
683
- const config = configuration();
684
- const resolver = config.displayNameFor[modelClass];
685
- const resolved = applyResolver(resolver, instance);
686
- if (resolved !== null) return resolved;
687
- for (const field of ["name", "title", "number"]) {
688
- const value = instance[field];
689
- if (value !== null && value !== void 0 && String(value).length > 0) {
690
- return String(value);
691
- }
692
- }
693
- } catch {
694
- }
695
- return null;
696
- }
697
- function applyResolver(resolver, instance) {
698
- if (typeof resolver === "string") {
699
- const value = instance[resolver];
700
- if (value !== null && value !== void 0 && String(value).length > 0) {
701
- return String(value);
702
- }
703
- return null;
704
- }
705
- if (typeof resolver === "function") {
706
- try {
707
- const value = resolver(instance);
708
- if (typeof value === "string" && value.length > 0) return value;
709
- if (value !== null && value !== void 0 && String(value).length > 0) {
710
- return String(value);
711
- }
712
- } catch {
713
- }
714
- }
715
- return null;
716
- }
717
- function describeError(error) {
718
- if (error instanceof Error) return `${error.name}: ${error.message}`;
719
- return String(error);
720
- }
1
+ import { current, configuration, emitDbEvent, resolveDisplayName, makeAsyncContextCapture } from '../chunk-CE3R7DVB.js';
2
+ import { logger } from '../chunk-C5OSM557.js';
3
+ import '../chunk-SIAA4J6H.js';
721
4
 
722
5
  // src/db/prisma.ts
723
6
  var CAPTURED_OPERATIONS = /* @__PURE__ */ new Set([
@@ -743,7 +26,7 @@ var OPERATION_TO_DB_OPERATION = {
743
26
  function ezlogsPrisma() {
744
27
  return (client) => client.$extends(buildPrismaExtension(client));
745
28
  }
746
- function buildPrismaExtension(client) {
29
+ function buildPrismaExtension(client, schemaClient = client) {
747
30
  return {
748
31
  name: "ezlogs",
749
32
  query: {
@@ -754,9 +37,9 @@ function buildPrismaExtension(client) {
754
37
  }
755
38
  const result = await runTagged(client, ctx);
756
39
  try {
757
- recordPrismaOperation(ctx, result);
40
+ recordPrismaOperation(ctx, result, tableNameFor(schemaClient, ctx.model));
758
41
  } catch (error) {
759
- logger.debug(`prisma capture failed: ${describeError2(error)}`);
42
+ logger.debug(`prisma capture failed: ${describeError(error)}`);
760
43
  }
761
44
  return result;
762
45
  }
@@ -784,7 +67,7 @@ async function runTagged(client, ctx) {
784
67
  if (!isTransactionUnsupported(error)) throw error;
785
68
  taggingDisabled.add(client);
786
69
  logger.warn(
787
- `this Prisma client can't run transactions, so DB writes won't be linked to their request (they still show up as their own actions): ${describeError2(error)}`
70
+ `this Prisma client can't run transactions, so DB writes won't be linked to their request (they still show up as their own actions): ${describeError(error)}`
788
71
  );
789
72
  return ctx.query(ctx.args);
790
73
  }
@@ -814,21 +97,30 @@ function isTransactionUnsupported(error) {
814
97
  const message = error instanceof Error ? error.message : String(error);
815
98
  return /transaction/i.test(message) && /not (?:be )?supported|unsupported|not available/i.test(message);
816
99
  }
817
- function recordPrismaOperation(ctx, result) {
100
+ function tableNameFor(schemaClient, model) {
101
+ try {
102
+ const dbName = schemaClient?._runtimeDataModel?.models?.[model]?.dbName;
103
+ return typeof dbName === "string" && dbName.length > 0 ? dbName : model;
104
+ } catch {
105
+ return model;
106
+ }
107
+ }
108
+ function recordPrismaOperation(ctx, result, table) {
818
109
  const dbOperation = OPERATION_TO_DB_OPERATION[ctx.operation];
819
110
  if (!dbOperation) return;
820
111
  if (isBatchResult(result)) {
821
112
  emitDbEvent({
822
113
  modelClass: ctx.model,
114
+ table,
823
115
  operation: dbOperation,
824
116
  resourceId: null,
825
117
  // For batch updates we still capture the `args.data` shape so
826
118
  // downstream sees what columns were touched even if we can't
827
119
  // identify a specific row.
828
- ...dbOperation === "update" && isPlainObject2(ctx.args.data) ? {
120
+ ...dbOperation === "update" && isPlainObject(ctx.args.data) ? {
829
121
  changes: extractChangesFromUpdateData(ctx.args.data)
830
122
  } : {},
831
- ...dbOperation === "create" && isPlainObject2(ctx.args.data) ? {
123
+ ...dbOperation === "create" && isPlainObject(ctx.args.data) ? {
832
124
  initialAttributes: ctx.args.data
833
125
  } : {}
834
126
  });
@@ -836,16 +128,17 @@ function recordPrismaOperation(ctx, result) {
836
128
  }
837
129
  if (Array.isArray(result)) {
838
130
  for (const row of result) {
839
- emitSingleRowEvent(ctx, dbOperation, row);
131
+ emitSingleRowEvent(ctx, dbOperation, row, table);
840
132
  }
841
133
  return;
842
134
  }
843
- emitSingleRowEvent(ctx, dbOperation, result);
135
+ emitSingleRowEvent(ctx, dbOperation, result, table);
844
136
  }
845
- function emitSingleRowEvent(ctx, dbOperation, row) {
846
- if (!isPlainObject2(row)) {
137
+ function emitSingleRowEvent(ctx, dbOperation, row, table) {
138
+ if (!isPlainObject(row)) {
847
139
  emitDbEvent({
848
140
  modelClass: ctx.model,
141
+ table,
849
142
  operation: dbOperation,
850
143
  resourceId: null
851
144
  });
@@ -857,9 +150,13 @@ function emitSingleRowEvent(ctx, dbOperation, row) {
857
150
  if (dbOperation === "create") {
858
151
  emitDbEvent({
859
152
  modelClass: ctx.model,
153
+ table,
860
154
  operation: "create",
861
155
  resourceId,
862
- initialAttributes: extractCreateAttributes(ctx, rowObj),
156
+ initialAttributes: {
157
+ ...isPlainObject(ctx.args.data) ? ctx.args.data : {},
158
+ ...rowObj
159
+ },
863
160
  displayName,
864
161
  modelInstance: rowObj
865
162
  });
@@ -868,6 +165,7 @@ function emitSingleRowEvent(ctx, dbOperation, row) {
868
165
  if (dbOperation === "update") {
869
166
  emitDbEvent({
870
167
  modelClass: ctx.model,
168
+ table,
871
169
  operation: "update",
872
170
  resourceId,
873
171
  changes: extractUpdateChangesFromArgs(ctx, rowObj),
@@ -878,47 +176,38 @@ function emitSingleRowEvent(ctx, dbOperation, row) {
878
176
  }
879
177
  emitDbEvent({
880
178
  modelClass: ctx.model,
179
+ table,
881
180
  operation: "destroy",
882
181
  resourceId,
182
+ initialAttributes: rowObj,
883
183
  displayName,
884
184
  modelInstance: rowObj
885
185
  });
886
186
  }
887
- function extractCreateAttributes(ctx, resultRow) {
888
- if (isPlainObject2(ctx.args.data)) {
889
- return ctx.args.data;
890
- }
891
- if (ctx.operation === "upsert" && isPlainObject2(ctx.args.create)) {
892
- return ctx.args.create;
893
- }
894
- return resultRow;
895
- }
896
187
  function extractUpdateChangesFromArgs(ctx, resultRow) {
897
- const data = isPlainObject2(ctx.args.data) ? ctx.args.data : ctx.operation === "upsert" && isPlainObject2(ctx.args.update) ? ctx.args.update : null;
188
+ const data = isPlainObject(ctx.args.data) ? ctx.args.data : ctx.operation === "upsert" && isPlainObject(ctx.args.update) ? ctx.args.update : null;
898
189
  if (!data) return [];
899
190
  return Object.keys(data).map((attribute) => ({
900
191
  attribute,
901
- from: null,
902
192
  to: resultRow[attribute] ?? data[attribute]
903
193
  }));
904
194
  }
905
195
  function extractChangesFromUpdateData(data) {
906
196
  return Object.keys(data).map((attribute) => ({
907
197
  attribute,
908
- from: null,
909
198
  to: data[attribute]
910
199
  }));
911
200
  }
912
201
  function isBatchResult(value) {
913
- return isPlainObject2(value) && typeof value.count === "number" && Object.keys(value).length === 1;
202
+ return isPlainObject(value) && typeof value.count === "number" && Object.keys(value).length === 1;
914
203
  }
915
- function isPlainObject2(value) {
204
+ function isPlainObject(value) {
916
205
  if (value === null || typeof value !== "object") return false;
917
206
  if (Array.isArray(value)) return false;
918
207
  if (value instanceof Date) return false;
919
208
  return true;
920
209
  }
921
- function describeError2(error) {
210
+ function describeError(error) {
922
211
  if (error instanceof Error) return `${error.name}: ${error.message}`;
923
212
  return String(error);
924
213
  }
@@ -1002,9 +291,9 @@ function applyEzlogsExtension(prisma) {
1002
291
  return prisma;
1003
292
  }
1004
293
  try {
1005
- return client.$extends(buildPrismaExtension(null));
294
+ return client.$extends(buildPrismaExtension(null, prisma));
1006
295
  } catch (error) {
1007
- logger.debug(`patchPrismaClient: $extends failed: ${describeError2(error)}`);
296
+ logger.debug(`patchPrismaClient: $extends failed: ${describeError(error)}`);
1008
297
  return prisma;
1009
298
  }
1010
299
  }