@vite-hub/rate-limit 0.0.3 → 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, isAbsolute, relative, resolve, sep } 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";
@@ -219,10 +220,10 @@ 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) {
@@ -261,7 +262,13 @@ async function persistProviderJsonRecord(file, value, removeIfEmpty) {
261
262
  await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
262
263
  }
263
264
  async function writeProviderOutputConfig(file, value, ownership = {}, options = {}) {
264
- 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);
265
272
  }
266
273
  function mergeProviderOutputConfig(existing, value, ownership = {}) {
267
274
  assertProviderJsonRecord(existing);
@@ -279,13 +286,15 @@ async function cleanProviderOutputConfig(file, ownership) {
279
286
  if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
280
287
  const existing = await readProviderJsonRecord(file);
281
288
  if (!existing) return;
282
- const next = deleteOwnedFields(existing, ownership);
289
+ const next = deleteOwnedFields(existing, ownership, true);
283
290
  let changed = (ownership.keys ?? []).some((key) => key in existing);
284
291
  for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
292
+ if (arrayOwnership.preserveOnCleanup) continue;
285
293
  if (!(field in existing)) continue;
286
294
  const current = existing[field];
287
- const preserved = preserveUnownedKeyedArrayEntries(current, arrayOwnership);
288
- 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;
289
298
  if (preserved.length) next[field] = preserved;
290
299
  }
291
300
  if (!changed) return;
@@ -309,10 +318,13 @@ async function writeCloudflareWranglerConfig(options) {
309
318
  return;
310
319
  }
311
320
  await mkdir(outputRoot, { recursive: true });
312
- 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
+ });
313
325
  }
314
326
  //#endregion
315
- //#region ../internal/src/build/vite.ts
327
+ //#region ../internal/src/object.ts
316
328
  var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
317
329
  var __defProp = Object.defineProperty;
318
330
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -2661,84 +2673,14 @@ error: ${text}`);
2661
2673
  version
2662
2674
  });
2663
2675
  })))();
2664
- const projectRootDirectoryMarkers = [
2665
- ["server", "agents"],
2666
- ["server", "browsers"],
2667
- ["server", "schedules"],
2668
- ["server", "templates"],
2669
- ["server", "workspaces"]
2670
- ];
2671
- const projectRootDefinitionFileMarkers = [
2672
- ".ts",
2673
- ".mts",
2674
- ".cts",
2675
- ".js",
2676
- ".mjs",
2677
- ".cjs"
2678
- ].flatMap((extension) => [["server", `email${extension}`], [`server.email${extension}`]]);
2679
- const projectRootFileMarkers = [["package.json"]];
2680
- function createNoExternalMerger(packageName) {
2681
- return (current) => {
2682
- if (current === true) return true;
2683
- if (!current) return [packageName];
2684
- const values = Array.isArray(current) ? current : [current];
2685
- return values.includes(packageName) ? values : [...values, packageName];
2686
- };
2687
- }
2688
- function isServerEnvironment(name, config) {
2689
- return name === "ssr" || config.consumer === "server";
2690
- }
2691
- function includesNitroVitePlugin(value) {
2692
- if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
2693
- if (!value || typeof value !== "object") return false;
2694
- return "name" in value && value.name === "nitro:main";
2695
- }
2696
- function hasNitroConfigContext(config) {
2697
- return config["__vitehubNitroConfigContext"] === true || includesNitroVitePlugin(config.plugins);
2698
- }
2699
- function shouldSkipViteProviderBuild(command, mode) {
2700
- return command === "serve" || mode === "e2e";
2701
- }
2702
- function resolveViteHubProjectRoot(root, options = {}) {
2703
- const resolvedRoot = resolve(root);
2704
- if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
2705
- if (basename(resolvedRoot) === "app") {
2706
- const parent = dirname(resolvedRoot);
2707
- if (hasProjectRootDirectoryMarker(parent) || hasProjectRootDefinitionFileMarker(parent)) return parent;
2708
- }
2709
- let current = resolvedRoot;
2710
- while (true) {
2711
- if (hasProjectRootMarker(current)) return current;
2712
- const parent = dirname(current);
2713
- if (parent === current) return resolvedRoot;
2714
- current = parent;
2715
- }
2716
- }
2717
- function hasProjectRootDirectoryMarker(root) {
2718
- for (const marker of projectRootDirectoryMarkers) try {
2719
- if (statSync(resolve(root, ...marker)).isDirectory()) return true;
2720
- } catch (error) {
2721
- if (error.code !== "ENOENT") throw error;
2722
- }
2723
- return false;
2724
- }
2725
- function hasProjectRootMarker(root) {
2726
- if (hasProjectRootDirectoryMarker(root)) return true;
2727
- if (hasProjectRootDefinitionFileMarker(root)) return true;
2728
- for (const marker of projectRootFileMarkers) try {
2729
- if (statSync(resolve(root, ...marker)).isFile()) return true;
2730
- } catch (error) {
2731
- if (error.code !== "ENOENT") throw error;
2732
- }
2733
- return false;
2734
- }
2735
- function hasProjectRootDefinitionFileMarker(root) {
2736
- for (const marker of projectRootDefinitionFileMarkers) try {
2737
- if (statSync(resolve(root, ...marker)).isFile()) return true;
2738
- } catch (error) {
2739
- 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;
2740
2683
  }
2741
- return false;
2742
2684
  }
2743
2685
  //#endregion
2744
2686
  //#region ../internal/src/build/esbuild.ts
@@ -2746,13 +2688,264 @@ const viteRawNamespace = "vitehub-vite-raw";
2746
2688
  const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
2747
2689
  const markdownTemplateFileSuffix = ".template.md";
2748
2690
  const markdownTemplateModuleQuery = "markdown-template";
2749
- const markdownTemplateRegistryId = "#vitehub/templates";
2750
- const markdownTemplateRegistryPath = ".vitehub/markdown-template/templates.mjs";
2751
2691
  const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
2692
+ const skipResolvedAlias = "vitehubSkipResolvedAlias";
2693
+ const encodedAliasPrefixMarker = "\0vitehub-prefix:";
2694
+ const encodedAliasExactMarker = "\0vitehub-exact:";
2752
2695
  const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
2753
- function resolveEsbuildAliases(aliases) {
2754
- if (!aliases) return;
2755
- 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
+ };
2756
2949
  }
2757
2950
  function stripMarkdownCode(template) {
2758
2951
  let fence;
@@ -2827,7 +3020,7 @@ async function resolveViteRawSpecifier(path, rootDir) {
2827
3020
  await stat(publicPath);
2828
3021
  return publicPath;
2829
3022
  } catch (error) {
2830
- if (error.code !== "ENOENT") throw error;
3023
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
2831
3024
  return resolve(rootDir, rootRelativePath);
2832
3025
  }
2833
3026
  }
@@ -2852,14 +3045,16 @@ function createViteRawPlugin(rootDir, frameworkRuntime) {
2852
3045
  const raw = hasViteRawQuery(args.path);
2853
3046
  if (!markdownTemplate && !raw) return;
2854
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
+ };
2855
3053
  const resolved = await build.resolve(specifier, {
2856
3054
  importer: args.importer,
2857
3055
  kind: args.kind,
2858
3056
  namespace: args.namespace,
2859
- pluginData: markdownTemplate ? {
2860
- ...args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {},
2861
- [skipMarkdownTemplateResolve]: true
2862
- } : args.pluginData,
3057
+ pluginData,
2863
3058
  resolveDir: args.resolveDir,
2864
3059
  with: args.with
2865
3060
  });
@@ -2912,7 +3107,7 @@ function createViteRawPlugin(rootDir, frameworkRuntime) {
2912
3107
  importer,
2913
3108
  kind: "import-statement",
2914
3109
  pluginData: {
2915
- ...args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {},
3110
+ ...args.pluginData,
2916
3111
  [skipMarkdownTemplateResolve]: true
2917
3112
  },
2918
3113
  resolveDir: dirname(importer)
@@ -2939,24 +3134,34 @@ function createViteRawPlugin(rootDir, frameworkRuntime) {
2939
3134
  }
2940
3135
  };
2941
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
+ }
2942
3145
  async function bundleEsmEntry(entryFile, outfile, options = {}) {
3146
+ options.signal?.throwIfAborted();
2943
3147
  const format = options.format || "esm";
2944
3148
  const platform = options.platform || "neutral";
2945
- const markdownTemplateRoot = options.rootDir && resolveViteHubProjectRoot(options.rootDir);
2946
- const aliases = resolveEsbuildAliases({
2947
- ...markdownTemplateRoot ? { [markdownTemplateRegistryId]: resolve(markdownTemplateRoot, markdownTemplateRegistryPath) } : {},
2948
- ...options.alias
2949
- });
2950
- const frameworkRuntime = Object.keys(aliases || {}).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
2951
- await (0, import_main.build)({
2952
- 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,
2953
3159
  banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
2954
- "import { createRequire as __createRequire } from \"node:module\";",
2955
- "import { dirname as __vitehubDirname } from \"node:path\";",
2956
- "import { fileURLToPath as __vitehubFileURLToPath } from \"node:url\";",
2957
- "globalThis.require = __createRequire(import.meta.url);",
2958
- "globalThis.__filename = __vitehubFileURLToPath(import.meta.url);",
2959
- "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
+ "}"
2960
3165
  ] : []].filter(Boolean).join("\n") } : void 0,
2961
3166
  bundle: true,
2962
3167
  conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
@@ -2965,13 +3170,37 @@ async function bundleEsmEntry(entryFile, outfile, options = {}) {
2965
3170
  format,
2966
3171
  logLevel: "silent",
2967
3172
  mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
3173
+ resolveExtensions: options.extensions,
2968
3174
  minifyIdentifiers: options.minifyIdentifiers,
3175
+ minifyWhitespace: options.minifyWhitespace,
2969
3176
  outfile,
3177
+ packages: options.packages,
2970
3178
  platform,
2971
- plugins: [...options.plugins ?? [], createViteRawPlugin(options.rootDir, frameworkRuntime)],
3179
+ preserveSymlinks: options.preserveSymlinks,
3180
+ plugins,
2972
3181
  sourcemap: false,
2973
3182
  target: "es2022",
2974
- 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
2975
3204
  });
2976
3205
  }
2977
3206
  //#endregion
@@ -2997,8 +3226,8 @@ function createNodeFunctionConfig(extra = {}) {
2997
3226
  }
2998
3227
  //#endregion
2999
3228
  //#region ../internal/src/build/cloudflare-provider-output.ts
3000
- const cloudflareProviderOutputKey = Symbol.for("vitehub.cloudflareProviderOutput");
3001
- const cloudflareProviderOutputByNitro = /* @__PURE__ */ new WeakMap();
3229
+ const providerOutputCatalogRegistry$1 = globalThis;
3230
+ const providerOutputCatalogByNitroValue = providerOutputCatalogRegistry$1.__vitehubProviderOutputCatalogsByNitroValue ??= /* @__PURE__ */ new WeakMap();
3002
3231
  function cloneRecord(value) {
3003
3232
  return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
3004
3233
  }
@@ -3011,16 +3240,6 @@ function cloneProviderValue(value) {
3011
3240
  if (value && typeof value === "object") return cloneProviderRecord(value);
3012
3241
  return value;
3013
3242
  }
3014
- function useCloudflareProviderOutput(config) {
3015
- const owner = config;
3016
- return owner[cloudflareProviderOutputKey] ??= {
3017
- appliedByOwner: /* @__PURE__ */ new Map(),
3018
- contributionsByOwner: /* @__PURE__ */ new Map()
3019
- };
3020
- }
3021
- function registerCloudflareProviderOutput(config, owner, contribution) {
3022
- useCloudflareProviderOutput(config).contributionsByOwner.set(owner, contribution);
3023
- }
3024
3243
  function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner) {
3025
3244
  const current = Array.isArray(existing) ? existing.map(cloneProviderRecord) : [];
3026
3245
  return (incoming ?? []).filter((entry) => {
@@ -3040,7 +3259,10 @@ function removeEntries(existing, entries) {
3040
3259
  }
3041
3260
  function removeContribution(wrangler, contribution) {
3042
3261
  const queues = cloneProviderRecord(wrangler.queues);
3262
+ const secrets = cloneProviderRecord(wrangler.secrets);
3263
+ const environments = cloneProviderRecord(wrangler.env);
3043
3264
  const hasQueues = Boolean(contribution.queues?.consumers?.length || contribution.queues?.producers?.length);
3265
+ const hasSecrets = Boolean(contribution.requiredSecrets?.length || Object.keys(contribution.requiredSecretsByEnvironment ?? {}).length);
3044
3266
  if (contribution.queues?.consumers?.length) {
3045
3267
  const consumers = removeEntries(queues.consumers, contribution.queues.consumers);
3046
3268
  if (consumers.length) queues.consumers = consumers;
@@ -3051,20 +3273,59 @@ function removeContribution(wrangler, contribution) {
3051
3273
  if (producers.length) queues.producers = producers;
3052
3274
  else delete queues.producers;
3053
3275
  }
3054
- 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;
3055
3296
  return {
3056
- ...hasQueues ? withoutQueues : wrangler,
3297
+ ...withoutOwned,
3057
3298
  ...hasQueues && Object.keys(queues).length ? { queues } : {},
3299
+ ...hasSecrets && Object.keys(secrets).length ? { secrets } : {},
3300
+ ...hasSecrets && Object.keys(environments).length ? { env: environments } : {},
3058
3301
  ...contribution.r2Buckets?.length ? { r2_buckets: removeEntries(wrangler.r2_buckets, contribution.r2Buckets) } : {},
3059
3302
  ...contribution.rateLimits?.length ? { ratelimits: removeEntries(wrangler.ratelimits, contribution.rateLimits) } : {}
3060
3303
  };
3061
3304
  }
3062
3305
  function mergeContribution(wrangler, owner, contribution) {
3063
3306
  const queues = cloneProviderRecord(wrangler.queues);
3307
+ const secrets = cloneProviderRecord(wrangler.secrets);
3308
+ const environments = cloneProviderRecord(wrangler.env);
3064
3309
  const consumers = compatibleEntries(queues.consumers, contribution.queues?.consumers, "queue", [], owner);
3065
3310
  const producers = compatibleEntries(queues.producers, contribution.queues?.producers, "binding", ["queue"], owner);
3066
3311
  const r2Buckets = compatibleEntries(wrangler.r2_buckets, contribution.r2Buckets, "binding", ["bucket_name"], owner);
3067
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
+ }
3068
3329
  const nextQueues = mergeProviderOutputConfig(queues, {
3069
3330
  ...consumers.length ? { consumers } : {},
3070
3331
  ...producers.length ? { producers } : {}
@@ -3075,7 +3336,9 @@ function mergeContribution(wrangler, owner, contribution) {
3075
3336
  return [mergeProviderOutputConfig(wrangler, {
3076
3337
  ...Object.keys(nextQueues).length ? { queues: nextQueues } : {},
3077
3338
  ...r2Buckets.length ? { r2_buckets: r2Buckets } : {},
3078
- ...rateLimits.length ? { ratelimits: rateLimits } : {}
3339
+ ...rateLimits.length ? { ratelimits: rateLimits } : {},
3340
+ ...Object.keys(secrets).length ? { secrets } : {},
3341
+ ...Object.keys(environments).length ? { env: environments } : {}
3079
3342
  }, { arrays: {
3080
3343
  r2_buckets: { key: "binding" },
3081
3344
  ratelimits: { key: "name" }
@@ -3085,25 +3348,37 @@ function mergeContribution(wrangler, owner, contribution) {
3085
3348
  producers
3086
3349
  },
3087
3350
  r2Buckets,
3088
- rateLimits
3351
+ rateLimits,
3352
+ requiredSecrets,
3353
+ requiredSecretsByEnvironment
3089
3354
  }];
3090
3355
  }
3091
- 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) {
3092
3371
  const nitro = cloneRecord(value);
3093
3372
  const cloudflare = cloneRecord(nitro.cloudflare);
3094
- const catalog = useCloudflareProviderOutput(config);
3095
- const inherited = value && typeof value === "object" ? value[cloudflareProviderOutputKey] ?? cloudflareProviderOutputByNitro.get(value) : void 0;
3096
- if (inherited && inherited !== catalog) {
3097
- for (const [owner, contribution] of inherited.appliedByOwner) catalog.appliedByOwner.set(owner, contribution);
3098
- catalog.contributionsByOwner = new Map([...inherited.contributionsByOwner, ...catalog.contributionsByOwner]);
3099
- }
3373
+ const inherited = inheritedProviderOutputCatalog(inheritedValue) ?? inheritedProviderOutputCatalog(value);
3374
+ if (inherited && inherited !== catalog) catalog.inheritCloudflareContributions(inherited);
3100
3375
  let wrangler = cloneProviderRecord(cloudflare.wrangler);
3101
- for (const contribution of catalog.appliedByOwner.values()) wrangler = removeContribution(wrangler, contribution);
3102
- catalog.appliedByOwner.clear();
3103
- 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()) {
3104
3379
  const [merged, applied] = mergeContribution(wrangler, owner, contribution);
3105
3380
  wrangler = merged;
3106
- catalog.appliedByOwner.set(owner, applied);
3381
+ catalog.replaceAppliedCloudflareContribution(owner, applied);
3107
3382
  }
3108
3383
  const output = !Object.keys(cloudflare).length && !Object.keys(wrangler).length ? nitro : {
3109
3384
  ...nitro,
@@ -3112,82 +3387,529 @@ function composeNitroCloudflareProviderOutput(config, value) {
3112
3387
  wrangler
3113
3388
  }
3114
3389
  };
3115
- Object.defineProperty(output, cloudflareProviderOutputKey, {
3116
- enumerable: true,
3117
- value: catalog
3118
- });
3119
- cloudflareProviderOutputByNitro.set(output, catalog);
3390
+ associateProviderOutputCatalog(output, catalog);
3120
3391
  return output;
3121
3392
  }
3122
3393
  //#endregion
3123
- //#region ../internal/src/build/deployment-output.ts
3124
- const composedProviderOutputKey = Symbol.for("vitehub.composedProviderOutput");
3125
- const providerDeploymentOutputWrites = /* @__PURE__ */ new Map();
3126
- 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) {
3127
3607
  const owner = config;
3128
- return owner[composedProviderOutputKey] ??= {
3129
- runtimeModuleFilesByProduct: {},
3130
- vercelRuntimePackagesByProduct: {}
3131
- };
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;
3132
3613
  }
3133
- function registerProviderRuntimeModules(composed, product, runtimeModuleFiles) {
3134
- if (composed) composed.runtimeModuleFilesByProduct[product] = runtimeModuleFiles;
3614
+ function contributeCloudflareProviderOutput(catalog, contribution) {
3615
+ const { owner, ...value } = contribution;
3616
+ catalog.replaceCloudflareContribution(owner, value);
3135
3617
  }
3136
- function resolveClientOutput(rootDir, clientOutDir) {
3137
- const clientDir = resolve(rootDir, clientOutDir);
3138
- return {
3139
- clientDir,
3140
- staticIndex: hasStaticIndex(clientDir)
3618
+ function contributeProviderRuntime(catalog, contribution, generation) {
3619
+ catalog?.replaceRuntimeContribution(contribution, generation);
3620
+ }
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];
3141
3638
  };
3142
3639
  }
3143
- function createDefaultCloudflareStaticOutputDir(rootDir) {
3144
- return resolve(rootDir, "dist", "client");
3640
+ function isServerEnvironment(name, config) {
3641
+ return name === "ssr" || config.consumer === "server";
3145
3642
  }
3146
- function createDefaultVercelOutputRoot(rootDir) {
3147
- return resolve(rootDir, ".vercel", "output");
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";
3148
3647
  }
3149
- function createDefaultNetlifyOutputRoot(rootDir) {
3150
- return resolve(rootDir, ".netlify", "v1");
3648
+ function hasNitroConfigContext(config) {
3649
+ return config["__vitehubNitroConfigContext"] === true || includesNitroVitePlugin(config.plugins);
3151
3650
  }
3152
- function assertNetlifyFunctionName(functionName) {
3153
- if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw new Error(`Invalid Netlify function name: ${functionName}`);
3651
+ function shouldSkipViteProviderBuild(command, mode) {
3652
+ return command === "serve" || mode === "e2e";
3154
3653
  }
3155
- function resolveNetlifyFunctionFile(functionsRoot, functionName) {
3156
- assertNetlifyFunctionName(functionName);
3157
- return resolve(functionsRoot, `${functionName}.mjs`);
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
+ }
3158
3671
  }
3159
- async function appendNetlifyFunctionConfig(outfile, config) {
3160
- if (!config) return;
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;
3161
3797
  await writeFile(outfile, `${(await readFile(outfile, "utf8")).trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
3162
3798
  }
3163
- async function writeCloudflareDeploymentOutput(options) {
3799
+ async function writeCloudflareDeploymentOutput(options, signal) {
3800
+ signal?.throwIfAborted();
3164
3801
  const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
3165
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));
3166
3805
  const files = Object.entries(options.files ?? {});
3167
3806
  const workerOutfile = options.bundleEntry ? resolve(outputRoot, options.bundleOutfileName ?? "index.js") : void 0;
3168
3807
  if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw new Error(`Cloudflare output file conflicts with bundle outfile: ${workerOutfile}`);
3169
- await mkdir(outputRoot, { recursive: true });
3170
- const writes = [
3171
- writeCloudflareWranglerConfig({
3172
- outputRoot,
3173
- rootDir: options.rootDir,
3174
- wranglerConfig: options.wranglerConfig,
3175
- wranglerConfigOwnership: options.wranglerConfigOwnership ?? { keys: options.wranglerConfigKeys }
3176
- }),
3177
- options.bundleEntry && staticIndex ? copyClientOutput(clientDir, options.staticOutputDir ?? createDefaultCloudflareStaticOutputDir(options.rootDir)) : Promise.resolve(),
3178
- ...files.map(([fileName, contents]) => writeFile(resolve(outputRoot, fileName), contents, "utf8"))
3179
- ];
3180
- if (options.bundleEntry && workerOutfile) {
3181
- 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, {
3182
3904
  force: true,
3183
3905
  recursive: true
3184
- });
3185
- writes.push(bundleEsmEntry(options.bundleEntry, workerOutfile, {
3186
- ...options.bundleOptions,
3187
- rootDir: options.rootDir
3188
- }));
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);
3189
3912
  }
3190
- await Promise.all(writes);
3191
3913
  }
3192
3914
  async function copyVercelClientOutput(rootDir, clientDir, staticOutputDir) {
3193
3915
  const cloudflareOutputRoot = createDefaultCloudflareOutputRoot(rootDir);
@@ -3206,53 +3928,199 @@ async function copyVercelClientOutput(rootDir, clientDir, staticOutputDir) {
3206
3928
  recursive: true
3207
3929
  });
3208
3930
  }
3209
- async function writeVercelDeploymentOutput(options) {
3931
+ async function writeVercelDeploymentOutput(options, signal) {
3932
+ signal?.throwIfAborted();
3210
3933
  const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
3211
3934
  const outputRoot = options.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir);
3935
+ const stagedOutputRoot = `${outputRoot}.pending`;
3936
+ const previousOutputRoot = `${outputRoot}.previous`;
3212
3937
  const functionOutput = options.function ?? { kind: "root" };
3213
3938
  const serverFunctionName = functionOutput.kind === "root" ? "__server.func" : functionOutput.name;
3214
3939
  const config = options.config ?? (functionOutput.kind === "root" ? createVercelConfigJson() : {});
3215
- const serverDir = resolve(outputRoot, "functions", serverFunctionName);
3940
+ const serverDir = resolve(stagedOutputRoot, "functions", serverFunctionName);
3216
3941
  const serverEntry = resolve(serverDir, "index.mjs");
3217
- await mkdir(serverDir, { recursive: true });
3218
- const staleFiles = (await readdir(serverDir)).filter((file) => file !== "node_modules");
3219
- await Promise.all(staleFiles.map((file) => rm(resolve(serverDir, file), {
3220
- force: true,
3221
- recursive: true
3222
- })));
3223
- await Promise.all([
3224
- 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, {
3225
3974
  ...options.bundleOptions,
3226
- rootDir: options.rootDir
3227
- }),
3228
- writeFile(resolve(serverDir, ".vc-config.json"), `${stringifyProviderOutputConfig(options.functionConfig ?? createNodeFunctionConfig())}\n`, "utf8"),
3229
- writeProviderOutputConfig(resolve(outputRoot, "config.json"), config, { keys: options.configKeys }),
3230
- staticIndex ? copyVercelClientOutput(options.rootDir, clientDir, options.staticOutputDir ?? resolve(outputRoot, "static")) : Promise.resolve()
3231
- ]);
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
+ }
3232
4055
  }
3233
- async function writeNetlifyDeploymentOutput(options) {
4056
+ async function writeNetlifyDeploymentOutput(options, signal) {
4057
+ signal?.throwIfAborted();
3234
4058
  const outputRoot = options.outputRoot ?? createDefaultNetlifyOutputRoot(options.rootDir);
3235
- 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
+ }
3236
4077
  const functionWrites = (options.functions ?? []).map(async (func) => {
3237
4078
  const outfile = resolveNetlifyFunctionFile(functionsRoot, func.functionName);
3238
- await rm(outfile, {
3239
- force: true,
3240
- recursive: true
3241
- });
3242
4079
  await mkdir(dirname(outfile), { recursive: true });
3243
4080
  await bundleEsmEntry(func.bundleEntry, outfile, {
3244
4081
  ...func.bundleOptions,
3245
4082
  minifyIdentifiers: func.config ? true : func.bundleOptions.minifyIdentifiers,
3246
- rootDir: options.rootDir
4083
+ rootDir: options.sourceRootDir ?? options.rootDir,
4084
+ signal
3247
4085
  });
3248
4086
  await appendNetlifyFunctionConfig(outfile, func.config);
3249
4087
  });
3250
- await mkdir(outputRoot, { recursive: true });
3251
- 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 {}
3252
4117
  }
3253
- async function cleanupCloudflareDeploymentOutput(rootDir, cleanupInput) {
4118
+ async function cleanupCloudflareDeploymentOutput(rootDir, cleanupInput, signal) {
3254
4119
  const cleanup = typeof cleanupInput === "function" ? await cleanupInput() : cleanupInput;
4120
+ signal?.throwIfAborted();
3255
4121
  const outputRoot = cleanup.outputRoot ?? createDefaultCloudflareOutputRoot(rootDir);
4122
+ if (!shouldRunCloudflareDeploymentOutputCleanup(outputRoot, cleanup)) return;
4123
+ const wranglerConfigOwnership = await resolvePersistedProviderOutputOwnership(outputRoot, cleanup.wranglerConfigOwnership, cleanup.wranglerConfigOwnershipFiles);
3256
4124
  const writes = (cleanup.fileNames ?? []).map((fileName) => rm(resolve(outputRoot, fileName), {
3257
4125
  force: true,
3258
4126
  recursive: true
@@ -3260,9 +4128,10 @@ async function cleanupCloudflareDeploymentOutput(rootDir, cleanupInput) {
3260
4128
  writes.push(writeCloudflareWranglerConfig({
3261
4129
  outputRoot,
3262
4130
  rootDir,
3263
- wranglerConfigOwnership: cleanup.wranglerConfigOwnership
4131
+ wranglerConfigOwnership
3264
4132
  }));
3265
4133
  await Promise.all(writes);
4134
+ await writeProviderOutputOwnershipFiles(outputRoot, cleanup.wranglerConfigOwnership, cleanup.wranglerConfigOwnershipFiles);
3266
4135
  try {
3267
4136
  await rmdir(outputRoot);
3268
4137
  } catch (error) {
@@ -3270,7 +4139,11 @@ async function cleanupCloudflareDeploymentOutput(rootDir, cleanupInput) {
3270
4139
  if (code !== "ENOENT" && code !== "ENOTEMPTY") throw error;
3271
4140
  }
3272
4141
  }
3273
- 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();
3274
4147
  const outputRoot = cleanup.outputRoot ?? createDefaultVercelOutputRoot(rootDir);
3275
4148
  const writes = [];
3276
4149
  if (cleanup.serverFunctionName) writes.push(rm(resolve(outputRoot, "functions", cleanup.serverFunctionName), {
@@ -3280,10 +4153,11 @@ async function cleanupVercelDeploymentOutput(rootDir, cleanup) {
3280
4153
  writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
3281
4154
  await Promise.all(writes);
3282
4155
  }
3283
- async function cleanupVercelDeploymentOutputs(rootDir, cleanup) {
3284
- 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)));
3285
4158
  }
3286
- async function cleanupNetlifyDeploymentOutput(rootDir, cleanup) {
4159
+ async function cleanupNetlifyDeploymentOutput(rootDir, cleanup, signal) {
4160
+ signal?.throwIfAborted();
3287
4161
  const outputRoot = cleanup.outputRoot ?? createDefaultNetlifyOutputRoot(rootDir);
3288
4162
  const functionsRoot = resolve(outputRoot, "functions");
3289
4163
  const writes = (cleanup.functionNames ?? []).map((functionName) => rm(resolveNetlifyFunctionFile(functionsRoot, functionName), {
@@ -3293,42 +4167,488 @@ async function cleanupNetlifyDeploymentOutput(rootDir, cleanup) {
3293
4167
  writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
3294
4168
  await Promise.all(writes);
3295
4169
  }
3296
- 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]);
3297
4174
  const writes = [];
3298
4175
  if (options.cloudflare) writes.push(writeCloudflareDeploymentOutput({
3299
4176
  ...options.cloudflare,
3300
4177
  clientOutDir: options.clientOutDir,
3301
- rootDir: options.rootDir
3302
- }));
3303
- else if (options.cleanup?.cloudflare) writes.push(cleanupCloudflareDeploymentOutput(options.rootDir, options.cleanup.cloudflare));
4178
+ rootDir: options.rootDir,
4179
+ sourceRootDir: options.sourceRootDir
4180
+ }, signal));
3304
4181
  if (options.netlify) writes.push(writeNetlifyDeploymentOutput({
3305
4182
  ...options.netlify,
3306
4183
  clientOutDir: options.clientOutDir,
3307
- rootDir: options.rootDir
3308
- }));
3309
- else if (options.cleanup?.netlify) writes.push(cleanupNetlifyDeploymentOutput(options.rootDir, options.cleanup.netlify));
4184
+ rootDir: options.rootDir,
4185
+ sourceRootDir: options.sourceRootDir
4186
+ }, signal));
3310
4187
  if (options.vercel) writes.push(writeVercelDeploymentOutput({
3311
4188
  ...options.vercel,
3312
4189
  clientOutDir: options.clientOutDir,
3313
- rootDir: options.rootDir
3314
- }));
3315
- 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) {
3316
4222
  const cleanup = typeof options.cleanup.vercel === "function" ? await options.cleanup.vercel() : options.cleanup.vercel;
3317
- 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
+ }
3318
4229
  }
3319
- await Promise.all(writes);
3320
- await options.afterWrite?.();
4230
+ await transaction?.snapshot(cleanupPaths, [clientDir]);
4231
+ await settleWrites(cleanups.map((cleanup) => cleanup()));
4232
+ signal?.throwIfAborted();
3321
4233
  }
3322
- async function writeProviderDeploymentOutputs(options) {
3323
- const key = resolve(options.rootDir);
3324
- const write = (providerDeploymentOutputWrites.get(key) ?? Promise.resolve()).catch(() => void 0).then(() => writeProviderDeploymentOutputsNow(options));
3325
- 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);
3326
4640
  try {
3327
- await write;
4641
+ await finalization;
3328
4642
  } finally {
3329
- if (providerDeploymentOutputWrites.get(key) === write) providerDeploymentOutputWrites.delete(key);
4643
+ if (providerDeploymentOutputFinalizations.get(catalog) === active) providerDeploymentOutputFinalizations.delete(catalog);
3330
4644
  }
3331
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
+ }
3332
4652
  //#endregion
3333
4653
  //#region ../internal/src/definition-catalog.ts
3334
4654
  const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
@@ -3353,11 +4673,15 @@ function readDirEntries(root) {
3353
4673
  throw error;
3354
4674
  }
3355
4675
  }
4676
+ function isGitRepositoryDirectory(directory) {
4677
+ return existsSync(resolve$1(directory, ".git"));
4678
+ }
3356
4679
  function listMatchingFiles(root, predicate, options = {}) {
3357
4680
  const files = [];
3358
4681
  for (const entry of readDirEntries(root)) {
3359
4682
  const absolute = resolve$1(root, entry.name);
3360
4683
  if (entry.isDirectory() && !entry.isSymbolicLink()) {
4684
+ if (isGitRepositoryDirectory(absolute)) continue;
3361
4685
  if (entry.name.startsWith(".")) continue;
3362
4686
  if (ignoredDirs.has(entry.name)) continue;
3363
4687
  files.push(...listMatchingFiles(absolute, predicate, options));
@@ -3766,6 +5090,9 @@ function discoverRateLimitCatalog(options) {
3766
5090
  declarations: [...declarations.values()].sort((left, right) => left.name.localeCompare(right.name))
3767
5091
  };
3768
5092
  }
5093
+ function discoverRateLimitDeclarations(options) {
5094
+ return discoverRateLimitCatalog(options).declarations;
5095
+ }
3769
5096
  //#endregion
3770
5097
  //#region src/internal/manifest.ts
3771
5098
  const rateLimitManifestPath = ".vitehub/rate-limit/manifest.json";
@@ -3799,12 +5126,15 @@ function outputStateFile(rootDir) {
3799
5126
  async function readOutputState(rootDir) {
3800
5127
  try {
3801
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) : [];
3802
5132
  return {
3803
- bindings: Array.isArray(parsed.bindings) ? parsed.bindings.filter((value) => typeof value === "string") : [],
3804
- standalone: parsed.standalone !== false && Array.isArray(parsed.bindings) && parsed.bindings.length > 0
5133
+ bindings,
5134
+ standalone: state.standalone !== false && bindings.length > 0
3805
5135
  };
3806
5136
  } catch (error) {
3807
- if (error.code === "ENOENT") return {
5137
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return {
3808
5138
  bindings: [],
3809
5139
  standalone: false
3810
5140
  };
@@ -3850,8 +5180,10 @@ function createCloudflareRateLimitBindings(declarations, namespace) {
3850
5180
  function resolveRateLimitNamespace(configured) {
3851
5181
  return configured?.trim() || void 0;
3852
5182
  }
3853
- async function writeRateLimitProviderOutput(options) {
5183
+ async function writeRateLimitProviderOutput(options, write = writeProviderDeploymentOutputs) {
5184
+ options.signal?.throwIfAborted();
3854
5185
  const state = await readOutputState(options.rootDir);
5186
+ options.signal?.throwIfAborted();
3855
5187
  const currentBindings = options.declarations.map((declaration) => getCloudflareRateLimitBindingName(declaration.name));
3856
5188
  const previousBindings = options.previousDeclarations?.map((declaration) => getCloudflareRateLimitBindingName(declaration.name)) ?? [];
3857
5189
  const ownership = { arrays: { ratelimits: {
@@ -3864,7 +5196,7 @@ async function writeRateLimitProviderOutput(options) {
3864
5196
  } } };
3865
5197
  if (options.cloudflareOwnedByNitro) {
3866
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.");
3867
- if (state.standalone && state.bindings.length > 0) await writeProviderDeploymentOutputs({
5199
+ if (state.standalone && state.bindings.length > 0) await write({
3868
5200
  clientOutDir: options.clientOutDir,
3869
5201
  cleanup: { cloudflare: {
3870
5202
  outputRoot: createDefaultCloudflareOutputRoot(options.rootDir),
@@ -3875,13 +5207,15 @@ async function writeRateLimitProviderOutput(options) {
3875
5207
  } },
3876
5208
  rootDir: options.rootDir
3877
5209
  });
5210
+ options.signal?.throwIfAborted();
3878
5211
  await writeOutputState(options.rootDir, []);
5212
+ options.signal?.throwIfAborted();
3879
5213
  await writeRateLimitManifest(options.rootDir, options.declarations, options.provider);
3880
5214
  return;
3881
5215
  }
3882
5216
  if (options.provider === "cloudflare" && options.declarations.length > 0) {
3883
5217
  if (!options.namespace) throw new Error("[vitehub] Cloudflare Rate Limit requires rateLimit.namespace to isolate counters between deployments.");
3884
- await writeProviderDeploymentOutputs({
5218
+ await write({
3885
5219
  clientOutDir: options.clientOutDir,
3886
5220
  cloudflare: {
3887
5221
  outputRoot: createDefaultCloudflareOutputRoot(options.rootDir),
@@ -3890,11 +5224,13 @@ async function writeRateLimitProviderOutput(options) {
3890
5224
  },
3891
5225
  rootDir: options.rootDir
3892
5226
  });
5227
+ options.signal?.throwIfAborted();
3893
5228
  await writeOutputState(options.rootDir, currentBindings, true);
5229
+ options.signal?.throwIfAborted();
3894
5230
  await writeRateLimitManifest(options.rootDir, options.declarations, options.provider);
3895
5231
  return;
3896
5232
  }
3897
- await writeProviderDeploymentOutputs({
5233
+ await write({
3898
5234
  clientOutDir: options.clientOutDir,
3899
5235
  cleanup: { cloudflare: {
3900
5236
  outputRoot: createDefaultCloudflareOutputRoot(options.rootDir),
@@ -3902,7 +5238,9 @@ async function writeRateLimitProviderOutput(options) {
3902
5238
  } },
3903
5239
  rootDir: options.rootDir
3904
5240
  });
5241
+ options.signal?.throwIfAborted();
3905
5242
  await writeOutputState(options.rootDir, []);
5243
+ options.signal?.throwIfAborted();
3906
5244
  await writeRateLimitManifest(options.rootDir, options.declarations, options.provider);
3907
5245
  }
3908
5246
  //#endregion
@@ -3910,14 +5248,13 @@ async function writeRateLimitProviderOutput(options) {
3910
5248
  const packageName = "@vite-hub/rate-limit";
3911
5249
  const pluginName = "@vite-hub/rate-limit/vite";
3912
5250
  const generatedNitroPlugin = ".vitehub/nitro/rate-limit/plugin.ts";
3913
- const legacyGeneratedNitroMiddleware = ".vitehub/nitro/rate-limit/middleware.ts";
3914
5251
  const generatedRuntimeModule = ".vitehub/rate-limit/cloudflare-runtime.mjs";
3915
- const legacyGeneratedRegistry = ".vitehub/nitro/rate-limit/registry.mjs";
3916
5252
  const mergeNoExternal = createNoExternalMerger(packageName);
3917
5253
  function cloneNitroConfig(value) {
3918
5254
  return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
3919
5255
  }
3920
5256
  function mergeNitroConfig(config, value, declarations, namespace, provider, nitroCloudflare) {
5257
+ const providerOutput = useProviderOutputCatalog(config);
3921
5258
  const nitro = cloneNitroConfig(value);
3922
5259
  const plugins = Array.isArray(nitro.plugins) ? [...nitro.plugins] : [];
3923
5260
  if (!plugins.includes(generatedNitroPlugin)) plugins.unshift(generatedNitroPlugin);
@@ -3926,12 +5263,15 @@ function mergeNitroConfig(config, value, declarations, namespace, provider, nitr
3926
5263
  plugins
3927
5264
  };
3928
5265
  if (!nitroCloudflare || provider !== "cloudflare" || declarations.length === 0) {
3929
- registerCloudflareProviderOutput(config, "rate-limit", {});
3930
- return composeNitroCloudflareProviderOutput(config, baseNitro);
5266
+ contributeCloudflareProviderOutput(providerOutput, { owner: "rate-limit" });
5267
+ return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
3931
5268
  }
3932
5269
  if (!namespace) throw new Error("[vitehub] Cloudflare Rate Limit requires rateLimit.namespace to isolate counters between deployments.");
3933
- registerCloudflareProviderOutput(config, "rate-limit", { rateLimits: createCloudflareRateLimitBindings(declarations, namespace) });
3934
- return composeNitroCloudflareProviderOutput(config, baseNitro);
5270
+ contributeCloudflareProviderOutput(providerOutput, {
5271
+ owner: "rate-limit",
5272
+ rateLimits: createCloudflareRateLimitBindings(declarations, namespace)
5273
+ });
5274
+ return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
3935
5275
  }
3936
5276
  function renderRuntimeInstaller(runtimeConfig, importBase, nitro) {
3937
5277
  return [
@@ -3964,6 +5304,7 @@ function hubRateLimit(options = {}) {
3964
5304
  const importBase = options.importBase ?? packageName;
3965
5305
  let rateLimit = options;
3966
5306
  let composedOutput;
5307
+ const providerOutputGenerations = createProviderDeploymentOutputGenerationState();
3967
5308
  let declarations = [];
3968
5309
  let declarationFiles = /* @__PURE__ */ new Set();
3969
5310
  let cloudflareOwnedByNitro = false;
@@ -3999,7 +5340,7 @@ function hubRateLimit(options = {}) {
3999
5340
  async configResolved(config) {
4000
5341
  resolved = config;
4001
5342
  rateLimit = config.rateLimit ?? rateLimit;
4002
- composedOutput = useComposedProviderOutput(config);
5343
+ composedOutput = useProviderOutputCatalog(config);
4003
5344
  projectRoot = resolveViteHubProjectRoot(config.root, { projectRoot: rateLimit.projectRoot });
4004
5345
  const configuredNitro = config.nitro;
4005
5346
  const nitroCloudflare = resolveNitroHosting(configuredNitro) === "cloudflare";
@@ -4009,16 +5350,13 @@ function hubRateLimit(options = {}) {
4009
5350
  config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), provider, nitroCloudflare);
4010
5351
  await writeRateLimitManifest(config.root, declarations, provider);
4011
5352
  const pluginFile = resolve(config.root, generatedNitroPlugin);
4012
- const middlewareFile = resolve(config.root, legacyGeneratedNitroMiddleware);
4013
5353
  const runtimeFile = resolve(config.root, generatedRuntimeModule);
4014
5354
  const runtimeConfig = { provider };
4015
- await Promise.all([
4016
- rm(resolve(config.root, legacyGeneratedRegistry), { force: true }),
4017
- rm(middlewareFile, { force: true }),
4018
- writeFileIfChanged(pluginFile, renderRuntimeInstaller(runtimeConfig, importBase, true)),
4019
- writeFileIfChanged(runtimeFile, renderRuntimeInstaller(runtimeConfig, importBase, false))
4020
- ]);
4021
- 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
+ });
4022
5360
  },
4023
5361
  configEnvironment(name, config) {
4024
5362
  if (!isServerEnvironment(name, config)) return;
@@ -4033,27 +5371,60 @@ function hubRateLimit(options = {}) {
4033
5371
  if (provider !== "cloudflare" || !resolved?.build.ssr || !declarationFiles.has(id.split("?", 1)[0])) return;
4034
5372
  return `import ${JSON.stringify(normalizePath(resolve(resolved.root, generatedRuntimeModule)))}\n${code}`;
4035
5373
  },
4036
- 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
+ }
4037
5382
  if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
4038
- if (cloudflareOwnedByNitro && provider === "cloudflare") {
4039
- const configuredDeclarations = declarations;
4040
- collectDeclarations();
4041
- 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.");
4042
- await writeRateLimitManifest(resolved.root, declarations, provider);
4043
- } else await refreshDeclarations();
4044
- const namespace = resolveRateLimitNamespace(rateLimit.namespace);
4045
- await writeRateLimitProviderOutput({
4046
- clientOutDir: resolved.build.outDir,
4047
- cloudflareOwnedByNitro,
4048
- declarations,
4049
- namespace,
4050
- previousDeclarations,
4051
- provider,
4052
- rootDir: resolved.root
4053
- });
4054
- 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
+ }
4055
5426
  }
4056
5427
  };
4057
5428
  }
4058
5429
  //#endregion
4059
- export { hubRateLimit };
5430
+ export { discoverRateLimitDeclarations, hubRateLimit };