ezlogs-nextjs 0.3.1 → 0.4.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 (76) hide show
  1. package/README.md +149 -30
  2. package/bin/install-triggers.cjs +7 -2
  3. package/dist/actors/index.cjs +4 -4
  4. package/dist/actors/index.d.cts +1 -1
  5. package/dist/actors/index.d.ts +1 -1
  6. package/dist/actors/index.js +1 -1
  7. package/dist/{chunk-C5OSM557.js → chunk-FCFVIRQF.js} +7 -0
  8. package/dist/chunk-GI6BM4MR.js +443 -0
  9. package/dist/{chunk-YX2XPLOA.cjs → chunk-GMHOUAKD.cjs} +63 -34
  10. package/dist/{chunk-CU45I2WR.js → chunk-MHBS5FEP.js} +48 -20
  11. package/dist/chunk-MMLQXSSD.cjs +461 -0
  12. package/dist/{chunk-CE3R7DVB.js → chunk-NINIAL7M.js} +60 -384
  13. package/dist/{chunk-Y5NSHKWQ.cjs → chunk-NX4EL7BY.cjs} +57 -7
  14. package/dist/chunk-PS4U2GFJ.cjs +52 -0
  15. package/dist/chunk-R6IWVTX3.cjs +212 -0
  16. package/dist/{chunk-V5YNKKTG.cjs → chunk-TWTG5ILJ.cjs} +7 -0
  17. package/dist/chunk-U22T7QYY.js +200 -0
  18. package/dist/chunk-YMIGZYFH.js +48 -0
  19. package/dist/{chunk-WASXTDLW.cjs → chunk-YXZZNZG6.cjs} +71 -403
  20. package/dist/{chunk-DKRNNI4I.js → chunk-Z2TM3LGG.js} +53 -3
  21. package/dist/{configuration-OHLNivON.d.ts → configuration-CJ5yKVlP.d.cts} +14 -8
  22. package/dist/{configuration-OHLNivON.d.cts → configuration-CJ5yKVlP.d.ts} +14 -8
  23. package/dist/db/drizzle.cjs +5 -4
  24. package/dist/db/drizzle.js +3 -2
  25. package/dist/db/postgres-js.cjs +98 -0
  26. package/dist/db/postgres-js.d.cts +11 -0
  27. package/dist/db/postgres-js.d.ts +11 -0
  28. package/dist/db/postgres-js.js +95 -0
  29. package/dist/db/prisma.cjs +21 -20
  30. package/dist/db/prisma.d.cts +19 -2
  31. package/dist/db/prisma.d.ts +19 -2
  32. package/dist/db/prisma.js +6 -5
  33. package/dist/db/supabase.cjs +19 -12
  34. package/dist/db/supabase.d.cts +3 -2
  35. package/dist/db/supabase.d.ts +3 -2
  36. package/dist/db/supabase.js +11 -4
  37. package/dist/index.cjs +596 -165
  38. package/dist/index.d.cts +5 -3
  39. package/dist/index.d.ts +5 -3
  40. package/dist/index.js +492 -62
  41. package/dist/jobs/bullmq.cjs +63 -18
  42. package/dist/jobs/bullmq.d.cts +0 -4
  43. package/dist/jobs/bullmq.d.ts +0 -4
  44. package/dist/jobs/bullmq.js +59 -14
  45. package/dist/jobs/inngest.cjs +61 -24
  46. package/dist/jobs/inngest.d.cts +5 -1
  47. package/dist/jobs/inngest.d.ts +5 -1
  48. package/dist/jobs/inngest.js +55 -18
  49. package/dist/jobs/supabase-queues.cjs +17 -15
  50. package/dist/jobs/supabase-queues.d.cts +1 -1
  51. package/dist/jobs/supabase-queues.d.ts +1 -1
  52. package/dist/jobs/supabase-queues.js +15 -13
  53. package/dist/jobs/trigger.cjs +11 -12
  54. package/dist/jobs/trigger.d.cts +4 -3
  55. package/dist/jobs/trigger.d.ts +4 -3
  56. package/dist/jobs/trigger.js +7 -8
  57. package/dist/jobs/upstash-workflow.cjs +43 -35
  58. package/dist/jobs/upstash-workflow.d.cts +2 -8
  59. package/dist/jobs/upstash-workflow.d.ts +2 -8
  60. package/dist/jobs/upstash-workflow.js +38 -30
  61. package/dist/nextjs-plugin/index.cjs +39 -3
  62. package/dist/nextjs-plugin/index.d.cts +8 -1
  63. package/dist/nextjs-plugin/index.d.ts +8 -1
  64. package/dist/nextjs-plugin/index.js +39 -3
  65. package/dist/nextjs-plugin/loader.cjs +41 -3
  66. package/dist/nextjs-plugin/loader.d.cts +1 -0
  67. package/dist/nextjs-plugin/loader.d.ts +1 -0
  68. package/dist/nextjs-plugin/loader.js +42 -4
  69. package/dist/triggers/index.cjs +145 -92
  70. package/dist/triggers/index.d.cts +20 -5
  71. package/dist/triggers/index.d.ts +20 -5
  72. package/dist/triggers/index.js +125 -82
  73. package/package.json +11 -1
  74. package/sql/postgres/00_install.sql +1 -1
  75. package/dist/chunk-UQHEW6ER.js +0 -119
  76. package/dist/chunk-UWHYJH4M.cjs +0 -126
@@ -5,7 +5,7 @@ interface ParsedArgs {
5
5
  * Auto-detect mode. True when the user passes no `--tables=` flag or
6
6
  * explicitly passes `--tables=auto`. The CLI then introspects
7
7
  * `information_schema` and tracks every business table in the public
8
- * schema, minus a built-in infrastructure skip list.
8
+ * schema, minus the skip rules in `skipReason`.
9
9
  */
10
10
  autoTables: boolean;
11
11
  print: boolean;
@@ -23,6 +23,10 @@ type Detected = {
23
23
  };
24
24
  declare function detectEngine(connection: string | null): Detected;
25
25
  declare function buildTrackingSql(tables: string[], engine: "postgres" | "mysql"): string;
26
+ type DiscoveredRow = {
27
+ table_name: string;
28
+ has_auth_columns?: boolean;
29
+ };
26
30
  interface RunOptions {
27
31
  /** Async exec — caller passes a function that runs SQL against their DB. */
28
32
  exec?: (sql: string) => Promise<unknown>;
@@ -33,9 +37,7 @@ interface RunOptions {
33
37
  * with `pg.Client.prototype.query`.
34
38
  */
35
39
  query?: (sql: string) => Promise<{
36
- rows: Array<{
37
- table_name: string;
38
- }>;
40
+ rows: DiscoveredRow[];
39
41
  }>;
40
42
  /** Output sink. Defaults to console.log. Tests inject. */
41
43
  out?: (line: string) => void;
@@ -47,6 +49,10 @@ interface RunOptions {
47
49
  */
48
50
  declare function runInstall(args: ParsedArgs, options?: RunOptions): Promise<number>;
49
51
 
52
+ type Env = Record<string, string | undefined>;
53
+ /** Load env files from `dir` into `env`. Returns the file names loaded. */
54
+ declare function loadEnvFiles(dir: string, env?: Env): string[];
55
+
50
56
  /**
51
57
  * Minimal SQL executor shape. Anything that can `await fn(sql, params)`
52
58
  * works — we deliberately don't depend on any specific driver type.
@@ -139,6 +145,8 @@ interface AuditRow {
139
145
  txid?: string | null;
140
146
  /** When the trigger fired — becomes the event timestamp. */
141
147
  captured_at?: Date | null;
148
+ /** Actor id the writer set (`ezlogs.actor_id`), null when none. */
149
+ actor_id?: string | null;
142
150
  }
143
151
  /**
144
152
  * Claim (delete + return) the audit rows tagged with `correlationId`,
@@ -228,8 +236,15 @@ interface PgClientCtor {
228
236
  _ezlogsPatched?: boolean;
229
237
  };
230
238
  }
239
+ interface PgPoolCtor {
240
+ prototype: {
241
+ connect?: Function;
242
+ _ezlogsPoolPatched?: boolean;
243
+ };
244
+ }
231
245
  interface PgModule {
232
246
  Client: PgClientCtor;
247
+ Pool?: PgPoolCtor;
233
248
  }
234
249
  /**
235
250
  * Patch `pg.Client.prototype.query` to inject SET LOCAL for the
@@ -242,4 +257,4 @@ interface PgModule {
242
257
  */
243
258
  declare function patchPgClient(pgModule: PgModule): void;
244
259
 
245
- export { type AuditRow, type DatabaseContextSnapshot, type Detected, type PgLikeClient, type SqlExecutor, applyDatabaseContext, buildTrackingSql, detectEngine, detectTriggerTrackedTables, emitAuditRows, flushAuditLog, getDatabaseContext, parseArgs, patchPgClient, pruneAuditLog, readAuditRows, runInstall, sweepAuditLog, withDatabaseContext };
260
+ export { type AuditRow, type DatabaseContextSnapshot, type Detected, type PgLikeClient, type SqlExecutor, applyDatabaseContext, buildTrackingSql, detectEngine, detectTriggerTrackedTables, emitAuditRows, flushAuditLog, getDatabaseContext, loadEnvFiles, parseArgs, patchPgClient, pruneAuditLog, readAuditRows, runInstall, sweepAuditLog, withDatabaseContext };
@@ -5,7 +5,7 @@ interface ParsedArgs {
5
5
  * Auto-detect mode. True when the user passes no `--tables=` flag or
6
6
  * explicitly passes `--tables=auto`. The CLI then introspects
7
7
  * `information_schema` and tracks every business table in the public
8
- * schema, minus a built-in infrastructure skip list.
8
+ * schema, minus the skip rules in `skipReason`.
9
9
  */
10
10
  autoTables: boolean;
11
11
  print: boolean;
@@ -23,6 +23,10 @@ type Detected = {
23
23
  };
24
24
  declare function detectEngine(connection: string | null): Detected;
25
25
  declare function buildTrackingSql(tables: string[], engine: "postgres" | "mysql"): string;
26
+ type DiscoveredRow = {
27
+ table_name: string;
28
+ has_auth_columns?: boolean;
29
+ };
26
30
  interface RunOptions {
27
31
  /** Async exec — caller passes a function that runs SQL against their DB. */
28
32
  exec?: (sql: string) => Promise<unknown>;
@@ -33,9 +37,7 @@ interface RunOptions {
33
37
  * with `pg.Client.prototype.query`.
34
38
  */
35
39
  query?: (sql: string) => Promise<{
36
- rows: Array<{
37
- table_name: string;
38
- }>;
40
+ rows: DiscoveredRow[];
39
41
  }>;
40
42
  /** Output sink. Defaults to console.log. Tests inject. */
41
43
  out?: (line: string) => void;
@@ -47,6 +49,10 @@ interface RunOptions {
47
49
  */
48
50
  declare function runInstall(args: ParsedArgs, options?: RunOptions): Promise<number>;
49
51
 
52
+ type Env = Record<string, string | undefined>;
53
+ /** Load env files from `dir` into `env`. Returns the file names loaded. */
54
+ declare function loadEnvFiles(dir: string, env?: Env): string[];
55
+
50
56
  /**
51
57
  * Minimal SQL executor shape. Anything that can `await fn(sql, params)`
52
58
  * works — we deliberately don't depend on any specific driver type.
@@ -139,6 +145,8 @@ interface AuditRow {
139
145
  txid?: string | null;
140
146
  /** When the trigger fired — becomes the event timestamp. */
141
147
  captured_at?: Date | null;
148
+ /** Actor id the writer set (`ezlogs.actor_id`), null when none. */
149
+ actor_id?: string | null;
142
150
  }
143
151
  /**
144
152
  * Claim (delete + return) the audit rows tagged with `correlationId`,
@@ -228,8 +236,15 @@ interface PgClientCtor {
228
236
  _ezlogsPatched?: boolean;
229
237
  };
230
238
  }
239
+ interface PgPoolCtor {
240
+ prototype: {
241
+ connect?: Function;
242
+ _ezlogsPoolPatched?: boolean;
243
+ };
244
+ }
231
245
  interface PgModule {
232
246
  Client: PgClientCtor;
247
+ Pool?: PgPoolCtor;
233
248
  }
234
249
  /**
235
250
  * Patch `pg.Client.prototype.query` to inject SET LOCAL for the
@@ -242,4 +257,4 @@ interface PgModule {
242
257
  */
243
258
  declare function patchPgClient(pgModule: PgModule): void;
244
259
 
245
- export { type AuditRow, type DatabaseContextSnapshot, type Detected, type PgLikeClient, type SqlExecutor, applyDatabaseContext, buildTrackingSql, detectEngine, detectTriggerTrackedTables, emitAuditRows, flushAuditLog, getDatabaseContext, parseArgs, patchPgClient, pruneAuditLog, readAuditRows, runInstall, sweepAuditLog, withDatabaseContext };
260
+ export { type AuditRow, type DatabaseContextSnapshot, type Detected, type PgLikeClient, type SqlExecutor, applyDatabaseContext, buildTrackingSql, detectEngine, detectTriggerTrackedTables, emitAuditRows, flushAuditLog, getDatabaseContext, loadEnvFiles, parseArgs, patchPgClient, pruneAuditLog, readAuditRows, runInstall, sweepAuditLog, withDatabaseContext };
@@ -1,11 +1,15 @@
1
- export { patchPgClient } from '../chunk-DKRNNI4I.js';
2
- export { detectTriggerTrackedTables, emitAuditRows, flushAuditLog, pruneAuditLog, readAuditRows, sweepAuditLog } from '../chunk-CU45I2WR.js';
3
- import { DEFAULT_EXCLUDED_TABLES, getCurrentActor, current } from '../chunk-CE3R7DVB.js';
4
- import { logger } from '../chunk-C5OSM557.js';
1
+ export { patchPgClient } from '../chunk-Z2TM3LGG.js';
2
+ export { applyDatabaseContext, getDatabaseContext, withDatabaseContext } from '../chunk-YMIGZYFH.js';
3
+ export { detectTriggerTrackedTables, emitAuditRows, flushAuditLog, pruneAuditLog, readAuditRows, sweepAuditLog } from '../chunk-MHBS5FEP.js';
4
+ import '../chunk-NINIAL7M.js';
5
+ import { AUTH_SESSION_TABLE_NAMES } from '../chunk-GI6BM4MR.js';
6
+ import { logger } from '../chunk-FCFVIRQF.js';
5
7
  import '../chunk-SIAA4J6H.js';
6
8
  import { readFile } from 'fs/promises';
7
9
  import { dirname, join } from 'path';
8
10
  import { fileURLToPath } from 'url';
11
+ import { readFileSync } from 'fs';
12
+ import { createRequire } from 'module';
9
13
 
10
14
  var HERE = dirname(fileURLToPath(import.meta.url));
11
15
  function parseArgs(argv) {
@@ -46,12 +50,14 @@ Usage:
46
50
 
47
51
  Options:
48
52
  --connection=<url> Database connection string. Defaults to DATABASE_URL
49
- or POSTGRES_URL from the environment.
53
+ or POSTGRES_URL from the environment (.env, .env.local
54
+ and .env.[mode] are loaded the way Next.js loads them).
50
55
  --tables=<a,b,c> Comma-separated list of tables to attach the audit
51
56
  trigger to. Idempotent \u2014 re-runnable.
52
57
  --tables=auto DEFAULT. Introspect information_schema and track every
53
- business table in the public schema, minus a built-in
54
- infrastructure skip list (migrations, sessions, etc.).
58
+ business table in the public schema, minus migrations,
59
+ internals and auth-session tables (each skipped table
60
+ is listed with the reason).
55
61
  --tables=none Install infrastructure only; track no tables.
56
62
  Use this when you want full manual control.
57
63
  --print Print the SQL that would be applied; do not run it.
@@ -99,38 +105,44 @@ function escapeSqlIdentifier(name) {
99
105
  }
100
106
  return name;
101
107
  }
102
- var TRIGGER_INSTALL_SKIP_PATTERNS = [
103
- ...DEFAULT_EXCLUDED_TABLES,
108
+ var NAMED_SKIPS = [
104
109
  // Our own audit table — trigger on the audit table would be a loop.
105
- "ezlogs_audit_log",
110
+ ["ezlogs_audit_log", "EZLogs audit log"],
111
+ ["_prisma_migrations", "migration history"],
112
+ ["schema_migrations", "migration history"],
113
+ ["ar_internal_metadata", "Rails internals"],
106
114
  // Postgres internals (won't be in public schema, but defensive).
107
- /^pg_/,
108
- /^_litestream/,
109
- // Solid Queue / Solid Cache / Solid Cable (Rails 8 default infra
110
- // tables — show up in apps that share a database with Rails).
111
- /^solid_(queue|cache|cable)/,
112
- // ActiveStorage (same).
113
- /^active_storage_/,
114
- // ActiveRecord internals.
115
- "ar_internal_metadata",
116
- "schema_migrations"
115
+ [/^pg_/, "database internals"],
116
+ [/^_litestream/, "database internals"],
117
+ // Rails 8 infra tables, in apps that share a database with Rails.
118
+ [/^solid_(queue|cache|cable)/, "Rails infrastructure"],
119
+ [/^active_storage_/, "Rails infrastructure"]
117
120
  ];
118
- function shouldSkipTable(tableName) {
119
- for (const pattern of TRIGGER_INSTALL_SKIP_PATTERNS) {
120
- if (typeof pattern === "string") {
121
- if (tableName === pattern) return true;
122
- } else if (pattern.test(tableName)) {
123
- return true;
124
- }
121
+ function skipReason(tableName, hasAuthColumns) {
122
+ for (const [pattern, reason] of NAMED_SKIPS) {
123
+ if (typeof pattern === "string" ? tableName === pattern : pattern.test(tableName)) return reason;
124
+ }
125
+ if (AUTH_SESSION_TABLE_NAMES.test(tableName) && (hasAuthColumns !== false || /verif/i.test(tableName))) {
126
+ return "auth / session store (has token, expiry or session-data columns)";
125
127
  }
126
- return false;
128
+ return null;
127
129
  }
128
130
  var DISCOVER_TABLES_SQL = `
129
- SELECT table_name
130
- FROM information_schema.tables
131
- WHERE table_schema = 'public'
132
- AND table_type = 'BASE TABLE'
133
- ORDER BY table_name
131
+ SELECT t.table_name,
132
+ EXISTS (
133
+ SELECT 1 FROM information_schema.columns c
134
+ WHERE c.table_schema = t.table_schema
135
+ AND c.table_name = t.table_name
136
+ AND (
137
+ c.column_name ILIKE '%token%'
138
+ OR c.column_name ILIKE '%expir%'
139
+ OR lower(replace(c.column_name, '_', '')) IN ('sess', 'data', 'payload', 'lastactivity')
140
+ )
141
+ ) AS has_auth_columns
142
+ FROM information_schema.tables t
143
+ WHERE t.table_schema = 'public'
144
+ AND t.table_type = 'BASE TABLE'
145
+ ORDER BY t.table_name
134
146
  `.trim();
135
147
  async function runInstall(args, options = {}) {
136
148
  const out = options.out ?? ((line) => {
@@ -182,16 +194,17 @@ ${trackingSql}
182
194
  return 1;
183
195
  }
184
196
  let tablesToTrack;
185
- let skippedTables = [];
197
+ const skippedTables = [];
186
198
  if (args.autoTables) {
187
- if (!options.query) {
188
- tablesToTrack = [];
189
- } else {
199
+ tablesToTrack = [];
200
+ if (options.query) {
190
201
  try {
191
202
  const result = await options.query(DISCOVER_TABLES_SQL);
192
- const all = result.rows.map((r) => r.table_name);
193
- tablesToTrack = all.filter((name) => !shouldSkipTable(name));
194
- skippedTables = all.filter((name) => shouldSkipTable(name));
203
+ for (const row of result.rows) {
204
+ const reason = skipReason(row.table_name, row.has_auth_columns);
205
+ if (reason) skippedTables.push({ table: row.table_name, reason });
206
+ else tablesToTrack.push(row.table_name);
207
+ }
195
208
  } catch (error) {
196
209
  out(
197
210
  `[ezlogs] Could not introspect tables: ${error instanceof Error ? error.message : String(error)}. Pass --tables=<a,b,c> for explicit tracking.`
@@ -225,11 +238,15 @@ ${trackingSql}
225
238
  out(
226
239
  `[ezlogs] Postgres triggers installed. Tracking ${tablesToTrack.length} table(s): ${tablesToTrack.join(", ")}.`
227
240
  );
228
- if (skippedTables.length > 0) {
229
- out(
230
- `[ezlogs] Skipped ${skippedTables.length} infrastructure table(s) (migrations, sessions, etc.): ${skippedTables.join(", ")}. Track any of them manually with \`SELECT ezlogs_track('foo')\`.`
231
- );
232
- }
241
+ out(
242
+ "[ezlogs] Records are named by their name / title / number / label column. To name people's records (users, members), set `displayNameFor` in ezlogs.init (README: Name your records)."
243
+ );
244
+ }
245
+ if (skippedTables.length > 0) {
246
+ out(
247
+ `[ezlogs] Skipped ${skippedTables.length} table(s):
248
+ ` + skippedTables.map((s) => ` - ${s.table}: ${s.reason}`).join("\n") + "\n Track any of them with `SELECT ezlogs_track('table_name')`."
249
+ );
233
250
  }
234
251
  return 0;
235
252
  } catch (error) {
@@ -239,49 +256,75 @@ ${trackingSql}
239
256
  return 1;
240
257
  }
241
258
  }
242
-
243
- // src/triggers/context.ts
244
- function getDatabaseContext() {
245
- const actor = getCurrentActor();
246
- return {
247
- actorId: actor && actor.id ? actor.id : null,
248
- correlationId: current()
249
- };
250
- }
251
- async function applyDatabaseContext(exec) {
252
- const actor = getCurrentActor();
253
- const correlationId = current();
254
- if (!actor && !correlationId) return;
259
+ function loadEnvFiles(dir, env = process.env) {
260
+ const dev = env.NODE_ENV !== "production";
255
261
  try {
256
- if (actor && actor.id) {
257
- await exec(`SELECT set_config('ezlogs.actor_id', $1, true)`, [actor.id]);
262
+ const nextEnv = createRequire(join(dir, "package.json"))("@next/env");
263
+ if (env === process.env) {
264
+ const { loadedEnvFiles = [] } = nextEnv.loadEnvConfig(dir, dev, {
265
+ info: () => {
266
+ },
267
+ error: () => {
268
+ }
269
+ });
270
+ return loadedEnvFiles.map((f) => f.path);
258
271
  }
259
- if (correlationId) {
260
- await exec(
261
- `SELECT set_config('ezlogs.correlation_id', $1, true)`,
262
- [correlationId]
263
- );
264
- }
265
- } catch (err) {
266
- logger.debug(
267
- `applyDatabaseContext: set_config failed, continuing without context: ${err instanceof Error ? err.message : String(err)}`
268
- );
272
+ } catch {
269
273
  }
270
- }
271
- async function withDatabaseContext(client, callback) {
272
- await client.query("BEGIN");
273
- try {
274
- await applyDatabaseContext(async (sql, params) => client.query(sql, params));
275
- const result = await callback(client);
276
- await client.query("COMMIT");
277
- return result;
278
- } catch (err) {
274
+ const mode = env.NODE_ENV === "test" ? "test" : dev ? "development" : "production";
275
+ const files = [`.env.${mode}.local`, ...mode === "test" ? [] : [".env.local"], `.env.${mode}`, ".env"];
276
+ const loaded = [];
277
+ const parsed = {};
278
+ for (const file of files) {
279
+ let text;
279
280
  try {
280
- await client.query("ROLLBACK");
281
+ text = readFileSync(join(dir, file), "utf8");
281
282
  } catch {
283
+ continue;
284
+ }
285
+ loaded.push(file);
286
+ for (const [key, value] of Object.entries(parseEnvEntries(text))) {
287
+ if (!(key in parsed)) parsed[key] = value;
282
288
  }
283
- throw err;
284
289
  }
290
+ const resolving = /* @__PURE__ */ new Set();
291
+ const resolve = (key) => {
292
+ if (env[key] !== void 0) return env[key];
293
+ const entry = parsed[key];
294
+ if (!entry || resolving.has(key)) return void 0;
295
+ resolving.add(key);
296
+ const value = entry.expand ? expand(entry.value, resolve) : entry.value;
297
+ resolving.delete(key);
298
+ return value;
299
+ };
300
+ for (const key of Object.keys(parsed)) {
301
+ if (env[key] === void 0) env[key] = resolve(key);
302
+ }
303
+ return loaded;
304
+ }
305
+ function expand(value, lookup) {
306
+ return value.replace(
307
+ /\\\$|\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-([^}]*))?\}|\$([A-Za-z_][A-Za-z0-9_]*)/g,
308
+ (match, braced, fallback, bare) => {
309
+ if (match === "\\$") return "$";
310
+ const found = lookup(braced ?? bare);
311
+ return found !== void 0 && found !== "" ? found : fallback ?? "";
312
+ }
313
+ );
314
+ }
315
+ var LINE = /^\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?$/gm;
316
+ function parseEnvEntries(text) {
317
+ const out = {};
318
+ const src = text.replace(/\r\n?/g, "\n");
319
+ for (const match of src.matchAll(LINE)) {
320
+ let value = (match[2] ?? "").trim();
321
+ const quote = value[0];
322
+ const quoted = (quote === '"' || quote === "'" || quote === "`") && value.endsWith(quote) && value.length > 1;
323
+ if (quoted) value = value.slice(1, -1);
324
+ if (quote === '"' && quoted) value = value.replace(/\\n/g, "\n").replace(/\\r/g, "\r");
325
+ out[match[1]] = { value, expand: !(quoted && quote === "'") };
326
+ }
327
+ return out;
285
328
  }
286
329
 
287
- export { applyDatabaseContext, buildTrackingSql, detectEngine, getDatabaseContext, parseArgs, runInstall, withDatabaseContext };
330
+ export { buildTrackingSql, detectEngine, loadEnvFiles, parseArgs, runInstall };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ezlogs-nextjs",
3
- "version": "0.3.1",
3
+ "version": "0.4.2",
4
4
  "description": "EZLogs agent for Next.js — capture HTTP, database, and background-job events as plain-English Action cards.",
5
5
  "license": "MIT",
6
6
  "author": "EZLogs",
@@ -43,6 +43,11 @@
43
43
  "import": "./dist/db/drizzle.js",
44
44
  "require": "./dist/db/drizzle.cjs"
45
45
  },
46
+ "./postgres": {
47
+ "types": "./dist/db/postgres-js.d.ts",
48
+ "import": "./dist/db/postgres-js.js",
49
+ "require": "./dist/db/postgres-js.cjs"
50
+ },
46
51
  "./supabase": {
47
52
  "types": "./dist/db/supabase.d.ts",
48
53
  "import": "./dist/db/supabase.js",
@@ -142,9 +147,14 @@
142
147
  "@prisma/client": "^5.22.0",
143
148
  "@types/node": "^20.11.0",
144
149
  "@types/pg": "^8.20.0",
150
+ "@upstash/qstash": "^2.12.2",
145
151
  "@upstash/workflow": "^1.3.3",
146
152
  "bullmq": "^5.76.10",
153
+ "drizzle-orm": "^0.43.1",
147
154
  "pg": "^8.20.0",
155
+ "pg-cursor": "^2.22.1",
156
+ "pg-query-stream": "^4.17.1",
157
+ "postgres": "^3.4.9",
148
158
  "prisma": "^5.22.0",
149
159
  "sucrase": "^3.35.0",
150
160
  "tsup": "^8.0.2",
@@ -67,7 +67,7 @@ CREATE INDEX IF NOT EXISTS ezlogs_audit_log_correlation_idx
67
67
  WHERE correlation_id IS NOT NULL;
68
68
 
69
69
  -- Secondary index for the agent's retention sweep (rows older than
70
- -- 5 minutes are drained, rows older than 24 hours are deleted).
70
+ -- 5 minutes are drained, rows older than 7 days are deleted).
71
71
  CREATE INDEX IF NOT EXISTS ezlogs_audit_log_captured_at_idx
72
72
  ON public.ezlogs_audit_log (captured_at);
73
73
 
@@ -1,119 +0,0 @@
1
- import { flushAuditLog } from './chunk-CU45I2WR.js';
2
- import { configuration, build, current, pushEvent, generate, runWithCorrelation, sanitizeArgs } from './chunk-CE3R7DVB.js';
3
- import { logger } from './chunk-C5OSM557.js';
4
-
5
- // src/jobs/shared.ts
6
- var CORRELATION_PAYLOAD_KEY = "ezlogs_correlation_id";
7
- function emitJobEvent(input) {
8
- try {
9
- const config = configuration();
10
- if (!config.captureJobs) return;
11
- if (config.allExcludedJobClasses().includes(input.jobClass)) return;
12
- const sourceData = compactJobSourceData({
13
- job_class: input.jobClass,
14
- job_id: input.jobId ?? null,
15
- queue: input.queue ?? null,
16
- retry_count: input.retryCount ?? null,
17
- arguments: jobArguments(input.payload)
18
- });
19
- const event = build({
20
- source_type: "background_job",
21
- source_data: sourceData,
22
- outcome: input.outcome,
23
- correlation_id: input.correlationId ?? current(),
24
- resource_ids: [],
25
- context: null,
26
- duration_ms: input.durationMs ?? null,
27
- error_message: input.errorMessage ?? null,
28
- timestamp: input.startedAt
29
- });
30
- pushEvent(event);
31
- } catch (error) {
32
- logger.debug(`job emit failed: ${describeError(error)}`);
33
- }
34
- }
35
- async function runJobWithCapture(meta, work) {
36
- const correlationId = meta.correlationId ?? generate();
37
- return runWithCorrelation(correlationId, async () => {
38
- const startedAt = /* @__PURE__ */ new Date();
39
- const startMs = startedAt.getTime();
40
- const baseMeta = {
41
- jobClass: meta.jobClass,
42
- jobId: meta.jobId ?? null,
43
- queue: meta.queue ?? null,
44
- retryCount: meta.retryCount ?? null,
45
- correlationId,
46
- startedAt,
47
- payload: meta.payload
48
- };
49
- try {
50
- const result = await work();
51
- await flushJobAuditLog(startedAt);
52
- emitJobEvent({
53
- ...baseMeta,
54
- outcome: "success",
55
- durationMs: Date.now() - startMs
56
- });
57
- return result;
58
- } catch (error) {
59
- const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
60
- await flushJobAuditLog(startedAt);
61
- if (meta.isControlFlow?.(error)) throw error;
62
- emitJobEvent({
63
- ...baseMeta,
64
- outcome: "failure",
65
- errorMessage: message,
66
- durationMs: Date.now() - startMs
67
- });
68
- throw error;
69
- }
70
- });
71
- }
72
- var JOB_FLUSH_SKEW_MS = 500;
73
- async function flushJobAuditLog(startedAt) {
74
- try {
75
- await flushAuditLog(configuration().databaseReader, {
76
- since: new Date(startedAt.getTime() - JOB_FLUSH_SKEW_MS)
77
- });
78
- } catch (error) {
79
- logger.debug(`job audit flush failed: ${describeError(error)}`);
80
- }
81
- }
82
- function jobArguments(payload) {
83
- if (payload === null || payload === void 0) return null;
84
- const patterns = configuration().excludedGraphqlVariableKeys;
85
- if (Array.isArray(payload)) return payload.length === 0 ? null : sanitizeArgs(payload, patterns);
86
- if (typeof payload === "object" && Object.getPrototypeOf(payload) === Object.prototype) {
87
- const rest = { ...payload };
88
- delete rest[CORRELATION_PAYLOAD_KEY];
89
- if (Object.keys(rest).length === 0) return null;
90
- return sanitizeArgs([rest], patterns)[0];
91
- }
92
- return sanitizeArgs([payload], patterns);
93
- }
94
- function extractCorrelationFromPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
95
- if (payload === null || typeof payload !== "object") return null;
96
- const value = payload[key];
97
- return typeof value === "string" && value.length > 0 ? value : null;
98
- }
99
- function stampCorrelationOnPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
100
- if (!payload || typeof payload !== "object") return;
101
- if (typeof payload[key] === "string" && payload[key]) return;
102
- const id = current();
103
- if (!id) return;
104
- payload[key] = id;
105
- }
106
- function compactJobSourceData(data) {
107
- const out = {};
108
- for (const key of Object.keys(data)) {
109
- const value = data[key];
110
- if (value !== null && value !== void 0) out[key] = value;
111
- }
112
- return out;
113
- }
114
- function describeError(error) {
115
- if (error instanceof Error) return `${error.name}: ${error.message}`;
116
- return String(error);
117
- }
118
-
119
- export { CORRELATION_PAYLOAD_KEY, emitJobEvent, extractCorrelationFromPayload, flushJobAuditLog, runJobWithCapture, stampCorrelationOnPayload };