ezlogs-nextjs 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +98 -688
  3. package/bin/install-triggers.cjs +1 -1
  4. package/dist/actors/index.d.cts +1 -1
  5. package/dist/actors/index.d.ts +1 -1
  6. package/dist/{configuration-D9x9Gvds.d.cts → configuration-aUYgA8-h.d.cts} +20 -3
  7. package/dist/{configuration-D9x9Gvds.d.ts → configuration-aUYgA8-h.d.ts} +20 -3
  8. package/dist/db/drizzle.cjs +17 -6
  9. package/dist/db/drizzle.js +17 -6
  10. package/dist/db/prisma.cjs +271 -76
  11. package/dist/db/prisma.d.cts +38 -1
  12. package/dist/db/prisma.d.ts +38 -1
  13. package/dist/db/prisma.js +270 -77
  14. package/dist/db/supabase.cjs +17 -6
  15. package/dist/db/supabase.js +17 -6
  16. package/dist/index.cjs +459 -222
  17. package/dist/index.d.cts +2 -2
  18. package/dist/index.d.ts +2 -2
  19. package/dist/index.js +459 -222
  20. package/dist/jobs/bullmq.cjs +6 -5
  21. package/dist/jobs/bullmq.d.cts +16 -8
  22. package/dist/jobs/bullmq.d.ts +16 -8
  23. package/dist/jobs/bullmq.js +6 -5
  24. package/dist/jobs/inngest.cjs +16 -6
  25. package/dist/jobs/inngest.js +16 -6
  26. package/dist/jobs/supabase-queues.cjs +16 -6
  27. package/dist/jobs/supabase-queues.js +16 -6
  28. package/dist/jobs/trigger.cjs +16 -6
  29. package/dist/jobs/trigger.js +16 -6
  30. package/dist/jobs/upstash-workflow.cjs +16 -6
  31. package/dist/jobs/upstash-workflow.js +16 -6
  32. package/dist/nextjs-plugin/index.cjs +18 -0
  33. package/dist/nextjs-plugin/index.js +18 -0
  34. package/dist/nextjs-plugin/loader.cjs +44 -34
  35. package/dist/nextjs-plugin/loader.d.cts +10 -0
  36. package/dist/nextjs-plugin/loader.d.ts +10 -0
  37. package/dist/nextjs-plugin/loader.js +44 -34
  38. package/dist/triggers/index.cjs +43 -8
  39. package/dist/triggers/index.d.cts +7 -0
  40. package/dist/triggers/index.d.ts +7 -0
  41. package/dist/triggers/index.js +43 -8
  42. package/package.json +3 -4
  43. package/sql/postgres/00_install.sql +1 -1
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // CLI shim for `npx ezlogs-nextjs install-triggers`.
2
+ // CLI shim for `npx @ezlogs/nextjs install-triggers`.
3
3
  //
4
4
  // Lazy-imports the dist CJS bundle + `pg` so we don't load either when
5
5
  // the customer is just installing the package. `pg` is a devDependency
@@ -1,4 +1,4 @@
1
- import { a as ActorFromRequest } from '../configuration-D9x9Gvds.cjs';
1
+ import { a as ActorFromRequest } from '../configuration-aUYgA8-h.cjs';
2
2
 
3
3
  /**
4
4
  * Returns an `ActorFromRequest` that pulls the current user from
@@ -1,4 +1,4 @@
1
- import { a as ActorFromRequest } from '../configuration-D9x9Gvds.js';
1
+ import { a as ActorFromRequest } from '../configuration-aUYgA8-h.js';
2
2
 
3
3
  /**
4
4
  * Returns an `ActorFromRequest` that pulls the current user from
@@ -17,11 +17,19 @@ type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
17
17
  * not configurable.
18
18
  */
19
19
 
20
+ /** Categories of who/what performed an action. Mirrors the Ruby
21
+ * `Event#actor_kind` enum. Defaults to "human" on the server when
22
+ * absent. */
23
+ type ActorKind = "human" | "agent" | "system" | "hybrid";
20
24
  interface ActorContext {
21
25
  /** Stable identifier for the user (e.g. `user.id`). REQUIRED. */
22
26
  id: string;
23
27
  /** Human-readable label (e.g. `user.email`). Optional. */
24
28
  label?: string;
29
+ /** Category of actor. Optional — the server stamps `human` when
30
+ * absent. Auto-detection from the User-Agent fills this when the
31
+ * request looks like it came from an LLM client. */
32
+ kind?: ActorKind;
25
33
  }
26
34
  /**
27
35
  * Minimal request-shape contract for `actorFromRequest`. We don't import
@@ -53,7 +61,7 @@ type DisplayNameMap = Record<string, DisplayNameResolver>;
53
61
  /**
54
62
  * Classifier for Server Action failure return values.
55
63
  *
56
- * Many Next.js codebases (next-safe-action templates, the
64
+ * Many Next.js codebases (Velory, next-safe-action templates, the
57
65
  * Vercel App Router examples, tRPC) catch errors inside the action and
58
66
  * return `{ success: false, error: "..." }` instead of throwing. The
59
67
  * HTTP response is 200, so the agent can't tell the action failed
@@ -72,8 +80,7 @@ type ServerActionErrorClassifier = (result: unknown) => boolean | {
72
80
  errorMessage: string;
73
81
  } | null | undefined;
74
82
  interface InitOptions {
75
- /** Defaults to `https://app.ezlogs.io` (the hosted EZLogs service). Override for self-hosting. */
76
- serverUrl?: string;
83
+ serverUrl: string;
77
84
  projectToken: string;
78
85
  captureHttp?: boolean;
79
86
  captureDb?: boolean;
@@ -98,6 +105,16 @@ interface InitOptions {
98
105
  isServerActionError?: ServerActionErrorClassifier;
99
106
  /** Patch globalThis.fetch to inject X-Correlation-ID. Default true. */
100
107
  patchGlobalFetch?: boolean;
108
+ /**
109
+ * Suppress the "serverUrl is not HTTPS" warning when intentionally
110
+ * pointing the agent at a non-HTTPS endpoint (a local relay, a
111
+ * staging proxy on a private network, …). HTTPS is otherwise
112
+ * enforced by warning at init time so a typo in production
113
+ * (`http://app.ezlogs.io`) doesn't silently ship events in
114
+ * cleartext. localhost / 127.0.0.1 / [::1] / *.local are exempt
115
+ * by default — those are dev environments. Default false.
116
+ */
117
+ allowInsecureTransport?: boolean;
101
118
  /**
102
119
  * When true (default), the HTTP capturer extracts the current actor
103
120
  * from the most-recently-constructed Supabase client by calling
@@ -17,11 +17,19 @@ type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
17
17
  * not configurable.
18
18
  */
19
19
 
20
+ /** Categories of who/what performed an action. Mirrors the Ruby
21
+ * `Event#actor_kind` enum. Defaults to "human" on the server when
22
+ * absent. */
23
+ type ActorKind = "human" | "agent" | "system" | "hybrid";
20
24
  interface ActorContext {
21
25
  /** Stable identifier for the user (e.g. `user.id`). REQUIRED. */
22
26
  id: string;
23
27
  /** Human-readable label (e.g. `user.email`). Optional. */
24
28
  label?: string;
29
+ /** Category of actor. Optional — the server stamps `human` when
30
+ * absent. Auto-detection from the User-Agent fills this when the
31
+ * request looks like it came from an LLM client. */
32
+ kind?: ActorKind;
25
33
  }
26
34
  /**
27
35
  * Minimal request-shape contract for `actorFromRequest`. We don't import
@@ -53,7 +61,7 @@ type DisplayNameMap = Record<string, DisplayNameResolver>;
53
61
  /**
54
62
  * Classifier for Server Action failure return values.
55
63
  *
56
- * Many Next.js codebases (next-safe-action templates, the
64
+ * Many Next.js codebases (Velory, next-safe-action templates, the
57
65
  * Vercel App Router examples, tRPC) catch errors inside the action and
58
66
  * return `{ success: false, error: "..." }` instead of throwing. The
59
67
  * HTTP response is 200, so the agent can't tell the action failed
@@ -72,8 +80,7 @@ type ServerActionErrorClassifier = (result: unknown) => boolean | {
72
80
  errorMessage: string;
73
81
  } | null | undefined;
74
82
  interface InitOptions {
75
- /** Defaults to `https://app.ezlogs.io` (the hosted EZLogs service). Override for self-hosting. */
76
- serverUrl?: string;
83
+ serverUrl: string;
77
84
  projectToken: string;
78
85
  captureHttp?: boolean;
79
86
  captureDb?: boolean;
@@ -98,6 +105,16 @@ interface InitOptions {
98
105
  isServerActionError?: ServerActionErrorClassifier;
99
106
  /** Patch globalThis.fetch to inject X-Correlation-ID. Default true. */
100
107
  patchGlobalFetch?: boolean;
108
+ /**
109
+ * Suppress the "serverUrl is not HTTPS" warning when intentionally
110
+ * pointing the agent at a non-HTTPS endpoint (a local relay, a
111
+ * staging proxy on a private network, …). HTTPS is otherwise
112
+ * enforced by warning at init time so a typo in production
113
+ * (`http://app.ezlogs.io`) doesn't silently ship events in
114
+ * cleartext. localhost / 127.0.0.1 / [::1] / *.local are exempt
115
+ * by default — those are dev environments. Default false.
116
+ */
117
+ allowInsecureTransport?: boolean;
101
118
  /**
102
119
  * When true (default), the HTTP capturer extracts the current actor
103
120
  * from the most-recently-constructed Supabase client by calling
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- require('crypto');
4
-
5
3
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
6
4
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
7
5
  }) : x)(function(x) {
@@ -90,9 +88,8 @@ var DEFAULT_EXCLUDED_TABLES = Object.freeze([
90
88
  ]);
91
89
  var DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
92
90
  var DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
93
- var DEFAULT_SERVER_URL = "https://app.ezlogs.io";
94
91
  var Configuration = class {
95
- serverUrl = DEFAULT_SERVER_URL;
92
+ serverUrl = null;
96
93
  projectToken = null;
97
94
  captureHttp = true;
98
95
  captureDb = true;
@@ -104,6 +101,7 @@ var Configuration = class {
104
101
  logLevel = "warn";
105
102
  patchGlobalFetch = true;
106
103
  actorFromSupabase = true;
104
+ allowInsecureTransport = false;
107
105
  excludedPaths = [];
108
106
  excludedTables = [];
109
107
  excludedJobClasses = [];
@@ -131,7 +129,7 @@ var Configuration = class {
131
129
  */
132
130
  triggerTrackedTables = null;
133
131
  apply(options) {
134
- if (options.serverUrl !== void 0) this.serverUrl = options.serverUrl;
132
+ this.serverUrl = options.serverUrl;
135
133
  this.projectToken = options.projectToken;
136
134
  if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
137
135
  if (options.captureDb !== void 0) this.captureDb = options.captureDb;
@@ -156,6 +154,9 @@ var Configuration = class {
156
154
  if (options.patchGlobalFetch !== void 0) {
157
155
  this.patchGlobalFetch = options.patchGlobalFetch;
158
156
  }
157
+ if (options.allowInsecureTransport !== void 0) {
158
+ this.allowInsecureTransport = options.allowInsecureTransport;
159
+ }
159
160
  if (options.actorFromSupabase !== void 0) {
160
161
  this.actorFromSupabase = options.actorFromSupabase;
161
162
  }
@@ -514,7 +515,17 @@ var DB_SENSITIVE_PATTERNS = Object.freeze([
514
515
  "credit_card",
515
516
  "ssn",
516
517
  "social_security",
517
- "encrypted"
518
+ "encrypted",
519
+ "private_key",
520
+ "public_key",
521
+ "signing_key",
522
+ "pem",
523
+ "cipher",
524
+ "nonce",
525
+ "salt",
526
+ "digest",
527
+ "signature",
528
+ "hmac"
518
529
  ]);
519
530
  function emitDbEvent(input) {
520
531
  try {
@@ -1,5 +1,3 @@
1
- import 'crypto';
2
-
3
1
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
2
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
3
  }) : x)(function(x) {
@@ -88,9 +86,8 @@ var DEFAULT_EXCLUDED_TABLES = Object.freeze([
88
86
  ]);
89
87
  var DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
90
88
  var DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
91
- var DEFAULT_SERVER_URL = "https://app.ezlogs.io";
92
89
  var Configuration = class {
93
- serverUrl = DEFAULT_SERVER_URL;
90
+ serverUrl = null;
94
91
  projectToken = null;
95
92
  captureHttp = true;
96
93
  captureDb = true;
@@ -102,6 +99,7 @@ var Configuration = class {
102
99
  logLevel = "warn";
103
100
  patchGlobalFetch = true;
104
101
  actorFromSupabase = true;
102
+ allowInsecureTransport = false;
105
103
  excludedPaths = [];
106
104
  excludedTables = [];
107
105
  excludedJobClasses = [];
@@ -129,7 +127,7 @@ var Configuration = class {
129
127
  */
130
128
  triggerTrackedTables = null;
131
129
  apply(options) {
132
- if (options.serverUrl !== void 0) this.serverUrl = options.serverUrl;
130
+ this.serverUrl = options.serverUrl;
133
131
  this.projectToken = options.projectToken;
134
132
  if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
135
133
  if (options.captureDb !== void 0) this.captureDb = options.captureDb;
@@ -154,6 +152,9 @@ var Configuration = class {
154
152
  if (options.patchGlobalFetch !== void 0) {
155
153
  this.patchGlobalFetch = options.patchGlobalFetch;
156
154
  }
155
+ if (options.allowInsecureTransport !== void 0) {
156
+ this.allowInsecureTransport = options.allowInsecureTransport;
157
+ }
157
158
  if (options.actorFromSupabase !== void 0) {
158
159
  this.actorFromSupabase = options.actorFromSupabase;
159
160
  }
@@ -512,7 +513,17 @@ var DB_SENSITIVE_PATTERNS = Object.freeze([
512
513
  "credit_card",
513
514
  "ssn",
514
515
  "social_security",
515
- "encrypted"
516
+ "encrypted",
517
+ "private_key",
518
+ "public_key",
519
+ "signing_key",
520
+ "pem",
521
+ "cipher",
522
+ "nonce",
523
+ "salt",
524
+ "digest",
525
+ "signature",
526
+ "hmac"
516
527
  ]);
517
528
  function emitDbEvent(input) {
518
529
  try {
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- require('crypto');
4
-
5
3
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
6
4
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
7
5
  }) : x)(function(x) {
@@ -44,6 +42,86 @@ var logger = {
44
42
  error: (message) => safeWrite("error", message)
45
43
  };
46
44
 
45
+ // src/edge-fallback.ts
46
+ var ALS_CTOR = loadAsyncLocalStorage();
47
+ function loadAsyncLocalStorage() {
48
+ const fromGlobal = globalThis.AsyncLocalStorage;
49
+ if (typeof fromGlobal === "function") return fromGlobal;
50
+ try {
51
+ const req = typeof __require !== "undefined" ? __require : (
52
+ // In ESM, `createRequire` is the official escape hatch.
53
+ // We pull it via globalThis to avoid a static `import`
54
+ // that would itself be browser-bundled.
55
+ void 0
56
+ );
57
+ if (typeof req === "function") {
58
+ const moduleName = ["async", "hooks"].join("_");
59
+ const mod = req("node:" + moduleName);
60
+ if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
61
+ }
62
+ } catch {
63
+ }
64
+ return null;
65
+ }
66
+ function makeAsyncContextCapture() {
67
+ if (!ALS_CTOR) return null;
68
+ const ctor = ALS_CTOR;
69
+ if (typeof ctor.snapshot !== "function") return null;
70
+ const snapshot = ctor.snapshot.bind(ctor);
71
+ return () => {
72
+ const runSnapshot = snapshot();
73
+ return (fn) => runSnapshot(fn);
74
+ };
75
+ }
76
+ function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
77
+ const globalStore = globalThis;
78
+ let entry = globalStore[key];
79
+ if (!entry) {
80
+ const als2 = (() => {
81
+ if (!ALS_CTOR) return null;
82
+ try {
83
+ return new ALS_CTOR();
84
+ } catch {
85
+ return null;
86
+ }
87
+ })();
88
+ entry = { als: als2, edgeFallback: null };
89
+ globalStore[key] = entry;
90
+ }
91
+ const als = entry.als;
92
+ const stateRef = entry;
93
+ return {
94
+ read() {
95
+ if (als) return als.getStore()?.value ?? null;
96
+ return stateRef.edgeFallback?.value ?? null;
97
+ },
98
+ run(value, callback) {
99
+ if (als) return als.run({ value }, callback);
100
+ const previous = stateRef.edgeFallback;
101
+ stateRef.edgeFallback = { value };
102
+ try {
103
+ return callback();
104
+ } finally {
105
+ stateRef.edgeFallback = previous;
106
+ }
107
+ },
108
+ update(value) {
109
+ if (als) {
110
+ const store = als.getStore();
111
+ if (store) store.value = value;
112
+ return;
113
+ }
114
+ stateRef.edgeFallback = { value };
115
+ },
116
+ _resetForTests() {
117
+ stateRef.edgeFallback = null;
118
+ },
119
+ _isAsyncLocalStorage() {
120
+ return als !== null;
121
+ }
122
+ };
123
+ }
124
+
47
125
  // src/configuration.ts
48
126
  var DEFAULT_EXCLUDED_PATHS = Object.freeze([
49
127
  // Next.js / Vercel infrastructure noise
@@ -90,9 +168,8 @@ var DEFAULT_EXCLUDED_TABLES = Object.freeze([
90
168
  ]);
91
169
  var DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
92
170
  var DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
93
- var DEFAULT_SERVER_URL = "https://app.ezlogs.io";
94
171
  var Configuration = class {
95
- serverUrl = DEFAULT_SERVER_URL;
172
+ serverUrl = null;
96
173
  projectToken = null;
97
174
  captureHttp = true;
98
175
  captureDb = true;
@@ -104,6 +181,7 @@ var Configuration = class {
104
181
  logLevel = "warn";
105
182
  patchGlobalFetch = true;
106
183
  actorFromSupabase = true;
184
+ allowInsecureTransport = false;
107
185
  excludedPaths = [];
108
186
  excludedTables = [];
109
187
  excludedJobClasses = [];
@@ -131,7 +209,7 @@ var Configuration = class {
131
209
  */
132
210
  triggerTrackedTables = null;
133
211
  apply(options) {
134
- if (options.serverUrl !== void 0) this.serverUrl = options.serverUrl;
212
+ this.serverUrl = options.serverUrl;
135
213
  this.projectToken = options.projectToken;
136
214
  if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
137
215
  if (options.captureDb !== void 0) this.captureDb = options.captureDb;
@@ -156,6 +234,9 @@ var Configuration = class {
156
234
  if (options.patchGlobalFetch !== void 0) {
157
235
  this.patchGlobalFetch = options.patchGlobalFetch;
158
236
  }
237
+ if (options.allowInsecureTransport !== void 0) {
238
+ this.allowInsecureTransport = options.allowInsecureTransport;
239
+ }
159
240
  if (options.actorFromSupabase !== void 0) {
160
241
  this.actorFromSupabase = options.actorFromSupabase;
161
242
  }
@@ -407,76 +488,6 @@ function describe2(error) {
407
488
  return String(error);
408
489
  }
409
490
 
410
- // src/edge-fallback.ts
411
- var ALS_CTOR = loadAsyncLocalStorage();
412
- function loadAsyncLocalStorage() {
413
- const fromGlobal = globalThis.AsyncLocalStorage;
414
- if (typeof fromGlobal === "function") return fromGlobal;
415
- try {
416
- const req = typeof __require !== "undefined" ? __require : (
417
- // In ESM, `createRequire` is the official escape hatch.
418
- // We pull it via globalThis to avoid a static `import`
419
- // that would itself be browser-bundled.
420
- void 0
421
- );
422
- if (typeof req === "function") {
423
- const moduleName = ["async", "hooks"].join("_");
424
- const mod = req("node:" + moduleName);
425
- if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
426
- }
427
- } catch {
428
- }
429
- return null;
430
- }
431
- function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
432
- const globalStore = globalThis;
433
- let entry = globalStore[key];
434
- if (!entry) {
435
- const als2 = (() => {
436
- if (!ALS_CTOR) return null;
437
- try {
438
- return new ALS_CTOR();
439
- } catch {
440
- return null;
441
- }
442
- })();
443
- entry = { als: als2, edgeFallback: null };
444
- globalStore[key] = entry;
445
- }
446
- const als = entry.als;
447
- const stateRef = entry;
448
- return {
449
- read() {
450
- if (als) return als.getStore()?.value ?? null;
451
- return stateRef.edgeFallback?.value ?? null;
452
- },
453
- run(value, callback) {
454
- if (als) return als.run({ value }, callback);
455
- const previous = stateRef.edgeFallback;
456
- stateRef.edgeFallback = { value };
457
- try {
458
- return callback();
459
- } finally {
460
- stateRef.edgeFallback = previous;
461
- }
462
- },
463
- update(value) {
464
- if (als) {
465
- const store = als.getStore();
466
- if (store) store.value = value;
467
- return;
468
- }
469
- stateRef.edgeFallback = { value };
470
- },
471
- _resetForTests() {
472
- stateRef.edgeFallback = null;
473
- },
474
- _isAsyncLocalStorage() {
475
- return als !== null;
476
- }
477
- };
478
- }
479
-
480
491
  // src/correlation.ts
481
492
  var storage = createScopedStorage(
482
493
  /* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
@@ -514,7 +525,17 @@ var DB_SENSITIVE_PATTERNS = Object.freeze([
514
525
  "credit_card",
515
526
  "ssn",
516
527
  "social_security",
517
- "encrypted"
528
+ "encrypted",
529
+ "private_key",
530
+ "public_key",
531
+ "signing_key",
532
+ "pem",
533
+ "cipher",
534
+ "nonce",
535
+ "salt",
536
+ "digest",
537
+ "signature",
538
+ "hmac"
518
539
  ]);
519
540
  function emitDbEvent(input) {
520
541
  try {
@@ -822,5 +843,179 @@ function describeError2(error) {
822
843
  if (error instanceof Error) return `${error.name}: ${error.message}`;
823
844
  return String(error);
824
845
  }
846
+ var EZLOGS_PRISMA_BRAND = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:prismaPatched");
847
+ var EZLOGS_ADAPTER_BRAND = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:prismaPgAdapterPatched");
848
+ var ADAPTER_SNAPSHOT_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:prismaPgSnapshot");
849
+ var ADAPTER_MUTEX_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:prismaPgMutex");
850
+ var RAW_METHODS = /* @__PURE__ */ new Set([
851
+ "$transaction",
852
+ "$queryRaw",
853
+ "$queryRawUnsafe",
854
+ "$executeRaw",
855
+ "$executeRawUnsafe",
856
+ "$runCommandRaw"
857
+ ]);
858
+ var MODEL_METHODS = /* @__PURE__ */ new Set([
859
+ "create",
860
+ "createMany",
861
+ "createManyAndReturn",
862
+ "findUnique",
863
+ "findUniqueOrThrow",
864
+ "findFirst",
865
+ "findFirstOrThrow",
866
+ "findMany",
867
+ "update",
868
+ "updateMany",
869
+ "upsert",
870
+ "delete",
871
+ "deleteMany",
872
+ "count",
873
+ "aggregate",
874
+ "groupBy"
875
+ ]);
876
+ function patchPrismaPgAdapter(adapter) {
877
+ if (!adapter || typeof adapter !== "object") return adapter;
878
+ const adapterRec = adapter;
879
+ if (adapterRec[EZLOGS_ADAPTER_BRAND] === true) return adapter;
880
+ for (const method of ["queryRaw", "executeRaw", "transactionContext"]) {
881
+ const original = adapterRec[method];
882
+ if (typeof original !== "function") continue;
883
+ adapterRec[method] = function ezlogsPatchedAdapterMethod(...args) {
884
+ const snapshot = adapterRec[ADAPTER_SNAPSHOT_KEY];
885
+ const invoke = () => original.apply(this, args);
886
+ if (snapshot) return snapshot(invoke);
887
+ return invoke();
888
+ };
889
+ }
890
+ adapterRec[EZLOGS_ADAPTER_BRAND] = true;
891
+ return adapter;
892
+ }
893
+ function patchPrismaClient(prisma, adapter) {
894
+ if (!prisma || typeof prisma !== "object") {
895
+ return prisma;
896
+ }
897
+ if (prisma[EZLOGS_PRISMA_BRAND] === true) {
898
+ return prisma;
899
+ }
900
+ const captureAndRun = makeAsyncContextCapture();
901
+ if (!captureAndRun) {
902
+ logger.debug(
903
+ "patchPrismaClient: AsyncLocalStorage.snapshot() unavailable; skipping ALS bind, applying ezlogsPrisma() only."
904
+ );
905
+ return applyEzlogsExtension(prisma);
906
+ }
907
+ const patchedAdapter = adapter && typeof adapter === "object" && adapter[EZLOGS_ADAPTER_BRAND] === true ? adapter : null;
908
+ if (adapter && !patchedAdapter) {
909
+ logger.debug(
910
+ "patchPrismaClient: adapter is not the output of patchPrismaPgAdapter(). Correlation_id will be NULL on concurrent requests. Wrap the adapter first."
911
+ );
912
+ }
913
+ const extended = applyEzlogsExtension(prisma);
914
+ const wrapped = buildClientProxy(extended, captureAndRun, patchedAdapter);
915
+ return wrapped;
916
+ }
917
+ function applyEzlogsExtension(prisma) {
918
+ const client = prisma;
919
+ if (typeof client.$extends !== "function") {
920
+ logger.debug(
921
+ "patchPrismaClient: client has no $extends; skipping ezlogsPrisma extension."
922
+ );
923
+ return prisma;
924
+ }
925
+ try {
926
+ return client.$extends(ezlogsPrisma());
927
+ } catch (error) {
928
+ logger.debug(`patchPrismaClient: $extends failed: ${describeError2(error)}`);
929
+ return prisma;
930
+ }
931
+ }
932
+ function buildClientProxy(client, captureAndRun, adapter) {
933
+ const modelProxyCache = /* @__PURE__ */ new WeakMap();
934
+ return new Proxy(client, {
935
+ get(target, prop, receiver) {
936
+ if (prop === EZLOGS_PRISMA_BRAND) return true;
937
+ const value = Reflect.get(target, prop, receiver);
938
+ if (typeof prop !== "string") return value;
939
+ if (RAW_METHODS.has(prop) && typeof value === "function") {
940
+ return bindFunctionInSnapshot(value, target, captureAndRun, adapter);
941
+ }
942
+ if (isLikelyModelDelegate(value)) {
943
+ const cached = modelProxyCache.get(value);
944
+ if (cached) return cached;
945
+ const wrappedDelegate = buildModelProxy(value, captureAndRun, adapter);
946
+ modelProxyCache.set(value, wrappedDelegate);
947
+ return wrappedDelegate;
948
+ }
949
+ return value;
950
+ }
951
+ });
952
+ }
953
+ function buildModelProxy(delegate, captureAndRun, adapter) {
954
+ return new Proxy(delegate, {
955
+ get(target, prop, receiver) {
956
+ const value = Reflect.get(target, prop, receiver);
957
+ if (typeof prop === "string" && MODEL_METHODS.has(prop) && typeof value === "function") {
958
+ return bindFunctionInSnapshot(value, target, captureAndRun, adapter);
959
+ }
960
+ return value;
961
+ }
962
+ });
963
+ }
964
+ function bindFunctionInSnapshot(fn, thisArg, captureAndRun, adapter) {
965
+ return function bound(...args) {
966
+ const run = captureAndRun();
967
+ const boundArgs = args.map(
968
+ (a) => typeof a === "function" ? wrapCallbackInSnapshot(a, run) : a
969
+ );
970
+ const invoke = () => Reflect.apply(fn, thisArg, boundArgs);
971
+ if (!adapter) return run(invoke);
972
+ return enterAdapterMutex(
973
+ adapter,
974
+ () => run(() => {
975
+ adapter[ADAPTER_SNAPSHOT_KEY] = run;
976
+ let result;
977
+ try {
978
+ result = invoke();
979
+ } catch (sync) {
980
+ adapter[ADAPTER_SNAPSHOT_KEY] = null;
981
+ throw sync;
982
+ }
983
+ if (isThenable(result)) {
984
+ return result.finally(() => {
985
+ adapter[ADAPTER_SNAPSHOT_KEY] = null;
986
+ });
987
+ }
988
+ adapter[ADAPTER_SNAPSHOT_KEY] = null;
989
+ return result;
990
+ })
991
+ );
992
+ };
993
+ }
994
+ function enterAdapterMutex(adapter, body) {
995
+ const prev = adapter[ADAPTER_MUTEX_KEY] ?? Promise.resolve();
996
+ const next = prev.then(() => body());
997
+ adapter[ADAPTER_MUTEX_KEY] = next.then(
998
+ () => void 0,
999
+ () => void 0
1000
+ );
1001
+ return next;
1002
+ }
1003
+ function isThenable(value) {
1004
+ return value !== null && typeof value === "object" && typeof value.then === "function";
1005
+ }
1006
+ function wrapCallbackInSnapshot(cb, run) {
1007
+ return function wrapped(...args) {
1008
+ return run(() => Reflect.apply(cb, this, args));
1009
+ };
1010
+ }
1011
+ function isLikelyModelDelegate(value) {
1012
+ if (!value || typeof value !== "object") return false;
1013
+ if (Array.isArray(value)) return false;
1014
+ if (value instanceof Date) return false;
1015
+ const candidate = value;
1016
+ return typeof candidate.create === "function" && typeof candidate.findMany === "function";
1017
+ }
825
1018
 
826
1019
  exports.ezlogsPrisma = ezlogsPrisma;
1020
+ exports.patchPrismaClient = patchPrismaClient;
1021
+ exports.patchPrismaPgAdapter = patchPrismaPgAdapter;