@vite-hub/rate-limit 0.0.2 → 0.0.4

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.
package/dist/vite.js CHANGED
@@ -2,9 +2,10 @@ import { i as rateLimitPolicyKeys, n as declaredRateLimitPolicy, r as normalizeR
2
2
  import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "./cloudflare-BYZQ2tim.js";
3
3
  import { memoryRateLimitDriver } from "./drivers/memory.js";
4
4
  import { createRequire } from "node:module";
5
- import { cp, mkdir, readFile, readdir, rm, rmdir, stat, writeFile } from "node:fs/promises";
6
- import { basename, dirname, relative, resolve } from "node:path";
7
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
5
+ import { basename, dirname, isAbsolute, parse, relative, resolve, sep } from "node:path";
6
+ import { existsSync, readFileSync, readdirSync, renameSync, rmSync, statSync } from "node:fs";
7
+ import { cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
8
+ import { tmpdir } from "node:os";
8
9
  import { fileURLToPath } from "node:url";
9
10
  import { isDeepStrictEqual } from "node:util";
10
11
  import { Visitor, normalizePath, parseSync } from "vite";
@@ -61,10 +62,10 @@ const resolve$1 = function(...arguments_) {
61
62
  const path = index >= 0 ? arguments_[index] : cwd();
62
63
  if (!path || path.length === 0) continue;
63
64
  resolvedPath = `${path}/${resolvedPath}`;
64
- resolvedAbsolute = isAbsolute(path);
65
+ resolvedAbsolute = isAbsolute$1(path);
65
66
  }
66
67
  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
67
- if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
68
+ if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
68
69
  return resolvedPath.length > 0 ? resolvedPath : ".";
69
70
  };
70
71
  function normalizeString(path, allowAboveRoot) {
@@ -117,7 +118,7 @@ function normalizeString(path, allowAboveRoot) {
117
118
  }
118
119
  return res;
119
120
  }
120
- const isAbsolute = function(p) {
121
+ const isAbsolute$1 = function(p) {
121
122
  return _IS_ABSOLUTE_RE.test(p);
122
123
  };
123
124
  const relative$1 = function(from, to) {
@@ -135,7 +136,7 @@ const relative$1 = function(from, to) {
135
136
  const dirname$1 = function(p) {
136
137
  const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
137
138
  if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
138
- return segments.join("/") || (isAbsolute(p) ? "/" : ".");
139
+ return segments.join("/") || (isAbsolute$1(p) ? "/" : ".");
139
140
  };
140
141
  //#endregion
141
142
  //#region ../internal/src/build/client-output.ts
@@ -219,13 +220,14 @@ async function readProviderJsonRecord(file) {
219
220
  throw error;
220
221
  }
221
222
  }
222
- function deleteOwnedFields(value, ownership) {
223
+ function deleteOwnedFields(value, ownership, cleanup = false) {
223
224
  const next = { ...value };
224
225
  for (const key of ownership.keys ?? []) delete next[key];
225
- for (const field of Object.keys(ownership.arrays ?? {})) delete next[field];
226
+ for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) if (!cleanup || !arrayOwnership.preserveOnCleanup) delete next[field];
226
227
  return next;
227
228
  }
228
229
  function getKeyedArrayEntryValue(value, key) {
230
+ if (key === void 0) return value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string" ? value : void 0;
229
231
  if (!isProviderJsonRecord(value)) return;
230
232
  const entryValue = value[key];
231
233
  return entryValue === null || typeof entryValue === "boolean" || typeof entryValue === "number" || typeof entryValue === "string" ? entryValue : void 0;
@@ -260,7 +262,13 @@ async function persistProviderJsonRecord(file, value, removeIfEmpty) {
260
262
  await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
261
263
  }
262
264
  async function writeProviderOutputConfig(file, value, ownership = {}, options = {}) {
263
- await persistProviderJsonRecord(file, mergeProviderOutputConfig(await readProviderJsonRecord(file) ?? {}, value, ownership), options.removeIfEmpty === true);
265
+ const existing = await readProviderJsonRecord(file) ?? {};
266
+ const defaults = options.defaults ?? {};
267
+ assertProviderJsonRecord(defaults);
268
+ await persistProviderJsonRecord(file, mergeProviderOutputConfig({
269
+ ...defaults,
270
+ ...existing
271
+ }, value, ownership), options.removeIfEmpty === true);
264
272
  }
265
273
  function mergeProviderOutputConfig(existing, value, ownership = {}) {
266
274
  assertProviderJsonRecord(existing);
@@ -278,13 +286,15 @@ async function cleanProviderOutputConfig(file, ownership) {
278
286
  if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
279
287
  const existing = await readProviderJsonRecord(file);
280
288
  if (!existing) return;
281
- const next = deleteOwnedFields(existing, ownership);
289
+ const next = deleteOwnedFields(existing, ownership, true);
282
290
  let changed = (ownership.keys ?? []).some((key) => key in existing);
283
291
  for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
292
+ if (arrayOwnership.preserveOnCleanup) continue;
284
293
  if (!(field in existing)) continue;
285
294
  const current = existing[field];
286
- const preserved = preserveUnownedKeyedArrayEntries(current, arrayOwnership);
287
- changed ||= !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
295
+ const retained = arrayOwnership.retainOnCleanup ?? [];
296
+ const preserved = [...preserveUnownedKeyedArrayEntries(current, arrayOwnership, retained), ...retained];
297
+ changed ||= retained.length > 0 || !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
288
298
  if (preserved.length) next[field] = preserved;
289
299
  }
290
300
  if (!changed) return;
@@ -308,10 +318,13 @@ async function writeCloudflareWranglerConfig(options) {
308
318
  return;
309
319
  }
310
320
  await mkdir(outputRoot, { recursive: true });
311
- await writeProviderOutputConfig(configFile, options.wranglerConfig, options.wranglerConfigOwnership, { removeIfEmpty: true });
321
+ await writeProviderOutputConfig(configFile, options.wranglerConfig, options.wranglerConfigOwnership, {
322
+ defaults: options.wranglerConfigDefaults,
323
+ removeIfEmpty: true
324
+ });
312
325
  }
313
326
  //#endregion
314
- //#region ../internal/src/build/vite.ts
327
+ //#region ../internal/src/object.ts
315
328
  var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
316
329
  var __defProp = Object.defineProperty;
317
330
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -2660,83 +2673,14 @@ error: ${text}`);
2660
2673
  version
2661
2674
  });
2662
2675
  })))();
2663
- const projectRootDirectoryMarkers = [
2664
- ["server", "agents"],
2665
- ["server", "schedules"],
2666
- ["server", "templates"],
2667
- ["server", "workspaces"]
2668
- ];
2669
- const projectRootDefinitionFileMarkers = [
2670
- ".ts",
2671
- ".mts",
2672
- ".cts",
2673
- ".js",
2674
- ".mjs",
2675
- ".cjs"
2676
- ].flatMap((extension) => [["server", `email${extension}`], [`server.email${extension}`]]);
2677
- const projectRootFileMarkers = [["package.json"]];
2678
- function createNoExternalMerger(packageName) {
2679
- return (current) => {
2680
- if (current === true) return true;
2681
- if (!current) return [packageName];
2682
- const values = Array.isArray(current) ? current : [current];
2683
- return values.includes(packageName) ? values : [...values, packageName];
2684
- };
2685
- }
2686
- function isServerEnvironment(name, config) {
2687
- return name === "ssr" || config.consumer === "server";
2688
- }
2689
- function includesNitroVitePlugin(value) {
2690
- if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
2691
- if (!value || typeof value !== "object") return false;
2692
- return "name" in value && value.name === "nitro:main";
2693
- }
2694
- function hasNitroVitePlugin(config) {
2695
- return includesNitroVitePlugin(config.plugins);
2696
- }
2697
- function shouldSkipViteProviderBuild(command, mode) {
2698
- return command === "serve" || mode === "e2e";
2699
- }
2700
- function resolveViteHubProjectRoot(root, options = {}) {
2701
- const resolvedRoot = resolve(root);
2702
- if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
2703
- if (basename(resolvedRoot) === "app") {
2704
- const parent = dirname(resolvedRoot);
2705
- if (hasProjectRootDirectoryMarker(parent) || hasProjectRootDefinitionFileMarker(parent)) return parent;
2706
- }
2707
- let current = resolvedRoot;
2708
- while (true) {
2709
- if (hasProjectRootMarker(current)) return current;
2710
- const parent = dirname(current);
2711
- if (parent === current) return resolvedRoot;
2712
- current = parent;
2713
- }
2714
- }
2715
- function hasProjectRootDirectoryMarker(root) {
2716
- for (const marker of projectRootDirectoryMarkers) try {
2717
- if (statSync(resolve(root, ...marker)).isDirectory()) return true;
2718
- } catch (error) {
2719
- if (error.code !== "ENOENT") throw error;
2720
- }
2721
- return false;
2722
- }
2723
- function hasProjectRootMarker(root) {
2724
- if (hasProjectRootDirectoryMarker(root)) return true;
2725
- if (hasProjectRootDefinitionFileMarker(root)) return true;
2726
- for (const marker of projectRootFileMarkers) try {
2727
- if (statSync(resolve(root, ...marker)).isFile()) return true;
2728
- } catch (error) {
2729
- if (error.code !== "ENOENT") throw error;
2730
- }
2731
- return false;
2732
- }
2733
- function hasProjectRootDefinitionFileMarker(root) {
2734
- for (const marker of projectRootDefinitionFileMarkers) try {
2735
- if (statSync(resolve(root, ...marker)).isFile()) return true;
2736
- } catch (error) {
2737
- if (error.code !== "ENOENT") throw error;
2676
+ function isPlainObject(value) {
2677
+ if (value === null || Object(value) !== value || Array.isArray(value)) return false;
2678
+ try {
2679
+ Function.prototype.toString.call(value);
2680
+ return false;
2681
+ } catch {
2682
+ return true;
2738
2683
  }
2739
- return false;
2740
2684
  }
2741
2685
  //#endregion
2742
2686
  //#region ../internal/src/build/esbuild.ts
@@ -2744,13 +2688,264 @@ const viteRawNamespace = "vitehub-vite-raw";
2744
2688
  const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
2745
2689
  const markdownTemplateFileSuffix = ".template.md";
2746
2690
  const markdownTemplateModuleQuery = "markdown-template";
2747
- const markdownTemplateRegistryId = "#vitehub/templates";
2748
- const markdownTemplateRegistryPath = ".vitehub/markdown-template/templates.mjs";
2749
2691
  const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
2692
+ const skipResolvedAlias = "vitehubSkipResolvedAlias";
2693
+ const encodedAliasPrefixMarker = "\0vitehub-prefix:";
2694
+ const encodedAliasExactMarker = "\0vitehub-exact:";
2750
2695
  const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
2751
- function resolveEsbuildAliases(aliases) {
2752
- if (!aliases) return;
2753
- return Object.fromEntries(Object.entries(aliases).filter(([specifier]) => !specifier.endsWith("/")));
2696
+ function normalizePathSeparators(path) {
2697
+ return path.replaceAll("\\", "/");
2698
+ }
2699
+ function escapeRegExp(value) {
2700
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2701
+ }
2702
+ function collectPackageExportCandidates(packageName, exportsValue, packageRelativePath) {
2703
+ if (typeof exportsValue === "string") return normalizePathSeparators(exportsValue).replace(/^\.\//, "") === packageRelativePath ? [packageName] : [];
2704
+ if (!Array.isArray(exportsValue) && !isPlainObject(exportsValue)) return [];
2705
+ const candidates = [];
2706
+ const exportEntries = isPlainObject(exportsValue) && Object.keys(exportsValue).some((exportKey) => exportKey.startsWith(".")) ? Object.entries(exportsValue) : [[".", exportsValue]];
2707
+ for (const [exportKey, target] of exportEntries) {
2708
+ const targets = [target];
2709
+ while (targets.length) {
2710
+ const value = targets.shift();
2711
+ if (typeof value === "string") {
2712
+ const normalizedTarget = normalizePathSeparators(value).replace(/^\.\//, "");
2713
+ const targetParts = normalizedTarget.split("*");
2714
+ if (targetParts.length === 1) {
2715
+ if (normalizedTarget === packageRelativePath) candidates.push(`${packageName}${exportKey.slice(1)}`);
2716
+ continue;
2717
+ }
2718
+ const targetPattern = `${escapeRegExp(targetParts[0])}(.*?)${targetParts.slice(1).map((part, index) => `${index ? "\\1" : ""}${escapeRegExp(part)}`).join("")}`;
2719
+ const wildcard = new RegExp(`^${targetPattern}$`).exec(packageRelativePath)?.[1];
2720
+ if (wildcard === void 0) continue;
2721
+ candidates.push(`${packageName}${exportKey.slice(1).replace("*", wildcard)}`);
2722
+ } else if (Array.isArray(value)) targets.push(...value);
2723
+ else if (isPlainObject(value)) targets.push(...Object.values(value));
2724
+ }
2725
+ }
2726
+ return candidates;
2727
+ }
2728
+ function createResolvedAliasPlugin(aliases, aliasResolveDir) {
2729
+ const entries = Object.entries(aliases || {});
2730
+ if (!entries.length) return;
2731
+ const resolvedEntries = Promise.all(entries.map(async ([encodedSpecifier, replacement]) => {
2732
+ const prefixMarkerIndex = encodedSpecifier.lastIndexOf(encodedAliasPrefixMarker);
2733
+ const exactMarkerIndex = encodedSpecifier.lastIndexOf(encodedAliasExactMarker);
2734
+ const explicitlyEncodedPrefix = prefixMarkerIndex !== -1;
2735
+ const markerIndex = Math.max(prefixMarkerIndex, exactMarkerIndex);
2736
+ const specifier = markerIndex === -1 ? encodedSpecifier : encodedSpecifier.slice(0, markerIndex);
2737
+ const prefix = explicitlyEncodedPrefix || specifier.endsWith("/") && !Object.hasOwn(aliases, `${specifier}/`);
2738
+ const resolvedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
2739
+ const canonicalSpecifier = isAbsolute(resolvedSpecifier) ? normalizePathSeparators(await realpath(resolvedSpecifier).catch(() => resolvedSpecifier)) : resolvedSpecifier;
2740
+ const resolvedReplacement = isAbsolute(replacement) ? normalizePathSeparators(resolve(replacement)) : replacement;
2741
+ return {
2742
+ canonicalSpecifier: `${canonicalSpecifier}${prefix && !canonicalSpecifier.endsWith("/") ? "/" : ""}`,
2743
+ prefix,
2744
+ replacement: `${resolvedReplacement}${prefix && !/[\\/]$/.test(resolvedReplacement) ? "/" : ""}`,
2745
+ specifier: `${resolvedSpecifier}${prefix && !resolvedSpecifier.endsWith("/") ? "/" : ""}`
2746
+ };
2747
+ }));
2748
+ return {
2749
+ name: "vitehub-resolved-alias",
2750
+ setup(build) {
2751
+ const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
2752
+ build.onResolve({ filter: /.*/ }, async (args) => {
2753
+ if (args.pluginData?.[skipResolvedAlias]) return;
2754
+ const aliases = await resolvedEntries;
2755
+ let match = aliases.find(({ prefix, specifier }) => /^\.\.?[\\/]/.test(specifier) && (prefix ? args.path.startsWith(specifier) : args.path === specifier));
2756
+ let matchedAlias = match?.specifier;
2757
+ let matchedSpecifier = match ? args.path : void 0;
2758
+ let specifier = args.resolveDir && /^\.\.?[\\/]/.test(args.path) ? resolve(args.resolveDir, args.path) : args.path;
2759
+ let normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
2760
+ let canonicalSpecifier = normalizedSpecifier;
2761
+ const canonicalizeSpecifier = async () => {
2762
+ canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
2763
+ return canonicalSpecifier;
2764
+ };
2765
+ match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
2766
+ if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
2767
+ await canonicalizeSpecifier();
2768
+ match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
2769
+ }
2770
+ if (!match && isAbsolute(args.path)) for (const alias of aliases) {
2771
+ if (isAbsolute(alias.specifier)) continue;
2772
+ const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
2773
+ const aliasSegments = packageAlias.split("/");
2774
+ if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
2775
+ let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
2776
+ if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
2777
+ const scopeMarker = `/node_modules/${packageAlias}/`;
2778
+ const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
2779
+ const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
2780
+ if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
2781
+ }
2782
+ const packageMarker = `/node_modules/${packageName}/`;
2783
+ const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
2784
+ const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
2785
+ const cacheKey = [
2786
+ alias.specifier,
2787
+ alias.prefix,
2788
+ resolutionScope,
2789
+ args.importer,
2790
+ args.resolveDir,
2791
+ args.kind,
2792
+ args.namespace,
2793
+ JSON.stringify(args.with)
2794
+ ].join("\0");
2795
+ let resolution = args.pluginData ? void 0 : resolvedBareAliasPaths.get(cacheKey);
2796
+ if (!resolution) {
2797
+ resolution = (async () => {
2798
+ let resolvedAliasPath;
2799
+ if (alias.prefix && /^\.\.?[\\/]/.test(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
2800
+ else if (resolutionScope) {
2801
+ const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
2802
+ const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
2803
+ if (!isPlainObject(parsedPackageJson)) return;
2804
+ const packageJson = parsedPackageJson;
2805
+ if (packageJson.exports === void 0 && !alias.prefix) {
2806
+ const resolvedCandidate = await build.resolve(alias.specifier, {
2807
+ importer: args.importer,
2808
+ kind: args.kind,
2809
+ namespace: args.namespace,
2810
+ pluginData: {
2811
+ ...args.pluginData,
2812
+ [skipResolvedAlias]: true
2813
+ },
2814
+ resolveDir: args.resolveDir,
2815
+ with: args.with
2816
+ });
2817
+ if (!resolvedCandidate.errors.length && !resolvedCandidate.external && resolvedCandidate.namespace === "file" && normalizePathSeparators(resolve(resolvedCandidate.path)) === normalizedSpecifier) return {
2818
+ canonical: alias.specifier,
2819
+ normalized: alias.specifier,
2820
+ publicSpecifier: alias.specifier
2821
+ };
2822
+ return;
2823
+ }
2824
+ const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
2825
+ for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
2826
+ const resolvedCandidate = await build.resolve(publicSpecifier, {
2827
+ importer: args.importer,
2828
+ kind: args.kind,
2829
+ namespace: args.namespace,
2830
+ pluginData: {
2831
+ ...args.pluginData,
2832
+ [skipResolvedAlias]: true
2833
+ },
2834
+ resolveDir: args.resolveDir,
2835
+ with: args.with
2836
+ });
2837
+ if (resolvedCandidate.errors.length || resolvedCandidate.external || resolvedCandidate.namespace !== "file") continue;
2838
+ if (normalizePathSeparators(resolve(resolvedCandidate.path)) !== normalizedSpecifier) continue;
2839
+ matchingPublicSpecifiers.add(publicSpecifier);
2840
+ }
2841
+ if (matchingPublicSpecifiers.size === 1) {
2842
+ const publicSpecifier = [...matchingPublicSpecifiers][0];
2843
+ if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
2844
+ canonical: publicSpecifier,
2845
+ normalized: publicSpecifier,
2846
+ publicSpecifier
2847
+ };
2848
+ }
2849
+ return;
2850
+ } else {
2851
+ const resolvedAlias = await build.resolve(alias.specifier, {
2852
+ importer: args.importer,
2853
+ kind: args.kind,
2854
+ namespace: args.namespace,
2855
+ pluginData: {
2856
+ ...args.pluginData,
2857
+ [skipResolvedAlias]: true
2858
+ },
2859
+ resolveDir: args.resolveDir,
2860
+ with: args.with
2861
+ });
2862
+ if (resolvedAlias.errors.length || resolvedAlias.external || resolvedAlias.namespace !== "file") return;
2863
+ resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.path));
2864
+ }
2865
+ const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
2866
+ return {
2867
+ canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
2868
+ normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
2869
+ };
2870
+ })();
2871
+ if (!args.pluginData) resolvedBareAliasPaths.set(cacheKey, resolution);
2872
+ }
2873
+ const paths = await resolution;
2874
+ if (!paths) continue;
2875
+ if (paths.publicSpecifier) {
2876
+ match = alias;
2877
+ matchedAlias = alias.specifier;
2878
+ matchedSpecifier = paths.publicSpecifier;
2879
+ break;
2880
+ }
2881
+ const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
2882
+ let canonicalMatch = false;
2883
+ if (!normalizedMatch && paths.canonical !== paths.normalized) {
2884
+ await canonicalizeSpecifier();
2885
+ canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
2886
+ }
2887
+ if (normalizedMatch || canonicalMatch) {
2888
+ match = alias;
2889
+ matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
2890
+ matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
2891
+ break;
2892
+ }
2893
+ }
2894
+ matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
2895
+ matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
2896
+ if (!match) return;
2897
+ const target = match?.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match?.replacement ?? "");
2898
+ if (!target) return;
2899
+ const resolvedTarget = /^\.\.?[\\/]/.test(target) ? resolve(aliasResolveDir, target) : target;
2900
+ return build.resolve(resolvedTarget, {
2901
+ importer: args.importer,
2902
+ kind: args.kind,
2903
+ namespace: args.namespace,
2904
+ pluginData: {
2905
+ ...args.pluginData,
2906
+ [skipResolvedAlias]: true
2907
+ },
2908
+ resolveDir: args.resolveDir,
2909
+ with: args.with
2910
+ });
2911
+ });
2912
+ }
2913
+ };
2914
+ }
2915
+ function createViteAliasPlugin(aliases) {
2916
+ if (!Array.isArray(aliases)) return;
2917
+ const resolvingAlias = "vitehubResolvingAlias";
2918
+ return {
2919
+ name: "vitehub-vite-alias",
2920
+ setup(build) {
2921
+ build.onResolve({ filter: /.*/ }, async (args) => {
2922
+ if (args.pluginData?.[resolvingAlias]) return;
2923
+ const alias = aliases.find(({ find }) => {
2924
+ if (typeof find === "string") return args.path === find || args.path.startsWith(`${find}/`);
2925
+ find.lastIndex = 0;
2926
+ return find.test(args.path);
2927
+ });
2928
+ if (!alias) return;
2929
+ if (alias.customResolver) return { errors: [{ text: `[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(args.path)} because it uses customResolver.` }] };
2930
+ if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
2931
+ const replacement = typeof alias.find === "string" ? `${alias.replacement}${args.path.slice(alias.find.length)}` : args.path.replace(alias.find, alias.replacement);
2932
+ const result = await build.resolve(replacement, {
2933
+ importer: args.importer,
2934
+ kind: args.kind,
2935
+ namespace: args.namespace,
2936
+ pluginData: Object.assign({}, args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {}, { [resolvingAlias]: true }),
2937
+ resolveDir: args.resolveDir,
2938
+ with: args.with
2939
+ });
2940
+ const pluginData = Object.assign({}, result.pluginData);
2941
+ Reflect.deleteProperty(pluginData, resolvingAlias);
2942
+ return {
2943
+ ...result,
2944
+ pluginData
2945
+ };
2946
+ });
2947
+ }
2948
+ };
2754
2949
  }
2755
2950
  function stripMarkdownCode(template) {
2756
2951
  let fence;
@@ -2825,7 +3020,7 @@ async function resolveViteRawSpecifier(path, rootDir) {
2825
3020
  await stat(publicPath);
2826
3021
  return publicPath;
2827
3022
  } catch (error) {
2828
- if (error.code !== "ENOENT") throw error;
3023
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
2829
3024
  return resolve(rootDir, rootRelativePath);
2830
3025
  }
2831
3026
  }
@@ -2850,14 +3045,16 @@ function createViteRawPlugin(rootDir, frameworkRuntime) {
2850
3045
  const raw = hasViteRawQuery(args.path);
2851
3046
  if (!markdownTemplate && !raw) return;
2852
3047
  const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
3048
+ let pluginData = args.pluginData;
3049
+ if (markdownTemplate) pluginData = {
3050
+ ...args.pluginData,
3051
+ [skipMarkdownTemplateResolve]: true
3052
+ };
2853
3053
  const resolved = await build.resolve(specifier, {
2854
3054
  importer: args.importer,
2855
3055
  kind: args.kind,
2856
3056
  namespace: args.namespace,
2857
- pluginData: markdownTemplate ? {
2858
- ...args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {},
2859
- [skipMarkdownTemplateResolve]: true
2860
- } : args.pluginData,
3057
+ pluginData,
2861
3058
  resolveDir: args.resolveDir,
2862
3059
  with: args.with
2863
3060
  });
@@ -2910,7 +3107,7 @@ function createViteRawPlugin(rootDir, frameworkRuntime) {
2910
3107
  importer,
2911
3108
  kind: "import-statement",
2912
3109
  pluginData: {
2913
- ...args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {},
3110
+ ...args.pluginData,
2914
3111
  [skipMarkdownTemplateResolve]: true
2915
3112
  },
2916
3113
  resolveDir: dirname(importer)
@@ -2937,24 +3134,34 @@ function createViteRawPlugin(rootDir, frameworkRuntime) {
2937
3134
  }
2938
3135
  };
2939
3136
  }
3137
+ function createFileUrlPlugin() {
3138
+ return {
3139
+ name: "vitehub-file-url",
3140
+ setup(build) {
3141
+ build.onResolve({ filter: /^file:/ }, (args) => ({ path: fileURLToPath(args.path) }));
3142
+ }
3143
+ };
3144
+ }
2940
3145
  async function bundleEsmEntry(entryFile, outfile, options = {}) {
3146
+ options.signal?.throwIfAborted();
2941
3147
  const format = options.format || "esm";
2942
3148
  const platform = options.platform || "neutral";
2943
- const markdownTemplateRoot = options.rootDir && resolveViteHubProjectRoot(options.rootDir);
2944
- const aliases = resolveEsbuildAliases({
2945
- ...markdownTemplateRoot ? { [markdownTemplateRegistryId]: resolve(markdownTemplateRoot, markdownTemplateRegistryPath) } : {},
2946
- ...options.alias
2947
- });
2948
- const frameworkRuntime = Object.keys(aliases || {}).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
2949
- await (0, import_main.build)({
2950
- alias: aliases,
3149
+ const viteAliasPlugin = createViteAliasPlugin(options.alias);
3150
+ const frameworkRuntime = (Array.isArray(options.alias) ? options.alias.flatMap((alias) => typeof alias.find === "string" ? [alias.find] : []) : Object.keys(options.alias || {})).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
3151
+ const plugins = [];
3152
+ const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd());
3153
+ if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
3154
+ plugins.push(...options.plugins ?? [], createFileUrlPlugin());
3155
+ if (viteAliasPlugin) plugins.push(viteAliasPlugin);
3156
+ plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime));
3157
+ const result = await (0, import_main.build)({
3158
+ absWorkingDir: options.workingDir,
2951
3159
  banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
2952
- "import { createRequire as __createRequire } from \"node:module\";",
2953
- "import { dirname as __vitehubDirname } from \"node:path\";",
2954
- "import { fileURLToPath as __vitehubFileURLToPath } from \"node:url\";",
2955
- "globalThis.require = __createRequire(import.meta.url);",
2956
- "globalThis.__filename = __vitehubFileURLToPath(import.meta.url);",
2957
- "globalThis.__dirname = __vitehubDirname(globalThis.__filename);"
3160
+ "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
3161
+ " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
3162
+ " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
3163
+ " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
3164
+ "}"
2958
3165
  ] : []].filter(Boolean).join("\n") } : void 0,
2959
3166
  bundle: true,
2960
3167
  conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
@@ -2963,13 +3170,37 @@ async function bundleEsmEntry(entryFile, outfile, options = {}) {
2963
3170
  format,
2964
3171
  logLevel: "silent",
2965
3172
  mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
3173
+ resolveExtensions: options.extensions,
2966
3174
  minifyIdentifiers: options.minifyIdentifiers,
3175
+ minifyWhitespace: options.minifyWhitespace,
2967
3176
  outfile,
3177
+ packages: options.packages,
2968
3178
  platform,
2969
- plugins: [...options.plugins ?? [], createViteRawPlugin(options.rootDir, frameworkRuntime)],
3179
+ preserveSymlinks: options.preserveSymlinks,
3180
+ plugins,
2970
3181
  sourcemap: false,
2971
3182
  target: "es2022",
2972
- write: true
3183
+ write: options.signal ? false : true
3184
+ });
3185
+ options.signal?.throwIfAborted();
3186
+ if (options.signal) {
3187
+ await Promise.all((result.outputFiles ?? []).map(async (output) => {
3188
+ await mkdir(dirname(output.path), { recursive: true });
3189
+ options.signal.throwIfAborted();
3190
+ await writeFile(output.path, output.contents, { signal: options.signal });
3191
+ }));
3192
+ options.signal.throwIfAborted();
3193
+ }
3194
+ }
3195
+ //#endregion
3196
+ //#region ../internal/src/build/provider-output-sources.ts
3197
+ /** Removes retained provider output after readers release it, tolerating transient filesystem contention. */
3198
+ async function removeProviderOutputArtifactDir(path) {
3199
+ await rm(path, {
3200
+ force: true,
3201
+ maxRetries: 5,
3202
+ recursive: true,
3203
+ retryDelay: 50
2973
3204
  });
2974
3205
  }
2975
3206
  //#endregion
@@ -2995,8 +3226,8 @@ function createNodeFunctionConfig(extra = {}) {
2995
3226
  }
2996
3227
  //#endregion
2997
3228
  //#region ../internal/src/build/cloudflare-provider-output.ts
2998
- const cloudflareProviderOutputKey = Symbol.for("vitehub.cloudflareProviderOutput");
2999
- const cloudflareProviderOutputByNitro = /* @__PURE__ */ new WeakMap();
3229
+ const providerOutputCatalogRegistry$1 = globalThis;
3230
+ const providerOutputCatalogByNitroValue = providerOutputCatalogRegistry$1.__vitehubProviderOutputCatalogsByNitroValue ??= /* @__PURE__ */ new WeakMap();
3000
3231
  function cloneRecord(value) {
3001
3232
  return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
3002
3233
  }
@@ -3009,16 +3240,6 @@ function cloneProviderValue(value) {
3009
3240
  if (value && typeof value === "object") return cloneProviderRecord(value);
3010
3241
  return value;
3011
3242
  }
3012
- function useCloudflareProviderOutput(config) {
3013
- const owner = config;
3014
- return owner[cloudflareProviderOutputKey] ??= {
3015
- appliedByOwner: /* @__PURE__ */ new Map(),
3016
- contributionsByOwner: /* @__PURE__ */ new Map()
3017
- };
3018
- }
3019
- function registerCloudflareProviderOutput(config, owner, contribution) {
3020
- useCloudflareProviderOutput(config).contributionsByOwner.set(owner, contribution);
3021
- }
3022
3243
  function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner) {
3023
3244
  const current = Array.isArray(existing) ? existing.map(cloneProviderRecord) : [];
3024
3245
  return (incoming ?? []).filter((entry) => {
@@ -3038,7 +3259,10 @@ function removeEntries(existing, entries) {
3038
3259
  }
3039
3260
  function removeContribution(wrangler, contribution) {
3040
3261
  const queues = cloneProviderRecord(wrangler.queues);
3262
+ const secrets = cloneProviderRecord(wrangler.secrets);
3263
+ const environments = cloneProviderRecord(wrangler.env);
3041
3264
  const hasQueues = Boolean(contribution.queues?.consumers?.length || contribution.queues?.producers?.length);
3265
+ const hasSecrets = Boolean(contribution.requiredSecrets?.length || Object.keys(contribution.requiredSecretsByEnvironment ?? {}).length);
3042
3266
  if (contribution.queues?.consumers?.length) {
3043
3267
  const consumers = removeEntries(queues.consumers, contribution.queues.consumers);
3044
3268
  if (consumers.length) queues.consumers = consumers;
@@ -3049,20 +3273,59 @@ function removeContribution(wrangler, contribution) {
3049
3273
  if (producers.length) queues.producers = producers;
3050
3274
  else delete queues.producers;
3051
3275
  }
3052
- const { queues: _queues, ...withoutQueues } = wrangler;
3276
+ if (contribution.requiredSecrets?.length) {
3277
+ const required = removeEntries(secrets.required, contribution.requiredSecrets);
3278
+ if (required.length) secrets.required = required;
3279
+ else delete secrets.required;
3280
+ }
3281
+ for (const [name, requiredSecrets] of Object.entries(contribution.requiredSecretsByEnvironment ?? {})) {
3282
+ if (!(name in environments)) continue;
3283
+ const environment = cloneProviderRecord(environments[name]);
3284
+ const environmentSecrets = cloneProviderRecord(environment.secrets);
3285
+ const required = removeEntries(environmentSecrets.required, requiredSecrets);
3286
+ if (required.length) environmentSecrets.required = required;
3287
+ else delete environmentSecrets.required;
3288
+ if (Object.keys(environmentSecrets).length) environment.secrets = environmentSecrets;
3289
+ else delete environment.secrets;
3290
+ environments[name] = environment;
3291
+ }
3292
+ const withoutOwned = { ...wrangler };
3293
+ if (hasQueues) delete withoutOwned.queues;
3294
+ if (hasSecrets) delete withoutOwned.secrets;
3295
+ if (hasSecrets) delete withoutOwned.env;
3053
3296
  return {
3054
- ...hasQueues ? withoutQueues : wrangler,
3297
+ ...withoutOwned,
3055
3298
  ...hasQueues && Object.keys(queues).length ? { queues } : {},
3299
+ ...hasSecrets && Object.keys(secrets).length ? { secrets } : {},
3300
+ ...hasSecrets && Object.keys(environments).length ? { env: environments } : {},
3056
3301
  ...contribution.r2Buckets?.length ? { r2_buckets: removeEntries(wrangler.r2_buckets, contribution.r2Buckets) } : {},
3057
3302
  ...contribution.rateLimits?.length ? { ratelimits: removeEntries(wrangler.ratelimits, contribution.rateLimits) } : {}
3058
3303
  };
3059
3304
  }
3060
3305
  function mergeContribution(wrangler, owner, contribution) {
3061
3306
  const queues = cloneProviderRecord(wrangler.queues);
3307
+ const secrets = cloneProviderRecord(wrangler.secrets);
3308
+ const environments = cloneProviderRecord(wrangler.env);
3062
3309
  const consumers = compatibleEntries(queues.consumers, contribution.queues?.consumers, "queue", [], owner);
3063
3310
  const producers = compatibleEntries(queues.producers, contribution.queues?.producers, "binding", ["queue"], owner);
3064
3311
  const r2Buckets = compatibleEntries(wrangler.r2_buckets, contribution.r2Buckets, "binding", ["bucket_name"], owner);
3065
3312
  const rateLimits = compatibleEntries(wrangler.ratelimits, contribution.rateLimits, "name", ["namespace_id", "simple"], owner);
3313
+ const currentRequiredSecrets = Array.isArray(secrets.required) ? secrets.required : [];
3314
+ const requiredSecrets = (contribution.requiredSecrets ?? []).filter((name) => !currentRequiredSecrets.includes(name));
3315
+ if (requiredSecrets.length) secrets.required = [...currentRequiredSecrets, ...requiredSecrets];
3316
+ const requiredSecretsByEnvironment = {};
3317
+ for (const [name, value] of Object.entries(environments)) {
3318
+ const environment = cloneProviderRecord(value);
3319
+ const environmentSecrets = cloneProviderRecord(environment.secrets);
3320
+ const current = Array.isArray(environmentSecrets.required) ? environmentSecrets.required : [];
3321
+ const required = (contribution.requiredSecrets ?? []).filter((secret) => !current.includes(secret));
3322
+ if (required.length) {
3323
+ environmentSecrets.required = [...current, ...required];
3324
+ environment.secrets = environmentSecrets;
3325
+ environments[name] = environment;
3326
+ requiredSecretsByEnvironment[name] = required;
3327
+ }
3328
+ }
3066
3329
  const nextQueues = mergeProviderOutputConfig(queues, {
3067
3330
  ...consumers.length ? { consumers } : {},
3068
3331
  ...producers.length ? { producers } : {}
@@ -3073,7 +3336,9 @@ function mergeContribution(wrangler, owner, contribution) {
3073
3336
  return [mergeProviderOutputConfig(wrangler, {
3074
3337
  ...Object.keys(nextQueues).length ? { queues: nextQueues } : {},
3075
3338
  ...r2Buckets.length ? { r2_buckets: r2Buckets } : {},
3076
- ...rateLimits.length ? { ratelimits: rateLimits } : {}
3339
+ ...rateLimits.length ? { ratelimits: rateLimits } : {},
3340
+ ...Object.keys(secrets).length ? { secrets } : {},
3341
+ ...Object.keys(environments).length ? { env: environments } : {}
3077
3342
  }, { arrays: {
3078
3343
  r2_buckets: { key: "binding" },
3079
3344
  ratelimits: { key: "name" }
@@ -3083,25 +3348,37 @@ function mergeContribution(wrangler, owner, contribution) {
3083
3348
  producers
3084
3349
  },
3085
3350
  r2Buckets,
3086
- rateLimits
3351
+ rateLimits,
3352
+ requiredSecrets,
3353
+ requiredSecretsByEnvironment
3087
3354
  }];
3088
3355
  }
3089
- function composeNitroCloudflareProviderOutput(config, value) {
3356
+ function inheritedProviderOutputCatalog(value) {
3357
+ if (!value || typeof value !== "object") return;
3358
+ const cloudflare = value.cloudflare;
3359
+ const wrangler = cloudflare && typeof cloudflare === "object" ? cloudflare.wrangler : void 0;
3360
+ return providerOutputCatalogByNitroValue.get(value) ?? (cloudflare && typeof cloudflare === "object" ? providerOutputCatalogByNitroValue.get(cloudflare) : void 0) ?? (wrangler && typeof wrangler === "object" ? providerOutputCatalogByNitroValue.get(wrangler) : void 0);
3361
+ }
3362
+ function associateProviderOutputCatalog(output, catalog) {
3363
+ providerOutputCatalogByNitroValue.set(output, catalog);
3364
+ const cloudflare = output.cloudflare;
3365
+ if (!cloudflare || typeof cloudflare !== "object") return;
3366
+ providerOutputCatalogByNitroValue.set(cloudflare, catalog);
3367
+ const wrangler = cloudflare.wrangler;
3368
+ if (wrangler && typeof wrangler === "object") providerOutputCatalogByNitroValue.set(wrangler, catalog);
3369
+ }
3370
+ function composeNitroCloudflareProviderOutput(catalog, value, inheritedValue = value) {
3090
3371
  const nitro = cloneRecord(value);
3091
3372
  const cloudflare = cloneRecord(nitro.cloudflare);
3092
- const catalog = useCloudflareProviderOutput(config);
3093
- const inherited = value && typeof value === "object" ? value[cloudflareProviderOutputKey] ?? cloudflareProviderOutputByNitro.get(value) : void 0;
3094
- if (inherited && inherited !== catalog) {
3095
- for (const [owner, contribution] of inherited.appliedByOwner) catalog.appliedByOwner.set(owner, contribution);
3096
- catalog.contributionsByOwner = new Map([...inherited.contributionsByOwner, ...catalog.contributionsByOwner]);
3097
- }
3373
+ const inherited = inheritedProviderOutputCatalog(inheritedValue) ?? inheritedProviderOutputCatalog(value);
3374
+ if (inherited && inherited !== catalog) catalog.inheritCloudflareContributions(inherited);
3098
3375
  let wrangler = cloneProviderRecord(cloudflare.wrangler);
3099
- for (const contribution of catalog.appliedByOwner.values()) wrangler = removeContribution(wrangler, contribution);
3100
- catalog.appliedByOwner.clear();
3101
- for (const [owner, contribution] of catalog.contributionsByOwner) {
3376
+ for (const contribution of catalog.appliedCloudflareContributions()) wrangler = removeContribution(wrangler, contribution);
3377
+ catalog.clearAppliedCloudflareContributions();
3378
+ for (const [owner, contribution] of catalog.cloudflareContributions()) {
3102
3379
  const [merged, applied] = mergeContribution(wrangler, owner, contribution);
3103
3380
  wrangler = merged;
3104
- catalog.appliedByOwner.set(owner, applied);
3381
+ catalog.replaceAppliedCloudflareContribution(owner, applied);
3105
3382
  }
3106
3383
  const output = !Object.keys(cloudflare).length && !Object.keys(wrangler).length ? nitro : {
3107
3384
  ...nitro,
@@ -3110,130 +3387,740 @@ function composeNitroCloudflareProviderOutput(config, value) {
3110
3387
  wrangler
3111
3388
  }
3112
3389
  };
3113
- Object.defineProperty(output, cloudflareProviderOutputKey, {
3114
- enumerable: true,
3115
- value: catalog
3116
- });
3117
- cloudflareProviderOutputByNitro.set(output, catalog);
3390
+ associateProviderOutputCatalog(output, catalog);
3118
3391
  return output;
3119
3392
  }
3120
3393
  //#endregion
3121
- //#region ../internal/src/build/deployment-output.ts
3122
- const composedProviderOutputKey = Symbol.for("vitehub.composedProviderOutput");
3123
- const providerDeploymentOutputWrites = /* @__PURE__ */ new Map();
3124
- function useComposedProviderOutput(config) {
3394
+ //#region ../internal/src/build/provider-output-catalog.ts
3395
+ var ProviderOutputCatalog = class {
3396
+ #appliedCloudflareContributions = /* @__PURE__ */ new Map();
3397
+ #cloudflareContributions = /* @__PURE__ */ new Map();
3398
+ #runtimeContributions = /* @__PURE__ */ new Map();
3399
+ #runtimeContributionsByGeneration = /* @__PURE__ */ new WeakMap();
3400
+ #deploymentContributionSequence = 0;
3401
+ #deploymentContributions = /* @__PURE__ */ new Map();
3402
+ #deploymentGenerationRefs = /* @__PURE__ */ new WeakMap();
3403
+ #deploymentGenerations = /* @__PURE__ */ new Set();
3404
+ #pendingDeploymentDiscards = [];
3405
+ #takenDeploymentContributions = /* @__PURE__ */ new Map();
3406
+ appliedCloudflareContributions() {
3407
+ return this.#appliedCloudflareContributions.values();
3408
+ }
3409
+ appliedCloudflareContributionEntries() {
3410
+ return this.#appliedCloudflareContributions.entries();
3411
+ }
3412
+ clearAppliedCloudflareContributions() {
3413
+ this.#appliedCloudflareContributions.clear();
3414
+ }
3415
+ cloudflareContributions() {
3416
+ return this.#cloudflareContributions.entries();
3417
+ }
3418
+ inheritCloudflareContributions(catalog) {
3419
+ for (const [owner, contribution] of catalog.appliedCloudflareContributionEntries()) this.#appliedCloudflareContributions.set(owner, contribution);
3420
+ for (const [owner, contribution] of [...catalog.cloudflareContributions(), ...this.#cloudflareContributions]) this.#cloudflareContributions.set(owner, contribution);
3421
+ }
3422
+ replaceAppliedCloudflareContribution(owner, contribution) {
3423
+ this.#appliedCloudflareContributions.set(owner, contribution);
3424
+ }
3425
+ replaceCloudflareContribution(owner, contribution) {
3426
+ this.#cloudflareContributions.set(owner, contribution);
3427
+ }
3428
+ replaceRuntimeContribution(contribution, generation) {
3429
+ if (!generation) {
3430
+ this.#runtimeContributions.set(contribution.owner, contribution);
3431
+ return;
3432
+ }
3433
+ let contributions = this.#runtimeContributionsByGeneration.get(generation);
3434
+ if (!contributions) {
3435
+ contributions = /* @__PURE__ */ new Map();
3436
+ this.#runtimeContributionsByGeneration.set(generation, contributions);
3437
+ }
3438
+ contributions.set(contribution.owner, contribution);
3439
+ }
3440
+ runtimeContribution(product, generation) {
3441
+ return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.get(product);
3442
+ }
3443
+ runtimeContributions(generation) {
3444
+ return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.entries() ?? (/* @__PURE__ */ new Map()).entries();
3445
+ }
3446
+ resetRuntimeContributions() {
3447
+ this.#runtimeContributions.clear();
3448
+ }
3449
+ createDeploymentGeneration() {
3450
+ const generation = { valid: true };
3451
+ this.#trackDeploymentGeneration(generation);
3452
+ return generation;
3453
+ }
3454
+ replaceDeploymentContribution(contribution, generation) {
3455
+ const entry = {
3456
+ contribution,
3457
+ generation,
3458
+ sequence: this.#deploymentContributionSequence++
3459
+ };
3460
+ if (generation && !generation.valid) {
3461
+ this.#queueDeploymentDiscard(entry);
3462
+ return;
3463
+ }
3464
+ this.#restoreDeploymentContribution(entry);
3465
+ }
3466
+ resetDeploymentContributions(generation) {
3467
+ if (!generation) {
3468
+ for (const reference of this.#deploymentGenerations) {
3469
+ const current = reference.deref();
3470
+ if (current) current.valid = false;
3471
+ }
3472
+ this.#deploymentGenerations.clear();
3473
+ for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry);
3474
+ for (const taken of this.#takenDeploymentContributions.values()) {
3475
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
3476
+ for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback);
3477
+ }
3478
+ this.#deploymentContributions.clear();
3479
+ this.#takenDeploymentContributions.clear();
3480
+ return;
3481
+ }
3482
+ generation.valid = false;
3483
+ this.#deleteDeploymentGeneration(generation);
3484
+ for (const [owner, entries] of this.#deploymentContributions) {
3485
+ for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry);
3486
+ const remaining = entries.filter((entry) => entry.generation !== generation);
3487
+ if (remaining.length) this.#deploymentContributions.set(owner, remaining);
3488
+ else this.#deploymentContributions.delete(owner);
3489
+ }
3490
+ for (const [contribution, taken] of this.#takenDeploymentContributions) {
3491
+ const invalidatedFallbacks = taken.fallbacks.filter((entry) => entry.generation === generation);
3492
+ taken.fallbacks = taken.fallbacks.filter((entry) => entry.generation !== generation);
3493
+ for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback);
3494
+ if (taken.entry.generation !== generation) continue;
3495
+ this.#takenDeploymentContributions.delete(contribution);
3496
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
3497
+ for (const fallback of taken.fallbacks) if (taken.committed) this.#queueDeploymentDiscard(fallback);
3498
+ else this.#restoreDeploymentContribution(fallback);
3499
+ }
3500
+ }
3501
+ hasDeploymentContributions() {
3502
+ return this.#deploymentContributions.size > 0;
3503
+ }
3504
+ takeDeploymentContributions() {
3505
+ const contributions = [];
3506
+ for (const [owner, entries] of this.#deploymentContributions) {
3507
+ const entry = entries.at(-1);
3508
+ contributions.push(entry.contribution);
3509
+ this.#takenDeploymentContributions.set(entry.contribution, {
3510
+ committed: false,
3511
+ entry,
3512
+ entryDiscarded: false,
3513
+ fallbacks: entries.slice(0, -1)
3514
+ });
3515
+ this.#deploymentContributions.delete(owner);
3516
+ }
3517
+ return contributions;
3518
+ }
3519
+ deploymentContributionGeneration(contribution) {
3520
+ return this.#takenDeploymentContributions.get(contribution)?.entry.generation;
3521
+ }
3522
+ commitDeploymentContributions(contributions) {
3523
+ for (const contribution of contributions) {
3524
+ const taken = this.#takenDeploymentContributions.get(contribution);
3525
+ if (taken) taken.committed = true;
3526
+ }
3527
+ }
3528
+ async prepareDeploymentContributions(contributions) {
3529
+ const discarded = this.#pendingDeploymentDiscards.splice(0);
3530
+ for (const contribution of contributions) {
3531
+ const taken = this.#takenDeploymentContributions.get(contribution);
3532
+ if (!taken || taken.entryDiscarded || !taken.entry.contribution.discard) continue;
3533
+ taken.entryDiscarded = true;
3534
+ discarded.push(Promise.resolve().then(taken.entry.contribution.discard));
3535
+ }
3536
+ const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
3537
+ if (failure) throw failure.reason;
3538
+ }
3539
+ async completeDeploymentContributions(contributions) {
3540
+ const discarded = this.#pendingDeploymentDiscards.splice(0);
3541
+ const completedGenerations = /* @__PURE__ */ new Set();
3542
+ for (const contribution of contributions) {
3543
+ const taken = this.#takenDeploymentContributions.get(contribution);
3544
+ if (!taken) continue;
3545
+ this.#takenDeploymentContributions.delete(contribution);
3546
+ const entries = taken.entryDiscarded ? taken.fallbacks : [...taken.fallbacks, taken.entry];
3547
+ for (const entry of entries) {
3548
+ if (entry.generation) completedGenerations.add(entry.generation);
3549
+ if (entry.contribution.discard) discarded.push(entry.contribution.discard());
3550
+ }
3551
+ }
3552
+ for (const generation of completedGenerations) this.#retireDeploymentGeneration(generation);
3553
+ const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
3554
+ if (failure) throw failure.reason;
3555
+ }
3556
+ rollbackDeploymentContributions(contributions) {
3557
+ for (const contribution of contributions) {
3558
+ const taken = this.#takenDeploymentContributions.get(contribution);
3559
+ if (!taken) continue;
3560
+ this.#takenDeploymentContributions.delete(contribution);
3561
+ for (const entry of [...taken.fallbacks, taken.entry]) this.#restoreDeploymentContribution(entry);
3562
+ }
3563
+ }
3564
+ #restoreDeploymentContribution(entry) {
3565
+ if (entry.generation && !entry.generation.valid) return;
3566
+ if (entry.generation) this.#trackDeploymentGeneration(entry.generation);
3567
+ const entries = this.#deploymentContributions.get(entry.contribution.owner) ?? [];
3568
+ const replaced = entries.findIndex((candidate) => candidate.generation === entry.generation);
3569
+ if (replaced >= 0) {
3570
+ if (entries[replaced].sequence > entry.sequence) return;
3571
+ entries.splice(replaced, 1);
3572
+ }
3573
+ entries.push(entry);
3574
+ entries.sort((left, right) => left.sequence - right.sequence);
3575
+ this.#deploymentContributions.set(entry.contribution.owner, entries);
3576
+ }
3577
+ #retireDeploymentGeneration(generation) {
3578
+ const pending = [...this.#deploymentContributions.values()].some((entries) => entries.some((entry) => entry.generation === generation));
3579
+ const taken = [...this.#takenDeploymentContributions.values()].some((entry) => entry.entry.generation === generation || entry.fallbacks.some((fallback) => fallback.generation === generation));
3580
+ if (!pending && !taken) this.#deleteDeploymentGeneration(generation);
3581
+ }
3582
+ #trackDeploymentGeneration(generation) {
3583
+ if (this.#deploymentGenerationRefs.has(generation)) return;
3584
+ const reference = new WeakRef(generation);
3585
+ this.#deploymentGenerationRefs.set(generation, reference);
3586
+ this.#deploymentGenerations.add(reference);
3587
+ }
3588
+ #deleteDeploymentGeneration(generation) {
3589
+ const reference = this.#deploymentGenerationRefs.get(generation);
3590
+ if (reference) this.#deploymentGenerations.delete(reference);
3591
+ this.#deploymentGenerationRefs.delete(generation);
3592
+ }
3593
+ #queueDeploymentDiscard(entry) {
3594
+ if (!entry.contribution.discard) return;
3595
+ const discard = Promise.resolve().then(entry.contribution.discard);
3596
+ discard.catch(() => {});
3597
+ this.#pendingDeploymentDiscards.push(discard);
3598
+ }
3599
+ };
3600
+ const providerOutputCatalogRegistry = globalThis;
3601
+ const providerOutputCatalogs = providerOutputCatalogRegistry.__vitehubProviderOutputCatalogs ??= /* @__PURE__ */ new WeakMap();
3602
+ const providerOutputCatalog = Symbol.for("vitehub.provider-output-catalog");
3603
+ function createProviderOutputCatalog() {
3604
+ return new ProviderOutputCatalog();
3605
+ }
3606
+ function useProviderOutputCatalog(config) {
3125
3607
  const owner = config;
3126
- return owner[composedProviderOutputKey] ??= {
3127
- runtimeModuleFilesByProduct: {},
3128
- vercelRuntimePackagesByProduct: {}
3129
- };
3608
+ let catalog = owner[providerOutputCatalog] ?? providerOutputCatalogs.get(config);
3609
+ if (!catalog) catalog = createProviderOutputCatalog();
3610
+ owner[providerOutputCatalog] = catalog;
3611
+ providerOutputCatalogs.set(config, catalog);
3612
+ return catalog;
3130
3613
  }
3131
- function registerProviderRuntimeModules(composed, product, runtimeModuleFiles) {
3132
- if (composed) composed.runtimeModuleFilesByProduct[product] = runtimeModuleFiles;
3614
+ function contributeCloudflareProviderOutput(catalog, contribution) {
3615
+ const { owner, ...value } = contribution;
3616
+ catalog.replaceCloudflareContribution(owner, value);
3133
3617
  }
3134
- function resolveClientOutput(rootDir, clientOutDir) {
3135
- const clientDir = resolve(rootDir, clientOutDir);
3136
- return {
3137
- clientDir,
3138
- staticIndex: hasStaticIndex(clientDir)
3139
- };
3618
+ function contributeProviderRuntime(catalog, contribution, generation) {
3619
+ catalog?.replaceRuntimeContribution(contribution, generation);
3140
3620
  }
3141
- function createDefaultCloudflareStaticOutputDir(rootDir) {
3142
- return resolve(rootDir, "dist", "client");
3621
+ //#endregion
3622
+ //#region ../internal/src/build/vite.ts
3623
+ const projectRootDirectoryMarkers = [
3624
+ ["server", "agents"],
3625
+ ["server", "channels"],
3626
+ ["server", "browsers"],
3627
+ ["server", "emails"],
3628
+ ["server", "schedules"],
3629
+ ["server", "workspaces"]
3630
+ ];
3631
+ const projectRootFileMarkers = [["package.json"]];
3632
+ function createNoExternalMerger(packageName) {
3633
+ return (current) => {
3634
+ if (current === true) return true;
3635
+ if (!current) return [packageName];
3636
+ const values = Array.isArray(current) ? current : [current];
3637
+ return values.includes(packageName) ? values : [...values, packageName];
3638
+ };
3143
3639
  }
3144
- function createDefaultVercelOutputRoot(rootDir) {
3145
- return resolve(rootDir, ".vercel", "output");
3640
+ function isServerEnvironment(name, config) {
3641
+ return name === "ssr" || config.consumer === "server";
3146
3642
  }
3147
- function createDefaultNetlifyOutputRoot(rootDir) {
3148
- return resolve(rootDir, ".netlify", "v1");
3643
+ function includesNitroVitePlugin(value) {
3644
+ if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
3645
+ if (!value || typeof value !== "object") return false;
3646
+ return "name" in value && value.name === "nitro:main";
3149
3647
  }
3150
- function assertNetlifyFunctionName(functionName) {
3151
- if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw new Error(`Invalid Netlify function name: ${functionName}`);
3648
+ function hasNitroConfigContext(config) {
3649
+ return config["__vitehubNitroConfigContext"] === true || includesNitroVitePlugin(config.plugins);
3152
3650
  }
3153
- function resolveNetlifyFunctionFile(functionsRoot, functionName) {
3154
- assertNetlifyFunctionName(functionName);
3155
- return resolve(functionsRoot, `${functionName}.mjs`);
3651
+ function shouldSkipViteProviderBuild(command, mode) {
3652
+ return command === "serve" || mode === "e2e";
3156
3653
  }
3157
- async function appendNetlifyFunctionConfig(outfile, config) {
3158
- if (!config) return;
3159
- await writeFile(outfile, `${(await readFile(outfile, "utf8")).trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
3654
+ function resolveViteHubProjectRoot(root, options = {}) {
3655
+ const resolvedRoot = resolve(root);
3656
+ const temporaryRoot = resolve(tmpdir());
3657
+ const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
3658
+ if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
3659
+ if (basename(resolvedRoot) === "app") {
3660
+ const parent = dirname(resolvedRoot);
3661
+ if (parent !== sharedTemporaryRoot && hasProjectRootDirectoryMarker(parent)) return parent;
3662
+ }
3663
+ let current = resolvedRoot;
3664
+ while (true) {
3665
+ if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
3666
+ if (hasProjectRootMarker(current)) return current;
3667
+ const parent = dirname(current);
3668
+ if (parent === current) return resolvedRoot;
3669
+ current = parent;
3670
+ }
3160
3671
  }
3161
- async function writeCloudflareDeploymentOutput(options) {
3162
- const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
3163
- const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
3164
- const files = Object.entries(options.files ?? {});
3165
- const workerOutfile = options.bundleEntry ? resolve(outputRoot, options.bundleOutfileName ?? "index.js") : void 0;
3672
+ function hasProjectRootDirectoryMarker(root) {
3673
+ for (const marker of projectRootDirectoryMarkers) try {
3674
+ if (statSync(resolve(root, ...marker)).isDirectory()) return true;
3675
+ } catch (error) {
3676
+ if (error.code !== "ENOENT") throw error;
3677
+ }
3678
+ return false;
3679
+ }
3680
+ function hasProjectRootMarker(root) {
3681
+ if (hasProjectRootDirectoryMarker(root)) return true;
3682
+ for (const marker of projectRootFileMarkers) try {
3683
+ if (statSync(resolve(root, ...marker)).isFile()) return true;
3684
+ } catch (error) {
3685
+ if (error.code !== "ENOENT") throw error;
3686
+ }
3687
+ return false;
3688
+ }
3689
+ //#endregion
3690
+ //#region ../internal/src/build/deployment-output.ts
3691
+ const providerDeploymentOutputRegistry = globalThis;
3692
+ const providerDeploymentOutputWrites = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputWrites ??= /* @__PURE__ */ new Map();
3693
+ const providerDeploymentOutputFinalizations = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputFinalizations ??= /* @__PURE__ */ new WeakMap();
3694
+ const providerDeploymentOutputCompletedResets = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputCompletedResets ??= /* @__PURE__ */ new WeakMap();
3695
+ const providerDeploymentOutputRootStates = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputRootStates ??= /* @__PURE__ */ new Map();
3696
+ const providerDeploymentOutputOwnerOrder = [
3697
+ "agent",
3698
+ "database",
3699
+ "blob",
3700
+ "queue",
3701
+ "rate-limit",
3702
+ "schedule",
3703
+ "workflow",
3704
+ "vite-hub",
3705
+ "browser",
3706
+ "kv",
3707
+ "workspace"
3708
+ ];
3709
+ function throwIfProviderOutputAborted(signal) {
3710
+ if (!signal.aborted) return;
3711
+ throw signal.reason ?? new DOMException("Provider Output finalization aborted.", "AbortError");
3712
+ }
3713
+ async function settleWrites(writes) {
3714
+ const failure = (await Promise.allSettled(writes)).find((result) => result.status === "rejected");
3715
+ if (failure) throw failure.reason;
3716
+ }
3717
+ function resolveClientOutput(rootDir, clientOutDir) {
3718
+ const clientDir = resolve(rootDir, clientOutDir);
3719
+ return {
3720
+ clientDir,
3721
+ staticIndex: hasStaticIndex(clientDir)
3722
+ };
3723
+ }
3724
+ function createDefaultCloudflareStaticOutputDir(rootDir) {
3725
+ return resolve(rootDir, "dist", "client");
3726
+ }
3727
+ function resolveProviderOutputOwnershipFile(outputRoot, fileName) {
3728
+ if (!fileName || fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") throw new TypeError(`Invalid Provider Output ownership file name: ${JSON.stringify(fileName)}`);
3729
+ return resolve(outputRoot, fileName);
3730
+ }
3731
+ async function readProviderOutputOwnershipFile(outputRoot, fileName) {
3732
+ try {
3733
+ const parsed = JSON.parse(await readFile(resolveProviderOutputOwnershipFile(outputRoot, fileName), "utf8"));
3734
+ if (!Array.isArray(parsed) || !parsed.every((value) => typeof value === "string")) throw new TypeError(`Invalid Provider Output ownership file schema: ${JSON.stringify(fileName)}`);
3735
+ return parsed;
3736
+ } catch (error) {
3737
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return [];
3738
+ throw error;
3739
+ }
3740
+ }
3741
+ async function readCloudflareProviderDeploymentOutputState(rootDir, options) {
3742
+ const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(rootDir);
3743
+ let wranglerConfig = {};
3744
+ try {
3745
+ wranglerConfig = JSON.parse(await readFile(resolve(outputRoot, "wrangler.json"), "utf8"));
3746
+ } catch (error) {
3747
+ if (error.code !== "ENOENT") throw error;
3748
+ }
3749
+ return {
3750
+ wranglerConfig,
3751
+ wranglerConfigOwnership: await resolvePersistedProviderOutputOwnership(outputRoot, options.wranglerConfigOwnership, options.wranglerConfigOwnershipFiles)
3752
+ };
3753
+ }
3754
+ async function resolvePersistedProviderOutputOwnership(outputRoot, ownership, files) {
3755
+ if (!files || !Object.keys(files).length) return ownership;
3756
+ const arrays = { ...ownership?.arrays };
3757
+ await Promise.all(Object.entries(files).map(async ([field, fileName]) => {
3758
+ const current = arrays[field];
3759
+ if (!current) throw new TypeError(`Provider Output ownership file for ${JSON.stringify(field)} requires array ownership.`);
3760
+ arrays[field] = {
3761
+ ...current,
3762
+ values: [...await readProviderOutputOwnershipFile(outputRoot, fileName), ...current.values ?? []]
3763
+ };
3764
+ }));
3765
+ return {
3766
+ ...ownership,
3767
+ arrays
3768
+ };
3769
+ }
3770
+ async function writeProviderOutputOwnershipFiles(outputRoot, ownership, files) {
3771
+ await Promise.all(Object.entries(files ?? {}).map(async ([field, fileName]) => {
3772
+ const file = resolveProviderOutputOwnershipFile(outputRoot, fileName);
3773
+ const values = [...new Set(ownership?.arrays?.[field]?.values ?? [])];
3774
+ if (!values.length) {
3775
+ await rm(file, { force: true });
3776
+ return;
3777
+ }
3778
+ await mkdir(outputRoot, { recursive: true });
3779
+ await writeFile(file, `${JSON.stringify(values, null, 2)}\n`, "utf8");
3780
+ }));
3781
+ }
3782
+ function createDefaultVercelOutputRoot(rootDir) {
3783
+ return resolve(rootDir, ".vercel", "output");
3784
+ }
3785
+ function createDefaultNetlifyOutputRoot(rootDir) {
3786
+ return resolve(rootDir, ".netlify", "v1");
3787
+ }
3788
+ function assertNetlifyFunctionName(functionName) {
3789
+ if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw new Error(`Invalid Netlify function name: ${functionName}`);
3790
+ }
3791
+ function resolveNetlifyFunctionFile(functionsRoot, functionName) {
3792
+ assertNetlifyFunctionName(functionName);
3793
+ return resolve(functionsRoot, `${functionName}.mjs`);
3794
+ }
3795
+ async function appendNetlifyFunctionConfig(outfile, config) {
3796
+ if (!config) return;
3797
+ await writeFile(outfile, `${(await readFile(outfile, "utf8")).trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
3798
+ }
3799
+ async function writeCloudflareDeploymentOutput(options, signal) {
3800
+ signal?.throwIfAborted();
3801
+ const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
3802
+ const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
3803
+ const staticOutputDir = options.staticOutputDir ?? createDefaultCloudflareStaticOutputDir(options.rootDir);
3804
+ const copiesStaticOutput = Boolean(options.bundleEntry && staticIndex && resolve(clientDir) !== resolve(staticOutputDir));
3805
+ const files = Object.entries(options.files ?? {});
3806
+ const workerOutfile = options.bundleEntry ? resolve(outputRoot, options.bundleOutfileName ?? "index.js") : void 0;
3166
3807
  if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw new Error(`Cloudflare output file conflicts with bundle outfile: ${workerOutfile}`);
3167
- await mkdir(outputRoot, { recursive: true });
3168
- const writes = [
3169
- writeCloudflareWranglerConfig({
3170
- outputRoot,
3171
- rootDir: options.rootDir,
3172
- wranglerConfig: options.wranglerConfig,
3173
- wranglerConfigOwnership: options.wranglerConfigOwnership ?? { keys: options.wranglerConfigKeys }
3174
- }),
3175
- options.bundleEntry && staticIndex ? copyClientOutput(clientDir, options.staticOutputDir ?? createDefaultCloudflareStaticOutputDir(options.rootDir)) : Promise.resolve(),
3176
- ...files.map(([fileName, contents]) => writeFile(resolve(outputRoot, fileName), contents, "utf8"))
3177
- ];
3178
- if (options.bundleEntry && workerOutfile) {
3179
- await rm(workerOutfile, {
3808
+ const backupRoot = copiesStaticOutput ? await mkdtemp(resolve(options.rootDir, ".vitehub-cloudflare-output-")) : void 0;
3809
+ const previousOutputRoot = backupRoot ? resolve(backupRoot, "output") : `${outputRoot}.previous`;
3810
+ const previousStaticOutputDir = backupRoot ? resolve(backupRoot, "static") : `${staticOutputDir}.previous`;
3811
+ if (!backupRoot) await rm(previousOutputRoot, {
3812
+ force: true,
3813
+ recursive: true
3814
+ });
3815
+ if (copiesStaticOutput && !backupRoot) await rm(previousStaticOutputDir, {
3816
+ force: true,
3817
+ recursive: true
3818
+ });
3819
+ let hadPreviousOutput = false;
3820
+ let hadPreviousStaticOutput = false;
3821
+ let publicationSucceeded = false;
3822
+ let publicationStarted = false;
3823
+ let outputRestorationSucceeded = false;
3824
+ let staticRestorationSucceeded = false;
3825
+ try {
3826
+ try {
3827
+ await cp(outputRoot, previousOutputRoot, { recursive: true });
3828
+ hadPreviousOutput = true;
3829
+ } catch (error) {
3830
+ if (error.code !== "ENOENT") throw error;
3831
+ }
3832
+ if (copiesStaticOutput) try {
3833
+ await cp(staticOutputDir, previousStaticOutputDir, { recursive: true });
3834
+ hadPreviousStaticOutput = true;
3835
+ } catch (error) {
3836
+ if (error.code !== "ENOENT") throw error;
3837
+ }
3838
+ publicationStarted = true;
3839
+ await mkdir(outputRoot, { recursive: true });
3840
+ const wranglerConfigOwnership = await resolvePersistedProviderOutputOwnership(outputRoot, options.wranglerConfigOwnership ?? { keys: options.wranglerConfigKeys }, options.wranglerConfigOwnershipFiles);
3841
+ const writes = [
3842
+ writeCloudflareWranglerConfig({
3843
+ outputRoot,
3844
+ rootDir: options.rootDir,
3845
+ wranglerConfig: options.wranglerConfig,
3846
+ wranglerConfigDefaults: options.wranglerConfigDefaults,
3847
+ wranglerConfigOwnership
3848
+ }),
3849
+ options.bundleEntry && staticIndex ? copyClientOutput(clientDir, staticOutputDir) : Promise.resolve(),
3850
+ ...files.map(([fileName, contents]) => writeFile(resolve(outputRoot, fileName), contents, "utf8"))
3851
+ ];
3852
+ if (options.bundleEntry && workerOutfile) {
3853
+ const stagedWorkerOutfile = `${workerOutfile}.pending`;
3854
+ writes.push((async () => {
3855
+ try {
3856
+ await rm(stagedWorkerOutfile, {
3857
+ force: true,
3858
+ recursive: true
3859
+ });
3860
+ await bundleEsmEntry(options.bundleEntry, stagedWorkerOutfile, {
3861
+ ...options.bundleOptions,
3862
+ rootDir: options.sourceRootDir ?? options.rootDir,
3863
+ signal
3864
+ });
3865
+ signal?.throwIfAborted();
3866
+ await rename(stagedWorkerOutfile, workerOutfile);
3867
+ } catch (error) {
3868
+ await rm(stagedWorkerOutfile, {
3869
+ force: true,
3870
+ recursive: true
3871
+ });
3872
+ throw error;
3873
+ }
3874
+ })());
3875
+ }
3876
+ await settleWrites(writes);
3877
+ await writeProviderOutputOwnershipFiles(outputRoot, options.wranglerConfigOwnership, options.wranglerConfigOwnershipFiles);
3878
+ signal?.throwIfAborted();
3879
+ publicationSucceeded = true;
3880
+ } catch (error) {
3881
+ if (publicationStarted) {
3882
+ await rm(outputRoot, {
3883
+ force: true,
3884
+ recursive: true
3885
+ });
3886
+ if (hadPreviousOutput) {
3887
+ await cp(previousOutputRoot, outputRoot, { recursive: true });
3888
+ outputRestorationSucceeded = true;
3889
+ }
3890
+ if (copiesStaticOutput) {
3891
+ await rm(staticOutputDir, {
3892
+ force: true,
3893
+ recursive: true
3894
+ });
3895
+ if (hadPreviousStaticOutput) {
3896
+ await cp(previousStaticOutputDir, staticOutputDir, { recursive: true });
3897
+ staticRestorationSucceeded = true;
3898
+ }
3899
+ }
3900
+ }
3901
+ throw error;
3902
+ } finally {
3903
+ if (!publicationStarted || publicationSucceeded || outputRestorationSucceeded || !hadPreviousOutput) await rm(previousOutputRoot, {
3180
3904
  force: true,
3181
3905
  recursive: true
3182
- });
3183
- writes.push(bundleEsmEntry(options.bundleEntry, workerOutfile, {
3184
- ...options.bundleOptions,
3185
- rootDir: options.rootDir
3186
- }));
3906
+ }).catch(() => void 0);
3907
+ if (copiesStaticOutput && (!publicationStarted || publicationSucceeded || staticRestorationSucceeded || !hadPreviousStaticOutput)) await rm(previousStaticOutputDir, {
3908
+ force: true,
3909
+ recursive: true
3910
+ }).catch(() => void 0);
3911
+ if (backupRoot) await rmdir(backupRoot).catch(() => void 0);
3187
3912
  }
3188
- await Promise.all(writes);
3189
3913
  }
3190
- async function writeVercelDeploymentOutput(options) {
3914
+ async function copyVercelClientOutput(rootDir, clientDir, staticOutputDir) {
3915
+ const cloudflareOutputRoot = createDefaultCloudflareOutputRoot(rootDir);
3916
+ const outputRelativePath = relative(clientDir, cloudflareOutputRoot);
3917
+ const excludesCloudflareOutput = outputRelativePath && outputRelativePath !== ".." && !outputRelativePath.startsWith(`..${sep}`) && !isAbsolute(outputRelativePath);
3918
+ await copyClientOutput(clientDir, staticOutputDir);
3919
+ if (resolve(clientDir) === resolve(staticOutputDir) || !excludesCloudflareOutput) return;
3920
+ try {
3921
+ await readFile(resolve(cloudflareOutputRoot, "wrangler.json"));
3922
+ } catch (error) {
3923
+ if (error.code === "ENOENT") return;
3924
+ throw error;
3925
+ }
3926
+ await rm(resolve(staticOutputDir, outputRelativePath), {
3927
+ force: true,
3928
+ recursive: true
3929
+ });
3930
+ }
3931
+ async function writeVercelDeploymentOutput(options, signal) {
3932
+ signal?.throwIfAborted();
3191
3933
  const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
3192
3934
  const outputRoot = options.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir);
3935
+ const stagedOutputRoot = `${outputRoot}.pending`;
3936
+ const previousOutputRoot = `${outputRoot}.previous`;
3193
3937
  const functionOutput = options.function ?? { kind: "root" };
3194
3938
  const serverFunctionName = functionOutput.kind === "root" ? "__server.func" : functionOutput.name;
3195
3939
  const config = options.config ?? (functionOutput.kind === "root" ? createVercelConfigJson() : {});
3196
- const serverDir = resolve(outputRoot, "functions", serverFunctionName);
3940
+ const serverDir = resolve(stagedOutputRoot, "functions", serverFunctionName);
3197
3941
  const serverEntry = resolve(serverDir, "index.mjs");
3198
- await mkdir(serverDir, { recursive: true });
3199
- const staleFiles = (await readdir(serverDir)).filter((file) => file !== "node_modules");
3200
- await Promise.all(staleFiles.map((file) => rm(resolve(serverDir, file), {
3201
- force: true,
3202
- recursive: true
3203
- })));
3204
- await Promise.all([
3205
- bundleEsmEntry(options.bundleEntry, serverEntry, {
3942
+ const staticOutputDir = options.staticOutputDir ?? resolve(outputRoot, "static");
3943
+ const staticRelativePath = relative(outputRoot, staticOutputDir);
3944
+ const staticInsideOutputRoot = !staticRelativePath.startsWith(`..${sep}`) && !isAbsolute(staticRelativePath);
3945
+ const externalStaticNeedsCommit = staticIndex && !staticInsideOutputRoot && resolve(clientDir) !== resolve(staticOutputDir);
3946
+ const stagedStaticOutputDir = staticInsideOutputRoot ? resolve(stagedOutputRoot, staticRelativePath) : externalStaticNeedsCommit ? `${staticOutputDir}.pending` : staticOutputDir;
3947
+ const previousStaticOutputDir = `${staticOutputDir}.previous`;
3948
+ let replacedOutput = false;
3949
+ let installedOutput = false;
3950
+ let replacedExternalStatic = false;
3951
+ let installedExternalStatic = false;
3952
+ try {
3953
+ await rm(stagedOutputRoot, {
3954
+ force: true,
3955
+ recursive: true
3956
+ });
3957
+ try {
3958
+ await cp(outputRoot, stagedOutputRoot, { recursive: true });
3959
+ } catch (error) {
3960
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
3961
+ }
3962
+ await mkdir(serverDir, { recursive: true });
3963
+ await rm(serverDir, {
3964
+ force: true,
3965
+ recursive: true
3966
+ });
3967
+ await mkdir(serverDir, { recursive: true });
3968
+ try {
3969
+ await cp(resolve(outputRoot, "functions", serverFunctionName, "node_modules"), resolve(serverDir, "node_modules"), { recursive: true });
3970
+ } catch (error) {
3971
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
3972
+ }
3973
+ await bundleEsmEntry(options.bundleEntry, serverEntry, {
3206
3974
  ...options.bundleOptions,
3207
- rootDir: options.rootDir
3208
- }),
3209
- writeFile(resolve(serverDir, ".vc-config.json"), `${stringifyProviderOutputConfig(options.functionConfig ?? createNodeFunctionConfig())}\n`, "utf8"),
3210
- writeProviderOutputConfig(resolve(outputRoot, "config.json"), config, { keys: options.configKeys }),
3211
- staticIndex ? copyClientOutput(clientDir, options.staticOutputDir ?? resolve(outputRoot, "static")) : Promise.resolve()
3212
- ]);
3975
+ rootDir: options.sourceRootDir ?? options.rootDir,
3976
+ signal
3977
+ });
3978
+ await writeFile(resolve(serverDir, ".vc-config.json"), `${stringifyProviderOutputConfig(options.functionConfig ?? createNodeFunctionConfig())}\n`, "utf8");
3979
+ const failedWrite = (await Promise.allSettled([writeProviderOutputConfig(resolve(stagedOutputRoot, "config.json"), config, { keys: options.configKeys }), staticIndex ? copyVercelClientOutput(options.rootDir, clientDir, stagedStaticOutputDir) : Promise.resolve()])).find((result) => result.status === "rejected");
3980
+ if (failedWrite?.status === "rejected") throw failedWrite.reason;
3981
+ signal?.throwIfAborted();
3982
+ rmSync(previousOutputRoot, {
3983
+ force: true,
3984
+ recursive: true
3985
+ });
3986
+ if (existsSync(outputRoot)) {
3987
+ renameSync(outputRoot, previousOutputRoot);
3988
+ replacedOutput = true;
3989
+ }
3990
+ try {
3991
+ renameSync(stagedOutputRoot, outputRoot);
3992
+ installedOutput = true;
3993
+ } catch (error) {
3994
+ if (replacedOutput && existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
3995
+ replacedOutput = false;
3996
+ throw error;
3997
+ }
3998
+ signal?.throwIfAborted();
3999
+ if (externalStaticNeedsCommit) {
4000
+ rmSync(previousStaticOutputDir, {
4001
+ force: true,
4002
+ recursive: true
4003
+ });
4004
+ if (existsSync(staticOutputDir)) {
4005
+ renameSync(staticOutputDir, previousStaticOutputDir);
4006
+ replacedExternalStatic = true;
4007
+ }
4008
+ try {
4009
+ renameSync(stagedStaticOutputDir, staticOutputDir);
4010
+ installedExternalStatic = true;
4011
+ } catch (error) {
4012
+ if (replacedExternalStatic && existsSync(previousStaticOutputDir)) renameSync(previousStaticOutputDir, staticOutputDir);
4013
+ replacedExternalStatic = false;
4014
+ throw error;
4015
+ }
4016
+ signal?.throwIfAborted();
4017
+ }
4018
+ try {
4019
+ rmSync(previousOutputRoot, {
4020
+ force: true,
4021
+ recursive: true
4022
+ });
4023
+ } catch {}
4024
+ if (replacedExternalStatic) try {
4025
+ rmSync(previousStaticOutputDir, {
4026
+ force: true,
4027
+ recursive: true
4028
+ });
4029
+ } catch {}
4030
+ } catch (error) {
4031
+ await rm(stagedOutputRoot, {
4032
+ force: true,
4033
+ recursive: true
4034
+ });
4035
+ if (externalStaticNeedsCommit) await rm(stagedStaticOutputDir, {
4036
+ force: true,
4037
+ recursive: true
4038
+ });
4039
+ if (installedExternalStatic) rmSync(staticOutputDir, {
4040
+ force: true,
4041
+ recursive: true
4042
+ });
4043
+ if (replacedExternalStatic) {
4044
+ if (existsSync(previousStaticOutputDir)) renameSync(previousStaticOutputDir, staticOutputDir);
4045
+ }
4046
+ if (installedOutput) rmSync(outputRoot, {
4047
+ force: true,
4048
+ recursive: true
4049
+ });
4050
+ if (replacedOutput) {
4051
+ if (existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
4052
+ }
4053
+ throw error;
4054
+ }
3213
4055
  }
3214
- async function writeNetlifyDeploymentOutput(options) {
4056
+ async function writeNetlifyDeploymentOutput(options, signal) {
4057
+ signal?.throwIfAborted();
3215
4058
  const outputRoot = options.outputRoot ?? createDefaultNetlifyOutputRoot(options.rootDir);
3216
- const functionsRoot = resolve(outputRoot, "functions");
4059
+ const stagedOutputRoot = `${outputRoot}.pending`;
4060
+ const previousOutputRoot = `${outputRoot}.previous`;
4061
+ const functionsRoot = resolve(stagedOutputRoot, "functions");
4062
+ let replacedOutput = false;
4063
+ let installedOutput = false;
4064
+ await rm(stagedOutputRoot, {
4065
+ force: true,
4066
+ recursive: true
4067
+ });
4068
+ await rm(previousOutputRoot, {
4069
+ force: true,
4070
+ recursive: true
4071
+ });
4072
+ try {
4073
+ await cp(outputRoot, stagedOutputRoot, { recursive: true });
4074
+ } catch (error) {
4075
+ if (error.code !== "ENOENT") throw error;
4076
+ }
3217
4077
  const functionWrites = (options.functions ?? []).map(async (func) => {
3218
4078
  const outfile = resolveNetlifyFunctionFile(functionsRoot, func.functionName);
3219
- await rm(outfile, {
3220
- force: true,
3221
- recursive: true
3222
- });
3223
4079
  await mkdir(dirname(outfile), { recursive: true });
3224
4080
  await bundleEsmEntry(func.bundleEntry, outfile, {
3225
4081
  ...func.bundleOptions,
3226
4082
  minifyIdentifiers: func.config ? true : func.bundleOptions.minifyIdentifiers,
3227
- rootDir: options.rootDir
4083
+ rootDir: options.sourceRootDir ?? options.rootDir,
4084
+ signal
3228
4085
  });
3229
4086
  await appendNetlifyFunctionConfig(outfile, func.config);
3230
4087
  });
3231
- await mkdir(outputRoot, { recursive: true });
3232
- await Promise.all([writeProviderOutputConfig(resolve(outputRoot, "config.json"), options.config ?? {}, { keys: options.configKeys }), ...functionWrites]);
4088
+ try {
4089
+ await mkdir(stagedOutputRoot, { recursive: true });
4090
+ await settleWrites([writeProviderOutputConfig(resolve(stagedOutputRoot, "config.json"), options.config ?? {}, { keys: options.configKeys }), ...functionWrites]);
4091
+ signal?.throwIfAborted();
4092
+ if (existsSync(outputRoot)) {
4093
+ renameSync(outputRoot, previousOutputRoot);
4094
+ replacedOutput = true;
4095
+ }
4096
+ renameSync(stagedOutputRoot, outputRoot);
4097
+ installedOutput = true;
4098
+ signal?.throwIfAborted();
4099
+ } catch (error) {
4100
+ await rm(stagedOutputRoot, {
4101
+ force: true,
4102
+ recursive: true
4103
+ });
4104
+ if (installedOutput) rmSync(outputRoot, {
4105
+ force: true,
4106
+ recursive: true
4107
+ });
4108
+ if (replacedOutput && existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
4109
+ throw error;
4110
+ }
4111
+ try {
4112
+ rmSync(previousOutputRoot, {
4113
+ force: true,
4114
+ recursive: true
4115
+ });
4116
+ } catch {}
3233
4117
  }
3234
- async function cleanupCloudflareDeploymentOutput(rootDir, cleanupInput) {
4118
+ async function cleanupCloudflareDeploymentOutput(rootDir, cleanupInput, signal) {
3235
4119
  const cleanup = typeof cleanupInput === "function" ? await cleanupInput() : cleanupInput;
4120
+ signal?.throwIfAborted();
3236
4121
  const outputRoot = cleanup.outputRoot ?? createDefaultCloudflareOutputRoot(rootDir);
4122
+ if (!shouldRunCloudflareDeploymentOutputCleanup(outputRoot, cleanup)) return;
4123
+ const wranglerConfigOwnership = await resolvePersistedProviderOutputOwnership(outputRoot, cleanup.wranglerConfigOwnership, cleanup.wranglerConfigOwnershipFiles);
3237
4124
  const writes = (cleanup.fileNames ?? []).map((fileName) => rm(resolve(outputRoot, fileName), {
3238
4125
  force: true,
3239
4126
  recursive: true
@@ -3241,9 +4128,10 @@ async function cleanupCloudflareDeploymentOutput(rootDir, cleanupInput) {
3241
4128
  writes.push(writeCloudflareWranglerConfig({
3242
4129
  outputRoot,
3243
4130
  rootDir,
3244
- wranglerConfigOwnership: cleanup.wranglerConfigOwnership
4131
+ wranglerConfigOwnership
3245
4132
  }));
3246
4133
  await Promise.all(writes);
4134
+ await writeProviderOutputOwnershipFiles(outputRoot, cleanup.wranglerConfigOwnership, cleanup.wranglerConfigOwnershipFiles);
3247
4135
  try {
3248
4136
  await rmdir(outputRoot);
3249
4137
  } catch (error) {
@@ -3251,7 +4139,11 @@ async function cleanupCloudflareDeploymentOutput(rootDir, cleanupInput) {
3251
4139
  if (code !== "ENOENT" && code !== "ENOTEMPTY") throw error;
3252
4140
  }
3253
4141
  }
3254
- async function cleanupVercelDeploymentOutput(rootDir, cleanup) {
4142
+ function shouldRunCloudflareDeploymentOutputCleanup(outputRoot, cleanup) {
4143
+ return !cleanup.requirePersistedOwnership || Object.values(cleanup.wranglerConfigOwnershipFiles ?? {}).some((fileName) => existsSync(resolveProviderOutputOwnershipFile(outputRoot, fileName)));
4144
+ }
4145
+ async function cleanupVercelDeploymentOutput(rootDir, cleanup, signal) {
4146
+ signal?.throwIfAborted();
3255
4147
  const outputRoot = cleanup.outputRoot ?? createDefaultVercelOutputRoot(rootDir);
3256
4148
  const writes = [];
3257
4149
  if (cleanup.serverFunctionName) writes.push(rm(resolve(outputRoot, "functions", cleanup.serverFunctionName), {
@@ -3261,10 +4153,11 @@ async function cleanupVercelDeploymentOutput(rootDir, cleanup) {
3261
4153
  writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
3262
4154
  await Promise.all(writes);
3263
4155
  }
3264
- async function cleanupVercelDeploymentOutputs(rootDir, cleanup) {
3265
- await Promise.all((Array.isArray(cleanup) ? cleanup : [cleanup]).map((item) => cleanupVercelDeploymentOutput(rootDir, item)));
4156
+ async function cleanupVercelDeploymentOutputs(rootDir, cleanup, signal) {
4157
+ await Promise.all((Array.isArray(cleanup) ? cleanup : [cleanup]).map((item) => cleanupVercelDeploymentOutput(rootDir, item, signal)));
3266
4158
  }
3267
- async function cleanupNetlifyDeploymentOutput(rootDir, cleanup) {
4159
+ async function cleanupNetlifyDeploymentOutput(rootDir, cleanup, signal) {
4160
+ signal?.throwIfAborted();
3268
4161
  const outputRoot = cleanup.outputRoot ?? createDefaultNetlifyOutputRoot(rootDir);
3269
4162
  const functionsRoot = resolve(outputRoot, "functions");
3270
4163
  const writes = (cleanup.functionNames ?? []).map((functionName) => rm(resolveNetlifyFunctionFile(functionsRoot, functionName), {
@@ -3274,42 +4167,488 @@ async function cleanupNetlifyDeploymentOutput(rootDir, cleanup) {
3274
4167
  writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
3275
4168
  await Promise.all(writes);
3276
4169
  }
3277
- async function writeProviderDeploymentOutputsNow(options) {
4170
+ async function writeProviderDeploymentOutputsNow(options, signal, transaction) {
4171
+ signal?.throwIfAborted();
4172
+ const clientDir = resolve(options.rootDir, options.clientOutDir);
4173
+ await transaction?.snapshot(providerDeploymentOutputPaths(options), [clientDir]);
3278
4174
  const writes = [];
3279
4175
  if (options.cloudflare) writes.push(writeCloudflareDeploymentOutput({
3280
4176
  ...options.cloudflare,
3281
4177
  clientOutDir: options.clientOutDir,
3282
- rootDir: options.rootDir
3283
- }));
3284
- else if (options.cleanup?.cloudflare) writes.push(cleanupCloudflareDeploymentOutput(options.rootDir, options.cleanup.cloudflare));
4178
+ rootDir: options.rootDir,
4179
+ sourceRootDir: options.sourceRootDir
4180
+ }, signal));
3285
4181
  if (options.netlify) writes.push(writeNetlifyDeploymentOutput({
3286
4182
  ...options.netlify,
3287
4183
  clientOutDir: options.clientOutDir,
3288
- rootDir: options.rootDir
3289
- }));
3290
- else if (options.cleanup?.netlify) writes.push(cleanupNetlifyDeploymentOutput(options.rootDir, options.cleanup.netlify));
4184
+ rootDir: options.rootDir,
4185
+ sourceRootDir: options.sourceRootDir
4186
+ }, signal));
3291
4187
  if (options.vercel) writes.push(writeVercelDeploymentOutput({
3292
4188
  ...options.vercel,
3293
4189
  clientOutDir: options.clientOutDir,
3294
- rootDir: options.rootDir
3295
- }));
3296
- else if (options.cleanup?.vercel) {
4190
+ rootDir: options.rootDir,
4191
+ sourceRootDir: options.sourceRootDir
4192
+ }, signal));
4193
+ await settleWrites(writes);
4194
+ if (options.cloudflare && transaction) transaction.cloudflareWritten = true;
4195
+ signal?.throwIfAborted();
4196
+ await options.afterWrite?.(signal);
4197
+ signal?.throwIfAborted();
4198
+ const cleanups = [];
4199
+ const cleanupPaths = [];
4200
+ if (!options.cloudflare && options.cleanup?.cloudflare) {
4201
+ let cleanup = typeof options.cleanup.cloudflare === "function" ? await options.cleanup.cloudflare() : options.cleanup.cloudflare;
4202
+ const outputRoot = cleanup.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
4203
+ if (resolve(outputRoot) === clientDir) cleanup = {
4204
+ ...cleanup,
4205
+ fileNames: []
4206
+ };
4207
+ else if (transaction?.cloudflareWritten) cleanup = {
4208
+ ...cleanup,
4209
+ fileNames: []
4210
+ };
4211
+ if (shouldRunCloudflareDeploymentOutputCleanup(outputRoot, cleanup)) {
4212
+ cleanupPaths.push(outputRoot);
4213
+ cleanups.push(async () => await cleanupCloudflareDeploymentOutput(options.rootDir, cleanup, signal));
4214
+ }
4215
+ }
4216
+ if (!options.netlify && options.cleanup?.netlify) {
4217
+ const cleanup = options.cleanup.netlify;
4218
+ cleanupPaths.push(cleanup.outputRoot ?? createDefaultNetlifyOutputRoot(options.rootDir));
4219
+ cleanups.push(async () => await cleanupNetlifyDeploymentOutput(options.rootDir, cleanup, signal));
4220
+ }
4221
+ if (!options.vercel && options.cleanup?.vercel) {
3297
4222
  const cleanup = typeof options.cleanup.vercel === "function" ? await options.cleanup.vercel() : options.cleanup.vercel;
3298
- if (cleanup) writes.push(cleanupVercelDeploymentOutputs(options.rootDir, cleanup));
4223
+ signal?.throwIfAborted();
4224
+ if (cleanup) {
4225
+ const items = Array.isArray(cleanup) ? cleanup : [cleanup];
4226
+ cleanupPaths.push(...items.map((item) => item.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir)));
4227
+ cleanups.push(async () => await cleanupVercelDeploymentOutputs(options.rootDir, cleanup, signal));
4228
+ }
3299
4229
  }
3300
- await Promise.all(writes);
3301
- await options.afterWrite?.();
4230
+ await transaction?.snapshot(cleanupPaths, [clientDir]);
4231
+ await settleWrites(cleanups.map((cleanup) => cleanup()));
4232
+ signal?.throwIfAborted();
3302
4233
  }
3303
- async function writeProviderDeploymentOutputs(options) {
3304
- const key = resolve(options.rootDir);
3305
- const write = (providerDeploymentOutputWrites.get(key) ?? Promise.resolve()).catch(() => void 0).then(() => writeProviderDeploymentOutputsNow(options));
3306
- providerDeploymentOutputWrites.set(key, write);
4234
+ function providerDeploymentOutputPaths(options) {
4235
+ const clientDir = resolve(options.rootDir, options.clientOutDir);
4236
+ return [
4237
+ options.cloudflare && (options.cloudflare.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir)),
4238
+ options.cloudflare?.staticOutputDir,
4239
+ options.netlify?.outputRoot,
4240
+ options.vercel?.outputRoot,
4241
+ options.vercel?.staticOutputDir
4242
+ ].filter((path) => Boolean(path) && resolve(path) !== clientDir);
4243
+ }
4244
+ async function withProviderDeploymentOutputRootLock(rootDir, operation) {
4245
+ const key = resolve(rootDir);
4246
+ const state = providerDeploymentOutputRootStates.get(key) ?? { pending: 0 };
4247
+ providerDeploymentOutputRootStates.set(key, state);
4248
+ state.pending++;
4249
+ const current = (providerDeploymentOutputWrites.get(key) ?? Promise.resolve()).catch(() => void 0).then(async () => await operation(state));
4250
+ providerDeploymentOutputWrites.set(key, current);
4251
+ try {
4252
+ return await current;
4253
+ } finally {
4254
+ if (providerDeploymentOutputWrites.get(key) === current) providerDeploymentOutputWrites.delete(key);
4255
+ state.pending--;
4256
+ if (state.pending === 0 && providerDeploymentOutputRootStates.get(key) === state) providerDeploymentOutputRootStates.delete(key);
4257
+ }
4258
+ }
4259
+ function pathContains(parent, child) {
4260
+ const nested = relative(parent, child);
4261
+ return !nested || !nested.startsWith(`..${sep}`) && nested !== ".." && !isAbsolute(nested);
4262
+ }
4263
+ async function restoreProviderDeploymentOutputSnapshot(snapshot) {
4264
+ if (snapshot.present) await mkdir(dirname(snapshot.path), { recursive: true });
4265
+ const restoreRoot = await mkdtemp(resolve(snapshot.present ? dirname(snapshot.path) : tmpdir(), "vitehub-provider-output-restore-"));
4266
+ const staged = resolve(restoreRoot, "snapshot");
4267
+ const preservedRoot = resolve(restoreRoot, "preserved");
4268
+ try {
4269
+ await mkdir(preservedRoot, { recursive: true });
4270
+ const preserved = snapshot.preservedPaths.map((path, index) => ({
4271
+ backup: resolve(preservedRoot, String(index)),
4272
+ path,
4273
+ present: existsSync(path)
4274
+ }));
4275
+ await Promise.all(preserved.map(async (entry) => {
4276
+ if (entry.present) await cp(entry.path, entry.backup, { recursive: true });
4277
+ }));
4278
+ if (snapshot.present) await cp(snapshot.backup, staged, { recursive: true });
4279
+ await rm(snapshot.path, {
4280
+ force: true,
4281
+ recursive: true
4282
+ });
4283
+ if (snapshot.present) await rename(staged, snapshot.path);
4284
+ for (const entry of preserved) {
4285
+ await rm(entry.path, {
4286
+ force: true,
4287
+ recursive: true
4288
+ });
4289
+ if (entry.present) {
4290
+ await mkdir(dirname(entry.path), { recursive: true });
4291
+ await cp(entry.backup, entry.path, { recursive: true });
4292
+ }
4293
+ }
4294
+ } finally {
4295
+ await rm(restoreRoot, {
4296
+ force: true,
4297
+ recursive: true
4298
+ });
4299
+ }
4300
+ }
4301
+ async function withProviderDeploymentOutputRootTransaction(rootDir, operation, options = {}) {
4302
+ const roots = [
4303
+ createDefaultCloudflareOutputRoot(rootDir),
4304
+ createDefaultNetlifyOutputRoot(rootDir),
4305
+ createDefaultVercelOutputRoot(rootDir),
4306
+ resolve(rootDir, ".vitehub/agent"),
4307
+ resolve(rootDir, ".vitehub/blob/cloudflare-output.json"),
4308
+ resolve(rootDir, ".vitehub/queue/cloudflare-output.json"),
4309
+ resolve(rootDir, ".vitehub/queue/registry.mjs"),
4310
+ resolve(rootDir, ".vitehub/queue/vercel-output.json"),
4311
+ resolve(rootDir, ".vitehub/rate-limit/cloudflare-output.json"),
4312
+ resolve(rootDir, ".vitehub/rate-limit/manifest.json"),
4313
+ resolve(rootDir, ".vitehub/schedule"),
4314
+ resolve(rootDir, ".vitehub/workflow")
4315
+ ];
4316
+ const transactionRoot = await mkdtemp(resolve(tmpdir(), "vitehub-provider-output-"));
4317
+ const snapshots = /* @__PURE__ */ new Map();
4318
+ let snapshotIndex = 0;
4319
+ const transaction = {
4320
+ cloudflareWritten: false,
4321
+ async snapshot(paths, preservedPaths = []) {
4322
+ const resolvedPreservedPaths = [...new Set(preservedPaths.map((path) => resolve(path)))];
4323
+ for (const snapshot of snapshots.values()) {
4324
+ const additions = resolvedPreservedPaths.filter((path) => path !== snapshot.path && pathContains(snapshot.path, path) && !snapshot.preservedPaths.includes(path));
4325
+ snapshot.preservedPaths.push(...additions);
4326
+ if (snapshot.present) await Promise.all(additions.map((path) => rm(resolve(snapshot.backup, relative(snapshot.path, path)), {
4327
+ force: true,
4328
+ recursive: true
4329
+ })));
4330
+ }
4331
+ const pending = [...new Set(paths.map((path) => resolve(path)))].sort((left, right) => left.length - right.length).filter((path, index, all) => !all.slice(0, index).some((parent) => pathContains(parent, path))).filter((path) => ![...snapshots.keys()].some((parent) => pathContains(parent, path))).map((path) => ({
4332
+ backup: resolve(transactionRoot, String(snapshotIndex++)),
4333
+ path,
4334
+ present: existsSync(path),
4335
+ preservedPaths: resolvedPreservedPaths.filter((preserved) => preserved !== path && pathContains(path, preserved))
4336
+ }));
4337
+ const failure = (await Promise.allSettled(pending.map(async (snapshot) => {
4338
+ if (snapshot.present) {
4339
+ await cp(snapshot.path, snapshot.backup, { recursive: true });
4340
+ await Promise.all(snapshot.preservedPaths.map((path) => rm(resolve(snapshot.backup, relative(snapshot.path, path)), {
4341
+ force: true,
4342
+ recursive: true
4343
+ })));
4344
+ }
4345
+ }))).find((result) => result.status === "rejected");
4346
+ if (failure) {
4347
+ await Promise.all(pending.map((snapshot) => rm(snapshot.backup, {
4348
+ force: true,
4349
+ recursive: true
4350
+ })));
4351
+ throw failure.reason;
4352
+ }
4353
+ for (const snapshot of pending) {
4354
+ const children = [...snapshots.values()].filter((child) => pathContains(snapshot.path, child.path));
4355
+ if (snapshot.present) for (const child of children) {
4356
+ const nestedBackup = resolve(snapshot.backup, relative(snapshot.path, child.path));
4357
+ await rm(nestedBackup, {
4358
+ force: true,
4359
+ recursive: true
4360
+ });
4361
+ if (child.present) {
4362
+ await mkdir(dirname(nestedBackup), { recursive: true });
4363
+ await cp(child.backup, nestedBackup, { recursive: true });
4364
+ }
4365
+ }
4366
+ for (const child of children) {
4367
+ snapshots.delete(child.path);
4368
+ await rm(child.backup, {
4369
+ force: true,
4370
+ recursive: true
4371
+ });
4372
+ }
4373
+ snapshot.preservedPaths.push(...children.flatMap((child) => child.preservedPaths).filter((path) => !snapshot.preservedPaths.includes(path)));
4374
+ if (snapshot.present) await Promise.all(snapshot.preservedPaths.map((path) => rm(resolve(snapshot.backup, relative(snapshot.path, path)), {
4375
+ force: true,
4376
+ recursive: true
4377
+ })));
4378
+ snapshots.set(snapshot.path, snapshot);
4379
+ }
4380
+ }
4381
+ };
4382
+ try {
4383
+ if (options.snapshotInitialRoots !== false) await transaction.snapshot(roots);
4384
+ const result = await operation(transaction);
4385
+ await removeProviderOutputArtifactDir(transactionRoot).catch(() => void 0);
4386
+ return result;
4387
+ } catch (error) {
4388
+ const restorations = await Promise.allSettled([...snapshots.values()].map(restoreProviderDeploymentOutputSnapshot));
4389
+ if (restorations.every((result) => result.status === "fulfilled")) await rm(transactionRoot, {
4390
+ force: true,
4391
+ recursive: true
4392
+ });
4393
+ const restorationFailure = restorations.find((result) => result.status === "rejected");
4394
+ if (restorationFailure) throw new AggregateError([error, restorationFailure.reason], "Provider Output rollback failed");
4395
+ throw error;
4396
+ }
4397
+ }
4398
+ function contributeProviderDeploymentOutput(catalog, contribution, generation) {
4399
+ closeProviderDeploymentOutputGenerationCapture(generation);
4400
+ catalog?.replaceDeploymentContribution(contribution, generation);
4401
+ }
4402
+ const providerDeploymentOutputEnvironmentGenerations = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputEnvironmentGenerations ??= /* @__PURE__ */ new WeakMap();
4403
+ const providerDeploymentOutputGenerationEnvironments = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputGenerationEnvironments ??= /* @__PURE__ */ new WeakMap();
4404
+ const providerDeploymentOutputFallbackEnvironment = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputFallbackEnvironment ??= {};
4405
+ function closeProviderDeploymentOutputGenerationCapture(generation) {
4406
+ if (!generation) return;
4407
+ const captured = providerDeploymentOutputGenerationEnvironments.get(generation);
4408
+ if (!captured) return;
4409
+ const generations = providerDeploymentOutputEnvironmentGenerations.get(captured.catalog);
4410
+ if (generations?.get(captured.environment) === generation) generations.delete(captured.environment);
4411
+ providerDeploymentOutputGenerationEnvironments.delete(generation);
4412
+ }
4413
+ function createProviderDeploymentOutputGenerationState() {
4414
+ const generations = /* @__PURE__ */ new WeakMap();
4415
+ const readiness = /* @__PURE__ */ new WeakMap();
4416
+ const localEnvironment = (context) => context?.environment ?? context ?? providerDeploymentOutputFallbackEnvironment;
4417
+ const sharedEnvironment = (context) => context?.environment ?? providerDeploymentOutputFallbackEnvironment;
4418
+ return {
4419
+ capture(context, catalog) {
4420
+ const localEnvironmentKey = localEnvironment(context);
4421
+ readiness.delete(localEnvironmentKey);
4422
+ if (!catalog) {
4423
+ generations.set(localEnvironmentKey, void 0);
4424
+ return;
4425
+ }
4426
+ const environmentKey = sharedEnvironment(context);
4427
+ let catalogGenerations = providerDeploymentOutputEnvironmentGenerations.get(catalog);
4428
+ if (!catalogGenerations) {
4429
+ catalogGenerations = /* @__PURE__ */ new WeakMap();
4430
+ providerDeploymentOutputEnvironmentGenerations.set(catalog, catalogGenerations);
4431
+ }
4432
+ const sharedGeneration = catalogGenerations.get(environmentKey);
4433
+ const generation = !sharedGeneration || generations.get(localEnvironmentKey) === sharedGeneration ? catalog.createDeploymentGeneration() : sharedGeneration;
4434
+ catalogGenerations.set(environmentKey, generation);
4435
+ providerDeploymentOutputGenerationEnvironments.set(generation, {
4436
+ catalog,
4437
+ environment: environmentKey
4438
+ });
4439
+ generations.set(localEnvironmentKey, generation);
4440
+ },
4441
+ defer(context, catalog, contribution) {
4442
+ const localEnvironmentKey = localEnvironment(context);
4443
+ const state = { ready: false };
4444
+ readiness.set(localEnvironmentKey, state);
4445
+ contributeProviderDeploymentOutput(catalog, {
4446
+ ...contribution,
4447
+ ready: () => state.ready
4448
+ }, generations.get(localEnvironmentKey));
4449
+ },
4450
+ get(context) {
4451
+ return generations.get(localEnvironment(context));
4452
+ },
4453
+ ready(context) {
4454
+ const state = readiness.get(localEnvironment(context));
4455
+ if (state) state.ready = true;
4456
+ },
4457
+ async reset(context, catalog, failure) {
4458
+ const localEnvironmentKey = localEnvironment(context);
4459
+ const generation = generations.get(localEnvironmentKey);
4460
+ readiness.delete(localEnvironmentKey);
4461
+ closeProviderDeploymentOutputGenerationCapture(generation);
4462
+ await resetProviderDeploymentOutputs(catalog, failure, generation);
4463
+ }
4464
+ };
4465
+ }
4466
+ async function resetProviderDeploymentOutputs(catalog, failure, generation) {
4467
+ if (!catalog) return;
4468
+ const completedReset = providerDeploymentOutputCompletedResets.get(catalog);
4469
+ if (completedReset && failure !== void 0 && completedReset.failures.has(failure)) {
4470
+ if (generation) catalog.resetDeploymentContributions(generation);
4471
+ await completedReset.promise;
4472
+ return;
4473
+ }
4474
+ if (completedReset) providerDeploymentOutputCompletedResets.delete(catalog);
4475
+ if (generation) catalog.resetDeploymentContributions(generation);
4476
+ const active = providerDeploymentOutputFinalizations.get(catalog);
4477
+ if (active?.reset) {
4478
+ if (failure !== void 0 && !active.reset.failures.has(failure)) {
4479
+ active.reset.failures.add(failure);
4480
+ if (!generation) catalog.resetDeploymentContributions();
4481
+ }
4482
+ providerDeploymentOutputCompletedResets.set(catalog, active.reset);
4483
+ await active.reset.promise;
4484
+ return;
4485
+ }
4486
+ if (!generation) catalog.resetDeploymentContributions();
4487
+ if (active && (!generation || active.state.generations.has(generation))) {
4488
+ active.state.rollback = true;
4489
+ active.controller.abort(/* @__PURE__ */ new Error("Provider Output finalization reset"));
4490
+ active.reset = {
4491
+ failures: new Set([failure]),
4492
+ promise: active.promise.catch(() => void 0)
4493
+ };
4494
+ providerDeploymentOutputCompletedResets.set(catalog, active.reset);
4495
+ await active.reset.promise;
4496
+ } else if (failure !== void 0) providerDeploymentOutputCompletedResets.set(catalog, {
4497
+ failures: new Set([failure]),
4498
+ promise: Promise.resolve()
4499
+ });
4500
+ }
4501
+ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
4502
+ if (!catalog) return;
4503
+ const existing = providerDeploymentOutputFinalizations.get(catalog);
4504
+ if (existing) {
4505
+ try {
4506
+ await existing.promise;
4507
+ } catch (error) {
4508
+ if (!catalog.hasDeploymentContributions()) throw error;
4509
+ existing.handoff ??= (async () => {
4510
+ await existing.promise.catch(() => void 0);
4511
+ if (providerDeploymentOutputFinalizations.get(catalog) === existing) providerDeploymentOutputFinalizations.delete(catalog);
4512
+ await finalizeProviderDeploymentOutputs(catalog, options);
4513
+ })();
4514
+ await existing.handoff;
4515
+ return;
4516
+ }
4517
+ if (providerDeploymentOutputFinalizations.get(catalog) === existing) providerDeploymentOutputFinalizations.delete(catalog);
4518
+ if (catalog.hasDeploymentContributions()) await finalizeProviderDeploymentOutputs(catalog, options);
4519
+ return;
4520
+ }
4521
+ const controller = new AbortController();
4522
+ const state = {
4523
+ generations: /* @__PURE__ */ new Set(),
4524
+ rollback: false
4525
+ };
4526
+ const finalization = (async () => {
4527
+ const order = new Map(providerDeploymentOutputOwnerOrder.map((owner, index) => [owner, index]));
4528
+ const abort = () => controller.abort(options.signal?.reason);
4529
+ if (options.signal?.aborted) abort();
4530
+ else options.signal?.addEventListener("abort", abort, { once: true });
4531
+ try {
4532
+ while (true) {
4533
+ const contributions = catalog.takeDeploymentContributions();
4534
+ if (!contributions.length) return;
4535
+ try {
4536
+ if (contributions.some((contribution) => contribution.ready?.() === false)) {
4537
+ if (controller.signal.aborted) {
4538
+ await catalog.completeDeploymentContributions(contributions);
4539
+ throwIfProviderOutputAborted(controller.signal);
4540
+ }
4541
+ catalog.rollbackDeploymentContributions(contributions);
4542
+ return;
4543
+ }
4544
+ } catch (error) {
4545
+ catalog.rollbackDeploymentContributions(contributions);
4546
+ throw error;
4547
+ }
4548
+ for (const contribution of contributions) {
4549
+ const generation = catalog.deploymentContributionGeneration(contribution);
4550
+ if (generation) state.generations.add(generation);
4551
+ }
4552
+ contributions.sort((left, right) => order.get(left.owner) - order.get(right.owner));
4553
+ const grouped = /* @__PURE__ */ new Map();
4554
+ for (const contribution of contributions) {
4555
+ const rootDir = resolve(contribution.rootDir);
4556
+ const rootContributions = grouped.get(rootDir) ?? [];
4557
+ rootContributions.push(contribution);
4558
+ grouped.set(rootDir, rootContributions);
4559
+ }
4560
+ try {
4561
+ let decideRoots;
4562
+ const rootDecision = new Promise((resolve) => {
4563
+ decideRoots = resolve;
4564
+ });
4565
+ const roots = [...grouped.entries()].map(([rootDir, rootContributions]) => {
4566
+ let ready;
4567
+ let rejectReady;
4568
+ const readiness = new Promise((resolve, reject) => {
4569
+ ready = resolve;
4570
+ rejectReady = reject;
4571
+ });
4572
+ const write = withProviderDeploymentOutputRootLock(rootDir, async () => {
4573
+ await withProviderDeploymentOutputRootTransaction(rootDir, async (transaction) => {
4574
+ try {
4575
+ for (const contribution of rootContributions) {
4576
+ throwIfProviderOutputAborted(controller.signal);
4577
+ await contribution.write({
4578
+ readCloudflareState: async (options) => await readCloudflareProviderDeploymentOutputState(rootDir, options),
4579
+ signal: controller.signal,
4580
+ write: async (writeOptions) => {
4581
+ throwIfProviderOutputAborted(controller.signal);
4582
+ await writeProviderDeploymentOutputsNow(writeOptions, controller.signal, transaction);
4583
+ }
4584
+ });
4585
+ throwIfProviderOutputAborted(controller.signal);
4586
+ }
4587
+ ready();
4588
+ const rollback = await rootDecision;
4589
+ if (rollback !== void 0) throw rollback;
4590
+ throwIfProviderOutputAborted(controller.signal);
4591
+ } catch (error) {
4592
+ controller.abort(error);
4593
+ rejectReady(error);
4594
+ throw error;
4595
+ }
4596
+ }, { snapshotInitialRoots: rootContributions.some((contribution) => contribution.owner !== "kv") });
4597
+ });
4598
+ write.catch(rejectReady);
4599
+ return {
4600
+ readiness,
4601
+ write
4602
+ };
4603
+ });
4604
+ const failedRoot = (await Promise.allSettled(roots.map((root) => root.readiness))).find((result) => result.status === "rejected");
4605
+ if (failedRoot) {
4606
+ decideRoots(failedRoot.reason);
4607
+ await settleWrites(roots.map((root) => root.write));
4608
+ }
4609
+ try {
4610
+ await catalog.prepareDeploymentContributions(contributions);
4611
+ throwIfProviderOutputAborted(controller.signal);
4612
+ } catch (error) {
4613
+ decideRoots(error);
4614
+ await settleWrites(roots.map((root) => root.write));
4615
+ throw error;
4616
+ }
4617
+ catalog.commitDeploymentContributions(contributions);
4618
+ state.generations.clear();
4619
+ decideRoots(void 0);
4620
+ await settleWrites(roots.map((root) => root.write));
4621
+ await catalog.completeDeploymentContributions(contributions);
4622
+ } catch (error) {
4623
+ if (state.rollback) catalog.rollbackDeploymentContributions(contributions);
4624
+ else await catalog.completeDeploymentContributions(contributions);
4625
+ throw error;
4626
+ } finally {
4627
+ state.generations.clear();
4628
+ }
4629
+ }
4630
+ } finally {
4631
+ options.signal?.removeEventListener("abort", abort);
4632
+ }
4633
+ })();
4634
+ const active = {
4635
+ controller,
4636
+ promise: finalization,
4637
+ state
4638
+ };
4639
+ providerDeploymentOutputFinalizations.set(catalog, active);
3307
4640
  try {
3308
- await write;
4641
+ await finalization;
3309
4642
  } finally {
3310
- if (providerDeploymentOutputWrites.get(key) === write) providerDeploymentOutputWrites.delete(key);
4643
+ if (providerDeploymentOutputFinalizations.get(catalog) === active) providerDeploymentOutputFinalizations.delete(catalog);
3311
4644
  }
3312
4645
  }
4646
+ async function withProviderDeploymentOutputLock(rootDir, operation) {
4647
+ return await withProviderDeploymentOutputRootLock(rootDir, async () => await withProviderDeploymentOutputRootTransaction(rootDir, async (transaction) => await operation(async (options) => await writeProviderDeploymentOutputsNow(options, void 0, transaction))));
4648
+ }
4649
+ async function writeProviderDeploymentOutputs(options) {
4650
+ await withProviderDeploymentOutputLock(options.rootDir, async (write) => await write(options));
4651
+ }
3313
4652
  //#endregion
3314
4653
  //#region ../internal/src/definition-catalog.ts
3315
4654
  const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
@@ -3334,11 +4673,15 @@ function readDirEntries(root) {
3334
4673
  throw error;
3335
4674
  }
3336
4675
  }
4676
+ function isGitRepositoryDirectory(directory) {
4677
+ return existsSync(resolve$1(directory, ".git"));
4678
+ }
3337
4679
  function listMatchingFiles(root, predicate, options = {}) {
3338
4680
  const files = [];
3339
4681
  for (const entry of readDirEntries(root)) {
3340
4682
  const absolute = resolve$1(root, entry.name);
3341
4683
  if (entry.isDirectory() && !entry.isSymbolicLink()) {
4684
+ if (isGitRepositoryDirectory(absolute)) continue;
3342
4685
  if (entry.name.startsWith(".")) continue;
3343
4686
  if (ignoredDirs.has(entry.name)) continue;
3344
4687
  files.push(...listMatchingFiles(absolute, predicate, options));
@@ -3404,9 +4747,9 @@ function requireRateLimitBindings(program) {
3404
4747
  namespaces: /* @__PURE__ */ new Set()
3405
4748
  };
3406
4749
  for (const statement of program.body) {
3407
- if (statement.type !== "ImportDeclaration" || !rateLimitImports.has(statement.source.value)) continue;
4750
+ if (statement.type !== "ImportDeclaration" || statement.importKind === "type" || !rateLimitImports.has(statement.source.value)) continue;
3408
4751
  for (const specifier of statement.specifiers) {
3409
- if (specifier.type === "ImportSpecifier" && specifier.imported.type === "Identifier" && specifier.imported.name === "requireRateLimit") bindings.direct.add(specifier.local.name);
4752
+ if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && specifier.imported.type === "Identifier" && specifier.imported.name === "requireRateLimit") bindings.direct.add(specifier.local.name);
3410
4753
  if (specifier.type === "ImportNamespaceSpecifier") bindings.namespaces.add(specifier.local.name);
3411
4754
  }
3412
4755
  }
@@ -3438,7 +4781,6 @@ function addDynamicRateLimitBindings(declaration, scope) {
3438
4781
  for (const declarator of declaration.declarations) {
3439
4782
  if (!rateLimitDynamicImport(declarator.init)) continue;
3440
4783
  if (declarator.id.type === "Identifier") {
3441
- scope.shadows.delete(declarator.id.name);
3442
4784
  scope.namespaces.add(declarator.id.name);
3443
4785
  continue;
3444
4786
  }
@@ -3448,14 +4790,13 @@ function addDynamicRateLimitBindings(declaration, scope) {
3448
4790
  if ((property.computed ? property.key.type === "Literal" ? property.key.value : void 0 : property.key.type === "Identifier" ? property.key.name : void 0) !== "requireRateLimit") continue;
3449
4791
  const value = property.value.type === "AssignmentPattern" ? property.value.left : property.value;
3450
4792
  if (value.type !== "Identifier") continue;
3451
- scope.shadows.delete(value.name);
3452
4793
  scope.direct.add(value.name);
3453
4794
  }
3454
4795
  }
3455
4796
  }
3456
4797
  function variableDeclaration(statement) {
3457
- if (statement.type === "VariableDeclaration") return statement;
3458
- if (statement.type === "ExportNamedDeclaration" && statement.declaration?.type === "VariableDeclaration") return statement.declaration;
4798
+ const declaration = runtimeDeclaration(statement);
4799
+ return declaration?.type === "VariableDeclaration" ? declaration : void 0;
3459
4800
  }
3460
4801
  function addDynamicRateLimitBindingsFromStatements(statements, scope) {
3461
4802
  for (const statement of statements) {
@@ -3486,33 +4827,109 @@ function addBindingNames(pattern, names) {
3486
4827
  }
3487
4828
  for (const property of pattern.properties) addBindingNames(property.type === "RestElement" ? property.argument : property.value, names);
3488
4829
  }
3489
- function functionBindings(params) {
4830
+ function hoistedVariableBindings(root) {
3490
4831
  const names = /* @__PURE__ */ new Set();
3491
- for (const parameter of params) addBindingNames(parameter, names);
4832
+ let nestedScopeDepth = 0;
4833
+ const enterNestedScope = () => {
4834
+ nestedScopeDepth += 1;
4835
+ };
4836
+ const exitNestedScope = () => {
4837
+ nestedScopeDepth -= 1;
4838
+ };
4839
+ const program = root.type === "Program" ? root : {
4840
+ ...root,
4841
+ type: "Program",
4842
+ sourceType: "module",
4843
+ hashbang: null,
4844
+ parent: null
4845
+ };
4846
+ new Visitor({
4847
+ ArrowFunctionExpression: enterNestedScope,
4848
+ "ArrowFunctionExpression:exit": exitNestedScope,
4849
+ ClassDeclaration: enterNestedScope,
4850
+ "ClassDeclaration:exit": exitNestedScope,
4851
+ ClassExpression: enterNestedScope,
4852
+ "ClassExpression:exit": exitNestedScope,
4853
+ FunctionDeclaration: enterNestedScope,
4854
+ "FunctionDeclaration:exit": exitNestedScope,
4855
+ FunctionExpression: enterNestedScope,
4856
+ "FunctionExpression:exit": exitNestedScope,
4857
+ StaticBlock: enterNestedScope,
4858
+ "StaticBlock:exit": exitNestedScope,
4859
+ TSModuleDeclaration: enterNestedScope,
4860
+ "TSModuleDeclaration:exit": exitNestedScope,
4861
+ VariableDeclaration(declaration) {
4862
+ if (nestedScopeDepth === 0 && declaration.kind === "var" && !declaration.declare) for (const declarator of declaration.declarations) addBindingNames(declarator.id, names);
4863
+ }
4864
+ }).visit(program);
3492
4865
  return names;
3493
4866
  }
3494
- function variableBindings(declaration) {
4867
+ function functionBindings(node) {
3495
4868
  const names = /* @__PURE__ */ new Set();
3496
- for (const declarator of declaration?.declarations ?? []) addBindingNames(declarator.id, names);
4869
+ if (node.type === "FunctionExpression" && node.id) names.add(node.id.name);
4870
+ for (const parameter of node.params) addBindingNames(parameter, names);
3497
4871
  return names;
3498
4872
  }
3499
- function blockBindings(block) {
4873
+ function runtimeDeclaration(statement) {
4874
+ if (statement.type === "ExportNamedDeclaration") return statement.declaration ?? void 0;
4875
+ if (statement.type === "ExportDefaultDeclaration") {
4876
+ const declaration = statement.declaration;
4877
+ if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") return declaration;
4878
+ }
4879
+ if (statement.type === "VariableDeclaration" || statement.type === "FunctionDeclaration" || statement.type === "ClassDeclaration" || statement.type === "TSEnumDeclaration" || statement.type === "TSModuleDeclaration" || statement.type === "TSImportEqualsDeclaration") return statement;
4880
+ }
4881
+ function lexicalBindings(statements) {
3500
4882
  const names = /* @__PURE__ */ new Set();
3501
- for (const statement of block.body) {
3502
- if ((statement.type === "FunctionDeclaration" || statement.type === "ClassDeclaration") && statement.id) names.add(statement.id.name);
3503
- const declaration = statement.type === "VariableDeclaration" ? statement : statement.type === "ExportNamedDeclaration" && statement.declaration?.type === "VariableDeclaration" ? statement.declaration : void 0;
3504
- for (const declarator of declaration?.declarations ?? []) addBindingNames(declarator.id, names);
4883
+ for (const statement of statements) {
4884
+ const declaration = runtimeDeclaration(statement);
4885
+ if ((declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration") && declaration.id) {
4886
+ if (!declaration.declare) names.add(declaration.id.name);
4887
+ }
4888
+ if (declaration?.type === "VariableDeclaration" && declaration.kind !== "var" && !declaration.declare) for (const declarator of declaration.declarations) addBindingNames(declarator.id, names);
4889
+ if (declaration?.type === "TSEnumDeclaration" && !declaration.declare) names.add(declaration.id.name);
4890
+ if (declaration?.type === "TSModuleDeclaration" && !declaration.declare && !declaration.global && declaration.id.type === "Identifier") names.add(declaration.id.name);
4891
+ if (declaration?.type === "TSImportEqualsDeclaration" && declaration.importKind !== "type") names.add(declaration.id.name);
3505
4892
  }
3506
4893
  return names;
3507
4894
  }
3508
- function switchBindings(statement) {
3509
- const names = /* @__PURE__ */ new Set();
3510
- for (const switchCase of statement.cases) for (const child of switchCase.consequent) {
3511
- if ((child.type === "FunctionDeclaration" || child.type === "ClassDeclaration") && child.id) names.add(child.id.name);
3512
- if (child.type === "VariableDeclaration") for (const name of variableBindings(child)) names.add(name);
4895
+ function programBindings(program) {
4896
+ const names = lexicalBindings(program.body);
4897
+ for (const name of hoistedVariableBindings(program)) names.add(name);
4898
+ for (const statement of program.body) {
4899
+ if (statement.type !== "ImportDeclaration" || statement.importKind === "type") continue;
4900
+ for (const specifier of statement.specifiers) if (specifier.type !== "ImportSpecifier" || specifier.importKind !== "type") names.add(specifier.local.name);
3513
4901
  }
3514
4902
  return names;
3515
4903
  }
4904
+ function blockBindings(block) {
4905
+ return lexicalBindings(block.body);
4906
+ }
4907
+ function scopedStatementBindings(statements) {
4908
+ const names = lexicalBindings(statements);
4909
+ const program = {
4910
+ type: "Program",
4911
+ body: statements,
4912
+ sourceType: "module",
4913
+ hashbang: null,
4914
+ parent: null,
4915
+ start: 0,
4916
+ end: 0
4917
+ };
4918
+ for (const name of hoistedVariableBindings(program)) names.add(name);
4919
+ return names;
4920
+ }
4921
+ function variableBindings(declaration) {
4922
+ const names = /* @__PURE__ */ new Set();
4923
+ for (const declarator of declaration?.declarations ?? []) addBindingNames(declarator.id, names);
4924
+ return names;
4925
+ }
4926
+ function loopBindings(declaration) {
4927
+ if (declaration?.kind === "var") return /* @__PURE__ */ new Set();
4928
+ return variableBindings(declaration);
4929
+ }
4930
+ function switchBindings(statement) {
4931
+ return lexicalBindings(statement.cases.flatMap((switchCase) => switchCase.consequent));
4932
+ }
3516
4933
  function staticPropertyName(property) {
3517
4934
  if (property.computed || property.kind !== "init" || property.method) return;
3518
4935
  if (property.key.type === "Identifier") return property.key.name;
@@ -3558,12 +4975,15 @@ function extractRateLimitDeclarations(file, source) {
3558
4975
  if (!source.includes("requireRateLimit")) return [];
3559
4976
  const parsed = parseSync(file, source);
3560
4977
  if (parsed.errors.length > 0) throw new Error(`[vitehub] Could not parse ${file} while collecting Rate Limits: ${parsed.errors[0]?.message}`);
4978
+ const rootShadows = programBindings(parsed.program);
3561
4979
  const bindings = requireRateLimitBindings(parsed.program);
4980
+ if (!rootShadows.has("requireRateLimit")) bindings.direct.add("requireRateLimit");
3562
4981
  const declarations = [];
3563
4982
  const scopes = [{
3564
4983
  ...bindings,
3565
- shadows: /* @__PURE__ */ new Set()
4984
+ shadows: rootShadows
3566
4985
  }];
4986
+ const functionBodies = /* @__PURE__ */ new WeakSet();
3567
4987
  addDynamicRateLimitBindingsFromStatements(parsed.program.body, scopes[0]);
3568
4988
  const enterScope = (shadows) => {
3569
4989
  scopes.push({
@@ -3573,9 +4993,8 @@ function extractRateLimitDeclarations(file, source) {
3573
4993
  });
3574
4994
  };
3575
4995
  const enterFunction = (node) => {
3576
- const shadows = functionBindings(node.params);
3577
- if (node.type === "FunctionExpression" && node.id) shadows.add(node.id.name);
3578
- enterScope(shadows);
4996
+ enterScope(functionBindings(node));
4997
+ if (node.body?.type === "BlockStatement") functionBodies.add(node.body);
3579
4998
  };
3580
4999
  const exitScope = () => {
3581
5000
  scopes.pop();
@@ -3584,7 +5003,7 @@ function extractRateLimitDeclarations(file, source) {
3584
5003
  ArrowFunctionExpression: enterFunction,
3585
5004
  "ArrowFunctionExpression:exit": exitScope,
3586
5005
  BlockStatement(block) {
3587
- enterScope(blockBindings(block));
5006
+ enterScope(functionBodies.has(block) ? scopedStatementBindings(block.body) : blockBindings(block));
3588
5007
  addDynamicRateLimitBindingsFromStatements(block.body, scopes.at(-1));
3589
5008
  },
3590
5009
  "BlockStatement:exit": exitScope,
@@ -3620,22 +5039,32 @@ function extractRateLimitDeclarations(file, source) {
3620
5039
  FunctionExpression: enterFunction,
3621
5040
  "FunctionExpression:exit": exitScope,
3622
5041
  ForInStatement(node) {
3623
- enterScope(node.left.type === "VariableDeclaration" ? variableBindings(node.left) : /* @__PURE__ */ new Set());
5042
+ enterScope(node.left.type === "VariableDeclaration" ? loopBindings(node.left) : /* @__PURE__ */ new Set());
3624
5043
  },
3625
5044
  "ForInStatement:exit": exitScope,
3626
5045
  ForOfStatement(node) {
3627
- enterScope(node.left.type === "VariableDeclaration" ? variableBindings(node.left) : /* @__PURE__ */ new Set());
5046
+ enterScope(node.left.type === "VariableDeclaration" ? loopBindings(node.left) : /* @__PURE__ */ new Set());
3628
5047
  },
3629
5048
  "ForOfStatement:exit": exitScope,
3630
5049
  ForStatement(node) {
3631
- enterScope(node.init?.type === "VariableDeclaration" ? variableBindings(node.init) : /* @__PURE__ */ new Set());
5050
+ enterScope(node.init?.type === "VariableDeclaration" ? loopBindings(node.init) : /* @__PURE__ */ new Set());
3632
5051
  },
3633
5052
  "ForStatement:exit": exitScope,
3634
5053
  SwitchStatement(node) {
3635
5054
  enterScope(switchBindings(node));
3636
5055
  for (const switchCase of node.cases) addDynamicRateLimitBindingsFromStatements(switchCase.consequent, scopes.at(-1));
3637
5056
  },
3638
- "SwitchStatement:exit": exitScope
5057
+ "SwitchStatement:exit": exitScope,
5058
+ StaticBlock(node) {
5059
+ enterScope(scopedStatementBindings(node.body));
5060
+ addDynamicRateLimitBindingsFromStatements(node.body, scopes.at(-1));
5061
+ },
5062
+ "StaticBlock:exit": exitScope,
5063
+ TSModuleBlock(node) {
5064
+ enterScope(scopedStatementBindings(node.body));
5065
+ addDynamicRateLimitBindingsFromStatements(node.body, scopes.at(-1));
5066
+ },
5067
+ "TSModuleBlock:exit": exitScope
3639
5068
  }).visit(parsed.program);
3640
5069
  return declarations;
3641
5070
  }
@@ -3661,6 +5090,9 @@ function discoverRateLimitCatalog(options) {
3661
5090
  declarations: [...declarations.values()].sort((left, right) => left.name.localeCompare(right.name))
3662
5091
  };
3663
5092
  }
5093
+ function discoverRateLimitDeclarations(options) {
5094
+ return discoverRateLimitCatalog(options).declarations;
5095
+ }
3664
5096
  //#endregion
3665
5097
  //#region src/internal/manifest.ts
3666
5098
  const rateLimitManifestPath = ".vitehub/rate-limit/manifest.json";
@@ -3694,12 +5126,15 @@ function outputStateFile(rootDir) {
3694
5126
  async function readOutputState(rootDir) {
3695
5127
  try {
3696
5128
  const parsed = JSON.parse(await readFile(outputStateFile(rootDir), "utf8"));
5129
+ if (parsed === null || Object(parsed) !== parsed || Array.isArray(parsed)) throw new TypeError("[vitehub] Cloudflare Rate Limit output state must be a JSON object.");
5130
+ const state = parsed;
5131
+ const bindings = Array.isArray(state.bindings) ? state.bindings.filter((value) => value?.constructor === String) : [];
3697
5132
  return {
3698
- bindings: Array.isArray(parsed.bindings) ? parsed.bindings.filter((value) => typeof value === "string") : [],
3699
- standalone: parsed.standalone !== false && Array.isArray(parsed.bindings) && parsed.bindings.length > 0
5133
+ bindings,
5134
+ standalone: state.standalone !== false && bindings.length > 0
3700
5135
  };
3701
5136
  } catch (error) {
3702
- if (error.code === "ENOENT") return {
5137
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return {
3703
5138
  bindings: [],
3704
5139
  standalone: false
3705
5140
  };
@@ -3745,8 +5180,10 @@ function createCloudflareRateLimitBindings(declarations, namespace) {
3745
5180
  function resolveRateLimitNamespace(configured) {
3746
5181
  return configured?.trim() || void 0;
3747
5182
  }
3748
- async function writeRateLimitProviderOutput(options) {
5183
+ async function writeRateLimitProviderOutput(options, write = writeProviderDeploymentOutputs) {
5184
+ options.signal?.throwIfAborted();
3749
5185
  const state = await readOutputState(options.rootDir);
5186
+ options.signal?.throwIfAborted();
3750
5187
  const currentBindings = options.declarations.map((declaration) => getCloudflareRateLimitBindingName(declaration.name));
3751
5188
  const previousBindings = options.previousDeclarations?.map((declaration) => getCloudflareRateLimitBindingName(declaration.name)) ?? [];
3752
5189
  const ownership = { arrays: { ratelimits: {
@@ -3759,7 +5196,7 @@ async function writeRateLimitProviderOutput(options) {
3759
5196
  } } };
3760
5197
  if (options.cloudflareOwnedByNitro) {
3761
5198
  if (options.provider === "cloudflare" && options.declarations.length > 0 && !options.namespace) throw new Error("[vitehub] Cloudflare Rate Limit requires rateLimit.namespace to isolate counters between deployments.");
3762
- if (state.standalone && state.bindings.length > 0) await writeProviderDeploymentOutputs({
5199
+ if (state.standalone && state.bindings.length > 0) await write({
3763
5200
  clientOutDir: options.clientOutDir,
3764
5201
  cleanup: { cloudflare: {
3765
5202
  outputRoot: createDefaultCloudflareOutputRoot(options.rootDir),
@@ -3770,13 +5207,15 @@ async function writeRateLimitProviderOutput(options) {
3770
5207
  } },
3771
5208
  rootDir: options.rootDir
3772
5209
  });
5210
+ options.signal?.throwIfAborted();
3773
5211
  await writeOutputState(options.rootDir, []);
5212
+ options.signal?.throwIfAborted();
3774
5213
  await writeRateLimitManifest(options.rootDir, options.declarations, options.provider);
3775
5214
  return;
3776
5215
  }
3777
5216
  if (options.provider === "cloudflare" && options.declarations.length > 0) {
3778
5217
  if (!options.namespace) throw new Error("[vitehub] Cloudflare Rate Limit requires rateLimit.namespace to isolate counters between deployments.");
3779
- await writeProviderDeploymentOutputs({
5218
+ await write({
3780
5219
  clientOutDir: options.clientOutDir,
3781
5220
  cloudflare: {
3782
5221
  outputRoot: createDefaultCloudflareOutputRoot(options.rootDir),
@@ -3785,11 +5224,13 @@ async function writeRateLimitProviderOutput(options) {
3785
5224
  },
3786
5225
  rootDir: options.rootDir
3787
5226
  });
5227
+ options.signal?.throwIfAborted();
3788
5228
  await writeOutputState(options.rootDir, currentBindings, true);
5229
+ options.signal?.throwIfAborted();
3789
5230
  await writeRateLimitManifest(options.rootDir, options.declarations, options.provider);
3790
5231
  return;
3791
5232
  }
3792
- await writeProviderDeploymentOutputs({
5233
+ await write({
3793
5234
  clientOutDir: options.clientOutDir,
3794
5235
  cleanup: { cloudflare: {
3795
5236
  outputRoot: createDefaultCloudflareOutputRoot(options.rootDir),
@@ -3797,7 +5238,9 @@ async function writeRateLimitProviderOutput(options) {
3797
5238
  } },
3798
5239
  rootDir: options.rootDir
3799
5240
  });
5241
+ options.signal?.throwIfAborted();
3800
5242
  await writeOutputState(options.rootDir, []);
5243
+ options.signal?.throwIfAborted();
3801
5244
  await writeRateLimitManifest(options.rootDir, options.declarations, options.provider);
3802
5245
  }
3803
5246
  //#endregion
@@ -3805,14 +5248,13 @@ async function writeRateLimitProviderOutput(options) {
3805
5248
  const packageName = "@vite-hub/rate-limit";
3806
5249
  const pluginName = "@vite-hub/rate-limit/vite";
3807
5250
  const generatedNitroPlugin = ".vitehub/nitro/rate-limit/plugin.ts";
3808
- const legacyGeneratedNitroMiddleware = ".vitehub/nitro/rate-limit/middleware.ts";
3809
5251
  const generatedRuntimeModule = ".vitehub/rate-limit/cloudflare-runtime.mjs";
3810
- const legacyGeneratedRegistry = ".vitehub/nitro/rate-limit/registry.mjs";
3811
5252
  const mergeNoExternal = createNoExternalMerger(packageName);
3812
5253
  function cloneNitroConfig(value) {
3813
5254
  return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
3814
5255
  }
3815
5256
  function mergeNitroConfig(config, value, declarations, namespace, provider, nitroCloudflare) {
5257
+ const providerOutput = useProviderOutputCatalog(config);
3816
5258
  const nitro = cloneNitroConfig(value);
3817
5259
  const plugins = Array.isArray(nitro.plugins) ? [...nitro.plugins] : [];
3818
5260
  if (!plugins.includes(generatedNitroPlugin)) plugins.unshift(generatedNitroPlugin);
@@ -3821,12 +5263,15 @@ function mergeNitroConfig(config, value, declarations, namespace, provider, nitr
3821
5263
  plugins
3822
5264
  };
3823
5265
  if (!nitroCloudflare || provider !== "cloudflare" || declarations.length === 0) {
3824
- registerCloudflareProviderOutput(config, "rate-limit", {});
3825
- return composeNitroCloudflareProviderOutput(config, baseNitro);
5266
+ contributeCloudflareProviderOutput(providerOutput, { owner: "rate-limit" });
5267
+ return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
3826
5268
  }
3827
5269
  if (!namespace) throw new Error("[vitehub] Cloudflare Rate Limit requires rateLimit.namespace to isolate counters between deployments.");
3828
- registerCloudflareProviderOutput(config, "rate-limit", { rateLimits: createCloudflareRateLimitBindings(declarations, namespace) });
3829
- return composeNitroCloudflareProviderOutput(config, baseNitro);
5270
+ contributeCloudflareProviderOutput(providerOutput, {
5271
+ owner: "rate-limit",
5272
+ rateLimits: createCloudflareRateLimitBindings(declarations, namespace)
5273
+ });
5274
+ return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
3830
5275
  }
3831
5276
  function renderRuntimeInstaller(runtimeConfig, importBase, nitro) {
3832
5277
  return [
@@ -3859,6 +5304,7 @@ function hubRateLimit(options = {}) {
3859
5304
  const importBase = options.importBase ?? packageName;
3860
5305
  let rateLimit = options;
3861
5306
  let composedOutput;
5307
+ const providerOutputGenerations = createProviderDeploymentOutputGenerationState();
3862
5308
  let declarations = [];
3863
5309
  let declarationFiles = /* @__PURE__ */ new Set();
3864
5310
  let cloudflareOwnedByNitro = false;
@@ -3894,26 +5340,23 @@ function hubRateLimit(options = {}) {
3894
5340
  async configResolved(config) {
3895
5341
  resolved = config;
3896
5342
  rateLimit = config.rateLimit ?? rateLimit;
3897
- composedOutput = useComposedProviderOutput(config);
5343
+ composedOutput = useProviderOutputCatalog(config);
3898
5344
  projectRoot = resolveViteHubProjectRoot(config.root, { projectRoot: rateLimit.projectRoot });
3899
5345
  const configuredNitro = config.nitro;
3900
5346
  const nitroCloudflare = resolveNitroHosting(configuredNitro) === "cloudflare";
3901
- cloudflareOwnedByNitro = hasNitroVitePlugin(config) && nitroCloudflare;
5347
+ cloudflareOwnedByNitro = hasNitroConfigContext(config) && nitroCloudflare;
3902
5348
  provider = resolveProvider(rateLimit, config.command, configuredNitro);
3903
5349
  collectDeclarations();
3904
5350
  config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), provider, nitroCloudflare);
3905
5351
  await writeRateLimitManifest(config.root, declarations, provider);
3906
5352
  const pluginFile = resolve(config.root, generatedNitroPlugin);
3907
- const middlewareFile = resolve(config.root, legacyGeneratedNitroMiddleware);
3908
5353
  const runtimeFile = resolve(config.root, generatedRuntimeModule);
3909
5354
  const runtimeConfig = { provider };
3910
- await Promise.all([
3911
- rm(resolve(config.root, legacyGeneratedRegistry), { force: true }),
3912
- rm(middlewareFile, { force: true }),
3913
- writeFileIfChanged(pluginFile, renderRuntimeInstaller(runtimeConfig, importBase, true)),
3914
- writeFileIfChanged(runtimeFile, renderRuntimeInstaller(runtimeConfig, importBase, false))
3915
- ]);
3916
- registerProviderRuntimeModules(composedOutput, "rate-limit", { cloudflare: runtimeFile });
5355
+ await Promise.all([writeFileIfChanged(pluginFile, renderRuntimeInstaller(runtimeConfig, importBase, true)), writeFileIfChanged(runtimeFile, renderRuntimeInstaller(runtimeConfig, importBase, false))]);
5356
+ contributeProviderRuntime(composedOutput, {
5357
+ owner: "rate-limit",
5358
+ runtimeModules: { cloudflare: runtimeFile }
5359
+ });
3917
5360
  },
3918
5361
  configEnvironment(name, config) {
3919
5362
  if (!isServerEnvironment(name, config)) return;
@@ -3928,27 +5371,60 @@ function hubRateLimit(options = {}) {
3928
5371
  if (provider !== "cloudflare" || !resolved?.build.ssr || !declarationFiles.has(id.split("?", 1)[0])) return;
3929
5372
  return `import ${JSON.stringify(normalizePath(resolve(resolved.root, generatedRuntimeModule)))}\n${code}`;
3930
5373
  },
3931
- async closeBundle() {
5374
+ buildStart() {
5375
+ providerOutputGenerations.capture(this, composedOutput);
5376
+ },
5377
+ async buildEnd(error) {
5378
+ if (error) {
5379
+ await providerOutputGenerations.reset(this, composedOutput, error);
5380
+ return;
5381
+ }
3932
5382
  if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
3933
- if (cloudflareOwnedByNitro && provider === "cloudflare") {
3934
- const configuredDeclarations = declarations;
3935
- collectDeclarations();
3936
- if (JSON.stringify(declarations) !== JSON.stringify(configuredDeclarations)) throw new Error("[vitehub] Nitro Cloudflare Rate Limit declarations changed after config resolution. Generate Rate Limit source files before Vite config resolves.");
3937
- await writeRateLimitManifest(resolved.root, declarations, provider);
3938
- } else await refreshDeclarations();
3939
- const namespace = resolveRateLimitNamespace(rateLimit.namespace);
3940
- await writeRateLimitProviderOutput({
3941
- clientOutDir: resolved.build.outDir,
3942
- cloudflareOwnedByNitro,
3943
- declarations,
3944
- namespace,
3945
- previousDeclarations,
3946
- provider,
3947
- rootDir: resolved.root
3948
- });
3949
- previousDeclarations = declarations;
5383
+ try {
5384
+ if (cloudflareOwnedByNitro && provider === "cloudflare") {
5385
+ const configuredDeclarations = declarations;
5386
+ collectDeclarations();
5387
+ if (JSON.stringify(declarations) !== JSON.stringify(configuredDeclarations)) throw new Error("[vitehub] Nitro Cloudflare Rate Limit declarations changed after config resolution. Generate Rate Limit source files before Vite config resolves.");
5388
+ } else collectDeclarations();
5389
+ const namespace = resolveRateLimitNamespace(rateLimit.namespace);
5390
+ const config = resolved;
5391
+ const contributionDeclarations = declarations;
5392
+ const contributionPreviousDeclarations = previousDeclarations;
5393
+ contributeProviderDeploymentOutput(composedOutput, {
5394
+ owner: "rate-limit",
5395
+ rootDir: config.root,
5396
+ write: async ({ signal, write }) => {
5397
+ await writeRateLimitProviderOutput({
5398
+ clientOutDir: config.build.outDir,
5399
+ cloudflareOwnedByNitro,
5400
+ declarations: contributionDeclarations,
5401
+ namespace,
5402
+ previousDeclarations: contributionPreviousDeclarations,
5403
+ provider,
5404
+ rootDir: config.root,
5405
+ signal
5406
+ }, write);
5407
+ signal.throwIfAborted();
5408
+ previousDeclarations = contributionDeclarations;
5409
+ }
5410
+ }, providerOutputGenerations.get(this));
5411
+ } catch (error) {
5412
+ await providerOutputGenerations.reset(this, composedOutput, error);
5413
+ throw error;
5414
+ }
5415
+ },
5416
+ async renderError(error) {
5417
+ await providerOutputGenerations.reset(this, composedOutput, error);
5418
+ },
5419
+ closeBundle: {
5420
+ order: "post",
5421
+ sequential: true,
5422
+ async handler() {
5423
+ if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
5424
+ await finalizeProviderDeploymentOutputs(composedOutput);
5425
+ }
3950
5426
  }
3951
5427
  };
3952
5428
  }
3953
5429
  //#endregion
3954
- export { hubRateLimit };
5430
+ export { discoverRateLimitDeclarations, hubRateLimit };