@vite-hub/workflow 0.0.3 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -7,9 +7,9 @@
7
7
  <img alt="Workflow" src="https://img.shields.io/badge/Workflow-durable%20steps-7c3aed?style=flat-square">
8
8
  </p>
9
9
 
10
- `@vite-hub/workflow` defines long-running work once and starts it through one `runWorkflow()` API.
10
+ `@vite-hub/workflow` discovers named long-running work and exposes one provider-neutral API for starting and inspecting runs.
11
11
 
12
- Vercel definitions can register a native entry for durable execution. Definitions without one remain source-compatible, but execute inline and do not survive a function restart.
12
+ Use a Workflow when the application needs a run id, durable state, retries, cancellation, or resumable work. Use [Queue](https://vitehub.dev/docs/server-primitives/queue) when background delivery is enough and the application does not need to inspect a run.
13
13
 
14
14
  ## Install
15
15
 
@@ -17,96 +17,207 @@ Vercel definitions can register a native entry for durable execution. Definition
17
17
  pnpm add @vite-hub/workflow
18
18
  ```
19
19
 
20
- Add the provider dependency for the workflow provider you configure.
21
- OpenWorkflow worker lifecycle helpers live at `@vite-hub/workflow/runtime/openworkflow-worker`, so importing the provider-agnostic package root does not require OpenWorkflow's types.
20
+ Then install the dependency required by the selected provider:
22
21
 
23
- ## Minimal API
22
+ | Provider | Additional dependency | Durable state |
23
+ | -------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------ |
24
+ | Cloudflare Workflows | None in application code | Cloudflare owns run state. |
25
+ | Vercel Workflow | `workflow` and `@workflow/builders` for native durable definitions | Native definitions survive function restarts; plain handlers run inline. |
26
+ | OpenWorkflow | `openworkflow`; add `postgres` when using Postgres | Requires explicit SQLite or Postgres storage. |
27
+
28
+ Importing the provider-neutral package root does not load OpenWorkflow types. Worker lifecycle helpers live at `@vite-hub/workflow/runtime/openworkflow-worker`.
29
+
30
+ ## Define a workflow
24
31
 
25
32
  ```ts
26
- // server/workflows/welcome.ts
27
- import { defineWorkflow } from "@vite-hub/workflow"
33
+ // server/workflows/onboard-user.ts
34
+ import { defineWorkflow } from "@vite-hub/workflow";
28
35
 
29
- export default defineWorkflow<{ email: string }>(async ({ id, payload, step }) => {
30
- const email = await step?.do?.("send-email", {}, async () => {
31
- return { sentTo: payload.email }
32
- })
36
+ export default defineWorkflow<{ email: string }>(async ({ id, payload, provider }) => {
37
+ const idempotencyKey = `onboard-user:${payload.email}`;
38
+ const user = await upsertUser(payload.email, { idempotencyKey });
39
+ await sendWelcomeEmail(user.email, { idempotencyKey: `${idempotencyKey}:welcome-email` });
33
40
 
34
- return { id, email }
35
- })
41
+ return { id, provider };
42
+ });
36
43
  ```
37
44
 
38
- For a durable Vercel run, keep the same context-shaped interface and register a native entry containing the Workflow DevKit directive:
45
+ Both external operations receive keys derived from stable input. Preserve that idempotency when adding side effects so retrying a completed operation does not duplicate it.
39
46
 
40
- ```ts
41
- import { defineWorkflow, type WorkflowExecutionContext } from "@vite-hub/workflow"
47
+ ViteHub discovers `server/workflows/<name>.ts`, folder workflows such as `server/workflows/onboard-user/index.ts`, and `src/<name>.workflow.ts`. The file name becomes the name passed to runtime helpers.
48
+
49
+ ## Configure the provider
42
50
 
43
- interface WelcomePayload {
44
- email: string
51
+ ```ts
52
+ // server/workflow-runtime.ts
53
+ import type {
54
+ ResolvedWorkflowOptions,
55
+ WorkflowDefinition,
56
+ WorkflowDefinitionRegistry,
57
+ } from "@vite-hub/workflow";
58
+ import {
59
+ setWorkflowRuntimeConfig,
60
+ setWorkflowRuntimeRegistry,
61
+ } from "@vite-hub/workflow/runtime/state";
62
+ const postgresUrl = {
63
+ kind: "env-variable",
64
+ source: { kind: "env", name: "OPENWORKFLOW_POSTGRES_URL" },
65
+ } as const;
66
+
67
+ export const workflowConfig = {
68
+ provider: "openworkflow",
69
+ postgres: { url: postgresUrl },
70
+ } satisfies ResolvedWorkflowOptions;
71
+
72
+ const workflowRegistry = {
73
+ "onboard-user": async () => ({
74
+ default: (await import("./workflows/onboard-user.ts")).default as WorkflowDefinition,
75
+ }),
76
+ } satisfies WorkflowDefinitionRegistry;
77
+
78
+ export function installWorkflowRuntime() {
79
+ const url = process.env.OPENWORKFLOW_POSTGRES_URL;
80
+ if (!url) throw new Error("OPENWORKFLOW_POSTGRES_URL is required");
81
+
82
+ setWorkflowRuntimeConfig({
83
+ ...workflowConfig,
84
+ postgres: { ...workflowConfig.postgres, url },
85
+ });
86
+ setWorkflowRuntimeRegistry(workflowRegistry);
45
87
  }
88
+ ```
89
+
90
+ ```ts
91
+ // vite.config.ts
92
+ import { hubWorkflow } from "@vite-hub/workflow/vite";
93
+ import { defineConfig } from "vite";
94
+ import { workflowConfig } from "./server/workflow-runtime.ts";
46
95
 
47
- async function durableWelcome({ payload }: WorkflowExecutionContext<WelcomePayload>) {
48
- "use workflow"
96
+ export default defineConfig({
97
+ plugins: [hubWorkflow()],
98
+ workflow: workflowConfig,
99
+ });
100
+ ```
49
101
 
50
- return { sentTo: payload.email }
51
- }
102
+ The Vite config, application process, and worker below share one provider config. The runtime installer also registers the same definitions in both processes. Set `provider` explicitly when the deployment target should not decide it. Otherwise ViteHub selects Cloudflare on Cloudflare hosting and Vercel on other supported hosts. Node and Docker select OpenWorkflow when its storage is configured. Netlify cannot infer a provider.
52
103
 
53
- async function inlineWelcome({ payload }: WorkflowExecutionContext<WelcomePayload>) {
54
- return { sentTo: payload.email }
55
- }
104
+ OpenWorkflow accepts one storage choice: `postgres.url` or `sqlite.path`. Hosted credentials belong in Server Env, not source code.
56
105
 
57
- export default defineWorkflow(inlineWelcome, { native: durableWelcome })
106
+ ### Run an OpenWorkflow worker
107
+
108
+ `runWorkflow()` only enqueues an OpenWorkflow run. Start one worker in a long-lived Node or Docker process:
109
+
110
+ ```ts
111
+ // worker.ts
112
+ import { startOpenWorkflowWorker } from "@vite-hub/workflow/runtime/openworkflow-worker";
113
+ import { installWorkflowRuntime } from "./server/workflow-runtime.ts";
114
+
115
+ installWorkflowRuntime();
116
+ const worker = await startOpenWorkflowWorker();
58
117
  ```
59
118
 
60
- ViteHub transforms the native entry with Workflow DevKit when it generates Vercel provider output.
119
+ Keep this process running while it should consume queued runs, and do not start a worker per request. `startOpenWorkflowWorker()` installs `SIGINT` and `SIGTERM` handlers. If the host owns shutdown, await `worker.stop()` from its shutdown hook.
120
+
121
+ ## Start and inspect a run
61
122
 
62
123
  ```ts
63
- // server/api/welcome.post.ts
64
- import { getWorkflowRun, runWorkflow } from "@vite-hub/workflow"
65
- import { defineEventHandler, readBody } from "h3"
124
+ // server/api/onboard.post.ts
125
+ import { getWorkflowRun, runWorkflow } from "@vite-hub/workflow";
126
+ import { defineEventHandler, readBody } from "h3";
127
+ import { installWorkflowRuntime } from "../workflow-runtime.ts";
128
+
129
+ installWorkflowRuntime();
66
130
 
67
131
  export default defineEventHandler(async (event) => {
68
- const run = await runWorkflow("welcome", await readBody<{ email: string }>(event))
69
- return getWorkflowRun("welcome", run.id)
70
- })
132
+ const payload = await readBody<{ email: string }>(event);
133
+ const started = await runWorkflow("onboard-user", payload);
134
+
135
+ return await getWorkflowRun("onboard-user", started.id);
136
+ });
71
137
  ```
72
138
 
73
- `getWorkflowRun()` normalizes provider run and step state, including timestamps, attempts, and failures. `cancelWorkflow()` cancels a durable run, and `resumeWorkflowSignal()` forwards an opaque signal token created inside the native workflow. Providers that cannot perform an operation fail explicitly instead of simulating it.
139
+ `runWorkflow()` returns a normalized acknowledgement with an id, provider, and status. `getWorkflowRun()` returns normalized run and step state, including timestamps, attempts, results, and failures when the provider supplies them.
140
+
141
+ The other runtime helpers are:
142
+
143
+ - `deferWorkflow()` starts through the deferred provider path when available.
144
+ - `cancelWorkflow()` cancels a native Vercel run.
145
+ - `resumeWorkflowSignal()` resumes a registered Vercel Workflow DevKit hook token.
146
+ - `createWorkflow()` creates a named handle with `run`, `defer`, `getRun`, and `cancel` methods.
147
+
148
+ Unsupported provider operations fail with `WORKFLOW_OPERATION_UNSUPPORTED`; ViteHub does not pretend that an inline run was cancelled or resumed.
149
+
150
+ ## Make a Vercel workflow durable
151
+
152
+ A plain Vercel definition executes inline and does not survive a function restart. For durable execution, keep the same context-shaped handler and register a native Workflow DevKit entry:
153
+
154
+ ```sh
155
+ pnpm add workflow @workflow/builders
156
+ ```
157
+
158
+ ```ts
159
+ import { defineWorkflow, type WorkflowExecutionContext } from "@vite-hub/workflow";
160
+
161
+ interface OnboardPayload {
162
+ email: string;
163
+ }
164
+
165
+ async function upsertUserStep(email: string) {
166
+ "use step";
167
+
168
+ return await upsertUser(email, { idempotencyKey: `onboard-user:${email}` });
169
+ }
170
+
171
+ async function durableOnboard({ payload }: WorkflowExecutionContext<OnboardPayload>) {
172
+ "use workflow";
173
+
174
+ const user = await upsertUserStep(payload.email);
175
+ return { userId: user.id };
176
+ }
177
+
178
+ async function inlineOnboard({ payload }: WorkflowExecutionContext<OnboardPayload>) {
179
+ const user = await upsertUser(payload.email, { idempotencyKey: `onboard-user:${payload.email}` });
180
+ return { userId: user.id };
181
+ }
182
+
183
+ export default defineWorkflow(inlineOnboard, { native: durableOnboard });
184
+ ```
185
+
186
+ ViteHub transforms `native` when it generates Vercel output. Other providers keep using the normal handler. Put external side effects in idempotent `use step` functions because a durable step may be retried.
187
+
188
+ ## Handle stable failures
74
189
 
75
190
  Throw `ViteHubError` when app callers need a stable, inspectable Workflow failure instead of parsing log output or provider-specific messages. ViteHub-owned failures use the package's fixed `WorkflowErrorCode` vocabulary.
76
191
 
77
192
  ```ts
78
- import { ViteHubError } from "@vite-hub/runtime"
193
+ import { ViteHubError } from "@vite-hub/runtime";
79
194
 
80
195
  async function transcribe(recordingId: string) {
81
196
  try {
82
- return await transcribeRecording(recordingId)
83
- }
84
- catch (cause) {
197
+ return await transcribeRecording(recordingId);
198
+ } catch (cause) {
85
199
  throw new ViteHubError("TRANSCRIPTION_FAILED", "Transcription failed.", {
86
200
  cause,
87
201
  details: { recordingId },
88
- })
202
+ });
89
203
  }
90
204
  }
91
205
  ```
92
206
 
93
207
  `code` and `message` remain available through `error.toJSON()`. Keep `details` JSON-safe and free of secrets; `toJSON()` omits `cause`, which remains available only on the in-memory error. ViteHub's built-in codes are typed as `WorkflowErrorCode` and use code-derived messages and code-specific details. Workflow Step retry behavior belongs in the Step's retry options rather than the error.
94
208
 
95
- ```ts
96
- // vite.config.ts
97
- import { hubWorkflow } from "@vite-hub/workflow/vite"
98
- import { defineConfig } from "vite"
99
-
100
- export default defineConfig({
101
- plugins: [hubWorkflow()],
102
- workflow: { provider: "openworkflow" },
103
- })
104
- ```
105
-
106
- ## Vite Integration
209
+ ## Production checklist
107
210
 
108
- Use `hubWorkflow()` in Vite to discover `server/workflows/<name>.ts`, folder workflows such as `server/workflows/welcome/index.ts` with numbered step files, and `src/<name>.workflow.ts`.
211
+ - Confirm that the selected provider is durable enough for the work; inline Vercel handlers are not durable.
212
+ - Make side-effecting steps idempotent so retries do not duplicate work.
213
+ - Keep provider credentials and database URLs in Server Env.
214
+ - Configure durable OpenWorkflow storage and run its migrations before serving traffic.
215
+ - Verify start, inspection, failure, retry, cancellation, timeout, and restart behavior on the deployment host.
109
216
 
110
- Providers map to [OpenWorkflow](https://openworkflow.dev/docs/overview), [Cloudflare Workflows](https://developers.cloudflare.com/workflows/), or [Vercel Workflow](https://vercel.com/docs/workflow).
217
+ ## Documentation
111
218
 
112
- Learn more at [vitehub.dev](https://vitehub.dev).
219
+ - [Workflow guide](https://vitehub.dev/docs/server-primitives/workflows)
220
+ - [Runtime and host support](https://vitehub.dev/docs/frameworks-hosts/support-matrix)
221
+ - [OpenWorkflow](https://openworkflow.dev/docs/overview)
222
+ - [Cloudflare Workflows](https://developers.cloudflare.com/workflows/)
223
+ - [Vercel Workflow](https://vercel.com/docs/workflow)
@@ -31,11 +31,12 @@ function getCloudflareWorkflowClassName(name) {
31
31
  }
32
32
  function createCloudflareWorkflowBindings(definitions, options) {
33
33
  if (!definitions.length) return;
34
- if (definitions.length > 1 && options && (options.binding || options.name)) throw new TypeError("Cloudflare workflow binding and name overrides are only supported when one workflow is discovered.");
34
+ const configurable = definitions.filter((definition) => definition.source !== "agent-workflow-recovery");
35
+ if (configurable.length > 1 && options && (options.binding || options.name)) throw new TypeError("Cloudflare workflow binding and name overrides are only supported when one workflow is discovered.");
35
36
  return definitions.map((definition) => ({
36
- binding: definitions.length === 1 && options ? options.binding || getCloudflareWorkflowBindingName(definition.name) : getCloudflareWorkflowBindingName(definition.name),
37
+ binding: configurable.length === 1 && configurable[0] === definition && options ? options.binding || getCloudflareWorkflowBindingName(definition.name) : getCloudflareWorkflowBindingName(definition.name),
37
38
  class_name: getCloudflareWorkflowClassName(definition.name),
38
- name: definitions.length === 1 && options ? options.name || getCloudflareWorkflowName(definition.name) : getCloudflareWorkflowName(definition.name)
39
+ name: configurable.length === 1 && configurable[0] === definition && options ? options.name || getCloudflareWorkflowName(definition.name) : getCloudflareWorkflowName(definition.name)
39
40
  }));
40
41
  }
41
42
  //#endregion
@@ -1,7 +1,9 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  //#region ../internal/src/runtime/cloudflare-env.ts
3
3
  let activeEnv;
4
- const activeEnvStorage = new AsyncLocalStorage();
4
+ const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
5
+ const runtimeGlobal = globalThis;
6
+ const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
5
7
  function setActiveCloudflareEnv(env) {
6
8
  activeEnv = env;
7
9
  globalThis.__env__ = env;
@@ -18,7 +20,7 @@ function getActiveCloudflareEnv() {
18
20
  }
19
21
  function getCloudflareEnv(event) {
20
22
  const target = event;
21
- return target?.env || target?.context?.cloudflare?.env || target?.context?._platform?.cloudflare?.env || target?.req?.runtime?.cloudflare?.env || getActiveCloudflareEnv();
23
+ return target?.env || target?.context?.cloudflare?.env || target?.context?._platform?.cloudflare?.env || target?.req?.runtime?.cloudflare?.env || target?.node?.req?.runtime?.cloudflare?.env || getActiveCloudflareEnv();
22
24
  }
23
25
  function resolveWaitUntil(event) {
24
26
  const target = event;
@@ -31,7 +33,10 @@ function resolveWaitUntil(event) {
31
33
  target?.context?._platform?.cloudflare?.context,
32
34
  target?.req,
33
35
  target?.req?.runtime?.cloudflare,
34
- target?.req?.runtime?.cloudflare?.context
36
+ target?.req?.runtime?.cloudflare?.context,
37
+ target?.node?.req,
38
+ target?.node?.req?.runtime?.cloudflare,
39
+ target?.node?.req?.runtime?.cloudflare?.context
35
40
  ];
36
41
  for (const owner of owners) if (typeof owner?.waitUntil === "function") return owner.waitUntil.bind(owner);
37
42
  }
@@ -1,12 +1,17 @@
1
- import { t as normalizeWorkflowOptions } from "./config-BDqB6I4E.js";
2
- import { i as runWithActiveCloudflareEnv, t as createCloudflareRuntimeEvent } from "./cloudflare-env-mFp2Uj6Z.js";
1
+ import { t as normalizeWorkflowOptions } from "./config-BHknO_rT.js";
2
+ import { i as runWithActiveCloudflareEnv, t as createCloudflareRuntimeEvent } from "./cloudflare-env-DjxQNbrx.js";
3
3
  import { runWithWorkflowRuntimeEvent, setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry } from "./runtime/state.js";
4
4
  import { t as resolveAppFetch } from "./app-BZpq2cwC.js";
5
- import { H3, toWebHandler } from "h3/cloudflare";
6
5
  //#region ../internal/src/runtime/cloudflare-hosted.ts
7
6
  function createWebRequestHandler(appHandler) {
8
- const defaultHandler = toWebHandler(new H3());
9
- return async (request, context) => await Promise.resolve(appHandler ? appHandler(request, context) : defaultHandler(request, context));
7
+ return async (request, context) => await Promise.resolve(appHandler ? appHandler(request, context) : new Response(JSON.stringify({
8
+ status: 404,
9
+ message: `Cannot find any route matching [${request.method}] ${request.url}`
10
+ }), {
11
+ headers: { "content-type": "application/json;charset=UTF-8" },
12
+ status: 404,
13
+ statusText: "Not Found"
14
+ }));
10
15
  }
11
16
  function createCloudflareHostedWorker(adapter) {
12
17
  const requestHandler = createWebRequestHandler(resolveAppFetch(adapter.label, adapter.app));
@@ -22,18 +27,20 @@ function createCloudflareHostedWorker(adapter) {
22
27
  }
23
28
  //#endregion
24
29
  //#region src/runtime/cloudflare-vite.ts
30
+ function installWorkflowCloudflareRuntime(options = {}) {
31
+ setWorkflowRuntimeConfig(options.workflow === false ? false : normalizeWorkflowOptions(options.workflow, { hosting: "cloudflare" }));
32
+ setWorkflowRuntimeRegistry(options.registry);
33
+ }
25
34
  function createWorkflowCloudflareWorker(options = {}) {
26
- const workflowConfig = options.workflow === false ? false : normalizeWorkflowOptions(options.workflow, { hosting: "cloudflare" });
27
35
  return createCloudflareHostedWorker({
28
36
  app: options.app,
29
37
  label: "workflow",
30
38
  async onRequest({ env, executionContext, handle }) {
31
- setWorkflowRuntimeConfig(workflowConfig);
32
- setWorkflowRuntimeRegistry(options.registry);
39
+ installWorkflowCloudflareRuntime(options);
33
40
  const runtimeEvent = createCloudflareRuntimeEvent(env, executionContext);
34
41
  return await runWithActiveCloudflareEnv(env, () => runWithWorkflowRuntimeEvent(runtimeEvent, () => handle(runtimeEvent.context)));
35
42
  }
36
43
  });
37
44
  }
38
45
  //#endregion
39
- export { createWorkflowCloudflareWorker as t };
46
+ export { installWorkflowCloudflareRuntime as n, createWorkflowCloudflareWorker as t };
@@ -8,7 +8,13 @@ function normalizeHosting(hosting) {
8
8
  //#endregion
9
9
  //#region ../internal/src/object.ts
10
10
  function isPlainObject(value) {
11
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
11
+ if (value === null || Object(value) !== value || Array.isArray(value)) return false;
12
+ try {
13
+ Function.prototype.toString.call(value);
14
+ return false;
15
+ } catch {
16
+ return true;
17
+ }
12
18
  }
13
19
  //#endregion
14
20
  //#region src/config.ts
@@ -127,4 +133,4 @@ function normalizeWorkflowOptions(options, input = {}) {
127
133
  return resolveProvider(options || {}, normalizeHosting(input.hosting));
128
134
  }
129
135
  //#endregion
130
- export { normalizeWorkflowOptions as t };
136
+ export { isPlainObject as n, normalizeHosting as r, normalizeWorkflowOptions as t };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as WorkflowStepFunction, C as WorkflowProviderStep, D as WorkflowSharedOptions, E as WorkflowRunStep, M as WorkflowStepRunner, O as WorkflowSignalResult, S as WorkflowProviderOptions, T as WorkflowRunStatus, _ as WorkflowHandle, a as InferredWorkflowProviderOptions, b as WorkflowModuleProviderOptions, c as OpenWorkflowWorkerOptions, d as WorkflowCreateOptions, f as WorkflowDeferOptions, g as WorkflowExecutionContext, h as WorkflowDefinitionRegistry, i as DiscoveredWorkflowDefinition, j as WorkflowStepOptions, k as WorkflowStartOptions, l as ResolvedWorkflowOptions, m as WorkflowDefinitionOptions, n as CloudflareWorkflowInstance, o as OpenWorkflowPostgresOptions, p as WorkflowDefinition, r as CloudflareWorkflowProviderOptions, s as OpenWorkflowProviderOptions, t as CloudflareWorkflowBinding, u as VercelWorkflowProviderOptions, v as WorkflowHandler, w as WorkflowRun, x as WorkflowProvider, y as WorkflowModuleOptions } from "./types-BUlYBZwH.js";
1
+ import { A as WorkflowStepFunction, C as WorkflowProviderStep, D as WorkflowSharedOptions, E as WorkflowRunStep, M as WorkflowStepRunner, O as WorkflowSignalResult, S as WorkflowProviderOptions, T as WorkflowRunStatus, _ as WorkflowHandle, a as InferredWorkflowProviderOptions, b as WorkflowModuleProviderOptions, c as OpenWorkflowWorkerOptions, d as WorkflowCreateOptions, f as WorkflowDeferOptions, g as WorkflowExecutionContext, h as WorkflowDefinitionRegistry, i as DiscoveredWorkflowDefinition, j as WorkflowStepOptions, k as WorkflowStartOptions, l as ResolvedWorkflowOptions, m as WorkflowDefinitionOptions, n as CloudflareWorkflowInstance, o as OpenWorkflowPostgresOptions, p as WorkflowDefinition, r as CloudflareWorkflowProviderOptions, s as OpenWorkflowProviderOptions, t as CloudflareWorkflowBinding, u as VercelWorkflowProviderOptions, v as WorkflowHandler, w as WorkflowRun, x as WorkflowProvider, y as WorkflowModuleOptions } from "./types-B9RdRkKh.js";
2
2
  import { createWorkflowCloudflareWorker } from "./runtime/cloudflare-vite.js";
3
3
  import { ViteHubError } from "@vite-hub/runtime";
4
4
 
@@ -63,11 +63,16 @@ declare function createWorkflow<TPayload = unknown, TResult = unknown>(options:
63
63
  handler: WorkflowHandler<TPayload, TResult>;
64
64
  name: string;
65
65
  }): WorkflowHandle<TPayload, TResult>;
66
- declare function createWorkflow<TPayload = unknown, TResult = unknown>(name: string, options?: WorkflowCreateOptions<TPayload, TResult>): WorkflowHandle<TPayload, TResult>;
66
+ declare function createWorkflow<TPayload = unknown, TResult = unknown>(name: string, options: WorkflowCreateOptions<TPayload, TResult> & {
67
+ handler: WorkflowHandler<TPayload, TResult>;
68
+ }): WorkflowHandle<TPayload, TResult>;
69
+ declare function createWorkflow<TPayload = unknown>(name: string, options?: Omit<WorkflowCreateOptions<TPayload, unknown>, "handler"> & {
70
+ handler?: never;
71
+ }): WorkflowHandle<TPayload, unknown>;
67
72
  declare function createWorkflow<TPayload = unknown, TResult = unknown>(name: string, handler: WorkflowHandler<TPayload, TResult>, options?: WorkflowCreateOptions<TPayload, TResult>): WorkflowHandle<TPayload, TResult>;
68
- declare function runWorkflow<TPayload = unknown, TResult = unknown>(name: string, payload?: TPayload, options?: WorkflowDeferOptions): Promise<WorkflowRun<TPayload, TResult>>;
69
- declare function getWorkflowRun<TPayload = unknown, TResult = unknown>(name: string, id: string): Promise<WorkflowRun<TPayload, TResult>>;
70
- declare function cancelWorkflow<TPayload = unknown, TResult = unknown>(name: string, id: string): Promise<WorkflowRun<TPayload, TResult>>;
73
+ declare function runWorkflow<TPayload = unknown>(name: string, payload?: TPayload, options?: WorkflowDeferOptions): Promise<WorkflowRun<TPayload, unknown>>;
74
+ declare function getWorkflowRun(name: string, id: string): Promise<WorkflowRun<unknown, unknown>>;
75
+ declare function cancelWorkflow(name: string, id: string): Promise<WorkflowRun<unknown, unknown>>;
71
76
  declare function resumeWorkflowSignal<TPayload = unknown>(token: string, payload: TPayload): Promise<WorkflowSignalResult>;
72
77
  declare function deferWorkflow<TPayload = unknown>(name: string, payload?: TPayload, options?: WorkflowStartOptions): Promise<WorkflowRun<TPayload>>;
73
78
  //#endregion