ezlogs-nextjs 0.4.3 → 0.4.6

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 (66) hide show
  1. package/README.md +217 -86
  2. package/THIRD_PARTY_LICENSES.md +27 -0
  3. package/dist/actors/index.d.cts +1 -1
  4. package/dist/actors/index.d.ts +1 -1
  5. package/dist/{chunk-Z2TM3LGG.js → chunk-2NFJOT6Q.js} +1 -1
  6. package/dist/{chunk-R6IWVTX3.cjs → chunk-65HRY3PW.cjs} +31 -21
  7. package/dist/{chunk-YXZZNZG6.cjs → chunk-B3WST6ES.cjs} +9 -9
  8. package/dist/{chunk-MMLQXSSD.cjs → chunk-B5ZUQULZ.cjs} +18 -11
  9. package/dist/{chunk-NX4EL7BY.cjs → chunk-DM2EAOSF.cjs} +4 -4
  10. package/dist/chunk-DRE2VXFX.js +19 -0
  11. package/dist/chunk-H3FC5HMW.cjs +16 -0
  12. package/dist/{chunk-GI6BM4MR.js → chunk-IBSNHBUC.js} +18 -12
  13. package/dist/chunk-JWJKFZBW.js +52 -0
  14. package/dist/{chunk-MHBS5FEP.js → chunk-M3VBQ5KT.js} +27 -4
  15. package/dist/chunk-NFZ5OKF3.cjs +22 -0
  16. package/dist/{chunk-GMHOUAKD.cjs → chunk-O7SFYXJC.cjs} +37 -13
  17. package/dist/{chunk-U22T7QYY.js → chunk-PK2Z2ABL.js} +13 -3
  18. package/dist/{chunk-YMIGZYFH.js → chunk-RD47JECJ.js} +1 -1
  19. package/dist/chunk-RMKGMIV2.js +13 -0
  20. package/dist/{chunk-NINIAL7M.js → chunk-U3IJV5EJ.js} +1 -1
  21. package/dist/chunk-VJR4VB4B.cjs +56 -0
  22. package/dist/{chunk-PS4U2GFJ.cjs → chunk-YO6E763S.cjs} +5 -5
  23. package/dist/{configuration-CJ5yKVlP.d.cts → configuration-b9pImwFB.d.cts} +2 -2
  24. package/dist/{configuration-CJ5yKVlP.d.ts → configuration-b9pImwFB.d.ts} +2 -2
  25. package/dist/db/drizzle.cjs +3 -3
  26. package/dist/db/drizzle.js +2 -2
  27. package/dist/db/postgres-js.cjs +4 -4
  28. package/dist/db/postgres-js.js +2 -2
  29. package/dist/db/prisma.cjs +12 -12
  30. package/dist/db/prisma.js +2 -2
  31. package/dist/db/supabase.cjs +42 -17
  32. package/dist/db/supabase.d.cts +11 -5
  33. package/dist/db/supabase.d.ts +11 -5
  34. package/dist/db/supabase.js +33 -9
  35. package/dist/index.cjs +288 -142
  36. package/dist/index.d.cts +2 -2
  37. package/dist/index.d.ts +2 -2
  38. package/dist/index.js +198 -52
  39. package/dist/jobs/bullmq.cjs +44 -16
  40. package/dist/jobs/bullmq.d.cts +7 -1
  41. package/dist/jobs/bullmq.d.ts +7 -1
  42. package/dist/jobs/bullmq.js +33 -6
  43. package/dist/jobs/inngest.cjs +36 -17
  44. package/dist/jobs/inngest.d.cts +7 -1
  45. package/dist/jobs/inngest.d.ts +7 -1
  46. package/dist/jobs/inngest.js +23 -5
  47. package/dist/jobs/supabase-queues.cjs +9 -9
  48. package/dist/jobs/supabase-queues.js +4 -4
  49. package/dist/jobs/trigger.cjs +7 -7
  50. package/dist/jobs/trigger.js +4 -4
  51. package/dist/jobs/upstash-workflow.cjs +139 -23
  52. package/dist/jobs/upstash-workflow.d.cts +20 -2
  53. package/dist/jobs/upstash-workflow.d.ts +20 -2
  54. package/dist/jobs/upstash-workflow.js +129 -14
  55. package/dist/nextjs-plugin/index.cjs +46 -29
  56. package/dist/nextjs-plugin/index.js +46 -29
  57. package/dist/nextjs-plugin/loader.cjs +70 -60
  58. package/dist/nextjs-plugin/loader.d.cts +18 -1
  59. package/dist/nextjs-plugin/loader.d.ts +18 -1
  60. package/dist/nextjs-plugin/loader.js +70 -61
  61. package/dist/triggers/index.cjs +22 -16
  62. package/dist/triggers/index.d.cts +0 -10
  63. package/dist/triggers/index.d.ts +0 -10
  64. package/dist/triggers/index.js +11 -5
  65. package/package.json +6 -5
  66. package/sql/postgres/00_install.sql +20 -3
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkMMLQXSSD_cjs = require('./chunk-MMLQXSSD.cjs');
3
+ var chunkB5ZUQULZ_cjs = require('./chunk-B5ZUQULZ.cjs');
4
4
  var chunkTWTG5ILJ_cjs = require('./chunk-TWTG5ILJ.cjs');
5
5
  var chunkZDSQYCYV_cjs = require('./chunk-ZDSQYCYV.cjs');
6
6
 
@@ -50,7 +50,7 @@ function clearBuffer() {
50
50
  }
51
51
  function maxSize() {
52
52
  try {
53
- return chunkMMLQXSSD_cjs.configuration().bufferSize;
53
+ return chunkB5ZUQULZ_cjs.configuration().bufferSize;
54
54
  } catch {
55
55
  return 1e4;
56
56
  }
@@ -541,10 +541,10 @@ var DB_SENSITIVE_PATTERNS = Object.freeze([
541
541
  ]);
542
542
  function emitDbEvent(input) {
543
543
  try {
544
- const config = chunkMMLQXSSD_cjs.configuration();
544
+ const config = chunkB5ZUQULZ_cjs.configuration();
545
545
  if (!config.captureDb) return;
546
546
  if (config.excludedTables.includes(input.modelClass)) return;
547
- if (chunkMMLQXSSD_cjs.DEFAULT_EXCLUDED_TABLES.includes(input.modelClass) && !(input._fromTrigger && isBusinessSessionRow(input.modelClass, input.modelInstance))) {
547
+ if (chunkB5ZUQULZ_cjs.DEFAULT_EXCLUDED_TABLES.includes(input.modelClass) && !(input._fromTrigger && isBusinessSessionRow(input.modelClass, input.modelInstance))) {
548
548
  return;
549
549
  }
550
550
  if (config.databaseReader && !input._fromTrigger) {
@@ -567,7 +567,7 @@ function emitDbEvent(input) {
567
567
  operation: input.operation
568
568
  },
569
569
  outcome: "success",
570
- correlation_id: chunkMMLQXSSD_cjs.current(),
570
+ correlation_id: chunkB5ZUQULZ_cjs.current(),
571
571
  resource_ids: resourceIdStr === null ? [...related] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
572
572
  context,
573
573
  duration_ms: null,
@@ -580,7 +580,7 @@ function emitDbEvent(input) {
580
580
  }
581
581
  function buildContext(input) {
582
582
  const context = {};
583
- const actor = chunkMMLQXSSD_cjs.getCurrentActor();
583
+ const actor = chunkB5ZUQULZ_cjs.getCurrentActor();
584
584
  if (actor) context.actor = actor;
585
585
  if ((input.operation === "create" || input.operation === "destroy") && input.initialAttributes) {
586
586
  const filtered = filterMeaningfulAttributes(input.initialAttributes);
@@ -735,15 +735,15 @@ function isPrismaDecimal(value) {
735
735
  return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
736
736
  }
737
737
  function isBusinessSessionRow(table, row) {
738
- if (!chunkMMLQXSSD_cjs.AUTH_SESSION_TABLE_NAMES.test(table) || /verif/i.test(table) || !row) return false;
738
+ if (!chunkB5ZUQULZ_cjs.AUTH_SESSION_TABLE_NAMES.test(table) || /verif/i.test(table) || !row) return false;
739
739
  const columns = Object.keys(row);
740
- return columns.length > 0 && !columns.some(chunkMMLQXSSD_cjs.isSessionStoreColumn);
740
+ return columns.length > 0 && !columns.some(chunkB5ZUQULZ_cjs.isSessionStoreColumn);
741
741
  }
742
742
  var DISPLAY_NAME_COLUMNS = ["name", "title", "number", "label"];
743
743
  var MAX_DISPLAY_NAME_LENGTH = 120;
744
744
  function resolveDisplayName(modelClass, instance) {
745
745
  try {
746
- const config = chunkMMLQXSSD_cjs.configuration();
746
+ const config = chunkB5ZUQULZ_cjs.configuration();
747
747
  const resolver = config.displayNameFor[modelClass];
748
748
  const resolved = applyResolver(resolver, instance);
749
749
  if (resolved !== null) return resolved;
@@ -180,28 +180,34 @@ function configuration() {
180
180
  return g[GLOBAL_CONFIG_KEY];
181
181
  }
182
182
 
183
- // src/edge-fallback.ts
184
- var ALS_CTOR = loadAsyncLocalStorage();
185
- function loadAsyncLocalStorage() {
186
- const fromGlobal = globalThis.AsyncLocalStorage;
187
- if (typeof fromGlobal === "function") return fromGlobal;
188
- const moduleName = "node:" + ["async", "hooks"].join("_");
183
+ // src/node-builtin.ts
184
+ function loadNodeBuiltin(name) {
185
+ const moduleName = "node:" + name;
189
186
  try {
190
187
  const getBuiltin = globalThis.process?.getBuiltinModule;
191
188
  if (typeof getBuiltin === "function") {
192
189
  const mod = getBuiltin(moduleName);
193
- if (typeof mod?.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
190
+ if (mod) return mod;
194
191
  }
195
192
  } catch {
196
193
  }
197
194
  try {
198
195
  const req = typeof chunkZDSQYCYV_cjs.__require !== "undefined" ? chunkZDSQYCYV_cjs.__require : void 0;
199
- if (typeof req === "function") {
200
- const mod = req(moduleName);
201
- if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
202
- }
196
+ if (typeof req === "function") return req(moduleName);
203
197
  } catch {
204
198
  }
199
+ return null;
200
+ }
201
+
202
+ // src/edge-fallback.ts
203
+ var ALS_CTOR = loadAsyncLocalStorage();
204
+ function loadAsyncLocalStorage() {
205
+ const fromGlobal = globalThis.AsyncLocalStorage;
206
+ if (typeof fromGlobal === "function") return fromGlobal;
207
+ const mod = loadNodeBuiltin(
208
+ ["async", "hooks"].join("_")
209
+ );
210
+ if (typeof mod?.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
205
211
  warnNoAsyncLocalStorageOnNode();
206
212
  return null;
207
213
  }
@@ -453,6 +459,7 @@ exports.endCorrelationScope = endCorrelationScope;
453
459
  exports.generate = generate;
454
460
  exports.getCurrentActor = getCurrentActor;
455
461
  exports.isSessionStoreColumn = isSessionStoreColumn;
462
+ exports.loadNodeBuiltin = loadNodeBuiltin;
456
463
  exports.makeAsyncContextCapture = makeAsyncContextCapture;
457
464
  exports.maybeExtractSupabaseActor = maybeExtractSupabaseActor;
458
465
  exports.resolveCorrelation = resolveCorrelation;
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkMMLQXSSD_cjs = require('./chunk-MMLQXSSD.cjs');
3
+ var chunkB5ZUQULZ_cjs = require('./chunk-B5ZUQULZ.cjs');
4
4
  var chunkTWTG5ILJ_cjs = require('./chunk-TWTG5ILJ.cjs');
5
5
 
6
6
  // src/triggers/patch-pg.ts
@@ -28,7 +28,7 @@ function patchPgClient(pgModule) {
28
28
  function patchPgPool(Pool) {
29
29
  const proto = Pool?.prototype;
30
30
  if (!proto || typeof proto.connect !== "function" || proto._ezlogsPoolPatched) return;
31
- const captureAndRun = chunkMMLQXSSD_cjs.makeAsyncContextCapture();
31
+ const captureAndRun = chunkB5ZUQULZ_cjs.makeAsyncContextCapture();
32
32
  if (!captureAndRun) return;
33
33
  const originalConnect = proto.connect;
34
34
  proto.connect = function patchedConnect(...args) {
@@ -95,10 +95,10 @@ function runPatchedQuery(client, original, config, values, callback) {
95
95
  return wrapInTx(client, original, config, values, callback, ctx);
96
96
  }
97
97
  function snapshotContext() {
98
- const actor = chunkMMLQXSSD_cjs.getCurrentActor();
98
+ const actor = chunkB5ZUQULZ_cjs.getCurrentActor();
99
99
  return {
100
100
  actorId: actor && actor.id ? actor.id : null,
101
- correlationId: chunkMMLQXSSD_cjs.current()
101
+ correlationId: chunkB5ZUQULZ_cjs.current()
102
102
  };
103
103
  }
104
104
  async function injectAndRun(client, original, config, values, callback, ctx) {
@@ -0,0 +1,19 @@
1
+ // src/nextjs-plugin/instrumented-imports.ts
2
+ var INSTRUMENTED_IMPORTS = [
3
+ {
4
+ module: "@upstash/workflow/nextjs",
5
+ names: ["serve", "servePagesRouter", "createWorkflow", "createWorkflowPagesRouter", "serveMany", "serveManyPagesRouter"],
6
+ via: "upstash-workflow"
7
+ },
8
+ { module: "@upstash/workflow", names: ["serve", "Client"], via: "upstash-workflow" },
9
+ { module: "@upstash/qstash", names: ["Client"], via: "upstash-workflow" },
10
+ { module: "bullmq", names: ["Queue", "Worker"], via: "bullmq" },
11
+ { module: "inngest", names: ["Inngest"], via: "inngest" },
12
+ { module: "@supabase/supabase-js", names: ["createClient"], via: "supabase" },
13
+ { module: "@supabase/ssr", names: ["createServerClient"], via: "supabase" }
14
+ ];
15
+ var INSTRUMENTED_IMPORT_CONTENT = new RegExp(
16
+ `from\\s*["'](?:${[...new Set(INSTRUMENTED_IMPORTS.map((e) => e.module))].map((m) => m.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")).join("|")})["']`
17
+ );
18
+
19
+ export { INSTRUMENTED_IMPORTS, INSTRUMENTED_IMPORT_CONTENT };
@@ -0,0 +1,16 @@
1
+ 'use strict';
2
+
3
+ var chunkB5ZUQULZ_cjs = require('./chunk-B5ZUQULZ.cjs');
4
+
5
+ // src/job-delivery.ts
6
+ var storage = chunkB5ZUQULZ_cjs.createScopedStorage(/* @__PURE__ */ Symbol.for("ezlogs-nextjs:job-delivery"));
7
+ function runWithDeliverySlot(slot, callback) {
8
+ return storage.run(slot, callback);
9
+ }
10
+ function markJobDelivery() {
11
+ const slot = storage.read();
12
+ if (slot) slot.jobDelivery = true;
13
+ }
14
+
15
+ exports.markJobDelivery = markJobDelivery;
16
+ exports.runWithDeliverySlot = runWithDeliverySlot;
@@ -178,28 +178,34 @@ function configuration() {
178
178
  return g[GLOBAL_CONFIG_KEY];
179
179
  }
180
180
 
181
- // src/edge-fallback.ts
182
- var ALS_CTOR = loadAsyncLocalStorage();
183
- function loadAsyncLocalStorage() {
184
- const fromGlobal = globalThis.AsyncLocalStorage;
185
- if (typeof fromGlobal === "function") return fromGlobal;
186
- const moduleName = "node:" + ["async", "hooks"].join("_");
181
+ // src/node-builtin.ts
182
+ function loadNodeBuiltin(name) {
183
+ const moduleName = "node:" + name;
187
184
  try {
188
185
  const getBuiltin = globalThis.process?.getBuiltinModule;
189
186
  if (typeof getBuiltin === "function") {
190
187
  const mod = getBuiltin(moduleName);
191
- if (typeof mod?.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
188
+ if (mod) return mod;
192
189
  }
193
190
  } catch {
194
191
  }
195
192
  try {
196
193
  const req = typeof __require !== "undefined" ? __require : void 0;
197
- if (typeof req === "function") {
198
- const mod = req(moduleName);
199
- if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
200
- }
194
+ if (typeof req === "function") return req(moduleName);
201
195
  } catch {
202
196
  }
197
+ return null;
198
+ }
199
+
200
+ // src/edge-fallback.ts
201
+ var ALS_CTOR = loadAsyncLocalStorage();
202
+ function loadAsyncLocalStorage() {
203
+ const fromGlobal = globalThis.AsyncLocalStorage;
204
+ if (typeof fromGlobal === "function") return fromGlobal;
205
+ const mod = loadNodeBuiltin(
206
+ ["async", "hooks"].join("_")
207
+ );
208
+ if (typeof mod?.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
203
209
  warnNoAsyncLocalStorageOnNode();
204
210
  return null;
205
211
  }
@@ -440,4 +446,4 @@ function describe(value) {
440
446
  }
441
447
  }
442
448
 
443
- export { AUTH_SESSION_TABLE_NAMES, DEFAULT_EXCLUDED_EXTENSIONS, DEFAULT_EXCLUDED_TABLES, configuration, createScopedStorage, current, currentActorSource, endCorrelationScope, generate, getCurrentActor, isSessionStoreColumn, makeAsyncContextCapture, maybeExtractSupabaseActor, resolveCorrelation, runWithActorScope, runWithCorrelation, setActor };
449
+ export { AUTH_SESSION_TABLE_NAMES, DEFAULT_EXCLUDED_EXTENSIONS, DEFAULT_EXCLUDED_TABLES, configuration, createScopedStorage, current, currentActorSource, endCorrelationScope, generate, getCurrentActor, isSessionStoreColumn, loadNodeBuiltin, makeAsyncContextCapture, maybeExtractSupabaseActor, resolveCorrelation, runWithActorScope, runWithCorrelation, setActor };
@@ -0,0 +1,52 @@
1
+ import { logger } from './chunk-FCFVIRQF.js';
2
+
3
+ // src/instrument.ts
4
+ function instrumentFrom(replacements) {
5
+ return (key, original) => {
6
+ const replace = Object.prototype.hasOwnProperty.call(replacements, key) ? replacements[key] : void 0;
7
+ if (!replace) return original;
8
+ try {
9
+ return replace(original) ?? original;
10
+ } catch (error) {
11
+ logger.debug(`instrument ${key} failed (${error instanceof Error ? error.message : String(error)}); using the original`);
12
+ return original;
13
+ }
14
+ };
15
+ }
16
+ function instrumentClass(original, wrapInstance, mapArgs) {
17
+ if (typeof original !== "function") return original;
18
+ return new Proxy(original, {
19
+ construct(target, args, newTarget) {
20
+ let callArgs = args;
21
+ if (mapArgs) {
22
+ try {
23
+ callArgs = mapArgs(args);
24
+ } catch {
25
+ callArgs = args;
26
+ }
27
+ }
28
+ const instance = Reflect.construct(target, callArgs, newTarget);
29
+ try {
30
+ return wrapInstance(instance) ?? instance;
31
+ } catch {
32
+ return instance;
33
+ }
34
+ }
35
+ });
36
+ }
37
+ function instrumentFactory(original, wrapResult) {
38
+ if (typeof original !== "function") return original;
39
+ const factory = original;
40
+ return new Proxy(factory, {
41
+ apply(target, thisArg, args) {
42
+ const value = Reflect.apply(target, thisArg, args);
43
+ try {
44
+ return wrapResult(value) ?? value;
45
+ } catch {
46
+ return value;
47
+ }
48
+ }
49
+ });
50
+ }
51
+
52
+ export { instrumentClass, instrumentFactory, instrumentFrom };
@@ -1,5 +1,5 @@
1
- import { emitDbEvent } from './chunk-NINIAL7M.js';
2
- import { createScopedStorage, runWithCorrelation, getCurrentActor, runWithActorScope, current, generate } from './chunk-GI6BM4MR.js';
1
+ import { emitDbEvent } from './chunk-U3IJV5EJ.js';
2
+ import { createScopedStorage, runWithCorrelation, getCurrentActor, runWithActorScope, current, generate } from './chunk-IBSNHBUC.js';
3
3
  import { logger } from './chunk-FCFVIRQF.js';
4
4
 
5
5
  // src/triggers/emit-dedup.ts
@@ -218,7 +218,30 @@ function emitWithRowActor(row) {
218
218
  const actor = stored ? claimer?.id === stored ? claimer : { id: stored } : null;
219
219
  runWithActorScope(() => emitOne(row), actor);
220
220
  }
221
- async function flushAuditLog(exec, options = {}) {
221
+ var inFlightFlushes = /* @__PURE__ */ new Set();
222
+ var IN_FLIGHT_MAX_MS = 5e3;
223
+ function settleAuditFlushes(maxMs = IN_FLIGHT_MAX_MS) {
224
+ if (inFlightFlushes.size === 0) return Promise.resolve();
225
+ let timer;
226
+ return Promise.race([
227
+ Promise.allSettled([...inFlightFlushes]).then(() => void 0),
228
+ new Promise((resolve) => {
229
+ timer = setTimeout(resolve, maxMs);
230
+ timer.unref?.();
231
+ })
232
+ ]).finally(() => clearTimeout(timer));
233
+ }
234
+ function flushAuditLog(exec, options = {}) {
235
+ const work = readAndEmit(exec, options);
236
+ inFlightFlushes.add(work);
237
+ const done = () => inFlightFlushes.delete(work);
238
+ work.then(done, done);
239
+ const forget = setTimeout(done, IN_FLIGHT_MAX_MS);
240
+ forget.unref?.();
241
+ work.then(() => clearTimeout(forget), () => clearTimeout(forget));
242
+ return work;
243
+ }
244
+ async function readAndEmit(exec, options) {
222
245
  if (!exec) return;
223
246
  const correlationId = current();
224
247
  if (!correlationId) return;
@@ -523,4 +546,4 @@ function coerceJsonb(value) {
523
546
  return null;
524
547
  }
525
548
 
526
- export { auditLogInstalled, checkAuditLogAccess, detectTriggerTrackedTables, emitAuditRows, flushAuditLog, maintainAuditLogAfterRequests, pruneAuditLog, readAuditRows, runWithEmittedAuditIdsScope, sweepAuditLog };
549
+ export { auditLogInstalled, checkAuditLogAccess, detectTriggerTrackedTables, emitAuditRows, flushAuditLog, maintainAuditLogAfterRequests, pruneAuditLog, readAuditRows, runWithEmittedAuditIdsScope, settleAuditFlushes, sweepAuditLog };
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+
3
+ // src/nextjs-plugin/instrumented-imports.ts
4
+ var INSTRUMENTED_IMPORTS = [
5
+ {
6
+ module: "@upstash/workflow/nextjs",
7
+ names: ["serve", "servePagesRouter", "createWorkflow", "createWorkflowPagesRouter", "serveMany", "serveManyPagesRouter"],
8
+ via: "upstash-workflow"
9
+ },
10
+ { module: "@upstash/workflow", names: ["serve", "Client"], via: "upstash-workflow" },
11
+ { module: "@upstash/qstash", names: ["Client"], via: "upstash-workflow" },
12
+ { module: "bullmq", names: ["Queue", "Worker"], via: "bullmq" },
13
+ { module: "inngest", names: ["Inngest"], via: "inngest" },
14
+ { module: "@supabase/supabase-js", names: ["createClient"], via: "supabase" },
15
+ { module: "@supabase/ssr", names: ["createServerClient"], via: "supabase" }
16
+ ];
17
+ var INSTRUMENTED_IMPORT_CONTENT = new RegExp(
18
+ `from\\s*["'](?:${[...new Set(INSTRUMENTED_IMPORTS.map((e) => e.module))].map((m) => m.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")).join("|")})["']`
19
+ );
20
+
21
+ exports.INSTRUMENTED_IMPORTS = INSTRUMENTED_IMPORTS;
22
+ exports.INSTRUMENTED_IMPORT_CONTENT = INSTRUMENTED_IMPORT_CONTENT;
@@ -1,11 +1,11 @@
1
1
  'use strict';
2
2
 
3
- var chunkYXZZNZG6_cjs = require('./chunk-YXZZNZG6.cjs');
4
- var chunkMMLQXSSD_cjs = require('./chunk-MMLQXSSD.cjs');
3
+ var chunkB3WST6ES_cjs = require('./chunk-B3WST6ES.cjs');
4
+ var chunkB5ZUQULZ_cjs = require('./chunk-B5ZUQULZ.cjs');
5
5
  var chunkTWTG5ILJ_cjs = require('./chunk-TWTG5ILJ.cjs');
6
6
 
7
7
  // src/triggers/emit-dedup.ts
8
- var storage = chunkMMLQXSSD_cjs.createScopedStorage(
8
+ var storage = chunkB5ZUQULZ_cjs.createScopedStorage(
9
9
  /* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-emitted-ids-storage")
10
10
  );
11
11
  function currentEmittedAuditIds() {
@@ -103,7 +103,7 @@ async function sweepAuditLog(exec) {
103
103
  await loadTableMeta(exec, rows);
104
104
  for (const row of rows) {
105
105
  const correlationId = row.correlation_id ?? correlationForTx(row.txid);
106
- chunkMMLQXSSD_cjs.runWithCorrelation(correlationId, () => emitWithRowActor(row));
106
+ chunkB5ZUQULZ_cjs.runWithCorrelation(correlationId, () => emitWithRowActor(row));
107
107
  }
108
108
  return rows.length;
109
109
  } catch (err) {
@@ -216,13 +216,36 @@ function emitAuditRows(rows) {
216
216
  }
217
217
  function emitWithRowActor(row) {
218
218
  const stored = row.actor_id || null;
219
- const claimer = chunkMMLQXSSD_cjs.getCurrentActor();
219
+ const claimer = chunkB5ZUQULZ_cjs.getCurrentActor();
220
220
  const actor = stored ? claimer?.id === stored ? claimer : { id: stored } : null;
221
- chunkMMLQXSSD_cjs.runWithActorScope(() => emitOne(row), actor);
221
+ chunkB5ZUQULZ_cjs.runWithActorScope(() => emitOne(row), actor);
222
222
  }
223
- async function flushAuditLog(exec, options = {}) {
223
+ var inFlightFlushes = /* @__PURE__ */ new Set();
224
+ var IN_FLIGHT_MAX_MS = 5e3;
225
+ function settleAuditFlushes(maxMs = IN_FLIGHT_MAX_MS) {
226
+ if (inFlightFlushes.size === 0) return Promise.resolve();
227
+ let timer;
228
+ return Promise.race([
229
+ Promise.allSettled([...inFlightFlushes]).then(() => void 0),
230
+ new Promise((resolve) => {
231
+ timer = setTimeout(resolve, maxMs);
232
+ timer.unref?.();
233
+ })
234
+ ]).finally(() => clearTimeout(timer));
235
+ }
236
+ function flushAuditLog(exec, options = {}) {
237
+ const work = readAndEmit(exec, options);
238
+ inFlightFlushes.add(work);
239
+ const done = () => inFlightFlushes.delete(work);
240
+ work.then(done, done);
241
+ const forget = setTimeout(done, IN_FLIGHT_MAX_MS);
242
+ forget.unref?.();
243
+ work.then(() => clearTimeout(forget), () => clearTimeout(forget));
244
+ return work;
245
+ }
246
+ async function readAndEmit(exec, options) {
224
247
  if (!exec) return;
225
- const correlationId = chunkMMLQXSSD_cjs.current();
248
+ const correlationId = chunkB5ZUQULZ_cjs.current();
226
249
  if (!correlationId) return;
227
250
  lastRequestFlushAt = Date.now();
228
251
  const rows = await readAuditRows(exec, correlationId, options.since ?? null);
@@ -365,11 +388,11 @@ function emitFresh(rows) {
365
388
  emitAuditRows(fresh);
366
389
  }
367
390
  function correlationForTx(txid) {
368
- if (!txid) return chunkMMLQXSSD_cjs.generate();
391
+ if (!txid) return chunkB5ZUQULZ_cjs.generate();
369
392
  let id = txCorrelation.get(txid);
370
393
  if (!id) {
371
394
  if (txCorrelation.size >= 1e3) txCorrelation.clear();
372
- id = chunkMMLQXSSD_cjs.generate();
395
+ id = chunkB5ZUQULZ_cjs.generate();
373
396
  txCorrelation.set(txid, id);
374
397
  }
375
398
  return id;
@@ -390,7 +413,7 @@ function emitOne(row) {
390
413
  const newRow = withUtcTimestamps(coerceJsonb(row.new_row), naive);
391
414
  const related = row.resource_id === null ? relatedResourceIds(row.table_name, newRow ?? oldRow ?? {}) : null;
392
415
  if (op === "create" && newRow) {
393
- chunkYXZZNZG6_cjs.emitDbEvent({
416
+ chunkB3WST6ES_cjs.emitDbEvent({
394
417
  modelClass: row.table_name,
395
418
  operation: "create",
396
419
  resourceId: row.resource_id,
@@ -408,7 +431,7 @@ function emitOne(row) {
408
431
  if (changes.length === 0) {
409
432
  return;
410
433
  }
411
- chunkYXZZNZG6_cjs.emitDbEvent({
434
+ chunkB3WST6ES_cjs.emitDbEvent({
412
435
  modelClass: row.table_name,
413
436
  operation: "update",
414
437
  resourceId: row.resource_id,
@@ -424,7 +447,7 @@ function emitOne(row) {
424
447
  return;
425
448
  }
426
449
  if (op === "destroy" && oldRow) {
427
- chunkYXZZNZG6_cjs.emitDbEvent({
450
+ chunkB3WST6ES_cjs.emitDbEvent({
428
451
  modelClass: row.table_name,
429
452
  operation: "destroy",
430
453
  resourceId: row.resource_id,
@@ -534,4 +557,5 @@ exports.maintainAuditLogAfterRequests = maintainAuditLogAfterRequests;
534
557
  exports.pruneAuditLog = pruneAuditLog;
535
558
  exports.readAuditRows = readAuditRows;
536
559
  exports.runWithEmittedAuditIdsScope = runWithEmittedAuditIdsScope;
560
+ exports.settleAuditFlushes = settleAuditFlushes;
537
561
  exports.sweepAuditLog = sweepAuditLog;
@@ -1,6 +1,6 @@
1
- import { flushAuditLog } from './chunk-MHBS5FEP.js';
2
- import { build, pushEvent, sanitizeArgs } from './chunk-NINIAL7M.js';
3
- import { configuration, current, generate, runWithCorrelation, runWithActorScope, getCurrentActor, maybeExtractSupabaseActor, endCorrelationScope } from './chunk-GI6BM4MR.js';
1
+ import { flushAuditLog } from './chunk-M3VBQ5KT.js';
2
+ import { build, pushEvent, sanitizeArgs } from './chunk-U3IJV5EJ.js';
3
+ import { configuration, current, generate, runWithCorrelation, runWithActorScope, getCurrentActor, maybeExtractSupabaseActor, endCorrelationScope } from './chunk-IBSNHBUC.js';
4
4
  import { logger } from './chunk-FCFVIRQF.js';
5
5
 
6
6
  // src/jobs/shared.ts
@@ -18,6 +18,7 @@ function emitJobEvent(input) {
18
18
  job_id: input.jobId ?? null,
19
19
  queue: input.queue ?? null,
20
20
  retry_count: input.retryCount ?? null,
21
+ step: input.step ?? null,
21
22
  arguments: jobArguments(input.payload)
22
23
  });
23
24
  const event = build({
@@ -41,10 +42,15 @@ async function runJobWithCapture(meta, work) {
41
42
  const body = async () => {
42
43
  const startedAt = /* @__PURE__ */ new Date();
43
44
  const startMs = startedAt.getTime();
45
+ const step = meta.step;
44
46
  const baseMeta = {
45
47
  jobClass: meta.jobClass,
46
48
  jobId: meta.jobId ?? null,
47
49
  queue: meta.queue ?? null,
50
+ // Read when the event is built (after the run): the step it executed.
51
+ get step() {
52
+ return (typeof step === "function" ? step() : step) ?? null;
53
+ },
48
54
  retryCount: meta.retryCount ?? null,
49
55
  correlationId,
50
56
  startedAt,
@@ -63,6 +69,10 @@ async function runJobWithCapture(meta, work) {
63
69
  const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
64
70
  await flushJobAuditLog(startedAt);
65
71
  if (meta.isControlFlow?.(error)) throw error;
72
+ if (meta.isSuccessfulExit?.(error)) {
73
+ emitJobEvent({ ...baseMeta, outcome: "success", durationMs: Date.now() - startMs });
74
+ throw error;
75
+ }
66
76
  emitJobEvent({
67
77
  ...baseMeta,
68
78
  outcome: "failure",
@@ -1,4 +1,4 @@
1
- import { getCurrentActor, current } from './chunk-GI6BM4MR.js';
1
+ import { getCurrentActor, current } from './chunk-IBSNHBUC.js';
2
2
  import { logger } from './chunk-FCFVIRQF.js';
3
3
 
4
4
  // src/triggers/context.ts
@@ -0,0 +1,13 @@
1
+ import { createScopedStorage } from './chunk-IBSNHBUC.js';
2
+
3
+ // src/job-delivery.ts
4
+ var storage = createScopedStorage(/* @__PURE__ */ Symbol.for("ezlogs-nextjs:job-delivery"));
5
+ function runWithDeliverySlot(slot, callback) {
6
+ return storage.run(slot, callback);
7
+ }
8
+ function markJobDelivery() {
9
+ const slot = storage.read();
10
+ if (slot) slot.jobDelivery = true;
11
+ }
12
+
13
+ export { markJobDelivery, runWithDeliverySlot };
@@ -1,4 +1,4 @@
1
- import { configuration, DEFAULT_EXCLUDED_TABLES, current, getCurrentActor, AUTH_SESSION_TABLE_NAMES, isSessionStoreColumn } from './chunk-GI6BM4MR.js';
1
+ import { configuration, DEFAULT_EXCLUDED_TABLES, current, getCurrentActor, AUTH_SESSION_TABLE_NAMES, isSessionStoreColumn } from './chunk-IBSNHBUC.js';
2
2
  import { logger } from './chunk-FCFVIRQF.js';
3
3
  import { __export } from './chunk-SIAA4J6H.js';
4
4
 
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+
3
+ var chunkTWTG5ILJ_cjs = require('./chunk-TWTG5ILJ.cjs');
4
+
5
+ // src/instrument.ts
6
+ function instrumentFrom(replacements) {
7
+ return (key, original) => {
8
+ const replace = Object.prototype.hasOwnProperty.call(replacements, key) ? replacements[key] : void 0;
9
+ if (!replace) return original;
10
+ try {
11
+ return replace(original) ?? original;
12
+ } catch (error) {
13
+ chunkTWTG5ILJ_cjs.logger.debug(`instrument ${key} failed (${error instanceof Error ? error.message : String(error)}); using the original`);
14
+ return original;
15
+ }
16
+ };
17
+ }
18
+ function instrumentClass(original, wrapInstance, mapArgs) {
19
+ if (typeof original !== "function") return original;
20
+ return new Proxy(original, {
21
+ construct(target, args, newTarget) {
22
+ let callArgs = args;
23
+ if (mapArgs) {
24
+ try {
25
+ callArgs = mapArgs(args);
26
+ } catch {
27
+ callArgs = args;
28
+ }
29
+ }
30
+ const instance = Reflect.construct(target, callArgs, newTarget);
31
+ try {
32
+ return wrapInstance(instance) ?? instance;
33
+ } catch {
34
+ return instance;
35
+ }
36
+ }
37
+ });
38
+ }
39
+ function instrumentFactory(original, wrapResult) {
40
+ if (typeof original !== "function") return original;
41
+ const factory = original;
42
+ return new Proxy(factory, {
43
+ apply(target, thisArg, args) {
44
+ const value = Reflect.apply(target, thisArg, args);
45
+ try {
46
+ return wrapResult(value) ?? value;
47
+ } catch {
48
+ return value;
49
+ }
50
+ }
51
+ });
52
+ }
53
+
54
+ exports.instrumentClass = instrumentClass;
55
+ exports.instrumentFactory = instrumentFactory;
56
+ exports.instrumentFrom = instrumentFrom;
@@ -1,19 +1,19 @@
1
1
  'use strict';
2
2
 
3
- var chunkMMLQXSSD_cjs = require('./chunk-MMLQXSSD.cjs');
3
+ var chunkB5ZUQULZ_cjs = require('./chunk-B5ZUQULZ.cjs');
4
4
  var chunkTWTG5ILJ_cjs = require('./chunk-TWTG5ILJ.cjs');
5
5
 
6
6
  // src/triggers/context.ts
7
7
  function getDatabaseContext() {
8
- const actor = chunkMMLQXSSD_cjs.getCurrentActor();
8
+ const actor = chunkB5ZUQULZ_cjs.getCurrentActor();
9
9
  return {
10
10
  actorId: actor && actor.id ? actor.id : null,
11
- correlationId: chunkMMLQXSSD_cjs.current()
11
+ correlationId: chunkB5ZUQULZ_cjs.current()
12
12
  };
13
13
  }
14
14
  async function applyDatabaseContext(exec) {
15
- const actor = chunkMMLQXSSD_cjs.getCurrentActor();
16
- const correlationId = chunkMMLQXSSD_cjs.current();
15
+ const actor = chunkB5ZUQULZ_cjs.getCurrentActor();
16
+ const correlationId = chunkB5ZUQULZ_cjs.current();
17
17
  if (!actor && !correlationId) return;
18
18
  try {
19
19
  if (actor && actor.id) {
@@ -83,7 +83,7 @@ type DisplayNameMap = Record<string, DisplayNameResolver>;
83
83
  /**
84
84
  * Classifier for Server Action failure return values.
85
85
  *
86
- * Many Next.js codebases (Velory, next-safe-action templates, the
86
+ * Many Next.js codebases (in-house action wrappers, next-safe-action templates, the
87
87
  * Vercel App Router examples, tRPC) catch errors inside the action and
88
88
  * return `{ success: false, error: "..." }` instead of throwing. The
89
89
  * HTTP response is 200, so the agent can't tell the action failed
@@ -218,4 +218,4 @@ interface InitOptions {
218
218
  */
219
219
  type DatabaseReader = (sql: string, params: ReadonlyArray<unknown>) => Promise<unknown>;
220
220
 
221
- export type { ActorContext as A, DisplayNameMap as D, InitOptions as I, ActorFromRequest as a, ActorPrincipal as b };
221
+ export type { ActorFromRequest as A, DisplayNameMap as D, InitOptions as I, ActorContext as a, ActorPrincipal as b };
@@ -83,7 +83,7 @@ type DisplayNameMap = Record<string, DisplayNameResolver>;
83
83
  /**
84
84
  * Classifier for Server Action failure return values.
85
85
  *
86
- * Many Next.js codebases (Velory, next-safe-action templates, the
86
+ * Many Next.js codebases (in-house action wrappers, next-safe-action templates, the
87
87
  * Vercel App Router examples, tRPC) catch errors inside the action and
88
88
  * return `{ success: false, error: "..." }` instead of throwing. The
89
89
  * HTTP response is 200, so the agent can't tell the action failed
@@ -218,4 +218,4 @@ interface InitOptions {
218
218
  */
219
219
  type DatabaseReader = (sql: string, params: ReadonlyArray<unknown>) => Promise<unknown>;
220
220
 
221
- export type { ActorContext as A, DisplayNameMap as D, InitOptions as I, ActorFromRequest as a, ActorPrincipal as b };
221
+ export type { ActorFromRequest as A, DisplayNameMap as D, InitOptions as I, ActorContext as a, ActorPrincipal as b };