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