@vite-hub/workflow 0.0.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +168 -47
  2. package/dist/{_app-DgwN4ulW.d.ts → app-BojnC_yf.d.ts} +1 -4
  3. package/dist/{app-BZpq2cwC.js → app-CmMq8l4t.js} +2 -1
  4. package/dist/client-CU5rELC0.js +658 -0
  5. package/dist/{cloudflare-D0Di-QYL.js → cloudflare-BfFnNWB0.js} +20 -4
  6. package/dist/cloudflare-env-CGLx7lUd.js +115 -0
  7. package/dist/cloudflare-env-lookup-CfX6wZKb.d.ts +4 -0
  8. package/dist/{cloudflare-env-CIjdFTv6.d.ts → cloudflare-shared-CTqh_a2s.d.ts} +2 -2
  9. package/dist/config-DCvRDlxA.js +145 -0
  10. package/dist/definition.d.ts +19 -0
  11. package/dist/definition.js +31 -0
  12. package/dist/delay--ESDybVT.js +81 -0
  13. package/dist/dev-recorder-CTN5Fkao.js +10 -0
  14. package/dist/durability.d.ts +23 -0
  15. package/dist/durability.js +62 -0
  16. package/dist/error-diagnostics-8YNJ37rP.js +286 -0
  17. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  18. package/dist/errors-DCqRnZpN.js +35 -0
  19. package/dist/errors-DVwFb6Fd.d.ts +56 -0
  20. package/dist/index.d.ts +23 -71
  21. package/dist/index.js +23 -378
  22. package/dist/inspect-B72iFyj-.js +70 -0
  23. package/dist/object-Da1zyPCR.js +11 -0
  24. package/dist/openworkflow-TEaNk0LV.d.ts +50 -0
  25. package/dist/openworkflow-defaults-DDig2M4s.js +26 -0
  26. package/dist/openworkflow-storage-Dj9zUAsk.js +28 -0
  27. package/dist/openworkflow.d.ts +2 -0
  28. package/dist/openworkflow.js +2 -0
  29. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  30. package/dist/operations-B0L8kV5s.js +329 -0
  31. package/dist/operations.d.ts +71 -0
  32. package/dist/operations.js +314 -0
  33. package/dist/out-fRNaVslw.js +20357 -0
  34. package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
  35. package/dist/run-error-DBWqiJHH.js +110 -0
  36. package/dist/runtime/cloudflare-runner.d.ts +7 -19
  37. package/dist/runtime/cloudflare-runner.js +27 -10
  38. package/dist/runtime/cloudflare-shared.d.ts +2 -1
  39. package/dist/runtime/cloudflare-shared.js +1 -1
  40. package/dist/runtime/cloudflare-vite.d.ts +10 -11
  41. package/dist/runtime/cloudflare-vite.js +47 -1
  42. package/dist/runtime/dev-runs.d.ts +4 -0
  43. package/dist/runtime/dev-runs.js +73 -0
  44. package/dist/runtime/execute.d.ts +24 -7
  45. package/dist/runtime/execute.js +135 -6
  46. package/dist/runtime/openworkflow-worker.d.ts +34 -9
  47. package/dist/runtime/openworkflow-worker.js +156 -37
  48. package/dist/runtime/openworkflow.d.ts +2 -23
  49. package/dist/runtime/openworkflow.js +289 -46
  50. package/dist/runtime/state.d.ts +22 -21
  51. package/dist/runtime/state.js +99 -25
  52. package/dist/runtime/vercel-vite.d.ts +10 -12
  53. package/dist/runtime/vercel-vite.js +7 -4
  54. package/dist/types-CnKVDnEp.d.ts +241 -0
  55. package/dist/{vercel-B0MuIVgJ.js → vercel-BZU_O6ay.js} +78 -24
  56. package/dist/vite.d.ts +529 -23
  57. package/dist/vite.js +2789 -1609
  58. package/package.json +62 -34
  59. package/dist/cloudflare-env-DjxQNbrx.js +0 -58
  60. package/dist/cloudflare-shared-BVVgDSdq.d.ts +0 -1
  61. package/dist/cloudflare-vite-BkDgB6Sr.js +0 -46
  62. package/dist/config-BHknO_rT.js +0 -136
  63. package/dist/provider-operation-CW2cYfVy.js +0 -65
  64. package/dist/runtime-type-DGUn8Ple.js +0 -37
  65. package/dist/types-B9RdRkKh.d.ts +0 -169
@@ -0,0 +1,658 @@
1
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics-8YNJ37rP.js";
2
+ import { n as createWorkflowError } from "./errors-DCqRnZpN.js";
3
+ import { a as encodeNameHex, n as getCloudflareWorkflowBindingName } from "./cloudflare-BfFnNWB0.js";
4
+ import { a as getCloudflareEnv, n as resolveWaitUntil } from "./cloudflare-env-CGLx7lUd.js";
5
+ import { t as normalizeWorkflowOptions } from "./config-DCvRDlxA.js";
6
+ import { i as toCloudflareStartParams, r as resolveWorkflowStartAt } from "./delay--ESDybVT.js";
7
+ import { t as getWorkflowDevRecorder } from "./dev-recorder-CTN5Fkao.js";
8
+ import { runSerializedWorkflowHandler } from "./runtime/execute.js";
9
+ import { a as safeWorkflowName, i as runWorkflowProviderOperation, t as toWorkflowRunError } from "./run-error-DBWqiJHH.js";
10
+ import { cancelOpenWorkflowRun, getOpenWorkflowRun, runOpenWorkflow } from "./runtime/openworkflow.js";
11
+ import { getInlineWorkflowDefinitions, getWorkflowRunState, getWorkflowRuntimeConfig, getWorkflowRuntimeEvent, getWorkflowRuntimeRegistry, loadWorkflowDefinition, registerInlineWorkflowDefinition, runWithWorkflowRuntimeEvent, setWorkflowRun } from "./runtime/state.js";
12
+ import { a as startVercelWorkflow, n as inspectVercelWorkflowRun, r as resumeVercelWorkflowSignal, t as cancelVercelWorkflow } from "./vercel-BZU_O6ay.js";
13
+ import { deserializeResponse, getViteHubErrorShape, isSerializedResponse } from "@vite-hub/runtime";
14
+ import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
15
+ //#region ../internal/src/runtime/random.ts
16
+ function randomId(prefix) {
17
+ const body = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
18
+ return prefix ? `${prefix}_${body}` : body;
19
+ }
20
+ //#endregion
21
+ //#region src/integrations/vercel.ts
22
+ function getVercelWorkflowName(name) {
23
+ return `workflow--${encodeNameHex(name)}`;
24
+ }
25
+ //#endregion
26
+ //#region src/runtime/adapters.ts
27
+ function resolveDispatchObserver(event) {
28
+ if (!event || typeof event !== "object") return void 0;
29
+ const candidate = Object.hasOwn(event, "onDispatch") ? Reflect.get(event, "onDispatch") : void 0;
30
+ return typeof candidate === "function" ? candidate : void 0;
31
+ }
32
+ function resolveSettlementObserver(event) {
33
+ if (!event || typeof event !== "object") return void 0;
34
+ const candidate = Object.hasOwn(event, "settled") ? Reflect.get(event, "settled") : void 0;
35
+ if (typeof candidate === "function") return candidate;
36
+ const context = Object.hasOwn(event, "context") ? Reflect.get(event, "context") : void 0;
37
+ if (!context || typeof context !== "object") return void 0;
38
+ const contextObject = Object(context);
39
+ const nested = Object.hasOwn(contextObject, "settled") ? Reflect.get(contextObject, "settled") : void 0;
40
+ return typeof nested === "function" ? nested : void 0;
41
+ }
42
+ function unsupportedOperation(provider, operation) {
43
+ throw createWorkflowError({
44
+ code: "WORKFLOW_OPERATION_UNSUPPORTED",
45
+ details: {
46
+ operation,
47
+ provider
48
+ }
49
+ });
50
+ }
51
+ /**
52
+ * True on a development server: `vite dev` installs the run history. Code that ViteHub did not start, such as a test
53
+ * runner, has no history, so `NODE_ENV` decides there.
54
+ */
55
+ function isDevelopmentServer() {
56
+ if (getWorkflowDevRecorder()) return true;
57
+ const mode = globalThis.process?.env?.NODE_ENV;
58
+ return mode === "development" || mode === "test";
59
+ }
60
+ /**
61
+ * The Cloudflare Workflow binding of `name`. Only a development server runs the Workflow inline without it. Elsewhere,
62
+ * a missing binding fails, because an inline run is not durable.
63
+ */
64
+ function resolveCloudflareBinding(event, binding, name, definition) {
65
+ const env = getCloudflareEnv(event);
66
+ const bindingName = definition?.internalAgentInvocationRecovery ? getCloudflareWorkflowBindingName(name) : binding || getCloudflareWorkflowBindingName(name);
67
+ if (env && Object.hasOwn(env, bindingName)) return env[bindingName];
68
+ if (isDevelopmentServer()) return void 0;
69
+ throw workflowErrorDiagnostics.WORKFLOW_R0036({
70
+ binding: bindingName,
71
+ name
72
+ });
73
+ }
74
+ function resolveCloudflareInspectionBinding(event, binding, name) {
75
+ return resolveCloudflareBinding(event, binding, name, getWorkflowRuntimeRegistry()?.[name]);
76
+ }
77
+ /** The start can have reached Cloudflare, so the acknowledgement is unknown. */
78
+ function invalidCloudflareWorkflowStart(cause) {
79
+ return createWorkflowError({
80
+ ...cause === void 0 ? {} : { cause },
81
+ code: "WORKFLOW_PROVIDER_OPERATION_FAILED",
82
+ details: {
83
+ acknowledgement: "unknown",
84
+ operation: "create",
85
+ provider: "cloudflare",
86
+ reason: "Cloudflare Workflow provider returned an invalid workflow instance."
87
+ }
88
+ });
89
+ }
90
+ function normalizeCloudflareWorkflowStart(value, expectedId) {
91
+ if (typeof value !== "object" || value === null) throw invalidCloudflareWorkflowStart();
92
+ let id;
93
+ try {
94
+ id = Reflect.get(value, "id");
95
+ } catch (cause) {
96
+ throw invalidCloudflareWorkflowStart(cause);
97
+ }
98
+ if (typeof id !== "string" || !id || id !== expectedId) throw invalidCloudflareWorkflowStart();
99
+ return { id };
100
+ }
101
+ const cloudflareInstanceIdPattern = /^[a-zA-Z0-9_][a-zA-Z0-9_-]{0,99}$/;
102
+ /** The array-form `createBatch` accepts reserved ids, unlike the object form. */
103
+ function isCloudflareInstanceId(id) {
104
+ return cloudflareInstanceIdPattern.test(id);
105
+ }
106
+ const cloudflareStatusMap = {
107
+ cancelled: "cancelled",
108
+ complete: "completed",
109
+ completed: "completed",
110
+ errored: "failed",
111
+ failed: "failed",
112
+ paused: "running",
113
+ queued: "queued",
114
+ running: "running",
115
+ success: "completed",
116
+ terminated: "cancelled",
117
+ waiting: "running",
118
+ waitingforpause: "running"
119
+ };
120
+ function normalizeCloudflareStatus(status) {
121
+ const value = typeof status === "object" && status && Object.hasOwn(status, "status") ? status.status : status;
122
+ const normalized = String(value || "").toLowerCase();
123
+ return Object.hasOwn(cloudflareStatusMap, normalized) ? cloudflareStatusMap[normalized] : "unknown";
124
+ }
125
+ /** The run result from Cloudflare status: the stored value, or a `Response` when the handler returned one. */
126
+ function cloudflareRunResult(metadata) {
127
+ if (typeof metadata !== "object" || metadata === null || !Object.hasOwn(metadata, "output")) return void 0;
128
+ const output = metadata.output;
129
+ return isSerializedResponse(output) ? deserializeResponse(output) : output;
130
+ }
131
+ /** The `error` member of a Cloudflare `status()` record. */
132
+ function ownStatusError(metadata) {
133
+ if (typeof metadata !== "object" || metadata === null || !Object.hasOwn(metadata, "error")) return void 0;
134
+ return Reflect.get(metadata, "error");
135
+ }
136
+ /** Cloudflare `get(id)` rejects with `instance.not_found` when no instance has the id. */
137
+ function isCloudflareInstanceNotFound(error) {
138
+ if (typeof error !== "object" || error === null) return false;
139
+ try {
140
+ const message = Reflect.get(error, "message");
141
+ return typeof message === "string" && message.includes("instance.not_found");
142
+ } catch {
143
+ return false;
144
+ }
145
+ }
146
+ /**
147
+ * The Cloudflare Workflows service refused the call: its error carries a service code such as `(instance.already_exists)`,
148
+ * or local Miniflare rejected the instance id. A lost connection has neither.
149
+ */
150
+ function isCloudflareRejection(error) {
151
+ if (typeof error !== "object" || error === null) return false;
152
+ try {
153
+ const message = Reflect.get(error, "message");
154
+ return typeof message === "string" && /\((?:instance|workflow)\.[a-z_]+\)|^Workflow instance has invalid id/.test(message);
155
+ } catch {
156
+ return false;
157
+ }
158
+ }
159
+ function hasUnknownWorkflowAcknowledgement(error) {
160
+ if (!error || typeof error !== "object") return false;
161
+ const details = error.details;
162
+ return Boolean(details && typeof details === "object" && details.acknowledgement === "unknown");
163
+ }
164
+ /** Reads a Cloudflare Workflow instance and its run. A missing instance has no `instance` and reports `unknown`. */
165
+ async function readCloudflareRun(binding, id) {
166
+ const instance = await runWorkflowProviderOperation("cloudflare", "get", async () => {
167
+ try {
168
+ return await binding.get(id);
169
+ } catch (error) {
170
+ if (isCloudflareInstanceNotFound(error)) return void 0;
171
+ throw error;
172
+ }
173
+ });
174
+ if (!instance) return { run: {
175
+ id,
176
+ provider: "cloudflare",
177
+ status: "unknown"
178
+ } };
179
+ const metadata = await runWorkflowProviderOperation("cloudflare", "status", () => instance.status());
180
+ const status = normalizeCloudflareStatus(metadata);
181
+ return {
182
+ instance,
183
+ run: {
184
+ ...status === "failed" ? { error: toWorkflowRunError(ownStatusError(metadata)) } : {},
185
+ id,
186
+ metadata,
187
+ provider: "cloudflare",
188
+ result: status === "completed" ? cloudflareRunResult(metadata) : void 0,
189
+ status
190
+ }
191
+ };
192
+ }
193
+ const finishedRunStatuses = /* @__PURE__ */ new Set([
194
+ "cancelled",
195
+ "completed",
196
+ "failed"
197
+ ]);
198
+ /**
199
+ * Terminates a Cloudflare Workflow instance that has not finished and returns its run afterwards. A finished run keeps
200
+ * and reports its status, and a missing run reports `unknown`, as on OpenWorkflow.
201
+ */
202
+ async function cancelCloudflareRun(binding, id) {
203
+ const { instance, run } = await readCloudflareRun(binding, id);
204
+ if (!instance || run.status === "unknown" || finishedRunStatuses.has(run.status)) return run;
205
+ try {
206
+ await runWorkflowProviderOperation("cloudflare", "cancel", () => instance.terminate());
207
+ } catch (error) {
208
+ const latest = await readCloudflareRun(binding, id).catch(() => void 0);
209
+ if (latest && finishedRunStatuses.has(latest.run.status)) return latest.run;
210
+ throw error;
211
+ }
212
+ return (await readCloudflareRun(binding, id)).run;
213
+ }
214
+ function createCloudflareAdapter(config) {
215
+ const adapter = {
216
+ async cancel({ event, id, name }) {
217
+ const binding = resolveCloudflareInspectionBinding(event, config.binding, name);
218
+ return binding ? await cancelCloudflareRun(binding, id) : await inlineAdapter(config).cancel({
219
+ event,
220
+ id,
221
+ name
222
+ });
223
+ },
224
+ async get({ event, id, name }) {
225
+ const binding = resolveCloudflareInspectionBinding(event, config.binding, name);
226
+ if (binding) return (await readCloudflareRun(binding, id)).run;
227
+ return await inlineAdapter(config).get({
228
+ event,
229
+ id,
230
+ name
231
+ });
232
+ },
233
+ async run(context) {
234
+ const { definition, event, id, name, payload, startAt } = context;
235
+ if (!isCloudflareInstanceId(id)) throw workflowErrorDiagnostics.WORKFLOW_CLOUDFLARE_RUN_ID_INVALID({ id });
236
+ const binding = resolveCloudflareBinding(event, config.binding, name, definition);
237
+ if (binding) {
238
+ resolveDispatchObserver(event)?.();
239
+ let created = false;
240
+ const start = () => runWorkflowProviderOperation("cloudflare", "create", async () => {
241
+ const [instance] = await binding.createBatch([{
242
+ id,
243
+ params: toCloudflareStartParams(payload, startAt)
244
+ }]);
245
+ created = instance !== void 0;
246
+ return normalizeCloudflareWorkflowStart(instance || await binding.get(id), id);
247
+ }, { acknowledgement: (error, status) => status === void 0 ? isCloudflareRejection(error) ? "rejected" : "unknown" : status < 500 ? "rejected" : void 0 });
248
+ const instance = await start().catch(async (firstError) => {
249
+ try {
250
+ return await start();
251
+ } catch (retryError) {
252
+ if (hasUnknownWorkflowAcknowledgement(firstError)) throw firstError;
253
+ throw retryError;
254
+ }
255
+ });
256
+ if (!created) return await adapter.get({
257
+ event,
258
+ id,
259
+ name
260
+ });
261
+ return {
262
+ id: instance.id,
263
+ payload,
264
+ provider: "cloudflare",
265
+ status: "queued"
266
+ };
267
+ }
268
+ return await inlineAdapter(config).run(context);
269
+ },
270
+ resume: () => unsupportedOperation("cloudflare", "signals")
271
+ };
272
+ return adapter;
273
+ }
274
+ const warnedInlineOpenWorkflowNames = /* @__PURE__ */ new Set();
275
+ /**
276
+ * Every OpenWorkflow worker registers the Workflow Definitions of the build registry when it starts: discovered
277
+ * Workflows and discovered Agent Workflows. Any worker can claim a run, so a run of an inline
278
+ * `createWorkflow(name, handler)` could wait in storage on a worker that never registers it. Those runs execute inline
279
+ * in this process. A turn of an Agent that is not discovered fails with `WORKFLOW_AGENT_NOT_DISCOVERED`, so Agent turns are
280
+ * never inline.
281
+ */
282
+ function isDurableOpenWorkflowDefinition(name) {
283
+ const registry = getWorkflowRuntimeRegistry();
284
+ return Boolean(registry && Object.hasOwn(registry, name));
285
+ }
286
+ function createOpenWorkflowAdapter(config) {
287
+ const inline = inlineAdapter(config);
288
+ return {
289
+ cancel: async ({ event, id, name }) => isDurableOpenWorkflowDefinition(name) ? await cancelOpenWorkflowRun(config, name, id) : await inline.cancel({
290
+ event,
291
+ id,
292
+ name
293
+ }),
294
+ get: async ({ event, id, name }) => isDurableOpenWorkflowDefinition(name) ? await getOpenWorkflowRun(config, name, id) : await inline.get({
295
+ event,
296
+ id,
297
+ name
298
+ }),
299
+ resume: () => unsupportedOperation("openworkflow", "signals"),
300
+ run: async (context) => {
301
+ const { definition, event, name, options, payload, startAt } = context;
302
+ if (isDurableOpenWorkflowDefinition(name)) return await runOpenWorkflow(config, name, payload, definition, options, resolveDispatchObserver(event), startAt);
303
+ if (definition?.internalAgentWorkflow || definition?.internalAgentInvocationRecovery) throw workflowErrorDiagnostics.WORKFLOW_AGENT_NOT_DISCOVERED({ name });
304
+ if (!warnedInlineOpenWorkflowNames.has(name)) {
305
+ warnedInlineOpenWorkflowNames.add(name);
306
+ console.warn(`[vitehub:workflow] The Workflow ${JSON.stringify(name)} is not a discovered file, so OpenWorkflow workers cannot run it. Its runs execute inline in this process and are not durable. Move it to server/workflows/ to make it durable.`);
307
+ }
308
+ return {
309
+ ...await inline.run(context),
310
+ metadata: {
311
+ mode: "inline",
312
+ workflow: name
313
+ }
314
+ };
315
+ }
316
+ };
317
+ }
318
+ /** `setTimeout` fires at once for a delay above 2^31 - 1 ms (about 24.8 days), so a long wait uses several timers. */
319
+ const maximumTimerDelay = 2147483647;
320
+ async function waitUntilTime(startAt) {
321
+ while (startAt !== void 0 && startAt > Date.now()) await new Promise((resolve) => setTimeout(resolve, Math.min(startAt - Date.now(), maximumTimerDelay)));
322
+ }
323
+ function inlineAdapter(config) {
324
+ return {
325
+ cancel: () => unsupportedOperation(config.driver, "cancellation"),
326
+ async get({ id, name }) {
327
+ const run = getWorkflowRunState(name, id);
328
+ if (run) {
329
+ if (run.status === "running") return {
330
+ id,
331
+ provider: config.driver,
332
+ status: run.startAt === void 0 ? "running" : "queued"
333
+ };
334
+ return {
335
+ ...run.status === "failed" ? { error: toWorkflowRunError(run.error) } : {},
336
+ id,
337
+ provider: config.driver,
338
+ result: isSerializedResponse(run.result) ? deserializeResponse(run.result) : run.result,
339
+ status: run.status
340
+ };
341
+ }
342
+ return {
343
+ id,
344
+ provider: config.driver,
345
+ status: "unknown"
346
+ };
347
+ },
348
+ async run({ definition, event, id, name, payload, startAt }) {
349
+ const existing = getWorkflowRunState(name, id);
350
+ if (existing) return {
351
+ ...existing.status === "failed" ? { error: toWorkflowRunError(existing.error) } : {},
352
+ id,
353
+ metadata: config.driver === "vercel" ? {
354
+ mode: "inline",
355
+ workflow: getVercelWorkflowName(name)
356
+ } : void 0,
357
+ payload: existing.payload,
358
+ provider: config.driver,
359
+ result: isSerializedResponse(existing.result) ? deserializeResponse(existing.result) : existing.result,
360
+ status: existing.status === "running" ? "queued" : existing.status
361
+ };
362
+ resolveDispatchObserver(event)?.();
363
+ const recordRun = getWorkflowDevRecorder()?.start(name, id, config.driver);
364
+ const execute = () => runSerializedWorkflowHandler({
365
+ id,
366
+ name,
367
+ payload,
368
+ provider: config.driver
369
+ }, definition);
370
+ const run = waitUntilTime(startAt).then(() => {
371
+ runState.startAt = void 0;
372
+ return recordRun ? recordRun(execute) : execute();
373
+ }).then((result) => ({
374
+ result,
375
+ status: "completed"
376
+ })).catch((error) => ({
377
+ error,
378
+ status: "failed"
379
+ }));
380
+ const runState = setWorkflowRun(name, id, run, payload, true);
381
+ runState.startAt = startAt;
382
+ const waitUntil = resolveWaitUntil(event);
383
+ if (waitUntil) waitUntil(runState.promise);
384
+ return {
385
+ id,
386
+ metadata: config.driver === "vercel" ? {
387
+ mode: "inline",
388
+ workflow: getVercelWorkflowName(name)
389
+ } : void 0,
390
+ payload,
391
+ provider: config.driver,
392
+ status: "queued"
393
+ };
394
+ },
395
+ resume: () => unsupportedOperation(config.driver, "signals")
396
+ };
397
+ }
398
+ /**
399
+ * True when Workflow DevKit runs the `native` entry. `vite dev` does not run the Workflow DevKit transform, so the
400
+ * dev server runs the normal handler inline, as for every other Workflow there.
401
+ */
402
+ function runsNatively(definition) {
403
+ return Boolean(definition?.options?.native) && !getWorkflowDevRecorder();
404
+ }
405
+ /** Whether a registered Workflow has a native Vercel entry, so a run of it can wait for a signal. */
406
+ async function hasNativeWorkflowDefinition() {
407
+ const names = /* @__PURE__ */ new Set([...Object.keys(getWorkflowRuntimeRegistry() ?? {}), ...getInlineWorkflowDefinitions().keys()]);
408
+ for (const name of names) if ((await loadWorkflowDefinition(name))?.options?.native) return true;
409
+ return false;
410
+ }
411
+ function createVercelAdapter(config) {
412
+ const fallback = inlineAdapter(config);
413
+ return {
414
+ async cancel({ id, name }) {
415
+ const definition = await loadWorkflowDefinition(name);
416
+ if (!runsNatively(definition)) return await fallback.cancel({
417
+ event: void 0,
418
+ id,
419
+ name
420
+ });
421
+ return await cancelVercelWorkflow(name, definition, id);
422
+ },
423
+ async get({ id, name }) {
424
+ const definition = await loadWorkflowDefinition(name);
425
+ return runsNatively(definition) ? await inspectVercelWorkflowRun(name, definition, id) : await fallback.get({
426
+ event: void 0,
427
+ id,
428
+ name
429
+ });
430
+ },
431
+ async resume(token, payload) {
432
+ if (getWorkflowDevRecorder()) unsupportedOperation(config.driver, "signals");
433
+ try {
434
+ return await resumeVercelWorkflowSignal(token, payload);
435
+ } catch (error) {
436
+ if (getViteHubErrorShape(error)?.code === "VERCEL_WORKFLOW_SDK_LOAD_FAILED" && !await hasNativeWorkflowDefinition()) unsupportedOperation(config.driver, "signals");
437
+ throw error;
438
+ }
439
+ },
440
+ async run(context) {
441
+ const { definition, event, name, payload, startAt } = context;
442
+ if (!runsNatively(definition)) return await fallback.run(context);
443
+ return await startVercelWorkflow(name, definition, payload, resolveSettlementObserver(event), resolveDispatchObserver(event), startAt);
444
+ }
445
+ };
446
+ }
447
+ function getWorkflowRuntimeAdapter(config) {
448
+ if (config.driver === "cloudflare") return createCloudflareAdapter(config);
449
+ if (config.driver === "openworkflow") return createOpenWorkflowAdapter(config);
450
+ return createVercelAdapter(config);
451
+ }
452
+ //#endregion
453
+ //#region src/runtime/test-client.ts
454
+ /** The started runs of the current test. `vite-hub/test` reads the same list. */
455
+ function workflowTestRuns(test) {
456
+ return test.backend("workflow", () => []);
457
+ }
458
+ function toWorkflowRun(run, provider) {
459
+ return {
460
+ id: run.id,
461
+ payload: run.payload,
462
+ provider,
463
+ status: run.status
464
+ };
465
+ }
466
+ /** Records the run and does not start its handler, so a test asserts what the app started. */
467
+ function recordWorkflowTestRun(test, provider, input) {
468
+ const runs = workflowTestRuns(test);
469
+ const existing = runs.find((run) => run.workflow === input.name && run.id === input.id);
470
+ if (existing) return toWorkflowRun(existing, provider);
471
+ const run = {
472
+ deferred: input.deferred,
473
+ id: input.id,
474
+ payload: structuredClone(input.payload),
475
+ status: "queued",
476
+ workflow: input.name
477
+ };
478
+ runs.push(run);
479
+ return toWorkflowRun(run, provider);
480
+ }
481
+ /** Returns a recorded run, or a run with status `unknown` when the test started no run with this id. */
482
+ function getWorkflowTestRun(test, provider, name, id, cancel = false) {
483
+ const run = workflowTestRuns(test).find((item) => item.workflow === name && item.id === id);
484
+ if (!run) return {
485
+ id,
486
+ provider,
487
+ status: "unknown"
488
+ };
489
+ if (cancel) run.status = "cancelled";
490
+ return toWorkflowRun(run, provider);
491
+ }
492
+ //#endregion
493
+ //#region src/runtime/client.ts
494
+ function getActiveWorkflowConfig() {
495
+ const config = getWorkflowRuntimeConfig();
496
+ if (config === false) throw createWorkflowError({ code: "WORKFLOW_DISABLED" });
497
+ return config || normalizeWorkflowOptions(void 0, { hosting: "vercel" });
498
+ }
499
+ async function loadRequiredWorkflowDefinition(name) {
500
+ const definition = await loadWorkflowDefinition(name);
501
+ if (!definition) throw createWorkflowError({
502
+ code: "WORKFLOW_DEFINITION_NOT_FOUND",
503
+ details: safeWorkflowName(name) ? { name } : void 0
504
+ });
505
+ return definition;
506
+ }
507
+ function normalizeWorkflowRunIdValue(value) {
508
+ if (value === void 0) return null;
509
+ if (value === null || typeof value !== "object") return value;
510
+ if (Array.isArray(value)) return value.map((item) => normalizeWorkflowRunIdValue(item));
511
+ const record = value;
512
+ return Object.fromEntries(Object.keys(record).filter((key) => record[key] !== void 0).sort().map((key) => [key, normalizeWorkflowRunIdValue(record[key])]));
513
+ }
514
+ async function sha256Hex(value) {
515
+ const data = new TextEncoder().encode(value);
516
+ const digest = await crypto.subtle.digest("SHA-256", data);
517
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
518
+ }
519
+ async function createStableWorkflowRunId(name, value) {
520
+ const hash = await sha256Hex(`${name}:${JSON.stringify(normalizeWorkflowRunIdValue(value))}`);
521
+ return `${name.replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 67) || "workflow"}-${hash.slice(0, 32)}`;
522
+ }
523
+ async function resolveWorkflowStartOptions(name, payload, createOptions, startOptions) {
524
+ if (startOptions.id || !createOptions?.id) return startOptions;
525
+ return {
526
+ ...startOptions,
527
+ id: await createStableWorkflowRunId(name, await createOptions.id({
528
+ name,
529
+ payload
530
+ }))
531
+ };
532
+ }
533
+ function createWorkflow(nameOrOptions, handlerOrOptions, options) {
534
+ let name;
535
+ let handler;
536
+ let createOptions;
537
+ if (typeof nameOrOptions === "object" && nameOrOptions !== null) {
538
+ createOptions = nameOrOptions;
539
+ if (!createOptions.name || typeof createOptions.name !== "string") throw workflowErrorDiagnostics.WORKFLOW_R0009({ message: "`createWorkflow()` requires a workflow name." });
540
+ if (typeof createOptions.handler !== "function") throw workflowErrorDiagnostics.WORKFLOW_R0010({ message: "`createWorkflow()` requires a workflow handler." });
541
+ name = createOptions.name;
542
+ handler = createOptions.handler;
543
+ } else {
544
+ name = nameOrOptions;
545
+ if (!name || typeof name !== "string") throw workflowErrorDiagnostics.WORKFLOW_R0011({ message: "`createWorkflow()` requires a workflow name." });
546
+ handler = typeof handlerOrOptions === "function" ? handlerOrOptions : typeof handlerOrOptions === "object" && handlerOrOptions !== null ? handlerOrOptions.handler : void 0;
547
+ createOptions = typeof handlerOrOptions === "function" ? options : handlerOrOptions;
548
+ if (handler !== void 0 && typeof handler !== "function") throw workflowErrorDiagnostics.WORKFLOW_R0012({ message: "`createWorkflow()` requires a workflow handler." });
549
+ if (handler === void 0 && handlerOrOptions !== void 0 && (typeof handlerOrOptions !== "object" || handlerOrOptions === null)) throw workflowErrorDiagnostics.WORKFLOW_R0013({ message: "`createWorkflow()` options must be an object." });
550
+ }
551
+ if (handler !== void 0) registerInlineWorkflowDefinition(name, {
552
+ handler,
553
+ ...createOptions?.internalAgentWorkflow ? { internalAgentWorkflow: true } : {},
554
+ ...createOptions?.rootStep === void 0 ? {} : { options: { rootStep: createOptions.rootStep } }
555
+ });
556
+ return {
557
+ cancel: (id) => cancelWorkflow(name, id),
558
+ name,
559
+ defer: (payload, options = {}) => deferWorkflowStart(name, async () => await startWorkflowRun(name, payload, await resolveWorkflowStartOptions(name, payload, createOptions, options), true)),
560
+ getRun: (id) => getWorkflowRun(name, id),
561
+ async start(payload, options = {}) {
562
+ return await startWorkflow(name, payload, await resolveWorkflowStartOptions(name, payload, createOptions, options));
563
+ }
564
+ };
565
+ }
566
+ /** Starts one durable run of a Workflow Definition and returns its id and status. */
567
+ async function startWorkflow(name, payload, options = {}) {
568
+ return await startWorkflowRun(name, payload, options);
569
+ }
570
+ async function startWorkflowRun(name, payload, options, deferred = false) {
571
+ const config = getActiveWorkflowConfig();
572
+ const id = options.id || randomId("wrun");
573
+ const startAt = resolveWorkflowStartAt(options.delay);
574
+ const definition = await loadRequiredWorkflowDefinition(name);
575
+ if (config.driver === "vercel" && definition.options?.native && options.id) throw createWorkflowError({
576
+ code: "WORKFLOW_RUN_ID_UNSUPPORTED",
577
+ details: {
578
+ ...safeWorkflowName(name) ? { name } : {},
579
+ provider: "vercel"
580
+ }
581
+ });
582
+ const test = getViteHubTestMode();
583
+ if (test) return recordWorkflowTestRun(test, config.driver, {
584
+ deferred,
585
+ id,
586
+ name,
587
+ payload
588
+ });
589
+ return await getWorkflowRuntimeAdapter(config).run({
590
+ definition,
591
+ event: getWorkflowRuntimeEvent(),
592
+ id,
593
+ name,
594
+ options,
595
+ payload,
596
+ startAt
597
+ });
598
+ }
599
+ async function getWorkflowRun(name, id) {
600
+ const config = getActiveWorkflowConfig();
601
+ const test = getViteHubTestMode();
602
+ if (test) return getWorkflowTestRun(test, config.driver, name, id);
603
+ return await getWorkflowRuntimeAdapter(config).get({
604
+ event: getWorkflowRuntimeEvent(),
605
+ id,
606
+ name
607
+ });
608
+ }
609
+ async function cancelWorkflow(name, id) {
610
+ const config = getActiveWorkflowConfig();
611
+ const definition = await loadRequiredWorkflowDefinition(name);
612
+ const test = getViteHubTestMode();
613
+ if (test) {
614
+ if (config.driver === "vercel" && !definition.options?.native) throw createWorkflowError({
615
+ code: "WORKFLOW_OPERATION_UNSUPPORTED",
616
+ details: {
617
+ operation: "cancellation",
618
+ provider: config.driver
619
+ }
620
+ });
621
+ return getWorkflowTestRun(test, config.driver, name, id, true);
622
+ }
623
+ return await getWorkflowRuntimeAdapter(config).cancel({
624
+ event: getWorkflowRuntimeEvent(),
625
+ id,
626
+ name
627
+ });
628
+ }
629
+ /** Resumes a run that waits for a signal. `token` is the opaque token that the provider gave the waiting step. */
630
+ async function resumeWorkflow(token, payload) {
631
+ if (!token || typeof token !== "string") throw workflowErrorDiagnostics.WORKFLOW_R0014({ message: "`resumeWorkflow()` requires an opaque signal token." });
632
+ const config = getActiveWorkflowConfig();
633
+ if (getViteHubTestMode()) throw createWorkflowError({
634
+ code: "WORKFLOW_OPERATION_UNSUPPORTED",
635
+ details: {
636
+ operation: "signals",
637
+ provider: config.driver
638
+ }
639
+ });
640
+ return await getWorkflowRuntimeAdapter(config).resume(token, payload);
641
+ }
642
+ function deferWorkflowStart(name, start) {
643
+ const request = getWorkflowRuntimeEvent();
644
+ const promise = runWithWorkflowRuntimeEvent(request, start).then(() => void 0, (error) => {
645
+ console.error(`[vitehub] Deferred Workflow start failed for "${name}"`, error);
646
+ });
647
+ const waitUntil = resolveWaitUntil(request);
648
+ if (typeof waitUntil === "function") waitUntil(promise);
649
+ }
650
+ /**
651
+ * Starts a run after the response, through `waitUntil`. It returns nothing: a failure goes to the log.
652
+ * Call `startWorkflow()` when the caller needs the run ID or the start error.
653
+ */
654
+ function deferWorkflow(name, payload, options = {}) {
655
+ deferWorkflowStart(name, () => startWorkflowRun(name, payload, options, true));
656
+ }
657
+ //#endregion
658
+ export { resumeWorkflow as a, getWorkflowRun as i, createWorkflow as n, startWorkflow as o, deferWorkflow as r, cancelWorkflow as t };