ezlogs-nextjs 0.1.0
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.
- package/LICENSE +21 -0
- package/README.md +779 -0
- package/bin/install-triggers.cjs +75 -0
- package/dist/actors/index.cjs +111 -0
- package/dist/actors/index.d.cts +52 -0
- package/dist/actors/index.d.ts +52 -0
- package/dist/actors/index.js +107 -0
- package/dist/configuration-D9x9Gvds.d.cts +190 -0
- package/dist/configuration-D9x9Gvds.d.ts +190 -0
- package/dist/db/drizzle.cjs +898 -0
- package/dist/db/drizzle.d.cts +68 -0
- package/dist/db/drizzle.d.ts +68 -0
- package/dist/db/drizzle.js +893 -0
- package/dist/db/prisma.cjs +826 -0
- package/dist/db/prisma.d.cts +3 -0
- package/dist/db/prisma.d.ts +3 -0
- package/dist/db/prisma.js +824 -0
- package/dist/db/supabase.cjs +1027 -0
- package/dist/db/supabase.d.cts +32 -0
- package/dist/db/supabase.d.ts +32 -0
- package/dist/db/supabase.js +1024 -0
- package/dist/index.cjs +3329 -0
- package/dist/index.d.cts +305 -0
- package/dist/index.d.ts +305 -0
- package/dist/index.js +3317 -0
- package/dist/jobs/bullmq.cjs +624 -0
- package/dist/jobs/bullmq.d.cts +33 -0
- package/dist/jobs/bullmq.d.ts +33 -0
- package/dist/jobs/bullmq.js +621 -0
- package/dist/jobs/inngest.cjs +645 -0
- package/dist/jobs/inngest.d.cts +21 -0
- package/dist/jobs/inngest.d.ts +21 -0
- package/dist/jobs/inngest.js +642 -0
- package/dist/jobs/supabase-queues.cjs +661 -0
- package/dist/jobs/supabase-queues.d.cts +37 -0
- package/dist/jobs/supabase-queues.d.ts +37 -0
- package/dist/jobs/supabase-queues.js +657 -0
- package/dist/jobs/trigger.cjs +622 -0
- package/dist/jobs/trigger.d.cts +46 -0
- package/dist/jobs/trigger.d.ts +46 -0
- package/dist/jobs/trigger.js +619 -0
- package/dist/jobs/upstash-workflow.cjs +673 -0
- package/dist/jobs/upstash-workflow.d.cts +57 -0
- package/dist/jobs/upstash-workflow.d.ts +57 -0
- package/dist/jobs/upstash-workflow.js +669 -0
- package/dist/nextjs-plugin/index.cjs +232 -0
- package/dist/nextjs-plugin/index.d.cts +68 -0
- package/dist/nextjs-plugin/index.d.ts +68 -0
- package/dist/nextjs-plugin/index.js +229 -0
- package/dist/nextjs-plugin/loader.cjs +16248 -0
- package/dist/nextjs-plugin/loader.d.cts +61 -0
- package/dist/nextjs-plugin/loader.d.ts +61 -0
- package/dist/nextjs-plugin/loader.js +16242 -0
- package/dist/triggers/index.cjs +1354 -0
- package/dist/triggers/index.d.cts +243 -0
- package/dist/triggers/index.d.ts +243 -0
- package/dist/triggers/index.js +1337 -0
- package/package.json +150 -0
- package/sql/postgres/00_install.sql +205 -0
|
@@ -0,0 +1,1337 @@
|
|
|
1
|
+
import { readFile } from 'fs/promises';
|
|
2
|
+
import { dirname, join } from 'path';
|
|
3
|
+
import { fileURLToPath } from 'url';
|
|
4
|
+
import 'crypto';
|
|
5
|
+
|
|
6
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
7
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
8
|
+
}) : x)(function(x) {
|
|
9
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
10
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
// src/logger.ts
|
|
14
|
+
var LEVEL_RANK = {
|
|
15
|
+
debug: 10,
|
|
16
|
+
info: 20,
|
|
17
|
+
warn: 30,
|
|
18
|
+
error: 40,
|
|
19
|
+
silent: 100
|
|
20
|
+
};
|
|
21
|
+
var LEVEL_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:log-level");
|
|
22
|
+
function readLevel() {
|
|
23
|
+
const g = globalThis;
|
|
24
|
+
return g[LEVEL_KEY] ?? "warn";
|
|
25
|
+
}
|
|
26
|
+
function shouldLog(level) {
|
|
27
|
+
return LEVEL_RANK[level] >= LEVEL_RANK[readLevel()];
|
|
28
|
+
}
|
|
29
|
+
function safeWrite(level, message) {
|
|
30
|
+
try {
|
|
31
|
+
if (!shouldLog(level)) return;
|
|
32
|
+
const line = `[ezlogs] ${message}`;
|
|
33
|
+
if (level === "error" || level === "warn") {
|
|
34
|
+
console.error(line);
|
|
35
|
+
} else {
|
|
36
|
+
console.log(line);
|
|
37
|
+
}
|
|
38
|
+
} catch {
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
var logger = {
|
|
42
|
+
debug: (message) => safeWrite("debug", message),
|
|
43
|
+
info: (message) => safeWrite("info", message),
|
|
44
|
+
warn: (message) => safeWrite("warn", message),
|
|
45
|
+
error: (message) => safeWrite("error", message)
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
// src/configuration.ts
|
|
49
|
+
var DEFAULT_EXCLUDED_PATHS = Object.freeze([
|
|
50
|
+
// Next.js / Vercel infrastructure noise
|
|
51
|
+
"/_next/*",
|
|
52
|
+
"/_vercel/*",
|
|
53
|
+
"/__nextjs_*",
|
|
54
|
+
// NextAuth.js / Auth.js — skip session-refresh polls and CSRF/provider
|
|
55
|
+
// metadata GETs (high-frequency, no business meaning), but CAPTURE
|
|
56
|
+
// POSTs (callbacks, signin, signout, register). The POSTs are the
|
|
57
|
+
// actual auth events users care about; the GETs are pure plumbing.
|
|
58
|
+
Object.freeze({ path: "/api/auth/*", methods: ["GET", "HEAD"] }),
|
|
59
|
+
// Generic infrastructure
|
|
60
|
+
"/health*",
|
|
61
|
+
"/api/health",
|
|
62
|
+
"/up",
|
|
63
|
+
"/alive",
|
|
64
|
+
"/ready",
|
|
65
|
+
"/metrics",
|
|
66
|
+
"/favicon.ico",
|
|
67
|
+
"/.well-known*",
|
|
68
|
+
"/robots.txt",
|
|
69
|
+
"/sitemap.xml",
|
|
70
|
+
"/*.hot-update.*",
|
|
71
|
+
// Auth routes (common patterns across Clerk, NextAuth, custom auth)
|
|
72
|
+
"*/login*",
|
|
73
|
+
"*/logout*",
|
|
74
|
+
"*/sign-in*",
|
|
75
|
+
"*/sign-out*",
|
|
76
|
+
"*/signin*",
|
|
77
|
+
"*/signout*",
|
|
78
|
+
"/session*"
|
|
79
|
+
]);
|
|
80
|
+
var DEFAULT_EXCLUDED_TABLES = Object.freeze([
|
|
81
|
+
// Prisma migration ledger
|
|
82
|
+
"_prisma_migrations",
|
|
83
|
+
// Auth.js / NextAuth Prisma adapter — session/verification-token churn
|
|
84
|
+
// is auth machinery, not business activity. Account/User stay captured.
|
|
85
|
+
"Session",
|
|
86
|
+
"VerificationToken",
|
|
87
|
+
// Common cross-stack convention names for the same things
|
|
88
|
+
"sessions",
|
|
89
|
+
"session",
|
|
90
|
+
"verification_tokens"
|
|
91
|
+
]);
|
|
92
|
+
var DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
|
|
93
|
+
var DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
|
|
94
|
+
var DEFAULT_SERVER_URL = "https://app.ezlogs.io";
|
|
95
|
+
var Configuration = class {
|
|
96
|
+
serverUrl = DEFAULT_SERVER_URL;
|
|
97
|
+
projectToken = null;
|
|
98
|
+
captureHttp = true;
|
|
99
|
+
captureDb = true;
|
|
100
|
+
captureJobs = true;
|
|
101
|
+
bufferSize = 1e4;
|
|
102
|
+
/** Default 3000 ms — equivalent to Ruby's 3 seconds. */
|
|
103
|
+
sendInterval = 3e3;
|
|
104
|
+
retryAttempts = 3;
|
|
105
|
+
logLevel = "warn";
|
|
106
|
+
patchGlobalFetch = true;
|
|
107
|
+
actorFromSupabase = true;
|
|
108
|
+
excludedPaths = [];
|
|
109
|
+
excludedTables = [];
|
|
110
|
+
excludedJobClasses = [];
|
|
111
|
+
excludedGraphqlOperations = [];
|
|
112
|
+
excludedGraphqlVariableKeys = [];
|
|
113
|
+
actorFromRequest = null;
|
|
114
|
+
displayNameFor = {};
|
|
115
|
+
isServerActionError = null;
|
|
116
|
+
databaseReader = null;
|
|
117
|
+
databaseSnapshotMode = false;
|
|
118
|
+
databaseUrl = null;
|
|
119
|
+
/**
|
|
120
|
+
* Tables that have the `ezlogs_audit` trigger attached. Detected once
|
|
121
|
+
* at agent startup by reading `information_schema.triggers`. The
|
|
122
|
+
* supabase / drizzle / prisma adapters use this to decide whether
|
|
123
|
+
* their per-mutation emit is redundant: if the table is trigger-
|
|
124
|
+
* tracked the audit-log reader will surface the same write with full
|
|
125
|
+
* old/new state, so the adapter's emit is suppressed. Tables NOT in
|
|
126
|
+
* this set fall through to the adapter so they're still captured.
|
|
127
|
+
*
|
|
128
|
+
* `null` means "detection hasn't run yet or failed" — in that state
|
|
129
|
+
* `databaseReader`-wired apps suppress every adapter emit (the
|
|
130
|
+
* original Phase 5 behavior). After detection completes the agent
|
|
131
|
+
* gives the more accurate per-table answer.
|
|
132
|
+
*/
|
|
133
|
+
triggerTrackedTables = null;
|
|
134
|
+
apply(options) {
|
|
135
|
+
if (options.serverUrl !== void 0) this.serverUrl = options.serverUrl;
|
|
136
|
+
this.projectToken = options.projectToken;
|
|
137
|
+
if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
|
|
138
|
+
if (options.captureDb !== void 0) this.captureDb = options.captureDb;
|
|
139
|
+
if (options.captureJobs !== void 0) this.captureJobs = options.captureJobs;
|
|
140
|
+
if (options.bufferSize !== void 0) this.bufferSize = options.bufferSize;
|
|
141
|
+
if (options.sendInterval !== void 0) this.sendInterval = options.sendInterval;
|
|
142
|
+
if (options.retryAttempts !== void 0) this.retryAttempts = options.retryAttempts;
|
|
143
|
+
if (options.excludedPaths) this.excludedPaths = [...options.excludedPaths];
|
|
144
|
+
if (options.excludedTables) this.excludedTables = [...options.excludedTables];
|
|
145
|
+
if (options.excludedJobClasses) {
|
|
146
|
+
this.excludedJobClasses = [...options.excludedJobClasses];
|
|
147
|
+
}
|
|
148
|
+
if (options.excludedGraphqlOperations) {
|
|
149
|
+
this.excludedGraphqlOperations = [...options.excludedGraphqlOperations];
|
|
150
|
+
}
|
|
151
|
+
if (options.excludedGraphqlVariableKeys) {
|
|
152
|
+
this.excludedGraphqlVariableKeys = [...options.excludedGraphqlVariableKeys];
|
|
153
|
+
}
|
|
154
|
+
if (options.actorFromRequest) this.actorFromRequest = options.actorFromRequest;
|
|
155
|
+
if (options.displayNameFor) this.displayNameFor = { ...options.displayNameFor };
|
|
156
|
+
if (options.isServerActionError) this.isServerActionError = options.isServerActionError;
|
|
157
|
+
if (options.patchGlobalFetch !== void 0) {
|
|
158
|
+
this.patchGlobalFetch = options.patchGlobalFetch;
|
|
159
|
+
}
|
|
160
|
+
if (options.actorFromSupabase !== void 0) {
|
|
161
|
+
this.actorFromSupabase = options.actorFromSupabase;
|
|
162
|
+
}
|
|
163
|
+
if (options.databaseReader !== void 0) {
|
|
164
|
+
this.databaseReader = options.databaseReader;
|
|
165
|
+
}
|
|
166
|
+
if (options.databaseSnapshotMode !== void 0) {
|
|
167
|
+
this.databaseSnapshotMode = options.databaseSnapshotMode;
|
|
168
|
+
}
|
|
169
|
+
if (options.databaseUrl !== void 0) {
|
|
170
|
+
this.databaseUrl = options.databaseUrl;
|
|
171
|
+
}
|
|
172
|
+
if (options.logLevel) this.logLevel = options.logLevel;
|
|
173
|
+
}
|
|
174
|
+
allExcludedPaths() {
|
|
175
|
+
return [...DEFAULT_EXCLUDED_PATHS, ...this.excludedPaths];
|
|
176
|
+
}
|
|
177
|
+
allExcludedTables() {
|
|
178
|
+
return [...DEFAULT_EXCLUDED_TABLES, ...this.excludedTables];
|
|
179
|
+
}
|
|
180
|
+
allExcludedJobClasses() {
|
|
181
|
+
return [...DEFAULT_EXCLUDED_JOB_CLASSES, ...this.excludedJobClasses];
|
|
182
|
+
}
|
|
183
|
+
allExcludedGraphqlOperations() {
|
|
184
|
+
return [...DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, ...this.excludedGraphqlOperations];
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
var GLOBAL_CONFIG_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:configuration");
|
|
188
|
+
function configuration() {
|
|
189
|
+
const g = globalThis;
|
|
190
|
+
if (!g[GLOBAL_CONFIG_KEY]) {
|
|
191
|
+
g[GLOBAL_CONFIG_KEY] = new Configuration();
|
|
192
|
+
}
|
|
193
|
+
return g[GLOBAL_CONFIG_KEY];
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// src/triggers/install.ts
|
|
197
|
+
var HERE = dirname(fileURLToPath(import.meta.url));
|
|
198
|
+
function parseArgs(argv) {
|
|
199
|
+
const out = {
|
|
200
|
+
connection: process.env.DATABASE_URL ?? process.env.POSTGRES_URL ?? null,
|
|
201
|
+
tables: [],
|
|
202
|
+
autoTables: true,
|
|
203
|
+
print: false,
|
|
204
|
+
help: false
|
|
205
|
+
};
|
|
206
|
+
for (const arg of argv) {
|
|
207
|
+
if (arg === "--help" || arg === "-h") {
|
|
208
|
+
out.help = true;
|
|
209
|
+
} else if (arg === "--print") {
|
|
210
|
+
out.print = true;
|
|
211
|
+
} else if (arg.startsWith("--connection=")) {
|
|
212
|
+
out.connection = arg.slice("--connection=".length);
|
|
213
|
+
} else if (arg.startsWith("--tables=")) {
|
|
214
|
+
const raw = arg.slice("--tables=".length).trim();
|
|
215
|
+
if (raw === "auto" || raw === "") {
|
|
216
|
+
out.autoTables = true;
|
|
217
|
+
out.tables = [];
|
|
218
|
+
} else if (raw === "none") {
|
|
219
|
+
out.autoTables = false;
|
|
220
|
+
out.tables = [];
|
|
221
|
+
} else {
|
|
222
|
+
out.autoTables = false;
|
|
223
|
+
out.tables = raw.split(",").map((t) => t.trim()).filter(Boolean);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return out;
|
|
228
|
+
}
|
|
229
|
+
var HELP = `Install the ezlogs-nextjs row-trigger audit capture for Postgres.
|
|
230
|
+
|
|
231
|
+
Usage:
|
|
232
|
+
npx ezlogs-nextjs install-triggers [options]
|
|
233
|
+
|
|
234
|
+
Options:
|
|
235
|
+
--connection=<url> Database connection string. Defaults to DATABASE_URL
|
|
236
|
+
or POSTGRES_URL from the environment.
|
|
237
|
+
--tables=<a,b,c> Comma-separated list of tables to attach the audit
|
|
238
|
+
trigger to. Idempotent \u2014 re-runnable.
|
|
239
|
+
--tables=auto DEFAULT. Introspect information_schema and track every
|
|
240
|
+
business table in the public schema, minus a built-in
|
|
241
|
+
infrastructure skip list (migrations, sessions, etc.).
|
|
242
|
+
--tables=none Install infrastructure only; track no tables.
|
|
243
|
+
Use this when you want full manual control.
|
|
244
|
+
--print Print the SQL that would be applied; do not run it.
|
|
245
|
+
Useful for review or piping into another tool.
|
|
246
|
+
--help Show this message.
|
|
247
|
+
|
|
248
|
+
The install creates an \`ezlogs_audit_log\` table and the
|
|
249
|
+
\`ezlogs_track('table')\` / \`ezlogs_untrack('table')\` helpers. After
|
|
250
|
+
install you can call them directly to add or remove tables later.
|
|
251
|
+
|
|
252
|
+
PlanetScale users: triggers are not supported on PlanetScale. The CLI
|
|
253
|
+
will detect that and exit cleanly without making changes; the
|
|
254
|
+
per-ORM adapter (Drizzle / Prisma) remains the primary path on
|
|
255
|
+
your stack.
|
|
256
|
+
`;
|
|
257
|
+
function detectEngine(connection) {
|
|
258
|
+
if (!connection) return { engine: "unknown" };
|
|
259
|
+
if (/\.psdb\.cloud(?:[:/?]|$)/.test(connection)) {
|
|
260
|
+
return { engine: "planetscale" };
|
|
261
|
+
}
|
|
262
|
+
if (/^postgres(?:ql)?:\/\//i.test(connection)) {
|
|
263
|
+
return { engine: "postgres" };
|
|
264
|
+
}
|
|
265
|
+
if (/^mysql:\/\//i.test(connection)) {
|
|
266
|
+
return { engine: "mysql" };
|
|
267
|
+
}
|
|
268
|
+
return { engine: "unknown" };
|
|
269
|
+
}
|
|
270
|
+
async function loadInstallSql(engine) {
|
|
271
|
+
const path = join(HERE, "..", "..", "sql", engine, "00_install.sql");
|
|
272
|
+
return readFile(path, "utf8");
|
|
273
|
+
}
|
|
274
|
+
function buildTrackingSql(tables, engine) {
|
|
275
|
+
if (tables.length === 0) return "";
|
|
276
|
+
if (engine === "postgres") {
|
|
277
|
+
return tables.map((t) => `SELECT ezlogs_track('${escapeSqlIdentifier(t)}');`).join("\n");
|
|
278
|
+
}
|
|
279
|
+
return tables.map((t) => `CALL ezlogs_track('${escapeSqlIdentifier(t)}');`).join("\n");
|
|
280
|
+
}
|
|
281
|
+
function escapeSqlIdentifier(name) {
|
|
282
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
|
|
283
|
+
throw new Error(
|
|
284
|
+
`Invalid table name "${name}" \u2014 must match /^[A-Za-z_][A-Za-z0-9_]*$/.`
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
return name;
|
|
288
|
+
}
|
|
289
|
+
var TRIGGER_INSTALL_SKIP_PATTERNS = [
|
|
290
|
+
...DEFAULT_EXCLUDED_TABLES,
|
|
291
|
+
// Our own audit table — trigger on the audit table would be a loop.
|
|
292
|
+
"ezlogs_audit_log",
|
|
293
|
+
// Postgres internals (won't be in public schema, but defensive).
|
|
294
|
+
/^pg_/,
|
|
295
|
+
/^_litestream/,
|
|
296
|
+
// Solid Queue / Solid Cache / Solid Cable (Rails 8 default infra
|
|
297
|
+
// tables — show up in apps that share a database with Rails).
|
|
298
|
+
/^solid_(queue|cache|cable)/,
|
|
299
|
+
// ActiveStorage (same).
|
|
300
|
+
/^active_storage_/,
|
|
301
|
+
// ActiveRecord internals.
|
|
302
|
+
"ar_internal_metadata",
|
|
303
|
+
"schema_migrations"
|
|
304
|
+
];
|
|
305
|
+
function shouldSkipTable(tableName) {
|
|
306
|
+
for (const pattern of TRIGGER_INSTALL_SKIP_PATTERNS) {
|
|
307
|
+
if (typeof pattern === "string") {
|
|
308
|
+
if (tableName === pattern) return true;
|
|
309
|
+
} else if (pattern.test(tableName)) {
|
|
310
|
+
return true;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return false;
|
|
314
|
+
}
|
|
315
|
+
var DISCOVER_TABLES_SQL = `
|
|
316
|
+
SELECT table_name
|
|
317
|
+
FROM information_schema.tables
|
|
318
|
+
WHERE table_schema = 'public'
|
|
319
|
+
AND table_type = 'BASE TABLE'
|
|
320
|
+
ORDER BY table_name
|
|
321
|
+
`.trim();
|
|
322
|
+
async function runInstall(args, options = {}) {
|
|
323
|
+
const out = options.out ?? ((line) => {
|
|
324
|
+
console.log(line);
|
|
325
|
+
});
|
|
326
|
+
if (args.help) {
|
|
327
|
+
out(HELP);
|
|
328
|
+
return 0;
|
|
329
|
+
}
|
|
330
|
+
const detected = args.print ? { engine: "postgres" } : detectEngine(args.connection);
|
|
331
|
+
if (detected.engine === "planetscale") {
|
|
332
|
+
out(
|
|
333
|
+
"[ezlogs] Triggers are not supported on PlanetScale. The per-ORM adapter (Drizzle / Prisma / Supabase) remains the primary capture path on your stack \u2014 no install needed."
|
|
334
|
+
);
|
|
335
|
+
return 0;
|
|
336
|
+
}
|
|
337
|
+
if (detected.engine === "unknown" && !args.print) {
|
|
338
|
+
out(
|
|
339
|
+
"[ezlogs] Could not detect the database engine. Set --connection=<url> or DATABASE_URL, or run with --print to inspect the SQL without applying."
|
|
340
|
+
);
|
|
341
|
+
return 1;
|
|
342
|
+
}
|
|
343
|
+
if (detected.engine === "mysql") {
|
|
344
|
+
out(
|
|
345
|
+
"[ezlogs] MySQL trigger install not yet shipped (Phase 5 Step 2). Postgres install ready today; MySQL ships in a follow-up."
|
|
346
|
+
);
|
|
347
|
+
return 1;
|
|
348
|
+
}
|
|
349
|
+
const installSql = await loadInstallSql("postgres");
|
|
350
|
+
if (args.print) {
|
|
351
|
+
if (args.autoTables) {
|
|
352
|
+
out(installSql);
|
|
353
|
+
out(
|
|
354
|
+
"\n-- --tables=auto: trigger attachment SQL is generated at install time from information_schema. Re-run without --print to apply, or pass --tables=<a,b,c> to use an explicit list."
|
|
355
|
+
);
|
|
356
|
+
} else {
|
|
357
|
+
const trackingSql2 = buildTrackingSql(args.tables, "postgres");
|
|
358
|
+
const fullSql2 = trackingSql2 ? `${installSql}
|
|
359
|
+
${trackingSql2}
|
|
360
|
+
` : installSql;
|
|
361
|
+
out(fullSql2);
|
|
362
|
+
}
|
|
363
|
+
return 0;
|
|
364
|
+
}
|
|
365
|
+
if (!options.exec) {
|
|
366
|
+
out(
|
|
367
|
+
"[ezlogs] No exec function supplied. Use --print to dump the SQL, or run via the bundled CLI which wires `pg` for you."
|
|
368
|
+
);
|
|
369
|
+
return 1;
|
|
370
|
+
}
|
|
371
|
+
let tablesToTrack;
|
|
372
|
+
let skippedTables = [];
|
|
373
|
+
if (args.autoTables) {
|
|
374
|
+
if (!options.query) {
|
|
375
|
+
tablesToTrack = [];
|
|
376
|
+
} else {
|
|
377
|
+
try {
|
|
378
|
+
const result = await options.query(DISCOVER_TABLES_SQL);
|
|
379
|
+
const all = result.rows.map((r) => r.table_name);
|
|
380
|
+
tablesToTrack = all.filter((name) => !shouldSkipTable(name));
|
|
381
|
+
skippedTables = all.filter((name) => shouldSkipTable(name));
|
|
382
|
+
} catch (error) {
|
|
383
|
+
out(
|
|
384
|
+
`[ezlogs] Could not introspect tables: ${error instanceof Error ? error.message : String(error)}. Pass --tables=<a,b,c> for explicit tracking.`
|
|
385
|
+
);
|
|
386
|
+
return 1;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
} else {
|
|
390
|
+
tablesToTrack = args.tables;
|
|
391
|
+
}
|
|
392
|
+
for (const name of tablesToTrack) {
|
|
393
|
+
try {
|
|
394
|
+
escapeSqlIdentifier(name);
|
|
395
|
+
} catch (error) {
|
|
396
|
+
out(
|
|
397
|
+
`[ezlogs] Refusing to track ${JSON.stringify(name)} \u2014 ${error instanceof Error ? error.message : String(error)}`
|
|
398
|
+
);
|
|
399
|
+
return 1;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
const trackingSql = buildTrackingSql(tablesToTrack, "postgres");
|
|
403
|
+
const fullSql = trackingSql ? `${installSql}
|
|
404
|
+
${trackingSql}
|
|
405
|
+
` : installSql;
|
|
406
|
+
try {
|
|
407
|
+
await options.exec(fullSql);
|
|
408
|
+
if (tablesToTrack.length === 0) {
|
|
409
|
+
out(
|
|
410
|
+
"[ezlogs] Postgres triggers installed. No tables tracked yet \u2014 run `SELECT ezlogs_track('foo')` to attach the trigger, or re-run with --tables=auto to track every business table."
|
|
411
|
+
);
|
|
412
|
+
} else {
|
|
413
|
+
out(
|
|
414
|
+
`[ezlogs] Postgres triggers installed. Tracking ${tablesToTrack.length} table(s): ${tablesToTrack.join(", ")}.`
|
|
415
|
+
);
|
|
416
|
+
if (skippedTables.length > 0) {
|
|
417
|
+
out(
|
|
418
|
+
`[ezlogs] Skipped ${skippedTables.length} infrastructure table(s) (migrations, sessions, etc.): ${skippedTables.join(", ")}. Track any of them manually with \`SELECT ezlogs_track('foo')\`.`
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return 0;
|
|
423
|
+
} catch (error) {
|
|
424
|
+
logger.error(
|
|
425
|
+
`install-triggers failed: ${error instanceof Error ? error.message : String(error)}`
|
|
426
|
+
);
|
|
427
|
+
return 1;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// src/edge-fallback.ts
|
|
432
|
+
var ALS_CTOR = loadAsyncLocalStorage();
|
|
433
|
+
function loadAsyncLocalStorage() {
|
|
434
|
+
const fromGlobal = globalThis.AsyncLocalStorage;
|
|
435
|
+
if (typeof fromGlobal === "function") return fromGlobal;
|
|
436
|
+
try {
|
|
437
|
+
const req = typeof __require !== "undefined" ? __require : (
|
|
438
|
+
// In ESM, `createRequire` is the official escape hatch.
|
|
439
|
+
// We pull it via globalThis to avoid a static `import`
|
|
440
|
+
// that would itself be browser-bundled.
|
|
441
|
+
void 0
|
|
442
|
+
);
|
|
443
|
+
if (typeof req === "function") {
|
|
444
|
+
const moduleName = ["async", "hooks"].join("_");
|
|
445
|
+
const mod = req("node:" + moduleName);
|
|
446
|
+
if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
|
|
447
|
+
}
|
|
448
|
+
} catch {
|
|
449
|
+
}
|
|
450
|
+
return null;
|
|
451
|
+
}
|
|
452
|
+
function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
|
|
453
|
+
const globalStore = globalThis;
|
|
454
|
+
let entry = globalStore[key];
|
|
455
|
+
if (!entry) {
|
|
456
|
+
const als2 = (() => {
|
|
457
|
+
if (!ALS_CTOR) return null;
|
|
458
|
+
try {
|
|
459
|
+
return new ALS_CTOR();
|
|
460
|
+
} catch {
|
|
461
|
+
return null;
|
|
462
|
+
}
|
|
463
|
+
})();
|
|
464
|
+
entry = { als: als2, edgeFallback: null };
|
|
465
|
+
globalStore[key] = entry;
|
|
466
|
+
}
|
|
467
|
+
const als = entry.als;
|
|
468
|
+
const stateRef = entry;
|
|
469
|
+
return {
|
|
470
|
+
read() {
|
|
471
|
+
if (als) return als.getStore()?.value ?? null;
|
|
472
|
+
return stateRef.edgeFallback?.value ?? null;
|
|
473
|
+
},
|
|
474
|
+
run(value, callback) {
|
|
475
|
+
if (als) return als.run({ value }, callback);
|
|
476
|
+
const previous = stateRef.edgeFallback;
|
|
477
|
+
stateRef.edgeFallback = { value };
|
|
478
|
+
try {
|
|
479
|
+
return callback();
|
|
480
|
+
} finally {
|
|
481
|
+
stateRef.edgeFallback = previous;
|
|
482
|
+
}
|
|
483
|
+
},
|
|
484
|
+
update(value) {
|
|
485
|
+
if (als) {
|
|
486
|
+
const store = als.getStore();
|
|
487
|
+
if (store) store.value = value;
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
stateRef.edgeFallback = { value };
|
|
491
|
+
},
|
|
492
|
+
_resetForTests() {
|
|
493
|
+
stateRef.edgeFallback = null;
|
|
494
|
+
},
|
|
495
|
+
_isAsyncLocalStorage() {
|
|
496
|
+
return als !== null;
|
|
497
|
+
}
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// src/actor.ts
|
|
502
|
+
var storage = createScopedStorage(
|
|
503
|
+
/* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-storage")
|
|
504
|
+
);
|
|
505
|
+
function getCurrentActor() {
|
|
506
|
+
return storage.read();
|
|
507
|
+
}
|
|
508
|
+
var storage2 = createScopedStorage(
|
|
509
|
+
/* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
|
|
510
|
+
);
|
|
511
|
+
function current() {
|
|
512
|
+
return storage2.read();
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// src/triggers/context.ts
|
|
516
|
+
function getDatabaseContext() {
|
|
517
|
+
const actor = getCurrentActor();
|
|
518
|
+
return {
|
|
519
|
+
actorId: actor && actor.id ? actor.id : null,
|
|
520
|
+
correlationId: current()
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
async function applyDatabaseContext(exec) {
|
|
524
|
+
const actor = getCurrentActor();
|
|
525
|
+
const correlationId = current();
|
|
526
|
+
if (!actor && !correlationId) return;
|
|
527
|
+
try {
|
|
528
|
+
if (actor && actor.id) {
|
|
529
|
+
await exec(`SELECT set_config('ezlogs.actor_id', $1, true)`, [actor.id]);
|
|
530
|
+
}
|
|
531
|
+
if (correlationId) {
|
|
532
|
+
await exec(
|
|
533
|
+
`SELECT set_config('ezlogs.correlation_id', $1, true)`,
|
|
534
|
+
[correlationId]
|
|
535
|
+
);
|
|
536
|
+
}
|
|
537
|
+
} catch (err) {
|
|
538
|
+
logger.debug(
|
|
539
|
+
`applyDatabaseContext: set_config failed, continuing without context: ${err instanceof Error ? err.message : String(err)}`
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
async function withDatabaseContext(client, callback) {
|
|
544
|
+
await client.query("BEGIN");
|
|
545
|
+
try {
|
|
546
|
+
await applyDatabaseContext(async (sql, params) => client.query(sql, params));
|
|
547
|
+
const result = await callback(client);
|
|
548
|
+
await client.query("COMMIT");
|
|
549
|
+
return result;
|
|
550
|
+
} catch (err) {
|
|
551
|
+
try {
|
|
552
|
+
await client.query("ROLLBACK");
|
|
553
|
+
} catch {
|
|
554
|
+
}
|
|
555
|
+
throw err;
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// src/event-builder.ts
|
|
560
|
+
var SENSITIVE_KEYS = Object.freeze([
|
|
561
|
+
"password",
|
|
562
|
+
"token",
|
|
563
|
+
"secret",
|
|
564
|
+
"api_key",
|
|
565
|
+
"credit_card"
|
|
566
|
+
]);
|
|
567
|
+
var VALID_SOURCE_TYPES = [
|
|
568
|
+
"http_request",
|
|
569
|
+
"background_job",
|
|
570
|
+
"database_callback"
|
|
571
|
+
];
|
|
572
|
+
var VALID_OUTCOMES = ["success", "failure"];
|
|
573
|
+
function build(input) {
|
|
574
|
+
const source_type = validateSourceType(input.source_type);
|
|
575
|
+
const source_data_raw = validateSourceData(input.source_data);
|
|
576
|
+
const outcome = validateOutcome(input.outcome);
|
|
577
|
+
const timestamp = validateTimestamp(input.timestamp ?? null);
|
|
578
|
+
const resource_ids = validateResourceIds(input.resource_ids ?? []);
|
|
579
|
+
const context_raw = validateContext(input.context ?? null);
|
|
580
|
+
const duration_ms = validateDurationMs();
|
|
581
|
+
const error_message = input.error_message ?? null;
|
|
582
|
+
validateOutcomeErrorConsistency(outcome, error_message);
|
|
583
|
+
const source_data = sanitizeRecord(source_data_raw);
|
|
584
|
+
const context = context_raw === null ? null : sanitizeRecord(context_raw);
|
|
585
|
+
const correlation_id = input.correlation_id ?? null;
|
|
586
|
+
const event = {
|
|
587
|
+
timestamp,
|
|
588
|
+
source_type,
|
|
589
|
+
source_data,
|
|
590
|
+
outcome,
|
|
591
|
+
correlation_id,
|
|
592
|
+
resource_ids,
|
|
593
|
+
context,
|
|
594
|
+
duration_ms,
|
|
595
|
+
error_message
|
|
596
|
+
};
|
|
597
|
+
return event;
|
|
598
|
+
}
|
|
599
|
+
function validateSourceType(value) {
|
|
600
|
+
const normalized = String(value);
|
|
601
|
+
if (!VALID_SOURCE_TYPES.includes(normalized)) {
|
|
602
|
+
throw new ArgError(
|
|
603
|
+
`source_type must be one of ${VALID_SOURCE_TYPES.join(", ")}, got: ${normalized}`
|
|
604
|
+
);
|
|
605
|
+
}
|
|
606
|
+
return normalized;
|
|
607
|
+
}
|
|
608
|
+
function validateSourceData(value) {
|
|
609
|
+
if (value === null || value === void 0) {
|
|
610
|
+
throw new ArgError("source_data is required");
|
|
611
|
+
}
|
|
612
|
+
if (!isPlainObject(value)) {
|
|
613
|
+
throw new ArgError(
|
|
614
|
+
`source_data must be an object, got: ${describe(value)}`
|
|
615
|
+
);
|
|
616
|
+
}
|
|
617
|
+
return value;
|
|
618
|
+
}
|
|
619
|
+
function validateOutcome(value) {
|
|
620
|
+
const normalized = String(value);
|
|
621
|
+
if (!VALID_OUTCOMES.includes(normalized)) {
|
|
622
|
+
throw new ArgError(
|
|
623
|
+
`outcome must be one of ${VALID_OUTCOMES.join(", ")}, got: ${normalized}`
|
|
624
|
+
);
|
|
625
|
+
}
|
|
626
|
+
return normalized;
|
|
627
|
+
}
|
|
628
|
+
function validateTimestamp(value) {
|
|
629
|
+
if (value === null) {
|
|
630
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
631
|
+
}
|
|
632
|
+
if (typeof value === "string") {
|
|
633
|
+
const parsed = new Date(value);
|
|
634
|
+
if (Number.isNaN(parsed.getTime())) {
|
|
635
|
+
throw new ArgError(
|
|
636
|
+
`timestamp must be valid ISO 8601 format, got: ${value}`
|
|
637
|
+
);
|
|
638
|
+
}
|
|
639
|
+
return value;
|
|
640
|
+
}
|
|
641
|
+
if (value instanceof Date) {
|
|
642
|
+
if (Number.isNaN(value.getTime())) {
|
|
643
|
+
throw new ArgError("timestamp must be a valid Date");
|
|
644
|
+
}
|
|
645
|
+
return value.toISOString();
|
|
646
|
+
}
|
|
647
|
+
throw new ArgError(
|
|
648
|
+
`timestamp must be a string or Date, got: ${describe(value)}`
|
|
649
|
+
);
|
|
650
|
+
}
|
|
651
|
+
function validateResourceIds(value) {
|
|
652
|
+
if (!Array.isArray(value)) {
|
|
653
|
+
throw new ArgError(`resource_ids must be an array, got: ${describe(value)}`);
|
|
654
|
+
}
|
|
655
|
+
value.forEach((entry, index) => {
|
|
656
|
+
if (!isPlainObject(entry)) {
|
|
657
|
+
throw new ArgError(
|
|
658
|
+
`resource_ids[${index}] must be an object, got: ${describe(entry)}`
|
|
659
|
+
);
|
|
660
|
+
}
|
|
661
|
+
const e = entry;
|
|
662
|
+
if (!("resource_type" in e) || !("resource_id" in e)) {
|
|
663
|
+
throw new ArgError(
|
|
664
|
+
`resource_ids[${index}] must have resource_type and resource_id keys, got: ${Object.keys(e).join(", ")}`
|
|
665
|
+
);
|
|
666
|
+
}
|
|
667
|
+
if (typeof e.resource_type !== "string") {
|
|
668
|
+
throw new ArgError(
|
|
669
|
+
`resource_ids[${index}].resource_type must be a string, got: ${describe(e.resource_type)}`
|
|
670
|
+
);
|
|
671
|
+
}
|
|
672
|
+
if (typeof e.resource_id !== "string") {
|
|
673
|
+
throw new ArgError(
|
|
674
|
+
`resource_ids[${index}].resource_id must be a string, got: ${describe(e.resource_id)}`
|
|
675
|
+
);
|
|
676
|
+
}
|
|
677
|
+
});
|
|
678
|
+
return value;
|
|
679
|
+
}
|
|
680
|
+
function validateContext(value) {
|
|
681
|
+
if (value === null) return null;
|
|
682
|
+
if (!isPlainObject(value)) {
|
|
683
|
+
throw new ArgError(
|
|
684
|
+
`context must be an object or null, got: ${describe(value)}`
|
|
685
|
+
);
|
|
686
|
+
}
|
|
687
|
+
return value;
|
|
688
|
+
}
|
|
689
|
+
function validateDurationMs(value) {
|
|
690
|
+
return null;
|
|
691
|
+
}
|
|
692
|
+
function validateOutcomeErrorConsistency(outcome, error_message) {
|
|
693
|
+
if (outcome === "failure") {
|
|
694
|
+
if (error_message === null || error_message === "") {
|
|
695
|
+
throw new ArgError("error_message is required when outcome is 'failure'");
|
|
696
|
+
}
|
|
697
|
+
} else if (outcome === "success") {
|
|
698
|
+
if (error_message !== null) {
|
|
699
|
+
throw new ArgError("error_message must be null when outcome is 'success'");
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
function sanitizeRecord(input) {
|
|
704
|
+
const result = {};
|
|
705
|
+
for (const key of Object.keys(input)) {
|
|
706
|
+
const value = input[key];
|
|
707
|
+
if (isSensitiveKey(key)) {
|
|
708
|
+
result[key] = "[FILTERED]";
|
|
709
|
+
} else if (isPlainObject(value)) {
|
|
710
|
+
result[key] = sanitizeRecord(value);
|
|
711
|
+
} else if (Array.isArray(value)) {
|
|
712
|
+
result[key] = value.map(
|
|
713
|
+
(item) => isPlainObject(item) ? sanitizeRecord(item) : item
|
|
714
|
+
);
|
|
715
|
+
} else {
|
|
716
|
+
result[key] = value;
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
return result;
|
|
720
|
+
}
|
|
721
|
+
function isSensitiveKey(key) {
|
|
722
|
+
const lower = key.toLowerCase();
|
|
723
|
+
return SENSITIVE_KEYS.some((p) => lower.includes(p));
|
|
724
|
+
}
|
|
725
|
+
function isPlainObject(value) {
|
|
726
|
+
if (value === null || typeof value !== "object") return false;
|
|
727
|
+
const proto = Object.getPrototypeOf(value);
|
|
728
|
+
return proto === Object.prototype || proto === null;
|
|
729
|
+
}
|
|
730
|
+
function describe(value) {
|
|
731
|
+
if (value === null) return "null";
|
|
732
|
+
if (Array.isArray(value)) return "Array";
|
|
733
|
+
return typeof value;
|
|
734
|
+
}
|
|
735
|
+
var ArgError = class extends Error {
|
|
736
|
+
constructor(message) {
|
|
737
|
+
super(message);
|
|
738
|
+
this.name = "ArgError";
|
|
739
|
+
}
|
|
740
|
+
};
|
|
741
|
+
|
|
742
|
+
// src/pipeline/buffer.ts
|
|
743
|
+
var GLOBAL_QUEUE_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:buffer-queue");
|
|
744
|
+
function getQueue() {
|
|
745
|
+
const g = globalThis;
|
|
746
|
+
if (!g[GLOBAL_QUEUE_KEY]) g[GLOBAL_QUEUE_KEY] = [];
|
|
747
|
+
return g[GLOBAL_QUEUE_KEY];
|
|
748
|
+
}
|
|
749
|
+
function pushEvent(event) {
|
|
750
|
+
try {
|
|
751
|
+
const queue = getQueue();
|
|
752
|
+
const max = maxSize();
|
|
753
|
+
if (queue.length >= max) {
|
|
754
|
+
queue.shift();
|
|
755
|
+
logger.warn(`Buffer full (${max}), dropped oldest event`);
|
|
756
|
+
}
|
|
757
|
+
queue.push(event);
|
|
758
|
+
} catch (error) {
|
|
759
|
+
logger.error(`pushEvent failed: ${describe2(error)}`);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
function maxSize() {
|
|
763
|
+
try {
|
|
764
|
+
return configuration().bufferSize;
|
|
765
|
+
} catch {
|
|
766
|
+
return 1e4;
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
function describe2(error) {
|
|
770
|
+
if (error instanceof Error) return `${error.name}: ${error.message}`;
|
|
771
|
+
return String(error);
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
// src/db/shared.ts
|
|
775
|
+
var IGNORED_ATTRIBUTES = Object.freeze([
|
|
776
|
+
"id",
|
|
777
|
+
"createdAt",
|
|
778
|
+
"created_at",
|
|
779
|
+
"updatedAt",
|
|
780
|
+
"updated_at",
|
|
781
|
+
"deletedAt",
|
|
782
|
+
"deleted_at",
|
|
783
|
+
// Auth.js / NextAuth standard columns
|
|
784
|
+
"emailVerified",
|
|
785
|
+
"expires"
|
|
786
|
+
]);
|
|
787
|
+
var DB_SENSITIVE_PATTERNS = Object.freeze([
|
|
788
|
+
"password",
|
|
789
|
+
"token",
|
|
790
|
+
"secret",
|
|
791
|
+
"api_key",
|
|
792
|
+
"credit_card",
|
|
793
|
+
"ssn",
|
|
794
|
+
"social_security",
|
|
795
|
+
"encrypted"
|
|
796
|
+
]);
|
|
797
|
+
function emitDbEvent(input) {
|
|
798
|
+
try {
|
|
799
|
+
const config = configuration();
|
|
800
|
+
if (!config.captureDb) return;
|
|
801
|
+
if (config.allExcludedTables().includes(input.modelClass)) return;
|
|
802
|
+
if (config.databaseReader && !input._fromTrigger) {
|
|
803
|
+
const tracked = config.triggerTrackedTables;
|
|
804
|
+
if (tracked === null || tracked.has(input.modelClass)) return;
|
|
805
|
+
}
|
|
806
|
+
if (input.operation === "update") {
|
|
807
|
+
const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
|
|
808
|
+
if (meaningful.length === 0) return;
|
|
809
|
+
}
|
|
810
|
+
const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
|
|
811
|
+
const context = buildContext(input);
|
|
812
|
+
const event = build({
|
|
813
|
+
source_type: "database_callback",
|
|
814
|
+
source_data: {
|
|
815
|
+
model_class: input.modelClass,
|
|
816
|
+
operation: input.operation
|
|
817
|
+
},
|
|
818
|
+
outcome: "success",
|
|
819
|
+
correlation_id: current(),
|
|
820
|
+
resource_ids: resourceIdStr === null ? [] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
|
|
821
|
+
context,
|
|
822
|
+
duration_ms: null
|
|
823
|
+
});
|
|
824
|
+
pushEvent(event);
|
|
825
|
+
} catch (error) {
|
|
826
|
+
logger.debug(`db emit failed: ${describeError(error)}`);
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
function buildContext(input) {
|
|
830
|
+
const context = {};
|
|
831
|
+
const actor = getCurrentActor();
|
|
832
|
+
if (actor) context.actor = actor;
|
|
833
|
+
if ((input.operation === "create" || input.operation === "destroy") && input.initialAttributes) {
|
|
834
|
+
const filtered = filterMeaningfulAttributes(input.initialAttributes);
|
|
835
|
+
if (filtered !== null) context.initial_attributes = filtered;
|
|
836
|
+
}
|
|
837
|
+
if (input.operation === "update" && input.changes) {
|
|
838
|
+
const filtered = filterMeaningfulChanges(input.changes);
|
|
839
|
+
if (filtered.length > 0) {
|
|
840
|
+
context.changes = filtered.map((c) => {
|
|
841
|
+
const out = {
|
|
842
|
+
attribute: c.attribute,
|
|
843
|
+
to: formatForJson(c.to)
|
|
844
|
+
};
|
|
845
|
+
if (c.from !== void 0) out.from = formatForJson(c.from);
|
|
846
|
+
return out;
|
|
847
|
+
});
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
const displayName = input.displayName ?? (input.modelInstance ? resolveDisplayName(input.modelClass, input.modelInstance) : null);
|
|
851
|
+
if (displayName !== null) context.display_name = displayName;
|
|
852
|
+
return Object.keys(context).length === 0 ? null : context;
|
|
853
|
+
}
|
|
854
|
+
function filterMeaningfulAttributes(attrs) {
|
|
855
|
+
const out = {};
|
|
856
|
+
for (const key of Object.keys(attrs)) {
|
|
857
|
+
if (!isMeaningfulAttribute(key)) continue;
|
|
858
|
+
const value = attrs[key];
|
|
859
|
+
if (value === null || value === void 0) continue;
|
|
860
|
+
if (!isScalar(value)) continue;
|
|
861
|
+
out[key] = formatForJson(value);
|
|
862
|
+
}
|
|
863
|
+
return Object.keys(out).length === 0 ? null : out;
|
|
864
|
+
}
|
|
865
|
+
function filterMeaningfulChanges(changes) {
|
|
866
|
+
return changes.filter((c) => {
|
|
867
|
+
if (!isMeaningfulAttribute(c.attribute)) return false;
|
|
868
|
+
if (!isScalar(c.to)) return false;
|
|
869
|
+
if (c.from === void 0) return true;
|
|
870
|
+
if (!isScalar(c.from)) return false;
|
|
871
|
+
return valuesActuallyChanged(c.from, c.to);
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
function isMeaningfulAttribute(name) {
|
|
875
|
+
if (IGNORED_ATTRIBUTES.includes(name)) return false;
|
|
876
|
+
if (isDbSensitive(name)) return false;
|
|
877
|
+
return true;
|
|
878
|
+
}
|
|
879
|
+
function isDbSensitive(name) {
|
|
880
|
+
const lower = name.toLowerCase();
|
|
881
|
+
return DB_SENSITIVE_PATTERNS.some((p) => lower.includes(p));
|
|
882
|
+
}
|
|
883
|
+
function isScalar(value) {
|
|
884
|
+
if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
|
|
885
|
+
return true;
|
|
886
|
+
}
|
|
887
|
+
if (isPrismaDecimal(value)) return true;
|
|
888
|
+
if (Buffer.isBuffer?.(value)) return false;
|
|
889
|
+
if (Array.isArray(value)) return value.every((v) => isScalar(v));
|
|
890
|
+
return false;
|
|
891
|
+
}
|
|
892
|
+
function valuesActuallyChanged(from, to) {
|
|
893
|
+
if (from === null && to === null) return false;
|
|
894
|
+
if (from instanceof Date && to instanceof Date) {
|
|
895
|
+
return from.getTime() !== to.getTime();
|
|
896
|
+
}
|
|
897
|
+
return from !== to;
|
|
898
|
+
}
|
|
899
|
+
function formatForJson(value) {
|
|
900
|
+
if (value === null || value === void 0) return value;
|
|
901
|
+
if (value instanceof Date) return value.toISOString();
|
|
902
|
+
if (typeof value === "bigint") return value.toString();
|
|
903
|
+
if (isPrismaDecimal(value)) return Number(value.toString());
|
|
904
|
+
if (Array.isArray(value)) return value.map(formatForJson);
|
|
905
|
+
return value;
|
|
906
|
+
}
|
|
907
|
+
function isPrismaDecimal(value) {
|
|
908
|
+
if (value === null || typeof value !== "object") return false;
|
|
909
|
+
const obj = value;
|
|
910
|
+
return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
|
|
911
|
+
}
|
|
912
|
+
function resolveDisplayName(modelClass, instance) {
|
|
913
|
+
try {
|
|
914
|
+
const config = configuration();
|
|
915
|
+
const resolver = config.displayNameFor[modelClass];
|
|
916
|
+
const resolved = applyResolver(resolver, instance);
|
|
917
|
+
if (resolved !== null) return resolved;
|
|
918
|
+
for (const field of ["name", "title", "number"]) {
|
|
919
|
+
const value = instance[field];
|
|
920
|
+
if (value !== null && value !== void 0 && String(value).length > 0) {
|
|
921
|
+
return String(value);
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
} catch {
|
|
925
|
+
}
|
|
926
|
+
return null;
|
|
927
|
+
}
|
|
928
|
+
function applyResolver(resolver, instance) {
|
|
929
|
+
if (typeof resolver === "string") {
|
|
930
|
+
const value = instance[resolver];
|
|
931
|
+
if (value !== null && value !== void 0 && String(value).length > 0) {
|
|
932
|
+
return String(value);
|
|
933
|
+
}
|
|
934
|
+
return null;
|
|
935
|
+
}
|
|
936
|
+
if (typeof resolver === "function") {
|
|
937
|
+
try {
|
|
938
|
+
const value = resolver(instance);
|
|
939
|
+
if (typeof value === "string" && value.length > 0) return value;
|
|
940
|
+
if (value !== null && value !== void 0 && String(value).length > 0) {
|
|
941
|
+
return String(value);
|
|
942
|
+
}
|
|
943
|
+
} catch {
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
return null;
|
|
947
|
+
}
|
|
948
|
+
function describeError(error) {
|
|
949
|
+
if (error instanceof Error) return `${error.name}: ${error.message}`;
|
|
950
|
+
return String(error);
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// src/triggers/audit-snapshot.ts
|
|
954
|
+
var storage3 = createScopedStorage(
|
|
955
|
+
/* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-snapshot-storage")
|
|
956
|
+
);
|
|
957
|
+
function currentAuditSnapshot() {
|
|
958
|
+
return storage3.read();
|
|
959
|
+
}
|
|
960
|
+
function setAuditSnapshot(value) {
|
|
961
|
+
storage3.update(value);
|
|
962
|
+
}
|
|
963
|
+
function runWithAuditSnapshotScope(callback) {
|
|
964
|
+
return storage3.run(0n, callback);
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
// src/triggers/reader.ts
|
|
968
|
+
async function readAuditRows(exec, correlationId, snapshotMaxId = null) {
|
|
969
|
+
try {
|
|
970
|
+
const sql = snapshotMaxId === null ? `SELECT table_name, op, old_row, new_row, resource_id
|
|
971
|
+
FROM ezlogs_audit_log
|
|
972
|
+
WHERE correlation_id = $1
|
|
973
|
+
ORDER BY id ASC` : `SELECT table_name, op, old_row, new_row, resource_id
|
|
974
|
+
FROM ezlogs_audit_log
|
|
975
|
+
WHERE correlation_id = $1
|
|
976
|
+
OR (correlation_id IS NULL AND id > $2)
|
|
977
|
+
ORDER BY id ASC`;
|
|
978
|
+
const params = snapshotMaxId === null ? [correlationId] : [correlationId, snapshotMaxId.toString()];
|
|
979
|
+
const result = await exec(sql, params);
|
|
980
|
+
const rows = extractRows(result);
|
|
981
|
+
return rows.map((r) => normalizeAuditRow(r));
|
|
982
|
+
} catch (err) {
|
|
983
|
+
logger.debug(
|
|
984
|
+
`readAuditRows failed: ${err instanceof Error ? err.message : String(err)}`
|
|
985
|
+
);
|
|
986
|
+
return [];
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
async function takeAuditSnapshot(exec) {
|
|
990
|
+
try {
|
|
991
|
+
const result = await exec(
|
|
992
|
+
`SELECT COALESCE(MAX(id), 0) AS max_id FROM ezlogs_audit_log`,
|
|
993
|
+
[]
|
|
994
|
+
);
|
|
995
|
+
const rows = extractRows(result);
|
|
996
|
+
if (rows.length === 0) return;
|
|
997
|
+
const raw = rows[0] ?? {};
|
|
998
|
+
const value = typeof raw.max_id === "bigint" ? raw.max_id : typeof raw.max_id === "number" ? BigInt(raw.max_id) : typeof raw.max_id === "string" && /^\d+$/.test(raw.max_id) ? BigInt(raw.max_id) : null;
|
|
999
|
+
if (value === null) return;
|
|
1000
|
+
setAuditSnapshot(value);
|
|
1001
|
+
} catch (err) {
|
|
1002
|
+
logger.debug(
|
|
1003
|
+
`takeAuditSnapshot failed: ${err instanceof Error ? err.message : String(err)}`
|
|
1004
|
+
);
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
async function detectTriggerTrackedTables(exec) {
|
|
1008
|
+
try {
|
|
1009
|
+
const result = await exec(
|
|
1010
|
+
`SELECT event_object_table AS table_name
|
|
1011
|
+
FROM information_schema.triggers
|
|
1012
|
+
WHERE trigger_name = 'ezlogs_audit'
|
|
1013
|
+
AND trigger_schema = 'public'`,
|
|
1014
|
+
[]
|
|
1015
|
+
);
|
|
1016
|
+
const rows = extractRows(result);
|
|
1017
|
+
const tables = /* @__PURE__ */ new Set();
|
|
1018
|
+
for (const row of rows) {
|
|
1019
|
+
const r = row ?? {};
|
|
1020
|
+
if (typeof r.table_name === "string" && r.table_name.length > 0) {
|
|
1021
|
+
tables.add(r.table_name);
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
return tables;
|
|
1025
|
+
} catch (err) {
|
|
1026
|
+
logger.debug(
|
|
1027
|
+
`detectTriggerTrackedTables failed: ${err instanceof Error ? err.message : String(err)}`
|
|
1028
|
+
);
|
|
1029
|
+
return null;
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
function emitAuditRows(rows) {
|
|
1033
|
+
for (const row of rows) {
|
|
1034
|
+
emitOne(row);
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
async function flushAuditLog(exec) {
|
|
1038
|
+
if (!exec) return;
|
|
1039
|
+
const correlationId = current();
|
|
1040
|
+
if (!correlationId) return;
|
|
1041
|
+
const snapshot = currentAuditSnapshot();
|
|
1042
|
+
const rows = await readAuditRows(exec, correlationId, snapshot);
|
|
1043
|
+
if (rows.length === 0) return;
|
|
1044
|
+
emitAuditRows(rows);
|
|
1045
|
+
}
|
|
1046
|
+
function emitOne(row) {
|
|
1047
|
+
const op = mapOp(row.op);
|
|
1048
|
+
if (!op) return;
|
|
1049
|
+
const oldRow = coerceJsonb(row.old_row);
|
|
1050
|
+
const newRow = coerceJsonb(row.new_row);
|
|
1051
|
+
if (op === "create" && newRow) {
|
|
1052
|
+
emitDbEvent({
|
|
1053
|
+
modelClass: row.table_name,
|
|
1054
|
+
operation: "create",
|
|
1055
|
+
resourceId: row.resource_id,
|
|
1056
|
+
initialAttributes: newRow,
|
|
1057
|
+
modelInstance: newRow,
|
|
1058
|
+
displayName: null,
|
|
1059
|
+
_fromTrigger: true
|
|
1060
|
+
});
|
|
1061
|
+
return;
|
|
1062
|
+
}
|
|
1063
|
+
if (op === "update" && oldRow && newRow) {
|
|
1064
|
+
const changes = computeChanges(oldRow, newRow);
|
|
1065
|
+
if (changes.length === 0) {
|
|
1066
|
+
return;
|
|
1067
|
+
}
|
|
1068
|
+
emitDbEvent({
|
|
1069
|
+
modelClass: row.table_name,
|
|
1070
|
+
operation: "update",
|
|
1071
|
+
resourceId: row.resource_id,
|
|
1072
|
+
changes,
|
|
1073
|
+
// Prefer the post-state for the display name — that's what the
|
|
1074
|
+
// user just told the system to call this row.
|
|
1075
|
+
modelInstance: newRow,
|
|
1076
|
+
displayName: null,
|
|
1077
|
+
_fromTrigger: true
|
|
1078
|
+
});
|
|
1079
|
+
return;
|
|
1080
|
+
}
|
|
1081
|
+
if (op === "destroy" && oldRow) {
|
|
1082
|
+
emitDbEvent({
|
|
1083
|
+
modelClass: row.table_name,
|
|
1084
|
+
operation: "destroy",
|
|
1085
|
+
resourceId: row.resource_id,
|
|
1086
|
+
initialAttributes: oldRow,
|
|
1087
|
+
modelInstance: oldRow,
|
|
1088
|
+
displayName: null,
|
|
1089
|
+
_fromTrigger: true
|
|
1090
|
+
});
|
|
1091
|
+
return;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
function mapOp(op) {
|
|
1095
|
+
if (op === "INSERT") return "create";
|
|
1096
|
+
if (op === "UPDATE") return "update";
|
|
1097
|
+
if (op === "DELETE") return "destroy";
|
|
1098
|
+
return null;
|
|
1099
|
+
}
|
|
1100
|
+
function computeChanges(oldRow, newRow) {
|
|
1101
|
+
const out = [];
|
|
1102
|
+
for (const key of Object.keys(newRow)) {
|
|
1103
|
+
const before = oldRow[key];
|
|
1104
|
+
const after = newRow[key];
|
|
1105
|
+
if (deepEqual(before, after)) continue;
|
|
1106
|
+
out.push({ attribute: key, from: before, to: after });
|
|
1107
|
+
}
|
|
1108
|
+
return out;
|
|
1109
|
+
}
|
|
1110
|
+
function deepEqual(a, b) {
|
|
1111
|
+
if (a === b) return true;
|
|
1112
|
+
if (a === null || b === null) return false;
|
|
1113
|
+
if (typeof a !== typeof b) return false;
|
|
1114
|
+
if (typeof a !== "object") return false;
|
|
1115
|
+
try {
|
|
1116
|
+
return stableStringify(a) === stableStringify(b);
|
|
1117
|
+
} catch {
|
|
1118
|
+
return false;
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
function stableStringify(value) {
|
|
1122
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
1123
|
+
if (Array.isArray(value)) {
|
|
1124
|
+
return "[" + value.map((v) => stableStringify(v)).join(",") + "]";
|
|
1125
|
+
}
|
|
1126
|
+
const entries = Object.keys(value).sort().map((k) => JSON.stringify(k) + ":" + stableStringify(value[k]));
|
|
1127
|
+
return "{" + entries.join(",") + "}";
|
|
1128
|
+
}
|
|
1129
|
+
function extractRows(result) {
|
|
1130
|
+
if (!result) return [];
|
|
1131
|
+
if (Array.isArray(result)) return result;
|
|
1132
|
+
if (typeof result === "object" && Array.isArray(result.rows)) {
|
|
1133
|
+
return result.rows;
|
|
1134
|
+
}
|
|
1135
|
+
return [];
|
|
1136
|
+
}
|
|
1137
|
+
function normalizeAuditRow(raw) {
|
|
1138
|
+
const r = raw ?? {};
|
|
1139
|
+
return {
|
|
1140
|
+
table_name: String(r.table_name ?? ""),
|
|
1141
|
+
op: r.op,
|
|
1142
|
+
old_row: r.old_row ?? null,
|
|
1143
|
+
new_row: r.new_row ?? null,
|
|
1144
|
+
resource_id: r.resource_id == null ? null : String(r.resource_id)
|
|
1145
|
+
};
|
|
1146
|
+
}
|
|
1147
|
+
function coerceJsonb(value) {
|
|
1148
|
+
if (value === null || value === void 0) return null;
|
|
1149
|
+
if (typeof value === "string") {
|
|
1150
|
+
try {
|
|
1151
|
+
const parsed = JSON.parse(value);
|
|
1152
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
1153
|
+
} catch {
|
|
1154
|
+
return null;
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
if (typeof value === "object" && !Array.isArray(value)) return value;
|
|
1158
|
+
return null;
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
// src/triggers/patch-pg.ts
|
|
1162
|
+
var txState = /* @__PURE__ */ new WeakMap();
|
|
1163
|
+
function patchPgClient(pgModule) {
|
|
1164
|
+
if (!pgModule || !pgModule.Client || !pgModule.Client.prototype) {
|
|
1165
|
+
logger.debug("patchPgClient: not a recognized pg module shape, skipping");
|
|
1166
|
+
return;
|
|
1167
|
+
}
|
|
1168
|
+
const proto = pgModule.Client.prototype;
|
|
1169
|
+
if (proto._ezlogsPatched) return;
|
|
1170
|
+
const originalQuery = proto.query;
|
|
1171
|
+
proto.query = function patchedQuery(config, values, callback) {
|
|
1172
|
+
return runPatchedQuery(
|
|
1173
|
+
this,
|
|
1174
|
+
originalQuery,
|
|
1175
|
+
config,
|
|
1176
|
+
values,
|
|
1177
|
+
callback
|
|
1178
|
+
);
|
|
1179
|
+
};
|
|
1180
|
+
proto._ezlogsPatched = true;
|
|
1181
|
+
}
|
|
1182
|
+
function runPatchedQuery(client, original, config, values, callback) {
|
|
1183
|
+
const state = ensureState(client);
|
|
1184
|
+
const text = extractQueryText(config);
|
|
1185
|
+
const verb = leadingVerb(text);
|
|
1186
|
+
if (verb === "BEGIN" || verb === "START") {
|
|
1187
|
+
state.inTx = true;
|
|
1188
|
+
state.injected = false;
|
|
1189
|
+
return original.call(client, config, values, callback);
|
|
1190
|
+
}
|
|
1191
|
+
if (verb === "COMMIT" || verb === "ROLLBACK" || verb === "END") {
|
|
1192
|
+
const result = original.call(client, config, values, callback);
|
|
1193
|
+
state.inTx = false;
|
|
1194
|
+
state.injected = false;
|
|
1195
|
+
return result;
|
|
1196
|
+
}
|
|
1197
|
+
if (state.inTx) {
|
|
1198
|
+
if (state.injected) {
|
|
1199
|
+
return original.call(client, config, values, callback);
|
|
1200
|
+
}
|
|
1201
|
+
const ctx2 = snapshotContext();
|
|
1202
|
+
if (!ctx2.actorId && !ctx2.correlationId) {
|
|
1203
|
+
state.injected = true;
|
|
1204
|
+
return original.call(client, config, values, callback);
|
|
1205
|
+
}
|
|
1206
|
+
state.injected = true;
|
|
1207
|
+
return injectAndRun(client, original, config, values, callback, ctx2);
|
|
1208
|
+
}
|
|
1209
|
+
const ctx = snapshotContext();
|
|
1210
|
+
if (!ctx.actorId && !ctx.correlationId) {
|
|
1211
|
+
return original.call(client, config, values, callback);
|
|
1212
|
+
}
|
|
1213
|
+
return wrapInTx(client, original, config, values, callback, ctx);
|
|
1214
|
+
}
|
|
1215
|
+
function snapshotContext() {
|
|
1216
|
+
const actor = getCurrentActor();
|
|
1217
|
+
return {
|
|
1218
|
+
actorId: actor && actor.id ? actor.id : null,
|
|
1219
|
+
correlationId: current()
|
|
1220
|
+
};
|
|
1221
|
+
}
|
|
1222
|
+
async function injectAndRun(client, original, config, values, callback, ctx) {
|
|
1223
|
+
if (ctx.actorId) {
|
|
1224
|
+
await safeSet(client, original, {
|
|
1225
|
+
text: "SELECT set_config('ezlogs.actor_id', $1, true)",
|
|
1226
|
+
values: [ctx.actorId]
|
|
1227
|
+
});
|
|
1228
|
+
}
|
|
1229
|
+
if (ctx.correlationId) {
|
|
1230
|
+
await safeSet(client, original, {
|
|
1231
|
+
text: "SELECT set_config('ezlogs.correlation_id', $1, true)",
|
|
1232
|
+
values: [ctx.correlationId]
|
|
1233
|
+
});
|
|
1234
|
+
}
|
|
1235
|
+
return original.call(client, config, values, callback);
|
|
1236
|
+
}
|
|
1237
|
+
async function safeSet(client, original, cfg) {
|
|
1238
|
+
try {
|
|
1239
|
+
const result = original.call(client, cfg);
|
|
1240
|
+
if (result && typeof result.then === "function") {
|
|
1241
|
+
await result;
|
|
1242
|
+
}
|
|
1243
|
+
} catch (err) {
|
|
1244
|
+
logger.debug(
|
|
1245
|
+
`patchPgClient: SET LOCAL failed (continuing): ${err instanceof Error ? err.message : String(err)}`
|
|
1246
|
+
);
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
function wrapInTx(client, original, config, values, callback, ctx) {
|
|
1250
|
+
const state = ensureState(client);
|
|
1251
|
+
let userCb = null;
|
|
1252
|
+
let realValues = values;
|
|
1253
|
+
if (typeof callback === "function") {
|
|
1254
|
+
userCb = callback;
|
|
1255
|
+
} else if (typeof values === "function") {
|
|
1256
|
+
userCb = values;
|
|
1257
|
+
realValues = void 0;
|
|
1258
|
+
}
|
|
1259
|
+
const begin = original.call(client, "BEGIN");
|
|
1260
|
+
if (!begin || typeof begin.then !== "function") {
|
|
1261
|
+
return original.call(client, config, values, callback);
|
|
1262
|
+
}
|
|
1263
|
+
const wrapped = begin.then(async () => {
|
|
1264
|
+
state.inTx = true;
|
|
1265
|
+
state.injected = true;
|
|
1266
|
+
if (ctx.actorId) {
|
|
1267
|
+
await original.call(client, {
|
|
1268
|
+
text: "SELECT set_config('ezlogs.actor_id', $1, true)",
|
|
1269
|
+
values: [ctx.actorId]
|
|
1270
|
+
});
|
|
1271
|
+
}
|
|
1272
|
+
if (ctx.correlationId) {
|
|
1273
|
+
await original.call(client, {
|
|
1274
|
+
text: "SELECT set_config('ezlogs.correlation_id', $1, true)",
|
|
1275
|
+
values: [ctx.correlationId]
|
|
1276
|
+
});
|
|
1277
|
+
}
|
|
1278
|
+
}).then(
|
|
1279
|
+
() => (
|
|
1280
|
+
// Run the user's actual query in promise mode — DO NOT forward
|
|
1281
|
+
// the caller's callback. See comment above.
|
|
1282
|
+
original.call(client, config, realValues)
|
|
1283
|
+
)
|
|
1284
|
+
).then(
|
|
1285
|
+
async (result) => {
|
|
1286
|
+
await original.call(client, "COMMIT");
|
|
1287
|
+
state.inTx = false;
|
|
1288
|
+
state.injected = false;
|
|
1289
|
+
return result;
|
|
1290
|
+
},
|
|
1291
|
+
async (err) => {
|
|
1292
|
+
try {
|
|
1293
|
+
await original.call(client, "ROLLBACK");
|
|
1294
|
+
} catch {
|
|
1295
|
+
}
|
|
1296
|
+
state.inTx = false;
|
|
1297
|
+
state.injected = false;
|
|
1298
|
+
throw err;
|
|
1299
|
+
}
|
|
1300
|
+
);
|
|
1301
|
+
if (userCb) {
|
|
1302
|
+
wrapped.then(
|
|
1303
|
+
(result) => userCb(null, result),
|
|
1304
|
+
(err) => userCb(err instanceof Error ? err : new Error(String(err)))
|
|
1305
|
+
);
|
|
1306
|
+
return void 0;
|
|
1307
|
+
}
|
|
1308
|
+
return wrapped;
|
|
1309
|
+
}
|
|
1310
|
+
function ensureState(client) {
|
|
1311
|
+
let s = txState.get(client);
|
|
1312
|
+
if (!s) {
|
|
1313
|
+
s = { inTx: false, injected: false };
|
|
1314
|
+
txState.set(client, s);
|
|
1315
|
+
}
|
|
1316
|
+
return s;
|
|
1317
|
+
}
|
|
1318
|
+
function extractQueryText(config) {
|
|
1319
|
+
if (typeof config === "string") return config;
|
|
1320
|
+
if (config && typeof config === "object" && typeof config.text === "string") {
|
|
1321
|
+
return config.text;
|
|
1322
|
+
}
|
|
1323
|
+
return "";
|
|
1324
|
+
}
|
|
1325
|
+
function leadingVerb(text) {
|
|
1326
|
+
let s = text;
|
|
1327
|
+
while (true) {
|
|
1328
|
+
const before = s.length;
|
|
1329
|
+
s = s.replace(/^\s+/, "");
|
|
1330
|
+
s = s.replace(/^--[^\n]*\n?/, "");
|
|
1331
|
+
if (s.length === before) break;
|
|
1332
|
+
}
|
|
1333
|
+
const m = /^[A-Za-z]+/.exec(s);
|
|
1334
|
+
return m ? m[0].toUpperCase() : "";
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
export { applyDatabaseContext, buildTrackingSql, currentAuditSnapshot, detectEngine, detectTriggerTrackedTables, emitAuditRows, flushAuditLog, getDatabaseContext, parseArgs, patchPgClient, readAuditRows, runInstall, runWithAuditSnapshotScope, takeAuditSnapshot, withDatabaseContext };
|