@vite-hub/rate-limit 0.0.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vite.js CHANGED
@@ -1,17 +1,189 @@
1
- import { i as rateLimitPolicyKeys, n as declaredRateLimitPolicy, r as normalizeRateLimitPolicy, t as createRateLimiter } from "./limiter-CHaHluMr.js";
2
- import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "./cloudflare-BYZQ2tim.js";
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-CTAC_bbr.js";
2
+ import { i as rateLimitPolicyKeys, n as declaredRateLimitPolicy, r as normalizeRateLimitPolicy, t as createRateLimiter } from "./limiter-DBrMI4vi.js";
3
3
  import { memoryRateLimitDriver } from "./drivers/memory.js";
4
+ import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "./cloudflare-DUDRACVB.js";
5
+ import { n as relativeDefinitionFile, r as resolve$1 } from "./inspect-D-FzyM_x.js";
6
+ import { S as isPlainObject, _ as shouldSkipViteProviderBuild, b as removeViteHubDevServerFile, c as operationRpcPath, g as resolveViteHubProjectRoot, h as isServerEnvironment, m as createNoExternalAddition, p as internalErrorDiagnostics, r as collectOperationContributions, v as readViteHubDevServerFile, x as writeViteHubDevServerFile } from "./operations-B09NnEjT.js";
4
7
  import { createRequire } from "node:module";
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";
9
- import { fileURLToPath } from "node:url";
10
- import { isDeepStrictEqual } from "node:util";
11
- import { Visitor, normalizePath, parseSync } from "vite";
8
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
9
+ import { basename, relative, resolve } from "node:path";
10
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
11
+ import { Visitor, parseSync } from "vite";
12
12
  //#region \0rolldown/runtime.js
13
13
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
14
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
14
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
15
+ //#endregion
16
+ //#region ../internal/src/definition-catalog.ts
17
+ const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
18
+ const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
19
+ const ignoredDirs = /* @__PURE__ */ new Set([
20
+ "node_modules",
21
+ "dist",
22
+ ".output",
23
+ ".nuxt",
24
+ ".vercel",
25
+ ".git",
26
+ ".vitehub"
27
+ ]);
28
+ function resolveDefinitionScanRoots(rootDir, scanDirs = []) {
29
+ return [...new Set([rootDir, ...scanDirs].filter(Boolean))];
30
+ }
31
+ function readDirEntries(root) {
32
+ try {
33
+ return readdirSync(root, { withFileTypes: true });
34
+ } catch (error) {
35
+ if (error.code === "ENOENT") return [];
36
+ throw error;
37
+ }
38
+ }
39
+ function isGitRepositoryDirectory(directory) {
40
+ return existsSync(resolve$1(directory, ".git"));
41
+ }
42
+ function listMatchingFiles(root, predicate, options = {}) {
43
+ const files = [];
44
+ for (const entry of readDirEntries(root)) {
45
+ const absolute = resolve$1(root, entry.name);
46
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
47
+ if (isGitRepositoryDirectory(absolute)) continue;
48
+ if (entry.name.startsWith(".")) continue;
49
+ if (ignoredDirs.has(entry.name)) continue;
50
+ files.push(...listMatchingFiles(absolute, predicate, options));
51
+ continue;
52
+ }
53
+ if (entry.name.startsWith(".") && !options.includeHidden) continue;
54
+ if (entry.isFile() && predicate(entry.name)) files.push(absolute);
55
+ }
56
+ return files.sort();
57
+ }
58
+ function listSourceFiles(root, options = {}) {
59
+ return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
60
+ }
61
+ async function writeFileIfChanged(file, contents) {
62
+ if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
63
+ await mkdir(resolve$1(file, ".."), { recursive: true });
64
+ await writeFile(file, contents, "utf8");
65
+ }
66
+ //#endregion
67
+ //#region ../internal/src/nitro-kit.ts
68
+ function cloneArray(value) {
69
+ return Array.isArray(value) ? [...value] : [];
70
+ }
71
+ function isRecord(value) {
72
+ return Object(value) === value && !Array.isArray(value);
73
+ }
74
+ function sameHandler(left, right) {
75
+ return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
76
+ }
77
+ /** Create a Nitro 3 configuration builder for generated ViteHub output. */
78
+ function createNitroServerKit(value = {}) {
79
+ const config = isRecord(value) ? { ...value } : {};
80
+ const handlers = cloneArray(config.handlers);
81
+ const plugins = cloneArray(config.plugins);
82
+ config.handlers = handlers;
83
+ config.plugins = plugins;
84
+ return {
85
+ config,
86
+ addHandler(handler, position = "end") {
87
+ if (handlers.some((candidate) => isRecord(candidate) && sameHandler(candidate, handler))) return;
88
+ if (position === "start") handlers.unshift({ ...handler });
89
+ else handlers.push({ ...handler });
90
+ },
91
+ addPlugin(plugin, position = "end") {
92
+ if (plugins.includes(plugin)) return;
93
+ if (position === "start") plugins.unshift(plugin);
94
+ else plugins.push(plugin);
95
+ }
96
+ };
97
+ }
98
+ //#endregion
99
+ //#region ../internal/src/contributions.ts
100
+ function isThenable(value) {
101
+ return typeof value.then === "function";
102
+ }
103
+ async function flattenPlugins(value, plugins, seen) {
104
+ if (Array.isArray(value)) {
105
+ for (const item of value) await flattenPlugins(item, plugins, seen);
106
+ return;
107
+ }
108
+ if (!isPlainObject(value) || seen.has(value)) return;
109
+ seen.add(value);
110
+ if (isThenable(value)) {
111
+ await flattenPlugins(await value, plugins, seen);
112
+ return;
113
+ }
114
+ plugins.push(value);
115
+ }
116
+ /**
117
+ * Flattens Vite plugin options as `collectContributions` reads them: nested arrays and promised options become one
118
+ * list of plugin objects, and falsy entries are dropped. A plugin that filters itself out of `context.plugins` must
119
+ * filter this list, because `vitehub()` nests its plugins in an array.
120
+ */
121
+ async function flattenPluginOptions(plugins) {
122
+ const flattened = [];
123
+ await flattenPlugins(plugins ?? [], flattened, /* @__PURE__ */ new Set());
124
+ return flattened;
125
+ }
126
+ //#endregion
127
+ //#region ../internal/src/operations-vite.ts
128
+ const owners = /* @__PURE__ */ new Set([
129
+ "@vite-hub/kv/operations",
130
+ "@vite-hub/blob/operations",
131
+ "@vite-hub/email/operations",
132
+ "@vite-hub/rate-limit/operations"
133
+ ]);
134
+ const discoveryInstalled = Symbol.for("vitehub.operations.dev.discovery");
135
+ /** Publish only the elected standalone transport; other Console policies retain their own discovery hook. */
136
+ function publishStandaloneOperationServer(server) {
137
+ const http = server.httpServer;
138
+ if (!http || Reflect.get(server, discoveryInstalled)) return;
139
+ const root = resolve(server.config.root);
140
+ const handlers = Reflect.get(Object(Reflect.get(server.config, "nitro")), "handlers");
141
+ if (!Array.isArray(handlers) || !handlers.some((handler) => handler?.handler === resolve(root, ".vitehub/nitro/operations/rpc.mjs"))) return;
142
+ Reflect.set(server, discoveryInstalled, true);
143
+ let ownedUrl;
144
+ const write = () => {
145
+ const address = http.address();
146
+ if (!address || typeof address === "string") return;
147
+ const host = address.address === "::" || address.address === "0.0.0.0" ? "localhost" : address.family === "IPv6" ? `[${address.address}]` : address.address;
148
+ const url = server.resolvedUrls?.local[0] ?? `${server.config.server.https ? "https" : "http"}://${host}:${address.port}${server.config.base}`;
149
+ try {
150
+ writeViteHubDevServerFile(root, {
151
+ root,
152
+ url
153
+ });
154
+ ownedUrl = url;
155
+ } catch {}
156
+ };
157
+ if (http.listening) write();
158
+ else http.once("listening", write);
159
+ http.once("close", () => {
160
+ try {
161
+ if (ownedUrl && readViteHubDevServerFile(root)?.url === ownedUrl) removeViteHubDevServerFile(root);
162
+ } catch {}
163
+ });
164
+ }
165
+ /** Standalone primitives share one local Nitro RPC. The root integration owns its own access policy. */
166
+ async function installStandaloneOperationRpc(config, command, module) {
167
+ if (command !== "serve") return;
168
+ const plugins = await flattenPluginOptions(config.plugins);
169
+ if (plugins.some((plugin) => Reflect.get(plugin, "name") === "vite-hub/dependencies" || Reflect.get(plugin, "name") === "vite-hub/console")) return;
170
+ const contributions = (await collectOperationContributions(plugins)).filter((source) => source.runtime !== false);
171
+ if (contributions.find((source) => owners.has(source.module))?.module !== module) return;
172
+ const root = resolve(config.root ?? process.cwd());
173
+ const handler = resolve(root, ".vitehub/nitro/operations/rpc.mjs");
174
+ await writeFileIfChanged(handler, [
175
+ `import { createStandaloneOperationHandler } from ${JSON.stringify(module)}`,
176
+ ...contributions.map((entry, index) => `import * as source${index} from ${JSON.stringify(entry.module)}`),
177
+ `export default createStandaloneOperationHandler([${contributions.map((entry, index) => `{ operations: source${index}[${JSON.stringify(entry.export)}], plugin: ${JSON.stringify(entry.plugin)} }`).join(", ")}], ${JSON.stringify(root)})`,
178
+ ""
179
+ ].join("\n"));
180
+ const kit = createNitroServerKit(Reflect.get(config, "nitro"));
181
+ kit.addHandler({
182
+ handler,
183
+ route: operationRpcPath
184
+ });
185
+ Reflect.set(config, "nitro", kit.config);
186
+ }
15
187
  const VITEHUB_MODES = {
16
188
  e2e: "e2e",
17
189
  blob: "blob",
@@ -41,127 +213,6 @@ function getViteMode(env = process.env) {
41
213
  return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
42
214
  }
43
215
  //#endregion
44
- //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
45
- const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
46
- function normalizeWindowsPath(input = "") {
47
- if (!input) return input;
48
- return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
49
- }
50
- const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
51
- const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
52
- const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
53
- function cwd() {
54
- if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
55
- return "/";
56
- }
57
- const resolve$1 = function(...arguments_) {
58
- arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
59
- let resolvedPath = "";
60
- let resolvedAbsolute = false;
61
- for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
62
- const path = index >= 0 ? arguments_[index] : cwd();
63
- if (!path || path.length === 0) continue;
64
- resolvedPath = `${path}/${resolvedPath}`;
65
- resolvedAbsolute = isAbsolute$1(path);
66
- }
67
- resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
68
- if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
69
- return resolvedPath.length > 0 ? resolvedPath : ".";
70
- };
71
- function normalizeString(path, allowAboveRoot) {
72
- let res = "";
73
- let lastSegmentLength = 0;
74
- let lastSlash = -1;
75
- let dots = 0;
76
- let char = null;
77
- for (let index = 0; index <= path.length; ++index) {
78
- if (index < path.length) char = path[index];
79
- else if (char === "/") break;
80
- else char = "/";
81
- if (char === "/") {
82
- if (lastSlash === index - 1 || dots === 1);
83
- else if (dots === 2) {
84
- if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
85
- if (res.length > 2) {
86
- const lastSlashIndex = res.lastIndexOf("/");
87
- if (lastSlashIndex === -1) {
88
- res = "";
89
- lastSegmentLength = 0;
90
- } else {
91
- res = res.slice(0, lastSlashIndex);
92
- lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
93
- }
94
- lastSlash = index;
95
- dots = 0;
96
- continue;
97
- } else if (res.length > 0) {
98
- res = "";
99
- lastSegmentLength = 0;
100
- lastSlash = index;
101
- dots = 0;
102
- continue;
103
- }
104
- }
105
- if (allowAboveRoot) {
106
- res += res.length > 0 ? "/.." : "..";
107
- lastSegmentLength = 2;
108
- }
109
- } else {
110
- if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
111
- else res = path.slice(lastSlash + 1, index);
112
- lastSegmentLength = index - lastSlash - 1;
113
- }
114
- lastSlash = index;
115
- dots = 0;
116
- } else if (char === "." && dots !== -1) ++dots;
117
- else dots = -1;
118
- }
119
- return res;
120
- }
121
- const isAbsolute$1 = function(p) {
122
- return _IS_ABSOLUTE_RE.test(p);
123
- };
124
- const relative$1 = function(from, to) {
125
- const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
126
- const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
127
- if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
128
- const _fromCopy = [..._from];
129
- for (const segment of _fromCopy) {
130
- if (_to[0] !== segment) break;
131
- _from.shift();
132
- _to.shift();
133
- }
134
- return [..._from.map(() => ".."), ..._to].join("/");
135
- };
136
- const dirname$1 = function(p) {
137
- const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
138
- if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
139
- return segments.join("/") || (isAbsolute$1(p) ? "/" : ".");
140
- };
141
- //#endregion
142
- //#region ../internal/src/build/client-output.ts
143
- function hasStaticIndex(clientDir) {
144
- return existsSync(resolve$1(clientDir, "index.html"));
145
- }
146
- async function copyClientOutput(clientDir, targetDir) {
147
- const resolvedClientDir = resolve$1(clientDir);
148
- const resolvedTargetDir = resolve$1(targetDir);
149
- if (resolvedClientDir === resolvedTargetDir) return;
150
- await rm(resolvedTargetDir, {
151
- force: true,
152
- recursive: true
153
- });
154
- await mkdir(dirname$1(resolvedTargetDir), { recursive: true });
155
- const targetRelativePath = relative$1(resolvedClientDir, resolvedTargetDir);
156
- if (targetRelativePath && !targetRelativePath.startsWith("../")) {
157
- const [targetRootEntry] = targetRelativePath.split("/", 1);
158
- await mkdir(resolvedTargetDir, { recursive: true });
159
- await Promise.all((await readdir(resolvedClientDir)).filter((entry) => entry !== targetRootEntry).map((entry) => cp(resolve$1(resolvedClientDir, entry), resolve$1(resolvedTargetDir, entry), { recursive: true })));
160
- return;
161
- }
162
- await cp(resolvedClientDir, resolvedTargetDir, { recursive: true });
163
- }
164
- //#endregion
165
216
  //#region ../internal/src/build/provider-output-config.ts
166
217
  function isProviderJsonArray(value, ancestors) {
167
218
  if (Object.getPrototypeOf(value) !== Array.prototype || ancestors.has(value)) return false;
@@ -205,20 +256,7 @@ function isProviderJsonRecord(value) {
205
256
  }
206
257
  }
207
258
  function assertProviderJsonRecord(value) {
208
- if (!isProviderJsonRecord(value)) throw new TypeError("[vitehub] Provider output config must be a JSON object.");
209
- }
210
- function isFileNotFoundError(error) {
211
- return error instanceof Error && "code" in error && error.code === "ENOENT";
212
- }
213
- async function readProviderJsonRecord(file) {
214
- try {
215
- const parsed = JSON.parse(await readFile(file, "utf8"));
216
- assertProviderJsonRecord(parsed);
217
- return parsed;
218
- } catch (error) {
219
- if (isFileNotFoundError(error)) return;
220
- throw error;
221
- }
259
+ if (!isProviderJsonRecord(value)) throw internalErrorDiagnostics.INTERNAL_B0043({ message: "[vitehub] Provider output config must be a JSON object." });
222
260
  }
223
261
  function deleteOwnedFields(value, ownership, cleanup = false) {
224
262
  const next = { ...value };
@@ -238,7 +276,7 @@ function preserveUnownedKeyedArrayEntries(value, ownership, replacements = []) {
238
276
  const key = getKeyedArrayEntryValue(entry, ownership.key);
239
277
  return key === void 0 ? [] : [key];
240
278
  });
241
- const ownedKeys = new Set([...ownership.values ?? [], ...replacementKeys]);
279
+ const ownedKeys = /* @__PURE__ */ new Set([...ownership.values ?? [], ...replacementKeys]);
242
280
  return current.filter((entry) => {
243
281
  const key = getKeyedArrayEntryValue(entry, ownership.key);
244
282
  return key === void 0 || !ownedKeys.has(key);
@@ -254,22 +292,6 @@ function mergeOwnedArrays(existing, value, arrays) {
254
292
  }
255
293
  return next;
256
294
  }
257
- async function persistProviderJsonRecord(file, value, removeIfEmpty) {
258
- if (removeIfEmpty && !Object.keys(value).length) {
259
- await rm(file, { force: true });
260
- return;
261
- }
262
- await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
263
- }
264
- async function writeProviderOutputConfig(file, value, ownership = {}, options = {}) {
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);
272
- }
273
295
  function mergeProviderOutputConfig(existing, value, ownership = {}) {
274
296
  assertProviderJsonRecord(existing);
275
297
  assertProviderJsonRecord(value);
@@ -278,54 +300,7 @@ function mergeProviderOutputConfig(existing, value, ownership = {}) {
278
300
  ...mergeOwnedArrays(existing, value, ownership.arrays)
279
301
  };
280
302
  }
281
- function stringifyProviderOutputConfig(value) {
282
- assertProviderJsonRecord(value);
283
- return JSON.stringify(value, null, 2);
284
- }
285
- async function cleanProviderOutputConfig(file, ownership) {
286
- if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
287
- const existing = await readProviderJsonRecord(file);
288
- if (!existing) return;
289
- const next = deleteOwnedFields(existing, ownership, true);
290
- let changed = (ownership.keys ?? []).some((key) => key in existing);
291
- for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
292
- if (arrayOwnership.preserveOnCleanup) continue;
293
- if (!(field in existing)) continue;
294
- const current = existing[field];
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;
298
- if (preserved.length) next[field] = preserved;
299
- }
300
- if (!changed) return;
301
- await persistProviderJsonRecord(file, next, true);
302
- }
303
- //#endregion
304
- //#region ../internal/src/build/user-entry.ts
305
- function toSafeAppName(rootDir) {
306
- return basename(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
307
- }
308
- //#endregion
309
- //#region ../internal/src/build/cloudflare.ts
310
- function createDefaultCloudflareOutputRoot(rootDir) {
311
- return resolve(rootDir, "dist", toSafeAppName(rootDir));
312
- }
313
- async function writeCloudflareWranglerConfig(options) {
314
- const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
315
- const configFile = resolve(outputRoot, "wrangler.json");
316
- if (!options.wranglerConfig) {
317
- await cleanProviderOutputConfig(configFile, options.wranglerConfigOwnership ?? {});
318
- return;
319
- }
320
- await mkdir(outputRoot, { recursive: true });
321
- await writeProviderOutputConfig(configFile, options.wranglerConfig, options.wranglerConfigOwnership, {
322
- defaults: options.wranglerConfigDefaults,
323
- removeIfEmpty: true
324
- });
325
- }
326
- //#endregion
327
- //#region ../internal/src/object.ts
328
- var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
303
+ (/* @__PURE__ */ __commonJSMin(((exports, module) => {
329
304
  var __defProp = Object.defineProperty;
330
305
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
331
306
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -435,7 +410,7 @@ var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
435
410
  };
436
411
  }
437
412
  var ByteBuffer = class {
438
- constructor(buf = new Uint8Array(1024)) {
413
+ constructor(buf = /* @__PURE__ */ new Uint8Array(1024)) {
439
414
  this.buf = buf;
440
415
  this.len = 0;
441
416
  this.ptr = 0;
@@ -638,9 +613,7 @@ is not a problem with esbuild. You need to fix your environment instead.
638
613
  value += fromCharCode(code);
639
614
  break;
640
615
  }
641
- default:
642
- throwSyntaxError(bytes, --i);
643
- break;
616
+ default: throwSyntaxError(bytes, --i);
644
617
  }
645
618
  else if (c <= 127) value += fromCharCode(c);
646
619
  else if ((c & 224) === 192) value += fromCharCode((c & 31) << 6 | bytes[i++] & 63);
@@ -705,23 +678,21 @@ is not a problem with esbuild. You need to fix your environment instead.
705
678
  }
706
679
  if (c === 93) continue;
707
680
  break;
708
- case 2:
709
- if (property === null) {
710
- property = value;
711
- if (c === 58) {
712
- i++;
713
- continue;
714
- }
715
- } else {
716
- object[property] = value;
717
- property = null;
718
- if (c === 44) {
719
- i++;
720
- continue;
721
- }
722
- if (c === 125) continue;
681
+ case 2: if (property === null) {
682
+ property = value;
683
+ if (c === 58) {
684
+ i++;
685
+ continue;
723
686
  }
724
- break;
687
+ } else {
688
+ object[property] = value;
689
+ property = null;
690
+ if (c === 44) {
691
+ i++;
692
+ continue;
693
+ }
694
+ if (c === 125) continue;
695
+ }
725
696
  }
726
697
  break;
727
698
  }
@@ -966,19 +937,21 @@ is not a problem with esbuild. You need to fix your environment instead.
966
937
  if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`);
967
938
  flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
968
939
  }
969
- if (entryPoints) if (Array.isArray(entryPoints)) for (let i = 0, n = entryPoints.length; i < n; i++) {
970
- let entryPoint = entryPoints[i];
971
- if (typeof entryPoint === "object" && entryPoint !== null) {
972
- let entryPointKeys = /* @__PURE__ */ Object.create(null);
973
- let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
974
- let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
975
- checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
976
- if (input === void 0) throw new Error("Missing property \"in\" for entry point at index " + i);
977
- if (output === void 0) throw new Error("Missing property \"out\" for entry point at index " + i);
978
- entries.push([output, input]);
979
- } else entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
940
+ if (entryPoints) {
941
+ if (Array.isArray(entryPoints)) for (let i = 0, n = entryPoints.length; i < n; i++) {
942
+ let entryPoint = entryPoints[i];
943
+ if (typeof entryPoint === "object" && entryPoint !== null) {
944
+ let entryPointKeys = /* @__PURE__ */ Object.create(null);
945
+ let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
946
+ let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
947
+ checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
948
+ if (input === void 0) throw new Error("Missing property \"in\" for entry point at index " + i);
949
+ if (output === void 0) throw new Error("Missing property \"out\" for entry point at index " + i);
950
+ entries.push([output, input]);
951
+ } else entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
952
+ }
953
+ else for (let key in entryPoints) entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
980
954
  }
981
- else for (let key in entryPoints) entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
982
955
  if (stdin) {
983
956
  let stdinKeys = /* @__PURE__ */ Object.create(null);
984
957
  let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
@@ -1039,7 +1012,7 @@ is not a problem with esbuild. You need to fix your environment instead.
1039
1012
  let responseCallbacks = {};
1040
1013
  let nextRequestID = 0;
1041
1014
  let nextBuildKey = 0;
1042
- let stdout = new Uint8Array(16 * 1024);
1015
+ let stdout = /* @__PURE__ */ new Uint8Array(16384);
1043
1016
  let stdoutUsed = 0;
1044
1017
  let readFromStdout = (chunk) => {
1045
1018
  let limit = stdoutUsed + chunk.length;
@@ -1233,7 +1206,7 @@ is not a problem with esbuild. You need to fix your environment instead.
1233
1206
  });
1234
1207
  }
1235
1208
  };
1236
- if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
1209
+ if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1048576) {
1237
1210
  let next = start;
1238
1211
  start = () => fs3.writeFile(input, next);
1239
1212
  }
@@ -2122,11 +2095,13 @@ ${file}:${line}:${column}: ERROR: ${e.pluginName ? `[plugin: ${e.pluginName}] `
2122
2095
  return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
2123
2096
  }
2124
2097
  function generateBinPath() {
2125
- if (isValidBinaryPath(ESBUILD_BINARY_PATH)) if (!fs.existsSync(ESBUILD_BINARY_PATH)) console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
2126
- else return {
2127
- binPath: ESBUILD_BINARY_PATH,
2128
- isWASM: false
2129
- };
2098
+ if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
2099
+ if (!fs.existsSync(ESBUILD_BINARY_PATH)) console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
2100
+ else return {
2101
+ binPath: ESBUILD_BINARY_PATH,
2102
+ isWASM: false
2103
+ };
2104
+ }
2130
2105
  const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
2131
2106
  let binPath;
2132
2107
  try {
@@ -2489,7 +2464,7 @@ More information: The file containing the code for esbuild's JavaScript API (${_
2489
2464
  };
2490
2465
  var runServiceSync = (callback) => {
2491
2466
  let [command, args] = esbuildCommandAndArgs();
2492
- let stdin = new Uint8Array();
2467
+ let stdin = /* @__PURE__ */ new Uint8Array();
2493
2468
  let { readFromStdout, afterClose, service } = createChannel({
2494
2469
  writeToStdin(bytes) {
2495
2470
  if (stdin.length !== 0) throw new Error("Must run at most one command");
@@ -2504,7 +2479,7 @@ More information: The file containing the code for esbuild's JavaScript API (${_
2504
2479
  cwd: defaultWD,
2505
2480
  windowsHide: true,
2506
2481
  input: stdin,
2507
- maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
2482
+ maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16777216
2508
2483
  }));
2509
2484
  afterClose(null);
2510
2485
  };
@@ -2673,559 +2648,28 @@ error: ${text}`);
2673
2648
  version
2674
2649
  });
2675
2650
  })))();
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;
2683
- }
2684
- }
2685
- //#endregion
2686
- //#region ../internal/src/build/esbuild.ts
2687
- const viteRawNamespace = "vitehub-vite-raw";
2688
- const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
2689
- const markdownTemplateFileSuffix = ".template.md";
2690
- const markdownTemplateModuleQuery = "markdown-template";
2691
- const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
2692
- const skipResolvedAlias = "vitehubSkipResolvedAlias";
2693
- const encodedAliasPrefixMarker = "\0vitehub-prefix:";
2694
- const encodedAliasExactMarker = "\0vitehub-exact:";
2695
- const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
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
- };
2949
- }
2950
- function stripMarkdownCode(template) {
2951
- let fence;
2952
- let inList = false;
2953
- let previousLineBlank = true;
2954
- return template.split("\n").map((line) => {
2955
- const content = line.replace(/^(?: {0,3}> ?)+/, "");
2956
- if (!fence) {
2957
- const listIndented = inList && /^ {4}(?:`{3,}|~{3,})/.test(content);
2958
- const opening = (listIndented ? content.slice(4) : content).match(/^ {0,3}(`{3,}|~{3,})/);
2959
- if (!opening) {
2960
- if (/^ {0,3}(?:[-+*]|\d+[.)])\s+/.test(content)) inList = true;
2961
- else if (content.trim() && !/^ {2,}/.test(content)) inList = false;
2962
- const indentedCode = !inList && previousLineBlank && /^(?: {4}|\t)/.test(content) || inList && previousLineBlank && /^(?: {8}| {4}\t|\t{2})/.test(content);
2963
- previousLineBlank = content.trim() === "";
2964
- return indentedCode ? "" : line;
2965
- }
2966
- fence = {
2967
- marker: opening[1][0],
2968
- length: opening[1].length,
2969
- listIndented
2970
- };
2971
- previousLineBlank = false;
2972
- return "";
2973
- }
2974
- const closing = (fence.listIndented ? content.replace(/^ {4}/, "") : content).match(/^ {0,3}(`+|~+)\s*$/)?.[1];
2975
- if (closing?.[0] === fence.marker && closing.length >= fence.length) fence = void 0;
2976
- previousLineBlank = false;
2977
- return "";
2978
- }).join("\n");
2979
- }
2980
- function extractMarkdownTemplateImportSpecifiers(template) {
2981
- const visible = stripMarkdownCode(template).replace(/(`+)[\s\S]*?\1/g, "").replace(/(!?\[[^\]]*\])\([^)]*\)/g, "$1").replace(/^ {0,3}\[[^\]]+\]:\s*\S+/gm, "").replace(/<[^>]*>/g, "");
2982
- const specifiers = /* @__PURE__ */ new Set();
2983
- for (const match of visible.matchAll(/@(\.\.?\/[^\s<>{}[\]]+)/g)) {
2984
- const token = match[1];
2985
- const trailing = token.match(/[.,;:!?)]*$/)?.[0] || "";
2986
- specifiers.add(token.slice(0, token.length - trailing.length));
2987
- }
2988
- return [...specifiers];
2989
- }
2990
- function parseMarkdownTemplateRequest(id) {
2991
- const queryIndex = id.indexOf("?");
2992
- const path = id.split(/[?#]/, 1)[0];
2993
- if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix) ? { path } : void 0;
2994
- const query = id.slice(queryIndex + 1).split("#", 1)[0];
2995
- if (!new URLSearchParams(query).has(markdownTemplateModuleQuery)) return;
2996
- return { path };
2997
- }
2998
- function renderMarkdownTemplateModule(template, sourceId, imports = {}) {
2999
- return [
3000
- `import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier)}`,
3001
- `const vitehubMarkdownTemplate = ${JSON.stringify(template)}`,
3002
- `const vitehubMarkdownTemplateSourceId = ${JSON.stringify(sourceId)}`,
3003
- `const vitehubMarkdownTemplateImports = ${JSON.stringify(imports)}`,
3004
- "export default function render(data = {}) {",
3005
- " return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data, sourceId: vitehubMarkdownTemplateSourceId, resolveImport: (specifier, importer) => vitehubMarkdownTemplateImports[`${importer}\\0${specifier}`] })",
3006
- "}",
3007
- ""
3008
- ].join("\n");
3009
- }
3010
- function hasViteRawQuery(path) {
3011
- const queryIndex = path.indexOf("?");
3012
- return queryIndex !== -1 && /(?:^|&)raw(?:&|$)/.test(path.slice(queryIndex + 1));
3013
- }
3014
- async function resolveViteRawSpecifier(path, rootDir) {
3015
- if (path.startsWith("/@fs/")) return path.slice(5);
3016
- if (!rootDir || !path.startsWith("/")) return path;
3017
- const rootRelativePath = path.slice(1);
3018
- const publicPath = resolve(rootDir, "public", rootRelativePath);
3019
- try {
3020
- await stat(publicPath);
3021
- return publicPath;
3022
- } catch (error) {
3023
- if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
3024
- return resolve(rootDir, rootRelativePath);
3025
- }
3026
- }
3027
- function createViteRawPlugin(rootDir, frameworkRuntime) {
3028
- return {
3029
- name: "vitehub-vite-raw",
3030
- setup(build) {
3031
- build.onResolve({
3032
- filter: /^@vite-hub\/markdown-template$/,
3033
- namespace: viteMarkdownTemplateNamespace
3034
- }, async (args) => {
3035
- if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
3036
- return build.resolve("vite-hub/_internal/markdown-template", {
3037
- importer: args.importer,
3038
- kind: args.kind,
3039
- resolveDir: args.resolveDir
3040
- });
3041
- });
3042
- build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
3043
- if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
3044
- const markdownTemplate = parseMarkdownTemplateRequest(args.path);
3045
- const raw = hasViteRawQuery(args.path);
3046
- if (!markdownTemplate && !raw) return;
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
- };
3053
- const resolved = await build.resolve(specifier, {
3054
- importer: args.importer,
3055
- kind: args.kind,
3056
- namespace: args.namespace,
3057
- pluginData,
3058
- resolveDir: args.resolveDir,
3059
- with: args.with
3060
- });
3061
- if (resolved.errors.length) return {
3062
- errors: resolved.errors,
3063
- warnings: resolved.warnings
3064
- };
3065
- if (resolved.external) return {
3066
- external: true,
3067
- namespace: resolved.namespace,
3068
- path: resolved.path,
3069
- pluginData: resolved.pluginData,
3070
- sideEffects: resolved.sideEffects,
3071
- suffix: resolved.suffix,
3072
- warnings: resolved.warnings
3073
- };
3074
- if (resolved.namespace !== "file") return {
3075
- errors: [{ text: markdownTemplate ? `[vitehub] Markdown template fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this template import in a caller plugin.` : `[vitehub] Vite raw fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this raw import in a caller plugin.` }],
3076
- warnings: resolved.warnings
3077
- };
3078
- return {
3079
- namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
3080
- path: resolved.path,
3081
- pluginData: resolved.pluginData,
3082
- sideEffects: resolved.sideEffects,
3083
- suffix: resolved.suffix,
3084
- warnings: resolved.warnings
3085
- };
3086
- });
3087
- build.onLoad({
3088
- filter: /.*/,
3089
- namespace: viteRawNamespace
3090
- }, async (args) => ({
3091
- contents: await readFile(args.path),
3092
- loader: "text"
3093
- }));
3094
- build.onLoad({
3095
- filter: /.*/,
3096
- namespace: viteMarkdownTemplateNamespace
3097
- }, async (args) => ({
3098
- contents: await (async () => {
3099
- const template = await readFile(args.path, "utf8");
3100
- const imports = {};
3101
- const visited = new Set([args.path]);
3102
- const visit = async (source, importer) => {
3103
- for (const specifier of extractMarkdownTemplateImportSpecifiers(source)) {
3104
- const key = `${importer}\0${specifier}`;
3105
- if (imports[key]) continue;
3106
- const resolved = await build.resolve(specifier, {
3107
- importer,
3108
- kind: "import-statement",
3109
- pluginData: {
3110
- ...args.pluginData,
3111
- [skipMarkdownTemplateResolve]: true
3112
- },
3113
- resolveDir: dirname(importer)
3114
- });
3115
- if (resolved.errors.length) return Promise.reject(new Error(resolved.errors.map((error) => error.text).join("\n")));
3116
- if (resolved.external || resolved.namespace !== "file") throw new Error(`[vitehub] Could not resolve Markdown template import ${JSON.stringify(specifier)} from ${JSON.stringify(importer)} to a file.`);
3117
- const imported = {
3118
- id: resolved.path,
3119
- template: await readFile(resolved.path, "utf8")
3120
- };
3121
- imports[key] = imported;
3122
- if (!visited.has(imported.id)) {
3123
- visited.add(imported.id);
3124
- await visit(imported.template, imported.id);
3125
- }
3126
- }
3127
- };
3128
- await visit(template, args.path);
3129
- return renderMarkdownTemplateModule(template, args.path, imports);
3130
- })(),
3131
- loader: "js",
3132
- resolveDir: dirname(args.path)
3133
- }));
3134
- }
3135
- };
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
- }
3145
- async function bundleEsmEntry(entryFile, outfile, options = {}) {
3146
- options.signal?.throwIfAborted();
3147
- const format = options.format || "esm";
3148
- const platform = options.platform || "neutral";
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,
3159
- banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
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
- "}"
3165
- ] : []].filter(Boolean).join("\n") } : void 0,
3166
- bundle: true,
3167
- conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
3168
- entryPoints: [entryFile],
3169
- external: options.external,
3170
- format,
3171
- logLevel: "silent",
3172
- mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
3173
- resolveExtensions: options.extensions,
3174
- minifyIdentifiers: options.minifyIdentifiers,
3175
- minifyWhitespace: options.minifyWhitespace,
3176
- outfile,
3177
- packages: options.packages,
3178
- platform,
3179
- preserveSymlinks: options.preserveSymlinks,
3180
- plugins,
3181
- sourcemap: false,
3182
- target: "es2022",
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();
2651
+ /** Select the runtime constants from one resolved Vite configuration. */
2652
+ function resolveViteHubBundleDefines(config) {
2653
+ const defines = {};
2654
+ for (const name of ["__VITEHUB_PUBLIC_URL__", "__VITEHUB_APP_BASE_URL__"]) {
2655
+ const value = config.define?.[name];
2656
+ if (typeof value === "string") defines[name] = value;
3193
2657
  }
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
3204
- });
3205
- }
3206
- //#endregion
3207
- //#region ../internal/src/build/vercel-config.ts
3208
- function createVercelConfigJson() {
3209
- return {
3210
- routes: [{ handle: "filesystem" }, {
3211
- src: "/(.*)",
3212
- dest: "/__server"
3213
- }],
3214
- version: 3
3215
- };
3216
- }
3217
- function createNodeFunctionConfig(extra = {}) {
3218
- return {
3219
- handler: "index.mjs",
3220
- launcherType: "Nodejs",
3221
- runtime: "nodejs22.x",
3222
- shouldAddHelpers: false,
3223
- supportsResponseStreaming: true,
3224
- ...extra
3225
- };
2658
+ return defines;
3226
2659
  }
3227
2660
  //#endregion
3228
2661
  //#region ../internal/src/build/cloudflare-provider-output.ts
2662
+ function isDeepStrictEqual(left, right) {
2663
+ if (Object.is(left, right)) return true;
2664
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
2665
+ if (Array.isArray(left) !== Array.isArray(right)) return false;
2666
+ if (Array.isArray(left)) return left.length === right.length && left.every((value, index) => isDeepStrictEqual(value, right[index]));
2667
+ const leftRecord = left;
2668
+ const rightRecord = right;
2669
+ const leftKeys = Object.keys(leftRecord);
2670
+ const rightKeys = Object.keys(rightRecord);
2671
+ return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.hasOwn(rightRecord, key) && isDeepStrictEqual(leftRecord[key], rightRecord[key]));
2672
+ }
3229
2673
  const providerOutputCatalogRegistry$1 = globalThis;
3230
2674
  const providerOutputCatalogByNitroValue = providerOutputCatalogRegistry$1.__vitehubProviderOutputCatalogsByNitroValue ??= /* @__PURE__ */ new WeakMap();
3231
2675
  function cloneRecord(value) {
@@ -3249,7 +2693,7 @@ function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner)
3249
2693
  current.push(entry);
3250
2694
  return true;
3251
2695
  }
3252
- if (conflictKeys.some((key) => !isDeepStrictEqual(match[key], entry[key]))) throw new Error(`[vitehub] Cloudflare ${identityKey} ${JSON.stringify(identity)} from ${owner} is already assigned to an incompatible resource.`);
2696
+ if (conflictKeys.some((key) => !isDeepStrictEqual(match[key], entry[key]))) throw internalErrorDiagnostics.INTERNAL_B0001({ message: `[vitehub] Cloudflare ${identityKey} ${JSON.stringify(identity)} from ${owner} is already assigned to an incompatible resource.` });
3253
2697
  return false;
3254
2698
  });
3255
2699
  }
@@ -3279,7 +2723,7 @@ function removeContribution(wrangler, contribution) {
3279
2723
  else delete secrets.required;
3280
2724
  }
3281
2725
  for (const [name, requiredSecrets] of Object.entries(contribution.requiredSecretsByEnvironment ?? {})) {
3282
- if (!(name in environments)) continue;
2726
+ if (!Object.hasOwn(environments, name)) continue;
3283
2727
  const environment = cloneProviderRecord(environments[name]);
3284
2728
  const environmentSecrets = cloneProviderRecord(environment.secrets);
3285
2729
  const required = removeEntries(environmentSecrets.required, requiredSecrets);
@@ -3308,7 +2752,7 @@ function mergeContribution(wrangler, owner, contribution) {
3308
2752
  const environments = cloneProviderRecord(wrangler.env);
3309
2753
  const consumers = compatibleEntries(queues.consumers, contribution.queues?.consumers, "queue", [], owner);
3310
2754
  const producers = compatibleEntries(queues.producers, contribution.queues?.producers, "binding", ["queue"], owner);
3311
- const r2Buckets = compatibleEntries(wrangler.r2_buckets, contribution.r2Buckets, "binding", ["bucket_name"], owner);
2755
+ const r2Buckets = compatibleEntries(wrangler.r2_buckets, contribution.r2Buckets, "binding", ["bucket_name", "jurisdiction"], owner);
3312
2756
  const rateLimits = compatibleEntries(wrangler.ratelimits, contribution.rateLimits, "name", ["namespace_id", "simple"], owner);
3313
2757
  const currentRequiredSecrets = Array.isArray(secrets.required) ? secrets.required : [];
3314
2758
  const requiredSecrets = (contribution.requiredSecrets ?? []).filter((name) => !currentRequiredSecrets.includes(name));
@@ -3393,6 +2837,7 @@ function composeNitroCloudflareProviderOutput(catalog, value, inheritedValue = v
3393
2837
  //#endregion
3394
2838
  //#region ../internal/src/build/provider-output-catalog.ts
3395
2839
  var ProviderOutputCatalog = class {
2840
+ bundleDefines = {};
3396
2841
  #appliedCloudflareContributions = /* @__PURE__ */ new Map();
3397
2842
  #cloudflareContributions = /* @__PURE__ */ new Map();
3398
2843
  #runtimeContributions = /* @__PURE__ */ new Map();
@@ -3443,8 +2888,21 @@ var ProviderOutputCatalog = class {
3443
2888
  runtimeContributions(generation) {
3444
2889
  return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.entries() ?? (/* @__PURE__ */ new Map()).entries();
3445
2890
  }
3446
- resetRuntimeContributions() {
3447
- this.#runtimeContributions.clear();
2891
+ resetRuntimeContributions(generation, owner) {
2892
+ if (generation) {
2893
+ if (owner) this.#runtimeContributionsByGeneration.get(generation)?.delete(owner);
2894
+ else this.#runtimeContributionsByGeneration.delete(generation);
2895
+ return;
2896
+ }
2897
+ if (owner) this.#runtimeContributions.delete(owner);
2898
+ else this.#runtimeContributions.clear();
2899
+ }
2900
+ resetRuntimeContribution(product, generation) {
2901
+ if (!generation) {
2902
+ this.#runtimeContributions.delete(product);
2903
+ return;
2904
+ }
2905
+ this.#runtimeContributionsByGeneration.get(generation)?.delete(product);
3448
2906
  }
3449
2907
  createDeploymentGeneration() {
3450
2908
  const generation = { valid: true };
@@ -3607,6 +3065,7 @@ function useProviderOutputCatalog(config) {
3607
3065
  const owner = config;
3608
3066
  let catalog = owner[providerOutputCatalog] ?? providerOutputCatalogs.get(config);
3609
3067
  if (!catalog) catalog = createProviderOutputCatalog();
3068
+ catalog.bundleDefines = resolveViteHubBundleDefines(config);
3610
3069
  owner[providerOutputCatalog] = catalog;
3611
3070
  providerOutputCatalogs.set(config, catalog);
3612
3071
  return catalog;
@@ -3615,1091 +3074,6 @@ function contributeCloudflareProviderOutput(catalog, contribution) {
3615
3074
  const { owner, ...value } = contribution;
3616
3075
  catalog.replaceCloudflareContribution(owner, value);
3617
3076
  }
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];
3638
- };
3639
- }
3640
- function isServerEnvironment(name, config) {
3641
- return name === "ssr" || config.consumer === "server";
3642
- }
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";
3647
- }
3648
- function hasNitroConfigContext(config) {
3649
- return config["__vitehubNitroConfigContext"] === true || includesNitroVitePlugin(config.plugins);
3650
- }
3651
- function shouldSkipViteProviderBuild(command, mode) {
3652
- return command === "serve" || mode === "e2e";
3653
- }
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
- }
3671
- }
3672
- function hasProjectRootDirectoryMarker(root) {
3673
- for (const marker of projectRootDirectoryMarkers) try {
3674
- if (statSync(resolve(root, ...marker)).isDirectory()) return true;
3675
- } catch (error) {
3676
- if (error.code !== "ENOENT") throw error;
3677
- }
3678
- return false;
3679
- }
3680
- function hasProjectRootMarker(root) {
3681
- if (hasProjectRootDirectoryMarker(root)) return true;
3682
- for (const marker of projectRootFileMarkers) try {
3683
- if (statSync(resolve(root, ...marker)).isFile()) return true;
3684
- } catch (error) {
3685
- if (error.code !== "ENOENT") throw error;
3686
- }
3687
- return false;
3688
- }
3689
- //#endregion
3690
- //#region ../internal/src/build/deployment-output.ts
3691
- const providerDeploymentOutputRegistry = globalThis;
3692
- const providerDeploymentOutputWrites = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputWrites ??= /* @__PURE__ */ new Map();
3693
- const providerDeploymentOutputFinalizations = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputFinalizations ??= /* @__PURE__ */ new WeakMap();
3694
- const providerDeploymentOutputCompletedResets = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputCompletedResets ??= /* @__PURE__ */ new WeakMap();
3695
- const providerDeploymentOutputRootStates = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputRootStates ??= /* @__PURE__ */ new Map();
3696
- const providerDeploymentOutputOwnerOrder = [
3697
- "agent",
3698
- "database",
3699
- "blob",
3700
- "queue",
3701
- "rate-limit",
3702
- "schedule",
3703
- "workflow",
3704
- "vite-hub",
3705
- "browser",
3706
- "kv",
3707
- "workspace"
3708
- ];
3709
- function throwIfProviderOutputAborted(signal) {
3710
- if (!signal.aborted) return;
3711
- throw signal.reason ?? new DOMException("Provider Output finalization aborted.", "AbortError");
3712
- }
3713
- async function settleWrites(writes) {
3714
- const failure = (await Promise.allSettled(writes)).find((result) => result.status === "rejected");
3715
- if (failure) throw failure.reason;
3716
- }
3717
- function resolveClientOutput(rootDir, clientOutDir) {
3718
- const clientDir = resolve(rootDir, clientOutDir);
3719
- return {
3720
- clientDir,
3721
- staticIndex: hasStaticIndex(clientDir)
3722
- };
3723
- }
3724
- function createDefaultCloudflareStaticOutputDir(rootDir) {
3725
- return resolve(rootDir, "dist", "client");
3726
- }
3727
- function resolveProviderOutputOwnershipFile(outputRoot, fileName) {
3728
- if (!fileName || fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") throw new TypeError(`Invalid Provider Output ownership file name: ${JSON.stringify(fileName)}`);
3729
- return resolve(outputRoot, fileName);
3730
- }
3731
- async function readProviderOutputOwnershipFile(outputRoot, fileName) {
3732
- try {
3733
- const parsed = JSON.parse(await readFile(resolveProviderOutputOwnershipFile(outputRoot, fileName), "utf8"));
3734
- if (!Array.isArray(parsed) || !parsed.every((value) => typeof value === "string")) throw new TypeError(`Invalid Provider Output ownership file schema: ${JSON.stringify(fileName)}`);
3735
- return parsed;
3736
- } catch (error) {
3737
- if (error instanceof Error && "code" in error && error.code === "ENOENT") return [];
3738
- throw error;
3739
- }
3740
- }
3741
- async function readCloudflareProviderDeploymentOutputState(rootDir, options) {
3742
- const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(rootDir);
3743
- let wranglerConfig = {};
3744
- try {
3745
- wranglerConfig = JSON.parse(await readFile(resolve(outputRoot, "wrangler.json"), "utf8"));
3746
- } catch (error) {
3747
- if (error.code !== "ENOENT") throw error;
3748
- }
3749
- return {
3750
- wranglerConfig,
3751
- wranglerConfigOwnership: await resolvePersistedProviderOutputOwnership(outputRoot, options.wranglerConfigOwnership, options.wranglerConfigOwnershipFiles)
3752
- };
3753
- }
3754
- async function resolvePersistedProviderOutputOwnership(outputRoot, ownership, files) {
3755
- if (!files || !Object.keys(files).length) return ownership;
3756
- const arrays = { ...ownership?.arrays };
3757
- await Promise.all(Object.entries(files).map(async ([field, fileName]) => {
3758
- const current = arrays[field];
3759
- if (!current) throw new TypeError(`Provider Output ownership file for ${JSON.stringify(field)} requires array ownership.`);
3760
- arrays[field] = {
3761
- ...current,
3762
- values: [...await readProviderOutputOwnershipFile(outputRoot, fileName), ...current.values ?? []]
3763
- };
3764
- }));
3765
- return {
3766
- ...ownership,
3767
- arrays
3768
- };
3769
- }
3770
- async function writeProviderOutputOwnershipFiles(outputRoot, ownership, files) {
3771
- await Promise.all(Object.entries(files ?? {}).map(async ([field, fileName]) => {
3772
- const file = resolveProviderOutputOwnershipFile(outputRoot, fileName);
3773
- const values = [...new Set(ownership?.arrays?.[field]?.values ?? [])];
3774
- if (!values.length) {
3775
- await rm(file, { force: true });
3776
- return;
3777
- }
3778
- await mkdir(outputRoot, { recursive: true });
3779
- await writeFile(file, `${JSON.stringify(values, null, 2)}\n`, "utf8");
3780
- }));
3781
- }
3782
- function createDefaultVercelOutputRoot(rootDir) {
3783
- return resolve(rootDir, ".vercel", "output");
3784
- }
3785
- function createDefaultNetlifyOutputRoot(rootDir) {
3786
- return resolve(rootDir, ".netlify", "v1");
3787
- }
3788
- function assertNetlifyFunctionName(functionName) {
3789
- if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw new Error(`Invalid Netlify function name: ${functionName}`);
3790
- }
3791
- function resolveNetlifyFunctionFile(functionsRoot, functionName) {
3792
- assertNetlifyFunctionName(functionName);
3793
- return resolve(functionsRoot, `${functionName}.mjs`);
3794
- }
3795
- async function appendNetlifyFunctionConfig(outfile, config) {
3796
- if (!config) return;
3797
- await writeFile(outfile, `${(await readFile(outfile, "utf8")).trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
3798
- }
3799
- async function writeCloudflareDeploymentOutput(options, signal) {
3800
- signal?.throwIfAborted();
3801
- const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
3802
- const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
3803
- const staticOutputDir = options.staticOutputDir ?? createDefaultCloudflareStaticOutputDir(options.rootDir);
3804
- const copiesStaticOutput = Boolean(options.bundleEntry && staticIndex && resolve(clientDir) !== resolve(staticOutputDir));
3805
- const files = Object.entries(options.files ?? {});
3806
- const workerOutfile = options.bundleEntry ? resolve(outputRoot, options.bundleOutfileName ?? "index.js") : void 0;
3807
- if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw new Error(`Cloudflare output file conflicts with bundle outfile: ${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, {
3904
- force: true,
3905
- recursive: true
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);
3912
- }
3913
- }
3914
- async function copyVercelClientOutput(rootDir, clientDir, staticOutputDir) {
3915
- const cloudflareOutputRoot = createDefaultCloudflareOutputRoot(rootDir);
3916
- const outputRelativePath = relative(clientDir, cloudflareOutputRoot);
3917
- const excludesCloudflareOutput = outputRelativePath && outputRelativePath !== ".." && !outputRelativePath.startsWith(`..${sep}`) && !isAbsolute(outputRelativePath);
3918
- await copyClientOutput(clientDir, staticOutputDir);
3919
- if (resolve(clientDir) === resolve(staticOutputDir) || !excludesCloudflareOutput) return;
3920
- try {
3921
- await readFile(resolve(cloudflareOutputRoot, "wrangler.json"));
3922
- } catch (error) {
3923
- if (error.code === "ENOENT") return;
3924
- throw error;
3925
- }
3926
- await rm(resolve(staticOutputDir, outputRelativePath), {
3927
- force: true,
3928
- recursive: true
3929
- });
3930
- }
3931
- async function writeVercelDeploymentOutput(options, signal) {
3932
- signal?.throwIfAborted();
3933
- const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
3934
- const outputRoot = options.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir);
3935
- const stagedOutputRoot = `${outputRoot}.pending`;
3936
- const previousOutputRoot = `${outputRoot}.previous`;
3937
- const functionOutput = options.function ?? { kind: "root" };
3938
- const serverFunctionName = functionOutput.kind === "root" ? "__server.func" : functionOutput.name;
3939
- const config = options.config ?? (functionOutput.kind === "root" ? createVercelConfigJson() : {});
3940
- const serverDir = resolve(stagedOutputRoot, "functions", serverFunctionName);
3941
- const serverEntry = resolve(serverDir, "index.mjs");
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, {
3974
- ...options.bundleOptions,
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
- }
4055
- }
4056
- async function writeNetlifyDeploymentOutput(options, signal) {
4057
- signal?.throwIfAborted();
4058
- const outputRoot = options.outputRoot ?? createDefaultNetlifyOutputRoot(options.rootDir);
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
- }
4077
- const functionWrites = (options.functions ?? []).map(async (func) => {
4078
- const outfile = resolveNetlifyFunctionFile(functionsRoot, func.functionName);
4079
- await mkdir(dirname(outfile), { recursive: true });
4080
- await bundleEsmEntry(func.bundleEntry, outfile, {
4081
- ...func.bundleOptions,
4082
- minifyIdentifiers: func.config ? true : func.bundleOptions.minifyIdentifiers,
4083
- rootDir: options.sourceRootDir ?? options.rootDir,
4084
- signal
4085
- });
4086
- await appendNetlifyFunctionConfig(outfile, func.config);
4087
- });
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 {}
4117
- }
4118
- async function cleanupCloudflareDeploymentOutput(rootDir, cleanupInput, signal) {
4119
- const cleanup = typeof cleanupInput === "function" ? await cleanupInput() : cleanupInput;
4120
- signal?.throwIfAborted();
4121
- const outputRoot = cleanup.outputRoot ?? createDefaultCloudflareOutputRoot(rootDir);
4122
- if (!shouldRunCloudflareDeploymentOutputCleanup(outputRoot, cleanup)) return;
4123
- const wranglerConfigOwnership = await resolvePersistedProviderOutputOwnership(outputRoot, cleanup.wranglerConfigOwnership, cleanup.wranglerConfigOwnershipFiles);
4124
- const writes = (cleanup.fileNames ?? []).map((fileName) => rm(resolve(outputRoot, fileName), {
4125
- force: true,
4126
- recursive: true
4127
- }));
4128
- writes.push(writeCloudflareWranglerConfig({
4129
- outputRoot,
4130
- rootDir,
4131
- wranglerConfigOwnership
4132
- }));
4133
- await Promise.all(writes);
4134
- await writeProviderOutputOwnershipFiles(outputRoot, cleanup.wranglerConfigOwnership, cleanup.wranglerConfigOwnershipFiles);
4135
- try {
4136
- await rmdir(outputRoot);
4137
- } catch (error) {
4138
- const code = error.code;
4139
- if (code !== "ENOENT" && code !== "ENOTEMPTY") throw error;
4140
- }
4141
- }
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();
4147
- const outputRoot = cleanup.outputRoot ?? createDefaultVercelOutputRoot(rootDir);
4148
- const writes = [];
4149
- if (cleanup.serverFunctionName) writes.push(rm(resolve(outputRoot, "functions", cleanup.serverFunctionName), {
4150
- force: true,
4151
- recursive: true
4152
- }));
4153
- writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
4154
- await Promise.all(writes);
4155
- }
4156
- async function cleanupVercelDeploymentOutputs(rootDir, cleanup, signal) {
4157
- await Promise.all((Array.isArray(cleanup) ? cleanup : [cleanup]).map((item) => cleanupVercelDeploymentOutput(rootDir, item, signal)));
4158
- }
4159
- async function cleanupNetlifyDeploymentOutput(rootDir, cleanup, signal) {
4160
- signal?.throwIfAborted();
4161
- const outputRoot = cleanup.outputRoot ?? createDefaultNetlifyOutputRoot(rootDir);
4162
- const functionsRoot = resolve(outputRoot, "functions");
4163
- const writes = (cleanup.functionNames ?? []).map((functionName) => rm(resolveNetlifyFunctionFile(functionsRoot, functionName), {
4164
- force: true,
4165
- recursive: true
4166
- }));
4167
- writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
4168
- await Promise.all(writes);
4169
- }
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]);
4174
- const writes = [];
4175
- if (options.cloudflare) writes.push(writeCloudflareDeploymentOutput({
4176
- ...options.cloudflare,
4177
- clientOutDir: options.clientOutDir,
4178
- rootDir: options.rootDir,
4179
- sourceRootDir: options.sourceRootDir
4180
- }, signal));
4181
- if (options.netlify) writes.push(writeNetlifyDeploymentOutput({
4182
- ...options.netlify,
4183
- clientOutDir: options.clientOutDir,
4184
- rootDir: options.rootDir,
4185
- sourceRootDir: options.sourceRootDir
4186
- }, signal));
4187
- if (options.vercel) writes.push(writeVercelDeploymentOutput({
4188
- ...options.vercel,
4189
- clientOutDir: options.clientOutDir,
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) {
4222
- const cleanup = typeof options.cleanup.vercel === "function" ? await options.cleanup.vercel() : options.cleanup.vercel;
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
- }
4229
- }
4230
- await transaction?.snapshot(cleanupPaths, [clientDir]);
4231
- await settleWrites(cleanups.map((cleanup) => cleanup()));
4232
- signal?.throwIfAborted();
4233
- }
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);
4640
- try {
4641
- await finalization;
4642
- } finally {
4643
- if (providerDeploymentOutputFinalizations.get(catalog) === active) providerDeploymentOutputFinalizations.delete(catalog);
4644
- }
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
- }
4652
- //#endregion
4653
- //#region ../internal/src/definition-catalog.ts
4654
- const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
4655
- const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
4656
- const ignoredDirs = new Set([
4657
- "node_modules",
4658
- "dist",
4659
- ".output",
4660
- ".nuxt",
4661
- ".vercel",
4662
- ".git",
4663
- ".vitehub"
4664
- ]);
4665
- function resolveDefinitionScanRoots(rootDir, scanDirs = []) {
4666
- return [...new Set([rootDir, ...scanDirs].filter(Boolean))];
4667
- }
4668
- function readDirEntries(root) {
4669
- try {
4670
- return readdirSync(root, { withFileTypes: true });
4671
- } catch (error) {
4672
- if (error.code === "ENOENT") return [];
4673
- throw error;
4674
- }
4675
- }
4676
- function isGitRepositoryDirectory(directory) {
4677
- return existsSync(resolve$1(directory, ".git"));
4678
- }
4679
- function listMatchingFiles(root, predicate, options = {}) {
4680
- const files = [];
4681
- for (const entry of readDirEntries(root)) {
4682
- const absolute = resolve$1(root, entry.name);
4683
- if (entry.isDirectory() && !entry.isSymbolicLink()) {
4684
- if (isGitRepositoryDirectory(absolute)) continue;
4685
- if (entry.name.startsWith(".")) continue;
4686
- if (ignoredDirs.has(entry.name)) continue;
4687
- files.push(...listMatchingFiles(absolute, predicate, options));
4688
- continue;
4689
- }
4690
- if (entry.name.startsWith(".") && !options.includeHidden) continue;
4691
- if (entry.isFile() && predicate(entry.name)) files.push(absolute);
4692
- }
4693
- return files.sort();
4694
- }
4695
- function listSourceFiles(root, options = {}) {
4696
- return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
4697
- }
4698
- async function writeFileIfChanged(file, contents) {
4699
- if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
4700
- await mkdir(resolve$1(file, ".."), { recursive: true });
4701
- await writeFile(file, contents, "utf8");
4702
- }
4703
3077
  function deploymentPresetFromNitro(value) {
4704
3078
  const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
4705
3079
  if (!normalized) return;
@@ -4711,19 +3085,45 @@ function deploymentPresetFromNitro(value) {
4711
3085
  }
4712
3086
  //#endregion
4713
3087
  //#region ../internal/src/hosting.ts
3088
+ /**
3089
+ * Returns the Nitro preset name that this build targets, as the developer wrote it.
3090
+ * The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOSTING`.
3091
+ * Empty values are skipped.
3092
+ */
3093
+ function resolveHostPreset(input = {}) {
3094
+ const env = input.env ?? (typeof process === "undefined" ? {} : process.env);
3095
+ const nitroPreset = input.nitro && typeof input.nitro === "object" ? Reflect.get(input.nitro, "preset") : void 0;
3096
+ for (const value of [
3097
+ nitroPreset,
3098
+ input.hosting,
3099
+ env.NITRO_PRESET,
3100
+ env.SERVER_PRESET,
3101
+ env.VITEHUB_HOSTING
3102
+ ]) if (typeof value === "string" && value.trim()) return value.trim();
3103
+ }
3104
+ /** Returns the host that this build targets: `cloudflare`, `deno`, `netlify`, `node`, or `vercel`. */
3105
+ function resolveHost(input = {}) {
3106
+ return deploymentPresetFromNitro(resolveHostPreset(input));
3107
+ }
3108
+ /** Narrows a preset or host name to the hosts that have a native provider: Cloudflare, Netlify, or Vercel. */
4714
3109
  function getHostingProvider(hosting) {
4715
3110
  const preset = deploymentPresetFromNitro(hosting);
4716
3111
  if (preset === "cloudflare" || preset === "netlify" || preset === "vercel") return preset;
4717
3112
  }
4718
3113
  //#endregion
4719
3114
  //#region src/discovery.ts
4720
- const rateLimitImports = new Set(["@vite-hub/rate-limit", "vite-hub/rate-limit"]);
4721
- const ignoredSourceDirectories = new Set([
3115
+ const rateLimitImports = /* @__PURE__ */ new Set(["@vite-hub/rate-limit", "vite-hub/rate-limit"]);
3116
+ /** Functions whose calls declare a managed Rate Limit. Both consume the same counters. */
3117
+ const rateLimitGuards = ["checkRateLimit", "requireRateLimit"];
3118
+ function isRateLimitGuard(name) {
3119
+ return rateLimitGuards.some((guard) => guard === name);
3120
+ }
3121
+ const ignoredSourceDirectories = /* @__PURE__ */ new Set([
4722
3122
  "__tests__",
4723
3123
  "test",
4724
3124
  "tests"
4725
3125
  ]);
4726
- const nestedIgnoredSourceDirectories = new Set(["__tests__", "tests"]);
3126
+ const nestedIgnoredSourceDirectories = /* @__PURE__ */ new Set(["__tests__", "tests"]);
4727
3127
  function isApplicationSource(root, file) {
4728
3128
  const segments = relative(root, file).split(/[\\/]/);
4729
3129
  if (segments.length > 1 && ignoredSourceDirectories.has(segments[0])) return false;
@@ -4739,34 +3139,44 @@ function location(source, offset) {
4739
3139
  }
4740
3140
  function declarationError(file, source, node, message) {
4741
3141
  const { column, line } = location(source, node.start);
4742
- return /* @__PURE__ */ new Error(`[vitehub] ${message}\n at ${file}:${line}:${column}`);
3142
+ return rateLimitErrorDiagnostics.RATE_LIMIT_R0001({ message: `[vitehub] ${message}\n at ${file}:${line}:${column}` });
4743
3143
  }
4744
- function requireRateLimitBindings(program) {
3144
+ function rateLimitImportBindings(program) {
4745
3145
  const bindings = {
4746
- direct: /* @__PURE__ */ new Set(),
3146
+ direct: /* @__PURE__ */ new Map(),
4747
3147
  namespaces: /* @__PURE__ */ new Set()
4748
3148
  };
4749
3149
  for (const statement of program.body) {
4750
3150
  if (statement.type !== "ImportDeclaration" || statement.importKind === "type" || !rateLimitImports.has(statement.source.value)) continue;
4751
3151
  for (const specifier of statement.specifiers) {
4752
- if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && specifier.imported.type === "Identifier" && specifier.imported.name === "requireRateLimit") bindings.direct.add(specifier.local.name);
3152
+ if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && specifier.imported.type === "Identifier" && isRateLimitGuard(specifier.imported.name)) bindings.direct.set(specifier.local.name, specifier.imported.name);
4753
3153
  if (specifier.type === "ImportNamespaceSpecifier") bindings.namespaces.add(specifier.local.name);
4754
3154
  }
4755
3155
  }
4756
3156
  return bindings;
4757
3157
  }
4758
- function resolveRateLimitBinding(name, kind, scopes) {
3158
+ function resolveDirectGuard(name, scopes) {
3159
+ for (let index = scopes.length - 1; index >= 0; index -= 1) {
3160
+ const scope = scopes[index];
3161
+ const guard = scope.direct.get(name);
3162
+ if (guard) return guard;
3163
+ if (scope.shadows.has(name)) return void 0;
3164
+ }
3165
+ }
3166
+ function resolveNamespace(name, scopes) {
4759
3167
  for (let index = scopes.length - 1; index >= 0; index -= 1) {
4760
3168
  const scope = scopes[index];
4761
- if (scope[kind].has(name)) return true;
3169
+ if (scope.namespaces.has(name)) return true;
4762
3170
  if (scope.shadows.has(name)) return false;
4763
3171
  }
4764
3172
  return false;
4765
3173
  }
4766
- function rateLimitBindingName(callee, scopes) {
4767
- if (callee.type === "Identifier" && resolveRateLimitBinding(callee.name, "direct", scopes)) return callee.name;
4768
- if (callee.type !== "MemberExpression" || callee.object.type !== "Identifier" || !resolveRateLimitBinding(callee.object.name, "namespaces", scopes)) return;
4769
- return (callee.computed ? callee.property.type === "Literal" ? callee.property.value : void 0 : callee.property.type === "Identifier" ? callee.property.name : void 0) === "requireRateLimit" ? callee.object.name : void 0;
3174
+ /** The guard that a call invokes, or `undefined` when the callee is not a Rate Limit guard. */
3175
+ function rateLimitGuardOf(callee, scopes) {
3176
+ if (callee.type === "Identifier") return resolveDirectGuard(callee.name, scopes);
3177
+ if (callee.type !== "MemberExpression" || callee.object.type !== "Identifier" || !resolveNamespace(callee.object.name, scopes)) return;
3178
+ const property = callee.computed ? callee.property.type === "Literal" ? callee.property.value : void 0 : callee.property.type === "Identifier" ? callee.property.name : void 0;
3179
+ return isRateLimitGuard(property) ? property : void 0;
4770
3180
  }
4771
3181
  function rateLimitDynamicImport(expression) {
4772
3182
  if (!expression) return false;
@@ -4787,10 +3197,11 @@ function addDynamicRateLimitBindings(declaration, scope) {
4787
3197
  if (declarator.id.type !== "ObjectPattern") continue;
4788
3198
  for (const property of declarator.id.properties) {
4789
3199
  if (property.type !== "Property") continue;
4790
- if ((property.computed ? property.key.type === "Literal" ? property.key.value : void 0 : property.key.type === "Identifier" ? property.key.name : void 0) !== "requireRateLimit") continue;
3200
+ const name = property.computed ? property.key.type === "Literal" ? property.key.value : void 0 : property.key.type === "Identifier" ? property.key.name : void 0;
3201
+ if (!isRateLimitGuard(name)) continue;
4791
3202
  const value = property.value.type === "AssignmentPattern" ? property.value.left : property.value;
4792
3203
  if (value.type !== "Identifier") continue;
4793
- scope.direct.add(value.name);
3204
+ scope.direct.set(value.name, name);
4794
3205
  }
4795
3206
  }
4796
3207
  }
@@ -4944,19 +3355,19 @@ function staticString(expression) {
4944
3355
  if (value.type === "Literal" && typeof value.value === "string") return value.value;
4945
3356
  if (value.type === "TemplateLiteral" && value.expressions.length === 0) return value.quasis[0]?.value.cooked ?? value.quasis[0]?.value.raw;
4946
3357
  }
4947
- function staticPolicy(call, file, source) {
3358
+ function staticPolicy(call, guard, file, source) {
4948
3359
  const policyArgument = call.arguments[2];
4949
3360
  const policyNode = policyArgument?.type === "SpreadElement" ? policyArgument : policyArgument && unwrapStaticExpression(policyArgument);
4950
- if (!policyNode || policyNode.type !== "ObjectExpression") throw declarationError(file, source, call, "`requireRateLimit()` requires a static options object as its third argument.");
3361
+ if (!policyNode || policyNode.type !== "ObjectExpression") throw declarationError(file, source, call, `\`${guard}()\` requires a static options object as its third argument.`);
4951
3362
  const values = /* @__PURE__ */ new Map();
4952
3363
  for (const property of policyNode.properties) {
4953
- if (property.type !== "Property") throw declarationError(file, source, property, "`requireRateLimit()` options cannot use object spreads.");
3364
+ if (property.type !== "Property") throw declarationError(file, source, property, `\`${guard}()\` options cannot use object spreads.`);
4954
3365
  const name = staticPropertyName(property);
4955
3366
  if (name === "key") continue;
4956
- if (!name || !rateLimitPolicyKeys.has(name)) throw declarationError(file, source, property, `\`requireRateLimit()\` does not support the ${name ? `"${name}"` : "dynamic"} option.`);
3367
+ if (!name || !rateLimitPolicyKeys.has(name)) throw declarationError(file, source, property, `\`${guard}()\` does not support the ${name ? `"${name}"` : "dynamic"} option.`);
4957
3368
  const value = unwrapStaticExpression(property.value);
4958
3369
  const literal = value.type === "Literal" && typeof value.value === "number" ? value.value : staticString(value);
4959
- if (literal === void 0) throw declarationError(file, source, property.value, `\`requireRateLimit()\` policy option "${name}" must be a static literal.`);
3370
+ if (literal === void 0) throw declarationError(file, source, property.value, `\`${guard}()\` policy option "${name}" must be a static literal.`);
4960
3371
  values.set(name, literal);
4961
3372
  }
4962
3373
  const policy = {
@@ -4972,12 +3383,12 @@ function staticPolicy(call, file, source) {
4972
3383
  }
4973
3384
  }
4974
3385
  function extractRateLimitDeclarations(file, source) {
4975
- if (!source.includes("requireRateLimit")) return [];
3386
+ if (!rateLimitGuards.some((guard) => source.includes(guard))) return [];
4976
3387
  const parsed = parseSync(file, source);
4977
- if (parsed.errors.length > 0) throw new Error(`[vitehub] Could not parse ${file} while collecting Rate Limits: ${parsed.errors[0]?.message}`);
3388
+ if (parsed.errors.length > 0) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0002({ message: `[vitehub] Could not parse ${file} while collecting Rate Limits: ${parsed.errors[0]?.message}` });
4978
3389
  const rootShadows = programBindings(parsed.program);
4979
- const bindings = requireRateLimitBindings(parsed.program);
4980
- if (!rootShadows.has("requireRateLimit")) bindings.direct.add("requireRateLimit");
3390
+ const bindings = rateLimitImportBindings(parsed.program);
3391
+ for (const guard of rateLimitGuards) if (!rootShadows.has(guard) && !bindings.direct.has(guard)) bindings.direct.set(guard, guard);
4981
3392
  const declarations = [];
4982
3393
  const scopes = [{
4983
3394
  ...bindings,
@@ -4987,7 +3398,7 @@ function extractRateLimitDeclarations(file, source) {
4987
3398
  addDynamicRateLimitBindingsFromStatements(parsed.program.body, scopes[0]);
4988
3399
  const enterScope = (shadows) => {
4989
3400
  scopes.push({
4990
- direct: /* @__PURE__ */ new Set(),
3401
+ direct: /* @__PURE__ */ new Map(),
4991
3402
  namespaces: /* @__PURE__ */ new Set(),
4992
3403
  shadows
4993
3404
  });
@@ -5018,16 +3429,17 @@ function extractRateLimitDeclarations(file, source) {
5018
3429
  },
5019
3430
  "ClassExpression:exit": exitScope,
5020
3431
  CallExpression(call) {
5021
- if (!rateLimitBindingName(call.callee, scopes)) return;
5022
- if (call.arguments.length !== 3) throw declarationError(file, source, call, "`requireRateLimit()` requires an event, a stable ID, and a static options object.");
3432
+ const guard = rateLimitGuardOf(call.callee, scopes);
3433
+ if (!guard) return;
3434
+ if (call.arguments.length !== 3) throw declarationError(file, source, call, `\`${guard}()\` requires an event, a stable ID, and a static options object.`);
5023
3435
  const idNode = call.arguments[1];
5024
3436
  const staticId = idNode?.type === "SpreadElement" ? void 0 : idNode && staticString(idNode);
5025
- if (!staticId?.trim()) throw declarationError(file, source, idNode ?? call, "`requireRateLimit()` requires a non-empty static string ID.");
3437
+ if (!staticId?.trim()) throw declarationError(file, source, idNode ?? call, `\`${guard}()\` requires a non-empty static string ID.`);
5026
3438
  const id = staticId.trim();
5027
3439
  const sourceLocation = location(source, call.start);
5028
3440
  declarations.push({
5029
3441
  name: id,
5030
- policy: staticPolicy(call, file, source),
3442
+ policy: staticPolicy(call, guard, file, source),
5031
3443
  source: {
5032
3444
  file,
5033
3445
  ...sourceLocation
@@ -5077,11 +3489,11 @@ function discoverRateLimitCatalog(options) {
5077
3489
  if (extracted.length > 0) declarationFiles.add(file);
5078
3490
  for (const declaration of extracted) {
5079
3491
  const existing = declarations.get(declaration.name);
5080
- if (existing && JSON.stringify(existing.policy) !== JSON.stringify(declaration.policy)) throw new Error([
3492
+ if (existing && JSON.stringify(existing.policy) !== JSON.stringify(declaration.policy)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0003({ message: [
5081
3493
  `[vitehub] Conflicting Rate Limit policies for ID "${declaration.name}":`,
5082
3494
  ` - ${existing.source.file}:${existing.source.line}:${existing.source.column} ${JSON.stringify(existing.policy)}`,
5083
3495
  ` - ${declaration.source.file}:${declaration.source.line}:${declaration.source.column} ${JSON.stringify(declaration.policy)}`
5084
- ].join("\n"));
3496
+ ].join("\n") });
5085
3497
  if (!existing) declarations.set(declaration.name, declaration);
5086
3498
  }
5087
3499
  }
@@ -5094,11 +3506,62 @@ function discoverRateLimitDeclarations(options) {
5094
3506
  return discoverRateLimitCatalog(options).declarations;
5095
3507
  }
5096
3508
  //#endregion
3509
+ //#region src/inspect.ts
3510
+ function summarizeRateLimitDeclaration(projectRoot, declaration) {
3511
+ return {
3512
+ fields: [
3513
+ {
3514
+ label: "Limit",
3515
+ value: String(declaration.policy.limit)
3516
+ },
3517
+ {
3518
+ label: "Window",
3519
+ value: declaration.policy.window
3520
+ },
3521
+ {
3522
+ label: "Enforcement",
3523
+ value: declaration.policy.enforcement === "strict" ? "Strict" : "Best effort"
3524
+ },
3525
+ {
3526
+ label: "Provider failure",
3527
+ value: declaration.policy.failure === "allow" ? "Allow" : "Deny"
3528
+ },
3529
+ {
3530
+ label: "Source location",
3531
+ value: `${declaration.source.line}:${declaration.source.column}`
3532
+ }
3533
+ ],
3534
+ file: relativeDefinitionFile(projectRoot, declaration.source.file),
3535
+ name: declaration.name,
3536
+ source: "require-rate-limit"
3537
+ };
3538
+ }
3539
+ /** Lists `requireRateLimit()` declarations as serializable inspection summaries. */
3540
+ function inspectRateLimitDefinitions(options) {
3541
+ return discoverRateLimitDeclarations({
3542
+ rootDir: options.rootDir,
3543
+ scanDirs: options.scanDirs
3544
+ }).map((declaration) => summarizeRateLimitDeclaration(options.projectRoot, declaration));
3545
+ }
3546
+ /** Console section that lists discovered Rate Limit Definitions. `vitehub inspect definitions` reads the same data. */
3547
+ const rateLimitConsoleSection = {
3548
+ description: "Inspect discovered Rate Limit policies and their source locations.",
3549
+ icon: "i-lucide-gauge",
3550
+ id: "rate-limits",
3551
+ label: "Rate Limits",
3552
+ read: inspectRateLimitDefinitions,
3553
+ view: {
3554
+ kind: "definition-catalog",
3555
+ notice: "The page lists the policies. Enter a key to read its live counter or to reset it. Counters depend on the provider: a Cloudflare binding cannot be read or reset, and a memory counter exists only in this server process."
3556
+ }
3557
+ };
3558
+ //#endregion
5097
3559
  //#region src/internal/manifest.ts
5098
3560
  const rateLimitManifestPath = ".vitehub/rate-limit/manifest.json";
5099
3561
  function resolveProviderCapabilities(provider) {
3562
+ const driver = provider === "cloudflare" ? cloudflareRateLimitDriver({ binding: { limit: async () => ({ success: true }) } }) : memoryRateLimitDriver();
5100
3563
  return createRateLimiter({
5101
- driver: provider === "cloudflare" ? cloudflareRateLimitDriver({ binding: { limit: async () => ({ success: true }) } }) : memoryRateLimitDriver(),
3564
+ driver,
5102
3565
  limit: 1,
5103
3566
  window: "1m"
5104
3567
  }).capabilities;
@@ -5119,40 +3582,7 @@ async function writeRateLimitManifest(rootDir, declarations, provider) {
5119
3582
  await writeFileIfChanged(resolve(rootDir, rateLimitManifestPath), `${JSON.stringify(manifest, null, 2)}\n`);
5120
3583
  }
5121
3584
  //#endregion
5122
- //#region src/internal/provider-output.ts
5123
- function outputStateFile(rootDir) {
5124
- return resolve(rootDir, ".vitehub", "rate-limit", "cloudflare-output.json");
5125
- }
5126
- async function readOutputState(rootDir) {
5127
- try {
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) : [];
5132
- return {
5133
- bindings,
5134
- standalone: state.standalone !== false && bindings.length > 0
5135
- };
5136
- } catch (error) {
5137
- if (error instanceof Error && "code" in error && error.code === "ENOENT") return {
5138
- bindings: [],
5139
- standalone: false
5140
- };
5141
- throw error;
5142
- }
5143
- }
5144
- async function writeOutputState(rootDir, bindings, standalone = false) {
5145
- const file = outputStateFile(rootDir);
5146
- if (bindings.length === 0) {
5147
- await rm(file, { force: true });
5148
- return;
5149
- }
5150
- await mkdir(dirname(file), { recursive: true });
5151
- await writeFile(file, `${JSON.stringify({
5152
- bindings,
5153
- standalone
5154
- }, null, 2)}\n`, "utf8");
5155
- }
3585
+ //#region src/internal/cloudflare-bindings.ts
5156
3586
  function namespaceId(namespace, rateLimitId) {
5157
3587
  let hash = 2166136261;
5158
3588
  for (const character of `${namespace}:${rateLimitId}`) {
@@ -5164,9 +3594,9 @@ function namespaceId(namespace, rateLimitId) {
5164
3594
  function createCloudflareRateLimitBindings(declarations, namespace) {
5165
3595
  return declarations.map((declaration) => {
5166
3596
  const policy = normalizeRateLimitPolicy(declaration.policy);
5167
- if (policy.enforcement === "strict") throw new Error(`Rate Limit "${declaration.name}" requires strict enforcement, but Cloudflare's native Rate Limiting binding is best-effort.`);
3597
+ if (policy.enforcement === "strict") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0015({ message: `Rate Limit "${declaration.name}" requires strict enforcement, but Cloudflare's native Rate Limiting binding is best-effort.` });
5168
3598
  const period = policy.windowMs / 1e3;
5169
- if (period !== 10 && period !== 60) throw new Error(`Rate Limit "${declaration.name}" uses ${policy.window}, but Cloudflare Rate Limiting supports only 10s and 1m windows.`);
3599
+ if (period !== 10 && period !== 60) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0016({ message: `Rate Limit "${declaration.name}" uses ${policy.window}, but Cloudflare Rate Limiting supports only 10s and 1m windows.` });
5170
3600
  return {
5171
3601
  name: getCloudflareRateLimitBindingName(declaration.name),
5172
3602
  namespace_id: namespaceId(namespace, declaration.name),
@@ -5177,186 +3607,137 @@ function createCloudflareRateLimitBindings(declarations, namespace) {
5177
3607
  };
5178
3608
  });
5179
3609
  }
5180
- function resolveRateLimitNamespace(configured) {
5181
- return configured?.trim() || void 0;
5182
- }
5183
- async function writeRateLimitProviderOutput(options, write = writeProviderDeploymentOutputs) {
5184
- options.signal?.throwIfAborted();
5185
- const state = await readOutputState(options.rootDir);
5186
- options.signal?.throwIfAborted();
5187
- const currentBindings = options.declarations.map((declaration) => getCloudflareRateLimitBindingName(declaration.name));
5188
- const previousBindings = options.previousDeclarations?.map((declaration) => getCloudflareRateLimitBindingName(declaration.name)) ?? [];
5189
- const ownership = { arrays: { ratelimits: {
5190
- key: "name",
5191
- values: [...new Set([
5192
- ...state.bindings,
5193
- ...previousBindings,
5194
- ...currentBindings
5195
- ])]
5196
- } } };
5197
- if (options.cloudflareOwnedByNitro) {
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.");
5199
- if (state.standalone && state.bindings.length > 0) await write({
5200
- clientOutDir: options.clientOutDir,
5201
- cleanup: { cloudflare: {
5202
- outputRoot: createDefaultCloudflareOutputRoot(options.rootDir),
5203
- wranglerConfigOwnership: { arrays: { ratelimits: {
5204
- key: "name",
5205
- values: state.bindings
5206
- } } }
5207
- } },
5208
- rootDir: options.rootDir
5209
- });
5210
- options.signal?.throwIfAborted();
5211
- await writeOutputState(options.rootDir, []);
5212
- options.signal?.throwIfAborted();
5213
- await writeRateLimitManifest(options.rootDir, options.declarations, options.provider);
5214
- return;
5215
- }
5216
- if (options.provider === "cloudflare" && options.declarations.length > 0) {
5217
- if (!options.namespace) throw new Error("[vitehub] Cloudflare Rate Limit requires rateLimit.namespace to isolate counters between deployments.");
5218
- await write({
5219
- clientOutDir: options.clientOutDir,
5220
- cloudflare: {
5221
- outputRoot: createDefaultCloudflareOutputRoot(options.rootDir),
5222
- wranglerConfig: { ratelimits: createCloudflareRateLimitBindings(options.declarations, options.namespace) },
5223
- wranglerConfigOwnership: ownership
5224
- },
5225
- rootDir: options.rootDir
5226
- });
5227
- options.signal?.throwIfAborted();
5228
- await writeOutputState(options.rootDir, currentBindings, true);
5229
- options.signal?.throwIfAborted();
5230
- await writeRateLimitManifest(options.rootDir, options.declarations, options.provider);
5231
- return;
5232
- }
5233
- await write({
5234
- clientOutDir: options.clientOutDir,
5235
- cleanup: { cloudflare: {
5236
- outputRoot: createDefaultCloudflareOutputRoot(options.rootDir),
5237
- wranglerConfigOwnership: ownership
5238
- } },
5239
- rootDir: options.rootDir
5240
- });
5241
- options.signal?.throwIfAborted();
5242
- await writeOutputState(options.rootDir, []);
5243
- options.signal?.throwIfAborted();
5244
- await writeRateLimitManifest(options.rootDir, options.declarations, options.provider);
5245
- }
5246
3610
  //#endregion
5247
3611
  //#region src/vite.ts
5248
3612
  const packageName = "@vite-hub/rate-limit";
5249
3613
  const pluginName = "@vite-hub/rate-limit/vite";
5250
3614
  const generatedNitroPlugin = ".vitehub/nitro/rate-limit/plugin.ts";
5251
- const generatedRuntimeModule = ".vitehub/rate-limit/cloudflare-runtime.mjs";
5252
- const mergeNoExternal = createNoExternalMerger(packageName);
3615
+ const mergeNoExternal = createNoExternalAddition(packageName);
5253
3616
  function cloneNitroConfig(value) {
5254
3617
  return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
5255
3618
  }
5256
- function mergeNitroConfig(config, value, declarations, namespace, provider, nitroCloudflare) {
3619
+ function mergeNitroConfig(config, value, declarations, namespace, provider, nitroCloudflare, projectRoot) {
5257
3620
  const providerOutput = useProviderOutputCatalog(config);
5258
- const nitro = cloneNitroConfig(value);
5259
- const plugins = Array.isArray(nitro.plugins) ? [...nitro.plugins] : [];
5260
- if (!plugins.includes(generatedNitroPlugin)) plugins.unshift(generatedNitroPlugin);
5261
- const baseNitro = {
5262
- ...nitro,
5263
- plugins
5264
- };
3621
+ const kit = createNitroServerKit(cloneNitroConfig(value));
3622
+ kit.addPlugin(resolve(projectRoot, generatedNitroPlugin), "start");
3623
+ const baseNitro = kit.config;
5265
3624
  if (!nitroCloudflare || provider !== "cloudflare" || declarations.length === 0) {
5266
3625
  contributeCloudflareProviderOutput(providerOutput, { owner: "rate-limit" });
5267
3626
  return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
5268
3627
  }
5269
- if (!namespace) throw new Error("[vitehub] Cloudflare Rate Limit requires rateLimit.namespace to isolate counters between deployments.");
3628
+ if (!namespace) throw rateLimitErrorDiagnostics.RATE_LIMIT_B0001({ message: "[vitehub] Cloudflare Rate Limit requires rateLimit.namespace to isolate counters between deployments." });
5270
3629
  contributeCloudflareProviderOutput(providerOutput, {
5271
3630
  owner: "rate-limit",
5272
3631
  rateLimits: createCloudflareRateLimitBindings(declarations, namespace)
5273
3632
  });
5274
3633
  return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
5275
3634
  }
5276
- function renderRuntimeInstaller(runtimeConfig, importBase, nitro) {
3635
+ function renderRuntimeInstaller(runtimeConfig, importBase) {
5277
3636
  return [
5278
- ...nitro ? ["import { definePlugin } from 'nitro'"] : [],
3637
+ "import { definePlugin } from 'nitro'",
5279
3638
  `import { setRateLimitRuntimeConfig } from ${JSON.stringify(`${importBase}/runtime`)}`,
5280
3639
  "",
5281
3640
  `const config = ${JSON.stringify(runtimeConfig)}`,
5282
- ...nitro ? [
5283
- "export default definePlugin(() => {",
5284
- " setRateLimitRuntimeConfig(config)",
5285
- "})"
5286
- ] : ["setRateLimitRuntimeConfig(config)", "export default config"],
3641
+ "export default definePlugin(() => {",
3642
+ " setRateLimitRuntimeConfig(config)",
3643
+ "})",
5287
3644
  ""
5288
3645
  ].join("\n");
5289
3646
  }
3647
+ function resolveRateLimitNamespace(configured) {
3648
+ return configured?.trim() || void 0;
3649
+ }
5290
3650
  function resolveProvider(options, command, nitro, deferUnknown = false) {
5291
3651
  if (options.provider && options.provider !== "auto") return options.provider;
5292
3652
  if (command === "serve") return "memory";
5293
- const hosting = resolveNitroHosting(nitro);
3653
+ const hosting = getHostingProvider(resolveHost({ nitro }));
5294
3654
  if (hosting === "cloudflare") return "cloudflare";
5295
- if (hosting) throw new Error(`[vitehub] Rate Limit has no native ${hosting} driver. Configure a custom Rate Limiter instead of falling back to per-instance memory.`);
3655
+ if (hosting) throw rateLimitErrorDiagnostics.RATE_LIMIT_B0002({ message: `[vitehub] Rate Limit has no native ${hosting} driver. Configure a custom Rate Limiter instead of falling back to per-instance memory.` });
5296
3656
  if (deferUnknown) return;
5297
- throw new Error("[vitehub] Rate Limit provider cannot be inferred for a production build. Set rateLimit.provider to \"cloudflare\" or explicitly choose \"memory\" for a known single-process deployment.");
5298
- }
5299
- function resolveNitroHosting(nitro) {
5300
- const preset = cloneNitroConfig(nitro).preset;
5301
- return getHostingProvider(typeof preset === "string" ? preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOSTING);
3657
+ throw rateLimitErrorDiagnostics.RATE_LIMIT_B0003({ message: "[vitehub] Rate Limit provider cannot be inferred for a production build. Set rateLimit.provider to \"cloudflare\" or explicitly choose \"memory\" for a known single-process deployment." });
5302
3658
  }
5303
3659
  function hubRateLimit(options = {}) {
5304
3660
  const importBase = options.importBase ?? packageName;
5305
3661
  let rateLimit = options;
5306
- let composedOutput;
5307
- const providerOutputGenerations = createProviderDeploymentOutputGenerationState();
5308
3662
  let declarations = [];
5309
- let declarationFiles = /* @__PURE__ */ new Set();
5310
- let cloudflareOwnedByNitro = false;
5311
- let previousDeclarations = [];
3663
+ let cloudflareBindings = false;
5312
3664
  let provider = "memory";
5313
3665
  let projectRoot;
5314
3666
  let resolved;
5315
3667
  const collectDeclarations = () => {
5316
3668
  if (!projectRoot) return;
5317
- const catalog = discoverRateLimitCatalog({
3669
+ declarations = discoverRateLimitCatalog({
5318
3670
  rootDir: projectRoot,
5319
3671
  scanDirs: rateLimit.scanDirs
5320
- });
5321
- declarations = catalog.declarations;
5322
- declarationFiles = catalog.declarationFiles;
3672
+ }).declarations;
5323
3673
  };
5324
3674
  const refreshDeclarations = async () => {
5325
3675
  if (!projectRoot || !resolved) return;
5326
3676
  collectDeclarations();
5327
- await writeRateLimitManifest(resolved.root, declarations, provider);
3677
+ await writeRateLimitManifest(projectRoot, declarations, provider);
5328
3678
  };
3679
+ const inspectionRoot = () => projectRoot ?? resolveViteHubProjectRoot(process.cwd(), { projectRoot: rateLimit.projectRoot });
5329
3680
  return {
5330
3681
  name: pluginName,
5331
- config(config, env) {
5332
- rateLimit = config.rateLimit ?? rateLimit;
5333
- const configuredNitro = config.nitro;
5334
- projectRoot = resolveViteHubProjectRoot(config.root || process.cwd(), { projectRoot: rateLimit.projectRoot });
5335
- const configuredProvider = resolveProvider(rateLimit, env?.command ?? "serve", configuredNitro, true);
5336
- if (configuredProvider) provider = configuredProvider;
5337
- collectDeclarations();
5338
- config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), configuredProvider, resolveNitroHosting(configuredNitro) === "cloudflare");
3682
+ enforce: "pre",
3683
+ vitehub: {
3684
+ operations: [{
3685
+ export: "rateLimitOperations",
3686
+ load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).rateLimitOperations,
3687
+ module: "@vite-hub/rate-limit/operations"
3688
+ }],
3689
+ cli: async () => {
3690
+ const { createRateLimitCliContributor } = await import(
3691
+ /* @vite-ignore */
3692
+ "./cli.js"
3693
+ );
3694
+ return createRateLimitCliContributor();
3695
+ },
3696
+ inspect: () => ({
3697
+ definitions: [{
3698
+ kind: "rate-limit",
3699
+ label: "Rate Limits",
3700
+ list: () => inspectRateLimitDefinitions({
3701
+ projectRoot: inspectionRoot(),
3702
+ rootDir: inspectionRoot(),
3703
+ scanDirs: rateLimit.scanDirs
3704
+ })
3705
+ }],
3706
+ providerOutput: [{
3707
+ description: "Rate Limit manifest with provider and capabilities",
3708
+ owner: "rate-limit",
3709
+ path: resolve(inspectionRoot(), ".vitehub/rate-limit/manifest.json")
3710
+ }]
3711
+ })
3712
+ },
3713
+ config: {
3714
+ order: "pre",
3715
+ handler(config, env) {
3716
+ rateLimit = config.rateLimit ?? rateLimit;
3717
+ const configuredNitro = config.nitro;
3718
+ projectRoot = resolveViteHubProjectRoot(config.root || process.cwd(), { projectRoot: rateLimit.projectRoot });
3719
+ const configuredProvider = resolveProvider(rateLimit, env?.command ?? "serve", configuredNitro, true);
3720
+ if (configuredProvider) provider = configuredProvider;
3721
+ collectDeclarations();
3722
+ config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), configuredProvider, resolveHost({ nitro: configuredNitro }) === "cloudflare", projectRoot);
3723
+ return installStandaloneOperationRpc(config, env?.command ?? "build", "@vite-hub/rate-limit/operations");
3724
+ }
5339
3725
  },
5340
3726
  async configResolved(config) {
5341
3727
  resolved = config;
5342
3728
  rateLimit = config.rateLimit ?? rateLimit;
5343
- composedOutput = useProviderOutputCatalog(config);
5344
3729
  projectRoot = resolveViteHubProjectRoot(config.root, { projectRoot: rateLimit.projectRoot });
5345
3730
  const configuredNitro = config.nitro;
5346
- const nitroCloudflare = resolveNitroHosting(configuredNitro) === "cloudflare";
5347
- cloudflareOwnedByNitro = hasNitroConfigContext(config) && nitroCloudflare;
3731
+ const nitroCloudflare = resolveHost({ nitro: configuredNitro }) === "cloudflare";
5348
3732
  provider = resolveProvider(rateLimit, config.command, configuredNitro);
3733
+ cloudflareBindings = nitroCloudflare && provider === "cloudflare";
5349
3734
  collectDeclarations();
5350
- config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), provider, nitroCloudflare);
5351
- await writeRateLimitManifest(config.root, declarations, provider);
5352
- const pluginFile = resolve(config.root, generatedNitroPlugin);
5353
- const runtimeFile = resolve(config.root, generatedRuntimeModule);
5354
- const runtimeConfig = { provider };
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
- });
3735
+ config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), provider, nitroCloudflare, projectRoot);
3736
+ await writeRateLimitManifest(projectRoot, declarations, provider);
3737
+ await writeFileIfChanged(resolve(projectRoot, generatedNitroPlugin), renderRuntimeInstaller({ provider }, importBase));
3738
+ },
3739
+ configureServer(server) {
3740
+ publishStandaloneOperationServer(server);
5360
3741
  },
5361
3742
  configEnvironment(name, config) {
5362
3743
  if (!isServerEnvironment(name, config)) return;
@@ -5367,64 +3748,13 @@ function hubRateLimit(options = {}) {
5367
3748
  resolved = context.server.config;
5368
3749
  await refreshDeclarations();
5369
3750
  },
5370
- transform(code, id) {
5371
- if (provider !== "cloudflare" || !resolved?.build.ssr || !declarationFiles.has(id.split("?", 1)[0])) return;
5372
- return `import ${JSON.stringify(normalizePath(resolve(resolved.root, generatedRuntimeModule)))}\n${code}`;
5373
- },
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
- }
5382
- if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
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
- }
3751
+ buildEnd(error) {
3752
+ if (error || !cloudflareBindings || !resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
3753
+ const configuredDeclarations = declarations;
3754
+ collectDeclarations();
3755
+ if (JSON.stringify(declarations) !== JSON.stringify(configuredDeclarations)) throw rateLimitErrorDiagnostics.RATE_LIMIT_B0004({ message: "[vitehub] Nitro Cloudflare Rate Limit declarations changed after config resolution. Generate Rate Limit source files before Vite config resolves." });
5426
3756
  }
5427
3757
  };
5428
3758
  }
5429
3759
  //#endregion
5430
- export { discoverRateLimitDeclarations, hubRateLimit };
3760
+ export { discoverRateLimitDeclarations, hubRateLimit, inspectRateLimitDefinitions, rateLimitConsoleSection };