@upstash/workflow 0.2.0 → 0.2.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.
package/index.js CHANGED
@@ -20,7 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
- Client: () => Client3,
23
+ Client: () => Client4,
24
24
  StepTypes: () => StepTypes,
25
25
  WorkflowAbort: () => WorkflowAbort,
26
26
  WorkflowContext: () => WorkflowContext,
@@ -30,48 +30,8 @@ __export(src_exports, {
30
30
  });
31
31
  module.exports = __toCommonJS(src_exports);
32
32
 
33
- // src/error.ts
34
- var import_qstash = require("@upstash/qstash");
35
- var WorkflowError = class extends import_qstash.QstashError {
36
- constructor(message) {
37
- super(message);
38
- this.name = "WorkflowError";
39
- }
40
- };
41
- var WorkflowAbort = class extends Error {
42
- stepInfo;
43
- stepName;
44
- /**
45
- * whether workflow is to be canceled on abort
46
- */
47
- cancelWorkflow;
48
- /**
49
- *
50
- * @param stepName name of the aborting step
51
- * @param stepInfo step information
52
- * @param cancelWorkflow
53
- */
54
- constructor(stepName, stepInfo, cancelWorkflow = false) {
55
- super(
56
- `This is an Upstash Workflow error thrown after a step executes. It is expected to be raised. Make sure that you await for each step. Also, if you are using try/catch blocks, you should not wrap context.run/sleep/sleepUntil/call methods with try/catch. Aborting workflow after executing step '${stepName}'.`
57
- );
58
- this.name = "WorkflowAbort";
59
- this.stepName = stepName;
60
- this.stepInfo = stepInfo;
61
- this.cancelWorkflow = cancelWorkflow;
62
- }
63
- };
64
- var formatWorkflowError = (error) => {
65
- return error instanceof Error ? {
66
- error: error.name,
67
- message: error.message
68
- } : {
69
- error: "Error",
70
- message: "An error occured while executing workflow."
71
- };
72
- };
73
-
74
33
  // src/client/utils.ts
34
+ var import_qstash = require("@upstash/qstash");
75
35
  var makeNotifyRequest = async (requester, eventId, eventData) => {
76
36
  const result = await requester.request({
77
37
  path: ["v2", "notify", eventId],
@@ -105,32 +65,82 @@ var getSteps = async (requester, workflowRunId, messageId, debug) => {
105
65
  await debug?.log("INFO", "ENDPOINT_START", {
106
66
  message: `Pulled ${steps.length} steps from QStashand returned them without filtering with messageId.`
107
67
  });
108
- return steps;
68
+ return { steps, workflowRunEnded: false };
109
69
  } else {
110
70
  const index = steps.findIndex((item) => item.messageId === messageId);
111
71
  if (index === -1) {
112
- return [];
72
+ return { steps: [], workflowRunEnded: false };
113
73
  }
114
74
  const filteredSteps = steps.slice(0, index + 1);
115
75
  await debug?.log("INFO", "ENDPOINT_START", {
116
76
  message: `Pulled ${steps.length} steps from QStash and filtered them to ${filteredSteps.length} using messageId.`
117
77
  });
118
- return filteredSteps;
78
+ return { steps: filteredSteps, workflowRunEnded: false };
119
79
  }
120
80
  } catch (error) {
121
- await debug?.log("ERROR", "ERROR", {
122
- message: "failed while fetching steps.",
123
- error
124
- });
125
- throw new WorkflowError(`Failed while pulling steps. ${error}`);
81
+ if (error instanceof import_qstash.QstashError && error.status === 404) {
82
+ await debug?.log("WARN", "ENDPOINT_START", {
83
+ message: "Couldn't fetch workflow run steps. This can happen if the workflow run succesfully ends before some callback is executed.",
84
+ error
85
+ });
86
+ return { steps: void 0, workflowRunEnded: true };
87
+ } else {
88
+ throw error;
89
+ }
126
90
  }
127
91
  };
128
92
 
93
+ // src/error.ts
94
+ var import_qstash2 = require("@upstash/qstash");
95
+ var WorkflowError = class extends import_qstash2.QstashError {
96
+ constructor(message) {
97
+ super(message);
98
+ this.name = "WorkflowError";
99
+ }
100
+ };
101
+ var WorkflowAbort = class extends Error {
102
+ stepInfo;
103
+ stepName;
104
+ /**
105
+ * whether workflow is to be canceled on abort
106
+ */
107
+ cancelWorkflow;
108
+ /**
109
+ *
110
+ * @param stepName name of the aborting step
111
+ * @param stepInfo step information
112
+ * @param cancelWorkflow
113
+ */
114
+ constructor(stepName, stepInfo, cancelWorkflow = false) {
115
+ super(
116
+ `This is an Upstash Workflow error thrown after a step executes. It is expected to be raised. Make sure that you await for each step. Also, if you are using try/catch blocks, you should not wrap context.run/sleep/sleepUntil/call methods with try/catch. Aborting workflow after executing step '${stepName}'.`
117
+ );
118
+ this.name = "WorkflowAbort";
119
+ this.stepName = stepName;
120
+ this.stepInfo = stepInfo;
121
+ this.cancelWorkflow = cancelWorkflow;
122
+ }
123
+ };
124
+ var formatWorkflowError = (error) => {
125
+ return error instanceof Error ? {
126
+ error: error.name,
127
+ message: error.message
128
+ } : {
129
+ error: "Error",
130
+ message: "An error occured while executing workflow."
131
+ };
132
+ };
133
+
129
134
  // src/context/steps.ts
130
135
  var BaseLazyStep = class {
131
136
  stepName;
132
137
  // will be set in the subclasses
133
138
  constructor(stepName) {
139
+ if (!stepName) {
140
+ throw new WorkflowError(
141
+ "A workflow step name cannot be undefined or an empty string. Please provide a name for your workflow step."
142
+ );
143
+ }
134
144
  this.stepName = stepName;
135
145
  }
136
146
  };
@@ -223,15 +233,17 @@ var LazyCallStep = class extends BaseLazyStep {
223
233
  method;
224
234
  body;
225
235
  headers;
226
- stepType = "Call";
227
236
  retries;
228
- constructor(stepName, url, method, body, headers, retries) {
237
+ timeout;
238
+ stepType = "Call";
239
+ constructor(stepName, url, method, body, headers, retries, timeout) {
229
240
  super(stepName);
230
241
  this.url = url;
231
242
  this.method = method;
232
243
  this.body = body;
233
244
  this.headers = headers;
234
245
  this.retries = retries;
246
+ this.timeout = timeout;
235
247
  }
236
248
  getPlanStep(concurrent, targetStep) {
237
249
  return {
@@ -739,8 +751,8 @@ var StepTypes = [
739
751
  ];
740
752
 
741
753
  // src/workflow-requests.ts
742
- var import_qstash2 = require("@upstash/qstash");
743
- var triggerFirstInvocation = async (workflowContext, retries, debug) => {
754
+ var import_qstash3 = require("@upstash/qstash");
755
+ var triggerFirstInvocation = async (workflowContext, retries, useJSONContent, debug) => {
744
756
  const { headers } = getHeaders(
745
757
  "true",
746
758
  workflowContext.workflowRunId,
@@ -750,6 +762,9 @@ var triggerFirstInvocation = async (workflowContext, retries, debug) => {
750
762
  workflowContext.failureUrl,
751
763
  retries
752
764
  );
765
+ if (useJSONContent) {
766
+ headers["content-type"] = "application/json";
767
+ }
753
768
  try {
754
769
  const body = typeof workflowContext.requestPayload === "string" ? workflowContext.requestPayload : JSON.stringify(workflowContext.requestPayload);
755
770
  const result = await workflowContext.qstashClient.publish({
@@ -793,7 +808,7 @@ var triggerRouteFunction = async ({
793
808
  return ok("workflow-finished");
794
809
  } catch (error) {
795
810
  const error_ = error;
796
- if (error instanceof import_qstash2.QstashError && error.status === 400) {
811
+ if (error instanceof import_qstash3.QstashError && error.status === 400) {
797
812
  await debug?.log("WARN", "RESPONSE_WORKFLOW", {
798
813
  message: `tried to append to a cancelled workflow. exiting without publishing.`,
799
814
  name: error.name,
@@ -827,7 +842,7 @@ var triggerWorkflowDelete = async (workflowContext, debug, cancel = false) => {
827
842
  );
828
843
  return { deleted: true };
829
844
  } catch (error) {
830
- if (error instanceof import_qstash2.QstashError && error.status === 404) {
845
+ if (error instanceof import_qstash3.QstashError && error.status === 404) {
831
846
  await debug?.log("WARN", "SUBMIT_CLEANUP", {
832
847
  message: `Failed to remove workflow run ${workflowContext.workflowRunId} as it doesn't exist.`,
833
848
  name: error.name,
@@ -843,7 +858,10 @@ var recreateUserHeaders = (headers) => {
843
858
  const pairs = headers.entries();
844
859
  for (const [header, value] of pairs) {
845
860
  const headerLowerCase = header.toLowerCase();
846
- if (!headerLowerCase.startsWith("upstash-workflow-") && !headerLowerCase.startsWith("x-vercel-") && !headerLowerCase.startsWith("x-forwarded-") && headerLowerCase !== "cf-connecting-ip") {
861
+ if (!headerLowerCase.startsWith("upstash-workflow-") && // https://vercel.com/docs/edge-network/headers/request-headers#x-vercel-id
862
+ !headerLowerCase.startsWith("x-vercel-") && !headerLowerCase.startsWith("x-forwarded-") && // https://blog.cloudflare.com/preventing-request-loops-using-cdn-loop/
863
+ headerLowerCase !== "cf-connecting-ip" && headerLowerCase !== "cdn-loop" && headerLowerCase !== "cf-ew-via" && headerLowerCase !== "cf-ray" && // For Render https://render.com
864
+ headerLowerCase !== "render-proxy-ttl") {
847
865
  filteredHeaders.append(header, value);
848
866
  }
849
867
  }
@@ -861,11 +879,19 @@ var handleThirdPartyCallResult = async (request, requestPayload, client, workflo
861
879
  if (!workflowRunId2)
862
880
  throw new WorkflowError("workflow run id missing in context.call lazy fetch.");
863
881
  if (!messageId) throw new WorkflowError("message id missing in context.call lazy fetch.");
864
- const steps = await getSteps(client.http, workflowRunId2, messageId, debug);
882
+ const { steps, workflowRunEnded } = await getSteps(
883
+ client.http,
884
+ workflowRunId2,
885
+ messageId,
886
+ debug
887
+ );
888
+ if (workflowRunEnded) {
889
+ return ok("workflow-ended");
890
+ }
865
891
  const failingStep = steps.find((step) => step.messageId === messageId);
866
892
  if (!failingStep)
867
893
  throw new WorkflowError(
868
- "Failed to submit the context.call." + (steps.length === 0 ? "No steps found." : `No step was found with matching messageId ${messageId} out of ${steps.length} steps.`)
894
+ "Failed to submit the context.call. " + (steps.length === 0 ? "No steps found." : `No step was found with matching messageId ${messageId} out of ${steps.length} steps.`)
869
895
  );
870
896
  callbackPayload = atob(failingStep.body);
871
897
  }
@@ -946,7 +972,7 @@ ${atob(callbackMessage.body ?? "")}`
946
972
  );
947
973
  }
948
974
  };
949
- var getHeaders = (initHeaderValue, workflowRunId, workflowUrl, userHeaders, step, failureUrl, retries, callRetries) => {
975
+ var getHeaders = (initHeaderValue, workflowRunId, workflowUrl, userHeaders, step, failureUrl, retries, callRetries, callTimeout) => {
950
976
  const baseHeaders = {
951
977
  [WORKFLOW_INIT_HEADER]: initHeaderValue,
952
978
  [WORKFLOW_ID_HEADER]: workflowRunId,
@@ -956,6 +982,9 @@ var getHeaders = (initHeaderValue, workflowRunId, workflowUrl, userHeaders, step
956
982
  if (!step?.callUrl) {
957
983
  baseHeaders[`Upstash-Forward-${WORKFLOW_PROTOCOL_VERSION_HEADER}`] = WORKFLOW_PROTOCOL_VERSION;
958
984
  }
985
+ if (callTimeout) {
986
+ baseHeaders[`Upstash-Timeout`] = callTimeout.toString();
987
+ }
959
988
  if (failureUrl) {
960
989
  baseHeaders[`Upstash-Failure-Callback-Forward-${WORKFLOW_FAILURE_HEADER}`] = "true";
961
990
  if (!step?.callUrl) {
@@ -1331,7 +1360,8 @@ var AutoExecutor = class _AutoExecutor {
1331
1360
  singleStep,
1332
1361
  this.context.failureUrl,
1333
1362
  this.context.retries,
1334
- lazyStep instanceof LazyCallStep ? lazyStep.retries : void 0
1363
+ lazyStep instanceof LazyCallStep ? lazyStep.retries : void 0,
1364
+ lazyStep instanceof LazyCallStep ? lazyStep.timeout : void 0
1335
1365
  );
1336
1366
  const willWait = singleStep.concurrent === NO_CONCURRENCY || singleStep.stepId === 0;
1337
1367
  singleStep.out = JSON.stringify(singleStep.out);
@@ -1681,6 +1711,7 @@ var WorkflowContext = class {
1681
1711
  * @param body call body
1682
1712
  * @param headers call headers
1683
1713
  * @param retries number of call retries. 0 by default
1714
+ * @param timeout max duration to wait for the endpoint to respond. in seconds.
1684
1715
  * @returns call result as {
1685
1716
  * status: number;
1686
1717
  * body: unknown;
@@ -1688,9 +1719,17 @@ var WorkflowContext = class {
1688
1719
  * }
1689
1720
  */
1690
1721
  async call(stepName, settings) {
1691
- const { url, method = "GET", body, headers = {}, retries = 0 } = settings;
1722
+ const { url, method = "GET", body, headers = {}, retries = 0, timeout } = settings;
1692
1723
  const result = await this.addStep(
1693
- new LazyCallStep(stepName, url, method, body, headers, retries)
1724
+ new LazyCallStep(
1725
+ stepName,
1726
+ url,
1727
+ method,
1728
+ body,
1729
+ headers,
1730
+ retries,
1731
+ timeout
1732
+ )
1694
1733
  );
1695
1734
  if (typeof result === "string") {
1696
1735
  try {
@@ -1891,7 +1930,7 @@ function decodeBase64(base64) {
1891
1930
  }
1892
1931
 
1893
1932
  // src/serve/authorization.ts
1894
- var import_qstash3 = require("@upstash/qstash");
1933
+ var import_qstash4 = require("@upstash/qstash");
1895
1934
  var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowContext {
1896
1935
  static disabledMessage = "disabled-qstash-worklfow-run";
1897
1936
  /**
@@ -1922,7 +1961,7 @@ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowCon
1922
1961
  */
1923
1962
  static async tryAuthentication(routeFunction, context) {
1924
1963
  const disabledContext = new _DisabledWorkflowContext({
1925
- qstashClient: new import_qstash3.Client({
1964
+ qstashClient: new import_qstash4.Client({
1926
1965
  baseUrl: "disabled-client",
1927
1966
  token: "disabled-client"
1928
1967
  }),
@@ -2046,7 +2085,8 @@ var parseRequest = async (requestPayload, isFirstInvocation, workflowRunId, requ
2046
2085
  return {
2047
2086
  rawInitialPayload: requestPayload ?? "",
2048
2087
  steps: [],
2049
- isLastDuplicate: false
2088
+ isLastDuplicate: false,
2089
+ workflowRunEnded: false
2050
2090
  };
2051
2091
  } else {
2052
2092
  let rawSteps;
@@ -2056,7 +2096,21 @@ var parseRequest = async (requestPayload, isFirstInvocation, workflowRunId, requ
2056
2096
  "ENDPOINT_START",
2057
2097
  "request payload is empty, steps will be fetched from QStash."
2058
2098
  );
2059
- rawSteps = await getSteps(requester, workflowRunId, messageId, debug);
2099
+ const { steps: fetchedSteps, workflowRunEnded } = await getSteps(
2100
+ requester,
2101
+ workflowRunId,
2102
+ messageId,
2103
+ debug
2104
+ );
2105
+ if (workflowRunEnded) {
2106
+ return {
2107
+ rawInitialPayload: void 0,
2108
+ steps: void 0,
2109
+ isLastDuplicate: void 0,
2110
+ workflowRunEnded: true
2111
+ };
2112
+ }
2113
+ rawSteps = fetchedSteps;
2060
2114
  } else {
2061
2115
  rawSteps = JSON.parse(requestPayload);
2062
2116
  }
@@ -2066,7 +2120,8 @@ var parseRequest = async (requestPayload, isFirstInvocation, workflowRunId, requ
2066
2120
  return {
2067
2121
  rawInitialPayload,
2068
2122
  steps: deduplicatedSteps,
2069
- isLastDuplicate
2123
+ isLastDuplicate,
2124
+ workflowRunEnded: false
2070
2125
  };
2071
2126
  }
2072
2127
  };
@@ -2090,7 +2145,7 @@ var handleFailure = async (request, requestPayload, qstashClient, initialPayload
2090
2145
  const workflowContext = new WorkflowContext({
2091
2146
  qstashClient,
2092
2147
  workflowRunId,
2093
- initialPayload: initialPayloadParser(decodeBase64(sourceBody)),
2148
+ initialPayload: sourceBody ? initialPayloadParser(decodeBase64(sourceBody)) : void 0,
2094
2149
  headers: recreateUserHeaders(new Headers(sourceHeader)),
2095
2150
  steps: [],
2096
2151
  url,
@@ -2120,22 +2175,35 @@ var handleFailure = async (request, requestPayload, qstashClient, initialPayload
2120
2175
  };
2121
2176
 
2122
2177
  // src/serve/options.ts
2123
- var import_qstash4 = require("@upstash/qstash");
2124
2178
  var import_qstash5 = require("@upstash/qstash");
2179
+ var import_qstash6 = require("@upstash/qstash");
2125
2180
  var processOptions = (options) => {
2126
2181
  const environment = options?.env ?? (typeof process === "undefined" ? {} : process.env);
2127
2182
  const receiverEnvironmentVariablesSet = Boolean(
2128
2183
  environment.QSTASH_CURRENT_SIGNING_KEY && environment.QSTASH_NEXT_SIGNING_KEY
2129
2184
  );
2130
2185
  return {
2131
- qstashClient: new import_qstash5.Client({
2186
+ qstashClient: new import_qstash6.Client({
2132
2187
  baseUrl: environment.QSTASH_URL,
2133
2188
  token: environment.QSTASH_TOKEN
2134
2189
  }),
2135
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
2136
- onStepFinish: (workflowRunId, _finishCondition) => new Response(JSON.stringify({ workflowRunId }), {
2137
- status: 200
2138
- }),
2190
+ onStepFinish: (workflowRunId, finishCondition) => {
2191
+ if (finishCondition === "auth-fail") {
2192
+ console.error(AUTH_FAIL_MESSAGE);
2193
+ return new Response(
2194
+ JSON.stringify({
2195
+ message: AUTH_FAIL_MESSAGE,
2196
+ workflowRunId
2197
+ }),
2198
+ {
2199
+ status: 400
2200
+ }
2201
+ );
2202
+ }
2203
+ return new Response(JSON.stringify({ workflowRunId }), {
2204
+ status: 200
2205
+ });
2206
+ },
2139
2207
  initialPayloadParser: (initialRequest) => {
2140
2208
  if (!initialRequest) {
2141
2209
  return void 0;
@@ -2149,13 +2217,14 @@ var processOptions = (options) => {
2149
2217
  throw error;
2150
2218
  }
2151
2219
  },
2152
- receiver: receiverEnvironmentVariablesSet ? new import_qstash4.Receiver({
2220
+ receiver: receiverEnvironmentVariablesSet ? new import_qstash5.Receiver({
2153
2221
  currentSigningKey: environment.QSTASH_CURRENT_SIGNING_KEY,
2154
2222
  nextSigningKey: environment.QSTASH_NEXT_SIGNING_KEY
2155
2223
  }) : void 0,
2156
2224
  baseUrl: environment.UPSTASH_WORKFLOW_URL,
2157
2225
  env: environment,
2158
2226
  retries: DEFAULT_RETRIES,
2227
+ useJSONContent: false,
2159
2228
  ...options
2160
2229
  };
2161
2230
  };
@@ -2172,14 +2241,25 @@ var determineUrls = async (request, url, baseUrl, failureFunction, failureUrl, d
2172
2241
  });
2173
2242
  }
2174
2243
  const workflowFailureUrl = failureFunction ? workflowUrl : failureUrl;
2244
+ if (workflowUrl.includes("localhost")) {
2245
+ await debug?.log("WARN", "ENDPOINT_START", {
2246
+ message: `Workflow URL contains localhost. This can happen in local development, but shouldn't happen in production unless you have a route which contains localhost. Received: ${workflowUrl}`
2247
+ });
2248
+ }
2249
+ if (!(workflowUrl.startsWith("http://") || workflowUrl.startsWith("https://"))) {
2250
+ throw new WorkflowError(
2251
+ `Workflow URL should start with 'http://' or 'https://'. Recevied is '${workflowUrl}'`
2252
+ );
2253
+ }
2175
2254
  return {
2176
2255
  workflowUrl,
2177
2256
  workflowFailureUrl
2178
2257
  };
2179
2258
  };
2259
+ var AUTH_FAIL_MESSAGE = `Failed to authenticate Workflow request. If this is unexpected, see the caveat https://upstash.com/docs/workflow/basics/caveats#avoid-non-deterministic-code-outside-context-run`;
2180
2260
 
2181
2261
  // src/serve/index.ts
2182
- var serve = (routeFunction, options) => {
2262
+ var serveBase = (routeFunction, options) => {
2183
2263
  const {
2184
2264
  qstashClient,
2185
2265
  onStepFinish,
@@ -2191,7 +2271,8 @@ var serve = (routeFunction, options) => {
2191
2271
  failureFunction,
2192
2272
  baseUrl,
2193
2273
  env,
2194
- retries
2274
+ retries,
2275
+ useJSONContent
2195
2276
  } = processOptions(options);
2196
2277
  const debug = WorkflowLogger.getLogger(verbose);
2197
2278
  const handler = async (request) => {
@@ -2208,7 +2289,7 @@ var serve = (routeFunction, options) => {
2208
2289
  await verifyRequest(requestPayload, request.headers.get("upstash-signature"), receiver);
2209
2290
  const { isFirstInvocation, workflowRunId } = validateRequest(request);
2210
2291
  debug?.setWorkflowRunId(workflowRunId);
2211
- const { rawInitialPayload, steps, isLastDuplicate } = await parseRequest(
2292
+ const { rawInitialPayload, steps, isLastDuplicate, workflowRunEnded } = await parseRequest(
2212
2293
  requestPayload,
2213
2294
  isFirstInvocation,
2214
2295
  workflowRunId,
@@ -2216,8 +2297,11 @@ var serve = (routeFunction, options) => {
2216
2297
  request.headers.get("upstash-message-id"),
2217
2298
  debug
2218
2299
  );
2300
+ if (workflowRunEnded) {
2301
+ return onStepFinish(workflowRunId, "workflow-already-ended");
2302
+ }
2219
2303
  if (isLastDuplicate) {
2220
- return onStepFinish("no-workflow-id", "duplicate-step");
2304
+ return onStepFinish(workflowRunId, "duplicate-step");
2221
2305
  }
2222
2306
  const failureCheck = await handleFailure(
2223
2307
  request,
@@ -2231,7 +2315,7 @@ var serve = (routeFunction, options) => {
2231
2315
  throw failureCheck.error;
2232
2316
  } else if (failureCheck.value === "is-failure-callback") {
2233
2317
  await debug?.log("WARN", "RESPONSE_DEFAULT", "failureFunction executed");
2234
- return onStepFinish("no-workflow-id", "failure-callback");
2318
+ return onStepFinish(workflowRunId, "failure-callback");
2235
2319
  }
2236
2320
  const workflowContext = new WorkflowContext({
2237
2321
  qstashClient,
@@ -2253,7 +2337,11 @@ var serve = (routeFunction, options) => {
2253
2337
  await debug?.log("ERROR", "ERROR", { error: authCheck.error.message });
2254
2338
  throw authCheck.error;
2255
2339
  } else if (authCheck.value === "run-ended") {
2256
- return onStepFinish("no-workflow-id", "auth-fail");
2340
+ await debug?.log("ERROR", "ERROR", { error: AUTH_FAIL_MESSAGE });
2341
+ return onStepFinish(
2342
+ isFirstInvocation ? "no-workflow-id" : workflowContext.workflowRunId,
2343
+ "auth-fail"
2344
+ );
2257
2345
  }
2258
2346
  const callReturnCheck = await handleThirdPartyCallResult(
2259
2347
  request,
@@ -2270,7 +2358,7 @@ var serve = (routeFunction, options) => {
2270
2358
  });
2271
2359
  throw callReturnCheck.error;
2272
2360
  } else if (callReturnCheck.value === "continue-workflow") {
2273
- const result = isFirstInvocation ? await triggerFirstInvocation(workflowContext, retries, debug) : await triggerRouteFunction({
2361
+ const result = isFirstInvocation ? await triggerFirstInvocation(workflowContext, retries, useJSONContent, debug) : await triggerRouteFunction({
2274
2362
  onStep: async () => routeFunction(workflowContext),
2275
2363
  onCleanup: async () => {
2276
2364
  await triggerWorkflowDelete(workflowContext, debug);
@@ -2286,6 +2374,8 @@ var serve = (routeFunction, options) => {
2286
2374
  }
2287
2375
  await debug?.log("INFO", "RESPONSE_WORKFLOW");
2288
2376
  return onStepFinish(workflowContext.workflowRunId, "success");
2377
+ } else if (callReturnCheck.value === "workflow-ended") {
2378
+ return onStepFinish(workflowContext.workflowRunId, "workflow-already-ended");
2289
2379
  }
2290
2380
  await debug?.log("INFO", "RESPONSE_DEFAULT");
2291
2381
  return onStepFinish("no-workflow-id", "fromCallback");
@@ -2302,10 +2392,13 @@ var serve = (routeFunction, options) => {
2302
2392
  };
2303
2393
  return { handler: safeHandler };
2304
2394
  };
2395
+ var serve = (routeFunction, options) => {
2396
+ return serveBase(routeFunction, options);
2397
+ };
2305
2398
 
2306
2399
  // src/client/index.ts
2307
- var import_qstash6 = require("@upstash/qstash");
2308
- var Client3 = class {
2400
+ var import_qstash7 = require("@upstash/qstash");
2401
+ var Client4 = class {
2309
2402
  client;
2310
2403
  constructor(clientConfig) {
2311
2404
  if (!clientConfig.token) {
@@ -2313,7 +2406,7 @@ var Client3 = class {
2313
2406
  "QStash token is required for Upstash Workflow!\n\nTo fix this:\n1. Get your token from the Upstash Console (https://console.upstash.com/qstash)\n2. Initialize the workflow client with:\n\n const client = new Client({\n token: '<YOUR_QSTASH_TOKEN>'\n });"
2314
2407
  );
2315
2408
  }
2316
- this.client = new import_qstash6.Client(clientConfig);
2409
+ this.client = new import_qstash7.Client(clientConfig);
2317
2410
  }
2318
2411
  /**
2319
2412
  * Cancel an ongoing workflow