From bce853d2a95e093bb0e5884a4e021b051e999862 Mon Sep 17 00:00:00 2001 From: Isak Gustavsen Date: Wed, 25 Nov 2026 01:09:50 +0100 Subject: [PATCH 1/7] feat(void): add Cloudflare Workflows through a workflows/ convention Each default-exported defineWorkflow() or defineWorkflowEntrypoint() module in workflows/ becomes a Cloudflare Workflow with a WORKFLOW_ binding and Workflow class, started from routes with Definition.create(), createBatch() and get(). Params can be validated with a Standard Schema. Discovery follows queues/: subdirectories are joined with '-' and paths with a '_'-prefixed segment are ignored, so step helpers can live beside the workflows. Deploys to Cloudflare name each Workflow -, since Workflow names are account-scoped, and verify the emitted set before upload. Void platform deploys, framework mode and Node targets reject workflows/ for now. The generated Worker entry now imports convention modules through their namespace and fails startup with a named error when a module does not default-export a definition; this also covers durable-objects/. Closes #779 Co-Authored-By: Claude Opus 5.5 --- docs/.vitepress/config.ts | 2 + docs/guide/workflows.md | 162 ++++++++++++ docs/reference/api.md | 2 + docs/reference/api/workflows.md | 57 ++++ docs/reference/cli/setup.md | 4 +- docs/reference/resource-inference.md | 4 + docs/reference/structure.md | 5 + packages/void/AGENTS.md | 3 +- packages/void/package.json | 5 + packages/void/skills/void/SKILL.md | 1 + packages/void/src/application-analysis.ts | 4 + .../src/cli/deploy-artifact-validation.ts | 24 ++ .../void/src/cli/deploy-binding-snapshot.ts | 18 ++ .../void/src/cli/deploy-cloudflare-build.ts | 8 +- .../void/src/cli/deploy-cloudflare-migrate.ts | 2 + .../src/cli/deploy-cloudflare-preflight.ts | 10 + packages/void/src/cli/deploy.ts | 2 + packages/void/src/cli/info.ts | 11 +- packages/void/src/deploy.ts | 2 + packages/void/src/index.ts | 35 +++ packages/void/src/plugin-client-stubs.ts | 5 +- packages/void/src/plugin-cloudflare-config.ts | 12 +- packages/void/src/plugin-routing.ts | 9 + packages/void/src/plugin-worker-bindings.ts | 36 ++- packages/void/src/router/compile.ts | 86 ++++-- packages/void/src/runtime/workflows/index.ts | 246 ++++++++++++++++++ packages/void/src/shared/env.ts | 6 + .../void/src/shared/resource-definition.ts | 4 +- packages/void/src/workflows/config.ts | 55 ++++ packages/void/src/workflows/platform.ts | 10 + packages/void/src/workflows/scan.ts | 111 ++++++++ .../cloudflare-durable-build.test.ts | 106 +++++++- .../test/integration/workflow-runtime.test.ts | 222 ++++++++++++++++ packages/void/test/unit/compile.test.ts | 52 +++- packages/void/test/unit/info.test.ts | 31 +++ .../void/test/unit/plugin-inference.test.ts | 64 ++++- .../void/test/unit/workflow-runtime.test.ts | 151 +++++++++++ packages/void/test/unit/workflow-scan.test.ts | 165 ++++++++++++ packages/void/vite.config.ts | 1 + 39 files changed, 1700 insertions(+), 33 deletions(-) create mode 100644 docs/guide/workflows.md create mode 100644 docs/reference/api/workflows.md create mode 100644 packages/void/src/runtime/workflows/index.ts create mode 100644 packages/void/src/workflows/config.ts create mode 100644 packages/void/src/workflows/platform.ts create mode 100644 packages/void/src/workflows/scan.ts create mode 100644 packages/void/test/integration/workflow-runtime.test.ts create mode 100644 packages/void/test/unit/workflow-runtime.test.ts create mode 100644 packages/void/test/unit/workflow-scan.test.ts diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index af2f1a1aaf..c0be1394b0 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -126,6 +126,7 @@ const referenceItems: Array = [ { text: 'Authentication', link: '/reference/api/auth' }, { text: 'Fetch Client', link: '/reference/api/client' }, { text: 'Durable State and WebSockets', link: '/reference/api/durable' }, + { text: 'Workflows', link: '/reference/api/workflows' }, { text: 'Deployment artifacts', link: '/reference/api/deploy' }, { text: 'Database and Seeding', link: '/reference/api/database' }, { text: 'Resource Clients', link: '/reference/api/resources' }, @@ -385,6 +386,7 @@ export default extendConfig( { text: 'Sandboxes', link: '/guide/sandboxes' }, { text: 'Cron Jobs', link: '/guide/jobs' }, { text: 'Queues', link: '/guide/queues' }, + { text: 'Workflows', link: '/guide/workflows' }, { text: 'WebSockets', link: '/guide/websockets' }, { text: 'Server-Sent Events', link: '/guide/sse' }, { text: 'Live Event Streams', link: '/guide/live' }, diff --git a/docs/guide/workflows.md b/docs/guide/workflows.md new file mode 100644 index 0000000000..90cc4617f5 --- /dev/null +++ b/docs/guide/workflows.md @@ -0,0 +1,162 @@ +--- +description: 'Run durable multi-step jobs with Cloudflare Workflows: retried steps, sleeps, and typed params.' +outline: deep +--- + +# Workflows + +Use a Workflow for work that runs across several steps and must finish even if one fails, such as onboarding emails, imports, or payment follow-ups. Each step's result is saved, failed steps are retried, and a Workflow can sleep for minutes or days between steps. + +Create a module in `workflows/` with `defineWorkflow()`. Void creates the Cloudflare Workflow and its binding for you. Workflows run in local development and in direct Cloudflare deployments (`void deploy --platform cloudflare`). + +## Define a workflow + +```ts +// workflows/onboarding.ts +import { defineWorkflow } from 'void/workflows'; +import type { WorkflowEvent } from 'void/workflows'; + +export const Onboarding = defineWorkflow({ + async run(event: WorkflowEvent<{ userId: string }>, step) { + await step.do('send welcome email', async () => { + await sendWelcomeEmail(event.payload.userId); + }); + await step.sleep('wait a day', '1 day'); + await step.do('send tips', async () => { + await sendTips(event.payload.userId); + }); + }, +}); + +export default Onboarding; +``` + +Default-export the object returned by `defineWorkflow()`. Named-export it too so routes can import it. + +TypeScript and JavaScript files are supported. Subdirectories are scanned too, and files or directories starting with `_` are ignored, so keep shared step helpers in files such as `workflows/_email.ts`. + +`run` receives: + +- `event`, with the `payload` passed to `create()`, the `instanceId`, and a `timestamp` +- `step`, Cloudflare's [`WorkflowStep`](https://developers.cloudflare.com/workflows/build/workers-api/#workflowstep) with `step.do()`, `step.sleep()`, `step.sleepUntil()`, and `step.waitForEvent()` +- a context with the Worker `env` + +Imports such as `void/env`, `void/db`, and `void/kv` work inside steps. Keep side effects inside `step.do()` so a retry or a resumed instance doesn't repeat them. + +## Start an instance from a route + +```ts +// routes/api/signup.ts +import { defineHandler } from 'void'; +import { Onboarding } from '../../workflows/onboarding'; + +export const POST = defineHandler(async () => { + const instance = await Onboarding.create({ params: { userId: 'user_123' } }); + return { instanceId: instance.id }; +}); +``` + +`create()` accepts the same options as Cloudflare's [`Workflow.create()`](https://developers.cloudflare.com/workflows/build/workers-api/#create), such as `id` and `retention`. Its `params` are typed from your definition. Use `createBatch()` to start up to 100 instances at once. + +Check on an instance with `get()`: + +```ts +// routes/api/onboarding/[id].ts +import { defineHandler } from 'void'; +import { Onboarding } from '../../../workflows/onboarding'; + +export const GET = defineHandler(async (c) => { + const instance = await Onboarding.get(c.req.param('id')); + return instance.status(); +}); +``` + +The returned instance can also `pause()`, `resume()`, `restart()`, `terminate()`, and `sendEvent()`. + +## Validate params + +Pass a [Standard Schema](https://standardschema.dev) validator, such as Zod, Valibot, or ArkType, as `params`. `create()` and `createBatch()` validate the params before starting an instance, and `run` receives the parsed value: + +```ts +import * as v from 'valibot'; +// workflows/import.ts +import { defineWorkflow } from 'void/workflows'; + +export const Import = defineWorkflow({ + params: v.object({ fileKey: v.string(), notify: v.optional(v.boolean(), false) }), + async run(event, step) { + const rows = await step.do('parse', () => parseFile(event.payload.fileKey)); + if (event.payload.notify) { + await step.do('notify', () => notifyOwner(rows.length)); + } + }, +}); + +export default Import; +``` + +Invalid params throw a `WorkflowParamsError`. Its `issues` list each message and path. + +## Native Workflow classes + +Use `defineWorkflowEntrypoint()` to keep a class that extends Cloudflare's `WorkflowEntrypoint`. Void binds and exports the class without changing it, and reads the params type from its `run` method: + +```ts +// workflows/report.ts +import { WorkflowEntrypoint } from 'cloudflare:workers'; +import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers'; +import { defineWorkflowEntrypoint } from 'void/workflows'; + +class ReportWorkflow extends WorkflowEntrypoint { + async run(event: WorkflowEvent<{ month: string }>, step: WorkflowStep) { + return step.do('build report', () => buildReport(event.payload.month)); + } +} + +export const Report = defineWorkflowEntrypoint({ class: ReportWorkflow }); +export default Report; +``` + +`Report.create()`, `Report.createBatch()`, and `Report.get()` work as they do for `defineWorkflow()`. + +## Names and bindings + +Void derives the names from the file's path in `workflows/`, joining directories with `-` as it does for [queues](./queues.md#defining-queues). `workflows/send-welcome.ts` creates: + +- the `WORKFLOW_SEND_WELCOME` binding +- the exported `SendWelcomeWorkflow` class +- a Cloudflare Workflow named `-send-welcome`, since Workflow names must be unique within your Cloudflare account + +`workflows/order/notifications.ts` creates `WORKFLOW_ORDER_NOTIFICATIONS`, `OrderNotificationsWorkflow`, and `-order-notifications`. Each Workflow must have a unique name. + +Instances belong to the Workflow name. Renaming the file or the Worker starts a new, empty Workflow, and instances of the old one stop running. To move a file without changing its name, run `void info` first and add the name it suggests: + +```ts +export const Onboarding = defineWorkflow({ + name: 'onboarding', + async run(event, step) { + // ... + }, +}); +``` + +`name` must be a static string containing words that start with a letter. To choose the Cloudflare Workflow name yourself, add an entry for the generated binding and class in `void.config.ts`: + +```ts +// void.config.ts +import { defineConfig } from 'void/config'; + +export default defineConfig({ + cloudflare: { + workflows: [ + { name: 'onboarding', binding: 'WORKFLOW_ONBOARDING', class_name: 'OnboardingWorkflow' }, + ], + }, +}); +``` + +## Deployment support + +Workflows are available on the Workers Free plan, within [Cloudflare's Workflows limits](https://developers.cloudflare.com/workflows/reference/limits/). Deploy to your own Cloudflare account with `void deploy --platform cloudflare`. + +Void platforms do not support Workflows yet: `void deploy` to a Void platform stops with an error while `workflows/` contains modules. Workflows are also unavailable in meta-framework apps and on Node.js, Bun, and Deno. diff --git a/docs/reference/api.md b/docs/reference/api.md index 05a09b43da..258377b18c 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -24,6 +24,7 @@ Use this reference to find public imports, signatures, and return types. For set | [Authentication](./api/auth.md) | Sessions, users, and the auth client. | | [Fetch client](./api/client.md) | Typed requests and errors. | | [Durable State and WebSockets](./api/durable.md) | Persistent objects and typed connections. | +| [Workflows](./api/workflows.md) | Durable multi-step jobs. | | [Database and seeding](./api/database.md) | Queries, operators, and seed scripts. | | [KV, storage, AI, and logging](./api/resources.md) | Resource clients, cache revalidation, and logs. | | [Deployment artifacts](./api/deploy.md) | Package built apps for managed deployment. | @@ -45,6 +46,7 @@ Import Void's app-facing APIs from these paths: | `void/ws` | `defineRoom`, `defineWebSocket`, `connect`, WebSocket context, connection and action types | | `void/ws/server` | `getRoom`, `RoomHandle`, `RoomOptions`, `RoomPath`. Server-only: call room actions from routes, auth hooks, queues and cron jobs. | | `void/durable` | `defineDurableState`, `defineDurableObject`, typed state/RPC/context/migration types | +| `void/workflows` | `defineWorkflow`, `defineWorkflowEntrypoint`, `WorkflowParamsError`, Workflow event/step/API types. Server-only. | | `void/sse` | `eventStream`, `formatSse`, `formatSseText`, `getLastEventId`, `SseStreamClosedError`, SSE message and stream types | | `void/sse/client` | `connectEventStream`, browser `EventSource` wrapper types | | `void/live` | `defineLiveStream`, SSE topic fanout runtime types. Server-only. | diff --git a/docs/reference/api/workflows.md b/docs/reference/api/workflows.md new file mode 100644 index 0000000000..e45f14e55c --- /dev/null +++ b/docs/reference/api/workflows.md @@ -0,0 +1,57 @@ +--- +description: 'Durable multi-step Workflows from void/workflows.' +outline: deep +--- + +# Workflows + +Imported from `"void/workflows"`. See [Workflows](../../guide/workflows.md) for the file convention and deployment support. + +## `defineWorkflow(definition)` {#defineworkflow-definition} + +Defines a Cloudflare Workflow from a run function. The returned object must be the default export of a module under `workflows/`; named-export the same object to start instances elsewhere in the app. + +```ts +function defineWorkflow(definition: { + name?: string; + params?: StandardSchemaV1; + run( + event: Readonly>, + step: WorkflowStep, + context: { env: TEnv; ctx: ExecutionContext }, + ): Promise; +}): WorkflowApi, TParams>; +``` + +With `params`, `run` receives the schema's output type and `create()` accepts its input type. Without it, the params type comes from the `event` annotation. + +## `defineWorkflowEntrypoint(definition)` {#defineworkflowentrypoint-definition} + +Registers a class that extends Cloudflare's `WorkflowEntrypoint` without changing it. The params type is read from the class's `run(event)` annotation. + +```ts +function defineWorkflowEntrypoint(definition: { + name?: string; + class: TClass; +}): WorkflowApi; +``` + +## `WorkflowApi` {#workflowapi} + +| Member | Description | +| ------------------------------ | ----------------------------------------------------------------------------------------------------- | +| `class` | The Workflow class Void exports from the Worker. | +| `create(options?)` | Starts an instance. Options match Cloudflare's `create()`; `params` are typed and validated. | +| `createBatch(instances)` | Starts up to 100 instances and returns Cloudflare's `{ created, errors }` result. | +| `get(id)` | Returns a `WorkflowInstance` for `status()`, `pause()`, `resume()`, `terminate()`, and `sendEvent()`. | +| `create(binding, options?)`, … | Each method also accepts an explicit `Workflow` binding as its first argument. | + +`name` optionally fixes the resource identity instead of deriving it from the filename. Run `void info` and pin the displayed name before moving a deployed definition. + +## `WorkflowParamsError` {#workflowparamserror} + +Thrown by `create()` and `createBatch()` when params fail the definition's schema. `issues` is an array of `{ message, path? }`. + +## Types {#types} + +`WorkflowEvent`, `WorkflowStep`, `WorkflowContext`, `WorkflowCreateOptions`, `WorkflowApi`, and `WorkflowRun`. diff --git a/docs/reference/cli/setup.md b/docs/reference/cli/setup.md index cdaeba5a14..d9d815357b 100644 --- a/docs/reference/cli/setup.md +++ b/docs/reference/cli/setup.md @@ -12,9 +12,9 @@ void info void info --json ``` -Shows each Durable State and WebSocket definition's source file, inferred or explicit name, Worker class, and binding. WebSocket entries also include their route in JSON output. It runs locally without authentication, network requests, or file generation. +Shows each Durable State, WebSocket, and Workflow definition's source file, inferred or explicit name, Worker class, and binding. WebSocket entries also include their route in JSON output. It runs locally without authentication, network requests, or file generation. -Before moving a deployed definition, copy the suggested `name` into `defineDurableState()`, `defineRoom()`, or `defineWebSocket()`. Keep that name after moving the file to preserve the resource. See [Durable State](../../guide/durable-state.md#rename-a-file-while-keeping-its-state) and [WebSockets](../../guide/websockets.md#move-a-route-while-keeping-its-state) for migration flows, including WebSocket parameter renames. +Before moving a deployed definition, copy the suggested `name` into `defineDurableState()`, `defineRoom()`, `defineWebSocket()`, or `defineWorkflow()`. Keep that name after moving the file to preserve the resource. See [Durable State](../../guide/durable-state.md#rename-a-file-while-keeping-its-state) [WebSockets](../../guide/websockets.md#move-a-route-while-keeping-its-state), and [Workflows](../../guide/workflows.md#names-and-bindings) for migration flows, including WebSocket parameter renames. Resources recorded in `void.lock.json` without a matching definition appear separately. Adopt a suggested name only after identifying the resource you moved. If Void cannot suggest a name, restore its original source and inspect it before moving it again. diff --git a/docs/reference/resource-inference.md b/docs/reference/resource-inference.md index 0f0e3104b1..13407199dc 100644 --- a/docs/reference/resource-inference.md +++ b/docs/reference/resource-inference.md @@ -20,6 +20,7 @@ Void automatically detects which Cloudflare resources your project uses by scann | `QUEUE_*` | `Queue` | `import { queues } from "void/queues"` | `env.QUEUE_*` | | `VOID_LIVE` | `DurableObjectNamespace` | `import { defineLiveStream } from "void/live"` | n/a | | filename-derived | `DurableObjectNamespace` | A default-exported `defineDurableState()` module in `durable-objects/` | n/a | +| `WORKFLOW_*` | `Workflow` | A default-exported `defineWorkflow()` or `defineWorkflowEntrypoint()` module in `workflows/` | n/a | Auth detection also triggers when importing the `auth` specifier from `void/client` or a framework-specific client subpath such as `void/client/react` (but not when importing only `fetch`). @@ -29,6 +30,8 @@ use [explicit binding overrides](#explicit-binding-overrides). Durable state is inferred from files in `durable-objects/`. For example, `durable-objects/shopping-cart.ts` creates the `SHOPPING_CART` binding, exports `ShoppingCartDurableObject`, and records its migration. See [Durable State](../guide/durable-state.md). +Workflows are inferred from files in `workflows/`, including subdirectories; paths with a `_`-prefixed segment are ignored. For example, `workflows/send-welcome.ts` creates the `WORKFLOW_SEND_WELCOME` binding and exports `SendWelcomeWorkflow`. See [Workflows](../guide/workflows.md). + ## Scanned Directories ### Standard mode @@ -68,6 +71,7 @@ Regardless of mode, these are always checked: - **SSR entry** such as `src/main.ssr.ts`, for SSR apps that access bindings during rendering - **Application source** in `src/` or your configured `sourceDir`, including resource and auth imports - **`durable-objects/`**, which is scanned for typed Durable Object state modules in native Void apps +- **`workflows/`**, which is scanned for Workflow modules in native Void apps ## Custom Scan Directories diff --git a/docs/reference/structure.md b/docs/reference/structure.md index 954d5818be..59b9ecb7d4 100644 --- a/docs/reference/structure.md +++ b/docs/reference/structure.md @@ -13,6 +13,7 @@ const items = [ { name: "queues/", description: "Async queue consumers", link: "#queues" }, { name: "email/", description: "Inbound email handlers", link: "#email" }, { name: "durable-objects/", description: "Durable State modules", link: "#durable-objects" }, + { name: "workflows/", description: "Durable multi-step Workflows", link: "#workflows" }, { name: "src/", description: "Shared app code", link: "#src" }, { name: "public/", description: "Static assets (served as-is)", link: "#public" }, { name: ".void/", description: "Auto-generated (gitignored)", link: "#void" }, @@ -126,6 +127,10 @@ Generate schema with `void gen model` or write it by hand. Generate migrations w [Durable State](/guide/durable-state) modules. Each file default-exports a `defineDurableState()` definition. +## `workflows/` + +[Workflow](/guide/workflows) modules. Each file default-exports a `defineWorkflow()` or `defineWorkflowEntrypoint()` definition. + ## `src/` Shared application code such as components, utilities, and types. This directory has no special convention, so organize it however you like. diff --git a/packages/void/AGENTS.md b/packages/void/AGENTS.md index 2df952b689..7bd23dc518 100644 --- a/packages/void/AGENTS.md +++ b/packages/void/AGENTS.md @@ -146,7 +146,8 @@ generated entries must preserve the module-boundary rules below. - **Framework env schema**: `env` has no schema in a Worker whose own modules have not loaded `env.ts`, whatever the Vite plugin loaded in its process, so it returns raw values. The Class A wrapper (TanStack Start, React Router, vinext) imports `env.ts` ahead of the framework entry and awaits `_prepareEnv(env)` on every request, in dev and build. Unlike `_validateEnvOnce`, it never rejects: a read of a key that failed throws that key's error, async validators included, so requests that do not read it and a build-time prerender without production secrets still run. Both keep one result per key, reuse a validation for the same raw values, and keep the results with the env object they received. Reads through another object (the `cloudflare:workers` env that a D1 app's framework reads outside a request scope, the remote dev copy) get the latest validation's result while they hold the raw value it came from; never copy results to that object, which can come to hold other values. A validation in which a validator threw serves its reads but runs again on the next call. Results live on the process-global registry because `void deploy` bundles cron and queue jobs apart from the app, with a copy of `void/env` of their own: the jobs call `registry.prepare`, the `_prepareEnv` of the copy that registered the schema (key in `shared/env-registry.ts`). SvelteKit, Nuxt, Analog and Astro Workers do not load `env.ts` yet. - **Reserved `__VOID_*` names**: `envSchemaPlugin.config` (every mode, with or without `env.ts`) and `void env check` reject `__VOID_*` names in the root `.env` or declared in `env.ts`. Do not try to strip them from dev `vars` instead: Wrangler reads `.env` itself and writes it over `vars`, so a strip cannot be enforced. Manual trigger auth is a compile-time literal (`__VOID_SERVE` from `CompileOptions.dev`, false in builds and `vite preview`): dev accepts only `x-void-dev-trigger`, builds use the proxy token or build key. Never key it on `import.meta.env.DEV`, which is true in a `NODE_ENV=development` build. - **Typed Durable State convention**: each default-exported `defineDurableState()` definition in `durable-objects/*.ts` becomes a filename-derived binding and worker class (`shopping-cart.ts` → `SHOPPING_CART` / `ShoppingCartDurableObject`). The generated entry calls the internal `__bind()` hook so named imports can use `State.get(name)` without touching `c.env`, exports `State.class`, and emits a stable `new_sqlite_classes` migration. `syncWranglerDurableObjects()` persists bindings and append-only class migration history in `void.lock.json` through the generated Cloudflare config; never regenerate migration order solely from the current sorted files. The generated class extends `DurableObject` from `cloudflare:workers` so namespace stubs expose real RPC methods; runtime state and helpers use JavaScript private fields and methods. Runtime operations are serialized and persisted after successful typed RPC, `fetch`, or `alarm` handlers; versioned value migrations run on load. This is native-Void + Cloudflare only and is supported by direct Cloudflare deploys. Typed `*.ws.ts` routes likewise use SQLite-backed classes; their root-config sync uses the comment-preserving writer, retains legacy `new_classes` histories, and appends a new migration tag only for new classes. -- **Persistent resource names**: optional static `name` on Durable State and WebSocket definitions uses the same identity derivation as unnamed filenames/routes. Preserve unnamed defaults exactly. `void info` reports names and verified unmatched lock identities without executing source or writing files. Scanners use the shared AST reader; runtime validation imports only the Worker-safe `shared/resource-name.ts` leaf. Carry explicit names through generated metadata and `__bind()`; runtime mismatches fail instead of selecting an inferred replacement. WebSocket `key({ params })` is shared by namespace selection and hook `ctx.id`; absent keys keep the existing ordered `param=value` format. +- **Workflows convention**: each default-exported `defineWorkflow()` / `defineWorkflowEntrypoint()` under `workflows/` becomes `WORKFLOW_` / `Workflow` (`send-welcome.ts` → `WORKFLOW_SEND_WELCOME` / `SendWelcomeWorkflow`), bound through the same `__bind()` hook as Durable State. The binding prefix matches `QUEUE_*`. Discovery follows `queues/` rather than `durable-objects/`: subdirectories are joined with `-` (`order/notifications.ts` → `order-notifications`) and `_`-prefixed path segments are skipped. Workflows need no class migrations, so they are not written to `void.lock.json`; `mergeWorkerBindings()` emits only the additions (the Cloudflare plugin concatenates arrays) via `planWorkflowAdditions()`, naming each `-` because Workflow names are account-scoped. `void deploy --platform cloudflare` passes its Worker name to the build as `VOID_CLOUDFLARE_WORKER_NAME`, and `reconstructExpectedWorkflows()` pins the exact emitted set for `verifyGeneratedDeployConfig()`. An authored entry with the same binding and class keeps its name. Void platform deploys, framework mode and Node targets reject `workflows/` until platform provisioning exists. The generated entry imports convention modules through their namespace and fails Worker startup with a named error when the default export is not a definition; this guard also covers `durable-objects/`. +- **Persistent resource names**: optional static `name` on Durable State, WebSocket, and Workflow definitions uses the same identity derivation as unnamed filenames/routes. Preserve unnamed defaults exactly. `void info` reports names and verified unmatched lock identities without executing source or writing files. Scanners use the shared AST reader; runtime validation imports only the Worker-safe `shared/resource-name.ts` leaf. Carry explicit names through generated metadata and `__bind()`; runtime mismatches fail instead of selecting an inferred replacement. WebSocket `key({ params })` is shared by namespace selection and hook `ctx.id`; absent keys keep the existing ordered `param=value` format. - **Server room actions**: `defineRoom({ actions })` keeps each action's declared parameters and return type (`RoomActions` accepts any annotated parameter list, so unannotated parameters become `never`). Codegen adds `actions` to `WebSocketRouteMap` for room routes only, and `getRoom()` from `void/ws/server` resolves the same `bindingName` plus `buildWebSocketInstanceId()` key as `forwardWebSocketRequest()`. The generated route table registers route metadata once, after attaching `key`, through `__registerWebSocketRoutes`; the map lives on `globalThis` because dev can evaluate the module twice. Dispatch is Durable Object RPC (`__voidRoomAction`), so the WebSocket DO class extends `DurableObject` from `cloudflare:workers`; its own helpers are `#` methods so they stay off that RPC surface, and actions are never reachable from `fetch`, `webSocketMessage`, or client HTTP. - **Journal coherence invariant**: `db/migrations/*.sql` and `db/migrations/meta/_journal.json` must stay in sync — every `.sql` file has a matching journal entry (by `tag`) and vice versa. `assertJournalCoherence` in `src/migrations/validate.ts` is the gate, called from `deploy`, `db status`, `db migrate`, and `db reset`. The two CLI commands that mutate migration state — `void gen migration` and `void db rename-migrations` — are responsible for keeping the journal coherent themselves: when the journal has entries, the first delegates to `drizzle-kit generate --custom --name `, which writes the empty `.sql`, appends the journal entry, and writes a snapshot of the current schema (it refuses if the last entry's snapshot is missing and byte-restores the journal if drizzle-kit fails); with no journal entries it writes a plain timestamped `.sql`. The second rewrites `tag` values alongside the file renames and also renames the matching `meta/_snapshot.json` (with byte-level rollback on failure). Drift will fail loudly before touching any remote DB. This prevents an orphan scaffolded `.sql` file from half-applying against D1 and blocking later deploys. diff --git a/packages/void/package.json b/packages/void/package.json index ae781040ae..fbaddad40f 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -170,6 +170,11 @@ "import": "./dist/runtime/durable/index.mjs", "require": "./dist/runtime/durable/index.mjs" }, + "./workflows": { + "types": "./dist/runtime/workflows/index.d.mts", + "import": "./dist/runtime/workflows/index.mjs", + "require": "./dist/runtime/workflows/index.mjs" + }, "./seed": { "types": "./dist/runtime/db/seed.d.mts", "import": "./dist/runtime/db/seed.mjs", diff --git a/packages/void/skills/void/SKILL.md b/packages/void/skills/void/SKILL.md index f36ee0b6e0..25acb4eae7 100644 --- a/packages/void/skills/void/SKILL.md +++ b/packages/void/skills/void/SKILL.md @@ -51,6 +51,7 @@ Use `void deploy --skip-migrations` when database migrations run separately; it | AI inference (Workers AI, providers) | `docs/guide/ai.md` | | Platform AI logging policy | `docs/reference/cli/platform-users.md#ai-gateway-logging` | | Durable State and WebSockets | `docs/guide/durable-state.md`, `docs/guide/websockets.md` | +| Workflows | `docs/guide/workflows.md`, `docs/reference/api/workflows.md` | | Server-sent events and live streams | `docs/guide/sse.md`, `docs/guide/live.md` | | Sandboxes | `docs/guide/sandboxes.md` | | Email | `docs/guide/email.md`, then the matching guide under `docs/guide/email/` | diff --git a/packages/void/src/application-analysis.ts b/packages/void/src/application-analysis.ts index 7c21af1673..3dd814094e 100644 --- a/packages/void/src/application-analysis.ts +++ b/packages/void/src/application-analysis.ts @@ -15,6 +15,7 @@ import type { RouteEnvironment } from './router/parse-filename.ts'; import { scanMiddlewareSync, scanRoutePatternsSync } from './router/scan.ts'; import { scanWebSocketRoutesSync } from './router/websocket.ts'; import { isSandboxEnabled } from './sandbox/config.ts'; +import { scanWorkflowModules } from './workflows/scan.ts'; export type ApplicationReasons = { database: Array; @@ -40,6 +41,7 @@ export type ApplicationAnalysis = { websockets: ReturnType; allWebsockets: ReturnType; durableObjects: ReturnType; + workflows: ReturnType; email: ReturnType; routes: ReturnType; middleware: ReturnType; @@ -81,6 +83,7 @@ export function analyzeApplicationSync( ); // Typed durable modules currently use the root convention on every target. const durableObjects = scanDurableObjectModules(root); + const workflows = scanWorkflowModules(root); const email = scanEmailHandlersSync(paths.sourceRoot); const overrides = config.inference?.bindings; const bindingReason = ( @@ -127,6 +130,7 @@ export function analyzeApplicationSync( websockets, allWebsockets, durableObjects, + workflows, email, routes: scanRoutePatternsSync(root, paths, environment), middleware: scanMiddlewareSync(root, paths), diff --git a/packages/void/src/cli/deploy-artifact-validation.ts b/packages/void/src/cli/deploy-artifact-validation.ts index 8a05b1b0fb..69c45cf288 100644 --- a/packages/void/src/cli/deploy-artifact-validation.ts +++ b/packages/void/src/cli/deploy-artifact-validation.ts @@ -138,6 +138,8 @@ export function removeDeployPointer(root: string): void { const byName = (left: Record, right: Record) => String(left.name).localeCompare(String(right.name)); +const byBinding = (left: Record, right: Record) => + String(left.binding).localeCompare(String(right.binding)); /** * Check the generated deploy config before upload: the pinned account and Worker name, required @@ -168,6 +170,8 @@ export function verifyGeneratedDeployConfig( expectedContainers?: Array>; /** Exact pre-build Durable Object bindings, including Void's sandbox and live additions. */ expectedDurableObjectBindings?: Array>; + /** Exact pre-build Workflow entries, including Void's `workflows/` additions. */ + expectedWorkflows?: Array>; /** Exact pre-build migration sequence, including Void's sandbox and live additions. */ expectedMigrations?: Array>; /** Cron schedules the build should emit, derived from the source before the build. */ @@ -442,6 +446,26 @@ export function verifyGeneratedDeployConfig( }; } } + if (expected.expectedWorkflows) { + if (generated.workflows !== undefined && !Array.isArray(generated.workflows)) { + return { ok: false, reason: 'generated config workflows could not be verified.' }; + } + const emittedWorkflows = Array.isArray(generated.workflows) + ? (generated.workflows as Array>) + : []; + if ( + !deepEqual( + [...emittedWorkflows].sort(byBinding), + [...expected.expectedWorkflows].sort(byBinding), + ) + ) { + return { + ok: false, + reason: + 'generated config workflows differ from the pre-build Workflow set — refusing to deploy a Workflow the build added, removed, or retargeted.', + }; + } + } if (expected.expectedMigrations) { if (generated.migrations !== undefined && !Array.isArray(generated.migrations)) { return { ok: false, reason: 'generated config migrations could not be verified.' }; diff --git a/packages/void/src/cli/deploy-binding-snapshot.ts b/packages/void/src/cli/deploy-binding-snapshot.ts index f98147cc90..846d234cd3 100644 --- a/packages/void/src/cli/deploy-binding-snapshot.ts +++ b/packages/void/src/cli/deploy-binding-snapshot.ts @@ -20,6 +20,7 @@ import { SANDBOX_MIGRATION_TAG, hasSandboxSqliteMigration, } from '../sandbox/config.ts'; +import { planWorkflowAdditions, workflowConfigEntries } from '../workflows/config.ts'; import type { BindingIdentitySnapshot } from './deploy-types.ts'; import { resolveCloudflareOperationArgv } from './preset.ts'; import type { DesiredResourceSet, ProvisionDriftEntry } from './provision.ts'; @@ -125,6 +126,7 @@ export const DEPLOY_PASSTHROUGH_EXCLUDE_FIELDS: ReadonlySet = new Set, + workerName: string, + analysis?: ApplicationAnalysis, +): Array> { + const configured = workflowConfigEntries(rootConfig.workflows); + const modules = (analysis ?? analyzeApplicationSync(root, { config })).workflows; + return [...configured, ...planWorkflowAdditions(configured, modules, workerName)]; +} + export function reconstructExpectedDurableObjectState( config: VoidConfig, root: string, diff --git a/packages/void/src/cli/deploy-cloudflare-build.ts b/packages/void/src/cli/deploy-cloudflare-build.ts index dbfd0f040d..14decdbdf1 100644 --- a/packages/void/src/cli/deploy-cloudflare-build.ts +++ b/packages/void/src/cli/deploy-cloudflare-build.ts @@ -10,7 +10,11 @@ import type { VoidConfig } from '../config.ts'; import { collectMigrations } from '../migrations/collect.ts'; import { SqliteMigrationError } from '../migrations/sqlite-validation.ts'; import type { detectFramework } from '../plugin-inference.ts'; -import { CLOUDFLARE_DEPLOY_BUILD_ENV, CLOUDFLARE_QUEUE_NAMES_BUILD_ENV } from '../shared/env.ts'; +import { + CLOUDFLARE_DEPLOY_BUILD_ENV, + CLOUDFLARE_QUEUE_NAMES_BUILD_ENV, + CLOUDFLARE_WORKER_NAME_BUILD_ENV, +} from '../shared/env.ts'; import { CLOUDFLARE_PRESERVE_BINDINGS_BUILD_ENV } from '../shared/version-metadata.ts'; import { prepareCfBuildOutput, prepareCfFrameworkBuildOutput } from './cf-build-output.ts'; import { @@ -82,6 +86,8 @@ export async function buildCloudflareWorker(input: { // but local files cannot be serialized into the artifact this command uploads. deleteEnvVarCaseAware(buildChildEnv, CLOUDFLARE_DEPLOY_BUILD_ENV); buildChildEnv[CLOUDFLARE_DEPLOY_BUILD_ENV] = '1'; + deleteEnvVarCaseAware(buildChildEnv, CLOUDFLARE_WORKER_NAME_BUILD_ENV); + buildChildEnv[CLOUDFLARE_WORKER_NAME_BUILD_ENV] = workerName; deleteEnvVarCaseAware(buildChildEnv, CLOUDFLARE_QUEUE_NAMES_BUILD_ENV); if (desired.queueNames) { buildChildEnv[CLOUDFLARE_QUEUE_NAMES_BUILD_ENV] = JSON.stringify(desired.queueNames); diff --git a/packages/void/src/cli/deploy-cloudflare-migrate.ts b/packages/void/src/cli/deploy-cloudflare-migrate.ts index 9707dac368..f5fadef6c1 100644 --- a/packages/void/src/cli/deploy-cloudflare-migrate.ts +++ b/packages/void/src/cli/deploy-cloudflare-migrate.ts @@ -58,6 +58,7 @@ export async function migrateCloudflareWorker(input: { passthroughRawFields, expectedContainers, expectedDurableObjectState, + expectedWorkflows, runWrangler, assertUploaderStillPinned, schemaFacts, @@ -78,6 +79,7 @@ export async function migrateCloudflareWorker(input: { authEnabled, expectedContainers, expectedDurableObjectBindings: expectedDurableObjectState.bindings, + expectedWorkflows, expectedMigrations: expectedDurableObjectState.migrations, expectedCrons, }; diff --git a/packages/void/src/cli/deploy-cloudflare-preflight.ts b/packages/void/src/cli/deploy-cloudflare-preflight.ts index 1db27af462..2e719f616f 100644 --- a/packages/void/src/cli/deploy-cloudflare-preflight.ts +++ b/packages/void/src/cli/deploy-cloudflare-preflight.ts @@ -33,6 +33,7 @@ import { snapshotPassthroughRawFields, reconstructExpectedContainers, reconstructExpectedDurableObjectState, + reconstructExpectedWorkflows, } from './deploy-binding-snapshot.ts'; import { isWranglerNonInteractiveOrCI, @@ -225,6 +226,7 @@ export async function preflightCloudflareWorker(input: { passthroughRawFields: ReturnType; expectedContainers: ReturnType; expectedDurableObjectState: ReturnType; + expectedWorkflows: ReturnType; }> { const { root, @@ -691,6 +693,13 @@ export async function preflightCloudflareWorker(input: { preBuildRootConfig, { needsSandbox, needsLive, analysis: source.analysis }, ); + const expectedWorkflows = reconstructExpectedWorkflows( + voidConfig, + root, + preBuildRootConfig, + workerName, + source.analysis, + ); return { apiBaseUrl, complianceRegion, @@ -712,5 +721,6 @@ export async function preflightCloudflareWorker(input: { passthroughRawFields, expectedContainers, expectedDurableObjectState, + expectedWorkflows, }; } diff --git a/packages/void/src/cli/deploy.ts b/packages/void/src/cli/deploy.ts index 9e5109756c..483c022693 100644 --- a/packages/void/src/cli/deploy.ts +++ b/packages/void/src/cli/deploy.ts @@ -5,6 +5,7 @@ import { stashCloudflareDeployPointer } from '../cloudflare-config.ts'; import { readConfig } from '../config.ts'; import { detectFramework } from '../plugin-inference.ts'; import { buildEnv } from '../shared/untrusted-env.ts'; +import { assertNoWorkflowsForPlatform } from '../workflows/platform.ts'; import { getApiUrl, getToken, getTokenSource } from './auth.ts'; import { isExpiredTokenError, PlatformClient } from './client.ts'; import { maybeLinkCloudflareDeploy } from './cloudflare-link.ts'; @@ -300,6 +301,7 @@ async function runManagedDeploy( // Resolve the app type: void.config.ts > CLI flags > auto-detection. const voidConfig = readConfig(root); + assertNoWorkflowsForPlatform(root); cliLog.info('config_resolved', { target: voidConfig.target, appType: voidConfig.inference?.appType, diff --git a/packages/void/src/cli/info.ts b/packages/void/src/cli/info.ts index b2b9ee90c1..e768986a13 100644 --- a/packages/void/src/cli/info.ts +++ b/packages/void/src/cli/info.ts @@ -9,11 +9,12 @@ import { deriveWebSocketClassNameFromName, inferWebSocketResourceName, } from '../router/websocket.ts'; +import { inferWorkflowResourceName } from '../workflows/scan.ts'; import type { InfoArgs } from './info-args.ts'; export type PersistentResourceInfo = { file: string; - definition: 'defineDurableState' | 'defineRoom' | 'defineWebSocket'; + definition: 'defineDurableState' | 'defineRoom' | 'defineWebSocket' | 'defineWorkflow'; name: string; nameSource: 'inferred' | 'explicit'; className: string; @@ -135,6 +136,14 @@ export function getProjectInfo(root: string): ProjectInfo { className: module.className, bindingName: module.bindingName, })), + ...analysis.workflows.map((module) => ({ + file: relative(root, module.filePath), + definition: 'defineWorkflow' as const, + name: module.name ?? inferWorkflowResourceName(module.relativePath), + nameSource: module.name === undefined ? ('inferred' as const) : ('explicit' as const), + className: module.className, + bindingName: module.bindingName, + })), ]; resources.sort((a, b) => a.file.localeCompare(b.file)); return { resources, recordedResources: readRecordedResources(root, resources) }; diff --git a/packages/void/src/deploy.ts b/packages/void/src/deploy.ts index 0216c529fa..f9a6d9c3e7 100644 --- a/packages/void/src/deploy.ts +++ b/packages/void/src/deploy.ts @@ -23,6 +23,7 @@ import { readConfig, isNodeTarget } from './config.ts'; import { collectRevalidate } from './isr-config.ts'; import { hasEmailHandlers } from './router/email.ts'; import { validateSsrEntry } from './ssr/entry.ts'; +import { assertNoWorkflowsForPlatform } from './workflows/platform.ts'; /** * A disposable Cloudflare Build Output directory. Experimental: it follows Cloudflare's draft @@ -83,6 +84,7 @@ export async function prepareDeployArtifact( if (isNodeTarget(config.target) || config.output === 'static') { throw new Error('Artifact preparation requires a Void Cloudflare Worker build.'); } + assertNoWorkflowsForPlatform(root); let preset = resolveStaticDeployPreset(root, config); let analysis: Awaited> | undefined; if (!preset) { diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index c878b5caf0..7ebf27faaa 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -263,6 +263,32 @@ export function voidPlugin(options?: { 'durable: durable-objects/ is currently supported in Void apps only, not framework adapter mode.', ); } + const workflows = application.workflows; + if (detected && workflows.length > 0) { + throw new Error( + 'workflows: workflows/ is currently supported in Void apps only, not framework adapter mode.', + ); + } + for (const module of workflows) { + const owner = + websocketRoutes.find( + (route) => route.bindingName === module.bindingName || route.className === module.className, + )?.filePath ?? + durableObjects.find( + (durable) => + durable.bindingName === module.bindingName || durable.className === module.className, + )?.filePath; + if ( + owner !== undefined || + (sandboxConfig && + (sandboxConfig.binding === module.bindingName || + sandboxConfig.className === module.className)) + ) { + throw new Error( + `workflows: workflows/${module.relativePath} conflicts with ${owner === undefined ? 'the configured Sandbox binding or class' : `'${owner}'`}. Rename one of the files.`, + ); + } + } for (const module of durableObjects) { const websocketCollision = websocketRoutes.find( (route) => route.bindingName === module.bindingName || route.className === module.className, @@ -299,10 +325,12 @@ export function voidPlugin(options?: { reservedBindings: [ ...websocketRoutes.map((route) => route.bindingName), ...durableObjects.map((module) => module.bindingName), + ...workflows.map((module) => module.bindingName), ], reservedClasses: [ ...websocketRoutes.map((route) => route.className), ...durableObjects.map((module) => module.className), + ...workflows.map((module) => module.className), sandboxConfig?.className, ], }) @@ -404,6 +432,7 @@ export function voidPlugin(options?: { devTriggerToken, queues, durableObjects, + workflows, sandboxConfig, shouldEmitLive, liveConfig, @@ -844,6 +873,11 @@ export function voidPlugin(options?: { `durable: durable-objects/ requires target: "cloudflare". It is not available with target: '${config.target}'.`, ); } + if (workflows.length > 0) { + throw new Error( + `workflows: workflows/ requires target: "cloudflare". It is not available with target: '${config.target}'.`, + ); + } // `compileNodeApp` imports only the Hono app from the route table; the // `__emailHandler` the table exports for `email/` is never invoked, so // without this the build succeeds and every inbound handler is dead code. @@ -1000,6 +1034,7 @@ export function voidPlugin(options?: { return shouldEmitLive() ? liveConfig : undefined; }, durableObjects, + workflows, websocketTombstones, onDevAssetRoutingPolicyChange: updateDevAssetRoutingPolicy, // Native builds of eligible apps let Cloudflare serve hashed build files directly. diff --git a/packages/void/src/plugin-client-stubs.ts b/packages/void/src/plugin-client-stubs.ts index 25f759b04e..469192edb8 100644 --- a/packages/void/src/plugin-client-stubs.ts +++ b/packages/void/src/plugin-client-stubs.ts @@ -59,6 +59,7 @@ export function createClientStubsPlugin(): Plugin { `, 'void/live': '', 'void/durable': '', + 'void/workflows': '', }; const STUB_RESOLVE_FILTER = new RegExp( `^(${Object.keys(SERVER_ONLY_STUBS) @@ -75,11 +76,11 @@ export function createClientStubsPlugin(): Plugin { filter: { id: STUB_RESOLVE_FILTER }, handler(id) { if (this.environment?.name === 'client') { - if (id === 'void/live' || id === 'void/durable') { + if (id === 'void/live' || id === 'void/durable' || id === 'void/workflows') { this.error( id === 'void/live' ? 'void/live is server-only and cannot be imported by browser code. Import void/live/client instead.' - : 'void/durable is server-only and cannot be imported by browser code.', + : `${id} is server-only and cannot be imported by browser code.`, ); } return STUB_PREFIX + id; diff --git a/packages/void/src/plugin-cloudflare-config.ts b/packages/void/src/plugin-cloudflare-config.ts index a409a82273..de56041927 100644 --- a/packages/void/src/plugin-cloudflare-config.ts +++ b/packages/void/src/plugin-cloudflare-config.ts @@ -47,17 +47,23 @@ export function mergeCloudflareConfig(patch: object, fallback: object): Record; + workflows?: Array<{ + bindingName: string; + className: string; + filePath: string; + relativePath?: string; + name?: string; + }>; /** Data-preserving exports for removed WebSocket Durable Object routes. */ websocketTombstones?: Array; onDevAssetRoutingPolicyChange?: (policy: AssetRoutingPolicy) => boolean; @@ -654,6 +661,7 @@ export function routingPlugin( isr, notFound: policy.assetConfig.not_found_handling ?? 'none', durableObjects: options.durableObjects, + workflows: options.workflows, }), ); } @@ -681,6 +689,7 @@ export function routingPlugin( sandbox: sandboxEntry, live: options.live, durableObjects: options.durableObjects, + workflows: options.workflows, }), ); } diff --git a/packages/void/src/plugin-worker-bindings.ts b/packages/void/src/plugin-worker-bindings.ts index e966e3081b..6b6cd82396 100644 --- a/packages/void/src/plugin-worker-bindings.ts +++ b/packages/void/src/plugin-worker-bindings.ts @@ -16,6 +16,7 @@ import { readVoidDevCredentials, } from './plugin-ai-setup.ts'; import { hasBinding, shouldInjectEmailDevInboxVar } from './plugin-binding-utils.ts'; +import { defaultCloudflareWorkerName } from './plugin-cloudflare-config.ts'; import type { WorkerConfig } from './plugin-cloudflare-config.ts'; import type { EnvSchemaFacts } from './plugin-env-schema.ts'; import { cloudflareQueueName, readDeployBuildQueueNames } from './queues/cloudflare-names.ts'; @@ -29,11 +30,12 @@ import { sandboxContainerConfig, assertSandboxNamespaceConfig, } from './sandbox/config.ts'; -import { CLOUDFLARE_DEPLOY_BUILD_ENV } from './shared/env.ts'; +import { CLOUDFLARE_DEPLOY_BUILD_ENV, CLOUDFLARE_WORKER_NAME_BUILD_ENV } from './shared/env.ts'; import { CLOUDFLARE_PRESERVE_BINDINGS_BUILD_ENV, selectNativeVersionMetadataBinding, } from './shared/version-metadata.ts'; +import { planWorkflowAdditions, workflowConfigEntries } from './workflows/config.ts'; type DurableObjectBinding = { name: string; class_name: string }; type DurableObjectMigration = { @@ -63,6 +65,34 @@ function currentMigrations( return Array.isArray(current) ? (current as Array) : []; } +/** + * Add a `workflows` entry for each `workflows/` module. The Cloudflare plugin + * concatenates this patch with the resolved config, so only additions are emitted. + */ +function mergeWorkflowBindings( + result: Record, + resolved: WorkerConfig, + workflows: ApplicationAnalysis['workflows'], + root: string, +): void { + if (workflows.length === 0) { + return; + } + const patchEntries = workflowConfigEntries(result.workflows); + const deployWorkerName = + process.env[CLOUDFLARE_DEPLOY_BUILD_ENV] === '1' + ? process.env[CLOUDFLARE_WORKER_NAME_BUILD_ENV] + : undefined; + const additions = planWorkflowAdditions( + [...patchEntries, ...workflowConfigEntries((resolved as Record).workflows)], + workflows, + deployWorkerName || ((resolved as { name?: string }).name ?? defaultCloudflareWorkerName(root)), + ); + if (additions.length > 0) { + result.workflows = [...patchEntries, ...additions]; + } +} + export function mergeWorkerBindings( resolved: WorkerConfig, input: { @@ -81,6 +111,7 @@ export function mergeWorkerBindings( readonly devTriggerToken: string; readonly queues: ApplicationAnalysis['queues']; readonly durableObjects: ApplicationAnalysis['durableObjects']; + readonly workflows: ApplicationAnalysis['workflows']; readonly sandboxConfig: ReturnType | undefined; readonly shouldEmitLive: () => boolean; readonly liveConfig: ReturnType | undefined; @@ -104,6 +135,7 @@ export function mergeWorkerBindings( devTriggerToken, queues, durableObjects, + workflows, sandboxConfig, shouldEmitLive, liveConfig, @@ -390,6 +422,8 @@ export function mergeWorkerBindings( } } + mergeWorkflowBindings(result, resolved, workflows, root); + if (bindings.needsSandbox && sandboxConfig) { assertSandboxNamespaceConfig({ ...resolved, ...result }, sandboxConfig); const existingDurableObjectBindings = currentDurableObjectBindings(result, resolved); diff --git a/packages/void/src/router/compile.ts b/packages/void/src/router/compile.ts index 9683661503..25b7669234 100644 --- a/packages/void/src/router/compile.ts +++ b/packages/void/src/router/compile.ts @@ -1198,12 +1198,55 @@ export interface WorkerEntryOptions { * imported from `filePath`, bound to `bindingName`, and re-exported as * `className` so wrangler's `durable_objects.bindings` can find it. */ - durableObjects?: Array<{ - bindingName: string; - className: string; - filePath: string; - name?: string; - }>; + durableObjects?: Array; + /** + * Workflow definitions (`workflows/` directory). Each entry is imported from + * `filePath`, bound to `bindingName`, and re-exported as `className` so + * the Cloudflare `workflows` config can find it. + */ + workflows?: Array; +} + +type ResourceModuleCode = { imports: string; exports: string }; + +type ResourceModuleEntry = { + bindingName: string; + className: string; + filePath: string; + /** Path relative to the convention directory, for error messages. Defaults to the file name. */ + relativePath?: string; + name?: string; +}; + +/** + * Import each convention module through its namespace so a missing default + * export reaches the guard below instead of failing with a bundler error or a + * generic `Cannot read properties of undefined` at Worker startup. + */ +function compileResourceModules( + entries: ReadonlyArray, + options: { variable: string; directory: string; prefix: string; helpers: string }, +): ResourceModuleCode { + const imports = entries + .map( + ({ filePath }, index) => + `import * as ${options.variable}Module${index} from ${JSON.stringify(filePath)};`, + ) + .join('\n'); + const exports = entries + .map(({ bindingName, className, filePath, relativePath, name }, index) => { + const local = `${options.variable}${index}`; + const file = `${options.directory}/${relativePath ?? filePath.replaceAll('\\', '/').split('/').pop()}`; + const message = `${options.prefix}: ${file} must default-export ${options.helpers}.`; + return [ + `const ${local} = ${options.variable}Module${index}.default;`, + `if (typeof ${local}?.__bind !== "function") { throw new Error(${JSON.stringify(message)}); }`, + `${local}.__bind(${JSON.stringify(bindingName)}${name !== undefined ? `, ${JSON.stringify(name)}` : ''});`, + `export const ${className} = ${local}.class;`, + ].join('\n'); + }) + .join('\n'); + return { imports, exports }; } /** @@ -1239,6 +1282,7 @@ export function compileWorkerEntry(options: WorkerEntryOptions = {}): string { isr, notFound = 'none', durableObjects = [], + workflows = [], } = options; const remotePath = remote?.remotePath; const remoteBindingNames = JSON.stringify(remote?.bindingNames); @@ -1281,17 +1325,23 @@ export function compileWorkerEntry(options: WorkerEntryOptions = {}): string { ? `export { VoidLiveStreamDurableObject };\n__setLiveBindingName(${JSON.stringify(liveBindingName)});\n${liveDevCall}` : `export { VoidLiveStreamDurableObject as ${liveClassName} };\n__setLiveBindingName(${JSON.stringify(liveBindingName)});\n${liveDevCall}` : ''; - const durableObjectImports = durableObjects - .map( - ({ filePath }, index) => - `import __voidDurableObject${index} from ${JSON.stringify(filePath)};`, - ) + const durableObjectModules = compileResourceModules(durableObjects, { + variable: '__voidDurableObject', + directory: 'durable-objects', + prefix: 'durable', + helpers: 'defineDurableState() or defineDurableObject()', + }); + const workflowModules = compileResourceModules(workflows, { + variable: '__voidWorkflow', + directory: 'workflows', + prefix: 'workflows', + helpers: 'defineWorkflow() or defineWorkflowEntrypoint()', + }); + const resourceModuleImports = [durableObjectModules.imports, workflowModules.imports] + .filter(Boolean) .join('\n'); - const durableObjectExports = durableObjects - .map( - ({ bindingName, className, name }, index) => - `__voidDurableObject${index}.__bind(${JSON.stringify(bindingName)}${name !== undefined ? `, ${JSON.stringify(name)}` : ''});\nexport const ${className} = __voidDurableObject${index}.class;`, - ) + const resourceModuleExports = [durableObjectModules.exports, workflowModules.exports] + .filter(Boolean) .join('\n'); const runtimeEnvImport = `import { withRuntimeEnv } from ${JSON.stringify(runtimeEnvPath)};\n`; const remoteImport = remote @@ -1431,7 +1481,7 @@ ${envValidateCall}${remoteEnvSwap}${isrDeploymentStamp} const userEnv = __filte ` : ''; return `${sandboxImport}${entryImport}${liveRuntimeImport}import app, { scheduled, __voidCollectPrerenderPaths, __voidRenderStaticNotFound, __voidHandleInternalRoute, __withRawEnv${queueImport}${emailImport}${webSocketClasses.length > 0 ? `, ${webSocketClasses.join(', ')}` : ''}${liveRouteImport} } from 'virtual:void-routes'; -${durableObjectImports}\n${runtimeEnvImport}${emailProxyImport}${envSchemaImport}${remoteImport}${isrImport}${filterBindingsHelper}${assetHelper} +${resourceModuleImports}\n${runtimeEnvImport}${emailProxyImport}${envSchemaImport}${remoteImport}${isrImport}${filterBindingsHelper}${assetHelper} ${fetchDeclaration} ${scheduledHandler} ${emailHandler} @@ -1439,7 +1489,7 @@ ${emailReceiptHandler} ${queueFunction}${webSocketClasses.map((name) => `export { ${name} };`).join('\n')} ${liveExport} ${sandboxExport} -${durableObjectExports} +${resourceModuleExports} ${entryClass}`; } diff --git a/packages/void/src/runtime/workflows/index.ts b/packages/void/src/runtime/workflows/index.ts new file mode 100644 index 0000000000..6aeba30ed0 --- /dev/null +++ b/packages/void/src/runtime/workflows/index.ts @@ -0,0 +1,246 @@ +import { WorkflowEntrypoint } from 'cloudflare:workers'; +import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers'; +import { isResourceName } from '../../shared/resource-name.ts'; +import type { StandardSchemaV1 } from '../../standard-schema.ts'; +import { requireRuntimeBinding, withRuntimeEnv } from '../env/runtime.ts'; + +export type { WorkflowEvent, WorkflowStep }; + +type NativeWorkflowClass = new (...args: Array) => { + run(event: never, step: never): Promise; +}; + +/** Params type of a native class, read from its `run(event)` annotation. */ +export type NativeWorkflowParams = + InstanceType extends { + run(event: Readonly>, ...rest: Array): unknown; + } + ? TParams + : unknown; + +/** Context passed to a `defineWorkflow()` run function next to the event and step. */ +export type WorkflowContext = { + readonly env: TEnv; + readonly ctx: ExecutionContext; +}; + +/** Options for starting one Workflow instance. */ +export type WorkflowCreateOptions = Omit & { + params?: TParams; +}; + +export type WorkflowApi = { + class: TClass; + /** @internal Called by Void's generated Worker entry. */ + __bind(bindingName: string, resourceName?: string): void; + /** Start a new instance. Params are validated when the definition has a `params` schema. */ + create(options?: WorkflowCreateOptions): Promise; + create(binding: Workflow, options?: WorkflowCreateOptions): Promise; + /** Start up to 100 instances. Each instance's params are validated first. */ + createBatch( + instances: ReadonlyArray>, + ): Promise; + createBatch( + binding: Workflow, + instances: ReadonlyArray>, + ): Promise; + /** Get a handle to an existing instance. */ + get(id: string): Promise; + get(binding: Workflow, id: string): Promise; +}; + +export type WorkflowRun = ( + event: Readonly>, + step: WorkflowStep, + context: WorkflowContext, +) => Promise; + +export type WorkflowClass = new ( + ctx: ExecutionContext, + env: Record, +) => WorkflowEntrypoint, TParams>; + +/** Error thrown by `create()` and `createBatch()` when params fail the definition's schema. */ +export class WorkflowParamsError extends Error { + readonly issues: ReadonlyArray<{ message: string; path?: string }>; + + constructor(issues: ReadonlyArray) { + const flattened = Array.from(issues, (issue) => ({ + message: issue.message, + ...(issue.path?.length + ? { + path: issue.path + .map((segment) => String(typeof segment === 'object' ? segment.key : segment)) + .join('.'), + } + : {}), + })); + super( + `workflows: invalid params: ${flattened + .map((issue) => (issue.path ? `${issue.path}: ${issue.message}` : issue.message)) + .join('; ')}`, + ); + this.name = 'WorkflowParamsError'; + this.issues = flattened; + } +} + +function isWorkflowBinding(value: Workflow | TOther): value is Workflow { + return ( + typeof value === 'object' && + value !== null && + typeof (value as { create?: unknown }).create === 'function' && + typeof (value as { get?: unknown }).get === 'function' + ); +} + +function createWorkflowApi( + definitionName: string | undefined, + workflowClass: TClass, + schema: StandardSchemaV1 | undefined, +): WorkflowApi { + if (definitionName !== undefined && !isResourceName(definitionName)) { + throw new Error('workflows: name must contain a word starting with a letter.'); + } + let bindingName: string | undefined; + + function boundWorkflow(): Workflow { + if (!bindingName) { + throw new Error( + 'workflows: this definition is not bound. Default-export it from a file in workflows/.', + ); + } + return requireRuntimeBinding(bindingName); + } + + async function prepare( + options: WorkflowCreateOptions | undefined, + ): Promise { + if (!schema) { + return options; + } + const result = await schema['~standard'].validate(options?.params); + if (result.issues) { + throw new WorkflowParamsError(result.issues); + } + return { ...options, params: result.value }; + } + + return { + class: workflowClass, + __bind(name, resourceName) { + if (definitionName !== resourceName) { + throw new Error( + 'workflows: name must be statically discoverable in the workflow definition. Run void info to inspect this definition.', + ); + } + if (bindingName && bindingName !== name) { + throw new Error( + `workflows: definition is already bound to '${bindingName}' and cannot also bind to '${name}'.`, + ); + } + bindingName = name; + }, + async create( + bindingOrOptions?: Workflow | WorkflowCreateOptions, + maybeOptions?: WorkflowCreateOptions, + ) { + const explicit = isWorkflowBinding(bindingOrOptions); + const binding = explicit ? bindingOrOptions : boundWorkflow(); + const options = explicit ? maybeOptions : bindingOrOptions; + return binding.create(await prepare(options)); + }, + async createBatch( + bindingOrInstances: Workflow | ReadonlyArray>, + maybeInstances?: ReadonlyArray>, + ) { + const explicit = isWorkflowBinding(bindingOrInstances); + const binding = explicit ? bindingOrInstances : boundWorkflow(); + const instances = explicit ? (maybeInstances ?? []) : bindingOrInstances; + const prepared = await Promise.all( + Array.from(instances, async (instance) => (await prepare(instance)) ?? {}), + ); + return binding.createBatch({ instances: prepared }); + }, + get(bindingOrId: Workflow | string, maybeId?: string) { + if (typeof bindingOrId === 'string') { + return boundWorkflow().get(bindingOrId); + } + if (maybeId === undefined) { + throw new Error('workflows: get(binding, id) requires an instance id.'); + } + return bindingOrId.get(maybeId); + }, + }; +} + +type WorkflowDefinitionBase = { + /** Optional persistent resource name. Pin the name reported by `void info` before moving this definition. */ + name?: string; +}; + +/** + * Define a Workflow from a run function. Void generates the Cloudflare + * `WorkflowEntrypoint` class. Default-export the result from a file in `workflows/`. + */ +export function defineWorkflow< + TSchema extends StandardSchemaV1, + TEnv extends Record = Record, +>( + definition: WorkflowDefinitionBase & { + /** Standard Schema that validates params in `create()` and `createBatch()`. */ + params: TSchema; + run: WorkflowRun, TEnv>; + }, +): WorkflowApi< + WorkflowClass>, + StandardSchemaV1.InferInput +>; +export function defineWorkflow< + TParams = unknown, + TEnv extends Record = Record, +>( + definition: WorkflowDefinitionBase & { + params?: undefined; + run: WorkflowRun; + }, +): WorkflowApi, TParams>; +export function defineWorkflow( + definition: WorkflowDefinitionBase & { + params?: StandardSchemaV1; + run: WorkflowRun>; + }, +): WorkflowApi, unknown> { + if (typeof definition.run !== 'function') { + throw new Error('workflows: defineWorkflow() requires a run function.'); + } + const run = definition.run; + + class VoidWorkflow extends WorkflowEntrypoint, unknown> { + override run(event: Readonly>, step: WorkflowStep): Promise { + const env = this.env; + const ctx = this.ctx; + return withRuntimeEnv(env, () => run(event, step, { env, ctx })); + } + } + + return createWorkflowApi(definition.name, VoidWorkflow, definition.params); +} + +/** + * Register a native Cloudflare `WorkflowEntrypoint` class without changing it. + * Default-export the result from a file in `workflows/`. + */ +export function defineWorkflowEntrypoint< + TClass extends NativeWorkflowClass, + TParams = NativeWorkflowParams, +>( + definition: WorkflowDefinitionBase & { + class: TClass; + }, +): WorkflowApi { + if (typeof definition.class !== 'function') { + throw new Error('workflows: defineWorkflowEntrypoint() requires a class.'); + } + return createWorkflowApi(definition.name, definition.class, undefined); +} diff --git a/packages/void/src/shared/env.ts b/packages/void/src/shared/env.ts index fdb3322eb1..fdb6380416 100644 --- a/packages/void/src/shared/env.ts +++ b/packages/void/src/shared/env.ts @@ -41,6 +41,12 @@ export const CLOUDFLARE_DEPLOY_BUILD_ENV = 'VOID_CLOUDFLARE_DEPLOY_BUILD'; */ export const CLOUDFLARE_QUEUE_NAMES_BUILD_ENV = 'VOID_CLOUDFLARE_QUEUE_NAMES'; +/** + * The Worker name `void deploy --platform cloudflare` deploys to. Set only for + * its Vite build, which prefixes account-scoped Workflow names with it. + */ +export const CLOUDFLARE_WORKER_NAME_BUILD_ENV = 'VOID_CLOUDFLARE_WORKER_NAME'; + /** * Find legacy Vite dotenv variants. Void intentionally supports only `.env`; * production configuration is project-scoped remote state instead of a file. diff --git a/packages/void/src/shared/resource-definition.ts b/packages/void/src/shared/resource-definition.ts index 2c74460b25..7e85aeb92a 100644 --- a/packages/void/src/shared/resource-definition.ts +++ b/packages/void/src/shared/resource-definition.ts @@ -63,7 +63,9 @@ export function readResourceDefinition( ? new Set(['defineRoom', 'defineWebSocket']) : source === 'void/durable' ? new Set(['defineDurableState', 'defineDurableObject']) - : new Set(); + : source === 'void/workflows' + ? new Set(['defineWorkflow', 'defineWorkflowEntrypoint']) + : new Set(); for (const specifier of declaration.specifiers ?? []) { const local = specifier.local as AstNode | undefined; recordBindings(local); diff --git a/packages/void/src/workflows/config.ts b/packages/void/src/workflows/config.ts new file mode 100644 index 0000000000..610a6ded1e --- /dev/null +++ b/packages/void/src/workflows/config.ts @@ -0,0 +1,55 @@ +import { cloudflareWorkflowName } from './scan.ts'; +import type { WorkflowModule } from './scan.ts'; + +export type WorkflowConfigEntry = Record & { + name?: unknown; + binding?: unknown; + class_name?: unknown; + script_name?: unknown; +}; + +export function workflowConfigEntries(value: unknown): Array { + if (value === undefined) { + return []; + } + if ( + !Array.isArray(value) || + value.some((entry) => !entry || typeof entry !== 'object' || Array.isArray(entry)) + ) { + throw new Error('Cloudflare workflows configuration must be an array of objects.'); + } + return value as Array; +} + +/** + * The `workflows` entries Void adds for `workflows/` modules, given the entries + * already configured. A module whose binding is already configured for the same + * local class is kept as configured, so an authored entry can pin the name. + */ +export function planWorkflowAdditions( + existing: ReadonlyArray, + modules: ReadonlyArray>, + workerName: string, +): Array<{ name: string; binding: string; class_name: string }> { + const additions: Array<{ name: string; binding: string; class_name: string }> = []; + for (const module of modules) { + const configured = existing.find((entry) => entry.binding === module.bindingName); + if (configured) { + if (configured.class_name !== module.className || configured.script_name !== undefined) { + throw new Error( + `workflows: binding '${module.bindingName}' is already configured for another Workflow, but workflows/ requires class '${module.className}'.`, + ); + } + continue; + } + const name = cloudflareWorkflowName(module.resourceName, workerName); + const owner = [...existing, ...additions].find((entry) => entry.name === name); + if (owner) { + throw new Error( + `workflows: Workflow name '${name}' is already configured for binding '${String(owner.binding)}'.`, + ); + } + additions.push({ name, binding: module.bindingName, class_name: module.className }); + } + return additions; +} diff --git a/packages/void/src/workflows/platform.ts b/packages/void/src/workflows/platform.ts new file mode 100644 index 0000000000..b06544ff3c --- /dev/null +++ b/packages/void/src/workflows/platform.ts @@ -0,0 +1,10 @@ +import { scanWorkflowModules } from './scan.ts'; + +/** Void platform deploys do not provision Cloudflare Workflows yet. */ +export function assertNoWorkflowsForPlatform(root: string): void { + if (scanWorkflowModules(root).length > 0) { + throw new Error( + 'workflows: workflows/ is not supported on Void platforms yet. Deploy this app to your own Cloudflare account with `void deploy --platform cloudflare`.', + ); + } +} diff --git a/packages/void/src/workflows/scan.ts b/packages/void/src/workflows/scan.ts new file mode 100644 index 0000000000..7385175f33 --- /dev/null +++ b/packages/void/src/workflows/scan.ts @@ -0,0 +1,111 @@ +import { existsSync, readFileSync } from 'node:fs'; +import { join } from 'pathslash'; +import { globSync } from 'tinyglobby'; +import { readResourceDefinition } from '../shared/resource-definition.ts'; +import { resourceNameWords } from '../shared/resource-name.ts'; + +export type WorkflowModule = { + filePath: string; + /** Path relative to `workflows/`, with `/` separators. */ + relativePath: string; + bindingName: string; + className: string; + /** Kebab-case resource name. Cloudflare Workflow names are derived from it. */ + resourceName: string; + name?: string; +}; + +const MODULE_PATTERN = /\.(?:[cm]?[jt]s)$/; +const MODULE_GLOB = '**/*.{ts,mts,cts,js,mjs,cjs}'; + +const WORKFLOW_HELPERS = new Set(['defineWorkflow', 'defineWorkflowEntrypoint']); + +/** + * The name a module gets without an explicit `name`: its path relative to + * `workflows/` without the extension, with directories joined by `-`, as + * queue names are (`order/notifications.ts` → `order-notifications`). + */ +export function inferWorkflowResourceName(relativePath: string): string { + return relativePath.replaceAll('\\', '/').replace(MODULE_PATTERN, '').replaceAll('/', '-'); +} + +/** Module files under `workflows/`, skipping declarations and `_`-prefixed files or directories. */ +function listWorkflowFiles(directory: string): Array { + return globSync(MODULE_GLOB, { cwd: directory }) + .map((file) => file.replaceAll('\\', '/')) + .filter( + (file) => + !file.endsWith('.d.ts') && + !file.endsWith('.d.mts') && + !file.endsWith('.d.cts') && + file.split('/').every((segment) => !segment.startsWith('_')), + ) + .sort((a, b) => a.localeCompare(b)); +} + +export function deriveWorkflowResourceIdentity(name: string): { + bindingName: string; + className: string; + resourceName: string; +} { + const parts = resourceNameWords(name); + const classBase = parts.map((part) => part[0].toUpperCase() + part.slice(1)).join(''); + return { + bindingName: `WORKFLOW_${parts.join('_').toUpperCase()}`, + className: `${classBase}Workflow`, + resourceName: parts.join('-').toLowerCase(), + }; +} + +/** + * Cloudflare Workflow names are unique per account. Deploys prefix them with the + * Worker name; local development, where names only need to be unique per Worker, + * uses the resource name alone. + */ +export function cloudflareWorkflowName(resourceName: string, workerName?: string): string { + if (!workerName) { + return resourceName; + } + const prefix = workerName.toLowerCase().replaceAll('_', '-'); + return `${prefix}-${resourceName}`.slice(0, 64); +} + +export function scanWorkflowModules(root: string): Array { + const directory = join(root, 'workflows'); + if (!existsSync(directory)) { + return []; + } + + const modules = listWorkflowFiles(directory).map((relativePath) => { + const filePath = join(directory, relativePath); + const definition = readResourceDefinition( + filePath, + readFileSync(filePath, 'utf8'), + WORKFLOW_HELPERS, + ); + const name = definition?.name; + const resourceName = name ?? inferWorkflowResourceName(relativePath); + if (resourceNameWords(resourceName).length === 0) { + throw new Error(`workflows: cannot derive a name from workflows/${relativePath}.`); + } + return { + filePath, + relativePath, + ...deriveWorkflowResourceIdentity(resourceName), + ...(name === undefined ? {} : { name }), + }; + }); + + const bindings = new Set(); + const classes = new Set(); + for (const module of modules) { + if (bindings.has(module.bindingName) || classes.has(module.className)) { + throw new Error( + `workflows: duplicate generated name for 'workflows/${module.relativePath}'. Choose a different resource name or rename one of the workflows files.`, + ); + } + bindings.add(module.bindingName); + classes.add(module.className); + } + return modules; +} diff --git a/packages/void/test/integration/cloudflare-durable-build.test.ts b/packages/void/test/integration/cloudflare-durable-build.test.ts index 571e2f8fa1..c2c01e8b90 100644 --- a/packages/void/test/integration/cloudflare-durable-build.test.ts +++ b/packages/void/test/integration/cloudflare-durable-build.test.ts @@ -9,6 +9,7 @@ import { verifyGeneratedDeployConfig } from '../../src/cli/deploy-artifact-valid import { reconstructExpectedContainers, reconstructExpectedDurableObjectState, + reconstructExpectedWorkflows, snapshotBindingIdentities, snapshotPassthroughIdentities, snapshotPassthroughRawFields, @@ -18,7 +19,10 @@ import { syncWranglerBindings } from '../../src/cli/wrangler.ts'; import { materializeCloudflareConfig } from '../../src/cloudflare-config.ts'; import { renderVoidConfig } from '../../src/config-write.ts'; import { readConfig } from '../../src/config.ts'; -import { CLOUDFLARE_DEPLOY_BUILD_ENV } from '../../src/shared/env.ts'; +import { + CLOUDFLARE_DEPLOY_BUILD_ENV, + CLOUDFLARE_WORKER_NAME_BUILD_ENV, +} from '../../src/shared/env.ts'; const repository = join(import.meta.dirname, '..', '..', '..', '..'); const accountId = '0123456789abcdef0123456789abcdef'; @@ -149,6 +153,13 @@ export default defineDurableState({ initialState: { count: 0 }, methods: { incre ), expectedCrons: signals.expectedCrons, expectedDurableObjectBindings: durable.bindings, + expectedWorkflows: reconstructExpectedWorkflows( + config, + root, + rootConfig, + `durable-merge-${options.name}`, + analysis, + ), expectedMigrations: durable.migrations, }; const build = () => { @@ -172,9 +183,12 @@ export default defineDurableState({ initialState: { count: 0 }, methods: { incre containers?: Array; hyperdrive?: Array; ai?: unknown; + workflows?: Array; }; }; const emitted = build(); + // Workflows are opt-in: an app without workflows/ emits no Workflow config. + expect(emitted.workflows).toBeUndefined(); // Exercise worker/cloudflare overlap through the actual provider plugin, // alongside the existing native build rather than booting another one. if (options.name === 'native') { @@ -215,4 +229,94 @@ export default defineDurableState({ initialState: { count: 0 }, methods: { incre } }, ); + + it('emits Workflow entries named after the deployed Worker and keeps authored ones', () => { + const fixture = createIsolatedPlayground(repository, 'playground/ssr'); + const root = fixture.root; + try { + mkdirSync(join(root, 'workflows'), { recursive: true }); + writeFileSync( + join(root, 'workflows/welcome.ts'), + `import { defineWorkflow } from 'void/workflows'; +export default defineWorkflow({ async run(event, step) { return step.do('greet', async () => 'hi'); } });\n`, + ); + writeFileSync( + join(root, 'workflows/nightly-import.ts'), + `import { WorkflowEntrypoint } from 'cloudflare:workers'; +import { defineWorkflowEntrypoint } from 'void/workflows'; +class Importer extends WorkflowEntrypoint { async run() { return 'imported'; } } +export default defineWorkflowEntrypoint({ class: Importer });\n`, + ); + const pinned = { + name: 'legacy-import', + binding: 'WORKFLOW_NIGHTLY_IMPORT', + class_name: 'NightlyImportWorkflow', + }; + writeFileSync( + join(root, 'void.config.ts'), + renderVoidConfig({ + ...readConfig(root), + cloudflare: { name: 'workflow-merge', account_id: accountId, workflows: [pinned] }, + }), + ); + const config = readConfig(root); + const analysis = analyzeApplicationSync(root, { config }); + const configPath = materializeCloudflareConfig(root); + const rootConfig = parseRootWranglerConfig(configPath); + const expectedWorkflows = reconstructExpectedWorkflows( + config, + root, + rootConfig, + 'deployed-app', + analysis, + ); + expect(expectedWorkflows).toEqual([ + pinned, + { + name: 'deployed-app-welcome', + binding: 'WORKFLOW_WELCOME', + class_name: 'WelcomeWorkflow', + }, + ]); + const result = spawn.sync('vp', ['build'], { + cwd: root, + encoding: 'utf8', + timeout: 60_000, + maxBuffer: 10 * 1024 * 1024, + env: { + ...process.env, + [CLOUDFLARE_DEPLOY_BUILD_ENV]: '1', + [CLOUDFLARE_WORKER_NAME_BUILD_ENV]: 'deployed-app', + CLOUDFLARE_API_TOKEN: '', + CLOUDFLARE_API_KEY: '', + }, + }); + expect(result.status, `${result.stdout ?? ''}${result.stderr ?? ''}`).toBe(0); + const emitted = JSON.parse(readFileSync(join(root, 'dist/ssr/wrangler.json'), 'utf8')) as { + workflows?: Array>; + }; + expect(emitted.workflows).toEqual(expect.arrayContaining(expectedWorkflows)); + expect(emitted.workflows).toHaveLength(expectedWorkflows.length); + const worker = readFileSync(join(root, 'dist/ssr/index.js'), 'utf8'); + expect(worker).toMatch(/WelcomeWorkflow/); + expect(worker).toMatch(/NightlyImportWorkflow/); + expect( + verifyGeneratedDeployConfig(root, { + accountId, + workerName: 'workflow-merge', + passthroughIdentitySnapshot: snapshotPassthroughIdentities(rootConfig), + expectedWorkflows, + }), + ).toEqual({ ok: true }); + expect( + verifyGeneratedDeployConfig(root, { + accountId, + workerName: 'workflow-merge', + expectedWorkflows: [pinned], + }), + ).toMatchObject({ ok: false, reason: expect.stringContaining('workflows differ') }); + } finally { + fixture.cleanup(); + } + }, 120_000); }); diff --git a/packages/void/test/integration/workflow-runtime.test.ts b/packages/void/test/integration/workflow-runtime.test.ts new file mode 100644 index 0000000000..8680a01319 --- /dev/null +++ b/packages/void/test/integration/workflow-runtime.test.ts @@ -0,0 +1,222 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { Miniflare, convertV4MiniflareOptions } from 'miniflare'; +import { build } from 'vite'; +import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'; +import { compileWorkerEntry } from '../../src/router/compile.ts'; + +const root = join(import.meta.dirname, '..', '..', '..', '..'); +const runtimePath = join(root, 'packages/void/src/runtime/workflows/index.ts'); +const durablePath = join(root, 'packages/void/src/runtime/durable/index.ts'); +const temporary = mkdtempSync(join(tmpdir(), 'void-workflow-runtime-')); +type Runtime = { dispatchFetch(url: string): Promise; dispose(): Promise }; +let runtime: Runtime; + +const ROUTE_STUBS = ` +export const scheduled = async () => {}; +export const __voidCollectPrerenderPaths = async () => []; +export const __voidRenderStaticNotFound = async () => new Response(null, { status: 204 }); +export const __voidHandleInternalRoute = async () => null; +export const __withRawEnv = (_env, fn) => fn(); +`; + +/** Build a generated Worker entry for `entryOptions` into `name/worker.mjs`. */ +async function buildWorker( + name: string, + routes: string, + entryOptions: Parameters[0], +): Promise { + const directory = join(temporary, name); + const routesPath = join(temporary, `${name}-routes.ts`); + const entryPath = join(temporary, `${name}-entry.ts`); + writeFileSync(routesPath, ROUTE_STUBS + routes); + writeFileSync( + entryPath, + compileWorkerEntry({ + runtimeEnvPath: join(root, 'packages/void/src/runtime/env/runtime.ts'), + ...entryOptions, + }), + ); + await build({ + configFile: false, + logLevel: 'silent', + plugins: [ + { + name: 'workflow-runtime-fixture', + resolveId: (id) => (id === 'virtual:void-routes' ? routesPath : null), + }, + ], + ssr: { noExternal: true }, + build: { + outDir: directory, + emptyOutDir: true, + ssr: entryPath, + target: 'esnext', + rollupOptions: { + external: [/^cloudflare:/, /^node:/], + output: { entryFileNames: 'worker.mjs', codeSplitting: false }, + }, + }, + }); + return directory; +} + +function file(name: string, source: string): string { + const path = join(temporary, name); + writeFileSync(path, source); + return path; +} + +describe('Workflows through the generated Worker and a real Workflows engine', () => { + beforeAll(async () => { + const definition = file( + 'welcome.ts', + ` +import { defineWorkflow } from ${JSON.stringify(runtimePath)}; +const params = { '~standard': { version: 1, vendor: 'test', validate(value) { + return typeof value?.name === 'string' ? { value } : { issues: [{ message: 'name is required', path: ['name'] }] }; +} } }; +export const Welcome = defineWorkflow({ + params, + async run(event, step, { env }) { + const greeting = await step.do('greet', async () => env.GREETING + ', ' + event.payload.name); + return { greeting }; + }, +}); +export default Welcome; +`, + ); + const output = await buildWorker( + 'valid', + ` +import { Welcome } from ${JSON.stringify(definition)}; +export default { async fetch(request) { + const url = new URL(request.url); + if (url.pathname === '/start') { + try { + const instance = await Welcome.create({ id: url.searchParams.get('id'), params: { name: url.searchParams.get('name') ?? undefined } }); + return Response.json({ id: instance.id }); + } catch (error) { + return Response.json({ error: error.message }, { status: 400 }); + } + } + const instance = await Welcome.get(url.searchParams.get('id')); + return Response.json(await instance.status()); +}}; +`, + { + workflows: [ + { + bindingName: 'WORKFLOW_WELCOME', + className: 'WelcomeWorkflow', + filePath: definition, + }, + ], + }, + ); + runtime = new Miniflare( + convertV4MiniflareOptions({ + compatibilityDate: '2026-07-01', + compatibilityFlags: ['nodejs_compat'], + modules: true, + modulesRoot: output, + scriptPath: join(output, 'worker.mjs'), + bindings: { GREETING: 'Hello' }, + workflows: { WORKFLOW_WELCOME: { name: 'welcome', className: 'WelcomeWorkflow' } }, + }), + ) as unknown as Runtime; + }, 30_000); + + afterAll(async () => { + await runtime?.dispose(); + rmSync(temporary, { recursive: true, force: true }); + }); + + it('starts an instance from a route and runs its steps with the Worker env', async () => { + const started = await runtime.dispatchFetch('http://localhost/start?id=first&name=Ada'); + expect(started.status).toBe(200); + expect(await started.json()).toEqual({ id: 'first' }); + + let status: { status: string; output?: unknown } = { status: 'queued' }; + for (let attempt = 0; attempt < 100 && status.status !== 'complete'; attempt++) { + const response = await runtime.dispatchFetch('http://localhost/status?id=first'); + status = await response.json(); + if (status.status === 'errored') { + break; + } + await new Promise((resolve) => { + setTimeout(resolve, 50); + }); + } + expect(status).toMatchObject({ status: 'complete', output: { greeting: 'Hello, Ada' } }); + }); + + it('rejects invalid params before starting an instance', async () => { + const response = await runtime.dispatchFetch('http://localhost/start?id=invalid'); + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ + error: 'workflows: invalid params: name: name is required', + }); + }); +}); + +describe('convention modules without a definition default export', () => { + it.each([ + { + kind: 'workflows', + source: 'export const Welcome = 1;', + message: + 'workflows: workflows/missing.ts must default-export defineWorkflow() or defineWorkflowEntrypoint().', + }, + { + kind: 'workflows', + source: 'export default class Welcome {}', + message: + 'workflows: workflows/missing.ts must default-export defineWorkflow() or defineWorkflowEntrypoint().', + }, + { + kind: 'durable-objects', + source: 'export const Counter = 1;', + message: + 'durable: durable-objects/missing.ts must default-export defineDurableState() or defineDurableObject().', + }, + { + kind: 'durable-objects', + source: `import { defineDurableState } from ${JSON.stringify(durablePath)}; +export const Counter = defineDurableState({ initialState: 0, methods: {} });`, + message: + 'durable: durable-objects/missing.ts must default-export defineDurableState() or defineDurableObject().', + }, + ])( + 'fails Worker startup with a clear error for $kind: $source', + async ({ kind, source, message }) => { + const name = `${kind}-${Math.random().toString(36).slice(2)}`; + const definition = join(temporary, name, kind); + mkdirSync(definition, { recursive: true }); + const filePath = join(definition, 'missing.ts'); + writeFileSync(filePath, source); + const entry = { bindingName: 'MISSING', className: 'Missing', filePath }; + const output = await buildWorker( + name, + 'export default { fetch: () => new Response("ok") };', + kind === 'workflows' ? { workflows: [entry] } : { durableObjects: [entry] }, + ); + const worker = new Miniflare( + convertV4MiniflareOptions({ + compatibilityDate: '2026-07-01', + compatibilityFlags: ['nodejs_compat'], + modules: true, + modulesRoot: output, + scriptPath: join(output, 'worker.mjs'), + }), + ) as unknown as Runtime; + try { + await expect(worker.dispatchFetch('http://localhost/')).rejects.toThrow(message); + } finally { + await worker.dispose().catch(() => {}); + } + }, + 30_000, + ); +}); diff --git a/packages/void/test/unit/compile.test.ts b/packages/void/test/unit/compile.test.ts index 267e6d9bd3..517f63e490 100644 --- a/packages/void/test/unit/compile.test.ts +++ b/packages/void/test/unit/compile.test.ts @@ -857,11 +857,61 @@ describe('compileWorkerEntry', () => { ], }); - expect(code).toContain('import __voidDurableObject0 from "/app/durable-objects/counter.ts";'); + expect(code).toContain( + 'import * as __voidDurableObjectModule0 from "/app/durable-objects/counter.ts";', + ); expect(code).toContain('__voidDurableObject0.__bind("COUNTER");'); expect(code).toContain('export const CounterDurableObject = __voidDurableObject0.class;'); }); + it('re-exports Workflow modules as worker classes with their pinned names', () => { + const code = compileWorkerEntry({ + workflows: [ + { + bindingName: 'WORKFLOW_ONBOARDING', + className: 'OnboardingWorkflow', + filePath: '/app/workflows/onboarding.ts', + name: 'onboarding', + }, + ], + }); + + expect(code).toContain( + 'import * as __voidWorkflowModule0 from "/app/workflows/onboarding.ts";', + ); + expect(code).toContain('__voidWorkflow0.__bind("WORKFLOW_ONBOARDING", "onboarding");'); + expect(code).toContain('export const OnboardingWorkflow = __voidWorkflow0.class;'); + }); + + it('guards convention modules that do not default-export a definition', () => { + const code = compileWorkerEntry({ + durableObjects: [ + { + bindingName: 'COUNTER', + className: 'CounterDurableObject', + filePath: '/app/durable-objects/counter.ts', + }, + ], + workflows: [ + { + bindingName: 'WORKFLOW_ONBOARDING', + className: 'OnboardingWorkflow', + filePath: '/app/workflows/onboarding.ts', + }, + ], + }); + + expect(code).toContain( + 'if (typeof __voidDurableObject0?.__bind !== "function") { throw new Error("durable: durable-objects/counter.ts must default-export defineDurableState() or defineDurableObject()."); }', + ); + expect(code).toContain( + 'if (typeof __voidWorkflow0?.__bind !== "function") { throw new Error("workflows: workflows/onboarding.ts must default-export defineWorkflow() or defineWorkflowEntrypoint()."); }', + ); + expect(code.indexOf('typeof __voidWorkflow0?.__bind')).toBeLessThan( + code.indexOf('__voidWorkflow0.__bind('), + ); + }); + it('re-exports the live Durable Object class when enabled', () => { const code = compileWorkerEntry({ hasQueues: false, diff --git a/packages/void/test/unit/info.test.ts b/packages/void/test/unit/info.test.ts index c1474d0f4d..0a6e13c428 100644 --- a/packages/void/test/unit/info.test.ts +++ b/packages/void/test/unit/info.test.ts @@ -92,6 +92,37 @@ describe('void info', () => { expect(existsSync(join(root, '.void'))).toBe(false); }); + it('reports Workflow identities with inferred and explicit names', () => { + const root = project(); + write(root, 'workflows/send-welcome.ts', 'export default defineWorkflow({ async run() {} });'); + write( + root, + 'workflows/import-v2.ts', + `import { defineWorkflowEntrypoint } from 'void/workflows'; +export default defineWorkflowEntrypoint({ name: 'import', class: Importer });`, + ); + const info = getProjectInfo(root); + expect(info.resources).toEqual([ + { + file: 'workflows/import-v2.ts', + definition: 'defineWorkflow', + name: 'import', + nameSource: 'explicit', + className: 'ImportWorkflow', + bindingName: 'WORKFLOW_IMPORT', + }, + { + file: 'workflows/send-welcome.ts', + definition: 'defineWorkflow', + name: 'send-welcome', + nameSource: 'inferred', + className: 'SendWelcomeWorkflow', + bindingName: 'WORKFLOW_SEND_WELCOME', + }, + ]); + expect(formatProjectInfo(info)).toContain("add this to 'defineWorkflow':"); + }); + it('keeps explicit names visible after moving code and respects configured source paths', () => { const root = project(); write(root, 'void.config.ts', "export default { sourceDir: 'src' };"); diff --git a/packages/void/test/unit/plugin-inference.test.ts b/packages/void/test/unit/plugin-inference.test.ts index f053de23ff..ef8d34d157 100644 --- a/packages/void/test/unit/plugin-inference.test.ts +++ b/packages/void/test/unit/plugin-inference.test.ts @@ -761,6 +761,17 @@ describe('detectFramework', () => { 'void/durable', ), ).toThrow('void/durable is server-only'); + expect(() => + resolveId.call( + { + environment: { name: 'client' }, + error(message: string): never { + throw new Error(message); + }, + }, + 'void/workflows', + ), + ).toThrow('void/workflows is server-only'); } finally { cwd.mockRestore(); } @@ -830,8 +841,9 @@ describe('detectFramework', () => { try { voidPlugin(); const entry = readFileSync(join(root, '.void', 'entry.ts'), 'utf8'); - expect(entry).toContain('import __voidDurableObject0 from'); + expect(entry).toContain('import * as __voidDurableObjectModule0 from'); expect(entry).toContain('/durable-objects/shopping-cart.ts'); + expect(entry).toContain('const __voidDurableObject0 = __voidDurableObjectModule0.default;'); expect(entry).toContain('__voidDurableObject0.__bind("SHOPPING_CART")'); expect(entry).toContain( 'export const ShoppingCartDurableObject = __voidDurableObject0.class', @@ -841,6 +853,56 @@ describe('detectFramework', () => { } }); + it('exports convention-based Workflows from the worker entry', () => { + const root = createTempRoot(); + mkdirSync(join(root, 'routes'), { recursive: true }); + mkdirSync(join(root, 'workflows'), { recursive: true }); + writeFileSync(join(root, 'routes', 'index.ts'), 'export const GET = () => new Response("ok");'); + writeFileSync( + join(root, 'workflows', 'send-welcome.ts'), + 'export default { class: class SendWelcome {}, __bind() {} }', + ); + const cwd = vi.spyOn(process, 'cwd').mockReturnValue(root); + + try { + voidPlugin(); + const entry = readFileSync(join(root, '.void', 'entry.ts'), 'utf8'); + expect(entry).toContain('import * as __voidWorkflowModule0 from'); + expect(entry).toContain('/workflows/send-welcome.ts'); + expect(entry).toContain('__voidWorkflow0.__bind("WORKFLOW_SEND_WELCOME")'); + expect(entry).toContain('export const SendWelcomeWorkflow = __voidWorkflow0.class'); + expect(entry).toContain( + 'workflows: workflows/send-welcome.ts must default-export defineWorkflow() or defineWorkflowEntrypoint().', + ); + } finally { + cwd.mockRestore(); + } + }); + + it('rejects Workflow modules in framework adapter mode and on non-Cloudflare targets', () => { + const framework = createTempRoot(); + mkdirSync(join(framework, 'workflows'), { recursive: true }); + writeFileSync( + join(framework, 'package.json'), + JSON.stringify({ dependencies: { '@sveltejs/kit': '^2.0.0' } }), + ); + writeFileSync(join(framework, 'workflows', 'welcome.ts'), 'export default {}'); + const node = createTempRoot(); + mkdirSync(join(node, 'routes'), { recursive: true }); + mkdirSync(join(node, 'workflows'), { recursive: true }); + writeFileSync(join(node, 'void.json'), JSON.stringify({ target: 'node' })); + writeFileSync(join(node, 'workflows', 'welcome.ts'), 'export default {}'); + const cwd = vi.spyOn(process, 'cwd').mockReturnValue(framework); + + try { + expect(() => voidPlugin()).toThrow('workflows/ is currently supported in Void apps only'); + cwd.mockReturnValue(node); + expect(() => voidPlugin()).toThrow('workflows/ requires target: "cloudflare"'); + } finally { + cwd.mockRestore(); + } + }); + it('rejects typed Durable Object modules in framework adapter mode', () => { const root = createTempRoot(); mkdirSync(join(root, 'durable-objects'), { recursive: true }); diff --git a/packages/void/test/unit/workflow-runtime.test.ts b/packages/void/test/unit/workflow-runtime.test.ts new file mode 100644 index 0000000000..7455c6d1b4 --- /dev/null +++ b/packages/void/test/unit/workflow-runtime.test.ts @@ -0,0 +1,151 @@ +import { WorkflowEntrypoint } from 'cloudflare:workers'; +import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers'; +import { describe, expect, expectTypeOf, it, vi } from 'vite-plus/test'; +import { getRuntimeEnv, withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; +import { + defineWorkflow, + defineWorkflowEntrypoint, + WorkflowParamsError, +} from '../../src/runtime/workflows/index.ts'; +import type { WorkflowApi } from '../../src/runtime/workflows/index.ts'; +import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; + +vi.mock('cloudflare:workers', () => ({ + WorkflowEntrypoint: class { + protected ctx: unknown; + protected env: unknown; + constructor(ctx: unknown, env: unknown) { + this.ctx = ctx; + this.env = env; + } + }, +})); + +function binding() { + const instance = { id: 'instance' } as unknown as WorkflowInstance; + return { + instance, + workflow: { + create: vi.fn(async (_options?: unknown) => instance), + createBatch: vi.fn(async (_options: unknown) => ({ created: [instance], errors: [] })), + get: vi.fn(async (_id: string) => instance), + }, + }; +} + +/** A minimal Standard Schema for `{ userId: string }` that trims the id. */ +const userSchema: StandardSchemaV1<{ userId: string }, { userId: string }> = { + '~standard': { + version: 1, + vendor: 'test', + validate(value) { + if ( + typeof value === 'object' && + value !== null && + typeof (value as { userId?: unknown }).userId === 'string' + ) { + return { value: { userId: (value as { userId: string }).userId.trim() } }; + } + return { issues: [{ message: 'Expected a string', path: [{ key: 'userId' }] }] }; + }, + }, +}; + +describe('defineWorkflow', () => { + it('generates an entrypoint that runs inside the Worker env', async () => { + const seen: Array = []; + const Welcome = defineWorkflow({ + async run(event: WorkflowEvent<{ userId: string }>, step, context) { + seen.push(event.payload.userId, context.env.GREETING, getRuntimeEnv().GREETING); + return step.do('greet', async () => 'done'); + }, + }); + const step = { do: vi.fn(async (_name: string, fn: () => Promise) => fn()) }; + const instance = new Welcome.class({} as ExecutionContext, { GREETING: 'hello' }); + expect(instance).toBeInstanceOf(WorkflowEntrypoint); + const result = await instance.run( + { payload: { userId: 'u1' } } as WorkflowEvent<{ userId: string }>, + step as unknown as WorkflowStep, + ); + expect(result).toBe('done'); + expect(seen).toEqual(['u1', 'hello', 'hello']); + }); + + it('starts, batches, and gets instances through its convention binding', async () => { + const { workflow, instance } = binding(); + const Welcome = defineWorkflow({ + async run(_event: WorkflowEvent<{ userId: string }>) {}, + }); + await expect(Welcome.create({ params: { userId: 'u1' } })).rejects.toThrow('not bound'); + Welcome.__bind('WORKFLOW_WELCOME'); + await withRuntimeEnv({ WORKFLOW_WELCOME: workflow }, async () => { + expect(await Welcome.create({ id: 'a', params: { userId: 'u1' } })).toBe(instance); + expect(await Welcome.get('a')).toBe(instance); + await Welcome.createBatch([{ params: { userId: 'u2' } }]); + }); + expect(workflow.create).toHaveBeenCalledWith({ id: 'a', params: { userId: 'u1' } }); + expect(workflow.get).toHaveBeenCalledWith('a'); + expect(workflow.createBatch).toHaveBeenCalledWith({ + instances: [{ params: { userId: 'u2' } }], + }); + expect(() => Welcome.__bind('OTHER')).toThrow('already bound'); + }); + + it('accepts an explicit binding', async () => { + const { workflow } = binding(); + const Welcome = defineWorkflow({ async run() {} }); + await Welcome.create(workflow as unknown as Workflow, { id: 'b' }); + await Welcome.get(workflow as unknown as Workflow, 'b'); + expect(workflow.create).toHaveBeenCalledWith({ id: 'b' }); + expect(workflow.get).toHaveBeenCalledWith('b'); + }); + + it('validates and transforms params with its schema before starting', async () => { + const { workflow } = binding(); + const Welcome = defineWorkflow({ + params: userSchema, + async run(event) { + expectTypeOf(event.payload).toEqualTypeOf>(); + }, + }); + Welcome.__bind('WORKFLOW_WELCOME'); + await withRuntimeEnv({ WORKFLOW_WELCOME: workflow }, async () => { + await Welcome.create({ params: { userId: ' u1 ' } }); + const invalid = Welcome.create({ params: { userId: 1 as unknown as string } }); + await expect(invalid).rejects.toBeInstanceOf(WorkflowParamsError); + await expect(invalid).rejects.toThrow('workflows: invalid params: userId: Expected a string'); + await expect(Welcome.create()).rejects.toThrow('invalid params'); + await expect( + Welcome.createBatch([{ params: { userId: 'ok' } }, { params: {} as { userId: string } }]), + ).rejects.toThrow('invalid params'); + }); + expect(workflow.create).toHaveBeenCalledTimes(1); + expect(workflow.create).toHaveBeenCalledWith({ params: { userId: 'u1' } }); + expect(workflow.createBatch).not.toHaveBeenCalled(); + }); + + it('rejects a runtime identity that differs from static analysis and invalid names', () => { + const Welcome = defineWorkflow({ name: 'welcome', async run() {} }); + expect(() => Welcome.__bind('WORKFLOW_WELCOME', 'other')).toThrow('statically discoverable'); + expect(() => defineWorkflow({ name: '123', async run() {} })).toThrow('name must contain'); + }); +}); + +describe('defineWorkflowEntrypoint', () => { + it('keeps the native class and infers params from its run annotation', async () => { + class Importer extends WorkflowEntrypoint, { file: string }> { + override async run(_event: Readonly>, _step: WorkflowStep) { + return 'imported'; + } + } + const { workflow } = binding(); + const Import = defineWorkflowEntrypoint({ name: 'import', class: Importer }); + expect(Import.class).toBe(Importer); + Import.__bind('WORKFLOW_IMPORT', 'import'); + await withRuntimeEnv({ WORKFLOW_IMPORT: workflow }, () => + Import.create({ params: { file: 'a.csv' } }), + ); + expectTypeOf(Import).toEqualTypeOf>(); + expect(workflow.create).toHaveBeenCalledWith({ params: { file: 'a.csv' } }); + }); +}); diff --git a/packages/void/test/unit/workflow-scan.test.ts b/packages/void/test/unit/workflow-scan.test.ts new file mode 100644 index 0000000000..85da6f867b --- /dev/null +++ b/packages/void/test/unit/workflow-scan.test.ts @@ -0,0 +1,165 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { toSlash } from 'pathslash'; +import { afterEach, describe, expect, it } from 'vite-plus/test'; +import { planWorkflowAdditions } from '../../src/workflows/config.ts'; +import { assertNoWorkflowsForPlatform } from '../../src/workflows/platform.ts'; +import { + cloudflareWorkflowName, + deriveWorkflowResourceIdentity, + scanWorkflowModules, +} from '../../src/workflows/scan.ts'; + +const roots: Array = []; + +function createRoot(files: Record): string { + const root = mkdtempSync(join(tmpdir(), 'void-workflow-scan-')); + roots.push(root); + mkdirSync(join(root, 'workflows')); + for (const [filename, source] of Object.entries(files)) { + mkdirSync(dirname(join(root, 'workflows', filename)), { recursive: true }); + writeFileSync(join(root, 'workflows', filename), source); + } + return root; +} + +afterEach(() => { + for (const root of roots.splice(0)) { + rmSync(root, { recursive: true, force: true }); + } +}); + +describe('scanWorkflowModules', () => { + it('returns nothing without a workflows directory', () => { + const root = mkdtempSync(join(tmpdir(), 'void-workflow-scan-')); + roots.push(root); + expect(scanWorkflowModules(root)).toEqual([]); + expect(() => assertNoWorkflowsForPlatform(root)).not.toThrow(); + }); + + it('derives binding, class, and resource names from filenames', () => { + const root = createRoot({ 'send-welcome.ts': 'export default {}', 'types.d.ts': '' }); + expect(scanWorkflowModules(root)).toEqual([ + { + filePath: toSlash(join(root, 'workflows', 'send-welcome.ts')), + relativePath: 'send-welcome.ts', + bindingName: 'WORKFLOW_SEND_WELCOME', + className: 'SendWelcomeWorkflow', + resourceName: 'send-welcome', + }, + ]); + }); + + it('joins nested directories into the name, as queues do', () => { + const root = createRoot({ 'order/notifications.ts': 'export default {}' }); + expect(scanWorkflowModules(root)).toEqual([ + { + filePath: toSlash(join(root, 'workflows', 'order', 'notifications.ts')), + relativePath: 'order/notifications.ts', + bindingName: 'WORKFLOW_ORDER_NOTIFICATIONS', + className: 'OrderNotificationsWorkflow', + resourceName: 'order-notifications', + }, + ]); + }); + + it('ignores files and directories starting with an underscore', () => { + const root = createRoot({ + 'welcome.ts': 'export default {}', + '_steps.ts': 'export const send = () => {};', + '_lib/email.ts': 'export const send = () => {};', + 'order/_shared.ts': 'export const total = 0;', + }); + expect(scanWorkflowModules(root).map((module) => module.relativePath)).toEqual(['welcome.ts']); + }); + + it('rejects a nested path and a file that produce the same name', () => { + const root = createRoot({ + 'order/notifications.ts': 'export default {}', + 'order-notifications.ts': 'export default {}', + }); + expect(() => scanWorkflowModules(root)).toThrow('duplicate generated name'); + }); + + it('reads a static name through aliased imports without evaluating the module', () => { + const root = createRoot({ + 'renamed.ts': `import { defineWorkflowEntrypoint as workflow } from 'void/workflows'; + const name = 'nightly-import'; + export default workflow({ name, class: Importer });`, + }); + expect(scanWorkflowModules(root)[0]).toMatchObject({ + name: 'nightly-import', + ...deriveWorkflowResourceIdentity('nightly-import'), + }); + }); + + it('rejects files that normalize to the same generated names', () => { + const root = createRoot({ + 'send-welcome.ts': 'export default {}', + 'send_welcome.ts': 'export default {}', + }); + expect(() => scanWorkflowModules(root)).toThrow('duplicate generated name'); + }); + + it('rejects Void platform deploys while workflows exist', () => { + const root = createRoot({ 'welcome.ts': 'export default {}' }); + expect(() => assertNoWorkflowsForPlatform(root)).toThrow('void deploy --platform cloudflare'); + }); +}); + +describe('Cloudflare Workflow names', () => { + it('prefixes the account-scoped name with the Worker name', () => { + expect(cloudflareWorkflowName('welcome', 'My_App')).toBe('my-app-welcome'); + expect(cloudflareWorkflowName('welcome')).toBe('welcome'); + expect(cloudflareWorkflowName('w'.repeat(80), 'app')).toHaveLength(64); + }); + + it('adds only unconfigured modules and keeps an authored entry for the same class', () => { + const modules = [ + deriveWorkflowResourceIdentity('welcome'), + deriveWorkflowResourceIdentity('import'), + ]; + const authored = { + name: 'pinned-welcome', + binding: 'WORKFLOW_WELCOME', + class_name: 'WelcomeWorkflow', + }; + expect(planWorkflowAdditions([authored], modules, 'app')).toEqual([ + { name: 'app-import', binding: 'WORKFLOW_IMPORT', class_name: 'ImportWorkflow' }, + ]); + expect(planWorkflowAdditions([], [], 'app')).toEqual([]); + }); + + it('rejects a binding retargeted to another class or Worker, and a taken name', () => { + const modules = [deriveWorkflowResourceIdentity('welcome')]; + expect(() => + planWorkflowAdditions( + [{ name: 'x', binding: 'WORKFLOW_WELCOME', class_name: 'Other' }], + modules, + 'app', + ), + ).toThrow("binding 'WORKFLOW_WELCOME' is already configured"); + expect(() => + planWorkflowAdditions( + [ + { + name: 'x', + binding: 'WORKFLOW_WELCOME', + class_name: 'WelcomeWorkflow', + script_name: 'other-worker', + }, + ], + modules, + 'app', + ), + ).toThrow("binding 'WORKFLOW_WELCOME' is already configured"); + expect(() => + planWorkflowAdditions( + [{ name: 'app-welcome', binding: 'MINE', class_name: 'Mine' }], + modules, + 'app', + ), + ).toThrow("Workflow name 'app-welcome' is already configured for binding 'MINE'"); + }); +}); diff --git a/packages/void/vite.config.ts b/packages/void/vite.config.ts index a1773edb58..4d78ef3512 100644 --- a/packages/void/vite.config.ts +++ b/packages/void/vite.config.ts @@ -104,6 +104,7 @@ export default defineConfig({ 'src/runtime/db/postgres.ts', 'src/runtime/db/mysql.ts', 'src/runtime/durable/index.ts', + 'src/runtime/workflows/index.ts', 'src/runtime/db/seed.ts', 'src/runtime/db/validators/drizzle-zod.ts', 'src/runtime/db/validators/drizzle-valibot.ts', From aafcfd64e32a48b4f82d1b6ec5b245fa33e37ffb Mon Sep 17 00:00:00 2001 From: Isak Gustavsen Date: Wed, 25 Nov 2026 01:13:36 +0100 Subject: [PATCH 2/7] fix(void): infer bindings from workflows/ modules Resource imports used only inside workflows/, including _-prefixed step helpers and nested folders, now count toward binding inference, as they already do for durable-objects/. Apps with a sourceDir scan workflows/ too. Co-Authored-By: Claude Opus 5.5 --- docs/reference/resource-inference.md | 2 +- packages/void/src/plugin-inference.ts | 4 +++- .../void/test/unit/plugin-inference.test.ts | 18 ++++++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/docs/reference/resource-inference.md b/docs/reference/resource-inference.md index 13407199dc..8cfdaa0967 100644 --- a/docs/reference/resource-inference.md +++ b/docs/reference/resource-inference.md @@ -71,7 +71,7 @@ Regardless of mode, these are always checked: - **SSR entry** such as `src/main.ssr.ts`, for SSR apps that access bindings during rendering - **Application source** in `src/` or your configured `sourceDir`, including resource and auth imports - **`durable-objects/`**, which is scanned for typed Durable Object state modules in native Void apps -- **`workflows/`**, which is scanned for Workflow modules in native Void apps +- **`workflows/`**, which is scanned for Workflow modules and the resources they use in native Void apps ## Custom Scan Directories diff --git a/packages/void/src/plugin-inference.ts b/packages/void/src/plugin-inference.ts index c3ec28f2ca..e6c51e6d81 100644 --- a/packages/void/src/plugin-inference.ts +++ b/packages/void/src/plugin-inference.ts @@ -58,6 +58,7 @@ export const DEFAULT_SCAN_DIRS = [ 'crons', 'email', 'durable-objects', + 'workflows', 'src', ] as const; @@ -152,7 +153,8 @@ export function inferProjectBindings( ): InferredBindings { const paths = options?.paths ?? readProjectPaths(root); const dirs = - scanDirs ?? (paths.sourceDir ? [paths.sourceDir, 'durable-objects'] : DEFAULT_SCAN_DIRS); + scanDirs ?? + (paths.sourceDir ? [paths.sourceDir, 'durable-objects', 'workflows'] : DEFAULT_SCAN_DIRS); const allBindings: Array = []; const scannedFiles = new Set(); const routesPrefix = `${toSlash(paths.routesDir).replace(/\/$/, '')}/`; diff --git a/packages/void/test/unit/plugin-inference.test.ts b/packages/void/test/unit/plugin-inference.test.ts index ef8d34d157..4783d11f9f 100644 --- a/packages/void/test/unit/plugin-inference.test.ts +++ b/packages/void/test/unit/plugin-inference.test.ts @@ -378,6 +378,24 @@ describe('inferProjectBindings', () => { }); }); + it('infers resources used only by Workflow modules and their helpers', () => { + const root = createTempRoot(); + mkdirSync(join(root, 'workflows', 'order'), { recursive: true }); + writeFileSync( + join(root, 'workflows', '_storage.ts'), + `import { createStorage } from 'void/storage'; + export const files = (env) => createStorage(env.STORAGE);`, + ); + writeFileSync( + join(root, 'workflows', 'order', 'summary.ts'), + `import { createAi } from 'void/ai'; + export const ai = (env) => createAi(env);`, + ); + expect(inferProjectBindings(root)).toMatchObject({ needsAI: true, needsR2: true }); + writeFileSync(join(root, 'void.json'), JSON.stringify({ sourceDir: 'src' })); + expect(inferProjectBindings(root)).toMatchObject({ needsAI: true, needsR2: true }); + }); + it('detects live from a stream module outside the default directories only when scanned', () => { const root = createTempRoot(); mkdirSync(join(root, 'routes'), { recursive: true }); From 1d72f3a8f1be3515b459c78cb7b166d7f1fc4ddd Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Tue, 1 Dec 2026 09:17:31 +0900 Subject: [PATCH 3/7] Fix Workflow deployment and payload contracts. --- docs/guide/workflows.md | 6 +- docs/reference/api/workflows.md | 2 + packages/void/src/application-analysis.ts | 11 +++- .../src/cli/cloudflare-deploy/classify.ts | 2 +- .../void/src/cli/deploy-binding-snapshot.ts | 2 +- .../src/cli/deploy-cloudflare-preflight.ts | 14 ++--- .../void/src/cli/deploy-cloudflare-static.ts | 3 +- packages/void/src/cli/preset.ts | 10 +++- packages/void/src/index.ts | 5 +- packages/void/src/plugin-cloudflare-config.ts | 2 +- packages/void/src/plugin-inference.ts | 12 ++-- packages/void/src/runtime/workflows/index.ts | 13 ++-- .../void/src/shared/resource-definition.ts | 10 ++-- packages/void/src/workflows/scan.ts | 49 ++++++++------- .../test/unit/cloudflare-classify.test.ts | 40 +++++++++++++ packages/void/test/unit/info.test.ts | 6 +- .../void/test/unit/plugin-inference.test.ts | 32 ++++++++-- .../void/test/unit/workflow-runtime.test.ts | 1 + .../test/unit/workflow-runtime.typecheck.ts | 29 +++++++++ packages/void/test/unit/workflow-scan.test.ts | 59 +++++++++++++++---- 20 files changed, 239 insertions(+), 69 deletions(-) create mode 100644 packages/void/test/unit/workflow-runtime.typecheck.ts diff --git a/docs/guide/workflows.md b/docs/guide/workflows.md index 90cc4617f5..0b44273231 100644 --- a/docs/guide/workflows.md +++ b/docs/guide/workflows.md @@ -33,7 +33,7 @@ export default Onboarding; Default-export the object returned by `defineWorkflow()`. Named-export it too so routes can import it. -TypeScript and JavaScript files are supported. Subdirectories are scanned too, and files or directories starting with `_` are ignored, so keep shared step helpers in files such as `workflows/_email.ts`. +TypeScript and JavaScript files are supported, including subdirectories. Void discovers default exports created using a helper imported from `void/workflows`. Files and directories starting with `_` are excluded from Workflow discovery. `run` receives: @@ -56,7 +56,7 @@ export const POST = defineHandler(async () => { }); ``` -`create()` accepts the same options as Cloudflare's [`Workflow.create()`](https://developers.cloudflare.com/workflows/build/workers-api/#create), such as `id` and `retention`. Its `params` are typed from your definition. Use `createBatch()` to start up to 100 instances at once. +`create()` accepts the same options as Cloudflare's [`Workflow.create()`](https://developers.cloudflare.com/workflows/build/workers-api/#create), such as `id` and `retention`. Use `createBatch()` to start up to 100 instances at once. Both methods require `params` when your definition requires a payload. Check on an instance with `get()`: @@ -155,6 +155,8 @@ export default defineConfig({ }); ``` +If the generated Cloudflare Workflow name exceeds 64 characters, use this entry to give it a shorter name. + ## Deployment support Workflows are available on the Workers Free plan, within [Cloudflare's Workflows limits](https://developers.cloudflare.com/workflows/reference/limits/). Deploy to your own Cloudflare account with `void deploy --platform cloudflare`. diff --git a/docs/reference/api/workflows.md b/docs/reference/api/workflows.md index e45f14e55c..174765ecce 100644 --- a/docs/reference/api/workflows.md +++ b/docs/reference/api/workflows.md @@ -25,6 +25,8 @@ function defineWorkflow(definition: { With `params`, `run` receives the schema's output type and `create()` accepts its input type. Without it, the params type comes from the `event` annotation. +When the params type requires a payload, pass `params` to `create()` and to every entry in `createBatch()`. + ## `defineWorkflowEntrypoint(definition)` {#defineworkflowentrypoint-definition} Registers a class that extends Cloudflare's `WorkflowEntrypoint` without changing it. The params type is read from the class's `run(event)` annotation. diff --git a/packages/void/src/application-analysis.ts b/packages/void/src/application-analysis.ts index 674f00d335..fbbee8845e 100644 --- a/packages/void/src/application-analysis.ts +++ b/packages/void/src/application-analysis.ts @@ -80,6 +80,7 @@ export async function getNativeWorkerSourceFiles( ...analysis.queues.map(({ filePath }) => join(paths.queuesDir, filePath)), ...emailFiles.map((filePath) => join(paths.emailDir, filePath)), ...analysis.durableObjects.map(({ filePath }) => filePath), + ...analysis.workflows.map(({ filePath }) => filePath), ...(envFile !== null ? [envFile] : []), ]; } @@ -96,10 +97,17 @@ export function analyzeApplicationSync( const { config, environment } = options; const paths = resolveProjectPaths(root, config); const framework = detectFramework(root); + const workflows = scanWorkflowModules(root); const scanDirs = config.inference?.scanDirs ?? (framework ? FRAMEWORK_SCAN_DIRS : undefined); const inferred = inferProjectBindings( root, - { paths, environment, filterPages: !framework, bindings: config.inference?.bindings }, + { + paths, + environment, + filterPages: !framework, + bindings: config.inference?.bindings, + hasWorkflows: workflows.length > 0, + }, scanDirs, ); const authConfigPath = findVoidAuthConfig(root, paths); @@ -119,7 +127,6 @@ export function analyzeApplicationSync( ); // Typed durable modules currently use the root convention on every target. const durableObjects = scanDurableObjectModules(root); - const workflows = scanWorkflowModules(root); const email = scanEmailHandlersSync(paths.sourceRoot); const overrides = config.inference?.bindings; const bindingReason = ( diff --git a/packages/void/src/cli/cloudflare-deploy/classify.ts b/packages/void/src/cli/cloudflare-deploy/classify.ts index 37ed4c1bcf..468c535e4c 100644 --- a/packages/void/src/cli/cloudflare-deploy/classify.ts +++ b/packages/void/src/cli/cloudflare-deploy/classify.ts @@ -78,7 +78,7 @@ export function classifyCloudflareDeployApp( [ 'deploy: --platform cloudflare found no Void backend to deploy.', 'A full Void app has at least one of: routes/, pages/, middleware, crons/, queues/,', - 'email/, or an SSR entry. Add your server code, or use `void deploy` for a static site.', + 'email/, workflows/, or an SSR entry. Add your server code, or use `void deploy` for a static site.', ].join('\n'), ); } diff --git a/packages/void/src/cli/deploy-binding-snapshot.ts b/packages/void/src/cli/deploy-binding-snapshot.ts index c92f1e6039..6d5459bec8 100644 --- a/packages/void/src/cli/deploy-binding-snapshot.ts +++ b/packages/void/src/cli/deploy-binding-snapshot.ts @@ -291,7 +291,6 @@ type DurableObjectSnapshot = { migrations: Array>; }; -/** Reconstruct the Durable Object state emitted after the pre-build root config is synced. */ /** * The exact `workflows` entries the build should emit: the root config's, plus one * per `workflows/` module that the root config does not already bind. @@ -308,6 +307,7 @@ export function reconstructExpectedWorkflows( return [...configured, ...planWorkflowAdditions(configured, modules, workerName)]; } +/** Reconstruct the Durable Object state emitted after the pre-build root config is synced. */ export function reconstructExpectedDurableObjectState( config: VoidConfig, root: string, diff --git a/packages/void/src/cli/deploy-cloudflare-preflight.ts b/packages/void/src/cli/deploy-cloudflare-preflight.ts index 2c7e98f3f4..fb2cc9859d 100644 --- a/packages/void/src/cli/deploy-cloudflare-preflight.ts +++ b/packages/void/src/cli/deploy-cloudflare-preflight.ts @@ -290,6 +290,13 @@ export async function preflightCloudflareWorker(input: { } = connection; rootConfig = connection.rootConfig; const workerName = readWranglerTopLevelString(rootConfig, 'name') ?? deriveWorkerName(root); + const expectedWorkflows = reconstructExpectedWorkflows( + voidConfig, + root, + rootConfig, + workerName, + source.analysis, + ); printDeployContext(workerName, 'Cloudflare'); // Email setup makes credentialed calls, so it runs before the env-schema probe runs any @@ -693,13 +700,6 @@ export async function preflightCloudflareWorker(input: { preBuildRootConfig, { needsSandbox, needsLive, analysis: source.analysis }, ); - const expectedWorkflows = reconstructExpectedWorkflows( - voidConfig, - root, - preBuildRootConfig, - workerName, - source.analysis, - ); return { apiBaseUrl, complianceRegion, diff --git a/packages/void/src/cli/deploy-cloudflare-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index c80083a88e..0ffbeeae99 100644 --- a/packages/void/src/cli/deploy-cloudflare-static.ts +++ b/packages/void/src/cli/deploy-cloudflare-static.ts @@ -257,7 +257,8 @@ export async function resolveCloudflareVoidStaticPreset( hasLive: bindings.needsLive === true, }) || analysis.jobs.length > 0 || - analysis.queues.length > 0; + analysis.queues.length > 0 || + analysis.workflows.length > 0; if (hasRuntimeBackend) { return null; } diff --git a/packages/void/src/cli/preset.ts b/packages/void/src/cli/preset.ts index 5e82b3c7d8..f1d09da8f1 100644 --- a/packages/void/src/cli/preset.ts +++ b/packages/void/src/cli/preset.ts @@ -9,6 +9,7 @@ import { readPackageJson, } from '../shared/package-json.ts'; import { getSsrServerEntryPath, hasSsrEntry } from '../ssr/entry.ts'; +import { scanWorkflowModules } from '../workflows/scan.ts'; import { viteConfigImportsVoidPlugin } from './vite-config-patch.ts'; import { findWorkspaceMemberRoot, parsePackageManagerField } from './workspace.ts'; import type { PackageManager } from './workspace.ts'; @@ -471,6 +472,9 @@ export function findBackendSources(root: string): Array { if (ssrEntry) { found.push(relative(root, ssrEntry)); } + if (scanWorkflowModules(root).length > 0) { + found.push('workflows/'); + } return found; } @@ -479,7 +483,11 @@ export function findBackendSources(root: string): Array { */ export function hasBackendFiles(root: string): boolean { const paths = readProjectPaths(root); - return backendDirs(paths).some((dir) => existsSync(dir)) || hasSsrEntry(root, paths); + return ( + backendDirs(paths).some((dir) => existsSync(dir)) || + hasSsrEntry(root, paths) || + scanWorkflowModules(root).length > 0 + ); } function backendDirs(paths: ProjectPaths): Array { diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index f3e477b189..0f5f8e2a9a 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -608,7 +608,10 @@ export function voidPlugin(options?: { name: 'void:binding-watch', apply: 'serve', configureServer(server) { - const effectiveDirs = scanDirs ?? DEFAULT_SCAN_DIRS; + const effectiveDirs = scanDirs ?? [ + ...DEFAULT_SCAN_DIRS, + ...(workflows.length > 0 ? ['workflows'] : []), + ]; const watchDirs = [...new Set([...effectiveDirs, 'src'])].map((d) => join(root, d)); let hintShown = false; const check = (path: string) => { diff --git a/packages/void/src/plugin-cloudflare-config.ts b/packages/void/src/plugin-cloudflare-config.ts index bf873b7313..01a3e32d17 100644 --- a/packages/void/src/plugin-cloudflare-config.ts +++ b/packages/void/src/plugin-cloudflare-config.ts @@ -94,7 +94,6 @@ export function mergeCloudflareConfig(patch: object, fallback: object): WorkerCo return result; } -/** Translate Void's Wrangler-shaped settings to the configuration that the Cloudflare plugin takes. */ /** The Worker name a Void app gets when its config does not set one: its package or directory name. */ export function defaultCloudflareWorkerName(root: string): string { const packagePath = join(root, 'package.json'); @@ -110,6 +109,7 @@ export function defaultCloudflareWorkerName(root: string): string { ); } +/** Translate Void's Wrangler-shaped settings to the configuration that the Cloudflare plugin takes. */ export function toNativeCloudflareConfig(raw: WorkerConfig, root: string): CloudflareConfig { const name = defaultCloudflareWorkerName(root); const { env, vars, ...base } = raw; diff --git a/packages/void/src/plugin-inference.ts b/packages/void/src/plugin-inference.ts index c856ea513d..c9922cac66 100644 --- a/packages/void/src/plugin-inference.ts +++ b/packages/void/src/plugin-inference.ts @@ -17,6 +17,7 @@ import { isWebSocketPatternFile } from './router/websocket.ts'; import { conventionFileGlobs, isRouteFile } from './shared/convention-files.ts'; import { deriveFromSource } from './shared/source-analysis-cache.ts'; import { getSsrServerEntryPath } from './ssr/entry.ts'; +import { scanWorkflowModules } from './workflows/scan.ts'; const SOURCE_GLOB = '**/*.{ts,tsx,mts,js,jsx,mjs,astro}'; @@ -58,7 +59,6 @@ export const DEFAULT_SCAN_DIRS = [ 'crons', 'email', 'durable-objects', - 'workflows', 'src', ] as const; @@ -119,6 +119,8 @@ export type InferenceOptions = { environment?: RouteEnvironment; /** Also filter Void page files and their `.server` companions by environment. Off for framework apps. */ filterPages?: boolean; + /** Whether the application has a Workflow definition and its convention directory is active. */ + hasWorkflows?: boolean; }; function extractAstroFrontmatter(code: string): string { @@ -152,9 +154,11 @@ export function inferProjectBindings( scanDirs?: ReadonlyArray, ): InferredBindings { const paths = options?.paths ?? readProjectPaths(root); - const dirs = - scanDirs ?? - (paths.sourceDir ? [paths.sourceDir, 'durable-objects', 'workflows'] : DEFAULT_SCAN_DIRS); + const hasWorkflows = options?.hasWorkflows ?? scanWorkflowModules(root).length > 0; + const dirs = scanDirs ?? [ + ...(paths.sourceDir ? [paths.sourceDir, 'durable-objects'] : DEFAULT_SCAN_DIRS), + ...(hasWorkflows ? ['workflows'] : []), + ]; const allBindings: Array = []; const scannedFiles = new Set(); const routesPrefix = `${toSlash(paths.routesDir).replace(/\/$/, '')}/`; diff --git a/packages/void/src/runtime/workflows/index.ts b/packages/void/src/runtime/workflows/index.ts index 6aeba30ed0..0bb3896487 100644 --- a/packages/void/src/runtime/workflows/index.ts +++ b/packages/void/src/runtime/workflows/index.ts @@ -25,17 +25,20 @@ export type WorkflowContext = { }; /** Options for starting one Workflow instance. */ -export type WorkflowCreateOptions = Omit & { - params?: TParams; -}; +export type WorkflowCreateOptions = Omit & + (undefined extends TParams ? { params?: TParams } : { params: TParams }); + +type WorkflowCreateArguments = undefined extends TParams + ? [options?: WorkflowCreateOptions] + : [options: WorkflowCreateOptions]; export type WorkflowApi = { class: TClass; /** @internal Called by Void's generated Worker entry. */ __bind(bindingName: string, resourceName?: string): void; /** Start a new instance. Params are validated when the definition has a `params` schema. */ - create(options?: WorkflowCreateOptions): Promise; - create(binding: Workflow, options?: WorkflowCreateOptions): Promise; + create(...args: WorkflowCreateArguments): Promise; + create(binding: Workflow, ...args: WorkflowCreateArguments): Promise; /** Start up to 100 instances. Each instance's params are validated first. */ createBatch( instances: ReadonlyArray>, diff --git a/packages/void/src/shared/resource-definition.ts b/packages/void/src/shared/resource-definition.ts index 7e85aeb92a..b43dbc5bda 100644 --- a/packages/void/src/shared/resource-definition.ts +++ b/packages/void/src/shared/resource-definition.ts @@ -22,6 +22,7 @@ export function readResourceDefinition( filename: string, source: string, helpers: ReadonlySet, + options?: { requireImportedHelper?: boolean }, ): { helper: string; options?: AstNode; name?: string } | null { let program: AstProgram; try { @@ -176,7 +177,8 @@ export function readResourceDefinition( let helper: string | undefined; if (isIdentifier(callee)) { helper = - importedHelpers.get(callee.name) ?? (helpers.has(callee.name) ? callee.name : undefined); + importedHelpers.get(callee.name) ?? + (!options?.requireImportedHelper && helpers.has(callee.name) ? callee.name : undefined); } else if (isMemberExpression(callee) && isIdentifier(callee.object)) { const property = !callee.computed && isIdentifier(callee.property) @@ -193,7 +195,7 @@ export function readResourceDefinition( if (!helper) { return null; } - const options = resolve(call.arguments?.[0]); - const name = readName(options).value; - return { helper, options, ...(name === undefined ? {} : { name }) }; + const definitionOptions = resolve(call.arguments?.[0]); + const name = readName(definitionOptions).value; + return { helper, options: definitionOptions, ...(name === undefined ? {} : { name }) }; } diff --git a/packages/void/src/workflows/scan.ts b/packages/void/src/workflows/scan.ts index 7385175f33..74cb392448 100644 --- a/packages/void/src/workflows/scan.ts +++ b/packages/void/src/workflows/scan.ts @@ -1,8 +1,9 @@ -import { existsSync, readFileSync } from 'node:fs'; +import { existsSync } from 'node:fs'; import { join } from 'pathslash'; import { globSync } from 'tinyglobby'; import { readResourceDefinition } from '../shared/resource-definition.ts'; import { resourceNameWords } from '../shared/resource-name.ts'; +import { deriveFromSource } from '../shared/source-analysis-cache.ts'; export type WorkflowModule = { filePath: string; @@ -43,11 +44,9 @@ function listWorkflowFiles(directory: string): Array { .sort((a, b) => a.localeCompare(b)); } -export function deriveWorkflowResourceIdentity(name: string): { - bindingName: string; - className: string; - resourceName: string; -} { +export function deriveWorkflowResourceIdentity( + name: string, +): Pick { const parts = resourceNameWords(name); const classBase = parts.map((part) => part[0].toUpperCase() + part.slice(1)).join(''); return { @@ -63,11 +62,14 @@ export function deriveWorkflowResourceIdentity(name: string): { * uses the resource name alone. */ export function cloudflareWorkflowName(resourceName: string, workerName?: string): string { - if (!workerName) { - return resourceName; + const prefix = workerName?.toLowerCase().replaceAll('_', '-'); + const name = prefix ? `${prefix}-${resourceName}` : resourceName; + if (name.length > 64) { + throw new Error( + `workflows: generated Workflow name '${name}' exceeds Cloudflare's limit of 64 characters. Choose a shorter name in cloudflare.workflows.`, + ); } - const prefix = workerName.toLowerCase().replaceAll('_', '-'); - return `${prefix}-${resourceName}`.slice(0, 64); + return name; } export function scanWorkflowModules(root: string): Array { @@ -76,24 +78,27 @@ export function scanWorkflowModules(root: string): Array { return []; } - const modules = listWorkflowFiles(directory).map((relativePath) => { + const modules = listWorkflowFiles(directory).flatMap((relativePath) => { const filePath = join(directory, relativePath); - const definition = readResourceDefinition( - filePath, - readFileSync(filePath, 'utf8'), - WORKFLOW_HELPERS, + const definition = deriveFromSource(filePath, 'workflow-definition', (source) => + readResourceDefinition(filePath, source, WORKFLOW_HELPERS, { requireImportedHelper: true }), ); - const name = definition?.name; + if (!definition) { + return []; + } + const { name } = definition; const resourceName = name ?? inferWorkflowResourceName(relativePath); if (resourceNameWords(resourceName).length === 0) { throw new Error(`workflows: cannot derive a name from workflows/${relativePath}.`); } - return { - filePath, - relativePath, - ...deriveWorkflowResourceIdentity(resourceName), - ...(name === undefined ? {} : { name }), - }; + return [ + { + filePath, + relativePath, + ...deriveWorkflowResourceIdentity(resourceName), + ...(name === undefined ? {} : { name }), + }, + ]; }); const bindings = new Set(); diff --git a/packages/void/test/unit/cloudflare-classify.test.ts b/packages/void/test/unit/cloudflare-classify.test.ts index bdecd37f1b..13bac71d7c 100644 --- a/packages/void/test/unit/cloudflare-classify.test.ts +++ b/packages/void/test/unit/cloudflare-classify.test.ts @@ -5,6 +5,10 @@ import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; import { analyzeApplicationSync } from '../../src/application-analysis.ts'; import { classifyCloudflareDeployApp } from '../../src/cli/cloudflare-deploy/classify.ts'; import type { CloudflareDeployAppOptions } from '../../src/cli/cloudflare-deploy/classify.ts'; +import { + resolveCloudflareStaticPreset, + resolveCloudflareVoidStaticPreset, +} from '../../src/cli/deploy-cloudflare-static.ts'; import { syncWranglerDurableObjects } from '../../src/cli/wrangler.ts'; import type { VoidConfig } from '../../src/config.ts'; @@ -29,6 +33,42 @@ afterEach(() => { }); describe('classifyCloudflareDeployApp', () => { + it('selects a Worker for an app whose only backend is a Workflow', () => { + const root = mkdtempSync(join(tmpdir(), 'void-cloudflare-classify-')); + roots.push(root); + writeFileSync(join(root, 'package.json'), JSON.stringify({ devDependencies: { vite: '*' } })); + mkdirSync(join(root, 'workflows')); + writeFileSync( + join(root, 'workflows', 'onboarding.ts'), + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });", + ); + + expect(resolveCloudflareStaticPreset(root, {}, {})).toBeNull(); + expect(classify(root, {})).toEqual({ supported: true }); + expect(classify(root, { inference: { appType: 'void' } })).toEqual({ supported: true }); + }); + + it('keeps the full Worker when Pages are prerendered and a Workflow is declared', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-cloudflare-classify-')); + roots.push(root); + mkdirSync(join(root, 'pages')); + writeFileSync( + join(root, 'pages', 'index.tsx'), + 'export default function Page() { return null; }', + ); + const config = { output: 'static' } satisfies VoidConfig; + expect(await resolveCloudflareVoidStaticPreset(root, config)).toMatchObject({ + appType: 'static', + }); + + mkdirSync(join(root, 'workflows')); + writeFileSync( + join(root, 'workflows', 'onboarding.ts'), + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });", + ); + expect(await resolveCloudflareVoidStaticPreset(root, config)).toBeNull(); + }); + it('accepts a SvelteKit project whose routes live under src/routes', () => { const root = mkdtempSync(join(tmpdir(), 'void-cloudflare-classify-')); roots.push(root); diff --git a/packages/void/test/unit/info.test.ts b/packages/void/test/unit/info.test.ts index 0a6e13c428..108c132434 100644 --- a/packages/void/test/unit/info.test.ts +++ b/packages/void/test/unit/info.test.ts @@ -94,7 +94,11 @@ describe('void info', () => { it('reports Workflow identities with inferred and explicit names', () => { const root = project(); - write(root, 'workflows/send-welcome.ts', 'export default defineWorkflow({ async run() {} });'); + write( + root, + 'workflows/send-welcome.ts', + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });", + ); write( root, 'workflows/import-v2.ts', diff --git a/packages/void/test/unit/plugin-inference.test.ts b/packages/void/test/unit/plugin-inference.test.ts index 3766999799..b6ecceb035 100644 --- a/packages/void/test/unit/plugin-inference.test.ts +++ b/packages/void/test/unit/plugin-inference.test.ts @@ -389,13 +389,29 @@ describe('inferProjectBindings', () => { writeFileSync( join(root, 'workflows', 'order', 'summary.ts'), `import { createAi } from 'void/ai'; - export const ai = (env) => createAi(env);`, + import { defineWorkflow } from 'void/workflows'; + import { files } from '../_storage'; + export default defineWorkflow({ async run(event, step, { env }) { + const storage = files(env); + const ai = createAi(env); + } });`, ); expect(inferProjectBindings(root)).toMatchObject({ needsAI: true, needsR2: true }); writeFileSync(join(root, 'void.json'), JSON.stringify({ sourceDir: 'src' })); expect(inferProjectBindings(root)).toMatchObject({ needsAI: true, needsR2: true }); }); + it('does not infer bindings from an unrelated workflows directory', () => { + const root = createTempRoot(); + mkdirSync(join(root, 'workflows')); + writeFileSync( + join(root, 'workflows', '_maintenance.ts'), + "import { db } from 'void/db'; export const maintenance = () => db;", + ); + + expect(inferProjectBindings(root).needsD1).toBe(false); + }); + it('detects live from a stream module outside the default directories only when scanned', () => { const root = createTempRoot(); mkdirSync(join(root, 'routes'), { recursive: true }); @@ -885,7 +901,7 @@ describe('detectFramework', () => { writeFileSync(join(root, 'routes', 'index.ts'), 'export const GET = () => new Response("ok");'); writeFileSync( join(root, 'workflows', 'send-welcome.ts'), - 'export default { class: class SendWelcome {}, __bind() {} }', + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });", ); const cwd = vi.spyOn(process, 'cwd').mockReturnValue(root); @@ -911,15 +927,23 @@ describe('detectFramework', () => { join(framework, 'package.json'), JSON.stringify({ dependencies: { '@sveltejs/kit': '^2.0.0' } }), ); - writeFileSync(join(framework, 'workflows', 'welcome.ts'), 'export default {}'); + const definition = + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });"; const node = createTempRoot(); mkdirSync(join(node, 'routes'), { recursive: true }); mkdirSync(join(node, 'workflows'), { recursive: true }); writeFileSync(join(node, 'void.json'), JSON.stringify({ target: 'node' })); - writeFileSync(join(node, 'workflows', 'welcome.ts'), 'export default {}'); const cwd = vi.spyOn(process, 'cwd').mockReturnValue(framework); try { + for (const root of [framework, node]) { + writeFileSync(join(root, 'workflows', 'maintenance.ts'), 'export const run = () => {};'); + cwd.mockReturnValue(root); + expect(() => voidPlugin()).not.toThrow(); + } + writeFileSync(join(framework, 'workflows', 'welcome.ts'), definition); + writeFileSync(join(node, 'workflows', 'welcome.ts'), definition); + cwd.mockReturnValue(framework); expect(() => voidPlugin()).toThrow('workflows/ is currently supported in Void apps only'); cwd.mockReturnValue(node); expect(() => voidPlugin()).toThrow('workflows/ requires target: "cloudflare"'); diff --git a/packages/void/test/unit/workflow-runtime.test.ts b/packages/void/test/unit/workflow-runtime.test.ts index 7455c6d1b4..314375b96f 100644 --- a/packages/void/test/unit/workflow-runtime.test.ts +++ b/packages/void/test/unit/workflow-runtime.test.ts @@ -114,6 +114,7 @@ describe('defineWorkflow', () => { const invalid = Welcome.create({ params: { userId: 1 as unknown as string } }); await expect(invalid).rejects.toBeInstanceOf(WorkflowParamsError); await expect(invalid).rejects.toThrow('workflows: invalid params: userId: Expected a string'); + // @ts-expect-error JavaScript callers can omit required params, so still validate at runtime. await expect(Welcome.create()).rejects.toThrow('invalid params'); await expect( Welcome.createBatch([{ params: { userId: 'ok' } }, { params: {} as { userId: string } }]), diff --git a/packages/void/test/unit/workflow-runtime.typecheck.ts b/packages/void/test/unit/workflow-runtime.typecheck.ts new file mode 100644 index 0000000000..6d9cc9802f --- /dev/null +++ b/packages/void/test/unit/workflow-runtime.typecheck.ts @@ -0,0 +1,29 @@ +import { defineWorkflow } from '../../src/runtime/workflows/index.ts'; + +declare const binding: Workflow; + +const required = defineWorkflow<{ userId: string }>({ async run() {} }); +void required.create({ params: { userId: 'user' } }); +void required.create(binding, { params: { userId: 'user' } }); +void required.createBatch([{ params: { userId: 'user' } }]); +void required.createBatch(binding, [{ params: { userId: 'user' } }]); + +// @ts-expect-error The handler expects a userId. +void required.create(); +// @ts-expect-error Options without params are incomplete. +void required.create({ id: 'instance' }); +// @ts-expect-error An explicit binding does not make params optional. +void required.create(binding); +// @ts-expect-error Each batch entry needs a payload. +void required.createBatch([{}]); +// @ts-expect-error Each explicit-binding batch entry needs a payload. +void required.createBatch(binding, [{ id: 'instance' }]); + +const optional = defineWorkflow<{ userId: string } | undefined>({ async run() {} }); +void optional.create(); +void optional.create(binding); +void optional.createBatch([{}]); + +const noParams = defineWorkflow({ async run() {} }); +void noParams.create(); +void noParams.createBatch(binding, [{ id: 'instance' }]); diff --git a/packages/void/test/unit/workflow-scan.test.ts b/packages/void/test/unit/workflow-scan.test.ts index 85da6f867b..ecc3fcf0c0 100644 --- a/packages/void/test/unit/workflow-scan.test.ts +++ b/packages/void/test/unit/workflow-scan.test.ts @@ -12,6 +12,8 @@ import { } from '../../src/workflows/scan.ts'; const roots: Array = []; +const definition = `import { defineWorkflow } from 'void/workflows'; +export default defineWorkflow({ async run() {} });`; function createRoot(files: Record): string { const root = mkdtempSync(join(tmpdir(), 'void-workflow-scan-')); @@ -31,6 +33,16 @@ afterEach(() => { }); describe('scanWorkflowModules', () => { + it('ignores ordinary modules in the workflows directory', () => { + const root = createRoot({ + 'maintenance.ts': 'export default { run() {} }', + 'unrelated.ts': 'const defineWorkflow = (value) => value; export default defineWorkflow({});', + }); + + expect(scanWorkflowModules(root)).toEqual([]); + expect(() => assertNoWorkflowsForPlatform(root)).not.toThrow(); + }); + it('returns nothing without a workflows directory', () => { const root = mkdtempSync(join(tmpdir(), 'void-workflow-scan-')); roots.push(root); @@ -39,7 +51,7 @@ describe('scanWorkflowModules', () => { }); it('derives binding, class, and resource names from filenames', () => { - const root = createRoot({ 'send-welcome.ts': 'export default {}', 'types.d.ts': '' }); + const root = createRoot({ 'send-welcome.ts': definition, 'types.d.ts': '' }); expect(scanWorkflowModules(root)).toEqual([ { filePath: toSlash(join(root, 'workflows', 'send-welcome.ts')), @@ -52,7 +64,7 @@ describe('scanWorkflowModules', () => { }); it('joins nested directories into the name, as queues do', () => { - const root = createRoot({ 'order/notifications.ts': 'export default {}' }); + const root = createRoot({ 'order/notifications.ts': definition }); expect(scanWorkflowModules(root)).toEqual([ { filePath: toSlash(join(root, 'workflows', 'order', 'notifications.ts')), @@ -66,18 +78,19 @@ describe('scanWorkflowModules', () => { it('ignores files and directories starting with an underscore', () => { const root = createRoot({ - 'welcome.ts': 'export default {}', - '_steps.ts': 'export const send = () => {};', - '_lib/email.ts': 'export const send = () => {};', - 'order/_shared.ts': 'export const total = 0;', + 'welcome.ts': definition, + '_steps.ts': definition, + '_lib/email.ts': definition, + 'order/_shared.ts': definition, + 'order/ordinary.ts': 'export const total = 0;', }); expect(scanWorkflowModules(root).map((module) => module.relativePath)).toEqual(['welcome.ts']); }); it('rejects a nested path and a file that produce the same name', () => { const root = createRoot({ - 'order/notifications.ts': 'export default {}', - 'order-notifications.ts': 'export default {}', + 'order/notifications.ts': definition, + 'order-notifications.ts': definition, }); expect(() => scanWorkflowModules(root)).toThrow('duplicate generated name'); }); @@ -96,14 +109,14 @@ describe('scanWorkflowModules', () => { it('rejects files that normalize to the same generated names', () => { const root = createRoot({ - 'send-welcome.ts': 'export default {}', - 'send_welcome.ts': 'export default {}', + 'send-welcome.ts': definition, + 'send_welcome.ts': definition, }); expect(() => scanWorkflowModules(root)).toThrow('duplicate generated name'); }); it('rejects Void platform deploys while workflows exist', () => { - const root = createRoot({ 'welcome.ts': 'export default {}' }); + const root = createRoot({ 'welcome.ts': definition }); expect(() => assertNoWorkflowsForPlatform(root)).toThrow('void deploy --platform cloudflare'); }); }); @@ -112,7 +125,29 @@ describe('Cloudflare Workflow names', () => { it('prefixes the account-scoped name with the Worker name', () => { expect(cloudflareWorkflowName('welcome', 'My_App')).toBe('my-app-welcome'); expect(cloudflareWorkflowName('welcome')).toBe('welcome'); - expect(cloudflareWorkflowName('w'.repeat(80), 'app')).toHaveLength(64); + expect(cloudflareWorkflowName('w'.repeat(60), 'app')).toHaveLength(64); + }); + + it('rejects an overlong generated name and accepts an explicit provider name', () => { + const modules = [ + deriveWorkflowResourceIdentity('welcome'), + deriveWorkflowResourceIdentity('reporting'), + ]; + const worker = 'w'.repeat(63); + expect(() => planWorkflowAdditions([], modules, worker)).toThrow( + /64 characters.*cloudflare\.workflows/, + ); + expect( + planWorkflowAdditions( + modules.map((module) => ({ + binding: module.bindingName, + class_name: module.className, + name: module.resourceName, + })), + modules, + worker, + ), + ).toEqual([]); }); it('adds only unconfigured modules and keeps an authored entry for the same class', () => { From fcd232dc54284d635378649fe77ad61adb577377 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Tue, 1 Dec 2026 09:44:52 +0900 Subject: [PATCH 4/7] Fix Workflow deployment, discovery, and runtime contracts. --- docs/guide/workflows.md | 12 ++- docs/integrations/cloudflare.md | 2 +- docs/reference/api/workflows.md | 43 +++------ docs/reference/cli/deploy.md | 4 +- docs/reference/cli/setup.md | 2 +- docs/reference/config.md | 2 +- packages/deploy-cloudflare/src/version.ts | 2 +- packages/void/schema.json | 2 +- .../void/src/cli/deploy-cloudflare-build.ts | 29 ++++-- .../void/src/cli/deploy-cloudflare-helpers.ts | 25 ++++- .../void/src/cli/deploy-cloudflare-publish.ts | 1 + .../void/src/cli/deploy-cloudflare-static.ts | 32 +++++++ packages/void/src/cli/deploy-cloudflare.ts | 6 +- packages/void/src/cli/deploy-types.ts | 2 +- packages/void/src/cli/help.ts | 2 +- packages/void/src/cli/info.ts | 9 +- packages/void/src/plugin-inference.ts | 22 +++-- packages/void/src/plugin-routing.ts | 10 ++ packages/void/src/router/compile.ts | 18 +++- packages/void/src/runtime/workflows/index.ts | 93 +++++++++--------- .../void/src/shared/resource-definition.ts | 35 +++++-- packages/void/src/shared/resource-name.ts | 5 + packages/void/src/workflows/config.ts | 5 +- packages/void/src/workflows/scan.ts | 11 ++- .../test/integration/workflow-dev.test.ts | 45 +++++++++ .../test/integration/workflow-runtime.test.ts | 65 ++++++++++++- .../void/test/unit/cloudflare-deploy.test.ts | 92 +++++++++++++++++- packages/void/test/unit/info.test.ts | 22 ++++- .../void/test/unit/plugin-inference.test.ts | 27 ++++++ .../void/test/unit/workflow-runtime.test.ts | 16 +++- .../test/unit/workflow-runtime.typecheck.ts | 95 ++++++++++++++++++- packages/void/test/unit/workflow-scan.test.ts | 18 ++++ 32 files changed, 623 insertions(+), 131 deletions(-) create mode 100644 packages/void/test/integration/workflow-dev.test.ts diff --git a/docs/guide/workflows.md b/docs/guide/workflows.md index 0b44273231..70807e13f2 100644 --- a/docs/guide/workflows.md +++ b/docs/guide/workflows.md @@ -56,7 +56,7 @@ export const POST = defineHandler(async () => { }); ``` -`create()` accepts the same options as Cloudflare's [`Workflow.create()`](https://developers.cloudflare.com/workflows/build/workers-api/#create), such as `id` and `retention`. Use `createBatch()` to start up to 100 instances at once. Both methods require `params` when your definition requires a payload. +`create()` accepts the same options as Cloudflare's [`Workflow.create()`](https://developers.cloudflare.com/workflows/build/workers-api/#create), such as `id` and `retention`. Use `createBatch()` to start up to 100 instances at once. Both methods require `params` when your definition requires a payload. If you omit optional params, Cloudflare delivers an empty object as `event.payload`. A schema can supply a different default. Check on an instance with `get()`: @@ -99,7 +99,7 @@ Invalid params throw a `WorkflowParamsError`. Its `issues` list each message and ## Native Workflow classes -Use `defineWorkflowEntrypoint()` to keep a class that extends Cloudflare's `WorkflowEntrypoint`. Void binds and exports the class without changing it, and reads the params type from its `run` method: +Use `defineWorkflowEntrypoint()` to keep a class that extends Cloudflare's `WorkflowEntrypoint`. Void reads the params type from the class’s `run` method: ```ts // workflows/report.ts @@ -127,9 +127,9 @@ Void derives the names from the file's path in `workflows/`, joining directories - the exported `SendWelcomeWorkflow` class - a Cloudflare Workflow named `-send-welcome`, since Workflow names must be unique within your Cloudflare account -`workflows/order/notifications.ts` creates `WORKFLOW_ORDER_NOTIFICATIONS`, `OrderNotificationsWorkflow`, and `-order-notifications`. Each Workflow must have a unique name. +`workflows/order/notifications.ts` creates `WORKFLOW_ORDER_NOTIFICATIONS`, `OrderNotificationsWorkflow`, and `-order-notifications`. A path that starts with a digit, such as `2026-report.ts`, exports the class `Workflow2026Report` and uses the binding `WORKFLOW_2026_REPORT`. Each Workflow must have a unique name. -Instances belong to the Workflow name. Renaming the file or the Worker starts a new, empty Workflow, and instances of the old one stop running. To move a file without changing its name, run `void info` first and add the name it suggests: +Instances belong to the Workflow name. Changing the generated Workflow name directs new instances to a different Workflow. To move a file without changing its name, run `void info` first and add the name it suggests: ```ts export const Onboarding = defineWorkflow({ @@ -140,7 +140,7 @@ export const Onboarding = defineWorkflow({ }); ``` -`name` must be a static string containing words that start with a letter. To choose the Cloudflare Workflow name yourself, add an entry for the generated binding and class in `void.config.ts`: +`name` must be a static string containing at least one ASCII letter or digit. To choose the Cloudflare Workflow name yourself, add an entry for the generated binding and class in `void.config.ts`: ```ts // void.config.ts @@ -161,4 +161,6 @@ If the generated Cloudflare Workflow name exceeds 64 characters, use this entry Workflows are available on the Workers Free plan, within [Cloudflare's Workflows limits](https://developers.cloudflare.com/workflows/reference/limits/). Deploy to your own Cloudflare account with `void deploy --platform cloudflare`. +If Cloudflare rejects staging because you added, renamed, or removed a Workflow, run `void deploy --platform cloudflare --atomic` for that deployment. The new version receives traffic before Void checks readiness. + Void platforms do not support Workflows yet: `void deploy` to a Void platform stops with an error while `workflows/` contains modules. Workflows are also unavailable in meta-framework apps and on Node.js, Bun, and Deno. diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index 9d23adde63..b3963ab103 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -264,7 +264,7 @@ If readiness or trigger updates fail, Void restores the previous deployment. If Finish or cancel gradual rollouts in Cloudflare before deploying through Void. -For an existing Durable Object Worker that Cloudflare cannot stage, review the changes and use: +If Cloudflare cannot stage a change to a Durable Object or Workflow class on an existing Worker, review the changes and run the following command. ```sh void deploy --platform cloudflare --atomic diff --git a/docs/reference/api/workflows.md b/docs/reference/api/workflows.md index 174765ecce..a71f2fc684 100644 --- a/docs/reference/api/workflows.md +++ b/docs/reference/api/workflows.md @@ -11,42 +11,25 @@ Imported from `"void/workflows"`. See [Workflows](../../guide/workflows.md) for Defines a Cloudflare Workflow from a run function. The returned object must be the default export of a module under `workflows/`; named-export the same object to start instances elsewhere in the app. -```ts -function defineWorkflow(definition: { - name?: string; - params?: StandardSchemaV1; - run( - event: Readonly>, - step: WorkflowStep, - context: { env: TEnv; ctx: ExecutionContext }, - ): Promise; -}): WorkflowApi, TParams>; -``` - -With `params`, `run` receives the schema's output type and `create()` accepts its input type. Without it, the params type comes from the `event` annotation. - -When the params type requires a payload, pass `params` to `create()` and to every entry in `createBatch()`. +The definition accepts an optional `name`, an optional Standard Schema for `params`, and an async `run(event, step, { env, ctx })` function. -## `defineWorkflowEntrypoint(definition)` {#defineworkflowentrypoint-definition} +With a schema, `create()` and `createBatch()` accept its input and send its parsed output to Cloudflare. Instances started directly through Cloudflare must supply the payload that `run` expects. Without a schema, the params type comes from the `event` annotation or the type parameter to `defineWorkflow()`. + +Pass `params` to `create()` and to every entry in `createBatch()` when the definition requires a payload. Cloudflare delivers an empty object as `event.payload` if params are omitted or the schema returns `undefined`. When your handler accepts optional params, check the fields it needs. -Registers a class that extends Cloudflare's `WorkflowEntrypoint` without changing it. The params type is read from the class's `run(event)` annotation. +## `defineWorkflowEntrypoint(definition)` {#defineworkflowentrypoint-definition} -```ts -function defineWorkflowEntrypoint(definition: { - name?: string; - class: TClass; -}): WorkflowApi; -``` +Registers a class that extends Cloudflare's `WorkflowEntrypoint`. The params type comes from the class's `run(event)` annotation. You can omit params when the declared payload accepts an empty object. ## `WorkflowApi` {#workflowapi} -| Member | Description | -| ------------------------------ | ----------------------------------------------------------------------------------------------------- | -| `class` | The Workflow class Void exports from the Worker. | -| `create(options?)` | Starts an instance. Options match Cloudflare's `create()`; `params` are typed and validated. | -| `createBatch(instances)` | Starts up to 100 instances and returns Cloudflare's `{ created, errors }` result. | -| `get(id)` | Returns a `WorkflowInstance` for `status()`, `pause()`, `resume()`, `terminate()`, and `sendEvent()`. | -| `create(binding, options?)`, … | Each method also accepts an explicit `Workflow` binding as its first argument. | +| Member | Description | +| ------------------------------ | -------------------------------------------------------------------------------------------------------- | +| `class` | The Workflow entrypoint class for this definition. | +| `create(options?)` | Starts an instance. Options match Cloudflare's `create()`; `params` are typed and validated. | +| `createBatch(instances)` | Starts up to 100 instances and returns Cloudflare's `{ created, errors }` result. | +| `get(id)` | Returns a `WorkflowInstance` for `status()`, `pause()`, `resume()`, `terminate()`, and `sendEvent()`. | +| `create(binding, options?)`, … | Each method accepts an explicit `Workflow` binding for the handler’s payload type as its first argument. | `name` optionally fixes the resource identity instead of deriving it from the filename. Run `void info` and pin the displayed name before moving a deployed definition. diff --git a/docs/reference/cli/deploy.md b/docs/reference/cli/deploy.md index 031eb779e2..651273f9cf 100644 --- a/docs/reference/cli/deploy.md +++ b/docs/reference/cli/deploy.md @@ -39,12 +39,12 @@ For Drizzle projects, deploy performs a read-only schema drift check. If a new m | `--skip-migrations` | Deploy without applying application or authentication SQL migrations; supported on Cloudflare and Void platforms | | `--require-email` | Fail when email cannot be set up instead of deploying without it; requires `--platform cloudflare` | | `--provision` | Run resource provisioning again even when every resource exists; requires `--platform cloudflare` | -| `--atomic` | Publish an existing Durable Object Worker directly; readiness is checked after traffic changes | +| `--atomic` | Publish an existing Worker with Durable Objects or Workflows before checking readiness | | `--preview ` | Deploy a static site or SPA to a Cloudflare Preview; production is unchanged ([more](#void-deploy-preview)) | | `--json` | With `--preview`, print one JSON object on stdout; everything else goes to stderr | | `--debug` | Mirror the structured deploy log to stderr (also written to `~/.void/logs/`) | -`--atomic` applies to one deployment. For an existing Durable Object Worker that consistently cannot stage, set `deploy: { cloudflare: { mode: 'atomic' } }` in `void.config.ts` so plain `void deploy` uses atomic publication. The default is `staged`. +`--atomic` applies to one deployment. For a Worker with Durable Objects or Workflows that consistently cannot stage, set `deploy: { cloudflare: { mode: 'atomic' } }` in `void.config.ts` so plain `void deploy` uses atomic publication. The default is `staged`. Use `--skip-migrations` when you run migrations separately or share a database with a preview. The code must work with the database's current schema. The next deploy without this flag applies pending migrations. diff --git a/docs/reference/cli/setup.md b/docs/reference/cli/setup.md index 4198d53e55..f3257e7dd4 100644 --- a/docs/reference/cli/setup.md +++ b/docs/reference/cli/setup.md @@ -14,7 +14,7 @@ void info --json Shows each Durable State, WebSocket, and Workflow definition's source file, inferred or explicit name, Worker class, and binding. WebSocket entries also include their route in JSON output. It runs locally without authentication, network requests, or file generation. -Before moving a deployed definition, copy the suggested `name` into `defineDurableState()`, `defineRoom()`, `defineWebSocket()`, or `defineWorkflow()`. Keep that name after moving the file to preserve the resource. See [Durable State](../../guide/durable-state.md#rename-a-file-while-keeping-its-state) [WebSockets](../../guide/websockets.md#move-a-route-while-keeping-its-state), and [Workflows](../../guide/workflows.md#names-and-bindings) for migration flows, including WebSocket parameter renames. +Before moving a deployed definition, copy the suggested `name` into the helper shown by `void info`. Keep that name after moving the file to preserve the resource. See [Durable State](../../guide/durable-state.md#rename-a-file-while-keeping-its-state), [WebSockets](../../guide/websockets.md#move-a-route-while-keeping-its-state), and [Workflows](../../guide/workflows.md#names-and-bindings) for migration flows, including WebSocket parameter renames. Resources recorded in `void.lock.json` without a matching definition appear separately. Adopt a suggested name only after identifying the resource you moved. If Void cannot suggest a name, restore its original source and inspect it before moving it again. diff --git a/docs/reference/config.md b/docs/reference/config.md index 5ca4e19125..6e736bface 100644 --- a/docs/reference/config.md +++ b/docs/reference/config.md @@ -372,7 +372,7 @@ If you need to remove a value that Void previously generated, remove it from the ### `deploy.cloudflare.mode` -Direct Cloudflare deploys use `staged` by default: Void checks the new Worker before sending it production traffic. If Cloudflare cannot stage an existing Durable Object Worker, choose `atomic` after reviewing the pending Worker and database changes: +Direct Cloudflare deploys use `staged` by default: Void checks the new Worker before sending it production traffic. If Cloudflare cannot stage a Worker with Durable Objects or Workflows, choose `atomic` after reviewing the pending Worker and database changes: ```ts // Inside defineConfig({ ... }) diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index df051c98d1..7f7d9da7a9 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -894,7 +894,7 @@ export type CloudflareVersionActivationOptions = { activeVersionId: string, bindings: ReadonlyArray<{ name: string; type: 'secret_text' | 'secret_key' }>, ) => Promise | boolean; - /** Explicitly publish an existing Durable Object Worker in one atomic operation. */ + /** Explicitly publish an existing Worker in one atomic operation. */ atomic?: boolean; /** * Plaintext secrets to attach only to the uploaded candidate version. Supplying every remote diff --git a/packages/void/schema.json b/packages/void/schema.json index 486c2043d0..b6848490e4 100644 --- a/packages/void/schema.json +++ b/packages/void/schema.json @@ -406,7 +406,7 @@ "mode": { "type": "string", "enum": ["staged", "atomic"], - "description": "Staged is the default and verifies readiness before traffic. Atomic publishes a Durable Object Worker directly and verifies readiness afterward." + "description": "Staged is the default and verifies readiness before traffic. Atomic publishes a Worker with Durable Objects or Workflows directly and verifies readiness afterward." } }, "additionalProperties": false diff --git a/packages/void/src/cli/deploy-cloudflare-build.ts b/packages/void/src/cli/deploy-cloudflare-build.ts index 81b509c10e..5ea88902a1 100644 --- a/packages/void/src/cli/deploy-cloudflare-build.ts +++ b/packages/void/src/cli/deploy-cloudflare-build.ts @@ -24,6 +24,7 @@ import { resolveGeneratedDeployConfigPathDefault, } from './deploy-artifact-validation.ts'; import { DEPLOY_BINDING_IDENTITY_FIELDS, bindingIdentityKey } from './deploy-binding-snapshot.ts'; +import { activeWorkflowVersionForRemoval } from './deploy-cloudflare-helpers.ts'; import type { CloudflareDeploySource, CloudflarePreflight } from './deploy-cloudflare-preflight.ts'; import { prepareCloudflareFrameworkArtifact } from './deploy-cloudflare-static.ts'; import { log, getExitCode, resolveFullDeployBuildCommand } from './deploy-helpers.ts'; @@ -60,6 +61,7 @@ export async function buildCloudflareWorker(input: { migrations: ReturnType; d1MigrateToken: string | undefined; generatedConfigPath: string; + previousWorkflowVersionId?: string; prepareBuildOutput: () => ReturnType; }> { const { root, voidConfig, deps, exit, atomic, frameworkPreset, detectedFramework } = input; @@ -175,13 +177,20 @@ export async function buildCloudflareWorker(input: { deps.resolveGeneratedConfigPath ?? ((projectRoot) => readGeneratedDeployConfig(projectRoot).path) )(root); - if (atomic && !Array.isArray(parseRootWranglerConfig(lifecycleConfigPath).migrations)) { - log.error( - 'deploy: atomic deployment is only for Workers with Durable Object migration history.', - ); - return exit(1); - } + let previousWorkflowVersionId: string | undefined; try { + if ( + atomic && + !Array.isArray(parseRootWranglerConfig(lifecycleConfigPath).migrations) && + !input.preflight.expectedWorkflows.some( + (workflow) => workflow.script_name === undefined || workflow.script_name === workerName, + ) + ) { + previousWorkflowVersionId = await activeWorkflowVersionForRemoval( + { runWrangler, configPath, workerName, accountId }, + deps.readExistingWorker, + ); + } deduplicateGeneratedCompatibilityFlags(lifecycleConfigPath, configPath); await (deps.assertDurableObjectLifecycle ?? assertCloudflareDurableObjectLifecycleSupported)({ runWrangler, @@ -370,5 +379,11 @@ export async function buildCloudflareWorker(input: { } await preflight.dispose(); } - return { migrations, d1MigrateToken, generatedConfigPath, prepareBuildOutput }; + return { + migrations, + d1MigrateToken, + generatedConfigPath, + previousWorkflowVersionId, + prepareBuildOutput, + }; } diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index 999e641c36..00bc02fba4 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -320,6 +320,26 @@ export function createCfActivationRunner(options: { }); } +/** Pin the active version when its local Workflow qualifies a removal for atomic publication. */ +export async function activeWorkflowVersionForRemoval( + options: Parameters[0], + readWorker: typeof readExistingCloudflareWorker = readExistingCloudflareWorker, +): Promise { + const active = await readWorker(options); + const ownsWorkflow = active.bindings.some( + (binding) => + binding.type === 'workflow' && + typeof binding.class_name === 'string' && + (binding.script_name === undefined || binding.script_name === options.workerName), + ); + if (!ownsWorkflow) { + throw new Error( + 'deploy: atomic deployment requires Durable Object migration history or a local Workflow in the new or active Worker.', + ); + } + return active.versionId; +} + /** * Activation options shared by the Worker and static deploys: candidate tracking, the uploaded * binding check, readiness probing and trigger cleanup. @@ -346,6 +366,7 @@ export function cloudflareCandidateActivationOptions(options: { assertUploaderStillPinned: () => boolean; approvedKv: ReadonlyArray; staticAssetsBinding?: string; + previousWorkflowVersionId?: string; queueConsumerCleanup: ReturnType; }): Omit< CloudflareActivationOptions, @@ -364,7 +385,7 @@ export function cloudflareCandidateActivationOptions(options: { accountId, configPath, preserveTriggers: existingWorker !== null, - expectedPreviousVersionId: existingWorker?.versionId, + expectedPreviousVersionId: existingWorker?.versionId ?? options.previousWorkflowVersionId, trustedInheritanceVersionIds: existingWorker ? candidateReceipt?.parentVersionId === existingWorker.versionId ? candidateReceipt.versionIds @@ -832,7 +853,7 @@ function customRouteAccessHint(origin: string): Array { } const ATOMIC_ACCESS_ALTERNATIVE = - 'For a Worker with Durable Object migration history, `void deploy --platform cloudflare --atomic` publishes without the zero-traffic check. The new version receives traffic first, and the command still exits with an error because Void cannot verify readiness through Access.'; + 'For a Worker with Durable Object migration history or a local Workflow, `void deploy --platform cloudflare --atomic` publishes without the zero-traffic check. The new version receives traffic first, and the command still exits with an error because Void cannot verify readiness through Access.'; function formatCloudflareReadinessRestoration( result: Exclude, diff --git a/packages/void/src/cli/deploy-cloudflare-publish.ts b/packages/void/src/cli/deploy-cloudflare-publish.ts index 32de202db0..1e4ed026c8 100644 --- a/packages/void/src/cli/deploy-cloudflare-publish.ts +++ b/packages/void/src/cli/deploy-cloudflare-publish.ts @@ -124,6 +124,7 @@ export async function publishCloudflareWorker(input: { initialCloudflareCandidate, assertUploaderStillPinned, approvedKv: approvedHandoffKv, + previousWorkflowVersionId: input.build.previousWorkflowVersionId, queueConsumerCleanup, }), runWrangler: activationRunner, diff --git a/packages/void/src/cli/deploy-cloudflare-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index 0ffbeeae99..cf908615ce 100644 --- a/packages/void/src/cli/deploy-cloudflare-static.ts +++ b/packages/void/src/cli/deploy-cloudflare-static.ts @@ -27,6 +27,8 @@ import { hasEmailHandlers } from '../router/email.ts'; import { selectNativeVersionMetadataBinding } from '../shared/version-metadata.ts'; import { validateSsrEntry } from '../ssr/entry.ts'; import { prepareCfStaticBuildOutput } from './cf-build-output.ts'; +import { createActiveSecretPinner } from './cf-version-runner.ts'; +import { clearCloudflareCandidate } from './cloudflare-candidate.ts'; import type { CloudflareCandidateReceipt } from './cloudflare-candidate.ts'; import type { CloudflareChildReporter } from './cloudflare-child-report.ts'; import { readCloudflareLink } from './cloudflare-link.ts'; @@ -38,6 +40,7 @@ import { prepareExistingCloudflareDeployWithAuth } from './deploy-cloudflare-aut import { discoverRootWranglerConfig, activateCloudflareVersionWithProgress, + activeWorkflowVersionForRemoval, assertCloudflareDeployTargetUnchanged, cloudflareCandidateActivationOptions, confirmCloudflareDeployAuthentication, @@ -394,6 +397,18 @@ export async function runCloudflareStaticDeploy( } const rootConfig = parseRootWranglerConfig(configPath); const workerName = readWranglerTopLevelString(rootConfig, 'name') ?? deriveWorkerName(root); + let previousWorkflowVersionId: string | undefined; + if (options.atomic) { + try { + previousWorkflowVersionId = await activeWorkflowVersionForRemoval( + { runWrangler, configPath, workerName, accountId }, + deps.readExistingWorker, + ); + } catch (error) { + log.error(getErrorMessage(error)); + return exit(1); + } + } printDeployContext( workerName, options.preview === undefined ? 'Cloudflare' : `Cloudflare Preview ${options.preview}`, @@ -583,6 +598,7 @@ export async function runCloudflareStaticDeploy( assertUploaderStillPinned, approvedKv: [], staticAssetsBinding: 'ASSETS', + previousWorkflowVersionId, queueConsumerCleanup, }), runWrangler: activationRunner, @@ -594,9 +610,25 @@ export async function runCloudflareStaticDeploy( ...(existingWorker ? { preserve: true } : {}), }), assetsDirectoryOverride: stagedAssetsDirectory, + ...(options.atomic + ? { + atomic: true, + pinActiveSecrets: createActiveSecretPinner({ + output: cfOutput, + handoffPending: false, + requiredNames: [], + }), + } + : {}), }, ).finally(() => cfOutput?.dispose()); if (!execution.ok) { + if ( + execution.reason === 'atomic-readiness-failed' || + execution.reason === 'atomic-readiness-access-denied' + ) { + clearCloudflareCandidate(root); + } await reportCloudflareActivationFailure( reporter, formatCloudflareActivationError(execution), diff --git a/packages/void/src/cli/deploy-cloudflare.ts b/packages/void/src/cli/deploy-cloudflare.ts index 26b2ec8df8..6767d0f85b 100644 --- a/packages/void/src/cli/deploy-cloudflare.ts +++ b/packages/void/src/cli/deploy-cloudflare.ts @@ -110,13 +110,13 @@ export async function runCloudflareDeploy( resolveCloudflareStaticPreset(root, voidConfig, options) ?? (await resolveCloudflareVoidStaticPreset(root, voidConfig)); if (staticPreset) { - if (atomic) { - log.error('deploy: atomic deployment is only for Workers with Durable Objects.'); + if (atomic && options.preview !== undefined) { + log.error('deploy: --atomic is unavailable for static previews.'); return exit(1); } return runCloudflareStaticDeploy( root, - options, + { ...options, atomic }, voidConfig, staticPreset, cliLog, diff --git a/packages/void/src/cli/deploy-types.ts b/packages/void/src/cli/deploy-types.ts index fec9064c7f..9c2971f89e 100644 --- a/packages/void/src/cli/deploy-types.ts +++ b/packages/void/src/cli/deploy-types.ts @@ -50,7 +50,7 @@ export type RunDeployOptions = { * (CI / non-TTY, a blocker, a declined prompt). `--platform cloudflare` only. */ requireEmail?: boolean; - /** Publish an existing Durable Object Worker atomically after explicit operator choice. */ + /** Publish an existing Worker with Durable Objects or Workflows atomically after explicit operator choice. */ atomic?: boolean; /** * Create or update this named Cloudflare Preview instead of deploying production. diff --git a/packages/void/src/cli/help.ts b/packages/void/src/cli/help.ts index 78783a256c..69371d7d47 100644 --- a/packages/void/src/cli/help.ts +++ b/packages/void/src/cli/help.ts @@ -192,7 +192,7 @@ const HELP_TREE = { { command: '--atomic', description: - 'Publish a Durable Object Worker without pre-traffic staging (Cloudflare only)', + 'Publish a Worker with Durable Objects or Workflows before checking readiness (Cloudflare only)', }, { command: '--preview ', diff --git a/packages/void/src/cli/info.ts b/packages/void/src/cli/info.ts index e768986a13..6ea1d59559 100644 --- a/packages/void/src/cli/info.ts +++ b/packages/void/src/cli/info.ts @@ -10,11 +10,16 @@ import { inferWebSocketResourceName, } from '../router/websocket.ts'; import { inferWorkflowResourceName } from '../workflows/scan.ts'; +import type { WorkflowModule } from '../workflows/scan.ts'; import type { InfoArgs } from './info-args.ts'; export type PersistentResourceInfo = { file: string; - definition: 'defineDurableState' | 'defineRoom' | 'defineWebSocket' | 'defineWorkflow'; + definition: + | 'defineDurableState' + | 'defineRoom' + | 'defineWebSocket' + | WorkflowModule['definition']; name: string; nameSource: 'inferred' | 'explicit'; className: string; @@ -138,7 +143,7 @@ export function getProjectInfo(root: string): ProjectInfo { })), ...analysis.workflows.map((module) => ({ file: relative(root, module.filePath), - definition: 'defineWorkflow' as const, + definition: module.definition, name: module.name ?? inferWorkflowResourceName(module.relativePath), nameSource: module.name === undefined ? ('inferred' as const) : ('explicit' as const), className: module.className, diff --git a/packages/void/src/plugin-inference.ts b/packages/void/src/plugin-inference.ts index c9922cac66..a246d19198 100644 --- a/packages/void/src/plugin-inference.ts +++ b/packages/void/src/plugin-inference.ts @@ -1,5 +1,5 @@ import { existsSync, readFileSync } from 'node:fs'; -import { join, toSlash } from 'pathslash'; +import { join, relative, toSlash } from 'pathslash'; import { globSync } from 'tinyglobby'; import { applyBindingOverrides } from './application-features.ts'; import { inferBindingsFromSource, mergeBindings } from './inference/walk.ts'; @@ -164,11 +164,21 @@ export function inferProjectBindings( const routesPrefix = `${toSlash(paths.routesDir).replace(/\/$/, '')}/`; const pagesDir = toSlash(paths.pagesDir); const pagesPrefix = pagesDir.endsWith('/') ? pagesDir : `${pagesDir}/`; - const scanSourceFiles = (dirPath: string): Array => - globSync(conventionFileGlobs(dirPath, SOURCE_GLOB, paths.routesDir), { - cwd: dirPath, - absolute: true, - }); + const workflowsDir = join(root, 'workflows'); + const scanSourceFiles = (dirPath: string): Array => { + const patterns = conventionFileGlobs(dirPath, SOURCE_GLOB, paths.routesDir); + if (hasWorkflows) { + // Workflow modules also accept .cts and .cjs. Match step helpers with those + // extensions even when a custom scan directory starts above or inside workflows/. + const prefix = relative(dirPath, workflowsDir); + if (dirPath.startsWith(`${workflowsDir}/`)) { + patterns.push('**/*.{cts,cjs}'); + } else if (prefix !== '..' && !prefix.startsWith('../')) { + patterns.push(join(prefix, '**/*.{cts,cjs}')); + } + } + return globSync(patterns, { cwd: dirPath, absolute: true }); + }; const addFile = (file: string): void => { const normalizedFile = toSlash(file); if (scannedFiles.has(normalizedFile)) { diff --git a/packages/void/src/plugin-routing.ts b/packages/void/src/plugin-routing.ts index a8d406fc14..32bd6a4468 100644 --- a/packages/void/src/plugin-routing.ts +++ b/packages/void/src/plugin-routing.ts @@ -58,6 +58,7 @@ import { SSR_SERVER_ENTRY_RELATIVE_PATHS, SSR_CLIENT_ENTRY_RELATIVE_PATHS, } from './ssr/entry.ts'; +import { scanWorkflowModules } from './workflows/scan.ts'; const VIRTUAL_ROUTES_ID = 'virtual:void-routes'; const VIRTUAL_CLIENT_WORKER_ID = 'virtual:void-client-worker'; @@ -192,6 +193,7 @@ export function routingPlugin( const normalizedMiddlewareDir = normalizePath(middlewareDir); const normalizedJobsDir = normalizePath(jobsDir); const normalizedQueuesDir = normalizePath(queuesDir); + const normalizedWorkflowsDir = normalizePath(join(root, 'workflows')); const normalizedEmailDir = normalizePath(emailDir); const normalizedPagesDir = normalizePath(pagesDir); const ssrEntryAbsPaths = new Set( @@ -1000,7 +1002,10 @@ export function routingPlugin( const authImportCreated = event === 'add' && authConfigStale && compileOptions.auth !== null; + const workflowChanged = + options.workflows && isInDirectory(normalizedPath, normalizedWorkflowsDir); const sourceConventionChanged = + workflowChanged || isInDirectory(normalizedPath, normalizedRoutesDir) || isInDirectory(normalizedPath, normalizedMiddlewareDir) || isInDirectory(normalizedPath, normalizedJobsDir) || @@ -1016,6 +1021,11 @@ export function routingPlugin( const shouldRestart = await regenerateInOrder(async () => { invalidateSourceAnalysis(normalizedPath); + if (workflowChanged) { + // Cloudflare loads bindings and exported classes at startup. Ordinary step edits + // keep the same configuration and can use Vite's module updates. + return !isDeepStrictEqual(options.workflows, scanWorkflowModules(root)); + } // Re-scan and invalidate the virtual module in ALL environments. // The route table virtual module lives in the workerd environment, // not the client — so we must iterate all environments. diff --git a/packages/void/src/router/compile.ts b/packages/void/src/router/compile.ts index d6f79fb26c..6f1ca1f49d 100644 --- a/packages/void/src/router/compile.ts +++ b/packages/void/src/router/compile.ts @@ -1226,7 +1226,13 @@ type ResourceModuleEntry = { */ function compileResourceModules( entries: ReadonlyArray, - options: { variable: string; directory: string; prefix: string; helpers: string }, + options: { + variable: string; + directory: string; + prefix: string; + helpers: string; + validateWorkflowEnv?: boolean; + }, ): ResourceModuleCode { const imports = entries .map( @@ -1243,7 +1249,14 @@ function compileResourceModules( `const ${local} = ${options.variable}Module${index}.default;`, `if (typeof ${local}?.__bind !== "function") { throw new Error(${JSON.stringify(message)}); }`, `${local}.__bind(${JSON.stringify(bindingName)}${name !== undefined ? `, ${JSON.stringify(name)}` : ''});`, - `export const ${className} = ${local}.class;`, + options.validateWorkflowEnv + ? `export class ${className} extends ${local}.class { + async run(event, step) { + await _validateEnvOnce(this.env); + return withRuntimeEnv(this.env, () => super.run(event, step)); + } +}` + : `export const ${className} = ${local}.class;`, ].join('\n'); }) .join('\n'); @@ -1337,6 +1350,7 @@ export function compileWorkerEntry(options: WorkerEntryOptions = {}): string { directory: 'workflows', prefix: 'workflows', helpers: 'defineWorkflow() or defineWorkflowEntrypoint()', + validateWorkflowEnv: Boolean(envSchemaModule), }); const resourceModuleImports = [durableObjectModules.imports, workflowModules.imports] .filter(Boolean) diff --git a/packages/void/src/runtime/workflows/index.ts b/packages/void/src/runtime/workflows/index.ts index 0bb3896487..0e1d1f3452 100644 --- a/packages/void/src/runtime/workflows/index.ts +++ b/packages/void/src/runtime/workflows/index.ts @@ -1,22 +1,19 @@ import { WorkflowEntrypoint } from 'cloudflare:workers'; import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers'; -import { isResourceName } from '../../shared/resource-name.ts'; +import { isWorkflowName } from '../../shared/resource-name.ts'; import type { StandardSchemaV1 } from '../../standard-schema.ts'; import { requireRuntimeBinding, withRuntimeEnv } from '../env/runtime.ts'; export type { WorkflowEvent, WorkflowStep }; -type NativeWorkflowClass = new (...args: Array) => { - run(event: never, step: never): Promise; -}; +type NativeWorkflowClass = new (...args: Array) => WorkflowEntrypoint; /** Params type of a native class, read from its `run(event)` annotation. */ -export type NativeWorkflowParams = - InstanceType extends { - run(event: Readonly>, ...rest: Array): unknown; - } - ? TParams - : unknown; +export type NativeWorkflowParams = Parameters< + InstanceType['run'] +>[0] extends { payload: infer TParams } + ? TParams + : unknown; /** Context passed to a `defineWorkflow()` run function next to the event and step. */ export type WorkflowContext = { @@ -32,24 +29,32 @@ type WorkflowCreateArguments = undefined extends TParams ? [options?: WorkflowCreateOptions] : [options: WorkflowCreateOptions]; -export type WorkflowApi = { +// Cloudflare delivers an empty object when create() omits params or a schema returns undefined. +type WorkflowPayload = + | Exclude + | (undefined extends TParams ? Record : never); + +export type WorkflowApi = { class: TClass; /** @internal Called by Void's generated Worker entry. */ __bind(bindingName: string, resourceName?: string): void; /** Start a new instance. Params are validated when the definition has a `params` schema. */ create(...args: WorkflowCreateArguments): Promise; - create(binding: Workflow, ...args: WorkflowCreateArguments): Promise; + create( + binding: Workflow, + ...args: WorkflowCreateArguments + ): Promise; /** Start up to 100 instances. Each instance's params are validated first. */ createBatch( instances: ReadonlyArray>, ): Promise; createBatch( - binding: Workflow, + binding: Workflow, instances: ReadonlyArray>, ): Promise; /** Get a handle to an existing instance. */ get(id: string): Promise; - get(binding: Workflow, id: string): Promise; + get(binding: Workflow, id: string): Promise; }; export type WorkflowRun = ( @@ -58,10 +63,10 @@ export type WorkflowRun = ( context: WorkflowContext, ) => Promise; -export type WorkflowClass = new ( +export type WorkflowClass> = new ( ctx: ExecutionContext, - env: Record, -) => WorkflowEntrypoint, TParams>; + env: TEnv, +) => WorkflowEntrypoint; /** Error thrown by `create()` and `createBatch()` when params fail the definition's schema. */ export class WorkflowParamsError extends Error { @@ -97,13 +102,13 @@ function isWorkflowBinding(value: Workflow | TOther): value is Workflow ); } -function createWorkflowApi( +function createWorkflowApi( definitionName: string | undefined, workflowClass: TClass, schema: StandardSchemaV1 | undefined, -): WorkflowApi { - if (definitionName !== undefined && !isResourceName(definitionName)) { - throw new Error('workflows: name must contain a word starting with a letter.'); +): WorkflowApi { + if (definitionName !== undefined && !isWorkflowName(definitionName)) { + throw new Error('workflows: name must contain a letter or digit.'); } let bindingName: string | undefined; @@ -186,28 +191,23 @@ type WorkflowDefinitionBase = { * Define a Workflow from a run function. Void generates the Cloudflare * `WorkflowEntrypoint` class. Default-export the result from a file in `workflows/`. */ -export function defineWorkflow< - TSchema extends StandardSchemaV1, - TEnv extends Record = Record, ->( +export function defineWorkflow>( definition: WorkflowDefinitionBase & { /** Standard Schema that validates params in `create()` and `createBatch()`. */ params: TSchema; - run: WorkflowRun, TEnv>; + run: WorkflowRun>, TEnv>; }, ): WorkflowApi< - WorkflowClass>, - StandardSchemaV1.InferInput + WorkflowClass>, TEnv>, + StandardSchemaV1.InferInput, + WorkflowPayload> >; -export function defineWorkflow< - TParams = unknown, - TEnv extends Record = Record, ->( +export function defineWorkflow>( definition: WorkflowDefinitionBase & { params?: undefined; - run: WorkflowRun; + run: WorkflowRun, TEnv>; }, -): WorkflowApi, TParams>; +): WorkflowApi, TEnv>, TParams, WorkflowPayload>; export function defineWorkflow( definition: WorkflowDefinitionBase & { params?: StandardSchemaV1; @@ -230,20 +230,25 @@ export function defineWorkflow( return createWorkflowApi(definition.name, VoidWorkflow, definition.params); } +// A native class receives Cloudflare's event as declared in its own run method. +type NativeWorkflowInput = + Record extends TParams ? TParams | undefined : Exclude; + /** * Register a native Cloudflare `WorkflowEntrypoint` class without changing it. * Default-export the result from a file in `workflows/`. */ -export function defineWorkflowEntrypoint< - TClass extends NativeWorkflowClass, - TParams = NativeWorkflowParams, ->( - definition: WorkflowDefinitionBase & { - class: TClass; - }, -): WorkflowApi { - if (typeof definition.class !== 'function') { - throw new Error('workflows: defineWorkflowEntrypoint() requires a class.'); +export function defineWorkflowEntrypoint( + definition: WorkflowDefinitionBase & { class: TClass }, +): WorkflowApi< + TClass, + NativeWorkflowInput>, + NativeWorkflowParams +> { + if (!(definition.class?.prototype instanceof WorkflowEntrypoint)) { + throw new Error( + 'workflows: defineWorkflowEntrypoint() requires a class extending WorkflowEntrypoint.', + ); } return createWorkflowApi(definition.name, definition.class, undefined); } diff --git a/packages/void/src/shared/resource-definition.ts b/packages/void/src/shared/resource-definition.ts index b43dbc5bda..bcfeb1d6d2 100644 --- a/packages/void/src/shared/resource-definition.ts +++ b/packages/void/src/shared/resource-definition.ts @@ -5,8 +5,10 @@ import { isIdentifier, isMemberExpression, isObjectExpression, + moduleExportName, } from './ast.ts'; import type { + AstExportNamedDeclaration, AstImportDeclaration, AstImportNamespaceSpecifier, AstImportSpecifier, @@ -14,7 +16,7 @@ import type { AstProgram, AstVariableDeclaration, } from './ast.ts'; -import { isResourceName } from './resource-name.ts'; +import { isResourceName, isWorkflowName } from './resource-name.ts'; import { staticLiteral, unwrapStaticExpression } from './static-exports.ts'; /** Inspect default helper definitions without running application code. */ @@ -22,7 +24,7 @@ export function readResourceDefinition( filename: string, source: string, helpers: ReadonlySet, - options?: { requireImportedHelper?: boolean }, + convention?: 'workflows', ): { helper: string; options?: AstNode; name?: string } | null { let program: AstProgram; try { @@ -36,6 +38,7 @@ export function readResourceDefinition( const importedHelpers = new Map(); const namespaces = new Map>(); const bindings = new Set(); + let defaultExport: AstNode | undefined; function recordBindings(node: AstNode | undefined): void { if (isIdentifier(node)) { bindings.add(node.name); @@ -56,6 +59,22 @@ export function readResourceDefinition( } } for (const statement of program.body ?? []) { + if (statement.type === 'ExportDefaultDeclaration') { + defaultExport = statement.declaration as AstNode; + } else if ( + convention === 'workflows' && + statement.type === 'ExportNamedDeclaration' && + !statement.source && + statement.exportKind !== 'type' + ) { + const named = statement as AstExportNamedDeclaration; + const specifier = named.specifiers?.find( + (item) => item.exportKind !== 'type' && moduleExportName(item.exported) === 'default', + ); + if (specifier) { + defaultExport = specifier.local; + } + } if (statement.type === 'ImportDeclaration') { const declaration = statement as AstImportDeclaration; const source = declaration.source.value; @@ -156,9 +175,12 @@ export function readResourceDefinition( continue; } const value = staticLiteral(resolve(valueNode)); - if (!isResourceName(value)) { + const validName = convention === 'workflows' ? isWorkflowName : isResourceName; + if (!validName(value)) { + const requirement = + convention === 'workflows' ? 'a letter or digit' : 'a word starting with a letter'; throw new Error( - `${filename}: resource name must be a static string containing a word starting with a letter.`, + `${filename}: resource name must be a static string containing ${requirement}.`, ); } name = { present: true, value }; @@ -167,8 +189,7 @@ export function readResourceDefinition( return name; } - const statement = program.body?.find((node) => node.type === 'ExportDefaultDeclaration'); - const declaration = unwrapStaticExpression(statement?.declaration as AstNode | undefined); + const declaration = unwrapStaticExpression(defaultExport); const call = resolve(isIdentifier(declaration) ? definitions.get(declaration.name) : declaration); if (!isCallExpression(call)) { return null; @@ -178,7 +199,7 @@ export function readResourceDefinition( if (isIdentifier(callee)) { helper = importedHelpers.get(callee.name) ?? - (!options?.requireImportedHelper && helpers.has(callee.name) ? callee.name : undefined); + (convention !== 'workflows' && helpers.has(callee.name) ? callee.name : undefined); } else if (isMemberExpression(callee) && isIdentifier(callee.object)) { const property = !callee.computed && isIdentifier(callee.property) diff --git a/packages/void/src/shared/resource-name.ts b/packages/void/src/shared/resource-name.ts index 3552ed6601..d5224a749c 100644 --- a/packages/void/src/shared/resource-name.ts +++ b/packages/void/src/shared/resource-name.ts @@ -2,6 +2,11 @@ export function resourceNameWords(value: string): Array { return value.split(/[^a-zA-Z0-9]+/).filter(Boolean); } +/** Workflow resource names can start with a digit because the generated class adds a prefix. */ +export function isWorkflowName(value: unknown): value is string { + return typeof value === 'string' && /[a-zA-Z0-9]/.test(value); +} + export function isResourceName(value: unknown): value is string { if (typeof value !== 'string') { return false; diff --git a/packages/void/src/workflows/config.ts b/packages/void/src/workflows/config.ts index 610a6ded1e..f21379c15b 100644 --- a/packages/void/src/workflows/config.ts +++ b/packages/void/src/workflows/config.ts @@ -35,7 +35,10 @@ export function planWorkflowAdditions( for (const module of modules) { const configured = existing.find((entry) => entry.binding === module.bindingName); if (configured) { - if (configured.class_name !== module.className || configured.script_name !== undefined) { + if ( + configured.class_name !== module.className || + (configured.script_name !== undefined && configured.script_name !== workerName) + ) { throw new Error( `workflows: binding '${module.bindingName}' is already configured for another Workflow, but workflows/ requires class '${module.className}'.`, ); diff --git a/packages/void/src/workflows/scan.ts b/packages/void/src/workflows/scan.ts index 74cb392448..9742040d58 100644 --- a/packages/void/src/workflows/scan.ts +++ b/packages/void/src/workflows/scan.ts @@ -9,6 +9,7 @@ export type WorkflowModule = { filePath: string; /** Path relative to `workflows/`, with `/` separators. */ relativePath: string; + definition: 'defineWorkflow' | 'defineWorkflowEntrypoint'; bindingName: string; className: string; /** Kebab-case resource name. Cloudflare Workflow names are derived from it. */ @@ -51,7 +52,7 @@ export function deriveWorkflowResourceIdentity( const classBase = parts.map((part) => part[0].toUpperCase() + part.slice(1)).join(''); return { bindingName: `WORKFLOW_${parts.join('_').toUpperCase()}`, - className: `${classBase}Workflow`, + className: /^\d/.test(classBase) ? `Workflow${classBase}` : `${classBase}Workflow`, resourceName: parts.join('-').toLowerCase(), }; } @@ -78,10 +79,10 @@ export function scanWorkflowModules(root: string): Array { return []; } - const modules = listWorkflowFiles(directory).flatMap((relativePath) => { + const modules = listWorkflowFiles(directory).flatMap((relativePath) => { const filePath = join(directory, relativePath); const definition = deriveFromSource(filePath, 'workflow-definition', (source) => - readResourceDefinition(filePath, source, WORKFLOW_HELPERS, { requireImportedHelper: true }), + readResourceDefinition(filePath, source, WORKFLOW_HELPERS, 'workflows'), ); if (!definition) { return []; @@ -95,6 +96,10 @@ export function scanWorkflowModules(root: string): Array { { filePath, relativePath, + definition: + definition.helper === 'defineWorkflowEntrypoint' + ? 'defineWorkflowEntrypoint' + : 'defineWorkflow', ...deriveWorkflowResourceIdentity(resourceName), ...(name === undefined ? {} : { name }), }, diff --git a/packages/void/test/integration/workflow-dev.test.ts b/packages/void/test/integration/workflow-dev.test.ts new file mode 100644 index 0000000000..aa0e020e97 --- /dev/null +++ b/packages/void/test/integration/workflow-dev.test.ts @@ -0,0 +1,45 @@ +import { mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { it, onTestFinished } from 'vite-plus/test'; +import { + createIsolatedPlayground, + killChild, + spawnFixtureServer, + startServer, + waitForServer, +} from '../../../../test/integration-helpers.ts'; + +it('refreshes the Worker when a Workflow is added, renamed, or deleted during dev', async () => { + const fixture = createIsolatedPlayground( + join(import.meta.dirname, '../../../..'), + 'playground/ssr', + ); + onTestFinished(() => fixture.cleanup()); + const route = '/api/workflow-bindings'; + writeFileSync( + join(fixture.root, 'routes', route + '.ts'), + `import { defineHandler } from 'void'; +export const GET = defineHandler(c => Response.json(Object.keys(c.env).filter(key => key.startsWith('WORKFLOW_'))));`, + ); + const server = await startServer((port) => spawnFixtureServer(fixture.root, 'dev', port), 20_000); + onTestFinished(() => killChild(server.child)); + const waitForBindings = (...bindings: Array) => + waitForServer(server.base + route, 10_000, { + expectStatus: 200, + expectBody: JSON.stringify(bindings), + diagnostics: server.output, + }); + await waitForBindings(); + const directory = join(fixture.root, 'workflows'); + mkdirSync(directory); + const file = join(directory, 'welcome.ts'); + const workflow = (name: string) => + `import { defineWorkflow } from 'void/workflows'; +export default defineWorkflow({ name: ${JSON.stringify(name)}, async run(event, step) { return step.do('greet', async () => 'hello'); } });`; + writeFileSync(file, workflow('welcome')); + await waitForBindings('WORKFLOW_WELCOME'); + writeFileSync(file, workflow('onboarding')); + await waitForBindings('WORKFLOW_ONBOARDING'); + rmSync(file); + await waitForBindings(); +}, 60_000); diff --git a/packages/void/test/integration/workflow-runtime.test.ts b/packages/void/test/integration/workflow-runtime.test.ts index 8680a01319..e512b4eca0 100644 --- a/packages/void/test/integration/workflow-runtime.test.ts +++ b/packages/void/test/integration/workflow-runtime.test.ts @@ -13,6 +13,8 @@ const temporary = mkdtempSync(join(tmpdir(), 'void-workflow-runtime-')); type Runtime = { dispatchFetch(url: string): Promise; dispose(): Promise }; let runtime: Runtime; +afterAll(() => rmSync(temporary, { recursive: true, force: true })); + const ROUTE_STUBS = ` export const scheduled = async () => {}; export const __voidCollectPrerenderPaths = async () => []; @@ -130,7 +132,6 @@ export default { async fetch(request) { afterAll(async () => { await runtime?.dispose(); - rmSync(temporary, { recursive: true, force: true }); }); it('starts an instance from a route and runs its steps with the Worker env', async () => { @@ -161,6 +162,68 @@ export default { async fetch(request) { }); }); +describe('Workflow environment validation on a cold Worker', () => { + it.each(['defineWorkflow', 'defineWorkflowEntrypoint'])( + 'prepares async env validators for %s before its first step', + async (helper) => { + const envPath = join(root, 'packages/void/src/runtime/env/public.ts'); + const schema = file( + 'env-' + helper + '.ts', + ` +import { defineEnv } from ${JSON.stringify(envPath)}; +export default defineEnv({ VALUE: { '~standard': { + version: 1, vendor: 'test', async validate(value) { return { value: Number(value) }; } +} } }); +`, + ); + const definition = file( + 'cold-' + helper + '.ts', + ` +import { WorkflowEntrypoint } from 'cloudflare:workers'; +import { env } from ${JSON.stringify(envPath)}; +import { defineWorkflow, defineWorkflowEntrypoint } from ${JSON.stringify(runtimePath)}; +async function run(event, step) { + const value = env.VALUE; + return step.do('read', async () => value + 1); +} +${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run });' : 'class Cold extends WorkflowEntrypoint { run(event, step) { return run(event, step); } } export default defineWorkflowEntrypoint({ class: Cold });'} +`, + ); + const output = await buildWorker( + 'cold-' + helper, + 'export default { fetch: () => new Response() };', + { + envSchemaModule: { importPath: schema, helperPath: envPath }, + workflows: [{ bindingName: 'COLD', className: 'ColdWorkflow', filePath: definition }], + }, + ); + const worker = new Miniflare( + convertV4MiniflareOptions({ + compatibilityDate: '2026-07-01', + compatibilityFlags: ['nodejs_compat'], + modules: true, + modulesRoot: output, + scriptPath: join(output, 'worker.mjs'), + bindings: { VALUE: '41' }, + workflows: { COLD: { name: 'cold', className: 'ColdWorkflow' } }, + }), + ); + try { + const { COLD } = await worker.getBindings<{ COLD: Workflow }>(); + const instance = await COLD.create(); + await expect + .poll(async () => (await instance.status()).status, { + timeout: 5000, + }) + .toMatch(/^(complete|errored)$/); + expect(await instance.status()).toMatchObject({ status: 'complete', output: 42 }); + } finally { + await worker.dispose(); + } + }, + ); +}); + describe('convention modules without a definition default export', () => { it.each([ { diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 0ac6c802bc..714a6db5d7 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -756,7 +756,7 @@ describe('Cloudflare activation diagnostics', () => { expect(message).toContain('CF_ACCESS_READINESS_ORIGIN=https://dashboard.example.com'); expect(message).toContain('only if you control this hostname and it serves this Worker'); expect(message).toContain( - 'For a Worker with Durable Object migration history, `void deploy --platform cloudflare --atomic`', + 'For a Worker with Durable Object migration history or a local Workflow, `void deploy --platform cloudflare --atomic`', ); expect(message).toContain('still exits with an error'); expect(message).toContain('traffic was restored to the previous version'); @@ -1732,12 +1732,18 @@ describe('existing Cloudflare site handoff', () => { expect(lookups).toEqual([{ ok: true, subdomain: 'team.fed' }]); }); - it('refuses an atomic deploy when the Worker has no Durable Object migration history', async () => { + it('refuses an atomic deploy for a Worker that only binds an external Workflow', async () => { const root = site(); const activateVersion = vi.fn(); const assertDurableObjectLifecycle = vi.fn(); const { deps } = harness({ runBuild: () => build(root), + readExistingWorker: async () => ({ + ...existing, + bindings: [ + { type: 'workflow', name: 'EXTERNAL', workflow_name: 'shared', script_name: 'other' }, + ], + }), activateVersion, assertDurableObjectLifecycle, }); @@ -1747,9 +1753,7 @@ describe('existing Cloudflare site handoff', () => { runCloudflareDeploy(root, { platform: 'cloudflare', atomic: true }, silentCliLog, deps), ).rejects.toBeInstanceOf(ExitError); expect(output).toHaveBeenCalledWith( - expect.stringContaining( - 'atomic deployment is only for Workers with Durable Object migration history', - ), + expect.stringContaining('Durable Object migration history or a local Workflow'), ); expect(activateVersion).not.toHaveBeenCalled(); expect(assertDurableObjectLifecycle).not.toHaveBeenCalled(); @@ -1758,6 +1762,84 @@ describe('existing Cloudflare site handoff', () => { } }); + it.each(['add', 'remove', 'remove to static'] as const)( + 'supports the %s operation for a local Workflow in an atomic deployment', + async (operation) => { + const root = site(); + const configPath = join(root, 'wrangler.jsonc'); + const config = parseRootWranglerConfig(configPath); + config.preview_urls = false; + if (operation === 'add') { + mkdirSync(join(root, 'workflows')); + writeFileSync( + join(root, 'workflows/notify.ts'), + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });", + ); + } + writeFileSync(configPath, JSON.stringify(config)); + if (operation === 'remove to static') { + mkdirSync(join(root, 'dist')); + writeFileSync(join(root, 'dist/index.html'), '

Site

'); + } + const readExistingWorker = vi.fn().mockResolvedValue({ + ...existing, + bindings: [ + { + type: 'workflow', + name: 'WORKFLOW_NOTIFY', + workflow_name: 'site-notify', + class_name: 'NotifyWorkflow', + }, + ], + }); + const activateVersion = vi + .fn>() + .mockResolvedValue({ + ok: true, + versionId: 'new', + previousVersionId: existing.versionId, + previewUrl: 'https://site.example.com', + }); + const { deps } = harness({ + runBuild: () => { + build(root); + if (operation === 'add') { + const path = join(root, 'dist/ssr/wrangler.json'); + writeFileSync( + path, + JSON.stringify({ + ...parseRootWranglerConfig(path), + workflows: [ + { name: 'site-notify', binding: 'WORKFLOW_NOTIFY', class_name: 'NotifyWorkflow' }, + ], + }), + ); + } + }, + readExistingWorker, + verifyDeployConfig: verifyGeneratedDeployConfig, + activateVersion, + }); + await runCloudflareDeploy( + root, + { + platform: 'cloudflare', + atomic: true, + ...(operation === 'remove to static' ? { dir: 'dist' } : {}), + }, + silentCliLog, + deps, + ); + expect(readExistingWorker).toHaveBeenCalledTimes(operation === 'add' ? 0 : 1); + expect(activateVersion).toHaveBeenCalledWith( + expect.objectContaining({ + atomic: true, + expectedPreviousVersionId: operation === 'add' ? undefined : existing.versionId, + }), + ); + }, + ); + it('allows an explicit atomic deploy after the Durable Object migration preflight', async () => { const root = site(); const configPath = join(root, 'wrangler.jsonc'); diff --git a/packages/void/test/unit/info.test.ts b/packages/void/test/unit/info.test.ts index 108c132434..533fedd6a3 100644 --- a/packages/void/test/unit/info.test.ts +++ b/packages/void/test/unit/info.test.ts @@ -109,7 +109,7 @@ export default defineWorkflowEntrypoint({ name: 'import', class: Importer });`, expect(info.resources).toEqual([ { file: 'workflows/import-v2.ts', - definition: 'defineWorkflow', + definition: 'defineWorkflowEntrypoint', name: 'import', nameSource: 'explicit', className: 'ImportWorkflow', @@ -127,6 +127,26 @@ export default defineWorkflowEntrypoint({ name: 'import', class: Importer });`, expect(formatProjectInfo(info)).toContain("add this to 'defineWorkflow':"); }); + it('preserves an inferred numeric-leading Workflow name when pinned and moved', () => { + const root = project(); + const source = (options: string) => `import { defineWorkflowEntrypoint } from 'void/workflows'; +export default defineWorkflowEntrypoint({ ${options} class: Report });`; + write(root, 'workflows/2026-report.ts', source('')); + const info = getProjectInfo(root); + const [initial] = info.resources; + expect(initial).toMatchObject({ + name: '2026-report', + className: 'Workflow2026Report', + bindingName: 'WORKFLOW_2026_REPORT', + }); + expect(formatProjectInfo(info)).toContain("add this to 'defineWorkflowEntrypoint':"); + rmSync(join(root, 'workflows/2026-report.ts')); + write(root, 'workflows/archive/report.ts', source(`name: ${JSON.stringify(initial.name)},`)); + expect(getProjectInfo(root).resources).toEqual([ + { ...initial, file: 'workflows/archive/report.ts', nameSource: 'explicit' }, + ]); + }); + it('keeps explicit names visible after moving code and respects configured source paths', () => { const root = project(); write(root, 'void.config.ts', "export default { sourceDir: 'src' };"); diff --git a/packages/void/test/unit/plugin-inference.test.ts b/packages/void/test/unit/plugin-inference.test.ts index b6ecceb035..0f387d90c3 100644 --- a/packages/void/test/unit/plugin-inference.test.ts +++ b/packages/void/test/unit/plugin-inference.test.ts @@ -412,6 +412,33 @@ describe('inferProjectBindings', () => { expect(inferProjectBindings(root).needsD1).toBe(false); }); + it('infers bindings in .cts Workflow definitions and .cjs step helpers', () => { + const root = createTempRoot(); + mkdirSync(join(root, 'workflows')); + writeFileSync( + join(root, 'workflows', 'summary.cts'), + `import { defineWorkflow } from 'void/workflows'; +import { kv } from 'void/kv'; +import { read } from './_storage.cjs'; +export default defineWorkflow({ async run(event, step, { env }) { + return step.do('read', async () => [await kv.get('key'), await read(env)]); +} });`, + ); + writeFileSync( + join(root, 'workflows', '_storage.cjs'), + "exports.read = (env) => env.STORAGE.get('key');", + ); + expect(inferProjectBindings(root)).toMatchObject({ needsKV: true, needsR2: true }); + expect(inferProjectBindings(root, undefined, ['.'])).toMatchObject({ + needsKV: true, + needsR2: true, + }); + expect(inferProjectBindings(root, undefined, ['src'])).toMatchObject({ + needsKV: false, + needsR2: false, + }); + }); + it('detects live from a stream module outside the default directories only when scanned', () => { const root = createTempRoot(); mkdirSync(join(root, 'routes'), { recursive: true }); diff --git a/packages/void/test/unit/workflow-runtime.test.ts b/packages/void/test/unit/workflow-runtime.test.ts index 314375b96f..46996c7ade 100644 --- a/packages/void/test/unit/workflow-runtime.test.ts +++ b/packages/void/test/unit/workflow-runtime.test.ts @@ -128,11 +128,23 @@ describe('defineWorkflow', () => { it('rejects a runtime identity that differs from static analysis and invalid names', () => { const Welcome = defineWorkflow({ name: 'welcome', async run() {} }); expect(() => Welcome.__bind('WORKFLOW_WELCOME', 'other')).toThrow('statically discoverable'); - expect(() => defineWorkflow({ name: '123', async run() {} })).toThrow('name must contain'); + expect(() => defineWorkflow({ name: '---', async run() {} })).toThrow('name must contain'); + const Numeric = defineWorkflow({ name: '123', async run() {} }); + expect(() => Numeric.__bind('WORKFLOW_123', '123')).not.toThrow(); }); }); describe('defineWorkflowEntrypoint', () => { + it('rejects a plain class at definition time', () => { + class Plain { + async run() {} + } + // @ts-expect-error JavaScript callers can supply an ordinary class. + expect(() => defineWorkflowEntrypoint({ class: Plain })).toThrow( + 'extending WorkflowEntrypoint', + ); + }); + it('keeps the native class and infers params from its run annotation', async () => { class Importer extends WorkflowEntrypoint, { file: string }> { override async run(_event: Readonly>, _step: WorkflowStep) { @@ -146,7 +158,7 @@ describe('defineWorkflowEntrypoint', () => { await withRuntimeEnv({ WORKFLOW_IMPORT: workflow }, () => Import.create({ params: { file: 'a.csv' } }), ); - expectTypeOf(Import).toEqualTypeOf>(); + expectTypeOf(Import).toEqualTypeOf>>(); expect(workflow.create).toHaveBeenCalledWith({ params: { file: 'a.csv' } }); }); }); diff --git a/packages/void/test/unit/workflow-runtime.typecheck.ts b/packages/void/test/unit/workflow-runtime.typecheck.ts index 6d9cc9802f..5e76908f86 100644 --- a/packages/void/test/unit/workflow-runtime.typecheck.ts +++ b/packages/void/test/unit/workflow-runtime.typecheck.ts @@ -1,4 +1,7 @@ -import { defineWorkflow } from '../../src/runtime/workflows/index.ts'; +import { WorkflowEntrypoint } from 'cloudflare:workers'; +import { defineWorkflow, defineWorkflowEntrypoint } from '../../src/runtime/workflows/index.ts'; +import type { WorkflowEvent } from '../../src/runtime/workflows/index.ts'; +import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; declare const binding: Workflow; @@ -27,3 +30,93 @@ void optional.createBatch([{}]); const noParams = defineWorkflow({ async run() {} }); void noParams.create(); void noParams.createBatch(binding, [{ id: 'instance' }]); + +interface WorkflowEnv { + MAILER: string; +} + +const envWorkflow = defineWorkflow<{ id: number }, WorkflowEnv>({ + async run(_event, _step, { env }) { + env.MAILER.toUpperCase(); + }, +}); +declare const workerEnv: WorkflowEnv, ctx: ExecutionContext; +new envWorkflow.class(ctx, workerEnv); +declare const wrongBinding: Workflow<{ name: string }>; +// @ts-expect-error This binding can't receive the declared payload. +void envWorkflow.create(wrongBinding, { params: { id: 1 } }); +// @ts-expect-error Batch options must agree with the supplied binding. +void envWorkflow.createBatch(wrongBinding, [{ params: { id: 1 } }]); + +const converted = defineWorkflow({ + params: {} as StandardSchemaV1, + async run(event) { + event.payload.id.toFixed(); + }, +}); +declare const convertedBinding: Workflow<{ id: number }>; +void converted.create(convertedBinding, { params: '1' }); +declare const stringBinding: Workflow; +// @ts-expect-error The binding receives the parsed object. +void converted.create(stringBinding, { params: '1' }); + +defineWorkflow<{ userId: string } | undefined>({ + async run(event) { + if (event.payload) { + // @ts-expect-error Cloudflare uses an empty object when the caller omits params. + event.payload.userId.toUpperCase(); + } + event.payload.userId?.toUpperCase(); + }, +}); + +defineWorkflow({ + params: {} as StandardSchemaV1, + async run(event) { + // @ts-expect-error Undefined schema outputs arrive as an empty object. + event.payload.id.toFixed(); + event.payload.id?.toFixed(); + }, +}); + +const narrowHandler = async (_event: WorkflowEvent<{ id: number } | undefined>) => {}; +// @ts-expect-error This handler cannot receive the empty object produced by omitted params. +defineWorkflow<{ id: number } | undefined>({ run: narrowHandler }); +// @ts-expect-error This annotation excludes Cloudflare's empty payload. +defineWorkflow({ run: narrowHandler }); + +const inferred = defineWorkflow({ async run(_event: WorkflowEvent<{ id: number }>) {} }); +// @ts-expect-error The event annotation must still require params. +void inferred.create(); +// @ts-expect-error The event annotation determines the id type. +void inferred.create({ params: { id: 'x' } }); + +class OptionalNative extends WorkflowEntrypoint { + override async run(_event: WorkflowEvent<{ id: number } | undefined>) {} +} +const native = defineWorkflowEntrypoint({ class: OptionalNative }); +void native.create({ params: { id: 1 } }); +// @ts-expect-error This native class can't receive the empty object used for omitted params. +void native.create(); +// @ts-expect-error Passing undefined would deliver an empty object. +void native.create({ params: undefined }); + +class AcceptsEmpty extends WorkflowEntrypoint { + override async run(_event: WorkflowEvent<{ id?: number }>) {} +} +void defineWorkflowEntrypoint({ class: AcceptsEmpty }).create(); + +class VoidNative extends WorkflowEntrypoint { + override async run(_event: WorkflowEvent) {} +} +const voidNative = defineWorkflowEntrypoint({ class: VoidNative }); +// @ts-expect-error This native class expects void but the engine delivers an empty object. +void voidNative.create(); + +const noPayload = defineWorkflow({ + async run(event) { + const empty: Record = event.payload; + return empty; + }, +}); +void noPayload.create(); diff --git a/packages/void/test/unit/workflow-scan.test.ts b/packages/void/test/unit/workflow-scan.test.ts index ecc3fcf0c0..4cb0d11b94 100644 --- a/packages/void/test/unit/workflow-scan.test.ts +++ b/packages/void/test/unit/workflow-scan.test.ts @@ -56,6 +56,7 @@ describe('scanWorkflowModules', () => { { filePath: toSlash(join(root, 'workflows', 'send-welcome.ts')), relativePath: 'send-welcome.ts', + definition: 'defineWorkflow', bindingName: 'WORKFLOW_SEND_WELCOME', className: 'SendWelcomeWorkflow', resourceName: 'send-welcome', @@ -69,6 +70,7 @@ describe('scanWorkflowModules', () => { { filePath: toSlash(join(root, 'workflows', 'order', 'notifications.ts')), relativePath: 'order/notifications.ts', + definition: 'defineWorkflow', bindingName: 'WORKFLOW_ORDER_NOTIFICATIONS', className: 'OrderNotificationsWorkflow', resourceName: 'order-notifications', @@ -76,6 +78,19 @@ describe('scanWorkflowModules', () => { ]); }); + it('discovers local value exports aliased to default', () => { + const source = `import { defineWorkflow } from 'void/workflows'; +const Job = defineWorkflow({ name: 'daily', async run() {} });`; + const root = createRoot({ + 'digest.ts': `${source}\nexport { Job, Job as default };`, + 'types.ts': `${source}\nexport { type Job as default };`, + 'other.ts': `${source}\nexport { Job as default } from './digest';`, + }); + expect(scanWorkflowModules(root).map(({ relativePath, name }) => [relativePath, name])).toEqual( + [['digest.ts', 'daily']], + ); + }); + it('ignores files and directories starting with an underscore', () => { const root = createRoot({ 'welcome.ts': definition, @@ -163,6 +178,9 @@ describe('Cloudflare Workflow names', () => { expect(planWorkflowAdditions([authored], modules, 'app')).toEqual([ { name: 'app-import', binding: 'WORKFLOW_IMPORT', class_name: 'ImportWorkflow' }, ]); + expect(planWorkflowAdditions([{ ...authored, script_name: 'app' }], modules, 'app')).toEqual([ + { name: 'app-import', binding: 'WORKFLOW_IMPORT', class_name: 'ImportWorkflow' }, + ]); expect(planWorkflowAdditions([], [], 'app')).toEqual([]); }); From 914209aeee6abe84e338a0d0aadcfa35969b8ba8 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Tue, 1 Dec 2026 10:35:04 +0900 Subject: [PATCH 5/7] Fix Workflow discovery, execution scope, and static deployment. --- .github/scripts/packed-consumer.mjs | 31 ++++++ docs/guide/workflows.md | 4 +- packages/void/package.json | 1 + packages/void/src/cli/deploy-helpers.ts | 2 +- packages/void/src/cli/deploy.ts | 4 +- packages/void/src/cli/preset.ts | 16 ++- packages/void/src/deploy.ts | 2 +- packages/void/src/router/compile.ts | 27 +++--- packages/void/src/runtime/workflows/entry.ts | 97 +++++++++++++++++++ .../void/src/shared/resource-definition.ts | 23 ++++- .../integration/full-deploy-manifest.test.ts | 16 +++ .../test/integration/workflow-runtime.test.ts | 80 ++++++++++++++- packages/void/test/unit/compile.test.ts | 4 +- .../unit/deploy-artifact-preparation.test.ts | 21 ++++ .../void/test/unit/plugin-inference.test.ts | 4 +- .../void/test/unit/workflow-runtime.test.ts | 47 +++++++++ packages/void/test/unit/workflow-scan.test.ts | 9 ++ packages/void/vite.config.ts | 2 + 18 files changed, 363 insertions(+), 27 deletions(-) create mode 100644 packages/void/src/runtime/workflows/entry.ts diff --git a/.github/scripts/packed-consumer.mjs b/.github/scripts/packed-consumer.mjs index 383a57fb34..6072449505 100644 --- a/.github/scripts/packed-consumer.mjs +++ b/.github/scripts/packed-consumer.mjs @@ -326,6 +326,37 @@ try { JSON.parse(readFileSync(join(fixture, 'node_modules/void/package.json'), 'utf8')).version, version, ); + if (framework === 'react') { + // A standalone Workflow can be the only Void import in a worker project. + writeFileSync( + join(fixture, 'workflow.mts'), + `import { defineWorkflow } from 'void/workflows'; +export default defineWorkflow<{ id: string }>({ + async run(event, step) { return step.do('id', async () => event.payload.id); }, +});`, + ); + writeFileSync( + join(fixture, 'tsconfig.workflow.json'), + JSON.stringify({ + compilerOptions: { + module: 'NodeNext', + target: 'ES2022', + lib: ['ES2022'], + types: [], + strict: true, + noEmit: true, + }, + files: ['workflow.mts'], + }), + ); + await run( + process.execPath, + [join(fixture, 'node_modules/typescript/bin/tsc'), '-p', 'tsconfig.workflow.json'], + fixture, + ); + rmSync(join(fixture, 'workflow.mts')); + rmSync(join(fixture, 'tsconfig.workflow.json')); + } await run(process.execPath, [cli, 'prepare'], fixture); await run(manager, manager === 'npm' ? ['ci'] : ['install', '--frozen-lockfile'], fixture); const vite = join( diff --git a/docs/guide/workflows.md b/docs/guide/workflows.md index 70807e13f2..9e1b858df9 100644 --- a/docs/guide/workflows.md +++ b/docs/guide/workflows.md @@ -43,6 +43,8 @@ TypeScript and JavaScript files are supported, including subdirectories. Void di Imports such as `void/env`, `void/db`, and `void/kv` work inside steps. Keep side effects inside `step.do()` so a retry or a resumed instance doesn't repeat them. +Each step attempt has its own D1 session. To start from a bookmark, call `setSession({ bookmark })` inside the step before its first query. + ## Start an instance from a route ```ts @@ -163,4 +165,4 @@ Workflows are available on the Workers Free plan, within [Cloudflare's Workflows If Cloudflare rejects staging because you added, renamed, or removed a Workflow, run `void deploy --platform cloudflare --atomic` for that deployment. The new version receives traffic before Void checks readiness. -Void platforms do not support Workflows yet: `void deploy` to a Void platform stops with an error while `workflows/` contains modules. Workflows are also unavailable in meta-framework apps and on Node.js, Bun, and Deno. +Deploy the Workflow itself to Cloudflare. You can publish the same project's static assets to a Void platform with `void deploy --dir dist` or an explicit `inference.appType` of `static` or `spa`. Meta-framework apps and Node.js, Bun, and Deno targets do not support Workflows. diff --git a/packages/void/package.json b/packages/void/package.json index 5cafe97a4c..0020d58024 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -46,6 +46,7 @@ "#self/runtime/migration-handler-pg": "./dist/runtime/db/migrations/postgres-handler.mjs", "#self/runtime/migration-handler-mysql": "./dist/runtime/db/migrations/mysql-handler.mjs", "#self/runtime/ws-server": "./dist/runtime/ws/server.mjs", + "#self/runtime/workflow-entry": "./dist/runtime/workflows/entry.mjs", "#self/runtime/routing": "./dist/runtime/routing/index.mjs" }, "exports": { diff --git a/packages/void/src/cli/deploy-helpers.ts b/packages/void/src/cli/deploy-helpers.ts index 547cf5c1eb..f3e2dd6cd3 100644 --- a/packages/void/src/cli/deploy-helpers.ts +++ b/packages/void/src/cli/deploy-helpers.ts @@ -386,7 +386,7 @@ export function resolveStaticDeployPreset( }; // Re-detect build command (config stores app type, not command). - const detectedPreset = detectPreset(root, { spa: options?.spa }); + const detectedPreset = detectPreset(root, { spa: options?.spa, skipWorkflowDiscovery: true }); if (detectedPreset) { preset.buildCommand = detectedPreset.buildCommand; if (!outputDir) { diff --git a/packages/void/src/cli/deploy.ts b/packages/void/src/cli/deploy.ts index 413446b7e3..96d464b606 100644 --- a/packages/void/src/cli/deploy.ts +++ b/packages/void/src/cli/deploy.ts @@ -304,7 +304,6 @@ async function runManagedDeploy( // Resolve the app type: void.config.ts > CLI flags > auto-detection. const voidConfig = readConfig(root); - assertNoWorkflowsForPlatform(root); cliLog.info('config_resolved', { target: voidConfig.target, appType: voidConfig.inference?.appType, @@ -315,6 +314,9 @@ async function runManagedDeploy( dir: options?.dir, spa: options?.spa, }); + if (!preset) { + assertNoWorkflowsForPlatform(root); + } // Check for known framework after static overrides. const detected = detectFramework(root); diff --git a/packages/void/src/cli/preset.ts b/packages/void/src/cli/preset.ts index f1d09da8f1..522b85bbe6 100644 --- a/packages/void/src/cli/preset.ts +++ b/packages/void/src/cli/preset.ts @@ -245,7 +245,12 @@ export function formatProjectCommand(root: string, command: string): string { */ export function detectPreset( root: string, - options?: { dir?: string; spa?: boolean; strictBackend?: boolean }, + options?: { + dir?: string; + spa?: boolean; + strictBackend?: boolean; + skipWorkflowDiscovery?: boolean; + }, ): StaticPreset | null { // 1. Explicit --dir flag: skip build, use provided directory if (options?.dir) { @@ -281,7 +286,7 @@ export function detectPreset( } // 3. Has backend files → full deploy - if (hasBackendFiles(root)) { + if (hasBackendFiles(root, options)) { return null; } @@ -481,12 +486,15 @@ export function findBackendSources(root: string): Array { /** * Check whether the project has backend files that require a full worker deploy. */ -export function hasBackendFiles(root: string): boolean { +export function hasBackendFiles( + root: string, + options?: { skipWorkflowDiscovery?: boolean }, +): boolean { const paths = readProjectPaths(root); return ( backendDirs(paths).some((dir) => existsSync(dir)) || hasSsrEntry(root, paths) || - scanWorkflowModules(root).length > 0 + (!options?.skipWorkflowDiscovery && scanWorkflowModules(root).length > 0) ); } diff --git a/packages/void/src/deploy.ts b/packages/void/src/deploy.ts index f9a6d9c3e7..c68d9d23ed 100644 --- a/packages/void/src/deploy.ts +++ b/packages/void/src/deploy.ts @@ -84,10 +84,10 @@ export async function prepareDeployArtifact( if (isNodeTarget(config.target) || config.output === 'static') { throw new Error('Artifact preparation requires a Void Cloudflare Worker build.'); } - assertNoWorkflowsForPlatform(root); let preset = resolveStaticDeployPreset(root, config); let analysis: Awaited> | undefined; if (!preset) { + assertNoWorkflowsForPlatform(root); analysis = await analyzeApplication(root, { config, environment: 'prod' }); if ( !config.inference?.appType && diff --git a/packages/void/src/router/compile.ts b/packages/void/src/router/compile.ts index 6f1ca1f49d..5646463694 100644 --- a/packages/void/src/router/compile.ts +++ b/packages/void/src/router/compile.ts @@ -1231,7 +1231,7 @@ function compileResourceModules( directory: string; prefix: string; helpers: string; - validateWorkflowEnv?: boolean; + wrapClass?: (classExpression: string) => string; }, ): ResourceModuleCode { const imports = entries @@ -1245,18 +1245,12 @@ function compileResourceModules( const local = `${options.variable}${index}`; const file = `${options.directory}/${relativePath ?? filePath.replaceAll('\\', '/').split('/').pop()}`; const message = `${options.prefix}: ${file} must default-export ${options.helpers}.`; + const resourceClass = `${local}.class`; return [ `const ${local} = ${options.variable}Module${index}.default;`, `if (typeof ${local}?.__bind !== "function") { throw new Error(${JSON.stringify(message)}); }`, `${local}.__bind(${JSON.stringify(bindingName)}${name !== undefined ? `, ${JSON.stringify(name)}` : ''});`, - options.validateWorkflowEnv - ? `export class ${className} extends ${local}.class { - async run(event, step) { - await _validateEnvOnce(this.env); - return withRuntimeEnv(this.env, () => super.run(event, step)); - } -}` - : `export const ${className} = ${local}.class;`, + `export const ${className} = ${options.wrapClass?.(resourceClass) ?? resourceClass};`, ].join('\n'); }) .join('\n'); @@ -1350,9 +1344,20 @@ export function compileWorkerEntry(options: WorkerEntryOptions = {}): string { directory: 'workflows', prefix: 'workflows', helpers: 'defineWorkflow() or defineWorkflowEntrypoint()', - validateWorkflowEnv: Boolean(envSchemaModule), + wrapClass: (workflowClass) => + `__createWorkflowEntrypoint(${workflowClass}, { ${[ + envSchemaModule && 'validateEnv: _validateEnvOnce', + remotePath && `remoteEnv: (env) => ${createRemoteEnvCall}`, + ] + .filter(Boolean) + .join(', ')} })`, }); - const resourceModuleImports = [durableObjectModules.imports, workflowModules.imports] + const resourceModuleImports = [ + durableObjectModules.imports, + workflows.length > 0 && + `import { createWorkflowEntrypoint as __createWorkflowEntrypoint } from ${JSON.stringify(fileURLToPath(import.meta.resolve('#self/runtime/workflow-entry')))};`, + workflowModules.imports, + ] .filter(Boolean) .join('\n'); const resourceModuleExports = [durableObjectModules.exports, workflowModules.exports] diff --git a/packages/void/src/runtime/workflows/entry.ts b/packages/void/src/runtime/workflows/entry.ts new file mode 100644 index 0000000000..50fc554b95 --- /dev/null +++ b/packages/void/src/runtime/workflows/entry.ts @@ -0,0 +1,97 @@ +import type { + WorkflowEntrypoint, + WorkflowEvent, + WorkflowStep, + WorkflowStepConfig, + WorkflowStepContext, + WorkflowStepRollbackOptions, +} from 'cloudflare:workers'; +import { withRuntimeEnv } from '../env/runtime.ts'; +import type { RuntimeEnv } from '../env/runtime.ts'; + +type StepCallback = (context: WorkflowStepContext) => Promise; + +// Workflows invokes these callbacks over RPC. Each invocation needs its own +// request scope: a D1 session belongs to the step attempt that opened it. +function scopedStep(step: WorkflowStep, env: RuntimeEnv): WorkflowStep { + function scoped(callback: (input: Input) => Output) { + return typeof callback === 'function' + ? (input: Input) => withRuntimeEnv(env, () => callback(input)) + : callback; + } + + function scopedConfig(config: WorkflowStepConfig) { + const retries = config?.retries; + return typeof retries?.delay === 'function' + ? { ...config, retries: { ...retries, delay: scoped(retries.delay) } } + : config; + } + + function scopedRollback(options?: WorkflowStepRollbackOptions) { + return typeof options?.rollback === 'function' + ? { + ...options, + rollback: scoped(options.rollback), + ...(options.rollbackConfig && { rollbackConfig: scopedConfig(options.rollbackConfig) }), + } + : options; + } + + function runStep>( + name: string, + configOrCallback: WorkflowStepConfig | StepCallback, + callbackOrRollback?: StepCallback | WorkflowStepRollbackOptions, + rollback?: WorkflowStepRollbackOptions, + ) { + if (typeof configOrCallback === 'function') { + return step.do( + name, + scoped(configOrCallback), + scopedRollback(callbackOrRollback as WorkflowStepRollbackOptions | undefined), + ); + } + return step.do( + name, + scopedConfig(configOrCallback), + scoped(callbackOrRollback as StepCallback), + scopedRollback(rollback), + ); + } + + return { + // The overloads narrow the callback context from retries.delay. The engine + // supplies that context unchanged to each callback. + do: runStep as WorkflowStep['do'], + sleep: (name, duration) => step.sleep(name, duration), + sleepUntil: (name, timestamp) => step.sleepUntil(name, timestamp), + waitForEvent: (name, options) => step.waitForEvent(name, options), + }; +} + +type Entrypoint = new ( + ctx: ExecutionContext, + env: RuntimeEnv, +) => WorkflowEntrypoint; + +/** Create the class exported by the generated Worker for either Workflow definition form. */ +export function createWorkflowEntrypoint( + Workflow: Entrypoint, + options: { + validateEnv?: (env: RuntimeEnv) => Promise; + remoteEnv?: (env: RuntimeEnv) => RuntimeEnv; + }, +): Entrypoint { + return class extends Workflow { + constructor(ctx: ExecutionContext, env: RuntimeEnv) { + super(ctx, env.__VOID_REMOTE === '1' && options.remoteEnv ? options.remoteEnv(env) : env); + } + + override async run(event: Readonly>, step: WorkflowStep) { + const env = this.env; + if (options.validateEnv) { + await options.validateEnv(env); + } + return withRuntimeEnv(env, () => super.run(event, scopedStep(step, env))); + } + }; +} diff --git a/packages/void/src/shared/resource-definition.ts b/packages/void/src/shared/resource-definition.ts index bcfeb1d6d2..6394b5003b 100644 --- a/packages/void/src/shared/resource-definition.ts +++ b/packages/void/src/shared/resource-definition.ts @@ -13,7 +13,6 @@ import type { AstImportNamespaceSpecifier, AstImportSpecifier, AstNode, - AstProgram, AstVariableDeclaration, } from './ast.ts'; import { isResourceName, isWorkflowName } from './resource-name.ts'; @@ -26,12 +25,28 @@ export function readResourceDefinition( helpers: ReadonlySet, convention?: 'workflows', ): { helper: string; options?: AstNode; name?: string } | null { - let program: AstProgram; + let parsed: ReturnType; try { - program = asAstProgram(parseSync(filename, source).program); - } catch { + parsed = parseSync(filename, source); + } catch (error) { + if (convention === 'workflows' && source.includes('void/workflows')) { + throw new Error(`workflows: could not parse ${filename}`, { cause: error }); + } return null; } + // A fatal parse error can leave the AST empty and even stop before the import. + // Keep unrelated scripts in workflows/ outside the convention. + if ( + convention === 'workflows' && + parsed.errors.length > 0 && + (parsed.module.staticImports.some( + ({ moduleRequest }) => moduleRequest.value === 'void/workflows', + ) || + /\bfrom\s*['"]void\/workflows['"]/.test(source)) + ) { + throw new SyntaxError(`workflows: could not parse ${filename}\n${parsed.errors[0].codeframe}`); + } + const program = asAstProgram(parsed.program); const constants = new Map(); const definitions = new Map(); diff --git a/packages/void/test/integration/full-deploy-manifest.test.ts b/packages/void/test/integration/full-deploy-manifest.test.ts index dc2d853af1..3447b75443 100644 --- a/packages/void/test/integration/full-deploy-manifest.test.ts +++ b/packages/void/test/integration/full-deploy-manifest.test.ts @@ -218,6 +218,22 @@ describe('managed deployment manifests (built Worker)', () => { playground?.cleanup(); }); + it('deploys an explicit static directory alongside Workflow sources', async () => { + const workflows = join(fixture, 'workflows'); + mkdirSync(workflows); + try { + writeFileSync( + join(workflows, 'job.ts'), + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });", + ); + const captured = installPlatformMocks(); + await runDeploy(fixture, { dir: 'dist/client' }); + expect(captured.finalizeBody?.manifest).toMatchObject({ type: 'static', bindings: {} }); + } finally { + rmSync(workflows, { recursive: true, force: true }); + } + }); + beforeEach(() => { mockDetectFramework.mockReset().mockReturnValue(undefined); diff --git a/packages/void/test/integration/workflow-runtime.test.ts b/packages/void/test/integration/workflow-runtime.test.ts index e512b4eca0..a0bc302232 100644 --- a/packages/void/test/integration/workflow-runtime.test.ts +++ b/packages/void/test/integration/workflow-runtime.test.ts @@ -181,10 +181,15 @@ export default defineEnv({ VALUE: { '~standard': { ` import { WorkflowEntrypoint } from 'cloudflare:workers'; import { env } from ${JSON.stringify(envPath)}; +import { db, setSession } from ${JSON.stringify(join(root, 'packages/void/src/runtime/db/index.ts'))}; import { defineWorkflow, defineWorkflowEntrypoint } from ${JSON.stringify(runtimePath)}; async function run(event, step) { const value = env.VALUE; - return step.do('read', async () => value + 1); + setSession('first-primary'); + return step.do('read', { retries: { limit: 0, delay: 0 } }, async () => { + setSession('first-primary'); + return { value: value + 1, sameSession: db.$client === db.$client }; + }); } ${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run });' : 'class Cold extends WorkflowEntrypoint { run(event, step) { return run(event, step); } } export default defineWorkflowEntrypoint({ class: Cold });'} `, @@ -205,6 +210,7 @@ ${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run });' : 'cla modulesRoot: output, scriptPath: join(output, 'worker.mjs'), bindings: { VALUE: '41' }, + d1Databases: { DB: 'test' }, workflows: { COLD: { name: 'cold', className: 'ColdWorkflow' } }, }), ); @@ -216,7 +222,10 @@ ${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run });' : 'cla timeout: 5000, }) .toMatch(/^(complete|errored)$/); - expect(await instance.status()).toMatchObject({ status: 'complete', output: 42 }); + expect(await instance.status()).toMatchObject({ + status: 'complete', + output: { value: 42, sameSession: true }, + }); } finally { await worker.dispose(); } @@ -224,6 +233,73 @@ ${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run });' : 'cla ); }); +it.each(['defineWorkflow', 'defineWorkflowEntrypoint'])( + 'uses the same remote KV in a route and %s without an env schema', + async (helper) => { + const definition = file( + 'remote-' + helper + '.ts', + ` +import { WorkflowEntrypoint } from 'cloudflare:workers'; +import { getRuntimeBinding } from ${JSON.stringify(join(root, 'packages/void/src/runtime/env/runtime.ts'))}; +import { defineWorkflow, defineWorkflowEntrypoint } from ${JSON.stringify(runtimePath)}; +async function read(step, env) { + return step.do('read', async () => [ + await env.MY_KV.get('key'), await getRuntimeBinding('MY_KV').get('key'), + ]); +} +${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run(event, step, {env}) { return read(step, env); } });' : 'class Job extends WorkflowEntrypoint { run(event, step) { return read(step, this.env); } } export default defineWorkflowEntrypoint({class: Job});'} +`, + ); + const output = await buildWorker( + 'remote-' + helper, + 'export default { async fetch(req, env) { return new Response(await env.MY_KV.get("key")); } };', + { + remote: { + remotePath: join(root, 'packages/void/src/runtime/remote/index.ts'), + bindingNames: { kv: 'MY_KV' }, + }, + workflows: [{ bindingName: 'JOB', className: 'JobWorkflow', filePath: definition }], + }, + ); + const worker = new Miniflare( + convertV4MiniflareOptions({ + compatibilityDate: '2026-07-01', + compatibilityFlags: ['nodejs_compat'], + modules: true, + modulesRoot: output, + scriptPath: join(output, 'worker.mjs'), + bindings: { + __VOID_REMOTE: '1', + __VOID_PROXY_URL: 'https://proxy.test', + __VOID_PROJECT_ID: 'test', + __VOID_TOKEN: 'test', + }, + kvNamespaces: ['MY_KV'], + workflows: { JOB: { name: 'job', className: 'JobWorkflow' } }, + outboundService: (request) => + request.url === 'https://proxy.test/kv/get' + ? Response.json('remote') + : new Response(null, { status: 404 }), + }), + ); + try { + const { JOB, MY_KV } = await worker.getBindings<{ JOB: Workflow; MY_KV: KVNamespace }>(); + await MY_KV.put('key', 'local'); + expect(await (await worker.dispatchFetch('http://localhost/')).text()).toBe('remote'); + const instance = await JOB.create(); + await expect + .poll(async () => (await instance.status()).status) + .toMatch(/^(complete|errored)$/); + expect(await instance.status()).toMatchObject({ + status: 'complete', + output: ['remote', 'remote'], + }); + } finally { + await worker.dispose(); + } + }, +); + describe('convention modules without a definition default export', () => { it.each([ { diff --git a/packages/void/test/unit/compile.test.ts b/packages/void/test/unit/compile.test.ts index 517f63e490..a58549c444 100644 --- a/packages/void/test/unit/compile.test.ts +++ b/packages/void/test/unit/compile.test.ts @@ -880,7 +880,9 @@ describe('compileWorkerEntry', () => { 'import * as __voidWorkflowModule0 from "/app/workflows/onboarding.ts";', ); expect(code).toContain('__voidWorkflow0.__bind("WORKFLOW_ONBOARDING", "onboarding");'); - expect(code).toContain('export const OnboardingWorkflow = __voidWorkflow0.class;'); + expect(code).toContain( + 'export const OnboardingWorkflow = __createWorkflowEntrypoint(__voidWorkflow0.class', + ); }); it('guards convention modules that do not default-export a definition', () => { diff --git a/packages/void/test/unit/deploy-artifact-preparation.test.ts b/packages/void/test/unit/deploy-artifact-preparation.test.ts index dd84832dc6..e1d599ad9a 100644 --- a/packages/void/test/unit/deploy-artifact-preparation.test.ts +++ b/packages/void/test/unit/deploy-artifact-preparation.test.ts @@ -178,6 +178,27 @@ it.each([true, false, undefined])( }, ); +it('allows an explicit asset-only deploy from a project with Workflows', async () => { + mkdirSync(join(root, 'workflows')); + writeFileSync( + join(root, 'workflows/job.ts'), + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });", + ); + await expect(prepareDeployArtifact(root)).rejects.toThrow('not supported on Void platforms'); + // Packaging explicit static output must not even parse the Worker sources. + writeFileSync( + join(root, 'workflows/job.ts'), + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() { return ); } });", + ); + writeFileSync( + join(root, 'void.config.ts'), + "export default { inference: { appType: 'static', outputDir: 'dist/client' } };", + ); + const result = await prepareDeployArtifact(root); + expect(Object.keys(result.assets)).toEqual(['/index.html']); + expect(result.artifact.workerFiles).toBeUndefined(); +}); + it('keeps SPA plus API apps on the Worker deployment path', async () => { writeFileSync(join(root, 'package.json'), JSON.stringify({ devDependencies: { vite: '*' } })); mkdirSync(join(root, 'routes')); diff --git a/packages/void/test/unit/plugin-inference.test.ts b/packages/void/test/unit/plugin-inference.test.ts index 0f387d90c3..9f9e3a96f1 100644 --- a/packages/void/test/unit/plugin-inference.test.ts +++ b/packages/void/test/unit/plugin-inference.test.ts @@ -938,7 +938,9 @@ describe('detectFramework', () => { expect(entry).toContain('import * as __voidWorkflowModule0 from'); expect(entry).toContain('/workflows/send-welcome.ts'); expect(entry).toContain('__voidWorkflow0.__bind("WORKFLOW_SEND_WELCOME")'); - expect(entry).toContain('export const SendWelcomeWorkflow = __voidWorkflow0.class'); + expect(entry).toContain( + 'export const SendWelcomeWorkflow = __createWorkflowEntrypoint(__voidWorkflow0.class', + ); expect(entry).toContain( 'workflows: workflows/send-welcome.ts must default-export defineWorkflow() or defineWorkflowEntrypoint().', ); diff --git a/packages/void/test/unit/workflow-runtime.test.ts b/packages/void/test/unit/workflow-runtime.test.ts index 46996c7ade..53f64847f6 100644 --- a/packages/void/test/unit/workflow-runtime.test.ts +++ b/packages/void/test/unit/workflow-runtime.test.ts @@ -2,6 +2,7 @@ import { WorkflowEntrypoint } from 'cloudflare:workers'; import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers'; import { describe, expect, expectTypeOf, it, vi } from 'vite-plus/test'; import { getRuntimeEnv, withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; +import { createWorkflowEntrypoint } from '../../src/runtime/workflows/entry.ts'; import { defineWorkflow, defineWorkflowEntrypoint, @@ -52,6 +53,52 @@ const userSchema: StandardSchemaV1<{ userId: string }, { userId: string }> = { }; describe('defineWorkflow', () => { + it('restores the Worker env for deferred step, retry and rollback callbacks', async () => { + const seen: Array = []; + const delay = () => { + seen.push(getRuntimeEnv().VALUE); + return 1; + }; + const rollback = async () => { + seen.push(getRuntimeEnv().VALUE); + }; + const Job = defineWorkflow({ + async run(_event, step) { + await step.do('work', { retries: { limit: 1, delay } }, rollback, { + rollback, + rollbackConfig: { retries: { limit: 1, delay } }, + }); + }, + }); + const entry = createWorkflowEntrypoint(Job.class, {}); + const callbacks: Array<() => unknown> = []; + // Invoke the registered callbacks after run() has left its own request scope. + type RetryConfig = { retries: { delay: () => number } }; + const step = { + do( + _name: string, + config: RetryConfig, + run: () => Promise, + options: { rollback: () => Promise; rollbackConfig: RetryConfig }, + ) { + callbacks.push( + run, + config.retries.delay, + options.rollback, + options.rollbackConfig.retries.delay, + ); + }, + }; + await new entry({} as ExecutionContext, { VALUE: 'workflow' }).run( + {} as WorkflowEvent, + step as unknown as WorkflowStep, + ); + for (const callback of callbacks) { + await callback(); + } + expect(seen).toEqual(['workflow', 'workflow', 'workflow', 'workflow']); + }); + it('generates an entrypoint that runs inside the Worker env', async () => { const seen: Array = []; const Welcome = defineWorkflow({ diff --git a/packages/void/test/unit/workflow-scan.test.ts b/packages/void/test/unit/workflow-scan.test.ts index 4cb0d11b94..824397d2d8 100644 --- a/packages/void/test/unit/workflow-scan.test.ts +++ b/packages/void/test/unit/workflow-scan.test.ts @@ -33,9 +33,18 @@ afterEach(() => { }); describe('scanWorkflowModules', () => { + it.each([ + definition.replace('run() {}', 'run() { return ); }'), + `const broken = );\n${definition}`, + ])('reports a syntax error instead of dropping a Workflow', (source) => { + const root = createRoot({ 'notify.ts': source }); + expect(() => scanWorkflowModules(root)).toThrow(/notify\.ts[\s\S]*Unexpected token/i); + }); + it('ignores ordinary modules in the workflows directory', () => { const root = createRoot({ 'maintenance.ts': 'export default { run() {} }', + 'unfinished.ts': 'export default { run() { return ); } }', 'unrelated.ts': 'const defineWorkflow = (value) => value; export default defineWorkflow({});', }); diff --git a/packages/void/vite.config.ts b/packages/void/vite.config.ts index d0d7ce6f51..9a99f2225b 100644 --- a/packages/void/vite.config.ts +++ b/packages/void/vite.config.ts @@ -34,6 +34,7 @@ function injectWorkersTypesReferencePlugin() { 'runtime/live/server.d.mts', 'runtime/email/index.d.mts', 'runtime/email/testing.d.mts', + 'runtime/workflows/index.d.mts', ]); if (!targets.has(output.fileName)) { continue; @@ -105,6 +106,7 @@ export default defineConfig({ 'src/runtime/db/mysql.ts', 'src/runtime/durable/index.ts', 'src/runtime/workflows/index.ts', + 'src/runtime/workflows/entry.ts', 'src/runtime/db/seed.ts', 'src/runtime/db/validators/drizzle-zod.ts', 'src/runtime/db/validators/drizzle-valibot.ts', From b548e386cf3ceb74d0bf517aa7c96feba6202be6 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Tue, 1 Dec 2026 11:08:01 +0900 Subject: [PATCH 6/7] Fix Workflow discovery, deployment, and runtime context. --- docs/guide/workflows.md | 6 +- .../src/cli/cloudflare-deploy/classify.ts | 5 ++ packages/void/src/cli/deploy-helpers.ts | 26 ++++--- packages/void/src/cli/deploy.ts | 13 ++-- packages/void/src/cli/init.ts | 2 +- packages/void/src/cli/preset.ts | 22 +++--- packages/void/src/index.ts | 5 +- packages/void/src/router/compile.ts | 1 + packages/void/src/runtime/workflows/entry.ts | 4 ++ packages/void/src/runtime/workflows/index.ts | 4 +- .../void/src/shared/resource-definition.ts | 71 ++++++++++++------- packages/void/src/workflows/platform.ts | 3 + .../integration/full-deploy-manifest.test.ts | 6 +- .../test/integration/workflow-runtime.test.ts | 17 ++++- .../test/unit/cloudflare-classify.test.ts | 9 +++ .../unit/deploy-artifact-preparation.test.ts | 17 +++++ packages/void/test/unit/init.test.ts | 1 + .../void/test/unit/workflow-runtime.test.ts | 11 ++- packages/void/test/unit/workflow-scan.test.ts | 12 +++- 19 files changed, 168 insertions(+), 67 deletions(-) diff --git a/docs/guide/workflows.md b/docs/guide/workflows.md index 9e1b858df9..cc9a547a7f 100644 --- a/docs/guide/workflows.md +++ b/docs/guide/workflows.md @@ -33,7 +33,7 @@ export default Onboarding; Default-export the object returned by `defineWorkflow()`. Named-export it too so routes can import it. -TypeScript and JavaScript files are supported, including subdirectories. Void discovers default exports created using a helper imported from `void/workflows`. Files and directories starting with `_` are excluded from Workflow discovery. +TypeScript and JavaScript files are supported, including subdirectories. Void discovers default exports created using a helper imported from `void/workflows`. Files and directories starting with `_` are excluded from Workflow discovery. If you maintain an explicit `include` list in `tsconfig.json`, add `workflows` so TypeScript checks definitions started outside your app. `run` receives: @@ -165,4 +165,6 @@ Workflows are available on the Workers Free plan, within [Cloudflare's Workflows If Cloudflare rejects staging because you added, renamed, or removed a Workflow, run `void deploy --platform cloudflare --atomic` for that deployment. The new version receives traffic before Void checks readiness. -Deploy the Workflow itself to Cloudflare. You can publish the same project's static assets to a Void platform with `void deploy --dir dist` or an explicit `inference.appType` of `static` or `spa`. Meta-framework apps and Node.js, Bun, and Deno targets do not support Workflows. +To publish the same project's static assets to a connected Void platform, build the app and run `void deploy --platform void --dir dist/client`. You can also set `inference.appType` to `static` or `spa` and run `void deploy --platform void`. If you customize the build output, set `inference.outputDir` to the directory containing your public assets. + +Workflows require a native Void app targeting Cloudflare Workers. diff --git a/packages/void/src/cli/cloudflare-deploy/classify.ts b/packages/void/src/cli/cloudflare-deploy/classify.ts index 468c535e4c..b78b93a131 100644 --- a/packages/void/src/cli/cloudflare-deploy/classify.ts +++ b/packages/void/src/cli/cloudflare-deploy/classify.ts @@ -11,6 +11,7 @@ import { renderDeploySeedConfig } from '../../config-write.ts'; import type { VoidConfig } from '../../config.ts'; import { assertNoRootSourceConventionConflicts } from '../../project-paths.ts'; import { validateSsrEntry } from '../../ssr/entry.ts'; +import { FRAMEWORK_WORKFLOWS_ERROR } from '../../workflows/platform.ts'; import { CANDIDATE_FILE } from '../cloudflare-candidate.ts'; import { log } from '../deploy-helpers.ts'; import { deriveWorkerName } from '../deploy-resources.ts'; @@ -73,6 +74,10 @@ export function classifyCloudflareDeployApp( ); } + if (framework && application.workflows.length > 0) { + return unsupported(FRAMEWORK_WORKFLOWS_ERROR); + } + if (!framework && !hasBackendFiles(root)) { return unsupported( [ diff --git a/packages/void/src/cli/deploy-helpers.ts b/packages/void/src/cli/deploy-helpers.ts index f3e2dd6cd3..01a5699937 100644 --- a/packages/void/src/cli/deploy-helpers.ts +++ b/packages/void/src/cli/deploy-helpers.ts @@ -23,7 +23,12 @@ import { fetchRemoteSecretNames, formatEnvReport, validateProdEnv } from './env- import { isCancel, log as clackLog, text } from './interactive-prompts.ts'; import type { CliLogger } from './log-file.ts'; import { formatCount, getErrorMessage, pc } from './output.ts'; -import { detectPreset, formatProjectCommand, resolveProjectCommand } from './preset.ts'; +import { + defaultViteClientDir, + detectPreset, + formatProjectCommand, + resolveProjectCommand, +} from './preset.ts'; import type { StaticPreset } from './preset.ts'; import { attachSelectedPlatform, shouldLinkDeployProject, writeProjectConfig } from './project.ts'; import type { ProjectConfig } from './project.ts'; @@ -379,21 +384,14 @@ export function resolveStaticDeployPreset( const appType = voidConfig.inference?.appType; if (appType === 'static' || appType === 'spa') { const outputDir = voidConfig.inference?.outputDir; - const preset: StaticPreset = { - buildCommand: null, - outputDir: outputDir ? resolve(root, outputDir) : join(root, 'dist'), + const detected = detectPreset(root, { spa: options?.spa, skipWorkflowDiscovery: true }); + return { appType, + buildCommand: detected?.buildCommand ?? null, + outputDir: outputDir + ? resolve(root, outputDir) + : (detected?.outputDir ?? defaultViteClientDir(root)), }; - - // Re-detect build command (config stores app type, not command). - const detectedPreset = detectPreset(root, { spa: options?.spa, skipWorkflowDiscovery: true }); - if (detectedPreset) { - preset.buildCommand = detectedPreset.buildCommand; - if (!outputDir) { - preset.outputDir = detectedPreset.outputDir; - } - } - return preset; } return null; diff --git a/packages/void/src/cli/deploy.ts b/packages/void/src/cli/deploy.ts index 96d464b606..56f8d82532 100644 --- a/packages/void/src/cli/deploy.ts +++ b/packages/void/src/cli/deploy.ts @@ -172,6 +172,15 @@ async function runManagedDeploy( options: RunDeployOptions, cliLog: CliLogger, ): Promise { + // An explicit static deployment can share a project with a Cloudflare Workflow. + // Reject Worker deploys before looking up or creating a managed project. + if ( + !options.dir && + existsSync(join(root, 'workflows')) && + !resolveStaticDeployPreset(root, readConfig(root), options) + ) { + assertNoWorkflowsForPlatform(root); + } // Resolve the connected recipient before credentials, OIDC, builds, or platform requests. const apiUrl = getApiUrl(root); const requestedProjectSlug = getRequestedProjectSlug(options); @@ -314,10 +323,6 @@ async function runManagedDeploy( dir: options?.dir, spa: options?.spa, }); - if (!preset) { - assertNoWorkflowsForPlatform(root); - } - // Check for known framework after static overrides. const detected = detectFramework(root); // Detect git commit before build (only when not skipping build). Same scrub as diff --git a/packages/void/src/cli/init.ts b/packages/void/src/cli/init.ts index f7c587c019..9d278799ea 100644 --- a/packages/void/src/cli/init.ts +++ b/packages/void/src/cli/init.ts @@ -1089,7 +1089,7 @@ function setupTsconfig( types: ['void/env'], ...getScaffoldTsconfigCompilerOptions(pagesFramework), }, - include: ['src', 'pages', 'routes', 'middleware', 'crons', 'queues', 'db'], + include: ['src', 'pages', 'routes', 'middleware', 'crons', 'queues', 'workflows', 'db'], }; writeFileSync(tsconfigPath, JSON.stringify(tsconfig, null, 2) + '\n'); report.created('tsconfig.json'); diff --git a/packages/void/src/cli/preset.ts b/packages/void/src/cli/preset.ts index 522b85bbe6..e820fc6d68 100644 --- a/packages/void/src/cli/preset.ts +++ b/packages/void/src/cli/preset.ts @@ -297,13 +297,11 @@ export function detectPreset( const hasLocalVite = vitePlusRoot === root || hasViteDependency(pkg); if (hasLocalVite || vitePlusRoot !== undefined) { const buildCommand = resolveProjectScriptCommand(root, 'build'); - const viteConfig = VITE_CONFIG_FILES.map((name) => join(root, name)).find((path) => - existsSync(path), - ); + const viteConfig = findViteConfig(root); if (hasLocalVite || buildCommand || viteConfig || existsSync(join(root, 'index.html'))) { return { buildCommand: buildCommand ?? resolveProjectCommand(root, 'vite build'), - outputDir: resolve(root, viteSpaOutputDir(viteConfig)), + outputDir: defaultViteClientDir(root, viteConfig), appType: 'spa', }; } @@ -418,17 +416,23 @@ const VITE_CONFIG_FILES = [ ]; /** - * Where a Vite SPA build puts its browser files. A Vite config that uses + * Where a Vite build puts its browser files. A Vite config that uses * `voidPlugin()` (`void init` adds it) splits the output into `dist/client` * (browser files) and `dist/ssr` (the server bundle, its source map and * `wrangler.json`). Only `dist/client` may be uploaded: uploading `dist` * publishes the server files and leaves `/` without an `index.html`. A * project that installs `void` only for its CLI keeps Vite's plain `dist`. */ -function viteSpaOutputDir(config: string | undefined): string { - return config && viteConfigImportsVoidPlugin(config, readFileSync(config, 'utf8')) - ? 'dist/client' - : 'dist'; +export function defaultViteClientDir( + root: string, + config: string | undefined = findViteConfig(root), +): string { + const usesVoid = config && viteConfigImportsVoidPlugin(config, readFileSync(config, 'utf8')); + return resolve(root, usesVoid ? 'dist/client' : 'dist'); +} + +function findViteConfig(root: string): string | undefined { + return VITE_CONFIG_FILES.map((name) => join(root, name)).find((path) => existsSync(path)); } function hasViteDependency(pkg: Record): boolean { diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index 0f5f8e2a9a..e1a3290c5d 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -90,6 +90,7 @@ import type { RouteEnvironment } from './router/parse-filename.ts'; import { resolveSandboxConfig } from './sandbox/config.ts'; import { CLOUDFLARE_DEPLOY_BUILD_ENV, loadLocalEnv, resolveRemoteMode } from './shared/env.ts'; import { getSsrServerEntryPath, validateSsrEntry } from './ssr/entry.ts'; +import { FRAMEWORK_WORKFLOWS_ERROR } from './workflows/platform.ts'; const scheduledPointerCleanups = new Set(); @@ -268,9 +269,7 @@ export function voidPlugin(options?: { } const workflows = application.workflows; if (detected && workflows.length > 0) { - throw new Error( - 'workflows: workflows/ is currently supported in Void apps only, not framework adapter mode.', - ); + throw new Error(FRAMEWORK_WORKFLOWS_ERROR); } for (const module of workflows) { const owner = diff --git a/packages/void/src/router/compile.ts b/packages/void/src/router/compile.ts index 5646463694..a4424b4edf 100644 --- a/packages/void/src/router/compile.ts +++ b/packages/void/src/router/compile.ts @@ -1346,6 +1346,7 @@ export function compileWorkerEntry(options: WorkerEntryOptions = {}): string { helpers: 'defineWorkflow() or defineWorkflowEntrypoint()', wrapClass: (workflowClass) => `__createWorkflowEntrypoint(${workflowClass}, { ${[ + isr && 'isrDeploymentId: __VOID_ISR_DEPLOYMENT_ID', envSchemaModule && 'validateEnv: _validateEnvOnce', remotePath && `remoteEnv: (env) => ${createRemoteEnvCall}`, ] diff --git a/packages/void/src/runtime/workflows/entry.ts b/packages/void/src/runtime/workflows/entry.ts index 50fc554b95..18189a4418 100644 --- a/packages/void/src/runtime/workflows/entry.ts +++ b/packages/void/src/runtime/workflows/entry.ts @@ -77,6 +77,7 @@ type Entrypoint = new ( export function createWorkflowEntrypoint( Workflow: Entrypoint, options: { + isrDeploymentId?: string; validateEnv?: (env: RuntimeEnv) => Promise; remoteEnv?: (env: RuntimeEnv) => RuntimeEnv; }, @@ -88,6 +89,9 @@ export function createWorkflowEntrypoint( override async run(event: Readonly>, step: WorkflowStep) { const env = this.env; + if (options.isrDeploymentId !== undefined) { + env.__VOID_ISR_DEPLOYMENT_ID ??= options.isrDeploymentId; + } if (options.validateEnv) { await options.validateEnv(env); } diff --git a/packages/void/src/runtime/workflows/index.ts b/packages/void/src/runtime/workflows/index.ts index 0e1d1f3452..1363ebe008 100644 --- a/packages/void/src/runtime/workflows/index.ts +++ b/packages/void/src/runtime/workflows/index.ts @@ -2,7 +2,7 @@ import { WorkflowEntrypoint } from 'cloudflare:workers'; import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers'; import { isWorkflowName } from '../../shared/resource-name.ts'; import type { StandardSchemaV1 } from '../../standard-schema.ts'; -import { requireRuntimeBinding, withRuntimeEnv } from '../env/runtime.ts'; +import { getRuntimeEnv, requireRuntimeBinding, withRuntimeEnv } from '../env/runtime.ts'; export type { WorkflowEvent, WorkflowStep }; @@ -223,7 +223,7 @@ export function defineWorkflow( override run(event: Readonly>, step: WorkflowStep): Promise { const env = this.env; const ctx = this.ctx; - return withRuntimeEnv(env, () => run(event, step, { env, ctx })); + return withRuntimeEnv(env, () => run(event, step, { env: getRuntimeEnv(), ctx })); } } diff --git a/packages/void/src/shared/resource-definition.ts b/packages/void/src/shared/resource-definition.ts index 6394b5003b..9b1de28315 100644 --- a/packages/void/src/shared/resource-definition.ts +++ b/packages/void/src/shared/resource-definition.ts @@ -204,34 +204,53 @@ export function readResourceDefinition( return name; } - const declaration = unwrapStaticExpression(defaultExport); - const call = resolve(isIdentifier(declaration) ? definitions.get(declaration.name) : declaration); - if (!isCallExpression(call)) { - return null; - } - const callee = resolve(call.callee); - let helper: string | undefined; - if (isIdentifier(callee)) { - helper = - importedHelpers.get(callee.name) ?? - (convention !== 'workflows' && helpers.has(callee.name) ? callee.name : undefined); - } else if (isMemberExpression(callee) && isIdentifier(callee.object)) { - const property = - !callee.computed && isIdentifier(callee.property) - ? callee.property.name - : staticLiteral(callee.property); - if ( - typeof property === 'string' && - helpers.has(property) && - namespaces.get(callee.object.name)?.has(property) - ) { - helper = property; + function resourceCall(node: AstNode | undefined) { + const call = resolve(node); + if (!isCallExpression(call)) { + return null; + } + const callee = resolve(call.callee); + let helper: string | undefined; + if (isIdentifier(callee)) { + helper = + importedHelpers.get(callee.name) ?? + (convention !== 'workflows' && helpers.has(callee.name) ? callee.name : undefined); + } else if (isMemberExpression(callee) && isIdentifier(callee.object)) { + const property = + !callee.computed && isIdentifier(callee.property) + ? callee.property.name + : staticLiteral(callee.property); + if ( + typeof property === 'string' && + helpers.has(property) && + namespaces.get(callee.object.name)?.has(property) + ) { + helper = property; + } } + if (!helper) { + return null; + } + return { helper, options: resolve(call.arguments?.[0]) }; } - if (!helper) { + + const declaration = unwrapStaticExpression(defaultExport); + const definition = resourceCall( + isIdentifier(declaration) ? definitions.get(declaration.name) : declaration, + ); + if (!definition) { + if (convention === 'workflows') { + const hasWorkflow = + [...definitions.values()].some(resourceCall) || + program.body?.some( + (node) => node.type === 'ExpressionStatement' && resourceCall(node.expression as AstNode), + ); + if (hasWorkflow) { + throw new Error(`workflows: ${filename} must default-export its Workflow definition.`); + } + } return null; } - const definitionOptions = resolve(call.arguments?.[0]); - const name = readName(definitionOptions).value; - return { helper, options: definitionOptions, ...(name === undefined ? {} : { name }) }; + const name = readName(definition.options).value; + return { ...definition, ...(name === undefined ? {} : { name }) }; } diff --git a/packages/void/src/workflows/platform.ts b/packages/void/src/workflows/platform.ts index b06544ff3c..c88b69a14e 100644 --- a/packages/void/src/workflows/platform.ts +++ b/packages/void/src/workflows/platform.ts @@ -1,5 +1,8 @@ import { scanWorkflowModules } from './scan.ts'; +export const FRAMEWORK_WORKFLOWS_ERROR = + 'workflows: workflows/ is currently supported in Void apps only, not framework adapter mode.'; + /** Void platform deploys do not provision Cloudflare Workflows yet. */ export function assertNoWorkflowsForPlatform(root: string): void { if (scanWorkflowModules(root).length > 0) { diff --git a/packages/void/test/integration/full-deploy-manifest.test.ts b/packages/void/test/integration/full-deploy-manifest.test.ts index 3447b75443..eed52fd8b3 100644 --- a/packages/void/test/integration/full-deploy-manifest.test.ts +++ b/packages/void/test/integration/full-deploy-manifest.test.ts @@ -227,7 +227,11 @@ describe('managed deployment manifests (built Worker)', () => { "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });", ); const captured = installPlatformMocks(); - await runDeploy(fixture, { dir: 'dist/client' }); + await expect(runDeploy(fixture, { platform: 'void' })).rejects.toThrow( + 'not supported on Void platforms', + ); + expect(fetchMock).not.toHaveBeenCalled(); + await runDeploy(fixture, { platform: 'void', dir: 'dist/client' }); expect(captured.finalizeBody?.manifest).toMatchObject({ type: 'static', bindings: {} }); } finally { rmSync(workflows, { recursive: true, force: true }); diff --git a/packages/void/test/integration/workflow-runtime.test.ts b/packages/void/test/integration/workflow-runtime.test.ts index a0bc302232..feb82e24be 100644 --- a/packages/void/test/integration/workflow-runtime.test.ts +++ b/packages/void/test/integration/workflow-runtime.test.ts @@ -1,6 +1,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { isrKey } from '@void/isr/runtime'; import { Miniflare, convertV4MiniflareOptions } from 'miniflare'; import { build } from 'vite'; import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'; @@ -181,6 +182,7 @@ export default defineEnv({ VALUE: { '~standard': { ` import { WorkflowEntrypoint } from 'cloudflare:workers'; import { env } from ${JSON.stringify(envPath)}; +import { revalidate } from ${JSON.stringify(join(root, 'packages/void/src/runtime/isr/index.ts'))}; import { db, setSession } from ${JSON.stringify(join(root, 'packages/void/src/runtime/db/index.ts'))}; import { defineWorkflow, defineWorkflowEntrypoint } from ${JSON.stringify(runtimePath)}; async function run(event, step) { @@ -188,6 +190,7 @@ async function run(event, step) { setSession('first-primary'); return step.do('read', { retries: { limit: 0, delay: 0 } }, async () => { setSession('first-primary'); + await revalidate({ all: true }); return { value: value + 1, sameSession: db.$client === db.$client }; }); } @@ -196,8 +199,11 @@ ${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run });' : 'cla ); const output = await buildWorker( 'cold-' + helper, - 'export default { fetch: () => new Response() };', + `export const __VOID_ISR_DEPLOYMENT_ID = 'cold-build'; +export const __VOID_ISR_REVALIDATE = 60, __VOID_ISR_PAGES = [], __VOID_ISR_PATH_REVALIDATE = undefined; +export default { fetch: () => new Response() };`, { + isr: { runtimePath: join(root, 'packages/isr/src/runtime.ts') }, envSchemaModule: { importPath: schema, helperPath: envPath }, workflows: [{ bindingName: 'COLD', className: 'ColdWorkflow', filePath: definition }], }, @@ -211,11 +217,17 @@ ${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run });' : 'cla scriptPath: join(output, 'worker.mjs'), bindings: { VALUE: '41' }, d1Databases: { DB: 'test' }, + kvNamespaces: ['ISR_CACHE'], workflows: { COLD: { name: 'cold', className: 'ColdWorkflow' } }, }), ); try { - const { COLD } = await worker.getBindings<{ COLD: Workflow }>(); + const { COLD, ISR_CACHE } = await worker.getBindings<{ + COLD: Workflow; + ISR_CACHE: KVNamespace; + }>(); + const cachedPage = isrKey('cold-build', 'example.test', '/news'); + await ISR_CACHE.put(cachedPage, 'cached'); const instance = await COLD.create(); await expect .poll(async () => (await instance.status()).status, { @@ -226,6 +238,7 @@ ${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run });' : 'cla status: 'complete', output: { value: 42, sameSession: true }, }); + expect(await ISR_CACHE.get(cachedPage)).toBeNull(); } finally { await worker.dispose(); } diff --git a/packages/void/test/unit/cloudflare-classify.test.ts b/packages/void/test/unit/cloudflare-classify.test.ts index 13bac71d7c..d4338c0c6a 100644 --- a/packages/void/test/unit/cloudflare-classify.test.ts +++ b/packages/void/test/unit/cloudflare-classify.test.ts @@ -46,6 +46,15 @@ describe('classifyCloudflareDeployApp', () => { expect(resolveCloudflareStaticPreset(root, {}, {})).toBeNull(); expect(classify(root, {})).toEqual({ supported: true }); expect(classify(root, { inference: { appType: 'void' } })).toEqual({ supported: true }); + + writeFileSync( + join(root, 'package.json'), + JSON.stringify({ dependencies: { '@sveltejs/kit': '*' } }), + ); + expect(classify(root, {})).toEqual({ + supported: false, + reason: expect.stringContaining('framework adapter mode'), + }); }); it('keeps the full Worker when Pages are prerendered and a Workflow is declared', async () => { diff --git a/packages/void/test/unit/deploy-artifact-preparation.test.ts b/packages/void/test/unit/deploy-artifact-preparation.test.ts index e1d599ad9a..f01255bfe9 100644 --- a/packages/void/test/unit/deploy-artifact-preparation.test.ts +++ b/packages/void/test/unit/deploy-artifact-preparation.test.ts @@ -199,6 +199,23 @@ it('allows an explicit asset-only deploy from a project with Workflows', async ( expect(result.artifact.workerFiles).toBeUndefined(); }); +it.each(['static', 'spa'])( + 'packages only browser assets for an explicit %s Void app with routes', + async (appType) => { + mkdirSync(join(root, 'routes')); + writeFileSync( + join(root, 'vite.config.ts'), + "import { voidPlugin } from 'void'; export default { plugins: [voidPlugin()] };", + ); + writeFileSync( + join(root, 'void.config.ts'), + `export default { inference: { appType: '${appType}' } };`, + ); + const result = await prepareDeployArtifact(root); + expect(Object.keys(result.assets)).toEqual(['/index.html']); + }, +); + it('keeps SPA plus API apps on the Worker deployment path', async () => { writeFileSync(join(root, 'package.json'), JSON.stringify({ devDependencies: { vite: '*' } })); mkdirSync(join(root, 'routes')); diff --git a/packages/void/test/unit/init.test.ts b/packages/void/test/unit/init.test.ts index ae8bb331b6..5e573be32c 100644 --- a/packages/void/test/unit/init.test.ts +++ b/packages/void/test/unit/init.test.ts @@ -2478,6 +2478,7 @@ describe('isScaffoldableEmptyProject', () => { const tsconfig = JSON.parse(readFileSync(join(root, 'tsconfig.json'), 'utf8')); expect(tsconfig.compilerOptions.jsx).toBe('react-jsx'); expect(tsconfig.include).toContain('pages'); + expect(tsconfig.include).toContain('workflows'); expect(tsconfig.include).toContain('db'); expect(mockLogInfo).toHaveBeenCalledWith('Empty project detected. Creating a Pages starter.'); diff --git a/packages/void/test/unit/workflow-runtime.test.ts b/packages/void/test/unit/workflow-runtime.test.ts index 53f64847f6..f6f705444b 100644 --- a/packages/void/test/unit/workflow-runtime.test.ts +++ b/packages/void/test/unit/workflow-runtime.test.ts @@ -104,11 +104,20 @@ describe('defineWorkflow', () => { const Welcome = defineWorkflow({ async run(event: WorkflowEvent<{ userId: string }>, step, context) { seen.push(event.payload.userId, context.env.GREETING, getRuntimeEnv().GREETING); + expect(Object.keys(context.env)).toEqual(['GREETING']); + expect(context.env.__VOID_MARKER).toBeUndefined(); + expect('ISR_CACHE' in context.env).toBe(false); return step.do('greet', async () => 'done'); }, }); const step = { do: vi.fn(async (_name: string, fn: () => Promise) => fn()) }; - const instance = new Welcome.class({} as ExecutionContext, { GREETING: 'hello' }); + const instance = new Welcome.class({} as ExecutionContext, { + GREETING: 'hello', + __VOID_MARKER: true, + __PROJECT_ID: 'project', + __VOID_ISR_DEPLOYMENT_ID: 'build', + ISR_CACHE: {}, + }); expect(instance).toBeInstanceOf(WorkflowEntrypoint); const result = await instance.run( { payload: { userId: 'u1' } } as WorkflowEvent<{ userId: string }>, diff --git a/packages/void/test/unit/workflow-scan.test.ts b/packages/void/test/unit/workflow-scan.test.ts index 824397d2d8..460f075d1d 100644 --- a/packages/void/test/unit/workflow-scan.test.ts +++ b/packages/void/test/unit/workflow-scan.test.ts @@ -92,14 +92,22 @@ describe('scanWorkflowModules', () => { const Job = defineWorkflow({ name: 'daily', async run() {} });`; const root = createRoot({ 'digest.ts': `${source}\nexport { Job, Job as default };`, - 'types.ts': `${source}\nexport { type Job as default };`, - 'other.ts': `${source}\nexport { Job as default } from './digest';`, + 'types.ts': "export { type Job as default } from './digest';", + 'other.ts': "export { Job as default } from './digest';", }); expect(scanWorkflowModules(root).map(({ relativePath, name }) => [relativePath, name])).toEqual( [['digest.ts', 'daily']], ); }); + it.each([ + "import { defineWorkflow as job } from 'void/workflows'; export const Nightly = job({ async run() {} });", + "import * as wf from 'void/workflows'; const Nightly = wf.defineWorkflowEntrypoint({ class: Job }); export default {};", + ])('reports a Workflow definition missing its default export', (source) => { + const root = createRoot({ 'nested/nightly.ts': source }); + expect(() => scanWorkflowModules(root)).toThrow(/nightly\.ts.*default.export/i); + }); + it('ignores files and directories starting with an underscore', () => { const root = createRoot({ 'welcome.ts': definition, From c225a3e1555c2d1042ec263bdd0ae0b502a781ba Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Tue, 1 Dec 2026 12:06:33 +0900 Subject: [PATCH 7/7] Fix Workflow schedule recovery, discovery, and deployment contracts. --- .github/scripts/packed-consumer.mjs | 8 +- docs/guide/workflows.md | 6 +- docs/reference/config.md | 2 +- docs/reference/structure.md | 2 +- packages/deploy-cloudflare/src/existing.ts | 5 + packages/deploy-cloudflare/src/operations.ts | 14 ++ packages/deploy-cloudflare/src/version.ts | 134 ++++++++++++++---- .../test/unit/version.test.ts | 133 ++++++++++++++--- packages/void/AGENTS.md | 2 +- packages/void/src/cli/cf-version-runner.ts | 7 + .../src/cli/cloudflare-operation-process.ts | 79 ++++++++++- .../void/src/cli/deploy-cloudflare-helpers.ts | 36 ++++- packages/void/src/cli/deploy-helpers.ts | 2 +- packages/void/src/cli/preset.ts | 28 +++- packages/void/src/runtime/workflows/index.ts | 19 ++- .../void/src/shared/resource-definition.ts | 45 +++++- packages/void/src/workflows/scan.ts | 5 +- .../cloudflare-durable-build.test.ts | 2 +- .../void/test/unit/cf-version-runner.test.ts | 49 ++++--- .../void/test/unit/cloudflare-deploy.test.ts | 38 ++++- .../unit/cloudflare-operation-process.test.ts | 79 +++++++++++ .../void/test/unit/deploy-project.test.ts | 36 +++++ .../test/unit/workflow-runtime.typecheck.ts | 12 ++ packages/void/test/unit/workflow-scan.test.ts | 32 ++++- 24 files changed, 683 insertions(+), 92 deletions(-) diff --git a/.github/scripts/packed-consumer.mjs b/.github/scripts/packed-consumer.mjs index 6072449505..ba71cac2da 100644 --- a/.github/scripts/packed-consumer.mjs +++ b/.github/scripts/packed-consumer.mjs @@ -331,9 +331,13 @@ try { writeFileSync( join(fixture, 'workflow.mts'), `import { defineWorkflow } from 'void/workflows'; -export default defineWorkflow<{ id: string }>({ +const job = defineWorkflow<{ id: string }>({ async run(event, step) { return step.do('id', async () => event.payload.id); }, -});`, +}); +declare const receiver: Workflow<{ id: string; recipient: string }>; +// @ts-expect-error The receiver also requires a recipient. +void job.create(receiver, { params: { id: '1' } }); +export default job;`, ); writeFileSync( join(fixture, 'tsconfig.workflow.json'), diff --git a/docs/guide/workflows.md b/docs/guide/workflows.md index cc9a547a7f..3a1b16404f 100644 --- a/docs/guide/workflows.md +++ b/docs/guide/workflows.md @@ -33,7 +33,7 @@ export default Onboarding; Default-export the object returned by `defineWorkflow()`. Named-export it too so routes can import it. -TypeScript and JavaScript files are supported, including subdirectories. Void discovers default exports created using a helper imported from `void/workflows`. Files and directories starting with `_` are excluded from Workflow discovery. If you maintain an explicit `include` list in `tsconfig.json`, add `workflows` so TypeScript checks definitions started outside your app. +Keep `workflows/` at the project root, including when `sourceDir` is set. Write Workflow definitions as TypeScript or JavaScript ES modules with an import from `void/workflows` and a default export. In CommonJS projects, use `.mjs` or `.mts` for definitions. Subdirectories are supported. Files and directories starting with `_` are excluded from Workflow discovery. If you maintain an explicit `include` list in `tsconfig.json`, add `workflows` so TypeScript checks definitions started outside your app. `run` receives: @@ -127,9 +127,9 @@ Void derives the names from the file's path in `workflows/`, joining directories - the `WORKFLOW_SEND_WELCOME` binding - the exported `SendWelcomeWorkflow` class -- a Cloudflare Workflow named `-send-welcome`, since Workflow names must be unique within your Cloudflare account +- a Cloudflare Workflow named `_send-welcome`, since Workflow names must be unique within your Cloudflare account -`workflows/order/notifications.ts` creates `WORKFLOW_ORDER_NOTIFICATIONS`, `OrderNotificationsWorkflow`, and `-order-notifications`. A path that starts with a digit, such as `2026-report.ts`, exports the class `Workflow2026Report` and uses the binding `WORKFLOW_2026_REPORT`. Each Workflow must have a unique name. +`workflows/order/notifications.ts` creates `WORKFLOW_ORDER_NOTIFICATIONS`, `OrderNotificationsWorkflow`, and `_order-notifications`. A path that starts with a digit, such as `2026-report.ts`, exports the class `Workflow2026Report` and uses the binding `WORKFLOW_2026_REPORT`. Each Workflow must have a unique name. Instances belong to the Workflow name. Changing the generated Workflow name directs new instances to a different Workflow. To move a file without changing its name, run `void info` first and add the name it suggests: diff --git a/docs/reference/config.md b/docs/reference/config.md index 6e736bface..1bd9bcde68 100644 --- a/docs/reference/config.md +++ b/docs/reference/config.md @@ -62,7 +62,7 @@ When set, those conventions move under the configured directory: { "sourceDir": "src" } ``` -With that config, Void reads `src/pages`, `src/routes`, `src/db/schema.ts`, `src/db/migrations`, `src/auth.ts`, and `src/env.ts`. Project files such as `void.config.ts`, `vite.config.ts`, `package.json`, `tsconfig.json`, `public/`, and the local-only `.env` stay at the project root. Keep source files in the configured directory. Duplicate conventions at the root and under `sourceDir` cause a build error. +With that config, Void reads `src/pages`, `src/routes`, `src/db/schema.ts`, `src/db/migrations`, `src/auth.ts`, and `src/env.ts`. Project files such as `void.config.ts`, `vite.config.ts`, `package.json`, `tsconfig.json`, `public/`, and the local-only `.env` stay at the project root. Keep those source files in the configured directory. Workflow definitions stay in `workflows/` at the project root. Duplicate conventions at the root and under `sourceDir` cause a build error. ### `ai` diff --git a/docs/reference/structure.md b/docs/reference/structure.md index 59b9ecb7d4..e78b0fb39f 100644 --- a/docs/reference/structure.md +++ b/docs/reference/structure.md @@ -129,7 +129,7 @@ Generate schema with `void gen model` or write it by hand. Generate migrations w ## `workflows/` -[Workflow](/guide/workflows) modules. Each file default-exports a `defineWorkflow()` or `defineWorkflowEntrypoint()` definition. +[Workflow](/guide/workflows) modules. This directory stays at the project root when `sourceDir` is configured. Each Workflow module default-exports a `defineWorkflow()` or `defineWorkflowEntrypoint()` definition. ## `src/` diff --git a/packages/deploy-cloudflare/src/existing.ts b/packages/deploy-cloudflare/src/existing.ts index 202d3fa419..4a53a81107 100644 --- a/packages/deploy-cloudflare/src/existing.ts +++ b/packages/deploy-cloudflare/src/existing.ts @@ -13,6 +13,7 @@ import { cloudflareStagingPairGuidance } from './staging-guidance.ts'; export type ExistingCloudflareWorker = { versionId: string; + versionMessage?: string; bindings: Array>; runtime: Record; script: Record; @@ -145,6 +146,10 @@ async function readCloudflareWorker( return { snapshot: { versionId, + ...(isRecord(version.annotations) && + typeof version.annotations['workers/message'] === 'string' + ? { versionMessage: version.annotations['workers/message'] } + : {}), bindings: resources.bindings, runtime: resources.script_runtime, script: resources.script, diff --git a/packages/deploy-cloudflare/src/operations.ts b/packages/deploy-cloudflare/src/operations.ts index 4ce4930534..6bd7cc8a82 100644 --- a/packages/deploy-cloudflare/src/operations.ts +++ b/packages/deploy-cloudflare/src/operations.ts @@ -4,6 +4,14 @@ import type { R2LocationHint } from '@void/deploy-core'; type ConfigTarget = { configPath?: string }; type WorkerTarget = ConfigTarget & { workerName?: string }; +export type WorkflowScheduleCleanup = { + workflowName: string; + className: string; + limits?: unknown; + concurrency?: unknown; + default_retention?: unknown; +}; + export type CloudflareOperation = | ({ type: 'auth.whoami' | 'auth.login' | 'auth.logout' | 'auth.token' } & ConfigTarget) | ({ @@ -79,6 +87,12 @@ export type CloudflareOperation = | ({ type: 'previews.delete'; previewName: string } & WorkerTarget) | ({ type: 'triggers.deploy'; assets?: boolean } & WorkerTarget) | ({ type: 'triggers.clear-crons' | 'triggers.clear-domains' } & WorkerTarget) + | ({ + type: 'triggers.clear-workflow-schedules'; + workerName: string; + inspectOnly?: boolean; + } & WorkflowScheduleCleanup & + ConfigTarget) | ({ type: 'tail'; search?: string; versionId?: string; status?: 'error' } & WorkerTarget); export type CloudflareUploadResult = { diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 7f7d9da7a9..4fd4908bc8 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -14,7 +14,7 @@ import { isWorkerNotFound, } from './execute.ts'; import type { CloudflareCommandResult, CloudflareCommandRunner } from './execute.ts'; -import type { CloudflareUploadResult } from './operations.ts'; +import type { CloudflareUploadResult, WorkflowScheduleCleanup } from './operations.ts'; import { isVoidSecretDraftHeader, isVoidSecretOnlyDraft, @@ -58,6 +58,8 @@ export type CloudflareTriggerConfig = Readonly<{ crons: ReadonlyArray; queueConsumers: ReadonlyArray; workflows: ReadonlyArray; + /** Replay a previous name's schedule removal until the provider confirms it is clear. */ + workflowScheduleCleanup?: ReadonlyArray; /** * Email Routing addresses (`addresses` in Wrangler config). The Cloudflare CLI applies its * Email Routing plan inside `triggers deploy` — `undefined` skips the plan entirely, while @@ -282,15 +284,7 @@ export async function deployCloudflareVersionTriggers(options: { // config so an ephemeral assets directory (or another bundle-only field) cannot break the // post-activation reconciliation after `versions upload` has already consumed it. const base = pickWranglerTriggerContext(source); - const config = triggerWranglerConfig( - base, - triggerConfigWithRemovedWorkflowSchedules( - options.workerName, - options.triggerConfig, - options.previousTriggerConfig, - ), - options.manageRoutes, - ); + const config = triggerWranglerConfig(base, options.triggerConfig, options.manageRoutes); const directory = mkdtempSync(join(tmpdir(), 'void-version-triggers-')); const configPath = join(directory, 'wrangler.json'); try { @@ -302,6 +296,29 @@ export async function deployCloudflareVersionTriggers(options: { if (!isCleanCommandExit(deployed)) { return deployed; } + for (const workflow of workflowsToClear( + options.workerName, + options.triggerConfig, + options.previousTriggerConfig?.workflows, + [ + ...(options.previousTriggerConfig?.workflowScheduleCleanup ?? []), + ...(options.triggerConfig.workflowScheduleCleanup ?? []), + ], + )) { + const cleared = await options.runWrangler( + { + ...workflow, + type: 'triggers.clear-workflow-schedules', + workerName: options.workerName, + configPath, + inspectOnly: false, + }, + { capture: true }, + ); + if (!isCleanCommandExit(cleared)) { + return cleared; + } + } if (options.triggerConfig.crons.length === 0 && options.publishEmptyCrons) { const published = await options.publishEmptyCrons(); if (!isCleanCommandExit(published)) { @@ -511,6 +528,7 @@ function mergeTriggerCleanupBaselines( crons: unique(present.flatMap((config) => config.crons)), queueConsumers: unique(present.flatMap((config) => config.queueConsumers)), workflows: unique(present.flatMap((config) => config.workflows)), + workflowScheduleCleanup: present.flatMap((config) => config.workflowScheduleCleanup ?? []), ...(withAddresses.length === 0 ? {} : { addresses: [...new Set(withAddresses.flatMap((config) => config.addresses ?? []))] }), @@ -568,34 +586,79 @@ function triggerConfigWithQueueConsumerCleanup( }; } -function triggerConfigWithRemovedWorkflowSchedules( +function workflowsToClear( workerName: string, desired: CloudflareTriggerConfig, - previous: CloudflareTriggerConfig | undefined, -): CloudflareTriggerConfig { - if (!previous) { - return desired; - } + previous: ReadonlyArray = [], + outstanding: ReadonlyArray = [], +): Array { const desiredNames = new Set( desired.workflows.flatMap((workflow) => isRecord(workflow) && typeof workflow.name === 'string' ? [workflow.name] : [], ), ); - const removed = previous.workflows.flatMap((workflow) => { + const pending = new Map(); + for (const cleanup of outstanding) { + if (!desiredNames.has(cleanup.workflowName)) { + pending.set(cleanup.workflowName, cleanup); + } + } + for (const workflow of previous) { if ( !isRecord(workflow) || typeof workflow.name !== 'string' || typeof workflow.class_name !== 'string' || + !Array.isArray(workflow.schedules) || + workflow.schedules.length === 0 || desiredNames.has(workflow.name) || (typeof workflow.script_name === 'string' && workflow.script_name !== workerName) ) { - return []; + continue; } - return [{ ...workflow, schedules: [] }]; - }); - return removed.length === 0 - ? desired - : { ...desired, workflows: [...desired.workflows, ...removed] }; + pending.set(workflow.name, { + workflowName: workflow.name, + className: workflow.class_name, + limits: workflow.limits, + concurrency: workflow.concurrency, + default_retention: workflow.default_retention, + }); + } + return [...pending.values()]; +} + +// After an atomic publication the version can stay live even if trigger sync fails. +// Carry unconfirmed removals into its successor; a successful read retires the record. +async function recordWorkflowScheduleCleanup( + options: CloudflareVersionActivationOptions, + desired: CloudflareTriggerConfig, + previous: CloudflareTriggerConfig, +): Promise { + const removed = workflowsToClear(options.workerName, desired, previous.workflows); + const candidates = workflowsToClear( + options.workerName, + desired, + [], + previous.workflowScheduleCleanup, + ); + for (const candidate of candidates) { + if (removed.some(({ workflowName }) => workflowName === candidate.workflowName)) { + continue; + } + const inspected = await options.runWrangler( + { + ...candidate, + type: 'triggers.clear-workflow-schedules', + workerName: options.workerName, + configPath: options.configPath, + inspectOnly: true, + }, + { capture: true }, + ); + if (!isCleanCommandExit(inspected) || inspected.data !== false) { + removed.push(candidate); + } + } + return removed.length ? { ...desired, workflowScheduleCleanup: removed } : desired; } function hasCustomDomains(routes: ReadonlyArray | undefined): boolean { @@ -691,6 +754,7 @@ function parseTriggerConfig(value: unknown): CloudflareTriggerConfig | null { return null; } const addresses = readEmailAddresses(value.addresses); + const cleanup = value.workflowScheduleCleanup; if ( ['preserve', 'preserveRoutes', 'preserveWorkersDev', 'preservePreviewUrls', 'logpush'].some( (key) => value[key] !== undefined && typeof value[key] !== 'boolean', @@ -703,6 +767,14 @@ function parseTriggerConfig(value: unknown): CloudflareTriggerConfig | null { !Array.isArray(value.crons) || !Array.isArray(value.queueConsumers) || !Array.isArray(value.workflows) || + (cleanup !== undefined && + (!Array.isArray(cleanup) || + !cleanup.every( + (entry): entry is WorkflowScheduleCleanup => + isRecord(entry) && + typeof entry.workflowName === 'string' && + typeof entry.className === 'string', + ))) || (value.addresses !== undefined && addresses === undefined) ) { return null; @@ -721,6 +793,7 @@ function parseTriggerConfig(value: unknown): CloudflareTriggerConfig | null { crons: value.crons, queueConsumers: value.queueConsumers, workflows: value.workflows, + ...(cleanup && { workflowScheduleCleanup: cleanup }), ...(addresses === undefined ? {} : { addresses }), }; } @@ -1199,12 +1272,23 @@ async function activateCloudflareVersionWithSecretsFile( } desiredTriggerConfig = resolved; } + const versionedPreviousTriggerConfig = + previousMetadata?.schema === 2 ? previousMetadata.triggerConfig : undefined; + if ( + versionedPreviousTriggerConfig && + !desiredTriggerConfig.preserve && + !options.preserveTriggers + ) { + desiredTriggerConfig = await recordWorkflowScheduleCleanup( + options, + desiredTriggerConfig, + versionedPreviousTriggerConfig, + ); + } const message = desiredMetadata?.schema === 2 ? encodeCloudflareVersionMessage(desiredMetadata.migrations, desiredTriggerConfig) : options.message; - const versionedPreviousTriggerConfig = - previousMetadata?.schema === 2 ? previousMetadata.triggerConfig : undefined; const versionedPreviousTriggerConfigWithTraffic = versionedPreviousTriggerConfig && previousTrafficConfig ? { ...versionedPreviousTriggerConfig, ...previousTrafficConfig } diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index 50966c92ea..67955e65b2 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -18,7 +18,10 @@ import type { CloudflareOperation, CloudflareTriggerConfig, } from '../../src/index.ts'; -import { STALE_VERSION_HISTORY_DELAYS_MS } from '../../src/version.ts'; +import { + stabilizeCloudflareVersionTriggers, + STALE_VERSION_HISTORY_DELAYS_MS, +} from '../../src/version.ts'; import { operationFixture } from '../operation-fixture.ts'; import { apiSecretDraftVersion, voidSecretDraftVersion } from '../secret-draft-fixture.ts'; @@ -2759,24 +2762,120 @@ describe('Cloudflare version activation', () => { ]); }); - it('clears schedules without deleting removed workflow state', async () => { - let applied: Record | undefined; - await deployCloudflareVersionTriggers({ - runWrangler: operationFixture(async (args) => { - applied = readConfigArg(args); - return ok(); - }), + it('retains failed schedule cleanup across atomic deploy retries and retires it after success', async () => { + const old = { + name: 'nightly', + binding: 'JOB', + class_name: 'Job', + schedules: ['0 0 * * *'], + concurrency: { limit: 2 }, + }; + const desired = encodeCloudflareVersionMessage( + [], + triggersWith({ workflows: [{ ...old, name: 'pinned' }] }), + ); + let activeMessage = encodeCloudflareVersionMessage([], triggersWith({ workflows: [old] })); + let scheduled = true; + const operations: Array = []; + for (const attempt of [1, 2, 3]) { + const fixture = recoveryActivation({ + atomic: true, + previous: { id: CURRENT, number: 1, annotations: { 'workers/message': activeMessage } }, + }); + const outcome = await activateCloudflareVersion({ + ...fixture.options, + message: desired, + runWrangler: async (operation) => { + if (operation.type === 'worker.deploy') { + activeMessage = operation.message ?? ''; + } + if (operation.type === 'triggers.clear-workflow-schedules') { + expect(operation).toMatchObject({ + workflowName: 'nightly', + className: 'Job', + concurrency: { limit: 2 }, + }); + operations.push(operation.inspectOnly ? 'inspect' : 'clear'); + if (operation.inspectOnly) { + return { ...ok(), data: scheduled }; + } + if (attempt === 1) { + return { status: 1, stdout: '', stderr: '503' }; + } + scheduled = false; + return ok(); + } + return fixture.options.runWrangler(operation); + }, + }); + expect(outcome.ok, JSON.stringify(outcome)).toBe(attempt !== 1); + expect(activeMessage.includes('workflowScheduleCleanup')).toBe(attempt < 3); + } + expect(operations).toEqual(['clear', 'inspect', 'clear', 'inspect', 'clear']); + }); + + it('finishes pending schedule cleanup when rolling back to a version from before the Workflow', async () => { + const cleanup = { workflowName: 'nightly', className: 'Job' }; + const cleared: Array = []; + const result = await stabilizeCloudflareVersionTriggers({ workerName: 'app', - triggerConfig: triggersWith(), - previousTriggerConfig: triggersWith({ - workflows: [{ name: 'nightly', class_name: 'NightlyWorkflow', schedules: ['0 0 * * *'] }], - }), + targetVersionId: CURRENT, + targetTriggerConfig: triggersWith(), + previousTriggerConfig: triggersWith({ workflowScheduleCleanup: [cleanup] }), + runWrangler: async (operation) => { + if (operation.type === 'deployments.status') { + return { ...ok(), data: { versions: [{ version_id: CURRENT, percentage: 100 }] } }; + } + if (operation.type === 'triggers.clear-workflow-schedules') { + cleared.push(operation.workflowName); + } + return ok(); + }, }); - - expect(applied?.workflows).toEqual([ - { name: 'nightly', class_name: 'NightlyWorkflow', schedules: [] }, - ]); - }); + expect(result.ok).toBe(true); + expect(cleared).toEqual(['nightly']); + }); + + it.each([0, 1])( + 'clears a renamed Workflow schedule separately and returns its exit status %s', + async (status) => { + const old = { name: 'nightly', binding: 'JOB', class_name: 'Job', schedules: ['0 0 * * *'] }; + const current = { ...old, name: 'pinned' }; + const cleared: Array = []; + const result = await deployCloudflareVersionTriggers({ + runWrangler: async (operation) => { + if (operation.type === 'triggers.deploy' && operation.configPath) { + expect(JSON.parse(readFileSync(operation.configPath, 'utf8')).workflows).toEqual([ + current, + ]); + return ok(); + } + expect(operation).toMatchObject({ + type: 'triggers.clear-workflow-schedules', + workerName: 'app', + className: 'Job', + }); + if (operation.type === 'triggers.clear-workflow-schedules') { + cleared.push(operation.workflowName); + } + return { status, stdout: '', stderr: '' }; + }, + workerName: 'app', + triggerConfig: triggersWith({ workflows: [current] }), + previousTriggerConfig: triggersWith({ + workflows: [ + old, + old, + current, + { ...old, name: 'external', script_name: 'elsewhere' }, + { ...old, name: 'unscheduled', schedules: [] }, + ], + }), + }); + expect(cleared).toEqual(['nightly']); + expect(result.status).toBe(status); + }, + ); it('publishes an explicit empty set when removing the final custom domain', async () => { const publishEmptyCustomDomains = vi.fn(async () => ok()); diff --git a/packages/void/AGENTS.md b/packages/void/AGENTS.md index 57a6aefaa3..3628273991 100644 --- a/packages/void/AGENTS.md +++ b/packages/void/AGENTS.md @@ -148,7 +148,7 @@ generated entries must preserve the module-boundary rules below. - **Framework env schema**: `env` has no schema in a Worker whose own modules have not loaded `env.ts`, whatever the Vite plugin loaded in its process, so it returns raw values. The Class A wrapper (TanStack Start, React Router, vinext) imports `env.ts` ahead of the framework entry and awaits `_prepareEnv(env)` on every request, in dev and build. Unlike `_validateEnvOnce`, it never rejects: a read of a key that failed throws that key's error, async validators included, so requests that do not read it and a build-time prerender without production secrets still run. Both keep one result per key, reuse a validation for the same raw values, and keep the results with the env object they received. Reads through another object (the `cloudflare:workers` env that a D1 app's framework reads outside a request scope, the remote dev copy) get the latest validation's result while they hold the raw value it came from; never copy results to that object, which can come to hold other values. A validation in which a validator threw serves its reads but runs again on the next call. Results live on the process-global registry because `void deploy` bundles cron and queue jobs apart from the app, with a copy of `void/env` of their own: the jobs call `registry.prepare`, the `_prepareEnv` of the copy that registered the schema (key in `shared/env-registry.ts`). SvelteKit, Nuxt, Analog and Astro Workers do not load `env.ts` yet. - **Reserved `__VOID_*` names**: `envSchemaPlugin.config` (every mode, with or without `env.ts`) and `void env check` reject `__VOID_*` names in the root `.env` or declared in `env.ts`. Do not try to strip them from dev `vars` instead: Wrangler reads `.env` itself and writes it over `vars`, so a strip cannot be enforced. Manual trigger auth is a compile-time literal (`__VOID_SERVE` from `CompileOptions.dev`, false in builds and `vite preview`): dev accepts only `x-void-dev-trigger`, builds use the proxy token or build key. Never key it on `import.meta.env.DEV`, which is true in a `NODE_ENV=development` build. - **Typed Durable State convention**: each default-exported `defineDurableState()` definition in `durable-objects/*.ts` becomes a filename-derived binding and worker class (`shopping-cart.ts` → `SHOPPING_CART` / `ShoppingCartDurableObject`). The generated entry calls the internal `__bind()` hook so named imports can use `State.get(name)` without touching `c.env`, exports `State.class`, and emits a stable `new_sqlite_classes` migration. `syncWranglerDurableObjects()` persists bindings and append-only class migration history in `void.lock.json` through the generated Cloudflare config; never regenerate migration order solely from the current sorted files. The generated class extends `DurableObject` from `cloudflare:workers` so namespace stubs expose real RPC methods; runtime state and helpers use JavaScript private fields and methods. Runtime operations are serialized and persisted after successful typed RPC, `fetch`, or `alarm` handlers; versioned value migrations run on load. This is native-Void + Cloudflare only and is supported by direct Cloudflare deploys. Typed `*.ws.ts` routes likewise use SQLite-backed classes; their root-config sync uses the comment-preserving writer, retains legacy `new_classes` histories, and appends a new migration tag only for new classes. -- **Workflows convention**: each default-exported `defineWorkflow()` / `defineWorkflowEntrypoint()` under `workflows/` becomes `WORKFLOW_` / `Workflow` (`send-welcome.ts` → `WORKFLOW_SEND_WELCOME` / `SendWelcomeWorkflow`), bound through the same `__bind()` hook as Durable State. The binding prefix matches `QUEUE_*`. Discovery follows `queues/` rather than `durable-objects/`: subdirectories are joined with `-` (`order/notifications.ts` → `order-notifications`) and `_`-prefixed path segments are skipped. Workflows need no class migrations, so they are not written to `void.lock.json`; `mergeWorkerBindings()` emits only the additions (the Cloudflare plugin concatenates arrays) via `planWorkflowAdditions()`, naming each `-` because Workflow names are account-scoped. `void deploy --platform cloudflare` passes its Worker name to the build as `VOID_CLOUDFLARE_WORKER_NAME`, and `reconstructExpectedWorkflows()` pins the exact emitted set for `verifyGeneratedDeployConfig()`. An authored entry with the same binding and class keeps its name. Void platform deploys, framework mode and Node targets reject `workflows/` until platform provisioning exists. The generated entry imports convention modules through their namespace and fails Worker startup with a named error when the default export is not a definition; this guard also covers `durable-objects/`. +- **Workflows convention**: each default-exported `defineWorkflow()` / `defineWorkflowEntrypoint()` under `workflows/` becomes `WORKFLOW_` / `Workflow` (`send-welcome.ts` → `WORKFLOW_SEND_WELCOME` / `SendWelcomeWorkflow`), bound through the same `__bind()` hook as Durable State. The binding prefix matches `QUEUE_*`. Discovery follows `queues/` rather than `durable-objects/`: subdirectories are joined with `-` (`order/notifications.ts` → `order-notifications`) and `_`-prefixed path segments are skipped. Workflows need no class migrations, so they are not written to `void.lock.json`; `mergeWorkerBindings()` emits only the additions (the Cloudflare plugin concatenates arrays) via `planWorkflowAdditions()`, naming each `_` because Workflow names are account-scoped. `void deploy --platform cloudflare` passes its Worker name to the build as `VOID_CLOUDFLARE_WORKER_NAME`, and `reconstructExpectedWorkflows()` pins the exact emitted set for `verifyGeneratedDeployConfig()`. An authored entry with the same binding and class keeps its name. Void platform deploys, framework mode and Node targets reject `workflows/` until platform provisioning exists. The generated entry imports convention modules through their namespace and fails Worker startup with a named error when the default export is not a definition; this guard also covers `durable-objects/`. - **Persistent resource names**: optional static `name` on Durable State, WebSocket, and Workflow definitions uses the same identity derivation as unnamed filenames/routes. Preserve unnamed defaults exactly. `void info` reports names and verified unmatched lock identities without executing source or writing files. Scanners use the shared AST reader; runtime validation imports only the Worker-safe `shared/resource-name.ts` leaf. Carry explicit names through generated metadata and `__bind()`; runtime mismatches fail instead of selecting an inferred replacement. WebSocket `key({ params })` is shared by namespace selection and hook `ctx.id`; absent keys keep the existing ordered `param=value` format. - **Server room actions**: `defineRoom({ actions })` keeps each action's declared parameters and return type (`RoomActions` accepts any annotated parameter list, so unannotated parameters become `never`). Codegen adds `actions` to `WebSocketRouteMap` for room routes only, and `getRoom()` from `void/ws/server` resolves the same `bindingName` plus `buildWebSocketInstanceId()` key as `forwardWebSocketRequest()`. The generated route table registers route metadata once, after attaching `key`, through `__registerWebSocketRoutes`; the map lives on `globalThis` because dev can evaluate the module twice. Dispatch is Durable Object RPC (`__voidRoomAction`), so the WebSocket DO class extends `DurableObject` from `cloudflare:workers`; its own helpers are `#` methods so they stay off that RPC surface, and actions are never reachable from `fetch`, `webSocketMessage`, or client HTTP. - **Journal coherence invariant**: `db/migrations/*.sql` and `db/migrations/meta/_journal.json` must stay in sync — every `.sql` file has a matching journal entry (by `tag`) and vice versa. `assertJournalCoherence` in `src/migrations/validate.ts` is the gate, called from `deploy`, `db status`, `db migrate`, and `db reset`. The two CLI commands that mutate migration state — `void gen migration` and `void db rename-migrations` — are responsible for keeping the journal coherent themselves: when the journal has entries, the first delegates to `drizzle-kit generate --custom --name `, which writes the empty `.sql`, appends the journal entry, and writes a snapshot of the current schema (it refuses if the last entry's snapshot is missing and byte-restores the journal if drizzle-kit fails); with no journal entries it writes a plain timestamped `.sql`. The second rewrites `tag` values alongside the file renames and also renames the matching `meta/_snapshot.json` (with byte-level rollback on failure). Drift will fail loudly before touching any remote DB. This prevents an orphan scaffolded `.sql` file from half-applying against D1 and blocking later deploys. diff --git a/packages/void/src/cli/cf-version-runner.ts b/packages/void/src/cli/cf-version-runner.ts index 72982c92eb..03ebff32af 100644 --- a/packages/void/src/cli/cf-version-runner.ts +++ b/packages/void/src/cli/cf-version-runner.ts @@ -423,6 +423,7 @@ export function createCfVersionRunner(options: { workerName: string; runCf: CfCommand; verifyResources: (directory: string) => Promise; + clearWorkflowSchedules?: CloudflareCommandRunner; pinnedUpload?: { accountId: string; apiBaseUrl: string; @@ -556,6 +557,12 @@ export function createCfVersionRunner(options: { }; return async (operation, command) => { + if (operation.type === 'triggers.clear-workflow-schedules') { + if (operation.workerName !== workerName || !options.clearWorkflowSchedules) { + return failed('The Cloudflare Workflow schedule publisher is unavailable for this Worker.'); + } + return options.clearWorkflowSchedules(operation, command); + } if (operation.type === 'deployments.status') { const result = await run(['workers', 'deployments', 'list', '--worker', workerName], true); if (!isCleanCloudflareExit(result)) { diff --git a/packages/void/src/cli/cloudflare-operation-process.ts b/packages/void/src/cli/cloudflare-operation-process.ts index 0021394a4c..802455b761 100644 --- a/packages/void/src/cli/cloudflare-operation-process.ts +++ b/packages/void/src/cli/cloudflare-operation-process.ts @@ -384,6 +384,76 @@ async function clearWorkerCronSchedules(worker: string): Promise { return result(0); } +async function clearWorkflowSchedules( + request: Extract, +): Promise { + const { workerName: worker, workflowName: workflow, className } = request; + if (!/^[A-Za-z0-9_][A-Za-z0-9_-]{0,63}$/.test(workflow)) { + throw new Error('Invalid Cloudflare Workflow name.'); + } + const endpoint = `${apiBaseUrl()}/accounts/${encodeURIComponent(accountId())}/workflows/${encodeURIComponent(workflow)}`; + const headers = await apiHeaders(); + const current = await fetch(endpoint, { + headers, + redirect: 'error', + signal: AbortSignal.timeout(30_000), + }); + const body = object(await current.json()); + if ( + current.status === 404 && + Array.isArray(body.errors) && + body.errors.some((error) => object(error).code === 10_200) + ) { + return result(0, '', '', false); + } + if (!current.ok || body.success !== true) { + throw new Error(`Could not inspect Cloudflare Workflow ${workflow} (HTTP ${current.status}).`); + } + const active = object(body.result); + if ( + active.name !== workflow || + typeof active.script_name !== 'string' || + typeof active.class_name !== 'string' + ) { + throw new Error(`Cloudflare returned an invalid owner for Workflow ${workflow}.`); + } + // The old name can have moved to another Worker or class since this version ran. + if ( + active.script_name !== worker || + active.class_name !== className || + active.schedules === undefined || + (Array.isArray(active.schedules) && active.schedules.length === 0) + ) { + return result(0, '', '', false); + } + if (!Array.isArray(active.schedules)) { + throw new Error(`Cloudflare returned invalid schedules for Workflow ${workflow}.`); + } + if (request.inspectOnly) { + return result(0, '', '', true); + } + const cleared = await fetch(endpoint, { + method: 'PUT', + headers: { ...headers, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + script_name: worker, + class_name: className, + schedules: [], + limits: request.limits, + concurrency: request.concurrency, + default_retention: request.default_retention, + }), + redirect: 'error', + signal: AbortSignal.timeout(30_000), + }); + if (!cleared.ok || object(await cleared.json()).success !== true) { + throw new Error( + `Could not clear schedules for Cloudflare Workflow ${workflow} (HTTP ${cleared.status}).`, + ); + } + return result(0); +} + async function clearWorkerCustomDomains(worker: string): Promise { const endpoint = `${apiBaseUrl()}/accounts/${encodeURIComponent(accountId())}/workers/scripts/${encodeURIComponent(worker)}/domains/records`; const response = await fetch(endpoint, { @@ -1281,10 +1351,17 @@ async function workerChanges(): Promise { if (raw.name !== name) { throw new Error('Cloudflare Worker target changed.'); } - if (operation.type === 'triggers.clear-crons' || operation.type === 'triggers.clear-domains') { + if ( + operation.type === 'triggers.clear-crons' || + operation.type === 'triggers.clear-domains' || + operation.type === 'triggers.clear-workflow-schedules' + ) { if (raw.account_id !== undefined && raw.account_id !== accountId()) { throw new Error('Cloudflare trigger target changed.'); } + if (operation.type === 'triggers.clear-workflow-schedules') { + return clearWorkflowSchedules(operation); + } return operation.type === 'triggers.clear-crons' ? clearWorkerCronSchedules(name) : clearWorkerCustomDomains(name); diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index 00bc02fba4..f987fa4b23 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -1,6 +1,7 @@ import { existsSync } from 'node:fs'; import { assertCloudflareBindingsPreserved, + parseCloudflareVersionMessage, parseRootWranglerConfig, readExistingCloudflareWorker, readWranglerTopLevelString, @@ -42,6 +43,7 @@ import { createCloudflareEmptyCronPublisher, createCloudflareEmptyDomainPublisher, } from './cloudflare-operations.ts'; +import { isCleanCloudflareExit } from './cloudflare-process.ts'; import { readCloudflareWorkersDevSubdomain, rememberCloudflareWorkersDevSubdomain, @@ -305,6 +307,7 @@ export function createCfActivationRunner(options: { output: cfOutput, workerName: options.workerName, runCf, + clearWorkflowSchedules: runWrangler, pinnedUpload: { accountId, apiBaseUrl, @@ -332,12 +335,35 @@ export async function activeWorkflowVersionForRemoval( typeof binding.class_name === 'string' && (binding.script_name === undefined || binding.script_name === options.workerName), ); - if (!ownsWorkflow) { - throw new Error( - 'deploy: atomic deployment requires Durable Object migration history or a local Workflow in the new or active Worker.', - ); + if (ownsWorkflow) { + return active.versionId; + } + const metadata = parseCloudflareVersionMessage(active.versionMessage); + if (metadata?.schema === 2) { + for (const cleanup of metadata.triggerConfig.workflowScheduleCleanup ?? []) { + const checked = await options.runWrangler( + { + ...cleanup, + type: 'triggers.clear-workflow-schedules', + workerName: options.workerName, + configPath: options.configPath, + inspectOnly: true, + }, + { capture: true }, + ); + if (!isCleanCloudflareExit(checked) || typeof checked.data !== 'boolean') { + throw new Error( + 'deploy: could not verify outstanding Workflow schedule cleanup before atomic publication.', + ); + } + if (checked.data) { + return active.versionId; + } + } } - return active.versionId; + throw new Error( + 'deploy: atomic deployment requires Durable Object migration history or a local Workflow in the new or active Worker.', + ); } /** diff --git a/packages/void/src/cli/deploy-helpers.ts b/packages/void/src/cli/deploy-helpers.ts index 01a5699937..2108ed07e4 100644 --- a/packages/void/src/cli/deploy-helpers.ts +++ b/packages/void/src/cli/deploy-helpers.ts @@ -384,7 +384,7 @@ export function resolveStaticDeployPreset( const appType = voidConfig.inference?.appType; if (appType === 'static' || appType === 'spa') { const outputDir = voidConfig.inference?.outputDir; - const detected = detectPreset(root, { spa: options?.spa, skipWorkflowDiscovery: true }); + const detected = detectPreset(root, { spa: options?.spa, explicitStatic: { outputDir } }); return { appType, buildCommand: detected?.buildCommand ?? null, diff --git a/packages/void/src/cli/preset.ts b/packages/void/src/cli/preset.ts index e820fc6d68..73a4778d42 100644 --- a/packages/void/src/cli/preset.ts +++ b/packages/void/src/cli/preset.ts @@ -249,7 +249,7 @@ export function detectPreset( dir?: string; spa?: boolean; strictBackend?: boolean; - skipWorkflowDiscovery?: boolean; + explicitStatic?: { outputDir?: string }; }, ): StaticPreset | null { // 1. Explicit --dir flag: skip build, use provided directory @@ -286,7 +286,10 @@ export function detectPreset( } // 3. Has backend files → full deploy - if (hasBackendFiles(root, options)) { + const hasBackend = hasBackendFiles(root, { + skipWorkflowDiscovery: Boolean(options?.explicitStatic), + }); + if (hasBackend && !options?.explicitStatic) { return null; } @@ -309,6 +312,18 @@ export function detectPreset( } // 5. No build tool — look for pre-built output + if ( + options?.explicitStatic && + (hasBackend || options.explicitStatic.outputDir || !canServeStaticProjectRoot(root)) + ) { + // A mixed project can have an index.html beside server source. Use its configured + // output directory (or dist) and never select the project root as public assets. + return { + appType: 'static', + buildCommand: resolveProjectScriptCommand(root, 'build'), + outputDir: defaultViteClientDir(root), + }; + } if (existsSync(join(root, 'dist/index.html'))) { return { buildCommand: null, @@ -328,6 +343,15 @@ export function detectPreset( return null; } +function canServeStaticProjectRoot(root: string): boolean { + try { + return scanWorkflowModules(root).length === 0; + } catch { + // Explicit static deployments can use built assets while the Worker sources are incomplete. + return false; + } +} + /** * The refusal shown when an SSG project also carries backend sources and no * `inference.appType` says which one to deploy. Names the exact directories diff --git a/packages/void/src/runtime/workflows/index.ts b/packages/void/src/runtime/workflows/index.ts index 1363ebe008..2e5e0fed09 100644 --- a/packages/void/src/runtime/workflows/index.ts +++ b/packages/void/src/runtime/workflows/index.ts @@ -34,22 +34,33 @@ type WorkflowPayload = | Exclude | (undefined extends TParams ? Record : never); +// Workflow.create is a method, so its parameter is bivariant. Compare the +// delivered payload directly with what the concrete binding accepts. +type AcceptsPayload = TBinding extends Workflow + ? [TPayload] extends [NonNullable[0]>['params']] + ? true + : false + : never; + +type CompatibleBinding = TBinding & + (false extends AcceptsPayload ? never : unknown); + export type WorkflowApi = { class: TClass; /** @internal Called by Void's generated Worker entry. */ __bind(bindingName: string, resourceName?: string): void; /** Start a new instance. Params are validated when the definition has a `params` schema. */ create(...args: WorkflowCreateArguments): Promise; - create( - binding: Workflow, + create( + binding: CompatibleBinding, ...args: WorkflowCreateArguments ): Promise; /** Start up to 100 instances. Each instance's params are validated first. */ createBatch( instances: ReadonlyArray>, ): Promise; - createBatch( - binding: Workflow, + createBatch( + binding: CompatibleBinding, instances: ReadonlyArray>, ): Promise; /** Get a handle to an existing instance. */ diff --git a/packages/void/src/shared/resource-definition.ts b/packages/void/src/shared/resource-definition.ts index 9b1de28315..5aa8b4eef9 100644 --- a/packages/void/src/shared/resource-definition.ts +++ b/packages/void/src/shared/resource-definition.ts @@ -44,7 +44,10 @@ export function readResourceDefinition( ) || /\bfrom\s*['"]void\/workflows['"]/.test(source)) ) { - throw new SyntaxError(`workflows: could not parse ${filename}\n${parsed.errors[0].codeframe}`); + const hint = filename.endsWith('.cjs') ? ' Use .mjs for ES module syntax.' : ''; + throw new SyntaxError( + `workflows: could not parse ${filename}.${hint}\n${parsed.errors[0].codeframe}`, + ); } const program = asAstProgram(parsed.program); @@ -54,6 +57,13 @@ export function readResourceDefinition( const namespaces = new Map>(); const bindings = new Set(); let defaultExport: AstNode | undefined; + let commonJsExport: AstNode | undefined; + const isWorkflowRequire = (node: AstNode | undefined) => + convention === 'workflows' && + isCallExpression(node) && + isIdentifier(node.callee) && + node.callee.name === 'require' && + staticLiteral(node.arguments?.[0]) === 'void/workflows'; function recordBindings(node: AstNode | undefined): void { if (isIdentifier(node)) { bindings.add(node.name); @@ -74,6 +84,20 @@ export function readResourceDefinition( } } for (const statement of program.body ?? []) { + if (convention === 'workflows' && statement.type === 'ExpressionStatement') { + const assignment = statement.expression as AstNode; + const left = assignment.left as AstNode | undefined; + if ( + assignment.type === 'AssignmentExpression' && + assignment.operator === '=' && + isMemberExpression(left) && + isIdentifier(left.object) && + ((left.object.name === 'module' && moduleExportName(left.property) === 'exports') || + (left.object.name === 'exports' && moduleExportName(left.property) === 'default')) + ) { + commonJsExport = assignment.right as AstNode; + } + } if (statement.type === 'ExportDefaultDeclaration') { defaultExport = statement.declaration as AstNode; } else if ( @@ -128,6 +152,15 @@ export function readResourceDefinition( } for (const variable of (declaration as AstVariableDeclaration).declarations ?? []) { recordBindings(variable.id); + if (isWorkflowRequire(variable.init) && variable.id?.type === 'ObjectPattern') { + for (const property of variable.id.properties as Array) { + const helper = moduleExportName(property.key as AstNode | undefined); + const local = property.value as AstNode | undefined; + if (helper && helpers.has(helper) && isIdentifier(local)) { + importedHelpers.set(local.name, helper); + } + } + } if (isIdentifier(variable.id) && variable.init) { definitions.set(variable.id.name, variable.init); if (declaration.kind === 'const') { @@ -215,7 +248,7 @@ export function readResourceDefinition( helper = importedHelpers.get(callee.name) ?? (convention !== 'workflows' && helpers.has(callee.name) ? callee.name : undefined); - } else if (isMemberExpression(callee) && isIdentifier(callee.object)) { + } else if (isMemberExpression(callee)) { const property = !callee.computed && isIdentifier(callee.property) ? callee.property.name @@ -223,7 +256,8 @@ export function readResourceDefinition( if ( typeof property === 'string' && helpers.has(property) && - namespaces.get(callee.object.name)?.has(property) + ((isIdentifier(callee.object) && namespaces.get(callee.object.name)?.has(property)) || + isWorkflowRequire(resolve(callee.object))) ) { helper = property; } @@ -240,6 +274,11 @@ export function readResourceDefinition( ); if (!definition) { if (convention === 'workflows') { + if (resourceCall(commonJsExport)) { + throw new Error( + `workflows: ${filename} uses CommonJS. Use an ES module such as .mjs with import and export default for this Workflow definition.`, + ); + } const hasWorkflow = [...definitions.values()].some(resourceCall) || program.body?.some( diff --git a/packages/void/src/workflows/scan.ts b/packages/void/src/workflows/scan.ts index 9742040d58..ce57ca647f 100644 --- a/packages/void/src/workflows/scan.ts +++ b/packages/void/src/workflows/scan.ts @@ -63,8 +63,9 @@ export function deriveWorkflowResourceIdentity( * uses the resource name alone. */ export function cloudflareWorkflowName(resourceName: string, workerName?: string): string { - const prefix = workerName?.toLowerCase().replaceAll('_', '-'); - const name = prefix ? `${prefix}-${resourceName}` : resourceName; + // Resource names contain only letters, digits and hyphens. The last underscore + // always separates the original Worker name from its resource. + const name = workerName ? `${workerName}_${resourceName}` : resourceName; if (name.length > 64) { throw new Error( `workflows: generated Workflow name '${name}' exceeds Cloudflare's limit of 64 characters. Choose a shorter name in cloudflare.workflows.`, diff --git a/packages/void/test/integration/cloudflare-durable-build.test.ts b/packages/void/test/integration/cloudflare-durable-build.test.ts index c2c01e8b90..5b05aa570a 100644 --- a/packages/void/test/integration/cloudflare-durable-build.test.ts +++ b/packages/void/test/integration/cloudflare-durable-build.test.ts @@ -273,7 +273,7 @@ export default defineWorkflowEntrypoint({ class: Importer });\n`, expect(expectedWorkflows).toEqual([ pinned, { - name: 'deployed-app-welcome', + name: 'deployed-app_welcome', binding: 'WORKFLOW_WELCOME', class_name: 'WelcomeWorkflow', }, diff --git a/packages/void/test/unit/cf-version-runner.test.ts b/packages/void/test/unit/cf-version-runner.test.ts index ce68d5bedd..1c17aebd93 100644 --- a/packages/void/test/unit/cf-version-runner.test.ts +++ b/packages/void/test/unit/cf-version-runner.test.ts @@ -2555,7 +2555,7 @@ it('applies the immutable trigger snapshot through a private cf output copy', as } }); -it.each(['restore', 'remove'] as const)( +it.each(['restore', 'remove', 'rename'] as const)( 'replays workflow exports and schedules when triggers %s the previous workflow state', async (operation) => { const workflow = { @@ -2570,29 +2570,45 @@ it.each(['restore', 'remove'] as const)( migrations: [{ tag: 'v1', new_sqlite_classes: ['State'] }], workflows: operation === 'restore' ? [workflow] : [], }); - const desiredWorkflow = { ...workflow, schedules: ['30 * * * *'], concurrency: { limit: 2 } }; + const desiredWorkflow = { + ...workflow, + name: operation === 'rename' ? 'renamed-job' : workflow.name, + schedules: ['30 * * * *'], + concurrency: { limit: 2 }, + }; + const removedNames: Array = []; try { const calls: Array> = []; const runner = createCfVersionRunner({ output: prepared, workerName: 'void-test', verifyResources: async () => ({ status: 0, stdout: '', stderr: '' }), + clearWorkflowSchedules: async (request) => { + if (request.type === 'triggers.clear-workflow-schedules') { + removedNames.push(request.workflowName); + } + return { status: 0, stdout: '', stderr: '' }; + }, runCf: (args, { cwd }) => { calls.push(args); const worker = JSON.parse(readFileSync(getWorkerConfigPath(cwd), 'utf8')); - expect(worker.exports.Job).toEqual({ - type: 'workflow', - name: 'void-job', - ...(operation === 'restore' - ? { schedules: ['30 * * * *'], concurrency: { limit: 2 } } - : {}), - }); - expect(worker.env.JOB).toMatchObject({ - type: 'workflow', - name: 'void-job', - worker: 'void-test', - exportName: 'Job', - }); + if (operation === 'remove') { + expect(worker.exports.Job).toBeUndefined(); + expect(worker.env.JOB).toBeUndefined(); + } else { + expect(worker.exports.Job).toEqual({ + type: 'workflow', + name: desiredWorkflow.name, + schedules: ['30 * * * *'], + concurrency: { limit: 2 }, + }); + expect(worker.env.JOB).toMatchObject({ + type: 'workflow', + name: desiredWorkflow.name, + worker: 'void-test', + exportName: 'Job', + }); + } expect(worker.exports.State).toMatchObject({ type: 'durable-object', storage: 'sqlite' }); expect(worker.env.STATE).toMatchObject({ type: 'durable-object' }); expect(worker.env.FIXED).toEqual({ type: 'text', value: 'value' }); @@ -2612,12 +2628,13 @@ it.each(['restore', 'remove'] as const)( runWrangler: runner, triggerConfig: { ...base, - workflows: operation === 'restore' ? [desiredWorkflow] : [], + workflows: operation === 'remove' ? [] : [desiredWorkflow], }, previousTriggerConfig: { ...base, workflows: [workflow] }, }); expect(result.status).toBe(0); expect(calls).toEqual([['workers', 'triggers', 'deploy', '--prebuilt']]); + expect(removedNames).toEqual(operation === 'restore' ? [] : ['void-job']); const original = JSON.parse(readFileSync(getWorkerConfigPath(prepared.directory), 'utf8')); expect(original.exports.Job?.schedules).toEqual( operation === 'restore' ? ['0 * * * *'] : undefined, diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 714a6db5d7..bd55d040cb 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -1762,7 +1762,7 @@ describe('existing Cloudflare site handoff', () => { } }); - it.each(['add', 'remove', 'remove to static'] as const)( + it.each(['add', 'remove', 'remove to static', 'retry cleanup', 'completed cleanup'] as const)( 'supports the %s operation for a local Workflow in an atomic deployment', async (operation) => { const root = site(); @@ -1791,6 +1791,26 @@ describe('existing Cloudflare site handoff', () => { class_name: 'NotifyWorkflow', }, ], + ...((operation === 'retry cleanup' || operation === 'completed cleanup') && { + bindings: [], + versionMessage: + 'void:' + + JSON.stringify({ + schema: 2, + migrations: [], + triggerConfig: { + workers_dev: true, + preview_urls: false, + crons: [], + routes: [], + queueConsumers: [], + workflows: [], + workflowScheduleCleanup: [ + { workflowName: 'site-notify', className: 'NotifyWorkflow' }, + ], + }, + }), + }), }); const activateVersion = vi .fn>() @@ -1810,7 +1830,7 @@ describe('existing Cloudflare site handoff', () => { JSON.stringify({ ...parseRootWranglerConfig(path), workflows: [ - { name: 'site-notify', binding: 'WORKFLOW_NOTIFY', class_name: 'NotifyWorkflow' }, + { name: 'site_notify', binding: 'WORKFLOW_NOTIFY', class_name: 'NotifyWorkflow' }, ], }), ); @@ -1820,6 +1840,20 @@ describe('existing Cloudflare site handoff', () => { verifyDeployConfig: verifyGeneratedDeployConfig, activateVersion, }); + const defaultRunner = deps.runWrangler; + if (defaultRunner) { + deps.runWrangler = (request, command) => + request.type === 'triggers.clear-workflow-schedules' && request.inspectOnly + ? { ...cleanExit, data: operation === 'retry cleanup' } + : defaultRunner(request, command); + } + if (operation === 'completed cleanup') { + await expect( + runCloudflareDeploy(root, { platform: 'cloudflare', atomic: true }, silentCliLog, deps), + ).rejects.toBeInstanceOf(ExitError); + expect(activateVersion).not.toHaveBeenCalled(); + return; + } await runCloudflareDeploy( root, { diff --git a/packages/void/test/unit/cloudflare-operation-process.test.ts b/packages/void/test/unit/cloudflare-operation-process.test.ts index 6f65f63081..2c32198fba 100644 --- a/packages/void/test/unit/cloudflare-operation-process.test.ts +++ b/packages/void/test/unit/cloudflare-operation-process.test.ts @@ -319,6 +319,85 @@ registerHooks({ 30_000, ); +it.each(['scheduled', 'already cleared', 'inspect', 'moved', 'missing', 'denied'] as const)( + 'clears schedules of a removed Workflow by its provider name: %s', + async (state) => { + const directory = temporaryDirectory('void-workflow-schedules-'); + const requests: Array<{ method: string | undefined; url: string | undefined; body: unknown }> = + []; + const api = await listen( + createServer(async (request, response) => { + let data = ''; + for await (const chunk of request) { + data += chunk; + } + requests.push({ + method: request.method, + url: request.url, + body: data ? JSON.parse(data) : undefined, + }); + const missing = state === 'missing'; + const denied = state === 'denied' && request.method === 'PUT'; + response.writeHead(missing ? 404 : denied ? 403 : 200, { + 'Content-Type': 'application/json', + }); + response.end( + JSON.stringify({ + success: !missing && !denied, + errors: missing ? [{ code: 10_200 }] : [], + result: { + name: 'previous-name', + script_name: state === 'moved' ? 'another-worker' : 'test-worker', + class_name: 'Job', + schedules: + state === 'already cleared' || request.method === 'PUT' + ? [] + : [{ cron: '0 0 * * *' }], + }, + }), + ); + }), + ); + const configPath = join(directory, 'wrangler.json'); + writeFileSync(configPath, JSON.stringify({ name: 'test-worker', account_id: 'test-account' })); + const settings = { + concurrency: { limit: 2 }, + limits: { steps: 10 }, + default_retention: { success_retention: '7 days' }, + }; + const output = await runOperation( + directory, + { + type: 'triggers.clear-workflow-schedules', + workerName: 'test-worker', + workflowName: 'previous-name', + className: 'Job', + configPath, + inspectOnly: state === 'inspect', + ...settings, + }, + tokenEnv(api), + ); + expect(output.status, output.stderr).toBe(state === 'denied' ? 1 : 0); + if (state === 'inspect') { + expect(decodeCloudflareOperationResult(output).data).toBe(true); + } + const url = '/client/v4/accounts/test-account/workflows/previous-name'; + expect(requests).toEqual([ + { method: 'GET', url, body: undefined }, + ...(state === 'scheduled' || state === 'denied' + ? [ + { + method: 'PUT', + url, + body: { script_name: 'test-worker', class_name: 'Job', schedules: [], ...settings }, + }, + ] + : []), + ]); + }, +); + it.each(['clear-crons', 'clear-domains'])( 'clears %s through the pinned account API', async (operation) => { diff --git a/packages/void/test/unit/deploy-project.test.ts b/packages/void/test/unit/deploy-project.test.ts index 6c8f2b95ce..7033aeed71 100644 --- a/packages/void/test/unit/deploy-project.test.ts +++ b/packages/void/test/unit/deploy-project.test.ts @@ -425,6 +425,42 @@ describe('resolveFullDeployBuildCommand', () => { }); describe('resolveStaticDeployPreset', () => { + it('keeps root static assets when workflows/ only contains illustrations', () => { + const root = mkdtempSync(join(tmpdir(), 'void-static-assets-')); + tempDirs.push(root); + mkdirSync(join(root, 'workflows')); + writeFileSync(join(root, 'workflows', 'chart.svg'), ''); + writeFileSync(join(root, 'index.html'), '
'); + expect(resolveStaticDeployPreset(root, { inference: { appType: 'static' } })?.outputDir).toBe( + toSlash(root), + ); + writeFileSync( + join(root, 'workflows/job.ts'), + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({async run() {}})", + ); + expect(resolveStaticDeployPreset(root, { inference: { appType: 'static' } })?.outputDir).toBe( + toSlash(join(root, 'dist')), + ); + }); + it('builds the client of an explicitly static Vite app with routes and Workflows', () => { + const root = mkdtempSync(join(tmpdir(), 'void-static-workflows-')); + tempDirs.push(root); + mkdirSync(join(root, 'routes')); + mkdirSync(join(root, 'workflows')); + writeFileSync( + join(root, 'vite.config.ts'), + "import { voidPlugin } from 'void'; export default { plugins: [voidPlugin()] };", + ); + writeFileSync( + join(root, 'package.json'), + JSON.stringify({ scripts: { build: 'vite build' }, devDependencies: { vite: 'latest' } }), + ); + expect(resolveStaticDeployPreset(root, { inference: { appType: 'spa' } })).toEqual({ + appType: 'spa', + buildCommand: 'npm run build', + outputDir: toSlash(join(root, 'dist/client')), + }); + }); it('treats --dir as a static deploy override even in framework-shaped projects', () => { const root = mkdtempSync(join(tmpdir(), 'void-test-')); tempDirs.push(root); diff --git a/packages/void/test/unit/workflow-runtime.typecheck.ts b/packages/void/test/unit/workflow-runtime.typecheck.ts index 5e76908f86..eca1b10443 100644 --- a/packages/void/test/unit/workflow-runtime.typecheck.ts +++ b/packages/void/test/unit/workflow-runtime.typecheck.ts @@ -43,6 +43,16 @@ const envWorkflow = defineWorkflow<{ id: number }, WorkflowEnv>({ declare const workerEnv: WorkflowEnv, ctx: ExecutionContext; new envWorkflow.class(ctx, workerEnv); declare const wrongBinding: Workflow<{ name: string }>; +declare const narrowerBinding: Workflow<{ id: number; recipient: string }>; +// @ts-expect-error The definition cannot supply the recipient required by this binding. +void envWorkflow.create(narrowerBinding, { params: { id: 1 } }); +// @ts-expect-error The batch also sends only the definition's payload. +void envWorkflow.createBatch(narrowerBinding, [{ params: { id: 1 } }]); +declare const broaderBinding: Workflow<{ id: number | string }>; +void envWorkflow.create(broaderBinding, { params: { id: 1 } }); +declare const oneOfTwoBindings: typeof broaderBinding | typeof narrowerBinding; +// @ts-expect-error The receiver could be the binding requiring a recipient. +void envWorkflow.create(oneOfTwoBindings, { params: { id: 1 } }); // @ts-expect-error This binding can't receive the declared payload. void envWorkflow.create(wrongBinding, { params: { id: 1 } }); // @ts-expect-error Batch options must agree with the supplied binding. @@ -56,6 +66,8 @@ const converted = defineWorkflow({ }); declare const convertedBinding: Workflow<{ id: number }>; void converted.create(convertedBinding, { params: '1' }); +// @ts-expect-error The schema's output is missing recipient. +void converted.create(narrowerBinding, { params: '1' }); declare const stringBinding: Workflow; // @ts-expect-error The binding receives the parsed object. void converted.create(stringBinding, { params: '1' }); diff --git a/packages/void/test/unit/workflow-scan.test.ts b/packages/void/test/unit/workflow-scan.test.ts index 460f075d1d..5e315d8e59 100644 --- a/packages/void/test/unit/workflow-scan.test.ts +++ b/packages/void/test/unit/workflow-scan.test.ts @@ -59,6 +59,25 @@ describe('scanWorkflowModules', () => { expect(() => assertNoWorkflowsForPlatform(root)).not.toThrow(); }); + it('reports CommonJS Workflow definitions and leaves ordinary CommonJS helpers alone', () => { + const root = createRoot({ + 'tools.cjs': + "const { defineWorkflow } = require('void/workflows'); module.exports = { defineWorkflow };", + }); + expect(scanWorkflowModules(root)).toEqual([]); + writeFileSync( + join(root, 'workflows', 'job.cjs'), + `const { defineWorkflow } = require('void/workflows'); +module.exports = defineWorkflow({ async run() {} });`, + ); + expect(() => scanWorkflowModules(root)).toThrow(/job\.cjs.*\.mjs/); + writeFileSync( + join(root, 'workflows', 'job.cjs'), + "module.exports = require('void/workflows')['defineWorkflow']({ async run() {} });", + ); + expect(() => scanWorkflowModules(root)).toThrow(/job\.cjs.*\.mjs/); + }); + it('derives binding, class, and resource names from filenames', () => { const root = createRoot({ 'send-welcome.ts': definition, 'types.d.ts': '' }); expect(scanWorkflowModules(root)).toEqual([ @@ -155,7 +174,10 @@ const Job = defineWorkflow({ name: 'daily', async run() {} });`; describe('Cloudflare Workflow names', () => { it('prefixes the account-scoped name with the Worker name', () => { - expect(cloudflareWorkflowName('welcome', 'My_App')).toBe('my-app-welcome'); + expect(cloudflareWorkflowName('welcome', 'My_App')).toBe('My_App_welcome'); + expect(cloudflareWorkflowName('eu-charge', 'billing')).not.toBe( + cloudflareWorkflowName('charge', 'billing-eu'), + ); expect(cloudflareWorkflowName('welcome')).toBe('welcome'); expect(cloudflareWorkflowName('w'.repeat(60), 'app')).toHaveLength(64); }); @@ -193,10 +215,10 @@ describe('Cloudflare Workflow names', () => { class_name: 'WelcomeWorkflow', }; expect(planWorkflowAdditions([authored], modules, 'app')).toEqual([ - { name: 'app-import', binding: 'WORKFLOW_IMPORT', class_name: 'ImportWorkflow' }, + { name: 'app_import', binding: 'WORKFLOW_IMPORT', class_name: 'ImportWorkflow' }, ]); expect(planWorkflowAdditions([{ ...authored, script_name: 'app' }], modules, 'app')).toEqual([ - { name: 'app-import', binding: 'WORKFLOW_IMPORT', class_name: 'ImportWorkflow' }, + { name: 'app_import', binding: 'WORKFLOW_IMPORT', class_name: 'ImportWorkflow' }, ]); expect(planWorkflowAdditions([], [], 'app')).toEqual([]); }); @@ -226,10 +248,10 @@ describe('Cloudflare Workflow names', () => { ).toThrow("binding 'WORKFLOW_WELCOME' is already configured"); expect(() => planWorkflowAdditions( - [{ name: 'app-welcome', binding: 'MINE', class_name: 'Mine' }], + [{ name: 'app_welcome', binding: 'MINE', class_name: 'Mine' }], modules, 'app', ), - ).toThrow("Workflow name 'app-welcome' is already configured for binding 'MINE'"); + ).toThrow("Workflow name 'app_welcome' is already configured for binding 'MINE'"); }); });