@vite-hub/workflow 0.4.1 → 0.5.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 (60) hide show
  1. package/README.md +28 -10
  2. package/dist/{app-He0GTrYZ.js → app-DXUHElAz.js} +2 -3
  3. package/dist/{app-BojnC_yf.d.ts → app-wkVFd7m-.d.ts} +0 -2
  4. package/dist/{client-DkwOxEiT.js → client-CbBg4HlH.js} +88 -67
  5. package/dist/{cloudflare-BHfClPvT.js → cloudflare-Sgywkm1N.js} +3 -5
  6. package/dist/{cloudflare-env-CGLx7lUd.js → cloudflare-env-DHhzRZOs.js} +2 -4
  7. package/dist/cloudflare-env-lookup-BqomAHN5.d.ts +2 -0
  8. package/dist/{cloudflare-shared-CTqh_a2s.d.ts → cloudflare-shared-B9cY3-jD.d.ts} +1 -3
  9. package/dist/{config-C3DvtjfJ.js → config-CizNRTMi.js} +4 -7
  10. package/dist/definition.d.ts +2 -4
  11. package/dist/definition.js +3 -4
  12. package/dist/{delay-D1-nq_VE.js → delay-CtT3442d.js} +2 -4
  13. package/dist/{dev-recorder-CTN5Fkao.js → dev-recorder-Dltdmlkv.js} +1 -2
  14. package/dist/durability.d.ts +2 -4
  15. package/dist/durability.js +2 -3
  16. package/dist/{error-diagnostics-0V2T3JFw.js → error-diagnostics--2cV_ER1.js} +24 -7
  17. package/dist/{error-diagnostics-CQ4BUqRe.js → error-diagnostics-kKXseq8d.js} +10 -3
  18. package/dist/{errors-uhP8DZTi.d.ts → errors-CJZuvOcx.d.ts} +0 -7
  19. package/dist/{errors-DCqRnZpN.js → errors-CZf7oz4k.js} +1 -6
  20. package/dist/index.d.ts +7 -11
  21. package/dist/index.js +5 -6
  22. package/dist/{inspect-B72iFyj-.js → inspect-NBCAwsxi.js} +1 -2
  23. package/dist/{object-Da1zyPCR.js → object-CAK6UYR5.js} +1 -2
  24. package/dist/{openworkflow-BhzxV_Y3.d.ts → openworkflow-CdKbUGGa.d.ts} +7 -10
  25. package/dist/{openworkflow-defaults-DDig2M4s.js → openworkflow-defaults-DfQWtSRU.js} +2 -4
  26. package/dist/{openworkflow-storage-Dj9zUAsk.js → openworkflow-storage-Dde_f0es.js} +1 -2
  27. package/dist/openworkflow.js +1 -2
  28. package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CqZkx1Rm.d.ts} +8 -6
  29. package/dist/{operations-D_WJwjrS.js → operations-BBTmDm2H.js} +31 -44
  30. package/dist/operations.d.ts +5 -12
  31. package/dist/operations.js +33 -43
  32. package/dist/{out-DxLKolA0.js → out-r9T3bhTE.js} +2933 -2301
  33. package/dist/{rolldown-runtime-B4iAMlE-.js → rolldown-runtime-DYf_mQCB.js} +2 -3
  34. package/dist/{run-error-DBWqiJHH.js → run-error-8p4BtTMv.js} +5 -8
  35. package/dist/{run-failed-gVGo1BaF.js → run-failed-BcSjSU2t.js} +1 -2
  36. package/dist/runtime/cloudflare-runner.d.ts +14 -6
  37. package/dist/runtime/cloudflare-runner.js +16 -10
  38. package/dist/runtime/cloudflare-shared.d.ts +2 -2
  39. package/dist/runtime/cloudflare-shared.js +1 -2
  40. package/dist/runtime/cloudflare-vite.d.ts +5 -7
  41. package/dist/runtime/cloudflare-vite.js +5 -7
  42. package/dist/runtime/dev-runs.d.ts +1 -3
  43. package/dist/runtime/dev-runs.js +3 -3
  44. package/dist/runtime/execute.d.ts +3 -5
  45. package/dist/runtime/execute.js +66 -35
  46. package/dist/runtime/openworkflow-worker.d.ts +3 -4
  47. package/dist/runtime/openworkflow-worker.js +4 -10
  48. package/dist/runtime/openworkflow.d.ts +2 -2
  49. package/dist/runtime/openworkflow.js +37 -53
  50. package/dist/runtime/state.d.ts +2 -4
  51. package/dist/runtime/state.js +5 -4
  52. package/dist/runtime/vercel-vite.d.ts +3 -6
  53. package/dist/runtime/vercel-vite.js +4 -6
  54. package/dist/signals-BHQdxoJo.js +79 -0
  55. package/dist/{types-Dsmwsdlv.d.ts → types-DvYcvbPG.d.ts} +34 -6
  56. package/dist/{vercel-DTvm61iY.js → vercel-Cw_Z9-j4.js} +5 -14
  57. package/dist/vite.d.ts +12 -29
  58. package/dist/vite.js +4492 -2125
  59. package/package.json +13 -13
  60. package/dist/cloudflare-env-lookup-CfX6wZKb.d.ts +0 -4
@@ -1,12 +1,12 @@
1
- import { t as workflowErrorDiagnostics } from "../error-diagnostics-0V2T3JFw.js";
2
- import { t as resolveOpenWorkflowStorage } from "../openworkflow-storage-Dj9zUAsk.js";
3
- import { n as createWorkflowError } from "../errors-DCqRnZpN.js";
1
+ import { r as invariantError, t as defaultOpenWorkflowSqlitePath } from "../openworkflow-defaults-DfQWtSRU.js";
4
2
  import { readNonRetryableStepResult, resolveWorkflowStepOptions, runSerializedWorkflowHandler, toDurationMilliseconds, toNonRetryableStepResult, withWorkflowStepTimeout } from "./execute.js";
5
- import { r as invariantError, t as defaultOpenWorkflowSqlitePath } from "../openworkflow-defaults-DDig2M4s.js";
6
- import { i as runWorkflowProviderOperation, n as getWorkflowProviderStatus, t as toWorkflowRunError } from "../run-error-DBWqiJHH.js";
7
- import { t as emitWorkflowFailed } from "../run-failed-gVGo1BaF.js";
8
- import { deserializeResponse, isSerializedResponse } from "@vite-hub/runtime";
9
- //#region src/runtime/openworkflow.ts
3
+ import { n as createWorkflowError } from "../errors-CZf7oz4k.js";
4
+ import { i as runWorkflowProviderOperation, n as getWorkflowProviderStatus, t as toWorkflowRunError } from "../run-error-8p4BtTMv.js";
5
+ import { t as emitWorkflowFailed } from "../run-failed-BcSjSU2t.js";
6
+ import { t as resolveOpenWorkflowStorage } from "../openworkflow-storage-Dde_f0es.js";
7
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics--2cV_ER1.js";
8
+ import { deserializeResponse, isSerializedResponse } from "@vite-hub/runtime/internal/response";
9
+ // src/runtime/openworkflow.ts
10
10
  const defaultImporter = (specifier) => import(
11
11
  /* @vite-ignore */
12
12
  specifier
@@ -51,7 +51,6 @@ let databaseUrlResolver;
51
51
  function setOpenWorkflowDatabaseUrl(resolve) {
52
52
  databaseUrlResolver = resolve;
53
53
  }
54
- /** The Postgres URL of the Default Database, when the app has a Postgres Default Database. */
55
54
  function readDatabasePostgresUrl() {
56
55
  if (!databaseUrlResolver) return void 0;
57
56
  const url = databaseUrlResolver()?.trim();
@@ -98,14 +97,11 @@ function getOpenWorkflowConfig(config) {
98
97
  source: "default"
99
98
  };
100
99
  }
101
- /** How long a server waits for the setup lock that another server holds, before the worker start tries again. */
102
100
  const postgresSetupWaitMs = 12e4;
103
- /** How long the server that holds the setup lock waits for the second connection that the OpenWorkflow migration needs. */
104
101
  const postgresSecondConnectionTimeoutMs = 1e4;
105
102
  function sleep(ms) {
106
103
  return new Promise((resolve) => setTimeout(resolve, ms).unref?.());
107
104
  }
108
- /** Resolves `true` when `task` settles first, `false` when `ms` passes first. */
109
105
  function settlesWithin(task, ms) {
110
106
  let timer;
111
107
  return Promise.race([task.then(() => true), new Promise((resolve) => {
@@ -113,23 +109,6 @@ function settlesWithin(task, ms) {
113
109
  timer.unref?.();
114
110
  })]).finally(() => clearTimeout(timer));
115
111
  }
116
- /**
117
- * OpenWorkflow creates its Postgres schema without a lock. When servers start together, all but one fail with
118
- * `duplicate key value violates unique constraint`, and OpenWorkflow leaves the failed migration connection open in an
119
- * aborted transaction. So one server at a time sets up the schema, and the others then find it up to date.
120
- *
121
- * OpenWorkflow does not export its migrations, so they cannot run on the connection that holds the lock: they run on a
122
- * connection that `BackendPostgres.connect()` opens.
123
- * - A server tries the lock with `pg_try_advisory_xact_lock` in a short transaction. A server that does not get it
124
- * commits at once and tries again later, so a waiting server holds no connection.
125
- * - The server that gets it first checks that it can open a second connection. A pool of one connection, such as a
126
- * pooler with one server connection, cannot run the migration while the lock holds that connection, so the server
127
- * stops with `WORKFLOW_OPENWORKFLOW_SETUP_CONNECTION_UNAVAILABLE` before the setup starts.
128
- * - Then it holds the lock until OpenWorkflow finished the setup.
129
- * A transaction lock also works through a pooler in transaction mode, such as PgBouncer.
130
- * OpenWorkflow 0.11.0 locks its setup with a session lock
131
- * (https://github.com/openworkflowdev/openworkflow/commit/eb544db), which such a pooler does not keep, so this lock stays.
132
- */
133
112
  async function withPostgresSetupLock(postgres, url, schema, setup) {
134
113
  const sql = postgres.default(url, {
135
114
  idle_timeout: 1,
@@ -164,10 +143,6 @@ async function withPostgresSetupLock(postgres, url, schema, setup) {
164
143
  await sql.end({ timeout: 5 });
165
144
  }
166
145
  }
167
- /**
168
- * The backend that the OpenWorkflow client and its workers use. OpenWorkflow retries a failed run by its retry policy, so
169
- * only `failWorkflowRun()` knows when a run ends as `failed`. This wrapper sends `workflow.failed` then.
170
- */
171
146
  function reportFailedRuns(backend, definitions) {
172
147
  const failWorkflowRun = async (params) => {
173
148
  const run = await backend.failWorkflowRun(params);
@@ -222,10 +197,6 @@ function readRowId(row) {
222
197
  const id = Reflect.get(row, "id");
223
198
  return typeof id === "string" ? id : void 0;
224
199
  }
225
- /**
226
- * ViteHub starts a run with the caller's id as the OpenWorkflow idempotency key, and OpenWorkflow gives the run its own
227
- * UUID. The OpenWorkflow API reads runs by UUID only, so this lookup reads the key from the backend connection.
228
- */
229
200
  function createRunIdLookup(backend, options) {
230
201
  const connection = Reflect.get(backend, options.backend === "sqlite" ? "db" : "pg");
231
202
  return async (name, key) => {
@@ -234,7 +205,7 @@ function createRunIdLookup(backend, options) {
234
205
  const [row] = await connection`SELECT "id" FROM ${connection(options.schema)}.${connection("workflow_runs")} WHERE "namespace_id" = ${options.namespaceId} AND "workflow_name" = ${name} AND "idempotency_key" = ${key} ORDER BY "created_at" ASC, "id" ASC LIMIT 1`;
235
206
  return readRowId(row);
236
207
  }
237
- throw invariantError(`OpenWorkflow 0.9 backends keep their connection in \`db\` (SQLite) or \`pg\` (Postgres), but the ${options.backend} backend has neither`);
208
+ throw invariantError(`OpenWorkflow backends keep their connection in \`db\` (SQLite) or \`pg\` (Postgres), but the ${options.backend} backend has neither`);
238
209
  };
239
210
  }
240
211
  /** The storage that OpenWorkflow uses for `config` now, without credentials. */
@@ -269,10 +240,6 @@ async function getOpenWorkflowRuntime(config) {
269
240
  });
270
241
  return resolved;
271
242
  }
272
- /**
273
- * OpenWorkflow counts attempts, and `limit` counts the retries after the first attempt. OpenWorkflow caps each wait at
274
- * `maximumInterval`, 100 seconds by default, so the cap is the longest wait that the policy asks for.
275
- */
276
243
  function toOpenWorkflowRetryPolicy(name, options) {
277
244
  const { backoff, delay, limit } = resolveWorkflowStepOptions(name, options).retries;
278
245
  const initial = toDurationMilliseconds(delay);
@@ -284,7 +251,7 @@ function toOpenWorkflowRetryPolicy(name, options) {
284
251
  maximumInterval: `${initial * coefficient ** Math.max(limit - 1, 0)}ms`
285
252
  };
286
253
  }
287
- function createOpenWorkflowProviderStep(step) {
254
+ function createOpenWorkflowProviderStep(step, workflow) {
288
255
  return {
289
256
  async do(name, options, run) {
290
257
  const output = await step.run({
@@ -303,9 +270,33 @@ function createOpenWorkflowProviderStep(step) {
303
270
  if (error) throw error;
304
271
  return output;
305
272
  },
306
- sleep: async (name, milliseconds) => await step.sleep(name, `${milliseconds}ms`)
273
+ sleep: async (name, milliseconds) => await step.sleep(name, `${milliseconds}ms`),
274
+ async waitForSignal(name, token) {
275
+ const received = await step.waitForSignal({
276
+ name,
277
+ signal: token
278
+ });
279
+ if (received === null) throw workflowErrorDiagnostics.WORKFLOW_SIGNAL_TIMEOUT({ name: workflow });
280
+ return received.data;
281
+ }
307
282
  };
308
283
  }
284
+ /**
285
+ * Sends `value` to a live run that waits for the signal `token`. OpenWorkflow drops early signals and can match
286
+ * a wait left behind by cancellation, so check the run before sending.
287
+ */
288
+ async function resumeOpenWorkflowSignal(config, workflow, id, token, value) {
289
+ const runtime = await getOpenWorkflowRuntime(config);
290
+ return await runWorkflowProviderOperation("openworkflow", "resume-signal", async () => {
291
+ const run = await runtime.backend.getWorkflowRun({ workflowRunId: await runtime.findRunId(workflow, id) ?? id });
292
+ if (!run || run.workflowName !== workflow || terminalOpenWorkflowStatuses.has(normalizeOpenWorkflowStatus(run.status))) return false;
293
+ const { workflowRunIds } = await runtime.client.sendSignal({
294
+ data: value,
295
+ signal: token
296
+ });
297
+ return workflowRunIds.includes(run.id);
298
+ });
299
+ }
309
300
  async function registerOpenWorkflowDefinition(runtime, name, definition) {
310
301
  const existing = runtime.workflows.get(name);
311
302
  if (existing) return existing;
@@ -318,7 +309,7 @@ async function registerOpenWorkflowDefinition(runtime, name, definition) {
318
309
  name,
319
310
  payload: input,
320
311
  provider: "openworkflow",
321
- step: createOpenWorkflowProviderStep(step)
312
+ step: createOpenWorkflowProviderStep(step, name)
322
313
  }, openWorkflowDefinition);
323
314
  });
324
315
  runtime.workflows.set(name, workflow);
@@ -361,12 +352,10 @@ function serializeOpenWorkflowRun(run, name) {
361
352
  status
362
353
  };
363
354
  }
364
- /** OpenWorkflow stores `name`, `message`, and `stack`. The stack has server paths, so the step keeps the message only. */
365
355
  function toWorkflowRunStepError(error) {
366
356
  const message = typeof error === "object" && error !== null ? Reflect.get(error, "message") : void 0;
367
357
  return { message: typeof message === "string" && message ? message : "Workflow step failed." };
368
358
  }
369
- /** OpenWorkflow stores one row per step attempt. A run reports each step once, with its latest attempt. */
370
359
  function toWorkflowRunSteps(attempts) {
371
360
  const steps = /* @__PURE__ */ new Map();
372
361
  for (const attempt of attempts) {
@@ -449,10 +438,6 @@ const terminalOpenWorkflowStatuses = /* @__PURE__ */ new Set([
449
438
  "completed",
450
439
  "failed"
451
440
  ]);
452
- /**
453
- * Cancels a pending or running OpenWorkflow run of this Workflow and returns its state afterwards. A run of another
454
- * Workflow, or an unknown run, reports `unknown` without being cancelled. A finished run keeps and reports its status.
455
- */
456
441
  async function cancelOpenWorkflowRun(config, name, id) {
457
442
  const current = await getOpenWorkflowRun(config, name, id);
458
443
  if (current.status === "unknown" || terminalOpenWorkflowStatuses.has(current.status)) return current;
@@ -493,5 +478,4 @@ async function closeOpenWorkflowRuntimes(closing) {
493
478
  function setOpenWorkflowImporter(importer) {
494
479
  openWorkflowImporter = importer;
495
480
  }
496
- //#endregion
497
- export { cancelOpenWorkflowRun, describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRun, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, runOpenWorkflow, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter };
481
+ export { cancelOpenWorkflowRun, describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRun, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, resumeOpenWorkflowSignal, runOpenWorkflow, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter };
@@ -1,5 +1,4 @@
1
- import { f as WorkflowDefinition, l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-Dsmwsdlv.js";
2
- //#region src/runtime/state.d.ts
1
+ import { f as WorkflowDefinition, l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-DvYcvbPG.js";
3
2
  export interface WorkflowRunState<TResult = unknown> {
4
3
  error?: unknown;
5
4
  expiresAt?: number;
@@ -32,5 +31,4 @@ export declare function setWorkflowRun<TResult = unknown>(name: string, id: stri
32
31
  error?: unknown;
33
32
  }>, payload?: unknown, retainInFlight?: boolean): WorkflowRunState<TResult>;
34
33
  export declare function getWorkflowRunState(name: string, id: string): WorkflowRunState | undefined;
35
- export declare function resetWorkflowRuntime(): void;
36
- //#endregion
34
+ export declare function resetWorkflowRuntime(): void;
@@ -1,7 +1,8 @@
1
- import { t as workflowErrorDiagnostics } from "../error-diagnostics-0V2T3JFw.js";
2
- import { n as setWorkflowDevRecorder } from "../dev-recorder-CTN5Fkao.js";
1
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics--2cV_ER1.js";
2
+ import { n as setWorkflowDevRecorder } from "../dev-recorder-Dltdmlkv.js";
3
+ import { a as resetInlineWorkflowSignals } from "../signals-BHQdxoJo.js";
3
4
  import { AsyncLocalStorage } from "node:async_hooks";
4
- //#region src/runtime/state.ts
5
+ // src/runtime/state.ts
5
6
  const RUNS_LIMIT = 1024;
6
7
  const RUNS_TTL_MS = 3e5;
7
8
  let runtimeConfig;
@@ -243,7 +244,7 @@ function resetWorkflowRuntime() {
243
244
  inFlightRuns.clear();
244
245
  fallbackRunKeys.clear();
245
246
  completedRuns.clear();
247
+ resetInlineWorkflowSignals();
246
248
  setWorkflowDevRecorder(void 0);
247
249
  }
248
- //#endregion
249
250
  export { enterWorkflowRuntimeEvent, getInlineWorkflowDefinitions, getWorkflowRunState, getWorkflowRuntimeConfig, getWorkflowRuntimeEvent, getWorkflowRuntimeRegistry, loadWorkflowDefinition, registerInlineWorkflowDefinition, resetWorkflowRuntime, runWithWorkflowRuntimeEvent, setWorkflowRun, setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry, takeInlineWorkflowDefinition, takeInlineWorkflowDefinitionForModule };
@@ -1,7 +1,6 @@
1
- import { l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-Dsmwsdlv.js";
2
- import { t as VitehubApp } from "../app-BojnC_yf.js";
1
+ import { t as VitehubApp } from "../app-wkVFd7m-.js";
2
+ import { l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-DvYcvbPG.js";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
- //#region src/runtime/vercel.d.ts
5
4
  interface VercelRun {
6
5
  cancel: () => Promise<void>;
7
6
  completedAt: Promise<Date | undefined>;
@@ -55,8 +54,6 @@ interface VercelWorkflowRuntimeModule {
55
54
  };
56
55
  }
57
56
  export declare function setVercelWorkflowRuntimeModules(api: VercelWorkflowApiModule, runtime: VercelWorkflowRuntimeModule): void;
58
- //#endregion
59
- //#region src/runtime/vercel-vite.d.ts
60
57
  export declare function runWithVercelWorkflowRuntimeEvent<T>(req: unknown, res: unknown, run: () => T | Promise<T>): Promise<T>;
61
58
  interface WorkflowVercelServerOptions {
62
59
  app?: VitehubApp;
@@ -65,4 +62,4 @@ interface WorkflowVercelServerOptions {
65
62
  }
66
63
  export type WorkflowVercelServer = (req: IncomingMessage, res: ServerResponse) => unknown;
67
64
  export declare function createWorkflowVercelServer(options?: WorkflowVercelServerOptions): WorkflowVercelServer;
68
- //#endregion
65
+ export {};
@@ -1,9 +1,9 @@
1
+ import { t as resolveAppFetch } from "../app-DXUHElAz.js";
1
2
  import { runWithWorkflowRuntimeEvent, setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry } from "./state.js";
2
- import { i as setVercelWorkflowRuntimeModules } from "../vercel-DTvm61iY.js";
3
- import { t as resolveAppFetch } from "../app-He0GTrYZ.js";
3
+ import { i as setVercelWorkflowRuntimeModules } from "../vercel-Cw_Z9-j4.js";
4
4
  import { waitUntil } from "@vercel/functions";
5
5
  import { H3 } from "h3";
6
- //#region ../internal/src/runtime/vercel-hosted.ts
6
+ // ../internal/src/runtime/vercel-hosted.ts
7
7
  function createVercelHostedServer(adapter) {
8
8
  const appHandler = resolveAppFetch(adapter.label, adapter.app);
9
9
  let nodeHandlerPromise;
@@ -31,8 +31,7 @@ function createVercelHostedServer(adapter) {
31
31
  return handle();
32
32
  };
33
33
  }
34
- //#endregion
35
- //#region src/runtime/vercel-vite.ts
34
+ // src/runtime/vercel-vite.ts
36
35
  async function runWithVercelWorkflowRuntimeEvent(req, res, run) {
37
36
  return await runWithWorkflowRuntimeEvent({
38
37
  req,
@@ -51,5 +50,4 @@ function createWorkflowVercelServer(options = {}) {
51
50
  }
52
51
  });
53
52
  }
54
- //#endregion
55
53
  export { createWorkflowVercelServer, runWithVercelWorkflowRuntimeEvent, setVercelWorkflowRuntimeModules };
@@ -0,0 +1,79 @@
1
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics--2cV_ER1.js";
2
+ // src/runtime/signals.ts
3
+ const tokenPrefix = "vhsig1.";
4
+ const hosts = /* @__PURE__ */ new Set([
5
+ "cloudflare",
6
+ "inline",
7
+ "openworkflow"
8
+ ]);
9
+ function toBase64Url(text) {
10
+ let binary = "";
11
+ for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte);
12
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
13
+ }
14
+ function fromBase64Url(value) {
15
+ const binary = atob(value.replaceAll("-", "+").replaceAll("_", "/"));
16
+ return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
17
+ }
18
+ function createWorkflowSignalToken({ host, run, signal, workflow }) {
19
+ return `${tokenPrefix}${toBase64Url(JSON.stringify([
20
+ host,
21
+ workflow,
22
+ run,
23
+ signal
24
+ ]))}`;
25
+ }
26
+ /** The address in a token of `context.createSignal()`, or undefined for any other string. */
27
+ function readWorkflowSignalToken(token) {
28
+ if (!token.startsWith(tokenPrefix)) return void 0;
29
+ let value;
30
+ try {
31
+ value = JSON.parse(fromBase64Url(token.slice(7)));
32
+ } catch {
33
+ return;
34
+ }
35
+ if (!Array.isArray(value) || value.length !== 4 || !value.every((part) => typeof part === "string" && part !== "")) return void 0;
36
+ const [host, workflow, run, signal] = value;
37
+ if (!hosts.has(host)) return void 0;
38
+ return {
39
+ host,
40
+ run,
41
+ signal,
42
+ workflow
43
+ };
44
+ }
45
+ const inlineSignals = /* @__PURE__ */ new Map();
46
+ /** Adds the inline signal of `token`, so a `resumeWorkflow()` call before the wait keeps its value. */
47
+ function openInlineWorkflowSignal(token) {
48
+ if (!inlineSignals.has(token)) inlineSignals.set(token, {});
49
+ }
50
+ /** Forgets the inline signals of a run that ended. A later `resumeWorkflow()` call fails with `WORKFLOW_SIGNAL_NOT_WAITING`. */
51
+ function closeInlineWorkflowSignals(tokens) {
52
+ for (const token of tokens) inlineSignals.delete(token);
53
+ }
54
+ /** Waits in memory for the value of `resumeWorkflow(token, value)`. */
55
+ async function waitForInlineWorkflowSignal(token) {
56
+ const entry = inlineSignals.get(token) ?? {};
57
+ inlineSignals.set(token, entry);
58
+ if (entry.sent) {
59
+ inlineSignals.delete(token);
60
+ return entry.sent.value;
61
+ }
62
+ return await new Promise((resolve) => {
63
+ entry.resolve = (value) => {
64
+ inlineSignals.delete(token);
65
+ resolve(value);
66
+ };
67
+ });
68
+ }
69
+ /** Sends `value` to the inline signal of `token`. Fails when no run of this process has the signal open. */
70
+ function resumeInlineWorkflowSignal(token, address, value) {
71
+ const entry = inlineSignals.get(token);
72
+ if (!entry || entry.sent) throw workflowErrorDiagnostics.WORKFLOW_SIGNAL_NOT_WAITING({ run: address.run });
73
+ if (entry.resolve) entry.resolve(value);
74
+ else entry.sent = { value };
75
+ }
76
+ function resetInlineWorkflowSignals() {
77
+ inlineSignals.clear();
78
+ }
79
+ export { resetInlineWorkflowSignals as a, readWorkflowSignalToken as i, createWorkflowSignalToken as n, resumeInlineWorkflowSignal as o, openInlineWorkflowSignal as r, waitForInlineWorkflowSignal as s, closeInlineWorkflowSignals as t };
@@ -1,5 +1,4 @@
1
1
  import { Duration, Result } from "@vite-hub/runtime";
2
- //#region src/types.d.ts
3
2
  type WorkflowDriver = "cloudflare" | "openworkflow" | "vercel";
4
3
  interface CloudflareWorkflowBinding<TPayload = unknown> {
5
4
  createBatch: (batch: Array<{
@@ -11,6 +10,11 @@ interface CloudflareWorkflowBinding<TPayload = unknown> {
11
10
  interface CloudflareWorkflowInstance {
12
11
  id: string;
13
12
  status: () => Promise<unknown>;
13
+ /** Sends an event that `step.waitForEvent()` of the instance waits for. */
14
+ sendEvent?: (event: {
15
+ payload: unknown;
16
+ type: string;
17
+ }) => Promise<void>;
14
18
  /** Stops the instance. Cloudflare rejects the call when the instance has already finished. */
15
19
  terminate: () => Promise<void>;
16
20
  }
@@ -144,6 +148,24 @@ interface WorkflowProviderStep {
144
148
  sleep?: (name: string, milliseconds: number) => Promise<void>;
145
149
  /** Sleeps until a date. Without it, ViteHub sleeps for the time that is left until the date. */
146
150
  sleepUntil?: (name: string, date: Date) => Promise<void>;
151
+ /**
152
+ * Waits durably until `resumeWorkflow(token, value)` sends the signal, and returns the value. ViteHub names each
153
+ * wait by call order (`signal-1`, `signal-2`).
154
+ */
155
+ waitForSignal?: (name: string, token: string) => Promise<unknown>;
156
+ }
157
+ /**
158
+ * A signal of one run, from `context.createSignal()`. Give `token` to the code that will resume the run, such as the
159
+ * webhook URL of an outside service. `wait()` returns the value of `resumeWorkflow(token, value)`.
160
+ */
161
+ interface WorkflowSignal<TValue = unknown> {
162
+ /**
163
+ * The token of this signal. It is the same on each replay of the run. It is not a secret: check the caller, such as
164
+ * a webhook signature, before you pass a token from a request to `resumeWorkflow()`.
165
+ */
166
+ readonly token: string;
167
+ /** Waits until `resumeWorkflow(token, value)` sends the signal, and returns the value. */
168
+ wait: () => Promise<TValue>;
147
169
  }
148
170
  type WorkflowDurationUnit = "second" | "minute" | "hour" | "day" | "week" | "month" | "year";
149
171
  /**
@@ -190,8 +212,15 @@ interface WorkflowProviderContext<TPayload = unknown> {
190
212
  }
191
213
  /** The one object that a Workflow handler receives: the `payload` of the run, the run data, `sleep`, and `steps`. */
192
214
  interface WorkflowExecutionContext<TPayload = unknown> extends Omit<WorkflowProviderContext<TPayload>, "step"> {
193
- /** The provider step runner. Use `context.sleep()` to sleep. */
194
- step?: Omit<WorkflowProviderStep, "sleep" | "sleepUntil">;
215
+ /**
216
+ * Makes a signal that the run can wait for. `resumeWorkflow(signal.token, value)` ends the wait of
217
+ * `signal.wait()`. Only a folder Workflow's `index.ts` can wait: in a single-file Workflow, `wait()` throws
218
+ * `WORKFLOW_ROOT_STEP_SIGNAL`. The wait is durable on Cloudflare and OpenWorkflow. Inline runs (`vite dev`) wait in
219
+ * memory. Vercel does not support signals yet: `createSignal()` throws `WORKFLOW_SIGNAL_VERCEL_UNSUPPORTED`.
220
+ */
221
+ createSignal: <TValue = unknown>() => WorkflowSignal<TValue>;
222
+ /** The provider step runner. Use `context.sleep()` to sleep and `context.createSignal()` to wait for a signal. */
223
+ step?: Omit<WorkflowProviderStep, "sleep" | "sleepUntil" | "waitForSignal">;
195
224
  /**
196
225
  * Sleeps for a duration such as `'1 day'` or a number of milliseconds, or until a `Date`. Only a folder Workflow's
197
226
  * `index.ts` can sleep. In a single-file Workflow it throws `WORKFLOW_ROOT_STEP_SLEEP`. The sleep is durable on
@@ -236,7 +265,7 @@ type WorkflowStartArguments<TPayload> = undefined extends TPayload ? [payload?:
236
265
  * Codes that `startWorkflow()`, `getWorkflowRun()`, `cancelWorkflow()`, `resumeWorkflow()`, and the methods of a
237
266
  * WorkflowHandle return in the `[error, data]` tuple. Config errors throw instead.
238
267
  */
239
- type WorkflowResultErrorCode = "RUNTIME_DURATION_INVALID" | "WORKFLOW_CLOUDFLARE_RUN_ID_INVALID" | "WORKFLOW_OPERATION_UNSUPPORTED" | "WORKFLOW_PROVIDER_OPERATION_FAILED" | "WORKFLOW_R0014" | "WORKFLOW_RUN_ID_UNSUPPORTED" | "WORKFLOW_START_DELAY_INVALID";
268
+ type WorkflowResultErrorCode = "RUNTIME_DURATION_INVALID" | "WORKFLOW_CLOUDFLARE_RUN_ID_INVALID" | "WORKFLOW_OPERATION_UNSUPPORTED" | "WORKFLOW_PROVIDER_OPERATION_FAILED" | "WORKFLOW_R0014" | "WORKFLOW_RUN_ID_UNSUPPORTED" | "WORKFLOW_SIGNAL_NOT_WAITING" | "WORKFLOW_SIGNAL_TOKEN_INVALID" | "WORKFLOW_START_DELAY_INVALID";
240
269
  /** `cancel()`, `getRun()`, and `start()` return `[error, data]`, as `cancelWorkflow()`, `getWorkflowRun()`, and `startWorkflow()` do. */
241
270
  interface WorkflowHandle<TPayload = unknown, TResult = unknown> {
242
271
  cancel: (id: string) => Promise<Result<WorkflowRun<unknown, unknown>, WorkflowResultErrorCode>>;
@@ -278,5 +307,4 @@ interface DiscoveredWorkflowDefinition {
278
307
  source?: "agent-workflow" | "agent-workflow-recovery" | "inline" | "server-workflows" | "vite-suffix";
279
308
  steps?: string[];
280
309
  }
281
- //#endregion
282
- export { WorkflowRun as A, WorkflowStep as B, WorkflowName as C, WorkflowProviderStep as D, WorkflowProviderContext as E, WorkflowSharedOptions as F, WorkflowStepRegistry as G, WorkflowStepContext as H, WorkflowSignalResult as I, WorkflowStepRetries as K, WorkflowStartArguments as L, WorkflowRunStatus as M, WorkflowRunStep as N, WorkflowRegistry as O, WorkflowRuntimeConfigValue as P, WorkflowStartDelay as R, WorkflowModuleDriverOptions as S, WorkflowPayload as T, WorkflowStepFunction as U, WorkflowStepBackoff as V, WorkflowStepOptions as W, WorkflowDuration as _, InferredWorkflowDriverOptions as a, WorkflowHandle as b, OpenWorkflowWorkerOptions as c, WorkflowCreateOptions as d, WorkflowDefinition as f, WorkflowDriverOptions as g, WorkflowDriver as h, DiscoveredWorkflowDefinition as i, WorkflowRunError as j, WorkflowResultErrorCode as k, ResolvedWorkflowOptions as l, WorkflowDefinitionRegistry as m, CloudflareWorkflowDriverOptions as n, OpenWorkflowDriverOptions as o, WorkflowDefinitionOptions as p, WorkflowSteps as q, CloudflareWorkflowInstance as r, OpenWorkflowPostgresOptions as s, CloudflareWorkflowBinding as t, VercelWorkflowDriverOptions as u, WorkflowDurationUnit as v, WorkflowOptions as w, WorkflowHandler as x, WorkflowExecutionContext as y, WorkflowStartOptions as z };
310
+ export { WorkflowRun as A, WorkflowStartOptions as B, WorkflowName as C, WorkflowProviderStep as D, WorkflowProviderContext as E, WorkflowSharedOptions as F, WorkflowStepOptions as G, WorkflowStepBackoff as H, WorkflowSignal as I, WorkflowSteps as J, WorkflowStepRegistry as K, WorkflowSignalResult as L, WorkflowRunStatus as M, WorkflowRunStep as N, WorkflowRegistry as O, WorkflowRuntimeConfigValue as P, WorkflowStartArguments as R, WorkflowModuleDriverOptions as S, WorkflowPayload as T, WorkflowStepContext as U, WorkflowStep as V, WorkflowStepFunction as W, WorkflowDuration as _, InferredWorkflowDriverOptions as a, WorkflowHandle as b, OpenWorkflowWorkerOptions as c, WorkflowCreateOptions as d, WorkflowDefinition as f, WorkflowDriverOptions as g, WorkflowDriver as h, DiscoveredWorkflowDefinition as i, WorkflowRunError as j, WorkflowResultErrorCode as k, ResolvedWorkflowOptions as l, WorkflowDefinitionRegistry as m, CloudflareWorkflowDriverOptions as n, OpenWorkflowDriverOptions as o, WorkflowDefinitionOptions as p, WorkflowStepRetries as q, CloudflareWorkflowInstance as r, OpenWorkflowPostgresOptions as s, CloudflareWorkflowBinding as t, VercelWorkflowDriverOptions as u, WorkflowDurationUnit as v, WorkflowOptions as w, WorkflowHandler as x, WorkflowExecutionContext as y, WorkflowStartDelay as z };
@@ -1,17 +1,13 @@
1
- import { t as workflowErrorDiagnostics } from "./error-diagnostics-0V2T3JFw.js";
2
- import { n as createWorkflowError } from "./errors-DCqRnZpN.js";
3
- import { a as workflowStartAtKey } from "./delay-D1-nq_VE.js";
4
- import { a as safeWorkflowName, i as runWorkflowProviderOperation, r as isWorkflowBoundaryError, t as toWorkflowRunError } from "./run-error-DBWqiJHH.js";
5
- //#region src/runtime/vercel.ts
1
+ import { n as createWorkflowError } from "./errors-CZf7oz4k.js";
2
+ import { a as workflowStartAtKey } from "./delay-CtT3442d.js";
3
+ import { a as safeWorkflowName, i as runWorkflowProviderOperation, r as isWorkflowBoundaryError, t as toWorkflowRunError } from "./run-error-8p4BtTMv.js";
4
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics--2cV_ER1.js";
5
+ // src/runtime/vercel.ts
6
6
  async function loadVercelWorkflowRuntime() {
7
7
  const importVercelWorkflow = new Function("specifier", "return import(specifier)");
8
8
  const [api, runtime] = await Promise.all([importVercelWorkflow("workflow/api"), importVercelWorkflow("workflow/runtime")]);
9
9
  return createVercelWorkflowRuntime(api, runtime);
10
10
  }
11
- /**
12
- * The largest step page that Vercel's step listing accepts. A larger page fails with HTTP 400. Workflow DevKit's own
13
- * CLI uses the same bound (`packages/cli/src/lib/inspect/flag-bounds.ts` in vercel/workflow).
14
- */
15
11
  const vercelStepPageLimit = 100;
16
12
  function createVercelWorkflowRuntime(api, runtime) {
17
13
  const { getRun, resumeHook, start } = api;
@@ -151,10 +147,6 @@ async function readRunIdentity(run) {
151
147
  workflowName
152
148
  };
153
149
  }
154
- /**
155
- * The error of a failed native run. Workflow DevKit rejects `returnValue` of a failed run with
156
- * `WorkflowRunFailedError`, which keeps the thrown value in `cause`.
157
- */
158
150
  async function readVercelRunError(run) {
159
151
  try {
160
152
  await run.returnValue;
@@ -275,5 +267,4 @@ async function resumeVercelWorkflowSignal(token, payload) {
275
267
  provider: "vercel"
276
268
  };
277
269
  }
278
- //#endregion
279
270
  export { startVercelWorkflow as a, setVercelWorkflowRuntimeModules as i, inspectVercelWorkflowRun as n, resumeVercelWorkflowSignal as r, cancelVercelWorkflow as t };
package/dist/vite.d.ts CHANGED
@@ -1,19 +1,14 @@
1
- import { i as DiscoveredWorkflowDefinition, w as WorkflowOptions } from "./types-Dsmwsdlv.js";
2
- import { n as OperationContributionEntry } from "./operation-definition-nmRu_O3V.js";
1
+ import { n as OperationContributionEntry } from "./operation-definition-CqZkx1Rm.js";
2
+ import { i as DiscoveredWorkflowDefinition, w as WorkflowOptions } from "./types-DvYcvbPG.js";
3
3
  import { Plugin, ResolvedConfig, Rolldown, UserConfig } from "vite";
4
- //#region src/internal/runtime-modules.d.ts
5
4
  type WorkflowRuntimeModuleName = "cloudflare-runner" | "cloudflare-vite" | "dev-runs" | "execute" | "openworkflow-worker" | "state" | "vercel-vite";
6
5
  /**
7
6
  * The file path of a Workflow runtime module. Generated code imports it by path, so it needs no package export.
8
7
  * Schedule and Agent output receive these paths from the Workflow plugin.
9
8
  */
10
9
  export declare function workflowRuntimeModule(name: WorkflowRuntimeModuleName): string;
11
- //#endregion
12
- //#region ../internal/src/deployment.d.ts
13
10
  /** The host that ViteHub builds for: the `host` option of `vitehub()` and the value of `VITEHUB_HOST`. */
14
11
  type ViteHubHost = "cloudflare" | "deno" | "netlify" | "node" | "vercel";
15
- //#endregion
16
- //#region ../internal/src/inspect.d.ts
17
12
  interface ViteHubDefinitionField {
18
13
  label: string;
19
14
  value: string;
@@ -63,6 +58,8 @@ interface ViteHubResourceSummary {
63
58
  owner: string;
64
59
  /** Absent when no id is known yet. */
65
60
  source?: ViteHubResourceIdSource;
61
+ /** The resource is in the Wrangler config of a standalone Provider Output Worker, not in Nitro's. */
62
+ standalone?: boolean;
66
63
  }
67
64
  interface ViteHubInspectionContributor {
68
65
  definitions?: readonly ViteHubDefinitionInspector[];
@@ -73,8 +70,6 @@ type ViteHubInspectionContributorFactory = () => ViteHubInspectionContributor |
73
70
  interface ViteHubInspectionPluginMetadata {
74
71
  inspect?: ViteHubInspectionContributor | ViteHubInspectionContributorFactory;
75
72
  }
76
- //#endregion
77
- //#region ../internal/src/build/deployment-plan-output.d.ts
78
73
  /**
79
74
  * One set of host variables that the deployed app reads, as `deployment.json` lists it: a Server Env declaration, or
80
75
  * a variable that a primitive reads itself, such as `VITEHUB_SECRET` or `BLOB_READ_WRITE_TOKEN`.
@@ -104,8 +99,6 @@ interface DeploymentEnvContext {
104
99
  * Return names only, never values.
105
100
  */
106
101
  type DeploymentEnvContribution = (context: DeploymentEnvContext) => readonly DeploymentEnvEntry[];
107
- //#endregion
108
- //#region ../internal/src/durability.d.ts
109
102
  /**
110
103
  * One durability reporter that a primitive's Vite plugin contributes through `vitehub.durability`. The Node server
111
104
  * imports `export` from `module` at boot and calls it with `input` and the server environment. It returns the
@@ -128,8 +121,6 @@ interface DurabilityPluginMetadata {
128
121
  /** Called after Vite resolves the config. Return an empty list when the primitive is off. */
129
122
  durability?: () => readonly DurabilityContribution[];
130
123
  }
131
- //#endregion
132
- //#region ../internal/src/build/vite.d.ts
133
124
  interface ProviderOutputEnvironmentOwner {
134
125
  /** Install as the plugin's `buildApp` hook. */
135
126
  buildApp: (builder: {
@@ -156,8 +147,6 @@ type NitroPackageLoadingOptions = {
156
147
  runner?: string;
157
148
  };
158
149
  };
159
- //#endregion
160
- //#region src/discovery.d.ts
161
150
  export declare function discoverWorkflowDefinitions(options: {
162
151
  mode?: "vite-suffix" | "standalone";
163
152
  rootDir: string;
@@ -167,15 +156,11 @@ export declare function discoverWorkflowDefinitions(options: {
167
156
  mode: "server-workflows";
168
157
  scanDirs: string[];
169
158
  }): DiscoveredWorkflowDefinition[];
170
- //#endregion
171
- //#region src/internal/registry-types.d.ts
172
159
  /**
173
160
  * Types `startWorkflow()` with the name and payload of each Workflow Definition (`WorkflowRegistry`), and `steps` with
174
161
  * the step files of each folder Workflow (`WorkflowStepRegistry`).
175
162
  */
176
163
  export declare function createWorkflowTypes(file: string, definitions: DiscoveredWorkflowDefinition[], importBase?: string): string;
177
- //#endregion
178
- //#region ../internal/src/console.d.ts
179
164
  type MaybePromise<T> = T | Promise<T>;
180
165
  /** Lists discovered Definitions in a sidebar and shows the selected Definition's fields. */
181
166
  interface ViteHubConsoleDefinitionCatalogView {
@@ -507,8 +492,6 @@ interface ViteHubConsoleDocumentSetup {
507
492
  */
508
493
  schedule?: ViteHubConsoleDocumentHint;
509
494
  }
510
- //#endregion
511
- //#region src/inspect.d.ts
512
495
  interface WorkflowInspectionOptions {
513
496
  projectRoot: string;
514
497
  rootDir: string;
@@ -516,10 +499,16 @@ interface WorkflowInspectionOptions {
516
499
  }
517
500
  /** Lists user-facing Workflow Definitions. Generated Agent recovery Workflows are internal and stay hidden. */
518
501
  export declare function inspectWorkflowDefinitions(options: WorkflowInspectionOptions): ViteHubDefinitionSummary[];
502
+ /**
503
+ * Lists the Cloudflare Workflows that the build binds, with the same binding and Workflow names as the generated Wrangler
504
+ * config. Agent recovery Workflows are listed too, since the Worker needs their bindings. Reads local files only.
505
+ */
506
+ export declare function inspectWorkflowResources(options: WorkflowInspectionOptions & {
507
+ binding?: string;
508
+ name?: string;
509
+ }): ViteHubResourceSummary[];
519
510
  /** Console section that lists discovered Workflow Definitions. `vitehub inspect definitions` reads the same data. */
520
511
  export declare const workflowConsoleSection: ViteHubConsoleSectionContribution<WorkflowInspectionOptions>;
521
- //#endregion
522
- //#region src/vite.d.ts
523
512
  interface WorkflowNitroConfigOptions {
524
513
  nitro: Record<string, unknown>;
525
514
  projectRoot: string;
@@ -550,15 +539,10 @@ export type WorkflowVitePlugin = Plugin & Partial<Pick<ProviderOutputEnvironment
550
539
  };
551
540
  };
552
541
  interface InternalWorkflowModuleOptions {
553
- /** The module that exports `getPostgresConnectionUrl()`. Default `@vite-hub/database`. */
554
542
  databaseImport?: string;
555
543
  hosting?: string;
556
544
  importBase?: string;
557
545
  providerImportAliases?: Record<string, string>;
558
- /**
559
- * The app that the Workflow Provider Output serves next to the Workflows. `true` finds `src/server.ts` or
560
- * `src/worker.ts`, a file name such as `"server-workflow.ts"` picks that file in `src`, and `false` serves no app.
561
- */
562
546
  includeUserAppEntry?: boolean | string;
563
547
  workspaceDependencyRuntimeImports?: {
564
548
  shellWorkspace?: string;
@@ -566,5 +550,4 @@ interface InternalWorkflowModuleOptions {
566
550
  workspaceRuntimeModule?: string;
567
551
  }
568
552
  export declare function hubWorkflow(workflow?: WorkflowOptions, internalOptions?: InternalWorkflowModuleOptions): WorkflowVitePlugin;
569
- //#endregion
570
553
  export type { WorkflowInspectionOptions };