@vite-hub/workflow 0.6.0 → 0.7.0

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 (48) hide show
  1. package/README.md +32 -8
  2. package/dist/{app-DXUHElAz.js → app-Cpa9qCXr.js} +1 -1
  3. package/dist/{client-CbBg4HlH.js → client-CPxPxsl5.js} +37 -37
  4. package/dist/cloudflare-concurrency-counter-CDHHiMfn.js +136 -0
  5. package/dist/{config-CizNRTMi.js → config-CwCwuZqv.js} +1 -1
  6. package/dist/definition.d.ts +1 -1
  7. package/dist/definition.js +4 -1
  8. package/dist/{delay-CtT3442d.js → delay-JrpW40UF.js} +4 -2
  9. package/dist/durability.d.ts +3 -1
  10. package/dist/durability.js +7 -1
  11. package/dist/{error-diagnostics--2cV_ER1.js → error-diagnostics-35AEmfve.js} +25 -5
  12. package/dist/{error-diagnostics-kKXseq8d.js → error-diagnostics-CsiNo_oI.js} +3 -3
  13. package/dist/{errors-CJZuvOcx.d.ts → errors-DwKy5MQ8.d.ts} +1 -1
  14. package/dist/execute-CLmIXnON.js +355 -0
  15. package/dist/index.d.ts +12 -10
  16. package/dist/index.js +3 -3
  17. package/dist/{openworkflow-defaults-DfQWtSRU.js → invariant-Dj2R1eMr.js} +1 -4
  18. package/dist/openworkflow-BiwPTYEz.js +752 -0
  19. package/dist/{openworkflow-CdKbUGGa.d.ts → openworkflow-C65AWQSJ.d.ts} +23 -4
  20. package/dist/openworkflow-defaults-1n0DbLdb.js +4 -0
  21. package/dist/{operation-definition-CqZkx1Rm.d.ts → operations-Blwi3jQF.d.ts} +1 -0
  22. package/dist/{operations-BBTmDm2H.js → operations-DyaGK9zW.js} +70 -14
  23. package/dist/operations.d.ts +3 -59
  24. package/dist/operations.js +5 -5
  25. package/dist/results-DBp_bmUP.d.ts +60 -0
  26. package/dist/runtime/cloudflare-concurrency.d.ts +21 -0
  27. package/dist/runtime/cloudflare-concurrency.js +21 -0
  28. package/dist/runtime/cloudflare-runner.d.ts +1 -1
  29. package/dist/runtime/cloudflare-runner.js +7 -3
  30. package/dist/runtime/cloudflare-vite.d.ts +1 -1
  31. package/dist/runtime/cloudflare-vite.js +2 -2
  32. package/dist/runtime/execute.d.ts +8 -2
  33. package/dist/runtime/execute.js +1 -278
  34. package/dist/runtime/openworkflow-worker.d.ts +2 -2
  35. package/dist/runtime/openworkflow-worker.js +2 -2
  36. package/dist/runtime/openworkflow.d.ts +2 -2
  37. package/dist/runtime/openworkflow.js +1 -481
  38. package/dist/runtime/state.d.ts +1 -1
  39. package/dist/runtime/state.js +2 -2
  40. package/dist/runtime/vercel-vite.d.ts +1 -1
  41. package/dist/runtime/vercel-vite.js +2 -2
  42. package/dist/{signals-BHQdxoJo.js → signals-CdaxRNjN.js} +1 -1
  43. package/dist/{types-DvYcvbPG.d.ts → types-CvyOEp0V.d.ts} +33 -4
  44. package/dist/{vercel-Cw_Z9-j4.js → vercel-ADMH2MK8.js} +5 -3
  45. package/dist/vite.d.ts +18 -4
  46. package/dist/vite.js +553 -116
  47. package/package.json +3 -3
  48. package/dist/cloudflare-Sgywkm1N.js +0 -57
package/dist/vite.js CHANGED
@@ -1,14 +1,15 @@
1
1
  import { i as __toESM, n as __exportAll } from "./rolldown-runtime-DYf_mQCB.js";
2
- import { n as invariant, r as invariantError, t as defaultOpenWorkflowSqlitePath } from "./openworkflow-defaults-DfQWtSRU.js";
2
+ import { n as invariantError, t as invariant } from "./invariant-Dj2R1eMr.js";
3
3
  import { workflowDurabilityUrl } from "./durability.js";
4
- import { t as internalErrorDiagnostics } from "./error-diagnostics-kKXseq8d.js";
4
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-CsiNo_oI.js";
5
5
  import { n as isRecordOrFunction, t as isRecord } from "./object-CAK6UYR5.js";
6
- import { n as getHostingProvider, r as normalizeHosting, t as normalizeWorkflowOptions } from "./config-CizNRTMi.js";
6
+ import { n as getHostingProvider, r as normalizeHosting, t as normalizeWorkflowOptions } from "./config-CwCwuZqv.js";
7
7
  import { r as relativeDefinitionFile } from "./inspect-NBCAwsxi.js";
8
- import { i as getLegacyCloudflareWorkflowClassName, r as getCloudflareWorkflowClassName, t as createCloudflareWorkflowBindings } from "./cloudflare-Sgywkm1N.js";
9
- import { t as workflowErrorDiagnostics } from "./error-diagnostics--2cV_ER1.js";
10
- import { resolveWorkflowStepOptions, toStepPropertyName } from "./runtime/execute.js";
11
- import { a as workflowStartAtKey, n as generatedNativeEntryKey } from "./delay-CtT3442d.js";
8
+ import { c as getCloudflareWorkflowClassName, l as getLegacyCloudflareWorkflowClassName, n as cloudflareConcurrencyClassName, o as createCloudflareWorkflowBindings, r as cloudflareConcurrencyMigrationTag, t as cloudflareConcurrencyBinding } from "./cloudflare-concurrency-counter-CDHHiMfn.js";
9
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics-35AEmfve.js";
10
+ import { f as toStepPropertyName, i as resolveWorkflowStepOptions } from "./execute-CLmIXnON.js";
11
+ import { n as generatedNativeEntryKey, o as vercelNativeRegistryKey, r as generatedNativeRootStepKey, s as workflowStartAtKey } from "./delay-JrpW40UF.js";
12
+ import { t as defaultOpenWorkflowSqlitePath } from "./openworkflow-defaults-1n0DbLdb.js";
12
13
  import { builtinModules, createRequire, isBuiltin } from "node:module";
13
14
  import { dirname, normalize, relative, resolve } from "pathe";
14
15
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -230,12 +231,32 @@ function mergeOwnedArrays(existing, value, arrays) {
230
231
  const next = { ...value };
231
232
  for (const [field, ownership] of Object.entries(arrays ?? {})) {
232
233
  const incoming = Array.isArray(value[field]) ? value[field] : [];
233
- const merged = [...preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming), ...incoming];
234
+ const unowned = preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming);
235
+ const merged = ownership.key !== void 0 && ownership.preserveOrder && Array.isArray(existing[field]) ? mergeOrderedEntries(existing[field], unowned, incoming, ownership.key) : [...unowned, ...incoming];
234
236
  if (merged.length) next[field] = merged;
235
237
  else delete next[field];
236
238
  }
237
239
  return next;
238
240
  }
241
+ function mergeOrderedEntries(current, unowned, incoming, key) {
242
+ const preserved = new Set(unowned);
243
+ const replacements = new Map(incoming.flatMap((entry) => {
244
+ const identity = getKeyedArrayEntryValue(entry, key);
245
+ return identity === void 0 ? [] : [[identity, entry]];
246
+ }));
247
+ return [...current.flatMap((entry) => {
248
+ if (preserved.has(entry)) return [entry];
249
+ const identity = getKeyedArrayEntryValue(entry, key);
250
+ if (identity === void 0) return [];
251
+ const replacement = replacements.get(identity);
252
+ if (replacement === void 0) return [];
253
+ replacements.delete(identity);
254
+ return [replacement];
255
+ }), ...incoming.filter((entry) => {
256
+ const identity = getKeyedArrayEntryValue(entry, key);
257
+ return identity === void 0 || replacements.has(identity);
258
+ })];
259
+ }
239
260
  async function persistProviderJsonRecord(file, value, removeIfEmpty) {
240
261
  if (removeIfEmpty && !Object.keys(value).length) {
241
262
  await rm(file, { force: true });
@@ -255,19 +276,31 @@ async function writeProviderOutputConfig(file, value, ownership = {}, options =
255
276
  function mergeProviderOutputConfig(existing, value, ownership = {}) {
256
277
  assertProviderJsonRecord(existing);
257
278
  assertProviderJsonRecord(value);
258
- return {
279
+ const next = {
259
280
  ...deleteOwnedFields(existing, ownership),
260
281
  ...mergeOwnedArrays(existing, value, ownership.arrays)
261
282
  };
283
+ for (const [field, childOwnership] of Object.entries(ownership.objects ?? {})) {
284
+ const current = existing[field];
285
+ const incoming = value[field];
286
+ const merged = mergeProviderOutputConfig(isProviderJsonRecord(current) ? current : {}, isProviderJsonRecord(incoming) ? incoming : {}, childOwnership);
287
+ if (Object.keys(merged).length) next[field] = merged;
288
+ else delete next[field];
289
+ }
290
+ return next;
262
291
  }
263
292
  function stringifyProviderOutputConfig(value) {
264
293
  assertProviderJsonRecord(value);
265
294
  return JSON.stringify(value, null, 2);
266
295
  }
267
296
  async function cleanProviderOutputConfig(file, ownership) {
268
- if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
297
+ if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length && !Object.keys(ownership.objects ?? {}).length) return;
269
298
  const existing = await readProviderJsonRecord(file);
270
299
  if (!existing) return;
300
+ const next = cleanOwnedFields(existing, ownership);
301
+ if (next) await persistProviderJsonRecord(file, next, true);
302
+ }
303
+ function cleanOwnedFields(existing, ownership) {
271
304
  const next = deleteOwnedFields(existing, ownership, true);
272
305
  let changed = (ownership.keys ?? []).some((key) => key in existing);
273
306
  for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
@@ -279,8 +312,16 @@ async function cleanProviderOutputConfig(file, ownership) {
279
312
  changed ||= retained.length > 0 || !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
280
313
  if (preserved.length) next[field] = preserved;
281
314
  }
282
- if (!changed) return;
283
- await persistProviderJsonRecord(file, next, true);
315
+ for (const [field, childOwnership] of Object.entries(ownership.objects ?? {})) {
316
+ const current = existing[field];
317
+ if (!isProviderJsonRecord(current)) continue;
318
+ const cleaned = cleanOwnedFields(current, childOwnership);
319
+ if (!cleaned) continue;
320
+ changed = true;
321
+ if (Object.keys(cleaned).length) next[field] = cleaned;
322
+ else delete next[field];
323
+ }
324
+ if (changed) return next;
284
325
  }
285
326
  // ../internal/src/build/user-entry.ts
286
327
  function toSafeAppName(rootDir) {
@@ -3269,6 +3310,19 @@ function unwrapExpression(node) {
3269
3310
  while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
3270
3311
  return node;
3271
3312
  }
3313
+ /** A call argument without assertions, or undefined for a spread or missing argument. */
3314
+ function argumentExpression(argument) {
3315
+ return argument === void 0 || argument.type === "SpreadElement" ? void 0 : unwrapExpression(argument);
3316
+ }
3317
+ /** The expression of `export default <expression>`, without assertions. Declarations return undefined. */
3318
+ function defaultExportExpression(module) {
3319
+ for (const statement of module.program.body) {
3320
+ if (statement.type !== "ExportDefaultDeclaration") continue;
3321
+ const declaration = statement.declaration;
3322
+ if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration" || declaration.type === "TSInterfaceDeclaration") return;
3323
+ return unwrapExpression(declaration);
3324
+ }
3325
+ }
3272
3326
  function staticKey(property) {
3273
3327
  const key = property.key;
3274
3328
  if (key.type === "Identifier" && !property.computed) return key.name;
@@ -3290,6 +3344,10 @@ function objectProperties(object) {
3290
3344
  value: unwrapExpression(node.value)
3291
3345
  });
3292
3346
  }
3347
+ /** The last member named `name`, which is the one that the object keeps at runtime. */
3348
+ function findProperty(object, name) {
3349
+ return objectProperties(object).findLast((property) => property.key === name);
3350
+ }
3293
3351
  /** The value of a template literal without substitutions. */
3294
3352
  function staticTemplate(node) {
3295
3353
  if (node.expressions.length) return dynamic;
@@ -3576,6 +3634,9 @@ const ignoredSourceDirectories = /* @__PURE__ */ new Set([
3576
3634
  "node_modules"
3577
3635
  ]);
3578
3636
  const ignoredGeneratedDirectories = /* @__PURE__ */ new Set([".vitehub", ".vitest-tmp"]);
3637
+ function crossesIgnoredDirectory(parent, child) {
3638
+ return relative$1(parent, child).split(sep).some((segment) => ignoredSourceDirectories.has(segment) || ignoredGeneratedDirectories.has(segment));
3639
+ }
3579
3640
  function isTransientSourceDirectory(path) {
3580
3641
  return basename(path).startsWith(".drizzle-generate-");
3581
3642
  }
@@ -3671,8 +3732,26 @@ async function linkDependencies(source, target, resolveLinkTarget = (source) =>
3671
3732
  await symlink(resolveLinkTarget(resolvedSourceEntry), targetEntry, process.platform === "win32" ? "junction" : "dir");
3672
3733
  }
3673
3734
  }
3674
- /** Removes retained provider output after readers release it, tolerating transient filesystem contention. */
3675
- async function removeProviderOutputArtifactDir(path) {
3735
+ const keptFailedProviderOutputArtifactDirs = /* @__PURE__ */ new Set();
3736
+ function failureText(failure) {
3737
+ return failure instanceof Error ? `${failure.message}\n${failure.stack ?? ""}` : String(failure);
3738
+ }
3739
+ /**
3740
+ * Removes retained provider output after readers release it, tolerating transient filesystem contention. Pass the
3741
+ * build failure when a failed build discards its generation: with `VITEHUB_KEEP_FAILED_BUILD=1` the folder stays
3742
+ * for inspection.
3743
+ */
3744
+ async function removeProviderOutputArtifactDir(path, failure) {
3745
+ if (failure !== void 0) {
3746
+ const shown = relative$1(process.cwd(), path) || path;
3747
+ if (/^(?:1|true)$/i.test(process.env.VITEHUB_KEEP_FAILED_BUILD ?? "")) {
3748
+ if (!existsSync(path)) return;
3749
+ if (!keptFailedProviderOutputArtifactDirs.has(path)) console.warn(`[vitehub] The build failed. ViteHub kept its provider sources in ${shown} so you can inspect them. Remove the folder when you are done.`);
3750
+ keptFailedProviderOutputArtifactDirs.add(path);
3751
+ return;
3752
+ }
3753
+ if (failureText(failure).includes(basename(path))) console.warn(`[vitehub] The build error names files in ${shown}, which ViteHub removes after a failed build. Set VITEHUB_KEEP_FAILED_BUILD=1 to keep them.`);
3754
+ }
3676
3755
  await rm(path, {
3677
3756
  force: true,
3678
3757
  maxRetries: 5,
@@ -3929,7 +4008,7 @@ function traceComputedModuleSources(file, source, onRuntimePackageRequest) {
3929
4008
  }
3930
4009
  return paths;
3931
4010
  }
3932
- async function traceImportedSources(paths, root, configuredRoots) {
4011
+ async function traceImportedSources(paths, root, configuredRoots, aliases) {
3933
4012
  const entries = paths.filter((path) => traceableSourceExtensions.has(extname(path)));
3934
4013
  if (!entries.length) return /* @__PURE__ */ new Set();
3935
4014
  const { rolldown } = await importRolldown();
@@ -4070,7 +4149,7 @@ async function traceImportedSources(paths, root, configuredRoots) {
4070
4149
  if (log.code === "UNRESOLVED_IMPORT") throw Object.assign(new Error(log.message), { code: log.code });
4071
4150
  },
4072
4151
  platform: variant.platform,
4073
- plugins: [tracePlugin],
4152
+ plugins: [createResolvedAliasPlugin(aliases, configuredRoots[0] ?? root, root, false), tracePlugin],
4074
4153
  resolve: { conditionNames: variant.conditions }
4075
4154
  });
4076
4155
  try {
@@ -4216,6 +4295,11 @@ function resolveTsconfigReference(config, reference) {
4216
4295
  if (existsSync(resolved)) return resolved;
4217
4296
  } catch {}
4218
4297
  }
4298
+ function resolveTsconfigProjectReference(config, reference) {
4299
+ const path = resolve$1(dirname$1(config), reference);
4300
+ const file = existsSync(path) && statSync(path).isDirectory() ? resolve$1(path, "tsconfig.json") : path;
4301
+ return existsSync(file) && statSync(file).isFile() ? file : void 0;
4302
+ }
4219
4303
  async function tsconfigSourcesForPaths(root, paths) {
4220
4304
  const pending = [];
4221
4305
  for (const path of paths) {
@@ -4237,11 +4321,9 @@ async function tsconfigSourcesForPaths(root, paths) {
4237
4321
  sources.add(config);
4238
4322
  try {
4239
4323
  const parsed = parseJsonWithComments(await readFile(config, "utf8"));
4240
- const references = Array.isArray(parsed.extends) ? parsed.extends : parsed.extends ? [parsed.extends] : [];
4241
- for (const reference of references) {
4242
- const resolved = resolveTsconfigReference(config, reference);
4243
- if (resolved && !sources.has(resolved)) pending.push(resolved);
4244
- }
4324
+ const extended = (Array.isArray(parsed.extends) ? parsed.extends : parsed.extends ? [parsed.extends] : []).map((reference) => resolveTsconfigReference(config, reference));
4325
+ const projects = (Array.isArray(parsed.references) ? parsed.references : []).map((reference) => typeof reference?.path === "string" ? resolveTsconfigProjectReference(config, reference.path) : void 0);
4326
+ for (const resolved of [...extended, ...projects]) if (resolved && !sources.has(resolved)) pending.push(resolved);
4245
4327
  } catch {}
4246
4328
  }
4247
4329
  return [...sources];
@@ -4277,7 +4359,7 @@ async function retainProviderOutputSources(options) {
4277
4359
  const [index, root] = next.value;
4278
4360
  const requested = paths.filter((path) => path !== root && pathContains$1(root, path));
4279
4361
  const nestedConfiguredRoots = configuredRoots.filter((path) => pathContains$1(root, path));
4280
- const importedSources = await traceImportedSources(requested, root, nestedConfiguredRoots);
4362
+ const importedSources = await traceImportedSources(requested, root, nestedConfiguredRoots, options.aliases);
4281
4363
  const materializedSourcePaths = [...requested, ...importedSources];
4282
4364
  const tsconfigSources = await tsconfigSourcesForPaths(root, materializedSourcePaths);
4283
4365
  materializedSourcePaths.push(...tsconfigSources);
@@ -4365,7 +4447,7 @@ async function retainProviderOutputSources(options) {
4365
4447
  const nestedGeneratedOutput = scopedSegments.some((segment) => ignoredGeneratedDirectories.has(segment));
4366
4448
  const ignoredIndex = scopedSegments.findIndex((segment) => ignoredSourceDirectories.has(segment));
4367
4449
  const packageOutput = scopedSegments[ignoredIndex] === "dist" && !containingConfiguredRoot && (ignoredIndex === 0 ? packageRoots.has(root) : referencedPackages.has(resolve$1(root, ...scopedSegments.slice(0, ignoredIndex))));
4368
- if (nestedGeneratedOutput || ignoredIndex !== -1 && !packageOutput) return requested.some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource)) || [...importedSources].some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource)) || requestedOutputRoots.some((outputRoot) => pathContains$1(outputRoot, resolvedSource)) || configuredOutputClosures.some((outputRoot) => pathContains$1(outputRoot, resolvedSource) && !relative$1(outputRoot, resolvedSource).split(sep).some((segment) => ignoredSourceDirectories.has(segment))) && !nestedConfiguredRoots.some((configuredRoot) => pathContains$1(configuredRoot, resolvedSource)) || nestedConfiguredRoots.some((configuredRoot) => pathContains$1(resolvedSource, configuredRoot));
4450
+ if (nestedGeneratedOutput || ignoredIndex !== -1 && !packageOutput) return requested.some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource) && !crossesIgnoredDirectory(path, resolvedSource)) || [...importedSources].some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource)) || requestedOutputRoots.some((outputRoot) => pathContains$1(outputRoot, resolvedSource)) || configuredOutputClosures.some((outputRoot) => pathContains$1(outputRoot, resolvedSource) && !relative$1(outputRoot, resolvedSource).split(sep).some((segment) => ignoredSourceDirectories.has(segment))) && !nestedConfiguredRoots.some((configuredRoot) => pathContains$1(configuredRoot, resolvedSource)) || nestedConfiguredRoots.some((configuredRoot) => pathContains$1(resolvedSource, configuredRoot));
4369
4451
  return true;
4370
4452
  };
4371
4453
  await copyRetainedSourceTree(root, stagedRoot, (source) => shouldCopySource(resolve$1(source)));
@@ -4885,17 +4967,17 @@ var ProviderOutputCatalog = class {
4885
4967
  }
4886
4968
  this.#restoreDeploymentContribution(entry);
4887
4969
  }
4888
- resetDeploymentContributions(generation) {
4970
+ resetDeploymentContributions(generation, failure) {
4889
4971
  if (!generation) {
4890
4972
  for (const reference of this.#deploymentGenerations) {
4891
4973
  const current = reference.deref();
4892
4974
  if (current) current.valid = false;
4893
4975
  }
4894
4976
  this.#deploymentGenerations.clear();
4895
- for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry);
4977
+ for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry, failure);
4896
4978
  for (const taken of this.#takenDeploymentContributions.values()) {
4897
- if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
4898
- for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback);
4979
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry, failure);
4980
+ for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback, failure);
4899
4981
  }
4900
4982
  this.#deploymentContributions.clear();
4901
4983
  this.#takenDeploymentContributions.clear();
@@ -4904,7 +4986,7 @@ var ProviderOutputCatalog = class {
4904
4986
  generation.valid = false;
4905
4987
  this.#deleteDeploymentGeneration(generation);
4906
4988
  for (const [owner, entries] of this.#deploymentContributions) {
4907
- for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry);
4989
+ for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry, failure);
4908
4990
  const remaining = entries.filter((entry) => entry.generation !== generation);
4909
4991
  if (remaining.length) this.#deploymentContributions.set(owner, remaining);
4910
4992
  else this.#deploymentContributions.delete(owner);
@@ -4912,10 +4994,10 @@ var ProviderOutputCatalog = class {
4912
4994
  for (const [contribution, taken] of this.#takenDeploymentContributions) {
4913
4995
  const invalidatedFallbacks = taken.fallbacks.filter((entry) => entry.generation === generation);
4914
4996
  taken.fallbacks = taken.fallbacks.filter((entry) => entry.generation !== generation);
4915
- for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback);
4997
+ for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback, failure);
4916
4998
  if (taken.entry.generation !== generation) continue;
4917
4999
  this.#takenDeploymentContributions.delete(contribution);
4918
- if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
5000
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry, failure);
4919
5001
  for (const fallback of taken.fallbacks) if (taken.committed) this.#queueDeploymentDiscard(fallback);
4920
5002
  else this.#restoreDeploymentContribution(fallback);
4921
5003
  }
@@ -4958,7 +5040,7 @@ var ProviderOutputCatalog = class {
4958
5040
  const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
4959
5041
  if (failure) throw failure.reason;
4960
5042
  }
4961
- async completeDeploymentContributions(contributions) {
5043
+ async completeDeploymentContributions(contributions, buildFailure) {
4962
5044
  const discarded = this.#pendingDeploymentDiscards.splice(0);
4963
5045
  const completedGenerations = /* @__PURE__ */ new Set();
4964
5046
  for (const contribution of contributions) {
@@ -4968,7 +5050,7 @@ var ProviderOutputCatalog = class {
4968
5050
  const entries = taken.entryDiscarded ? taken.fallbacks : [...taken.fallbacks, taken.entry];
4969
5051
  for (const entry of entries) {
4970
5052
  if (entry.generation) completedGenerations.add(entry.generation);
4971
- if (entry.contribution.discard) discarded.push(entry.contribution.discard());
5053
+ if (entry.contribution.discard) discarded.push(entry.contribution.discard(entry === taken.entry ? buildFailure : void 0));
4972
5054
  }
4973
5055
  }
4974
5056
  for (const generation of completedGenerations) this.#retireDeploymentGeneration(generation);
@@ -5012,9 +5094,9 @@ var ProviderOutputCatalog = class {
5012
5094
  if (reference) this.#deploymentGenerations.delete(reference);
5013
5095
  this.#deploymentGenerationRefs.delete(generation);
5014
5096
  }
5015
- #queueDeploymentDiscard(entry) {
5097
+ #queueDeploymentDiscard(entry, failure) {
5016
5098
  if (!entry.contribution.discard) return;
5017
- const discard = Promise.resolve().then(entry.contribution.discard);
5099
+ const discard = Promise.resolve().then(async () => await entry.contribution.discard?.(failure));
5018
5100
  discard.catch(() => {});
5019
5101
  this.#pendingDeploymentDiscards.push(discard);
5020
5102
  }
@@ -5107,6 +5189,56 @@ const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
5107
5189
  * Later entries are Nuxt layers in Nuxt priority order.
5108
5190
  */
5109
5191
  const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
5192
+ /**
5193
+ * Server Env declarations that ViteHub features add before `hubEnv()` builds the registry, such as the Server Env of
5194
+ * discovered Channels. The application's `env.server` wins field by field.
5195
+ */
5196
+ const VITEHUB_ENV_SERVER = "__vitehubEnvServer";
5197
+ function isPackageServerEnvField(value) {
5198
+ return Array.isArray(value.names);
5199
+ }
5200
+ /** The kind of a contributed field. `hubEnv()` declares it as an optional `env()` with a non-canonical source. */
5201
+ const PACKAGE_SERVER_ENV_FIELD = "vitehub-package-env-field";
5202
+ function packageServerEnvDeclarations(fields) {
5203
+ return Object.fromEntries(Object.entries(fields).flatMap(([key, field]) => {
5204
+ if (!isPackageServerEnvField(field)) {
5205
+ const group = packageServerEnvDeclarations(field);
5206
+ return Object.keys(group).length ? [[key, group]] : [];
5207
+ }
5208
+ return [[key, {
5209
+ kind: PACKAGE_SERVER_ENV_FIELD,
5210
+ names: [...field.names],
5211
+ description: field.description,
5212
+ secret: field.secret,
5213
+ sourcePatterns: field.sourcePatterns
5214
+ }]];
5215
+ }));
5216
+ }
5217
+ function isServerEnvGroup(value) {
5218
+ return isRecord(value) && value.kind !== "env-variable" && value.kind !== "vitehub-package-env-field";
5219
+ }
5220
+ function mergeServerEnvGroups(base, added) {
5221
+ const merged = { ...base };
5222
+ for (const [key, value] of Object.entries(added)) {
5223
+ const current = merged[key];
5224
+ merged[key] = isServerEnvGroup(current) && isServerEnvGroup(value) ? mergeServerEnvGroups(current, value) : current ?? value;
5225
+ }
5226
+ return merged;
5227
+ }
5228
+ /**
5229
+ * Declare in Server Env the host variables that a package reads for its configured provider, under
5230
+ * `env.server.<group>`, so `inspectServerEnv()` and Setup pages list them with a description. Each value is optional:
5231
+ * the package reports a missing value when it uses the provider, and `deployment.json` keeps the deploy rule. The
5232
+ * source claims no canonical name, so the application can also read the variable under its own key. Declarations
5233
+ * that another feature already added at the same path stay, and the application's `env.server` wins field by field.
5234
+ */
5235
+ function contributeServerEnv(config, group, fields) {
5236
+ const declarations = packageServerEnvDeclarations(fields);
5237
+ if (!Object.keys(declarations).length) return;
5238
+ const contributed = Reflect.get(config, VITEHUB_ENV_SERVER);
5239
+ const server = isRecord(contributed) ? contributed : {};
5240
+ Reflect.set(config, VITEHUB_ENV_SERVER, mergeServerEnvGroups(server, { [group]: declarations }));
5241
+ }
5110
5242
  function includesNitroVitePlugin(value) {
5111
5243
  if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
5112
5244
  if (!value || typeof value !== "object") return false;
@@ -6000,23 +6132,23 @@ async function resetProviderDeploymentOutputs(catalog, failure, generation) {
6000
6132
  if (!catalog) return;
6001
6133
  const completedReset = providerDeploymentOutputCompletedResets.get(catalog);
6002
6134
  if (completedReset && failure !== void 0 && completedReset.failures.has(failure)) {
6003
- if (generation) catalog.resetDeploymentContributions(generation);
6135
+ if (generation) catalog.resetDeploymentContributions(generation, failure);
6004
6136
  await completedReset.promise;
6005
6137
  return;
6006
6138
  }
6007
6139
  if (completedReset) providerDeploymentOutputCompletedResets.delete(catalog);
6008
- if (generation) catalog.resetDeploymentContributions(generation);
6140
+ if (generation) catalog.resetDeploymentContributions(generation, failure);
6009
6141
  const active = providerDeploymentOutputFinalizations.get(catalog);
6010
6142
  if (active?.reset) {
6011
6143
  if (failure !== void 0 && !active.reset.failures.has(failure)) {
6012
6144
  active.reset.failures.add(failure);
6013
- if (!generation) catalog.resetDeploymentContributions();
6145
+ if (!generation) catalog.resetDeploymentContributions(void 0, failure);
6014
6146
  }
6015
6147
  providerDeploymentOutputCompletedResets.set(catalog, active.reset);
6016
6148
  await active.reset.promise;
6017
6149
  return;
6018
6150
  }
6019
- if (!generation) catalog.resetDeploymentContributions();
6151
+ if (!generation) catalog.resetDeploymentContributions(void 0, failure);
6020
6152
  if (active && (!generation || active.state.generations.has(generation))) {
6021
6153
  active.state.rollback = true;
6022
6154
  active.controller.abort(internalErrorDiagnostics.INTERNAL_B0039({ message: "Provider Output finalization reset" }));
@@ -6165,7 +6297,7 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
6165
6297
  await catalog.completeDeploymentContributions(contributions);
6166
6298
  } catch (error) {
6167
6299
  if (state.rollback) catalog.rollbackDeploymentContributions(contributions);
6168
- else await catalog.completeDeploymentContributions(contributions);
6300
+ else await catalog.completeDeploymentContributions(contributions, error);
6169
6301
  throw error;
6170
6302
  } finally {
6171
6303
  state.generations.clear();
@@ -6273,6 +6405,61 @@ function workflowDeploymentEnv(workflow) {
6273
6405
  ...schema
6274
6406
  ];
6275
6407
  }
6408
+ // src/server-env.ts
6409
+ const descriptions = {
6410
+ postgresUrl: "The Postgres URL of the database that stores the OpenWorkflow runs.",
6411
+ sqlitePath: "The path of the SQLite file that stores the OpenWorkflow runs.",
6412
+ namespaceId: "The namespace that keeps the runs of this app apart from other apps in the same database.",
6413
+ schema: "The Postgres schema of the OpenWorkflow tables."
6414
+ };
6415
+ function valueField(value, secret, description) {
6416
+ if (value === void 0 || typeof value === "string") return;
6417
+ const names = value.source?.names ?? (value.source?.name ? [value.source.name] : []);
6418
+ return names.length ? {
6419
+ names,
6420
+ secret,
6421
+ description
6422
+ } : void 0;
6423
+ }
6424
+ /**
6425
+ * The Server Env fields that configure OpenWorkflow storage, so Setup pages show them.
6426
+ */
6427
+ function workflowServerEnv(workflow) {
6428
+ if (!workflow || workflow.driver !== "openworkflow") return {};
6429
+ const { postgres, sqlite } = workflow;
6430
+ const namespaceId = {
6431
+ names: ["OPENWORKFLOW_NAMESPACE_ID"],
6432
+ secret: false,
6433
+ description: descriptions.namespaceId
6434
+ };
6435
+ const schema = postgres?.schema ? void 0 : {
6436
+ names: ["OPENWORKFLOW_SCHEMA"],
6437
+ secret: false,
6438
+ description: descriptions.schema
6439
+ };
6440
+ const fields = postgres?.url !== void 0 ? {
6441
+ postgresUrl: valueField(postgres.url, true, descriptions.postgresUrl),
6442
+ namespaceId: postgres.namespaceId ? void 0 : namespaceId,
6443
+ schema
6444
+ } : sqlite?.path !== void 0 ? {
6445
+ sqlitePath: valueField(sqlite.path, false, descriptions.sqlitePath),
6446
+ namespaceId: sqlite.namespaceId ? void 0 : namespaceId
6447
+ } : {
6448
+ sqlitePath: {
6449
+ names: ["OPENWORKFLOW_SQLITE_PATH"],
6450
+ secret: false,
6451
+ description: descriptions.sqlitePath
6452
+ },
6453
+ postgresUrl: {
6454
+ names: ["OPENWORKFLOW_POSTGRES_URL"],
6455
+ secret: true,
6456
+ description: descriptions.postgresUrl
6457
+ },
6458
+ namespaceId: postgres?.namespaceId && sqlite?.namespaceId ? void 0 : namespaceId,
6459
+ schema
6460
+ };
6461
+ return Object.fromEntries(Object.entries(fields).filter((entry) => entry[1] !== void 0));
6462
+ }
6276
6463
  // ../internal/src/definition-catalog.ts
6277
6464
  const sourceFilePattern$2 = /\.(?:c|m)?[jt]sx?$/i;
6278
6465
  const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
@@ -7043,6 +7230,17 @@ const cloudflareWorkflowWranglerConfigKeys = [
7043
7230
  "observability",
7044
7231
  "workflows"
7045
7232
  ];
7233
+ const cloudflareConcurrencyWranglerOwnership = {
7234
+ arrays: { migrations: {
7235
+ key: "tag",
7236
+ preserveOrder: true,
7237
+ values: [cloudflareConcurrencyMigrationTag]
7238
+ } },
7239
+ objects: { durable_objects: { arrays: { bindings: {
7240
+ key: "name",
7241
+ values: [cloudflareConcurrencyBinding]
7242
+ } } } }
7243
+ };
7046
7244
  const cloudflareWorkflowWrapperImport = `import worker, { runViteHubWorkflowDefinition } from "./worker.mjs"`;
7047
7245
  const nodeBuiltinExternals = [.../* @__PURE__ */ new Set([
7048
7246
  "node:*",
@@ -7175,21 +7373,21 @@ async function loadVercelWorkflowBuilders() {
7175
7373
  return await import("@workflow/builders");
7176
7374
  }
7177
7375
  /** Workflow and step IDs are source paths relative to `idRoot`, which is `rootDir` unless a copy of the sources must keep the IDs of another path. */
7178
- async function createVercelWorkflowTransformPlugin(rootDir, idRoot = rootDir) {
7376
+ async function createVercelWorkflowTransformPlugin(rootDir, idRoot = rootDir, include = () => true, mode = "step") {
7179
7377
  const builders = await loadVercelWorkflowBuilders();
7180
7378
  if (!builders) return void 0;
7181
7379
  const workingDir = idRoot.replace(/\\/g, "/").replace(/\/$/, "");
7182
7380
  return {
7183
7381
  name: "vitehub-vercel-workflow-transform",
7184
7382
  async load(id) {
7185
- if (!/\.[cm]?[jt]sx?$/.test(id) || !isAbsolute(id)) return;
7383
+ if (!/\.[cm]?[jt]sx?$/.test(id) || !isAbsolute(id) || !include(id.replaceAll("\\", "/"))) return;
7186
7384
  const source = await readFile(id, "utf8");
7187
7385
  if (!builders.shouldTransformFile(id, builders.detectWorkflowPatterns(source))) return;
7188
7386
  const file = id.replace(/\\/g, "/");
7189
7387
  const filename = relative$1(workingDir, file).replace(/\\/g, "/").split("/").filter((segment) => segment !== "..").join("/");
7190
7388
  const code = source.replace(/require\(\s*(['"])(?:server|client)-only\1\s*\)/g, "void 0");
7191
7389
  return {
7192
- code: (await builders.applySwcTransform(filename, code, "workflow", id, rootDir)).code,
7390
+ code: (await builders.applySwcTransform(filename, code, mode, id, rootDir)).code,
7193
7391
  moduleType: id.endsWith(".tsx") ? "tsx" : id.endsWith(".jsx") ? "jsx" : "js"
7194
7392
  };
7195
7393
  }
@@ -7231,6 +7429,72 @@ async function withVercelWorkflowPackageLink(rootDir, run) {
7231
7429
  if (ownsLink) await rm(target, { force: true });
7232
7430
  }
7233
7431
  }
7432
+ const nativeKeyPattern = /\bnative\s*(?::|(?=[,}]))/;
7433
+ const useWorkflowDirectivePattern = /^\s*["']use workflow["'];?/m;
7434
+ function parseWorkflowModule(file) {
7435
+ return buildSync({
7436
+ bundle: false,
7437
+ format: "esm",
7438
+ legalComments: "none",
7439
+ metafile: true,
7440
+ minifySyntax: true,
7441
+ stdin: {
7442
+ contents: readFileSync(file, "utf8"),
7443
+ loader: /\.[cm]?[jt]sx$/.test(file) ? "tsx" : "ts",
7444
+ sourcefile: file
7445
+ },
7446
+ write: false
7447
+ });
7448
+ }
7449
+ function declaresVercelNativeWorkflow(file) {
7450
+ return declaresWorkflowOption(file, "native");
7451
+ }
7452
+ function declaresWorkflowOption(file, option) {
7453
+ const module = scanModule(readFileSync(file, "utf8"), file);
7454
+ let definition = defaultExportExpression(module);
7455
+ const bindings = module.program.body.flatMap((statement) => statement.type === "VariableDeclaration" ? statement.declarations : []);
7456
+ const resolveBinding = (expression) => {
7457
+ const visited = /* @__PURE__ */ new Set();
7458
+ while (expression?.type === "Identifier") {
7459
+ const name = expression.name;
7460
+ if (visited.has(name)) return;
7461
+ visited.add(name);
7462
+ const init = bindings.find((binding) => binding.id.type === "Identifier" && binding.id.name === name)?.init;
7463
+ expression = init ? unwrapExpression(init) : void 0;
7464
+ }
7465
+ return expression;
7466
+ };
7467
+ definition = resolveBinding(definition);
7468
+ if (definition?.type === "CallExpression") definition = resolveBinding(argumentExpression(definition.arguments[0]));
7469
+ return definition?.type === "ObjectExpression" && Boolean(findProperty(definition, option));
7470
+ }
7471
+ function declaresWorkflowConcurrency(definition) {
7472
+ return !isAgentWorkflowDefinition(definition) && /\.(?:c|m)?[jt]sx?$/i.test(definition.handler) && existsSync(definition.handler) && declaresWorkflowOption(definition.handler, "concurrency");
7473
+ }
7474
+ function usesCloudflareConcurrency(definitions) {
7475
+ return definitions.some(declaresWorkflowConcurrency);
7476
+ }
7477
+ function addCloudflareConcurrencyWrangler(wrangler) {
7478
+ const durableObjects = record(wrangler.durable_objects);
7479
+ const bindings = Array.isArray(durableObjects.bindings) ? [...durableObjects.bindings].map(record) : [];
7480
+ if (!bindings.some((entry) => entry.name === "VITEHUB_WORKFLOW_CONCURRENCY")) bindings.push({
7481
+ class_name: cloudflareConcurrencyClassName,
7482
+ name: cloudflareConcurrencyBinding
7483
+ });
7484
+ const migrations = Array.isArray(wrangler.migrations) ? [...wrangler.migrations].map(record) : [];
7485
+ const declared = (key) => migrations.some((entry) => Array.isArray(entry[key]) && entry[key].includes("ViteHubWorkflowConcurrency"));
7486
+ if (!declared("new_sqlite_classes") && !declared("new_classes")) migrations.push({
7487
+ new_sqlite_classes: [cloudflareConcurrencyClassName],
7488
+ tag: cloudflareConcurrencyMigrationTag
7489
+ });
7490
+ return {
7491
+ durable_objects: {
7492
+ ...durableObjects,
7493
+ bindings
7494
+ },
7495
+ migrations
7496
+ };
7497
+ }
7234
7498
  /**
7235
7499
  * Whether a Workflow builds as a native Vercel Workflow. It throws when one does and the app did not install the
7236
7500
  * Workflow DevKit, so every native build path reports the same coded error.
@@ -7252,29 +7516,17 @@ function hasVercelNativeWorkflowEntry(rootDir, definitions, aliases = {}, native
7252
7516
  }
7253
7517
  return;
7254
7518
  }
7255
- const source = readFileSync(file, "utf8");
7256
- const parsed = buildSync({
7257
- bundle: false,
7258
- format: "esm",
7259
- legalComments: "none",
7260
- metafile: true,
7261
- minifySyntax: true,
7262
- stdin: {
7263
- contents: source,
7264
- loader: /\.[cm]?[jt]sx$/.test(file) ? "tsx" : "ts",
7265
- sourcefile: file
7266
- },
7267
- write: false
7268
- });
7519
+ if (!/\.(?:c|m)?[jt]sx?$/.test(file)) return;
7520
+ const parsed = parseWorkflowModule(file);
7269
7521
  const parsedSource = parsed.outputFiles[0].text;
7270
- if (/^\s*["']use workflow["'];?/m.test(parsedSource)) {
7522
+ if (useWorkflowDirectivePattern.test(parsedSource)) {
7271
7523
  if (!definitionDirs.some((definitionDir) => {
7272
7524
  const path = relative$1(definitionDir, file);
7273
7525
  return !path.startsWith("..") && !isAbsolute(path);
7274
7526
  })) throw workflowErrorDiagnostics.WORKFLOW_R0004({ message: `Native Vercel workflow entry ${JSON.stringify(relative$1(rootDir, file))} must be colocated with its discovered workflow definition.` });
7275
7527
  hasNativeEntry = true;
7276
7528
  }
7277
- if (definitionHandlers.has(file) && !/\bnative\s*(?::|(?=[,}]))/.test(parsedSource)) return;
7529
+ if (definitionHandlers.has(file) && !nativeKeyPattern.test(parsedSource)) return;
7278
7530
  const imports = Object.values(parsed.metafile.outputs).flatMap((output) => output.imports);
7279
7531
  for (const { path: specifier } of imports) {
7280
7532
  const alias = Object.entries(aliases).find(([find]) => specifier === find || specifier.startsWith(`${find}/`));
@@ -7571,6 +7823,8 @@ async function buildVercelNativeWorkflowOutput(rootDir, definitions, aliases = {
7571
7823
  keepNames: true,
7572
7824
  platform: "node",
7573
7825
  plugins: [
7826
+ createViteHubEntrySideEffectsPlugin(),
7827
+ createVercelStepAliasPlugin(aliases),
7574
7828
  createPseudoPackagePlugin(),
7575
7829
  createOptionalPackagesEsbuildPlugin(rootDir),
7576
7830
  {
@@ -7620,7 +7874,7 @@ async function buildVercelNativeWorkflowOutput(rootDir, definitions, aliases = {
7620
7874
  await writeFile(outputConfigFile, `${JSON.stringify({
7621
7875
  ...workflowConfig,
7622
7876
  ...viteHubConfig,
7623
- routes: [...workflowRoutes, ...viteHubRoutes]
7877
+ routes: [...new Map([...workflowRoutes, ...viteHubRoutes].map((route) => [JSON.stringify(route), route])).values()]
7624
7878
  }, null, 2)}\n`, "utf8");
7625
7879
  const generatedFiles = await collectVercelNativeWorkflowFiles(workflowRoot);
7626
7880
  const ownedFiles = Object.fromEntries(Object.entries(generatedFiles).filter(([file, digest]) => previousFiles[file] !== digest || previousFiles[file] === previousOwnership?.files[file]));
@@ -7642,6 +7896,59 @@ async function buildVercelNativeWorkflowOutput(rootDir, definitions, aliases = {
7642
7896
  throw error;
7643
7897
  }
7644
7898
  }
7899
+ function createVercelStepAliasPlugin(aliases) {
7900
+ const entries = Object.entries(aliases).map(([key, replacement]) => ({
7901
+ find: key.split(encodedAliasPrefixMarker)[0].split(encodedAliasExactMarker)[0],
7902
+ prefix: key.includes(encodedAliasPrefixMarker),
7903
+ replacement
7904
+ }));
7905
+ return {
7906
+ name: "vitehub-workflow-aliases",
7907
+ setup(build) {
7908
+ build.onResolve({ filter: /.*/ }, (args) => {
7909
+ if (args.pluginData?.vitehubWorkflowAliasResolved) return;
7910
+ const specifier = args.path.split("?", 1)[0];
7911
+ const alias = entries.find(({ find, prefix }) => prefix ? specifier.startsWith(find) : specifier === find);
7912
+ if (!alias) return;
7913
+ const replacement = alias.prefix ? `${alias.replacement.replace(/[\\/]$/, "")}/` : alias.replacement;
7914
+ return build.resolve(`${replacement}${args.path.slice(alias.find.length)}`, {
7915
+ importer: args.importer,
7916
+ kind: args.kind,
7917
+ namespace: args.namespace,
7918
+ resolveDir: args.resolveDir,
7919
+ pluginData: {
7920
+ ...args.pluginData,
7921
+ vitehubWorkflowAliasResolved: true
7922
+ }
7923
+ });
7924
+ });
7925
+ }
7926
+ };
7927
+ }
7928
+ function createViteHubEntrySideEffectsPlugin() {
7929
+ return {
7930
+ name: "vitehub-workflow-entry-side-effects",
7931
+ setup(build) {
7932
+ build.onResolve({ filter: /^vite-hub(?:\/|$)/ }, async (args) => {
7933
+ if (args.pluginData?.vitehubWorkflowEntryResolved) return;
7934
+ const result = await build.resolve(args.path, {
7935
+ importer: args.importer,
7936
+ kind: args.kind,
7937
+ namespace: args.namespace,
7938
+ resolveDir: args.resolveDir,
7939
+ pluginData: {
7940
+ ...args.pluginData,
7941
+ vitehubWorkflowEntryResolved: true
7942
+ }
7943
+ });
7944
+ return result.errors.length ? result : {
7945
+ ...result,
7946
+ sideEffects: true
7947
+ };
7948
+ });
7949
+ }
7950
+ };
7951
+ }
7645
7952
  function resolveWorkflowUserAppEntry(rootDir, entry) {
7646
7953
  return resolveUserAppEntry(rootDir, entry === true ? {} : { names: [entry] });
7647
7954
  }
@@ -7718,7 +8025,7 @@ function renderCloudflareWorkflowEntrypoint(definition, legacyAliases) {
7718
8025
  ""
7719
8026
  ].join("\n");
7720
8027
  }
7721
- function createCloudflareWorkflowNitroPlugin(entryFile, definitions) {
8028
+ function createCloudflareWorkflowNitroPlugin(entryFile, definitions, concurrency = false) {
7722
8029
  const moduleId = "virtual:vitehub-workflow-cloudflare-exports";
7723
8030
  const legacyAliases = getUniqueLegacyCloudflareWorkflowAliases(definitions);
7724
8031
  const resolvedModuleId = `\0${moduleId}`;
@@ -7749,6 +8056,7 @@ function createCloudflareWorkflowNitroPlugin(entryFile, definitions) {
7749
8056
  "",
7750
8057
  "installViteHubWorkflowRuntime()",
7751
8058
  "",
8059
+ ...concurrency ? [`export { ${cloudflareConcurrencyClassName} } from ${JSON.stringify(workflowRuntimeModule("cloudflare-concurrency"))}`, ""] : [],
7752
8060
  ...definitions.map((definition) => renderCloudflareWorkflowEntrypoint(definition, legacyAliases))
7753
8061
  ].join("\n");
7754
8062
  }
@@ -7756,7 +8064,7 @@ function createCloudflareWorkflowNitroPlugin(entryFile, definitions) {
7756
8064
  renderChunk(code, chunk) {
7757
8065
  if (!chunk.isEntry || chunk.fileName !== "index.mjs" && chunk.fileName !== "index.js") return null;
7758
8066
  return {
7759
- code: `${code}\nexport { ${definitions.flatMap((definition) => [getCloudflareWorkflowClassName(definition.name), ...legacyAliases.get(definition.name) ? [legacyAliases.get(definition.name)] : []]).join(", ")} } from './${fileName}'\n`,
8067
+ code: `${code}\nexport { ${definitions.flatMap((definition) => [getCloudflareWorkflowClassName(definition.name), ...legacyAliases.get(definition.name) ? [legacyAliases.get(definition.name)] : []]).concat(concurrency ? [cloudflareConcurrencyClassName] : []).join(", ")} } from './${fileName}'\n`,
7760
8068
  map: null
7761
8069
  };
7762
8070
  }
@@ -7805,11 +8113,13 @@ async function createCloudflareWorkflowNitroConfig(options) {
7805
8113
  const existingWorkflows = Array.isArray(wrangler.workflows) ? [...wrangler.workflows] : [];
7806
8114
  for (const workflow of workflows || []) if (!existingWorkflows.some((entry) => record(entry).binding === workflow.binding && record(entry).class_name === workflow.class_name && record(entry).name === workflow.name)) existingWorkflows.push(workflow);
7807
8115
  wrangler.workflows = existingWorkflows;
8116
+ const concurrency = usesCloudflareConcurrency(artifacts.providerDefinitions);
8117
+ if (concurrency) Object.assign(wrangler, addCloudflareConcurrencyWrangler(wrangler));
7808
8118
  cloudflare.wrangler = wrangler;
7809
8119
  nitro.cloudflare = cloudflare;
7810
8120
  const rollupConfig = { ...record(nitro.rollupConfig) };
7811
8121
  const plugins = Array.isArray(rollupConfig.plugins) ? [...rollupConfig.plugins] : [];
7812
- if (!plugins.some((plugin) => record(plugin).name === "vitehub-workflow-cloudflare-exports")) plugins.push(createCloudflareWorkflowNitroPlugin(artifacts.cloudflareWorkerFile, artifacts.providerDefinitions));
8122
+ if (!plugins.some((plugin) => record(plugin).name === "vitehub-workflow-cloudflare-exports")) plugins.push(createCloudflareWorkflowNitroPlugin(artifacts.cloudflareWorkerFile, artifacts.providerDefinitions, concurrency));
7813
8123
  rollupConfig.plugins = plugins;
7814
8124
  rollupConfig.external = mergeCloudflareWorkersExternal(rollupConfig.external);
7815
8125
  nitro.rollupConfig = rollupConfig;
@@ -7855,10 +8165,19 @@ function renderAgentWorkflowRegistryEntry(registryFile, definition, retainedAgen
7855
8165
  ` }, ${definition.source === "agent-workflow-recovery" ? "{ internalAgentInvocationRecovery: true }" : "{}"}),`
7856
8166
  ].join("\n");
7857
8167
  }
8168
+ function isAgentWorkflowDefinition(definition) {
8169
+ return definition.source === "agent-workflow" || definition.source === "agent-workflow-recovery";
8170
+ }
8171
+ function hasWorkflowIndexHandler(definition) {
8172
+ return definition.steps !== void 0 && /\.(?:c|m)?[jt]s$/i.test(definition.handler);
8173
+ }
7858
8174
  function getGeneratedVercelWorkflowExport(definition) {
7859
- if (!definition.steps?.length || /\.(?:c|m)?[jt]s$/i.test(definition.handler)) return;
8175
+ if (isAgentWorkflowDefinition(definition) || hasWorkflowIndexHandler(definition) || definition.steps?.length === 0) return;
7860
8176
  return `${getCloudflareWorkflowClassName(definition.name)}Native`;
7861
8177
  }
8178
+ function generatedVercelWorkflowFileName(name) {
8179
+ return createHash("sha256").update(name).digest("hex");
8180
+ }
7862
8181
  /** `@workflow/core` keeps the `sleep()` implementation of the Workflow VM on `globalThis` under this registered symbol. */
7863
8182
  const vercelWorkflowSleepSymbol = "WORKFLOW_SLEEP";
7864
8183
  function renderVercelNativeStep(name, implementation, step, options) {
@@ -7868,8 +8187,21 @@ async function createVercelNativeWorkflowContents(definition) {
7868
8187
  const imports = [];
7869
8188
  const workflows = [];
7870
8189
  const workflowExport = getGeneratedVercelWorkflowExport(definition);
8190
+ if (!workflowExport) return "";
8191
+ const startAt = `context[${JSON.stringify(workflowStartAtKey)}]`;
8192
+ const waitForStart = ` if (typeof ${startAt} === "number") await globalThis[Symbol.for(${JSON.stringify(vercelWorkflowSleepSymbol)})](new Date(${startAt}))`;
7871
8193
  const steps = definition.steps;
7872
- if (!workflowExport || !steps) return "";
8194
+ if (!steps) {
8195
+ const module = `${workflowExport}Module`;
8196
+ const step = `${workflowExport}Step`;
8197
+ return [
8198
+ `import * as ${module} from ${JSON.stringify(definition.handler)}`,
8199
+ "",
8200
+ `async function ${step}(payload) {\n "use step"\n const { getWorkflowMetadata } = await import("workflow")\n const { runWorkflowRootStep } = await import(${JSON.stringify(workflowRuntimeModule("execute"))})\n return await runWorkflowRootStep({ id: getWorkflowMetadata().workflowRunId, name: ${JSON.stringify(definition.name)}, payload, provider: "vercel" }, ${module}.default)\n}`,
8201
+ `export async function ${workflowExport}(context) {\n "use workflow"\n${waitForStart}\n return await ${step}(context.payload)\n}`,
8202
+ ""
8203
+ ].join("\n");
8204
+ }
7873
8205
  const stepOptions = await Promise.all(steps.map(readWorkflowStepOptions));
7874
8206
  const stepNames = steps.map((step, index) => {
7875
8207
  const implementation = `${workflowExport}Step${index}Implementation`;
@@ -7878,8 +8210,7 @@ async function createVercelNativeWorkflowContents(definition) {
7878
8210
  workflows.push(renderVercelNativeStep(name, implementation, `${definition.name}/${relative$1(definition.handler, step)}`, stepOptions[index]));
7879
8211
  return name;
7880
8212
  });
7881
- const startAt = `context[${JSON.stringify(workflowStartAtKey)}]`;
7882
- workflows.push(`export async function ${workflowExport}(context) {\n "use workflow"\n if (typeof ${startAt} === "number") await globalThis[Symbol.for(${JSON.stringify(vercelWorkflowSleepSymbol)})](new Date(${startAt}))\n let value = context.payload\n${stepNames.map((name) => ` value = await ${name}(value)`).join("\n")}\n return value\n}`);
8213
+ workflows.push(`export async function ${workflowExport}(context) {\n "use workflow"\n${waitForStart}\n let value = context.payload\n${stepNames.map((name) => ` value = await ${name}(value)`).join("\n")}\n return value\n}`);
7883
8214
  return [
7884
8215
  ...imports,
7885
8216
  "",
@@ -7888,30 +8219,44 @@ async function createVercelNativeWorkflowContents(definition) {
7888
8219
  ].join("\n");
7889
8220
  }
7890
8221
  function renderWorkflowRegistryEntry(registryFile, definition, vercelNativeFiles = {}, retainedAgentInstructions) {
7891
- if (definition.source === "agent-workflow" || definition.source === "agent-workflow-recovery") return renderAgentWorkflowRegistryEntry(registryFile, definition, retainedAgentInstructions);
7892
- if (!definition.steps) return ` [${JSON.stringify(definition.name)}]: async () => ${renderRegistryImport(registryFile, definition.handler)},`;
8222
+ if (isAgentWorkflowDefinition(definition)) return renderAgentWorkflowRegistryEntry(registryFile, definition, retainedAgentInstructions);
8223
+ const nativeExport = getGeneratedVercelWorkflowExport(definition);
8224
+ const vercelNativeFile = Object.hasOwn(vercelNativeFiles, definition.name) ? vercelNativeFiles[definition.name] : void 0;
8225
+ const nativeReference = nativeExport && vercelNativeFile ? `const native = Object.assign(async () => (await import(${JSON.stringify(workflowRuntimeModule("execute"))})).rejectDirectGeneratedWorkflowCall(), ${JSON.stringify({
8226
+ workflowId: `workflow//./.vitehub/workflow/vercel-native/${generatedVercelWorkflowFileName(definition.name)}//${nativeExport}`,
8227
+ [generatedNativeEntryKey]: true,
8228
+ ...definition.steps ? {} : { [generatedNativeRootStepKey]: true }
8229
+ })})` : "";
8230
+ if (!definition.steps) {
8231
+ if (!nativeReference) return ` [${JSON.stringify(definition.name)}]: async () => ${renderRegistryImport(registryFile, definition.handler)},`;
8232
+ return [
8233
+ ` [${JSON.stringify(definition.name)}]: async () => {`,
8234
+ ` const loaded = await ${renderRegistryImport(registryFile, definition.handler)}`,
8235
+ " if (typeof loaded.default?.handler !== \"function\" || loaded.default.native) return loaded",
8236
+ ` ${nativeReference}`,
8237
+ " return { ...loaded, default: { ...loaded.default, native } }",
8238
+ " },"
8239
+ ].join("\n");
8240
+ }
7893
8241
  const workflowDirectory = /\.(?:c|m)?[jt]s$/i.test(definition.handler) ? dirname$1(definition.handler) : definition.handler;
7894
8242
  const stepImports = definition.steps.map((step) => {
7895
8243
  const stepName = relative$1(workflowDirectory, step);
7896
8244
  return `{ name: ${JSON.stringify(stepName)}, ...await ${renderRegistryImport(registryFile, step)}.then(step => ({ options: { retries: step.retries, timeout: step.timeout }, run: step.default })) }`;
7897
8245
  });
7898
- const hasIndex = /\.(?:c|m)?[jt]s$/i.test(definition.handler);
8246
+ const hasIndex = hasWorkflowIndexHandler(definition);
7899
8247
  const indexImport = hasIndex ? `const index = await ${renderRegistryImport(registryFile, definition.handler)}` : "";
7900
- const nativeExport = getGeneratedVercelWorkflowExport(definition);
7901
- const vercelNativeFile = vercelNativeFiles[definition.name];
7902
- const nativeImport = nativeExport && vercelNativeFile ? `const native = (await import(${JSON.stringify(createImportPath(registryFile, vercelNativeFile))})).${nativeExport}\n native.workflowId ||= ${JSON.stringify(`workflow//./.vitehub/workflow/vercel-native//${nativeExport}`)}\n native[${JSON.stringify(generatedNativeEntryKey)}] = true` : "";
7903
8248
  const handler = hasIndex ? `index.default?.handler ? index.default : takeInlineWorkflowDefinitionForModule(${JSON.stringify(definition.name)}, index) || { handler: index.default }` : "{ handler: async ({ payload, steps }) => { let value = payload; for (const step of Object.values(steps)) value = await step(value); return value } }";
7904
8249
  return [
7905
8250
  ` [${JSON.stringify(definition.name)}]: async () => {`,
7906
8251
  ` const cached = registryEntryCache.get(${JSON.stringify(definition.name)})`,
7907
8252
  " if (cached) return cached",
7908
8253
  indexImport ? ` ${indexImport}` : "",
7909
- nativeImport ? ` ${nativeImport}` : "",
8254
+ nativeReference ? ` ${nativeReference}` : "",
7910
8255
  ` const steps = [${stepImports.join(", ")}]`,
7911
8256
  ` const definition = ${handler}`,
7912
8257
  " const entry = {",
7913
8258
  " ...definition,",
7914
- ` rootStep: false,${nativeImport ? " native," : ""}`,
8259
+ ` rootStep: false,${nativeReference ? " native," : ""}`,
7915
8260
  " handler: async (context) => {",
7916
8261
  " const workflowSteps = createWorkflowSteps(context, steps)",
7917
8262
  " return await definition.handler({ ...context, steps: workflowSteps })",
@@ -7999,7 +8344,7 @@ function createWorkflowRegistryContents(registryFile, definitions, importBases =
7999
8344
  ""
8000
8345
  ].join("\n");
8001
8346
  }
8002
- function createWorkflowRegistryIndexContents(definitions) {
8347
+ function createWorkflowRegistryIndexContents(definitions, requireVercelNative) {
8003
8348
  return [
8004
8349
  `const loadRegistryRuntime = () => import(${JSON.stringify(`./${generatedRegistryRuntimeFileName}`)})`,
8005
8350
  "",
@@ -8009,6 +8354,7 @@ function createWorkflowRegistryIndexContents(definitions) {
8009
8354
  return definition.source === "agent-workflow-recovery" ? ` [${JSON.stringify(definition.name)}]: Object.assign(${loader}, { internalAgentInvocationRecovery: true }),` : ` [${JSON.stringify(definition.name)}]: ${loader},`;
8010
8355
  }),
8011
8356
  "}",
8357
+ ...requireVercelNative ? [`Object.defineProperty(registry, Symbol.for(${JSON.stringify(vercelNativeRegistryKey)}), { value: true })`] : [],
8012
8358
  "",
8013
8359
  "export default registry",
8014
8360
  ""
@@ -8019,6 +8365,7 @@ function renderCloudflareWorkerWrapper(definitions) {
8019
8365
  return [
8020
8366
  definitions.length ? `import { WorkflowEntrypoint, waitUntil as viteHubWaitUntil } from "cloudflare:workers"` : `import { waitUntil as viteHubWaitUntil } from "cloudflare:workers"`,
8021
8367
  cloudflareWorkflowWrapperImport,
8368
+ ...usesCloudflareConcurrency(definitions) ? [`export { ${cloudflareConcurrencyClassName} } from "./worker.mjs"`] : [],
8022
8369
  "",
8023
8370
  ...definitions.map((definition) => renderCloudflareWorkflowEntrypoint(definition, legacyAliases)),
8024
8371
  "const viteHubWorker = {",
@@ -8032,7 +8379,7 @@ function renderCloudflareWorkerWrapper(definitions) {
8032
8379
  ""
8033
8380
  ].join("\n");
8034
8381
  }
8035
- function renderProviderEntry(spec, entryFile, userAppEntry, serializedWorkflowConfig, workflowImportBase, framework) {
8382
+ function renderProviderEntry(spec, entryFile, userAppEntry, serializedWorkflowConfig, workflowImportBase, framework, concurrency = false) {
8036
8383
  const installVercelWorkflowRuntime = spec.name === "vercel" && framework;
8037
8384
  const imports = [
8038
8385
  `import { ${spec.factory}${spec.name === "cloudflare" ? ", installWorkflowCloudflareRuntime" : ""}${installVercelWorkflowRuntime ? ", setVercelWorkflowRuntimeModules" : ""} } from ${JSON.stringify(workflowRuntimeModule(spec.runtimeModule))}`,
@@ -8043,6 +8390,7 @@ function renderProviderEntry(spec, entryFile, userAppEntry, serializedWorkflowCo
8043
8390
  if (userAppEntry) imports.push(`import workflowApp from ${JSON.stringify(createImportPath(entryFile, userAppEntry))}`);
8044
8391
  const cloudflareDispatcher = spec.name === "cloudflare" ? [
8045
8392
  "",
8393
+ ...concurrency ? [`export { ${cloudflareConcurrencyClassName} } from ${JSON.stringify(workflowRuntimeModule("cloudflare-concurrency"))}`, ""] : [],
8046
8394
  "export function installViteHubWorkflowRuntime() {",
8047
8395
  " installWorkflowCloudflareRuntime({ registry: workflowRegistry, workflow: workflowConfig })",
8048
8396
  "}",
@@ -8067,29 +8415,42 @@ function renderProviderEntry(spec, entryFile, userAppEntry, serializedWorkflowCo
8067
8415
  ""
8068
8416
  ].filter(Boolean).join("\n");
8069
8417
  }
8070
- async function writeProviderEntries(rootDir, workflow, importBases = {}, serverDirs, includeUserAppEntry = true, transformRegistry, definitionRootDir = rootDir, generatedDir = ensureGeneratedDir(rootDir, productName), retainedAgentInstructions) {
8071
- await mkdir(generatedDir, { recursive: true });
8072
- const registryFile = resolve$1(generatedDir, generatedRegistryFileName);
8073
- const definitions = discoverWorkflowDefinitions({
8074
- rootDir: definitionRootDir,
8075
- serverDirs
8076
- });
8077
- const providerDefinitions = withAgentInvocationRecoveryDefinitions(definitions);
8078
- const userAppEntry = includeUserAppEntry ? resolveWorkflowUserAppEntry(definitionRootDir, includeUserAppEntry) : void 0;
8079
- const cloudflareWorkflowConfig = resolveWorkflowConfig(workflow, "cloudflare");
8418
+ /**
8419
+ * Writes the generated entries for single-file Workflows and folders with only numbered steps, into
8420
+ * `<generatedDir>/vercel-native`. It returns the entry file of each Workflow name.
8421
+ */
8422
+ async function writeVercelNativeWorkflowFiles(generatedDir, definitions) {
8080
8423
  const vercelNativeDir = resolve$1(generatedDir, "vercel-native");
8081
- const nativeDefinitions = definitions.filter((definition) => getGeneratedVercelWorkflowExport(definition));
8424
+ const nativeDefinitions = definitions.filter((definition) => {
8425
+ if (!getGeneratedVercelWorkflowExport(definition)) return false;
8426
+ if (definition.steps) return true;
8427
+ const parsed = parseWorkflowModule(definition.handler);
8428
+ return Object.values(parsed.metafile.outputs).some((output) => output.exports.includes("default")) && !declaresVercelNativeWorkflow(definition.handler);
8429
+ });
8082
8430
  await rm(resolve$1(generatedDir, "vercel-native.mjs"), { force: true });
8083
8431
  await rm(vercelNativeDir, {
8084
8432
  force: true,
8085
8433
  recursive: true
8086
8434
  });
8087
- const vercelNativeFiles = Object.fromEntries(nativeDefinitions.map((definition) => [definition.name, resolve$1(vercelNativeDir, `${createHash("sha256").update(definition.name).digest("hex")}.mjs`)]));
8435
+ const vercelNativeFiles = Object.fromEntries(nativeDefinitions.map((definition) => [definition.name, resolve$1(vercelNativeDir, `${generatedVercelWorkflowFileName(definition.name)}.mjs`)]));
8088
8436
  if (nativeDefinitions.length) await mkdir(vercelNativeDir, { recursive: true });
8089
8437
  await Promise.all(nativeDefinitions.map(async (definition) => {
8090
8438
  const nativeFile = vercelNativeFiles[definition.name];
8091
8439
  await writeFile(nativeFile, await createVercelNativeWorkflowContents(definition), "utf8");
8092
8440
  }));
8441
+ return vercelNativeFiles;
8442
+ }
8443
+ async function writeProviderEntries(rootDir, workflow, importBases = {}, serverDirs, includeUserAppEntry = true, transformRegistry, definitionRootDir = rootDir, generatedDir = ensureGeneratedDir(rootDir, productName), retainedAgentInstructions, requireVercelNative = false) {
8444
+ await mkdir(generatedDir, { recursive: true });
8445
+ const registryFile = resolve$1(generatedDir, generatedRegistryFileName);
8446
+ const definitions = discoverWorkflowDefinitions({
8447
+ rootDir: definitionRootDir,
8448
+ serverDirs
8449
+ });
8450
+ const providerDefinitions = withAgentInvocationRecoveryDefinitions(definitions);
8451
+ const userAppEntry = includeUserAppEntry ? resolveWorkflowUserAppEntry(definitionRootDir, includeUserAppEntry) : void 0;
8452
+ const cloudflareWorkflowConfig = resolveWorkflowConfig(workflow, "cloudflare");
8453
+ const vercelNativeFiles = await writeVercelNativeWorkflowFiles(generatedDir, definitions);
8093
8454
  await Promise.all(definitions.filter((definition) => !getGeneratedVercelWorkflowExport(definition)).flatMap((definition) => definition.steps ?? []).map(async (step) => await readWorkflowStepOptions(step)));
8094
8455
  const registryRuntimeFile = resolve$1(generatedDir, generatedRegistryRuntimeFileName);
8095
8456
  const agentModules = importBases.agent ?? (providerDefinitions.some((definition) => definition.source === "agent-workflow") ? await installedAgentWorkflowModules(rootDir) : void 0);
@@ -8098,7 +8459,7 @@ async function writeProviderEntries(rootDir, workflow, importBases = {}, serverD
8098
8459
  agent: agentModules
8099
8460
  }, vercelNativeFiles, retainedAgentInstructions);
8100
8461
  await writeFile(registryRuntimeFile, transformRegistry ? await transformRegistry(registryContents, registryRuntimeFile) : registryContents, "utf8");
8101
- await writeFile(registryFile, createWorkflowRegistryIndexContents(providerDefinitions), "utf8");
8462
+ await writeFile(registryFile, createWorkflowRegistryIndexContents(providerDefinitions, requireVercelNative), "utf8");
8102
8463
  const entryFiles = {
8103
8464
  cloudflare: "",
8104
8465
  openworkflow: "",
@@ -8108,7 +8469,7 @@ async function writeProviderEntries(rootDir, workflow, importBases = {}, serverD
8108
8469
  const entryFile = resolve$1(generatedDir, spec.entryFile);
8109
8470
  const workflowConfig = spec.name === "cloudflare" ? cloudflareWorkflowConfig : resolveWorkflowConfig(workflow, spec.hosting);
8110
8471
  const serialized = JSON.stringify(workflowConfig, null, 2);
8111
- await writeFile(entryFile, renderProviderEntry(spec, entryFile, userAppEntry, serialized, importBases.workflow ?? "@vite-hub/workflow", Boolean(importBases.workflow)), "utf8");
8472
+ await writeFile(entryFile, renderProviderEntry(spec, entryFile, userAppEntry, serialized, importBases.workflow ?? "@vite-hub/workflow", Boolean(importBases.workflow), spec.name === "cloudflare" && usesCloudflareConcurrency(providerDefinitions)), "utf8");
8112
8473
  entryFiles[spec.name] = entryFile;
8113
8474
  }));
8114
8475
  return {
@@ -8148,12 +8509,14 @@ function createCloudflareOutput(rootDir, artifacts, providerImportAliases) {
8148
8509
  const workflowConfig = artifacts.cloudflareWorkflowConfig && artifacts.cloudflareWorkflowConfig.driver === "cloudflare" ? artifacts.cloudflareWorkflowConfig : false;
8149
8510
  const workflowDefinitions = workflowConfig ? artifacts.providerDefinitions : [];
8150
8511
  const workflows = createCloudflareWorkflowBindings(workflowDefinitions, workflowConfig);
8512
+ const concurrency = usesCloudflareConcurrency(workflowDefinitions);
8151
8513
  const wranglerConfig = {
8152
8514
  compatibility_date: defaultCloudflareCompatibilityDate,
8153
8515
  compatibility_flags: ["nodejs_compat"],
8154
8516
  main: "index.js",
8155
8517
  observability: { enabled: true },
8156
- ...workflows ? { workflows } : {}
8518
+ ...workflows ? { workflows } : {},
8519
+ ...concurrency ? addCloudflareConcurrencyWrangler({}) : {}
8157
8520
  };
8158
8521
  return {
8159
8522
  bundleEntry: artifacts.cloudflareWorkerFile,
@@ -8184,7 +8547,10 @@ function createCloudflareOutput(rootDir, artifacts, providerImportAliases) {
8184
8547
  bundleOutfileName: "worker.mjs",
8185
8548
  files: { "index.js": createCloudflareWorkflowWrapper(artifacts) },
8186
8549
  outputRoot: createDefaultCloudflareOutputRoot(rootDir),
8187
- wranglerConfigKeys: cloudflareWorkflowWranglerConfigKeys,
8550
+ wranglerConfigOwnership: {
8551
+ ...cloudflareConcurrencyWranglerOwnership,
8552
+ keys: cloudflareWorkflowWranglerConfigKeys
8553
+ },
8188
8554
  wranglerConfig
8189
8555
  };
8190
8556
  }
@@ -8206,7 +8572,10 @@ async function createCloudflareWorkflowCleanup(rootDir, cloudflareInNitro = fals
8206
8572
  deployedWorkflowSourcesPath
8207
8573
  ] : ["worker.mjs", deployedWorkflowSourcesPath],
8208
8574
  outputRoot,
8209
- wranglerConfigOwnership: { keys: cloudflareInNitro ? [] : ownsWrapper ? cloudflareWorkflowWranglerConfigKeys : ["workflows"] }
8575
+ wranglerConfigOwnership: {
8576
+ ...ownsWrapper && !cloudflareInNitro ? cloudflareConcurrencyWranglerOwnership : {},
8577
+ keys: cloudflareInNitro ? [] : ownsWrapper ? cloudflareWorkflowWranglerConfigKeys : ["workflows"]
8578
+ }
8210
8579
  };
8211
8580
  }
8212
8581
  function createVercelOutput(rootDir, artifacts, workflowTransformPlugin, frameworkImportBase, providerImportAliases, serverFunctionName) {
@@ -8365,16 +8734,44 @@ async function assertVercelStepRetries(definitions) {
8365
8734
  }
8366
8735
  }
8367
8736
  }
8737
+ function assertVercelWorkflowsRunNatively(definitions) {
8738
+ for (const definition of definitions) {
8739
+ if (declaresWorkflowConcurrency(definition)) throw workflowErrorDiagnostics.WORKFLOW_CONCURRENCY_VERCEL_UNSUPPORTED({ name: definition.name });
8740
+ if (isAgentWorkflowDefinition(definition) || !hasWorkflowIndexHandler(definition) || declaresVercelNativeWorkflow(definition.handler)) continue;
8741
+ throw workflowErrorDiagnostics.WORKFLOW_VERCEL_INDEX_NOT_NATIVE({
8742
+ file: definition.handler,
8743
+ name: definition.name
8744
+ });
8745
+ }
8746
+ }
8747
+ function resolveVercelNativeWorkflowAliases(providerAliases, nitroAliases = {}) {
8748
+ return {
8749
+ ...nitroAliases,
8750
+ ...providerAliases,
8751
+ ...Object.fromEntries(Object.entries(nitroAliases).filter(([find]) => find.startsWith("@vite-hub/") || find.startsWith("#vitehub/")))
8752
+ };
8753
+ }
8754
+ async function writeNitroVercelNativeWorkflowOutput(rootDir, artifacts, aliases, bundleDefines) {
8755
+ await withProviderDeploymentOutputLock(rootDir, async () => {
8756
+ assertVercelWorkflowsRunNatively(artifacts.providerDefinitions);
8757
+ await assertVercelStepRetries(artifacts.providerDefinitions);
8758
+ await buildVercelNativeWorkflowOutput(rootDir, artifacts.providerDefinitions, aliases, artifacts.vercelNativeFiles, await readVercelNativeWorkflowState(rootDir), bundleDefines);
8759
+ await updateVercelWorkflowFunctionOwnership(rootDir, void 0, false);
8760
+ });
8761
+ }
8368
8762
  async function generateProviderOutputsWithinLock(options, writeProviderDeploymentOutputs) {
8763
+ const { cloudflare: cloudflareWorkflowConfig, vercel: vercelWorkflowConfig } = resolveWorkflowProviderOutputs(options.workflow, options.hosting, options.inline);
8764
+ const vercelWorkflow = Boolean(vercelWorkflowConfig && vercelWorkflowConfig.driver === "vercel");
8369
8765
  let artifacts = options.artifacts ?? await writeProviderEntries(options.rootDir, options.workflow, {
8370
8766
  agent: options.agentModules,
8371
8767
  workflow: options.importBase,
8372
8768
  workspaceRuntime: options.workspaceRuntimeModule,
8373
8769
  workspaceDependencies: options.workspaceDependencyRuntimeImports
8374
- }, options.serverDirs, options.includeUserAppEntry, options.transformRegistry, options.definitionRootDir);
8375
- const { cloudflare: cloudflareWorkflowConfig, vercel: vercelWorkflowConfig } = resolveWorkflowProviderOutputs(options.workflow, options.hosting, options.inline);
8376
- const vercelWorkflow = Boolean(vercelWorkflowConfig && vercelWorkflowConfig.driver === "vercel");
8377
- if (vercelWorkflow) await assertVercelStepRetries(artifacts.providerDefinitions);
8770
+ }, options.serverDirs, options.includeUserAppEntry, options.transformRegistry, options.definitionRootDir, void 0, void 0, vercelWorkflow);
8771
+ if (vercelWorkflow) {
8772
+ assertVercelWorkflowsRunNatively(artifacts.providerDefinitions);
8773
+ await assertVercelStepRetries(artifacts.providerDefinitions);
8774
+ }
8378
8775
  const workflowTransformPlugin = vercelWorkflow && !options.nitroServer ? await createVercelWorkflowTransformPlugin(options.rootDir) : void 0;
8379
8776
  let commitGeneratedArtifacts = async () => {};
8380
8777
  let rollbackGeneratedArtifacts = async () => {};
@@ -8473,11 +8870,11 @@ async function generateProviderOutputsWithinLock(options, writeProviderDeploymen
8473
8870
  handler: publishedSource(definition.handler),
8474
8871
  ...definition.steps ? { steps: definition.steps.map(publishedSource) } : {}
8475
8872
  }));
8476
- const nativeAliases = Object.fromEntries(Object.entries({
8873
+ const nativeAliases = Object.fromEntries(Object.entries(resolveVercelNativeWorkflowAliases({
8477
8874
  ...options.providerImportAliases,
8478
8875
  ...options.providerRuntimeImportAliases?.vercel
8479
- }).map(([alias, target]) => [alias, publishedSource(target)]));
8480
- if (vercelWorkflow && hasVercelNativeWorkflowEntry(options.rootDir, nativeDefinitions, nativeAliases, artifacts.vercelNativeFiles)) assertNoExternalCanonicalWorkflowOutput(previousNativeOutput);
8876
+ }, options.nitroAliases)).map(([alias, target]) => [alias, publishedSource(target)]));
8877
+ if (!options.nativeOutputInNitro && vercelWorkflow && hasVercelNativeWorkflowEntry(options.rootDir, nativeDefinitions, nativeAliases, artifacts.vercelNativeFiles)) assertNoExternalCanonicalWorkflowOutput(previousNativeOutput);
8481
8878
  const deploymentOutput = {
8482
8879
  clientOutDir: options.clientOutDir,
8483
8880
  cloudflare: cloudflareOutput,
@@ -8506,10 +8903,11 @@ async function generateProviderOutputsWithinLock(options, writeProviderDeploymen
8506
8903
  signal
8507
8904
  });
8508
8905
  }
8509
- if (vercelWorkflow) await buildVercelNativeWorkflowOutput(options.rootDir, nativeDefinitions, nativeAliases, artifacts.vercelNativeFiles, previousNativeOutput, options.bundleDefines);
8510
- else await cleanVercelNativeWorkflowOutput(options.rootDir);
8511
- signal?.throwIfAborted();
8512
- await updateVercelWorkflowFunctionOwnership(options.rootDir, vercelOutput ? options.serverFunctionName ?? "__server.func" : void 0, Boolean(vercelOutput && !options.serverFunctionName));
8906
+ if (!options.nativeOutputInNitro) {
8907
+ if (vercelWorkflow) await buildVercelNativeWorkflowOutput(options.rootDir, nativeDefinitions, nativeAliases, artifacts.vercelNativeFiles, previousNativeOutput, options.bundleDefines);
8908
+ else await cleanVercelNativeWorkflowOutput(options.rootDir);
8909
+ await updateVercelWorkflowFunctionOwnership(options.rootDir, vercelOutput ? options.serverFunctionName ?? "__server.func" : void 0, Boolean(vercelOutput && !options.serverFunctionName));
8910
+ }
8513
8911
  signal?.throwIfAborted();
8514
8912
  },
8515
8913
  rootDir: options.rootDir,
@@ -8751,12 +9149,14 @@ function importSpecifier(file, target) {
8751
9149
  * the step files of each folder Workflow (`WorkflowStepRegistry`).
8752
9150
  */
8753
9151
  function createWorkflowTypes(file, definitions, importBase = "@vite-hub/workflow") {
8754
- const registryEntries = definitions.flatMap((definition) => {
9152
+ const agentEntries = definitions.filter(isAgentWorkflow).map((definition) => ` ${JSON.stringify(definition.name)}: unknown`);
9153
+ const standalone = definitions.filter((definition) => !isAgentWorkflow(definition));
9154
+ const registryEntries = standalone.flatMap((definition) => {
8755
9155
  if (!sourceFilePattern.test(definition.handler)) return [` ${JSON.stringify(definition.name)}: import(${JSON.stringify(importBase)}).WorkflowDefinition<unknown>`];
8756
9156
  const moduleType = `typeof import(${JSON.stringify(importSpecifier(file, definition.handler))})`;
8757
9157
  return [...javaScriptFilePattern.test(definition.handler) ? [` ${ignoreJavaScriptTypes}`] : [], ` ${JSON.stringify(definition.name)}: ${moduleType} extends { default: infer TDefault } ? TDefault : unknown`];
8758
9158
  });
8759
- const stepEntries = definitions.filter((definition) => definition.steps?.length).flatMap((definition) => {
9159
+ const stepEntries = standalone.filter((definition) => definition.steps?.length).flatMap((definition) => {
8760
9160
  const directory = sourceFilePattern.test(definition.handler) ? dirname(definition.handler) : definition.handler;
8761
9161
  return [
8762
9162
  ` ${JSON.stringify(definition.name)}: {`,
@@ -8770,6 +9170,11 @@ function createWorkflowTypes(file, definitions, importBase = "@vite-hub/workflow
8770
9170
  " interface WorkflowRegistry {",
8771
9171
  ...registryEntries,
8772
9172
  " }",
9173
+ ...agentEntries.length ? [
9174
+ " interface AgentWorkflowRegistry {",
9175
+ ...agentEntries,
9176
+ " }"
9177
+ ] : [],
8773
9178
  " interface WorkflowStepRegistry {",
8774
9179
  ...stepEntries,
8775
9180
  " }",
@@ -8777,6 +9182,9 @@ function createWorkflowTypes(file, definitions, importBase = "@vite-hub/workflow
8777
9182
  ""
8778
9183
  ].join("\n");
8779
9184
  }
9185
+ function isAgentWorkflow(definition) {
9186
+ return definition.source === "agent-workflow" || definition.source === "agent-workflow-recovery";
9187
+ }
8780
9188
  /**
8781
9189
  * Writes `.vitehub/workflow.d.ts` when its contents change. Keep an empty declaration before the first
8782
9190
  * folder step so ViteHub's types entry can reference it throughout a development session.
@@ -8902,6 +9310,7 @@ function hubWorkflow(workflow, internalOptions = {}) {
8902
9310
  const workflowServerDirs = config["__vitehubServerDirs"] ?? build?.serverDirs;
8903
9311
  const providerSources = discoverWorkflowProviderSources(config.root, workflowServerDirs);
8904
9312
  const retainedSources = artifactDir ? await retainProviderOutputSources({
9313
+ aliases,
8905
9314
  artifactDir: resolve$1(artifactDir, ".vitehub", "workflow", "sources"),
8906
9315
  paths: [...providerOutputAliasSources(aliases, [config.root]), ...providerSources.paths],
8907
9316
  roots: [config.root]
@@ -8914,7 +9323,8 @@ function hubWorkflow(workflow, internalOptions = {}) {
8914
9323
  workflow: internalOptions?.importBase,
8915
9324
  workspaceRuntime: internalOptions?.workspaceRuntimeModule,
8916
9325
  workspaceDependencies: internalOptions?.workspaceDependencyRuntimeImports
8917
- }, retainedServerDirs, internalOptions?.includeUserAppEntry, config.plugins.find((plugin) => plugin.vitehub?.agent?.transformWorkflowRegistry)?.vitehub?.agent?.transformWorkflowRegistry, definitionRootDir, artifactDir ? resolve$1(artifactDir, "output") : void 0, retainedAgentInstructions);
9326
+ }, retainedServerDirs, internalOptions?.includeUserAppEntry, config.plugins.find((plugin) => plugin.vitehub?.agent?.transformWorkflowRegistry)?.vitehub?.agent?.transformWorkflowRegistry, definitionRootDir, artifactDir ? resolve$1(artifactDir, "output") : void 0, retainedAgentInstructions, true);
9327
+ assertVercelWorkflowsRunNatively(artifacts.providerDefinitions);
8918
9328
  const retainedAliases = retainedSources ? retainProviderOutputAliases(aliases, retainedSources) : aliases;
8919
9329
  const native = hasVercelNativeWorkflowEntry(rootDir, artifacts.providerDefinitions, retainedAliases, artifacts.vercelNativeFiles);
8920
9330
  const workflowRequire = native ? createRequire(import.meta.url) : void 0;
@@ -8945,6 +9355,7 @@ function hubWorkflow(workflow, internalOptions = {}) {
8945
9355
  let devRootDir;
8946
9356
  let nitroOptions;
8947
9357
  let vercelNativeEntry = false;
9358
+ let separateNitroConfig;
8948
9359
  function addVercelWorkflowWebhookRoute() {
8949
9360
  if (startupBuild && vercelNativeEntry && nitroOptions) addVercelWorkflowNitroRoutes(nitroOptions);
8950
9361
  }
@@ -9003,7 +9414,8 @@ function hubWorkflow(workflow, internalOptions = {}) {
9003
9414
  workflow: internalOptions.importBase,
9004
9415
  workspaceRuntime: internalOptions.workspaceRuntimeModule,
9005
9416
  workspaceDependencies: internalOptions.workspaceDependencyRuntimeImports
9006
- }, serverDirs, internalOptions.includeUserAppEntry, config.plugins.find((plugin) => plugin.vitehub?.agent?.transformWorkflowRegistry)?.vitehub?.agent?.transformWorkflowRegistry, config.root);
9417
+ }, serverDirs, internalOptions.includeUserAppEntry, config.plugins.find((plugin) => plugin.vitehub?.agent?.transformWorkflowRegistry)?.vitehub?.agent?.transformWorkflowRegistry, config.root, void 0, void 0, true);
9418
+ assertVercelWorkflowsRunNatively(artifacts.providerDefinitions);
9007
9419
  const native = hasVercelNativeWorkflowEntry(rootDir, artifacts.providerDefinitions, await providerImportAliases(config), artifacts.vercelNativeFiles);
9008
9420
  vercelModuleTransform = native ? await createVercelWorkflowModuleTransform(rootDir) : void 0;
9009
9421
  return {
@@ -9028,6 +9440,7 @@ function hubWorkflow(workflow, internalOptions = {}) {
9028
9440
  configPlugins = config.plugins;
9029
9441
  if (startupBuild && internalOptions.hosting) resolveWorkflow(workflow);
9030
9442
  devWorkflow = resolveDevWorkflow();
9443
+ contributeServerEnv(config, "workflow", workflowServerEnv(devWorkflow));
9031
9444
  if (startupBuild && !internalOptions.hosting && !resolveNitroVercelFunctionName(config, "workflow")) return;
9032
9445
  const projectRoot = Reflect.get(config, VITEHUB_PROJECT_ROOT);
9033
9446
  devRootDir = resolveViteHubProjectRoot(resolve$1(config.root || process.cwd()), { projectRoot: typeof projectRoot === "string" ? projectRoot : void 0 });
@@ -9066,7 +9479,7 @@ function hubWorkflow(workflow, internalOptions = {}) {
9066
9479
  }
9067
9480
  if (!(/\.(?:c|m)?[jt]s$/i.test(file) && /(?:\/workflows\/|\.workflow\.|\/agents\/|\.agent\.)/i.test(file)) && !registryDependency) return;
9068
9481
  const { changed } = await writeDevRegistry(rootDir, workflowConfig);
9069
- await writeWorkflowTypes(rootDir, discoverWorkflowDevDefinitions(rootDir, serverDirs), internalOptions.importBase);
9482
+ await writeWorkflowTypes(rootDir, discoverWorkflowDevDefinitions(rootDir, serverDirs, registersAgentWorkflows(workflowConfig)), internalOptions.importBase);
9070
9483
  const filesToInvalidate = new Set([...changed, resolve$1(rootDir, workflowDevGeneratedDir, "dev-registry.mjs")].map((file) => file.replace(/\\/g, "/")));
9071
9484
  let invalidated = false;
9072
9485
  for (const changedFile of filesToInvalidate) for (const module of environment?.moduleGraph.getModulesByFile(changedFile) ?? []) {
@@ -9134,7 +9547,8 @@ function hubWorkflow(workflow, internalOptions = {}) {
9134
9547
  await writeDevRegistry(devRootDir, startupBuild ? devWorkflow && (buildNeedsStartupRegistry() || vercel) ? devWorkflow : void 0 : devWorkflow ?? false, vercel);
9135
9548
  }
9136
9549
  const typesRoot = devRootDir ?? resolveViteHubProjectRoot(config.root);
9137
- await writeWorkflowTypes(typesRoot, workflow === false ? [] : discoverWorkflowDevDefinitions(typesRoot, buildServerDirs), internalOptions.importBase);
9550
+ const typesWorkflow = devRootDir ? devWorkflow : resolveDevWorkflow();
9551
+ await writeWorkflowTypes(typesRoot, workflow === false ? [] : discoverWorkflowDevDefinitions(typesRoot, buildServerDirs, registersAgentWorkflows(typesWorkflow)), internalOptions.importBase);
9138
9552
  },
9139
9553
  configEnvironment(name, config) {
9140
9554
  if (!isServerEnvironment(name, config)) return;
@@ -9158,6 +9572,7 @@ function hubWorkflow(workflow, internalOptions = {}) {
9158
9572
  export: "workflowDurability",
9159
9573
  input: {
9160
9574
  driver: options.driver,
9575
+ ...options.driver === "vercel" && resolveOutputs(workflow).vercel ? { native: true } : {},
9161
9576
  defaultDatabase: options.driver === "openworkflow" && readPostgresDefaultDatabase(databasePlugin) === true,
9162
9577
  ...options.driver === "openworkflow" && options.postgres?.url !== void 0 ? { postgresUrl: workflowDurabilityUrl(options.postgres.url) } : {},
9163
9578
  ...options.driver === "openworkflow" && options.sqlite?.path !== void 0 ? { sqlitePath: options.sqlite.path } : {}
@@ -9233,6 +9648,9 @@ function hubWorkflow(workflow, internalOptions = {}) {
9233
9648
  };
9234
9649
  },
9235
9650
  workflow: {
9651
+ prepareSeparateNitroBuild(config) {
9652
+ if (resolveOutputs(workflow).vercel) separateNitroConfig = config;
9653
+ },
9236
9654
  async createNitroConfig({ nitro, projectRoot, serverDirs: nitroServerDirs, transformRegistry, viteConfig }) {
9237
9655
  if (viteConfig && (Reflect.get(viteConfig, "__vitehubNitroConfigContext") === true || !normalizeHosting(internalOptions.hosting).includes("cloudflare"))) return nitro;
9238
9656
  const input = viteConfig ? {
@@ -9265,6 +9683,21 @@ function hubWorkflow(workflow, internalOptions = {}) {
9265
9683
  providerOutputEnvironment.nitro.setup(nitro);
9266
9684
  nitroOptions = nitro.options;
9267
9685
  addVercelWorkflowWebhookRoute();
9686
+ const config = separateNitroConfig;
9687
+ if (!config) return;
9688
+ const nitroServerDirs = serverDirs;
9689
+ nitro.hooks?.hook("compiled", async () => {
9690
+ const rootDir = resolveViteHubProjectRoot(config.root);
9691
+ await writeNitroVercelNativeWorkflowOutput(rootDir, await writeProviderEntries(rootDir, workflow, {
9692
+ agent: agentWorkflowModules(config.plugins),
9693
+ workflow: internalOptions.importBase,
9694
+ workspaceRuntime: internalOptions.workspaceRuntimeModule,
9695
+ workspaceDependencies: internalOptions.workspaceDependencyRuntimeImports
9696
+ }, nitroServerDirs, internalOptions.includeUserAppEntry, agentWorkflowRegistryTransform(config.plugins), config.root, void 0, void 0, true), resolveVercelNativeWorkflowAliases({
9697
+ ...await providerImportAliases(config),
9698
+ ...providerRuntimeImportAliases("vercel", void 0, getProviderOutputCatalog(config))
9699
+ }, nitro.options.alias), resolveViteHubBundleDefines(config));
9700
+ });
9268
9701
  }
9269
9702
  },
9270
9703
  async buildStart() {
@@ -9337,9 +9770,11 @@ function hubWorkflow(workflow, internalOptions = {}) {
9337
9770
  };
9338
9771
  const providerSources = discoverWorkflowProviderSources(config.root, workflowServerDirs);
9339
9772
  const outputs = resolveOutputs(workflowOptions);
9340
- const nitroServer = nitroOwnsVercelServer(config, workflowOptions);
9773
+ const nativeOutputInNitro = Boolean(separateNitroConfig && outputs.vercel);
9774
+ const nitroServer = nitroOwnsVercelServer(config, workflowOptions) || nativeOutputInNitro;
9341
9775
  const cloudflareInNitro = Reflect.get(config, "nitro")?.rollupConfig?.plugins?.some((plugin) => plugin?.name === "vitehub-workflow-cloudflare-exports") ?? false;
9342
9776
  const retainedSources = !outputs.cloudflare && !outputs.vercel || nitroServer ? { resolve: (path) => path } : await retainProviderOutputSources({
9777
+ aliases: importAliases,
9343
9778
  artifactDir: resolve$1(artifactDir, "sources"),
9344
9779
  paths: [
9345
9780
  ...providerOutputAliasSources(importAliases, [config.root]),
@@ -9362,11 +9797,11 @@ function hubWorkflow(workflow, internalOptions = {}) {
9362
9797
  workflow: internalOptions?.importBase,
9363
9798
  workspaceRuntime: internalOptions?.workspaceRuntimeModule,
9364
9799
  workspaceDependencies: internalOptions?.workspaceDependencyRuntimeImports
9365
- }, retainedServerDirs, internalOptions?.includeUserAppEntry, transformRegistry, retainedDefinitionRoot, resolve$1(artifactDir, "output"), retainedAgentInstructions);
9800
+ }, retainedServerDirs, internalOptions?.includeUserAppEntry, transformRegistry, retainedDefinitionRoot, resolve$1(artifactDir, "output"), retainedAgentInstructions, Boolean(outputs.vercel && outputs.vercel.driver === "vercel"));
9366
9801
  stagedArtifactDirs.set(environment, artifactDir);
9367
9802
  contributeProviderDeploymentOutput(buildProviderOutput, {
9368
- discard: async () => {
9369
- await removeProviderOutputArtifactDir(artifactDir);
9803
+ discard: async (failure) => {
9804
+ await removeProviderOutputArtifactDir(artifactDir, failure);
9370
9805
  if (stagedArtifactDirs.get(environment) === artifactDir) stagedArtifactDirs.delete(environment);
9371
9806
  },
9372
9807
  owner: "workflow",
@@ -9389,6 +9824,8 @@ function hubWorkflow(workflow, internalOptions = {}) {
9389
9824
  definitionRootDir: retainedDefinitionRoot,
9390
9825
  serverDirs: retainedServerDirs,
9391
9826
  nitroServer,
9827
+ nitroAliases: nitroServer ? nitroOptions?.alias : void 0,
9828
+ nativeOutputInNitro,
9392
9829
  sourceRootDir: retainedSources.resolve(rootDir),
9393
9830
  includeUserAppEntry: internalOptions?.includeUserAppEntry,
9394
9831
  workflow: workflowOptions,
@@ -9399,7 +9836,7 @@ function hubWorkflow(workflow, internalOptions = {}) {
9399
9836
  }
9400
9837
  }, generation);
9401
9838
  } catch (error) {
9402
- await removeProviderOutputArtifactDir(artifactDir);
9839
+ await removeProviderOutputArtifactDir(artifactDir, error);
9403
9840
  if (stagedArtifactDirs.get(environment) === artifactDir) stagedArtifactDirs.delete(environment);
9404
9841
  await providerOutputGenerations.reset(this, buildProviderOutput, error);
9405
9842
  throw error;
@@ -9412,7 +9849,7 @@ function hubWorkflow(workflow, internalOptions = {}) {
9412
9849
  await providerOutputGenerations.reset(this, build?.providerOutput ?? providerOutput, error);
9413
9850
  const artifactDir = stagedArtifactDirs.get(environment);
9414
9851
  if (artifactDir) {
9415
- await removeProviderOutputArtifactDir(artifactDir);
9852
+ await removeProviderOutputArtifactDir(artifactDir, error);
9416
9853
  if (stagedArtifactDirs.get(environment) === artifactDir) stagedArtifactDirs.delete(environment);
9417
9854
  }
9418
9855
  },