ezlogs-nextjs 0.3.1 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +149 -30
  2. package/bin/install-triggers.cjs +7 -2
  3. package/dist/actors/index.cjs +4 -4
  4. package/dist/actors/index.d.cts +1 -1
  5. package/dist/actors/index.d.ts +1 -1
  6. package/dist/actors/index.js +1 -1
  7. package/dist/{chunk-C5OSM557.js → chunk-FCFVIRQF.js} +7 -0
  8. package/dist/chunk-GI6BM4MR.js +443 -0
  9. package/dist/{chunk-YX2XPLOA.cjs → chunk-GMHOUAKD.cjs} +63 -34
  10. package/dist/{chunk-CU45I2WR.js → chunk-MHBS5FEP.js} +48 -20
  11. package/dist/chunk-MMLQXSSD.cjs +461 -0
  12. package/dist/{chunk-CE3R7DVB.js → chunk-NINIAL7M.js} +60 -384
  13. package/dist/{chunk-Y5NSHKWQ.cjs → chunk-NX4EL7BY.cjs} +57 -7
  14. package/dist/chunk-PS4U2GFJ.cjs +52 -0
  15. package/dist/chunk-R6IWVTX3.cjs +212 -0
  16. package/dist/{chunk-V5YNKKTG.cjs → chunk-TWTG5ILJ.cjs} +7 -0
  17. package/dist/chunk-U22T7QYY.js +200 -0
  18. package/dist/chunk-YMIGZYFH.js +48 -0
  19. package/dist/{chunk-WASXTDLW.cjs → chunk-YXZZNZG6.cjs} +71 -403
  20. package/dist/{chunk-DKRNNI4I.js → chunk-Z2TM3LGG.js} +53 -3
  21. package/dist/{configuration-OHLNivON.d.ts → configuration-CJ5yKVlP.d.cts} +14 -8
  22. package/dist/{configuration-OHLNivON.d.cts → configuration-CJ5yKVlP.d.ts} +14 -8
  23. package/dist/db/drizzle.cjs +5 -4
  24. package/dist/db/drizzle.js +3 -2
  25. package/dist/db/postgres-js.cjs +98 -0
  26. package/dist/db/postgres-js.d.cts +11 -0
  27. package/dist/db/postgres-js.d.ts +11 -0
  28. package/dist/db/postgres-js.js +95 -0
  29. package/dist/db/prisma.cjs +21 -20
  30. package/dist/db/prisma.d.cts +19 -2
  31. package/dist/db/prisma.d.ts +19 -2
  32. package/dist/db/prisma.js +6 -5
  33. package/dist/db/supabase.cjs +19 -12
  34. package/dist/db/supabase.d.cts +3 -2
  35. package/dist/db/supabase.d.ts +3 -2
  36. package/dist/db/supabase.js +11 -4
  37. package/dist/index.cjs +596 -165
  38. package/dist/index.d.cts +5 -3
  39. package/dist/index.d.ts +5 -3
  40. package/dist/index.js +492 -62
  41. package/dist/jobs/bullmq.cjs +63 -18
  42. package/dist/jobs/bullmq.d.cts +0 -4
  43. package/dist/jobs/bullmq.d.ts +0 -4
  44. package/dist/jobs/bullmq.js +59 -14
  45. package/dist/jobs/inngest.cjs +61 -24
  46. package/dist/jobs/inngest.d.cts +5 -1
  47. package/dist/jobs/inngest.d.ts +5 -1
  48. package/dist/jobs/inngest.js +55 -18
  49. package/dist/jobs/supabase-queues.cjs +17 -15
  50. package/dist/jobs/supabase-queues.d.cts +1 -1
  51. package/dist/jobs/supabase-queues.d.ts +1 -1
  52. package/dist/jobs/supabase-queues.js +15 -13
  53. package/dist/jobs/trigger.cjs +11 -12
  54. package/dist/jobs/trigger.d.cts +4 -3
  55. package/dist/jobs/trigger.d.ts +4 -3
  56. package/dist/jobs/trigger.js +7 -8
  57. package/dist/jobs/upstash-workflow.cjs +43 -35
  58. package/dist/jobs/upstash-workflow.d.cts +2 -8
  59. package/dist/jobs/upstash-workflow.d.ts +2 -8
  60. package/dist/jobs/upstash-workflow.js +38 -30
  61. package/dist/nextjs-plugin/index.cjs +39 -3
  62. package/dist/nextjs-plugin/index.d.cts +8 -1
  63. package/dist/nextjs-plugin/index.d.ts +8 -1
  64. package/dist/nextjs-plugin/index.js +39 -3
  65. package/dist/nextjs-plugin/loader.cjs +41 -3
  66. package/dist/nextjs-plugin/loader.d.cts +1 -0
  67. package/dist/nextjs-plugin/loader.d.ts +1 -0
  68. package/dist/nextjs-plugin/loader.js +42 -4
  69. package/dist/triggers/index.cjs +145 -92
  70. package/dist/triggers/index.d.cts +20 -5
  71. package/dist/triggers/index.d.ts +20 -5
  72. package/dist/triggers/index.js +125 -82
  73. package/package.json +11 -1
  74. package/sql/postgres/00_install.sql +1 -1
  75. package/dist/chunk-UQHEW6ER.js +0 -119
  76. package/dist/chunk-UWHYJH4M.cjs +0 -126
@@ -0,0 +1,212 @@
1
+ 'use strict';
2
+
3
+ var chunkGMHOUAKD_cjs = require('./chunk-GMHOUAKD.cjs');
4
+ var chunkYXZZNZG6_cjs = require('./chunk-YXZZNZG6.cjs');
5
+ var chunkMMLQXSSD_cjs = require('./chunk-MMLQXSSD.cjs');
6
+ var chunkTWTG5ILJ_cjs = require('./chunk-TWTG5ILJ.cjs');
7
+
8
+ // src/jobs/shared.ts
9
+ var CORRELATION_PAYLOAD_KEY = "ezlogs_correlation_id";
10
+ var ACTOR_PAYLOAD_KEY = "ezlogs_actor";
11
+ var ACTOR_TOKEN = /^a([0-9a-f]{2,128})_([0-9a-f]{16})$/;
12
+ var ACTOR_ID_MAX_BYTES = 64;
13
+ function emitJobEvent(input) {
14
+ try {
15
+ const config = chunkMMLQXSSD_cjs.configuration();
16
+ if (!config.captureJobs) return;
17
+ if (config.allExcludedJobClasses().includes(input.jobClass)) return;
18
+ const sourceData = compactJobSourceData({
19
+ job_class: input.jobClass,
20
+ job_id: input.jobId ?? null,
21
+ queue: input.queue ?? null,
22
+ retry_count: input.retryCount ?? null,
23
+ arguments: jobArguments(input.payload)
24
+ });
25
+ const event = chunkYXZZNZG6_cjs.build({
26
+ source_type: "background_job",
27
+ source_data: sourceData,
28
+ outcome: input.outcome,
29
+ correlation_id: input.correlationId ?? chunkMMLQXSSD_cjs.current(),
30
+ resource_ids: [],
31
+ context: null,
32
+ duration_ms: input.durationMs ?? null,
33
+ error_message: input.errorMessage ?? null,
34
+ timestamp: input.startedAt
35
+ });
36
+ chunkYXZZNZG6_cjs.pushEvent(event);
37
+ } catch (error) {
38
+ chunkTWTG5ILJ_cjs.logger.debug(`job emit failed: ${describeError(error)}`);
39
+ }
40
+ }
41
+ async function runJobWithCapture(meta, work) {
42
+ const correlationId = meta.correlationId ?? chunkMMLQXSSD_cjs.generate();
43
+ const body = async () => {
44
+ const startedAt = /* @__PURE__ */ new Date();
45
+ const startMs = startedAt.getTime();
46
+ const baseMeta = {
47
+ jobClass: meta.jobClass,
48
+ jobId: meta.jobId ?? null,
49
+ queue: meta.queue ?? null,
50
+ retryCount: meta.retryCount ?? null,
51
+ correlationId,
52
+ startedAt,
53
+ payload: meta.payload
54
+ };
55
+ try {
56
+ const result = await work();
57
+ await flushJobAuditLog(startedAt);
58
+ emitJobEvent({
59
+ ...baseMeta,
60
+ outcome: "success",
61
+ durationMs: Date.now() - startMs
62
+ });
63
+ return result;
64
+ } catch (error) {
65
+ const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
66
+ await flushJobAuditLog(startedAt);
67
+ if (meta.isControlFlow?.(error)) throw error;
68
+ emitJobEvent({
69
+ ...baseMeta,
70
+ outcome: "failure",
71
+ errorMessage: message,
72
+ durationMs: Date.now() - startMs
73
+ });
74
+ throw error;
75
+ }
76
+ };
77
+ const scoped = () => body().finally(chunkMMLQXSSD_cjs.endCorrelationScope);
78
+ return chunkMMLQXSSD_cjs.runWithCorrelation(correlationId, () => chunkMMLQXSSD_cjs.runWithActorScope(scoped, meta.actor ?? null));
79
+ }
80
+ var JOB_FLUSH_SKEW_MS = 500;
81
+ async function flushJobAuditLog(startedAt) {
82
+ try {
83
+ await chunkGMHOUAKD_cjs.flushAuditLog(chunkMMLQXSSD_cjs.configuration().databaseReader, {
84
+ since: new Date(startedAt.getTime() - JOB_FLUSH_SKEW_MS)
85
+ });
86
+ } catch (error) {
87
+ chunkTWTG5ILJ_cjs.logger.debug(`job audit flush failed: ${describeError(error)}`);
88
+ }
89
+ }
90
+ function jobArguments(payload) {
91
+ if (payload === null || payload === void 0) return null;
92
+ const patterns = chunkMMLQXSSD_cjs.configuration().excludedGraphqlVariableKeys;
93
+ if (Array.isArray(payload)) return payload.length === 0 ? null : chunkYXZZNZG6_cjs.sanitizeArgs(payload, patterns);
94
+ if (typeof payload === "object" && Object.getPrototypeOf(payload) === Object.prototype) {
95
+ const rest = { ...payload };
96
+ delete rest[CORRELATION_PAYLOAD_KEY];
97
+ delete rest[ACTOR_PAYLOAD_KEY];
98
+ if (Object.keys(rest).length === 0) return null;
99
+ return chunkYXZZNZG6_cjs.sanitizeArgs([rest], patterns)[0];
100
+ }
101
+ return chunkYXZZNZG6_cjs.sanitizeArgs([payload], patterns);
102
+ }
103
+ function extractCorrelationFromPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
104
+ if (payload === null || typeof payload !== "object") return null;
105
+ const value = payload[key];
106
+ return typeof value === "string" && value.length > 0 ? value : null;
107
+ }
108
+ function stampCorrelationOnPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
109
+ if (!payload || typeof payload !== "object") return payload;
110
+ if (typeof payload[key] === "string" && payload[key]) return payload;
111
+ const id = chunkMMLQXSSD_cjs.current();
112
+ if (!id) return payload;
113
+ return { ...payload, [key]: id };
114
+ }
115
+ function compactJobSourceData(data) {
116
+ const out = {};
117
+ for (const key of Object.keys(data)) {
118
+ const value = data[key];
119
+ if (value !== null && value !== void 0) out[key] = value;
120
+ }
121
+ return out;
122
+ }
123
+ function describeError(error) {
124
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
125
+ return String(error);
126
+ }
127
+ function pendingActorToken(correlationId) {
128
+ try {
129
+ const actor = chunkMMLQXSSD_cjs.getCurrentActor();
130
+ if (!actor || actor.kind && actor.kind !== "human" || actor.principal) return null;
131
+ const actorId = actor.id;
132
+ const key = chunkMMLQXSSD_cjs.configuration().projectToken;
133
+ if (!actorId || !key) return null;
134
+ const bytes = new TextEncoder().encode(actorId);
135
+ if (bytes.length > ACTOR_ID_MAX_BYTES) return null;
136
+ const memoKey = `${key}
137
+ ${correlationId}
138
+ ${actorId}`;
139
+ let pending = tokenMemo.get(memoKey);
140
+ if (!pending) {
141
+ if (tokenMemo.size >= 1e3) tokenMemo.clear();
142
+ pending = actorTag(key, correlationId, actorId).then(
143
+ (tag) => `a${toHex(bytes)}_${tag}`,
144
+ (error) => {
145
+ chunkTWTG5ILJ_cjs.logger.debug(`actor stamp failed: ${describeError(error)}`);
146
+ return null;
147
+ }
148
+ );
149
+ tokenMemo.set(memoKey, pending);
150
+ }
151
+ return pending;
152
+ } catch (error) {
153
+ chunkTWTG5ILJ_cjs.logger.debug(`actor stamp failed: ${describeError(error)}`);
154
+ return null;
155
+ }
156
+ }
157
+ var tokenMemo = /* @__PURE__ */ new Map();
158
+ function signedActorToken(correlationId) {
159
+ const now = pendingActorToken(correlationId);
160
+ if (now || chunkMMLQXSSD_cjs.getCurrentActor() || !chunkMMLQXSSD_cjs.configuration().actorFromSupabase) return now;
161
+ return chunkMMLQXSSD_cjs.maybeExtractSupabaseActor().then(
162
+ () => pendingActorToken(correlationId),
163
+ () => null
164
+ );
165
+ }
166
+ async function actorToken(correlationId) {
167
+ return await pendingActorToken(correlationId) ?? null;
168
+ }
169
+ async function readActorToken(token, correlationId) {
170
+ try {
171
+ const match = typeof token === "string" ? ACTOR_TOKEN.exec(token) : null;
172
+ const key = chunkMMLQXSSD_cjs.configuration().projectToken;
173
+ if (!match || !key || match[1].length % 2 !== 0) return null;
174
+ const bytes = new Uint8Array(match[1].match(/../g).map((h) => parseInt(h, 16)));
175
+ const actorId = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
176
+ if (!actorId) return null;
177
+ const expected = await actorTag(key, correlationId, actorId);
178
+ let diff = 0;
179
+ for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ match[2].charCodeAt(i);
180
+ return diff === 0 ? { id: actorId } : null;
181
+ } catch {
182
+ return null;
183
+ }
184
+ }
185
+ async function actorTag(key, correlationId, actorId) {
186
+ const enc = new TextEncoder();
187
+ const hmacKey = await globalThis.crypto.subtle.importKey(
188
+ "raw",
189
+ enc.encode(key),
190
+ { name: "HMAC", hash: "SHA-256" },
191
+ false,
192
+ ["sign"]
193
+ );
194
+ const mac = await globalThis.crypto.subtle.sign("HMAC", hmacKey, enc.encode(`${correlationId}
195
+ ${actorId}`));
196
+ return toHex(new Uint8Array(mac).subarray(0, 8));
197
+ }
198
+ function toHex(bytes) {
199
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
200
+ }
201
+
202
+ exports.ACTOR_PAYLOAD_KEY = ACTOR_PAYLOAD_KEY;
203
+ exports.CORRELATION_PAYLOAD_KEY = CORRELATION_PAYLOAD_KEY;
204
+ exports.actorToken = actorToken;
205
+ exports.emitJobEvent = emitJobEvent;
206
+ exports.extractCorrelationFromPayload = extractCorrelationFromPayload;
207
+ exports.flushJobAuditLog = flushJobAuditLog;
208
+ exports.readActorToken = readActorToken;
209
+ exports.runJobWithCapture = runJobWithCapture;
210
+ exports.signedActorToken = signedActorToken;
211
+ exports.stampCorrelationOnPayload = stampCorrelationOnPayload;
212
+ exports.toHex = toHex;
@@ -34,6 +34,13 @@ function safeWrite(level, message) {
34
34
  var logger = {
35
35
  debug: (message) => safeWrite("debug", message),
36
36
  info: (message) => safeWrite("info", message),
37
+ /** An info line that also shows at the default `warn` level (startup confirmation). */
38
+ notice: (message) => {
39
+ try {
40
+ if (shouldLog("warn")) console.log(`[ezlogs] ${message}`);
41
+ } catch {
42
+ }
43
+ },
37
44
  warn: (message) => safeWrite("warn", message),
38
45
  error: (message) => safeWrite("error", message)
39
46
  };
@@ -0,0 +1,200 @@
1
+ import { flushAuditLog } from './chunk-MHBS5FEP.js';
2
+ import { build, pushEvent, sanitizeArgs } from './chunk-NINIAL7M.js';
3
+ import { configuration, current, generate, runWithCorrelation, runWithActorScope, getCurrentActor, maybeExtractSupabaseActor, endCorrelationScope } from './chunk-GI6BM4MR.js';
4
+ import { logger } from './chunk-FCFVIRQF.js';
5
+
6
+ // src/jobs/shared.ts
7
+ var CORRELATION_PAYLOAD_KEY = "ezlogs_correlation_id";
8
+ var ACTOR_PAYLOAD_KEY = "ezlogs_actor";
9
+ var ACTOR_TOKEN = /^a([0-9a-f]{2,128})_([0-9a-f]{16})$/;
10
+ var ACTOR_ID_MAX_BYTES = 64;
11
+ function emitJobEvent(input) {
12
+ try {
13
+ const config = configuration();
14
+ if (!config.captureJobs) return;
15
+ if (config.allExcludedJobClasses().includes(input.jobClass)) return;
16
+ const sourceData = compactJobSourceData({
17
+ job_class: input.jobClass,
18
+ job_id: input.jobId ?? null,
19
+ queue: input.queue ?? null,
20
+ retry_count: input.retryCount ?? null,
21
+ arguments: jobArguments(input.payload)
22
+ });
23
+ const event = build({
24
+ source_type: "background_job",
25
+ source_data: sourceData,
26
+ outcome: input.outcome,
27
+ correlation_id: input.correlationId ?? current(),
28
+ resource_ids: [],
29
+ context: null,
30
+ duration_ms: input.durationMs ?? null,
31
+ error_message: input.errorMessage ?? null,
32
+ timestamp: input.startedAt
33
+ });
34
+ pushEvent(event);
35
+ } catch (error) {
36
+ logger.debug(`job emit failed: ${describeError(error)}`);
37
+ }
38
+ }
39
+ async function runJobWithCapture(meta, work) {
40
+ const correlationId = meta.correlationId ?? generate();
41
+ const body = async () => {
42
+ const startedAt = /* @__PURE__ */ new Date();
43
+ const startMs = startedAt.getTime();
44
+ const baseMeta = {
45
+ jobClass: meta.jobClass,
46
+ jobId: meta.jobId ?? null,
47
+ queue: meta.queue ?? null,
48
+ retryCount: meta.retryCount ?? null,
49
+ correlationId,
50
+ startedAt,
51
+ payload: meta.payload
52
+ };
53
+ try {
54
+ const result = await work();
55
+ await flushJobAuditLog(startedAt);
56
+ emitJobEvent({
57
+ ...baseMeta,
58
+ outcome: "success",
59
+ durationMs: Date.now() - startMs
60
+ });
61
+ return result;
62
+ } catch (error) {
63
+ const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
64
+ await flushJobAuditLog(startedAt);
65
+ if (meta.isControlFlow?.(error)) throw error;
66
+ emitJobEvent({
67
+ ...baseMeta,
68
+ outcome: "failure",
69
+ errorMessage: message,
70
+ durationMs: Date.now() - startMs
71
+ });
72
+ throw error;
73
+ }
74
+ };
75
+ const scoped = () => body().finally(endCorrelationScope);
76
+ return runWithCorrelation(correlationId, () => runWithActorScope(scoped, meta.actor ?? null));
77
+ }
78
+ var JOB_FLUSH_SKEW_MS = 500;
79
+ async function flushJobAuditLog(startedAt) {
80
+ try {
81
+ await flushAuditLog(configuration().databaseReader, {
82
+ since: new Date(startedAt.getTime() - JOB_FLUSH_SKEW_MS)
83
+ });
84
+ } catch (error) {
85
+ logger.debug(`job audit flush failed: ${describeError(error)}`);
86
+ }
87
+ }
88
+ function jobArguments(payload) {
89
+ if (payload === null || payload === void 0) return null;
90
+ const patterns = configuration().excludedGraphqlVariableKeys;
91
+ if (Array.isArray(payload)) return payload.length === 0 ? null : sanitizeArgs(payload, patterns);
92
+ if (typeof payload === "object" && Object.getPrototypeOf(payload) === Object.prototype) {
93
+ const rest = { ...payload };
94
+ delete rest[CORRELATION_PAYLOAD_KEY];
95
+ delete rest[ACTOR_PAYLOAD_KEY];
96
+ if (Object.keys(rest).length === 0) return null;
97
+ return sanitizeArgs([rest], patterns)[0];
98
+ }
99
+ return sanitizeArgs([payload], patterns);
100
+ }
101
+ function extractCorrelationFromPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
102
+ if (payload === null || typeof payload !== "object") return null;
103
+ const value = payload[key];
104
+ return typeof value === "string" && value.length > 0 ? value : null;
105
+ }
106
+ function stampCorrelationOnPayload(payload, key = CORRELATION_PAYLOAD_KEY) {
107
+ if (!payload || typeof payload !== "object") return payload;
108
+ if (typeof payload[key] === "string" && payload[key]) return payload;
109
+ const id = current();
110
+ if (!id) return payload;
111
+ return { ...payload, [key]: id };
112
+ }
113
+ function compactJobSourceData(data) {
114
+ const out = {};
115
+ for (const key of Object.keys(data)) {
116
+ const value = data[key];
117
+ if (value !== null && value !== void 0) out[key] = value;
118
+ }
119
+ return out;
120
+ }
121
+ function describeError(error) {
122
+ if (error instanceof Error) return `${error.name}: ${error.message}`;
123
+ return String(error);
124
+ }
125
+ function pendingActorToken(correlationId) {
126
+ try {
127
+ const actor = getCurrentActor();
128
+ if (!actor || actor.kind && actor.kind !== "human" || actor.principal) return null;
129
+ const actorId = actor.id;
130
+ const key = configuration().projectToken;
131
+ if (!actorId || !key) return null;
132
+ const bytes = new TextEncoder().encode(actorId);
133
+ if (bytes.length > ACTOR_ID_MAX_BYTES) return null;
134
+ const memoKey = `${key}
135
+ ${correlationId}
136
+ ${actorId}`;
137
+ let pending = tokenMemo.get(memoKey);
138
+ if (!pending) {
139
+ if (tokenMemo.size >= 1e3) tokenMemo.clear();
140
+ pending = actorTag(key, correlationId, actorId).then(
141
+ (tag) => `a${toHex(bytes)}_${tag}`,
142
+ (error) => {
143
+ logger.debug(`actor stamp failed: ${describeError(error)}`);
144
+ return null;
145
+ }
146
+ );
147
+ tokenMemo.set(memoKey, pending);
148
+ }
149
+ return pending;
150
+ } catch (error) {
151
+ logger.debug(`actor stamp failed: ${describeError(error)}`);
152
+ return null;
153
+ }
154
+ }
155
+ var tokenMemo = /* @__PURE__ */ new Map();
156
+ function signedActorToken(correlationId) {
157
+ const now = pendingActorToken(correlationId);
158
+ if (now || getCurrentActor() || !configuration().actorFromSupabase) return now;
159
+ return maybeExtractSupabaseActor().then(
160
+ () => pendingActorToken(correlationId),
161
+ () => null
162
+ );
163
+ }
164
+ async function actorToken(correlationId) {
165
+ return await pendingActorToken(correlationId) ?? null;
166
+ }
167
+ async function readActorToken(token, correlationId) {
168
+ try {
169
+ const match = typeof token === "string" ? ACTOR_TOKEN.exec(token) : null;
170
+ const key = configuration().projectToken;
171
+ if (!match || !key || match[1].length % 2 !== 0) return null;
172
+ const bytes = new Uint8Array(match[1].match(/../g).map((h) => parseInt(h, 16)));
173
+ const actorId = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
174
+ if (!actorId) return null;
175
+ const expected = await actorTag(key, correlationId, actorId);
176
+ let diff = 0;
177
+ for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ match[2].charCodeAt(i);
178
+ return diff === 0 ? { id: actorId } : null;
179
+ } catch {
180
+ return null;
181
+ }
182
+ }
183
+ async function actorTag(key, correlationId, actorId) {
184
+ const enc = new TextEncoder();
185
+ const hmacKey = await globalThis.crypto.subtle.importKey(
186
+ "raw",
187
+ enc.encode(key),
188
+ { name: "HMAC", hash: "SHA-256" },
189
+ false,
190
+ ["sign"]
191
+ );
192
+ const mac = await globalThis.crypto.subtle.sign("HMAC", hmacKey, enc.encode(`${correlationId}
193
+ ${actorId}`));
194
+ return toHex(new Uint8Array(mac).subarray(0, 8));
195
+ }
196
+ function toHex(bytes) {
197
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
198
+ }
199
+
200
+ export { ACTOR_PAYLOAD_KEY, CORRELATION_PAYLOAD_KEY, actorToken, emitJobEvent, extractCorrelationFromPayload, flushJobAuditLog, readActorToken, runJobWithCapture, signedActorToken, stampCorrelationOnPayload, toHex };
@@ -0,0 +1,48 @@
1
+ import { getCurrentActor, current } from './chunk-GI6BM4MR.js';
2
+ import { logger } from './chunk-FCFVIRQF.js';
3
+
4
+ // src/triggers/context.ts
5
+ function getDatabaseContext() {
6
+ const actor = getCurrentActor();
7
+ return {
8
+ actorId: actor && actor.id ? actor.id : null,
9
+ correlationId: current()
10
+ };
11
+ }
12
+ async function applyDatabaseContext(exec) {
13
+ const actor = getCurrentActor();
14
+ const correlationId = current();
15
+ if (!actor && !correlationId) return;
16
+ try {
17
+ if (actor && actor.id) {
18
+ await exec(`SELECT set_config('ezlogs.actor_id', $1, true)`, [actor.id]);
19
+ }
20
+ if (correlationId) {
21
+ await exec(
22
+ `SELECT set_config('ezlogs.correlation_id', $1, true)`,
23
+ [correlationId]
24
+ );
25
+ }
26
+ } catch (err) {
27
+ logger.debug(
28
+ `applyDatabaseContext: set_config failed, continuing without context: ${err instanceof Error ? err.message : String(err)}`
29
+ );
30
+ }
31
+ }
32
+ async function withDatabaseContext(client, callback) {
33
+ await client.query("BEGIN");
34
+ try {
35
+ await applyDatabaseContext(async (sql, params) => client.query(sql, params));
36
+ const result = await callback(client);
37
+ await client.query("COMMIT");
38
+ return result;
39
+ } catch (err) {
40
+ try {
41
+ await client.query("ROLLBACK");
42
+ } catch {
43
+ }
44
+ throw err;
45
+ }
46
+ }
47
+
48
+ export { applyDatabaseContext, getDatabaseContext, withDatabaseContext };