@vite-hub/workflow 0.6.1 → 0.8.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 (49) hide show
  1. package/README.md +33 -9
  2. package/dist/{app-DXUHElAz.js → app-Cpa9qCXr.js} +1 -1
  3. package/dist/{client-CbBg4HlH.js → client-T41cNf3k.js} +41 -52
  4. package/dist/cloudflare-concurrency-counter-CDHHiMfn.js +136 -0
  5. package/dist/{config-CizNRTMi.js → config-G0z9jHLM.js} +6 -6
  6. package/dist/definition.d.ts +1 -1
  7. package/dist/definition.js +4 -1
  8. package/dist/{delay-CtT3442d.js → delay-B4azP18B.js} +7 -5
  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-zu08sWGG.js +353 -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-CdKbUGGa.d.ts → openworkflow-DHuxMJQB.d.ts} +23 -4
  19. package/dist/openworkflow-defaults-1n0DbLdb.js +4 -0
  20. package/dist/openworkflow-zD8luED5.js +749 -0
  21. package/dist/{operation-definition-CqZkx1Rm.d.ts → operations-Blwi3jQF.d.ts} +1 -0
  22. package/dist/{operations-BBTmDm2H.js → operations-C2XbDDDV.js} +71 -15
  23. package/dist/operations.d.ts +3 -59
  24. package/dist/operations.js +5 -5
  25. package/dist/results-DqbEUMCH.d.ts +60 -0
  26. package/dist/{run-error-8p4BtTMv.js → run-error-zZh1_IBo.js} +5 -21
  27. package/dist/runtime/cloudflare-concurrency.d.ts +21 -0
  28. package/dist/runtime/cloudflare-concurrency.js +21 -0
  29. package/dist/runtime/cloudflare-runner.d.ts +1 -1
  30. package/dist/runtime/cloudflare-runner.js +7 -3
  31. package/dist/runtime/cloudflare-vite.d.ts +1 -1
  32. package/dist/runtime/cloudflare-vite.js +2 -2
  33. package/dist/runtime/execute.d.ts +8 -2
  34. package/dist/runtime/execute.js +1 -278
  35. package/dist/runtime/openworkflow-worker.d.ts +2 -2
  36. package/dist/runtime/openworkflow-worker.js +5 -6
  37. package/dist/runtime/openworkflow.d.ts +2 -2
  38. package/dist/runtime/openworkflow.js +1 -481
  39. package/dist/runtime/state.d.ts +1 -1
  40. package/dist/runtime/state.js +2 -2
  41. package/dist/runtime/vercel-vite.d.ts +1 -1
  42. package/dist/runtime/vercel-vite.js +2 -2
  43. package/dist/{signals-BHQdxoJo.js → signals-CdaxRNjN.js} +1 -1
  44. package/dist/{types-DvYcvbPG.d.ts → types-DrhUXMsE.d.ts} +34 -4
  45. package/dist/{vercel-Cw_Z9-j4.js → vercel-DRezYOUp.js} +8 -6
  46. package/dist/vite.d.ts +19 -4
  47. package/dist/vite.js +970 -212
  48. package/package.json +3 -3
  49. 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-G0z9jHLM.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-zu08sWGG.js";
11
+ import { n as generatedNativeEntryKey, o as vercelNativeRegistryKey, r as generatedNativeRootStepKey, s as workflowStartAtKey } from "./delay-B4azP18B.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) {
@@ -3223,6 +3264,150 @@ async function copyRuntimePackageFiles(packageDir, targetDir) {
3223
3264
  await unlessGone(() => copyFile(join(packageDir, path), target));
3224
3265
  }
3225
3266
  }
3267
+ // ../internal/src/source-files.ts
3268
+ const ignoredDirs = /* @__PURE__ */ new Set([
3269
+ "node_modules",
3270
+ "dist",
3271
+ ".output",
3272
+ ".nuxt",
3273
+ ".vercel",
3274
+ ".git",
3275
+ ".vitehub"
3276
+ ]);
3277
+ const racyWindowNs = 2000000000n;
3278
+ const storeKey = Symbol.for("vite-hub.source-files.v1");
3279
+ function store() {
3280
+ const existing = Reflect.get(globalThis, storeKey);
3281
+ if (isStore(existing)) return existing;
3282
+ const created = {
3283
+ derived: /* @__PURE__ */ new Map(),
3284
+ texts: /* @__PURE__ */ new Map(),
3285
+ trees: /* @__PURE__ */ new Map()
3286
+ };
3287
+ Reflect.set(globalThis, storeKey, created);
3288
+ return created;
3289
+ }
3290
+ function isStore(value) {
3291
+ return typeof value === "object" && value !== null && "texts" in value && "trees" in value && "derived" in value;
3292
+ }
3293
+ function errorCode$1(error) {
3294
+ return typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
3295
+ }
3296
+ function statOrMissing(path) {
3297
+ try {
3298
+ return statSync(path, { bigint: true });
3299
+ } catch (error) {
3300
+ if (errorCode$1(error) === "ENOENT" || errorCode$1(error) === "ENOTDIR") return;
3301
+ throw error;
3302
+ }
3303
+ }
3304
+ function signature(stats) {
3305
+ return `${stats.ino}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`;
3306
+ }
3307
+ function isSettled(stats) {
3308
+ const changed = stats.mtimeNs > stats.ctimeNs ? stats.mtimeNs : stats.ctimeNs;
3309
+ return BigInt(Date.now()) * 1000000n - changed > racyWindowNs;
3310
+ }
3311
+ function readDirEntries$1(root) {
3312
+ try {
3313
+ return readdirSync(root, { withFileTypes: true });
3314
+ } catch (error) {
3315
+ if (errorCode$1(error) === "ENOENT") return [];
3316
+ throw error;
3317
+ }
3318
+ }
3319
+ function walkTree(root, directories, files, nested = false) {
3320
+ const before = statOrMissing(root);
3321
+ let trusted = before !== void 0 && isSettled(before);
3322
+ if (before) directories.set(root, signature(before));
3323
+ if (nested && existsSync(resolve(root, ".git"))) return trusted;
3324
+ for (const entry of readDirEntries$1(root)) {
3325
+ const path = resolve(root, entry.name);
3326
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
3327
+ if (entry.name.startsWith(".") || ignoredDirs.has(entry.name)) continue;
3328
+ if (!walkTree(path, directories, files, true)) trusted = false;
3329
+ continue;
3330
+ }
3331
+ if (entry.isFile()) files.push({
3332
+ hidden: entry.name.startsWith("."),
3333
+ name: entry.name,
3334
+ path
3335
+ });
3336
+ }
3337
+ return trusted;
3338
+ }
3339
+ function isCurrent(tree) {
3340
+ for (const [directory, stored] of tree.directories) {
3341
+ const stats = statOrMissing(directory);
3342
+ if (!stats || signature(stats) !== stored) return false;
3343
+ }
3344
+ return true;
3345
+ }
3346
+ function sourceTree(root) {
3347
+ const trees = store().trees;
3348
+ const cached = trees.get(root);
3349
+ if (cached && isCurrent(cached)) return cached;
3350
+ const directories = /* @__PURE__ */ new Map();
3351
+ const files = [];
3352
+ const trusted = walkTree(root, directories, files);
3353
+ files.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
3354
+ const tree = {
3355
+ directories,
3356
+ files
3357
+ };
3358
+ if (trusted) trees.set(root, tree);
3359
+ else trees.delete(root);
3360
+ return tree;
3361
+ }
3362
+ /**
3363
+ * The files below `root` whose name matches `predicate`, sorted by path. The walk skips hidden folders, Git
3364
+ * repositories, and build output folders such as `node_modules`, `dist`, and `.vitehub`. Hidden files need
3365
+ * `includeHidden`. Symbolic links are skipped.
3366
+ */
3367
+ function listSourceTreeFiles(root, predicate, options = {}) {
3368
+ const files = [];
3369
+ for (const file of sourceTree(resolve(root)).files) {
3370
+ if (file.hidden && !options.includeHidden) continue;
3371
+ if (predicate(file.name)) files.push(file.path);
3372
+ }
3373
+ return files;
3374
+ }
3375
+ /** The UTF-8 text of a source file. A file that did not change since the last read is not read again. */
3376
+ function readSourceText(file) {
3377
+ const path = resolve(file);
3378
+ const texts = store().texts;
3379
+ const stats = statOrMissing(path);
3380
+ if (!stats) return readFileSync(path, "utf8");
3381
+ const current = signature(stats);
3382
+ const cached = texts.get(path);
3383
+ if (cached?.trusted && cached.signature === current) return cached.text;
3384
+ const read = readFileSync(path, "utf8");
3385
+ const text = cached?.text === read ? cached.text : read;
3386
+ texts.set(path, {
3387
+ signature: current,
3388
+ text,
3389
+ trusted: isSettled(stats)
3390
+ });
3391
+ return text;
3392
+ }
3393
+ /**
3394
+ * A value that `compute` derives from the text of a source file, such as its syntax tree. The value is computed again
3395
+ * only when the text changes. `kind` separates the values of different callers for one file. The last two texts of a
3396
+ * file are kept, because some callers read both the file and its transformed code.
3397
+ */
3398
+ function deriveFromSource(kind, file, source, compute) {
3399
+ const derived = store().derived;
3400
+ const key = `${kind}\0${file}`;
3401
+ const entries = derived.get(key) ?? [];
3402
+ const cached = entries.find((entry) => entry.source === source);
3403
+ if (cached) return cached.value;
3404
+ const value = compute();
3405
+ derived.set(key, [{
3406
+ source,
3407
+ value
3408
+ }, ...entries.slice(0, 1)]);
3409
+ return value;
3410
+ }
3226
3411
  // ../internal/src/build/scan-module.ts
3227
3412
  /**
3228
3413
  * Reads facts from JavaScript and TypeScript modules at build and dev time. The scanner parses each module once with
@@ -3252,8 +3437,15 @@ function scanModule(source, file = "module.ts") {
3252
3437
  source
3253
3438
  };
3254
3439
  }
3440
+ /** `scanModule` with a result that is shared while `source` stays the same for `file`. */
3441
+ function scanModuleText(source, file) {
3442
+ return deriveFromSource("scan-module", file, source, () => scanModule(source, file));
3443
+ }
3255
3444
  /** Lists the names that a module exports. A default export reads as `default`. Type-only exports are left out. */
3256
3445
  function exportNames(source, file = "module.ts") {
3446
+ return [...deriveFromSource("export-names", file, source, () => readExportNames(source, file))];
3447
+ }
3448
+ function readExportNames(source, file) {
3257
3449
  const { module } = parseSync(file, source, {
3258
3450
  lang: moduleLanguage(file),
3259
3451
  sourceType: "module"
@@ -3269,6 +3461,28 @@ function unwrapExpression(node) {
3269
3461
  while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
3270
3462
  return node;
3271
3463
  }
3464
+ /** A call argument without assertions, or undefined for a spread or missing argument. */
3465
+ function argumentExpression(argument) {
3466
+ return argument === void 0 || argument.type === "SpreadElement" ? void 0 : unwrapExpression(argument);
3467
+ }
3468
+ /** Calls whose callee is a plain identifier in `names`, such as `defineCollection(...)`, in source order. */
3469
+ function findCalls(module, names) {
3470
+ const wanted = new Set(names);
3471
+ const calls = [];
3472
+ walk(module.program, (node) => {
3473
+ if (node.type === "CallExpression" && node.callee.type === "Identifier" && wanted.has(node.callee.name)) calls.push(node);
3474
+ });
3475
+ return calls.sort((left, right) => left.start - right.start);
3476
+ }
3477
+ /** The expression of `export default <expression>`, without assertions. Declarations return undefined. */
3478
+ function defaultExportExpression(module) {
3479
+ for (const statement of module.program.body) {
3480
+ if (statement.type !== "ExportDefaultDeclaration") continue;
3481
+ const declaration = statement.declaration;
3482
+ if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration" || declaration.type === "TSInterfaceDeclaration") return;
3483
+ return unwrapExpression(declaration);
3484
+ }
3485
+ }
3272
3486
  function staticKey(property) {
3273
3487
  const key = property.key;
3274
3488
  if (key.type === "Identifier" && !property.computed) return key.name;
@@ -3290,6 +3504,10 @@ function objectProperties(object) {
3290
3504
  value: unwrapExpression(node.value)
3291
3505
  });
3292
3506
  }
3507
+ /** The last member named `name`, which is the one that the object keeps at runtime. */
3508
+ function findProperty(object, name) {
3509
+ return objectProperties(object).findLast((property) => property.key === name);
3510
+ }
3293
3511
  /** The value of a template literal without substitutions. */
3294
3512
  function staticTemplate(node) {
3295
3513
  if (node.expressions.length) return dynamic;
@@ -3477,10 +3695,10 @@ function referencedProviderSourcePaths(contents, publishedSourcesDir) {
3477
3695
  return [...references].filter((reference) => ![...references].some((parent) => parent !== reference && pathContains$1(parent, reference)));
3478
3696
  }
3479
3697
  /** Dotenv files (`.env*`, Wrangler `.dev.vars*`), registry credentials, and Wrangler state hold local secrets. */
3480
- const localSecretFile = /^(?:\.env|\.dev\.vars)(?:\..*)?$|^\.(?:netrc|npmrc|wrangler)$/;
3698
+ const localSecretFile$1 = /^(?:\.env|\.dev\.vars)(?:\..*)?$|^\.(?:netrc|npmrc|wrangler)$/;
3481
3699
  /** A retained snapshot and a deployment never receive local secret files, even inside a directory that the code names. */
3482
3700
  function isLocalSecretFile(path) {
3483
- return localSecretFile.test(basename(path));
3701
+ return localSecretFile$1.test(basename(path));
3484
3702
  }
3485
3703
  /**
3486
3704
  * Copies the durable generated sources that deployment files name into deployment artifacts and rewrites their
@@ -3576,6 +3794,9 @@ const ignoredSourceDirectories = /* @__PURE__ */ new Set([
3576
3794
  "node_modules"
3577
3795
  ]);
3578
3796
  const ignoredGeneratedDirectories = /* @__PURE__ */ new Set([".vitehub", ".vitest-tmp"]);
3797
+ function crossesIgnoredDirectory(parent, child) {
3798
+ return relative$1(parent, child).split(sep).some((segment) => ignoredSourceDirectories.has(segment) || ignoredGeneratedDirectories.has(segment));
3799
+ }
3579
3800
  function isTransientSourceDirectory(path) {
3580
3801
  return basename(path).startsWith(".drizzle-generate-");
3581
3802
  }
@@ -3671,8 +3892,26 @@ async function linkDependencies(source, target, resolveLinkTarget = (source) =>
3671
3892
  await symlink(resolveLinkTarget(resolvedSourceEntry), targetEntry, process.platform === "win32" ? "junction" : "dir");
3672
3893
  }
3673
3894
  }
3674
- /** Removes retained provider output after readers release it, tolerating transient filesystem contention. */
3675
- async function removeProviderOutputArtifactDir(path) {
3895
+ const keptFailedProviderOutputArtifactDirs = /* @__PURE__ */ new Set();
3896
+ function failureText(failure) {
3897
+ return failure instanceof Error ? `${failure.message}\n${failure.stack ?? ""}` : String(failure);
3898
+ }
3899
+ /**
3900
+ * Removes retained provider output after readers release it, tolerating transient filesystem contention. Pass the
3901
+ * build failure when a failed build discards its generation: with `VITEHUB_KEEP_FAILED_BUILD=1` the folder stays
3902
+ * for inspection.
3903
+ */
3904
+ async function removeProviderOutputArtifactDir(path, failure) {
3905
+ if (failure !== void 0) {
3906
+ const shown = relative$1(process.cwd(), path) || path;
3907
+ if (/^(?:1|true)$/i.test(process.env.VITEHUB_KEEP_FAILED_BUILD ?? "")) {
3908
+ if (!existsSync(path)) return;
3909
+ 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.`);
3910
+ keptFailedProviderOutputArtifactDirs.add(path);
3911
+ return;
3912
+ }
3913
+ 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.`);
3914
+ }
3676
3915
  await rm(path, {
3677
3916
  force: true,
3678
3917
  maxRetries: 5,
@@ -3929,7 +4168,7 @@ function traceComputedModuleSources(file, source, onRuntimePackageRequest) {
3929
4168
  }
3930
4169
  return paths;
3931
4170
  }
3932
- async function traceImportedSources(paths, root, configuredRoots) {
4171
+ async function traceImportedSources(paths, root, configuredRoots, aliases) {
3933
4172
  const entries = paths.filter((path) => traceableSourceExtensions.has(extname(path)));
3934
4173
  if (!entries.length) return /* @__PURE__ */ new Set();
3935
4174
  const { rolldown } = await importRolldown();
@@ -4070,7 +4309,7 @@ async function traceImportedSources(paths, root, configuredRoots) {
4070
4309
  if (log.code === "UNRESOLVED_IMPORT") throw Object.assign(new Error(log.message), { code: log.code });
4071
4310
  },
4072
4311
  platform: variant.platform,
4073
- plugins: [tracePlugin],
4312
+ plugins: [createResolvedAliasPlugin(aliases, configuredRoots[0] ?? root, root, false), tracePlugin],
4074
4313
  resolve: { conditionNames: variant.conditions }
4075
4314
  });
4076
4315
  try {
@@ -4216,6 +4455,11 @@ function resolveTsconfigReference(config, reference) {
4216
4455
  if (existsSync(resolved)) return resolved;
4217
4456
  } catch {}
4218
4457
  }
4458
+ function resolveTsconfigProjectReference(config, reference) {
4459
+ const path = resolve$1(dirname$1(config), reference);
4460
+ const file = existsSync(path) && statSync(path).isDirectory() ? resolve$1(path, "tsconfig.json") : path;
4461
+ return existsSync(file) && statSync(file).isFile() ? file : void 0;
4462
+ }
4219
4463
  async function tsconfigSourcesForPaths(root, paths) {
4220
4464
  const pending = [];
4221
4465
  for (const path of paths) {
@@ -4237,11 +4481,9 @@ async function tsconfigSourcesForPaths(root, paths) {
4237
4481
  sources.add(config);
4238
4482
  try {
4239
4483
  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
- }
4484
+ const extended = (Array.isArray(parsed.extends) ? parsed.extends : parsed.extends ? [parsed.extends] : []).map((reference) => resolveTsconfigReference(config, reference));
4485
+ const projects = (Array.isArray(parsed.references) ? parsed.references : []).map((reference) => typeof reference?.path === "string" ? resolveTsconfigProjectReference(config, reference.path) : void 0);
4486
+ for (const resolved of [...extended, ...projects]) if (resolved && !sources.has(resolved)) pending.push(resolved);
4245
4487
  } catch {}
4246
4488
  }
4247
4489
  return [...sources];
@@ -4277,7 +4519,7 @@ async function retainProviderOutputSources(options) {
4277
4519
  const [index, root] = next.value;
4278
4520
  const requested = paths.filter((path) => path !== root && pathContains$1(root, path));
4279
4521
  const nestedConfiguredRoots = configuredRoots.filter((path) => pathContains$1(root, path));
4280
- const importedSources = await traceImportedSources(requested, root, nestedConfiguredRoots);
4522
+ const importedSources = await traceImportedSources(requested, root, nestedConfiguredRoots, options.aliases);
4281
4523
  const materializedSourcePaths = [...requested, ...importedSources];
4282
4524
  const tsconfigSources = await tsconfigSourcesForPaths(root, materializedSourcePaths);
4283
4525
  materializedSourcePaths.push(...tsconfigSources);
@@ -4365,7 +4607,7 @@ async function retainProviderOutputSources(options) {
4365
4607
  const nestedGeneratedOutput = scopedSegments.some((segment) => ignoredGeneratedDirectories.has(segment));
4366
4608
  const ignoredIndex = scopedSegments.findIndex((segment) => ignoredSourceDirectories.has(segment));
4367
4609
  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));
4610
+ 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
4611
  return true;
4370
4612
  };
4371
4613
  await copyRetainedSourceTree(root, stagedRoot, (source) => shouldCopySource(resolve$1(source)));
@@ -4885,17 +5127,17 @@ var ProviderOutputCatalog = class {
4885
5127
  }
4886
5128
  this.#restoreDeploymentContribution(entry);
4887
5129
  }
4888
- resetDeploymentContributions(generation) {
5130
+ resetDeploymentContributions(generation, failure) {
4889
5131
  if (!generation) {
4890
5132
  for (const reference of this.#deploymentGenerations) {
4891
5133
  const current = reference.deref();
4892
5134
  if (current) current.valid = false;
4893
5135
  }
4894
5136
  this.#deploymentGenerations.clear();
4895
- for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry);
5137
+ for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry, failure);
4896
5138
  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);
5139
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry, failure);
5140
+ for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback, failure);
4899
5141
  }
4900
5142
  this.#deploymentContributions.clear();
4901
5143
  this.#takenDeploymentContributions.clear();
@@ -4904,7 +5146,7 @@ var ProviderOutputCatalog = class {
4904
5146
  generation.valid = false;
4905
5147
  this.#deleteDeploymentGeneration(generation);
4906
5148
  for (const [owner, entries] of this.#deploymentContributions) {
4907
- for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry);
5149
+ for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry, failure);
4908
5150
  const remaining = entries.filter((entry) => entry.generation !== generation);
4909
5151
  if (remaining.length) this.#deploymentContributions.set(owner, remaining);
4910
5152
  else this.#deploymentContributions.delete(owner);
@@ -4912,10 +5154,10 @@ var ProviderOutputCatalog = class {
4912
5154
  for (const [contribution, taken] of this.#takenDeploymentContributions) {
4913
5155
  const invalidatedFallbacks = taken.fallbacks.filter((entry) => entry.generation === generation);
4914
5156
  taken.fallbacks = taken.fallbacks.filter((entry) => entry.generation !== generation);
4915
- for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback);
5157
+ for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback, failure);
4916
5158
  if (taken.entry.generation !== generation) continue;
4917
5159
  this.#takenDeploymentContributions.delete(contribution);
4918
- if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
5160
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry, failure);
4919
5161
  for (const fallback of taken.fallbacks) if (taken.committed) this.#queueDeploymentDiscard(fallback);
4920
5162
  else this.#restoreDeploymentContribution(fallback);
4921
5163
  }
@@ -4958,7 +5200,7 @@ var ProviderOutputCatalog = class {
4958
5200
  const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
4959
5201
  if (failure) throw failure.reason;
4960
5202
  }
4961
- async completeDeploymentContributions(contributions) {
5203
+ async completeDeploymentContributions(contributions, buildFailure) {
4962
5204
  const discarded = this.#pendingDeploymentDiscards.splice(0);
4963
5205
  const completedGenerations = /* @__PURE__ */ new Set();
4964
5206
  for (const contribution of contributions) {
@@ -4968,7 +5210,7 @@ var ProviderOutputCatalog = class {
4968
5210
  const entries = taken.entryDiscarded ? taken.fallbacks : [...taken.fallbacks, taken.entry];
4969
5211
  for (const entry of entries) {
4970
5212
  if (entry.generation) completedGenerations.add(entry.generation);
4971
- if (entry.contribution.discard) discarded.push(entry.contribution.discard());
5213
+ if (entry.contribution.discard) discarded.push(entry.contribution.discard(entry === taken.entry ? buildFailure : void 0));
4972
5214
  }
4973
5215
  }
4974
5216
  for (const generation of completedGenerations) this.#retireDeploymentGeneration(generation);
@@ -5012,9 +5254,9 @@ var ProviderOutputCatalog = class {
5012
5254
  if (reference) this.#deploymentGenerations.delete(reference);
5013
5255
  this.#deploymentGenerationRefs.delete(generation);
5014
5256
  }
5015
- #queueDeploymentDiscard(entry) {
5257
+ #queueDeploymentDiscard(entry, failure) {
5016
5258
  if (!entry.contribution.discard) return;
5017
- const discard = Promise.resolve().then(entry.contribution.discard);
5259
+ const discard = Promise.resolve().then(async () => await entry.contribution.discard?.(failure));
5018
5260
  discard.catch(() => {});
5019
5261
  this.#pendingDeploymentDiscards.push(discard);
5020
5262
  }
@@ -5107,6 +5349,56 @@ const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
5107
5349
  * Later entries are Nuxt layers in Nuxt priority order.
5108
5350
  */
5109
5351
  const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
5352
+ /**
5353
+ * Server Env declarations that ViteHub features add before `hubEnv()` builds the registry, such as the Server Env of
5354
+ * discovered Channels. The application's `env.server` wins field by field.
5355
+ */
5356
+ const VITEHUB_ENV_SERVER = "__vitehubEnvServer";
5357
+ function isPackageServerEnvField(value) {
5358
+ return Array.isArray(value.names);
5359
+ }
5360
+ /** The kind of a contributed field. `hubEnv()` declares it as an optional `env()` with a non-canonical source. */
5361
+ const PACKAGE_SERVER_ENV_FIELD = "vitehub-package-env-field";
5362
+ function packageServerEnvDeclarations(fields) {
5363
+ return Object.fromEntries(Object.entries(fields).flatMap(([key, field]) => {
5364
+ if (!isPackageServerEnvField(field)) {
5365
+ const group = packageServerEnvDeclarations(field);
5366
+ return Object.keys(group).length ? [[key, group]] : [];
5367
+ }
5368
+ return [[key, {
5369
+ kind: PACKAGE_SERVER_ENV_FIELD,
5370
+ names: [...field.names],
5371
+ description: field.description,
5372
+ secret: field.secret,
5373
+ sourcePatterns: field.sourcePatterns
5374
+ }]];
5375
+ }));
5376
+ }
5377
+ function isServerEnvGroup(value) {
5378
+ return isRecord(value) && value.kind !== "env-variable" && value.kind !== "vitehub-package-env-field";
5379
+ }
5380
+ function mergeServerEnvGroups(base, added) {
5381
+ const merged = { ...base };
5382
+ for (const [key, value] of Object.entries(added)) {
5383
+ const current = merged[key];
5384
+ merged[key] = isServerEnvGroup(current) && isServerEnvGroup(value) ? mergeServerEnvGroups(current, value) : current ?? value;
5385
+ }
5386
+ return merged;
5387
+ }
5388
+ /**
5389
+ * Declare in Server Env the host variables that a package reads for its configured provider, under
5390
+ * `env.server.<group>`, so `inspectServerEnv()` and Setup pages list them with a description. Each value is optional:
5391
+ * the package reports a missing value when it uses the provider, and `deployment.json` keeps the deploy rule. The
5392
+ * source claims no canonical name, so the application can also read the variable under its own key. Declarations
5393
+ * that another feature already added at the same path stay, and the application's `env.server` wins field by field.
5394
+ */
5395
+ function contributeServerEnv(config, group, fields) {
5396
+ const declarations = packageServerEnvDeclarations(fields);
5397
+ if (!Object.keys(declarations).length) return;
5398
+ const contributed = Reflect.get(config, VITEHUB_ENV_SERVER);
5399
+ const server = isRecord(contributed) ? contributed : {};
5400
+ Reflect.set(config, VITEHUB_ENV_SERVER, mergeServerEnvGroups(server, { [group]: declarations }));
5401
+ }
5110
5402
  function includesNitroVitePlugin(value) {
5111
5403
  if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
5112
5404
  if (!value || typeof value !== "object") return false;
@@ -5175,6 +5467,24 @@ function isMissingProjectMarker(error) {
5175
5467
  const code = error.code;
5176
5468
  return code === "ENOENT" || code === "ENOTDIR";
5177
5469
  }
5470
+ /** The owner of the generated code that a Vite or Nuxt config writes, from the CLI discovery and Node test markers. */
5471
+ function viteHubGeneratedOwner(config) {
5472
+ if (Reflect.get(config, "vitehubNodeTest") === true) return "node-test";
5473
+ return Reflect.get(config, "vitehubCliDiscovery") === true ? "cli" : "app";
5474
+ }
5475
+ /**
5476
+ * The generated-code folder of an owner, relative to the project root: `.vitehub` for the app, `.vitehub/cli` and
5477
+ * `.vitehub/node-test` for the others. State that the processes share, such as the Email outbox or the Env secret,
5478
+ * stays in `.vitehub`, and so do the declaration files that TypeScript reads, because their contents follow only the
5479
+ * Definitions.
5480
+ */
5481
+ function viteHubGeneratedCodeDir(owner = "app") {
5482
+ return owner === "app" ? ".vitehub" : `.vitehub/${owner}`;
5483
+ }
5484
+ /** The absolute generated-code folder of an owner. See {@link viteHubGeneratedCodeDir}. */
5485
+ function viteHubGeneratedCodeRoot(projectRoot, owner = "app") {
5486
+ return resolve$1(projectRoot, viteHubGeneratedCodeDir(owner));
5487
+ }
5178
5488
  // ../internal/src/build/deployment-output.ts
5179
5489
  const providerDeploymentOutputRegistry = globalThis;
5180
5490
  const providerDeploymentOutputWrites = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputWrites ??= /* @__PURE__ */ new Map();
@@ -6000,23 +6310,23 @@ async function resetProviderDeploymentOutputs(catalog, failure, generation) {
6000
6310
  if (!catalog) return;
6001
6311
  const completedReset = providerDeploymentOutputCompletedResets.get(catalog);
6002
6312
  if (completedReset && failure !== void 0 && completedReset.failures.has(failure)) {
6003
- if (generation) catalog.resetDeploymentContributions(generation);
6313
+ if (generation) catalog.resetDeploymentContributions(generation, failure);
6004
6314
  await completedReset.promise;
6005
6315
  return;
6006
6316
  }
6007
6317
  if (completedReset) providerDeploymentOutputCompletedResets.delete(catalog);
6008
- if (generation) catalog.resetDeploymentContributions(generation);
6318
+ if (generation) catalog.resetDeploymentContributions(generation, failure);
6009
6319
  const active = providerDeploymentOutputFinalizations.get(catalog);
6010
6320
  if (active?.reset) {
6011
6321
  if (failure !== void 0 && !active.reset.failures.has(failure)) {
6012
6322
  active.reset.failures.add(failure);
6013
- if (!generation) catalog.resetDeploymentContributions();
6323
+ if (!generation) catalog.resetDeploymentContributions(void 0, failure);
6014
6324
  }
6015
6325
  providerDeploymentOutputCompletedResets.set(catalog, active.reset);
6016
6326
  await active.reset.promise;
6017
6327
  return;
6018
6328
  }
6019
- if (!generation) catalog.resetDeploymentContributions();
6329
+ if (!generation) catalog.resetDeploymentContributions(void 0, failure);
6020
6330
  if (active && (!generation || active.state.generations.has(generation))) {
6021
6331
  active.state.rollback = true;
6022
6332
  active.controller.abort(internalErrorDiagnostics.INTERNAL_B0039({ message: "Provider Output finalization reset" }));
@@ -6165,7 +6475,7 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
6165
6475
  await catalog.completeDeploymentContributions(contributions);
6166
6476
  } catch (error) {
6167
6477
  if (state.rollback) catalog.rollbackDeploymentContributions(contributions);
6168
- else await catalog.completeDeploymentContributions(contributions);
6478
+ else await catalog.completeDeploymentContributions(contributions, error);
6169
6479
  throw error;
6170
6480
  } finally {
6171
6481
  state.generations.clear();
@@ -6273,19 +6583,248 @@ function workflowDeploymentEnv(workflow) {
6273
6583
  ...schema
6274
6584
  ];
6275
6585
  }
6586
+ // src/server-env.ts
6587
+ const descriptions = {
6588
+ postgresUrl: "The Postgres URL of the database that stores the OpenWorkflow runs.",
6589
+ sqlitePath: "The path of the SQLite file that stores the OpenWorkflow runs.",
6590
+ namespaceId: "The namespace that keeps the runs of this app apart from other apps in the same database.",
6591
+ schema: "The Postgres schema of the OpenWorkflow tables."
6592
+ };
6593
+ function valueField(value, secret, description) {
6594
+ if (value === void 0 || typeof value === "string") return;
6595
+ const names = value.source?.names ?? (value.source?.name ? [value.source.name] : []);
6596
+ return names.length ? {
6597
+ names,
6598
+ secret,
6599
+ description
6600
+ } : void 0;
6601
+ }
6602
+ /**
6603
+ * The Server Env fields that configure OpenWorkflow storage, so Setup pages show them.
6604
+ */
6605
+ function workflowServerEnv(workflow) {
6606
+ if (!workflow || workflow.driver !== "openworkflow") return {};
6607
+ const { postgres, sqlite } = workflow;
6608
+ const namespaceId = {
6609
+ names: ["OPENWORKFLOW_NAMESPACE_ID"],
6610
+ secret: false,
6611
+ description: descriptions.namespaceId
6612
+ };
6613
+ const schema = postgres?.schema ? void 0 : {
6614
+ names: ["OPENWORKFLOW_SCHEMA"],
6615
+ secret: false,
6616
+ description: descriptions.schema
6617
+ };
6618
+ const fields = postgres?.url !== void 0 ? {
6619
+ postgresUrl: valueField(postgres.url, true, descriptions.postgresUrl),
6620
+ namespaceId: postgres.namespaceId ? void 0 : namespaceId,
6621
+ schema
6622
+ } : sqlite?.path !== void 0 ? {
6623
+ sqlitePath: valueField(sqlite.path, false, descriptions.sqlitePath),
6624
+ namespaceId: sqlite.namespaceId ? void 0 : namespaceId
6625
+ } : {
6626
+ sqlitePath: {
6627
+ names: ["OPENWORKFLOW_SQLITE_PATH"],
6628
+ secret: false,
6629
+ description: descriptions.sqlitePath
6630
+ },
6631
+ postgresUrl: {
6632
+ names: ["OPENWORKFLOW_POSTGRES_URL"],
6633
+ secret: true,
6634
+ description: descriptions.postgresUrl
6635
+ },
6636
+ namespaceId: postgres?.namespaceId && sqlite?.namespaceId ? void 0 : namespaceId,
6637
+ schema
6638
+ };
6639
+ return Object.fromEntries(Object.entries(fields).filter((entry) => entry[1] !== void 0));
6640
+ }
6641
+ // ../internal/src/build/colocated-agent-files.ts
6642
+ function flatAgentProjectSourceRoot(handler, serverDir, projectRoot) {
6643
+ if (!serverDir || !projectRoot) return;
6644
+ const path = relative$1(resolve$1(serverDir, "agents"), handler);
6645
+ if (!isAbsolute(path) && path !== ".." && !path.startsWith(`..${sep}`)) return resolve$1(projectRoot);
6646
+ }
6647
+ function resolveColocatedAgentWorkspaceRoot(handler) {
6648
+ const directory = join(dirname$1(handler), "workspace");
6649
+ return existsSync(directory) && statSync(directory).isDirectory() ? directory : void 0;
6650
+ }
6651
+ function resolveDiscoveredAgentSourceRoot(definition) {
6652
+ const colocatedRoot = resolveColocatedAgentWorkspaceRoot(definition.handler);
6653
+ return {
6654
+ sourceRootDir: colocatedRoot ?? definition.sourceRootDir ?? dirname$1(definition.handler),
6655
+ projectSourceRoot: !colocatedRoot && definition.sourceRootDir !== void 0
6656
+ };
6657
+ }
6658
+ const localSourceModule = /^(?:@vite-hub|vite-hub)\/source$/;
6659
+ function stringList(value) {
6660
+ if (typeof value === "string") return [value];
6661
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) return value;
6662
+ }
6663
+ function literalLocalSource(input, kind) {
6664
+ if (isRecord(input) && !kind && "source" in input) return literalLocalSource(input.source);
6665
+ if (isRecord(input) && ("repo" in input || "url" in input || "server" in input || "content" in input)) return;
6666
+ if (typeof input === "string" && kind === "glob") {
6667
+ const parts = input.replaceAll("\\", "/").replace(/^\.\//, "").split("/").filter(Boolean);
6668
+ const wild = parts.findIndex((part) => /[*?[\]{}()!]/.test(part));
6669
+ return wild === -1 ? {
6670
+ include: ["**/*"],
6671
+ path: parts.join("/") || "."
6672
+ } : {
6673
+ include: [parts.slice(wild).join("/")],
6674
+ path: parts.slice(0, wild).join("/") || "."
6675
+ };
6676
+ }
6677
+ if (typeof input === "string") return { path: input };
6678
+ if (!isRecord(input)) return;
6679
+ const include = stringList(input.include);
6680
+ if (include && kind !== "file") return {
6681
+ dot: input.dot === true,
6682
+ ignore: stringList(input.ignore),
6683
+ include,
6684
+ path: typeof input.cwd === "string" ? input.cwd : "."
6685
+ };
6686
+ if (typeof input.path === "string" && kind !== "glob") return { path: input.path };
6687
+ }
6688
+ function literalLocalSources(handler) {
6689
+ const module = scanModule(readFileSync(handler, "utf8"), handler);
6690
+ const helpers = /* @__PURE__ */ new Map();
6691
+ for (const statement of module.program.body) {
6692
+ if (statement.type !== "ImportDeclaration" || statement.importKind === "type" || !localSourceModule.test(String(statement.source.value))) continue;
6693
+ for (const specifier of statement.specifiers) {
6694
+ if (specifier.type !== "ImportSpecifier" || specifier.importKind === "type") continue;
6695
+ const name = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
6696
+ if (name === "file" || name === "glob") helpers.set(specifier.local.name, name);
6697
+ }
6698
+ }
6699
+ const sources = [];
6700
+ for (const call of findCalls(module, helpers.keys())) {
6701
+ const argument = argumentExpression(call.arguments[0]);
6702
+ const input = argument ? staticValue(argument) : void 0;
6703
+ const kind = call.callee.type === "Identifier" ? helpers.get(call.callee.name) : void 0;
6704
+ const source = input === dynamic ? void 0 : literalLocalSource(input, kind);
6705
+ if (source) sources.push(source);
6706
+ }
6707
+ walk(module.program, (node) => {
6708
+ if (node.type !== "ObjectExpression") return;
6709
+ const entries = findProperty(node, "sources")?.value;
6710
+ if (entries?.type !== "ObjectExpression") return;
6711
+ for (const entry of objectProperties(entries)) {
6712
+ const input = entry.value ? staticValue(entry.value) : dynamic;
6713
+ const source = input === dynamic ? void 0 : literalLocalSource(input);
6714
+ if (source) sources.push(source);
6715
+ }
6716
+ });
6717
+ return sources;
6718
+ }
6719
+ function contains(root, path) {
6720
+ const nested = relative$1(root, path);
6721
+ return !isAbsolute(nested) && nested !== ".." && !nested.startsWith(`..${sep}`);
6722
+ }
6723
+ /**
6724
+ * The folder that holds the snapshot of a flat Agent's local Sources in a retained sources folder. It sits beside the
6725
+ * numbered source trees and has no dot folder, so globs such as Netlify's `includedFiles` package it.
6726
+ */
6727
+ function flatAgentSourceSnapshotDir(sourcesDir, handler, projectRoot) {
6728
+ const name = contains(projectRoot, handler) ? relative$1(projectRoot, handler) : basename(handler);
6729
+ return join(sourcesDir, "agent-sources", name.replace(/\.(?:c|m)?[jt]s$/i, ""));
6730
+ }
6731
+ const localSecretFile = /^(?:\.env|\.dev\.vars)(?:\..*)?$/i;
6732
+ function skippedSourceEntry(name) {
6733
+ const lower = name.toLowerCase();
6734
+ return lower === "node_modules" || lower === ".git" || localSecretFile.test(name);
6735
+ }
6736
+ function allowedSnapshotPath(root, path) {
6737
+ return contains(root, path) && !relative$1(root, path).split(sep).some(skippedSourceEntry);
6738
+ }
6739
+ function matchedGlobFiles(folder, source) {
6740
+ const include = source.include.map((pattern) => new Minimatch(pattern.replaceAll("\\", "/"), { dot: source.dot }));
6741
+ const ignore = (source.ignore ?? []).map((pattern) => new Minimatch(pattern.replaceAll("\\", "/"), { dot: true }));
6742
+ const files = [];
6743
+ const visit = (directory) => {
6744
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
6745
+ if (skippedSourceEntry(entry.name)) continue;
6746
+ const path = join(directory, entry.name);
6747
+ if (entry.isDirectory()) visit(path);
6748
+ if (!entry.isFile()) continue;
6749
+ const key = relative$1(folder, path).split(sep).join("/");
6750
+ if (include.some((pattern) => pattern.match(key)) && !ignore.some((pattern) => pattern.match(key))) files.push(path);
6751
+ }
6752
+ };
6753
+ visit(folder);
6754
+ return files;
6755
+ }
6756
+ /**
6757
+ * Copies the local Sources that a flat Agent names with literal `file()` and `glob()` options into `targetDir`, at
6758
+ * their paths under `projectRoot`. A deployment uses this folder as the Agent's Source root, so it ships these files
6759
+ * and not the whole project. A Source with computed options is not copied: it cannot read local files after deploy.
6760
+ */
6761
+ async function snapshotFlatAgentSources(handler, projectRoot, targetDir) {
6762
+ await mkdir(targetDir, { recursive: true });
6763
+ const root = realpathSync(projectRoot);
6764
+ for (const source of literalLocalSources(handler)) {
6765
+ const from = resolve$1(root, source.path);
6766
+ if (!allowedSnapshotPath(root, from) || !existsSync(from)) continue;
6767
+ const realFrom = realpathSync(from);
6768
+ if (!allowedSnapshotPath(root, realFrom)) continue;
6769
+ const target = resolve$1(targetDir, relative$1(root, from));
6770
+ if (source.include) {
6771
+ if (!statSync(realFrom).isDirectory()) continue;
6772
+ await mkdir(target, { recursive: true });
6773
+ for (const path of matchedGlobFiles(realFrom, {
6774
+ ...source,
6775
+ include: source.include
6776
+ })) {
6777
+ const destination = resolve$1(target, relative$1(realFrom, path));
6778
+ await mkdir(dirname$1(destination), { recursive: true });
6779
+ await copyFile(path, destination);
6780
+ }
6781
+ } else if (statSync(realFrom).isFile()) {
6782
+ await mkdir(dirname$1(target), { recursive: true });
6783
+ await copyFile(realFrom, target);
6784
+ }
6785
+ }
6786
+ }
6787
+ function isFolderAgentEntry(file) {
6788
+ if (!/^(?:agent|index)\.(?:c|m)?[jt]s$/i.test(basename(file))) return false;
6789
+ return !(basename(file).toLowerCase().startsWith("agent.") && basename(dirname$1(file)) === "agents" && basename(dirname$1(dirname$1(file))) === "server");
6790
+ }
6791
+ function colocatedAgentFilesRoot(handler, directoryName) {
6792
+ if (!isFolderAgentEntry(handler)) return;
6793
+ const root = join(dirname$1(handler), directoryName);
6794
+ return existsSync(root) ? root : void 0;
6795
+ }
6796
+ function resolveColocatedAgentFilesRoot(handler, directoryName) {
6797
+ const root = colocatedAgentFilesRoot(handler, directoryName);
6798
+ return root && statSync(root).isDirectory() ? root : void 0;
6799
+ }
6800
+ function readColocatedAgentFiles(handler, directoryName) {
6801
+ const root = colocatedAgentFilesRoot(handler, directoryName);
6802
+ if (!root) return;
6803
+ if (!statSync(root).isDirectory()) return;
6804
+ const files = {};
6805
+ const visit = (directory) => {
6806
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {
6807
+ const file = join(directory, entry.name);
6808
+ const target = relative$1(root, file).replace(/\\/g, "/");
6809
+ if (entry.isDirectory()) {
6810
+ visit(file);
6811
+ continue;
6812
+ }
6813
+ if (!entry.isFile()) continue;
6814
+ const content = readFileSync(file);
6815
+ files[target] = {
6816
+ content: content.toString("base64"),
6817
+ encoding: "base64"
6818
+ };
6819
+ }
6820
+ };
6821
+ visit(root);
6822
+ return Object.keys(files).length ? files : void 0;
6823
+ }
6276
6824
  // ../internal/src/definition-catalog.ts
6277
6825
  const sourceFilePattern$2 = /\.(?:c|m)?[jt]sx?$/i;
6278
6826
  const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
6279
6827
  const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
6280
- const ignoredDirs = /* @__PURE__ */ new Set([
6281
- "node_modules",
6282
- "dist",
6283
- ".output",
6284
- ".nuxt",
6285
- ".vercel",
6286
- ".git",
6287
- ".vitehub"
6288
- ]);
6289
6828
  function resolveDefinitionScanRoots(rootDir, scanDirs = []) {
6290
6829
  return [...new Set([rootDir, ...scanDirs].filter(Boolean))];
6291
6830
  }
@@ -6308,32 +6847,11 @@ function createSuffixDefinitionSource(source, roots, pattern, normalizeName, opt
6308
6847
  source
6309
6848
  };
6310
6849
  }
6311
- function readDirEntries$1(root) {
6312
- try {
6313
- return readdirSync(root, { withFileTypes: true });
6314
- } catch (error) {
6315
- if (error.code === "ENOENT") return [];
6316
- throw error;
6317
- }
6318
- }
6319
6850
  function isGitRepositoryDirectory(directory) {
6320
6851
  return existsSync(resolve(directory, ".git"));
6321
6852
  }
6322
6853
  function listMatchingFiles(root, predicate, options = {}) {
6323
- const files = [];
6324
- for (const entry of readDirEntries$1(root)) {
6325
- const absolute = resolve(root, entry.name);
6326
- if (entry.isDirectory() && !entry.isSymbolicLink()) {
6327
- if (isGitRepositoryDirectory(absolute)) continue;
6328
- if (entry.name.startsWith(".")) continue;
6329
- if (ignoredDirs.has(entry.name)) continue;
6330
- files.push(...listMatchingFiles(absolute, predicate, options));
6331
- continue;
6332
- }
6333
- if (entry.name.startsWith(".") && !options.includeHidden) continue;
6334
- if (entry.isFile() && predicate(entry.name)) files.push(absolute);
6335
- }
6336
- return files.sort();
6854
+ return listSourceTreeFiles(root, predicate, options);
6337
6855
  }
6338
6856
  /** A module that a Definitions folder can hold: JavaScript or TypeScript, and not a declaration, test, or spec file. */
6339
6857
  function isDefinitionSourceFile(name) {
@@ -6507,7 +7025,7 @@ function resolveAgentReExport(file, source, masked) {
6507
7025
  ]) if (existsSync(candidate) && statSync(candidate).isFile()) return candidate;
6508
7026
  }
6509
7027
  function maskSourceLiterals(source, file) {
6510
- return maskLiterals(scanModule(source, file));
7028
+ return deriveFromSource("masked-literals", file, source, () => maskLiterals(scanModuleText(source, file)));
6511
7029
  }
6512
7030
  function isFolderAgentImplementationTarget(file) {
6513
7031
  const fileName = normalize(file).split("/").pop();
@@ -6517,7 +7035,7 @@ function isFolderAgentImplementationTarget(file) {
6517
7035
  function extractAgentRuntime(file, seen = /* @__PURE__ */ new Set()) {
6518
7036
  if (seen.has(file)) return void 0;
6519
7037
  seen.add(file);
6520
- const source = readFileSync(file, "utf8");
7038
+ const source = readSourceText(file);
6521
7039
  const masked = maskSourceLiterals(source, file);
6522
7040
  const start = findAgentObjectStart(source, masked);
6523
7041
  if (start === void 0) {
@@ -6564,7 +7082,7 @@ function extractAgentWorkflowName(file, fallbackName) {
6564
7082
  if (/^false(?:\s+as\s+const)?$/.test(runtime.masked || "")) return void 0;
6565
7083
  const shorthand = /^([A-Za-z_$][\w$]*)$/.exec(runtime.masked || "")?.[1];
6566
7084
  if (shorthand) {
6567
- const source = readFileSync(file, "utf8");
7085
+ const source = readSourceText(file);
6568
7086
  const masked = maskSourceLiterals(source, file);
6569
7087
  const declaration = new RegExp(`\\b(?:const|let|var)\\s+${shorthand}\\s*(?::(?:=>|[^=])*?)?=\\s*`).exec(masked);
6570
7088
  if (declaration) {
@@ -6636,11 +7154,11 @@ function discoverSuffixAgentWorkflowDefinitions(roots) {
6636
7154
  return workflowDefinition ? [workflowDefinition] : [];
6637
7155
  });
6638
7156
  }
6639
- function discoverFlatServerAgentWorkflowDefinitions(scanDirs) {
7157
+ function discoverFlatServerAgentWorkflowDefinitions(scanDirs, projectRoot) {
6640
7158
  const folderAgentFiles = scanDirs.flatMap((scanDir) => findFolderAgentFiles(resolve(scanDir, "agents")));
6641
7159
  const folderAgentDirs = new Set(folderAgentFiles.map((file) => normalize(resolve(file, ".."))));
6642
7160
  const folderAgentTargets = new Set(folderAgentFiles.flatMap((file) => {
6643
- const source = readFileSync(file, "utf8");
7161
+ const source = readSourceText(file);
6644
7162
  const target = resolveAgentReExport(file, source, maskSourceLiterals(source, file));
6645
7163
  const relativeTarget = target && normalize(relative$1(resolve(file, ".."), target));
6646
7164
  return target && relativeTarget && relativeTarget !== ".." && !relativeTarget.startsWith("../") && isFolderAgentImplementationTarget(target) ? [normalize(target)] : [];
@@ -6667,7 +7185,12 @@ function discoverFlatServerAgentWorkflowDefinitions(scanDirs) {
6667
7185
  })
6668
7186
  })]).flatMap((definition) => {
6669
7187
  const workflowDefinition = toAgentWorkflowDefinition(definition.handler, definition.name);
6670
- return workflowDefinition ? [workflowDefinition] : [];
7188
+ if (!workflowDefinition) return [];
7189
+ const sourceRootDir = flatAgentProjectSourceRoot(definition.handler, scanDirs[0], projectRoot);
7190
+ return [{
7191
+ ...workflowDefinition,
7192
+ ...sourceRootDir ? { sourceRootDir } : {}
7193
+ }];
6671
7194
  });
6672
7195
  }
6673
7196
  function discoverConfiguredServerAgentWorkflowDefinitions(scanDirs) {
@@ -6676,7 +7199,7 @@ function discoverConfiguredServerAgentWorkflowDefinitions(scanDirs) {
6676
7199
  const agentsDir = resolve(scanDir, "agents");
6677
7200
  const files = findFolderAgentFiles(agentsDir);
6678
7201
  const targets = new Set(files.flatMap((file) => {
6679
- const source = readFileSync(file, "utf8");
7202
+ const source = readSourceText(file);
6680
7203
  const target = resolveAgentReExport(file, source, maskSourceLiterals(source, file));
6681
7204
  const relativeTarget = target && normalize(relative$1(resolve(file, ".."), target));
6682
7205
  return target && relativeTarget && relativeTarget !== ".." && !relativeTarget.startsWith("../") ? [normalize(target)] : [];
@@ -6691,8 +7214,8 @@ function discoverConfiguredServerAgentWorkflowDefinitions(scanDirs) {
6691
7214
  }
6692
7215
  return sortDefinitions(definitions);
6693
7216
  }
6694
- function discoverAgentWorkflowDefinitions(roots, serverScanDirs) {
6695
- return mergeDefinitions("agent workflow", discoverSuffixAgentWorkflowDefinitions(roots), discoverFlatServerAgentWorkflowDefinitions(serverScanDirs), discoverConfiguredServerAgentWorkflowDefinitions(serverScanDirs));
7217
+ function discoverAgentWorkflowDefinitions(roots, serverScanDirs, projectRoot) {
7218
+ return mergeDefinitions("agent workflow", discoverSuffixAgentWorkflowDefinitions(roots), discoverFlatServerAgentWorkflowDefinitions(serverScanDirs, projectRoot), discoverConfiguredServerAgentWorkflowDefinitions(serverScanDirs));
6696
7219
  }
6697
7220
  function discoverWorkflowFolders(scanDirs, source) {
6698
7221
  const definitions = /* @__PURE__ */ new Map();
@@ -6740,7 +7263,7 @@ function discoverWorkflowDefinitions(options) {
6740
7263
  handler: file,
6741
7264
  name,
6742
7265
  source: "vite-suffix"
6743
- }) })]), discoverFlatServerWorkflowDefinitions(serverScanDirs, "server-workflows"), folderDefinitions, options.mode === "standalone" ? [] : discoverAgentWorkflowDefinitions(roots, serverScanDirs));
7266
+ }) })]), discoverFlatServerWorkflowDefinitions(serverScanDirs, "server-workflows"), folderDefinitions, options.mode === "standalone" ? [] : discoverAgentWorkflowDefinitions(roots, serverScanDirs, options.projectRoot ?? options.rootDir));
6744
7267
  }
6745
7268
  // src/internal/runtime-type.ts
6746
7269
  function isRuntimeRecord(value) {
@@ -6750,44 +7273,6 @@ function isRuntimeRecord(value) {
6750
7273
  function getAgentInvocationRecoveryWorkflowName(agentWorkflowName) {
6751
7274
  return `vitehub-agent-invocation-recovery-${agentWorkflowName}`;
6752
7275
  }
6753
- // ../internal/src/build/colocated-agent-files.ts
6754
- function isFolderAgentEntry(file) {
6755
- if (!/^(?:agent|index)\.(?:c|m)?[jt]s$/i.test(basename(file))) return false;
6756
- return !(basename(file).toLowerCase().startsWith("agent.") && basename(dirname$1(file)) === "agents" && basename(dirname$1(dirname$1(file))) === "server");
6757
- }
6758
- function colocatedAgentFilesRoot(handler, directoryName) {
6759
- if (!isFolderAgentEntry(handler)) return;
6760
- const root = join(dirname$1(handler), directoryName);
6761
- return existsSync(root) ? root : void 0;
6762
- }
6763
- function resolveColocatedAgentFilesRoot(handler, directoryName) {
6764
- const root = colocatedAgentFilesRoot(handler, directoryName);
6765
- return root && statSync(root).isDirectory() ? root : void 0;
6766
- }
6767
- function readColocatedAgentFiles(handler, directoryName) {
6768
- const root = colocatedAgentFilesRoot(handler, directoryName);
6769
- if (!root) return;
6770
- if (!statSync(root).isDirectory()) return;
6771
- const files = {};
6772
- const visit = (directory) => {
6773
- for (const entry of readdirSync(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {
6774
- const file = join(directory, entry.name);
6775
- const target = relative$1(root, file).replace(/\\/g, "/");
6776
- if (entry.isDirectory()) {
6777
- visit(file);
6778
- continue;
6779
- }
6780
- if (!entry.isFile()) continue;
6781
- const content = readFileSync(file);
6782
- files[target] = {
6783
- content: content.toString("base64"),
6784
- encoding: "base64"
6785
- };
6786
- }
6787
- };
6788
- visit(root);
6789
- return Object.keys(files).length ? files : void 0;
6790
- }
6791
7276
  // ../internal/src/build/esbuild.ts
6792
7277
  const viteRawNamespace = "vitehub-vite-raw";
6793
7278
  const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
@@ -7043,6 +7528,17 @@ const cloudflareWorkflowWranglerConfigKeys = [
7043
7528
  "observability",
7044
7529
  "workflows"
7045
7530
  ];
7531
+ const cloudflareConcurrencyWranglerOwnership = {
7532
+ arrays: { migrations: {
7533
+ key: "tag",
7534
+ preserveOrder: true,
7535
+ values: [cloudflareConcurrencyMigrationTag]
7536
+ } },
7537
+ objects: { durable_objects: { arrays: { bindings: {
7538
+ key: "name",
7539
+ values: [cloudflareConcurrencyBinding]
7540
+ } } } }
7541
+ };
7046
7542
  const cloudflareWorkflowWrapperImport = `import worker, { runViteHubWorkflowDefinition } from "./worker.mjs"`;
7047
7543
  const nodeBuiltinExternals = [.../* @__PURE__ */ new Set([
7048
7544
  "node:*",
@@ -7175,21 +7671,21 @@ async function loadVercelWorkflowBuilders() {
7175
7671
  return await import("@workflow/builders");
7176
7672
  }
7177
7673
  /** 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) {
7674
+ async function createVercelWorkflowTransformPlugin(rootDir, idRoot = rootDir, include = () => true, mode = "step") {
7179
7675
  const builders = await loadVercelWorkflowBuilders();
7180
7676
  if (!builders) return void 0;
7181
7677
  const workingDir = idRoot.replace(/\\/g, "/").replace(/\/$/, "");
7182
7678
  return {
7183
7679
  name: "vitehub-vercel-workflow-transform",
7184
7680
  async load(id) {
7185
- if (!/\.[cm]?[jt]sx?$/.test(id) || !isAbsolute(id)) return;
7681
+ if (!/\.[cm]?[jt]sx?$/.test(id) || !isAbsolute(id) || !include(id.replaceAll("\\", "/"))) return;
7186
7682
  const source = await readFile(id, "utf8");
7187
7683
  if (!builders.shouldTransformFile(id, builders.detectWorkflowPatterns(source))) return;
7188
7684
  const file = id.replace(/\\/g, "/");
7189
7685
  const filename = relative$1(workingDir, file).replace(/\\/g, "/").split("/").filter((segment) => segment !== "..").join("/");
7190
7686
  const code = source.replace(/require\(\s*(['"])(?:server|client)-only\1\s*\)/g, "void 0");
7191
7687
  return {
7192
- code: (await builders.applySwcTransform(filename, code, "workflow", id, rootDir)).code,
7688
+ code: (await builders.applySwcTransform(filename, code, mode, id, rootDir)).code,
7193
7689
  moduleType: id.endsWith(".tsx") ? "tsx" : id.endsWith(".jsx") ? "jsx" : "js"
7194
7690
  };
7195
7691
  }
@@ -7231,6 +7727,72 @@ async function withVercelWorkflowPackageLink(rootDir, run) {
7231
7727
  if (ownsLink) await rm(target, { force: true });
7232
7728
  }
7233
7729
  }
7730
+ const nativeKeyPattern = /\bnative\s*(?::|(?=[,}]))/;
7731
+ const useWorkflowDirectivePattern = /^\s*["']use workflow["'];?/m;
7732
+ function parseWorkflowModule(file) {
7733
+ return buildSync({
7734
+ bundle: false,
7735
+ format: "esm",
7736
+ legalComments: "none",
7737
+ metafile: true,
7738
+ minifySyntax: true,
7739
+ stdin: {
7740
+ contents: readFileSync(file, "utf8"),
7741
+ loader: /\.[cm]?[jt]sx$/.test(file) ? "tsx" : "ts",
7742
+ sourcefile: file
7743
+ },
7744
+ write: false
7745
+ });
7746
+ }
7747
+ function declaresVercelNativeWorkflow(file) {
7748
+ return declaresWorkflowOption(file, "native");
7749
+ }
7750
+ function declaresWorkflowOption(file, option) {
7751
+ const module = scanModule(readFileSync(file, "utf8"), file);
7752
+ let definition = defaultExportExpression(module);
7753
+ const bindings = module.program.body.flatMap((statement) => statement.type === "VariableDeclaration" ? statement.declarations : []);
7754
+ const resolveBinding = (expression) => {
7755
+ const visited = /* @__PURE__ */ new Set();
7756
+ while (expression?.type === "Identifier") {
7757
+ const name = expression.name;
7758
+ if (visited.has(name)) return;
7759
+ visited.add(name);
7760
+ const init = bindings.find((binding) => binding.id.type === "Identifier" && binding.id.name === name)?.init;
7761
+ expression = init ? unwrapExpression(init) : void 0;
7762
+ }
7763
+ return expression;
7764
+ };
7765
+ definition = resolveBinding(definition);
7766
+ if (definition?.type === "CallExpression") definition = resolveBinding(argumentExpression(definition.arguments[0]));
7767
+ return definition?.type === "ObjectExpression" && Boolean(findProperty(definition, option));
7768
+ }
7769
+ function declaresWorkflowConcurrency(definition) {
7770
+ return !isAgentWorkflowDefinition(definition) && /\.(?:c|m)?[jt]sx?$/i.test(definition.handler) && existsSync(definition.handler) && declaresWorkflowOption(definition.handler, "concurrency");
7771
+ }
7772
+ function usesCloudflareConcurrency(definitions) {
7773
+ return definitions.some(declaresWorkflowConcurrency);
7774
+ }
7775
+ function addCloudflareConcurrencyWrangler(wrangler) {
7776
+ const durableObjects = record(wrangler.durable_objects);
7777
+ const bindings = Array.isArray(durableObjects.bindings) ? [...durableObjects.bindings].map(record) : [];
7778
+ if (!bindings.some((entry) => entry.name === "VITEHUB_WORKFLOW_CONCURRENCY")) bindings.push({
7779
+ class_name: cloudflareConcurrencyClassName,
7780
+ name: cloudflareConcurrencyBinding
7781
+ });
7782
+ const migrations = Array.isArray(wrangler.migrations) ? [...wrangler.migrations].map(record) : [];
7783
+ const declared = (key) => migrations.some((entry) => Array.isArray(entry[key]) && entry[key].includes("ViteHubWorkflowConcurrency"));
7784
+ if (!declared("new_sqlite_classes") && !declared("new_classes")) migrations.push({
7785
+ new_sqlite_classes: [cloudflareConcurrencyClassName],
7786
+ tag: cloudflareConcurrencyMigrationTag
7787
+ });
7788
+ return {
7789
+ durable_objects: {
7790
+ ...durableObjects,
7791
+ bindings
7792
+ },
7793
+ migrations
7794
+ };
7795
+ }
7234
7796
  /**
7235
7797
  * Whether a Workflow builds as a native Vercel Workflow. It throws when one does and the app did not install the
7236
7798
  * Workflow DevKit, so every native build path reports the same coded error.
@@ -7252,29 +7814,17 @@ function hasVercelNativeWorkflowEntry(rootDir, definitions, aliases = {}, native
7252
7814
  }
7253
7815
  return;
7254
7816
  }
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
- });
7817
+ if (!/\.(?:c|m)?[jt]sx?$/.test(file)) return;
7818
+ const parsed = parseWorkflowModule(file);
7269
7819
  const parsedSource = parsed.outputFiles[0].text;
7270
- if (/^\s*["']use workflow["'];?/m.test(parsedSource)) {
7820
+ if (useWorkflowDirectivePattern.test(parsedSource)) {
7271
7821
  if (!definitionDirs.some((definitionDir) => {
7272
7822
  const path = relative$1(definitionDir, file);
7273
7823
  return !path.startsWith("..") && !isAbsolute(path);
7274
7824
  })) throw workflowErrorDiagnostics.WORKFLOW_R0004({ message: `Native Vercel workflow entry ${JSON.stringify(relative$1(rootDir, file))} must be colocated with its discovered workflow definition.` });
7275
7825
  hasNativeEntry = true;
7276
7826
  }
7277
- if (definitionHandlers.has(file) && !/\bnative\s*(?::|(?=[,}]))/.test(parsedSource)) return;
7827
+ if (definitionHandlers.has(file) && !nativeKeyPattern.test(parsedSource)) return;
7278
7828
  const imports = Object.values(parsed.metafile.outputs).flatMap((output) => output.imports);
7279
7829
  for (const { path: specifier } of imports) {
7280
7830
  const alias = Object.entries(aliases).find(([find]) => specifier === find || specifier.startsWith(`${find}/`));
@@ -7571,6 +8121,8 @@ async function buildVercelNativeWorkflowOutput(rootDir, definitions, aliases = {
7571
8121
  keepNames: true,
7572
8122
  platform: "node",
7573
8123
  plugins: [
8124
+ createViteHubEntrySideEffectsPlugin(),
8125
+ createVercelStepAliasPlugin(aliases),
7574
8126
  createPseudoPackagePlugin(),
7575
8127
  createOptionalPackagesEsbuildPlugin(rootDir),
7576
8128
  {
@@ -7620,7 +8172,7 @@ async function buildVercelNativeWorkflowOutput(rootDir, definitions, aliases = {
7620
8172
  await writeFile(outputConfigFile, `${JSON.stringify({
7621
8173
  ...workflowConfig,
7622
8174
  ...viteHubConfig,
7623
- routes: [...workflowRoutes, ...viteHubRoutes]
8175
+ routes: [...new Map([...workflowRoutes, ...viteHubRoutes].map((route) => [JSON.stringify(route), route])).values()]
7624
8176
  }, null, 2)}\n`, "utf8");
7625
8177
  const generatedFiles = await collectVercelNativeWorkflowFiles(workflowRoot);
7626
8178
  const ownedFiles = Object.fromEntries(Object.entries(generatedFiles).filter(([file, digest]) => previousFiles[file] !== digest || previousFiles[file] === previousOwnership?.files[file]));
@@ -7642,6 +8194,59 @@ async function buildVercelNativeWorkflowOutput(rootDir, definitions, aliases = {
7642
8194
  throw error;
7643
8195
  }
7644
8196
  }
8197
+ function createVercelStepAliasPlugin(aliases) {
8198
+ const entries = Object.entries(aliases).map(([key, replacement]) => ({
8199
+ find: key.split(encodedAliasPrefixMarker)[0].split(encodedAliasExactMarker)[0],
8200
+ prefix: key.includes(encodedAliasPrefixMarker),
8201
+ replacement
8202
+ }));
8203
+ return {
8204
+ name: "vitehub-workflow-aliases",
8205
+ setup(build) {
8206
+ build.onResolve({ filter: /.*/ }, (args) => {
8207
+ if (args.pluginData?.vitehubWorkflowAliasResolved) return;
8208
+ const specifier = args.path.split("?", 1)[0];
8209
+ const alias = entries.find(({ find, prefix }) => prefix ? specifier.startsWith(find) : specifier === find);
8210
+ if (!alias) return;
8211
+ const replacement = alias.prefix ? `${alias.replacement.replace(/[\\/]$/, "")}/` : alias.replacement;
8212
+ return build.resolve(`${replacement}${args.path.slice(alias.find.length)}`, {
8213
+ importer: args.importer,
8214
+ kind: args.kind,
8215
+ namespace: args.namespace,
8216
+ resolveDir: args.resolveDir,
8217
+ pluginData: {
8218
+ ...args.pluginData,
8219
+ vitehubWorkflowAliasResolved: true
8220
+ }
8221
+ });
8222
+ });
8223
+ }
8224
+ };
8225
+ }
8226
+ function createViteHubEntrySideEffectsPlugin() {
8227
+ return {
8228
+ name: "vitehub-workflow-entry-side-effects",
8229
+ setup(build) {
8230
+ build.onResolve({ filter: /^vite-hub(?:\/|$)/ }, async (args) => {
8231
+ if (args.pluginData?.vitehubWorkflowEntryResolved) return;
8232
+ const result = await build.resolve(args.path, {
8233
+ importer: args.importer,
8234
+ kind: args.kind,
8235
+ namespace: args.namespace,
8236
+ resolveDir: args.resolveDir,
8237
+ pluginData: {
8238
+ ...args.pluginData,
8239
+ vitehubWorkflowEntryResolved: true
8240
+ }
8241
+ });
8242
+ return result.errors.length ? result : {
8243
+ ...result,
8244
+ sideEffects: true
8245
+ };
8246
+ });
8247
+ }
8248
+ };
8249
+ }
7645
8250
  function resolveWorkflowUserAppEntry(rootDir, entry) {
7646
8251
  return resolveUserAppEntry(rootDir, entry === true ? {} : { names: [entry] });
7647
8252
  }
@@ -7718,7 +8323,7 @@ function renderCloudflareWorkflowEntrypoint(definition, legacyAliases) {
7718
8323
  ""
7719
8324
  ].join("\n");
7720
8325
  }
7721
- function createCloudflareWorkflowNitroPlugin(entryFile, definitions) {
8326
+ function createCloudflareWorkflowNitroPlugin(entryFile, definitions, concurrency = false) {
7722
8327
  const moduleId = "virtual:vitehub-workflow-cloudflare-exports";
7723
8328
  const legacyAliases = getUniqueLegacyCloudflareWorkflowAliases(definitions);
7724
8329
  const resolvedModuleId = `\0${moduleId}`;
@@ -7749,6 +8354,7 @@ function createCloudflareWorkflowNitroPlugin(entryFile, definitions) {
7749
8354
  "",
7750
8355
  "installViteHubWorkflowRuntime()",
7751
8356
  "",
8357
+ ...concurrency ? [`export { ${cloudflareConcurrencyClassName} } from ${JSON.stringify(workflowRuntimeModule("cloudflare-concurrency"))}`, ""] : [],
7752
8358
  ...definitions.map((definition) => renderCloudflareWorkflowEntrypoint(definition, legacyAliases))
7753
8359
  ].join("\n");
7754
8360
  }
@@ -7756,7 +8362,7 @@ function createCloudflareWorkflowNitroPlugin(entryFile, definitions) {
7756
8362
  renderChunk(code, chunk) {
7757
8363
  if (!chunk.isEntry || chunk.fileName !== "index.mjs" && chunk.fileName !== "index.js") return null;
7758
8364
  return {
7759
- code: `${code}\nexport { ${definitions.flatMap((definition) => [getCloudflareWorkflowClassName(definition.name), ...legacyAliases.get(definition.name) ? [legacyAliases.get(definition.name)] : []]).join(", ")} } from './${fileName}'\n`,
8365
+ 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
8366
  map: null
7761
8367
  };
7762
8368
  }
@@ -7805,11 +8411,13 @@ async function createCloudflareWorkflowNitroConfig(options) {
7805
8411
  const existingWorkflows = Array.isArray(wrangler.workflows) ? [...wrangler.workflows] : [];
7806
8412
  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
8413
  wrangler.workflows = existingWorkflows;
8414
+ const concurrency = usesCloudflareConcurrency(artifacts.providerDefinitions);
8415
+ if (concurrency) Object.assign(wrangler, addCloudflareConcurrencyWrangler(wrangler));
7808
8416
  cloudflare.wrangler = wrangler;
7809
8417
  nitro.cloudflare = cloudflare;
7810
8418
  const rollupConfig = { ...record(nitro.rollupConfig) };
7811
8419
  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));
8420
+ if (!plugins.some((plugin) => record(plugin).name === "vitehub-workflow-cloudflare-exports")) plugins.push(createCloudflareWorkflowNitroPlugin(artifacts.cloudflareWorkerFile, artifacts.providerDefinitions, concurrency));
7813
8421
  rollupConfig.plugins = plugins;
7814
8422
  rollupConfig.external = mergeCloudflareWorkersExternal(rollupConfig.external);
7815
8423
  nitro.rollupConfig = rollupConfig;
@@ -7818,10 +8426,6 @@ async function createCloudflareWorkflowNitroConfig(options) {
7818
8426
  function renderRegistryImport(registryFile, file) {
7819
8427
  return `import(${JSON.stringify(pathToFileURL(file).href)})`;
7820
8428
  }
7821
- function resolveAgentWorkspaceSourceRoot(file) {
7822
- const workspaceDirectory = join(dirname$1(file), "workspace");
7823
- return existsSync(workspaceDirectory) && statSync(workspaceDirectory).isDirectory() ? workspaceDirectory : dirname$1(file);
7824
- }
7825
8429
  function readAgentInstructions(file, dependencies) {
7826
8430
  const instructions = join(dirname$1(file), "instructions.md");
7827
8431
  if (!existsSync(instructions) || !statSync(instructions).isFile()) return;
@@ -7842,23 +8446,33 @@ function readAgentSkills(file) {
7842
8446
  }));
7843
8447
  }
7844
8448
  function renderAgentWorkflowRegistryEntry(registryFile, definition, retainedAgentInstructions) {
8449
+ const { sourceRootDir, projectSourceRoot } = resolveDiscoveredAgentSourceRoot(definition);
7845
8450
  const instructions = retainedAgentInstructions?.has(definition.handler) ? retainedAgentInstructions.get(definition.handler) : readAgentInstructions(definition.handler);
7846
8451
  return [
7847
8452
  ` [${JSON.stringify(definition.name)}]: Object.assign(async () => {`,
7848
8453
  ` const cached = registryEntryCache.get(${JSON.stringify(definition.name)})`,
7849
8454
  " if (cached) return cached",
7850
8455
  ` const loaded = await ${renderRegistryImport(registryFile, definition.handler)}`,
7851
- ` const agent = workspaceAgentWithSourceRoot(agentWithColocatedSkills(agentWithColocatedInstructions("default" in loaded ? loaded.default : loaded, ${JSON.stringify(instructions)}), ${JSON.stringify(readAgentSkills(definition.handler))}), ${JSON.stringify(resolveAgentWorkspaceSourceRoot(definition.handler))}, ${JSON.stringify(instructions)})`,
8456
+ ` const agent = workspaceAgentWithSourceRoot(agentWithColocatedSkills(agentWithColocatedInstructions("default" in loaded ? loaded.default : loaded, ${JSON.stringify(instructions)}), ${JSON.stringify(readAgentSkills(definition.handler))}), ${JSON.stringify(sourceRootDir)}, ${JSON.stringify(instructions)}, ${projectSourceRoot})`,
7852
8457
  ` const entry = { rootStep: false, handler: async (context) => await runAgentWorkflowDefinition(agent, { ...context, payload: { ...context.payload, agentIdentity: context.payload?.agentIdentity || { name: ${JSON.stringify(definition.agentIdentity || definition.name)} } } }, runAgentInline)${definition.source === "agent-workflow-recovery" ? ", internalAgentInvocationRecovery: true" : ""} }`,
7853
8458
  ` registryEntryCache.set(${JSON.stringify(definition.name)}, entry)`,
7854
8459
  " return entry",
7855
8460
  ` }, ${definition.source === "agent-workflow-recovery" ? "{ internalAgentInvocationRecovery: true }" : "{}"}),`
7856
8461
  ].join("\n");
7857
8462
  }
8463
+ function isAgentWorkflowDefinition(definition) {
8464
+ return definition.source === "agent-workflow" || definition.source === "agent-workflow-recovery";
8465
+ }
8466
+ function hasWorkflowIndexHandler(definition) {
8467
+ return definition.steps !== void 0 && /\.(?:c|m)?[jt]s$/i.test(definition.handler);
8468
+ }
7858
8469
  function getGeneratedVercelWorkflowExport(definition) {
7859
- if (!definition.steps?.length || /\.(?:c|m)?[jt]s$/i.test(definition.handler)) return;
8470
+ if (isAgentWorkflowDefinition(definition) || hasWorkflowIndexHandler(definition) || definition.steps?.length === 0) return;
7860
8471
  return `${getCloudflareWorkflowClassName(definition.name)}Native`;
7861
8472
  }
8473
+ function generatedVercelWorkflowFileName(name) {
8474
+ return createHash("sha256").update(name).digest("hex");
8475
+ }
7862
8476
  /** `@workflow/core` keeps the `sleep()` implementation of the Workflow VM on `globalThis` under this registered symbol. */
7863
8477
  const vercelWorkflowSleepSymbol = "WORKFLOW_SLEEP";
7864
8478
  function renderVercelNativeStep(name, implementation, step, options) {
@@ -7868,8 +8482,21 @@ async function createVercelNativeWorkflowContents(definition) {
7868
8482
  const imports = [];
7869
8483
  const workflows = [];
7870
8484
  const workflowExport = getGeneratedVercelWorkflowExport(definition);
8485
+ if (!workflowExport) return "";
8486
+ const startAt = `context[${JSON.stringify(workflowStartAtKey)}]`;
8487
+ const waitForStart = ` if (typeof ${startAt} === "number") await globalThis[Symbol.for(${JSON.stringify(vercelWorkflowSleepSymbol)})](new Date(${startAt}))`;
7871
8488
  const steps = definition.steps;
7872
- if (!workflowExport || !steps) return "";
8489
+ if (!steps) {
8490
+ const module = `${workflowExport}Module`;
8491
+ const step = `${workflowExport}Step`;
8492
+ return [
8493
+ `import * as ${module} from ${JSON.stringify(definition.handler)}`,
8494
+ "",
8495
+ `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}`,
8496
+ `export async function ${workflowExport}(context) {\n "use workflow"\n${waitForStart}\n return await ${step}(context.payload)\n}`,
8497
+ ""
8498
+ ].join("\n");
8499
+ }
7873
8500
  const stepOptions = await Promise.all(steps.map(readWorkflowStepOptions));
7874
8501
  const stepNames = steps.map((step, index) => {
7875
8502
  const implementation = `${workflowExport}Step${index}Implementation`;
@@ -7878,8 +8505,7 @@ async function createVercelNativeWorkflowContents(definition) {
7878
8505
  workflows.push(renderVercelNativeStep(name, implementation, `${definition.name}/${relative$1(definition.handler, step)}`, stepOptions[index]));
7879
8506
  return name;
7880
8507
  });
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}`);
8508
+ 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
8509
  return [
7884
8510
  ...imports,
7885
8511
  "",
@@ -7888,30 +8514,44 @@ async function createVercelNativeWorkflowContents(definition) {
7888
8514
  ].join("\n");
7889
8515
  }
7890
8516
  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)},`;
8517
+ if (isAgentWorkflowDefinition(definition)) return renderAgentWorkflowRegistryEntry(registryFile, definition, retainedAgentInstructions);
8518
+ const nativeExport = getGeneratedVercelWorkflowExport(definition);
8519
+ const vercelNativeFile = Object.hasOwn(vercelNativeFiles, definition.name) ? vercelNativeFiles[definition.name] : void 0;
8520
+ const nativeReference = nativeExport && vercelNativeFile ? `const native = Object.assign(async () => (await import(${JSON.stringify(workflowRuntimeModule("execute"))})).rejectDirectGeneratedWorkflowCall(), ${JSON.stringify({
8521
+ workflowId: `workflow//./.vitehub/workflow/vercel-native/${generatedVercelWorkflowFileName(definition.name)}//${nativeExport}`,
8522
+ [generatedNativeEntryKey]: true,
8523
+ ...definition.steps ? {} : { [generatedNativeRootStepKey]: true }
8524
+ })})` : "";
8525
+ if (!definition.steps) {
8526
+ if (!nativeReference) return ` [${JSON.stringify(definition.name)}]: async () => ${renderRegistryImport(registryFile, definition.handler)},`;
8527
+ return [
8528
+ ` [${JSON.stringify(definition.name)}]: async () => {`,
8529
+ ` const loaded = await ${renderRegistryImport(registryFile, definition.handler)}`,
8530
+ " if (typeof loaded.default?.handler !== \"function\" || loaded.default.native) return loaded",
8531
+ ` ${nativeReference}`,
8532
+ " return { ...loaded, default: { ...loaded.default, native } }",
8533
+ " },"
8534
+ ].join("\n");
8535
+ }
7893
8536
  const workflowDirectory = /\.(?:c|m)?[jt]s$/i.test(definition.handler) ? dirname$1(definition.handler) : definition.handler;
7894
8537
  const stepImports = definition.steps.map((step) => {
7895
8538
  const stepName = relative$1(workflowDirectory, step);
7896
8539
  return `{ name: ${JSON.stringify(stepName)}, ...await ${renderRegistryImport(registryFile, step)}.then(step => ({ options: { retries: step.retries, timeout: step.timeout }, run: step.default })) }`;
7897
8540
  });
7898
- const hasIndex = /\.(?:c|m)?[jt]s$/i.test(definition.handler);
8541
+ const hasIndex = hasWorkflowIndexHandler(definition);
7899
8542
  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
8543
  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
8544
  return [
7905
8545
  ` [${JSON.stringify(definition.name)}]: async () => {`,
7906
8546
  ` const cached = registryEntryCache.get(${JSON.stringify(definition.name)})`,
7907
8547
  " if (cached) return cached",
7908
8548
  indexImport ? ` ${indexImport}` : "",
7909
- nativeImport ? ` ${nativeImport}` : "",
8549
+ nativeReference ? ` ${nativeReference}` : "",
7910
8550
  ` const steps = [${stepImports.join(", ")}]`,
7911
8551
  ` const definition = ${handler}`,
7912
8552
  " const entry = {",
7913
8553
  " ...definition,",
7914
- ` rootStep: false,${nativeImport ? " native," : ""}`,
8554
+ ` rootStep: false,${nativeReference ? " native," : ""}`,
7915
8555
  " handler: async (context) => {",
7916
8556
  " const workflowSteps = createWorkflowSteps(context, steps)",
7917
8557
  " return await definition.handler({ ...context, steps: workflowSteps })",
@@ -7999,7 +8639,7 @@ function createWorkflowRegistryContents(registryFile, definitions, importBases =
7999
8639
  ""
8000
8640
  ].join("\n");
8001
8641
  }
8002
- function createWorkflowRegistryIndexContents(definitions) {
8642
+ function createWorkflowRegistryIndexContents(definitions, requireVercelNative) {
8003
8643
  return [
8004
8644
  `const loadRegistryRuntime = () => import(${JSON.stringify(`./${generatedRegistryRuntimeFileName}`)})`,
8005
8645
  "",
@@ -8009,6 +8649,7 @@ function createWorkflowRegistryIndexContents(definitions) {
8009
8649
  return definition.source === "agent-workflow-recovery" ? ` [${JSON.stringify(definition.name)}]: Object.assign(${loader}, { internalAgentInvocationRecovery: true }),` : ` [${JSON.stringify(definition.name)}]: ${loader},`;
8010
8650
  }),
8011
8651
  "}",
8652
+ ...requireVercelNative ? [`Object.defineProperty(registry, Symbol.for(${JSON.stringify(vercelNativeRegistryKey)}), { value: true })`] : [],
8012
8653
  "",
8013
8654
  "export default registry",
8014
8655
  ""
@@ -8019,6 +8660,7 @@ function renderCloudflareWorkerWrapper(definitions) {
8019
8660
  return [
8020
8661
  definitions.length ? `import { WorkflowEntrypoint, waitUntil as viteHubWaitUntil } from "cloudflare:workers"` : `import { waitUntil as viteHubWaitUntil } from "cloudflare:workers"`,
8021
8662
  cloudflareWorkflowWrapperImport,
8663
+ ...usesCloudflareConcurrency(definitions) ? [`export { ${cloudflareConcurrencyClassName} } from "./worker.mjs"`] : [],
8022
8664
  "",
8023
8665
  ...definitions.map((definition) => renderCloudflareWorkflowEntrypoint(definition, legacyAliases)),
8024
8666
  "const viteHubWorker = {",
@@ -8032,7 +8674,7 @@ function renderCloudflareWorkerWrapper(definitions) {
8032
8674
  ""
8033
8675
  ].join("\n");
8034
8676
  }
8035
- function renderProviderEntry(spec, entryFile, userAppEntry, serializedWorkflowConfig, workflowImportBase, framework) {
8677
+ function renderProviderEntry(spec, entryFile, userAppEntry, serializedWorkflowConfig, workflowImportBase, framework, concurrency = false) {
8036
8678
  const installVercelWorkflowRuntime = spec.name === "vercel" && framework;
8037
8679
  const imports = [
8038
8680
  `import { ${spec.factory}${spec.name === "cloudflare" ? ", installWorkflowCloudflareRuntime" : ""}${installVercelWorkflowRuntime ? ", setVercelWorkflowRuntimeModules" : ""} } from ${JSON.stringify(workflowRuntimeModule(spec.runtimeModule))}`,
@@ -8043,6 +8685,7 @@ function renderProviderEntry(spec, entryFile, userAppEntry, serializedWorkflowCo
8043
8685
  if (userAppEntry) imports.push(`import workflowApp from ${JSON.stringify(createImportPath(entryFile, userAppEntry))}`);
8044
8686
  const cloudflareDispatcher = spec.name === "cloudflare" ? [
8045
8687
  "",
8688
+ ...concurrency ? [`export { ${cloudflareConcurrencyClassName} } from ${JSON.stringify(workflowRuntimeModule("cloudflare-concurrency"))}`, ""] : [],
8046
8689
  "export function installViteHubWorkflowRuntime() {",
8047
8690
  " installWorkflowCloudflareRuntime({ registry: workflowRegistry, workflow: workflowConfig })",
8048
8691
  "}",
@@ -8067,29 +8710,52 @@ function renderProviderEntry(spec, entryFile, userAppEntry, serializedWorkflowCo
8067
8710
  ""
8068
8711
  ].filter(Boolean).join("\n");
8069
8712
  }
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");
8713
+ /**
8714
+ * Writes the generated entries for single-file Workflows and folders with only numbered steps, into
8715
+ * `<generatedDir>/vercel-native`. It returns the entry file of each Workflow name.
8716
+ */
8717
+ async function writeVercelNativeWorkflowFiles(generatedDir, definitions) {
8080
8718
  const vercelNativeDir = resolve$1(generatedDir, "vercel-native");
8081
- const nativeDefinitions = definitions.filter((definition) => getGeneratedVercelWorkflowExport(definition));
8719
+ const nativeDefinitions = definitions.filter((definition) => {
8720
+ if (!getGeneratedVercelWorkflowExport(definition)) return false;
8721
+ if (definition.steps) return true;
8722
+ const parsed = parseWorkflowModule(definition.handler);
8723
+ return Object.values(parsed.metafile.outputs).some((output) => output.exports.includes("default")) && !declaresVercelNativeWorkflow(definition.handler);
8724
+ });
8082
8725
  await rm(resolve$1(generatedDir, "vercel-native.mjs"), { force: true });
8083
8726
  await rm(vercelNativeDir, {
8084
8727
  force: true,
8085
8728
  recursive: true
8086
8729
  });
8087
- const vercelNativeFiles = Object.fromEntries(nativeDefinitions.map((definition) => [definition.name, resolve$1(vercelNativeDir, `${createHash("sha256").update(definition.name).digest("hex")}.mjs`)]));
8730
+ const vercelNativeFiles = Object.fromEntries(nativeDefinitions.map((definition) => [definition.name, resolve$1(vercelNativeDir, `${generatedVercelWorkflowFileName(definition.name)}.mjs`)]));
8088
8731
  if (nativeDefinitions.length) await mkdir(vercelNativeDir, { recursive: true });
8089
8732
  await Promise.all(nativeDefinitions.map(async (definition) => {
8090
8733
  const nativeFile = vercelNativeFiles[definition.name];
8091
8734
  await writeFile(nativeFile, await createVercelNativeWorkflowContents(definition), "utf8");
8092
8735
  }));
8736
+ return vercelNativeFiles;
8737
+ }
8738
+ async function writeProviderEntries(rootDir, workflow, importBases = {}, serverDirs, includeUserAppEntry = true, transformRegistry, definitionRootDir = rootDir, generatedDir = ensureGeneratedDir(rootDir, productName), retainedAgentInstructions, requireVercelNative = false, projectRoot = definitionRootDir, flatAgentSources) {
8739
+ await mkdir(generatedDir, { recursive: true });
8740
+ const registryFile = resolve$1(generatedDir, generatedRegistryFileName);
8741
+ const discovered = discoverWorkflowDefinitions({
8742
+ projectRoot,
8743
+ rootDir: definitionRootDir,
8744
+ serverDirs
8745
+ });
8746
+ const definitions = flatAgentSources ? await Promise.all(discovered.map(async (definition) => {
8747
+ if (definition.source !== "agent-workflow" || !definition.sourceRootDir || resolveColocatedAgentWorkspaceRoot(definition.handler)) return definition;
8748
+ const sourceRootDir = flatAgentSourceSnapshotDir(flatAgentSources.sourcesDir, definition.handler, projectRoot);
8749
+ await snapshotFlatAgentSources(definition.handler, flatAgentSources.projectRoot, sourceRootDir);
8750
+ return {
8751
+ ...definition,
8752
+ sourceRootDir
8753
+ };
8754
+ })) : discovered;
8755
+ const providerDefinitions = withAgentInvocationRecoveryDefinitions(definitions);
8756
+ const userAppEntry = includeUserAppEntry ? resolveWorkflowUserAppEntry(definitionRootDir, includeUserAppEntry) : void 0;
8757
+ const cloudflareWorkflowConfig = resolveWorkflowConfig(workflow, "cloudflare");
8758
+ const vercelNativeFiles = await writeVercelNativeWorkflowFiles(generatedDir, definitions);
8093
8759
  await Promise.all(definitions.filter((definition) => !getGeneratedVercelWorkflowExport(definition)).flatMap((definition) => definition.steps ?? []).map(async (step) => await readWorkflowStepOptions(step)));
8094
8760
  const registryRuntimeFile = resolve$1(generatedDir, generatedRegistryRuntimeFileName);
8095
8761
  const agentModules = importBases.agent ?? (providerDefinitions.some((definition) => definition.source === "agent-workflow") ? await installedAgentWorkflowModules(rootDir) : void 0);
@@ -8098,7 +8764,7 @@ async function writeProviderEntries(rootDir, workflow, importBases = {}, serverD
8098
8764
  agent: agentModules
8099
8765
  }, vercelNativeFiles, retainedAgentInstructions);
8100
8766
  await writeFile(registryRuntimeFile, transformRegistry ? await transformRegistry(registryContents, registryRuntimeFile) : registryContents, "utf8");
8101
- await writeFile(registryFile, createWorkflowRegistryIndexContents(providerDefinitions), "utf8");
8767
+ await writeFile(registryFile, createWorkflowRegistryIndexContents(providerDefinitions, requireVercelNative), "utf8");
8102
8768
  const entryFiles = {
8103
8769
  cloudflare: "",
8104
8770
  openworkflow: "",
@@ -8108,7 +8774,7 @@ async function writeProviderEntries(rootDir, workflow, importBases = {}, serverD
8108
8774
  const entryFile = resolve$1(generatedDir, spec.entryFile);
8109
8775
  const workflowConfig = spec.name === "cloudflare" ? cloudflareWorkflowConfig : resolveWorkflowConfig(workflow, spec.hosting);
8110
8776
  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");
8777
+ await writeFile(entryFile, renderProviderEntry(spec, entryFile, userAppEntry, serialized, importBases.workflow ?? "@vite-hub/workflow", Boolean(importBases.workflow), spec.name === "cloudflare" && usesCloudflareConcurrency(providerDefinitions)), "utf8");
8112
8778
  entryFiles[spec.name] = entryFile;
8113
8779
  }));
8114
8780
  return {
@@ -8148,12 +8814,14 @@ function createCloudflareOutput(rootDir, artifacts, providerImportAliases) {
8148
8814
  const workflowConfig = artifacts.cloudflareWorkflowConfig && artifacts.cloudflareWorkflowConfig.driver === "cloudflare" ? artifacts.cloudflareWorkflowConfig : false;
8149
8815
  const workflowDefinitions = workflowConfig ? artifacts.providerDefinitions : [];
8150
8816
  const workflows = createCloudflareWorkflowBindings(workflowDefinitions, workflowConfig);
8817
+ const concurrency = usesCloudflareConcurrency(workflowDefinitions);
8151
8818
  const wranglerConfig = {
8152
8819
  compatibility_date: defaultCloudflareCompatibilityDate,
8153
8820
  compatibility_flags: ["nodejs_compat"],
8154
8821
  main: "index.js",
8155
8822
  observability: { enabled: true },
8156
- ...workflows ? { workflows } : {}
8823
+ ...workflows ? { workflows } : {},
8824
+ ...concurrency ? addCloudflareConcurrencyWrangler({}) : {}
8157
8825
  };
8158
8826
  return {
8159
8827
  bundleEntry: artifacts.cloudflareWorkerFile,
@@ -8184,7 +8852,10 @@ function createCloudflareOutput(rootDir, artifacts, providerImportAliases) {
8184
8852
  bundleOutfileName: "worker.mjs",
8185
8853
  files: { "index.js": createCloudflareWorkflowWrapper(artifacts) },
8186
8854
  outputRoot: createDefaultCloudflareOutputRoot(rootDir),
8187
- wranglerConfigKeys: cloudflareWorkflowWranglerConfigKeys,
8855
+ wranglerConfigOwnership: {
8856
+ ...cloudflareConcurrencyWranglerOwnership,
8857
+ keys: cloudflareWorkflowWranglerConfigKeys
8858
+ },
8188
8859
  wranglerConfig
8189
8860
  };
8190
8861
  }
@@ -8206,7 +8877,10 @@ async function createCloudflareWorkflowCleanup(rootDir, cloudflareInNitro = fals
8206
8877
  deployedWorkflowSourcesPath
8207
8878
  ] : ["worker.mjs", deployedWorkflowSourcesPath],
8208
8879
  outputRoot,
8209
- wranglerConfigOwnership: { keys: cloudflareInNitro ? [] : ownsWrapper ? cloudflareWorkflowWranglerConfigKeys : ["workflows"] }
8880
+ wranglerConfigOwnership: {
8881
+ ...ownsWrapper && !cloudflareInNitro ? cloudflareConcurrencyWranglerOwnership : {},
8882
+ keys: cloudflareInNitro ? [] : ownsWrapper ? cloudflareWorkflowWranglerConfigKeys : ["workflows"]
8883
+ }
8210
8884
  };
8211
8885
  }
8212
8886
  function createVercelOutput(rootDir, artifacts, workflowTransformPlugin, frameworkImportBase, providerImportAliases, serverFunctionName) {
@@ -8365,16 +9039,44 @@ async function assertVercelStepRetries(definitions) {
8365
9039
  }
8366
9040
  }
8367
9041
  }
9042
+ function assertVercelWorkflowsRunNatively(definitions) {
9043
+ for (const definition of definitions) {
9044
+ if (declaresWorkflowConcurrency(definition)) throw workflowErrorDiagnostics.WORKFLOW_CONCURRENCY_VERCEL_UNSUPPORTED({ name: definition.name });
9045
+ if (isAgentWorkflowDefinition(definition) || !hasWorkflowIndexHandler(definition) || declaresVercelNativeWorkflow(definition.handler)) continue;
9046
+ throw workflowErrorDiagnostics.WORKFLOW_VERCEL_INDEX_NOT_NATIVE({
9047
+ file: definition.handler,
9048
+ name: definition.name
9049
+ });
9050
+ }
9051
+ }
9052
+ function resolveVercelNativeWorkflowAliases(providerAliases, nitroAliases = {}) {
9053
+ return {
9054
+ ...nitroAliases,
9055
+ ...providerAliases,
9056
+ ...Object.fromEntries(Object.entries(nitroAliases).filter(([find]) => find.startsWith("@vite-hub/") || find.startsWith("#vitehub/")))
9057
+ };
9058
+ }
9059
+ async function writeNitroVercelNativeWorkflowOutput(rootDir, artifacts, aliases, bundleDefines) {
9060
+ await withProviderDeploymentOutputLock(rootDir, async () => {
9061
+ assertVercelWorkflowsRunNatively(artifacts.providerDefinitions);
9062
+ await assertVercelStepRetries(artifacts.providerDefinitions);
9063
+ await buildVercelNativeWorkflowOutput(rootDir, artifacts.providerDefinitions, aliases, artifacts.vercelNativeFiles, await readVercelNativeWorkflowState(rootDir), bundleDefines);
9064
+ await updateVercelWorkflowFunctionOwnership(rootDir, void 0, false);
9065
+ });
9066
+ }
8368
9067
  async function generateProviderOutputsWithinLock(options, writeProviderDeploymentOutputs) {
9068
+ const { cloudflare: cloudflareWorkflowConfig, vercel: vercelWorkflowConfig } = resolveWorkflowProviderOutputs(options.workflow, options.hosting, options.inline);
9069
+ const vercelWorkflow = Boolean(vercelWorkflowConfig && vercelWorkflowConfig.driver === "vercel");
8369
9070
  let artifacts = options.artifacts ?? await writeProviderEntries(options.rootDir, options.workflow, {
8370
9071
  agent: options.agentModules,
8371
9072
  workflow: options.importBase,
8372
9073
  workspaceRuntime: options.workspaceRuntimeModule,
8373
9074
  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);
9075
+ }, options.serverDirs, options.includeUserAppEntry, options.transformRegistry, options.definitionRootDir, void 0, void 0, vercelWorkflow);
9076
+ if (vercelWorkflow) {
9077
+ assertVercelWorkflowsRunNatively(artifacts.providerDefinitions);
9078
+ await assertVercelStepRetries(artifacts.providerDefinitions);
9079
+ }
8378
9080
  const workflowTransformPlugin = vercelWorkflow && !options.nitroServer ? await createVercelWorkflowTransformPlugin(options.rootDir) : void 0;
8379
9081
  let commitGeneratedArtifacts = async () => {};
8380
9082
  let rollbackGeneratedArtifacts = async () => {};
@@ -8473,11 +9175,11 @@ async function generateProviderOutputsWithinLock(options, writeProviderDeploymen
8473
9175
  handler: publishedSource(definition.handler),
8474
9176
  ...definition.steps ? { steps: definition.steps.map(publishedSource) } : {}
8475
9177
  }));
8476
- const nativeAliases = Object.fromEntries(Object.entries({
9178
+ const nativeAliases = Object.fromEntries(Object.entries(resolveVercelNativeWorkflowAliases({
8477
9179
  ...options.providerImportAliases,
8478
9180
  ...options.providerRuntimeImportAliases?.vercel
8479
- }).map(([alias, target]) => [alias, publishedSource(target)]));
8480
- if (vercelWorkflow && hasVercelNativeWorkflowEntry(options.rootDir, nativeDefinitions, nativeAliases, artifacts.vercelNativeFiles)) assertNoExternalCanonicalWorkflowOutput(previousNativeOutput);
9181
+ }, options.nitroAliases)).map(([alias, target]) => [alias, publishedSource(target)]));
9182
+ if (!options.nativeOutputInNitro && vercelWorkflow && hasVercelNativeWorkflowEntry(options.rootDir, nativeDefinitions, nativeAliases, artifacts.vercelNativeFiles)) assertNoExternalCanonicalWorkflowOutput(previousNativeOutput);
8481
9183
  const deploymentOutput = {
8482
9184
  clientOutDir: options.clientOutDir,
8483
9185
  cloudflare: cloudflareOutput,
@@ -8506,10 +9208,11 @@ async function generateProviderOutputsWithinLock(options, writeProviderDeploymen
8506
9208
  signal
8507
9209
  });
8508
9210
  }
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));
9211
+ if (!options.nativeOutputInNitro) {
9212
+ if (vercelWorkflow) await buildVercelNativeWorkflowOutput(options.rootDir, nativeDefinitions, nativeAliases, artifacts.vercelNativeFiles, previousNativeOutput, options.bundleDefines);
9213
+ else await cleanVercelNativeWorkflowOutput(options.rootDir);
9214
+ await updateVercelWorkflowFunctionOwnership(options.rootDir, vercelOutput ? options.serverFunctionName ?? "__server.func" : void 0, Boolean(vercelOutput && !options.serverFunctionName));
9215
+ }
8513
9216
  signal?.throwIfAborted();
8514
9217
  },
8515
9218
  rootDir: options.rootDir,
@@ -8603,8 +9306,10 @@ const workflowConsoleSection = {
8603
9306
  }
8604
9307
  };
8605
9308
  // src/internal/dev-registry.ts
8606
- const workflowDevGeneratedDir = ".vitehub/nitro/workflow";
8607
9309
  const workflowTestSetupFile = "test-setup.mjs";
9310
+ function workflowDevGeneratedDirectory(projectRoot, owner) {
9311
+ return resolve$1(viteHubGeneratedCodeRoot(projectRoot, owner), "nitro", "workflow");
9312
+ }
8608
9313
  const generatedFilesSeparatePerCommand = {
8609
9314
  build: {
8610
9315
  plugin: "build-plugin.mjs",
@@ -8708,7 +9413,7 @@ async function writeIfChanged(file, contents) {
8708
9413
  * not change are not written again.
8709
9414
  */
8710
9415
  async function writeWorkflowDevRegistryFiles(options) {
8711
- const directory = resolve$1(options.projectRoot, workflowDevGeneratedDir);
9416
+ const directory = workflowDevGeneratedDirectory(options.projectRoot, options.owner);
8712
9417
  await mkdir(directory, { recursive: true });
8713
9418
  const names = generatedFilesSeparatePerCommand[options.dev ? "dev" : "build"];
8714
9419
  const registry = resolve$1(directory, names.registry);
@@ -8751,12 +9456,14 @@ function importSpecifier(file, target) {
8751
9456
  * the step files of each folder Workflow (`WorkflowStepRegistry`).
8752
9457
  */
8753
9458
  function createWorkflowTypes(file, definitions, importBase = "@vite-hub/workflow") {
8754
- const registryEntries = definitions.flatMap((definition) => {
9459
+ const agentEntries = definitions.filter(isAgentWorkflow).map((definition) => ` ${JSON.stringify(definition.name)}: unknown`);
9460
+ const standalone = definitions.filter((definition) => !isAgentWorkflow(definition));
9461
+ const registryEntries = standalone.flatMap((definition) => {
8755
9462
  if (!sourceFilePattern.test(definition.handler)) return [` ${JSON.stringify(definition.name)}: import(${JSON.stringify(importBase)}).WorkflowDefinition<unknown>`];
8756
9463
  const moduleType = `typeof import(${JSON.stringify(importSpecifier(file, definition.handler))})`;
8757
9464
  return [...javaScriptFilePattern.test(definition.handler) ? [` ${ignoreJavaScriptTypes}`] : [], ` ${JSON.stringify(definition.name)}: ${moduleType} extends { default: infer TDefault } ? TDefault : unknown`];
8758
9465
  });
8759
- const stepEntries = definitions.filter((definition) => definition.steps?.length).flatMap((definition) => {
9466
+ const stepEntries = standalone.filter((definition) => definition.steps?.length).flatMap((definition) => {
8760
9467
  const directory = sourceFilePattern.test(definition.handler) ? dirname(definition.handler) : definition.handler;
8761
9468
  return [
8762
9469
  ` ${JSON.stringify(definition.name)}: {`,
@@ -8770,6 +9477,11 @@ function createWorkflowTypes(file, definitions, importBase = "@vite-hub/workflow
8770
9477
  " interface WorkflowRegistry {",
8771
9478
  ...registryEntries,
8772
9479
  " }",
9480
+ ...agentEntries.length ? [
9481
+ " interface AgentWorkflowRegistry {",
9482
+ ...agentEntries,
9483
+ " }"
9484
+ ] : [],
8773
9485
  " interface WorkflowStepRegistry {",
8774
9486
  ...stepEntries,
8775
9487
  " }",
@@ -8777,6 +9489,9 @@ function createWorkflowTypes(file, definitions, importBase = "@vite-hub/workflow
8777
9489
  ""
8778
9490
  ].join("\n");
8779
9491
  }
9492
+ function isAgentWorkflow(definition) {
9493
+ return definition.source === "agent-workflow" || definition.source === "agent-workflow-recovery";
9494
+ }
8780
9495
  /**
8781
9496
  * Writes `.vitehub/workflow.d.ts` when its contents change. Keep an empty declaration before the first
8782
9497
  * folder step so ViteHub's types entry can reference it throughout a development session.
@@ -8804,6 +9519,10 @@ function agentWorkflowRegistryTransform(plugins) {
8804
9519
  const noExternalAddition = createNoExternalAddition(workflowPackageName);
8805
9520
  const workflowBuildAssociation = Symbol("vitehubWorkflowBuildAssociation");
8806
9521
  const workflowEnvironmentAssociation = Symbol("vitehubWorkflowEnvironmentAssociation");
9522
+ function workflowProjectRoot(config) {
9523
+ const configured = Reflect.get(config, VITEHUB_PROJECT_ROOT);
9524
+ return resolveViteHubProjectRoot(config.root, { projectRoot: typeof configured === "string" ? configured : void 0 });
9525
+ }
8807
9526
  function resolveStringAliases(config) {
8808
9527
  return encodeProviderOutputAliases(config.resolve.alias);
8809
9528
  }
@@ -8897,11 +9616,12 @@ function hubWorkflow(workflow, internalOptions = {}) {
8897
9616
  const build = scheduledBuildConfig(config);
8898
9617
  const workflowOptions = build?.workflow ?? workflow;
8899
9618
  if (resolveWorkflow(workflowOptions)?.driver !== "vercel") return;
8900
- const rootDir = resolveViteHubProjectRoot(config.root);
9619
+ const rootDir = workflowProjectRoot(config);
8901
9620
  const aliases = await providerImportAliases(config);
8902
9621
  const workflowServerDirs = config["__vitehubServerDirs"] ?? build?.serverDirs;
8903
9622
  const providerSources = discoverWorkflowProviderSources(config.root, workflowServerDirs);
8904
9623
  const retainedSources = artifactDir ? await retainProviderOutputSources({
9624
+ aliases,
8905
9625
  artifactDir: resolve$1(artifactDir, ".vitehub", "workflow", "sources"),
8906
9626
  paths: [...providerOutputAliasSources(aliases, [config.root]), ...providerSources.paths],
8907
9627
  roots: [config.root]
@@ -8914,7 +9634,11 @@ function hubWorkflow(workflow, internalOptions = {}) {
8914
9634
  workflow: internalOptions?.importBase,
8915
9635
  workspaceRuntime: internalOptions?.workspaceRuntimeModule,
8916
9636
  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);
9637
+ }, retainedServerDirs, internalOptions?.includeUserAppEntry, config.plugins.find((plugin) => plugin.vitehub?.agent?.transformWorkflowRegistry)?.vitehub?.agent?.transformWorkflowRegistry, definitionRootDir, artifactDir ? resolve$1(artifactDir, "output") : void 0, retainedAgentInstructions, true, retainedSources?.resolve(rootDir) ?? rootDir, artifactDir ? {
9638
+ projectRoot: rootDir,
9639
+ sourcesDir: resolve$1(artifactDir, ".vitehub", "workflow", "sources")
9640
+ } : void 0);
9641
+ assertVercelWorkflowsRunNatively(artifacts.providerDefinitions);
8918
9642
  const retainedAliases = retainedSources ? retainProviderOutputAliases(aliases, retainedSources) : aliases;
8919
9643
  const native = hasVercelNativeWorkflowEntry(rootDir, artifacts.providerDefinitions, retainedAliases, artifacts.vercelNativeFiles);
8920
9644
  const workflowRequire = native ? createRequire(import.meta.url) : void 0;
@@ -8945,6 +9669,7 @@ function hubWorkflow(workflow, internalOptions = {}) {
8945
9669
  let devRootDir;
8946
9670
  let nitroOptions;
8947
9671
  let vercelNativeEntry = false;
9672
+ let separateNitroConfig;
8948
9673
  function addVercelWorkflowWebhookRoute() {
8949
9674
  if (startupBuild && vercelNativeEntry && nitroOptions) addVercelWorkflowNitroRoutes(nitroOptions);
8950
9675
  }
@@ -8978,6 +9703,7 @@ function hubWorkflow(workflow, internalOptions = {}) {
8978
9703
  console.warn(`[vitehub:workflow] ${report} The dev server runs without Workflows until you fix the Workflow configuration.`);
8979
9704
  }
8980
9705
  let configPlugins;
9706
+ let generatedOwner = "app";
8981
9707
  async function writeDevRegistry(rootDir, workflow, vercel) {
8982
9708
  return await writeWorkflowDevRegistryFiles({
8983
9709
  agentModules: agentWorkflowModules(configPlugins),
@@ -8988,6 +9714,7 @@ function hubWorkflow(workflow, internalOptions = {}) {
8988
9714
  importBase: internalOptions.importBase,
8989
9715
  projectRoot: rootDir,
8990
9716
  pluginPath: devStartupPlugin,
9717
+ owner: generatedOwner,
8991
9718
  vercel,
8992
9719
  workflow
8993
9720
  });
@@ -8997,13 +9724,14 @@ function hubWorkflow(workflow, internalOptions = {}) {
8997
9724
  }
8998
9725
  let vercelModuleTransform;
8999
9726
  async function prepareVercelNitroRegistry(config) {
9000
- const rootDir = resolveViteHubProjectRoot(config.root);
9727
+ const rootDir = workflowProjectRoot(config);
9001
9728
  const artifacts = await writeProviderEntries(rootDir, workflow, {
9002
9729
  agent: agentWorkflowModules(config.plugins),
9003
9730
  workflow: internalOptions.importBase,
9004
9731
  workspaceRuntime: internalOptions.workspaceRuntimeModule,
9005
9732
  workspaceDependencies: internalOptions.workspaceDependencyRuntimeImports
9006
- }, serverDirs, internalOptions.includeUserAppEntry, config.plugins.find((plugin) => plugin.vitehub?.agent?.transformWorkflowRegistry)?.vitehub?.agent?.transformWorkflowRegistry, config.root);
9733
+ }, serverDirs, internalOptions.includeUserAppEntry, config.plugins.find((plugin) => plugin.vitehub?.agent?.transformWorkflowRegistry)?.vitehub?.agent?.transformWorkflowRegistry, config.root, void 0, void 0, true, rootDir);
9734
+ assertVercelWorkflowsRunNatively(artifacts.providerDefinitions);
9007
9735
  const native = hasVercelNativeWorkflowEntry(rootDir, artifacts.providerDefinitions, await providerImportAliases(config), artifacts.vercelNativeFiles);
9008
9736
  vercelModuleTransform = native ? await createVercelWorkflowModuleTransform(rootDir) : void 0;
9009
9737
  return {
@@ -9025,9 +9753,11 @@ function hubWorkflow(workflow, internalOptions = {}) {
9025
9753
  const buildConfig = config;
9026
9754
  buildConfig.__vitehubWorkflowServerDirs = serverDirs;
9027
9755
  startupBuild = env.command === "build";
9756
+ generatedOwner = viteHubGeneratedOwner(config);
9028
9757
  configPlugins = config.plugins;
9029
9758
  if (startupBuild && internalOptions.hosting) resolveWorkflow(workflow);
9030
9759
  devWorkflow = resolveDevWorkflow();
9760
+ contributeServerEnv(config, "workflow", workflowServerEnv(devWorkflow));
9031
9761
  if (startupBuild && !internalOptions.hosting && !resolveNitroVercelFunctionName(config, "workflow")) return;
9032
9762
  const projectRoot = Reflect.get(config, VITEHUB_PROJECT_ROOT);
9033
9763
  devRootDir = resolveViteHubProjectRoot(resolve$1(config.root || process.cwd()), { projectRoot: typeof projectRoot === "string" ? projectRoot : void 0 });
@@ -9036,7 +9766,7 @@ function hubWorkflow(workflow, internalOptions = {}) {
9036
9766
  const kit = createNitroServerKit(Reflect.get(config, "nitro"));
9037
9767
  kit.addPlugin(plugin, "start");
9038
9768
  Reflect.set(config, "nitro", kit.config);
9039
- if (process.env.VITEST) return { test: { setupFiles: [resolve$1(devRootDir, workflowDevGeneratedDir, workflowTestSetupFile)] } };
9769
+ if (process.env.VITEST) return { test: { setupFiles: [resolve$1(workflowDevGeneratedDirectory(devRootDir, generatedOwner), workflowTestSetupFile)] } };
9040
9770
  }
9041
9771
  },
9042
9772
  configureServer(server) {
@@ -9047,9 +9777,9 @@ function hubWorkflow(workflow, internalOptions = {}) {
9047
9777
  server.watcher.add([...watchedDirectories, rootDir]);
9048
9778
  const refresh = async (path) => {
9049
9779
  const file = path.replace(/\\/g, "/");
9050
- if (file.includes(`/.vitehub/nitro/workflow/`)) return;
9780
+ if (file.startsWith(`${workflowDevGeneratedDirectory(rootDir, generatedOwner).replace(/\\/g, "/")}/`)) return;
9051
9781
  const environment = server.environments.nitro ?? server.environments.ssr;
9052
- const registryPath = resolve$1(rootDir, workflowDevGeneratedDir, "dev-registry.mjs").replace(/\\/g, "/");
9782
+ const registryPath = resolve$1(workflowDevGeneratedDirectory(rootDir, generatedOwner), "dev-registry.mjs").replace(/\\/g, "/");
9053
9783
  const modules = [...environment?.moduleGraph.getModulesByFile(file) ?? []];
9054
9784
  const visited = /* @__PURE__ */ new Set();
9055
9785
  let registryDependency = false;
@@ -9066,8 +9796,8 @@ function hubWorkflow(workflow, internalOptions = {}) {
9066
9796
  }
9067
9797
  if (!(/\.(?:c|m)?[jt]s$/i.test(file) && /(?:\/workflows\/|\.workflow\.|\/agents\/|\.agent\.)/i.test(file)) && !registryDependency) return;
9068
9798
  const { changed } = await writeDevRegistry(rootDir, workflowConfig);
9069
- await writeWorkflowTypes(rootDir, discoverWorkflowDevDefinitions(rootDir, serverDirs), internalOptions.importBase);
9070
- const filesToInvalidate = new Set([...changed, resolve$1(rootDir, workflowDevGeneratedDir, "dev-registry.mjs")].map((file) => file.replace(/\\/g, "/")));
9799
+ await writeWorkflowTypes(rootDir, discoverWorkflowDevDefinitions(rootDir, serverDirs, registersAgentWorkflows(workflowConfig)), internalOptions.importBase);
9800
+ const filesToInvalidate = new Set([...changed, resolve$1(workflowDevGeneratedDirectory(rootDir, generatedOwner), "dev-registry.mjs")].map((file) => file.replace(/\\/g, "/")));
9071
9801
  let invalidated = false;
9072
9802
  for (const changedFile of filesToInvalidate) for (const module of environment?.moduleGraph.getModulesByFile(changedFile) ?? []) {
9073
9803
  environment.moduleGraph.invalidateModule(module);
@@ -9134,7 +9864,8 @@ function hubWorkflow(workflow, internalOptions = {}) {
9134
9864
  await writeDevRegistry(devRootDir, startupBuild ? devWorkflow && (buildNeedsStartupRegistry() || vercel) ? devWorkflow : void 0 : devWorkflow ?? false, vercel);
9135
9865
  }
9136
9866
  const typesRoot = devRootDir ?? resolveViteHubProjectRoot(config.root);
9137
- await writeWorkflowTypes(typesRoot, workflow === false ? [] : discoverWorkflowDevDefinitions(typesRoot, buildServerDirs), internalOptions.importBase);
9867
+ const typesWorkflow = devRootDir ? devWorkflow : resolveDevWorkflow();
9868
+ await writeWorkflowTypes(typesRoot, workflow === false ? [] : discoverWorkflowDevDefinitions(typesRoot, buildServerDirs, registersAgentWorkflows(typesWorkflow)), internalOptions.importBase);
9138
9869
  },
9139
9870
  configEnvironment(name, config) {
9140
9871
  if (!isServerEnvironment(name, config)) return;
@@ -9158,6 +9889,7 @@ function hubWorkflow(workflow, internalOptions = {}) {
9158
9889
  export: "workflowDurability",
9159
9890
  input: {
9160
9891
  driver: options.driver,
9892
+ ...options.driver === "vercel" && resolveOutputs(workflow).vercel ? { native: true } : {},
9161
9893
  defaultDatabase: options.driver === "openworkflow" && readPostgresDefaultDatabase(databasePlugin) === true,
9162
9894
  ...options.driver === "openworkflow" && options.postgres?.url !== void 0 ? { postgresUrl: workflowDurabilityUrl(options.postgres.url) } : {},
9163
9895
  ...options.driver === "openworkflow" && options.sqlite?.path !== void 0 ? { sqlitePath: options.sqlite.path } : {}
@@ -9233,6 +9965,9 @@ function hubWorkflow(workflow, internalOptions = {}) {
9233
9965
  };
9234
9966
  },
9235
9967
  workflow: {
9968
+ prepareSeparateNitroBuild(config) {
9969
+ if (resolveOutputs(workflow).vercel) separateNitroConfig = config;
9970
+ },
9236
9971
  async createNitroConfig({ nitro, projectRoot, serverDirs: nitroServerDirs, transformRegistry, viteConfig }) {
9237
9972
  if (viteConfig && (Reflect.get(viteConfig, "__vitehubNitroConfigContext") === true || !normalizeHosting(internalOptions.hosting).includes("cloudflare"))) return nitro;
9238
9973
  const input = viteConfig ? {
@@ -9265,6 +10000,21 @@ function hubWorkflow(workflow, internalOptions = {}) {
9265
10000
  providerOutputEnvironment.nitro.setup(nitro);
9266
10001
  nitroOptions = nitro.options;
9267
10002
  addVercelWorkflowWebhookRoute();
10003
+ const config = separateNitroConfig;
10004
+ if (!config) return;
10005
+ const nitroServerDirs = serverDirs;
10006
+ nitro.hooks?.hook("compiled", async () => {
10007
+ const rootDir = resolveViteHubProjectRoot(config.root);
10008
+ await writeNitroVercelNativeWorkflowOutput(rootDir, await writeProviderEntries(rootDir, workflow, {
10009
+ agent: agentWorkflowModules(config.plugins),
10010
+ workflow: internalOptions.importBase,
10011
+ workspaceRuntime: internalOptions.workspaceRuntimeModule,
10012
+ workspaceDependencies: internalOptions.workspaceDependencyRuntimeImports
10013
+ }, nitroServerDirs, internalOptions.includeUserAppEntry, agentWorkflowRegistryTransform(config.plugins), config.root, void 0, void 0, true), resolveVercelNativeWorkflowAliases({
10014
+ ...await providerImportAliases(config),
10015
+ ...providerRuntimeImportAliases("vercel", void 0, getProviderOutputCatalog(config))
10016
+ }, nitro.options.alias), resolveViteHubBundleDefines(config));
10017
+ });
9268
10018
  }
9269
10019
  },
9270
10020
  async buildStart() {
@@ -9321,7 +10071,7 @@ function hubWorkflow(workflow, internalOptions = {}) {
9321
10071
  const config = build?.config ?? resolved;
9322
10072
  const buildProviderOutput = build?.providerOutput ?? providerOutput;
9323
10073
  if (!config || shouldSkipViteProviderBuild(config.command)) return;
9324
- const rootDir = resolveViteHubProjectRoot(config.root);
10074
+ const rootDir = workflowProjectRoot(config);
9325
10075
  const plugins = config.plugins;
9326
10076
  const generation = providerOutputGenerations.get(this);
9327
10077
  const environment = generation ?? buildEnvironment(this);
@@ -9337,9 +10087,12 @@ function hubWorkflow(workflow, internalOptions = {}) {
9337
10087
  };
9338
10088
  const providerSources = discoverWorkflowProviderSources(config.root, workflowServerDirs);
9339
10089
  const outputs = resolveOutputs(workflowOptions);
9340
- const nitroServer = nitroOwnsVercelServer(config, workflowOptions);
10090
+ const nativeOutputInNitro = Boolean(separateNitroConfig && outputs.vercel);
10091
+ const nitroServer = nitroOwnsVercelServer(config, workflowOptions) || nativeOutputInNitro;
9341
10092
  const cloudflareInNitro = Reflect.get(config, "nitro")?.rollupConfig?.plugins?.some((plugin) => plugin?.name === "vitehub-workflow-cloudflare-exports") ?? false;
9342
- const retainedSources = !outputs.cloudflare && !outputs.vercel || nitroServer ? { resolve: (path) => path } : await retainProviderOutputSources({
10093
+ const retainsSources = Boolean(outputs.cloudflare || outputs.vercel) && !nitroServer;
10094
+ const retainedSources = !retainsSources ? { resolve: (path) => path } : await retainProviderOutputSources({
10095
+ aliases: importAliases,
9343
10096
  artifactDir: resolve$1(artifactDir, "sources"),
9344
10097
  paths: [
9345
10098
  ...providerOutputAliasSources(importAliases, [config.root]),
@@ -9362,11 +10115,14 @@ function hubWorkflow(workflow, internalOptions = {}) {
9362
10115
  workflow: internalOptions?.importBase,
9363
10116
  workspaceRuntime: internalOptions?.workspaceRuntimeModule,
9364
10117
  workspaceDependencies: internalOptions?.workspaceDependencyRuntimeImports
9365
- }, retainedServerDirs, internalOptions?.includeUserAppEntry, transformRegistry, retainedDefinitionRoot, resolve$1(artifactDir, "output"), retainedAgentInstructions);
10118
+ }, retainedServerDirs, internalOptions?.includeUserAppEntry, transformRegistry, retainedDefinitionRoot, resolve$1(artifactDir, "output"), retainedAgentInstructions, Boolean(outputs.vercel && outputs.vercel.driver === "vercel"), retainedSources.resolve(rootDir), retainsSources ? {
10119
+ projectRoot: rootDir,
10120
+ sourcesDir: resolve$1(artifactDir, "sources")
10121
+ } : void 0);
9366
10122
  stagedArtifactDirs.set(environment, artifactDir);
9367
10123
  contributeProviderDeploymentOutput(buildProviderOutput, {
9368
- discard: async () => {
9369
- await removeProviderOutputArtifactDir(artifactDir);
10124
+ discard: async (failure) => {
10125
+ await removeProviderOutputArtifactDir(artifactDir, failure);
9370
10126
  if (stagedArtifactDirs.get(environment) === artifactDir) stagedArtifactDirs.delete(environment);
9371
10127
  },
9372
10128
  owner: "workflow",
@@ -9389,6 +10145,8 @@ function hubWorkflow(workflow, internalOptions = {}) {
9389
10145
  definitionRootDir: retainedDefinitionRoot,
9390
10146
  serverDirs: retainedServerDirs,
9391
10147
  nitroServer,
10148
+ nitroAliases: nitroServer ? nitroOptions?.alias : void 0,
10149
+ nativeOutputInNitro,
9392
10150
  sourceRootDir: retainedSources.resolve(rootDir),
9393
10151
  includeUserAppEntry: internalOptions?.includeUserAppEntry,
9394
10152
  workflow: workflowOptions,
@@ -9399,7 +10157,7 @@ function hubWorkflow(workflow, internalOptions = {}) {
9399
10157
  }
9400
10158
  }, generation);
9401
10159
  } catch (error) {
9402
- await removeProviderOutputArtifactDir(artifactDir);
10160
+ await removeProviderOutputArtifactDir(artifactDir, error);
9403
10161
  if (stagedArtifactDirs.get(environment) === artifactDir) stagedArtifactDirs.delete(environment);
9404
10162
  await providerOutputGenerations.reset(this, buildProviderOutput, error);
9405
10163
  throw error;
@@ -9412,7 +10170,7 @@ function hubWorkflow(workflow, internalOptions = {}) {
9412
10170
  await providerOutputGenerations.reset(this, build?.providerOutput ?? providerOutput, error);
9413
10171
  const artifactDir = stagedArtifactDirs.get(environment);
9414
10172
  if (artifactDir) {
9415
- await removeProviderOutputArtifactDir(artifactDir);
10173
+ await removeProviderOutputArtifactDir(artifactDir, error);
9416
10174
  if (stagedArtifactDirs.get(environment) === artifactDir) stagedArtifactDirs.delete(environment);
9417
10175
  }
9418
10176
  },