ezlogs-nextjs 0.1.0 → 0.1.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 (41) 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 +17 -6
  11. package/dist/db/prisma.js +17 -6
  12. package/dist/db/supabase.cjs +17 -6
  13. package/dist/db/supabase.js +17 -6
  14. package/dist/index.cjs +459 -222
  15. package/dist/index.d.cts +2 -2
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.js +459 -222
  18. package/dist/jobs/bullmq.cjs +6 -5
  19. package/dist/jobs/bullmq.d.cts +16 -8
  20. package/dist/jobs/bullmq.d.ts +16 -8
  21. package/dist/jobs/bullmq.js +6 -5
  22. package/dist/jobs/inngest.cjs +16 -6
  23. package/dist/jobs/inngest.js +16 -6
  24. package/dist/jobs/supabase-queues.cjs +16 -6
  25. package/dist/jobs/supabase-queues.js +16 -6
  26. package/dist/jobs/trigger.cjs +16 -6
  27. package/dist/jobs/trigger.js +16 -6
  28. package/dist/jobs/upstash-workflow.cjs +16 -6
  29. package/dist/jobs/upstash-workflow.js +16 -6
  30. package/dist/nextjs-plugin/index.cjs +18 -0
  31. package/dist/nextjs-plugin/index.js +18 -0
  32. package/dist/nextjs-plugin/loader.cjs +44 -34
  33. package/dist/nextjs-plugin/loader.d.cts +10 -0
  34. package/dist/nextjs-plugin/loader.d.ts +10 -0
  35. package/dist/nextjs-plugin/loader.js +44 -34
  36. package/dist/triggers/index.cjs +43 -8
  37. package/dist/triggers/index.d.cts +7 -0
  38. package/dist/triggers/index.d.ts +7 -0
  39. package/dist/triggers/index.js +43 -8
  40. package/package.json +3 -4
  41. package/sql/postgres/00_install.sql +1 -1
package/dist/index.cjs CHANGED
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- var crypto = require('crypto');
4
-
5
3
  var __defProp = Object.defineProperty;
6
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
5
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
@@ -26,7 +24,7 @@ function configuration() {
26
24
  }
27
25
  return g[GLOBAL_CONFIG_KEY];
28
26
  }
29
- var DEFAULT_EXCLUDED_PATHS, DEFAULT_EXCLUDED_EXTENSIONS, DEFAULT_EXCLUDED_TABLES, DEFAULT_EXCLUDED_JOB_CLASSES, DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, DEFAULT_SERVER_URL, Configuration, GLOBAL_CONFIG_KEY;
27
+ var DEFAULT_EXCLUDED_PATHS, DEFAULT_EXCLUDED_EXTENSIONS, DEFAULT_EXCLUDED_TABLES, DEFAULT_EXCLUDED_JOB_CLASSES, DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, Configuration, GLOBAL_CONFIG_KEY;
30
28
  var init_configuration = __esm({
31
29
  "src/configuration.ts"() {
32
30
  DEFAULT_EXCLUDED_PATHS = Object.freeze([
@@ -91,9 +89,8 @@ var init_configuration = __esm({
91
89
  ]);
92
90
  DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
93
91
  DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
94
- DEFAULT_SERVER_URL = "https://app.ezlogs.io";
95
92
  Configuration = class {
96
- serverUrl = DEFAULT_SERVER_URL;
93
+ serverUrl = null;
97
94
  projectToken = null;
98
95
  captureHttp = true;
99
96
  captureDb = true;
@@ -105,6 +102,7 @@ var init_configuration = __esm({
105
102
  logLevel = "warn";
106
103
  patchGlobalFetch = true;
107
104
  actorFromSupabase = true;
105
+ allowInsecureTransport = false;
108
106
  excludedPaths = [];
109
107
  excludedTables = [];
110
108
  excludedJobClasses = [];
@@ -132,7 +130,7 @@ var init_configuration = __esm({
132
130
  */
133
131
  triggerTrackedTables = null;
134
132
  apply(options) {
135
- if (options.serverUrl !== void 0) this.serverUrl = options.serverUrl;
133
+ this.serverUrl = options.serverUrl;
136
134
  this.projectToken = options.projectToken;
137
135
  if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
138
136
  if (options.captureDb !== void 0) this.captureDb = options.captureDb;
@@ -157,6 +155,9 @@ var init_configuration = __esm({
157
155
  if (options.patchGlobalFetch !== void 0) {
158
156
  this.patchGlobalFetch = options.patchGlobalFetch;
159
157
  }
158
+ if (options.allowInsecureTransport !== void 0) {
159
+ this.allowInsecureTransport = options.allowInsecureTransport;
160
+ }
160
161
  if (options.actorFromSupabase !== void 0) {
161
162
  this.actorFromSupabase = options.actorFromSupabase;
162
163
  }
@@ -368,11 +369,22 @@ var init_edge_fallback = __esm({
368
369
  ALS_CTOR = loadAsyncLocalStorage();
369
370
  }
370
371
  });
372
+
373
+ // src/correlation.ts
371
374
  function generate() {
372
375
  const ts = Date.now();
373
- const hex = crypto.randomBytes(4).toString("hex");
376
+ const hex = randomHexBytes(4);
374
377
  return `ezl_${ts}_${hex}`;
375
378
  }
379
+ function randomHexBytes(byteCount) {
380
+ const buf = new Uint8Array(byteCount);
381
+ globalThis.crypto.getRandomValues(buf);
382
+ let out = "";
383
+ for (let i = 0; i < buf.length; i++) {
384
+ out += buf[i].toString(16).padStart(2, "0");
385
+ }
386
+ return out;
387
+ }
376
388
  function resolveCorrelation(headers) {
377
389
  if (!headers) return generate();
378
390
  const ezlogs2 = safeRead(headers, CORRELATION_HEADER);
@@ -393,9 +405,17 @@ function safeRead(headers, name) {
393
405
  }
394
406
  function wrapPlatformId(platformId) {
395
407
  const ts = Date.now();
396
- const hex = crypto.createHash("sha1").update(platformId).digest("hex").slice(0, 8);
408
+ const hex = fnv1aHex(platformId);
397
409
  return `ezl_${ts}_${hex}`;
398
410
  }
411
+ function fnv1aHex(input) {
412
+ let hash = 2166136261;
413
+ for (let i = 0; i < input.length; i++) {
414
+ hash ^= input.charCodeAt(i);
415
+ hash = Math.imul(hash, 16777619);
416
+ }
417
+ return (hash >>> 0).toString(16).padStart(8, "0");
418
+ }
399
419
  function current() {
400
420
  return storage.read();
401
421
  }
@@ -446,6 +466,12 @@ function validateActor(input) {
446
466
  if (obj.label !== void 0 && obj.label !== null) {
447
467
  result.label = String(obj.label);
448
468
  }
469
+ if (obj.kind !== void 0 && obj.kind !== null) {
470
+ const kind = String(obj.kind);
471
+ if (VALID_KINDS.has(kind)) {
472
+ result.kind = kind;
473
+ }
474
+ }
449
475
  return result;
450
476
  }
451
477
  function describe2(value) {
@@ -455,7 +481,7 @@ function describe2(value) {
455
481
  return Object.prototype.toString.call(value);
456
482
  }
457
483
  }
458
- var storage2;
484
+ var storage2, VALID_KINDS;
459
485
  var init_actor = __esm({
460
486
  "src/actor.ts"() {
461
487
  init_logger();
@@ -463,6 +489,7 @@ var init_actor = __esm({
463
489
  storage2 = createScopedStorage(
464
490
  /* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-storage")
465
491
  );
492
+ VALID_KINDS = /* @__PURE__ */ new Set(["human", "agent", "system", "hybrid"]);
466
493
  }
467
494
  });
468
495
 
@@ -855,7 +882,17 @@ var init_shared = __esm({
855
882
  "credit_card",
856
883
  "ssn",
857
884
  "social_security",
858
- "encrypted"
885
+ "encrypted",
886
+ "private_key",
887
+ "public_key",
888
+ "signing_key",
889
+ "pem",
890
+ "cipher",
891
+ "nonce",
892
+ "salt",
893
+ "digest",
894
+ "signature",
895
+ "hmac"
859
896
  ]);
860
897
  }
861
898
  });
@@ -1671,13 +1708,27 @@ function runWithAuditSnapshotScope(callback) {
1671
1708
  return storage3.run(0n, callback);
1672
1709
  }
1673
1710
 
1711
+ // src/triggers/emit-dedup.ts
1712
+ init_edge_fallback();
1713
+ var storage4 = createScopedStorage(
1714
+ /* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-emitted-ids-storage")
1715
+ );
1716
+ function currentEmittedAuditIds() {
1717
+ return storage4.read();
1718
+ }
1719
+ function runWithEmittedAuditIdsScope(callback) {
1720
+ const existing = storage4.read();
1721
+ if (existing !== null) return callback();
1722
+ return storage4.run(/* @__PURE__ */ new Set(), callback);
1723
+ }
1724
+
1674
1725
  // src/triggers/reader.ts
1675
1726
  async function readAuditRows(exec, correlationId, snapshotMaxId = null) {
1676
1727
  try {
1677
- const sql = snapshotMaxId === null ? `SELECT table_name, op, old_row, new_row, resource_id
1728
+ const sql = snapshotMaxId === null ? `SELECT id, table_name, op, old_row, new_row, resource_id
1678
1729
  FROM ezlogs_audit_log
1679
1730
  WHERE correlation_id = $1
1680
- ORDER BY id ASC` : `SELECT table_name, op, old_row, new_row, resource_id
1731
+ ORDER BY id ASC` : `SELECT id, table_name, op, old_row, new_row, resource_id
1681
1732
  FROM ezlogs_audit_log
1682
1733
  WHERE correlation_id = $1
1683
1734
  OR (correlation_id IS NULL AND id > $2)
@@ -1748,7 +1799,19 @@ async function flushAuditLog(exec) {
1748
1799
  const snapshot = currentAuditSnapshot();
1749
1800
  const rows = await readAuditRows(exec, correlationId, snapshot);
1750
1801
  if (rows.length === 0) return;
1751
- emitAuditRows(rows);
1802
+ const emitted = currentEmittedAuditIds();
1803
+ if (emitted === null) {
1804
+ emitAuditRows(rows);
1805
+ return;
1806
+ }
1807
+ const fresh = [];
1808
+ for (const row of rows) {
1809
+ if (row.id === "" || emitted.has(row.id)) continue;
1810
+ emitted.add(row.id);
1811
+ fresh.push(row);
1812
+ }
1813
+ if (fresh.length === 0) return;
1814
+ emitAuditRows(fresh);
1752
1815
  }
1753
1816
  function emitOne(row) {
1754
1817
  const op = mapOp(row.op);
@@ -1844,6 +1907,7 @@ function extractRows(result) {
1844
1907
  function normalizeAuditRow(raw) {
1845
1908
  const r = raw ?? {};
1846
1909
  return {
1910
+ id: r.id == null ? "" : String(r.id),
1847
1911
  table_name: String(r.table_name ?? ""),
1848
1912
  op: r.op,
1849
1913
  old_row: r.old_row ?? null,
@@ -1896,6 +1960,31 @@ function detect() {
1896
1960
 
1897
1961
  // src/http/capture.ts
1898
1962
  init_actor();
1963
+
1964
+ // src/user-agent-detector.ts
1965
+ var PATTERNS = [
1966
+ { prefix: "claude-", vendor: "claude", label: "Claude" },
1967
+ { prefix: "anthropic-", vendor: "claude", label: "Claude" },
1968
+ { prefix: "gpt-", vendor: "openai", label: "ChatGPT" },
1969
+ { prefix: "chatgpt-", vendor: "openai", label: "ChatGPT" },
1970
+ { prefix: "openai-", vendor: "openai", label: "ChatGPT" },
1971
+ { prefix: "cursor-", vendor: "cursor", label: "Cursor" },
1972
+ { prefix: "windsurf-", vendor: "windsurf", label: "Windsurf" }
1973
+ ];
1974
+ function classifyUserAgent(userAgent) {
1975
+ if (typeof userAgent !== "string" || userAgent.length === 0) return null;
1976
+ const ua = userAgent.toLowerCase();
1977
+ const match = PATTERNS.find((p) => ua.startsWith(p.prefix));
1978
+ if (!match) return null;
1979
+ return {
1980
+ kind: "agent",
1981
+ vendor: match.vendor,
1982
+ label: match.label,
1983
+ suggestedId: `agent:${match.vendor}`
1984
+ };
1985
+ }
1986
+
1987
+ // src/http/capture.ts
1899
1988
  init_correlation();
1900
1989
 
1901
1990
  // src/http/path-matcher.ts
@@ -1941,6 +2030,8 @@ var SENSITIVE_VARIABLE_PATTERNS = Object.freeze([
1941
2030
  "apikey",
1942
2031
  "private_key",
1943
2032
  "privatekey",
2033
+ "public_key",
2034
+ "signing_key",
1944
2035
  "secret_key",
1945
2036
  "secretkey",
1946
2037
  "credential",
@@ -1953,7 +2044,18 @@ var SENSITIVE_VARIABLE_PATTERNS = Object.freeze([
1953
2044
  "credit_card",
1954
2045
  "card_number",
1955
2046
  "cvv",
1956
- "cvc"
2047
+ "cvc",
2048
+ // Crypto-material patterns — aligned with DB_SENSITIVE_PATTERNS
2049
+ // (PR #45). Request bodies can carry the same key material as DB
2050
+ // columns (a webhook POST containing a `signature` field, an HMAC
2051
+ // header echoed into a JSON body, a `pem`-encoded cert blob, etc).
2052
+ "pem",
2053
+ "cipher",
2054
+ "nonce",
2055
+ "salt",
2056
+ "digest",
2057
+ "signature",
2058
+ "hmac"
1957
2059
  ]);
1958
2060
  var MAX_NESTING_DEPTH = 3;
1959
2061
  var MAX_ARRAY_DISPLAY_SIZE = 5;
@@ -2288,92 +2390,118 @@ function isPlainObject3(value) {
2288
2390
  // src/http/capture.ts
2289
2391
  function captureRoute(handler, context = {}) {
2290
2392
  return async (...args) => {
2291
- if (!configuration().captureHttp) {
2292
- return Promise.resolve(handler(...args));
2293
- }
2294
- const request = args[0];
2295
- if (!request || typeof request !== "object" || !("url" in request)) {
2296
- return Promise.resolve(handler(...args));
2297
- }
2298
- const snapshot = await snapshotRequest(request);
2299
- if (snapshot === null) return Promise.resolve(handler(...args));
2300
- const correlationId = resolveCorrelation(request.headers ?? null);
2301
- return runWithCorrelation(
2302
- correlationId,
2303
- () => runWithActorAndAuditScope(async () => {
2304
- await maybeRunActorHook(request);
2305
- const startMs = Date.now();
2306
- let statusCode = null;
2307
- let response = null;
2308
- let exception = null;
2309
- let graphqlErrorMessage = null;
2310
- try {
2311
- response = await Promise.resolve(handler(...args));
2312
- statusCode = response.status;
2313
- if (snapshot.graphqlBody !== null && response.status === 200) {
2314
- graphqlErrorMessage = await readGraphqlErrors(response);
2315
- }
2316
- return response;
2317
- } catch (e) {
2318
- exception = e instanceof Error ? e : new Error(String(e));
2319
- throw e;
2320
- } finally {
2321
- await maybeExtractSupabaseActor();
2322
- await emitEvent({
2323
- snapshot,
2324
- context,
2325
- statusCode,
2326
- exception,
2327
- graphqlErrorMessage,
2328
- durationMs: Date.now() - startMs,
2329
- startedAt: new Date(startMs)
2330
- });
2331
- if (isServerless()) {
2332
- await flushScheduler.flushNow().catch(() => {
2393
+ let handlerInvoked = false;
2394
+ const runHandler = (...invokeArgs) => {
2395
+ handlerInvoked = true;
2396
+ return handler(...invokeArgs);
2397
+ };
2398
+ try {
2399
+ if (!configuration().captureHttp) {
2400
+ return Promise.resolve(runHandler(...args));
2401
+ }
2402
+ const request = args[0];
2403
+ if (!request || typeof request !== "object" || !("url" in request)) {
2404
+ return Promise.resolve(runHandler(...args));
2405
+ }
2406
+ const snapshot = await snapshotRequest(request);
2407
+ if (snapshot === null) return Promise.resolve(runHandler(...args));
2408
+ const correlationId = resolveCorrelation(request.headers ?? null);
2409
+ return await runWithCorrelation(
2410
+ correlationId,
2411
+ () => runWithActorAndAuditScope(async () => {
2412
+ await maybeRunActorHook(request);
2413
+ const startMs = Date.now();
2414
+ let statusCode = null;
2415
+ let response = null;
2416
+ let exception = null;
2417
+ let graphqlErrorMessage = null;
2418
+ try {
2419
+ response = await Promise.resolve(runHandler(...args));
2420
+ statusCode = response.status;
2421
+ if (snapshot.graphqlBody !== null && response.status === 200) {
2422
+ graphqlErrorMessage = await readGraphqlErrors(response);
2423
+ }
2424
+ return response;
2425
+ } catch (e) {
2426
+ exception = e instanceof Error ? e : new Error(String(e));
2427
+ throw e;
2428
+ } finally {
2429
+ await maybeExtractSupabaseActor();
2430
+ await emitEvent({
2431
+ snapshot,
2432
+ context,
2433
+ statusCode,
2434
+ exception,
2435
+ graphqlErrorMessage,
2436
+ durationMs: Date.now() - startMs,
2437
+ startedAt: new Date(startMs)
2333
2438
  });
2439
+ if (isServerless()) {
2440
+ await flushScheduler.flushNow().catch(() => {
2441
+ });
2442
+ }
2334
2443
  }
2335
- }
2336
- })
2337
- );
2444
+ })
2445
+ );
2446
+ } catch (preCaptureError) {
2447
+ if (handlerInvoked) throw preCaptureError;
2448
+ logger.warn(
2449
+ `captureRoute pre-handler setup failed (${describeError7(preCaptureError)}); bypassing capture for this request`
2450
+ );
2451
+ return Promise.resolve(handler(...args));
2452
+ }
2338
2453
  };
2339
2454
  }
2340
2455
  var CORRELATION_HEADER2 = "x-ezlogs-correlation-id";
2341
2456
  function withMiddlewareCapture(middleware) {
2342
2457
  return async (request, ...rest) => {
2343
- const correlationId = resolveCorrelation(request.headers);
2458
+ let middlewareInvoked = false;
2459
+ const runMiddleware = (req, ...mRest) => {
2460
+ middlewareInvoked = true;
2461
+ return middleware(req, ...mRest);
2462
+ };
2344
2463
  try {
2345
- request.headers.set(CORRELATION_HEADER2, correlationId);
2346
- } catch {
2347
- }
2348
- return runWithCorrelation(
2349
- correlationId,
2350
- () => runWithActorAndAuditScope(async () => {
2351
- const startMs = Date.now();
2352
- const startedAt = new Date(startMs);
2353
- const response = await Promise.resolve(middleware(request, ...rest));
2354
- try {
2355
- if (response?.headers && typeof response.headers.set === "function") {
2356
- response.headers.set(CORRELATION_HEADER2, correlationId);
2464
+ const correlationId = resolveCorrelation(request.headers);
2465
+ try {
2466
+ request.headers.set(CORRELATION_HEADER2, correlationId);
2467
+ } catch {
2468
+ }
2469
+ return await runWithCorrelation(
2470
+ correlationId,
2471
+ () => runWithActorAndAuditScope(async () => {
2472
+ const startMs = Date.now();
2473
+ const startedAt = new Date(startMs);
2474
+ const response = await Promise.resolve(runMiddleware(request, ...rest));
2475
+ try {
2476
+ if (response?.headers && typeof response.headers.set === "function") {
2477
+ response.headers.set(CORRELATION_HEADER2, correlationId);
2478
+ }
2479
+ } catch {
2357
2480
  }
2358
- } catch {
2359
- }
2360
- try {
2361
- if (shouldEmitPageNavigation(request)) {
2362
- await maybeRunActorHook(request);
2363
- await maybeExtractSupabaseActor();
2364
- await emitPageNavigationEvent({
2365
- request,
2366
- statusCode: typeof response?.status === "number" ? response.status : null,
2367
- durationMs: Date.now() - startMs,
2368
- startedAt
2369
- });
2481
+ try {
2482
+ if (shouldEmitPageNavigation(request)) {
2483
+ await maybeRunActorHook(request);
2484
+ await maybeExtractSupabaseActor();
2485
+ await emitPageNavigationEvent({
2486
+ request,
2487
+ statusCode: typeof response?.status === "number" ? response.status : null,
2488
+ durationMs: Date.now() - startMs,
2489
+ startedAt
2490
+ });
2491
+ }
2492
+ } catch (error) {
2493
+ logger.debug(`page navigation capture failed: ${describeError7(error)}`);
2370
2494
  }
2371
- } catch (error) {
2372
- logger.debug(`page navigation capture failed: ${describeError7(error)}`);
2373
- }
2374
- return response;
2375
- })
2376
- );
2495
+ return response;
2496
+ })
2497
+ );
2498
+ } catch (preCaptureError) {
2499
+ if (middlewareInvoked) throw preCaptureError;
2500
+ logger.warn(
2501
+ `withMiddlewareCapture pre-handler setup failed (${describeError7(preCaptureError)}); bypassing capture for this request`
2502
+ );
2503
+ return await Promise.resolve(middleware(request, ...rest));
2504
+ }
2377
2505
  };
2378
2506
  }
2379
2507
  function shouldEmitPageNavigation(request) {
@@ -2447,106 +2575,132 @@ function pageControllerFromPath(pathname) {
2447
2575
  }
2448
2576
  function capturePagesApi(handler, context = {}) {
2449
2577
  return async (...args) => {
2450
- if (!configuration().captureHttp) {
2578
+ let handlerInvoked = false;
2579
+ const runHandler = (...invokeArgs) => {
2580
+ handlerInvoked = true;
2581
+ return handler(...invokeArgs);
2582
+ };
2583
+ try {
2584
+ if (!configuration().captureHttp) {
2585
+ return Promise.resolve(runHandler(...args));
2586
+ }
2587
+ const req = args[0];
2588
+ const res = args[1];
2589
+ if (!req || !res) return Promise.resolve(runHandler(...args));
2590
+ const snapshot = snapshotPagesRequest(req);
2591
+ if (snapshot === null) return Promise.resolve(runHandler(...args));
2592
+ const correlationId = resolveCorrelation({
2593
+ get: (name) => readPagesHeader(req, name)
2594
+ });
2595
+ return await runWithCorrelation(
2596
+ correlationId,
2597
+ () => runWithActorAndAuditScope(async () => {
2598
+ await maybeRunActorHookFromPages(req);
2599
+ const startMs = Date.now();
2600
+ let exception = null;
2601
+ try {
2602
+ const result = await Promise.resolve(runHandler(...args));
2603
+ return result;
2604
+ } catch (e) {
2605
+ exception = e instanceof Error ? e : new Error(String(e));
2606
+ throw e;
2607
+ } finally {
2608
+ await maybeExtractSupabaseActor();
2609
+ await emitEvent({
2610
+ snapshot,
2611
+ context,
2612
+ statusCode: typeof res.statusCode === "number" ? res.statusCode : null,
2613
+ exception,
2614
+ graphqlErrorMessage: null,
2615
+ durationMs: Date.now() - startMs,
2616
+ startedAt: new Date(startMs)
2617
+ });
2618
+ if (isServerless()) {
2619
+ await flushScheduler.flushNow().catch(() => void 0);
2620
+ }
2621
+ }
2622
+ })
2623
+ );
2624
+ } catch (preCaptureError) {
2625
+ if (handlerInvoked) throw preCaptureError;
2626
+ logger.warn(
2627
+ `capturePagesApi pre-handler setup failed (${describeError7(preCaptureError)}); bypassing capture for this request`
2628
+ );
2451
2629
  return Promise.resolve(handler(...args));
2452
2630
  }
2453
- const req = args[0];
2454
- const res = args[1];
2455
- if (!req || !res) return Promise.resolve(handler(...args));
2456
- const snapshot = snapshotPagesRequest(req);
2457
- if (snapshot === null) return Promise.resolve(handler(...args));
2458
- const correlationId = resolveCorrelation({
2459
- get: (name) => readPagesHeader(req, name)
2460
- });
2461
- return runWithCorrelation(
2462
- correlationId,
2463
- () => runWithActorAndAuditScope(async () => {
2464
- await maybeRunActorHookFromPages(req);
2465
- const startMs = Date.now();
2466
- let exception = null;
2467
- try {
2468
- const result = await Promise.resolve(handler(...args));
2469
- return result;
2470
- } catch (e) {
2471
- exception = e instanceof Error ? e : new Error(String(e));
2472
- throw e;
2473
- } finally {
2474
- await maybeExtractSupabaseActor();
2475
- await emitEvent({
2476
- snapshot,
2477
- context,
2478
- statusCode: typeof res.statusCode === "number" ? res.statusCode : null,
2479
- exception,
2480
- graphqlErrorMessage: null,
2481
- durationMs: Date.now() - startMs,
2482
- startedAt: new Date(startMs)
2483
- });
2484
- if (isServerless()) {
2485
- await flushScheduler.flushNow().catch(() => void 0);
2486
- }
2487
- }
2488
- })
2489
- );
2490
2631
  };
2491
2632
  }
2492
2633
  function captureServerAction(action, actionName) {
2493
2634
  return async (...args) => {
2494
- if (!configuration().captureHttp) {
2495
- return Promise.resolve(action(...args));
2496
- }
2497
- const headersAdapter = await readNextHeadersAsAdapter();
2498
- const correlationId = resolveCorrelation(headersAdapter);
2499
- return runWithCorrelation(
2500
- correlationId,
2501
- () => runWithActorAndAuditScope(async () => {
2502
- const startMs = Date.now();
2503
- const startedAt = new Date(startMs);
2504
- let exception = null;
2505
- await maybeRunActorHookFromServerAction();
2506
- try {
2507
- const result = await Promise.resolve(action(...args));
2508
- await maybeExtractSupabaseActor();
2509
- const failure = classifyServerActionResult(result);
2510
- await emitServerActionEvent({
2511
- actionName,
2512
- statusCode: failure ? 500 : 200,
2513
- exception: failure ? new Error(failure.errorMessage) : null,
2514
- durationMs: Date.now() - startMs,
2515
- startedAt,
2516
- args
2517
- });
2518
- return result;
2519
- } catch (e) {
2520
- if (isNextControlFlowError(e)) {
2635
+ let actionInvoked = false;
2636
+ const runAction = (...invokeArgs) => {
2637
+ actionInvoked = true;
2638
+ return action(...invokeArgs);
2639
+ };
2640
+ try {
2641
+ if (!configuration().captureHttp) {
2642
+ return Promise.resolve(runAction(...args));
2643
+ }
2644
+ const headersAdapter = await readNextHeadersAsAdapter();
2645
+ const correlationId = resolveCorrelation(headersAdapter);
2646
+ return await runWithCorrelation(
2647
+ correlationId,
2648
+ () => runWithActorAndAuditScope(async () => {
2649
+ const startMs = Date.now();
2650
+ const startedAt = new Date(startMs);
2651
+ let exception = null;
2652
+ await maybeRunActorHookFromServerAction();
2653
+ try {
2654
+ const result = await Promise.resolve(runAction(...args));
2521
2655
  await maybeExtractSupabaseActor();
2656
+ const failure = classifyServerActionResult(result);
2522
2657
  await emitServerActionEvent({
2523
2658
  actionName,
2524
- statusCode: 200,
2525
- exception: null,
2659
+ statusCode: failure ? 500 : 200,
2660
+ exception: failure ? new Error(failure.errorMessage) : null,
2661
+ durationMs: Date.now() - startMs,
2662
+ startedAt,
2663
+ args
2664
+ });
2665
+ return result;
2666
+ } catch (e) {
2667
+ if (isNextControlFlowError(e)) {
2668
+ await maybeExtractSupabaseActor();
2669
+ await emitServerActionEvent({
2670
+ actionName,
2671
+ statusCode: 200,
2672
+ exception: null,
2673
+ durationMs: Date.now() - startMs,
2674
+ startedAt,
2675
+ args
2676
+ });
2677
+ throw e;
2678
+ }
2679
+ exception = e instanceof Error ? e : new Error(String(e));
2680
+ await maybeExtractSupabaseActor();
2681
+ await emitServerActionEvent({
2682
+ actionName,
2683
+ statusCode: 500,
2684
+ exception,
2526
2685
  durationMs: Date.now() - startMs,
2527
2686
  startedAt,
2528
2687
  args
2529
2688
  });
2530
2689
  throw e;
2690
+ } finally {
2691
+ if (isServerless()) {
2692
+ await flushScheduler.flushNow().catch(() => void 0);
2693
+ }
2531
2694
  }
2532
- exception = e instanceof Error ? e : new Error(String(e));
2533
- await maybeExtractSupabaseActor();
2534
- await emitServerActionEvent({
2535
- actionName,
2536
- statusCode: 500,
2537
- exception,
2538
- durationMs: Date.now() - startMs,
2539
- startedAt,
2540
- args
2541
- });
2542
- throw e;
2543
- } finally {
2544
- if (isServerless()) {
2545
- await flushScheduler.flushNow().catch(() => void 0);
2546
- }
2547
- }
2548
- })
2549
- );
2695
+ })
2696
+ );
2697
+ } catch (preCaptureError) {
2698
+ if (actionInvoked) throw preCaptureError;
2699
+ logger.warn(
2700
+ `captureServerAction pre-handler setup failed (${describeError7(preCaptureError)}); bypassing capture for this action`
2701
+ );
2702
+ return Promise.resolve(action(...args));
2703
+ }
2550
2704
  };
2551
2705
  }
2552
2706
  function captureServerActionExport(value, actionName) {
@@ -2907,59 +3061,59 @@ async function snapshotRequest(request) {
2907
3061
  }
2908
3062
  async function maybeRunActorHook(request) {
2909
3063
  const hook = configuration().actorFromRequest;
2910
- if (!hook) return;
2911
- try {
2912
- const result = await Promise.resolve(hook(request));
2913
- setActor(result ?? null);
2914
- } catch (error) {
2915
- logger.debug(`actorFromRequest hook failed: ${describeError7(error)}`);
3064
+ let hookResult = null;
3065
+ if (hook) {
3066
+ try {
3067
+ hookResult = await Promise.resolve(hook(request));
3068
+ } catch (error) {
3069
+ logger.debug(`actorFromRequest hook failed: ${describeError7(error)}`);
3070
+ }
2916
3071
  }
3072
+ const userAgent = safeGetHeader(request.headers, "user-agent");
3073
+ applyActorFromHookAndUa(hookResult, userAgent);
2917
3074
  }
2918
3075
  async function maybeRunActorHookFromPages(req) {
2919
3076
  const hook = configuration().actorFromRequest;
2920
- if (!hook) return;
2921
- try {
2922
- const result = await Promise.resolve(hook(req));
2923
- setActor(result ?? null);
2924
- } catch (error) {
2925
- logger.debug(`actorFromRequest hook (pages) failed: ${describeError7(error)}`);
3077
+ let hookResult = null;
3078
+ if (hook) {
3079
+ try {
3080
+ hookResult = await Promise.resolve(hook(req));
3081
+ } catch (error) {
3082
+ logger.debug(`actorFromRequest hook (pages) failed: ${describeError7(error)}`);
3083
+ }
2926
3084
  }
3085
+ const userAgent = readPagesHeader(req, "user-agent");
3086
+ applyActorFromHookAndUa(hookResult, userAgent);
2927
3087
  }
2928
3088
  async function maybeRunActorHookFromServerAction() {
2929
3089
  const hook = configuration().actorFromRequest;
2930
- if (!hook) {
2931
- logger.debug("actorFromRequest hook (server action): no hook configured");
2932
- return;
2933
- }
2934
3090
  const headers = await loadNextHeaders();
2935
- if (!headers) {
2936
- logger.debug(
2937
- "actorFromRequest hook (server action): skipped, no next/headers available"
2938
- );
3091
+ if (!hook && !headers) {
3092
+ logger.debug("actorFromRequest (server action): no hook + no next/headers");
2939
3093
  return;
2940
3094
  }
2941
- const facade = {
2942
- headers,
2943
- method: "POST",
2944
- url: ""
2945
- };
2946
- try {
2947
- const result = await Promise.resolve(hook(facade));
2948
- if (result) {
3095
+ let hookResult = null;
3096
+ if (hook) {
3097
+ if (!headers) {
2949
3098
  logger.debug(
2950
- `actorFromRequest hook (server action): set actor id=${result.id ?? "?"}`
3099
+ "actorFromRequest hook (server action): skipped, no next/headers available"
2951
3100
  );
2952
3101
  } else {
2953
- logger.debug(
2954
- "actorFromRequest hook (server action): returned null/undefined"
2955
- );
3102
+ const facade = { headers, method: "POST", url: "" };
3103
+ try {
3104
+ hookResult = await Promise.resolve(hook(facade));
3105
+ logger.debug(
3106
+ hookResult ? `actorFromRequest hook (server action): set actor id=${hookResult.id ?? "?"}` : "actorFromRequest hook (server action): returned null/undefined"
3107
+ );
3108
+ } catch (error) {
3109
+ logger.debug(
3110
+ `actorFromRequest hook (server action) failed: ${describeError7(error)}`
3111
+ );
3112
+ }
2956
3113
  }
2957
- setActor(result ?? null);
2958
- } catch (error) {
2959
- logger.debug(
2960
- `actorFromRequest hook (server action) failed: ${describeError7(error)}`
2961
- );
2962
3114
  }
3115
+ const userAgent = headers ? safeGetHeader(headers, "user-agent") : null;
3116
+ applyActorFromHookAndUa(hookResult, userAgent);
2963
3117
  }
2964
3118
  async function maybeExtractSupabaseActor() {
2965
3119
  const config = configuration();
@@ -3042,14 +3196,29 @@ async function readNextHeadersAsAdapter() {
3042
3196
  };
3043
3197
  }
3044
3198
  async function loadNextHeaders() {
3199
+ const mod = await tryLoadNextHeadersModule();
3200
+ if (!mod) return null;
3045
3201
  try {
3046
- const mod = await import('next/headers');
3047
3202
  return await Promise.resolve(mod.headers());
3048
3203
  } catch (error) {
3049
- logger.debug(`loadNextHeaders failed: ${describeError7(error)}`);
3204
+ logger.debug(`loadNextHeaders mod.headers() failed: ${describeError7(error)}`);
3050
3205
  return null;
3051
3206
  }
3052
3207
  }
3208
+ async function tryLoadNextHeadersModule() {
3209
+ try {
3210
+ return await import('next/headers');
3211
+ } catch (firstError) {
3212
+ try {
3213
+ return await import('next/headers.js');
3214
+ } catch (secondError) {
3215
+ logger.debug(
3216
+ `loadNextHeaders: neither "next/headers" nor "next/headers.js" resolved (${describeError7(firstError)}; ${describeError7(secondError)})`
3217
+ );
3218
+ return null;
3219
+ }
3220
+ }
3221
+ }
3053
3222
  function readPagesHeader(req, name) {
3054
3223
  const raw = req.headers;
3055
3224
  if (raw instanceof Headers) return raw.get(name);
@@ -3107,7 +3276,9 @@ async function emitEvent(input) {
3107
3276
  });
3108
3277
  pushEvent(event);
3109
3278
  } catch (error) {
3110
- logger.error(`http capture emit failed: ${describeError7(error)}`);
3279
+ const cid = current();
3280
+ const cidLabel = cid ? ` (correlation_id=${cid})` : "";
3281
+ logger.error(`http capture emit failed${cidLabel}: ${describeError7(error)}`);
3111
3282
  }
3112
3283
  }
3113
3284
  function buildContext2() {
@@ -3127,13 +3298,19 @@ async function takeTriggerAuditSnapshotIfEnabled() {
3127
3298
  await takeAuditSnapshot(config.databaseReader);
3128
3299
  }
3129
3300
  function runWithActorAndAuditScope(callback) {
3130
- if (!configuration().databaseSnapshotMode) {
3301
+ const config = configuration();
3302
+ const hasReader = config.databaseReader != null;
3303
+ const snapshotEnabled = config.databaseSnapshotMode;
3304
+ if (!hasReader) {
3131
3305
  return runWithActorScope(callback);
3132
3306
  }
3133
3307
  return runWithActorScope(
3134
- () => runWithAuditSnapshotScope(async () => {
3135
- await takeTriggerAuditSnapshotIfEnabled();
3136
- return callback();
3308
+ () => runWithEmittedAuditIdsScope(() => {
3309
+ if (!snapshotEnabled) return callback();
3310
+ return runWithAuditSnapshotScope(async () => {
3311
+ await takeTriggerAuditSnapshotIfEnabled();
3312
+ return callback();
3313
+ });
3137
3314
  })
3138
3315
  );
3139
3316
  }
@@ -3187,15 +3364,58 @@ function describeError7(error) {
3187
3364
  if (error instanceof Error) return `${error.name}: ${error.message}`;
3188
3365
  return String(error);
3189
3366
  }
3367
+ function applyActorFromHookAndUa(hookResult, userAgent) {
3368
+ const uaMatch = classifyUserAgent(userAgent);
3369
+ if (hookResult != null && typeof hookResult === "object" && !Array.isArray(hookResult)) {
3370
+ if (uaMatch === null) {
3371
+ setActor(hookResult);
3372
+ return;
3373
+ }
3374
+ const hookObj = hookResult;
3375
+ const existingKind = hookObj.kind;
3376
+ if (typeof existingKind === "string" && existingKind.length > 0) {
3377
+ setActor(hookObj);
3378
+ return;
3379
+ }
3380
+ setActor({ ...hookObj, kind: uaMatch.kind });
3381
+ return;
3382
+ }
3383
+ if (uaMatch !== null) {
3384
+ setActor(synthesizeAgentActor(uaMatch));
3385
+ return;
3386
+ }
3387
+ setActor(null);
3388
+ }
3389
+ function synthesizeAgentActor(detection) {
3390
+ return {
3391
+ id: detection.suggestedId,
3392
+ label: detection.label,
3393
+ kind: detection.kind
3394
+ };
3395
+ }
3396
+ function safeGetHeader(headers, name) {
3397
+ try {
3398
+ return headers.get(name);
3399
+ } catch {
3400
+ return null;
3401
+ }
3402
+ }
3190
3403
 
3191
3404
  // src/index.ts
3192
3405
  var initialized = false;
3193
- var beforeExitInstalled = false;
3406
+ var BEFORE_EXIT_INSTALLED_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:beforeExitInstalled");
3407
+ function isBeforeExitInstalled() {
3408
+ return globalThis[BEFORE_EXIT_INSTALLED_KEY] === true;
3409
+ }
3410
+ function markBeforeExitInstalled() {
3411
+ globalThis[BEFORE_EXIT_INSTALLED_KEY] = true;
3412
+ }
3194
3413
  var ezlogs = {
3195
3414
  init(options) {
3196
3415
  const config = configuration();
3197
3416
  config.apply(options);
3198
3417
  if (options.logLevel) setLogLevel(options.logLevel);
3418
+ warnIfInsecureServerUrl(config.serverUrl, config.allowInsecureTransport);
3199
3419
  flushScheduler.start();
3200
3420
  if (config.patchGlobalFetch) patchGlobalFetch();
3201
3421
  const resolvedDbUrl = options.databaseUrl ?? detectDatabaseUrlFromEnv();
@@ -3305,12 +3525,29 @@ function runTriggerTrackedTablesDetection() {
3305
3525
  });
3306
3526
  }
3307
3527
  function installBeforeExitHook() {
3308
- if (beforeExitInstalled) return;
3528
+ if (isBeforeExitInstalled()) return;
3309
3529
  if (typeof process === "undefined" || !process.on) return;
3310
3530
  process.on("beforeExit", () => {
3311
3531
  void flushScheduler.flushNow();
3312
3532
  });
3313
- beforeExitInstalled = true;
3533
+ markBeforeExitInstalled();
3534
+ }
3535
+ function warnIfInsecureServerUrl(serverUrl, allowInsecure) {
3536
+ if (!serverUrl || allowInsecure) return;
3537
+ let parsed;
3538
+ try {
3539
+ parsed = new URL(serverUrl);
3540
+ } catch {
3541
+ return;
3542
+ }
3543
+ if (parsed.protocol === "https:") return;
3544
+ const host = parsed.hostname.toLowerCase();
3545
+ if (host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1" || host.endsWith(".local")) {
3546
+ return;
3547
+ }
3548
+ console.warn(
3549
+ `[ezlogs] serverUrl is not HTTPS (${serverUrl}); events will be sent in cleartext. Set allowInsecureTransport: true to suppress this warning.`
3550
+ );
3314
3551
  }
3315
3552
  function _internalsForTests() {
3316
3553
  return { buffer: buffer_exports, flushScheduler };