ezlogs-nextjs 0.3.0 → 0.3.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.
- package/README.md +15 -2
- package/bin/install-triggers.cjs +33 -5
- package/dist/actors/index.cjs +5 -37
- package/dist/actors/index.js +2 -34
- package/dist/chunk-C5OSM557.js +39 -0
- package/dist/chunk-CE3R7DVB.js +1127 -0
- package/dist/chunk-CU45I2WR.js +498 -0
- package/dist/chunk-DKRNNI4I.js +180 -0
- package/dist/chunk-SIAA4J6H.js +17 -0
- package/dist/chunk-UQHEW6ER.js +119 -0
- package/dist/chunk-UWHYJH4M.cjs +126 -0
- package/dist/chunk-V5YNKKTG.cjs +42 -0
- package/dist/chunk-WASXTDLW.cjs +1151 -0
- package/dist/chunk-Y5NSHKWQ.cjs +182 -0
- package/dist/chunk-YX2XPLOA.cjs +508 -0
- package/dist/chunk-ZDSQYCYV.cjs +21 -0
- package/dist/db/drizzle.cjs +6 -821
- package/dist/db/drizzle.js +5 -820
- package/dist/db/prisma.cjs +28 -853
- package/dist/db/prisma.js +14 -839
- package/dist/db/supabase.cjs +21 -836
- package/dist/db/supabase.js +14 -829
- package/dist/index.cjs +132 -2362
- package/dist/index.js +34 -2270
- package/dist/jobs/bullmq.cjs +13 -1465
- package/dist/jobs/bullmq.js +7 -1459
- package/dist/jobs/inngest.cjs +14 -1422
- package/dist/jobs/inngest.js +8 -1416
- package/dist/jobs/supabase-queues.cjs +15 -1467
- package/dist/jobs/supabase-queues.js +10 -1462
- package/dist/jobs/trigger.cjs +9 -1454
- package/dist/jobs/trigger.js +5 -1450
- package/dist/jobs/upstash-workflow.cjs +30 -1456
- package/dist/jobs/upstash-workflow.d.cts +2 -1
- package/dist/jobs/upstash-workflow.d.ts +2 -1
- package/dist/jobs/upstash-workflow.js +27 -1453
- package/dist/nextjs-plugin/index.cjs +1 -1
- package/dist/nextjs-plugin/index.js +1 -1
- package/dist/nextjs-plugin/loader.cjs +21 -25
- package/dist/nextjs-plugin/loader.js +1 -5
- package/dist/triggers/index.cjs +40 -1434
- package/dist/triggers/index.js +6 -1421
- package/package.json +2 -1
package/dist/jobs/inngest.js
CHANGED
|
@@ -1,1416 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
}
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
});
|
|
7
|
-
|
|
8
|
-
// src/logger.ts
|
|
9
|
-
var LEVEL_RANK = {
|
|
10
|
-
debug: 10,
|
|
11
|
-
info: 20,
|
|
12
|
-
warn: 30,
|
|
13
|
-
error: 40,
|
|
14
|
-
silent: 100
|
|
15
|
-
};
|
|
16
|
-
var LEVEL_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:log-level");
|
|
17
|
-
function readLevel() {
|
|
18
|
-
const g = globalThis;
|
|
19
|
-
return g[LEVEL_KEY] ?? "warn";
|
|
20
|
-
}
|
|
21
|
-
function shouldLog(level) {
|
|
22
|
-
return LEVEL_RANK[level] >= LEVEL_RANK[readLevel()];
|
|
23
|
-
}
|
|
24
|
-
function safeWrite(level, message) {
|
|
25
|
-
try {
|
|
26
|
-
if (!shouldLog(level)) return;
|
|
27
|
-
const line = `[ezlogs] ${message}`;
|
|
28
|
-
if (level === "error" || level === "warn") {
|
|
29
|
-
console.error(line);
|
|
30
|
-
} else {
|
|
31
|
-
console.log(line);
|
|
32
|
-
}
|
|
33
|
-
} catch {
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
var logger = {
|
|
37
|
-
debug: (message) => safeWrite("debug", message),
|
|
38
|
-
info: (message) => safeWrite("info", message),
|
|
39
|
-
warn: (message) => safeWrite("warn", message),
|
|
40
|
-
error: (message) => safeWrite("error", message)
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
// src/event-builder.ts
|
|
44
|
-
var SENSITIVE_KEYS = Object.freeze([
|
|
45
|
-
"password",
|
|
46
|
-
"token",
|
|
47
|
-
"secret",
|
|
48
|
-
"api_key",
|
|
49
|
-
"credit_card"
|
|
50
|
-
]);
|
|
51
|
-
var VALID_SOURCE_TYPES = [
|
|
52
|
-
"http_request",
|
|
53
|
-
"background_job",
|
|
54
|
-
"database_callback"
|
|
55
|
-
];
|
|
56
|
-
var VALID_OUTCOMES = ["success", "failure"];
|
|
57
|
-
function build(input) {
|
|
58
|
-
const source_type = validateSourceType(input.source_type);
|
|
59
|
-
const source_data_raw = validateSourceData(input.source_data);
|
|
60
|
-
const outcome = validateOutcome(input.outcome);
|
|
61
|
-
const timestamp = validateTimestamp(input.timestamp ?? null);
|
|
62
|
-
const resource_ids = validateResourceIds(input.resource_ids ?? []);
|
|
63
|
-
const context_raw = validateContext(input.context ?? null);
|
|
64
|
-
const duration_ms = validateDurationMs(input.duration_ms ?? null);
|
|
65
|
-
const error_message = input.error_message ?? null;
|
|
66
|
-
validateOutcomeErrorConsistency(outcome, error_message);
|
|
67
|
-
const source_data = sanitizeRecord(source_data_raw);
|
|
68
|
-
const context = context_raw === null ? null : sanitizeRecord(context_raw);
|
|
69
|
-
const correlation_id = input.correlation_id ?? null;
|
|
70
|
-
const event = {
|
|
71
|
-
timestamp,
|
|
72
|
-
source_type,
|
|
73
|
-
source_data,
|
|
74
|
-
outcome,
|
|
75
|
-
correlation_id,
|
|
76
|
-
resource_ids,
|
|
77
|
-
context,
|
|
78
|
-
duration_ms,
|
|
79
|
-
error_message
|
|
80
|
-
};
|
|
81
|
-
return event;
|
|
82
|
-
}
|
|
83
|
-
function validateSourceType(value) {
|
|
84
|
-
if (value === null || value === void 0) {
|
|
85
|
-
throw new ArgError("source_type is required");
|
|
86
|
-
}
|
|
87
|
-
const normalized = String(value);
|
|
88
|
-
if (!VALID_SOURCE_TYPES.includes(normalized)) {
|
|
89
|
-
throw new ArgError(
|
|
90
|
-
`source_type must be one of ${VALID_SOURCE_TYPES.join(", ")}, got: ${normalized}`
|
|
91
|
-
);
|
|
92
|
-
}
|
|
93
|
-
return normalized;
|
|
94
|
-
}
|
|
95
|
-
function validateSourceData(value) {
|
|
96
|
-
if (value === null || value === void 0) {
|
|
97
|
-
throw new ArgError("source_data is required");
|
|
98
|
-
}
|
|
99
|
-
if (!isPlainObject(value)) {
|
|
100
|
-
throw new ArgError(
|
|
101
|
-
`source_data must be an object, got: ${describe(value)}`
|
|
102
|
-
);
|
|
103
|
-
}
|
|
104
|
-
return value;
|
|
105
|
-
}
|
|
106
|
-
function validateOutcome(value) {
|
|
107
|
-
if (value === null || value === void 0) {
|
|
108
|
-
throw new ArgError("outcome is required");
|
|
109
|
-
}
|
|
110
|
-
const normalized = String(value);
|
|
111
|
-
if (!VALID_OUTCOMES.includes(normalized)) {
|
|
112
|
-
throw new ArgError(
|
|
113
|
-
`outcome must be one of ${VALID_OUTCOMES.join(", ")}, got: ${normalized}`
|
|
114
|
-
);
|
|
115
|
-
}
|
|
116
|
-
return normalized;
|
|
117
|
-
}
|
|
118
|
-
function validateTimestamp(value) {
|
|
119
|
-
if (value === null) {
|
|
120
|
-
return (/* @__PURE__ */ new Date()).toISOString();
|
|
121
|
-
}
|
|
122
|
-
if (typeof value === "string") {
|
|
123
|
-
const parsed = new Date(value);
|
|
124
|
-
if (Number.isNaN(parsed.getTime())) {
|
|
125
|
-
throw new ArgError(
|
|
126
|
-
`timestamp must be valid ISO 8601 format, got: ${value}`
|
|
127
|
-
);
|
|
128
|
-
}
|
|
129
|
-
return value;
|
|
130
|
-
}
|
|
131
|
-
if (value instanceof Date) {
|
|
132
|
-
if (Number.isNaN(value.getTime())) {
|
|
133
|
-
throw new ArgError("timestamp must be a valid Date");
|
|
134
|
-
}
|
|
135
|
-
return value.toISOString();
|
|
136
|
-
}
|
|
137
|
-
throw new ArgError(
|
|
138
|
-
`timestamp must be a string or Date, got: ${describe(value)}`
|
|
139
|
-
);
|
|
140
|
-
}
|
|
141
|
-
function validateResourceIds(value) {
|
|
142
|
-
if (!Array.isArray(value)) {
|
|
143
|
-
throw new ArgError(`resource_ids must be an array, got: ${describe(value)}`);
|
|
144
|
-
}
|
|
145
|
-
value.forEach((entry, index) => {
|
|
146
|
-
if (!isPlainObject(entry)) {
|
|
147
|
-
throw new ArgError(
|
|
148
|
-
`resource_ids[${index}] must be an object, got: ${describe(entry)}`
|
|
149
|
-
);
|
|
150
|
-
}
|
|
151
|
-
const e = entry;
|
|
152
|
-
if (!("resource_type" in e) || !("resource_id" in e)) {
|
|
153
|
-
throw new ArgError(
|
|
154
|
-
`resource_ids[${index}] must have resource_type and resource_id keys, got: ${Object.keys(e).join(", ")}`
|
|
155
|
-
);
|
|
156
|
-
}
|
|
157
|
-
if (typeof e.resource_type !== "string") {
|
|
158
|
-
throw new ArgError(
|
|
159
|
-
`resource_ids[${index}].resource_type must be a string, got: ${describe(e.resource_type)}`
|
|
160
|
-
);
|
|
161
|
-
}
|
|
162
|
-
if (typeof e.resource_id !== "string") {
|
|
163
|
-
throw new ArgError(
|
|
164
|
-
`resource_ids[${index}].resource_id must be a string, got: ${describe(e.resource_id)}`
|
|
165
|
-
);
|
|
166
|
-
}
|
|
167
|
-
});
|
|
168
|
-
return value;
|
|
169
|
-
}
|
|
170
|
-
function validateContext(value) {
|
|
171
|
-
if (value === null) return null;
|
|
172
|
-
if (!isPlainObject(value)) {
|
|
173
|
-
throw new ArgError(
|
|
174
|
-
`context must be an object or null, got: ${describe(value)}`
|
|
175
|
-
);
|
|
176
|
-
}
|
|
177
|
-
return value;
|
|
178
|
-
}
|
|
179
|
-
function validateDurationMs(value) {
|
|
180
|
-
if (value === null || value === void 0) return null;
|
|
181
|
-
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
182
|
-
throw new ArgError(`duration_ms must be a number, got: ${describe(value)}`);
|
|
183
|
-
}
|
|
184
|
-
if (!Number.isInteger(value)) {
|
|
185
|
-
throw new ArgError(`duration_ms must be an integer, got: ${value}`);
|
|
186
|
-
}
|
|
187
|
-
if (value < 0) {
|
|
188
|
-
throw new ArgError(`duration_ms must be >= 0, got: ${value}`);
|
|
189
|
-
}
|
|
190
|
-
return value;
|
|
191
|
-
}
|
|
192
|
-
function validateOutcomeErrorConsistency(outcome, error_message) {
|
|
193
|
-
if (outcome === "failure") {
|
|
194
|
-
if (error_message === null || error_message === "") {
|
|
195
|
-
throw new ArgError("error_message is required when outcome is 'failure'");
|
|
196
|
-
}
|
|
197
|
-
} else if (outcome === "success") {
|
|
198
|
-
if (error_message !== null) {
|
|
199
|
-
throw new ArgError("error_message must be null when outcome is 'success'");
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
function sanitizeRecord(input) {
|
|
204
|
-
const result = {};
|
|
205
|
-
for (const key of Object.keys(input)) {
|
|
206
|
-
const value = input[key];
|
|
207
|
-
if (isSensitiveKey(key)) {
|
|
208
|
-
result[key] = "[FILTERED]";
|
|
209
|
-
} else if (isPlainObject(value)) {
|
|
210
|
-
result[key] = sanitizeRecord(value);
|
|
211
|
-
} else if (Array.isArray(value)) {
|
|
212
|
-
result[key] = value.map(
|
|
213
|
-
(item) => isPlainObject(item) ? sanitizeRecord(item) : item
|
|
214
|
-
);
|
|
215
|
-
} else {
|
|
216
|
-
result[key] = value;
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
return result;
|
|
220
|
-
}
|
|
221
|
-
function isSensitiveKey(key) {
|
|
222
|
-
const lower = key.toLowerCase();
|
|
223
|
-
return SENSITIVE_KEYS.some((p) => lower.includes(p));
|
|
224
|
-
}
|
|
225
|
-
function isPlainObject(value) {
|
|
226
|
-
if (value === null || typeof value !== "object") return false;
|
|
227
|
-
const proto = Object.getPrototypeOf(value);
|
|
228
|
-
return proto === Object.prototype || proto === null;
|
|
229
|
-
}
|
|
230
|
-
function describe(value) {
|
|
231
|
-
if (value === null) return "null";
|
|
232
|
-
if (Array.isArray(value)) return "Array";
|
|
233
|
-
return typeof value;
|
|
234
|
-
}
|
|
235
|
-
var ArgError = class extends Error {
|
|
236
|
-
constructor(message) {
|
|
237
|
-
super(message);
|
|
238
|
-
this.name = "ArgError";
|
|
239
|
-
}
|
|
240
|
-
};
|
|
241
|
-
|
|
242
|
-
// src/configuration.ts
|
|
243
|
-
var DEFAULT_EXCLUDED_PATHS = Object.freeze([
|
|
244
|
-
// Next.js / Vercel infrastructure noise
|
|
245
|
-
"/_next/*",
|
|
246
|
-
"/_vercel/*",
|
|
247
|
-
"/__nextjs_*",
|
|
248
|
-
// NextAuth.js / Auth.js — skip session-refresh polls and CSRF/provider
|
|
249
|
-
// metadata GETs (high-frequency, no business meaning), but CAPTURE
|
|
250
|
-
// POSTs (callbacks, signin, signout, register). The POSTs are the
|
|
251
|
-
// actual auth events users care about; the GETs are pure plumbing.
|
|
252
|
-
Object.freeze({ path: "/api/auth/*", methods: ["GET", "HEAD"] }),
|
|
253
|
-
// Generic infrastructure
|
|
254
|
-
"/health*",
|
|
255
|
-
"/api/health",
|
|
256
|
-
"/up",
|
|
257
|
-
"/alive",
|
|
258
|
-
"/ready",
|
|
259
|
-
"/metrics",
|
|
260
|
-
"/favicon.ico",
|
|
261
|
-
"/.well-known*",
|
|
262
|
-
"/robots.txt",
|
|
263
|
-
"/sitemap.xml",
|
|
264
|
-
"/*.hot-update.*",
|
|
265
|
-
// Auth routes (common patterns across Clerk, NextAuth, custom auth)
|
|
266
|
-
"*/login*",
|
|
267
|
-
"*/logout*",
|
|
268
|
-
"*/sign-in*",
|
|
269
|
-
"*/sign-out*",
|
|
270
|
-
"*/signin*",
|
|
271
|
-
"*/signout*",
|
|
272
|
-
"/session*"
|
|
273
|
-
]);
|
|
274
|
-
var DEFAULT_EXCLUDED_TABLES = Object.freeze([
|
|
275
|
-
// Prisma migration ledger
|
|
276
|
-
"_prisma_migrations",
|
|
277
|
-
// Auth.js / NextAuth Prisma adapter — session/verification-token churn
|
|
278
|
-
// is auth machinery, not business activity. Account/User stay captured.
|
|
279
|
-
"Session",
|
|
280
|
-
"VerificationToken",
|
|
281
|
-
// Common cross-stack convention names for the same things
|
|
282
|
-
"sessions",
|
|
283
|
-
"session",
|
|
284
|
-
"verification_tokens"
|
|
285
|
-
]);
|
|
286
|
-
var DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
|
|
287
|
-
var DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
|
|
288
|
-
var Configuration = class {
|
|
289
|
-
serverUrl = null;
|
|
290
|
-
projectToken = null;
|
|
291
|
-
captureHttp = true;
|
|
292
|
-
captureDb = true;
|
|
293
|
-
captureJobs = true;
|
|
294
|
-
bufferSize = 1e4;
|
|
295
|
-
/** Default 3000 ms — equivalent to Ruby's 3 seconds. */
|
|
296
|
-
sendInterval = 3e3;
|
|
297
|
-
retryAttempts = 3;
|
|
298
|
-
logLevel = "warn";
|
|
299
|
-
patchGlobalFetch = true;
|
|
300
|
-
actorFromSupabase = true;
|
|
301
|
-
allowInsecureTransport = false;
|
|
302
|
-
excludedPaths = [];
|
|
303
|
-
excludedTables = [];
|
|
304
|
-
excludedJobClasses = [];
|
|
305
|
-
excludedGraphqlOperations = [];
|
|
306
|
-
excludedGraphqlVariableKeys = [];
|
|
307
|
-
actorFromRequest = null;
|
|
308
|
-
displayNameFor = {};
|
|
309
|
-
isServerActionError = null;
|
|
310
|
-
databaseReader = null;
|
|
311
|
-
databaseUrl = null;
|
|
312
|
-
/**
|
|
313
|
-
* Tables that have the `ezlogs_audit` trigger attached. Detected once
|
|
314
|
-
* at agent startup by reading `information_schema.triggers`. The
|
|
315
|
-
* supabase / drizzle / prisma adapters use this to decide whether
|
|
316
|
-
* their per-mutation emit is redundant: if the table is trigger-
|
|
317
|
-
* tracked the audit-log reader will surface the same write with full
|
|
318
|
-
* old/new state, so the adapter's emit is suppressed. Tables NOT in
|
|
319
|
-
* this set fall through to the adapter so they're still captured.
|
|
320
|
-
*
|
|
321
|
-
* `null` means "detection hasn't run yet or failed" — in that state
|
|
322
|
-
* `databaseReader`-wired apps suppress every adapter emit (the
|
|
323
|
-
* original Phase 5 behavior). After detection completes the agent
|
|
324
|
-
* gives the more accurate per-table answer.
|
|
325
|
-
*/
|
|
326
|
-
triggerTrackedTables = null;
|
|
327
|
-
apply(options) {
|
|
328
|
-
this.serverUrl = options.serverUrl;
|
|
329
|
-
this.projectToken = options.projectToken;
|
|
330
|
-
if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
|
|
331
|
-
if (options.captureDb !== void 0) this.captureDb = options.captureDb;
|
|
332
|
-
if (options.captureJobs !== void 0) this.captureJobs = options.captureJobs;
|
|
333
|
-
if (options.bufferSize !== void 0) this.bufferSize = options.bufferSize;
|
|
334
|
-
if (options.sendInterval !== void 0) this.sendInterval = options.sendInterval;
|
|
335
|
-
if (options.retryAttempts !== void 0) this.retryAttempts = options.retryAttempts;
|
|
336
|
-
if (options.excludedPaths) this.excludedPaths = [...options.excludedPaths];
|
|
337
|
-
if (options.excludedTables) this.excludedTables = [...options.excludedTables];
|
|
338
|
-
if (options.excludedJobClasses) {
|
|
339
|
-
this.excludedJobClasses = [...options.excludedJobClasses];
|
|
340
|
-
}
|
|
341
|
-
if (options.excludedGraphqlOperations) {
|
|
342
|
-
this.excludedGraphqlOperations = [...options.excludedGraphqlOperations];
|
|
343
|
-
}
|
|
344
|
-
if (options.excludedGraphqlVariableKeys) {
|
|
345
|
-
this.excludedGraphqlVariableKeys = [...options.excludedGraphqlVariableKeys];
|
|
346
|
-
}
|
|
347
|
-
if (options.actorFromRequest) this.actorFromRequest = options.actorFromRequest;
|
|
348
|
-
if (options.displayNameFor) this.displayNameFor = { ...options.displayNameFor };
|
|
349
|
-
if (options.isServerActionError) this.isServerActionError = options.isServerActionError;
|
|
350
|
-
if (options.patchGlobalFetch !== void 0) {
|
|
351
|
-
this.patchGlobalFetch = options.patchGlobalFetch;
|
|
352
|
-
}
|
|
353
|
-
if (options.allowInsecureTransport !== void 0) {
|
|
354
|
-
this.allowInsecureTransport = options.allowInsecureTransport;
|
|
355
|
-
}
|
|
356
|
-
if (options.actorFromSupabase !== void 0) {
|
|
357
|
-
this.actorFromSupabase = options.actorFromSupabase;
|
|
358
|
-
}
|
|
359
|
-
if (options.databaseReader !== void 0) {
|
|
360
|
-
this.databaseReader = options.databaseReader;
|
|
361
|
-
}
|
|
362
|
-
if (options.databaseUrl !== void 0) {
|
|
363
|
-
this.databaseUrl = options.databaseUrl;
|
|
364
|
-
}
|
|
365
|
-
if (options.logLevel) this.logLevel = options.logLevel;
|
|
366
|
-
}
|
|
367
|
-
allExcludedPaths() {
|
|
368
|
-
return [...DEFAULT_EXCLUDED_PATHS, ...this.excludedPaths];
|
|
369
|
-
}
|
|
370
|
-
allExcludedTables() {
|
|
371
|
-
return [...DEFAULT_EXCLUDED_TABLES, ...this.excludedTables];
|
|
372
|
-
}
|
|
373
|
-
allExcludedJobClasses() {
|
|
374
|
-
return [...DEFAULT_EXCLUDED_JOB_CLASSES, ...this.excludedJobClasses];
|
|
375
|
-
}
|
|
376
|
-
allExcludedGraphqlOperations() {
|
|
377
|
-
return [...DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, ...this.excludedGraphqlOperations];
|
|
378
|
-
}
|
|
379
|
-
};
|
|
380
|
-
var GLOBAL_CONFIG_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:configuration");
|
|
381
|
-
function configuration() {
|
|
382
|
-
const g = globalThis;
|
|
383
|
-
if (!g[GLOBAL_CONFIG_KEY]) {
|
|
384
|
-
g[GLOBAL_CONFIG_KEY] = new Configuration();
|
|
385
|
-
}
|
|
386
|
-
return g[GLOBAL_CONFIG_KEY];
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
// src/pipeline/buffer.ts
|
|
390
|
-
var GLOBAL_QUEUE_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:buffer-queue");
|
|
391
|
-
function getQueue() {
|
|
392
|
-
const g = globalThis;
|
|
393
|
-
if (!g[GLOBAL_QUEUE_KEY]) g[GLOBAL_QUEUE_KEY] = [];
|
|
394
|
-
return g[GLOBAL_QUEUE_KEY];
|
|
395
|
-
}
|
|
396
|
-
function pushEvent(event) {
|
|
397
|
-
try {
|
|
398
|
-
const queue = getQueue();
|
|
399
|
-
const max = maxSize();
|
|
400
|
-
if (queue.length >= max) {
|
|
401
|
-
queue.shift();
|
|
402
|
-
logger.warn(`Buffer full (${max}), dropped oldest event`);
|
|
403
|
-
}
|
|
404
|
-
queue.push(event);
|
|
405
|
-
} catch (error) {
|
|
406
|
-
logger.error(`pushEvent failed: ${describe2(error)}`);
|
|
407
|
-
}
|
|
408
|
-
}
|
|
409
|
-
function maxSize() {
|
|
410
|
-
try {
|
|
411
|
-
return configuration().bufferSize;
|
|
412
|
-
} catch {
|
|
413
|
-
return 1e4;
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
function describe2(error) {
|
|
417
|
-
if (error instanceof Error) return `${error.name}: ${error.message}`;
|
|
418
|
-
return String(error);
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
// src/edge-fallback.ts
|
|
422
|
-
var ALS_CTOR = loadAsyncLocalStorage();
|
|
423
|
-
function loadAsyncLocalStorage() {
|
|
424
|
-
const fromGlobal = globalThis.AsyncLocalStorage;
|
|
425
|
-
if (typeof fromGlobal === "function") return fromGlobal;
|
|
426
|
-
try {
|
|
427
|
-
const req = typeof __require !== "undefined" ? __require : (
|
|
428
|
-
// In ESM, `createRequire` is the official escape hatch.
|
|
429
|
-
// We pull it via globalThis to avoid a static `import`
|
|
430
|
-
// that would itself be browser-bundled.
|
|
431
|
-
void 0
|
|
432
|
-
);
|
|
433
|
-
if (typeof req === "function") {
|
|
434
|
-
const moduleName = ["async", "hooks"].join("_");
|
|
435
|
-
const mod = req("node:" + moduleName);
|
|
436
|
-
if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
|
|
437
|
-
}
|
|
438
|
-
} catch {
|
|
439
|
-
}
|
|
440
|
-
return null;
|
|
441
|
-
}
|
|
442
|
-
function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
|
|
443
|
-
const globalStore = globalThis;
|
|
444
|
-
let entry = globalStore[key];
|
|
445
|
-
if (!entry) {
|
|
446
|
-
const als2 = (() => {
|
|
447
|
-
if (!ALS_CTOR) return null;
|
|
448
|
-
try {
|
|
449
|
-
return new ALS_CTOR();
|
|
450
|
-
} catch {
|
|
451
|
-
return null;
|
|
452
|
-
}
|
|
453
|
-
})();
|
|
454
|
-
entry = { als: als2, edgeFallback: null };
|
|
455
|
-
globalStore[key] = entry;
|
|
456
|
-
}
|
|
457
|
-
const als = entry.als;
|
|
458
|
-
const stateRef = entry;
|
|
459
|
-
return {
|
|
460
|
-
read() {
|
|
461
|
-
if (als) return als.getStore()?.value ?? null;
|
|
462
|
-
return stateRef.edgeFallback?.value ?? null;
|
|
463
|
-
},
|
|
464
|
-
run(value, callback) {
|
|
465
|
-
if (als) return als.run({ value }, callback);
|
|
466
|
-
const previous = stateRef.edgeFallback;
|
|
467
|
-
stateRef.edgeFallback = { value };
|
|
468
|
-
try {
|
|
469
|
-
return callback();
|
|
470
|
-
} finally {
|
|
471
|
-
stateRef.edgeFallback = previous;
|
|
472
|
-
}
|
|
473
|
-
},
|
|
474
|
-
update(value) {
|
|
475
|
-
if (als) {
|
|
476
|
-
const store = als.getStore();
|
|
477
|
-
if (store) store.value = value;
|
|
478
|
-
return;
|
|
479
|
-
}
|
|
480
|
-
stateRef.edgeFallback = { value };
|
|
481
|
-
},
|
|
482
|
-
_resetForTests() {
|
|
483
|
-
stateRef.edgeFallback = null;
|
|
484
|
-
},
|
|
485
|
-
_isAsyncLocalStorage() {
|
|
486
|
-
return als !== null;
|
|
487
|
-
}
|
|
488
|
-
};
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
// src/correlation.ts
|
|
492
|
-
var storage = createScopedStorage(
|
|
493
|
-
/* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
|
|
494
|
-
);
|
|
495
|
-
function generate() {
|
|
496
|
-
const ts = Date.now();
|
|
497
|
-
const hex = randomHexBytes(4);
|
|
498
|
-
return `ezl_${ts}_${hex}`;
|
|
499
|
-
}
|
|
500
|
-
function randomHexBytes(byteCount) {
|
|
501
|
-
const buf = new Uint8Array(byteCount);
|
|
502
|
-
globalThis.crypto.getRandomValues(buf);
|
|
503
|
-
let out = "";
|
|
504
|
-
for (let i = 0; i < buf.length; i++) {
|
|
505
|
-
out += buf[i].toString(16).padStart(2, "0");
|
|
506
|
-
}
|
|
507
|
-
return out;
|
|
508
|
-
}
|
|
509
|
-
function current() {
|
|
510
|
-
return storage.read();
|
|
511
|
-
}
|
|
512
|
-
function runWithCorrelation(correlationId, callback) {
|
|
513
|
-
return storage.run(correlationId, callback);
|
|
514
|
-
}
|
|
515
|
-
|
|
516
|
-
// src/http/sanitize.ts
|
|
517
|
-
var SENSITIVE_VARIABLE_PATTERNS = Object.freeze([
|
|
518
|
-
"password",
|
|
519
|
-
"passwd",
|
|
520
|
-
"pwd",
|
|
521
|
-
"token",
|
|
522
|
-
"access_token",
|
|
523
|
-
"refresh_token",
|
|
524
|
-
"api_token",
|
|
525
|
-
"auth_token",
|
|
526
|
-
"secret",
|
|
527
|
-
"api_secret",
|
|
528
|
-
"client_secret",
|
|
529
|
-
"api_key",
|
|
530
|
-
"apikey",
|
|
531
|
-
"private_key",
|
|
532
|
-
"privatekey",
|
|
533
|
-
"public_key",
|
|
534
|
-
"signing_key",
|
|
535
|
-
"secret_key",
|
|
536
|
-
"secretkey",
|
|
537
|
-
"credential",
|
|
538
|
-
"auth",
|
|
539
|
-
"authorization",
|
|
540
|
-
"encrypted",
|
|
541
|
-
"encrypted_data",
|
|
542
|
-
"ssn",
|
|
543
|
-
"social_security",
|
|
544
|
-
"credit_card",
|
|
545
|
-
"card_number",
|
|
546
|
-
"cvv",
|
|
547
|
-
"cvc",
|
|
548
|
-
// Crypto-material patterns — aligned with DB_SENSITIVE_PATTERNS
|
|
549
|
-
// (PR #45). Request bodies can carry the same key material as DB
|
|
550
|
-
// columns (a webhook POST containing a `signature` field, an HMAC
|
|
551
|
-
// header echoed into a JSON body, a `pem`-encoded cert blob, etc).
|
|
552
|
-
"pem",
|
|
553
|
-
"cipher",
|
|
554
|
-
"nonce",
|
|
555
|
-
"salt",
|
|
556
|
-
"digest",
|
|
557
|
-
"signature",
|
|
558
|
-
"hmac",
|
|
559
|
-
// 0.2.0 additions (not yet in the Rails gem's list).
|
|
560
|
-
"passcode",
|
|
561
|
-
"cardnumber"
|
|
562
|
-
]);
|
|
563
|
-
var SENSITIVE_WORD_PATTERNS = Object.freeze([
|
|
564
|
-
"pin",
|
|
565
|
-
"otp",
|
|
566
|
-
"totp",
|
|
567
|
-
"iban",
|
|
568
|
-
"mfa",
|
|
569
|
-
"passphrase"
|
|
570
|
-
]);
|
|
571
|
-
function snakeLower(key) {
|
|
572
|
-
return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
573
|
-
}
|
|
574
|
-
function matchesSensitiveKey(key, substringPatterns) {
|
|
575
|
-
const lower = key.toLowerCase();
|
|
576
|
-
const snake = snakeLower(key);
|
|
577
|
-
if (substringPatterns.some((p) => lower.includes(p) || snake.includes(p))) {
|
|
578
|
-
return true;
|
|
579
|
-
}
|
|
580
|
-
const words = snake.split(/[^a-z0-9]+/);
|
|
581
|
-
return SENSITIVE_WORD_PATTERNS.some((w) => words.includes(w));
|
|
582
|
-
}
|
|
583
|
-
var MAX_NESTING_DEPTH = 3;
|
|
584
|
-
var MAX_ARRAY_DISPLAY_SIZE = 5;
|
|
585
|
-
function passesLuhn(digits) {
|
|
586
|
-
let sum = 0;
|
|
587
|
-
for (let i = 0; i < digits.length; i += 1) {
|
|
588
|
-
let d = Number(digits[digits.length - 1 - i]);
|
|
589
|
-
if (i % 2 === 1) {
|
|
590
|
-
d *= 2;
|
|
591
|
-
if (d > 9) d -= 9;
|
|
592
|
-
}
|
|
593
|
-
sum += d;
|
|
594
|
-
}
|
|
595
|
-
return sum % 10 === 0;
|
|
596
|
-
}
|
|
597
|
-
var SECRET_TEXT_PATTERNS = [
|
|
598
|
-
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
|
|
599
|
-
/\beyJ[\w-]+\.[\w-]+\.[\w-]+/g,
|
|
600
|
-
/\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]+/g,
|
|
601
|
-
/\bsk-[A-Za-z0-9_-]{16,}/g,
|
|
602
|
-
/\bgh[pousr]_[A-Za-z0-9]{20,}/g,
|
|
603
|
-
/\bxox[abposr]-[A-Za-z0-9-]+/g,
|
|
604
|
-
/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g
|
|
605
|
-
];
|
|
606
|
-
var EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
|
|
607
|
-
function scrubSecretsInText(text, options = {}) {
|
|
608
|
-
let out = text;
|
|
609
|
-
for (const pattern of SECRET_TEXT_PATTERNS) out = out.replace(pattern, "[FILTERED]");
|
|
610
|
-
out = out.replace(/\b(Bearer|Basic)\s+[\w.~+/=-]+/gi, "$1 [FILTERED]").replace(/\b\d(?:[ -]?\d){12,18}\b/g, (match) => {
|
|
611
|
-
const digits = match.replace(/[ -]/g, "");
|
|
612
|
-
return (digits.length === 15 || digits.length === 16) && passesLuhn(digits) ? "[FILTERED]" : match;
|
|
613
|
-
});
|
|
614
|
-
return options.emails ? out.replace(EMAIL, "[FILTERED]") : out;
|
|
615
|
-
}
|
|
616
|
-
function sanitizeArgs(args, userPatterns = []) {
|
|
617
|
-
return sanitizeArrayValue(args, 0, userPatterns);
|
|
618
|
-
}
|
|
619
|
-
function sanitizeValue(key, value, depth, userPatterns) {
|
|
620
|
-
if (isSensitiveKey2(key, userPatterns)) return "[FILTERED]";
|
|
621
|
-
if (isPlainObject2(value)) {
|
|
622
|
-
return sanitizeNestedObject(value, depth, userPatterns);
|
|
623
|
-
}
|
|
624
|
-
if (Array.isArray(value)) {
|
|
625
|
-
return sanitizeArrayValue(value, depth, userPatterns);
|
|
626
|
-
}
|
|
627
|
-
return value;
|
|
628
|
-
}
|
|
629
|
-
function sanitizeNestedObject(hash, depth, userPatterns) {
|
|
630
|
-
if (depth >= MAX_NESTING_DEPTH) return "[Object]";
|
|
631
|
-
if (Object.keys(hash).length === 0) return {};
|
|
632
|
-
const out = {};
|
|
633
|
-
for (const k of Object.keys(hash)) {
|
|
634
|
-
out[k] = sanitizeValue(k, hash[k], depth + 1, userPatterns);
|
|
635
|
-
}
|
|
636
|
-
return out;
|
|
637
|
-
}
|
|
638
|
-
function sanitizeArrayValue(array, depth, userPatterns) {
|
|
639
|
-
if (array.length === 0) return [];
|
|
640
|
-
const allPrimitive = array.every(isPrimitive);
|
|
641
|
-
if (allPrimitive) {
|
|
642
|
-
if (array.length <= MAX_ARRAY_DISPLAY_SIZE) return array;
|
|
643
|
-
const preview = array.slice(0, MAX_ARRAY_DISPLAY_SIZE);
|
|
644
|
-
return `${JSON.stringify(preview)}... (${array.length} total)`;
|
|
645
|
-
}
|
|
646
|
-
if (array.length <= MAX_ARRAY_DISPLAY_SIZE) {
|
|
647
|
-
return array.map((item) => sanitizeArrayItem(item, depth, userPatterns));
|
|
648
|
-
}
|
|
649
|
-
return {
|
|
650
|
-
_truncated: true,
|
|
651
|
-
_count: array.length,
|
|
652
|
-
_preview: array.slice(0, MAX_ARRAY_DISPLAY_SIZE).map((item) => sanitizeArrayItem(item, depth, userPatterns))
|
|
653
|
-
};
|
|
654
|
-
}
|
|
655
|
-
function sanitizeArrayItem(item, depth, userPatterns) {
|
|
656
|
-
if (isPrimitive(item)) return item;
|
|
657
|
-
if (isPlainObject2(item)) {
|
|
658
|
-
return sanitizeNestedObject(item, depth + 1, userPatterns);
|
|
659
|
-
}
|
|
660
|
-
if (Array.isArray(item)) return sanitizeArrayValue(item, depth + 1, userPatterns);
|
|
661
|
-
return "[Object]";
|
|
662
|
-
}
|
|
663
|
-
function isSensitiveKey2(key, userPatterns) {
|
|
664
|
-
if (matchesSensitiveKey(key, SENSITIVE_VARIABLE_PATTERNS)) return true;
|
|
665
|
-
const lower = key.toLowerCase();
|
|
666
|
-
return userPatterns.some((p) => lower.includes(p.toLowerCase()));
|
|
667
|
-
}
|
|
668
|
-
function isPrimitive(value) {
|
|
669
|
-
return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
|
|
670
|
-
}
|
|
671
|
-
function isPlainObject2(value) {
|
|
672
|
-
if (value === null || typeof value !== "object") return false;
|
|
673
|
-
const proto = Object.getPrototypeOf(value);
|
|
674
|
-
return proto === Object.prototype || proto === null;
|
|
675
|
-
}
|
|
676
|
-
|
|
677
|
-
// src/actor.ts
|
|
678
|
-
var storage2 = createScopedStorage(
|
|
679
|
-
/* @__PURE__ */ Symbol.for("ezlogs-nextjs:actor-storage")
|
|
680
|
-
);
|
|
681
|
-
function getCurrentActor() {
|
|
682
|
-
return storage2.read();
|
|
683
|
-
}
|
|
684
|
-
function runWithActorScope(callback) {
|
|
685
|
-
return storage2.run(null, callback);
|
|
686
|
-
}
|
|
687
|
-
|
|
688
|
-
// src/db/shared.ts
|
|
689
|
-
var IGNORED_ATTRIBUTES = Object.freeze([
|
|
690
|
-
"id",
|
|
691
|
-
"createdAt",
|
|
692
|
-
"created_at",
|
|
693
|
-
"updatedAt",
|
|
694
|
-
"updated_at",
|
|
695
|
-
// Auth.js / NextAuth standard columns
|
|
696
|
-
"emailVerified",
|
|
697
|
-
"expires"
|
|
698
|
-
]);
|
|
699
|
-
var DB_SENSITIVE_PATTERNS = Object.freeze([
|
|
700
|
-
"password",
|
|
701
|
-
"token",
|
|
702
|
-
"secret",
|
|
703
|
-
"api_key",
|
|
704
|
-
"credit_card",
|
|
705
|
-
"ssn",
|
|
706
|
-
"social_security",
|
|
707
|
-
"encrypted",
|
|
708
|
-
"private_key",
|
|
709
|
-
"public_key",
|
|
710
|
-
"signing_key",
|
|
711
|
-
"pem",
|
|
712
|
-
"cipher",
|
|
713
|
-
"nonce",
|
|
714
|
-
"salt",
|
|
715
|
-
"digest",
|
|
716
|
-
"signature",
|
|
717
|
-
"hmac",
|
|
718
|
-
// 0.2.0 additions. `credential` / `passwd` / `apikey` were already in
|
|
719
|
-
// the HTTP list; `passcode` / `card_number` / `cardnumber` / `cvv` /
|
|
720
|
-
// `cvc` are new. Whole-word `pin` / `otp` / `totp` / `iban` come from
|
|
721
|
-
// SENSITIVE_WORD_PATTERNS. The SQL trigger mirrors this list.
|
|
722
|
-
"credential",
|
|
723
|
-
"passwd",
|
|
724
|
-
"passcode",
|
|
725
|
-
"apikey",
|
|
726
|
-
"card_number",
|
|
727
|
-
"cardnumber",
|
|
728
|
-
"cvv",
|
|
729
|
-
"cvc"
|
|
730
|
-
]);
|
|
731
|
-
function emitDbEvent(input) {
|
|
732
|
-
try {
|
|
733
|
-
const config = configuration();
|
|
734
|
-
if (!config.captureDb) return;
|
|
735
|
-
if (config.allExcludedTables().includes(input.modelClass)) return;
|
|
736
|
-
if (config.databaseReader && !input._fromTrigger) {
|
|
737
|
-
const tracked = config.triggerTrackedTables;
|
|
738
|
-
if (tracked === null || tracked.has(input.table ?? input.modelClass)) return;
|
|
739
|
-
}
|
|
740
|
-
if (input.operation === "update") {
|
|
741
|
-
const meaningful = input.changes ? filterMeaningfulChanges(input.changes) : [];
|
|
742
|
-
if (meaningful.length === 0) return;
|
|
743
|
-
}
|
|
744
|
-
const resourceIdStr = input.resourceId === null || input.resourceId === void 0 ? null : String(input.resourceId);
|
|
745
|
-
const related = resourceIdStr === null ? input.relatedResourceIds ?? [] : [];
|
|
746
|
-
const context = buildContext(
|
|
747
|
-
related.length > 0 ? { ...input, displayName: null, modelInstance: null } : input
|
|
748
|
-
);
|
|
749
|
-
const event = build({
|
|
750
|
-
source_type: "database_callback",
|
|
751
|
-
source_data: {
|
|
752
|
-
model_class: input.modelClass,
|
|
753
|
-
operation: input.operation
|
|
754
|
-
},
|
|
755
|
-
outcome: "success",
|
|
756
|
-
correlation_id: current(),
|
|
757
|
-
resource_ids: resourceIdStr === null ? [...related] : [{ resource_type: input.modelClass, resource_id: resourceIdStr }],
|
|
758
|
-
context,
|
|
759
|
-
duration_ms: null,
|
|
760
|
-
timestamp: input.timestamp ?? null
|
|
761
|
-
});
|
|
762
|
-
pushEvent(event);
|
|
763
|
-
} catch (error) {
|
|
764
|
-
logger.debug(`db emit failed: ${describeError(error)}`);
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
function buildContext(input) {
|
|
768
|
-
const context = {};
|
|
769
|
-
const actor = getCurrentActor();
|
|
770
|
-
if (actor) context.actor = actor;
|
|
771
|
-
if ((input.operation === "create" || input.operation === "destroy") && input.initialAttributes) {
|
|
772
|
-
const filtered = filterMeaningfulAttributes(input.initialAttributes);
|
|
773
|
-
if (filtered !== null) context.initial_attributes = filtered;
|
|
774
|
-
}
|
|
775
|
-
if (input.operation === "update" && input.changes) {
|
|
776
|
-
const filtered = filterMeaningfulChanges(input.changes);
|
|
777
|
-
if (filtered.length > 0) {
|
|
778
|
-
context.changes = filtered.map((c) => {
|
|
779
|
-
const out = {
|
|
780
|
-
attribute: c.attribute,
|
|
781
|
-
to: formatForJson(c.to)
|
|
782
|
-
};
|
|
783
|
-
if (c.from !== void 0) out.from = formatForJson(c.from);
|
|
784
|
-
return out;
|
|
785
|
-
});
|
|
786
|
-
}
|
|
787
|
-
}
|
|
788
|
-
const displayName = input.displayName ?? (input.modelInstance ? resolveDisplayName(input.modelClass, input.modelInstance) : null);
|
|
789
|
-
if (displayName !== null) context.display_name = displayName;
|
|
790
|
-
return Object.keys(context).length === 0 ? null : context;
|
|
791
|
-
}
|
|
792
|
-
function filterMeaningfulAttributes(attrs) {
|
|
793
|
-
const out = {};
|
|
794
|
-
for (const key of Object.keys(attrs)) {
|
|
795
|
-
if (!isMeaningfulAttribute(key)) continue;
|
|
796
|
-
const value = attrs[key];
|
|
797
|
-
if (value === null || value === void 0) continue;
|
|
798
|
-
if (!isScalar(value)) continue;
|
|
799
|
-
out[key] = formatForJson(value);
|
|
800
|
-
}
|
|
801
|
-
return Object.keys(out).length === 0 ? null : out;
|
|
802
|
-
}
|
|
803
|
-
function filterMeaningfulChanges(changes) {
|
|
804
|
-
return flattenNestedChanges(changes).filter((c) => {
|
|
805
|
-
if (!isMeaningfulAttribute(c.attribute)) return false;
|
|
806
|
-
if (!isScalar(c.to)) return false;
|
|
807
|
-
if (c.from === void 0) return true;
|
|
808
|
-
if (!isScalar(c.from)) return false;
|
|
809
|
-
return valuesActuallyChanged(c.from, c.to);
|
|
810
|
-
});
|
|
811
|
-
}
|
|
812
|
-
var MAX_NESTED_DEPTH = 3;
|
|
813
|
-
var MAX_NESTED_LEAVES = 20;
|
|
814
|
-
var MAX_UNKNOWN_FROM_LEAVES = 5;
|
|
815
|
-
function flattenNestedChanges(changes) {
|
|
816
|
-
if (!changes.some((c) => isPlainRecord(c.to) || isPlainRecord(c.from))) return changes;
|
|
817
|
-
const out = [];
|
|
818
|
-
for (const c of changes) {
|
|
819
|
-
if (!isPlainRecord(c.to) && !isPlainRecord(c.from)) {
|
|
820
|
-
out.push(c);
|
|
821
|
-
continue;
|
|
822
|
-
}
|
|
823
|
-
if (!isMeaningfulAttribute(c.attribute)) continue;
|
|
824
|
-
const leaves = [];
|
|
825
|
-
collectLeafChanges(c.attribute, c.from, c.to, 1, leaves);
|
|
826
|
-
const cap = c.from === void 0 ? MAX_UNKNOWN_FROM_LEAVES : MAX_NESTED_LEAVES;
|
|
827
|
-
out.push(...leaves.slice(0, cap).map(scrubLeaf));
|
|
828
|
-
}
|
|
829
|
-
return out;
|
|
830
|
-
}
|
|
831
|
-
function collectLeafChanges(path, from, to, depth, out) {
|
|
832
|
-
if (out.length > MAX_NESTED_LEAVES) return;
|
|
833
|
-
const fromObj = isPlainRecord(from);
|
|
834
|
-
const toObj = isPlainRecord(to);
|
|
835
|
-
if ((fromObj || toObj) && depth <= MAX_NESTED_DEPTH && (fromObj || from == null) && (toObj || to == null)) {
|
|
836
|
-
const f = fromObj ? from : {};
|
|
837
|
-
const t = toObj ? to : {};
|
|
838
|
-
for (const key of /* @__PURE__ */ new Set([...Object.keys(f), ...Object.keys(t)])) {
|
|
839
|
-
const before = from === void 0 ? void 0 : f[key] ?? null;
|
|
840
|
-
collectLeafChanges(`${path}.${key}`, before, t[key] ?? null, depth + 1, out);
|
|
841
|
-
}
|
|
842
|
-
return;
|
|
843
|
-
}
|
|
844
|
-
if (from !== void 0 && sameJson(from, to)) return;
|
|
845
|
-
out.push(from === void 0 ? { attribute: path, to } : { attribute: path, from, to });
|
|
846
|
-
}
|
|
847
|
-
function scrubLeaf(change) {
|
|
848
|
-
const scrub = (v) => typeof v === "string" ? scrubSecretsInText(v) : v;
|
|
849
|
-
const out = { attribute: change.attribute, to: scrub(change.to) };
|
|
850
|
-
if (change.from !== void 0) out.from = scrub(change.from);
|
|
851
|
-
return out;
|
|
852
|
-
}
|
|
853
|
-
function isPlainRecord(value) {
|
|
854
|
-
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
855
|
-
const proto = Object.getPrototypeOf(value);
|
|
856
|
-
return proto === Object.prototype || proto === null;
|
|
857
|
-
}
|
|
858
|
-
function sameJson(a, b) {
|
|
859
|
-
if (a === b) return true;
|
|
860
|
-
try {
|
|
861
|
-
return JSON.stringify(a) === JSON.stringify(b);
|
|
862
|
-
} catch {
|
|
863
|
-
return false;
|
|
864
|
-
}
|
|
865
|
-
}
|
|
866
|
-
function isMeaningfulAttribute(name) {
|
|
867
|
-
if (IGNORED_ATTRIBUTES.includes(name)) return false;
|
|
868
|
-
if (isDbSensitive(name)) return false;
|
|
869
|
-
return true;
|
|
870
|
-
}
|
|
871
|
-
function isDbSensitive(name) {
|
|
872
|
-
return matchesSensitiveKey(name, DB_SENSITIVE_PATTERNS);
|
|
873
|
-
}
|
|
874
|
-
function isScalar(value) {
|
|
875
|
-
if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date) {
|
|
876
|
-
return true;
|
|
877
|
-
}
|
|
878
|
-
if (isPrismaDecimal(value)) return true;
|
|
879
|
-
if (Buffer.isBuffer?.(value)) return false;
|
|
880
|
-
if (Array.isArray(value)) return value.every((v) => isScalar(v));
|
|
881
|
-
return false;
|
|
882
|
-
}
|
|
883
|
-
function valuesActuallyChanged(from, to) {
|
|
884
|
-
if (from === null && to === null) return false;
|
|
885
|
-
if (from instanceof Date && to instanceof Date) {
|
|
886
|
-
return from.getTime() !== to.getTime();
|
|
887
|
-
}
|
|
888
|
-
return from !== to;
|
|
889
|
-
}
|
|
890
|
-
function formatForJson(value) {
|
|
891
|
-
if (value === null || value === void 0) return value;
|
|
892
|
-
if (value instanceof Date) return value.toISOString();
|
|
893
|
-
if (typeof value === "bigint") return value.toString();
|
|
894
|
-
if (isPrismaDecimal(value)) return Number(value.toString());
|
|
895
|
-
if (Array.isArray(value)) return value.map(formatForJson);
|
|
896
|
-
return value;
|
|
897
|
-
}
|
|
898
|
-
function isPrismaDecimal(value) {
|
|
899
|
-
if (value === null || typeof value !== "object") return false;
|
|
900
|
-
const obj = value;
|
|
901
|
-
return typeof obj.toString === "function" && typeof obj.toFixed === "function" && "d" in obj && "e" in obj && "s" in obj;
|
|
902
|
-
}
|
|
903
|
-
var DISPLAY_NAME_COLUMNS = ["name", "title", "number", "label"];
|
|
904
|
-
var MAX_DISPLAY_NAME_LENGTH = 120;
|
|
905
|
-
function resolveDisplayName(modelClass, instance) {
|
|
906
|
-
try {
|
|
907
|
-
const config = configuration();
|
|
908
|
-
const resolver = config.displayNameFor[modelClass];
|
|
909
|
-
const resolved = applyResolver(resolver, instance);
|
|
910
|
-
if (resolved !== null) return resolved;
|
|
911
|
-
const columns = /* @__PURE__ */ new Map();
|
|
912
|
-
for (const key of Object.keys(instance)) {
|
|
913
|
-
if (isDbSensitive(key)) continue;
|
|
914
|
-
const norm = key.toLowerCase().replace(/_/g, "");
|
|
915
|
-
if (!columns.has(norm)) columns.set(norm, instance[key]);
|
|
916
|
-
}
|
|
917
|
-
const text = (norm) => {
|
|
918
|
-
const value = columns.get(norm);
|
|
919
|
-
if (typeof value !== "string" && typeof value !== "number" && typeof value !== "bigint") {
|
|
920
|
-
return null;
|
|
921
|
-
}
|
|
922
|
-
const str = String(value).trim();
|
|
923
|
-
return str.length > 0 ? str.slice(0, MAX_DISPLAY_NAME_LENGTH) : null;
|
|
924
|
-
};
|
|
925
|
-
for (const column of DISPLAY_NAME_COLUMNS) {
|
|
926
|
-
const value = text(column);
|
|
927
|
-
if (value !== null) return value;
|
|
928
|
-
}
|
|
929
|
-
return text(`${singularNorm(modelClass)}number`);
|
|
930
|
-
} catch {
|
|
931
|
-
}
|
|
932
|
-
return null;
|
|
933
|
-
}
|
|
934
|
-
function singularNorm(modelClass) {
|
|
935
|
-
const norm = modelClass.toLowerCase().replace(/_/g, "");
|
|
936
|
-
if (norm.endsWith("ies")) return norm.slice(0, -3) + "y";
|
|
937
|
-
if (/(ss|us|is)$/.test(norm)) return norm;
|
|
938
|
-
if (/(xes|ches|shes|sses)$/.test(norm)) return norm.slice(0, -2);
|
|
939
|
-
return norm.endsWith("s") ? norm.slice(0, -1) : norm;
|
|
940
|
-
}
|
|
941
|
-
function applyResolver(resolver, instance) {
|
|
942
|
-
if (typeof resolver === "string") {
|
|
943
|
-
const value = instance[resolver];
|
|
944
|
-
if (value !== null && value !== void 0 && String(value).length > 0) {
|
|
945
|
-
return String(value);
|
|
946
|
-
}
|
|
947
|
-
return null;
|
|
948
|
-
}
|
|
949
|
-
if (typeof resolver === "function") {
|
|
950
|
-
try {
|
|
951
|
-
const value = resolver(instance);
|
|
952
|
-
if (typeof value === "string" && value.length > 0) return value;
|
|
953
|
-
if (value !== null && value !== void 0 && String(value).length > 0) {
|
|
954
|
-
return String(value);
|
|
955
|
-
}
|
|
956
|
-
} catch {
|
|
957
|
-
}
|
|
958
|
-
}
|
|
959
|
-
return null;
|
|
960
|
-
}
|
|
961
|
-
function describeError(error) {
|
|
962
|
-
if (error instanceof Error) return `${error.name}: ${error.message}`;
|
|
963
|
-
return String(error);
|
|
964
|
-
}
|
|
965
|
-
|
|
966
|
-
// src/triggers/emit-dedup.ts
|
|
967
|
-
var storage3 = createScopedStorage(
|
|
968
|
-
/* @__PURE__ */ Symbol.for("ezlogs-nextjs:audit-emitted-ids-storage")
|
|
969
|
-
);
|
|
970
|
-
function currentEmittedAuditIds() {
|
|
971
|
-
return storage3.read();
|
|
972
|
-
}
|
|
973
|
-
|
|
974
|
-
// src/triggers/reader.ts
|
|
975
|
-
var COLUMNS = "id, table_name, op, old_row, new_row, resource_id, correlation_id, txid, captured_at";
|
|
976
|
-
var ORPHAN_AGE = "5 minutes";
|
|
977
|
-
var PRUNE_AGE = "24 hours";
|
|
978
|
-
var SWEEP_BATCH = 100;
|
|
979
|
-
var PRUNE_BATCH = 2e3;
|
|
980
|
-
var SWEEP_INTERVAL_MS = 1e4;
|
|
981
|
-
var PRUNE_INTERVAL_MS = 10 * 6e4;
|
|
982
|
-
var lastSweepAt = 0;
|
|
983
|
-
var lastPruneAt = 0;
|
|
984
|
-
var deleteDenied = false;
|
|
985
|
-
var txCorrelation = /* @__PURE__ */ new Map();
|
|
986
|
-
async function readAuditRows(exec, correlationId, since = null) {
|
|
987
|
-
const where = since ? "correlation_id = $1 AND captured_at >= $2" : "correlation_id = $1";
|
|
988
|
-
const params = since ? [correlationId, since.toISOString()] : [correlationId];
|
|
989
|
-
try {
|
|
990
|
-
if (!deleteDenied) {
|
|
991
|
-
try {
|
|
992
|
-
return sortById(
|
|
993
|
-
extractRows(
|
|
994
|
-
await exec(
|
|
995
|
-
`DELETE FROM ezlogs_audit_log WHERE ${where} RETURNING ${COLUMNS}`,
|
|
996
|
-
params
|
|
997
|
-
)
|
|
998
|
-
).map(normalizeAuditRow)
|
|
999
|
-
);
|
|
1000
|
-
} catch (err) {
|
|
1001
|
-
if (!isPermissionDenied(err)) throw err;
|
|
1002
|
-
deleteDenied = true;
|
|
1003
|
-
logger.warn(
|
|
1004
|
-
"the database role used by the agent cannot DELETE from ezlogs_audit_log. Rows will not be cleaned up after they are sent; grant DELETE or schedule `DELETE FROM ezlogs_audit_log WHERE captured_at < now() - interval '24 hours'`."
|
|
1005
|
-
);
|
|
1006
|
-
}
|
|
1007
|
-
}
|
|
1008
|
-
const result = await exec(
|
|
1009
|
-
`SELECT ${COLUMNS} FROM ezlogs_audit_log WHERE ${where} ORDER BY id ASC`,
|
|
1010
|
-
params
|
|
1011
|
-
);
|
|
1012
|
-
return extractRows(result).map(normalizeAuditRow);
|
|
1013
|
-
} catch (err) {
|
|
1014
|
-
logger.debug(
|
|
1015
|
-
`readAuditRows failed: ${err instanceof Error ? err.message : String(err)}`
|
|
1016
|
-
);
|
|
1017
|
-
return [];
|
|
1018
|
-
}
|
|
1019
|
-
}
|
|
1020
|
-
async function sweepAuditLog(exec) {
|
|
1021
|
-
if (deleteDenied) return 0;
|
|
1022
|
-
try {
|
|
1023
|
-
const rows = sortById(
|
|
1024
|
-
extractRows(
|
|
1025
|
-
await exec(
|
|
1026
|
-
`DELETE FROM ezlogs_audit_log
|
|
1027
|
-
WHERE id IN (
|
|
1028
|
-
SELECT id FROM ezlogs_audit_log
|
|
1029
|
-
WHERE (correlation_id IS NULL
|
|
1030
|
-
OR captured_at < now() - interval '${ORPHAN_AGE}')
|
|
1031
|
-
-- Never resurface history: past the retention cap a
|
|
1032
|
-
-- row is pruned, not sent as new activity.
|
|
1033
|
-
AND captured_at > now() - interval '${PRUNE_AGE}'
|
|
1034
|
-
ORDER BY id
|
|
1035
|
-
LIMIT ${SWEEP_BATCH}
|
|
1036
|
-
FOR UPDATE SKIP LOCKED)
|
|
1037
|
-
RETURNING ${COLUMNS}`,
|
|
1038
|
-
[]
|
|
1039
|
-
)
|
|
1040
|
-
).map(normalizeAuditRow)
|
|
1041
|
-
);
|
|
1042
|
-
await loadTableMeta(exec, rows);
|
|
1043
|
-
for (const row of rows) {
|
|
1044
|
-
const correlationId = row.correlation_id ?? correlationForTx(row.txid);
|
|
1045
|
-
runWithCorrelation(
|
|
1046
|
-
correlationId,
|
|
1047
|
-
() => runWithActorScope(() => emitOne(row))
|
|
1048
|
-
);
|
|
1049
|
-
}
|
|
1050
|
-
return rows.length;
|
|
1051
|
-
} catch (err) {
|
|
1052
|
-
logger.debug(
|
|
1053
|
-
`sweepAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
|
|
1054
|
-
);
|
|
1055
|
-
return 0;
|
|
1056
|
-
}
|
|
1057
|
-
}
|
|
1058
|
-
async function pruneAuditLog(exec) {
|
|
1059
|
-
if (deleteDenied) return;
|
|
1060
|
-
try {
|
|
1061
|
-
await exec(
|
|
1062
|
-
`DELETE FROM ezlogs_audit_log
|
|
1063
|
-
WHERE id IN (
|
|
1064
|
-
SELECT id FROM ezlogs_audit_log
|
|
1065
|
-
WHERE captured_at < now() - interval '${PRUNE_AGE}'
|
|
1066
|
-
LIMIT ${PRUNE_BATCH})`,
|
|
1067
|
-
[]
|
|
1068
|
-
);
|
|
1069
|
-
} catch (err) {
|
|
1070
|
-
logger.debug(
|
|
1071
|
-
`pruneAuditLog failed: ${err instanceof Error ? err.message : String(err)}`
|
|
1072
|
-
);
|
|
1073
|
-
}
|
|
1074
|
-
}
|
|
1075
|
-
function emitAuditRows(rows) {
|
|
1076
|
-
for (const row of rows) {
|
|
1077
|
-
emitOne(row);
|
|
1078
|
-
}
|
|
1079
|
-
}
|
|
1080
|
-
async function flushAuditLog(exec, options = {}) {
|
|
1081
|
-
if (!exec) return;
|
|
1082
|
-
const correlationId = current();
|
|
1083
|
-
if (!correlationId) return;
|
|
1084
|
-
const rows = await readAuditRows(exec, correlationId, options.since ?? null);
|
|
1085
|
-
await loadTableMeta(exec, rows);
|
|
1086
|
-
emitFresh(rows);
|
|
1087
|
-
const now = Date.now();
|
|
1088
|
-
if (now - lastPruneAt >= PRUNE_INTERVAL_MS) {
|
|
1089
|
-
lastPruneAt = now;
|
|
1090
|
-
await pruneAuditLog(exec);
|
|
1091
|
-
}
|
|
1092
|
-
if (now - lastSweepAt >= SWEEP_INTERVAL_MS) {
|
|
1093
|
-
lastSweepAt = now;
|
|
1094
|
-
await sweepAuditLog(exec);
|
|
1095
|
-
}
|
|
1096
|
-
}
|
|
1097
|
-
var tableMeta = /* @__PURE__ */ new Map();
|
|
1098
|
-
var META_RETRY_MS = 6e4;
|
|
1099
|
-
var metaRetryAt = 0;
|
|
1100
|
-
async function loadTableMeta(exec, rows) {
|
|
1101
|
-
if (Date.now() < metaRetryAt) return;
|
|
1102
|
-
const tables = [
|
|
1103
|
-
...new Set(rows.map((r) => r.table_name).filter((t) => t !== "" && !t.includes(",") && !tableMeta.has(t)))
|
|
1104
|
-
];
|
|
1105
|
-
if (tables.length === 0) return;
|
|
1106
|
-
const list = tables.join(",");
|
|
1107
|
-
try {
|
|
1108
|
-
const fkRows = extractRows(
|
|
1109
|
-
await exec(
|
|
1110
|
-
`SELECT cl.relname AS table_name, a.attname AS column_name, rf.relname AS ref_table
|
|
1111
|
-
FROM pg_constraint c
|
|
1112
|
-
JOIN pg_class cl ON cl.oid = c.conrelid
|
|
1113
|
-
JOIN pg_namespace n ON n.oid = cl.relnamespace
|
|
1114
|
-
JOIN pg_class rf ON rf.oid = c.confrelid
|
|
1115
|
-
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
|
|
1116
|
-
WHERE c.contype = 'f'
|
|
1117
|
-
AND n.nspname = 'public'
|
|
1118
|
-
AND array_length(c.conkey, 1) = 1
|
|
1119
|
-
AND cl.relname = ANY(string_to_array($1, ','))
|
|
1120
|
-
ORDER BY cl.relname, a.attnum`,
|
|
1121
|
-
[list]
|
|
1122
|
-
)
|
|
1123
|
-
);
|
|
1124
|
-
const tsRows = extractRows(
|
|
1125
|
-
await exec(
|
|
1126
|
-
`SELECT cl.relname AS table_name, a.attname AS column_name
|
|
1127
|
-
FROM pg_attribute a
|
|
1128
|
-
JOIN pg_class cl ON cl.oid = a.attrelid
|
|
1129
|
-
JOIN pg_namespace n ON n.oid = cl.relnamespace
|
|
1130
|
-
WHERE n.nspname = 'public'
|
|
1131
|
-
AND cl.relname = ANY(string_to_array($1, ','))
|
|
1132
|
-
AND a.attnum > 0
|
|
1133
|
-
AND NOT a.attisdropped
|
|
1134
|
-
AND a.atttypid = 'timestamp'::regtype`,
|
|
1135
|
-
[list]
|
|
1136
|
-
)
|
|
1137
|
-
);
|
|
1138
|
-
const fks = /* @__PURE__ */ new Map();
|
|
1139
|
-
for (const raw of fkRows) {
|
|
1140
|
-
const r = raw ?? {};
|
|
1141
|
-
if (typeof r.table_name !== "string" || typeof r.column_name !== "string" || typeof r.ref_table !== "string") {
|
|
1142
|
-
continue;
|
|
1143
|
-
}
|
|
1144
|
-
fks.set(r.table_name, [...fks.get(r.table_name) ?? [], { column: r.column_name, refTable: r.ref_table }]);
|
|
1145
|
-
}
|
|
1146
|
-
const timestamps = /* @__PURE__ */ new Map();
|
|
1147
|
-
for (const raw of tsRows) {
|
|
1148
|
-
const r = raw ?? {};
|
|
1149
|
-
if (typeof r.table_name !== "string" || typeof r.column_name !== "string") continue;
|
|
1150
|
-
timestamps.set(r.table_name, (timestamps.get(r.table_name) ?? /* @__PURE__ */ new Set()).add(r.column_name));
|
|
1151
|
-
}
|
|
1152
|
-
for (const table of tables) {
|
|
1153
|
-
tableMeta.set(table, { fks: fks.get(table) ?? [], naiveTimestamps: timestamps.get(table) ?? /* @__PURE__ */ new Set() });
|
|
1154
|
-
}
|
|
1155
|
-
} catch (err) {
|
|
1156
|
-
metaRetryAt = Date.now() + META_RETRY_MS;
|
|
1157
|
-
logger.debug(`table metadata lookup failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1158
|
-
}
|
|
1159
|
-
}
|
|
1160
|
-
function relatedResourceIds(table, row) {
|
|
1161
|
-
const out = [];
|
|
1162
|
-
for (const fk of tableMeta.get(table)?.fks ?? []) {
|
|
1163
|
-
const value = row[fk.column];
|
|
1164
|
-
if (typeof value === "string" || typeof value === "number") {
|
|
1165
|
-
out.push({ resource_type: fk.refTable, resource_id: String(value) });
|
|
1166
|
-
}
|
|
1167
|
-
}
|
|
1168
|
-
return out;
|
|
1169
|
-
}
|
|
1170
|
-
function emitFresh(rows) {
|
|
1171
|
-
if (rows.length === 0) return;
|
|
1172
|
-
const emitted = currentEmittedAuditIds();
|
|
1173
|
-
if (emitted === null) {
|
|
1174
|
-
emitAuditRows(rows);
|
|
1175
|
-
return;
|
|
1176
|
-
}
|
|
1177
|
-
const fresh = [];
|
|
1178
|
-
for (const row of rows) {
|
|
1179
|
-
if (row.id === "" || emitted.has(row.id)) continue;
|
|
1180
|
-
emitted.add(row.id);
|
|
1181
|
-
fresh.push(row);
|
|
1182
|
-
}
|
|
1183
|
-
emitAuditRows(fresh);
|
|
1184
|
-
}
|
|
1185
|
-
function correlationForTx(txid) {
|
|
1186
|
-
if (!txid) return generate();
|
|
1187
|
-
let id = txCorrelation.get(txid);
|
|
1188
|
-
if (!id) {
|
|
1189
|
-
if (txCorrelation.size >= 1e3) txCorrelation.clear();
|
|
1190
|
-
id = generate();
|
|
1191
|
-
txCorrelation.set(txid, id);
|
|
1192
|
-
}
|
|
1193
|
-
return id;
|
|
1194
|
-
}
|
|
1195
|
-
function isPermissionDenied(err) {
|
|
1196
|
-
return err?.code === "42501";
|
|
1197
|
-
}
|
|
1198
|
-
function sortById(rows) {
|
|
1199
|
-
return rows.sort(
|
|
1200
|
-
(a, b) => a.id.length !== b.id.length ? a.id.length - b.id.length : a.id < b.id ? -1 : a.id > b.id ? 1 : 0
|
|
1201
|
-
);
|
|
1202
|
-
}
|
|
1203
|
-
function emitOne(row) {
|
|
1204
|
-
const op = mapOp(row.op);
|
|
1205
|
-
if (!op) return;
|
|
1206
|
-
const naive = tableMeta.get(row.table_name)?.naiveTimestamps ?? null;
|
|
1207
|
-
const oldRow = withUtcTimestamps(coerceJsonb(row.old_row), naive);
|
|
1208
|
-
const newRow = withUtcTimestamps(coerceJsonb(row.new_row), naive);
|
|
1209
|
-
const related = row.resource_id === null ? relatedResourceIds(row.table_name, newRow ?? oldRow ?? {}) : null;
|
|
1210
|
-
if (op === "create" && newRow) {
|
|
1211
|
-
emitDbEvent({
|
|
1212
|
-
modelClass: row.table_name,
|
|
1213
|
-
operation: "create",
|
|
1214
|
-
resourceId: row.resource_id,
|
|
1215
|
-
initialAttributes: newRow,
|
|
1216
|
-
modelInstance: newRow,
|
|
1217
|
-
displayName: null,
|
|
1218
|
-
timestamp: row.captured_at ?? null,
|
|
1219
|
-
relatedResourceIds: related,
|
|
1220
|
-
_fromTrigger: true
|
|
1221
|
-
});
|
|
1222
|
-
return;
|
|
1223
|
-
}
|
|
1224
|
-
if (op === "update" && oldRow && newRow) {
|
|
1225
|
-
const changes = computeChanges(oldRow, newRow);
|
|
1226
|
-
if (changes.length === 0) {
|
|
1227
|
-
return;
|
|
1228
|
-
}
|
|
1229
|
-
emitDbEvent({
|
|
1230
|
-
modelClass: row.table_name,
|
|
1231
|
-
operation: "update",
|
|
1232
|
-
resourceId: row.resource_id,
|
|
1233
|
-
changes,
|
|
1234
|
-
// Prefer the post-state for the display name — that's what the
|
|
1235
|
-
// user just told the system to call this row.
|
|
1236
|
-
modelInstance: newRow,
|
|
1237
|
-
displayName: null,
|
|
1238
|
-
timestamp: row.captured_at ?? null,
|
|
1239
|
-
relatedResourceIds: related,
|
|
1240
|
-
_fromTrigger: true
|
|
1241
|
-
});
|
|
1242
|
-
return;
|
|
1243
|
-
}
|
|
1244
|
-
if (op === "destroy" && oldRow) {
|
|
1245
|
-
emitDbEvent({
|
|
1246
|
-
modelClass: row.table_name,
|
|
1247
|
-
operation: "destroy",
|
|
1248
|
-
resourceId: row.resource_id,
|
|
1249
|
-
initialAttributes: oldRow,
|
|
1250
|
-
modelInstance: oldRow,
|
|
1251
|
-
displayName: null,
|
|
1252
|
-
timestamp: row.captured_at ?? null,
|
|
1253
|
-
relatedResourceIds: related,
|
|
1254
|
-
_fromTrigger: true
|
|
1255
|
-
});
|
|
1256
|
-
return;
|
|
1257
|
-
}
|
|
1258
|
-
}
|
|
1259
|
-
var NAIVE_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;
|
|
1260
|
-
function withUtcTimestamps(row, naiveColumns) {
|
|
1261
|
-
if (!row) return row;
|
|
1262
|
-
const out = {};
|
|
1263
|
-
for (const [key, value] of Object.entries(row)) {
|
|
1264
|
-
const isNaiveColumn = naiveColumns ? naiveColumns.has(key) : /(_at|At)$/.test(key);
|
|
1265
|
-
out[key] = isNaiveColumn && typeof value === "string" && NAIVE_TIMESTAMP.test(value) ? `${value}Z` : value;
|
|
1266
|
-
}
|
|
1267
|
-
return out;
|
|
1268
|
-
}
|
|
1269
|
-
function mapOp(op) {
|
|
1270
|
-
if (op === "INSERT") return "create";
|
|
1271
|
-
if (op === "UPDATE") return "update";
|
|
1272
|
-
if (op === "DELETE") return "destroy";
|
|
1273
|
-
return null;
|
|
1274
|
-
}
|
|
1275
|
-
function computeChanges(oldRow, newRow) {
|
|
1276
|
-
const out = [];
|
|
1277
|
-
for (const key of Object.keys(newRow)) {
|
|
1278
|
-
const before = oldRow[key];
|
|
1279
|
-
const after = newRow[key];
|
|
1280
|
-
if (deepEqual(before, after)) continue;
|
|
1281
|
-
out.push({ attribute: key, from: before, to: after });
|
|
1282
|
-
}
|
|
1283
|
-
return out;
|
|
1284
|
-
}
|
|
1285
|
-
function deepEqual(a, b) {
|
|
1286
|
-
if (a === b) return true;
|
|
1287
|
-
if (a === null || b === null) return false;
|
|
1288
|
-
if (typeof a !== typeof b) return false;
|
|
1289
|
-
if (typeof a !== "object") return false;
|
|
1290
|
-
try {
|
|
1291
|
-
return stableStringify(a) === stableStringify(b);
|
|
1292
|
-
} catch {
|
|
1293
|
-
return false;
|
|
1294
|
-
}
|
|
1295
|
-
}
|
|
1296
|
-
function stableStringify(value) {
|
|
1297
|
-
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
1298
|
-
if (Array.isArray(value)) {
|
|
1299
|
-
return "[" + value.map((v) => stableStringify(v)).join(",") + "]";
|
|
1300
|
-
}
|
|
1301
|
-
const entries = Object.keys(value).sort().map((k) => JSON.stringify(k) + ":" + stableStringify(value[k]));
|
|
1302
|
-
return "{" + entries.join(",") + "}";
|
|
1303
|
-
}
|
|
1304
|
-
function extractRows(result) {
|
|
1305
|
-
if (!result) return [];
|
|
1306
|
-
if (Array.isArray(result)) return result;
|
|
1307
|
-
if (typeof result === "object" && Array.isArray(result.rows)) {
|
|
1308
|
-
return result.rows;
|
|
1309
|
-
}
|
|
1310
|
-
return [];
|
|
1311
|
-
}
|
|
1312
|
-
function toDate(value) {
|
|
1313
|
-
if (value == null) return null;
|
|
1314
|
-
const d = value instanceof Date ? value : new Date(String(value));
|
|
1315
|
-
return Number.isNaN(d.getTime()) ? null : d;
|
|
1316
|
-
}
|
|
1317
|
-
function normalizeAuditRow(raw) {
|
|
1318
|
-
const r = raw ?? {};
|
|
1319
|
-
return {
|
|
1320
|
-
id: r.id == null ? "" : String(r.id),
|
|
1321
|
-
table_name: String(r.table_name ?? ""),
|
|
1322
|
-
op: r.op,
|
|
1323
|
-
old_row: r.old_row ?? null,
|
|
1324
|
-
new_row: r.new_row ?? null,
|
|
1325
|
-
resource_id: r.resource_id == null ? null : String(r.resource_id),
|
|
1326
|
-
correlation_id: r.correlation_id == null ? null : String(r.correlation_id),
|
|
1327
|
-
txid: r.txid == null ? null : String(r.txid),
|
|
1328
|
-
captured_at: toDate(r.captured_at)
|
|
1329
|
-
};
|
|
1330
|
-
}
|
|
1331
|
-
function coerceJsonb(value) {
|
|
1332
|
-
if (value === null || value === void 0) return null;
|
|
1333
|
-
if (typeof value === "string") {
|
|
1334
|
-
try {
|
|
1335
|
-
const parsed = JSON.parse(value);
|
|
1336
|
-
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
1337
|
-
} catch {
|
|
1338
|
-
return null;
|
|
1339
|
-
}
|
|
1340
|
-
}
|
|
1341
|
-
if (typeof value === "object" && !Array.isArray(value)) return value;
|
|
1342
|
-
return null;
|
|
1343
|
-
}
|
|
1344
|
-
|
|
1345
|
-
// src/jobs/shared.ts
|
|
1346
|
-
var CORRELATION_PAYLOAD_KEY = "ezlogs_correlation_id";
|
|
1347
|
-
function emitJobEvent(input) {
|
|
1348
|
-
try {
|
|
1349
|
-
const config = configuration();
|
|
1350
|
-
if (!config.captureJobs) return;
|
|
1351
|
-
if (config.allExcludedJobClasses().includes(input.jobClass)) return;
|
|
1352
|
-
const sourceData = compactJobSourceData({
|
|
1353
|
-
job_class: input.jobClass,
|
|
1354
|
-
job_id: input.jobId ?? null,
|
|
1355
|
-
queue: input.queue ?? null,
|
|
1356
|
-
retry_count: input.retryCount ?? null,
|
|
1357
|
-
arguments: jobArguments(input.payload)
|
|
1358
|
-
});
|
|
1359
|
-
const event = build({
|
|
1360
|
-
source_type: "background_job",
|
|
1361
|
-
source_data: sourceData,
|
|
1362
|
-
outcome: input.outcome,
|
|
1363
|
-
correlation_id: input.correlationId ?? current(),
|
|
1364
|
-
resource_ids: [],
|
|
1365
|
-
context: null,
|
|
1366
|
-
duration_ms: input.durationMs ?? null,
|
|
1367
|
-
error_message: input.errorMessage ?? null,
|
|
1368
|
-
timestamp: input.startedAt
|
|
1369
|
-
});
|
|
1370
|
-
pushEvent(event);
|
|
1371
|
-
} catch (error) {
|
|
1372
|
-
logger.debug(`job emit failed: ${describeError2(error)}`);
|
|
1373
|
-
}
|
|
1374
|
-
}
|
|
1375
|
-
var JOB_FLUSH_SKEW_MS = 500;
|
|
1376
|
-
async function flushJobAuditLog(startedAt) {
|
|
1377
|
-
try {
|
|
1378
|
-
await flushAuditLog(configuration().databaseReader, {
|
|
1379
|
-
since: new Date(startedAt.getTime() - JOB_FLUSH_SKEW_MS)
|
|
1380
|
-
});
|
|
1381
|
-
} catch (error) {
|
|
1382
|
-
logger.debug(`job audit flush failed: ${describeError2(error)}`);
|
|
1383
|
-
}
|
|
1384
|
-
}
|
|
1385
|
-
function jobArguments(payload) {
|
|
1386
|
-
if (payload === null || payload === void 0) return null;
|
|
1387
|
-
const patterns = configuration().excludedGraphqlVariableKeys;
|
|
1388
|
-
if (Array.isArray(payload)) return payload.length === 0 ? null : sanitizeArgs(payload, patterns);
|
|
1389
|
-
if (typeof payload === "object" && Object.getPrototypeOf(payload) === Object.prototype) {
|
|
1390
|
-
const rest = { ...payload };
|
|
1391
|
-
delete rest[CORRELATION_PAYLOAD_KEY];
|
|
1392
|
-
if (Object.keys(rest).length === 0) return null;
|
|
1393
|
-
return sanitizeArgs([rest], patterns)[0];
|
|
1394
|
-
}
|
|
1395
|
-
return sanitizeArgs([payload], patterns);
|
|
1396
|
-
}
|
|
1397
|
-
function extractCorrelationFromPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
|
|
1398
|
-
if (payload === null || typeof payload !== "object") return null;
|
|
1399
|
-
const value = payload[key];
|
|
1400
|
-
return typeof value === "string" && value.length > 0 ? value : null;
|
|
1401
|
-
}
|
|
1402
|
-
function compactJobSourceData(data) {
|
|
1403
|
-
const out = {};
|
|
1404
|
-
for (const key of Object.keys(data)) {
|
|
1405
|
-
const value = data[key];
|
|
1406
|
-
if (value !== null && value !== void 0) out[key] = value;
|
|
1407
|
-
}
|
|
1408
|
-
return out;
|
|
1409
|
-
}
|
|
1410
|
-
function describeError2(error) {
|
|
1411
|
-
if (error instanceof Error) return `${error.name}: ${error.message}`;
|
|
1412
|
-
return String(error);
|
|
1413
|
-
}
|
|
1
|
+
import { extractCorrelationFromPayload, emitJobEvent, flushJobAuditLog } from '../chunk-UQHEW6ER.js';
|
|
2
|
+
import '../chunk-CU45I2WR.js';
|
|
3
|
+
import { current, generate, runWithCorrelation } from '../chunk-CE3R7DVB.js';
|
|
4
|
+
import { logger } from '../chunk-C5OSM557.js';
|
|
5
|
+
import '../chunk-SIAA4J6H.js';
|
|
1414
6
|
|
|
1415
7
|
// src/jobs/inngest.ts
|
|
1416
8
|
function ezlogsInngestMiddleware() {
|
|
@@ -1452,7 +44,7 @@ function ezlogsInngestMiddleware() {
|
|
|
1452
44
|
payload: eventData
|
|
1453
45
|
});
|
|
1454
46
|
} catch (error) {
|
|
1455
|
-
logger.debug(`inngest capture failed: ${
|
|
47
|
+
logger.debug(`inngest capture failed: ${describeError(error)}`);
|
|
1456
48
|
}
|
|
1457
49
|
}
|
|
1458
50
|
};
|
|
@@ -1480,7 +72,7 @@ function ezlogsInngestMiddleware() {
|
|
|
1480
72
|
payload.data = data;
|
|
1481
73
|
}
|
|
1482
74
|
} catch (error) {
|
|
1483
|
-
logger.debug(`inngest send-stamp failed: ${
|
|
75
|
+
logger.debug(`inngest send-stamp failed: ${describeError(error)}`);
|
|
1484
76
|
}
|
|
1485
77
|
}
|
|
1486
78
|
};
|
|
@@ -1510,7 +102,7 @@ function formatError(error) {
|
|
|
1510
102
|
}
|
|
1511
103
|
return String(error);
|
|
1512
104
|
}
|
|
1513
|
-
function
|
|
105
|
+
function describeError(error) {
|
|
1514
106
|
if (error instanceof Error) return `${error.name}: ${error.message}`;
|
|
1515
107
|
return String(error);
|
|
1516
108
|
}
|