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,37 @@
|
|
|
1
|
+
interface SupabaseClientLike {
|
|
2
|
+
schema?: (name: string) => SupabaseSchemaLike;
|
|
3
|
+
rpc?: (fn: string, args?: unknown) => unknown;
|
|
4
|
+
}
|
|
5
|
+
interface SupabaseSchemaLike {
|
|
6
|
+
rpc: (fn: string, args?: unknown) => unknown;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Returns the same client with `.schema('pgmq_public').rpc('send', ...)`
|
|
10
|
+
* instrumented to stamp the current correlation id on the message
|
|
11
|
+
* body. Idempotent.
|
|
12
|
+
*/
|
|
13
|
+
declare function wrapSupabaseQueueClient<T extends SupabaseClientLike>(client: T): T;
|
|
14
|
+
/**
|
|
15
|
+
* Worker-side wrapper. Call this inside your Edge Function / poller
|
|
16
|
+
* for each message you process. It:
|
|
17
|
+
* 1. Reads the correlation id from `message[CORRELATION_PAYLOAD_KEY]`.
|
|
18
|
+
* 2. Runs your `work()` inside that correlation scope.
|
|
19
|
+
* 3. Emits a background_job event on resolve/reject.
|
|
20
|
+
* 4. Re-throws on failure so your retry/ack logic still works.
|
|
21
|
+
*/
|
|
22
|
+
declare function captureQueueMessage<T>(meta: {
|
|
23
|
+
queueName: string;
|
|
24
|
+
message: unknown;
|
|
25
|
+
/** pgmq message id for the row (becomes job_id). Optional. */
|
|
26
|
+
messageId?: string | number | bigint | null;
|
|
27
|
+
/** Number of times this message has been read+attempted. */
|
|
28
|
+
readCount?: number | null;
|
|
29
|
+
}, work: () => Promise<T>): Promise<T>;
|
|
30
|
+
/**
|
|
31
|
+
* Imperatively stamp the correlation id onto a pgmq message body
|
|
32
|
+
* before passing it to a non-wrapped client. Available for users
|
|
33
|
+
* who want explicit control.
|
|
34
|
+
*/
|
|
35
|
+
declare function stampPgmqPayload(message: unknown): unknown;
|
|
36
|
+
|
|
37
|
+
export { captureQueueMessage, stampPgmqPayload, wrapSupabaseQueueClient };
|
|
@@ -0,0 +1,657 @@
|
|
|
1
|
+
import { randomBytes } from 'crypto';
|
|
2
|
+
|
|
3
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
4
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
5
|
+
}) : x)(function(x) {
|
|
6
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
7
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
// src/logger.ts
|
|
11
|
+
var LEVEL_RANK = {
|
|
12
|
+
debug: 10,
|
|
13
|
+
info: 20,
|
|
14
|
+
warn: 30,
|
|
15
|
+
error: 40,
|
|
16
|
+
silent: 100
|
|
17
|
+
};
|
|
18
|
+
var LEVEL_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:log-level");
|
|
19
|
+
function readLevel() {
|
|
20
|
+
const g = globalThis;
|
|
21
|
+
return g[LEVEL_KEY] ?? "warn";
|
|
22
|
+
}
|
|
23
|
+
function shouldLog(level) {
|
|
24
|
+
return LEVEL_RANK[level] >= LEVEL_RANK[readLevel()];
|
|
25
|
+
}
|
|
26
|
+
function safeWrite(level, message) {
|
|
27
|
+
try {
|
|
28
|
+
if (!shouldLog(level)) return;
|
|
29
|
+
const line = `[ezlogs] ${message}`;
|
|
30
|
+
if (level === "error" || level === "warn") {
|
|
31
|
+
console.error(line);
|
|
32
|
+
} else {
|
|
33
|
+
console.log(line);
|
|
34
|
+
}
|
|
35
|
+
} catch {
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
var logger = {
|
|
39
|
+
debug: (message) => safeWrite("debug", message),
|
|
40
|
+
info: (message) => safeWrite("info", message),
|
|
41
|
+
warn: (message) => safeWrite("warn", message),
|
|
42
|
+
error: (message) => safeWrite("error", message)
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
// src/event-builder.ts
|
|
46
|
+
var SENSITIVE_KEYS = Object.freeze([
|
|
47
|
+
"password",
|
|
48
|
+
"token",
|
|
49
|
+
"secret",
|
|
50
|
+
"api_key",
|
|
51
|
+
"credit_card"
|
|
52
|
+
]);
|
|
53
|
+
var VALID_SOURCE_TYPES = [
|
|
54
|
+
"http_request",
|
|
55
|
+
"background_job",
|
|
56
|
+
"database_callback"
|
|
57
|
+
];
|
|
58
|
+
var VALID_OUTCOMES = ["success", "failure"];
|
|
59
|
+
function build(input) {
|
|
60
|
+
const source_type = validateSourceType(input.source_type);
|
|
61
|
+
const source_data_raw = validateSourceData(input.source_data);
|
|
62
|
+
const outcome = validateOutcome(input.outcome);
|
|
63
|
+
const timestamp = validateTimestamp(input.timestamp ?? null);
|
|
64
|
+
const resource_ids = validateResourceIds(input.resource_ids ?? []);
|
|
65
|
+
const context_raw = validateContext();
|
|
66
|
+
const duration_ms = validateDurationMs(input.duration_ms ?? null);
|
|
67
|
+
const error_message = input.error_message ?? null;
|
|
68
|
+
validateOutcomeErrorConsistency(outcome, error_message);
|
|
69
|
+
const source_data = sanitizeRecord(source_data_raw);
|
|
70
|
+
const context = context_raw === null ? null : sanitizeRecord(context_raw);
|
|
71
|
+
const correlation_id = input.correlation_id ?? null;
|
|
72
|
+
const event = {
|
|
73
|
+
timestamp,
|
|
74
|
+
source_type,
|
|
75
|
+
source_data,
|
|
76
|
+
outcome,
|
|
77
|
+
correlation_id,
|
|
78
|
+
resource_ids,
|
|
79
|
+
context,
|
|
80
|
+
duration_ms,
|
|
81
|
+
error_message
|
|
82
|
+
};
|
|
83
|
+
return event;
|
|
84
|
+
}
|
|
85
|
+
function validateSourceType(value) {
|
|
86
|
+
const normalized = String(value);
|
|
87
|
+
if (!VALID_SOURCE_TYPES.includes(normalized)) {
|
|
88
|
+
throw new ArgError(
|
|
89
|
+
`source_type must be one of ${VALID_SOURCE_TYPES.join(", ")}, got: ${normalized}`
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
return normalized;
|
|
93
|
+
}
|
|
94
|
+
function validateSourceData(value) {
|
|
95
|
+
if (value === null || value === void 0) {
|
|
96
|
+
throw new ArgError("source_data is required");
|
|
97
|
+
}
|
|
98
|
+
if (!isPlainObject(value)) {
|
|
99
|
+
throw new ArgError(
|
|
100
|
+
`source_data must be an object, got: ${describe(value)}`
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
return value;
|
|
104
|
+
}
|
|
105
|
+
function validateOutcome(value) {
|
|
106
|
+
if (value === null || value === void 0) {
|
|
107
|
+
throw new ArgError("outcome is required");
|
|
108
|
+
}
|
|
109
|
+
const normalized = String(value);
|
|
110
|
+
if (!VALID_OUTCOMES.includes(normalized)) {
|
|
111
|
+
throw new ArgError(
|
|
112
|
+
`outcome must be one of ${VALID_OUTCOMES.join(", ")}, got: ${normalized}`
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
return normalized;
|
|
116
|
+
}
|
|
117
|
+
function validateTimestamp(value) {
|
|
118
|
+
if (value === null) {
|
|
119
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
120
|
+
}
|
|
121
|
+
if (typeof value === "string") {
|
|
122
|
+
const parsed = new Date(value);
|
|
123
|
+
if (Number.isNaN(parsed.getTime())) {
|
|
124
|
+
throw new ArgError(
|
|
125
|
+
`timestamp must be valid ISO 8601 format, got: ${value}`
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
return value;
|
|
129
|
+
}
|
|
130
|
+
if (value instanceof Date) {
|
|
131
|
+
if (Number.isNaN(value.getTime())) {
|
|
132
|
+
throw new ArgError("timestamp must be a valid Date");
|
|
133
|
+
}
|
|
134
|
+
return value.toISOString();
|
|
135
|
+
}
|
|
136
|
+
throw new ArgError(
|
|
137
|
+
`timestamp must be a string or Date, got: ${describe(value)}`
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
function validateResourceIds(value) {
|
|
141
|
+
if (!Array.isArray(value)) {
|
|
142
|
+
throw new ArgError(`resource_ids must be an array, got: ${describe(value)}`);
|
|
143
|
+
}
|
|
144
|
+
value.forEach((entry, index) => {
|
|
145
|
+
if (!isPlainObject(entry)) {
|
|
146
|
+
throw new ArgError(
|
|
147
|
+
`resource_ids[${index}] must be an object, got: ${describe(entry)}`
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
const e = entry;
|
|
151
|
+
if (!("resource_type" in e) || !("resource_id" in e)) {
|
|
152
|
+
throw new ArgError(
|
|
153
|
+
`resource_ids[${index}] must have resource_type and resource_id keys, got: ${Object.keys(e).join(", ")}`
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
if (typeof e.resource_type !== "string") {
|
|
157
|
+
throw new ArgError(
|
|
158
|
+
`resource_ids[${index}].resource_type must be a string, got: ${describe(e.resource_type)}`
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
if (typeof e.resource_id !== "string") {
|
|
162
|
+
throw new ArgError(
|
|
163
|
+
`resource_ids[${index}].resource_id must be a string, got: ${describe(e.resource_id)}`
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
return value;
|
|
168
|
+
}
|
|
169
|
+
function validateContext(value) {
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
function validateDurationMs(value) {
|
|
173
|
+
if (value === null || value === void 0) return null;
|
|
174
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
175
|
+
throw new ArgError(`duration_ms must be a number, got: ${describe(value)}`);
|
|
176
|
+
}
|
|
177
|
+
if (!Number.isInteger(value)) {
|
|
178
|
+
throw new ArgError(`duration_ms must be an integer, got: ${value}`);
|
|
179
|
+
}
|
|
180
|
+
if (value < 0) {
|
|
181
|
+
throw new ArgError(`duration_ms must be >= 0, got: ${value}`);
|
|
182
|
+
}
|
|
183
|
+
return value;
|
|
184
|
+
}
|
|
185
|
+
function validateOutcomeErrorConsistency(outcome, error_message) {
|
|
186
|
+
if (outcome === "failure") {
|
|
187
|
+
if (error_message === null || error_message === "") {
|
|
188
|
+
throw new ArgError("error_message is required when outcome is 'failure'");
|
|
189
|
+
}
|
|
190
|
+
} else if (outcome === "success") {
|
|
191
|
+
if (error_message !== null) {
|
|
192
|
+
throw new ArgError("error_message must be null when outcome is 'success'");
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
function sanitizeRecord(input) {
|
|
197
|
+
const result = {};
|
|
198
|
+
for (const key of Object.keys(input)) {
|
|
199
|
+
const value = input[key];
|
|
200
|
+
if (isSensitiveKey(key)) {
|
|
201
|
+
result[key] = "[FILTERED]";
|
|
202
|
+
} else if (isPlainObject(value)) {
|
|
203
|
+
result[key] = sanitizeRecord(value);
|
|
204
|
+
} else if (Array.isArray(value)) {
|
|
205
|
+
result[key] = value.map(
|
|
206
|
+
(item) => isPlainObject(item) ? sanitizeRecord(item) : item
|
|
207
|
+
);
|
|
208
|
+
} else {
|
|
209
|
+
result[key] = value;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return result;
|
|
213
|
+
}
|
|
214
|
+
function isSensitiveKey(key) {
|
|
215
|
+
const lower = key.toLowerCase();
|
|
216
|
+
return SENSITIVE_KEYS.some((p) => lower.includes(p));
|
|
217
|
+
}
|
|
218
|
+
function isPlainObject(value) {
|
|
219
|
+
if (value === null || typeof value !== "object") return false;
|
|
220
|
+
const proto = Object.getPrototypeOf(value);
|
|
221
|
+
return proto === Object.prototype || proto === null;
|
|
222
|
+
}
|
|
223
|
+
function describe(value) {
|
|
224
|
+
if (value === null) return "null";
|
|
225
|
+
if (Array.isArray(value)) return "Array";
|
|
226
|
+
return typeof value;
|
|
227
|
+
}
|
|
228
|
+
var ArgError = class extends Error {
|
|
229
|
+
constructor(message) {
|
|
230
|
+
super(message);
|
|
231
|
+
this.name = "ArgError";
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
// src/configuration.ts
|
|
236
|
+
var DEFAULT_EXCLUDED_PATHS = Object.freeze([
|
|
237
|
+
// Next.js / Vercel infrastructure noise
|
|
238
|
+
"/_next/*",
|
|
239
|
+
"/_vercel/*",
|
|
240
|
+
"/__nextjs_*",
|
|
241
|
+
// NextAuth.js / Auth.js — skip session-refresh polls and CSRF/provider
|
|
242
|
+
// metadata GETs (high-frequency, no business meaning), but CAPTURE
|
|
243
|
+
// POSTs (callbacks, signin, signout, register). The POSTs are the
|
|
244
|
+
// actual auth events users care about; the GETs are pure plumbing.
|
|
245
|
+
Object.freeze({ path: "/api/auth/*", methods: ["GET", "HEAD"] }),
|
|
246
|
+
// Generic infrastructure
|
|
247
|
+
"/health*",
|
|
248
|
+
"/api/health",
|
|
249
|
+
"/up",
|
|
250
|
+
"/alive",
|
|
251
|
+
"/ready",
|
|
252
|
+
"/metrics",
|
|
253
|
+
"/favicon.ico",
|
|
254
|
+
"/.well-known*",
|
|
255
|
+
"/robots.txt",
|
|
256
|
+
"/sitemap.xml",
|
|
257
|
+
"/*.hot-update.*",
|
|
258
|
+
// Auth routes (common patterns across Clerk, NextAuth, custom auth)
|
|
259
|
+
"*/login*",
|
|
260
|
+
"*/logout*",
|
|
261
|
+
"*/sign-in*",
|
|
262
|
+
"*/sign-out*",
|
|
263
|
+
"*/signin*",
|
|
264
|
+
"*/signout*",
|
|
265
|
+
"/session*"
|
|
266
|
+
]);
|
|
267
|
+
var DEFAULT_EXCLUDED_TABLES = Object.freeze([
|
|
268
|
+
// Prisma migration ledger
|
|
269
|
+
"_prisma_migrations",
|
|
270
|
+
// Auth.js / NextAuth Prisma adapter — session/verification-token churn
|
|
271
|
+
// is auth machinery, not business activity. Account/User stay captured.
|
|
272
|
+
"Session",
|
|
273
|
+
"VerificationToken",
|
|
274
|
+
// Common cross-stack convention names for the same things
|
|
275
|
+
"sessions",
|
|
276
|
+
"session",
|
|
277
|
+
"verification_tokens"
|
|
278
|
+
]);
|
|
279
|
+
var DEFAULT_EXCLUDED_JOB_CLASSES = Object.freeze([]);
|
|
280
|
+
var DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS = Object.freeze(["IntrospectionQuery", "__*"]);
|
|
281
|
+
var DEFAULT_SERVER_URL = "https://app.ezlogs.io";
|
|
282
|
+
var Configuration = class {
|
|
283
|
+
serverUrl = DEFAULT_SERVER_URL;
|
|
284
|
+
projectToken = null;
|
|
285
|
+
captureHttp = true;
|
|
286
|
+
captureDb = true;
|
|
287
|
+
captureJobs = true;
|
|
288
|
+
bufferSize = 1e4;
|
|
289
|
+
/** Default 3000 ms — equivalent to Ruby's 3 seconds. */
|
|
290
|
+
sendInterval = 3e3;
|
|
291
|
+
retryAttempts = 3;
|
|
292
|
+
logLevel = "warn";
|
|
293
|
+
patchGlobalFetch = true;
|
|
294
|
+
actorFromSupabase = true;
|
|
295
|
+
excludedPaths = [];
|
|
296
|
+
excludedTables = [];
|
|
297
|
+
excludedJobClasses = [];
|
|
298
|
+
excludedGraphqlOperations = [];
|
|
299
|
+
excludedGraphqlVariableKeys = [];
|
|
300
|
+
actorFromRequest = null;
|
|
301
|
+
displayNameFor = {};
|
|
302
|
+
isServerActionError = null;
|
|
303
|
+
databaseReader = null;
|
|
304
|
+
databaseSnapshotMode = false;
|
|
305
|
+
databaseUrl = null;
|
|
306
|
+
/**
|
|
307
|
+
* Tables that have the `ezlogs_audit` trigger attached. Detected once
|
|
308
|
+
* at agent startup by reading `information_schema.triggers`. The
|
|
309
|
+
* supabase / drizzle / prisma adapters use this to decide whether
|
|
310
|
+
* their per-mutation emit is redundant: if the table is trigger-
|
|
311
|
+
* tracked the audit-log reader will surface the same write with full
|
|
312
|
+
* old/new state, so the adapter's emit is suppressed. Tables NOT in
|
|
313
|
+
* this set fall through to the adapter so they're still captured.
|
|
314
|
+
*
|
|
315
|
+
* `null` means "detection hasn't run yet or failed" — in that state
|
|
316
|
+
* `databaseReader`-wired apps suppress every adapter emit (the
|
|
317
|
+
* original Phase 5 behavior). After detection completes the agent
|
|
318
|
+
* gives the more accurate per-table answer.
|
|
319
|
+
*/
|
|
320
|
+
triggerTrackedTables = null;
|
|
321
|
+
apply(options) {
|
|
322
|
+
if (options.serverUrl !== void 0) this.serverUrl = options.serverUrl;
|
|
323
|
+
this.projectToken = options.projectToken;
|
|
324
|
+
if (options.captureHttp !== void 0) this.captureHttp = options.captureHttp;
|
|
325
|
+
if (options.captureDb !== void 0) this.captureDb = options.captureDb;
|
|
326
|
+
if (options.captureJobs !== void 0) this.captureJobs = options.captureJobs;
|
|
327
|
+
if (options.bufferSize !== void 0) this.bufferSize = options.bufferSize;
|
|
328
|
+
if (options.sendInterval !== void 0) this.sendInterval = options.sendInterval;
|
|
329
|
+
if (options.retryAttempts !== void 0) this.retryAttempts = options.retryAttempts;
|
|
330
|
+
if (options.excludedPaths) this.excludedPaths = [...options.excludedPaths];
|
|
331
|
+
if (options.excludedTables) this.excludedTables = [...options.excludedTables];
|
|
332
|
+
if (options.excludedJobClasses) {
|
|
333
|
+
this.excludedJobClasses = [...options.excludedJobClasses];
|
|
334
|
+
}
|
|
335
|
+
if (options.excludedGraphqlOperations) {
|
|
336
|
+
this.excludedGraphqlOperations = [...options.excludedGraphqlOperations];
|
|
337
|
+
}
|
|
338
|
+
if (options.excludedGraphqlVariableKeys) {
|
|
339
|
+
this.excludedGraphqlVariableKeys = [...options.excludedGraphqlVariableKeys];
|
|
340
|
+
}
|
|
341
|
+
if (options.actorFromRequest) this.actorFromRequest = options.actorFromRequest;
|
|
342
|
+
if (options.displayNameFor) this.displayNameFor = { ...options.displayNameFor };
|
|
343
|
+
if (options.isServerActionError) this.isServerActionError = options.isServerActionError;
|
|
344
|
+
if (options.patchGlobalFetch !== void 0) {
|
|
345
|
+
this.patchGlobalFetch = options.patchGlobalFetch;
|
|
346
|
+
}
|
|
347
|
+
if (options.actorFromSupabase !== void 0) {
|
|
348
|
+
this.actorFromSupabase = options.actorFromSupabase;
|
|
349
|
+
}
|
|
350
|
+
if (options.databaseReader !== void 0) {
|
|
351
|
+
this.databaseReader = options.databaseReader;
|
|
352
|
+
}
|
|
353
|
+
if (options.databaseSnapshotMode !== void 0) {
|
|
354
|
+
this.databaseSnapshotMode = options.databaseSnapshotMode;
|
|
355
|
+
}
|
|
356
|
+
if (options.databaseUrl !== void 0) {
|
|
357
|
+
this.databaseUrl = options.databaseUrl;
|
|
358
|
+
}
|
|
359
|
+
if (options.logLevel) this.logLevel = options.logLevel;
|
|
360
|
+
}
|
|
361
|
+
allExcludedPaths() {
|
|
362
|
+
return [...DEFAULT_EXCLUDED_PATHS, ...this.excludedPaths];
|
|
363
|
+
}
|
|
364
|
+
allExcludedTables() {
|
|
365
|
+
return [...DEFAULT_EXCLUDED_TABLES, ...this.excludedTables];
|
|
366
|
+
}
|
|
367
|
+
allExcludedJobClasses() {
|
|
368
|
+
return [...DEFAULT_EXCLUDED_JOB_CLASSES, ...this.excludedJobClasses];
|
|
369
|
+
}
|
|
370
|
+
allExcludedGraphqlOperations() {
|
|
371
|
+
return [...DEFAULT_EXCLUDED_GRAPHQL_OPERATIONS, ...this.excludedGraphqlOperations];
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
var GLOBAL_CONFIG_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:configuration");
|
|
375
|
+
function configuration() {
|
|
376
|
+
const g = globalThis;
|
|
377
|
+
if (!g[GLOBAL_CONFIG_KEY]) {
|
|
378
|
+
g[GLOBAL_CONFIG_KEY] = new Configuration();
|
|
379
|
+
}
|
|
380
|
+
return g[GLOBAL_CONFIG_KEY];
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// src/pipeline/buffer.ts
|
|
384
|
+
var GLOBAL_QUEUE_KEY = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:buffer-queue");
|
|
385
|
+
function getQueue() {
|
|
386
|
+
const g = globalThis;
|
|
387
|
+
if (!g[GLOBAL_QUEUE_KEY]) g[GLOBAL_QUEUE_KEY] = [];
|
|
388
|
+
return g[GLOBAL_QUEUE_KEY];
|
|
389
|
+
}
|
|
390
|
+
function pushEvent(event) {
|
|
391
|
+
try {
|
|
392
|
+
const queue = getQueue();
|
|
393
|
+
const max = maxSize();
|
|
394
|
+
if (queue.length >= max) {
|
|
395
|
+
queue.shift();
|
|
396
|
+
logger.warn(`Buffer full (${max}), dropped oldest event`);
|
|
397
|
+
}
|
|
398
|
+
queue.push(event);
|
|
399
|
+
} catch (error) {
|
|
400
|
+
logger.error(`pushEvent failed: ${describe2(error)}`);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
function maxSize() {
|
|
404
|
+
try {
|
|
405
|
+
return configuration().bufferSize;
|
|
406
|
+
} catch {
|
|
407
|
+
return 1e4;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
function describe2(error) {
|
|
411
|
+
if (error instanceof Error) return `${error.name}: ${error.message}`;
|
|
412
|
+
return String(error);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// src/edge-fallback.ts
|
|
416
|
+
var ALS_CTOR = loadAsyncLocalStorage();
|
|
417
|
+
function loadAsyncLocalStorage() {
|
|
418
|
+
const fromGlobal = globalThis.AsyncLocalStorage;
|
|
419
|
+
if (typeof fromGlobal === "function") return fromGlobal;
|
|
420
|
+
try {
|
|
421
|
+
const req = typeof __require !== "undefined" ? __require : (
|
|
422
|
+
// In ESM, `createRequire` is the official escape hatch.
|
|
423
|
+
// We pull it via globalThis to avoid a static `import`
|
|
424
|
+
// that would itself be browser-bundled.
|
|
425
|
+
void 0
|
|
426
|
+
);
|
|
427
|
+
if (typeof req === "function") {
|
|
428
|
+
const moduleName = ["async", "hooks"].join("_");
|
|
429
|
+
const mod = req("node:" + moduleName);
|
|
430
|
+
if (typeof mod.AsyncLocalStorage === "function") return mod.AsyncLocalStorage;
|
|
431
|
+
}
|
|
432
|
+
} catch {
|
|
433
|
+
}
|
|
434
|
+
return null;
|
|
435
|
+
}
|
|
436
|
+
function createScopedStorage(key = /* @__PURE__ */ Symbol.for("ezlogs-nextjs:default-scoped-storage")) {
|
|
437
|
+
const globalStore = globalThis;
|
|
438
|
+
let entry = globalStore[key];
|
|
439
|
+
if (!entry) {
|
|
440
|
+
const als2 = (() => {
|
|
441
|
+
if (!ALS_CTOR) return null;
|
|
442
|
+
try {
|
|
443
|
+
return new ALS_CTOR();
|
|
444
|
+
} catch {
|
|
445
|
+
return null;
|
|
446
|
+
}
|
|
447
|
+
})();
|
|
448
|
+
entry = { als: als2, edgeFallback: null };
|
|
449
|
+
globalStore[key] = entry;
|
|
450
|
+
}
|
|
451
|
+
const als = entry.als;
|
|
452
|
+
const stateRef = entry;
|
|
453
|
+
return {
|
|
454
|
+
read() {
|
|
455
|
+
if (als) return als.getStore()?.value ?? null;
|
|
456
|
+
return stateRef.edgeFallback?.value ?? null;
|
|
457
|
+
},
|
|
458
|
+
run(value, callback) {
|
|
459
|
+
if (als) return als.run({ value }, callback);
|
|
460
|
+
const previous = stateRef.edgeFallback;
|
|
461
|
+
stateRef.edgeFallback = { value };
|
|
462
|
+
try {
|
|
463
|
+
return callback();
|
|
464
|
+
} finally {
|
|
465
|
+
stateRef.edgeFallback = previous;
|
|
466
|
+
}
|
|
467
|
+
},
|
|
468
|
+
update(value) {
|
|
469
|
+
if (als) {
|
|
470
|
+
const store = als.getStore();
|
|
471
|
+
if (store) store.value = value;
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
stateRef.edgeFallback = { value };
|
|
475
|
+
},
|
|
476
|
+
_resetForTests() {
|
|
477
|
+
stateRef.edgeFallback = null;
|
|
478
|
+
},
|
|
479
|
+
_isAsyncLocalStorage() {
|
|
480
|
+
return als !== null;
|
|
481
|
+
}
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// src/correlation.ts
|
|
486
|
+
var storage = createScopedStorage(
|
|
487
|
+
/* @__PURE__ */ Symbol.for("ezlogs-nextjs:correlation-storage")
|
|
488
|
+
);
|
|
489
|
+
function generate() {
|
|
490
|
+
const ts = Date.now();
|
|
491
|
+
const hex = randomBytes(4).toString("hex");
|
|
492
|
+
return `ezl_${ts}_${hex}`;
|
|
493
|
+
}
|
|
494
|
+
function current() {
|
|
495
|
+
return storage.read();
|
|
496
|
+
}
|
|
497
|
+
function runWithCorrelation(correlationId, callback) {
|
|
498
|
+
return storage.run(correlationId, callback);
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// src/jobs/shared.ts
|
|
502
|
+
var CORRELATION_PAYLOAD_KEY = "ezlogs_correlation_id";
|
|
503
|
+
function emitJobEvent(input) {
|
|
504
|
+
try {
|
|
505
|
+
const config = configuration();
|
|
506
|
+
if (!config.captureJobs) return;
|
|
507
|
+
if (config.allExcludedJobClasses().includes(input.jobClass)) return;
|
|
508
|
+
const sourceData = compactJobSourceData({
|
|
509
|
+
job_class: input.jobClass,
|
|
510
|
+
job_id: input.jobId ?? null,
|
|
511
|
+
queue: input.queue ?? null,
|
|
512
|
+
retry_count: input.retryCount ?? null
|
|
513
|
+
});
|
|
514
|
+
const event = build({
|
|
515
|
+
source_type: "background_job",
|
|
516
|
+
source_data: sourceData,
|
|
517
|
+
outcome: input.outcome,
|
|
518
|
+
correlation_id: input.correlationId ?? current(),
|
|
519
|
+
resource_ids: [],
|
|
520
|
+
context: null,
|
|
521
|
+
duration_ms: input.durationMs ?? null,
|
|
522
|
+
error_message: input.errorMessage ?? null,
|
|
523
|
+
timestamp: input.startedAt
|
|
524
|
+
});
|
|
525
|
+
pushEvent(event);
|
|
526
|
+
} catch (error) {
|
|
527
|
+
logger.debug(`job emit failed: ${describeError(error)}`);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
async function runJobWithCapture(meta, work) {
|
|
531
|
+
const correlationId = meta.correlationId ?? generate();
|
|
532
|
+
return runWithCorrelation(correlationId, async () => {
|
|
533
|
+
const startedAt = /* @__PURE__ */ new Date();
|
|
534
|
+
const startMs = startedAt.getTime();
|
|
535
|
+
const baseMeta = {
|
|
536
|
+
jobClass: meta.jobClass,
|
|
537
|
+
jobId: meta.jobId ?? null,
|
|
538
|
+
queue: meta.queue ?? null,
|
|
539
|
+
retryCount: meta.retryCount ?? null,
|
|
540
|
+
correlationId,
|
|
541
|
+
startedAt
|
|
542
|
+
};
|
|
543
|
+
try {
|
|
544
|
+
const result = await work();
|
|
545
|
+
emitJobEvent({
|
|
546
|
+
...baseMeta,
|
|
547
|
+
outcome: "success",
|
|
548
|
+
durationMs: Date.now() - startMs
|
|
549
|
+
});
|
|
550
|
+
return result;
|
|
551
|
+
} catch (error) {
|
|
552
|
+
const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
553
|
+
emitJobEvent({
|
|
554
|
+
...baseMeta,
|
|
555
|
+
outcome: "failure",
|
|
556
|
+
errorMessage: message,
|
|
557
|
+
durationMs: Date.now() - startMs
|
|
558
|
+
});
|
|
559
|
+
throw error;
|
|
560
|
+
}
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
function extractCorrelationFromPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
|
|
564
|
+
if (payload === null || typeof payload !== "object") return null;
|
|
565
|
+
const value = payload[key];
|
|
566
|
+
return typeof value === "string" && value.length > 0 ? value : null;
|
|
567
|
+
}
|
|
568
|
+
function stampCorrelationOnPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
|
|
569
|
+
if (!payload || typeof payload !== "object") return;
|
|
570
|
+
if (typeof payload[key] === "string" && payload[key]) return;
|
|
571
|
+
const id = current();
|
|
572
|
+
if (!id) return;
|
|
573
|
+
payload[key] = id;
|
|
574
|
+
}
|
|
575
|
+
function compactJobSourceData(data) {
|
|
576
|
+
const out = {};
|
|
577
|
+
for (const key of Object.keys(data)) {
|
|
578
|
+
const value = data[key];
|
|
579
|
+
if (value !== null && value !== void 0) out[key] = value;
|
|
580
|
+
}
|
|
581
|
+
return out;
|
|
582
|
+
}
|
|
583
|
+
function describeError(error) {
|
|
584
|
+
if (error instanceof Error) return `${error.name}: ${error.message}`;
|
|
585
|
+
return String(error);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// src/jobs/supabase-queues.ts
|
|
589
|
+
var WRAPPED_FLAG = "__ezlogsSupabaseQueuesWrapped";
|
|
590
|
+
function wrapSupabaseQueueClient(client) {
|
|
591
|
+
if (client[WRAPPED_FLAG]) return client;
|
|
592
|
+
if (typeof client.schema !== "function") return client;
|
|
593
|
+
const originalSchema = client.schema.bind(client);
|
|
594
|
+
const wrappedSchema = (name) => {
|
|
595
|
+
const schema = originalSchema(name);
|
|
596
|
+
if (name === "pgmq_public") return wrapPgmqSchema(schema);
|
|
597
|
+
return schema;
|
|
598
|
+
};
|
|
599
|
+
client.schema = wrappedSchema;
|
|
600
|
+
Object.defineProperty(client, WRAPPED_FLAG, {
|
|
601
|
+
value: true,
|
|
602
|
+
enumerable: false,
|
|
603
|
+
configurable: false
|
|
604
|
+
});
|
|
605
|
+
return client;
|
|
606
|
+
}
|
|
607
|
+
function wrapPgmqSchema(schema) {
|
|
608
|
+
if (typeof schema.rpc !== "function") return schema;
|
|
609
|
+
const originalRpc = schema.rpc.bind(schema);
|
|
610
|
+
const wrappedRpc = (fn, args) => {
|
|
611
|
+
if ((fn === "send" || fn === "send_batch") && isPlainObject2(args)) {
|
|
612
|
+
const stamped = stampPgmqMessage(args);
|
|
613
|
+
return originalRpc(fn, stamped);
|
|
614
|
+
}
|
|
615
|
+
return originalRpc(fn, args);
|
|
616
|
+
};
|
|
617
|
+
schema.rpc = wrappedRpc;
|
|
618
|
+
return schema;
|
|
619
|
+
}
|
|
620
|
+
function stampPgmqMessage(args) {
|
|
621
|
+
if ("message" in args && isPlainObject2(args.message)) {
|
|
622
|
+
stampCorrelationOnPayload(args.message);
|
|
623
|
+
} else if (Array.isArray(args.messages)) {
|
|
624
|
+
for (const msg of args.messages) {
|
|
625
|
+
if (isPlainObject2(msg)) {
|
|
626
|
+
stampCorrelationOnPayload(msg);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
return args;
|
|
631
|
+
}
|
|
632
|
+
async function captureQueueMessage(meta, work) {
|
|
633
|
+
const correlationId = extractCorrelationFromPayload(meta.message);
|
|
634
|
+
return runJobWithCapture(
|
|
635
|
+
{
|
|
636
|
+
jobClass: meta.queueName,
|
|
637
|
+
jobId: meta.messageId !== void 0 && meta.messageId !== null ? String(meta.messageId) : null,
|
|
638
|
+
queue: meta.queueName,
|
|
639
|
+
retryCount: meta.readCount ?? null,
|
|
640
|
+
correlationId
|
|
641
|
+
},
|
|
642
|
+
work
|
|
643
|
+
);
|
|
644
|
+
}
|
|
645
|
+
function stampPgmqPayload(message) {
|
|
646
|
+
if (!isPlainObject2(message)) return message;
|
|
647
|
+
stampCorrelationOnPayload(message);
|
|
648
|
+
return message;
|
|
649
|
+
}
|
|
650
|
+
function isPlainObject2(value) {
|
|
651
|
+
if (value === null || typeof value !== "object") return false;
|
|
652
|
+
if (Array.isArray(value)) return false;
|
|
653
|
+
if (value instanceof Date) return false;
|
|
654
|
+
return true;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
export { captureQueueMessage, stampPgmqPayload, wrapSupabaseQueueClient };
|