@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.
- package/README.md +52 -35
- package/dist/{app-CmMq8l4t.js → app-He0GTrYZ.js} +1 -1
- package/dist/{client-CU5rELC0.js → client-DkwOxEiT.js} +88 -39
- package/dist/{cloudflare-BfFnNWB0.js → cloudflare-BHfClPvT.js} +1 -1
- package/dist/{config-DCvRDlxA.js → config-C3DvtjfJ.js} +1 -1
- package/dist/definition.d.ts +10 -11
- package/dist/definition.js +24 -22
- package/dist/{delay--ESDybVT.js → delay-D1-nq_VE.js} +6 -41
- package/dist/durability.d.ts +1 -1
- package/dist/{error-diagnostics-8YNJ37rP.js → error-diagnostics-0V2T3JFw.js} +45 -14
- package/dist/{error-diagnostics-DSkCJC_L.js → error-diagnostics-CQ4BUqRe.js} +5 -1
- package/dist/{errors-DVwFb6Fd.d.ts → errors-uhP8DZTi.d.ts} +12 -1
- package/dist/index.d.ts +30 -11
- package/dist/index.js +12 -5
- package/dist/{openworkflow-TEaNk0LV.d.ts → openworkflow-BhzxV_Y3.d.ts} +3 -1
- package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-nmRu_O3V.d.ts} +5 -0
- package/dist/{operations-B0L8kV5s.js → operations-D_WJwjrS.js} +9 -5
- package/dist/operations.d.ts +2 -2
- package/dist/operations.js +2 -2
- package/dist/{out-fRNaVslw.js → out-DxLKolA0.js} +1 -1
- package/dist/{rolldown-runtime-CMFfr-1z.js → rolldown-runtime-B4iAMlE-.js} +10 -1
- package/dist/run-failed-gVGo1BaF.js +18 -0
- package/dist/runtime/cloudflare-runner.d.ts +1 -1
- package/dist/runtime/cloudflare-runner.js +17 -5
- package/dist/runtime/cloudflare-vite.d.ts +1 -1
- package/dist/runtime/cloudflare-vite.js +2 -2
- package/dist/runtime/execute.d.ts +25 -4
- package/dist/runtime/execute.js +108 -15
- package/dist/runtime/openworkflow-worker.d.ts +2 -2
- package/dist/runtime/openworkflow-worker.js +1 -1
- package/dist/runtime/openworkflow.d.ts +1 -1
- package/dist/runtime/openworkflow.js +37 -11
- package/dist/runtime/state.d.ts +1 -1
- package/dist/runtime/state.js +2 -6
- package/dist/runtime/vercel-vite.d.ts +1 -1
- package/dist/runtime/vercel-vite.js +2 -2
- package/dist/{types-CnKVDnEp.d.ts → types-Dsmwsdlv.d.ts} +67 -26
- package/dist/{vercel-BZU_O6ay.js → vercel-DTvm61iY.js} +4 -4
- package/dist/vite.d.ts +17 -11
- package/dist/vite.js +1116 -529
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
# @vite-hub/workflow
|
|
2
2
|
|
|
3
3
|
<p>
|
|
4
|
-
<a href="https://vitehub.dev"><img alt="ViteHub" src="https://
|
|
5
|
-
<img alt="TypeScript" src="https://
|
|
6
|
-
<img alt="Vite" src="https://
|
|
7
|
-
<img alt="Workflow" src="https://
|
|
4
|
+
<a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/static/v1?label=ViteHub&message=vitehub.dev&color=blue"></a>
|
|
5
|
+
<img alt="TypeScript" src="https://img.shields.io/static/v1?label=TypeScript&message=ready&color=blue">
|
|
6
|
+
<img alt="Vite" src="https://img.shields.io/static/v1?label=Vite&message=discovery&color=blue">
|
|
7
|
+
<img alt="Workflow" src="https://img.shields.io/static/v1?label=Workflow&message=durable+steps&color=blue">
|
|
8
8
|
</p>
|
|
9
9
|
|
|
10
10
|
`@vite-hub/workflow` discovers named long-running work and exposes one provider-neutral API for starting and inspecting runs.
|
|
@@ -37,20 +37,22 @@ The former `workflow.database` option was never connected to Named Databases. It
|
|
|
37
37
|
// server/workflows/onboard-user.ts
|
|
38
38
|
import { defineWorkflow } from "@vite-hub/workflow";
|
|
39
39
|
|
|
40
|
-
export default defineWorkflow
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
40
|
+
export default defineWorkflow<{ email: string }>({
|
|
41
|
+
handler: async ({ payload, id, provider }) => {
|
|
42
|
+
const idempotencyKey = `onboard-user:${payload.email}`;
|
|
43
|
+
const user = await upsertUser(payload.email, { idempotencyKey });
|
|
44
|
+
await sendWelcomeEmail(user.email, { idempotencyKey: `${idempotencyKey}:welcome-email` });
|
|
44
45
|
|
|
45
|
-
|
|
46
|
+
return { id, provider };
|
|
47
|
+
},
|
|
46
48
|
});
|
|
47
49
|
```
|
|
48
50
|
|
|
49
51
|
Both external operations receive keys derived from stable input. Preserve that idempotency when adding side effects so retrying a completed operation does not duplicate it.
|
|
50
52
|
|
|
51
|
-
ViteHub discovers `server/workflows/<name>.ts`, folder workflows such as `server/workflows/onboard-user/index.ts`, and `src/<name>.workflow.ts`. The file or folder
|
|
53
|
+
ViteHub discovers `server/workflows/<name>.ts`, folder workflows such as `server/workflows/onboard-user/index.ts`, and `src/<name>.workflow.ts`. The file or folder path is the Workflow name. `defineWorkflow()` takes one object and no name. Pass the name to the runtime helpers.
|
|
52
54
|
|
|
53
|
-
The handler gets
|
|
55
|
+
The handler gets one object with `payload`, `id`, `name`, `provider`, `sleep`, and `steps`. Pass the payload type as the type argument of `defineWorkflow()`. ViteHub writes the names and payload types to `.vitehub/workflow.d.ts`, so `startWorkflow("onboard-user", payload)` checks both.
|
|
54
56
|
|
|
55
57
|
## Call typed steps
|
|
56
58
|
|
|
@@ -60,9 +62,11 @@ A folder Workflow runs its numbered files as steps. `01.create-user.ts` becomes
|
|
|
60
62
|
// server/workflows/onboard-user/index.ts
|
|
61
63
|
import { defineWorkflow } from "@vite-hub/workflow";
|
|
62
64
|
|
|
63
|
-
export default defineWorkflow
|
|
64
|
-
|
|
65
|
-
|
|
65
|
+
export default defineWorkflow<{ email: string }>({
|
|
66
|
+
handler: async ({ payload, steps }) => {
|
|
67
|
+
const user = await steps.createUser(payload);
|
|
68
|
+
return await steps.sendWelcome(user);
|
|
69
|
+
},
|
|
66
70
|
});
|
|
67
71
|
```
|
|
68
72
|
|
|
@@ -80,7 +84,7 @@ export default async function sendWelcome(user: { id: string, email: string }) {
|
|
|
80
84
|
}
|
|
81
85
|
```
|
|
82
86
|
|
|
83
|
-
The Vite Integration writes `.vitehub/workflow.d.ts`.
|
|
87
|
+
The Vite Integration writes `.vitehub/workflow.d.ts`. A step name shared by multiple folders accepts only inputs that all those steps accept and can return any of their result types. A call to a step that has no file is a type error. At runtime, only the current folder's steps are available. Include `.vitehub/workflow.d.ts` in your TypeScript project; `vite-hub` includes it through `.vitehub/types.d.ts`.
|
|
84
88
|
|
|
85
89
|
## Configure the driver
|
|
86
90
|
|
|
@@ -176,15 +180,18 @@ installWorkflowRuntime();
|
|
|
176
180
|
|
|
177
181
|
export default defineEventHandler(async (event) => {
|
|
178
182
|
const payload = await readBody<{ email: string }>(event);
|
|
179
|
-
const started = await startWorkflow("onboard-user", payload);
|
|
183
|
+
const [startError, started] = await startWorkflow("onboard-user", payload);
|
|
184
|
+
if (startError) throw startError;
|
|
180
185
|
|
|
181
|
-
|
|
186
|
+
const [error, run] = await getWorkflowRun("onboard-user", started.id);
|
|
187
|
+
if (error) throw error;
|
|
188
|
+
return run;
|
|
182
189
|
});
|
|
183
190
|
```
|
|
184
191
|
|
|
185
|
-
`startWorkflow()` returns a normalized acknowledgement with an id, provider, and status. When you pass `{ id }`, that id is the run id on Cloudflare, OpenWorkflow, and inline runs, and a second start with the same id returns the first run. `getWorkflowRun()` returns normalized run and step state, including timestamps, attempts, and results when the provider supplies them. A failed run has `error`: `{ message, name?, code? }`, safe to send as JSON, on every provider. `metadata` keeps provider data and no longer holds the error. Every provider reports the same statuses: a sleeping or waiting run reports `running`, a Cloudflare `terminated` run reports `cancelled`, and a run id that does not exist reports `unknown`.
|
|
192
|
+
`startWorkflow()` returns `[error, run]`: a normalized acknowledgement with an id, provider, and status. `getWorkflowRun()`, `cancelWorkflow()`, `resumeWorkflow()`, and the `start`, `getRun`, and `cancel` methods of a handle also return `[error, data]`. A provider failure, an unsupported option, or an invalid `delay` is `error`; its `code` is a `WorkflowResultErrorCode`. A config error, such as an unknown Workflow name, throws. When you pass `{ id }`, that id is the run id on Cloudflare, OpenWorkflow, and inline runs, and a second start with the same id returns the first run. `getWorkflowRun()` returns normalized run and step state, including timestamps, attempts, and results when the provider supplies them. A failed run has `error`: `{ message, name?, code? }`, safe to send as JSON, on every provider. `metadata` keeps provider data and no longer holds the error. Every provider reports the same statuses: a sleeping or waiting run reports `running`, a Cloudflare `terminated` run reports `cancelled`, and a run id that does not exist reports `unknown`.
|
|
186
193
|
|
|
187
|
-
To set your own id, pass `{ id }`. On Cloudflare, start with a letter, a digit, or `_`, then use only letters, digits, `-`, and `_`, up to 100 characters.
|
|
194
|
+
To set your own id, pass `{ id }`. On Cloudflare, start with a letter, a digit, or `_`, then use only letters, digits, `-`, and `_`, up to 100 characters. `startWorkflow()` returns the error `WORKFLOW_CLOUDFLARE_RUN_ID_INVALID` for another id. Inspection queries the binding because existing instance ids can follow different rules.
|
|
188
195
|
|
|
189
196
|
The other runtime helpers are:
|
|
190
197
|
|
|
@@ -205,10 +212,10 @@ Inline run inspection uses weak references while execution is active. A reachabl
|
|
|
205
212
|
|
|
206
213
|
## Start a run later
|
|
207
214
|
|
|
208
|
-
Pass `delay` to start the run later. It accepts
|
|
215
|
+
Pass `delay` to start the run later. It accepts a duration such as `"30m"` or `"3 days"`, or a `Date` that the run must not start before. A `Date` in the past starts the run now. `startWorkflow()` returns `RUNTIME_DURATION_INVALID` for an invalid duration, including a bare number, and `WORKFLOW_START_DELAY_INVALID` for an invalid or out-of-range start time. Use a `Date` for a month or a calendar time. `delay` works with `{ id }`.
|
|
209
216
|
|
|
210
217
|
```ts fragment
|
|
211
|
-
await startWorkflow("send-reminder", { email }, { delay: "3 days", id: `reminder-${userId}` });
|
|
218
|
+
const [error, run] = await startWorkflow("send-reminder", { email }, { delay: "3 days", id: `reminder-${userId}` });
|
|
212
219
|
```
|
|
213
220
|
|
|
214
221
|
| Provider | How the delay works | Status during the delay |
|
|
@@ -216,7 +223,7 @@ await startWorkflow("send-reminder", { email }, { delay: "3 days", id: `reminder
|
|
|
216
223
|
| OpenWorkflow | The run stays pending in storage until its start time (`availableAt`). | `queued` |
|
|
217
224
|
| Cloudflare | The run sleeps with `step.sleepUntil()` before the handler. A waiting instance does not count toward the concurrency limit. | `running` |
|
|
218
225
|
| Vercel `native` entry of a folder Workflow | The generated entry calls Workflow DevKit `sleep()` before the first step. | `running` |
|
|
219
|
-
| Vercel `native` entry that you wrote | Not supported. `startWorkflow()`
|
|
226
|
+
| Vercel `native` entry that you wrote | Not supported. `startWorkflow()` returns the error `WORKFLOW_OPERATION_UNSUPPORTED`. | |
|
|
220
227
|
| Inline runs (`vite dev`, normal Vercel handlers) | A timer in the process. It is not durable: a restart loses the run. | `queued` |
|
|
221
228
|
|
|
222
229
|
For a recurring run, call `startWorkflow()` from a [Schedule](https://vitehub.dev/docs/schedule) handler.
|
|
@@ -251,12 +258,13 @@ async function durableOnboard({ payload }: WorkflowProviderContext<OnboardPayloa
|
|
|
251
258
|
return { userId: user.id };
|
|
252
259
|
}
|
|
253
260
|
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
|
|
261
|
+
export default defineWorkflow<OnboardPayload>({
|
|
262
|
+
handler: async ({ payload }) => {
|
|
263
|
+
const user = await upsertUser(payload.email, { idempotencyKey: `onboard-user:${payload.email}` });
|
|
264
|
+
return { userId: user.id };
|
|
265
|
+
},
|
|
266
|
+
native: durableOnboard,
|
|
267
|
+
});
|
|
260
268
|
```
|
|
261
269
|
|
|
262
270
|
ViteHub transforms `native` when it generates Vercel output. Other providers keep using the normal handler. `vite dev` does not transform `native`, so the dev server runs the normal handler inline, also with the Vercel provider. Test the durable entry on a Vercel preview deployment. Vercel calls `native` with a `WorkflowProviderContext`, which has no `steps` runner. Put external side effects in idempotent `use step` functions because a durable step may be retried.
|
|
@@ -282,7 +290,14 @@ async function transcribe(recordingId: string) {
|
|
|
282
290
|
|
|
283
291
|
`code` and `message` remain available through `error.toJSON()`. Keep `details` JSON-safe and free of secrets; `toJSON()` omits `cause`, which remains available only on the in-memory error. ViteHub's built-in codes are typed as `WorkflowErrorCode` and use code-derived messages and code-specific details. A `ViteHubError` does not change the retry policy.
|
|
284
292
|
|
|
285
|
-
A step
|
|
293
|
+
A step gets 3 retries after the first attempt, 10 seconds apart and then twice as long each time. A step file can export its own policy and a time limit for each attempt:
|
|
294
|
+
|
|
295
|
+
```ts
|
|
296
|
+
export const retries = { limit: 5, delay: "30 seconds", backoff: "exponential" };
|
|
297
|
+
export const timeout = "2 minutes";
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
Cloudflare gets both in `step.do()`. OpenWorkflow gets `retries` as its `retryPolicy`, and a generated Vercel step gets `limit` as `maxRetries`. Vercel steps cannot set `delay` or `backoff`, so the build fails with `WORKFLOW_STEP_RETRY_DELAY_UNSUPPORTED`. Outside Cloudflare, ViteHub enforces `timeout` itself: it aborts the `signal` that the step function gets as its second argument and fails the attempt. Code that ignores the signal keeps running. An inline run does not retry. See [Retries and sleeps](https://vitehub.dev/docs/workflows/limits-and-errors#retries-and-sleeps).
|
|
286
301
|
|
|
287
302
|
Throw `NonRetryableError` when another attempt cannot succeed. The run fails at once on every provider. `getWorkflowRun()` reports the error `message` and `name` in `metadata` for inline and OpenWorkflow runs, Cloudflare keeps the error in its status record in `metadata`, and a Vercel `native` run reports the message on the failed step in `steps`.
|
|
288
303
|
|
|
@@ -298,11 +313,13 @@ Only a folder Workflow can sleep. Its `index.ts` calls `context.sleep()` between
|
|
|
298
313
|
|
|
299
314
|
```ts fragment
|
|
300
315
|
// server/workflows/remind-user/index.ts, next to 01.send-welcome.ts and 02.send-reminder.ts
|
|
301
|
-
export default defineWorkflow
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
316
|
+
export default defineWorkflow<{ email: string, remindAt: string }>({
|
|
317
|
+
handler: async ({ payload, sleep, steps }) => {
|
|
318
|
+
await steps.sendWelcome(payload);
|
|
319
|
+
await sleep("1 day");
|
|
320
|
+
await sleep(new Date(payload.remindAt));
|
|
321
|
+
await steps.sendReminder(payload);
|
|
322
|
+
},
|
|
306
323
|
});
|
|
307
324
|
```
|
|
308
325
|
|
|
@@ -334,7 +351,7 @@ A single-file Workflow runs as one root step, and a replay after a sleep would r
|
|
|
334
351
|
A typed Workflow handle requires a payload when its handler requires one. Both `start()` and `defer()` use this rule. A handle with an optional payload or `void` input can still start with no argument. To set start options for a no-input Workflow, pass `undefined` first.
|
|
335
352
|
|
|
336
353
|
```ts fragment
|
|
337
|
-
const welcome = createWorkflow("welcome", async (
|
|
354
|
+
const welcome = createWorkflow<{ email: string }>("welcome", async ({ payload }) => {
|
|
338
355
|
await sendWelcomeEmail(payload.email)
|
|
339
356
|
})
|
|
340
357
|
await welcome.start({ email: "ada@example.com" })
|
|
@@ -1,16 +1,17 @@
|
|
|
1
|
-
import { t as workflowErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { t as workflowErrorDiagnostics } from "./error-diagnostics-0V2T3JFw.js";
|
|
2
2
|
import { n as createWorkflowError } from "./errors-DCqRnZpN.js";
|
|
3
|
-
import { a as encodeNameHex, n as getCloudflareWorkflowBindingName } from "./cloudflare-
|
|
3
|
+
import { a as encodeNameHex, n as getCloudflareWorkflowBindingName } from "./cloudflare-BHfClPvT.js";
|
|
4
4
|
import { a as getCloudflareEnv, n as resolveWaitUntil } from "./cloudflare-env-CGLx7lUd.js";
|
|
5
|
-
import { t as normalizeWorkflowOptions } from "./config-
|
|
6
|
-
import { i as toCloudflareStartParams, r as resolveWorkflowStartAt } from "./delay
|
|
5
|
+
import { t as normalizeWorkflowOptions } from "./config-C3DvtjfJ.js";
|
|
6
|
+
import { i as toCloudflareStartParams, r as resolveWorkflowStartAt } from "./delay-D1-nq_VE.js";
|
|
7
7
|
import { t as getWorkflowDevRecorder } from "./dev-recorder-CTN5Fkao.js";
|
|
8
8
|
import { runSerializedWorkflowHandler } from "./runtime/execute.js";
|
|
9
9
|
import { a as safeWorkflowName, i as runWorkflowProviderOperation, t as toWorkflowRunError } from "./run-error-DBWqiJHH.js";
|
|
10
|
+
import { t as emitWorkflowFailed } from "./run-failed-gVGo1BaF.js";
|
|
10
11
|
import { cancelOpenWorkflowRun, getOpenWorkflowRun, runOpenWorkflow } from "./runtime/openworkflow.js";
|
|
11
12
|
import { getInlineWorkflowDefinitions, getWorkflowRunState, getWorkflowRuntimeConfig, getWorkflowRuntimeEvent, getWorkflowRuntimeRegistry, loadWorkflowDefinition, registerInlineWorkflowDefinition, runWithWorkflowRuntimeEvent, setWorkflowRun } from "./runtime/state.js";
|
|
12
|
-
import { a as startVercelWorkflow, n as inspectVercelWorkflowRun, r as resumeVercelWorkflowSignal, t as cancelVercelWorkflow } from "./vercel-
|
|
13
|
-
import { deserializeResponse, getViteHubErrorShape, isSerializedResponse } from "@vite-hub/runtime";
|
|
13
|
+
import { a as startVercelWorkflow, n as inspectVercelWorkflowRun, r as resumeVercelWorkflowSignal, t as cancelVercelWorkflow } from "./vercel-DTvm61iY.js";
|
|
14
|
+
import { deserializeResponse, getViteHubErrorShape, isRuntimeDiagnostic, isSerializedResponse, toResultError } from "@vite-hub/runtime";
|
|
14
15
|
import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
|
|
15
16
|
//#region ../internal/src/runtime/random.ts
|
|
16
17
|
function randomId(prefix) {
|
|
@@ -379,8 +380,10 @@ function inlineAdapter(config) {
|
|
|
379
380
|
}));
|
|
380
381
|
const runState = setWorkflowRun(name, id, run, payload, true);
|
|
381
382
|
runState.startAt = startAt;
|
|
382
|
-
const
|
|
383
|
-
|
|
383
|
+
const notify = runState.promise.then(async (outcome) => {
|
|
384
|
+
if (outcome.status === "failed") await emitWorkflowFailed(name, id, outcome.error, definition);
|
|
385
|
+
});
|
|
386
|
+
resolveWaitUntil(event)?.(notify);
|
|
384
387
|
return {
|
|
385
388
|
id,
|
|
386
389
|
metadata: config.driver === "vercel" ? {
|
|
@@ -400,12 +403,12 @@ function inlineAdapter(config) {
|
|
|
400
403
|
* dev server runs the normal handler inline, as for every other Workflow there.
|
|
401
404
|
*/
|
|
402
405
|
function runsNatively(definition) {
|
|
403
|
-
return Boolean(definition?.
|
|
406
|
+
return Boolean(definition?.native) && !getWorkflowDevRecorder();
|
|
404
407
|
}
|
|
405
408
|
/** Whether a registered Workflow has a native Vercel entry, so a run of it can wait for a signal. */
|
|
406
409
|
async function hasNativeWorkflowDefinition() {
|
|
407
410
|
const names = /* @__PURE__ */ new Set([...Object.keys(getWorkflowRuntimeRegistry() ?? {}), ...getInlineWorkflowDefinitions().keys()]);
|
|
408
|
-
for (const name of names) if ((await loadWorkflowDefinition(name))?.
|
|
411
|
+
for (const name of names) if ((await loadWorkflowDefinition(name))?.native) return true;
|
|
409
412
|
return false;
|
|
410
413
|
}
|
|
411
414
|
function createVercelAdapter(config) {
|
|
@@ -491,6 +494,47 @@ function getWorkflowTestRun(test, provider, name, id, cancel = false) {
|
|
|
491
494
|
}
|
|
492
495
|
//#endregion
|
|
493
496
|
//#region src/runtime/client.ts
|
|
497
|
+
const resultErrorCodes = /* @__PURE__ */ new Set([
|
|
498
|
+
"RUNTIME_DURATION_INVALID",
|
|
499
|
+
"WORKFLOW_CLOUDFLARE_RUN_ID_INVALID",
|
|
500
|
+
"WORKFLOW_OPERATION_UNSUPPORTED",
|
|
501
|
+
"WORKFLOW_PROVIDER_OPERATION_FAILED",
|
|
502
|
+
"WORKFLOW_R0014",
|
|
503
|
+
"WORKFLOW_RUN_ID_UNSUPPORTED",
|
|
504
|
+
"WORKFLOW_START_DELAY_INVALID"
|
|
505
|
+
]);
|
|
506
|
+
function resultError(diagnostic) {
|
|
507
|
+
return toResultError(diagnostic);
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Returns a runtime failure of a Workflow call as a catalog error. The providers throw `ViteHubError` inside the
|
|
511
|
+
* package. The catalog error keeps its `details` in `data` and the provider error in `cause`. Config errors throw.
|
|
512
|
+
*/
|
|
513
|
+
function toWorkflowResultError(error) {
|
|
514
|
+
if (isRuntimeDiagnostic(error) && resultErrorCodes.has(error.code)) return resultError(error);
|
|
515
|
+
const shape = getViteHubErrorShape(error);
|
|
516
|
+
if (!shape || !resultErrorCodes.has(shape.code)) throw error;
|
|
517
|
+
const cause = error instanceof Error ? error.cause : void 0;
|
|
518
|
+
const details = shape.details ?? {};
|
|
519
|
+
if (shape.code === "WORKFLOW_PROVIDER_OPERATION_FAILED") return resultError(workflowErrorDiagnostics.WORKFLOW_PROVIDER_OPERATION_FAILED({
|
|
520
|
+
...details,
|
|
521
|
+
cause
|
|
522
|
+
}));
|
|
523
|
+
if (shape.code === "WORKFLOW_RUN_ID_UNSUPPORTED") return resultError(workflowErrorDiagnostics.WORKFLOW_RUN_ID_UNSUPPORTED({ cause }));
|
|
524
|
+
return resultError(workflowErrorDiagnostics.WORKFLOW_OPERATION_UNSUPPORTED({
|
|
525
|
+
cause,
|
|
526
|
+
operation: details.operation,
|
|
527
|
+
provider: details.provider
|
|
528
|
+
}));
|
|
529
|
+
}
|
|
530
|
+
/** Runs one Workflow call and returns its runtime failure as `[error, undefined]`. */
|
|
531
|
+
async function toWorkflowResult(run) {
|
|
532
|
+
try {
|
|
533
|
+
return [void 0, await run()];
|
|
534
|
+
} catch (error) {
|
|
535
|
+
return [toWorkflowResultError(error), void 0];
|
|
536
|
+
}
|
|
537
|
+
}
|
|
494
538
|
function getActiveWorkflowConfig() {
|
|
495
539
|
const config = getWorkflowRuntimeConfig();
|
|
496
540
|
if (config === false) throw createWorkflowError({ code: "WORKFLOW_DISABLED" });
|
|
@@ -551,7 +595,7 @@ function createWorkflow(nameOrOptions, handlerOrOptions, options) {
|
|
|
551
595
|
if (handler !== void 0) registerInlineWorkflowDefinition(name, {
|
|
552
596
|
handler,
|
|
553
597
|
...createOptions?.internalAgentWorkflow ? { internalAgentWorkflow: true } : {},
|
|
554
|
-
...createOptions?.rootStep === void 0 ? {} : {
|
|
598
|
+
...createOptions?.rootStep === void 0 ? {} : { rootStep: createOptions.rootStep }
|
|
555
599
|
});
|
|
556
600
|
return {
|
|
557
601
|
cancel: (id) => cancelWorkflow(name, id),
|
|
@@ -559,20 +603,20 @@ function createWorkflow(nameOrOptions, handlerOrOptions, options) {
|
|
|
559
603
|
defer: (payload, options = {}) => deferWorkflowStart(name, async () => await startWorkflowRun(name, payload, await resolveWorkflowStartOptions(name, payload, createOptions, options), true)),
|
|
560
604
|
getRun: (id) => getWorkflowRun(name, id),
|
|
561
605
|
async start(payload, options = {}) {
|
|
562
|
-
|
|
606
|
+
const startOptions = await resolveWorkflowStartOptions(name, payload, createOptions, options);
|
|
607
|
+
return await toWorkflowResult(() => startWorkflowRun(name, payload, startOptions));
|
|
563
608
|
}
|
|
564
609
|
};
|
|
565
610
|
}
|
|
566
|
-
/** Starts one durable run of a Workflow Definition and returns its id and status. */
|
|
567
611
|
async function startWorkflow(name, payload, options = {}) {
|
|
568
|
-
return await startWorkflowRun(name, payload, options);
|
|
612
|
+
return await toWorkflowResult(() => startWorkflowRun(name, payload, options));
|
|
569
613
|
}
|
|
570
614
|
async function startWorkflowRun(name, payload, options, deferred = false) {
|
|
571
615
|
const config = getActiveWorkflowConfig();
|
|
572
616
|
const id = options.id || randomId("wrun");
|
|
573
617
|
const startAt = resolveWorkflowStartAt(options.delay);
|
|
574
618
|
const definition = await loadRequiredWorkflowDefinition(name);
|
|
575
|
-
if (config.driver === "vercel" && definition.
|
|
619
|
+
if (config.driver === "vercel" && definition.native && options.id) throw createWorkflowError({
|
|
576
620
|
code: "WORKFLOW_RUN_ID_UNSUPPORTED",
|
|
577
621
|
details: {
|
|
578
622
|
...safeWorkflowName(name) ? { name } : {},
|
|
@@ -596,48 +640,53 @@ async function startWorkflowRun(name, payload, options, deferred = false) {
|
|
|
596
640
|
startAt
|
|
597
641
|
});
|
|
598
642
|
}
|
|
643
|
+
/**
|
|
644
|
+
* Reads one run and returns `[error, run]`. A provider failure is `error`. A run that the provider does not know has
|
|
645
|
+
* `status: "unknown"`. Config errors throw.
|
|
646
|
+
*/
|
|
599
647
|
async function getWorkflowRun(name, id) {
|
|
600
648
|
const config = getActiveWorkflowConfig();
|
|
601
649
|
const test = getViteHubTestMode();
|
|
602
|
-
if (test) return getWorkflowTestRun(test, config.driver, name, id);
|
|
603
|
-
return await getWorkflowRuntimeAdapter(config).get({
|
|
650
|
+
if (test) return [void 0, getWorkflowTestRun(test, config.driver, name, id)];
|
|
651
|
+
return await toWorkflowResult(() => getWorkflowRuntimeAdapter(config).get({
|
|
604
652
|
event: getWorkflowRuntimeEvent(),
|
|
605
653
|
id,
|
|
606
654
|
name
|
|
607
|
-
});
|
|
655
|
+
}));
|
|
608
656
|
}
|
|
657
|
+
/**
|
|
658
|
+
* Cancels one run and returns `[error, run]`. A provider failure, or a provider that cannot cancel the run, is
|
|
659
|
+
* `error`. Config errors, for example an unknown Workflow name, throw.
|
|
660
|
+
*/
|
|
609
661
|
async function cancelWorkflow(name, id) {
|
|
610
662
|
const config = getActiveWorkflowConfig();
|
|
611
663
|
const definition = await loadRequiredWorkflowDefinition(name);
|
|
612
664
|
const test = getViteHubTestMode();
|
|
613
665
|
if (test) {
|
|
614
|
-
if (config.driver === "vercel" && !definition.
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
}
|
|
620
|
-
});
|
|
621
|
-
return getWorkflowTestRun(test, config.driver, name, id, true);
|
|
666
|
+
if (config.driver === "vercel" && !definition.native) return [resultError(workflowErrorDiagnostics.WORKFLOW_OPERATION_UNSUPPORTED({
|
|
667
|
+
operation: "cancellation",
|
|
668
|
+
provider: config.driver
|
|
669
|
+
})), void 0];
|
|
670
|
+
return [void 0, getWorkflowTestRun(test, config.driver, name, id, true)];
|
|
622
671
|
}
|
|
623
|
-
return await getWorkflowRuntimeAdapter(config).cancel({
|
|
672
|
+
return await toWorkflowResult(() => getWorkflowRuntimeAdapter(config).cancel({
|
|
624
673
|
event: getWorkflowRuntimeEvent(),
|
|
625
674
|
id,
|
|
626
675
|
name
|
|
627
|
-
});
|
|
676
|
+
}));
|
|
628
677
|
}
|
|
629
|
-
/**
|
|
678
|
+
/**
|
|
679
|
+
* Resumes a run that waits for a signal and returns `[error, signal]`. `token` is the opaque token that the provider
|
|
680
|
+
* gave the waiting step. An empty token or a provider failure is `error`. Config errors throw.
|
|
681
|
+
*/
|
|
630
682
|
async function resumeWorkflow(token, payload) {
|
|
631
|
-
if (!token || typeof token !== "string")
|
|
683
|
+
if (!token || typeof token !== "string") return [resultError(workflowErrorDiagnostics.WORKFLOW_R0014({ message: "`resumeWorkflow()` requires an opaque signal token." })), void 0];
|
|
632
684
|
const config = getActiveWorkflowConfig();
|
|
633
|
-
if (getViteHubTestMode())
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
}
|
|
639
|
-
});
|
|
640
|
-
return await getWorkflowRuntimeAdapter(config).resume(token, payload);
|
|
685
|
+
if (getViteHubTestMode()) return [resultError(workflowErrorDiagnostics.WORKFLOW_OPERATION_UNSUPPORTED({
|
|
686
|
+
operation: "signals",
|
|
687
|
+
provider: config.driver
|
|
688
|
+
})), void 0];
|
|
689
|
+
return await toWorkflowResult(() => getWorkflowRuntimeAdapter(config).resume(token, payload));
|
|
641
690
|
}
|
|
642
691
|
function deferWorkflowStart(name, start) {
|
|
643
692
|
const request = getWorkflowRuntimeEvent();
|
|
@@ -651,7 +700,7 @@ function deferWorkflowStart(name, start) {
|
|
|
651
700
|
* Starts a run after the response, through `waitUntil`. It returns nothing: a failure goes to the log.
|
|
652
701
|
* Call `startWorkflow()` when the caller needs the run ID or the start error.
|
|
653
702
|
*/
|
|
654
|
-
function deferWorkflow(name, payload, options = {}) {
|
|
703
|
+
function deferWorkflow(...[name, payload, options = {}]) {
|
|
655
704
|
deferWorkflowStart(name, () => startWorkflowRun(name, payload, options, true));
|
|
656
705
|
}
|
|
657
706
|
//#endregion
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as workflowErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { t as workflowErrorDiagnostics } from "./error-diagnostics-0V2T3JFw.js";
|
|
2
2
|
//#region ../internal/src/integrations/hex.ts
|
|
3
3
|
const textEncoder = new TextEncoder();
|
|
4
4
|
new TextDecoder();
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as workflowErrorDiagnostics } from "./error-diagnostics-8YNJ37rP.js";
|
|
2
1
|
import { t as isRecord } from "./object-Da1zyPCR.js";
|
|
2
|
+
import { t as workflowErrorDiagnostics } from "./error-diagnostics-0V2T3JFw.js";
|
|
3
3
|
import { defu } from "defu";
|
|
4
4
|
/** Maps a host name or a Nitro preset name, such as `cloudflare-module` or `node-server`, to its ViteHub host. */
|
|
5
5
|
function hostFromNitroPreset(value) {
|
package/dist/definition.d.ts
CHANGED
|
@@ -1,19 +1,18 @@
|
|
|
1
|
-
import { f as WorkflowDefinition
|
|
1
|
+
import { f as WorkflowDefinition } from "./types-Dsmwsdlv.js";
|
|
2
2
|
//#region src/definition.d.ts
|
|
3
3
|
/**
|
|
4
|
-
* Defines
|
|
5
|
-
*
|
|
4
|
+
* Defines a Workflow from one object: `defineWorkflow({ handler, ...options })`. The file path is the Workflow name.
|
|
5
|
+
* The handler receives one object, `{ payload, steps, sleep, ...context }`. Pass the payload type as the type argument.
|
|
6
|
+
* It types `startWorkflow()` for this Workflow.
|
|
6
7
|
*
|
|
7
8
|
* ```ts
|
|
8
|
-
* export default defineWorkflow
|
|
9
|
-
*
|
|
10
|
-
*
|
|
9
|
+
* export default defineWorkflow<{ email: string }>({
|
|
10
|
+
* handler: async ({ payload, steps }) => {
|
|
11
|
+
* const user = await steps.createUser(payload)
|
|
12
|
+
* return await steps.sendWelcome(user)
|
|
13
|
+
* },
|
|
11
14
|
* })
|
|
12
15
|
* ```
|
|
13
16
|
*/
|
|
14
|
-
export declare function defineWorkflow<
|
|
15
|
-
/** Throws when a definition names another Workflow than the one ViteHub discovered at its path. */
|
|
16
|
-
export declare function assertWorkflowDefinitionName(discoveredName: string, definition: {
|
|
17
|
-
name?: string;
|
|
18
|
-
} | undefined): void;
|
|
17
|
+
export declare function defineWorkflow<TPayload = undefined, TResult = unknown>(definition: WorkflowDefinition<TPayload, TResult>, ...removed: unknown[]): WorkflowDefinition<TPayload, TResult>;
|
|
19
18
|
//#endregion
|
package/dist/definition.js
CHANGED
|
@@ -1,31 +1,33 @@
|
|
|
1
|
-
import { t as
|
|
1
|
+
import { t as isRecord } from "./object-Da1zyPCR.js";
|
|
2
|
+
import { t as workflowErrorDiagnostics } from "./error-diagnostics-0V2T3JFw.js";
|
|
2
3
|
//#region src/definition.ts
|
|
4
|
+
const workflowDefinitionKeys = /* @__PURE__ */ new Set([
|
|
5
|
+
"handler",
|
|
6
|
+
"native",
|
|
7
|
+
"rootStep"
|
|
8
|
+
]);
|
|
3
9
|
/**
|
|
4
|
-
* Defines
|
|
5
|
-
*
|
|
10
|
+
* Defines a Workflow from one object: `defineWorkflow({ handler, ...options })`. The file path is the Workflow name.
|
|
11
|
+
* The handler receives one object, `{ payload, steps, sleep, ...context }`. Pass the payload type as the type argument.
|
|
12
|
+
* It types `startWorkflow()` for this Workflow.
|
|
6
13
|
*
|
|
7
14
|
* ```ts
|
|
8
|
-
* export default defineWorkflow
|
|
9
|
-
*
|
|
10
|
-
*
|
|
15
|
+
* export default defineWorkflow<{ email: string }>({
|
|
16
|
+
* handler: async ({ payload, steps }) => {
|
|
17
|
+
* const user = await steps.createUser(payload)
|
|
18
|
+
* return await steps.sendWelcome(user)
|
|
19
|
+
* },
|
|
11
20
|
* })
|
|
12
21
|
* ```
|
|
13
22
|
*/
|
|
14
|
-
function defineWorkflow(
|
|
15
|
-
if (typeof
|
|
16
|
-
if (
|
|
17
|
-
|
|
18
|
-
if (
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
options
|
|
23
|
-
};
|
|
24
|
-
}
|
|
25
|
-
/** Throws when a definition names another Workflow than the one ViteHub discovered at its path. */
|
|
26
|
-
function assertWorkflowDefinitionName(discoveredName, definition) {
|
|
27
|
-
if (definition?.name === void 0 || definition.name === discoveredName) return;
|
|
28
|
-
throw workflowErrorDiagnostics.WORKFLOW_C0019({ message: `[vitehub] The Workflow at ${JSON.stringify(discoveredName)} calls \`defineWorkflow(${JSON.stringify(definition.name)})\`. Pass ${JSON.stringify(discoveredName)}, the name that ViteHub reads from its folder or file name.` });
|
|
23
|
+
function defineWorkflow(definition, ...removed) {
|
|
24
|
+
if (typeof definition === "string" || typeof definition === "function" || removed.length) throw workflowErrorDiagnostics.WORKFLOW_C0015({ message: "`defineWorkflow(name, handler, options)` was removed. The file path is the Workflow name. Pass one object: `defineWorkflow({ handler, ...options })`." });
|
|
25
|
+
if (!isRecord(definition)) throw workflowErrorDiagnostics.WORKFLOW_C0015({ message: "`defineWorkflow()` expects one object with `handler`." });
|
|
26
|
+
const unknownKey = Object.keys(definition).find((key) => !workflowDefinitionKeys.has(key));
|
|
27
|
+
if (unknownKey) throw workflowErrorDiagnostics.WORKFLOW_C0015({ message: `\`defineWorkflow()\` does not support the ${JSON.stringify(unknownKey)} option.` });
|
|
28
|
+
if (typeof definition.handler !== "function") throw workflowErrorDiagnostics.WORKFLOW_C0014({ message: "`defineWorkflow()` requires a workflow handler." });
|
|
29
|
+
if (definition.native !== void 0 && typeof definition.native !== "function") throw workflowErrorDiagnostics.WORKFLOW_C0016({ message: "`defineWorkflow()` native entry must be a workflow handler." });
|
|
30
|
+
return definition;
|
|
29
31
|
}
|
|
30
32
|
//#endregion
|
|
31
|
-
export {
|
|
33
|
+
export { defineWorkflow };
|
|
@@ -1,55 +1,20 @@
|
|
|
1
|
-
import { t as workflowErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { t as workflowErrorDiagnostics } from "./error-diagnostics-0V2T3JFw.js";
|
|
2
|
+
import { parseDuration } from "@vite-hub/runtime";
|
|
2
3
|
//#region src/runtime/delay.ts
|
|
3
|
-
const durationUnits = {
|
|
4
|
-
ms: 1,
|
|
5
|
-
millisecond: 1,
|
|
6
|
-
milliseconds: 1,
|
|
7
|
-
s: 1e3,
|
|
8
|
-
sec: 1e3,
|
|
9
|
-
secs: 1e3,
|
|
10
|
-
second: 1e3,
|
|
11
|
-
seconds: 1e3,
|
|
12
|
-
m: 6e4,
|
|
13
|
-
min: 6e4,
|
|
14
|
-
mins: 6e4,
|
|
15
|
-
minute: 6e4,
|
|
16
|
-
minutes: 6e4,
|
|
17
|
-
h: 36e5,
|
|
18
|
-
hr: 36e5,
|
|
19
|
-
hrs: 36e5,
|
|
20
|
-
hour: 36e5,
|
|
21
|
-
hours: 36e5,
|
|
22
|
-
d: 864e5,
|
|
23
|
-
day: 864e5,
|
|
24
|
-
days: 864e5,
|
|
25
|
-
w: 6048e5,
|
|
26
|
-
week: 6048e5,
|
|
27
|
-
weeks: 6048e5
|
|
28
|
-
};
|
|
29
4
|
/** The largest time that a JavaScript Date can hold. */
|
|
30
5
|
const maximumTime = 864e13;
|
|
31
6
|
function isDate(value) {
|
|
32
7
|
return Object.prototype.toString.call(value) === "[object Date]";
|
|
33
8
|
}
|
|
34
|
-
function parseDelayMilliseconds(delay) {
|
|
35
|
-
if (typeof delay === "number") return Number.isFinite(delay) && delay >= 0 ? delay : void 0;
|
|
36
|
-
const match = /^(\d+(?:\.\d+)?)\s*([a-z]+)$/i.exec(delay.trim());
|
|
37
|
-
const unit = match && durationUnits[match[2].toLowerCase()];
|
|
38
|
-
return unit ? Number(match[1]) * unit : void 0;
|
|
39
|
-
}
|
|
40
9
|
/**
|
|
41
10
|
* The time in milliseconds when a delayed run starts, or `undefined` when the run starts now. A `Date` in the past
|
|
42
|
-
* starts now. A
|
|
11
|
+
* starts now. A duration that is not valid, such as a number, throws `RUNTIME_DURATION_INVALID`. An invalid `Date`, or
|
|
12
|
+
* a time that a `Date` cannot hold, throws `WORKFLOW_START_DELAY_INVALID`.
|
|
43
13
|
*/
|
|
44
14
|
function resolveWorkflowStartAt(delay, now = Date.now()) {
|
|
45
15
|
if (delay === void 0) return void 0;
|
|
46
|
-
|
|
47
|
-
if (isDate(delay)
|
|
48
|
-
else if (typeof delay === "number" || typeof delay === "string") {
|
|
49
|
-
const milliseconds = parseDelayMilliseconds(delay);
|
|
50
|
-
startAt = milliseconds === void 0 ? void 0 : now + milliseconds;
|
|
51
|
-
}
|
|
52
|
-
if (startAt === void 0 || !Number.isFinite(startAt) || startAt > maximumTime) throw workflowErrorDiagnostics.WORKFLOW_START_DELAY_INVALID({ delay: isDate(delay) ? "Invalid Date" : String(delay) });
|
|
16
|
+
const startAt = isDate(delay) ? Date.prototype.getTime.call(delay) : now + parseDuration(delay, "delay");
|
|
17
|
+
if (!Number.isFinite(startAt) || startAt > maximumTime) throw workflowErrorDiagnostics.WORKFLOW_START_DELAY_INVALID({ delay: isDate(delay) ? "Invalid Date" : String(delay) });
|
|
53
18
|
return startAt > now ? startAt : void 0;
|
|
54
19
|
}
|
|
55
20
|
/**
|
package/dist/durability.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { P as WorkflowRuntimeConfigValue } from "./types-Dsmwsdlv.js";
|
|
2
2
|
import { Durability, DurabilityContext } from "@vite-hub/runtime/durability";
|
|
3
3
|
//#region src/durability.d.ts
|
|
4
4
|
/** What the build passes to `workflowDurability()`. The storage values may name runtime environment variables. */
|