ezlogs-nextjs 0.4.4 → 0.4.7

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 (65) hide show
  1. package/README.md +73 -13
  2. package/dist/actors/index.d.cts +1 -1
  3. package/dist/actors/index.d.ts +1 -1
  4. package/dist/{chunk-MMLQXSSD.cjs → chunk-2YCQFLXW.cjs} +21 -11
  5. package/dist/{chunk-YMIGZYFH.js → chunk-343ZGTMH.js} +1 -1
  6. package/dist/{chunk-Z2TM3LGG.js → chunk-5ZMOWEBY.js} +1 -1
  7. package/dist/{chunk-GI6BM4MR.js → chunk-7MFKEYDN.js} +21 -12
  8. package/dist/{chunk-NINIAL7M.js → chunk-AXIQTU52.js} +1 -1
  9. package/dist/chunk-BE3RCFNP.js +13 -0
  10. package/dist/chunk-CHVJ4WPM.cjs +16 -0
  11. package/dist/{chunk-MHBS5FEP.js → chunk-CYAFYBKF.js} +27 -4
  12. package/dist/chunk-DRE2VXFX.js +19 -0
  13. package/dist/{chunk-GMHOUAKD.cjs → chunk-EXGEA4KE.cjs} +37 -13
  14. package/dist/{chunk-PS4U2GFJ.cjs → chunk-JB4UYCZI.cjs} +5 -5
  15. package/dist/chunk-JWJKFZBW.js +52 -0
  16. package/dist/{chunk-R6IWVTX3.cjs → chunk-KOFR5OC3.cjs} +31 -21
  17. package/dist/chunk-NFZ5OKF3.cjs +22 -0
  18. package/dist/{chunk-U22T7QYY.js → chunk-Q3HRVWCS.js} +13 -3
  19. package/dist/{chunk-YXZZNZG6.cjs → chunk-UC2KS5EG.cjs} +9 -9
  20. package/dist/chunk-VJR4VB4B.cjs +56 -0
  21. package/dist/{chunk-NX4EL7BY.cjs → chunk-XWEBKN65.cjs} +4 -4
  22. package/dist/{configuration-CJ5yKVlP.d.cts → configuration-b9pImwFB.d.cts} +2 -2
  23. package/dist/{configuration-CJ5yKVlP.d.ts → configuration-b9pImwFB.d.ts} +2 -2
  24. package/dist/db/drizzle.cjs +3 -3
  25. package/dist/db/drizzle.js +2 -2
  26. package/dist/db/postgres-js.cjs +4 -4
  27. package/dist/db/postgres-js.js +2 -2
  28. package/dist/db/prisma.cjs +12 -12
  29. package/dist/db/prisma.js +2 -2
  30. package/dist/db/supabase.cjs +42 -17
  31. package/dist/db/supabase.d.cts +11 -5
  32. package/dist/db/supabase.d.ts +11 -5
  33. package/dist/db/supabase.js +33 -9
  34. package/dist/index.cjs +303 -142
  35. package/dist/index.d.cts +2 -2
  36. package/dist/index.d.ts +2 -2
  37. package/dist/index.js +213 -52
  38. package/dist/jobs/bullmq.cjs +44 -16
  39. package/dist/jobs/bullmq.d.cts +7 -1
  40. package/dist/jobs/bullmq.d.ts +7 -1
  41. package/dist/jobs/bullmq.js +33 -6
  42. package/dist/jobs/inngest.cjs +171 -48
  43. package/dist/jobs/inngest.d.cts +13 -7
  44. package/dist/jobs/inngest.d.ts +13 -7
  45. package/dist/jobs/inngest.js +162 -40
  46. package/dist/jobs/supabase-queues.cjs +9 -9
  47. package/dist/jobs/supabase-queues.js +4 -4
  48. package/dist/jobs/trigger.cjs +7 -7
  49. package/dist/jobs/trigger.js +4 -4
  50. package/dist/jobs/upstash-workflow.cjs +139 -23
  51. package/dist/jobs/upstash-workflow.d.cts +20 -2
  52. package/dist/jobs/upstash-workflow.d.ts +20 -2
  53. package/dist/jobs/upstash-workflow.js +129 -14
  54. package/dist/nextjs-plugin/index.cjs +46 -29
  55. package/dist/nextjs-plugin/index.js +46 -29
  56. package/dist/nextjs-plugin/loader.cjs +104 -65
  57. package/dist/nextjs-plugin/loader.d.cts +18 -1
  58. package/dist/nextjs-plugin/loader.d.ts +18 -1
  59. package/dist/nextjs-plugin/loader.js +104 -66
  60. package/dist/triggers/index.cjs +22 -16
  61. package/dist/triggers/index.d.cts +0 -10
  62. package/dist/triggers/index.d.ts +0 -10
  63. package/dist/triggers/index.js +11 -5
  64. package/package.json +1 -1
  65. package/sql/postgres/00_install.sql +20 -3
@@ -1,7 +1,7 @@
1
- import { extractCorrelationFromPayload, runJobWithCapture, stampCorrelationOnPayload } from '../chunk-U22T7QYY.js';
2
- import '../chunk-MHBS5FEP.js';
3
- import '../chunk-NINIAL7M.js';
4
- import '../chunk-GI6BM4MR.js';
1
+ import { extractCorrelationFromPayload, runJobWithCapture, stampCorrelationOnPayload } from '../chunk-Q3HRVWCS.js';
2
+ import '../chunk-CYAFYBKF.js';
3
+ import '../chunk-AXIQTU52.js';
4
+ import '../chunk-7MFKEYDN.js';
5
5
  import '../chunk-FCFVIRQF.js';
6
6
  import '../chunk-SIAA4J6H.js';
7
7
 
@@ -1,9 +1,9 @@
1
1
  'use strict';
2
2
 
3
- var chunkR6IWVTX3_cjs = require('../chunk-R6IWVTX3.cjs');
4
- require('../chunk-GMHOUAKD.cjs');
5
- require('../chunk-YXZZNZG6.cjs');
6
- var chunkMMLQXSSD_cjs = require('../chunk-MMLQXSSD.cjs');
3
+ var chunkKOFR5OC3_cjs = require('../chunk-KOFR5OC3.cjs');
4
+ require('../chunk-EXGEA4KE.cjs');
5
+ require('../chunk-UC2KS5EG.cjs');
6
+ var chunk2YCQFLXW_cjs = require('../chunk-2YCQFLXW.cjs');
7
7
  var chunkTWTG5ILJ_cjs = require('../chunk-TWTG5ILJ.cjs');
8
8
  require('../chunk-ZDSQYCYV.cjs');
9
9
 
@@ -31,20 +31,20 @@ async function runWithEzlogsCapture(params) {
31
31
  const queueName = ctx.run?.queue?.name ?? null;
32
32
  const attemptNumber = ctx.attempt?.number ?? 1;
33
33
  const retryCount = Math.max(0, attemptNumber - 1);
34
- return chunkR6IWVTX3_cjs.runJobWithCapture(
34
+ return chunkKOFR5OC3_cjs.runJobWithCapture(
35
35
  {
36
36
  jobClass: taskId,
37
37
  jobId: runId,
38
38
  queue: queueName,
39
39
  retryCount,
40
- correlationId: chunkR6IWVTX3_cjs.extractCorrelationFromPayload(params.payload),
40
+ correlationId: chunkKOFR5OC3_cjs.extractCorrelationFromPayload(params.payload),
41
41
  payload: params.payload
42
42
  },
43
43
  () => params.next()
44
44
  );
45
45
  }
46
46
  function stampPayloadForTrigger(payload) {
47
- const id = chunkMMLQXSSD_cjs.current();
47
+ const id = chunk2YCQFLXW_cjs.current();
48
48
  if (!id) return payload;
49
49
  if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
50
50
  return payload;
@@ -1,7 +1,7 @@
1
- import { runJobWithCapture, extractCorrelationFromPayload } from '../chunk-U22T7QYY.js';
2
- import '../chunk-MHBS5FEP.js';
3
- import '../chunk-NINIAL7M.js';
4
- import { current } from '../chunk-GI6BM4MR.js';
1
+ import { runJobWithCapture, extractCorrelationFromPayload } from '../chunk-Q3HRVWCS.js';
2
+ import '../chunk-CYAFYBKF.js';
3
+ import '../chunk-AXIQTU52.js';
4
+ import { current } from '../chunk-7MFKEYDN.js';
5
5
  import { logger } from '../chunk-FCFVIRQF.js';
6
6
  import '../chunk-SIAA4J6H.js';
7
7
 
@@ -1,9 +1,11 @@
1
1
  'use strict';
2
2
 
3
- var chunkR6IWVTX3_cjs = require('../chunk-R6IWVTX3.cjs');
4
- require('../chunk-GMHOUAKD.cjs');
5
- require('../chunk-YXZZNZG6.cjs');
6
- var chunkMMLQXSSD_cjs = require('../chunk-MMLQXSSD.cjs');
3
+ var chunkCHVJ4WPM_cjs = require('../chunk-CHVJ4WPM.cjs');
4
+ var chunkVJR4VB4B_cjs = require('../chunk-VJR4VB4B.cjs');
5
+ var chunkKOFR5OC3_cjs = require('../chunk-KOFR5OC3.cjs');
6
+ require('../chunk-EXGEA4KE.cjs');
7
+ require('../chunk-UC2KS5EG.cjs');
8
+ var chunk2YCQFLXW_cjs = require('../chunk-2YCQFLXW.cjs');
7
9
  var chunkTWTG5ILJ_cjs = require('../chunk-TWTG5ILJ.cjs');
8
10
  require('../chunk-ZDSQYCYV.cjs');
9
11
 
@@ -29,7 +31,7 @@ function wrapWorkflowClient(client) {
29
31
  if (typeof client.trigger === "function") {
30
32
  const original = client.trigger.bind(client);
31
33
  client.trigger = async (params) => {
32
- if (chunkMMLQXSSD_cjs.current()) await chunkMMLQXSSD_cjs.maybeExtractSupabaseActor();
34
+ if (chunk2YCQFLXW_cjs.current()) await chunk2YCQFLXW_cjs.maybeExtractSupabaseActor();
33
35
  return original(
34
36
  Array.isArray(params) ? await Promise.all(params.map(stampTriggerOptions)) : await stampTriggerOptions(params)
35
37
  );
@@ -43,14 +45,14 @@ function wrapWorkflowClient(client) {
43
45
  return client;
44
46
  }
45
47
  async function stampTriggerOptions(options) {
46
- const current2 = chunkMMLQXSSD_cjs.current();
48
+ const current2 = chunk2YCQFLXW_cjs.current();
47
49
  if (!current2 || !options || typeof options !== "object") return options;
48
50
  const opts = options;
49
51
  const headers = { ...opts.headers ?? {} };
50
52
  const supplied = Object.keys(headers).find((k) => k.toLowerCase() === CORRELATION_HEADER);
51
53
  const id = supplied ? headers[supplied] : current2;
52
54
  if (!supplied) headers[CORRELATION_HEADER] = id;
53
- const token = AGENT_CORRELATION_ID.test(id) ? await chunkR6IWVTX3_cjs.actorToken(id) : null;
55
+ const token = AGENT_CORRELATION_ID.test(id) ? await chunkKOFR5OC3_cjs.actorToken(id) : null;
54
56
  if (token && !Object.keys(headers).some((k) => k.toLowerCase() === ACTOR_HEADER)) {
55
57
  headers[ACTOR_HEADER] = token;
56
58
  }
@@ -75,43 +77,150 @@ function wrapQStashClient(client) {
75
77
  return client;
76
78
  }
77
79
  async function stampPublishRequest(request) {
78
- const id = chunkMMLQXSSD_cjs.current();
80
+ const id = chunk2YCQFLXW_cjs.current();
79
81
  if (!id || !request || typeof request !== "object") return request;
80
82
  const headerKey = `${FORWARD_PREFIX}${CORRELATION_HEADER}`;
81
83
  const raw = request.headers;
82
84
  const headers = raw instanceof Headers || Array.isArray(raw) ? Object.fromEntries(new Headers(raw)) : { ...raw ?? {} };
83
85
  if (Object.keys(headers).some((key) => key.toLowerCase() === headerKey)) return request;
84
86
  headers[headerKey] = id;
85
- await chunkMMLQXSSD_cjs.maybeExtractSupabaseActor();
86
- const token = await chunkR6IWVTX3_cjs.actorToken(id);
87
+ await chunk2YCQFLXW_cjs.maybeExtractSupabaseActor();
88
+ const token = await chunkKOFR5OC3_cjs.actorToken(id);
87
89
  if (token) headers[`${FORWARD_PREFIX}${ACTOR_HEADER}`] = token;
88
90
  return { ...request, headers };
89
91
  }
92
+ var warnedNoHeaders = false;
90
93
  async function captureWorkflowRequest(meta, work) {
91
- const headers = meta.request.headers;
92
- const correlationId = readCorrelationFromHeaders(headers);
93
- const runId = readHeader(headers, "upstash-workflow-runid");
94
+ if (meta.context?.disabled === true) return work();
95
+ chunkCHVJ4WPM_cjs.markJobDelivery();
96
+ if (insideStepCapture.read()) return work();
97
+ const headers = meta.request?.headers ?? meta.context?.headers;
98
+ if (!headers) {
99
+ if (!warnedNoHeaders) {
100
+ warnedNoHeaders = true;
101
+ chunkTWTG5ILJ_cjs.logger.warn(
102
+ "captureWorkflowRequest got no headers (pass { context, workflowName }); this step runs without capture"
103
+ );
104
+ }
105
+ return work();
106
+ }
107
+ const runId = readHeader(headers, "upstash-workflow-runid") ?? meta.context?.workflowRunId ?? null;
108
+ const correlationId = readCorrelationFromHeaders(headers) ?? correlationFromRunId(runId);
94
109
  const retried = parseRetried(readHeader(headers, "upstash-retried"));
95
- const actor = correlationId ? await chunkR6IWVTX3_cjs.readActorToken(
110
+ const actor = correlationId ? await chunkKOFR5OC3_cjs.readActorToken(
96
111
  readHeader(headers, ACTOR_HEADER) ?? readHeader(headers, `${FORWARD_PREFIX}${ACTOR_HEADER}`),
97
112
  correlationId
98
- ) ?? await chunkR6IWVTX3_cjs.readActorToken(runId ? AGENT_RUN_ID.exec(runId)?.[2] : null, correlationId) : null;
99
- return chunkR6IWVTX3_cjs.runJobWithCapture(
113
+ ) ?? await chunkKOFR5OC3_cjs.readActorToken(runId ? AGENT_RUN_ID.exec(runId)?.[2] : null, correlationId) : null;
114
+ return insideStepCapture.run(true, () => chunkKOFR5OC3_cjs.runJobWithCapture(
100
115
  {
101
116
  jobClass: meta.workflowName,
102
117
  jobId: runId,
103
118
  queue: meta.stepName ?? meta.workflowName,
119
+ step: () => meta.ranStep?.() ?? meta.stepName ?? null,
104
120
  retryCount: retried,
105
121
  correlationId,
106
- actor
122
+ actor,
123
+ // The SDK ends each delivery by throwing: WorkflowAbort after a
124
+ // step ran (and WorkflowCancelAbort on context.cancel()) is a
125
+ // finished step, WorkflowAuthError is its signature probe that
126
+ // runs no step. Only other errors are failures.
127
+ isControlFlow: (error) => errorName(error) === "WorkflowAuthError",
128
+ isSuccessfulExit: (error) => SUCCESSFUL_EXITS.has(errorName(error))
107
129
  },
108
130
  work
109
- );
131
+ ));
132
+ }
133
+ var insideStepCapture = chunk2YCQFLXW_cjs.createScopedStorage(/* @__PURE__ */ Symbol.for("ezlogs-nextjs:upstash-step-capture"));
134
+ function workflowNameOf(context) {
135
+ try {
136
+ if (typeof context.url === "string") return new URL(context.url).pathname;
137
+ } catch {
138
+ }
139
+ return "upstash-workflow";
110
140
  }
141
+ function captureRouteFunction(routeFunction) {
142
+ if (typeof routeFunction !== "function") return routeFunction;
143
+ const run = routeFunction;
144
+ return function ezlogsWorkflowStep(context, ...rest) {
145
+ if (!context || typeof context !== "object" || !context.headers) return run.call(this, context, ...rest);
146
+ const ran = {};
147
+ const watched = watchRunSteps(context, ran);
148
+ return captureWorkflowRequest(
149
+ { context, workflowName: workflowNameOf(context), ranStep: () => ran.step },
150
+ () => run.call(this, watched, ...rest)
151
+ );
152
+ };
153
+ }
154
+ function watchRunSteps(context, ran) {
155
+ if (typeof context.run !== "function") return context;
156
+ try {
157
+ return new Proxy(context, {
158
+ get(target, key) {
159
+ const value = Reflect.get(target, key, target);
160
+ if (typeof value !== "function") return value;
161
+ if (key !== "run") return value.bind(target);
162
+ const run = value;
163
+ return (name, fn, ...rest) => {
164
+ if (typeof fn !== "function") return run.call(target, name, fn, ...rest);
165
+ const step = fn;
166
+ return run.call(target, name, (...args) => {
167
+ if (typeof name === "string" && ran.step === void 0) ran.step = name;
168
+ return step(...args);
169
+ }, ...rest);
170
+ };
171
+ }
172
+ });
173
+ } catch {
174
+ return context;
175
+ }
176
+ }
177
+ function instrumentServe(original) {
178
+ if (typeof original !== "function") return original;
179
+ const serve = original;
180
+ return function ezlogsServe(routeFunction, ...rest) {
181
+ const served = serve.call(this, captureRouteFunction(routeFunction), ...rest);
182
+ if (!served || typeof served !== "object") return served;
183
+ const handlers = { ...served };
184
+ for (const [name, handler] of Object.entries(handlers)) {
185
+ if (typeof handler !== "function") continue;
186
+ const deliver = handler;
187
+ handlers[name] = function ezlogsDelivery(...args) {
188
+ if (signedByQStash(args[0])) chunkCHVJ4WPM_cjs.markJobDelivery();
189
+ return deliver.apply(this, args);
190
+ };
191
+ }
192
+ return handlers;
193
+ };
194
+ }
195
+ function signedByQStash(request) {
196
+ const headers = request?.headers;
197
+ if (!headers || typeof headers !== "object") return false;
198
+ if (typeof headers.get === "function") return Boolean(headers.get("upstash-signature"));
199
+ return Boolean(headers["upstash-signature"]);
200
+ }
201
+ function instrumentCreateWorkflow(original) {
202
+ if (typeof original !== "function") return original;
203
+ const create = original;
204
+ return function ezlogsCreateWorkflow(routeFunction, ...rest) {
205
+ return create.call(this, captureRouteFunction(routeFunction), ...rest);
206
+ };
207
+ }
208
+ var __ezlogsInstrument = chunkVJR4VB4B_cjs.instrumentFrom({
209
+ "@upstash/workflow/nextjs#serve": instrumentServe,
210
+ "@upstash/workflow/nextjs#servePagesRouter": instrumentServe,
211
+ "@upstash/workflow/nextjs#createWorkflow": instrumentCreateWorkflow,
212
+ "@upstash/workflow/nextjs#createWorkflowPagesRouter": instrumentCreateWorkflow,
213
+ // Its workflows come from createWorkflow (captured there); only the handlers are marked.
214
+ "@upstash/workflow/nextjs#serveMany": instrumentServe,
215
+ "@upstash/workflow/nextjs#serveManyPagesRouter": instrumentServe,
216
+ "@upstash/workflow#serve": instrumentServe,
217
+ "@upstash/workflow#Client": (original) => chunkVJR4VB4B_cjs.instrumentClass(original, (client) => wrapWorkflowClient(client)),
218
+ "@upstash/qstash#Client": (original) => chunkVJR4VB4B_cjs.instrumentClass(original, (client) => wrapQStashClient(client))
219
+ });
111
220
  function emitUpstashWorkflowEvent(input) {
112
221
  try {
113
222
  const headers = input.request.headers;
114
- chunkR6IWVTX3_cjs.emitJobEvent({
223
+ chunkKOFR5OC3_cjs.emitJobEvent({
115
224
  jobClass: input.workflowName,
116
225
  jobId: readHeader(headers, "upstash-workflow-runid"),
117
226
  queue: input.workflowName,
@@ -129,7 +238,7 @@ function emitUpstashWorkflowEvent(input) {
129
238
  function randomHex(bytes) {
130
239
  const buf = new Uint8Array(bytes);
131
240
  globalThis.crypto.getRandomValues(buf);
132
- return chunkR6IWVTX3_cjs.toHex(buf);
241
+ return chunkKOFR5OC3_cjs.toHex(buf);
133
242
  }
134
243
  function readHeader(headers, name) {
135
244
  try {
@@ -139,14 +248,20 @@ function readHeader(headers, name) {
139
248
  return null;
140
249
  }
141
250
  }
251
+ var SUCCESSFUL_EXITS = /* @__PURE__ */ new Set(["WorkflowAbort", "WorkflowCancelAbort"]);
252
+ function errorName(error) {
253
+ return error !== null && typeof error === "object" ? String(error.name ?? "") : "";
254
+ }
255
+ function correlationFromRunId(runId) {
256
+ const fromRunId = runId ? AGENT_RUN_ID.exec(runId)?.[1] : void 0;
257
+ return fromRunId && isAcceptableStepId(fromRunId) ? fromRunId : null;
258
+ }
142
259
  function readCorrelationFromHeaders(headers) {
143
260
  for (const name of [CORRELATION_HEADER, LEGACY_CORRELATION_HEADER]) {
144
261
  const value = readHeader(headers, name) ?? readHeader(headers, `${FORWARD_PREFIX}${name}`);
145
262
  if (value && isAcceptableStepId(value)) return value;
146
263
  }
147
- const runId = readHeader(headers, "upstash-workflow-runid");
148
- const fromRunId = runId ? AGENT_RUN_ID.exec(runId)?.[1] : void 0;
149
- return fromRunId && isAcceptableStepId(fromRunId) ? fromRunId : null;
264
+ return correlationFromRunId(readHeader(headers, "upstash-workflow-runid"));
150
265
  }
151
266
  function parseRetried(value) {
152
267
  if (value === null) return null;
@@ -159,6 +274,7 @@ function describeError(error) {
159
274
  return String(error);
160
275
  }
161
276
 
277
+ exports.__ezlogsInstrument = __ezlogsInstrument;
162
278
  exports.captureWorkflowRequest = captureWorkflowRequest;
163
279
  exports.emitUpstashWorkflowEvent = emitUpstashWorkflowEvent;
164
280
  exports.wrapQStashClient = wrapQStashClient;
@@ -40,13 +40,31 @@ declare function wrapQStashClient<T extends QStashClientLike>(client: T): T;
40
40
  * Workflow retry / failure-routing semantics still work.
41
41
  */
42
42
  declare function captureWorkflowRequest<T>(meta: {
43
- request: Request | {
43
+ /**
44
+ * The workflow's context (`serve(async (context) => …)`), or the
45
+ * delivery Request. With the context, the run id comes from
46
+ * `context.workflowRunId`: Upstash keeps only the triggering
47
+ * request's headers on `context.headers`, without the per-delivery
48
+ * `Upstash-Workflow-RunId`.
49
+ */
50
+ context?: {
51
+ headers: Headers;
52
+ workflowRunId?: string;
53
+ };
54
+ request?: Request | {
44
55
  headers: Headers;
45
56
  };
46
57
  workflowName: string;
47
58
  /** Optional explicit step name; defaults to workflowName. */
48
59
  stepName?: string;
60
+ /** @internal The step this delivery ran, read when it ends (the plugin's serve()). */
61
+ ranStep?: () => string | undefined;
49
62
  }, work: () => Promise<T>): Promise<T>;
63
+ /**
64
+ * Replacements for the plugin's instrumented imports (instrument.ts).
65
+ * Internal: called by build-time generated code, not by apps.
66
+ */
67
+ declare const __ezlogsInstrument: (key: string, original: unknown) => unknown;
50
68
  /**
51
69
  * Standalone capture entry — for users who already have a finished
52
70
  * request/response pair and just want an event recorded (e.g.
@@ -63,4 +81,4 @@ declare function emitUpstashWorkflowEvent(input: {
63
81
  startedAt?: Date;
64
82
  }): void;
65
83
 
66
- export { captureWorkflowRequest, emitUpstashWorkflowEvent, wrapQStashClient, wrapWorkflowClient };
84
+ export { __ezlogsInstrument, captureWorkflowRequest, emitUpstashWorkflowEvent, wrapQStashClient, wrapWorkflowClient };
@@ -40,13 +40,31 @@ declare function wrapQStashClient<T extends QStashClientLike>(client: T): T;
40
40
  * Workflow retry / failure-routing semantics still work.
41
41
  */
42
42
  declare function captureWorkflowRequest<T>(meta: {
43
- request: Request | {
43
+ /**
44
+ * The workflow's context (`serve(async (context) => …)`), or the
45
+ * delivery Request. With the context, the run id comes from
46
+ * `context.workflowRunId`: Upstash keeps only the triggering
47
+ * request's headers on `context.headers`, without the per-delivery
48
+ * `Upstash-Workflow-RunId`.
49
+ */
50
+ context?: {
51
+ headers: Headers;
52
+ workflowRunId?: string;
53
+ };
54
+ request?: Request | {
44
55
  headers: Headers;
45
56
  };
46
57
  workflowName: string;
47
58
  /** Optional explicit step name; defaults to workflowName. */
48
59
  stepName?: string;
60
+ /** @internal The step this delivery ran, read when it ends (the plugin's serve()). */
61
+ ranStep?: () => string | undefined;
49
62
  }, work: () => Promise<T>): Promise<T>;
63
+ /**
64
+ * Replacements for the plugin's instrumented imports (instrument.ts).
65
+ * Internal: called by build-time generated code, not by apps.
66
+ */
67
+ declare const __ezlogsInstrument: (key: string, original: unknown) => unknown;
50
68
  /**
51
69
  * Standalone capture entry — for users who already have a finished
52
70
  * request/response pair and just want an event recorded (e.g.
@@ -63,4 +81,4 @@ declare function emitUpstashWorkflowEvent(input: {
63
81
  startedAt?: Date;
64
82
  }): void;
65
83
 
66
- export { captureWorkflowRequest, emitUpstashWorkflowEvent, wrapQStashClient, wrapWorkflowClient };
84
+ export { __ezlogsInstrument, captureWorkflowRequest, emitUpstashWorkflowEvent, wrapQStashClient, wrapWorkflowClient };
@@ -1,7 +1,9 @@
1
- import { actorToken, readActorToken, runJobWithCapture, emitJobEvent, toHex } from '../chunk-U22T7QYY.js';
2
- import '../chunk-MHBS5FEP.js';
3
- import '../chunk-NINIAL7M.js';
4
- import { current, maybeExtractSupabaseActor } from '../chunk-GI6BM4MR.js';
1
+ import { markJobDelivery } from '../chunk-BE3RCFNP.js';
2
+ import { instrumentFrom, instrumentClass } from '../chunk-JWJKFZBW.js';
3
+ import { actorToken, readActorToken, runJobWithCapture, toHex, emitJobEvent } from '../chunk-Q3HRVWCS.js';
4
+ import '../chunk-CYAFYBKF.js';
5
+ import '../chunk-AXIQTU52.js';
6
+ import { createScopedStorage, current, maybeExtractSupabaseActor } from '../chunk-7MFKEYDN.js';
5
7
  import { logger } from '../chunk-FCFVIRQF.js';
6
8
  import '../chunk-SIAA4J6H.js';
7
9
 
@@ -85,27 +87,134 @@ async function stampPublishRequest(request) {
85
87
  if (token) headers[`${FORWARD_PREFIX}${ACTOR_HEADER}`] = token;
86
88
  return { ...request, headers };
87
89
  }
90
+ var warnedNoHeaders = false;
88
91
  async function captureWorkflowRequest(meta, work) {
89
- const headers = meta.request.headers;
90
- const correlationId = readCorrelationFromHeaders(headers);
91
- const runId = readHeader(headers, "upstash-workflow-runid");
92
+ if (meta.context?.disabled === true) return work();
93
+ markJobDelivery();
94
+ if (insideStepCapture.read()) return work();
95
+ const headers = meta.request?.headers ?? meta.context?.headers;
96
+ if (!headers) {
97
+ if (!warnedNoHeaders) {
98
+ warnedNoHeaders = true;
99
+ logger.warn(
100
+ "captureWorkflowRequest got no headers (pass { context, workflowName }); this step runs without capture"
101
+ );
102
+ }
103
+ return work();
104
+ }
105
+ const runId = readHeader(headers, "upstash-workflow-runid") ?? meta.context?.workflowRunId ?? null;
106
+ const correlationId = readCorrelationFromHeaders(headers) ?? correlationFromRunId(runId);
92
107
  const retried = parseRetried(readHeader(headers, "upstash-retried"));
93
108
  const actor = correlationId ? await readActorToken(
94
109
  readHeader(headers, ACTOR_HEADER) ?? readHeader(headers, `${FORWARD_PREFIX}${ACTOR_HEADER}`),
95
110
  correlationId
96
111
  ) ?? await readActorToken(runId ? AGENT_RUN_ID.exec(runId)?.[2] : null, correlationId) : null;
97
- return runJobWithCapture(
112
+ return insideStepCapture.run(true, () => runJobWithCapture(
98
113
  {
99
114
  jobClass: meta.workflowName,
100
115
  jobId: runId,
101
116
  queue: meta.stepName ?? meta.workflowName,
117
+ step: () => meta.ranStep?.() ?? meta.stepName ?? null,
102
118
  retryCount: retried,
103
119
  correlationId,
104
- actor
120
+ actor,
121
+ // The SDK ends each delivery by throwing: WorkflowAbort after a
122
+ // step ran (and WorkflowCancelAbort on context.cancel()) is a
123
+ // finished step, WorkflowAuthError is its signature probe that
124
+ // runs no step. Only other errors are failures.
125
+ isControlFlow: (error) => errorName(error) === "WorkflowAuthError",
126
+ isSuccessfulExit: (error) => SUCCESSFUL_EXITS.has(errorName(error))
105
127
  },
106
128
  work
107
- );
129
+ ));
130
+ }
131
+ var insideStepCapture = createScopedStorage(/* @__PURE__ */ Symbol.for("ezlogs-nextjs:upstash-step-capture"));
132
+ function workflowNameOf(context) {
133
+ try {
134
+ if (typeof context.url === "string") return new URL(context.url).pathname;
135
+ } catch {
136
+ }
137
+ return "upstash-workflow";
108
138
  }
139
+ function captureRouteFunction(routeFunction) {
140
+ if (typeof routeFunction !== "function") return routeFunction;
141
+ const run = routeFunction;
142
+ return function ezlogsWorkflowStep(context, ...rest) {
143
+ if (!context || typeof context !== "object" || !context.headers) return run.call(this, context, ...rest);
144
+ const ran = {};
145
+ const watched = watchRunSteps(context, ran);
146
+ return captureWorkflowRequest(
147
+ { context, workflowName: workflowNameOf(context), ranStep: () => ran.step },
148
+ () => run.call(this, watched, ...rest)
149
+ );
150
+ };
151
+ }
152
+ function watchRunSteps(context, ran) {
153
+ if (typeof context.run !== "function") return context;
154
+ try {
155
+ return new Proxy(context, {
156
+ get(target, key) {
157
+ const value = Reflect.get(target, key, target);
158
+ if (typeof value !== "function") return value;
159
+ if (key !== "run") return value.bind(target);
160
+ const run = value;
161
+ return (name, fn, ...rest) => {
162
+ if (typeof fn !== "function") return run.call(target, name, fn, ...rest);
163
+ const step = fn;
164
+ return run.call(target, name, (...args) => {
165
+ if (typeof name === "string" && ran.step === void 0) ran.step = name;
166
+ return step(...args);
167
+ }, ...rest);
168
+ };
169
+ }
170
+ });
171
+ } catch {
172
+ return context;
173
+ }
174
+ }
175
+ function instrumentServe(original) {
176
+ if (typeof original !== "function") return original;
177
+ const serve = original;
178
+ return function ezlogsServe(routeFunction, ...rest) {
179
+ const served = serve.call(this, captureRouteFunction(routeFunction), ...rest);
180
+ if (!served || typeof served !== "object") return served;
181
+ const handlers = { ...served };
182
+ for (const [name, handler] of Object.entries(handlers)) {
183
+ if (typeof handler !== "function") continue;
184
+ const deliver = handler;
185
+ handlers[name] = function ezlogsDelivery(...args) {
186
+ if (signedByQStash(args[0])) markJobDelivery();
187
+ return deliver.apply(this, args);
188
+ };
189
+ }
190
+ return handlers;
191
+ };
192
+ }
193
+ function signedByQStash(request) {
194
+ const headers = request?.headers;
195
+ if (!headers || typeof headers !== "object") return false;
196
+ if (typeof headers.get === "function") return Boolean(headers.get("upstash-signature"));
197
+ return Boolean(headers["upstash-signature"]);
198
+ }
199
+ function instrumentCreateWorkflow(original) {
200
+ if (typeof original !== "function") return original;
201
+ const create = original;
202
+ return function ezlogsCreateWorkflow(routeFunction, ...rest) {
203
+ return create.call(this, captureRouteFunction(routeFunction), ...rest);
204
+ };
205
+ }
206
+ var __ezlogsInstrument = instrumentFrom({
207
+ "@upstash/workflow/nextjs#serve": instrumentServe,
208
+ "@upstash/workflow/nextjs#servePagesRouter": instrumentServe,
209
+ "@upstash/workflow/nextjs#createWorkflow": instrumentCreateWorkflow,
210
+ "@upstash/workflow/nextjs#createWorkflowPagesRouter": instrumentCreateWorkflow,
211
+ // Its workflows come from createWorkflow (captured there); only the handlers are marked.
212
+ "@upstash/workflow/nextjs#serveMany": instrumentServe,
213
+ "@upstash/workflow/nextjs#serveManyPagesRouter": instrumentServe,
214
+ "@upstash/workflow#serve": instrumentServe,
215
+ "@upstash/workflow#Client": (original) => instrumentClass(original, (client) => wrapWorkflowClient(client)),
216
+ "@upstash/qstash#Client": (original) => instrumentClass(original, (client) => wrapQStashClient(client))
217
+ });
109
218
  function emitUpstashWorkflowEvent(input) {
110
219
  try {
111
220
  const headers = input.request.headers;
@@ -137,14 +246,20 @@ function readHeader(headers, name) {
137
246
  return null;
138
247
  }
139
248
  }
249
+ var SUCCESSFUL_EXITS = /* @__PURE__ */ new Set(["WorkflowAbort", "WorkflowCancelAbort"]);
250
+ function errorName(error) {
251
+ return error !== null && typeof error === "object" ? String(error.name ?? "") : "";
252
+ }
253
+ function correlationFromRunId(runId) {
254
+ const fromRunId = runId ? AGENT_RUN_ID.exec(runId)?.[1] : void 0;
255
+ return fromRunId && isAcceptableStepId(fromRunId) ? fromRunId : null;
256
+ }
140
257
  function readCorrelationFromHeaders(headers) {
141
258
  for (const name of [CORRELATION_HEADER, LEGACY_CORRELATION_HEADER]) {
142
259
  const value = readHeader(headers, name) ?? readHeader(headers, `${FORWARD_PREFIX}${name}`);
143
260
  if (value && isAcceptableStepId(value)) return value;
144
261
  }
145
- const runId = readHeader(headers, "upstash-workflow-runid");
146
- const fromRunId = runId ? AGENT_RUN_ID.exec(runId)?.[1] : void 0;
147
- return fromRunId && isAcceptableStepId(fromRunId) ? fromRunId : null;
262
+ return correlationFromRunId(readHeader(headers, "upstash-workflow-runid"));
148
263
  }
149
264
  function parseRetried(value) {
150
265
  if (value === null) return null;
@@ -157,4 +272,4 @@ function describeError(error) {
157
272
  return String(error);
158
273
  }
159
274
 
160
- export { captureWorkflowRequest, emitUpstashWorkflowEvent, wrapQStashClient, wrapWorkflowClient };
275
+ export { __ezlogsInstrument, captureWorkflowRequest, emitUpstashWorkflowEvent, wrapQStashClient, wrapWorkflowClient };