@vite-hub/schedule 0.0.4 → 0.1.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 +68 -5
  2. package/dist/definition-CMiOg1lg.js +111 -0
  3. package/dist/definition.d.ts +4 -6
  4. package/dist/definition.js +2 -42
  5. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  6. package/dist/error-diagnostics-in7mif5s.js +45 -0
  7. package/dist/execute-BJrgNgQ0.js +201 -0
  8. package/dist/index.d.ts +7 -40
  9. package/dist/index.js +2 -7
  10. package/dist/inspect-DTfAo5gS.js +118 -0
  11. package/dist/kv-storage-Bv9ocZT-.d.ts +18 -0
  12. package/dist/nuxt.d.ts +4 -6
  13. package/dist/nuxt.js +2 -1
  14. package/dist/operations-gk2qzhYV.js +131 -0
  15. package/dist/operations-tNUdj3G4.d.ts +212 -0
  16. package/dist/operations.d.ts +61 -0
  17. package/dist/operations.js +921 -0
  18. package/dist/registry-module.d.ts +0 -5
  19. package/dist/runtime/kv.d.ts +4 -0
  20. package/dist/{kv-BJ1I9IlJ.js → runtime/kv.js} +1 -1
  21. package/dist/runtime/process.d.ts +26 -5
  22. package/dist/runtime/process.js +337 -75
  23. package/dist/runtime/state.d.ts +8 -12
  24. package/dist/runtime/state.js +2 -2
  25. package/dist/runtime/static.d.ts +18 -12
  26. package/dist/runtime/static.js +2 -150
  27. package/dist/runtime.d.ts +36 -4
  28. package/dist/runtime.js +5 -3
  29. package/dist/state-DSxmHPn3.js +448 -0
  30. package/dist/static-6g82xguw.js +245 -0
  31. package/dist/store-QAOd8bxm.d.ts +11 -0
  32. package/dist/types-CHdV9FQU.d.ts +113 -0
  33. package/dist/vite-BAVyZ8hZ.d.ts +474 -0
  34. package/dist/{vite-BHs17nWX.js → vite-BJwZkMrn.js} +1366 -339
  35. package/dist/vite.d.ts +2 -52
  36. package/dist/vite.js +2 -3
  37. package/dist/wait-until-BmIqRo4x.js +87 -0
  38. package/package.json +67 -21
  39. package/dist/client-DpCD4YFE.js +0 -233
  40. package/dist/discovery-DkFAN7Wd.d.ts +0 -15
  41. package/dist/discovery-DvU3B6iD.js +0 -753
  42. package/dist/due-Bbh4yIxq.js +0 -59
  43. package/dist/execute-B-pii4wf.js +0 -211
  44. package/dist/runtime/driver.d.ts +0 -26
  45. package/dist/runtime/driver.js +0 -337
  46. package/dist/state-By7WU_ks.js +0 -472
  47. package/dist/store-t-74rsM_.d.ts +0 -48
  48. package/dist/types-Bcje4dLV.d.ts +0 -136
  49. package/dist/wait-until-BzIwzXw4.js +0 -23
@@ -1,21 +1,33 @@
1
- import { a as readObjectProperty, c as writeRuntimeRegistryFile, d as dirname$1, f as relative$1, i as maskSourceLiterals, l as createImportPath, n as findDefaultExportCall, o as splitTopLevel, p as resolve$1, r as findMatching, s as createRuntimeRegistryContents, t as discoverScheduleDefinitions, u as ensureGeneratedDir } from "./discovery-DvU3B6iD.js";
1
+ import { t as scheduleErrorDiagnostics } from "./error-diagnostics-in7mif5s.js";
2
+ import { a as relative$1, i as isAbsolute$1, n as relativeDefinitionFile, o as resolve$1, r as dirname$1 } from "./inspect-DTfAo5gS.js";
3
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-A_8Kp-48.js";
2
4
  import { builtinModules, createRequire } from "node:module";
3
- import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync } from "node:fs";
4
- import { basename, dirname, extname, isAbsolute, normalize, parse, relative, resolve, sep } from "node:path";
5
- import { cp, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, writeFile } from "node:fs/promises";
6
- import { fileURLToPath, pathToFileURL } from "node:url";
7
5
  import { randomUUID } from "node:crypto";
6
+ import { cp, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, writeFile } from "node:fs/promises";
7
+ import { basename, dirname, extname, isAbsolute, normalize, parse, relative, resolve, sep } from "node:path";
8
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync } from "node:fs";
8
9
  import { tmpdir } from "node:os";
10
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
11
  import { build } from "esbuild";
12
+ import { parseSync } from "vite";
10
13
  import { isDeepStrictEqual } from "node:util";
11
14
  //#region ../internal/src/build/client-output.ts
12
15
  function hasStaticIndex(clientDir) {
13
16
  return existsSync(resolve$1(clientDir, "index.html"));
14
17
  }
15
- async function copyClientOutput(clientDir, targetDir) {
18
+ async function copyClientOutput(clientDir, targetDir, excludedDirs = []) {
16
19
  const resolvedClientDir = resolve$1(clientDir);
17
20
  const resolvedTargetDir = resolve$1(targetDir);
18
21
  if (resolvedClientDir === resolvedTargetDir) return;
22
+ const excluded = /* @__PURE__ */ new Set();
23
+ for (const dir of excludedDirs) {
24
+ const resolved = resolve$1(dir);
25
+ if (resolved !== resolvedClientDir && resolved.startsWith(`${resolvedClientDir}/`)) excluded.add(resolved);
26
+ }
27
+ const filter = (source) => {
28
+ const resolved = resolve$1(source);
29
+ return ![...excluded].some((dir) => resolved === dir || resolved.startsWith(`${dir}/`));
30
+ };
19
31
  await rm(resolvedTargetDir, {
20
32
  force: true,
21
33
  recursive: true
@@ -25,10 +37,16 @@ async function copyClientOutput(clientDir, targetDir) {
25
37
  if (targetRelativePath && !targetRelativePath.startsWith("../")) {
26
38
  const [targetRootEntry] = targetRelativePath.split("/", 1);
27
39
  await mkdir(resolvedTargetDir, { recursive: true });
28
- await Promise.all((await readdir(resolvedClientDir)).filter((entry) => entry !== targetRootEntry).map((entry) => cp(resolve$1(resolvedClientDir, entry), resolve$1(resolvedTargetDir, entry), { recursive: true })));
40
+ await Promise.all((await readdir(resolvedClientDir)).filter((entry) => entry !== targetRootEntry).map((entry) => cp(resolve$1(resolvedClientDir, entry), resolve$1(resolvedTargetDir, entry), {
41
+ recursive: true,
42
+ filter
43
+ })));
29
44
  return;
30
45
  }
31
- await cp(resolvedClientDir, resolvedTargetDir, { recursive: true });
46
+ await cp(resolvedClientDir, resolvedTargetDir, {
47
+ recursive: true,
48
+ filter
49
+ });
32
50
  }
33
51
  //#endregion
34
52
  //#region ../internal/src/build/provider-output-config.ts
@@ -74,7 +92,7 @@ function isProviderJsonRecord(value) {
74
92
  }
75
93
  }
76
94
  function assertProviderJsonRecord(value) {
77
- if (!isProviderJsonRecord(value)) throw new TypeError("[vitehub] Provider output config must be a JSON object.");
95
+ if (!isProviderJsonRecord(value)) throw internalErrorDiagnostics.INTERNAL_B0043({ message: "[vitehub] Provider output config must be a JSON object." });
78
96
  }
79
97
  function isFileNotFoundError(error) {
80
98
  return error instanceof Error && "code" in error && error.code === "ENOENT";
@@ -107,7 +125,7 @@ function preserveUnownedKeyedArrayEntries(value, ownership, replacements = []) {
107
125
  const key = getKeyedArrayEntryValue(entry, ownership.key);
108
126
  return key === void 0 ? [] : [key];
109
127
  });
110
- const ownedKeys = new Set([...ownership.values ?? [], ...replacementKeys]);
128
+ const ownedKeys = /* @__PURE__ */ new Set([...ownership.values ?? [], ...replacementKeys]);
111
129
  return current.filter((entry) => {
112
130
  const key = getKeyedArrayEntryValue(entry, ownership.key);
113
131
  return key === void 0 || !ownedKeys.has(key);
@@ -195,12 +213,7 @@ async function writeCloudflareWranglerConfig(options) {
195
213
  //#region ../internal/src/object.ts
196
214
  function isPlainObject(value) {
197
215
  if (value === null || Object(value) !== value || Array.isArray(value)) return false;
198
- try {
199
- Function.prototype.toString.call(value);
200
- return false;
201
- } catch {
202
- return true;
203
- }
216
+ return typeof value === "object";
204
217
  }
205
218
  //#endregion
206
219
  //#region ../internal/src/build/esbuild.ts
@@ -480,62 +493,20 @@ function createViteAliasPlugin(aliases) {
480
493
  }
481
494
  };
482
495
  }
483
- function stripMarkdownCode(template) {
484
- let fence;
485
- let inList = false;
486
- let previousLineBlank = true;
487
- return template.split("\n").map((line) => {
488
- const content = line.replace(/^(?: {0,3}> ?)+/, "");
489
- if (!fence) {
490
- const listIndented = inList && /^ {4}(?:`{3,}|~{3,})/.test(content);
491
- const opening = (listIndented ? content.slice(4) : content).match(/^ {0,3}(`{3,}|~{3,})/);
492
- if (!opening) {
493
- if (/^ {0,3}(?:[-+*]|\d+[.)])\s+/.test(content)) inList = true;
494
- else if (content.trim() && !/^ {2,}/.test(content)) inList = false;
495
- const indentedCode = !inList && previousLineBlank && /^(?: {4}|\t)/.test(content) || inList && previousLineBlank && /^(?: {8}| {4}\t|\t{2})/.test(content);
496
- previousLineBlank = content.trim() === "";
497
- return indentedCode ? "" : line;
498
- }
499
- fence = {
500
- marker: opening[1][0],
501
- length: opening[1].length,
502
- listIndented
503
- };
504
- previousLineBlank = false;
505
- return "";
506
- }
507
- const closing = (fence.listIndented ? content.replace(/^ {4}/, "") : content).match(/^ {0,3}(`+|~+)\s*$/)?.[1];
508
- if (closing?.[0] === fence.marker && closing.length >= fence.length) fence = void 0;
509
- previousLineBlank = false;
510
- return "";
511
- }).join("\n");
512
- }
513
- function extractMarkdownTemplateImportSpecifiers(template) {
514
- const visible = stripMarkdownCode(template).replace(/(`+)[\s\S]*?\1/g, "").replace(/(!?\[[^\]]*\])\([^)]*\)/g, "$1").replace(/^ {0,3}\[[^\]]+\]:\s*\S+/gm, "").replace(/<[^>]*>/g, "");
515
- const specifiers = /* @__PURE__ */ new Set();
516
- for (const match of visible.matchAll(/@(\.\.?\/[^\s<>{}[\]]+)/g)) {
517
- const token = match[1];
518
- const trailing = token.match(/[.,;:!?)]*$/)?.[0] || "";
519
- specifiers.add(token.slice(0, token.length - trailing.length));
520
- }
521
- return [...specifiers];
522
- }
523
496
  function parseMarkdownTemplateRequest(id) {
497
+ if (id.includes("#")) return;
524
498
  const queryIndex = id.indexOf("?");
525
- const path = id.split(/[?#]/, 1)[0];
499
+ const path = id.split("?", 1)[0];
526
500
  if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix) ? { path } : void 0;
527
- const query = id.slice(queryIndex + 1).split("#", 1)[0];
528
- if (!new URLSearchParams(query).has(markdownTemplateModuleQuery)) return;
501
+ if (id.slice(queryIndex + 1) !== markdownTemplateModuleQuery) return;
529
502
  return { path };
530
503
  }
531
- function renderMarkdownTemplateModule(template, sourceId, imports = {}) {
504
+ function renderMarkdownTemplateModule(template) {
532
505
  return [
533
506
  `import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier)}`,
534
507
  `const vitehubMarkdownTemplate = ${JSON.stringify(template)}`,
535
- `const vitehubMarkdownTemplateSourceId = ${JSON.stringify(sourceId)}`,
536
- `const vitehubMarkdownTemplateImports = ${JSON.stringify(imports)}`,
537
508
  "export default function render(data = {}) {",
538
- " return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data, sourceId: vitehubMarkdownTemplateSourceId, resolveImport: (specifier, importer) => vitehubMarkdownTemplateImports[`${importer}\\0${specifier}`] })",
509
+ " return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data })",
539
510
  "}",
540
511
  ""
541
512
  ].join("\n");
@@ -628,45 +599,22 @@ function createViteRawPlugin(rootDir, frameworkRuntime) {
628
599
  filter: /.*/,
629
600
  namespace: viteMarkdownTemplateNamespace
630
601
  }, async (args) => ({
631
- contents: await (async () => {
632
- const template = await readFile(args.path, "utf8");
633
- const imports = {};
634
- const visited = new Set([args.path]);
635
- const visit = async (source, importer) => {
636
- for (const specifier of extractMarkdownTemplateImportSpecifiers(source)) {
637
- const key = `${importer}\0${specifier}`;
638
- if (imports[key]) continue;
639
- const resolved = await build.resolve(specifier, {
640
- importer,
641
- kind: "import-statement",
642
- pluginData: {
643
- ...args.pluginData,
644
- [skipMarkdownTemplateResolve]: true
645
- },
646
- resolveDir: dirname(importer)
647
- });
648
- if (resolved.errors.length) return Promise.reject(new Error(resolved.errors.map((error) => error.text).join("\n")));
649
- if (resolved.external || resolved.namespace !== "file") throw new Error(`[vitehub] Could not resolve Markdown template import ${JSON.stringify(specifier)} from ${JSON.stringify(importer)} to a file.`);
650
- const imported = {
651
- id: resolved.path,
652
- template: await readFile(resolved.path, "utf8")
653
- };
654
- imports[key] = imported;
655
- if (!visited.has(imported.id)) {
656
- visited.add(imported.id);
657
- await visit(imported.template, imported.id);
658
- }
659
- }
660
- };
661
- await visit(template, args.path);
662
- return renderMarkdownTemplateModule(template, args.path, imports);
663
- })(),
602
+ contents: renderMarkdownTemplateModule(await readFile(args.path, "utf8")),
664
603
  loader: "js",
665
604
  resolveDir: dirname(args.path)
666
605
  }));
667
606
  }
668
607
  };
669
608
  }
609
+ /** Select the runtime constants from one resolved Vite configuration. */
610
+ function resolveViteHubBundleDefines(config) {
611
+ const defines = {};
612
+ for (const name of ["__VITEHUB_PUBLIC_URL__", "__VITEHUB_APP_BASE_URL__"]) {
613
+ const value = config.define?.[name];
614
+ if (typeof value === "string") defines[name] = value;
615
+ }
616
+ return defines;
617
+ }
670
618
  function createFileUrlPlugin() {
671
619
  return {
672
620
  name: "vitehub-file-url",
@@ -698,13 +646,16 @@ async function bundleEsmEntry(entryFile, outfile, options = {}) {
698
646
  ] : []].filter(Boolean).join("\n") } : void 0,
699
647
  bundle: true,
700
648
  conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
649
+ define: options.define,
701
650
  entryPoints: [entryFile],
702
651
  external: options.external,
703
652
  format,
653
+ keepNames: options.minifySyntax || options.minifyIdentifiers,
704
654
  logLevel: "silent",
705
655
  mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
706
656
  resolveExtensions: options.extensions,
707
657
  minifyIdentifiers: options.minifyIdentifiers,
658
+ minifySyntax: options.minifySyntax,
708
659
  minifyWhitespace: options.minifyWhitespace,
709
660
  outfile,
710
661
  packages: options.packages,
@@ -726,6 +677,261 @@ async function bundleEsmEntry(entryFile, outfile, options = {}) {
726
677
  }
727
678
  }
728
679
  //#endregion
680
+ //#region ../internal/src/build/paths.ts
681
+ function generatedDirSegments(productName) {
682
+ return [".vitehub", productName];
683
+ }
684
+ function ensureGeneratedDir(rootDir, productName) {
685
+ return resolve$1(rootDir, ...generatedDirSegments(productName));
686
+ }
687
+ function createImportPath(fromFile, targetFile) {
688
+ const fromDir = realpathIfExists(dirname$1(fromFile));
689
+ const target = realpathIfExists(targetFile);
690
+ const importPath = relative$1(fromDir, target);
691
+ return importPath.startsWith(".") ? importPath : `./${importPath}`;
692
+ }
693
+ function realpathIfExists(path) {
694
+ try {
695
+ return realpathSync.native(path);
696
+ } catch {
697
+ return resolve$1(path);
698
+ }
699
+ }
700
+ //#endregion
701
+ //#region ../internal/src/build/scan-module.ts
702
+ /**
703
+ * Reads facts from JavaScript and TypeScript modules at build and dev time. The scanner parses each module once with
704
+ * the oxc parser that Vite ships through Rolldown, and never runs it. Values that are not static literals read as
705
+ * `dynamic`, so callers can report their own diagnostics.
706
+ */
707
+ /** The value of an expression that the scanner cannot read without running the module. */
708
+ const dynamic = Symbol("dynamic");
709
+ function languageOf(file) {
710
+ if (/\.(?:c|m)?tsx$/i.test(file)) return "tsx";
711
+ if (/\.(?:c|m)?jsx$/i.test(file)) return "jsx";
712
+ if (/\.(?:c|m)?js$/i.test(file)) return "js";
713
+ return "ts";
714
+ }
715
+ /** Parses a module once. `file` selects the grammar from its extension and defaults to TypeScript. */
716
+ function scanModule(source, file = "module.ts") {
717
+ const result = parseSync(file, source, {
718
+ lang: languageOf(file),
719
+ preserveParens: false,
720
+ sourceType: "module"
721
+ });
722
+ return {
723
+ comments: result.comments,
724
+ errors: result.errors,
725
+ file,
726
+ program: result.program,
727
+ source
728
+ };
729
+ }
730
+ function isNode(value) {
731
+ return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
732
+ }
733
+ /** Visits `node` and its descendants. Return `false` from `visit` to skip the children of a node. */
734
+ function walk(node, visit, parent) {
735
+ if (visit(node, parent) === false) return;
736
+ const fields = node;
737
+ for (const key in fields) {
738
+ const child = fields[key];
739
+ if (typeof child !== "object" || child === null || key === "parent") continue;
740
+ if (Array.isArray(child)) {
741
+ for (const item of child) if (isNode(item)) walk(item, visit, node);
742
+ } else if (isNode(child)) walk(child, visit, node);
743
+ }
744
+ }
745
+ /** Removes parentheses, `as`, `satisfies`, `!`, and `<T>` assertions around an expression. */
746
+ function unwrapExpression(node) {
747
+ while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
748
+ return node;
749
+ }
750
+ /** A call argument without assertions, or undefined for a spread or missing argument. */
751
+ function argumentExpression(argument) {
752
+ return argument === void 0 || argument.type === "SpreadElement" ? void 0 : unwrapExpression(argument);
753
+ }
754
+ /** Calls whose callee is a plain identifier in `names`, such as `defineCollection(...)`, in source order. */
755
+ function findCalls(module, names) {
756
+ const wanted = new Set(names);
757
+ const calls = [];
758
+ walk(module.program, (node) => {
759
+ if (node.type === "CallExpression" && node.callee.type === "Identifier" && wanted.has(node.callee.name)) calls.push(node);
760
+ });
761
+ return calls.sort((left, right) => left.start - right.start);
762
+ }
763
+ /** The expression of `export default <expression>`, without assertions. Declarations return undefined. */
764
+ function defaultExportExpression(module) {
765
+ for (const statement of module.program.body) {
766
+ if (statement.type !== "ExportDefaultDeclaration") continue;
767
+ const declaration = statement.declaration;
768
+ if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration" || declaration.type === "TSInterfaceDeclaration") return;
769
+ return unwrapExpression(declaration);
770
+ }
771
+ }
772
+ /**
773
+ * Finds `export default defineX({ ... })` for one of `names`. With `positionalOptionsIndex`, a call whose first
774
+ * argument is not an object and that has more than one argument reads its options from that argument. Returns
775
+ * undefined when the options are not an object literal.
776
+ */
777
+ function findDefaultExportCall(module, names, options = {}) {
778
+ const call = defaultExportExpression(module);
779
+ if (call?.type !== "CallExpression" || call.callee.type !== "Identifier" || !names.includes(call.callee.name)) return;
780
+ const name = call.callee.name;
781
+ const first = argumentExpression(call.arguments[0]);
782
+ if (first?.type === "ObjectExpression") return {
783
+ call,
784
+ name,
785
+ options: first
786
+ };
787
+ if (options.positionalOptionsIndex === void 0 || first === void 0 || call.arguments.length < 2) return;
788
+ const positional = call.arguments[options.positionalOptionsIndex];
789
+ if (positional === void 0) return {
790
+ call,
791
+ name
792
+ };
793
+ const object = argumentExpression(positional);
794
+ return object?.type === "ObjectExpression" ? {
795
+ call,
796
+ name,
797
+ options: object
798
+ } : void 0;
799
+ }
800
+ function staticKey(property) {
801
+ const key = property.key;
802
+ if (key.type === "Identifier" && !property.computed) return key.name;
803
+ if (key.type === "PrivateIdentifier") return;
804
+ const value = staticValue(key);
805
+ return typeof value === "string" || typeof value === "number" || typeof value === "bigint" ? String(value) : void 0;
806
+ }
807
+ /** The members of an object literal in source order. */
808
+ function objectProperties(object) {
809
+ return object.properties.map((node) => node.type === "SpreadElement" ? {
810
+ computed: false,
811
+ key: void 0,
812
+ node,
813
+ value: void 0
814
+ } : {
815
+ computed: node.computed,
816
+ key: staticKey(node),
817
+ node,
818
+ value: unwrapExpression(node.value)
819
+ });
820
+ }
821
+ /** The last member named `name`, which is the one that the object keeps at runtime. */
822
+ function findProperty(object, name) {
823
+ return objectProperties(object).findLast((property) => property.key === name);
824
+ }
825
+ /** The value of a template literal without substitutions. */
826
+ function staticTemplate(node) {
827
+ if (node.expressions.length) return dynamic;
828
+ return node.quasis[0]?.value.cooked ?? dynamic;
829
+ }
830
+ const escapePattern = /\\(u\{[^}]*\}?|u[\s\S]{0,4}|x[\s\S]{0,2}|0\d|[\s\S])/g;
831
+ /**
832
+ * True when a string literal has an escape that strict mode code rejects. The parser recovers from some bad escapes
833
+ * and accepts legacy octal escapes, so the scanner checks them again.
834
+ */
835
+ function hasInvalidEscape(raw) {
836
+ for (const [, escape = ""] of raw.matchAll(escapePattern)) if (escape.startsWith("u{")) {
837
+ const code = escape.slice(2, -1);
838
+ if (!escape.endsWith("}") || !/^[\da-fA-F]+$/.test(code) || Number.parseInt(code, 16) > 1114111) return true;
839
+ } else if (escape.startsWith("u")) {
840
+ if (!/^u[\da-fA-F]{4}$/.test(escape)) return true;
841
+ } else if (escape.startsWith("x")) {
842
+ if (!/^x[\da-fA-F]{2}$/.test(escape)) return true;
843
+ } else if (/^(?:[1-9]|0\d)$/.test(escape)) return true;
844
+ return false;
845
+ }
846
+ /**
847
+ * Reads a literal value: strings, numbers, booleans, `null`, `undefined`, template literals without substitutions,
848
+ * and arrays and objects of these. Any other expression gives `dynamic`.
849
+ */
850
+ function staticValue(node) {
851
+ node = unwrapExpression(node);
852
+ switch (node.type) {
853
+ case "Literal":
854
+ if ("regex" in node) return dynamic;
855
+ return typeof node.value === "string" && hasInvalidEscape(node.raw ?? "") ? dynamic : node.value;
856
+ case "TemplateLiteral": return staticTemplate(node);
857
+ case "Identifier": return node.name === "undefined" ? void 0 : dynamic;
858
+ case "UnaryExpression": {
859
+ if (node.operator === "void") return staticValue(node.argument) === dynamic ? dynamic : void 0;
860
+ const value = staticValue(node.argument);
861
+ if (node.operator === "-" && (typeof value === "number" || typeof value === "bigint")) return -value;
862
+ return dynamic;
863
+ }
864
+ case "ArrayExpression": {
865
+ const values = [];
866
+ for (const element of node.elements) {
867
+ if (element === null || element.type === "SpreadElement") return dynamic;
868
+ const value = staticValue(element);
869
+ if (value === dynamic) return dynamic;
870
+ values.push(value);
871
+ }
872
+ return values;
873
+ }
874
+ case "ObjectExpression": {
875
+ const values = {};
876
+ for (const property of objectProperties(node)) {
877
+ if (property.key === void 0 || property.node.type !== "Property" || property.node.kind !== "init" || property.node.method || property.value === void 0) return dynamic;
878
+ const value = staticValue(property.value);
879
+ if (value === dynamic) return dynamic;
880
+ Object.defineProperty(values, property.key, {
881
+ configurable: true,
882
+ enumerable: true,
883
+ value,
884
+ writable: true
885
+ });
886
+ }
887
+ return values;
888
+ }
889
+ default: return dynamic;
890
+ }
891
+ }
892
+ /** The static string value of an expression, or undefined when it is not a string literal. */
893
+ function staticString(node) {
894
+ if (node === void 0) return;
895
+ const value = staticValue(node);
896
+ return typeof value === "string" ? value : void 0;
897
+ }
898
+ function isLineTerminator(char) {
899
+ return char === "\n" || char === "\r" || char === "\u2028" || char === "\u2029";
900
+ }
901
+ /** Comments, JSX text, and string, template, and regular expression literals, sorted by position. Templates are not split. */
902
+ function literalSpans(module) {
903
+ const spans = module.comments.map((comment) => ({
904
+ end: comment.end,
905
+ inert: true,
906
+ start: comment.start
907
+ }));
908
+ walk(module.program, (node) => {
909
+ if (node.type === "TemplateLiteral" || node.type === "JSXText") {
910
+ spans.push({
911
+ end: node.end,
912
+ inert: node.type === "JSXText",
913
+ start: node.start
914
+ });
915
+ return false;
916
+ }
917
+ if (node.type === "Literal" && (typeof node.value === "string" || "regex" in node)) spans.push({
918
+ end: node.end,
919
+ inert: false,
920
+ start: node.start
921
+ });
922
+ });
923
+ return spans.sort((left, right) => left.start - right.start);
924
+ }
925
+ /**
926
+ * The module source with comments, strings, templates, regular expressions, and JSX text replaced by spaces. Line
927
+ * terminators and all positions stay the same, so text matches map back to the source.
928
+ */
929
+ function maskLiterals(module) {
930
+ const output = module.source.split("");
931
+ for (const span of literalSpans(module)) for (let index = span.start; index < span.end; index++) if (!isLineTerminator(output[index] ?? "")) output[index] = " ";
932
+ return output.join("");
933
+ }
934
+ //#endregion
729
935
  //#region ../internal/src/build/provider-output-sources.ts
730
936
  function escapeRegExp(value) {
731
937
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -738,7 +944,8 @@ function rewriteRetainedProviderSourcePaths(contents, retainedSourcesDir, publis
738
944
  const serializedPublishedSeparator = publishedSeparator === "\\" ? "\\\\" : "/";
739
945
  const serializedPath = new RegExp(`${escapeRegExp(serializedRetainedSourcesDir)}((?:(?:\\\\\\\\|/)[^"\\\\/]*)+)`, "g");
740
946
  const normalizedContents = contents.replace(serializedPath, (_matched, suffix) => {
741
- return `${serializedPublishedSourcesDir}${suffix.replaceAll("\\\\", serializedPublishedSeparator).replaceAll("/", serializedPublishedSeparator)}`;
947
+ const normalizedSuffix = suffix.replaceAll("\\\\", serializedPublishedSeparator).replaceAll("/", serializedPublishedSeparator);
948
+ return `${serializedPublishedSourcesDir}${normalizedSuffix}`;
742
949
  });
743
950
  const replacements = [
744
951
  [`${pathToFileURL(retainedSourcesDir).href}/`, `${pathToFileURL(publishedSourcesDir).href}/`],
@@ -849,7 +1056,7 @@ function retainProviderOutputAliases(aliases, retainedSources) {
849
1056
  }
850
1057
  return retainedAliases;
851
1058
  }
852
- const ignoredSourceDirectories = new Set([
1059
+ const ignoredSourceDirectories = /* @__PURE__ */ new Set([
853
1060
  ".git",
854
1061
  ".netlify",
855
1062
  ".nuxt",
@@ -861,7 +1068,7 @@ const ignoredSourceDirectories = new Set([
861
1068
  "dist",
862
1069
  "node_modules"
863
1070
  ]);
864
- const ignoredGeneratedDirectories = new Set([".vitehub", ".vitest-tmp"]);
1071
+ const ignoredGeneratedDirectories = /* @__PURE__ */ new Set([".vitehub", ".vitest-tmp"]);
865
1072
  function isTransientSourceDirectory(path) {
866
1073
  return basename(path).startsWith(".drizzle-generate-");
867
1074
  }
@@ -941,7 +1148,7 @@ function commonSourceRoot(root, paths) {
941
1148
  }
942
1149
  return common;
943
1150
  }
944
- const traceableSourceExtensions = new Set([
1151
+ const traceableSourceExtensions = /* @__PURE__ */ new Set([
945
1152
  ".cjs",
946
1153
  ".cts",
947
1154
  ".js",
@@ -959,8 +1166,34 @@ function resolveComputedModuleSource(file, specifier, resolveFrom = file) {
959
1166
  return;
960
1167
  }
961
1168
  }
1169
+ /** The index of the delimiter that closes the one at `open`. `masked` has no literals or comments. */
1170
+ function matchingDelimiter(masked, open) {
1171
+ let depth = 0;
1172
+ for (let index = open; index < masked.length; index++) {
1173
+ const char = masked[index];
1174
+ if (char === "(" || char === "[" || char === "{") depth++;
1175
+ else if ((char === ")" || char === "]" || char === "}") && --depth === 0) return index;
1176
+ }
1177
+ }
1178
+ /** Splits `source.slice(start, end)` at top-level commas. */
1179
+ function splitTopLevel(source, masked, start, end) {
1180
+ const parts = [];
1181
+ let depth = 0;
1182
+ let partStart = start;
1183
+ for (let index = start; index < end; index++) {
1184
+ const char = masked[index];
1185
+ if (char === "(" || char === "[" || char === "{") depth++;
1186
+ else if (char === ")" || char === "]" || char === "}") depth--;
1187
+ else if (char === "," && depth === 0) {
1188
+ parts.push(source.slice(partStart, index).trim());
1189
+ partStart = index + 1;
1190
+ }
1191
+ }
1192
+ parts.push(source.slice(partStart, end).trim());
1193
+ return parts;
1194
+ }
962
1195
  function traceComputedModuleSources(file, source, onRuntimePackageRequest) {
963
- const masked = maskSourceLiterals(source);
1196
+ const masked = maskLiterals(scanModule(source, file));
964
1197
  const bindings = /* @__PURE__ */ new Map();
965
1198
  for (const match of source.matchAll(/\b(?:const|let|var)\s+([A-Z_$][\w$]*)\s*=\s*([`"'])(.*?)\2/gis)) {
966
1199
  const quoteOffset = match[0].indexOf(match[2]);
@@ -968,7 +1201,7 @@ function traceComputedModuleSources(file, source, onRuntimePackageRequest) {
968
1201
  if (match[2] === "`" && match[3].includes("${")) continue;
969
1202
  bindings.set(match[1], match[3]);
970
1203
  }
971
- const createRequireNames = new Set(["createRequire"]);
1204
+ const createRequireNames = /* @__PURE__ */ new Set(["createRequire"]);
972
1205
  for (const match of source.matchAll(/\bimport\s+(?:[A-Z_$][\w$]*\s*,\s*)?\{([^}]*)\}\s*from\s*([`"'])(?:node:)?module\2/gis)) for (const specifier of match[1].split(",")) {
973
1206
  const binding = /^\s*createRequire(?:\s+as\s+([A-Z_$][\w$]*))?\s*$/i.exec(specifier)?.[1];
974
1207
  if (binding) createRequireNames.add(binding);
@@ -995,17 +1228,18 @@ function traceComputedModuleSources(file, source, onRuntimePackageRequest) {
995
1228
  if (!literal || literal[1] === "`" && literal[2].includes("${")) return void 0;
996
1229
  return literal[2];
997
1230
  };
998
- const createRequireBase = (expression) => {
1231
+ const createRequireBase = (start, end) => {
1232
+ const expression = source.slice(start, end);
999
1233
  const normalized = expression.trim();
1000
1234
  if (normalized === "import.meta.url" || normalized === "__filename") return file;
1001
1235
  const direct = staticModuleSpecifier(normalized);
1002
1236
  if (direct) return direct;
1003
1237
  const newUrl = /^new\s+URL\s*\(/i.exec(normalized);
1004
1238
  if (!newUrl) return file;
1005
- const openParen = normalized.indexOf("(", newUrl.index);
1006
- const closeParen = findMatching(normalized, openParen, "(", ")");
1007
- if (closeParen === void 0 || normalized.slice(closeParen + 1).trim()) return file;
1008
- const [relativeUrl, baseUrl] = splitTopLevel(normalized.slice(openParen + 1, closeParen));
1239
+ const openParen = start + expression.indexOf(normalized) + normalized.indexOf("(", newUrl.index);
1240
+ const closeParen = matchingDelimiter(masked, openParen);
1241
+ if (closeParen === void 0 || closeParen >= end || source.slice(closeParen + 1, end).trim()) return file;
1242
+ const [relativeUrl, baseUrl] = splitTopLevel(source, masked, openParen + 1, closeParen);
1009
1243
  const relativePath = relativeUrl ? staticModuleSpecifier(relativeUrl) : void 0;
1010
1244
  if (!relativePath || baseUrl?.replace(/\s/g, "") !== "import.meta.url") return file;
1011
1245
  return fileURLToPath(new URL(relativePath, pathToFileURL(file)));
@@ -1014,8 +1248,8 @@ function traceComputedModuleSources(file, source, onRuntimePackageRequest) {
1014
1248
  for (const match of masked.matchAll(/\b(?:const|let|var)\s+([A-Z_$][\w$]*)\s*=\s*([A-Z_$][\w$]*(?:\s*\.\s*createRequire)?)\s*\(/gi)) {
1015
1249
  if (!isCreateRequireExpression(match[2])) continue;
1016
1250
  const openParen = match.index + match[0].lastIndexOf("(");
1017
- const closeParen = findMatching(masked, openParen, "(", ")");
1018
- const base = closeParen === void 0 ? file : createRequireBase(source.slice(openParen + 1, closeParen));
1251
+ const closeParen = matchingDelimiter(masked, openParen);
1252
+ const base = closeParen === void 0 ? file : createRequireBase(openParen + 1, closeParen);
1019
1253
  boundRequireBases.set(match[1], base);
1020
1254
  }
1021
1255
  const boundResolveBases = /* @__PURE__ */ new Map();
@@ -1026,8 +1260,8 @@ function traceComputedModuleSources(file, source, onRuntimePackageRequest) {
1026
1260
  for (const match of masked.matchAll(/\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*([A-Z_$][\w$]*(?:\s*\.\s*createRequire)?)\s*\(/gi)) {
1027
1261
  if (!isCreateRequireExpression(match[2])) continue;
1028
1262
  const openParen = match.index + match[0].lastIndexOf("(");
1029
- const closeParen = findMatching(masked, openParen, "(", ")");
1030
- const base = closeParen === void 0 ? file : createRequireBase(source.slice(openParen + 1, closeParen));
1263
+ const closeParen = matchingDelimiter(masked, openParen);
1264
+ const base = closeParen === void 0 ? file : createRequireBase(openParen + 1, closeParen);
1031
1265
  recordBoundResolve(match[1], base);
1032
1266
  }
1033
1267
  for (const match of masked.matchAll(/\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*([A-Z_$][\w$]*)\b/gi)) {
@@ -1075,16 +1309,16 @@ function traceComputedModuleSources(file, source, onRuntimePackageRequest) {
1075
1309
  for (const match of masked.matchAll(/\b([A-Z_$][\w$]*(?:\s*\.\s*createRequire)?)\s*\(/gi)) {
1076
1310
  if (!isCreateRequireExpression(match[1])) continue;
1077
1311
  const openParen = match.index + match[0].lastIndexOf("(");
1078
- const closeParen = findMatching(masked, openParen, "(", ")");
1312
+ const closeParen = matchingDelimiter(masked, openParen);
1079
1313
  if (closeParen === void 0) continue;
1080
1314
  const invocation = /^\s*(?:\.\s*resolve\s*)?\(/i.exec(masked.slice(closeParen + 1));
1081
1315
  if (!invocation) continue;
1082
1316
  const invocationOpenParen = closeParen + 1 + invocation[0].lastIndexOf("(");
1083
- const invocationCloseParen = findMatching(masked, invocationOpenParen, "(", ")");
1317
+ const invocationCloseParen = matchingDelimiter(masked, invocationOpenParen);
1084
1318
  if (invocationCloseParen === void 0) continue;
1085
- const [target] = splitTopLevel(source.slice(invocationOpenParen + 1, invocationCloseParen));
1319
+ const [target] = splitTopLevel(source, masked, invocationOpenParen + 1, invocationCloseParen);
1086
1320
  const specifier = target ? staticModuleSpecifier(target) : void 0;
1087
- if (specifier) recordRequest(specifier, /\.\s*resolve/i.test(invocation[0]) ? "require-resolve" : "require-call", createRequireBase(source.slice(openParen + 1, closeParen)));
1321
+ if (specifier) recordRequest(specifier, /\.\s*resolve/i.test(invocation[0]) ? "require-resolve" : "require-call", createRequireBase(openParen + 1, closeParen));
1088
1322
  }
1089
1323
  for (const match of masked.matchAll(/\b([A-Z_$][\w$]*)\s*\(\s*([A-Z_$][\w$]*)\s*\)/gi)) {
1090
1324
  const specifier = bindings.get(match[2]);
@@ -1180,6 +1414,19 @@ async function traceImportedSources(paths, root, configuredRoots) {
1180
1414
  platform: "node"
1181
1415
  }
1182
1416
  ];
1417
+ const computedModuleSources = /* @__PURE__ */ new Map();
1418
+ const traceComputedModuleSourcesOnce = (file, source) => {
1419
+ const cached = computedModuleSources.get(file);
1420
+ if (cached?.source === source) return cached;
1421
+ const requests = [];
1422
+ const traced = {
1423
+ paths: traceComputedModuleSources(file, source, (request) => requests.push(request)),
1424
+ requests,
1425
+ source
1426
+ };
1427
+ computedModuleSources.set(file, traced);
1428
+ return traced;
1429
+ };
1183
1430
  try {
1184
1431
  const importedSources = new Set(entries);
1185
1432
  const scannedModuleRequestSources = /* @__PURE__ */ new Set();
@@ -1276,9 +1523,7 @@ async function traceImportedSources(paths, root, configuredRoots) {
1276
1523
  const source = await readFile(request.path, "utf8").catch(() => void 0);
1277
1524
  if (!source) return void 0;
1278
1525
  const runtimeRequests = /* @__PURE__ */ new Map();
1279
- traceComputedModuleSources(request.path, source, (runtimeRequest) => {
1280
- runtimeRequests.set(`${runtimeRequest.kind}\0${runtimeRequest.resolveFrom}\0${runtimeRequest.specifier}`, runtimeRequest);
1281
- });
1526
+ for (const runtimeRequest of traceComputedModuleSourcesOnce(request.path, source).requests) runtimeRequests.set(`${runtimeRequest.kind}\0${runtimeRequest.resolveFrom}\0${runtimeRequest.specifier}`, runtimeRequest);
1282
1527
  await Promise.all([...runtimeRequests.values()].map(async (runtimeRequest) => {
1283
1528
  const resolveFrom = runtimeRequest.resolveFrom ?? request.path;
1284
1529
  const resolution = await traceBuild.resolve(runtimeRequest.specifier, {
@@ -1310,7 +1555,7 @@ async function traceImportedSources(paths, root, configuredRoots) {
1310
1555
  const moduleRequestSourceContents = await Promise.all(moduleRequestSources.map(async (path) => [path, await readFile(path, "utf8")]));
1311
1556
  for (const [file, source] of moduleRequestSourceContents) {
1312
1557
  scannedModuleRequestSources.add(file);
1313
- for (const imported of traceComputedModuleSources(file, source)) {
1558
+ for (const imported of traceComputedModuleSourcesOnce(file, source).paths) {
1314
1559
  importedSources.add(imported);
1315
1560
  if (traceableSourceExtensions.has(extname(imported)) && !tracedEntries.has(imported) && !pendingEntries.includes(imported)) pendingEntries.push(imported);
1316
1561
  }
@@ -1342,6 +1587,22 @@ function packageMetadataSourcesForPath(root, path) {
1342
1587
  }
1343
1588
  return sources;
1344
1589
  }
1590
+ /**
1591
+ * Generated Provider Output can import a package by the physical pnpm store path
1592
+ * that Vite resolved during the source build. Retained source trees do not copy
1593
+ * `node_modules/.pnpm`, so keep only the store package directories that the
1594
+ * traced source graph actually references.
1595
+ */
1596
+ function pnpmStorePackageRoot(root, source) {
1597
+ const segments = relative(root, source).split(sep);
1598
+ let nodeModulesIndex = -1;
1599
+ for (let index = segments.length - 2; index >= 0; index -= 1) if (segments[index] === "node_modules" && segments[index + 1] === ".pnpm") {
1600
+ nodeModulesIndex = index;
1601
+ break;
1602
+ }
1603
+ if (nodeModulesIndex === -1) return;
1604
+ return segments[nodeModulesIndex + 2] ? resolve(root, ...segments.slice(0, nodeModulesIndex + 3)) : void 0;
1605
+ }
1345
1606
  function parseJsonWithComments(source) {
1346
1607
  let output = "";
1347
1608
  let blockComment = false;
@@ -1486,7 +1747,7 @@ async function retainProviderOutputSources(options) {
1486
1747
  const retainedContainer = resolve(artifactDir, String(index));
1487
1748
  const retainedRoot = resolve(retainedContainer, relative(captureRoot, root));
1488
1749
  retainedRoots.set(root, retainedRoot);
1489
- const materializedSources = [...new Set([
1750
+ const materializedSources = [.../* @__PURE__ */ new Set([
1490
1751
  ...materializedSourcePaths,
1491
1752
  ...governingPackageMetadata,
1492
1753
  ...materializedSourcePaths.flatMap((path) => packageMetadataSourcesForPath(captureRoot, path))
@@ -1570,11 +1831,47 @@ async function retainProviderOutputSources(options) {
1570
1831
  await cp(stagedContainer, retainedContainer, { recursive: true });
1571
1832
  }
1572
1833
  const resolveRetainedDependencyTarget = (source) => {
1573
- if (!pathContains$1(root, source) || relative(root, source).split(sep).includes("node_modules")) return source;
1834
+ if (!pathContains$1(root, source)) {
1835
+ const capturedSource = pnpmStorePackageRoot(captureRoot, source) && resolve(retainedContainer, relative(captureRoot, source));
1836
+ return capturedSource && existsSync(capturedSource) ? capturedSource : source;
1837
+ }
1838
+ if (relative(root, source).split(sep).includes("node_modules")) return source;
1574
1839
  const retainedSource = resolve(retainedRoot, relative(root, source));
1575
1840
  return existsSync(retainedSource) ? retainedSource : source;
1576
1841
  };
1577
1842
  for (const dependencies of dependencyRoots(root)) await linkDependencies(dependencies, resolve(retainedRoot, "node_modules"), resolveRetainedDependencyTarget);
1843
+ const retainedPnpmPackages = /* @__PURE__ */ new Set();
1844
+ for (const source of materializedSources) {
1845
+ const packageRoot = pnpmStorePackageRoot(root, source);
1846
+ if (packageRoot && pathContains$1(root, packageRoot) && existsSync(packageRoot)) retainedPnpmPackages.add(packageRoot);
1847
+ }
1848
+ await Promise.all([...retainedPnpmPackages].map(async (source) => {
1849
+ const target = resolve(retainedRoot, relative(root, source));
1850
+ let directory = dirname(target);
1851
+ while (pathContains$1(retainedRoot, directory)) {
1852
+ try {
1853
+ if (lstatSync(directory).isSymbolicLink()) await rm(directory, {
1854
+ force: true,
1855
+ recursive: true
1856
+ });
1857
+ } catch (error) {
1858
+ if (error.code !== "ENOENT") throw error;
1859
+ }
1860
+ await mkdir(directory, { recursive: true });
1861
+ if (directory === retainedRoot) break;
1862
+ directory = dirname(directory);
1863
+ }
1864
+ try {
1865
+ if (lstatSync(target).isSymbolicLink()) await rm(target, {
1866
+ force: true,
1867
+ recursive: true
1868
+ });
1869
+ else if (existsSync(target)) return;
1870
+ } catch (error) {
1871
+ if (error.code !== "ENOENT") throw error;
1872
+ }
1873
+ await cp(realpathSync(source), target, { recursive: true });
1874
+ }));
1578
1875
  for (const source of escapedMaterializedSources) {
1579
1876
  const sourceDirectory = statSync(source).isDirectory() ? source : dirname(source);
1580
1877
  for (const dependencies of dependencyRoots(sourceDirectory)) await linkDependencies(dependencies, pathContains$1(captureRoot, dependencies) ? resolve(retainedContainer, relative(captureRoot, dependencies)) : resolve(retainedContainer, "node_modules"), resolveRetainedDependencyTarget);
@@ -1629,6 +1926,7 @@ function createNodeFunctionConfig(extra = {}) {
1629
1926
  //#endregion
1630
1927
  //#region ../internal/src/build/provider-output-catalog.ts
1631
1928
  var ProviderOutputCatalog = class {
1929
+ bundleDefines = {};
1632
1930
  #appliedCloudflareContributions = /* @__PURE__ */ new Map();
1633
1931
  #cloudflareContributions = /* @__PURE__ */ new Map();
1634
1932
  #runtimeContributions = /* @__PURE__ */ new Map();
@@ -1679,8 +1977,21 @@ var ProviderOutputCatalog = class {
1679
1977
  runtimeContributions(generation) {
1680
1978
  return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.entries() ?? (/* @__PURE__ */ new Map()).entries();
1681
1979
  }
1682
- resetRuntimeContributions() {
1683
- this.#runtimeContributions.clear();
1980
+ resetRuntimeContributions(generation, owner) {
1981
+ if (generation) {
1982
+ if (owner) this.#runtimeContributionsByGeneration.get(generation)?.delete(owner);
1983
+ else this.#runtimeContributionsByGeneration.delete(generation);
1984
+ return;
1985
+ }
1986
+ if (owner) this.#runtimeContributions.delete(owner);
1987
+ else this.#runtimeContributions.clear();
1988
+ }
1989
+ resetRuntimeContribution(product, generation) {
1990
+ if (!generation) {
1991
+ this.#runtimeContributions.delete(product);
1992
+ return;
1993
+ }
1994
+ this.#runtimeContributionsByGeneration.get(generation)?.delete(product);
1684
1995
  }
1685
1996
  createDeploymentGeneration() {
1686
1997
  const generation = { valid: true };
@@ -1843,24 +2154,35 @@ function useProviderOutputCatalog(config) {
1843
2154
  const owner = config;
1844
2155
  let catalog = owner[providerOutputCatalog] ?? providerOutputCatalogs.get(config);
1845
2156
  if (!catalog) catalog = createProviderOutputCatalog();
2157
+ catalog.bundleDefines = resolveViteHubBundleDefines(config);
1846
2158
  owner[providerOutputCatalog] = catalog;
1847
2159
  providerOutputCatalogs.set(config, catalog);
1848
2160
  return catalog;
1849
2161
  }
1850
2162
  //#endregion
1851
2163
  //#region ../internal/src/build/vite.ts
2164
+ async function prepareViteHubProviderSources(plugins, sources) {
2165
+ for (const plugin of plugins) await plugin.vitehub?.providerOutput?.prepareSources?.(sources);
2166
+ }
1852
2167
  async function collectViteHubProviderImportAliases(plugins) {
1853
2168
  return Object.assign({}, ...await Promise.all(plugins.map(async (plugin) => await plugin.vitehub?.providerOutput?.getImportAliases?.() ?? {})));
1854
2169
  }
1855
2170
  const projectRootDirectoryMarkers = [
1856
2171
  ["server", "agents"],
1857
2172
  ["server", "channels"],
2173
+ ["server", "connections"],
1858
2174
  ["server", "browsers"],
1859
2175
  ["server", "emails"],
1860
2176
  ["server", "schedules"],
1861
2177
  ["server", "workspaces"]
1862
2178
  ];
1863
- const projectRootFileMarkers = [["package.json"]];
2179
+ const projectRootFileMarkers = [
2180
+ ["package.json"],
2181
+ ["nuxt.config.ts"],
2182
+ ["nuxt.config.mts"],
2183
+ ["nuxt.config.js"],
2184
+ ["nuxt.config.mjs"]
2185
+ ];
1864
2186
  function createNoExternalMerger(packageName) {
1865
2187
  return (current) => {
1866
2188
  if (current === true) return true;
@@ -1890,7 +2212,12 @@ function resolveViteHubProjectRoot(root, options = {}) {
1890
2212
  if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
1891
2213
  if (basename(resolvedRoot) === "app") {
1892
2214
  const parent = dirname(resolvedRoot);
1893
- if (parent !== sharedTemporaryRoot && hasProjectRootDirectoryMarker(parent)) return parent;
2215
+ if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
2216
+ "nuxt.config.ts",
2217
+ "nuxt.config.mts",
2218
+ "nuxt.config.js",
2219
+ "nuxt.config.mjs"
2220
+ ]))) return parent;
1894
2221
  }
1895
2222
  let current = resolvedRoot;
1896
2223
  while (true) {
@@ -1911,10 +2238,16 @@ function hasProjectRootDirectoryMarker(root) {
1911
2238
  }
1912
2239
  function hasProjectRootMarker(root) {
1913
2240
  if (hasProjectRootDirectoryMarker(root)) return true;
1914
- for (const marker of projectRootFileMarkers) try {
1915
- if (statSync(resolve(root, ...marker)).isFile()) return true;
1916
- } catch (error) {
1917
- if (error.code !== "ENOENT") throw error;
2241
+ return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
2242
+ }
2243
+ function hasProjectRootFileMarker(root, markers) {
2244
+ for (const marker of markers) {
2245
+ const path = Array.isArray(marker) ? marker : [marker];
2246
+ try {
2247
+ if (statSync(resolve(root, ...path)).isFile()) return true;
2248
+ } catch (error) {
2249
+ if (error.code !== "ENOENT") throw error;
2250
+ }
1918
2251
  }
1919
2252
  return false;
1920
2253
  }
@@ -1930,7 +2263,6 @@ const providerDeploymentOutputOwnerOrder = [
1930
2263
  "database",
1931
2264
  "blob",
1932
2265
  "queue",
1933
- "rate-limit",
1934
2266
  "schedule",
1935
2267
  "workflow",
1936
2268
  "vite-hub",
@@ -1957,13 +2289,13 @@ function createDefaultCloudflareStaticOutputDir(rootDir) {
1957
2289
  return resolve(rootDir, "dist", "client");
1958
2290
  }
1959
2291
  function resolveProviderOutputOwnershipFile(outputRoot, fileName) {
1960
- if (!fileName || fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") throw new TypeError(`Invalid Provider Output ownership file name: ${JSON.stringify(fileName)}`);
2292
+ if (!fileName || fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") throw internalErrorDiagnostics.INTERNAL_B0034({ message: `Invalid Provider Output ownership file name: ${JSON.stringify(fileName)}` });
1961
2293
  return resolve(outputRoot, fileName);
1962
2294
  }
1963
2295
  async function readProviderOutputOwnershipFile(outputRoot, fileName) {
1964
2296
  try {
1965
2297
  const parsed = JSON.parse(await readFile(resolveProviderOutputOwnershipFile(outputRoot, fileName), "utf8"));
1966
- if (!Array.isArray(parsed) || !parsed.every((value) => typeof value === "string")) throw new TypeError(`Invalid Provider Output ownership file schema: ${JSON.stringify(fileName)}`);
2298
+ if (!Array.isArray(parsed) || !parsed.every((value) => typeof value === "string")) throw internalErrorDiagnostics.INTERNAL_B0035({ message: `Invalid Provider Output ownership file schema: ${JSON.stringify(fileName)}` });
1967
2299
  return parsed;
1968
2300
  } catch (error) {
1969
2301
  if (error instanceof Error && "code" in error && error.code === "ENOENT") return [];
@@ -1988,7 +2320,7 @@ async function resolvePersistedProviderOutputOwnership(outputRoot, ownership, fi
1988
2320
  const arrays = { ...ownership?.arrays };
1989
2321
  await Promise.all(Object.entries(files).map(async ([field, fileName]) => {
1990
2322
  const current = arrays[field];
1991
- if (!current) throw new TypeError(`Provider Output ownership file for ${JSON.stringify(field)} requires array ownership.`);
2323
+ if (!current) throw internalErrorDiagnostics.INTERNAL_B0036({ message: `Provider Output ownership file for ${JSON.stringify(field)} requires array ownership.` });
1992
2324
  arrays[field] = {
1993
2325
  ...current,
1994
2326
  values: [...await readProviderOutputOwnershipFile(outputRoot, fileName), ...current.values ?? []]
@@ -2017,8 +2349,14 @@ function createDefaultVercelOutputRoot(rootDir) {
2017
2349
  function createDefaultNetlifyOutputRoot(rootDir) {
2018
2350
  return resolve(rootDir, ".netlify", "v1");
2019
2351
  }
2352
+ /** Restore a retained complete publication before generation or transaction snapshots. Call under the output lock. */
2353
+ function recoverNetlifyDeploymentOutput(rootDir) {
2354
+ const outputRoot = createDefaultNetlifyOutputRoot(rootDir);
2355
+ const previousOutputRoot = `${outputRoot}.previous`;
2356
+ if (!existsSync(outputRoot) && existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
2357
+ }
2020
2358
  function assertNetlifyFunctionName(functionName) {
2021
- if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw new Error(`Invalid Netlify function name: ${functionName}`);
2359
+ if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw internalErrorDiagnostics.INTERNAL_B0037({ message: `Invalid Netlify function name: ${functionName}` });
2022
2360
  }
2023
2361
  function resolveNetlifyFunctionFile(functionsRoot, functionName) {
2024
2362
  assertNetlifyFunctionName(functionName);
@@ -2026,7 +2364,8 @@ function resolveNetlifyFunctionFile(functionsRoot, functionName) {
2026
2364
  }
2027
2365
  async function appendNetlifyFunctionConfig(outfile, config) {
2028
2366
  if (!config) return;
2029
- await writeFile(outfile, `${(await readFile(outfile, "utf8")).trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
2367
+ const bundled = await readFile(outfile, "utf8");
2368
+ await writeFile(outfile, `${bundled.trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
2030
2369
  }
2031
2370
  async function writeCloudflareDeploymentOutput(options, signal) {
2032
2371
  signal?.throwIfAborted();
@@ -2036,7 +2375,7 @@ async function writeCloudflareDeploymentOutput(options, signal) {
2036
2375
  const copiesStaticOutput = Boolean(options.bundleEntry && staticIndex && resolve(clientDir) !== resolve(staticOutputDir));
2037
2376
  const files = Object.entries(options.files ?? {});
2038
2377
  const workerOutfile = options.bundleEntry ? resolve(outputRoot, options.bundleOutfileName ?? "index.js") : void 0;
2039
- if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw new Error(`Cloudflare output file conflicts with bundle outfile: ${workerOutfile}`);
2378
+ if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw internalErrorDiagnostics.INTERNAL_B0038({ message: `Cloudflare output file conflicts with bundle outfile: ${workerOutfile}` });
2040
2379
  const backupRoot = copiesStaticOutput ? await mkdtemp(resolve(options.rootDir, ".vitehub-cloudflare-output-")) : void 0;
2041
2380
  const previousOutputRoot = backupRoot ? resolve(backupRoot, "output") : `${outputRoot}.previous`;
2042
2381
  const previousStaticOutputDir = backupRoot ? resolve(backupRoot, "static") : `${staticOutputDir}.previous`;
@@ -2078,7 +2417,7 @@ async function writeCloudflareDeploymentOutput(options, signal) {
2078
2417
  wranglerConfigDefaults: options.wranglerConfigDefaults,
2079
2418
  wranglerConfigOwnership
2080
2419
  }),
2081
- options.bundleEntry && staticIndex ? copyClientOutput(clientDir, staticOutputDir) : Promise.resolve(),
2420
+ options.bundleEntry && staticIndex ? copyClientOutput(clientDir, staticOutputDir, [outputRoot]) : Promise.resolve(),
2082
2421
  ...files.map(([fileName, contents]) => writeFile(resolve(outputRoot, fileName), contents, "utf8"))
2083
2422
  ];
2084
2423
  if (options.bundleEntry && workerOutfile) {
@@ -2091,6 +2430,13 @@ async function writeCloudflareDeploymentOutput(options, signal) {
2091
2430
  });
2092
2431
  await bundleEsmEntry(options.bundleEntry, stagedWorkerOutfile, {
2093
2432
  ...options.bundleOptions,
2433
+ define: {
2434
+ ...options.bundleDefines,
2435
+ ...options.bundleOptions?.define
2436
+ },
2437
+ minifyIdentifiers: options.bundleOptions?.minifyIdentifiers ?? true,
2438
+ minifySyntax: options.bundleOptions?.minifySyntax ?? true,
2439
+ minifyWhitespace: options.bundleOptions?.minifyWhitespace ?? true,
2094
2440
  rootDir: options.sourceRootDir ?? options.rootDir,
2095
2441
  signal
2096
2442
  });
@@ -2204,6 +2550,13 @@ async function writeVercelDeploymentOutput(options, signal) {
2204
2550
  }
2205
2551
  await bundleEsmEntry(options.bundleEntry, serverEntry, {
2206
2552
  ...options.bundleOptions,
2553
+ define: {
2554
+ ...options.bundleDefines,
2555
+ ...options.bundleOptions?.define
2556
+ },
2557
+ minifyIdentifiers: options.bundleOptions?.minifyIdentifiers ?? true,
2558
+ minifySyntax: options.bundleOptions?.minifySyntax ?? true,
2559
+ minifyWhitespace: options.bundleOptions?.minifyWhitespace ?? true,
2207
2560
  rootDir: options.sourceRootDir ?? options.rootDir,
2208
2561
  signal
2209
2562
  });
@@ -2311,7 +2664,14 @@ async function writeNetlifyDeploymentOutput(options, signal) {
2311
2664
  await mkdir(dirname(outfile), { recursive: true });
2312
2665
  await bundleEsmEntry(func.bundleEntry, outfile, {
2313
2666
  ...func.bundleOptions,
2314
- minifyIdentifiers: func.config ? true : func.bundleOptions.minifyIdentifiers,
2667
+ conditions: func.bundleOptions.conditions ?? ["netlify", "node"],
2668
+ define: {
2669
+ ...options.bundleDefines,
2670
+ ...func.bundleOptions.define
2671
+ },
2672
+ minifyIdentifiers: func.config ? true : func.bundleOptions.minifyIdentifiers ?? true,
2673
+ minifySyntax: func.bundleOptions.minifySyntax ?? true,
2674
+ minifyWhitespace: func.bundleOptions.minifyWhitespace ?? true,
2315
2675
  rootDir: options.sourceRootDir ?? options.rootDir,
2316
2676
  signal
2317
2677
  });
@@ -2408,19 +2768,22 @@ async function writeProviderDeploymentOutputsNow(options, signal, transaction) {
2408
2768
  ...options.cloudflare,
2409
2769
  clientOutDir: options.clientOutDir,
2410
2770
  rootDir: options.rootDir,
2411
- sourceRootDir: options.sourceRootDir
2771
+ sourceRootDir: options.sourceRootDir,
2772
+ bundleDefines: options.bundleDefines
2412
2773
  }, signal));
2413
2774
  if (options.netlify) writes.push(writeNetlifyDeploymentOutput({
2414
2775
  ...options.netlify,
2415
2776
  clientOutDir: options.clientOutDir,
2416
2777
  rootDir: options.rootDir,
2417
- sourceRootDir: options.sourceRootDir
2778
+ sourceRootDir: options.sourceRootDir,
2779
+ bundleDefines: options.bundleDefines
2418
2780
  }, signal));
2419
2781
  if (options.vercel) writes.push(writeVercelDeploymentOutput({
2420
2782
  ...options.vercel,
2421
2783
  clientOutDir: options.clientOutDir,
2422
2784
  rootDir: options.rootDir,
2423
- sourceRootDir: options.sourceRootDir
2785
+ sourceRootDir: options.sourceRootDir,
2786
+ bundleDefines: options.bundleDefines
2424
2787
  }, signal));
2425
2788
  await settleWrites(writes);
2426
2789
  if (options.cloudflare && transaction) transaction.cloudflareWritten = true;
@@ -2531,6 +2894,7 @@ async function restoreProviderDeploymentOutputSnapshot(snapshot) {
2531
2894
  }
2532
2895
  }
2533
2896
  async function withProviderDeploymentOutputRootTransaction(rootDir, operation, options = {}) {
2897
+ recoverNetlifyDeploymentOutput(rootDir);
2534
2898
  const roots = [
2535
2899
  createDefaultCloudflareOutputRoot(rootDir),
2536
2900
  createDefaultNetlifyOutputRoot(rootDir),
@@ -2540,8 +2904,6 @@ async function withProviderDeploymentOutputRootTransaction(rootDir, operation, o
2540
2904
  resolve(rootDir, ".vitehub/queue/cloudflare-output.json"),
2541
2905
  resolve(rootDir, ".vitehub/queue/registry.mjs"),
2542
2906
  resolve(rootDir, ".vitehub/queue/vercel-output.json"),
2543
- resolve(rootDir, ".vitehub/rate-limit/cloudflare-output.json"),
2544
- resolve(rootDir, ".vitehub/rate-limit/manifest.json"),
2545
2907
  resolve(rootDir, ".vitehub/schedule"),
2546
2908
  resolve(rootDir, ".vitehub/workflow")
2547
2909
  ];
@@ -2718,15 +3080,15 @@ async function resetProviderDeploymentOutputs(catalog, failure, generation) {
2718
3080
  if (!generation) catalog.resetDeploymentContributions();
2719
3081
  if (active && (!generation || active.state.generations.has(generation))) {
2720
3082
  active.state.rollback = true;
2721
- active.controller.abort(/* @__PURE__ */ new Error("Provider Output finalization reset"));
3083
+ active.controller.abort(internalErrorDiagnostics.INTERNAL_B0039({ message: "Provider Output finalization reset" }));
2722
3084
  active.reset = {
2723
- failures: new Set([failure]),
3085
+ failures: /* @__PURE__ */ new Set([failure]),
2724
3086
  promise: active.promise.catch(() => void 0)
2725
3087
  };
2726
3088
  providerDeploymentOutputCompletedResets.set(catalog, active.reset);
2727
3089
  await active.reset.promise;
2728
3090
  } else if (failure !== void 0) providerDeploymentOutputCompletedResets.set(catalog, {
2729
- failures: new Set([failure]),
3091
+ failures: /* @__PURE__ */ new Set([failure]),
2730
3092
  promise: Promise.resolve()
2731
3093
  });
2732
3094
  }
@@ -2750,6 +3112,7 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
2750
3112
  if (catalog.hasDeploymentContributions()) await finalizeProviderDeploymentOutputs(catalog, options);
2751
3113
  return;
2752
3114
  }
3115
+ const bundleDefines = { ...catalog.bundleDefines };
2753
3116
  const controller = new AbortController();
2754
3117
  const state = {
2755
3118
  generations: /* @__PURE__ */ new Set(),
@@ -2811,7 +3174,13 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
2811
3174
  signal: controller.signal,
2812
3175
  write: async (writeOptions) => {
2813
3176
  throwIfProviderOutputAborted(controller.signal);
2814
- await writeProviderDeploymentOutputsNow(writeOptions, controller.signal, transaction);
3177
+ await writeProviderDeploymentOutputsNow({
3178
+ ...writeOptions,
3179
+ bundleDefines: {
3180
+ ...bundleDefines,
3181
+ ...writeOptions.bundleDefines
3182
+ }
3183
+ }, controller.signal, transaction);
2815
3184
  }
2816
3185
  });
2817
3186
  throwIfProviderOutputAborted(controller.signal);
@@ -2904,6 +3273,431 @@ function getViteMode(env = process.env) {
2904
3273
  return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
2905
3274
  }
2906
3275
  //#endregion
3276
+ //#region ../internal/src/definition-catalog.ts
3277
+ const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
3278
+ const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
3279
+ const ignoredDirs = /* @__PURE__ */ new Set([
3280
+ "node_modules",
3281
+ "dist",
3282
+ ".output",
3283
+ ".nuxt",
3284
+ ".vercel",
3285
+ ".git",
3286
+ ".vitehub"
3287
+ ]);
3288
+ function resolveDefinitionScanRoots(rootDir, scanDirs = []) {
3289
+ return [...new Set([rootDir, ...scanDirs].filter(Boolean))];
3290
+ }
3291
+ function createDirectoryDefinitionSource(source, scanDirs, subdir, options = {}) {
3292
+ return {
3293
+ ...options,
3294
+ kind: "directory",
3295
+ scanDirs,
3296
+ source,
3297
+ subdir
3298
+ };
3299
+ }
3300
+ function createSuffixDefinitionSource(source, roots, pattern, normalizeName, options = {}) {
3301
+ return {
3302
+ ...options,
3303
+ kind: "suffix",
3304
+ normalizeName,
3305
+ pattern,
3306
+ roots,
3307
+ source
3308
+ };
3309
+ }
3310
+ function readDirEntries(root) {
3311
+ try {
3312
+ return readdirSync(root, { withFileTypes: true });
3313
+ } catch (error) {
3314
+ if (error.code === "ENOENT") return [];
3315
+ throw error;
3316
+ }
3317
+ }
3318
+ function isGitRepositoryDirectory(directory) {
3319
+ return existsSync(resolve$1(directory, ".git"));
3320
+ }
3321
+ function listMatchingFiles(root, predicate, options = {}) {
3322
+ const files = [];
3323
+ for (const entry of readDirEntries(root)) {
3324
+ const absolute = resolve$1(root, entry.name);
3325
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
3326
+ if (isGitRepositoryDirectory(absolute)) continue;
3327
+ if (entry.name.startsWith(".")) continue;
3328
+ if (ignoredDirs.has(entry.name)) continue;
3329
+ files.push(...listMatchingFiles(absolute, predicate, options));
3330
+ continue;
3331
+ }
3332
+ if (entry.name.startsWith(".") && !options.includeHidden) continue;
3333
+ if (entry.isFile() && predicate(entry.name)) files.push(absolute);
3334
+ }
3335
+ return files.sort();
3336
+ }
3337
+ function listSourceFiles(root, options = {}) {
3338
+ return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
3339
+ }
3340
+ function normalizePathDefinitionName(rootDir, file) {
3341
+ return relative$1(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
3342
+ }
3343
+ function normalizeSuffixDefinitionName(rootDir, file, pattern, options = {}) {
3344
+ const normalized = relative$1(rootDir, file).replace(pattern, "");
3345
+ if (options.stripPrefix && normalized.startsWith(options.stripPrefix)) return normalized.slice(options.stripPrefix.length);
3346
+ return normalized;
3347
+ }
3348
+ function sortDefinitions(definitions) {
3349
+ return [...definitions.values()].sort((left, right) => left.name.localeCompare(right.name));
3350
+ }
3351
+ function registerDefinition(definitions, definition, sourceLabel) {
3352
+ const existing = definitions.get(definition.name);
3353
+ if (existing) throw internalErrorDiagnostics.INTERNAL_C0001({ message: `Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}` });
3354
+ definitions.set(definition.name, definition);
3355
+ }
3356
+ function mergeDefinitions(feature, ...sources) {
3357
+ const definitions = /* @__PURE__ */ new Map();
3358
+ for (const source of sources) {
3359
+ if (!source) continue;
3360
+ for (const definition of source) {
3361
+ const existing = definitions.get(definition.name);
3362
+ if (existing && existing.handler !== definition.handler) throw internalErrorDiagnostics.INTERNAL_C0002({ message: `Duplicate ${feature} name "${definition.name}" from multiple discovery sources:\n - ${existing.handler} (${existing.source ?? "unknown"})\n - ${definition.handler} (${definition.source ?? "unknown"})` });
3363
+ if (!existing) definitions.set(definition.name, definition);
3364
+ }
3365
+ }
3366
+ return sortDefinitions(definitions);
3367
+ }
3368
+ function createDefinition(source, file, name) {
3369
+ if (source.createDefinition) return source.createDefinition({
3370
+ file,
3371
+ name
3372
+ });
3373
+ return {
3374
+ handler: file,
3375
+ name,
3376
+ source: source.source
3377
+ };
3378
+ }
3379
+ function scanSuffixDefinitions(feature, source) {
3380
+ const definitions = /* @__PURE__ */ new Map();
3381
+ for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => {
3382
+ source.pattern.lastIndex = 0;
3383
+ return source.pattern.test(name);
3384
+ }, { includeHidden: source.includeHidden })) {
3385
+ const name = source.normalizeName(root, file);
3386
+ if (!name) continue;
3387
+ registerDefinition(definitions, createDefinition(source, file, name), feature);
3388
+ }
3389
+ return sortDefinitions(definitions);
3390
+ }
3391
+ function scanDirectoryDefinitions(feature, source) {
3392
+ const definitions = /* @__PURE__ */ new Map();
3393
+ for (const scanDir of source.scanDirs) {
3394
+ const directory = resolve$1(scanDir, source.subdir);
3395
+ for (const file of listSourceFiles(directory, { includeHidden: source.includeHidden })) {
3396
+ const name = source.normalizeName ? source.normalizeName(directory, file) : normalizePathDefinitionName(directory, file);
3397
+ if (!name) continue;
3398
+ registerDefinition(definitions, createDefinition(source, file, name), feature);
3399
+ }
3400
+ }
3401
+ return sortDefinitions(definitions);
3402
+ }
3403
+ function discoverDefinitions(feature, sources) {
3404
+ return mergeDefinitions(feature, ...sources.map((source) => source.kind === "suffix" ? scanSuffixDefinitions(feature, source) : scanDirectoryDefinitions(feature, source)));
3405
+ }
3406
+ function createImportExpression(registryFile, file) {
3407
+ const importPath = relative$1(resolve$1(registryFile, ".."), file);
3408
+ return `import(${JSON.stringify(importPath.startsWith(".") ? importPath : `./${importPath}`)})`;
3409
+ }
3410
+ function createRuntimeRegistryContents(registryFile, definitions) {
3411
+ return [
3412
+ "",
3413
+ "const registry = {",
3414
+ ...definitions.map((definition) => ` [${JSON.stringify(definition.name)}]: async () => ${createImportExpression(registryFile, definition.handler)},`),
3415
+ "}",
3416
+ "",
3417
+ "export default registry",
3418
+ ""
3419
+ ].join("\n");
3420
+ }
3421
+ async function writeRuntimeRegistryFile(registryFile, definitions) {
3422
+ await writeFileIfChanged(registryFile, createRuntimeRegistryContents(registryFile, definitions));
3423
+ }
3424
+ async function writeFileIfChanged(file, contents) {
3425
+ if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
3426
+ await mkdir(resolve$1(file, ".."), { recursive: true });
3427
+ await writeFile(file, contents, "utf8");
3428
+ }
3429
+ //#endregion
3430
+ //#region ../internal/src/nitro-kit.ts
3431
+ function cloneArray(value) {
3432
+ return Array.isArray(value) ? [...value] : [];
3433
+ }
3434
+ function isRecord$2(value) {
3435
+ return Object(value) === value && !Array.isArray(value);
3436
+ }
3437
+ function sameHandler(left, right) {
3438
+ return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
3439
+ }
3440
+ /** Create a Nitro 3 configuration builder for generated ViteHub output. */
3441
+ function createNitroServerKit(value = {}) {
3442
+ const config = isRecord$2(value) ? { ...value } : {};
3443
+ const handlers = cloneArray(config.handlers);
3444
+ const plugins = cloneArray(config.plugins);
3445
+ config.handlers = handlers;
3446
+ config.plugins = plugins;
3447
+ return {
3448
+ config,
3449
+ addHandler(handler, position = "end") {
3450
+ if (handlers.some((candidate) => isRecord$2(candidate) && sameHandler(candidate, handler))) return;
3451
+ if (position === "start") handlers.unshift({ ...handler });
3452
+ else handlers.push({ ...handler });
3453
+ },
3454
+ addPlugin(plugin, position = "end") {
3455
+ if (plugins.includes(plugin)) return;
3456
+ if (position === "start") plugins.unshift(plugin);
3457
+ else plugins.push(plugin);
3458
+ }
3459
+ };
3460
+ }
3461
+ //#endregion
3462
+ //#region ../internal/src/contributions.ts
3463
+ const unnamedPlugin = "unnamed plugin";
3464
+ function isNonEmptyString(value) {
3465
+ return String(value) === value && value.length > 0;
3466
+ }
3467
+ function isThenable(value) {
3468
+ return typeof value.then === "function";
3469
+ }
3470
+ async function flattenPlugins(value, plugins, seen) {
3471
+ if (Array.isArray(value)) {
3472
+ for (const item of value) await flattenPlugins(item, plugins, seen);
3473
+ return;
3474
+ }
3475
+ if (!isPlainObject(value) || seen.has(value)) return;
3476
+ seen.add(value);
3477
+ if (isThenable(value)) {
3478
+ await flattenPlugins(await value, plugins, seen);
3479
+ return;
3480
+ }
3481
+ plugins.push(value);
3482
+ }
3483
+ function readModule(value) {
3484
+ if (!/^file:/i.test(value)) return value;
3485
+ const url = value.slice(5);
3486
+ if (!url.startsWith("/")) throw new TypeError("relative file URL");
3487
+ return fileURLToPath(`file:${url}`);
3488
+ }
3489
+ function isRelative(module) {
3490
+ return !isAbsolute$1(module) && /^\.\.?(?:[\\/]|$)/.test(module);
3491
+ }
3492
+ /** Describes a contribution as `module#export from plugin "name"` for messages. */
3493
+ function describeContribution(contribution) {
3494
+ const { export: exportName, module } = contribution.definition;
3495
+ return `${exportName === "default" ? module : `${module}#${exportName}`} from plugin ${JSON.stringify(contribution.plugin)}`;
3496
+ }
3497
+ async function collectContributions(plugins, options) {
3498
+ const candidates = [];
3499
+ await flattenPlugins(plugins ?? [], candidates, /* @__PURE__ */ new Set());
3500
+ const collected = /* @__PURE__ */ new Map();
3501
+ for (const plugin of candidates) {
3502
+ if (!Object.hasOwn(plugin, "vitehub")) continue;
3503
+ const metadata = Reflect.get(plugin, "vitehub");
3504
+ if (!isPlainObject(metadata) || !Object.hasOwn(metadata, options.key)) continue;
3505
+ const source = metadata[options.key];
3506
+ const pluginName = Reflect.get(plugin, "name");
3507
+ const contributor = isNonEmptyString(pluginName) ? pluginName : unnamedPlugin;
3508
+ const fail = (reason) => {
3509
+ throw options.invalid(`[vitehub] Plugin ${JSON.stringify(contributor)} contributed an invalid ${options.kind}: ${reason}`);
3510
+ };
3511
+ const callable = typeof source === "function";
3512
+ const entries = callable ? await Reflect.apply(source, void 0, [options.context]) : source;
3513
+ if (entries === void 0 && callable) continue;
3514
+ if (!Array.isArray(entries)) fail(`\`vitehub.${options.key}\` must be an array or a function that returns one.`);
3515
+ const list = entries;
3516
+ for (const entry of list) {
3517
+ const contribution = readContribution(entry, contributor, options, fail);
3518
+ const { plugin: _plugin, reason: _reason, ...definitionIdentity } = contribution;
3519
+ const identity = JSON.stringify(definitionIdentity);
3520
+ const existing = collected.get(contribution.name);
3521
+ if (existing?.identity === identity) continue;
3522
+ if (existing) throw options.duplicate(`[vitehub] ${options.kind} ${JSON.stringify(contribution.name)} is contributed more than once:\n - ${describeContribution(existing.contribution)}\n - ${describeContribution(contribution)}\nEach ${options.kind} name must have one contribution. Rename or remove one.`);
3523
+ collected.set(contribution.name, {
3524
+ contribution,
3525
+ identity
3526
+ });
3527
+ }
3528
+ }
3529
+ return [...collected.values()].map(({ contribution }) => contribution).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
3530
+ }
3531
+ function readContribution(entry, plugin, options, fail) {
3532
+ if (!isPlainObject(entry)) return fail("expected { name, definition: { module, export? }, reason? }.");
3533
+ const { definition, name, reason } = entry;
3534
+ if (!isNonEmptyString(name) || name.trim() !== name) return fail("`name` must be a non-empty string without surrounding whitespace.");
3535
+ const nameProblem = options.checkName?.(name);
3536
+ if (nameProblem) return fail(`${options.kind} ${JSON.stringify(name)}: ${nameProblem}`);
3537
+ if (!isPlainObject(definition)) return fail(`${options.kind} ${JSON.stringify(name)} needs \`definition: { module, export? }\`.`);
3538
+ if (!isNonEmptyString(definition.module)) return fail(`\`definition.module\` of ${options.kind} ${JSON.stringify(name)} must be a non-empty string.`);
3539
+ let module;
3540
+ try {
3541
+ module = readModule(definition.module);
3542
+ } catch {
3543
+ return fail(`\`definition.module\` of ${options.kind} ${JSON.stringify(name)} must be a valid file URL or module specifier.`);
3544
+ }
3545
+ if (isRelative(module)) return fail(`\`definition.module\` of ${options.kind} ${JSON.stringify(name)} is relative: ${JSON.stringify(module)}. Use an absolute file path, a file: URL, or a package specifier.`);
3546
+ const exportName = definition.export ?? "default";
3547
+ if (!isNonEmptyString(exportName)) return fail(`\`definition.export\` of ${options.kind} ${JSON.stringify(name)} must be a non-empty string.`);
3548
+ if (reason !== void 0 && !isNonEmptyString(reason)) return fail(`\`reason\` of ${options.kind} ${JSON.stringify(name)} must be a non-empty string.`);
3549
+ const base = {
3550
+ definition: {
3551
+ export: exportName,
3552
+ module
3553
+ },
3554
+ name,
3555
+ plugin
3556
+ };
3557
+ if (reason !== void 0) base.reason = reason;
3558
+ return {
3559
+ ...options.fields?.(entry, fail),
3560
+ ...base
3561
+ };
3562
+ }
3563
+ //#endregion
3564
+ //#region src/contributions.ts
3565
+ const scheduleNamePattern = /^[a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)*$/i;
3566
+ /** Error for a Schedule name with two definitions. Both sources are named so the user knows which to rename. */
3567
+ function duplicateScheduleError(name, first, second) {
3568
+ return scheduleErrorDiagnostics.SCHEDULE_B0006({ message: `[vitehub] Schedule "${name}" is defined more than once:\n - ${first}\n - ${second}\nRename or remove one definition. Each Schedule name must have one definition.` });
3569
+ }
3570
+ function invalidContribution(contribution, reason) {
3571
+ return scheduleErrorDiagnostics.SCHEDULE_B0007({ message: `[vitehub] Plugin ${JSON.stringify(contribution.plugin)} contributed an invalid Schedule: ${reason}` });
3572
+ }
3573
+ /**
3574
+ * Collects `vitehub.schedules` contributions from Vite plugins. Two contributions with one name fail with
3575
+ * `SCHEDULE_B0006`. Invalid entries fail with `SCHEDULE_B0007`.
3576
+ */
3577
+ async function collectScheduleContributions(plugins, context) {
3578
+ const contributions = await collectContributions(plugins, {
3579
+ checkName: (name) => scheduleNamePattern.test(name) ? void 0 : "`name` must be letters, numbers, dots, underscores, dashes, and slashes, for example \"content/publish\".",
3580
+ context,
3581
+ duplicate: (message) => scheduleErrorDiagnostics.SCHEDULE_B0006({ message }),
3582
+ invalid: (message) => scheduleErrorDiagnostics.SCHEDULE_B0007({ message }),
3583
+ key: "schedules",
3584
+ kind: "Schedule"
3585
+ });
3586
+ for (const contribution of contributions) {
3587
+ const { export: exportName, module } = contribution.definition;
3588
+ if (!isAbsolute(module)) throw invalidContribution(contribution, `\`definition.module\` of Schedule ${JSON.stringify(contribution.name)} must be an absolute file path or a file: URL, because the build reads its cron from source.`);
3589
+ if (exportName !== "default") throw invalidContribution(contribution, `Schedule ${JSON.stringify(contribution.name)} uses \`definition.export: ${JSON.stringify(exportName)}\`. Schedule Definitions must be the default export, because the build reads its cron from \`export default defineSchedule()\`.`);
3590
+ }
3591
+ return contributions;
3592
+ }
3593
+ //#endregion
3594
+ //#region src/discovery.ts
3595
+ /** Discovery source of Schedule Definitions that Vite plugins contribute through `vitehub.schedules`. */
3596
+ const contributedScheduleSource = "vite-plugin-contribution";
3597
+ /**
3598
+ * Whether a Definition is a server Schedule: a `server/schedules/` file or a contribution. Server Schedules share one
3599
+ * delivery path, for example the generated Nitro wake plugin when `providerOutput` is `auto`.
3600
+ */
3601
+ function isServerScheduleDefinition(definition) {
3602
+ return definition.source === "server-schedules" || definition.source === "vite-plugin-contribution";
3603
+ }
3604
+ const scheduleSuffixPattern = /\.schedule\.(?:c|m)?[jt]s$/i;
3605
+ function readScheduleDiscoveryMetadata(file, contribution) {
3606
+ const source = readFileSync(file, "utf8");
3607
+ const module = scanModule(source, file);
3608
+ const definition = findDefaultExportCall(module, ["defineSchedule"], { positionalOptionsIndex: 2 });
3609
+ const unsupported = (offset, message) => {
3610
+ const line = source.slice(0, offset).split("\n").length;
3611
+ throw scheduleErrorDiagnostics.SCHEDULE_B0005({ message: `[vitehub] ${file}:${line}: ${message}` });
3612
+ };
3613
+ if (!definition) {
3614
+ const call = findCalls(module, ["defineSchedule"])[0];
3615
+ const message = "Schedule discovery requires a direct default export of defineSchedule() with literal options.";
3616
+ if (call) unsupported(call.start, message);
3617
+ if (module.errors[0]) unsupported(0, `${message} The file has a syntax error: ${module.errors[0].message}`);
3618
+ if (contribution) throw scheduleErrorDiagnostics.SCHEDULE_B0005({ message: `[vitehub] ${contribution} has no default export of defineSchedule(). The build reads contributed Schedules from source, so the module must contain \`export default defineSchedule({ cron: "...", handler })\`.` });
3619
+ return {};
3620
+ }
3621
+ const start = definition.call.start;
3622
+ let manual = false;
3623
+ for (const property of definition.options ? objectProperties(definition.options) : []) {
3624
+ if (property.key === void 0 || property.computed) unsupported(start, "Schedule discovery cannot resolve spread, computed, or escaped option keys. Declare manual with an unescaped literal key and a literal true or false value.");
3625
+ if (property.key !== "manual") continue;
3626
+ const value = property.node.type === "Property" && property.node.kind === "init" && !property.node.method && property.value?.type === "Literal" && typeof property.value.value === "boolean" ? property.value.value : void 0;
3627
+ if (value === void 0) unsupported(start, "Schedule discovery requires manual to be a literal true or false; it cannot evaluate this expression.");
3628
+ manual = value === true;
3629
+ }
3630
+ return { manual };
3631
+ }
3632
+ function createDiscoveredScheduleDefinition(source) {
3633
+ return (context) => {
3634
+ return {
3635
+ ...readScheduleDiscoveryMetadata(context.file),
3636
+ handler: context.file,
3637
+ name: context.name,
3638
+ source
3639
+ };
3640
+ };
3641
+ }
3642
+ function normalizeSuffixScheduleName(rootDir, file) {
3643
+ return normalizeSuffixDefinitionName(rootDir, file, scheduleSuffixPattern, { stripPrefix: "src/" });
3644
+ }
3645
+ function normalizeDirectoryScheduleName(directory, file) {
3646
+ return normalizePathDefinitionName(directory, file);
3647
+ }
3648
+ function createContributedScheduleDefinition(contribution) {
3649
+ const file = contribution.definition.module;
3650
+ if (!existsSync(file)) throw scheduleErrorDiagnostics.SCHEDULE_B0007({ message: `[vitehub] ${describeContribution(contribution)} adds Schedule "${contribution.name}", but the Definition module does not exist.` });
3651
+ const definition = {
3652
+ ...readScheduleDiscoveryMetadata(file, describeContribution(contribution)),
3653
+ contributor: contribution.plugin,
3654
+ handler: file,
3655
+ name: contribution.name,
3656
+ source: contributedScheduleSource
3657
+ };
3658
+ if (contribution.reason) definition.reason = contribution.reason;
3659
+ return definition;
3660
+ }
3661
+ function mergeContributedScheduleDefinitions(discovered, contributions) {
3662
+ if (!contributions?.length) return discovered;
3663
+ const definitions = new Map(discovered.map((definition) => [definition.name, definition]));
3664
+ for (const contribution of contributions) {
3665
+ const existing = definitions.get(contribution.name);
3666
+ if (existing) {
3667
+ const first = existing.source === "vite-plugin-contribution" ? describeContribution({
3668
+ definition: {
3669
+ export: "default",
3670
+ module: existing.handler
3671
+ },
3672
+ plugin: existing.contributor ?? "unnamed plugin"
3673
+ }) : existing.handler;
3674
+ throw duplicateScheduleError(contribution.name, first, describeContribution(contribution));
3675
+ }
3676
+ definitions.set(contribution.name, createContributedScheduleDefinition(contribution));
3677
+ }
3678
+ return [...definitions.values()].sort((left, right) => left.name.localeCompare(right.name));
3679
+ }
3680
+ function discoverScheduleDefinitions(options) {
3681
+ if (options.mode === "server-schedules") return discoverDefinitions("schedule", [createDirectoryDefinitionSource("server-schedules", options.scanDirs, "schedules", {
3682
+ createDefinition: createDiscoveredScheduleDefinition("server-schedules"),
3683
+ normalizeName: normalizeDirectoryScheduleName
3684
+ })]);
3685
+ const roots = resolveDefinitionScanRoots(options.rootDir, options.scanDirs);
3686
+ const serverRoots = resolveDefinitionScanRoots(options.serverRootDir || options.rootDir, options.scanDirs);
3687
+ const serverScanDirs = options.serverDirs ?? serverRoots.map((root) => resolve(root, "server"));
3688
+ for (const directory of serverScanDirs) if (roots.every((root) => {
3689
+ const path = relative(resolve(root), resolve(directory));
3690
+ return path === ".." || path.startsWith(`..${sep}`) || isAbsolute(path);
3691
+ })) roots.push(directory);
3692
+ return mergeContributedScheduleDefinitions(mergeDefinitions("schedule", discoverDefinitions("schedule", [createSuffixDefinitionSource("vite-suffix", roots, scheduleSuffixPattern, normalizeSuffixScheduleName, { createDefinition: createDiscoveredScheduleDefinition("vite-suffix") })]).filter((definition) => !serverScanDirs.some((directory) => {
3693
+ const path = relative(resolve(directory, "schedules"), definition.handler);
3694
+ return path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path);
3695
+ })), discoverDefinitions("schedule", [createDirectoryDefinitionSource("server-schedules", serverScanDirs, "schedules", {
3696
+ createDefinition: createDiscoveredScheduleDefinition("server-schedules"),
3697
+ normalizeName: normalizeDirectoryScheduleName
3698
+ })])), options.contributions);
3699
+ }
3700
+ //#endregion
2907
3701
  //#region src/integrations/vercel.ts
2908
3702
  function getVercelSchedulePath(name) {
2909
3703
  return `/api/vitehub/schedules/vercel/${name.replace(/[^a-z0-9/_-]+/gi, "_")}`;
@@ -2918,17 +3712,24 @@ const cloudflareScheduleWorkerMarker = "vitehub-schedule-provider-output";
2918
3712
  const deployedScheduleSourcesPath = ".vitehub/schedule/sources";
2919
3713
  const denoCronFileName = "deno-cron.mjs";
2920
3714
  const generatedRegistryFileName = "registry.mjs";
3715
+ function isRecord$1(value) {
3716
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3717
+ }
3718
+ function readStringArray(value) {
3719
+ return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
3720
+ }
3721
+ function isVercelCron(value) {
3722
+ return isRecord$1(value) && typeof value.path === "string" && typeof value.schedule === "string";
3723
+ }
2921
3724
  function resolveScheduleRuntimeEntry(resolveImport = (specifier) => import.meta.resolve(specifier)) {
2922
3725
  return fileURLToPath(resolveImport(scheduleStaticRuntimeImport));
2923
3726
  }
2924
3727
  function resolveScheduleDefinitionEntry(resolveImport = (specifier) => import.meta.resolve(specifier)) {
2925
- return resolve(dirname(fileURLToPath(resolveImport(`${schedulePackageName}/package.json`))), "dist/definition.js");
3728
+ const packageRoot = dirname(fileURLToPath(resolveImport(`${schedulePackageName}/package.json`)));
3729
+ return resolve(packageRoot, "dist/definition.js");
2926
3730
  }
2927
3731
  const scheduleRuntimeEntry = resolveScheduleRuntimeEntry();
2928
3732
  const scheduleDefinitionEntry = resolveScheduleDefinitionEntry();
2929
- function staticScheduleDefinitions(definitions) {
2930
- return definitions.filter((definition) => definition.runtimeOnly !== true);
2931
- }
2932
3733
  async function publishRetainedProviderSources(artifacts, retainedSourcesDir, signal) {
2933
3734
  signal?.throwIfAborted();
2934
3735
  const generatedDir = artifacts.generatedDir;
@@ -2947,7 +3748,8 @@ async function publishRetainedProviderSources(artifacts, retainedSourcesDir, sig
2947
3748
  await cp(retainedSourcesDir, nextSourcesDir, { recursive: true });
2948
3749
  await rebasePublishedProviderSourceLinks(nextSourcesDir, retainedSourcesDir, publishedSourcesDir);
2949
3750
  const registryFile = resolve(nextDir, generatedRegistryFileName);
2950
- await writeFile(registryFile, rewriteRetainedProviderSourcePaths(await readFile(registryFile, "utf8"), retainedSourcesDir, publishedSourcesDir, {
3751
+ const registryContents = await readFile(registryFile, "utf8");
3752
+ await writeFile(registryFile, rewriteRetainedProviderSourcePaths(registryContents, retainedSourcesDir, publishedSourcesDir, {
2951
3753
  published: resolve(generatedDir, generatedRegistryFileName),
2952
3754
  retained: artifacts.registryFile
2953
3755
  }), "utf8");
@@ -3004,28 +3806,36 @@ const cronFieldPattern = /^[*,/\-0-9]+$/;
3004
3806
  function validateProviderCron(cron, scheduleName) {
3005
3807
  const fields = cron.trim().split(/\s+/);
3006
3808
  const hasVercelDayConflict = fields[2] !== "*" && fields[4] !== "*";
3007
- if (fields.length !== 5 || !fields.every((field) => cronFieldPattern.test(field)) || hasVercelDayConflict) throw new Error(`Schedule "${scheduleName}" uses cron "${cron}", but provider wake output only supports five-field UTC cron syntax compatible with Cloudflare, Vercel, and Netlify.`);
3809
+ if (fields.length !== 5 || !fields.every((field) => cronFieldPattern.test(field)) || hasVercelDayConflict) throw scheduleErrorDiagnostics.SCHEDULE_R0003({ message: `Schedule "${scheduleName}" uses cron "${cron}", but provider wake output only supports five-field UTC cron syntax compatible with Cloudflare, Vercel, and Netlify.` });
3008
3810
  }
3009
3811
  function readStaticScheduleCron(file, scheduleName) {
3010
- const definition = findDefaultExportCall(readFileSync(file, "utf8"), ["defineSchedule"]);
3011
- const cron = definition && readStaticString(readObjectProperty(definition.argument, "cron"));
3012
- if (!cron) throw new Error(`Schedule "${scheduleName}" must declare a static cron string for provider wake output.`);
3812
+ const definition = findDefaultExportCall(scanModule(readFileSync(file, "utf8"), file), ["defineSchedule"], { positionalOptionsIndex: 2 });
3813
+ const cron = definition && staticString(definition.call.arguments.length > 1 ? argumentExpression(definition.call.arguments[0]) : definition.options && findProperty(definition.options, "cron")?.value);
3814
+ if (!cron) throw scheduleErrorDiagnostics.SCHEDULE_R0004({ message: `Schedule "${scheduleName}" must declare a static cron string for provider wake output.` });
3013
3815
  return cron;
3014
3816
  }
3015
- function readStaticString(source) {
3016
- if (!source || !/^["'`]/.test(source)) return;
3017
- const quote = source[0];
3018
- let value = "";
3019
- for (let index = 1; index < source.length; index++) if (source[index] === "\\") value += source[++index] || "";
3020
- else if (source[index] === quote) return source.slice(index + 1).trim() ? void 0 : value;
3021
- else value += source[index];
3817
+ /**
3818
+ * Reads the `timeZone` option of a `defineSchedule()` call. Returns `undefined`
3819
+ * when the call does not declare it, the string when it is static, and `null`
3820
+ * when it is present but dynamic.
3821
+ */
3822
+ function readStaticScheduleTimeZone(file) {
3823
+ const definition = findDefaultExportCall(scanModule(readFileSync(file, "utf8"), file), ["defineSchedule"], { positionalOptionsIndex: 2 });
3824
+ const property = definition?.options && findProperty(definition.options, "timeZone");
3825
+ if (!property) return void 0;
3826
+ return property.value ? staticString(property.value) ?? null : null;
3827
+ }
3828
+ function assertProviderTimeZone(file, scheduleName) {
3829
+ const timeZone = readStaticScheduleTimeZone(file);
3830
+ if (timeZone === void 0 || timeZone === "UTC") return;
3831
+ throw scheduleErrorDiagnostics.SCHEDULE_R0003({ message: `Schedule "${scheduleName}" declares timeZone ${timeZone === null ? "with a value that is not a static string" : JSON.stringify(timeZone)}, but provider cron output supports only UTC. Remove timeZone and write the cron in UTC, or run Schedules with the process driver (\`runtime: { driver: "process" }\`).` });
3022
3832
  }
3023
3833
  function renderProviderEntry(file, registryFile, provider, scheduleName, workflow) {
3024
3834
  const runtimeImport = createImportPath(file, scheduleRuntimeEntry);
3025
3835
  const workflowRuntime = provider === "vercel" ? workflow : void 0;
3026
3836
  return [
3027
3837
  `import scheduleRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
3028
- `import { executeStaticSchedule } from ${JSON.stringify(runtimeImport)}`,
3838
+ `import { executeStaticSchedule, ${provider === "vercel" ? "isScheduleCronAuthorized, " : ""}missingScheduleDefinitionError, normalizeCron, unwrapScheduleDefinition } from ${JSON.stringify(runtimeImport)}`,
3029
3839
  ...workflowRuntime ? [
3030
3840
  `import workflowRegistry from ${JSON.stringify(createImportPath(file, workflowRuntime.registryFile))}`,
3031
3841
  `import { setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry } from ${JSON.stringify(`${workflowRuntime.importBase}/runtime/state`)}`,
@@ -3042,13 +3852,13 @@ function renderProviderEntry(file, registryFile, provider, scheduleName, workflo
3042
3852
  " const loader = scheduleRegistry[name]",
3043
3853
  " if (!loader) return undefined",
3044
3854
  " const loaded = await loader()",
3045
- " return loaded?.default ?? loaded",
3855
+ " return unwrapScheduleDefinition(loaded)",
3046
3856
  "}",
3047
3857
  "",
3048
3858
  "async function runSchedule(name, cron, scheduledAt) {",
3049
3859
  " const definition = await loadScheduleDefinition(name)",
3050
3860
  " if (!definition) {",
3051
- " throw new Error(`Missing schedule definition: ${name}`)",
3861
+ " throw missingScheduleDefinitionError(name)",
3052
3862
  " }",
3053
3863
  " return await executeStaticSchedule({ cron, definition, name, scheduledAt })",
3054
3864
  "}",
@@ -3059,9 +3869,10 @@ function renderProviderEntry(file, registryFile, provider, scheduleName, workflo
3059
3869
  " return new Response('ViteHub schedule provider wake endpoint')",
3060
3870
  " },",
3061
3871
  " async scheduled(event, env, ctx) {",
3872
+ " if (typeof event.cron !== 'string' || !event.cron.trim()) return",
3062
3873
  " const tasks = Object.entries(scheduleRegistry).map(async ([name]) => {",
3063
3874
  " const definition = await loadScheduleDefinition(name)",
3064
- " if (!definition || definition.cron !== event.cron) return",
3875
+ " if (!definition || normalizeCron(definition.cron) !== normalizeCron(event.cron)) return",
3065
3876
  " await executeStaticSchedule({ cron: event.cron, definition, name, scheduledAt: new Date(event.scheduledTime), waitUntil: (promise) => ctx.waitUntil(promise) })",
3066
3877
  " })",
3067
3878
  " await Promise.all(tasks)",
@@ -3071,7 +3882,7 @@ function renderProviderEntry(file, registryFile, provider, scheduleName, workflo
3071
3882
  "export default async function scheduleHandler(req, res) {",
3072
3883
  " const cronSecret = process.env.CRON_SECRET",
3073
3884
  " const authorization = req.headers?.authorization || req.headers?.Authorization",
3074
- " if (cronSecret && authorization !== `Bearer ${cronSecret}`) {",
3885
+ " if (cronSecret && !isScheduleCronAuthorized(authorization, cronSecret)) {",
3075
3886
  " res.statusCode = 401",
3076
3887
  " res.end('Unauthorized.')",
3077
3888
  " return",
@@ -3098,13 +3909,13 @@ function renderNetlifyScheduleFunction(file, registryFile, scheduleName, cron, i
3098
3909
  const runtimeImport = createImportPath(file, scheduleRuntimeEntry);
3099
3910
  return [
3100
3911
  `import scheduleRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
3101
- `import { executeStaticSchedule } from ${JSON.stringify(runtimeImport)}`,
3912
+ `import { executeStaticSchedule, unwrapScheduleDefinition } from ${JSON.stringify(runtimeImport)}`,
3102
3913
  "",
3103
3914
  `const scheduleName = ${JSON.stringify(scheduleName)}`,
3104
3915
  "",
3105
3916
  "export default async function netlifyScheduleHandler(request) {",
3106
3917
  " const loaded = await scheduleRegistry[scheduleName]?.()",
3107
- " const definition = loaded?.default ?? loaded",
3918
+ " const definition = unwrapScheduleDefinition(loaded)",
3108
3919
  " if (!definition) return new Response('Missing schedule definition.', { status: 404 })",
3109
3920
  ` await executeStaticSchedule({ cron: ${JSON.stringify(cron)}, definition, name: scheduleName, scheduledAt: new Date() })`,
3110
3921
  " return new Response(null, { status: 204 })",
@@ -3133,7 +3944,7 @@ function renderDenoCronEntry(file, registryFile, crons, runtimeImport = schedule
3133
3944
  });
3134
3945
  return [
3135
3946
  `import scheduleRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
3136
- `import { executeStaticSchedule } from ${JSON.stringify(runtimeImport)}`,
3947
+ `import { executeStaticSchedule, missingScheduleDefinitionError, unwrapScheduleDefinition } from ${JSON.stringify(runtimeImport)}`,
3137
3948
  "",
3138
3949
  `const scheduleCrons = ${JSON.stringify(scheduleCrons, null, 2)}`,
3139
3950
  "",
@@ -3141,14 +3952,14 @@ function renderDenoCronEntry(file, registryFile, crons, runtimeImport = schedule
3141
3952
  " const loader = scheduleRegistry[name]",
3142
3953
  " if (!loader) return undefined",
3143
3954
  " const loaded = await loader()",
3144
- " return loaded?.default ?? loaded",
3955
+ " return unwrapScheduleDefinition(loaded)",
3145
3956
  "}",
3146
3957
  "",
3147
3958
  "for (const { cron, cronName, name } of scheduleCrons) {",
3148
3959
  " Deno.cron(cronName, cron, async () => {",
3149
3960
  " const definition = await loadScheduleDefinition(name)",
3150
3961
  " if (!definition) {",
3151
- " throw new Error(`Missing schedule definition: ${name}`)",
3962
+ " throw missingScheduleDefinitionError(name)",
3152
3963
  " }",
3153
3964
  " await executeStaticSchedule({ cron, definition, name, scheduledAt: new Date() })",
3154
3965
  " })",
@@ -3169,7 +3980,7 @@ function createScheduleDefinitionAliasPlugin() {
3169
3980
  async function writeProviderEntries(rootDir, source, providedDefinitions) {
3170
3981
  const generatedDir = ensureGeneratedDir(rootDir, productName);
3171
3982
  const registryFile = resolve(generatedDir, generatedRegistryFileName);
3172
- const definitions = (providedDefinitions ?? discoverScheduleDefinitions({ rootDir })).filter((definition) => !source || definition.source === source).filter((definition) => definition.runtimeOnly !== true);
3983
+ const definitions = (providedDefinitions ?? discoverScheduleDefinitions({ rootDir })).filter((definition) => !source || definition.source === source);
3173
3984
  await writeRuntimeRegistryFile(registryFile, definitions);
3174
3985
  const cloudflareWorkerFile = resolve(generatedDir, "cloudflare-worker.mjs");
3175
3986
  const denoCronFile = resolve(generatedDir, denoCronFileName);
@@ -3188,11 +3999,12 @@ async function writeProviderEntries(rootDir, source, providedDefinitions) {
3188
3999
  async function readDefinitionCrons(definitions) {
3189
4000
  const crons = await readRuntimeDefinitionCrons(definitions);
3190
4001
  for (const [name, cron] of crons) validateProviderCron(cron, name);
4002
+ for (const definition of definitions) assertProviderTimeZone(definition.handler, definition.name);
3191
4003
  return crons;
3192
4004
  }
3193
4005
  async function readRuntimeDefinitionCrons(definitions) {
3194
4006
  const crons = /* @__PURE__ */ new Map();
3195
- for (const definition of staticScheduleDefinitions(definitions)) {
4007
+ for (const definition of definitions) {
3196
4008
  const cron = readStaticScheduleCron(definition.handler, definition.name);
3197
4009
  crons.set(definition.name, cron);
3198
4010
  }
@@ -3200,7 +4012,7 @@ async function readRuntimeDefinitionCrons(definitions) {
3200
4012
  }
3201
4013
  async function writeVercelScheduleFunctions(options, crons) {
3202
4014
  options.signal?.throwIfAborted();
3203
- const definitions = staticScheduleDefinitions(options.definitions);
4015
+ const definitions = options.definitions;
3204
4016
  const outputRoot = options.outputRoot;
3205
4017
  const functionRoot = resolve(outputRoot, "functions", "api", "vitehub", "schedules", "vercel");
3206
4018
  const stagedFunctionRoot = `${functionRoot}.pending`;
@@ -3215,7 +4027,7 @@ async function writeVercelScheduleFunctions(options, crons) {
3215
4027
  for (const definition of definitions) {
3216
4028
  const safeName = definition.name.replace(/[^a-z0-9/_-]+/gi, "_").split("/").filter(Boolean).join("/");
3217
4029
  const existingName = emittedFunctionNames.get(safeName);
3218
- if (existingName) throw new Error(`Schedule "${definition.name}" and "${existingName}" both emit the same Vercel function path: ${safeName}`);
4030
+ if (existingName) throw scheduleErrorDiagnostics.SCHEDULE_R0005({ message: `Schedule "${definition.name}" and "${existingName}" both emit the same Vercel function path: ${safeName}` });
3219
4031
  emittedFunctionNames.set(safeName, definition.name);
3220
4032
  const segments = safeName.split("/");
3221
4033
  const functionDir = resolve(stagedFunctionRoot, ...segments.slice(0, -1), `${segments.at(-1)}.func`);
@@ -3226,6 +4038,7 @@ async function writeVercelScheduleFunctions(options, crons) {
3226
4038
  await writeFile(wrapperFile, renderProviderEntry(wrapperFile, options.registryFile, "vercel", definition.name, options.workflow), "utf8");
3227
4039
  await bundleEsmEntry(wrapperFile, functionFile, {
3228
4040
  alias: options.bundleAlias,
4041
+ define: options.bundleDefines,
3229
4042
  external: options.bundleExternal,
3230
4043
  format: "esm",
3231
4044
  platform: "node",
@@ -3291,9 +4104,11 @@ async function writeVercelScheduleFunctions(options, crons) {
3291
4104
  vercelConfig = createVercelConfigJson();
3292
4105
  }
3293
4106
  const schedulePathPrefix = "/api/vitehub/schedules/vercel/";
3294
- const previousCrons = vercelConfig.crons ?? [];
4107
+ const rawPreviousCrons = vercelConfig.crons;
4108
+ const previousCrons = Array.isArray(rawPreviousCrons) ? rawPreviousCrons.filter(isVercelCron) : [];
4109
+ const hasMalformedCrons = rawPreviousCrons !== void 0 && (!Array.isArray(rawPreviousCrons) || previousCrons.length !== rawPreviousCrons.length);
3295
4110
  const existingCrons = previousCrons.filter((cron) => !cron.path.startsWith(schedulePathPrefix));
3296
- if (!definitions.length && existingCrons.length === previousCrons.length) {
4111
+ if (!definitions.length && !hasMalformedCrons && existingCrons.length === previousCrons.length) {
3297
4112
  await removeEmptyDirectories(functionRoot, options.rootDir);
3298
4113
  options.signal?.throwIfAborted();
3299
4114
  if (previousCrons.length === 0) {
@@ -3355,13 +4170,13 @@ async function writeVercelScheduleFunctions(options, crons) {
3355
4170
  }
3356
4171
  }
3357
4172
  async function createNetlifyScheduleFunctionOutputs(options) {
3358
- const definitions = staticScheduleDefinitions(options.definitions);
4173
+ const definitions = options.definitions;
3359
4174
  const crons = await readDefinitionCrons(definitions);
3360
4175
  const emitted = /* @__PURE__ */ new Map();
3361
4176
  return definitions.map((definition) => {
3362
4177
  const fileName = sanitizeNetlifyScheduleFunctionName(definition.name);
3363
4178
  const existingName = emitted.get(fileName);
3364
- if (existingName) throw new Error(`Schedule "${definition.name}" and "${existingName}" both emit the same Netlify function file: ${fileName}`);
4179
+ if (existingName) throw scheduleErrorDiagnostics.SCHEDULE_R0006({ message: `Schedule "${definition.name}" and "${existingName}" both emit the same Netlify function file: ${fileName}` });
3365
4180
  emitted.set(fileName, definition.name);
3366
4181
  const file = resolve(options.functionRoot, fileName);
3367
4182
  return {
@@ -3378,69 +4193,117 @@ async function writeNetlifyScheduleFunctions(options) {
3378
4193
  const publishedSourcesDir = resolve(dirname(options.registryFile), "sources");
3379
4194
  const netlifySourcesDir = resolve(options.outputRoot, "schedule", "sources");
3380
4195
  const includedSourcesDir = relative(functionRoot, netlifySourcesDir).replace(/\\/g, "/");
3381
- const stagedFunctionRoot = `${functionRoot}.pending`;
3382
- const backupFunctionRoot = `${functionRoot}.previous`;
3383
- await rm(stagedFunctionRoot, {
3384
- force: true,
3385
- recursive: true
3386
- });
3387
- await cp(functionRoot, stagedFunctionRoot, {
3388
- force: true,
3389
- recursive: true
3390
- }).catch((error) => {
3391
- if (error.code !== "ENOENT") throw error;
3392
- });
3393
- const existingFiles = await readdir(stagedFunctionRoot).catch((error) => error.code === "ENOENT" ? [] : Promise.reject(error));
3394
- await Promise.all(existingFiles.filter((file) => /^vitehub-schedule-.+\.mjs$/.test(file)).map((file) => rm(resolve(stagedFunctionRoot, file), {
3395
- force: true,
3396
- recursive: true
3397
- })));
3398
- const outputs = await createNetlifyScheduleFunctionOutputs({
3399
- definitions: options.definitions,
3400
- functionRoot: stagedFunctionRoot,
3401
- includedSourcesDir: existsSync(publishedSourcesDir) ? includedSourcesDir : void 0,
3402
- registryFile: options.registryFile
3403
- });
3404
- options.signal?.throwIfAborted();
3405
- if (outputs.length === 0) await mkdir(stagedFunctionRoot, { recursive: true });
3406
- else {
3407
- await mkdir(stagedFunctionRoot, { recursive: true });
4196
+ const stagedOutputRoot = `${options.outputRoot}.pending`;
4197
+ const backupOutputRoot = `${options.outputRoot}.previous`;
4198
+ const stagedFunctionRoot = resolve(stagedOutputRoot, "functions");
4199
+ const stagedSourcesDir = resolve(stagedOutputRoot, "schedule", "sources");
4200
+ let preserveRecovery = false;
4201
+ try {
4202
+ await rm(stagedOutputRoot, {
4203
+ force: true,
4204
+ recursive: true
4205
+ });
4206
+ await cp(options.outputRoot, stagedOutputRoot, {
4207
+ force: true,
4208
+ recursive: true,
4209
+ verbatimSymlinks: true
4210
+ }).catch((error) => {
4211
+ if (error.code !== "ENOENT") throw error;
4212
+ });
4213
+ await rm(stagedSourcesDir, {
4214
+ force: true,
4215
+ recursive: true
4216
+ });
4217
+ const existingFiles = await readdir(stagedFunctionRoot).catch((error) => error.code === "ENOENT" ? [] : Promise.reject(error));
4218
+ await Promise.all(existingFiles.filter((file) => /^vitehub-schedule-.+\.mjs$/.test(file)).map((file) => rm(resolve(stagedFunctionRoot, file), {
4219
+ force: true,
4220
+ recursive: true
4221
+ })));
4222
+ const outputs = await createNetlifyScheduleFunctionOutputs({
4223
+ definitions: options.definitions,
4224
+ functionRoot: stagedFunctionRoot,
4225
+ includedSourcesDir: existsSync(publishedSourcesDir) ? includedSourcesDir : void 0,
4226
+ registryFile: options.registryFile
4227
+ });
3408
4228
  options.signal?.throwIfAborted();
3409
- await Promise.all(outputs.map(async (output) => writeFile(output.file, output.source, {
3410
- encoding: "utf8",
4229
+ if (outputs.length === 0) await mkdir(stagedFunctionRoot, { recursive: true });
4230
+ else {
4231
+ await mkdir(stagedFunctionRoot, { recursive: true });
4232
+ options.signal?.throwIfAborted();
4233
+ const failure = (await Promise.allSettled(outputs.map(async (output) => {
4234
+ const wrapperFile = `${output.file}.source.mjs`;
4235
+ await writeFile(wrapperFile, output.source, {
4236
+ encoding: "utf8",
4237
+ signal: options.signal
4238
+ });
4239
+ try {
4240
+ await bundleEsmEntry(wrapperFile, output.file, {
4241
+ alias: options.bundleAlias,
4242
+ define: options.bundleDefines,
4243
+ external: options.bundleExternal,
4244
+ format: "esm",
4245
+ platform: "node",
4246
+ plugins: [createScheduleDefinitionAliasPlugin()],
4247
+ rootDir: options.sourceRootDir ?? options.rootDir,
4248
+ signal: options.signal,
4249
+ workingDir: options.sourceRootDir ?? options.rootDir
4250
+ });
4251
+ } finally {
4252
+ await rm(wrapperFile, { force: true });
4253
+ }
4254
+ }))).find((result) => result.status === "rejected");
4255
+ if (failure) throw failure.reason;
4256
+ }
4257
+ await publishProviderSourcesToDeploymentOutputs({
4258
+ destinations: [{
4259
+ files: outputs.map((output) => output.file),
4260
+ runtimeSourcesDir: relative(options.rootDir, netlifySourcesDir).replace(/\\/g, "/"),
4261
+ sourcesDir: stagedSourcesDir
4262
+ }],
4263
+ publishedSourcesDir,
3411
4264
  signal: options.signal
3412
- })));
3413
- }
3414
- await publishProviderSourcesToDeploymentOutputs({
3415
- destinations: [{
3416
- files: outputs.map((output) => output.file),
3417
- runtimeSourcesDir: relative(options.rootDir, netlifySourcesDir).replace(/\\/g, "/"),
3418
- sourcesDir: netlifySourcesDir
3419
- }],
3420
- publishedSourcesDir,
3421
- signal: options.signal
3422
- });
3423
- options.signal?.throwIfAborted();
3424
- rmSync(backupFunctionRoot, {
3425
- force: true,
3426
- recursive: true
3427
- });
3428
- try {
3429
- renameSync(functionRoot, backupFunctionRoot);
3430
- } catch (error) {
3431
- if (error.code !== "ENOENT") throw error;
3432
- }
3433
- try {
3434
- renameSync(stagedFunctionRoot, functionRoot);
3435
- rmSync(backupFunctionRoot, {
4265
+ });
4266
+ if (existsSync(stagedSourcesDir)) await rebasePublishedProviderSourceLinks(stagedSourcesDir, stagedSourcesDir, netlifySourcesDir);
4267
+ options.signal?.throwIfAborted();
4268
+ rmSync(backupOutputRoot, {
3436
4269
  force: true,
3437
4270
  recursive: true
3438
4271
  });
3439
- } catch (error) {
3440
- if (existsSync(backupFunctionRoot)) renameSync(backupFunctionRoot, functionRoot);
3441
- throw error;
4272
+ let movedPrevious = false;
4273
+ try {
4274
+ if (existsSync(options.outputRoot)) {
4275
+ renameSync(options.outputRoot, backupOutputRoot);
4276
+ movedPrevious = true;
4277
+ }
4278
+ renameSync(stagedOutputRoot, options.outputRoot);
4279
+ } catch (error) {
4280
+ if (movedPrevious) try {
4281
+ renameSync(backupOutputRoot, options.outputRoot);
4282
+ } catch (restoreError) {
4283
+ try {
4284
+ await rename(backupOutputRoot, options.outputRoot);
4285
+ } catch (retryError) {
4286
+ preserveRecovery = true;
4287
+ throw new AggregateError([
4288
+ error,
4289
+ restoreError,
4290
+ retryError
4291
+ ], `Netlify Schedule rollback failed; previous output retained at ${backupOutputRoot}`);
4292
+ }
4293
+ }
4294
+ throw error;
4295
+ }
4296
+ await rm(backupOutputRoot, {
4297
+ force: true,
4298
+ recursive: true
4299
+ }).catch(() => void 0);
4300
+ if (outputs.length === 0) await removeEmptyDirectories(functionRoot, options.rootDir).catch(() => void 0);
4301
+ } finally {
4302
+ if (!preserveRecovery) await rm(stagedOutputRoot, {
4303
+ force: true,
4304
+ recursive: true
4305
+ }).catch(() => void 0);
3442
4306
  }
3443
- if (outputs.length === 0) await removeEmptyDirectories(functionRoot, options.rootDir);
3444
4307
  }
3445
4308
  async function writeCloudflareScheduleOutput(options) {
3446
4309
  options.signal?.throwIfAborted();
@@ -3453,10 +4316,10 @@ async function writeCloudflareScheduleOutput(options) {
3453
4316
  } catch (error) {
3454
4317
  if (error.code !== "ENOENT") throw error;
3455
4318
  }
3456
- const existingTriggers = typeof wranglerConfig.triggers === "object" && wranglerConfig.triggers !== null ? wranglerConfig.triggers : {};
4319
+ const existingTriggers = isRecord$1(wranglerConfig.triggers) ? wranglerConfig.triggers : {};
3457
4320
  const previousState = await readCloudflareOutputState(options.previousStateFile ?? options.stateFile);
3458
4321
  options.signal?.throwIfAborted();
3459
- const externalCrons = (existingTriggers.crons ?? []).filter((cron) => !previousState?.crons.includes(cron));
4322
+ const externalCrons = readStringArray(existingTriggers.crons).filter((cron) => !previousState?.crons.includes(cron));
3460
4323
  const ownedCrons = options.crons.filter((cron) => !externalCrons.includes(cron));
3461
4324
  const main = typeof wranglerConfig.main === "string" && wranglerConfig.main ? wranglerConfig.main : "index.js";
3462
4325
  wranglerConfig = {
@@ -3467,12 +4330,13 @@ async function writeCloudflareScheduleOutput(options) {
3467
4330
  observability: wranglerConfig.observability ?? { enabled: true },
3468
4331
  triggers: {
3469
4332
  ...existingTriggers,
3470
- crons: [...new Set([...externalCrons, ...options.crons])]
4333
+ crons: [.../* @__PURE__ */ new Set([...externalCrons, ...options.crons])]
3471
4334
  }
3472
4335
  };
3473
4336
  await Promise.all([
3474
4337
  bundleEsmEntry(options.bundleEntry, resolve(outputRoot, main), {
3475
4338
  alias: options.bundleAlias,
4339
+ define: options.bundleDefines,
3476
4340
  banner: `// ${cloudflareScheduleWorkerMarker}`,
3477
4341
  conditions: [
3478
4342
  "workerd",
@@ -3566,6 +4430,7 @@ async function cleanCloudflareScheduleOutput(rootDir, stateFile, previousStateFi
3566
4430
  ]);
3567
4431
  }
3568
4432
  async function generateProviderOutputsWithinLock(options) {
4433
+ recoverNetlifyDeploymentOutput(options.rootDir);
3569
4434
  options.signal?.throwIfAborted();
3570
4435
  const generatedDir = resolve(options.rootDir, ".vitehub", productName);
3571
4436
  const previousGeneratedDir = `${generatedDir}.${randomUUID()}.previous`;
@@ -3589,6 +4454,7 @@ async function generateProviderOutputsWithinLock(options) {
3589
4454
  await writeFile(stagedDenoCronInputFile, renderDenoCronEntry(artifacts.denoCronFile, artifacts.registryFile, crons, options.runtimeImport), "utf8");
3590
4455
  await bundleEsmEntry(stagedDenoCronInputFile, stagedDenoCronFile, {
3591
4456
  alias: options.bundleAlias,
4457
+ define: options.bundleDefines,
3592
4458
  external: [
3593
4459
  ...builtinModules,
3594
4460
  ...builtinModules.map((name) => `node:${name}`),
@@ -3608,6 +4474,7 @@ async function generateProviderOutputsWithinLock(options) {
3608
4474
  options.signal?.throwIfAborted();
3609
4475
  await writeCloudflareScheduleOutput({
3610
4476
  bundleAlias: options.bundleAlias,
4477
+ bundleDefines: options.bundleDefines,
3611
4478
  bundleEntry: artifacts.cloudflareWorkerFile,
3612
4479
  crons: [...new Set(crons.values())],
3613
4480
  rootDir: options.rootDir,
@@ -3629,6 +4496,7 @@ async function generateProviderOutputsWithinLock(options) {
3629
4496
  options.signal?.throwIfAborted();
3630
4497
  await writeVercelScheduleFunctions({
3631
4498
  bundleAlias: options.bundleAlias,
4499
+ bundleDefines: options.bundleDefines,
3632
4500
  bundleExternal: options.bundleExternal,
3633
4501
  definitions: artifacts.definitions,
3634
4502
  outputRoot: createDefaultVercelOutputRoot(options.rootDir),
@@ -3640,6 +4508,10 @@ async function generateProviderOutputsWithinLock(options) {
3640
4508
  }, crons);
3641
4509
  options.signal?.throwIfAborted();
3642
4510
  await writeNetlifyScheduleFunctions({
4511
+ bundleAlias: options.bundleAlias,
4512
+ bundleDefines: options.bundleDefines,
4513
+ bundleExternal: options.bundleExternal,
4514
+ sourceRootDir: options.sourceRootDir,
3643
4515
  definitions: artifacts.definitions,
3644
4516
  outputRoot: createDefaultNetlifyOutputRoot(options.rootDir),
3645
4517
  registryFile: artifacts.registryFile,
@@ -3661,19 +4533,143 @@ async function generateProviderOutputsWithinLock(options) {
3661
4533
  }
3662
4534
  }
3663
4535
  //#endregion
3664
- //#region src/targets-module.ts
3665
- const SCHEDULE_TARGETS_ID = "#vitehub/schedule/targets";
3666
- function getScheduleTargetNames(definitions) {
3667
- return definitions.filter((definition) => definition.allowRuntimeSchedules).map((definition) => definition.name).sort();
3668
- }
3669
- function createScheduleTargetsContents(definitions, options = {}) {
3670
- const targets = getScheduleTargetNames(definitions);
3671
- const union = targets.length ? targets.map((target) => JSON.stringify(target)).join(" | ") : "never";
4536
+ //#region src/inspect.ts
4537
+ function inspectTimeZone(file) {
4538
+ const timeZone = readStaticScheduleTimeZone(file);
4539
+ return timeZone === null ? "Not a static string" : timeZone ?? "UTC";
4540
+ }
4541
+ function summarizeScheduleDefinition(projectRoot, definition, crons) {
4542
+ const cron = crons.get(definition.name);
4543
+ const fields = [{
4544
+ label: "Kind",
4545
+ value: "Static schedule"
4546
+ }];
4547
+ if (cron) fields.push({
4548
+ label: "Cron",
4549
+ value: cron
4550
+ }, {
4551
+ label: "Time zone",
4552
+ value: inspectTimeZone(definition.handler)
4553
+ });
4554
+ if (definition.manual) fields.push({
4555
+ label: "Manual",
4556
+ value: "Enabled"
4557
+ });
4558
+ if (definition.contributor) fields.push({
4559
+ label: "Contributed by",
4560
+ value: definition.contributor
4561
+ });
4562
+ if (definition.reason) fields.push({
4563
+ label: "Reason",
4564
+ value: definition.reason
4565
+ });
4566
+ return {
4567
+ fields,
4568
+ file: relativeDefinitionFile(projectRoot, definition.handler),
4569
+ name: definition.name,
4570
+ source: definition.source || "schedule"
4571
+ };
4572
+ }
4573
+ /**
4574
+ * Lists Schedule Definitions with their static cron when the Definition declares one. Contributed Definitions name the
4575
+ * plugin that added them and its reason.
4576
+ */
4577
+ async function inspectScheduleDefinitions(options) {
4578
+ const definitions = discoverScheduleDefinitions({
4579
+ contributions: await collectScheduleContributions(options.plugins, {
4580
+ projectRoot: options.projectRoot,
4581
+ root: options.rootDir,
4582
+ serverDirs: options.serverDirs
4583
+ }),
4584
+ rootDir: options.rootDir,
4585
+ serverDirs: options.serverDirs,
4586
+ serverRootDir: options.serverRootDir
4587
+ });
4588
+ const crons = /* @__PURE__ */ new Map();
4589
+ for (const definition of definitions) try {
4590
+ for (const [name, cron] of await readRuntimeDefinitionCrons([definition])) crons.set(name, cron);
4591
+ } catch {}
4592
+ return definitions.map((definition) => summarizeScheduleDefinition(options.projectRoot, definition, crons));
4593
+ }
4594
+ function definitionRecord(summary) {
4595
+ const field = (label) => summary.fields.find((entry) => entry.label === label)?.value;
4596
+ const cron = field("Cron");
4597
+ const timeZone = field("Time zone");
4598
+ return {
4599
+ cells: {
4600
+ manual: field("Manual") === "Enabled" ? "Yes" : "No",
4601
+ schedule: summary.name,
4602
+ timing: !cron ? "-" : timeZone === "UTC" ? cron : `${cron} (${timeZone})`
4603
+ },
4604
+ fields: [
4605
+ ...summary.fields,
4606
+ {
4607
+ label: "File",
4608
+ value: summary.file
4609
+ },
4610
+ {
4611
+ label: "Source",
4612
+ value: summary.source
4613
+ },
4614
+ {
4615
+ label: "Runs",
4616
+ value: `Use \`vitehub schedule runs ${summary.name}\` to list runs that this runtime recorded.`
4617
+ }
4618
+ ],
4619
+ id: `definition:${summary.name}`,
4620
+ runnable: field("Manual") === "Enabled"
4621
+ };
4622
+ }
4623
+ /** Lists Schedule Definitions as Console records. The ids use the `definition:` prefix. */
4624
+ async function inspectScheduleConsoleRecords(options) {
4625
+ return (await inspectScheduleDefinitions(options)).map(definitionRecord);
4626
+ }
4627
+ /**
4628
+ * Console section for Schedules. Records list discovered Schedule Definitions. `vitehub inspect definitions` reads the
4629
+ * same Definitions, and `vitehub schedule runs <name>` lists the runs that a runtime recorded.
4630
+ */
4631
+ const scheduleConsoleSection = {
4632
+ description: "Inspect Schedule Definitions.",
4633
+ icon: "i-lucide-calendar-clock",
4634
+ id: "schedules",
4635
+ label: "Schedules",
4636
+ read: inspectScheduleConsoleRecords,
4637
+ view: {
4638
+ columns: [
4639
+ {
4640
+ key: "schedule",
4641
+ label: "Schedule"
4642
+ },
4643
+ {
4644
+ key: "timing",
4645
+ label: "Cron"
4646
+ },
4647
+ {
4648
+ key: "manual",
4649
+ label: "Manual"
4650
+ }
4651
+ ],
4652
+ kind: "record-table",
4653
+ notice: "The host runs each Schedule on its UTC cron. Definitions with `manual: true` can also run from the Console or `vitehub schedule run`."
4654
+ }
4655
+ };
4656
+ //#endregion
4657
+ //#region src/internal/registry-module.ts
4658
+ /**
4659
+ * Renders the `#vitehub/schedule/registry` virtual module. A virtual module has no directory, so a relative import would
4660
+ * resolve against the Vite root, which is the app directory under Nuxt. Each definition is imported by its absolute
4661
+ * path with forward slashes: Vite and the bundler resolve `C:/repo/...`, but Node rejects `C:\repo\...` as a URL scheme.
4662
+ */
4663
+ function renderScheduleRegistryModule(definitions) {
3672
4664
  return [
3673
- `export const scheduleTargetNames = ${JSON.stringify(targets)};`,
3674
- options.types ? `export type ScheduleTargetName = ${union};` : "",
4665
+ "",
4666
+ "const registry = {",
4667
+ ...definitions.map((definition) => ` [${JSON.stringify(definition.name)}]: async () => import(${JSON.stringify(definition.handler.replace(/\\/g, "/"))}),`),
4668
+ "}",
4669
+ "",
4670
+ "export default registry",
3675
4671
  ""
3676
- ].filter((line) => line !== "").join("\n");
4672
+ ].join("\n");
3677
4673
  }
3678
4674
  //#endregion
3679
4675
  //#region src/vite.ts
@@ -3683,14 +4679,21 @@ async function readScheduleDefinitionCrons(definitions) {
3683
4679
  const SCHEDULE_VITE_PLUGIN_NAME = "@vite-hub/schedule/vite";
3684
4680
  const SCHEDULE_REGISTRY_ID = "#vitehub/schedule/registry";
3685
4681
  const RESOLVED_SCHEDULE_REGISTRY_ID = "\0#vitehub/schedule/registry";
3686
- const RESOLVED_SCHEDULE_TARGETS_ID = `\0${SCHEDULE_TARGETS_ID}`;
3687
- const registryImportAnchor = ".vitehub/schedule/registry.js";
3688
4682
  const generatedNitroSchedulePlugin = ".vitehub/nitro/schedule/plugin.ts";
3689
4683
  const generatedNitroProviderRegistry = ".vitehub/nitro/schedule/provider-registry.js";
3690
- const generatedNitroRuntimeRegistry = ".vitehub/nitro/schedule/runtime-registry.js";
3691
4684
  const generatedNitroStaticRegistry = ".vitehub/nitro/schedule/static-registry.js";
3692
4685
  const generatedNitroCloudflareModule = "./.vitehub/nitro/schedule/module.mjs";
3693
4686
  const mergeNoExternal = createNoExternalMerger(schedulePackageName);
4687
+ function invalidateScheduleRegistry(server) {
4688
+ const registry = server.moduleGraph.getModuleById(RESOLVED_SCHEDULE_REGISTRY_ID);
4689
+ if (registry) server.moduleGraph.invalidateModule(registry);
4690
+ for (const environment of Object.values(server.environments ?? {})) {
4691
+ const module = environment.moduleGraph.getModuleById(RESOLVED_SCHEDULE_REGISTRY_ID);
4692
+ if (!module) continue;
4693
+ environment.moduleGraph.invalidateModule(module);
4694
+ if (environment.config.consumer === "server") environment.hot.send({ type: "full-reload" });
4695
+ }
4696
+ }
3694
4697
  function resolveSchedulePluginRoots(root, options = {}) {
3695
4698
  const resolvedViteRoot = resolve(root);
3696
4699
  return {
@@ -3703,11 +4706,13 @@ function isRecord(value) {
3703
4706
  }
3704
4707
  function resolveProcessRuntimeOptions(value) {
3705
4708
  if (value === void 0) return;
3706
- if (!isRecord(value) || value.driver !== "process") throw new TypeError("Schedule Process Runtime driver must be \"process\".");
3707
- if (value.prefix !== void 0 && typeof value.prefix !== "string") throw new TypeError("Schedule Process Runtime prefix must be a string.");
3708
- if (value.intervalMs !== void 0 && (typeof value.intervalMs !== "number" || !Number.isFinite(value.intervalMs) || value.intervalMs <= 0 || value.intervalMs > 6e4)) throw new TypeError("Schedule Process Runtime intervalMs must be a positive number no greater than 60000.");
3709
- if (value.concurrency !== void 0 && (typeof value.concurrency !== "number" || !Number.isInteger(value.concurrency) || value.concurrency < 1)) throw new TypeError("Schedule Process Runtime concurrency must be a positive integer.");
4709
+ if (!isRecord(value) || value.driver !== "process") throw scheduleErrorDiagnostics.SCHEDULE_B0001({ message: "Schedule Process Runtime driver must be \"process\"." });
4710
+ if (value.prefix !== void 0 && typeof value.prefix !== "string") throw scheduleErrorDiagnostics.SCHEDULE_B0002({ message: "Schedule Process Runtime prefix must be a string." });
4711
+ if (value.catchUpMs !== void 0 && (typeof value.catchUpMs !== "number" || !Number.isFinite(value.catchUpMs) || value.catchUpMs < 0)) throw scheduleErrorDiagnostics.SCHEDULE_B0005({ message: "Schedule Process Runtime catchUpMs must be a non-negative number." });
4712
+ if (value.intervalMs !== void 0 && (typeof value.intervalMs !== "number" || !Number.isFinite(value.intervalMs) || value.intervalMs <= 0 || value.intervalMs > 6e4)) throw scheduleErrorDiagnostics.SCHEDULE_B0003({ message: "Schedule Process Runtime intervalMs must be a positive number no greater than 60000." });
4713
+ if (value.concurrency !== void 0 && (typeof value.concurrency !== "number" || !Number.isInteger(value.concurrency) || value.concurrency < 1)) throw scheduleErrorDiagnostics.SCHEDULE_B0004({ message: "Schedule Process Runtime concurrency must be a positive integer." });
3710
4714
  return {
4715
+ ...value.catchUpMs !== void 0 ? { catchUpMs: value.catchUpMs } : {},
3711
4716
  ...value.concurrency !== void 0 ? { concurrency: value.concurrency } : {},
3712
4717
  driver: "process",
3713
4718
  ...value.intervalMs !== void 0 ? { intervalMs: value.intervalMs } : {},
@@ -3745,19 +4750,22 @@ function isGeneratedNitroRegistration(value, generatedPath) {
3745
4750
  }
3746
4751
  function mergeNitroScheduleConfig(value, options) {
3747
4752
  const nitro = cloneNitroConfig(value);
3748
- nitro.plugins = [...Array.isArray(nitro.plugins) ? nitro.plugins.filter((plugin) => !isGeneratedNitroRegistration(plugin, generatedNitroSchedulePlugin)) : [], options.plugin];
3749
- if (!options.providerWake) return nitro;
3750
- nitro.modules = [...Array.isArray(nitro.modules) ? nitro.modules.filter((module) => !isGeneratedNitroRegistration(module, generatedNitroCloudflareModule)) : [], options.module];
3751
- nitro.cloudflare ||= {};
3752
- nitro.cloudflare.wrangler ||= {};
3753
- const wrangler = nitro.cloudflare.wrangler;
4753
+ nitro.plugins = Array.isArray(nitro.plugins) ? nitro.plugins.filter((plugin) => !isGeneratedNitroRegistration(plugin, generatedNitroSchedulePlugin)) : [];
4754
+ const kit = createNitroServerKit(nitro);
4755
+ kit.addPlugin(options.plugin);
4756
+ const configured = kit.config;
4757
+ if (!options.providerWake) return configured;
4758
+ configured.modules = [...Array.isArray(configured.modules) ? configured.modules.filter((module) => !isGeneratedNitroRegistration(module, generatedNitroCloudflareModule)) : [], options.module];
4759
+ configured.cloudflare ||= {};
4760
+ configured.cloudflare.wrangler ||= {};
4761
+ const wrangler = configured.cloudflare.wrangler;
3754
4762
  const existingTriggers = isRecord(wrangler.triggers) ? wrangler.triggers : {};
3755
4763
  const existingCrons = Array.isArray(existingTriggers.crons) ? existingTriggers.crons.filter((cron) => typeof cron === "string") : [];
3756
4764
  wrangler.triggers = {
3757
4765
  ...existingTriggers,
3758
- crons: [...new Set([...existingCrons, ...options.crons])]
4766
+ crons: [.../* @__PURE__ */ new Set([...existingCrons, ...options.crons])]
3759
4767
  };
3760
- return nitro;
4768
+ return configured;
3761
4769
  }
3762
4770
  function mergeNitroVercelCrons(value, definitions, crons) {
3763
4771
  const nitro = cloneNitroConfig(value);
@@ -3776,7 +4784,8 @@ function renderNitroSchedulePlugin(options) {
3776
4784
  const importBase = options.importBase ?? "@vite-hub/schedule";
3777
4785
  const providerWake = options.providerDefinitions.length > 0;
3778
4786
  const processRuntime = options.processRuntime;
3779
- const processDriverOptions = processRuntime ? {
4787
+ const processRuntimeOptions = processRuntime ? {
4788
+ ...processRuntime.catchUpMs !== void 0 ? { catchUpMs: processRuntime.catchUpMs } : {},
3780
4789
  ...processRuntime.concurrency !== void 0 ? { concurrency: processRuntime.concurrency } : {},
3781
4790
  ...processRuntime.intervalMs !== void 0 ? { intervalMs: processRuntime.intervalMs } : {}
3782
4791
  } : void 0;
@@ -3785,16 +4794,16 @@ function renderNitroSchedulePlugin(options) {
3785
4794
  "import { definePlugin } from 'nitro'",
3786
4795
  ...providerWake ? [`import scheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.providerRegistryFile))}`, `import { executeCloudflareStaticSchedules } from ${JSON.stringify(options.runtimeImport ?? `${importBase}/runtime/static`)}`] : [],
3787
4796
  ...processRuntime ? [
3788
- `import { createKVRuntimeScheduleStore, createKVScheduleRunStore } from ${JSON.stringify(importBase)}`,
3789
- `import { installScheduleRuntime } from ${JSON.stringify(`${importBase}/runtime/driver`)}`,
3790
- `import { createProcessScheduleWakeDriver } from ${JSON.stringify(`${importBase}/runtime/process`)}`,
3791
- `import runtimeScheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.runtimeRegistryFile))}`,
4797
+ `import { normalizeScheduleRuntimeError } from ${JSON.stringify(options.runtimeImport ?? `${importBase}/runtime/static`)}`,
4798
+ `import { createKVScheduleRunStore } from ${JSON.stringify(`${importBase}/runtime`)}`,
4799
+ `import { scheduleKVStorage } from ${JSON.stringify(`${importBase}/runtime/kv`)}`,
4800
+ `import { installProcessScheduleRuntime, onShutdown } from ${JSON.stringify(`${importBase}/runtime/process`)}`,
3792
4801
  `import staticScheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.staticRegistryFile))}`
3793
4802
  ] : [],
3794
4803
  "",
3795
4804
  ...processRuntime ? [
3796
- `const processDriverOptions = ${JSON.stringify(processDriverOptions, null, 2)}`,
3797
- `const scheduleStoreOptions = ${JSON.stringify(scheduleStoreOptions, null, 2)}`,
4805
+ `const processRuntimeOptions = ${JSON.stringify(processRuntimeOptions, null, 2)}`,
4806
+ `const scheduleStoreOptions = { ...${JSON.stringify(scheduleStoreOptions, null, 2)}, kvStore: scheduleKVStorage }`,
3798
4807
  ""
3799
4808
  ] : [],
3800
4809
  "export default definePlugin((nitroApp) => {",
@@ -3807,7 +4816,7 @@ function renderNitroSchedulePlugin(options) {
3807
4816
  " function captureRuntimeError(error: unknown) {",
3808
4817
  " let runtimeError: Error",
3809
4818
  " try {",
3810
- " runtimeError = error instanceof Error ? error : new Error(String(error))",
4819
+ " runtimeError = normalizeScheduleRuntimeError(error)",
3811
4820
  " }",
3812
4821
  " catch {",
3813
4822
  " return",
@@ -3821,13 +4830,11 @@ function renderNitroSchedulePlugin(options) {
3821
4830
  " }",
3822
4831
  " catch {}",
3823
4832
  " }",
3824
- " const runtimeInstallation = installScheduleRuntime({",
3825
- " createDriver: createProcessScheduleWakeDriver(processDriverOptions),",
4833
+ " const runtimeInstallation = installProcessScheduleRuntime({",
4834
+ " ...processRuntimeOptions,",
3826
4835
  " onError: captureRuntimeError,",
3827
- " registry: runtimeScheduleRegistry,",
3828
- " runtimeScheduleStore: createKVRuntimeScheduleStore(scheduleStoreOptions),",
4836
+ " registry: staticScheduleRegistry,",
3829
4837
  " scheduleRunStore: createKVScheduleRunStore(scheduleStoreOptions),",
3830
- " staticRegistry: staticScheduleRegistry,",
3831
4838
  " }).then(",
3832
4839
  " controller => ({ controller }),",
3833
4840
  " error => {",
@@ -3835,30 +4842,14 @@ function renderNitroSchedulePlugin(options) {
3835
4842
  " return { error }",
3836
4843
  " },",
3837
4844
  " )",
3838
- " const nodeProcess = globalThis.process",
3839
- " const shutdownSignals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM']",
3840
- " let runtimeClose: Promise<void> | undefined",
3841
- " function removeRuntimeShutdownSignals() {",
3842
- " for (const signal of shutdownSignals) nodeProcess?.off(signal, closeRuntimeOnSignal)",
3843
- " }",
3844
- " function closeRuntime() {",
3845
- " removeRuntimeShutdownSignals()",
3846
- " runtimeClose ??= runtimeInstallation.then(async (result) => {",
3847
- " if ('controller' in result) await result.controller.close()",
3848
- " })",
3849
- " return runtimeClose",
3850
- " }",
3851
- " function closeRuntimeOnSignal(signal: NodeJS.Signals) {",
3852
- " void closeRuntime().catch(captureRuntimeError).finally(() => {",
3853
- " if (nodeProcess) nodeProcess.kill(nodeProcess.pid, signal)",
3854
- " })",
3855
- " }",
3856
- " for (const signal of shutdownSignals) nodeProcess?.prependOnceListener(signal, closeRuntimeOnSignal)",
4845
+ " // ViteHub runs this drain on a stop signal, before the server closes HTTP, or when Nitro closes.",
4846
+ " onShutdown(nitroApp, 'schedule', () => runtimeInstallation.then(async (result) => {",
4847
+ " if ('controller' in result) await result.controller.close()",
4848
+ " }).catch(captureRuntimeError))",
3857
4849
  " nitroApp.hooks.hook('request', async () => {",
3858
4850
  " const result = await runtimeInstallation",
3859
4851
  " if ('error' in result) throw result.error",
3860
- " })",
3861
- " nitroApp.hooks.hook('close', closeRuntime)"
4852
+ " })"
3862
4853
  ] : [],
3863
4854
  "})",
3864
4855
  "",
@@ -3900,7 +4891,6 @@ async function writeNitroSchedulePlugin(root, options) {
3900
4891
  const pluginFile = resolve(root, generatedNitroSchedulePlugin);
3901
4892
  const moduleFile = resolve(root, generatedNitroCloudflareModule);
3902
4893
  const providerRegistryFile = resolve(root, generatedNitroProviderRegistry);
3903
- const runtimeRegistryFile = resolve(root, generatedNitroRuntimeRegistry);
3904
4894
  const staticRegistryFile = resolve(root, generatedNitroStaticRegistry);
3905
4895
  await mkdir(dirname(pluginFile), { recursive: true });
3906
4896
  const writes = [writeFile(pluginFile, renderNitroSchedulePlugin({
@@ -3909,13 +4899,10 @@ async function writeNitroSchedulePlugin(root, options) {
3909
4899
  processRuntime: options.processRuntime,
3910
4900
  providerDefinitions: options.providerDefinitions,
3911
4901
  providerRegistryFile,
3912
- runtimeRegistryFile,
3913
4902
  staticRegistryFile,
3914
4903
  runtimeImport: options.runtimeImport
3915
4904
  }), "utf8")];
3916
4905
  if (options.processRuntime) {
3917
- writes.push(writeFile(runtimeRegistryFile, createRuntimeRegistryContents(runtimeRegistryFile, options.runtimeDefinitions), "utf8"));
3918
- writes.push(writeFile(runtimeRegistryFile.replace(/\.js$/, ".d.ts"), renderScheduleRegistryTypes(options.importBase), "utf8"));
3919
4906
  writes.push(writeFile(staticRegistryFile, createRuntimeRegistryContents(staticRegistryFile, options.staticDefinitions), "utf8"));
3920
4907
  writes.push(writeFile(staticRegistryFile.replace(/\.js$/, ".d.ts"), renderScheduleRegistryTypes(options.importBase), "utf8"));
3921
4908
  }
@@ -3929,16 +4916,15 @@ async function writeNitroSchedulePlugin(root, options) {
3929
4916
  return generatedNitroSchedulePlugin;
3930
4917
  }
3931
4918
  function hasServerScheduleDefinitions(definitions) {
3932
- return definitions.some((definition) => definition.runtimeOnly !== true && definition.source === "server-schedules");
4919
+ return definitions.some(isServerScheduleDefinition);
3933
4920
  }
3934
4921
  function hasViteSuffixScheduleDefinitions(definitions) {
3935
- return definitions.some((definition) => definition.runtimeOnly !== true && definition.source === "vite-suffix");
4922
+ return definitions.some((definition) => definition.source === "vite-suffix");
3936
4923
  }
3937
4924
  function selectNitroScheduleDefinitions(definitions, options) {
3938
4925
  if (options.providerOutput === false || options.providerOutput === "standalone") return [];
3939
- const staticDefinitions = definitions.filter((definition) => definition.runtimeOnly !== true);
3940
- if (options.providerOutput === "nitro") return staticDefinitions;
3941
- return staticDefinitions.filter((definition) => definition.source === "server-schedules");
4926
+ if (options.providerOutput === "nitro") return definitions;
4927
+ return definitions.filter(isServerScheduleDefinition);
3942
4928
  }
3943
4929
  function selectStandaloneProviderSource(definitions, options) {
3944
4930
  if (options.providerOutput === "auto" || options.providerOutput === void 0) return hasServerScheduleDefinitions(definitions) ? "vite-suffix" : void 0;
@@ -3948,14 +4934,19 @@ function shouldInstallNitroSchedulePlugin(definitions, options) {
3948
4934
  }
3949
4935
  function shouldEmitStandaloneProviderOutput(definitions, options) {
3950
4936
  if (options.providerOutput === false || options.providerOutput === "nitro") return false;
3951
- if (options.providerOutput === "standalone") return definitions.some((definition) => definition.runtimeOnly !== true);
4937
+ if (options.providerOutput === "standalone") return definitions.length > 0;
3952
4938
  if (hasServerScheduleDefinitions(definitions)) return hasViteSuffixScheduleDefinitions(definitions);
3953
- return definitions.some((definition) => definition.runtimeOnly !== true);
4939
+ return definitions.length > 0;
3954
4940
  }
3955
4941
  async function createScheduleNitroConfig(options = {}) {
3956
4942
  const processRuntime = resolveProcessRuntimeOptions(options.runtime);
3957
4943
  const roots = resolveSchedulePluginRoots(options.root || process.cwd(), options);
3958
4944
  const definitions = discoverScheduleDefinitions({
4945
+ contributions: options.contributions ?? await collectScheduleContributions(options.plugins, {
4946
+ projectRoot: roots.projectRoot,
4947
+ root: roots.viteRoot,
4948
+ serverDirs: options.serverDirs
4949
+ }),
3959
4950
  rootDir: roots.viteRoot,
3960
4951
  serverDirs: options.serverDirs,
3961
4952
  serverRootDir: roots.projectRoot
@@ -3963,7 +4954,7 @@ async function createScheduleNitroConfig(options = {}) {
3963
4954
  const installNitroPlugin = shouldInstallNitroSchedulePlugin(definitions, options);
3964
4955
  const nitroPreset = isRecord(options.nitro) && typeof options.nitro.preset === "string" ? options.nitro.preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOSTING || "";
3965
4956
  const standaloneProviderSource = selectStandaloneProviderSource(definitions, options);
3966
- const vercelDefinitions = options.command === "build" && nitroPreset.startsWith("vercel") && (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options) ? definitions.filter((definition) => definition.runtimeOnly !== true && (standaloneProviderSource === void 0 || definition.source === standaloneProviderSource)) : [];
4957
+ const vercelDefinitions = options.command === "build" && nitroPreset.startsWith("vercel") && (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options) ? definitions.filter((definition) => standaloneProviderSource === void 0 || definition.source === standaloneProviderSource) : [];
3967
4958
  if (!installNitroPlugin && !vercelDefinitions.length) return null;
3968
4959
  let nitro = options.nitro;
3969
4960
  if (vercelDefinitions.length) nitro = mergeNitroVercelCrons(nitro, vercelDefinitions, await readDefinitionCrons(vercelDefinitions));
@@ -3976,8 +4967,7 @@ async function createScheduleNitroConfig(options = {}) {
3976
4967
  importBase: options.importBase,
3977
4968
  processRuntime,
3978
4969
  providerDefinitions: nitroDefinitions,
3979
- runtimeDefinitions: definitions,
3980
- staticDefinitions: definitions.filter((definition) => definition.runtimeOnly !== true && !nitroDefinitionNames.has(definition.name) && !(processRuntime && options.providerOutput === "standalone")),
4970
+ staticDefinitions: definitions.filter((definition) => !nitroDefinitionNames.has(definition.name) && !(processRuntime && options.providerOutput === "standalone")),
3981
4971
  runtimeImport: options.runtimeImport
3982
4972
  });
3983
4973
  return mergeNitroScheduleConfig(nitro, {
@@ -3997,37 +4987,35 @@ function hubSchedule(options = {}) {
3997
4987
  let standaloneProviderSource;
3998
4988
  let serverDirs;
3999
4989
  let viteRoot;
4000
- function discoverViteSchedules() {
4001
- if (!projectRoot || !viteRoot) return [];
4002
- return discoverScheduleDefinitions({
4003
- mode: "vite-suffix",
4004
- rootDir: viteRoot,
4005
- serverDirs,
4006
- serverRootDir: projectRoot
4990
+ let contributions = [];
4991
+ async function collectPluginScheduleContributions(plugins, roots) {
4992
+ return await collectScheduleContributions(plugins, {
4993
+ projectRoot: roots.projectRoot,
4994
+ root: roots.viteRoot,
4995
+ serverDirs
4007
4996
  });
4008
4997
  }
4009
4998
  function discoverRegistrySchedules() {
4010
4999
  if (!projectRoot || !viteRoot) return [];
4011
5000
  return discoverScheduleDefinitions({
5001
+ contributions,
4012
5002
  rootDir: viteRoot,
4013
5003
  serverDirs,
4014
5004
  serverRootDir: projectRoot
4015
5005
  });
4016
5006
  }
4017
5007
  function createRegistryContents() {
4018
- const definitions = discoverRegistrySchedules();
4019
- return createRuntimeRegistryContents(projectRoot ? resolve(projectRoot, registryImportAnchor) : registryImportAnchor, definitions);
4020
- }
4021
- function createTargetsContents() {
4022
- return createScheduleTargetsContents(discoverViteSchedules(), { types: false });
5008
+ return renderScheduleRegistryModule(discoverRegistrySchedules());
4023
5009
  }
4024
- return {
5010
+ const inspectable = {
4025
5011
  name: SCHEDULE_VITE_PLUGIN_NAME,
4026
5012
  enforce: "pre",
4027
5013
  async config(config, env) {
4028
5014
  serverDirs = config["__vitehubServerDirs"] ?? serverDirs;
4029
5015
  const roots = resolveSchedulePluginRoots(config.root || process.cwd(), options);
5016
+ contributions = await collectPluginScheduleContributions(config.plugins, roots);
4030
5017
  const definitions = discoverScheduleDefinitions({
5018
+ contributions,
4031
5019
  rootDir: roots.viteRoot,
4032
5020
  serverDirs,
4033
5021
  serverRootDir: roots.projectRoot
@@ -4037,6 +5025,7 @@ function hubSchedule(options = {}) {
4037
5025
  const nitro = await createScheduleNitroConfig({
4038
5026
  ...options,
4039
5027
  command: env.command,
5028
+ contributions,
4040
5029
  nitroOwnsPaths: hasNitroConfigContext(config),
4041
5030
  nitro: config.nitro,
4042
5031
  root: config.root || process.cwd(),
@@ -4045,33 +5034,48 @@ function hubSchedule(options = {}) {
4045
5034
  if (!nitro) return null;
4046
5035
  config.nitro = nitro;
4047
5036
  },
4048
- configResolved(config) {
5037
+ async configResolved(config) {
4049
5038
  resolved = config;
4050
5039
  providerOutput = useProviderOutputCatalog(config);
4051
5040
  const roots = resolveSchedulePluginRoots(config.root, options);
4052
5041
  projectRoot = roots.projectRoot;
4053
5042
  viteRoot = roots.viteRoot;
5043
+ contributions = await collectPluginScheduleContributions(config.plugins, roots);
5044
+ const definitions = discoverRegistrySchedules();
5045
+ emitStandaloneProviderOutput = (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options);
5046
+ standaloneProviderSource = selectStandaloneProviderSource(definitions, options);
5047
+ if (config.command) {
5048
+ const nitro = await createScheduleNitroConfig({
5049
+ ...options,
5050
+ command: config.command,
5051
+ contributions,
5052
+ nitro: config.nitro,
5053
+ nitroOwnsPaths: hasNitroConfigContext(config),
5054
+ root: config.root,
5055
+ serverDirs
5056
+ });
5057
+ if (nitro) {
5058
+ const configWithNitro = config;
5059
+ configWithNitro.nitro = nitro;
5060
+ }
5061
+ }
4054
5062
  },
4055
5063
  configEnvironment(name, config) {
4056
5064
  if (!isServerEnvironment(name, config)) return;
4057
5065
  return { resolve: { noExternal: mergeNoExternal(config.resolve?.noExternal) } };
4058
5066
  },
4059
- handleHotUpdate(context) {
5067
+ async handleHotUpdate(context) {
4060
5068
  const file = normalize(context.file).replace(/\\/g, "/");
4061
5069
  const serverSchedule = (serverDirs ?? [resolve(projectRoot ?? resolved?.root ?? context.server.config.root, "server")]).map((directory) => `${resolve(directory, "schedules").replace(/\\/g, "/")}/`).some((directory) => file.startsWith(directory) && /\.(?:c|m)?[jt]s$/i.test(file.slice(directory.length)));
4062
- if (!/\.schedule\.(?:c|m)?[jt]s$/i.test(file) && !serverSchedule) return;
4063
- const registryModule = context.server.moduleGraph.getModuleById(RESOLVED_SCHEDULE_REGISTRY_ID);
4064
- if (registryModule) context.server.moduleGraph.invalidateModule(registryModule);
4065
- const targetsModule = context.server.moduleGraph.getModuleById(RESOLVED_SCHEDULE_TARGETS_ID);
4066
- if (targetsModule) context.server.moduleGraph.invalidateModule(targetsModule);
5070
+ const contributedSchedule = contributions.some((contribution) => normalize(contribution.definition.module).replace(/\\/g, "/") === file);
5071
+ if (!/\.schedule\.(?:c|m)?[jt]s$/i.test(file) && !serverSchedule && !contributedSchedule) return;
5072
+ invalidateScheduleRegistry(context.server);
4067
5073
  },
4068
5074
  resolveId(id) {
4069
5075
  if (id === SCHEDULE_REGISTRY_ID) return RESOLVED_SCHEDULE_REGISTRY_ID;
4070
- if (id === "#vitehub/schedule/targets") return RESOLVED_SCHEDULE_TARGETS_ID;
4071
5076
  },
4072
5077
  load(id) {
4073
5078
  if (id === RESOLVED_SCHEDULE_REGISTRY_ID) return createRegistryContents();
4074
- if (id === RESOLVED_SCHEDULE_TARGETS_ID) return createTargetsContents();
4075
5079
  },
4076
5080
  buildStart() {
4077
5081
  providerOutputGenerations.capture(this, providerOutput);
@@ -4088,7 +5092,7 @@ function hubSchedule(options = {}) {
4088
5092
  try {
4089
5093
  const definitions = emitStandaloneProviderOutput ? discoverRegistrySchedules() : [];
4090
5094
  const crons = await readDefinitionCrons(definitions);
4091
- const prepareWorkflow = (config.plugins ?? []).find((candidate) => candidate.vitehub?.workflow?.prepareScheduleRuntime)?.vitehub?.workflow?.prepareScheduleRuntime;
5095
+ const prepareWorkflow = definitions.length ? (config.plugins ?? []).find((candidate) => candidate.vitehub?.workflow?.prepareScheduleRuntime)?.vitehub?.workflow?.prepareScheduleRuntime : void 0;
4092
5096
  artifactDir = resolve(rootDir, ".vitehub/schedule-generations", randomUUID());
4093
5097
  const contributionArtifactDir = artifactDir;
4094
5098
  const workflow = await prepareWorkflow?.(resolve(contributionArtifactDir, "workflow"));
@@ -4108,6 +5112,7 @@ function hubSchedule(options = {}) {
4108
5112
  ],
4109
5113
  roots: [rootDir]
4110
5114
  }) : { resolve: (path) => path };
5115
+ if (definitions.length || workflow) await prepareViteHubProviderSources(config.plugins ?? [], retainedSources);
4111
5116
  const retainedDefinitions = definitions.map((definition) => ({
4112
5117
  ...definition,
4113
5118
  handler: retainedSources.resolve(definition.handler)
@@ -4161,6 +5166,28 @@ function hubSchedule(options = {}) {
4161
5166
  }
4162
5167
  }
4163
5168
  };
5169
+ inspectable.vitehub = {
5170
+ operations: [{
5171
+ export: "scheduleOperations",
5172
+ load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).scheduleOperations,
5173
+ module: "@vite-hub/schedule/operations"
5174
+ }],
5175
+ inspect: () => ({ definitions: [{
5176
+ kind: "schedule",
5177
+ label: "Schedules",
5178
+ list: () => {
5179
+ const roots = resolveSchedulePluginRoots(viteRoot ?? process.cwd(), options);
5180
+ return inspectScheduleDefinitions({
5181
+ plugins: resolved?.plugins,
5182
+ projectRoot: roots.projectRoot,
5183
+ rootDir: roots.viteRoot,
5184
+ serverDirs,
5185
+ serverRootDir: roots.projectRoot
5186
+ });
5187
+ }
5188
+ }] })
5189
+ };
5190
+ return inspectable;
4164
5191
  }
4165
5192
  //#endregion
4166
- export { hubSchedule as n, readScheduleDefinitionCrons as r, createScheduleNitroConfig as t };
5193
+ export { scheduleConsoleSection as a, collectScheduleContributions as c, inspectScheduleDefinitions as i, hubSchedule as n, contributedScheduleSource as o, readScheduleDefinitionCrons as r, discoverScheduleDefinitions as s, createScheduleNitroConfig as t };