@vite-hub/workflow 0.3.1 → 0.4.1

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 (41) hide show
  1. package/README.md +52 -35
  2. package/dist/{app-CmMq8l4t.js → app-He0GTrYZ.js} +1 -1
  3. package/dist/{client-CU5rELC0.js → client-DkwOxEiT.js} +88 -39
  4. package/dist/{cloudflare-BfFnNWB0.js → cloudflare-BHfClPvT.js} +1 -1
  5. package/dist/{config-DCvRDlxA.js → config-C3DvtjfJ.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-D1-nq_VE.js} +6 -41
  9. package/dist/durability.d.ts +1 -1
  10. package/dist/{error-diagnostics-8YNJ37rP.js → error-diagnostics-0V2T3JFw.js} +45 -14
  11. package/dist/{error-diagnostics-DSkCJC_L.js → error-diagnostics-CQ4BUqRe.js} +5 -1
  12. package/dist/{errors-DVwFb6Fd.d.ts → errors-uhP8DZTi.d.ts} +12 -1
  13. package/dist/index.d.ts +30 -11
  14. package/dist/index.js +12 -5
  15. package/dist/{openworkflow-TEaNk0LV.d.ts → openworkflow-BhzxV_Y3.d.ts} +3 -1
  16. package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-nmRu_O3V.d.ts} +5 -0
  17. package/dist/{operations-B0L8kV5s.js → operations-D_WJwjrS.js} +9 -5
  18. package/dist/operations.d.ts +2 -2
  19. package/dist/operations.js +2 -2
  20. package/dist/{out-fRNaVslw.js → out-DxLKolA0.js} +1 -1
  21. package/dist/{rolldown-runtime-CMFfr-1z.js → rolldown-runtime-B4iAMlE-.js} +10 -1
  22. package/dist/run-failed-gVGo1BaF.js +18 -0
  23. package/dist/runtime/cloudflare-runner.d.ts +1 -1
  24. package/dist/runtime/cloudflare-runner.js +17 -5
  25. package/dist/runtime/cloudflare-vite.d.ts +1 -1
  26. package/dist/runtime/cloudflare-vite.js +2 -2
  27. package/dist/runtime/execute.d.ts +25 -4
  28. package/dist/runtime/execute.js +108 -15
  29. package/dist/runtime/openworkflow-worker.d.ts +2 -2
  30. package/dist/runtime/openworkflow-worker.js +1 -1
  31. package/dist/runtime/openworkflow.d.ts +1 -1
  32. package/dist/runtime/openworkflow.js +37 -11
  33. package/dist/runtime/state.d.ts +1 -1
  34. package/dist/runtime/state.js +2 -6
  35. package/dist/runtime/vercel-vite.d.ts +1 -1
  36. package/dist/runtime/vercel-vite.js +2 -2
  37. package/dist/{types-CnKVDnEp.d.ts → types-Dsmwsdlv.d.ts} +67 -26
  38. package/dist/{vercel-BZU_O6ay.js → vercel-DTvm61iY.js} +4 -4
  39. package/dist/vite.d.ts +17 -11
  40. package/dist/vite.js +1116 -529
  41. package/package.json +4 -4
@@ -8,6 +8,21 @@ const workflowErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
8
8
  why: ({ name }) => `[vitehub] The Agent Workflow ${JSON.stringify(name)} is not a discovered Agent, so OpenWorkflow workers cannot run its turns.`,
9
9
  fix: "Move the Agent to server/agents/, so that the build adds its Workflow to the registry that every OpenWorkflow worker loads. To run it without a Workflow, call runAgent()."
10
10
  },
11
+ WORKFLOW_PROVIDER_OPERATION_FAILED: {
12
+ why: ({ operation, provider, reason }) => `The ${provider} Workflow provider failed during ${operation}.${reason ? ` ${reason}` : ""}`,
13
+ fix: ({ acknowledgement }) => acknowledgement === "unknown" ? "The call may have reached the provider. If the original start supplied a run `id`, check that ID with `getWorkflowRun()` and reuse the same ID if you retry. If you do not know the original ID, verify whether the run started before trying again. Read `error.cause` for the provider error." : "Read `error.cause` for the provider error. Retry when the provider is available again.",
14
+ data: ({ acknowledgement, operation, provider, reason, status }) => ({
15
+ acknowledgement,
16
+ operation,
17
+ provider,
18
+ reason,
19
+ status
20
+ })
21
+ },
22
+ WORKFLOW_RUN_ID_UNSUPPORTED: {
23
+ why: "A native Vercel Workflow assigns its own run ID, so `startWorkflow()` cannot use the `id` option.",
24
+ fix: "Remove `id` from the options of `startWorkflow()`. Store the `id` of the run that it returns."
25
+ },
11
26
  WORKFLOW_DEFINITION_NOT_FOUND: {
12
27
  why: ({ available, workflow }) => workflow === void 0 ? "Workflow definition was not found." : `Unknown Workflow: ${workflow}.${available ?? ""}`,
13
28
  fix: "Pass the name of a Workflow Definition, the file name in `server/workflows/` without the extension."
@@ -22,7 +37,11 @@ const workflowErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
22
37
  },
23
38
  WORKFLOW_OPERATION_UNSUPPORTED: {
24
39
  why: ({ note, operation, provider }) => note === void 0 ? `workflow ${operation} is not supported by the ${provider} provider for this run.` : `workflow ${operation} is not supported by the ${provider} provider. ${note}`,
25
- fix: "Use an operation that the provider supports, or run the app with a Workflow provider that supports it. The message says what the provider cannot do."
40
+ fix: "Use an operation that the provider supports, or run the app with a Workflow provider that supports it. The message says what the provider cannot do.",
41
+ data: ({ operation, provider }) => ({
42
+ operation,
43
+ provider
44
+ })
26
45
  },
27
46
  WORKFLOW_REGISTRY_MISSING: {
28
47
  why: ({ workflow }) => `Unknown Workflow: ${workflow}. The runtime has no Workflow registry.`,
@@ -98,28 +117,20 @@ const workflowErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
98
117
  },
99
118
  WORKFLOW_C0014: {
100
119
  ...dynamicError,
101
- fix: "Pass a function as the second argument of `defineWorkflow()`, such as `defineWorkflow(\"onboard-user\", async (payload, { steps }) => { ... })`."
120
+ fix: "Set `handler` to a function in the object that you pass to `defineWorkflow()`, such as `defineWorkflow({ handler: async ({ payload, steps }) => { ... } })`."
102
121
  },
103
122
  WORKFLOW_C0015: {
104
123
  ...dynamicError,
105
- fix: "Pass the options of `defineWorkflow()` as an object, such as `{ native: durableOnboard }`, or remove the third argument."
124
+ fix: "Pass one object to `defineWorkflow()`, such as `defineWorkflow({ handler, native })`, with only `handler`, `native`, and `rootStep`. The file path is the Workflow name, so do not pass a name."
106
125
  },
107
126
  WORKFLOW_C0016: {
108
127
  ...dynamicError,
109
- fix: "Set `native` in the `defineWorkflow()` options to a function, or remove it."
128
+ fix: "Set `native` in the object that you pass to `defineWorkflow()` to a function, or remove it."
110
129
  },
111
130
  WORKFLOW_C0017: {
112
131
  ...dynamicError,
113
132
  fix: "Remove `workflow.database`, and set `workflow.sqlite.path` or `workflow.postgres.url`."
114
133
  },
115
- WORKFLOW_C0018: {
116
- ...dynamicError,
117
- fix: "Pass the Workflow name as the first argument of `defineWorkflow()`, such as `defineWorkflow(\"onboard-user\", handler)`."
118
- },
119
- WORKFLOW_C0019: {
120
- ...dynamicError,
121
- fix: "Pass the name that the message gives to `defineWorkflow()`, or rename the Workflow file or folder to the name that the definition uses."
122
- },
123
134
  WORKFLOW_C0020: {
124
135
  ...dynamicError,
125
136
  fix: "Set `workflow: { driver: \"openworkflow\", sqlite: { path: \".vitehub/data/workflow.sqlite\" } }` or `workflow.postgres.url`, and start the worker with `startOpenWorkflowWorker()`."
@@ -144,6 +155,10 @@ const workflowErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
144
155
  why: ({ seconds }) => `Another server held the OpenWorkflow schema setup lock for ${seconds} seconds. This server did not start the schema setup.`,
145
156
  fix: "Check the server that holds the setup lock and let its migration finish. The worker retries automatically. If you start a worker yourself, retry after the lock is released."
146
157
  },
158
+ WORKFLOW_PAYLOAD_JSON_INVALID: {
159
+ why: "[vitehub] The request has the `application/json` content type, but its body is not valid JSON.",
160
+ fix: "Send a JSON body with `content-type: application/json`, or send another content type to read the body as text. Read `error.cause` for the parse error."
161
+ },
147
162
  WORKFLOW_R0001: {
148
163
  ...dynamicError,
149
164
  fix: "Remove `workflow.binding` and `workflow.name`, which apply only to an app with one Workflow, or keep one Workflow under `server/workflows/`."
@@ -277,8 +292,24 @@ const workflowErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
277
292
  fix: "Write the duration as a number, one space, and a unit: second, minute, hour, day, week, month, or year, with or without a final `s`. For example `context.sleep('2 hours')`, `context.sleep(5_000)`, or `context.sleep(new Date(payload.remindAt))`."
278
293
  },
279
294
  WORKFLOW_START_DELAY_INVALID: {
280
- why: ({ delay }) => `[vitehub] \`startWorkflow()\` does not accept the delay ${JSON.stringify(delay)}. A delay is a number of milliseconds of 0 or more, a duration such as \`"30 minutes"\` or \`"3 days"\`, or a valid \`Date\`.`,
281
- fix: "Pass `{ delay: 60_000 }`, `{ delay: \"1 hour\" }`, or `{ delay: new Date(\"2026-12-01T09:00:00Z\") }`. The duration units are ms, seconds, minutes, hours, days, and weeks. For a month or a calendar time, pass a `Date`."
295
+ why: ({ delay }) => `[vitehub] \`startWorkflow()\` does not accept the delay ${JSON.stringify(delay)}. A delay is a duration such as \`"30m"\` or \`"3 days"\`, or a valid \`Date\`, that ends before the year 275760.`,
296
+ fix: "Pass `{ delay: \"1h\" }`, `{ delay: \"3 days\" }`, or `{ delay: new Date(\"2026-12-01T09:00:00Z\") }`. For a month or a calendar time, pass a `Date`."
297
+ },
298
+ WORKFLOW_STEP_OPTIONS_INVALID: {
299
+ why: ({ option, step, value }) => `[vitehub] The Workflow step ${JSON.stringify(step)} sets \`${option}\` to ${value}. A step takes \`retries: { limit, delay, backoff }\` and \`timeout\`.`,
300
+ fix: "Set `retries.limit` to a whole number of 0 or more, `retries.delay` to a duration such as `'30 seconds'` or a number of milliseconds, `retries.backoff` to `'constant'` or `'exponential'`, and `timeout` to a duration that is more than 0. Remove other keys."
301
+ },
302
+ WORKFLOW_STEP_OPTIONS_NOT_STATIC: {
303
+ why: ({ file, option }) => `[vitehub] The Workflow step file ${JSON.stringify(file)} exports \`${option}\`, and the build cannot read its value without running the file.`,
304
+ fix: "Write the value in the export itself, with literals only, such as `export const retries = { limit: 5, delay: '30 seconds' }` or `export const timeout = '2 minutes'`. The build reads it from the source to check it and to configure the provider."
305
+ },
306
+ WORKFLOW_STEP_RETRY_DELAY_UNSUPPORTED: {
307
+ why: ({ file }) => `[vitehub] The Workflow step file ${JSON.stringify(file)} sets \`retries.delay\` or \`retries.backoff\`. On Vercel, Workflow DevKit runs this step and retries it after about one second. It has no wait or backoff option for a step.`,
308
+ fix: "Remove `delay` and `backoff` from `retries`, and keep `limit`. To wait longer between attempts, deploy the Workflow on Cloudflare or OpenWorkflow."
309
+ },
310
+ WORKFLOW_STEP_TIMEOUT: {
311
+ why: ({ step, timeout }) => `[vitehub] The Workflow step ${JSON.stringify(step)} ran longer than its timeout of ${timeout}. ViteHub aborted the step's signal and failed this attempt.`,
312
+ fix: "Make the step finish sooner, or set a longer `timeout` in the step file. Pass the `signal` of the step to `fetch()` and other calls, so they stop when the attempt times out. The provider retries the step as its `retries` say."
282
313
  }
283
314
  }
284
315
  });
@@ -170,7 +170,7 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
170
170
  },
171
171
  INTERNAL_R0004: {
172
172
  ...dynamicError,
173
- fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `fetch()` Source options, or ask the server for a smaller response."
173
+ fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `url()` Source options, or ask the server for a smaller response."
174
174
  },
175
175
  INTERNAL_R0005: {
176
176
  ...dynamicError,
@@ -216,6 +216,10 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
216
216
  why: ({ variable }) => `[vitehub] ${variable} must be the 43-character private key that \`vitehub secret console-key\` prints, and its name 1 to 64 of A-Z, 0-9, and _.`,
217
217
  fix: "Set the variable that the message names to the private key that `vitehub secret console-key` prints, and name it `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` with A-Z, 0-9, and _ in `<NAME>`."
218
218
  },
219
+ INTERNAL_DEV_SERVER_NOT_FOUND: {
220
+ why: ({ command }) => `[vitehub] No dev server of this project is running, and --url is not set, so \`vitehub ${command}\` has no app to call.`,
221
+ fix: "Start the dev server of this project, such as with `pnpm dev`, or pass --url with the app URL, such as --url http://localhost:3000."
222
+ },
219
223
  INTERNAL_FORGE_NOT_INSTALLED: {
220
224
  why: ({ feature }) => `${feature} needs @vite-hub/forge, and the app did not install it.`,
221
225
  fix: "Install Forge in your app with `pnpm add @vite-hub/forge`, then build again."
@@ -32,6 +32,17 @@ type WorkflowOperationDetails = {
32
32
  };
33
33
  /** `rejected`: the provider answered and refused the call. `unknown`: the call can have reached the provider. */
34
34
  type WorkflowProviderAcknowledgement = "rejected" | "unknown";
35
+ /** What `WORKFLOW_PROVIDER_OPERATION_FAILED` keeps in `error.data` when a Workflow call returns it. */
36
+ type WorkflowProviderFailure = {
37
+ /** `rejected`: the provider answered and refused the call. `unknown`: the call can have reached the provider. */
38
+ acknowledgement?: WorkflowProviderAcknowledgement;
39
+ operation: string;
40
+ provider: string;
41
+ /** The provider error name and the first line of its message, without URLs, file paths, or credentials. */
42
+ reason?: string;
43
+ /** The HTTP status of the provider, when it sent one. */
44
+ status?: number;
45
+ };
35
46
  type WorkflowProviderOperationDetails = WorkflowOperationDetails & {
36
47
  acknowledgement?: WorkflowProviderAcknowledgement;
37
48
  /** The provider error name and the first line of its message, without URLs, file paths, or credentials. */
@@ -53,4 +64,4 @@ declare class NonRetryableError extends Error {
53
64
  readonly fatal = true;
54
65
  }
55
66
  //#endregion
56
- export { WorkflowProviderName as a, WorkflowOperationName as i, WorkflowErrorCode as n, WorkflowErrorDetails as r, NonRetryableError as t };
67
+ export { WorkflowProviderFailure as a, WorkflowOperationName as i, WorkflowErrorCode as n, WorkflowProviderName as o, WorkflowErrorDetails as r, NonRetryableError as t };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { C as WorkflowOptions, D as WorkflowRunError, E as WorkflowRun, F as WorkflowStep, I as WorkflowStepFunction, L as WorkflowStepOptions, M as WorkflowSignalResult, N as WorkflowStartDelay, O as WorkflowRunStatus, P as WorkflowStartOptions, R as WorkflowStepRegistry, S as WorkflowModuleDriverOptions, T as WorkflowProviderStep, _ as WorkflowDuration, a as InferredWorkflowDriverOptions, b as WorkflowHandle, c as OpenWorkflowWorkerOptions, d as WorkflowCreateOptions, f as WorkflowDefinition, g as WorkflowDriverOptions, h as WorkflowDriver, i as DiscoveredWorkflowDefinition, j as WorkflowSharedOptions, k as WorkflowRunStep, l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry, n as CloudflareWorkflowDriverOptions, o as OpenWorkflowDriverOptions, p as WorkflowDefinitionOptions, r as CloudflareWorkflowInstance, s as OpenWorkflowPostgresOptions, t as CloudflareWorkflowBinding, u as VercelWorkflowDriverOptions, v as WorkflowDurationUnit, w as WorkflowProviderContext, x as WorkflowHandler, y as WorkflowExecutionContext, z as WorkflowSteps } from "./types-CnKVDnEp.js";
1
+ import { A as WorkflowRun, B as WorkflowStep, C as WorkflowName, D as WorkflowProviderStep, E as WorkflowProviderContext, F as WorkflowSharedOptions, G as WorkflowStepRegistry, H as WorkflowStepContext, I as WorkflowSignalResult, K as WorkflowStepRetries, L as WorkflowStartArguments, M as WorkflowRunStatus, N as WorkflowRunStep, O as WorkflowRegistry, R as WorkflowStartDelay, S as WorkflowModuleDriverOptions, T as WorkflowPayload, U as WorkflowStepFunction, V as WorkflowStepBackoff, W as WorkflowStepOptions, _ as WorkflowDuration, a as InferredWorkflowDriverOptions, b as WorkflowHandle, c as OpenWorkflowWorkerOptions, d as WorkflowCreateOptions, f as WorkflowDefinition, g as WorkflowDriverOptions, h as WorkflowDriver, i as DiscoveredWorkflowDefinition, j as WorkflowRunError, k as WorkflowResultErrorCode, l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry, n as CloudflareWorkflowDriverOptions, o as OpenWorkflowDriverOptions, p as WorkflowDefinitionOptions, q as WorkflowSteps, r as CloudflareWorkflowInstance, s as OpenWorkflowPostgresOptions, t as CloudflareWorkflowBinding, u as VercelWorkflowDriverOptions, v as WorkflowDurationUnit, w as WorkflowOptions, x as WorkflowHandler, y as WorkflowExecutionContext, z as WorkflowStartOptions } from "./types-Dsmwsdlv.js";
2
2
  import { defineWorkflow } from "./definition.js";
3
- import { a as WorkflowProviderName, i as WorkflowOperationName, n as WorkflowErrorCode, r as WorkflowErrorDetails, t as NonRetryableError } from "./errors-DVwFb6Fd.js";
3
+ import { a as WorkflowProviderFailure, i as WorkflowOperationName, n as WorkflowErrorCode, o as WorkflowProviderName, r as WorkflowErrorDetails, t as NonRetryableError } from "./errors-uhP8DZTi.js";
4
+ import { Result } from "@vite-hub/runtime";
4
5
  //#region src/integrations/cloudflare.d.ts
5
6
  export declare function getCloudflareWorkflowBindingName(name: string): string;
6
7
  //#endregion
@@ -16,17 +17,34 @@ export declare function createWorkflow<TPayload = unknown>(name: string, options
16
17
  handler?: never;
17
18
  }): WorkflowHandle<TPayload, unknown>;
18
19
  export declare function createWorkflow<TPayload = unknown, TResult = unknown>(name: string, handler: WorkflowHandler<TPayload, TResult>, options?: WorkflowCreateOptions<TPayload, TResult>): WorkflowHandle<TPayload, TResult>;
19
- /** Starts one durable run of a Workflow Definition and returns its id and status. */
20
- export declare function startWorkflow<TPayload = unknown>(name: string, payload?: TPayload, options?: WorkflowStartOptions): Promise<WorkflowRun<TPayload, unknown>>;
21
- export declare function getWorkflowRun(name: string, id: string): Promise<WorkflowRun<unknown, unknown>>;
22
- export declare function cancelWorkflow(name: string, id: string): Promise<WorkflowRun<unknown, unknown>>;
23
- /** Resumes a run that waits for a signal. `token` is the opaque token that the provider gave the waiting step. */
24
- export declare function resumeWorkflow<TPayload = unknown>(token: string, payload: TPayload): Promise<WorkflowSignalResult>;
20
+ /**
21
+ * Starts one durable run of a Workflow Definition and returns `[error, run]`. `run` has the id and the status.
22
+ * The name and the payload type come from `WorkflowRegistry`, which ViteHub writes to `.vitehub/workflow.d.ts`.
23
+ * A provider failure, an unsupported option, or an invalid `delay` is `error`. Config errors, for example an unknown
24
+ * Workflow name, throw.
25
+ */
26
+ export declare function startWorkflow<TArgs extends WorkflowStartCall>(...args: TArgs): Promise<Result<WorkflowRun<WorkflowPayload<TArgs[0]>, unknown>, WorkflowResultErrorCode>>;
27
+ type WorkflowStartCall = { [TName in WorkflowName]: [name: TName, ...WorkflowStartArguments<WorkflowPayload<TName>>]; }[WorkflowName];
28
+ /**
29
+ * Reads one run and returns `[error, run]`. A provider failure is `error`. A run that the provider does not know has
30
+ * `status: "unknown"`. Config errors throw.
31
+ */
32
+ export declare function getWorkflowRun(name: string, id: string): Promise<Result<WorkflowRun<unknown, unknown>, WorkflowResultErrorCode>>;
33
+ /**
34
+ * Cancels one run and returns `[error, run]`. A provider failure, or a provider that cannot cancel the run, is
35
+ * `error`. Config errors, for example an unknown Workflow name, throw.
36
+ */
37
+ export declare function cancelWorkflow(name: string, id: string): Promise<Result<WorkflowRun<unknown, unknown>, WorkflowResultErrorCode>>;
38
+ /**
39
+ * Resumes a run that waits for a signal and returns `[error, signal]`. `token` is the opaque token that the provider
40
+ * gave the waiting step. An empty token or a provider failure is `error`. Config errors throw.
41
+ */
42
+ export declare function resumeWorkflow<TPayload = unknown>(token: string, payload: TPayload): Promise<Result<WorkflowSignalResult, WorkflowResultErrorCode>>;
25
43
  /**
26
44
  * Starts a run after the response, through `waitUntil`. It returns nothing: a failure goes to the log.
27
45
  * Call `startWorkflow()` when the caller needs the run ID or the start error.
28
46
  */
29
- export declare function deferWorkflow<TPayload = unknown>(name: string, payload?: TPayload, options?: WorkflowStartOptions): void;
47
+ export declare function deferWorkflow(...[name, payload, options]: WorkflowStartCall): void;
30
48
  //#endregion
31
49
  //#region src/runtime/payload.d.ts
32
50
  interface PayloadSchema<T> {
@@ -40,8 +58,9 @@ interface ParsePayloadSchema<T> {
40
58
  parse: (payload: unknown) => T;
41
59
  }
42
60
  type PayloadValidator<T> = PayloadSchema<T> | ParsePayloadSchema<T> | ((payload: unknown) => T | Promise<T>);
43
- export declare function readRequestPayload<T = unknown>(request: Request): Promise<T>;
61
+ /** Reads a JSON body as parsed JSON and any other body as text. The value is not checked: pass it to `validatePayload()`. */
62
+ export declare function readRequestPayload(request: Request): Promise<unknown>;
44
63
  export declare function validatePayload<T>(payload: unknown, schema: PayloadValidator<T>): Promise<T>;
45
64
  export declare function readValidatedPayload<T>(request: Request, schema: PayloadValidator<T>): Promise<T>;
46
65
  //#endregion
47
- export { type CloudflareWorkflowBinding, type CloudflareWorkflowDriverOptions, type CloudflareWorkflowInstance, type DiscoveredWorkflowDefinition, type InferredWorkflowDriverOptions, NonRetryableError, type OpenWorkflowDriverOptions, type OpenWorkflowPostgresOptions, type OpenWorkflowWorkerOptions, type ResolvedWorkflowOptions, type VercelWorkflowDriverOptions, type WorkflowCreateOptions, type WorkflowDefinition, type WorkflowDefinitionOptions, type WorkflowDefinitionRegistry, type WorkflowDriver, type WorkflowDriverOptions, type WorkflowDuration, type WorkflowDurationUnit, type WorkflowErrorCode, type WorkflowErrorDetails, type WorkflowExecutionContext, type WorkflowHandle, type WorkflowHandler, type WorkflowModuleDriverOptions, type WorkflowOperationName, type WorkflowOptions, type WorkflowProviderContext, type WorkflowProviderName, type WorkflowProviderStep, type WorkflowRun, type WorkflowRunError, type WorkflowRunStatus, type WorkflowRunStep, type WorkflowSharedOptions, type WorkflowSignalResult, type WorkflowStartDelay, type WorkflowStartOptions, type WorkflowStep, type WorkflowStepFunction, type WorkflowStepOptions, type WorkflowStepRegistry, type WorkflowSteps, defineWorkflow };
66
+ export { type CloudflareWorkflowBinding, type CloudflareWorkflowDriverOptions, type CloudflareWorkflowInstance, type DiscoveredWorkflowDefinition, type InferredWorkflowDriverOptions, NonRetryableError, type OpenWorkflowDriverOptions, type OpenWorkflowPostgresOptions, type OpenWorkflowWorkerOptions, type ResolvedWorkflowOptions, type VercelWorkflowDriverOptions, type WorkflowCreateOptions, type WorkflowDefinition, type WorkflowDefinitionOptions, type WorkflowDefinitionRegistry, type WorkflowDriver, type WorkflowDriverOptions, type WorkflowDuration, type WorkflowDurationUnit, type WorkflowErrorCode, type WorkflowErrorDetails, type WorkflowExecutionContext, type WorkflowHandle, type WorkflowHandler, type WorkflowModuleDriverOptions, type WorkflowName, type WorkflowOperationName, type WorkflowOptions, type WorkflowPayload, type WorkflowProviderContext, type WorkflowProviderFailure, type WorkflowProviderName, type WorkflowProviderStep, type WorkflowRegistry, type WorkflowResultErrorCode, type WorkflowRun, type WorkflowRunError, type WorkflowRunStatus, type WorkflowRunStep, type WorkflowSharedOptions, type WorkflowSignalResult, type WorkflowStartDelay, type WorkflowStartOptions, type WorkflowStep, type WorkflowStepBackoff, type WorkflowStepContext, type WorkflowStepFunction, type WorkflowStepOptions, type WorkflowStepRegistry, type WorkflowStepRetries, type WorkflowSteps, defineWorkflow };
package/dist/index.js CHANGED
@@ -1,12 +1,19 @@
1
- import { t as workflowErrorDiagnostics } from "./error-diagnostics-8YNJ37rP.js";
1
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics-0V2T3JFw.js";
2
2
  import { defineWorkflow } from "./definition.js";
3
3
  import { t as NonRetryableError } from "./errors-DCqRnZpN.js";
4
- import { n as getCloudflareWorkflowBindingName } from "./cloudflare-BfFnNWB0.js";
5
- import { a as resumeWorkflow, i as getWorkflowRun, n as createWorkflow, o as startWorkflow, r as deferWorkflow, t as cancelWorkflow } from "./client-CU5rELC0.js";
4
+ import { n as getCloudflareWorkflowBindingName } from "./cloudflare-BHfClPvT.js";
5
+ import { a as resumeWorkflow, i as getWorkflowRun, n as createWorkflow, o as startWorkflow, r as deferWorkflow, t as cancelWorkflow } from "./client-DkwOxEiT.js";
6
6
  //#region src/runtime/payload.ts
7
+ /** Reads a JSON body as parsed JSON and any other body as text. The value is not checked: pass it to `validatePayload()`. */
7
8
  async function readRequestPayload(request) {
8
- if (request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() === "application/json") return await request.json();
9
- return await request.text();
9
+ const contentType = request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
10
+ const text = await request.text();
11
+ if (contentType !== "application/json") return text;
12
+ try {
13
+ return JSON.parse(text);
14
+ } catch (cause) {
15
+ throw workflowErrorDiagnostics.WORKFLOW_PAYLOAD_JSON_INVALID({ cause });
16
+ }
10
17
  }
11
18
  async function validatePayload(payload, schema) {
12
19
  if (typeof schema === "function") return await schema(payload);
@@ -1,4 +1,4 @@
1
- import { E as WorkflowRun, P as WorkflowStartOptions, f as WorkflowDefinition, l as ResolvedWorkflowOptions } from "./types-CnKVDnEp.js";
1
+ import { A as WorkflowRun, f as WorkflowDefinition, l as ResolvedWorkflowOptions, z as WorkflowStartOptions } from "./types-Dsmwsdlv.js";
2
2
  //#region src/runtime/openworkflow.d.ts
3
3
  type OpenWorkflowModule = typeof import("openworkflow");
4
4
  type OpenWorkflowPostgresModule = typeof import("openworkflow/postgres");
@@ -10,6 +10,8 @@ type OpenWorkflowImporter = <T>(specifier: string) => Promise<T>;
10
10
  interface OpenWorkflowRuntime {
11
11
  backend: OpenWorkflowBackend;
12
12
  client: OpenWorkflowClient;
13
+ /** The registered ViteHub definitions, by name. */
14
+ definitions: Map<string, WorkflowDefinition>;
13
15
  /** Returns the OpenWorkflow id of the first run of `name` that started with the id `key`. */
14
16
  findRunId: (name: string, key: string) => Promise<string | undefined>;
15
17
  workflows: Map<string, OpenWorkflowRunnable>;
@@ -115,6 +115,11 @@ interface OperationContext {
115
115
  surface: "console" | "cli" | "mcp" | "agent";
116
116
  /** Set by the host from generated build identity, never from request input or runtime NODE_ENV. */
117
117
  development?: boolean;
118
+ /**
119
+ * The project root of a development server, for operations that read build files, such as `bundle.report`. Hosts set
120
+ * it only with `development`, so a deployed server never reads project files through it.
121
+ */
122
+ projectRoot?: string;
118
123
  env?: Record<string, unknown>;
119
124
  waitUntil?: (task: Promise<unknown>) => void;
120
125
  request?: Request;
@@ -1,6 +1,6 @@
1
- import { t as workflowErrorDiagnostics } from "./error-diagnostics-8YNJ37rP.js";
2
- import { a as resumeWorkflow, i as getWorkflowRun, o as startWorkflow, t as cancelWorkflow } from "./client-CU5rELC0.js";
3
1
  import { t as isRecord } from "./object-Da1zyPCR.js";
2
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics-0V2T3JFw.js";
3
+ import { a as resumeWorkflow, i as getWorkflowRun, o as startWorkflow, t as cancelWorkflow } from "./client-DkwOxEiT.js";
4
4
  import { t as getWorkflowDevRecorder } from "./dev-recorder-CTN5Fkao.js";
5
5
  import { n as redactInspectionValue, t as redactInspectionText } from "./inspect-B72iFyj-.js";
6
6
  import { t as toWorkflowRunError } from "./run-error-DBWqiJHH.js";
@@ -252,13 +252,15 @@ async function run(operation, input) {
252
252
  workflow
253
253
  }));
254
254
  }
255
- const started = await startWorkflow(workflow, payload);
255
+ const [error, started] = await startWorkflow(workflow, payload);
256
+ if (error) throw error;
256
257
  rememberRun(started.id, workflow);
257
258
  return { run: await toWorkflowRunView(started, workflow) };
258
259
  }
259
260
  if (operation === "resume") {
260
261
  const { payload, token } = input;
261
- const signal = await resumeWorkflow(token, payload);
262
+ const [error, signal] = await resumeWorkflow(token, payload);
263
+ if (error) throw error;
262
264
  return { signal: {
263
265
  id: signal.id,
264
266
  provider: signal.provider
@@ -267,7 +269,9 @@ async function run(operation, input) {
267
269
  const { runId, workflow: named } = input;
268
270
  const workflow = named ?? startedRuns.get(runId);
269
271
  if (!workflow) throw failure(workflowErrorDiagnostics.WORKFLOW_RUN_UNKNOWN({ runId }));
270
- return { run: await toWorkflowRunView(operation === "get" ? await getWorkflowRun(workflow, runId) : await cancelWorkflow(workflow, runId), workflow) };
272
+ const [error, found] = operation === "get" ? await getWorkflowRun(workflow, runId) : await cancelWorkflow(workflow, runId);
273
+ if (error) throw error;
274
+ return { run: await toWorkflowRunView(found, workflow) };
271
275
  }
272
276
  /** The run history of `vite dev`. Hosted providers keep their own history, which ViteHub does not list. */
273
277
  function devRecorder() {
@@ -1,5 +1,5 @@
1
- import { O as WorkflowRunStatus, h as WorkflowDriver } from "./types-CnKVDnEp.js";
2
- import { t as AnyOperation } from "./operation-definition-8gOe-ubD.js";
1
+ import { M as WorkflowRunStatus, h as WorkflowDriver } from "./types-Dsmwsdlv.js";
2
+ import { t as AnyOperation } from "./operation-definition-nmRu_O3V.js";
3
3
  //#region src/results.d.ts
4
4
  /** One Workflow run as the operations return it. The start payload is not included. */
5
5
  interface WorkflowRunView {
@@ -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-CQ4BUqRe.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-D_WJwjrS.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;
@@ -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 };
@@ -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-Dsmwsdlv.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 {
@@ -1,9 +1,11 @@
1
- import { t as workflowErrorDiagnostics } from "../error-diagnostics-8YNJ37rP.js";
1
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics-0V2T3JFw.js";
2
2
  import { n as createWorkflowError, r as isNonRetryableError } from "../errors-DCqRnZpN.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-D1-nq_VE.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
10
  /** The Cloudflare errors that a step already made. They pass the run boundary as they are, not wrapped again. */
9
11
  const cloudflareNonRetryableErrors = /* @__PURE__ */ new WeakSet();
@@ -17,7 +19,7 @@ function wrapCloudflareWorkflowStep(step, createNonRetryableError, env, runtimeE
17
19
  if (!step?.do) return step;
18
20
  return {
19
21
  async do(name, options, run) {
20
- return await step.do(name, options, async () => await runWithActiveCloudflareEnv(env, async () => await runWithWorkflowRuntimeEvent(runtimeEvent(), async () => {
22
+ return await step.do(name, resolveWorkflowStepOptions(name, options), async () => await runWithActiveCloudflareEnv(env, async () => await runWithWorkflowRuntimeEvent(runtimeEvent(), async () => {
21
23
  try {
22
24
  return await run();
23
25
  } catch (error) {
@@ -52,15 +54,25 @@ async function runCloudflareWorkflow({ config, createNonRetryableError, env, eve
52
54
  });
53
55
  await step.sleepUntil("vitehub-delay", new Date(startAt));
54
56
  }
57
+ const id = event?.instanceId || event?.id;
55
58
  try {
56
59
  return await runWithWorkflowRuntimeEvent(runtimeEvent, () => runSerializedWorkflowHandler({
57
- id: event?.instanceId || event?.id,
60
+ id,
58
61
  name,
59
62
  payload,
60
63
  provider: "cloudflare",
61
64
  step: providerStep
62
65
  }, definition));
63
66
  } catch (error) {
67
+ if (id && hasRunFailedListeners() && !definition.internalAgentWorkflow && !definition.internalAgentInvocationRecovery) try {
68
+ if (providerStep?.do) await providerStep.do("vitehub-notify-terminal-failure", { retries: { limit: 0 } }, async () => {
69
+ await emitWorkflowFailed(name, id, error, definition);
70
+ return null;
71
+ });
72
+ else await emitWorkflowFailed(name, id, error, definition);
73
+ } catch (notificationError) {
74
+ console.error("[vitehub] Could not checkpoint the Workflow failure notification.", notificationError);
75
+ }
64
76
  throw translateNonRetryableError(error, createNonRetryableError);
65
77
  }
66
78
  });
@@ -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-Dsmwsdlv.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-C3DvtjfJ.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-He0GTrYZ.js";
5
5
  import "./cloudflare-shared.js";
6
6
  //#region ../internal/src/runtime/cloudflare-hosted.ts
7
7
  function createWebRequestHandler(appHandler) {
@@ -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, H as WorkflowStepContext, K as WorkflowStepRetries, U as WorkflowStepFunction, W as WorkflowStepOptions, _ as WorkflowDuration, f as WorkflowDefinition } from "../types-Dsmwsdlv.js";
2
+ import { t as NonRetryableError } from "../errors-uhP8DZTi.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