@vite-hub/workflow 0.3.1 → 0.5.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.
Files changed (45) hide show
  1. package/README.md +79 -44
  2. package/dist/{app-CmMq8l4t.js → app-2Y7sBAG6.js} +1 -1
  3. package/dist/{client-CU5rELC0.js → client-CgBcDlGn.js} +155 -80
  4. package/dist/{cloudflare-BfFnNWB0.js → cloudflare-Datj_znU.js} +1 -1
  5. package/dist/{config-DCvRDlxA.js → config-z1651xc2.js} +1 -1
  6. package/dist/definition.d.ts +10 -11
  7. package/dist/definition.js +24 -22
  8. package/dist/{delay--ESDybVT.js → delay-CHN4tv3i.js} +6 -42
  9. package/dist/durability.d.ts +1 -1
  10. package/dist/{error-diagnostics-DSkCJC_L.js → error-diagnostics-C0KyI408.js} +10 -2
  11. package/dist/{error-diagnostics-8YNJ37rP.js → error-diagnostics-DMeaFmQD.js} +68 -19
  12. package/dist/{errors-DCqRnZpN.js → errors-BNxEeeCO.js} +0 -4
  13. package/dist/{errors-DVwFb6Fd.d.ts → errors-D-fNDVg0.d.ts} +12 -6
  14. package/dist/index.d.ts +32 -11
  15. package/dist/index.js +13 -6
  16. package/dist/{openworkflow-TEaNk0LV.d.ts → openworkflow-BoaENgh9.d.ts} +8 -7
  17. package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-CI2PJGqu.d.ts} +13 -2
  18. package/dist/{operations-B0L8kV5s.js → operations-CYntpf-T.js} +34 -41
  19. package/dist/operations.d.ts +5 -8
  20. package/dist/operations.js +27 -32
  21. package/dist/{out-fRNaVslw.js → out-DxLKolA0.js} +1 -1
  22. package/dist/{rolldown-runtime-CMFfr-1z.js → rolldown-runtime-B4iAMlE-.js} +10 -1
  23. package/dist/{run-error-DBWqiJHH.js → run-error-Ctn50EYz.js} +1 -2
  24. package/dist/run-failed-gVGo1BaF.js +18 -0
  25. package/dist/runtime/cloudflare-runner.d.ts +12 -2
  26. package/dist/runtime/cloudflare-runner.js +28 -9
  27. package/dist/runtime/cloudflare-vite.d.ts +1 -1
  28. package/dist/runtime/cloudflare-vite.js +2 -2
  29. package/dist/runtime/dev-runs.js +1 -0
  30. package/dist/runtime/execute.d.ts +25 -4
  31. package/dist/runtime/execute.js +168 -43
  32. package/dist/runtime/openworkflow-worker.d.ts +2 -2
  33. package/dist/runtime/openworkflow-worker.js +4 -9
  34. package/dist/runtime/openworkflow.d.ts +2 -2
  35. package/dist/runtime/openworkflow.js +60 -49
  36. package/dist/runtime/state.d.ts +1 -1
  37. package/dist/runtime/state.js +4 -6
  38. package/dist/runtime/vercel-vite.d.ts +1 -1
  39. package/dist/runtime/vercel-vite.js +2 -2
  40. package/dist/signals-C1iolifd.js +80 -0
  41. package/dist/{types-CnKVDnEp.d.ts → types-BWPHeugk.d.ts} +99 -28
  42. package/dist/{vercel-BZU_O6ay.js → vercel-BIkBFrQQ.js} +6 -14
  43. package/dist/vite.d.ts +27 -16
  44. package/dist/vite.js +3404 -961
  45. package/package.json +4 -4
@@ -1,5 +1,5 @@
1
- import { t as internalErrorDiagnostics } from "./error-diagnostics-DSkCJC_L.js";
2
1
  import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
2
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-C0KyI408.js";
3
3
  import { toJsonSchema } from "@valibot/to-json-schema";
4
4
  import * as v from "valibot";
5
5
  //#region ../internal/src/standard-schema.ts
@@ -143,7 +143,7 @@ function table(rows) {
143
143
  }
144
144
  //#endregion
145
145
  //#region src/operations.ts
146
- const runtime = () => import("./operations-B0L8kV5s.js");
146
+ const runtime = () => import("./operations-CYntpf-T.js");
147
147
  const name = v.pipe(v.string(), v.check((value) => value.trim() !== "", "Name a Workflow."));
148
148
  const runId = v.pipe(v.string(), v.check((value) => value.trim() !== "", "Pass the id of a run."));
149
149
  const maxRequestBytes = 1048576;
@@ -172,8 +172,12 @@ const start = defineWorkflowOperation({
172
172
  run: async (input) => (await runtime()).runWorkflowOperation("start", input)
173
173
  });
174
174
  const get = defineWorkflowOperation({
175
- cli: { positional: ["runId"] },
176
- description: "Show the status and result of a Workflow run. Pass `workflow` for a run that this runtime did not start.",
175
+ cli: {
176
+ command: "runs get",
177
+ format: formatRun,
178
+ positional: ["runId"]
179
+ },
180
+ description: "Show the status and result of a Workflow run, with its steps when `vite dev` recorded it. Pass `workflow` for a run that this runtime did not start.",
177
181
  input: v.object({
178
182
  runId,
179
183
  workflow: v.optional(name)
@@ -227,6 +231,24 @@ function formatRuns({ runs }) {
227
231
  function json(value) {
228
232
  return JSON.stringify(value ?? null, null, 2);
229
233
  }
234
+ /** The steps of a run that `vite dev` recorded. A run of another runtime has no steps. */
235
+ function stepLines(steps) {
236
+ if (!steps) return [];
237
+ if (!steps.length) return ["Steps: none"];
238
+ return ["Steps:", table([[
239
+ "STEP",
240
+ "STATUS",
241
+ "STARTED AT",
242
+ "COMPLETED AT",
243
+ "ERROR"
244
+ ], ...steps.map((step) => [
245
+ step.name,
246
+ step.status,
247
+ step.startedAt,
248
+ step.completedAt ?? "-",
249
+ step.error?.message ?? "-"
250
+ ])])];
251
+ }
230
252
  function formatRun({ run }) {
231
253
  return [
232
254
  `Run: ${run.id}`,
@@ -237,19 +259,7 @@ function formatRun({ run }) {
237
259
  ...run.startedAt ? [`Started at: ${run.startedAt}`] : [],
238
260
  ...run.completedAt ? [`Completed at: ${run.completedAt}`] : [],
239
261
  ...run.error ? [`Error: ${run.error.code ? `${run.error.code} ` : ""}${run.error.message}`] : [],
240
- ...run.steps.length ? ["Steps:", table([[
241
- "STEP",
242
- "STATUS",
243
- "STARTED AT",
244
- "COMPLETED AT",
245
- "ERROR"
246
- ], ...run.steps.map((step) => [
247
- step.name,
248
- step.status,
249
- step.startedAt,
250
- step.completedAt ?? "-",
251
- step.error?.message ?? "-"
252
- ])])] : ["Steps: none"],
262
+ ...stepLines(run.steps),
253
263
  ...run.status === "completed" ? ["Result:", json(run.result)] : [],
254
264
  ""
255
265
  ].join("\n");
@@ -283,21 +293,6 @@ const workflowOperations = [
283
293
  name: "workflow.runs-list",
284
294
  run: async (input) => (await runtime()).listWorkflowRuns(input)
285
295
  }),
286
- defineWorkflowOperation({
287
- cli: {
288
- command: "runs show",
289
- format: formatRun,
290
- positional: ["id"]
291
- },
292
- description: "Show one Workflow run that `vite dev` recorded, with its steps, status, result, and error.",
293
- input: v.strictObject({
294
- id: runId,
295
- workflow: v.optional(name)
296
- }),
297
- kind: "read",
298
- name: "workflow.runs-show",
299
- run: async (input) => (await runtime()).showWorkflowRun(input)
300
- }),
301
296
  defineWorkflowOperation({
302
297
  cli: {
303
298
  command: "runs clear",
@@ -1,4 +1,4 @@
1
- import { n as __require, t as __commonJSMin } from "./rolldown-runtime-CMFfr-1z.js";
1
+ import { r as __require, t as __commonJSMin } from "./rolldown-runtime-B4iAMlE-.js";
2
2
  //#region ../../node_modules/.pnpm/@vercel+nft@1.11.0_rollup@4.67.5_supports-color@10.2.2/node_modules/@vercel/nft/out/types.js
3
3
  var require_types = /* @__PURE__ */ __commonJSMin(((exports) => {
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -7,6 +7,15 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
9
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
10
+ var __exportAll = (all, no_symbols) => {
11
+ let target = {};
12
+ for (var name in all) __defProp(target, name, {
13
+ get: all[name],
14
+ enumerable: true
15
+ });
16
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
17
+ return target;
18
+ };
10
19
  var __copyProps = (to, from, except, desc) => {
11
20
  if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
21
  key = keys[i];
@@ -23,4 +32,4 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
32
  }) : target, mod));
24
33
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
25
34
  //#endregion
26
- export { __require as n, __toESM as r, __commonJSMin as t };
35
+ export { __toESM as i, __exportAll as n, __require as r, __commonJSMin as t };
@@ -1,4 +1,4 @@
1
- import { n as createWorkflowError } from "./errors-DCqRnZpN.js";
1
+ import { n as createWorkflowError } from "./errors-BNxEeeCO.js";
2
2
  import { t as getWorkflowDevRecorder } from "./dev-recorder-CTN5Fkao.js";
3
3
  import { t as redactInspectionText } from "./inspect-B72iFyj-.js";
4
4
  import { getViteHubErrorShape } from "@vite-hub/runtime";
@@ -45,7 +45,6 @@ function getWorkflowProviderReason(error) {
45
45
  const reason = safeName ? `${safeName}: ${text}` : text;
46
46
  return reason.length > maxReasonLength ? `${reason.slice(0, 199)}…` : reason;
47
47
  }
48
- /** `vite dev` installs the run history. Elsewhere, `NODE_ENV` says whether the app runs a development server. */
49
48
  function isDevelopment() {
50
49
  return Boolean(getWorkflowDevRecorder()) || globalThis.process?.env?.NODE_ENV === "development";
51
50
  }
@@ -0,0 +1,18 @@
1
+ import { emitRunFailed, toRunFailedError } from "@vite-hub/runtime/internal/run-failed";
2
+ //#region src/runtime/run-failed.ts
3
+ /**
4
+ * Sends `workflow.failed` to the listeners, such as Webhooks, when a run ends in failure with no retry left. An Agent
5
+ * turn runs in an internal Workflow and reports `invocation.failed` from its Invocation instead.
6
+ */
7
+ async function emitWorkflowFailed(name, runId, error, definition) {
8
+ if (definition?.internalAgentWorkflow || definition?.internalAgentInvocationRecovery) return;
9
+ await emitRunFailed({
10
+ event: "workflow.failed",
11
+ workflow: name,
12
+ runId,
13
+ error: toRunFailedError(error),
14
+ failedAt: (/* @__PURE__ */ new Date()).toISOString()
15
+ });
16
+ }
17
+ //#endregion
18
+ export { emitWorkflowFailed as t };
@@ -1,4 +1,4 @@
1
- import { T as WorkflowProviderStep, l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-CnKVDnEp.js";
1
+ import { D as WorkflowProviderStep, l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-BWPHeugk.js";
2
2
  import { t as CloudflareWorkerEnv } from "../cloudflare-env-lookup-CfX6wZKb.js";
3
3
  //#region src/runtime/cloudflare-runner.d.ts
4
4
  export interface CloudflareWorkflowEvent {
@@ -6,6 +6,15 @@ export interface CloudflareWorkflowEvent {
6
6
  instanceId?: string;
7
7
  payload?: unknown;
8
8
  }
9
+ /** The `step` of a Cloudflare Workflow: the ViteHub step runner names, and `waitForEvent()`. */
10
+ export interface CloudflareWorkflowStep extends Omit<WorkflowProviderStep, "waitForSignal"> {
11
+ waitForEvent?: (name: string, options: {
12
+ timeout?: string;
13
+ type: string;
14
+ }) => Promise<{
15
+ payload?: unknown;
16
+ }>;
17
+ }
9
18
  export interface RunCloudflareWorkflowOptions {
10
19
  config: false | ResolvedWorkflowOptions | undefined;
11
20
  createNonRetryableError?: (error: Error) => Error;
@@ -13,7 +22,8 @@ export interface RunCloudflareWorkflowOptions {
13
22
  event: CloudflareWorkflowEvent;
14
23
  name: string;
15
24
  registry: WorkflowDefinitionRegistry;
16
- step?: WorkflowProviderStep;
25
+ step?: CloudflareWorkflowStep;
17
26
  }
27
+ export declare function cloudflareSignalEventType(signal: string): string;
18
28
  export declare function runCloudflareWorkflow({ config, createNonRetryableError, env, event, name, registry, step }: RunCloudflareWorkflowOptions): Promise<unknown>;
19
29
  //#endregion
@@ -1,11 +1,16 @@
1
- import { t as workflowErrorDiagnostics } from "../error-diagnostics-8YNJ37rP.js";
2
- import { n as createWorkflowError, r as isNonRetryableError } from "../errors-DCqRnZpN.js";
1
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics-DMeaFmQD.js";
2
+ import { n as createWorkflowError, r as isNonRetryableError } from "../errors-BNxEeeCO.js";
3
3
  import { r as runWithActiveCloudflareEnv } from "../cloudflare-env-CGLx7lUd.js";
4
- import { t as fromCloudflareStartParams } from "../delay--ESDybVT.js";
5
- import { runSerializedWorkflowHandler } from "./execute.js";
4
+ import { t as fromCloudflareStartParams } from "../delay-CHN4tv3i.js";
5
+ import { resolveWorkflowStepOptions, runSerializedWorkflowHandler } from "./execute.js";
6
+ import { t as emitWorkflowFailed } from "../run-failed-gVGo1BaF.js";
6
7
  import { loadWorkflowDefinition, runWithWorkflowRuntimeEvent, setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry } from "./state.js";
8
+ import { hasRunFailedListeners } from "@vite-hub/runtime/internal/run-failed";
7
9
  //#region src/runtime/cloudflare-runner.ts
8
- /** The Cloudflare errors that a step already made. They pass the run boundary as they are, not wrapped again. */
10
+ function cloudflareSignalEventType(signal) {
11
+ return `vitehub-${signal}`;
12
+ }
13
+ const cloudflareSignalTimeout = "365 days";
9
14
  const cloudflareNonRetryableErrors = /* @__PURE__ */ new WeakSet();
10
15
  function translateNonRetryableError(error, createNonRetryableError) {
11
16
  if (!createNonRetryableError || !isNonRetryableError(error) || cloudflareNonRetryableErrors.has(error)) return error;
@@ -17,7 +22,7 @@ function wrapCloudflareWorkflowStep(step, createNonRetryableError, env, runtimeE
17
22
  if (!step?.do) return step;
18
23
  return {
19
24
  async do(name, options, run) {
20
- return await step.do(name, options, async () => await runWithActiveCloudflareEnv(env, async () => await runWithWorkflowRuntimeEvent(runtimeEvent(), async () => {
25
+ return await step.do(name, resolveWorkflowStepOptions(name, options), async () => await runWithActiveCloudflareEnv(env, async () => await runWithWorkflowRuntimeEvent(runtimeEvent(), async () => {
21
26
  try {
22
27
  return await run();
23
28
  } catch (error) {
@@ -26,7 +31,11 @@ function wrapCloudflareWorkflowStep(step, createNonRetryableError, env, runtimeE
26
31
  })));
27
32
  },
28
33
  ...step.sleep ? { sleep: async (name, milliseconds) => await step.sleep(name, milliseconds) } : {},
29
- ...step.sleepUntil ? { sleepUntil: async (name, date) => await step.sleepUntil(name, date) } : {}
34
+ ...step.sleepUntil ? { sleepUntil: async (name, date) => await step.sleepUntil(name, date) } : {},
35
+ ...step.waitForEvent ? { waitForSignal: async (name) => (await step.waitForEvent(name, {
36
+ timeout: cloudflareSignalTimeout,
37
+ type: cloudflareSignalEventType(name)
38
+ })).payload } : {}
30
39
  };
31
40
  }
32
41
  async function runCloudflareWorkflow({ config, createNonRetryableError, env, event, name, registry, step }) {
@@ -52,18 +61,28 @@ async function runCloudflareWorkflow({ config, createNonRetryableError, env, eve
52
61
  });
53
62
  await step.sleepUntil("vitehub-delay", new Date(startAt));
54
63
  }
64
+ const id = event?.instanceId || event?.id;
55
65
  try {
56
66
  return await runWithWorkflowRuntimeEvent(runtimeEvent, () => runSerializedWorkflowHandler({
57
- id: event?.instanceId || event?.id,
67
+ id,
58
68
  name,
59
69
  payload,
60
70
  provider: "cloudflare",
61
71
  step: providerStep
62
72
  }, definition));
63
73
  } catch (error) {
74
+ if (id && hasRunFailedListeners() && !definition.internalAgentWorkflow && !definition.internalAgentInvocationRecovery) try {
75
+ if (providerStep?.do) await providerStep.do("vitehub-notify-terminal-failure", { retries: { limit: 0 } }, async () => {
76
+ await emitWorkflowFailed(name, id, error, definition);
77
+ return null;
78
+ });
79
+ else await emitWorkflowFailed(name, id, error, definition);
80
+ } catch (notificationError) {
81
+ console.error("[vitehub] Could not checkpoint the Workflow failure notification.", notificationError);
82
+ }
64
83
  throw translateNonRetryableError(error, createNonRetryableError);
65
84
  }
66
85
  });
67
86
  }
68
87
  //#endregion
69
- export { runCloudflareWorkflow };
88
+ export { cloudflareSignalEventType, runCloudflareWorkflow };
@@ -1,4 +1,4 @@
1
- import { l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-CnKVDnEp.js";
1
+ import { l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-BWPHeugk.js";
2
2
  import { t as CloudflareWorkerEnv } from "../cloudflare-env-lookup-CfX6wZKb.js";
3
3
  import { t as CloudflareWorkerExecutionContext } from "../cloudflare-shared-CTqh_a2s.js";
4
4
  import { t as VitehubApp } from "../app-BojnC_yf.js";
@@ -1,7 +1,7 @@
1
1
  import { r as runWithActiveCloudflareEnv, t as createCloudflareRuntimeEvent } from "../cloudflare-env-CGLx7lUd.js";
2
- import { t as normalizeWorkflowOptions } from "../config-DCvRDlxA.js";
2
+ import { t as normalizeWorkflowOptions } from "../config-z1651xc2.js";
3
3
  import { runWithWorkflowRuntimeEvent, setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry } from "./state.js";
4
- import { t as resolveAppFetch } from "../app-CmMq8l4t.js";
4
+ import { t as resolveAppFetch } from "../app-2Y7sBAG6.js";
5
5
  import "./cloudflare-shared.js";
6
6
  //#region ../internal/src/runtime/cloudflare-hosted.ts
7
7
  function createWebRequestHandler(appHandler) {
@@ -10,6 +10,7 @@ function createWorkflowDevRecorder() {
10
10
  runs.clear();
11
11
  return count;
12
12
  },
13
+ get: (workflow, id) => runs.get(JSON.stringify([workflow, id])),
13
14
  list: () => [...runs.values()].reverse(),
14
15
  start(workflow, id, provider) {
15
16
  const key = JSON.stringify([workflow, id]);
@@ -1,13 +1,34 @@
1
- import { I as WorkflowStepFunction, L as WorkflowStepOptions, f as WorkflowDefinition, w as WorkflowProviderContext } from "../types-CnKVDnEp.js";
2
- import { t as NonRetryableError } from "../errors-DVwFb6Fd.js";
1
+ import { E as WorkflowProviderContext, G as WorkflowStepOptions, U as WorkflowStepContext, W as WorkflowStepFunction, _ as WorkflowDuration, f as WorkflowDefinition, q as WorkflowStepRetries } from "../types-BWPHeugk.js";
2
+ import { t as NonRetryableError } from "../errors-D-fNDVg0.js";
3
3
  //#region src/runtime/execute.d.ts
4
- export declare function runProviderStep<TResult>(step: WorkflowProviderContext["step"], name: string, run: () => TResult | Promise<TResult>, options?: WorkflowStepOptions): Promise<TResult>;
4
+ /** The options of a step with the default retries filled in. */
5
+ export interface ResolvedWorkflowStepOptions {
6
+ retries: Required<WorkflowStepRetries>;
7
+ timeout?: WorkflowDuration;
8
+ }
9
+ /**
10
+ * Checks the options of a step and fills in the default retries. A step file, `context.step.do()`, and every provider
11
+ * read the options through this function, so an invalid value fails the same way everywhere.
12
+ */
13
+ export declare function resolveWorkflowStepOptions(step: string, options: unknown): ResolvedWorkflowStepOptions;
14
+ /**
15
+ * Runs one attempt of a step. When `timeout` passes, the step's `signal` aborts and the attempt fails with
16
+ * `WORKFLOW_STEP_TIMEOUT`, so the provider retries it. A step that ignores the signal keeps running in the background:
17
+ * JavaScript cannot stop a promise.
18
+ */
19
+ export declare function runWorkflowStepAttempt<TResult>(step: string, timeout: WorkflowDuration | undefined, run: (context: WorkflowStepContext) => TResult | Promise<TResult>): Promise<TResult>;
20
+ /** Adds a timeout once, including when a provider receives an already wrapped folder step. */
21
+ export declare function withWorkflowStepTimeout<TResult>(name: string, timeout: WorkflowDuration | undefined, run: () => TResult | Promise<TResult>): () => TResult | Promise<TResult>;
22
+ export declare function runProviderStep<TResult>(step: WorkflowProviderContext["step"], name: string, run: (context: WorkflowStepContext) => TResult | Promise<TResult>, options?: WorkflowStepOptions): Promise<TResult>;
5
23
  /** `01.create-user.ts` becomes the `createUser` step. */
6
24
  export declare function toStepPropertyName(file: string): string;
7
25
  export declare function createWorkflowSteps(context: WorkflowProviderContext, stepModules: Array<{
8
26
  name: string;
27
+ options?: WorkflowStepOptions;
9
28
  run: WorkflowStepFunction;
10
- }>): Record<string, WorkflowStepFunction>;
29
+ }>): Record<string, (input: unknown) => Promise<unknown>>;
30
+ /** The milliseconds of a `WorkflowDuration`: a number of 0 or more, or a string such as `'30 seconds'`. */
31
+ export declare function toDurationMilliseconds(value: unknown): number | undefined;
11
32
  /**
12
33
  * The step result that says the step threw a `NonRetryableError`. A provider that retries every error, such as
13
34
  * OpenWorkflow, ends the step with it, so it does not run the step again. The caller throws the error outside the
@@ -1,17 +1,105 @@
1
- import { t as workflowErrorDiagnostics } from "../error-diagnostics-8YNJ37rP.js";
2
- import { r as isNonRetryableError, t as NonRetryableError } from "../errors-DCqRnZpN.js";
1
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics-DMeaFmQD.js";
2
+ import { n as createWorkflowError, r as isNonRetryableError, t as NonRetryableError } from "../errors-BNxEeeCO.js";
3
3
  import { t as getWorkflowDevRecorder } from "../dev-recorder-CTN5Fkao.js";
4
- import { isResponse, serializeResponse, toResponse } from "@vite-hub/runtime";
4
+ import { n as createWorkflowSignalToken, r as openInlineWorkflowSignal, s as waitForInlineWorkflowSignal, t as closeInlineWorkflowSignals } from "../signals-C1iolifd.js";
5
+ import { isResponse, serializeResponse, toResponse } from "@vite-hub/runtime/internal/response";
5
6
  //#region src/runtime/execute.ts
6
- const defaultStepOptions = { retries: {
7
+ const defaultRetries = {
7
8
  backoff: "exponential",
8
9
  delay: "10 seconds",
9
10
  limit: 3
10
- } };
11
- async function runProviderStep(step, name, run, options = defaultStepOptions) {
12
- if (typeof step?.do === "function") return await step.do(name, options, run);
11
+ };
12
+ const stepOptionKeys = /* @__PURE__ */ new Set(["retries", "timeout"]);
13
+ const retryOptionKeys = /* @__PURE__ */ new Set([
14
+ "backoff",
15
+ "delay",
16
+ "limit"
17
+ ]);
18
+ function isPlainObject(value) {
19
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20
+ }
21
+ /**
22
+ * Checks the options of a step and fills in the default retries. A step file, `context.step.do()`, and every provider
23
+ * read the options through this function, so an invalid value fails the same way everywhere.
24
+ */
25
+ function resolveWorkflowStepOptions(step, options) {
26
+ const invalid = (option, value) => workflowErrorDiagnostics.WORKFLOW_STEP_OPTIONS_INVALID({
27
+ option,
28
+ step,
29
+ value: typeof value === "string" ? JSON.stringify(value) : String(value)
30
+ });
31
+ if (options === void 0) return { retries: { ...defaultRetries } };
32
+ if (!isPlainObject(options)) throw invalid("options", options);
33
+ for (const key of Object.keys(options)) if (!stepOptionKeys.has(key)) throw invalid(key, options[key]);
34
+ const retries = options.retries ?? {};
35
+ if (!isPlainObject(retries)) throw invalid("retries", retries);
36
+ for (const key of Object.keys(retries)) if (!retryOptionKeys.has(key)) throw invalid(`retries.${key}`, retries[key]);
37
+ const { backoff = defaultRetries.backoff, delay = defaultRetries.delay, limit = defaultRetries.limit } = retries;
38
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 0) throw invalid("retries.limit", limit);
39
+ if (toDurationMilliseconds(delay) === void 0) throw invalid("retries.delay", delay);
40
+ if (backoff !== "constant" && backoff !== "exponential") throw invalid("retries.backoff", backoff);
41
+ const timeout = options.timeout;
42
+ if (timeout !== void 0 && !toDurationMilliseconds(timeout)) throw invalid("timeout", timeout);
43
+ return {
44
+ retries: {
45
+ backoff,
46
+ delay,
47
+ limit
48
+ },
49
+ ...timeout === void 0 ? {} : { timeout }
50
+ };
51
+ }
52
+ function onTimeout(milliseconds, callback) {
53
+ const deadline = Date.now() + milliseconds;
54
+ let timer;
55
+ const arm = () => {
56
+ timer = setTimeout(() => Date.now() >= deadline ? callback() : arm(), Math.min(Math.max(deadline - Date.now(), 0), maxTimerDelay));
57
+ };
58
+ arm();
59
+ return () => clearTimeout(timer);
60
+ }
61
+ /**
62
+ * Runs one attempt of a step. When `timeout` passes, the step's `signal` aborts and the attempt fails with
63
+ * `WORKFLOW_STEP_TIMEOUT`, so the provider retries it. A step that ignores the signal keeps running in the background:
64
+ * JavaScript cannot stop a promise.
65
+ */
66
+ async function runWorkflowStepAttempt(step, timeout, run) {
67
+ const controller = new AbortController();
68
+ const milliseconds = timeout === void 0 ? void 0 : toDurationMilliseconds(timeout);
69
+ if (milliseconds === void 0) return await run({ signal: controller.signal });
70
+ const label = typeof timeout === "number" ? `${timeout} ms` : String(timeout);
71
+ let cancel = () => {};
72
+ const expired = new Promise((_resolve, reject) => {
73
+ cancel = onTimeout(milliseconds, () => {
74
+ const error = workflowErrorDiagnostics.WORKFLOW_STEP_TIMEOUT({
75
+ step,
76
+ timeout: label
77
+ });
78
+ controller.abort(error);
79
+ reject(error);
80
+ });
81
+ });
82
+ try {
83
+ return await Promise.race([Promise.resolve().then(() => run({ signal: controller.signal })), expired]);
84
+ } finally {
85
+ cancel();
86
+ }
87
+ }
88
+ const timedAttempts = /* @__PURE__ */ new WeakSet();
89
+ /** Adds a timeout once, including when a provider receives an already wrapped folder step. */
90
+ function withWorkflowStepTimeout(name, timeout, run) {
91
+ if (timeout === void 0 || timedAttempts.has(run)) return run;
92
+ const attempt = () => runWorkflowStepAttempt(name, timeout, run);
93
+ timedAttempts.add(attempt);
94
+ return attempt;
95
+ }
96
+ async function runProviderStep(step, name, run, options) {
97
+ const resolved = resolveWorkflowStepOptions(name, options);
98
+ const attempt = () => runWorkflowStepAttempt(name, resolved.timeout, run);
99
+ timedAttempts.add(attempt);
100
+ if (typeof step?.do === "function") return await step.do(name, resolved, attempt);
13
101
  const recorder = getWorkflowDevRecorder();
14
- return recorder ? await recorder.step(name, run) : await run();
102
+ return recorder ? await recorder.step(name, attempt) : await attempt();
15
103
  }
16
104
  /** `01.create-user.ts` becomes the `createUser` step. */
17
105
  function toStepPropertyName(file) {
@@ -25,10 +113,9 @@ function createWorkflowSteps(context, stepModules) {
25
113
  const previousName = names.get(propertyName);
26
114
  if (previousName) throw workflowErrorDiagnostics.WORKFLOW_C0010({ message: `[vitehub] Workflow step files ${JSON.stringify(previousName)} and ${JSON.stringify(module.name)} both normalize to the \`${propertyName}\` step property. Rename one file so each step property is unique.` });
27
115
  names.set(propertyName, module.name);
28
- return [propertyName, async (input) => await runProviderStep(context.step, `${context.name}/${module.name}`, () => module.run(input))];
116
+ return [propertyName, async (input) => await runProviderStep(context.step, `${context.name}/${module.name}`, (stepContext) => module.run(input, stepContext), module.options)];
29
117
  }));
30
118
  }
31
- /** The units of a sleep duration, in milliseconds. Cloudflare reads a month as 30 days and a year as 365.25 days. */
32
119
  const durationUnits = {
33
120
  second: 1e3,
34
121
  minute: 6e4,
@@ -39,16 +126,20 @@ const durationUnits = {
39
126
  year: 315576e5
40
127
  };
41
128
  const durationPattern = /^(\d+(?:\.\d+)?) (second|minute|hour|day|week|month|year)s?$/;
42
- /** A sleep target: a number of milliseconds, or a date. */
129
+ /** The milliseconds of a `WorkflowDuration`: a number of 0 or more, or a string such as `'30 seconds'`. */
130
+ function toDurationMilliseconds(value) {
131
+ if (typeof value === "number") return Number.isFinite(value) && value >= 0 ? value : void 0;
132
+ if (typeof value !== "string") return void 0;
133
+ const match = durationPattern.exec(value);
134
+ return match ? Number(match[1]) * durationUnits[match[2]] : void 0;
135
+ }
43
136
  function toSleepTarget(name, until) {
44
137
  if (Object.prototype.toString.call(until) === "[object Date]") {
45
138
  const date = new Date(until.getTime());
46
139
  if (Number.isFinite(date.getTime())) return date;
47
- } else if (typeof until === "number") {
48
- if (Number.isFinite(until) && until >= 0) return until;
49
- } else if (typeof until === "string") {
50
- const match = durationPattern.exec(until);
51
- if (match) return Number(match[1]) * durationUnits[match[2]];
140
+ } else {
141
+ const milliseconds = toDurationMilliseconds(until);
142
+ if (milliseconds !== void 0) return milliseconds;
52
143
  }
53
144
  const value = typeof until === "string" ? JSON.stringify(until) : String(until);
54
145
  throw workflowErrorDiagnostics.WORKFLOW_SLEEP_DURATION_INVALID({
@@ -56,15 +147,10 @@ function toSleepTarget(name, until) {
56
147
  value
57
148
  });
58
149
  }
59
- /** Node fires a timer longer than this at once, so a longer wait uses more than one timer. */
60
150
  const maxTimerDelay = 2147483647;
61
151
  async function waitUntil(time) {
62
152
  for (let left = time - Date.now(); left > 0; left = time - Date.now()) await new Promise((resolve) => setTimeout(resolve, Math.min(left, maxTimerDelay)));
63
153
  }
64
- /**
65
- * `context.sleep()` of a folder Workflow. It names each sleep by call order (`sleep-1`, `sleep-2`), so the orchestrator
66
- * must call it in the same order on each replay. Without a provider sleep, the run is inline and waits with a timer.
67
- */
68
154
  function createSleep(context) {
69
155
  let count = 0;
70
156
  return async (until) => {
@@ -80,19 +166,52 @@ function createSleep(context) {
80
166
  await runProviderStep(void 0, name, async () => await waitUntil(time));
81
167
  };
82
168
  }
83
- /**
84
- * Gives every handler `context.sleep()` and a step runner. Generated folder Workflows replace this empty runner with
85
- * their step files. The context keeps the provider step at runtime, so the generated step runner can use it.
86
- */
87
- function toExecutionContext(context, sleep) {
169
+ function createSignals(context, wait) {
170
+ let count = 0;
171
+ const inlineTokens = [];
172
+ const createSignal = () => {
173
+ if (context.provider === "vercel") throw workflowErrorDiagnostics.WORKFLOW_SIGNAL_VERCEL_UNSUPPORTED({ name: context.name });
174
+ const step = context.step;
175
+ if (step?.do && !step.waitForSignal) throw createWorkflowError({
176
+ code: "WORKFLOW_OPERATION_UNSUPPORTED",
177
+ details: {
178
+ operation: "signals",
179
+ provider: context.provider
180
+ }
181
+ });
182
+ const name = `signal-${++count}`;
183
+ const inline = !step?.waitForSignal;
184
+ const token = createWorkflowSignalToken({
185
+ host: inline ? "inline" : context.provider,
186
+ run: context.id ?? "",
187
+ signal: name,
188
+ workflow: context.name
189
+ });
190
+ if (inline) {
191
+ openInlineWorkflowSignal(token);
192
+ inlineTokens.push(token);
193
+ }
194
+ let waiting;
195
+ return {
196
+ token,
197
+ wait: () => waiting ??= wait ? wait() : inline ? runProviderStep(void 0, name, async () => await waitForInlineWorkflowSignal(token)) : step.waitForSignal(name, token)
198
+ };
199
+ };
200
+ return {
201
+ close: () => closeInlineWorkflowSignals(inlineTokens),
202
+ createSignal
203
+ };
204
+ }
205
+ function toExecutionContext(context, sleep, createSignal) {
88
206
  return {
89
207
  ...context,
208
+ createSignal,
90
209
  sleep,
91
210
  steps: {}
92
211
  };
93
212
  }
94
- /** The root step result that says the handler called `context.sleep()`. A replay reads it and fails the same way. */
95
213
  const rootStepSleepResult = { "~vitehubRootStepSleep": true };
214
+ const rootStepSignalResult = { "~vitehubRootStepSignal": true };
96
215
  function toNonRetryableStepResult(error) {
97
216
  if (!isNonRetryableError(error)) return void 0;
98
217
  const code = Reflect.get(error, "code");
@@ -109,38 +228,44 @@ function readNonRetryableStepResult(value) {
109
228
  error.name = name;
110
229
  return code === void 0 ? error : Object.assign(error, { code });
111
230
  }
112
- /**
113
- * Runs the handler in its root step, or alone for a folder Workflow (`rootStep: false`). A sleep inside the root step
114
- * fails the run with `WORKFLOW_ROOT_STEP_SLEEP` on every provider. The root step returns a marker instead of throwing,
115
- * so the provider does not retry it and run the code before the sleep again.
116
- */
117
231
  async function runInRootStep(context, definition, encode) {
118
- if (definition.options?.rootStep === false) return await encode(await definition.handler(context.payload, toExecutionContext(context, createSleep(context))));
119
- let slept = false;
232
+ if (definition.rootStep === false) {
233
+ const signals = createSignals(context);
234
+ try {
235
+ return await encode(await definition.handler(toExecutionContext(context, createSleep(context), signals.createSignal)));
236
+ } finally {
237
+ signals.close();
238
+ }
239
+ }
240
+ let suspended;
120
241
  const sleepError = () => workflowErrorDiagnostics.WORKFLOW_ROOT_STEP_SLEEP({ name: context.name });
242
+ const signalError = () => workflowErrorDiagnostics.WORKFLOW_ROOT_STEP_SIGNAL({ name: context.name });
121
243
  const sleep = async () => {
122
- slept = true;
244
+ suspended = rootStepSleepResult;
123
245
  throw sleepError();
124
246
  };
247
+ const signals = createSignals(context, async () => {
248
+ suspended = rootStepSignalResult;
249
+ throw signalError();
250
+ });
125
251
  const output = await runProviderStep(context.step, context.name, async () => {
126
252
  try {
127
- const value = await encode(await definition.handler(context.payload, toExecutionContext(context, sleep)));
128
- return slept ? rootStepSleepResult : value;
253
+ const value = await encode(await definition.handler(toExecutionContext(context, sleep, signals.createSignal)));
254
+ return suspended ?? value;
129
255
  } catch (error) {
130
- if (slept) return rootStepSleepResult;
256
+ if (suspended) return suspended;
131
257
  throw error;
258
+ } finally {
259
+ signals.close();
132
260
  }
133
261
  });
134
262
  if (typeof output === "object" && output !== null && "~vitehubRootStepSleep" in output) throw sleepError();
263
+ if (typeof output === "object" && output !== null && "~vitehubRootStepSignal" in output) throw signalError();
135
264
  return output;
136
265
  }
137
266
  async function runWorkflowHandler(context, definition) {
138
267
  return toResponse(await runInRootStep(context, definition, (value) => value));
139
268
  }
140
- /**
141
- * The stored result of a run. A `Response` from the handler is stored as a serialized Response. Any other value is
142
- * stored as JSON, so every provider returns the same plain value.
143
- */
144
269
  async function toStoredWorkflowResult(value) {
145
270
  if (isResponse(value)) return await serializeResponse(value);
146
271
  const json = JSON.stringify(value);
@@ -151,4 +276,4 @@ async function runSerializedWorkflowHandler(context, definition) {
151
276
  return await runInRootStep(context, definition, toStoredWorkflowResult);
152
277
  }
153
278
  //#endregion
154
- export { createWorkflowSteps, readNonRetryableStepResult, runProviderStep, runSerializedWorkflowHandler, runWorkflowHandler, toNonRetryableStepResult, toStepPropertyName };
279
+ export { createWorkflowSteps, readNonRetryableStepResult, resolveWorkflowStepOptions, runProviderStep, runSerializedWorkflowHandler, runWorkflowHandler, runWorkflowStepAttempt, toDurationMilliseconds, toNonRetryableStepResult, toStepPropertyName, withWorkflowStepTimeout };
@@ -1,5 +1,5 @@
1
- import { l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-CnKVDnEp.js";
2
- import { o as getOpenWorkflowRuntime } from "../openworkflow-TEaNk0LV.js";
1
+ import { l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-BWPHeugk.js";
2
+ import { o as getOpenWorkflowRuntime } from "../openworkflow-BoaENgh9.js";
3
3
  import { ViteHubError } from "@vite-hub/runtime";
4
4
  import { ShutdownApp } from "@vite-hub/runtime/internal/shutdown";
5
5
  //#region src/runtime/openworkflow-worker.d.ts