@vite-hub/workspace 0.0.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +225 -58
  2. package/dist/{ai-CjxvGqM0.d.ts → ai-BW2ZhizI.d.ts} +22 -7
  3. package/dist/{ai-BqCC8BpY.js → ai-BZyLwULx.js} +147 -66
  4. package/dist/ai.d.ts +2 -2
  5. package/dist/ai.js +1 -1
  6. package/dist/{asset-registry-8QI3ML3K.js → asset-registry-DfBV5kmw.js} +3 -2
  7. package/dist/association-Cm0dUTDU-CDDhJnIh-Cv3bWnVb.js +19 -0
  8. package/dist/blob-database.d.ts +521 -0
  9. package/dist/blob-database.js +601 -0
  10. package/dist/cloudflare.d.ts +5 -6
  11. package/dist/cloudflare.js +1 -1
  12. package/dist/config-B7dmzDX3.js +1112 -0
  13. package/dist/{config-DE9xlaIw.d.ts → config-DLKdaFWN.d.ts} +1 -2
  14. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  15. package/dist/error-diagnostics-DY5GP47p.js +96 -0
  16. package/dist/events-7EBoeIPd-A2RUkJi5-BxrICQ17.js +354 -0
  17. package/dist/events-CRaLy7U3-3PNNp5WZ-Gv9nd0cH.js +214 -0
  18. package/dist/events-CeChclTf-CX-gD8oy-4aL2j6V-.js +527 -0
  19. package/dist/feed-DsC7Vws1-M_de2nSK-tKc0Pwo8.js +248 -0
  20. package/dist/feed-Dyf730Ys-D0HgBba6-BUnCa5gS.js +179 -0
  21. package/dist/file-C0_aPWSS.js +26 -0
  22. package/dist/file-metadata-CxDy-E2H.js +58 -0
  23. package/dist/{files-Q6xZjDHA.js → files-C7Px8uaC.js} +3 -3
  24. package/dist/forgejo-BN8ItCfl-Bbn4vhDd.js +2278 -0
  25. package/dist/{github-DHnjxQIX.js → github-CPxHtFB7.js} +16 -23
  26. package/dist/github-DtncTfmv-Du2S8lGF.js +4159 -0
  27. package/dist/gitlab-BoDm8-BC-xzZsW9eW.js +2530 -0
  28. package/dist/glob--XcLlcml.js +22 -0
  29. package/dist/glob--kNYDbfU.js +30 -0
  30. package/dist/graphql-DG5aJBT3-DceyFYdM-C4saqX37.js +489 -0
  31. package/dist/{host-DJH8cuoU.js → host-CFnrTXTK.js} +97 -41
  32. package/dist/{hosted-RPeJOCFz.js → hosted-acMA5XyL.js} +102 -19
  33. package/dist/hosted-vercel-blob-DKntsHaf.js +12603 -0
  34. package/dist/hosted-vercel-blob.d.ts +5 -6
  35. package/dist/hosted-vercel-blob.js +1 -1
  36. package/dist/hosted.d.ts +6 -7
  37. package/dist/hosted.js +1 -1
  38. package/dist/index.d.ts +57 -36
  39. package/dist/index.js +56 -56
  40. package/dist/inspect-BoObD2cJ.js +167 -0
  41. package/dist/internal/path.d.ts +2 -0
  42. package/dist/internal/path.js +2 -0
  43. package/dist/lifecycle-BwZ7c9hb.js +596 -0
  44. package/dist/loader.d.ts +5 -6
  45. package/dist/loader.js +3 -2
  46. package/dist/mcp-resources-BREFCmtn.js +39 -0
  47. package/dist/memory-BbwOqDXl.js +248 -0
  48. package/dist/metadata-target-DZEZQGHA.js +1588 -0
  49. package/dist/mountx.d.ts +4 -6
  50. package/dist/mountx.js +10 -8
  51. package/dist/nitro.d.ts +1 -1
  52. package/dist/nitro.js +1 -1
  53. package/dist/nuxt.d.ts +13 -12
  54. package/dist/nuxt.js +4 -8
  55. package/dist/operations-BcpWr41m.js +159 -0
  56. package/dist/operations-CGqY1XeG.js +965 -0
  57. package/dist/operations-DnOwKsJT.d.ts +136 -0
  58. package/dist/operations.d.ts +53 -0
  59. package/dist/operations.js +2 -0
  60. package/dist/path-CNAwN7pw.js +114 -0
  61. package/dist/path-DrSIenjj.js +59 -0
  62. package/dist/path-zHxQUbqa.d.ts +9 -0
  63. package/dist/plugins-DqQ8b4T5.d.ts +10 -0
  64. package/dist/provider-kXjfli9u.js +1457 -0
  65. package/dist/providers/github/store.d.ts +3 -5
  66. package/dist/providers/github/store.js +1 -1
  67. package/dist/{registry-D3yzt8HQ.js → registry-Bp-8UUfG.js} +9 -7
  68. package/dist/{registry-Uj6IVxes.d.ts → registry-Cg1TJVVZ.d.ts} +1 -2
  69. package/dist/{request-execution-B-dSFlGB.js → request-execution-Dk9rY-Yh.js} +19 -19
  70. package/dist/{chunk-2rV9d50f.js → rolldown-runtime-B4iAMlE-.js} +2 -2
  71. package/dist/runtime/assets.d.ts +3 -5
  72. package/dist/runtime/assets.js +7 -6
  73. package/dist/runtime/empty-assets-registry.d.ts +1 -2
  74. package/dist/runtime/empty-registry.d.ts +1 -2
  75. package/dist/runtime/state.d.ts +3 -3
  76. package/dist/runtime/state.js +6 -6
  77. package/dist/runtime/workspace.d.ts +1 -1
  78. package/dist/runtime/workspace.js +1 -1
  79. package/dist/runtime.d.ts +51 -17
  80. package/dist/runtime.js +320 -60
  81. package/dist/{search-BpiCF2Tw.js → search-CrTmXj5h.js} +10 -9
  82. package/dist/server-BNQ-Nbjj.js +290 -0
  83. package/dist/server.d.ts +22 -34
  84. package/dist/server.js +2 -328
  85. package/dist/shared-DalXdP0i.js +2158 -0
  86. package/dist/source-metadata.d.ts +6 -7
  87. package/dist/source-metadata.js +7 -7
  88. package/dist/{state-tYcRWEh2.d.ts → state-B8zbLi5t.d.ts} +3 -3
  89. package/dist/store-CXgmu-uw.js +1729 -0
  90. package/dist/{sync-DnTQwt8r.js → sync-CN6ec-5M.js} +61 -41
  91. package/dist/templates-Bn8a-pd2-D9DhJEVD-CBfXNRzz.js +125 -0
  92. package/dist/test.d.ts +1 -1
  93. package/dist/test.js +1 -1
  94. package/dist/{token-CVzURBxC.js → token-CO62GglH.js} +3 -3
  95. package/dist/{types-CYuwjJ4V.d.ts → types-DeK9GIxy.d.ts} +256 -24
  96. package/dist/{use-BTNDR5Rd.js → use-BQj7nSz6.js} +82 -41
  97. package/dist/{use-BiHzt0xA.d.ts → use-DhwhbAVV.d.ts} +16 -11
  98. package/dist/utils-Blrh4N2n.js +545 -0
  99. package/dist/vite-BEvgU2GY.js +20909 -0
  100. package/dist/vite-CcZmMQ7S.d.ts +476 -0
  101. package/dist/vite.d.ts +2 -2
  102. package/dist/vite.js +2 -2
  103. package/dist/webhooks-DgHwxxYz-D1V2LOr1-azofFOiP.js +1565 -0
  104. package/dist/{workspace-Dq08Yn72.js → workspace-6pxkOuxr.js} +361 -230
  105. package/dist/{workspace-Xddf4G1B.d.ts → workspace-BWJQBK1u.d.ts} +4 -3
  106. package/package.json +89 -55
  107. package/dist/collections/client.d.ts +0 -39
  108. package/dist/collections/client.js +0 -137
  109. package/dist/collections.d.ts +0 -59
  110. package/dist/collections.js +0 -159
  111. package/dist/config-Bc3c4Su1.js +0 -7904
  112. package/dist/config-CHLLWklZ.js +0 -36
  113. package/dist/file-Bc1X7pco.js +0 -23
  114. package/dist/glob-CEZKeZFC.js +0 -18
  115. package/dist/hosted-vercel-blob-d6C8ND5j.js +0 -23580
  116. package/dist/lifecycle-LrL3sA4n.js +0 -316
  117. package/dist/metadata-target-B0tOmVW7.js +0 -717
  118. package/dist/path-Cp59koVz.js +0 -139
  119. package/dist/provider-B1yLjCJJ.js +0 -746
  120. package/dist/publish.d.ts +0 -35
  121. package/dist/publish.js +0 -112
  122. package/dist/runtime-options-BsPSv5O7.js +0 -13
  123. package/dist/runtime-type-iEE6BjQJ.js +0 -34
  124. package/dist/shared-DTR1Hhma.js +0 -331
  125. package/dist/store-Dt_Jyys3.js +0 -608
  126. package/dist/vite-BptCrpv2.js +0 -4526
  127. package/dist/vite-CtA9guIM.d.ts +0 -66
@@ -1,4526 +0,0 @@
1
- import { s as normalizeSafeWorkspacePath } from "./path-Cp59koVz.js";
2
- import { n as isPlainObject, t as normalizeWorkspaceOptions } from "./config-CHLLWklZ.js";
3
- import { s as createMemoryWorkspaceStore } from "./provider-B1yLjCJJ.js";
4
- import { n as installHostedWorkspaceRuntime } from "./hosted-RPeJOCFz.js";
5
- import { t as normalizeWorkspaceDefinition } from "./registry-D3yzt8HQ.js";
6
- import { n as installHostedVercelBlobWorkspaceRuntime } from "./hosted-vercel-blob-d6C8ND5j.js";
7
- import { n as syncWorkspaceDefinition } from "./lifecycle-LrL3sA4n.js";
8
- import { ensureWorkspaceDevToken, readWorkspaceDevToken, refreshWorkspaceDevToken, runWorkspaceDevCommand, validateWorkspaceDevToken, workspaceDevHeader, workspaceDevRoute, workspaceDevTokenHeader, workspaceDevTokenServerId } from "./server.js";
9
- import { createRequire } from "node:module";
10
- import { basename, dirname, extname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
11
- import { createHash } from "node:crypto";
12
- import { existsSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync } from "node:fs";
13
- import { access, copyFile, cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
14
- import { tmpdir } from "node:os";
15
- import { fileURLToPath, pathToFileURL } from "node:url";
16
- import { build } from "esbuild";
17
- import { renderMarkdownTemplate } from "@vite-hub/markdown-template";
18
- import { parseMarkdownTemplateRequest } from "@vite-hub/markdown-template/internal/vite";
19
- import { resolveModulePath } from "exsolve";
20
- import { createJiti } from "jiti";
21
- //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
22
- const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
23
- function normalizeWindowsPath(input = "") {
24
- if (!input) return input;
25
- return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
26
- }
27
- const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
28
- const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
29
- const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
30
- function cwd() {
31
- if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
32
- return "/";
33
- }
34
- const resolve$1 = function(...arguments_) {
35
- arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
36
- let resolvedPath = "";
37
- let resolvedAbsolute = false;
38
- for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
39
- const path = index >= 0 ? arguments_[index] : cwd();
40
- if (!path || path.length === 0) continue;
41
- resolvedPath = `${path}/${resolvedPath}`;
42
- resolvedAbsolute = isAbsolute$1(path);
43
- }
44
- resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
45
- if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
46
- return resolvedPath.length > 0 ? resolvedPath : ".";
47
- };
48
- function normalizeString(path, allowAboveRoot) {
49
- let res = "";
50
- let lastSegmentLength = 0;
51
- let lastSlash = -1;
52
- let dots = 0;
53
- let char = null;
54
- for (let index = 0; index <= path.length; ++index) {
55
- if (index < path.length) char = path[index];
56
- else if (char === "/") break;
57
- else char = "/";
58
- if (char === "/") {
59
- if (lastSlash === index - 1 || dots === 1);
60
- else if (dots === 2) {
61
- if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
62
- if (res.length > 2) {
63
- const lastSlashIndex = res.lastIndexOf("/");
64
- if (lastSlashIndex === -1) {
65
- res = "";
66
- lastSegmentLength = 0;
67
- } else {
68
- res = res.slice(0, lastSlashIndex);
69
- lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
70
- }
71
- lastSlash = index;
72
- dots = 0;
73
- continue;
74
- } else if (res.length > 0) {
75
- res = "";
76
- lastSegmentLength = 0;
77
- lastSlash = index;
78
- dots = 0;
79
- continue;
80
- }
81
- }
82
- if (allowAboveRoot) {
83
- res += res.length > 0 ? "/.." : "..";
84
- lastSegmentLength = 2;
85
- }
86
- } else {
87
- if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
88
- else res = path.slice(lastSlash + 1, index);
89
- lastSegmentLength = index - lastSlash - 1;
90
- }
91
- lastSlash = index;
92
- dots = 0;
93
- } else if (char === "." && dots !== -1) ++dots;
94
- else dots = -1;
95
- }
96
- return res;
97
- }
98
- const isAbsolute$1 = function(p) {
99
- return _IS_ABSOLUTE_RE.test(p);
100
- };
101
- const relative$1 = function(from, to) {
102
- const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
103
- const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
104
- if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
105
- const _fromCopy = [..._from];
106
- for (const segment of _fromCopy) {
107
- if (_to[0] !== segment) break;
108
- _from.shift();
109
- _to.shift();
110
- }
111
- return [..._from.map(() => ".."), ..._to].join("/");
112
- };
113
- const dirname$1 = function(p) {
114
- const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
115
- if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
116
- return segments.join("/") || (isAbsolute$1(p) ? "/" : ".");
117
- };
118
- //#endregion
119
- //#region ../internal/src/build/client-output.ts
120
- function hasStaticIndex(clientDir) {
121
- return existsSync(resolve$1(clientDir, "index.html"));
122
- }
123
- async function copyClientOutput(clientDir, targetDir) {
124
- const resolvedClientDir = resolve$1(clientDir);
125
- const resolvedTargetDir = resolve$1(targetDir);
126
- if (resolvedClientDir === resolvedTargetDir) return;
127
- await rm(resolvedTargetDir, {
128
- force: true,
129
- recursive: true
130
- });
131
- await mkdir(dirname$1(resolvedTargetDir), { recursive: true });
132
- const targetRelativePath = relative$1(resolvedClientDir, resolvedTargetDir);
133
- if (targetRelativePath && !targetRelativePath.startsWith("../")) {
134
- const [targetRootEntry] = targetRelativePath.split("/", 1);
135
- await mkdir(resolvedTargetDir, { recursive: true });
136
- await Promise.all((await readdir(resolvedClientDir)).filter((entry) => entry !== targetRootEntry).map((entry) => cp(resolve$1(resolvedClientDir, entry), resolve$1(resolvedTargetDir, entry), { recursive: true })));
137
- return;
138
- }
139
- await cp(resolvedClientDir, resolvedTargetDir, { recursive: true });
140
- }
141
- //#endregion
142
- //#region ../internal/src/build/provider-output-config.ts
143
- function isProviderJsonArray(value, ancestors) {
144
- if (Object.getPrototypeOf(value) !== Array.prototype || ancestors.has(value)) return false;
145
- if (Reflect.ownKeys(value).length !== value.length + 1) return false;
146
- ancestors.add(value);
147
- try {
148
- for (let index = 0; index < value.length; index++) {
149
- const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
150
- if (!descriptor?.enumerable || !("value" in descriptor) || !isProviderJsonValue(descriptor.value, ancestors)) return false;
151
- }
152
- return true;
153
- } finally {
154
- ancestors.delete(value);
155
- }
156
- }
157
- function isProviderJsonRecordValue(value, ancestors) {
158
- const prototype = Object.getPrototypeOf(value);
159
- if (prototype !== Object.prototype && prototype !== null || ancestors.has(value)) return false;
160
- ancestors.add(value);
161
- try {
162
- return Reflect.ownKeys(value).every((key) => {
163
- if (typeof key !== "string") return false;
164
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
165
- return descriptor?.enumerable === true && "value" in descriptor && isProviderJsonValue(descriptor.value, ancestors);
166
- });
167
- } finally {
168
- ancestors.delete(value);
169
- }
170
- }
171
- function isProviderJsonValue(value, ancestors) {
172
- if (value === null || typeof value === "boolean" || typeof value === "string") return true;
173
- if (typeof value === "number") return Number.isFinite(value);
174
- if (Array.isArray(value)) return isProviderJsonArray(value, ancestors);
175
- return typeof value === "object" && isProviderJsonRecordValue(value, ancestors);
176
- }
177
- function isProviderJsonRecord(value) {
178
- try {
179
- return typeof value === "object" && value !== null && !Array.isArray(value) && isProviderJsonRecordValue(value, /* @__PURE__ */ new Set());
180
- } catch {
181
- return false;
182
- }
183
- }
184
- function assertProviderJsonRecord(value) {
185
- if (!isProviderJsonRecord(value)) throw new TypeError("[vitehub] Provider output config must be a JSON object.");
186
- }
187
- function isFileNotFoundError(error) {
188
- return error instanceof Error && "code" in error && error.code === "ENOENT";
189
- }
190
- async function readProviderJsonRecord(file) {
191
- try {
192
- const parsed = JSON.parse(await readFile(file, "utf8"));
193
- assertProviderJsonRecord(parsed);
194
- return parsed;
195
- } catch (error) {
196
- if (isFileNotFoundError(error)) return;
197
- throw error;
198
- }
199
- }
200
- function deleteOwnedFields(value, ownership, cleanup = false) {
201
- const next = { ...value };
202
- for (const key of ownership.keys ?? []) delete next[key];
203
- for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) if (!cleanup || !arrayOwnership.preserveOnCleanup) delete next[field];
204
- return next;
205
- }
206
- function getKeyedArrayEntryValue(value, key) {
207
- if (key === void 0) return value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string" ? value : void 0;
208
- if (!isProviderJsonRecord(value)) return;
209
- const entryValue = value[key];
210
- return entryValue === null || typeof entryValue === "boolean" || typeof entryValue === "number" || typeof entryValue === "string" ? entryValue : void 0;
211
- }
212
- function preserveUnownedKeyedArrayEntries(value, ownership, replacements = []) {
213
- const current = Array.isArray(value) ? value : [];
214
- const replacementKeys = replacements.flatMap((entry) => {
215
- const key = getKeyedArrayEntryValue(entry, ownership.key);
216
- return key === void 0 ? [] : [key];
217
- });
218
- const ownedKeys = new Set([...ownership.values ?? [], ...replacementKeys]);
219
- return current.filter((entry) => {
220
- const key = getKeyedArrayEntryValue(entry, ownership.key);
221
- return key === void 0 || !ownedKeys.has(key);
222
- });
223
- }
224
- function mergeOwnedArrays(existing, value, arrays) {
225
- const next = { ...value };
226
- for (const [field, ownership] of Object.entries(arrays ?? {})) {
227
- const incoming = Array.isArray(value[field]) ? value[field] : [];
228
- const merged = [...preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming), ...incoming];
229
- if (merged.length) next[field] = merged;
230
- else delete next[field];
231
- }
232
- return next;
233
- }
234
- async function persistProviderJsonRecord(file, value, removeIfEmpty) {
235
- if (removeIfEmpty && !Object.keys(value).length) {
236
- await rm(file, { force: true });
237
- return;
238
- }
239
- await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
240
- }
241
- async function writeProviderOutputConfig(file, value, ownership = {}, options = {}) {
242
- const existing = await readProviderJsonRecord(file) ?? {};
243
- const defaults = options.defaults ?? {};
244
- assertProviderJsonRecord(defaults);
245
- await persistProviderJsonRecord(file, mergeProviderOutputConfig({
246
- ...defaults,
247
- ...existing
248
- }, value, ownership), options.removeIfEmpty === true);
249
- }
250
- function mergeProviderOutputConfig(existing, value, ownership = {}) {
251
- assertProviderJsonRecord(existing);
252
- assertProviderJsonRecord(value);
253
- return {
254
- ...deleteOwnedFields(existing, ownership),
255
- ...mergeOwnedArrays(existing, value, ownership.arrays)
256
- };
257
- }
258
- function stringifyProviderOutputConfig(value) {
259
- assertProviderJsonRecord(value);
260
- return JSON.stringify(value, null, 2);
261
- }
262
- async function cleanProviderOutputConfig(file, ownership) {
263
- if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
264
- const existing = await readProviderJsonRecord(file);
265
- if (!existing) return;
266
- const next = deleteOwnedFields(existing, ownership, true);
267
- let changed = (ownership.keys ?? []).some((key) => key in existing);
268
- for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
269
- if (arrayOwnership.preserveOnCleanup) continue;
270
- if (!(field in existing)) continue;
271
- const current = existing[field];
272
- const retained = arrayOwnership.retainOnCleanup ?? [];
273
- const preserved = [...preserveUnownedKeyedArrayEntries(current, arrayOwnership, retained), ...retained];
274
- changed ||= retained.length > 0 || !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
275
- if (preserved.length) next[field] = preserved;
276
- }
277
- if (!changed) return;
278
- await persistProviderJsonRecord(file, next, true);
279
- }
280
- //#endregion
281
- //#region ../internal/src/build/user-entry.ts
282
- function toSafeAppName(rootDir) {
283
- return basename(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
284
- }
285
- //#endregion
286
- //#region ../internal/src/build/cloudflare.ts
287
- function createDefaultCloudflareOutputRoot(rootDir) {
288
- return resolve(rootDir, "dist", toSafeAppName(rootDir));
289
- }
290
- async function writeCloudflareWranglerConfig(options) {
291
- const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
292
- const configFile = resolve(outputRoot, "wrangler.json");
293
- if (!options.wranglerConfig) {
294
- await cleanProviderOutputConfig(configFile, options.wranglerConfigOwnership ?? {});
295
- return;
296
- }
297
- await mkdir(outputRoot, { recursive: true });
298
- await writeProviderOutputConfig(configFile, options.wranglerConfig, options.wranglerConfigOwnership, {
299
- defaults: options.wranglerConfigDefaults,
300
- removeIfEmpty: true
301
- });
302
- }
303
- //#endregion
304
- //#region ../internal/src/build/esbuild.ts
305
- const viteRawNamespace = "vitehub-vite-raw";
306
- const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
307
- const markdownTemplateFileSuffix = ".template.md";
308
- const markdownTemplateModuleQuery = "markdown-template";
309
- const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
310
- const skipResolvedAlias = "vitehubSkipResolvedAlias";
311
- const encodedAliasPrefixMarker = "\0vitehub-prefix:";
312
- const encodedAliasExactMarker = "\0vitehub-exact:";
313
- const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
314
- function normalizePathSeparators(path) {
315
- return path.replaceAll("\\", "/");
316
- }
317
- function escapeRegExp(value) {
318
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
319
- }
320
- function collectPackageExportCandidates(packageName, exportsValue, packageRelativePath) {
321
- if (typeof exportsValue === "string") return normalizePathSeparators(exportsValue).replace(/^\.\//, "") === packageRelativePath ? [packageName] : [];
322
- if (!Array.isArray(exportsValue) && !isPlainObject(exportsValue)) return [];
323
- const candidates = [];
324
- const exportEntries = isPlainObject(exportsValue) && Object.keys(exportsValue).some((exportKey) => exportKey.startsWith(".")) ? Object.entries(exportsValue) : [[".", exportsValue]];
325
- for (const [exportKey, target] of exportEntries) {
326
- const targets = [target];
327
- while (targets.length) {
328
- const value = targets.shift();
329
- if (typeof value === "string") {
330
- const normalizedTarget = normalizePathSeparators(value).replace(/^\.\//, "");
331
- const targetParts = normalizedTarget.split("*");
332
- if (targetParts.length === 1) {
333
- if (normalizedTarget === packageRelativePath) candidates.push(`${packageName}${exportKey.slice(1)}`);
334
- continue;
335
- }
336
- const targetPattern = `${escapeRegExp(targetParts[0])}(.*?)${targetParts.slice(1).map((part, index) => `${index ? "\\1" : ""}${escapeRegExp(part)}`).join("")}`;
337
- const wildcard = new RegExp(`^${targetPattern}$`).exec(packageRelativePath)?.[1];
338
- if (wildcard === void 0) continue;
339
- candidates.push(`${packageName}${exportKey.slice(1).replace("*", wildcard)}`);
340
- } else if (Array.isArray(value)) targets.push(...value);
341
- else if (isPlainObject(value)) targets.push(...Object.values(value));
342
- }
343
- }
344
- return candidates;
345
- }
346
- function createResolvedAliasPlugin(aliases, aliasResolveDir) {
347
- const entries = Object.entries(aliases || {});
348
- if (!entries.length) return;
349
- const resolvedEntries = Promise.all(entries.map(async ([encodedSpecifier, replacement]) => {
350
- const prefixMarkerIndex = encodedSpecifier.lastIndexOf(encodedAliasPrefixMarker);
351
- const exactMarkerIndex = encodedSpecifier.lastIndexOf(encodedAliasExactMarker);
352
- const explicitlyEncodedPrefix = prefixMarkerIndex !== -1;
353
- const markerIndex = Math.max(prefixMarkerIndex, exactMarkerIndex);
354
- const specifier = markerIndex === -1 ? encodedSpecifier : encodedSpecifier.slice(0, markerIndex);
355
- const prefix = explicitlyEncodedPrefix || specifier.endsWith("/") && !Object.hasOwn(aliases, `${specifier}/`);
356
- const resolvedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
357
- const canonicalSpecifier = isAbsolute(resolvedSpecifier) ? normalizePathSeparators(await realpath(resolvedSpecifier).catch(() => resolvedSpecifier)) : resolvedSpecifier;
358
- const resolvedReplacement = isAbsolute(replacement) ? normalizePathSeparators(resolve(replacement)) : replacement;
359
- return {
360
- canonicalSpecifier: `${canonicalSpecifier}${prefix && !canonicalSpecifier.endsWith("/") ? "/" : ""}`,
361
- prefix,
362
- replacement: `${resolvedReplacement}${prefix && !/[\\/]$/.test(resolvedReplacement) ? "/" : ""}`,
363
- specifier: `${resolvedSpecifier}${prefix && !resolvedSpecifier.endsWith("/") ? "/" : ""}`
364
- };
365
- }));
366
- return {
367
- name: "vitehub-resolved-alias",
368
- setup(build) {
369
- const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
370
- build.onResolve({ filter: /.*/ }, async (args) => {
371
- if (args.pluginData?.[skipResolvedAlias]) return;
372
- const aliases = await resolvedEntries;
373
- let match = aliases.find(({ prefix, specifier }) => /^\.\.?[\\/]/.test(specifier) && (prefix ? args.path.startsWith(specifier) : args.path === specifier));
374
- let matchedAlias = match?.specifier;
375
- let matchedSpecifier = match ? args.path : void 0;
376
- let specifier = args.resolveDir && /^\.\.?[\\/]/.test(args.path) ? resolve(args.resolveDir, args.path) : args.path;
377
- let normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
378
- let canonicalSpecifier = normalizedSpecifier;
379
- const canonicalizeSpecifier = async () => {
380
- canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
381
- return canonicalSpecifier;
382
- };
383
- match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
384
- if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
385
- await canonicalizeSpecifier();
386
- match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
387
- }
388
- if (!match && isAbsolute(args.path)) for (const alias of aliases) {
389
- if (isAbsolute(alias.specifier)) continue;
390
- const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
391
- const aliasSegments = packageAlias.split("/");
392
- if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
393
- let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
394
- if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
395
- const scopeMarker = `/node_modules/${packageAlias}/`;
396
- const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
397
- const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
398
- if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
399
- }
400
- const packageMarker = `/node_modules/${packageName}/`;
401
- const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
402
- const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
403
- const cacheKey = [
404
- alias.specifier,
405
- alias.prefix,
406
- resolutionScope,
407
- args.importer,
408
- args.resolveDir,
409
- args.kind,
410
- args.namespace,
411
- JSON.stringify(args.with)
412
- ].join("\0");
413
- let resolution = args.pluginData ? void 0 : resolvedBareAliasPaths.get(cacheKey);
414
- if (!resolution) {
415
- resolution = (async () => {
416
- let resolvedAliasPath;
417
- if (alias.prefix && /^\.\.?[\\/]/.test(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
418
- else if (resolutionScope) {
419
- const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
420
- const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
421
- if (!isPlainObject(parsedPackageJson)) return;
422
- const packageJson = parsedPackageJson;
423
- if (packageJson.exports === void 0 && !alias.prefix) {
424
- const resolvedCandidate = await build.resolve(alias.specifier, {
425
- importer: args.importer,
426
- kind: args.kind,
427
- namespace: args.namespace,
428
- pluginData: {
429
- ...args.pluginData,
430
- [skipResolvedAlias]: true
431
- },
432
- resolveDir: args.resolveDir,
433
- with: args.with
434
- });
435
- if (!resolvedCandidate.errors.length && !resolvedCandidate.external && resolvedCandidate.namespace === "file" && normalizePathSeparators(resolve(resolvedCandidate.path)) === normalizedSpecifier) return {
436
- canonical: alias.specifier,
437
- normalized: alias.specifier,
438
- publicSpecifier: alias.specifier
439
- };
440
- return;
441
- }
442
- const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
443
- for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
444
- const resolvedCandidate = await build.resolve(publicSpecifier, {
445
- importer: args.importer,
446
- kind: args.kind,
447
- namespace: args.namespace,
448
- pluginData: {
449
- ...args.pluginData,
450
- [skipResolvedAlias]: true
451
- },
452
- resolveDir: args.resolveDir,
453
- with: args.with
454
- });
455
- if (resolvedCandidate.errors.length || resolvedCandidate.external || resolvedCandidate.namespace !== "file") continue;
456
- if (normalizePathSeparators(resolve(resolvedCandidate.path)) !== normalizedSpecifier) continue;
457
- matchingPublicSpecifiers.add(publicSpecifier);
458
- }
459
- if (matchingPublicSpecifiers.size === 1) {
460
- const publicSpecifier = [...matchingPublicSpecifiers][0];
461
- if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
462
- canonical: publicSpecifier,
463
- normalized: publicSpecifier,
464
- publicSpecifier
465
- };
466
- }
467
- return;
468
- } else {
469
- const resolvedAlias = await build.resolve(alias.specifier, {
470
- importer: args.importer,
471
- kind: args.kind,
472
- namespace: args.namespace,
473
- pluginData: {
474
- ...args.pluginData,
475
- [skipResolvedAlias]: true
476
- },
477
- resolveDir: args.resolveDir,
478
- with: args.with
479
- });
480
- if (resolvedAlias.errors.length || resolvedAlias.external || resolvedAlias.namespace !== "file") return;
481
- resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.path));
482
- }
483
- const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
484
- return {
485
- canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
486
- normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
487
- };
488
- })();
489
- if (!args.pluginData) resolvedBareAliasPaths.set(cacheKey, resolution);
490
- }
491
- const paths = await resolution;
492
- if (!paths) continue;
493
- if (paths.publicSpecifier) {
494
- match = alias;
495
- matchedAlias = alias.specifier;
496
- matchedSpecifier = paths.publicSpecifier;
497
- break;
498
- }
499
- const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
500
- let canonicalMatch = false;
501
- if (!normalizedMatch && paths.canonical !== paths.normalized) {
502
- await canonicalizeSpecifier();
503
- canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
504
- }
505
- if (normalizedMatch || canonicalMatch) {
506
- match = alias;
507
- matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
508
- matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
509
- break;
510
- }
511
- }
512
- matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
513
- matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
514
- if (!match) return;
515
- const target = match?.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match?.replacement ?? "");
516
- if (!target) return;
517
- const resolvedTarget = /^\.\.?[\\/]/.test(target) ? resolve(aliasResolveDir, target) : target;
518
- return build.resolve(resolvedTarget, {
519
- importer: args.importer,
520
- kind: args.kind,
521
- namespace: args.namespace,
522
- pluginData: {
523
- ...args.pluginData,
524
- [skipResolvedAlias]: true
525
- },
526
- resolveDir: args.resolveDir,
527
- with: args.with
528
- });
529
- });
530
- }
531
- };
532
- }
533
- function createViteAliasPlugin(aliases) {
534
- if (!Array.isArray(aliases)) return;
535
- const resolvingAlias = "vitehubResolvingAlias";
536
- return {
537
- name: "vitehub-vite-alias",
538
- setup(build) {
539
- build.onResolve({ filter: /.*/ }, async (args) => {
540
- if (args.pluginData?.[resolvingAlias]) return;
541
- const alias = aliases.find(({ find }) => {
542
- if (typeof find === "string") return args.path === find || args.path.startsWith(`${find}/`);
543
- find.lastIndex = 0;
544
- return find.test(args.path);
545
- });
546
- if (!alias) return;
547
- if (alias.customResolver) return { errors: [{ text: `[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(args.path)} because it uses customResolver.` }] };
548
- if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
549
- const replacement = typeof alias.find === "string" ? `${alias.replacement}${args.path.slice(alias.find.length)}` : args.path.replace(alias.find, alias.replacement);
550
- const result = await build.resolve(replacement, {
551
- importer: args.importer,
552
- kind: args.kind,
553
- namespace: args.namespace,
554
- pluginData: Object.assign({}, args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {}, { [resolvingAlias]: true }),
555
- resolveDir: args.resolveDir,
556
- with: args.with
557
- });
558
- const pluginData = Object.assign({}, result.pluginData);
559
- Reflect.deleteProperty(pluginData, resolvingAlias);
560
- return {
561
- ...result,
562
- pluginData
563
- };
564
- });
565
- }
566
- };
567
- }
568
- function stripMarkdownCode(template) {
569
- let fence;
570
- let inList = false;
571
- let previousLineBlank = true;
572
- return template.split("\n").map((line) => {
573
- const content = line.replace(/^(?: {0,3}> ?)+/, "");
574
- if (!fence) {
575
- const listIndented = inList && /^ {4}(?:`{3,}|~{3,})/.test(content);
576
- const opening = (listIndented ? content.slice(4) : content).match(/^ {0,3}(`{3,}|~{3,})/);
577
- if (!opening) {
578
- if (/^ {0,3}(?:[-+*]|\d+[.)])\s+/.test(content)) inList = true;
579
- else if (content.trim() && !/^ {2,}/.test(content)) inList = false;
580
- const indentedCode = !inList && previousLineBlank && /^(?: {4}|\t)/.test(content) || inList && previousLineBlank && /^(?: {8}| {4}\t|\t{2})/.test(content);
581
- previousLineBlank = content.trim() === "";
582
- return indentedCode ? "" : line;
583
- }
584
- fence = {
585
- marker: opening[1][0],
586
- length: opening[1].length,
587
- listIndented
588
- };
589
- previousLineBlank = false;
590
- return "";
591
- }
592
- const closing = (fence.listIndented ? content.replace(/^ {4}/, "") : content).match(/^ {0,3}(`+|~+)\s*$/)?.[1];
593
- if (closing?.[0] === fence.marker && closing.length >= fence.length) fence = void 0;
594
- previousLineBlank = false;
595
- return "";
596
- }).join("\n");
597
- }
598
- function extractMarkdownTemplateImportSpecifiers(template) {
599
- const visible = stripMarkdownCode(template).replace(/(`+)[\s\S]*?\1/g, "").replace(/(!?\[[^\]]*\])\([^)]*\)/g, "$1").replace(/^ {0,3}\[[^\]]+\]:\s*\S+/gm, "").replace(/<[^>]*>/g, "");
600
- const specifiers = /* @__PURE__ */ new Set();
601
- for (const match of visible.matchAll(/@(\.\.?\/[^\s<>{}[\]]+)/g)) {
602
- const token = match[1];
603
- const trailing = token.match(/[.,;:!?)]*$/)?.[0] || "";
604
- specifiers.add(token.slice(0, token.length - trailing.length));
605
- }
606
- return [...specifiers];
607
- }
608
- function parseMarkdownTemplateRequest$1(id) {
609
- const queryIndex = id.indexOf("?");
610
- const path = id.split(/[?#]/, 1)[0];
611
- if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix) ? { path } : void 0;
612
- const query = id.slice(queryIndex + 1).split("#", 1)[0];
613
- if (!new URLSearchParams(query).has(markdownTemplateModuleQuery)) return;
614
- return { path };
615
- }
616
- function renderMarkdownTemplateModule(template, sourceId, imports = {}) {
617
- return [
618
- `import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier)}`,
619
- `const vitehubMarkdownTemplate = ${JSON.stringify(template)}`,
620
- `const vitehubMarkdownTemplateSourceId = ${JSON.stringify(sourceId)}`,
621
- `const vitehubMarkdownTemplateImports = ${JSON.stringify(imports)}`,
622
- "export default function render(data = {}) {",
623
- " return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data, sourceId: vitehubMarkdownTemplateSourceId, resolveImport: (specifier, importer) => vitehubMarkdownTemplateImports[`${importer}\\0${specifier}`] })",
624
- "}",
625
- ""
626
- ].join("\n");
627
- }
628
- function hasViteRawQuery(path) {
629
- const queryIndex = path.indexOf("?");
630
- return queryIndex !== -1 && /(?:^|&)raw(?:&|$)/.test(path.slice(queryIndex + 1));
631
- }
632
- async function resolveViteRawSpecifier(path, rootDir) {
633
- if (path.startsWith("/@fs/")) return path.slice(5);
634
- if (!rootDir || !path.startsWith("/")) return path;
635
- const rootRelativePath = path.slice(1);
636
- const publicPath = resolve(rootDir, "public", rootRelativePath);
637
- try {
638
- await stat(publicPath);
639
- return publicPath;
640
- } catch (error) {
641
- if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
642
- return resolve(rootDir, rootRelativePath);
643
- }
644
- }
645
- function createViteRawPlugin(rootDir, frameworkRuntime) {
646
- return {
647
- name: "vitehub-vite-raw",
648
- setup(build) {
649
- build.onResolve({
650
- filter: /^@vite-hub\/markdown-template$/,
651
- namespace: viteMarkdownTemplateNamespace
652
- }, async (args) => {
653
- if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
654
- return build.resolve("vite-hub/_internal/markdown-template", {
655
- importer: args.importer,
656
- kind: args.kind,
657
- resolveDir: args.resolveDir
658
- });
659
- });
660
- build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
661
- if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
662
- const markdownTemplate = parseMarkdownTemplateRequest$1(args.path);
663
- const raw = hasViteRawQuery(args.path);
664
- if (!markdownTemplate && !raw) return;
665
- const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
666
- let pluginData = args.pluginData;
667
- if (markdownTemplate) pluginData = {
668
- ...args.pluginData,
669
- [skipMarkdownTemplateResolve]: true
670
- };
671
- const resolved = await build.resolve(specifier, {
672
- importer: args.importer,
673
- kind: args.kind,
674
- namespace: args.namespace,
675
- pluginData,
676
- resolveDir: args.resolveDir,
677
- with: args.with
678
- });
679
- if (resolved.errors.length) return {
680
- errors: resolved.errors,
681
- warnings: resolved.warnings
682
- };
683
- if (resolved.external) return {
684
- external: true,
685
- namespace: resolved.namespace,
686
- path: resolved.path,
687
- pluginData: resolved.pluginData,
688
- sideEffects: resolved.sideEffects,
689
- suffix: resolved.suffix,
690
- warnings: resolved.warnings
691
- };
692
- if (resolved.namespace !== "file") return {
693
- 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.` }],
694
- warnings: resolved.warnings
695
- };
696
- return {
697
- namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
698
- path: resolved.path,
699
- pluginData: resolved.pluginData,
700
- sideEffects: resolved.sideEffects,
701
- suffix: resolved.suffix,
702
- warnings: resolved.warnings
703
- };
704
- });
705
- build.onLoad({
706
- filter: /.*/,
707
- namespace: viteRawNamespace
708
- }, async (args) => ({
709
- contents: await readFile(args.path),
710
- loader: "text"
711
- }));
712
- build.onLoad({
713
- filter: /.*/,
714
- namespace: viteMarkdownTemplateNamespace
715
- }, async (args) => ({
716
- contents: await (async () => {
717
- const template = await readFile(args.path, "utf8");
718
- const imports = {};
719
- const visited = new Set([args.path]);
720
- const visit = async (source, importer) => {
721
- for (const specifier of extractMarkdownTemplateImportSpecifiers(source)) {
722
- const key = `${importer}\0${specifier}`;
723
- if (imports[key]) continue;
724
- const resolved = await build.resolve(specifier, {
725
- importer,
726
- kind: "import-statement",
727
- pluginData: {
728
- ...args.pluginData,
729
- [skipMarkdownTemplateResolve]: true
730
- },
731
- resolveDir: dirname(importer)
732
- });
733
- if (resolved.errors.length) return Promise.reject(new Error(resolved.errors.map((error) => error.text).join("\n")));
734
- 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.`);
735
- const imported = {
736
- id: resolved.path,
737
- template: await readFile(resolved.path, "utf8")
738
- };
739
- imports[key] = imported;
740
- if (!visited.has(imported.id)) {
741
- visited.add(imported.id);
742
- await visit(imported.template, imported.id);
743
- }
744
- }
745
- };
746
- await visit(template, args.path);
747
- return renderMarkdownTemplateModule(template, args.path, imports);
748
- })(),
749
- loader: "js",
750
- resolveDir: dirname(args.path)
751
- }));
752
- }
753
- };
754
- }
755
- function createFileUrlPlugin() {
756
- return {
757
- name: "vitehub-file-url",
758
- setup(build) {
759
- build.onResolve({ filter: /^file:/ }, (args) => ({ path: fileURLToPath(args.path) }));
760
- }
761
- };
762
- }
763
- async function bundleEsmEntry(entryFile, outfile, options = {}) {
764
- options.signal?.throwIfAborted();
765
- const format = options.format || "esm";
766
- const platform = options.platform || "neutral";
767
- const viteAliasPlugin = createViteAliasPlugin(options.alias);
768
- 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/"));
769
- const plugins = [];
770
- const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd());
771
- if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
772
- plugins.push(...options.plugins ?? [], createFileUrlPlugin());
773
- if (viteAliasPlugin) plugins.push(viteAliasPlugin);
774
- plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime));
775
- const result = await build({
776
- absWorkingDir: options.workingDir,
777
- banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
778
- "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
779
- " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
780
- " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
781
- " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
782
- "}"
783
- ] : []].filter(Boolean).join("\n") } : void 0,
784
- bundle: true,
785
- conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
786
- entryPoints: [entryFile],
787
- external: options.external,
788
- format,
789
- logLevel: "silent",
790
- mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
791
- resolveExtensions: options.extensions,
792
- minifyIdentifiers: options.minifyIdentifiers,
793
- minifyWhitespace: options.minifyWhitespace,
794
- outfile,
795
- packages: options.packages,
796
- platform,
797
- preserveSymlinks: options.preserveSymlinks,
798
- plugins,
799
- sourcemap: false,
800
- target: "es2022",
801
- write: options.signal ? false : true
802
- });
803
- options.signal?.throwIfAborted();
804
- if (options.signal) {
805
- await Promise.all((result.outputFiles ?? []).map(async (output) => {
806
- await mkdir(dirname(output.path), { recursive: true });
807
- options.signal.throwIfAborted();
808
- await writeFile(output.path, output.contents, { signal: options.signal });
809
- }));
810
- options.signal.throwIfAborted();
811
- }
812
- }
813
- //#endregion
814
- //#region ../internal/src/build/paths.ts
815
- function createImportPath(fromFile, targetFile) {
816
- const importPath = relative$1(realpathIfExists(dirname$1(fromFile)), realpathIfExists(targetFile));
817
- return importPath.startsWith(".") ? importPath : `./${importPath}`;
818
- }
819
- function realpathIfExists(path) {
820
- try {
821
- return realpathSync.native(path);
822
- } catch {
823
- return resolve$1(path);
824
- }
825
- }
826
- //#endregion
827
- //#region ../internal/src/build/provider-output-sources.ts
828
- /** Removes retained provider output after readers release it, tolerating transient filesystem contention. */
829
- async function removeProviderOutputArtifactDir(path) {
830
- await rm(path, {
831
- force: true,
832
- maxRetries: 5,
833
- recursive: true,
834
- retryDelay: 50
835
- });
836
- }
837
- //#endregion
838
- //#region ../internal/src/build/vercel-config.ts
839
- function createVercelConfigJson() {
840
- return {
841
- routes: [{ handle: "filesystem" }, {
842
- src: "/(.*)",
843
- dest: "/__server"
844
- }],
845
- version: 3
846
- };
847
- }
848
- function createNodeFunctionConfig(extra = {}) {
849
- return {
850
- handler: "index.mjs",
851
- launcherType: "Nodejs",
852
- runtime: "nodejs22.x",
853
- shouldAddHelpers: false,
854
- supportsResponseStreaming: true,
855
- ...extra
856
- };
857
- }
858
- //#endregion
859
- //#region ../internal/src/build/provider-output-catalog.ts
860
- var ProviderOutputCatalog = class {
861
- #appliedCloudflareContributions = /* @__PURE__ */ new Map();
862
- #cloudflareContributions = /* @__PURE__ */ new Map();
863
- #runtimeContributions = /* @__PURE__ */ new Map();
864
- #runtimeContributionsByGeneration = /* @__PURE__ */ new WeakMap();
865
- #deploymentContributionSequence = 0;
866
- #deploymentContributions = /* @__PURE__ */ new Map();
867
- #deploymentGenerationRefs = /* @__PURE__ */ new WeakMap();
868
- #deploymentGenerations = /* @__PURE__ */ new Set();
869
- #pendingDeploymentDiscards = [];
870
- #takenDeploymentContributions = /* @__PURE__ */ new Map();
871
- appliedCloudflareContributions() {
872
- return this.#appliedCloudflareContributions.values();
873
- }
874
- appliedCloudflareContributionEntries() {
875
- return this.#appliedCloudflareContributions.entries();
876
- }
877
- clearAppliedCloudflareContributions() {
878
- this.#appliedCloudflareContributions.clear();
879
- }
880
- cloudflareContributions() {
881
- return this.#cloudflareContributions.entries();
882
- }
883
- inheritCloudflareContributions(catalog) {
884
- for (const [owner, contribution] of catalog.appliedCloudflareContributionEntries()) this.#appliedCloudflareContributions.set(owner, contribution);
885
- for (const [owner, contribution] of [...catalog.cloudflareContributions(), ...this.#cloudflareContributions]) this.#cloudflareContributions.set(owner, contribution);
886
- }
887
- replaceAppliedCloudflareContribution(owner, contribution) {
888
- this.#appliedCloudflareContributions.set(owner, contribution);
889
- }
890
- replaceCloudflareContribution(owner, contribution) {
891
- this.#cloudflareContributions.set(owner, contribution);
892
- }
893
- replaceRuntimeContribution(contribution, generation) {
894
- if (!generation) {
895
- this.#runtimeContributions.set(contribution.owner, contribution);
896
- return;
897
- }
898
- let contributions = this.#runtimeContributionsByGeneration.get(generation);
899
- if (!contributions) {
900
- contributions = /* @__PURE__ */ new Map();
901
- this.#runtimeContributionsByGeneration.set(generation, contributions);
902
- }
903
- contributions.set(contribution.owner, contribution);
904
- }
905
- runtimeContribution(product, generation) {
906
- return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.get(product);
907
- }
908
- runtimeContributions(generation) {
909
- return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.entries() ?? (/* @__PURE__ */ new Map()).entries();
910
- }
911
- resetRuntimeContributions() {
912
- this.#runtimeContributions.clear();
913
- }
914
- createDeploymentGeneration() {
915
- const generation = { valid: true };
916
- this.#trackDeploymentGeneration(generation);
917
- return generation;
918
- }
919
- replaceDeploymentContribution(contribution, generation) {
920
- const entry = {
921
- contribution,
922
- generation,
923
- sequence: this.#deploymentContributionSequence++
924
- };
925
- if (generation && !generation.valid) {
926
- this.#queueDeploymentDiscard(entry);
927
- return;
928
- }
929
- this.#restoreDeploymentContribution(entry);
930
- }
931
- resetDeploymentContributions(generation) {
932
- if (!generation) {
933
- for (const reference of this.#deploymentGenerations) {
934
- const current = reference.deref();
935
- if (current) current.valid = false;
936
- }
937
- this.#deploymentGenerations.clear();
938
- for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry);
939
- for (const taken of this.#takenDeploymentContributions.values()) {
940
- if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
941
- for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback);
942
- }
943
- this.#deploymentContributions.clear();
944
- this.#takenDeploymentContributions.clear();
945
- return;
946
- }
947
- generation.valid = false;
948
- this.#deleteDeploymentGeneration(generation);
949
- for (const [owner, entries] of this.#deploymentContributions) {
950
- for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry);
951
- const remaining = entries.filter((entry) => entry.generation !== generation);
952
- if (remaining.length) this.#deploymentContributions.set(owner, remaining);
953
- else this.#deploymentContributions.delete(owner);
954
- }
955
- for (const [contribution, taken] of this.#takenDeploymentContributions) {
956
- const invalidatedFallbacks = taken.fallbacks.filter((entry) => entry.generation === generation);
957
- taken.fallbacks = taken.fallbacks.filter((entry) => entry.generation !== generation);
958
- for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback);
959
- if (taken.entry.generation !== generation) continue;
960
- this.#takenDeploymentContributions.delete(contribution);
961
- if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
962
- for (const fallback of taken.fallbacks) if (taken.committed) this.#queueDeploymentDiscard(fallback);
963
- else this.#restoreDeploymentContribution(fallback);
964
- }
965
- }
966
- hasDeploymentContributions() {
967
- return this.#deploymentContributions.size > 0;
968
- }
969
- takeDeploymentContributions() {
970
- const contributions = [];
971
- for (const [owner, entries] of this.#deploymentContributions) {
972
- const entry = entries.at(-1);
973
- contributions.push(entry.contribution);
974
- this.#takenDeploymentContributions.set(entry.contribution, {
975
- committed: false,
976
- entry,
977
- entryDiscarded: false,
978
- fallbacks: entries.slice(0, -1)
979
- });
980
- this.#deploymentContributions.delete(owner);
981
- }
982
- return contributions;
983
- }
984
- deploymentContributionGeneration(contribution) {
985
- return this.#takenDeploymentContributions.get(contribution)?.entry.generation;
986
- }
987
- commitDeploymentContributions(contributions) {
988
- for (const contribution of contributions) {
989
- const taken = this.#takenDeploymentContributions.get(contribution);
990
- if (taken) taken.committed = true;
991
- }
992
- }
993
- async prepareDeploymentContributions(contributions) {
994
- const discarded = this.#pendingDeploymentDiscards.splice(0);
995
- for (const contribution of contributions) {
996
- const taken = this.#takenDeploymentContributions.get(contribution);
997
- if (!taken || taken.entryDiscarded || !taken.entry.contribution.discard) continue;
998
- taken.entryDiscarded = true;
999
- discarded.push(Promise.resolve().then(taken.entry.contribution.discard));
1000
- }
1001
- const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
1002
- if (failure) throw failure.reason;
1003
- }
1004
- async completeDeploymentContributions(contributions) {
1005
- const discarded = this.#pendingDeploymentDiscards.splice(0);
1006
- const completedGenerations = /* @__PURE__ */ new Set();
1007
- for (const contribution of contributions) {
1008
- const taken = this.#takenDeploymentContributions.get(contribution);
1009
- if (!taken) continue;
1010
- this.#takenDeploymentContributions.delete(contribution);
1011
- const entries = taken.entryDiscarded ? taken.fallbacks : [...taken.fallbacks, taken.entry];
1012
- for (const entry of entries) {
1013
- if (entry.generation) completedGenerations.add(entry.generation);
1014
- if (entry.contribution.discard) discarded.push(entry.contribution.discard());
1015
- }
1016
- }
1017
- for (const generation of completedGenerations) this.#retireDeploymentGeneration(generation);
1018
- const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
1019
- if (failure) throw failure.reason;
1020
- }
1021
- rollbackDeploymentContributions(contributions) {
1022
- for (const contribution of contributions) {
1023
- const taken = this.#takenDeploymentContributions.get(contribution);
1024
- if (!taken) continue;
1025
- this.#takenDeploymentContributions.delete(contribution);
1026
- for (const entry of [...taken.fallbacks, taken.entry]) this.#restoreDeploymentContribution(entry);
1027
- }
1028
- }
1029
- #restoreDeploymentContribution(entry) {
1030
- if (entry.generation && !entry.generation.valid) return;
1031
- if (entry.generation) this.#trackDeploymentGeneration(entry.generation);
1032
- const entries = this.#deploymentContributions.get(entry.contribution.owner) ?? [];
1033
- const replaced = entries.findIndex((candidate) => candidate.generation === entry.generation);
1034
- if (replaced >= 0) {
1035
- if (entries[replaced].sequence > entry.sequence) return;
1036
- entries.splice(replaced, 1);
1037
- }
1038
- entries.push(entry);
1039
- entries.sort((left, right) => left.sequence - right.sequence);
1040
- this.#deploymentContributions.set(entry.contribution.owner, entries);
1041
- }
1042
- #retireDeploymentGeneration(generation) {
1043
- const pending = [...this.#deploymentContributions.values()].some((entries) => entries.some((entry) => entry.generation === generation));
1044
- const taken = [...this.#takenDeploymentContributions.values()].some((entry) => entry.entry.generation === generation || entry.fallbacks.some((fallback) => fallback.generation === generation));
1045
- if (!pending && !taken) this.#deleteDeploymentGeneration(generation);
1046
- }
1047
- #trackDeploymentGeneration(generation) {
1048
- if (this.#deploymentGenerationRefs.has(generation)) return;
1049
- const reference = new WeakRef(generation);
1050
- this.#deploymentGenerationRefs.set(generation, reference);
1051
- this.#deploymentGenerations.add(reference);
1052
- }
1053
- #deleteDeploymentGeneration(generation) {
1054
- const reference = this.#deploymentGenerationRefs.get(generation);
1055
- if (reference) this.#deploymentGenerations.delete(reference);
1056
- this.#deploymentGenerationRefs.delete(generation);
1057
- }
1058
- #queueDeploymentDiscard(entry) {
1059
- if (!entry.contribution.discard) return;
1060
- const discard = Promise.resolve().then(entry.contribution.discard);
1061
- discard.catch(() => {});
1062
- this.#pendingDeploymentDiscards.push(discard);
1063
- }
1064
- };
1065
- const providerOutputCatalogRegistry = globalThis;
1066
- const providerOutputCatalogs = providerOutputCatalogRegistry.__vitehubProviderOutputCatalogs ??= /* @__PURE__ */ new WeakMap();
1067
- const providerOutputCatalog = Symbol.for("vitehub.provider-output-catalog");
1068
- function createProviderOutputCatalog() {
1069
- return new ProviderOutputCatalog();
1070
- }
1071
- function useProviderOutputCatalog(config) {
1072
- const owner = config;
1073
- let catalog = owner[providerOutputCatalog] ?? providerOutputCatalogs.get(config);
1074
- if (!catalog) catalog = createProviderOutputCatalog();
1075
- owner[providerOutputCatalog] = catalog;
1076
- providerOutputCatalogs.set(config, catalog);
1077
- return catalog;
1078
- }
1079
- //#endregion
1080
- //#region ../internal/src/build/vite.ts
1081
- const generatedViteHubFilesPattern = "**/.vitehub/**";
1082
- const projectRootDirectoryMarkers = [
1083
- ["server", "agents"],
1084
- ["server", "channels"],
1085
- ["server", "browsers"],
1086
- ["server", "emails"],
1087
- ["server", "schedules"],
1088
- ["server", "workspaces"]
1089
- ];
1090
- const projectRootFileMarkers = [["package.json"]];
1091
- const VITEHUB_ENV_PUBLIC_ID = "#vitehub/env/public";
1092
- const VITEHUB_ENV_SERVER_ID = "#vitehub/env/server";
1093
- function createNoExternalMerger(packageName) {
1094
- return (current) => {
1095
- if (current === true) return true;
1096
- if (!current) return [packageName];
1097
- const values = Array.isArray(current) ? current : [current];
1098
- return values.includes(packageName) ? values : [...values, packageName];
1099
- };
1100
- }
1101
- function isServerEnvironment(name, config) {
1102
- return name === "ssr" || config.consumer === "server";
1103
- }
1104
- function shouldSkipViteProviderBuild(command, mode) {
1105
- return command === "serve" || mode === "e2e";
1106
- }
1107
- function mergeGeneratedViteHubWatchIgnored(ignored) {
1108
- if (!ignored) return [generatedViteHubFilesPattern];
1109
- if (Array.isArray(ignored)) return ignored.includes(generatedViteHubFilesPattern) ? ignored : [...ignored, generatedViteHubFilesPattern];
1110
- return [ignored, generatedViteHubFilesPattern];
1111
- }
1112
- function resolveViteHubProjectRoot(root, options = {}) {
1113
- const resolvedRoot = resolve(root);
1114
- const temporaryRoot = resolve(tmpdir());
1115
- const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
1116
- if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
1117
- if (basename(resolvedRoot) === "app") {
1118
- const parent = dirname(resolvedRoot);
1119
- if (parent !== sharedTemporaryRoot && hasProjectRootDirectoryMarker(parent)) return parent;
1120
- }
1121
- let current = resolvedRoot;
1122
- while (true) {
1123
- if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
1124
- if (hasProjectRootMarker(current)) return current;
1125
- const parent = dirname(current);
1126
- if (parent === current) return resolvedRoot;
1127
- current = parent;
1128
- }
1129
- }
1130
- function hasProjectRootDirectoryMarker(root) {
1131
- for (const marker of projectRootDirectoryMarkers) try {
1132
- if (statSync(resolve(root, ...marker)).isDirectory()) return true;
1133
- } catch (error) {
1134
- if (error.code !== "ENOENT") throw error;
1135
- }
1136
- return false;
1137
- }
1138
- function hasProjectRootMarker(root) {
1139
- if (hasProjectRootDirectoryMarker(root)) return true;
1140
- for (const marker of projectRootFileMarkers) try {
1141
- if (statSync(resolve(root, ...marker)).isFile()) return true;
1142
- } catch (error) {
1143
- if (error.code !== "ENOENT") throw error;
1144
- }
1145
- return false;
1146
- }
1147
- function viteHubEnvPublicModulePath(root) {
1148
- return resolve(root, ".vitehub", "env", "public.mjs");
1149
- }
1150
- function viteHubEnvServerModulePath(root) {
1151
- return resolve(root, ".vitehub", "env", "server.mjs");
1152
- }
1153
- function createViteHubEnvImportAliases(root) {
1154
- return {
1155
- [VITEHUB_ENV_PUBLIC_ID]: viteHubEnvPublicModulePath(root),
1156
- [VITEHUB_ENV_SERVER_ID]: viteHubEnvServerModulePath(root)
1157
- };
1158
- }
1159
- //#endregion
1160
- //#region ../internal/src/build/deployment-output.ts
1161
- const providerDeploymentOutputRegistry = globalThis;
1162
- const providerDeploymentOutputWrites = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputWrites ??= /* @__PURE__ */ new Map();
1163
- const providerDeploymentOutputFinalizations = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputFinalizations ??= /* @__PURE__ */ new WeakMap();
1164
- const providerDeploymentOutputCompletedResets = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputCompletedResets ??= /* @__PURE__ */ new WeakMap();
1165
- const providerDeploymentOutputRootStates = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputRootStates ??= /* @__PURE__ */ new Map();
1166
- const providerDeploymentOutputOwnerOrder = [
1167
- "agent",
1168
- "database",
1169
- "blob",
1170
- "queue",
1171
- "rate-limit",
1172
- "schedule",
1173
- "workflow",
1174
- "vite-hub",
1175
- "browser",
1176
- "kv",
1177
- "workspace"
1178
- ];
1179
- function throwIfProviderOutputAborted(signal) {
1180
- if (!signal.aborted) return;
1181
- throw signal.reason ?? new DOMException("Provider Output finalization aborted.", "AbortError");
1182
- }
1183
- async function settleWrites(writes) {
1184
- const failure = (await Promise.allSettled(writes)).find((result) => result.status === "rejected");
1185
- if (failure) throw failure.reason;
1186
- }
1187
- function resolveClientOutput(rootDir, clientOutDir) {
1188
- const clientDir = resolve(rootDir, clientOutDir);
1189
- return {
1190
- clientDir,
1191
- staticIndex: hasStaticIndex(clientDir)
1192
- };
1193
- }
1194
- function createDefaultCloudflareStaticOutputDir(rootDir) {
1195
- return resolve(rootDir, "dist", "client");
1196
- }
1197
- function resolveProviderOutputOwnershipFile(outputRoot, fileName) {
1198
- if (!fileName || fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") throw new TypeError(`Invalid Provider Output ownership file name: ${JSON.stringify(fileName)}`);
1199
- return resolve(outputRoot, fileName);
1200
- }
1201
- async function readProviderOutputOwnershipFile(outputRoot, fileName) {
1202
- try {
1203
- const parsed = JSON.parse(await readFile(resolveProviderOutputOwnershipFile(outputRoot, fileName), "utf8"));
1204
- if (!Array.isArray(parsed) || !parsed.every((value) => typeof value === "string")) throw new TypeError(`Invalid Provider Output ownership file schema: ${JSON.stringify(fileName)}`);
1205
- return parsed;
1206
- } catch (error) {
1207
- if (error instanceof Error && "code" in error && error.code === "ENOENT") return [];
1208
- throw error;
1209
- }
1210
- }
1211
- async function readCloudflareProviderDeploymentOutputState(rootDir, options) {
1212
- const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(rootDir);
1213
- let wranglerConfig = {};
1214
- try {
1215
- wranglerConfig = JSON.parse(await readFile(resolve(outputRoot, "wrangler.json"), "utf8"));
1216
- } catch (error) {
1217
- if (error.code !== "ENOENT") throw error;
1218
- }
1219
- return {
1220
- wranglerConfig,
1221
- wranglerConfigOwnership: await resolvePersistedProviderOutputOwnership(outputRoot, options.wranglerConfigOwnership, options.wranglerConfigOwnershipFiles)
1222
- };
1223
- }
1224
- async function resolvePersistedProviderOutputOwnership(outputRoot, ownership, files) {
1225
- if (!files || !Object.keys(files).length) return ownership;
1226
- const arrays = { ...ownership?.arrays };
1227
- await Promise.all(Object.entries(files).map(async ([field, fileName]) => {
1228
- const current = arrays[field];
1229
- if (!current) throw new TypeError(`Provider Output ownership file for ${JSON.stringify(field)} requires array ownership.`);
1230
- arrays[field] = {
1231
- ...current,
1232
- values: [...await readProviderOutputOwnershipFile(outputRoot, fileName), ...current.values ?? []]
1233
- };
1234
- }));
1235
- return {
1236
- ...ownership,
1237
- arrays
1238
- };
1239
- }
1240
- async function writeProviderOutputOwnershipFiles(outputRoot, ownership, files) {
1241
- await Promise.all(Object.entries(files ?? {}).map(async ([field, fileName]) => {
1242
- const file = resolveProviderOutputOwnershipFile(outputRoot, fileName);
1243
- const values = [...new Set(ownership?.arrays?.[field]?.values ?? [])];
1244
- if (!values.length) {
1245
- await rm(file, { force: true });
1246
- return;
1247
- }
1248
- await mkdir(outputRoot, { recursive: true });
1249
- await writeFile(file, `${JSON.stringify(values, null, 2)}\n`, "utf8");
1250
- }));
1251
- }
1252
- function createDefaultVercelOutputRoot(rootDir) {
1253
- return resolve(rootDir, ".vercel", "output");
1254
- }
1255
- function createDefaultNetlifyOutputRoot(rootDir) {
1256
- return resolve(rootDir, ".netlify", "v1");
1257
- }
1258
- function assertNetlifyFunctionName(functionName) {
1259
- if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw new Error(`Invalid Netlify function name: ${functionName}`);
1260
- }
1261
- function resolveNetlifyFunctionFile(functionsRoot, functionName) {
1262
- assertNetlifyFunctionName(functionName);
1263
- return resolve(functionsRoot, `${functionName}.mjs`);
1264
- }
1265
- async function appendNetlifyFunctionConfig(outfile, config) {
1266
- if (!config) return;
1267
- await writeFile(outfile, `${(await readFile(outfile, "utf8")).trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
1268
- }
1269
- async function writeCloudflareDeploymentOutput(options, signal) {
1270
- signal?.throwIfAborted();
1271
- const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
1272
- const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
1273
- const staticOutputDir = options.staticOutputDir ?? createDefaultCloudflareStaticOutputDir(options.rootDir);
1274
- const copiesStaticOutput = Boolean(options.bundleEntry && staticIndex && resolve(clientDir) !== resolve(staticOutputDir));
1275
- const files = Object.entries(options.files ?? {});
1276
- const workerOutfile = options.bundleEntry ? resolve(outputRoot, options.bundleOutfileName ?? "index.js") : void 0;
1277
- if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw new Error(`Cloudflare output file conflicts with bundle outfile: ${workerOutfile}`);
1278
- const backupRoot = copiesStaticOutput ? await mkdtemp(resolve(options.rootDir, ".vitehub-cloudflare-output-")) : void 0;
1279
- const previousOutputRoot = backupRoot ? resolve(backupRoot, "output") : `${outputRoot}.previous`;
1280
- const previousStaticOutputDir = backupRoot ? resolve(backupRoot, "static") : `${staticOutputDir}.previous`;
1281
- if (!backupRoot) await rm(previousOutputRoot, {
1282
- force: true,
1283
- recursive: true
1284
- });
1285
- if (copiesStaticOutput && !backupRoot) await rm(previousStaticOutputDir, {
1286
- force: true,
1287
- recursive: true
1288
- });
1289
- let hadPreviousOutput = false;
1290
- let hadPreviousStaticOutput = false;
1291
- let publicationSucceeded = false;
1292
- let publicationStarted = false;
1293
- let outputRestorationSucceeded = false;
1294
- let staticRestorationSucceeded = false;
1295
- try {
1296
- try {
1297
- await cp(outputRoot, previousOutputRoot, { recursive: true });
1298
- hadPreviousOutput = true;
1299
- } catch (error) {
1300
- if (error.code !== "ENOENT") throw error;
1301
- }
1302
- if (copiesStaticOutput) try {
1303
- await cp(staticOutputDir, previousStaticOutputDir, { recursive: true });
1304
- hadPreviousStaticOutput = true;
1305
- } catch (error) {
1306
- if (error.code !== "ENOENT") throw error;
1307
- }
1308
- publicationStarted = true;
1309
- await mkdir(outputRoot, { recursive: true });
1310
- const wranglerConfigOwnership = await resolvePersistedProviderOutputOwnership(outputRoot, options.wranglerConfigOwnership ?? { keys: options.wranglerConfigKeys }, options.wranglerConfigOwnershipFiles);
1311
- const writes = [
1312
- writeCloudflareWranglerConfig({
1313
- outputRoot,
1314
- rootDir: options.rootDir,
1315
- wranglerConfig: options.wranglerConfig,
1316
- wranglerConfigDefaults: options.wranglerConfigDefaults,
1317
- wranglerConfigOwnership
1318
- }),
1319
- options.bundleEntry && staticIndex ? copyClientOutput(clientDir, staticOutputDir) : Promise.resolve(),
1320
- ...files.map(([fileName, contents]) => writeFile(resolve(outputRoot, fileName), contents, "utf8"))
1321
- ];
1322
- if (options.bundleEntry && workerOutfile) {
1323
- const stagedWorkerOutfile = `${workerOutfile}.pending`;
1324
- writes.push((async () => {
1325
- try {
1326
- await rm(stagedWorkerOutfile, {
1327
- force: true,
1328
- recursive: true
1329
- });
1330
- await bundleEsmEntry(options.bundleEntry, stagedWorkerOutfile, {
1331
- ...options.bundleOptions,
1332
- rootDir: options.sourceRootDir ?? options.rootDir,
1333
- signal
1334
- });
1335
- signal?.throwIfAborted();
1336
- await rename(stagedWorkerOutfile, workerOutfile);
1337
- } catch (error) {
1338
- await rm(stagedWorkerOutfile, {
1339
- force: true,
1340
- recursive: true
1341
- });
1342
- throw error;
1343
- }
1344
- })());
1345
- }
1346
- await settleWrites(writes);
1347
- await writeProviderOutputOwnershipFiles(outputRoot, options.wranglerConfigOwnership, options.wranglerConfigOwnershipFiles);
1348
- signal?.throwIfAborted();
1349
- publicationSucceeded = true;
1350
- } catch (error) {
1351
- if (publicationStarted) {
1352
- await rm(outputRoot, {
1353
- force: true,
1354
- recursive: true
1355
- });
1356
- if (hadPreviousOutput) {
1357
- await cp(previousOutputRoot, outputRoot, { recursive: true });
1358
- outputRestorationSucceeded = true;
1359
- }
1360
- if (copiesStaticOutput) {
1361
- await rm(staticOutputDir, {
1362
- force: true,
1363
- recursive: true
1364
- });
1365
- if (hadPreviousStaticOutput) {
1366
- await cp(previousStaticOutputDir, staticOutputDir, { recursive: true });
1367
- staticRestorationSucceeded = true;
1368
- }
1369
- }
1370
- }
1371
- throw error;
1372
- } finally {
1373
- if (!publicationStarted || publicationSucceeded || outputRestorationSucceeded || !hadPreviousOutput) await rm(previousOutputRoot, {
1374
- force: true,
1375
- recursive: true
1376
- }).catch(() => void 0);
1377
- if (copiesStaticOutput && (!publicationStarted || publicationSucceeded || staticRestorationSucceeded || !hadPreviousStaticOutput)) await rm(previousStaticOutputDir, {
1378
- force: true,
1379
- recursive: true
1380
- }).catch(() => void 0);
1381
- if (backupRoot) await rmdir(backupRoot).catch(() => void 0);
1382
- }
1383
- }
1384
- async function copyVercelClientOutput(rootDir, clientDir, staticOutputDir) {
1385
- const cloudflareOutputRoot = createDefaultCloudflareOutputRoot(rootDir);
1386
- const outputRelativePath = relative(clientDir, cloudflareOutputRoot);
1387
- const excludesCloudflareOutput = outputRelativePath && outputRelativePath !== ".." && !outputRelativePath.startsWith(`..${sep}`) && !isAbsolute(outputRelativePath);
1388
- await copyClientOutput(clientDir, staticOutputDir);
1389
- if (resolve(clientDir) === resolve(staticOutputDir) || !excludesCloudflareOutput) return;
1390
- try {
1391
- await readFile(resolve(cloudflareOutputRoot, "wrangler.json"));
1392
- } catch (error) {
1393
- if (error.code === "ENOENT") return;
1394
- throw error;
1395
- }
1396
- await rm(resolve(staticOutputDir, outputRelativePath), {
1397
- force: true,
1398
- recursive: true
1399
- });
1400
- }
1401
- async function writeVercelDeploymentOutput(options, signal) {
1402
- signal?.throwIfAborted();
1403
- const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
1404
- const outputRoot = options.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir);
1405
- const stagedOutputRoot = `${outputRoot}.pending`;
1406
- const previousOutputRoot = `${outputRoot}.previous`;
1407
- const functionOutput = options.function ?? { kind: "root" };
1408
- const serverFunctionName = functionOutput.kind === "root" ? "__server.func" : functionOutput.name;
1409
- const config = options.config ?? (functionOutput.kind === "root" ? createVercelConfigJson() : {});
1410
- const serverDir = resolve(stagedOutputRoot, "functions", serverFunctionName);
1411
- const serverEntry = resolve(serverDir, "index.mjs");
1412
- const staticOutputDir = options.staticOutputDir ?? resolve(outputRoot, "static");
1413
- const staticRelativePath = relative(outputRoot, staticOutputDir);
1414
- const staticInsideOutputRoot = !staticRelativePath.startsWith(`..${sep}`) && !isAbsolute(staticRelativePath);
1415
- const externalStaticNeedsCommit = staticIndex && !staticInsideOutputRoot && resolve(clientDir) !== resolve(staticOutputDir);
1416
- const stagedStaticOutputDir = staticInsideOutputRoot ? resolve(stagedOutputRoot, staticRelativePath) : externalStaticNeedsCommit ? `${staticOutputDir}.pending` : staticOutputDir;
1417
- const previousStaticOutputDir = `${staticOutputDir}.previous`;
1418
- let replacedOutput = false;
1419
- let installedOutput = false;
1420
- let replacedExternalStatic = false;
1421
- let installedExternalStatic = false;
1422
- try {
1423
- await rm(stagedOutputRoot, {
1424
- force: true,
1425
- recursive: true
1426
- });
1427
- try {
1428
- await cp(outputRoot, stagedOutputRoot, { recursive: true });
1429
- } catch (error) {
1430
- if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
1431
- }
1432
- await mkdir(serverDir, { recursive: true });
1433
- await rm(serverDir, {
1434
- force: true,
1435
- recursive: true
1436
- });
1437
- await mkdir(serverDir, { recursive: true });
1438
- try {
1439
- await cp(resolve(outputRoot, "functions", serverFunctionName, "node_modules"), resolve(serverDir, "node_modules"), { recursive: true });
1440
- } catch (error) {
1441
- if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
1442
- }
1443
- await bundleEsmEntry(options.bundleEntry, serverEntry, {
1444
- ...options.bundleOptions,
1445
- rootDir: options.sourceRootDir ?? options.rootDir,
1446
- signal
1447
- });
1448
- await writeFile(resolve(serverDir, ".vc-config.json"), `${stringifyProviderOutputConfig(options.functionConfig ?? createNodeFunctionConfig())}\n`, "utf8");
1449
- 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");
1450
- if (failedWrite?.status === "rejected") throw failedWrite.reason;
1451
- signal?.throwIfAborted();
1452
- rmSync(previousOutputRoot, {
1453
- force: true,
1454
- recursive: true
1455
- });
1456
- if (existsSync(outputRoot)) {
1457
- renameSync(outputRoot, previousOutputRoot);
1458
- replacedOutput = true;
1459
- }
1460
- try {
1461
- renameSync(stagedOutputRoot, outputRoot);
1462
- installedOutput = true;
1463
- } catch (error) {
1464
- if (replacedOutput && existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
1465
- replacedOutput = false;
1466
- throw error;
1467
- }
1468
- signal?.throwIfAborted();
1469
- if (externalStaticNeedsCommit) {
1470
- rmSync(previousStaticOutputDir, {
1471
- force: true,
1472
- recursive: true
1473
- });
1474
- if (existsSync(staticOutputDir)) {
1475
- renameSync(staticOutputDir, previousStaticOutputDir);
1476
- replacedExternalStatic = true;
1477
- }
1478
- try {
1479
- renameSync(stagedStaticOutputDir, staticOutputDir);
1480
- installedExternalStatic = true;
1481
- } catch (error) {
1482
- if (replacedExternalStatic && existsSync(previousStaticOutputDir)) renameSync(previousStaticOutputDir, staticOutputDir);
1483
- replacedExternalStatic = false;
1484
- throw error;
1485
- }
1486
- signal?.throwIfAborted();
1487
- }
1488
- try {
1489
- rmSync(previousOutputRoot, {
1490
- force: true,
1491
- recursive: true
1492
- });
1493
- } catch {}
1494
- if (replacedExternalStatic) try {
1495
- rmSync(previousStaticOutputDir, {
1496
- force: true,
1497
- recursive: true
1498
- });
1499
- } catch {}
1500
- } catch (error) {
1501
- await rm(stagedOutputRoot, {
1502
- force: true,
1503
- recursive: true
1504
- });
1505
- if (externalStaticNeedsCommit) await rm(stagedStaticOutputDir, {
1506
- force: true,
1507
- recursive: true
1508
- });
1509
- if (installedExternalStatic) rmSync(staticOutputDir, {
1510
- force: true,
1511
- recursive: true
1512
- });
1513
- if (replacedExternalStatic) {
1514
- if (existsSync(previousStaticOutputDir)) renameSync(previousStaticOutputDir, staticOutputDir);
1515
- }
1516
- if (installedOutput) rmSync(outputRoot, {
1517
- force: true,
1518
- recursive: true
1519
- });
1520
- if (replacedOutput) {
1521
- if (existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
1522
- }
1523
- throw error;
1524
- }
1525
- }
1526
- async function writeNetlifyDeploymentOutput(options, signal) {
1527
- signal?.throwIfAborted();
1528
- const outputRoot = options.outputRoot ?? createDefaultNetlifyOutputRoot(options.rootDir);
1529
- const stagedOutputRoot = `${outputRoot}.pending`;
1530
- const previousOutputRoot = `${outputRoot}.previous`;
1531
- const functionsRoot = resolve(stagedOutputRoot, "functions");
1532
- let replacedOutput = false;
1533
- let installedOutput = false;
1534
- await rm(stagedOutputRoot, {
1535
- force: true,
1536
- recursive: true
1537
- });
1538
- await rm(previousOutputRoot, {
1539
- force: true,
1540
- recursive: true
1541
- });
1542
- try {
1543
- await cp(outputRoot, stagedOutputRoot, { recursive: true });
1544
- } catch (error) {
1545
- if (error.code !== "ENOENT") throw error;
1546
- }
1547
- const functionWrites = (options.functions ?? []).map(async (func) => {
1548
- const outfile = resolveNetlifyFunctionFile(functionsRoot, func.functionName);
1549
- await mkdir(dirname(outfile), { recursive: true });
1550
- await bundleEsmEntry(func.bundleEntry, outfile, {
1551
- ...func.bundleOptions,
1552
- minifyIdentifiers: func.config ? true : func.bundleOptions.minifyIdentifiers,
1553
- rootDir: options.sourceRootDir ?? options.rootDir,
1554
- signal
1555
- });
1556
- await appendNetlifyFunctionConfig(outfile, func.config);
1557
- });
1558
- try {
1559
- await mkdir(stagedOutputRoot, { recursive: true });
1560
- await settleWrites([writeProviderOutputConfig(resolve(stagedOutputRoot, "config.json"), options.config ?? {}, { keys: options.configKeys }), ...functionWrites]);
1561
- signal?.throwIfAborted();
1562
- if (existsSync(outputRoot)) {
1563
- renameSync(outputRoot, previousOutputRoot);
1564
- replacedOutput = true;
1565
- }
1566
- renameSync(stagedOutputRoot, outputRoot);
1567
- installedOutput = true;
1568
- signal?.throwIfAborted();
1569
- } catch (error) {
1570
- await rm(stagedOutputRoot, {
1571
- force: true,
1572
- recursive: true
1573
- });
1574
- if (installedOutput) rmSync(outputRoot, {
1575
- force: true,
1576
- recursive: true
1577
- });
1578
- if (replacedOutput && existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
1579
- throw error;
1580
- }
1581
- try {
1582
- rmSync(previousOutputRoot, {
1583
- force: true,
1584
- recursive: true
1585
- });
1586
- } catch {}
1587
- }
1588
- async function cleanupCloudflareDeploymentOutput(rootDir, cleanupInput, signal) {
1589
- const cleanup = typeof cleanupInput === "function" ? await cleanupInput() : cleanupInput;
1590
- signal?.throwIfAborted();
1591
- const outputRoot = cleanup.outputRoot ?? createDefaultCloudflareOutputRoot(rootDir);
1592
- if (!shouldRunCloudflareDeploymentOutputCleanup(outputRoot, cleanup)) return;
1593
- const wranglerConfigOwnership = await resolvePersistedProviderOutputOwnership(outputRoot, cleanup.wranglerConfigOwnership, cleanup.wranglerConfigOwnershipFiles);
1594
- const writes = (cleanup.fileNames ?? []).map((fileName) => rm(resolve(outputRoot, fileName), {
1595
- force: true,
1596
- recursive: true
1597
- }));
1598
- writes.push(writeCloudflareWranglerConfig({
1599
- outputRoot,
1600
- rootDir,
1601
- wranglerConfigOwnership
1602
- }));
1603
- await Promise.all(writes);
1604
- await writeProviderOutputOwnershipFiles(outputRoot, cleanup.wranglerConfigOwnership, cleanup.wranglerConfigOwnershipFiles);
1605
- try {
1606
- await rmdir(outputRoot);
1607
- } catch (error) {
1608
- const code = error.code;
1609
- if (code !== "ENOENT" && code !== "ENOTEMPTY") throw error;
1610
- }
1611
- }
1612
- function shouldRunCloudflareDeploymentOutputCleanup(outputRoot, cleanup) {
1613
- return !cleanup.requirePersistedOwnership || Object.values(cleanup.wranglerConfigOwnershipFiles ?? {}).some((fileName) => existsSync(resolveProviderOutputOwnershipFile(outputRoot, fileName)));
1614
- }
1615
- async function cleanupVercelDeploymentOutput(rootDir, cleanup, signal) {
1616
- signal?.throwIfAborted();
1617
- const outputRoot = cleanup.outputRoot ?? createDefaultVercelOutputRoot(rootDir);
1618
- const writes = [];
1619
- if (cleanup.serverFunctionName) writes.push(rm(resolve(outputRoot, "functions", cleanup.serverFunctionName), {
1620
- force: true,
1621
- recursive: true
1622
- }));
1623
- writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
1624
- await Promise.all(writes);
1625
- }
1626
- async function cleanupVercelDeploymentOutputs(rootDir, cleanup, signal) {
1627
- await Promise.all((Array.isArray(cleanup) ? cleanup : [cleanup]).map((item) => cleanupVercelDeploymentOutput(rootDir, item, signal)));
1628
- }
1629
- async function cleanupNetlifyDeploymentOutput(rootDir, cleanup, signal) {
1630
- signal?.throwIfAborted();
1631
- const outputRoot = cleanup.outputRoot ?? createDefaultNetlifyOutputRoot(rootDir);
1632
- const functionsRoot = resolve(outputRoot, "functions");
1633
- const writes = (cleanup.functionNames ?? []).map((functionName) => rm(resolveNetlifyFunctionFile(functionsRoot, functionName), {
1634
- force: true,
1635
- recursive: true
1636
- }));
1637
- writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
1638
- await Promise.all(writes);
1639
- }
1640
- async function writeProviderDeploymentOutputsNow(options, signal, transaction) {
1641
- signal?.throwIfAborted();
1642
- const clientDir = resolve(options.rootDir, options.clientOutDir);
1643
- await transaction?.snapshot(providerDeploymentOutputPaths(options), [clientDir]);
1644
- const writes = [];
1645
- if (options.cloudflare) writes.push(writeCloudflareDeploymentOutput({
1646
- ...options.cloudflare,
1647
- clientOutDir: options.clientOutDir,
1648
- rootDir: options.rootDir,
1649
- sourceRootDir: options.sourceRootDir
1650
- }, signal));
1651
- if (options.netlify) writes.push(writeNetlifyDeploymentOutput({
1652
- ...options.netlify,
1653
- clientOutDir: options.clientOutDir,
1654
- rootDir: options.rootDir,
1655
- sourceRootDir: options.sourceRootDir
1656
- }, signal));
1657
- if (options.vercel) writes.push(writeVercelDeploymentOutput({
1658
- ...options.vercel,
1659
- clientOutDir: options.clientOutDir,
1660
- rootDir: options.rootDir,
1661
- sourceRootDir: options.sourceRootDir
1662
- }, signal));
1663
- await settleWrites(writes);
1664
- if (options.cloudflare && transaction) transaction.cloudflareWritten = true;
1665
- signal?.throwIfAborted();
1666
- await options.afterWrite?.(signal);
1667
- signal?.throwIfAborted();
1668
- const cleanups = [];
1669
- const cleanupPaths = [];
1670
- if (!options.cloudflare && options.cleanup?.cloudflare) {
1671
- let cleanup = typeof options.cleanup.cloudflare === "function" ? await options.cleanup.cloudflare() : options.cleanup.cloudflare;
1672
- const outputRoot = cleanup.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
1673
- if (resolve(outputRoot) === clientDir) cleanup = {
1674
- ...cleanup,
1675
- fileNames: []
1676
- };
1677
- else if (transaction?.cloudflareWritten) cleanup = {
1678
- ...cleanup,
1679
- fileNames: []
1680
- };
1681
- if (shouldRunCloudflareDeploymentOutputCleanup(outputRoot, cleanup)) {
1682
- cleanupPaths.push(outputRoot);
1683
- cleanups.push(async () => await cleanupCloudflareDeploymentOutput(options.rootDir, cleanup, signal));
1684
- }
1685
- }
1686
- if (!options.netlify && options.cleanup?.netlify) {
1687
- const cleanup = options.cleanup.netlify;
1688
- cleanupPaths.push(cleanup.outputRoot ?? createDefaultNetlifyOutputRoot(options.rootDir));
1689
- cleanups.push(async () => await cleanupNetlifyDeploymentOutput(options.rootDir, cleanup, signal));
1690
- }
1691
- if (!options.vercel && options.cleanup?.vercel) {
1692
- const cleanup = typeof options.cleanup.vercel === "function" ? await options.cleanup.vercel() : options.cleanup.vercel;
1693
- signal?.throwIfAborted();
1694
- if (cleanup) {
1695
- const items = Array.isArray(cleanup) ? cleanup : [cleanup];
1696
- cleanupPaths.push(...items.map((item) => item.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir)));
1697
- cleanups.push(async () => await cleanupVercelDeploymentOutputs(options.rootDir, cleanup, signal));
1698
- }
1699
- }
1700
- await transaction?.snapshot(cleanupPaths, [clientDir]);
1701
- await settleWrites(cleanups.map((cleanup) => cleanup()));
1702
- signal?.throwIfAborted();
1703
- }
1704
- function providerDeploymentOutputPaths(options) {
1705
- const clientDir = resolve(options.rootDir, options.clientOutDir);
1706
- return [
1707
- options.cloudflare && (options.cloudflare.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir)),
1708
- options.cloudflare?.staticOutputDir,
1709
- options.netlify?.outputRoot,
1710
- options.vercel?.outputRoot,
1711
- options.vercel?.staticOutputDir
1712
- ].filter((path) => Boolean(path) && resolve(path) !== clientDir);
1713
- }
1714
- async function withProviderDeploymentOutputRootLock(rootDir, operation) {
1715
- const key = resolve(rootDir);
1716
- const state = providerDeploymentOutputRootStates.get(key) ?? { pending: 0 };
1717
- providerDeploymentOutputRootStates.set(key, state);
1718
- state.pending++;
1719
- const current = (providerDeploymentOutputWrites.get(key) ?? Promise.resolve()).catch(() => void 0).then(async () => await operation(state));
1720
- providerDeploymentOutputWrites.set(key, current);
1721
- try {
1722
- return await current;
1723
- } finally {
1724
- if (providerDeploymentOutputWrites.get(key) === current) providerDeploymentOutputWrites.delete(key);
1725
- state.pending--;
1726
- if (state.pending === 0 && providerDeploymentOutputRootStates.get(key) === state) providerDeploymentOutputRootStates.delete(key);
1727
- }
1728
- }
1729
- function pathContains(parent, child) {
1730
- const nested = relative(parent, child);
1731
- return !nested || !nested.startsWith(`..${sep}`) && nested !== ".." && !isAbsolute(nested);
1732
- }
1733
- async function restoreProviderDeploymentOutputSnapshot(snapshot) {
1734
- if (snapshot.present) await mkdir(dirname(snapshot.path), { recursive: true });
1735
- const restoreRoot = await mkdtemp(resolve(snapshot.present ? dirname(snapshot.path) : tmpdir(), "vitehub-provider-output-restore-"));
1736
- const staged = resolve(restoreRoot, "snapshot");
1737
- const preservedRoot = resolve(restoreRoot, "preserved");
1738
- try {
1739
- await mkdir(preservedRoot, { recursive: true });
1740
- const preserved = snapshot.preservedPaths.map((path, index) => ({
1741
- backup: resolve(preservedRoot, String(index)),
1742
- path,
1743
- present: existsSync(path)
1744
- }));
1745
- await Promise.all(preserved.map(async (entry) => {
1746
- if (entry.present) await cp(entry.path, entry.backup, { recursive: true });
1747
- }));
1748
- if (snapshot.present) await cp(snapshot.backup, staged, { recursive: true });
1749
- await rm(snapshot.path, {
1750
- force: true,
1751
- recursive: true
1752
- });
1753
- if (snapshot.present) await rename(staged, snapshot.path);
1754
- for (const entry of preserved) {
1755
- await rm(entry.path, {
1756
- force: true,
1757
- recursive: true
1758
- });
1759
- if (entry.present) {
1760
- await mkdir(dirname(entry.path), { recursive: true });
1761
- await cp(entry.backup, entry.path, { recursive: true });
1762
- }
1763
- }
1764
- } finally {
1765
- await rm(restoreRoot, {
1766
- force: true,
1767
- recursive: true
1768
- });
1769
- }
1770
- }
1771
- async function withProviderDeploymentOutputRootTransaction(rootDir, operation, options = {}) {
1772
- const roots = [
1773
- createDefaultCloudflareOutputRoot(rootDir),
1774
- createDefaultNetlifyOutputRoot(rootDir),
1775
- createDefaultVercelOutputRoot(rootDir),
1776
- resolve(rootDir, ".vitehub/agent"),
1777
- resolve(rootDir, ".vitehub/blob/cloudflare-output.json"),
1778
- resolve(rootDir, ".vitehub/queue/cloudflare-output.json"),
1779
- resolve(rootDir, ".vitehub/queue/registry.mjs"),
1780
- resolve(rootDir, ".vitehub/queue/vercel-output.json"),
1781
- resolve(rootDir, ".vitehub/rate-limit/cloudflare-output.json"),
1782
- resolve(rootDir, ".vitehub/rate-limit/manifest.json"),
1783
- resolve(rootDir, ".vitehub/schedule"),
1784
- resolve(rootDir, ".vitehub/workflow")
1785
- ];
1786
- const transactionRoot = await mkdtemp(resolve(tmpdir(), "vitehub-provider-output-"));
1787
- const snapshots = /* @__PURE__ */ new Map();
1788
- let snapshotIndex = 0;
1789
- const transaction = {
1790
- cloudflareWritten: false,
1791
- async snapshot(paths, preservedPaths = []) {
1792
- const resolvedPreservedPaths = [...new Set(preservedPaths.map((path) => resolve(path)))];
1793
- for (const snapshot of snapshots.values()) {
1794
- const additions = resolvedPreservedPaths.filter((path) => path !== snapshot.path && pathContains(snapshot.path, path) && !snapshot.preservedPaths.includes(path));
1795
- snapshot.preservedPaths.push(...additions);
1796
- if (snapshot.present) await Promise.all(additions.map((path) => rm(resolve(snapshot.backup, relative(snapshot.path, path)), {
1797
- force: true,
1798
- recursive: true
1799
- })));
1800
- }
1801
- 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) => ({
1802
- backup: resolve(transactionRoot, String(snapshotIndex++)),
1803
- path,
1804
- present: existsSync(path),
1805
- preservedPaths: resolvedPreservedPaths.filter((preserved) => preserved !== path && pathContains(path, preserved))
1806
- }));
1807
- const failure = (await Promise.allSettled(pending.map(async (snapshot) => {
1808
- if (snapshot.present) {
1809
- await cp(snapshot.path, snapshot.backup, { recursive: true });
1810
- await Promise.all(snapshot.preservedPaths.map((path) => rm(resolve(snapshot.backup, relative(snapshot.path, path)), {
1811
- force: true,
1812
- recursive: true
1813
- })));
1814
- }
1815
- }))).find((result) => result.status === "rejected");
1816
- if (failure) {
1817
- await Promise.all(pending.map((snapshot) => rm(snapshot.backup, {
1818
- force: true,
1819
- recursive: true
1820
- })));
1821
- throw failure.reason;
1822
- }
1823
- for (const snapshot of pending) {
1824
- const children = [...snapshots.values()].filter((child) => pathContains(snapshot.path, child.path));
1825
- if (snapshot.present) for (const child of children) {
1826
- const nestedBackup = resolve(snapshot.backup, relative(snapshot.path, child.path));
1827
- await rm(nestedBackup, {
1828
- force: true,
1829
- recursive: true
1830
- });
1831
- if (child.present) {
1832
- await mkdir(dirname(nestedBackup), { recursive: true });
1833
- await cp(child.backup, nestedBackup, { recursive: true });
1834
- }
1835
- }
1836
- for (const child of children) {
1837
- snapshots.delete(child.path);
1838
- await rm(child.backup, {
1839
- force: true,
1840
- recursive: true
1841
- });
1842
- }
1843
- snapshot.preservedPaths.push(...children.flatMap((child) => child.preservedPaths).filter((path) => !snapshot.preservedPaths.includes(path)));
1844
- if (snapshot.present) await Promise.all(snapshot.preservedPaths.map((path) => rm(resolve(snapshot.backup, relative(snapshot.path, path)), {
1845
- force: true,
1846
- recursive: true
1847
- })));
1848
- snapshots.set(snapshot.path, snapshot);
1849
- }
1850
- }
1851
- };
1852
- try {
1853
- if (options.snapshotInitialRoots !== false) await transaction.snapshot(roots);
1854
- const result = await operation(transaction);
1855
- await removeProviderOutputArtifactDir(transactionRoot).catch(() => void 0);
1856
- return result;
1857
- } catch (error) {
1858
- const restorations = await Promise.allSettled([...snapshots.values()].map(restoreProviderDeploymentOutputSnapshot));
1859
- if (restorations.every((result) => result.status === "fulfilled")) await rm(transactionRoot, {
1860
- force: true,
1861
- recursive: true
1862
- });
1863
- const restorationFailure = restorations.find((result) => result.status === "rejected");
1864
- if (restorationFailure) throw new AggregateError([error, restorationFailure.reason], "Provider Output rollback failed");
1865
- throw error;
1866
- }
1867
- }
1868
- function contributeProviderDeploymentOutput(catalog, contribution, generation) {
1869
- closeProviderDeploymentOutputGenerationCapture(generation);
1870
- catalog?.replaceDeploymentContribution(contribution, generation);
1871
- }
1872
- const providerDeploymentOutputEnvironmentGenerations = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputEnvironmentGenerations ??= /* @__PURE__ */ new WeakMap();
1873
- const providerDeploymentOutputGenerationEnvironments = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputGenerationEnvironments ??= /* @__PURE__ */ new WeakMap();
1874
- const providerDeploymentOutputFallbackEnvironment = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputFallbackEnvironment ??= {};
1875
- function closeProviderDeploymentOutputGenerationCapture(generation) {
1876
- if (!generation) return;
1877
- const captured = providerDeploymentOutputGenerationEnvironments.get(generation);
1878
- if (!captured) return;
1879
- const generations = providerDeploymentOutputEnvironmentGenerations.get(captured.catalog);
1880
- if (generations?.get(captured.environment) === generation) generations.delete(captured.environment);
1881
- providerDeploymentOutputGenerationEnvironments.delete(generation);
1882
- }
1883
- function createProviderDeploymentOutputGenerationState() {
1884
- const generations = /* @__PURE__ */ new WeakMap();
1885
- const readiness = /* @__PURE__ */ new WeakMap();
1886
- const localEnvironment = (context) => context?.environment ?? context ?? providerDeploymentOutputFallbackEnvironment;
1887
- const sharedEnvironment = (context) => context?.environment ?? providerDeploymentOutputFallbackEnvironment;
1888
- return {
1889
- capture(context, catalog) {
1890
- const localEnvironmentKey = localEnvironment(context);
1891
- readiness.delete(localEnvironmentKey);
1892
- if (!catalog) {
1893
- generations.set(localEnvironmentKey, void 0);
1894
- return;
1895
- }
1896
- const environmentKey = sharedEnvironment(context);
1897
- let catalogGenerations = providerDeploymentOutputEnvironmentGenerations.get(catalog);
1898
- if (!catalogGenerations) {
1899
- catalogGenerations = /* @__PURE__ */ new WeakMap();
1900
- providerDeploymentOutputEnvironmentGenerations.set(catalog, catalogGenerations);
1901
- }
1902
- const sharedGeneration = catalogGenerations.get(environmentKey);
1903
- const generation = !sharedGeneration || generations.get(localEnvironmentKey) === sharedGeneration ? catalog.createDeploymentGeneration() : sharedGeneration;
1904
- catalogGenerations.set(environmentKey, generation);
1905
- providerDeploymentOutputGenerationEnvironments.set(generation, {
1906
- catalog,
1907
- environment: environmentKey
1908
- });
1909
- generations.set(localEnvironmentKey, generation);
1910
- },
1911
- defer(context, catalog, contribution) {
1912
- const localEnvironmentKey = localEnvironment(context);
1913
- const state = { ready: false };
1914
- readiness.set(localEnvironmentKey, state);
1915
- contributeProviderDeploymentOutput(catalog, {
1916
- ...contribution,
1917
- ready: () => state.ready
1918
- }, generations.get(localEnvironmentKey));
1919
- },
1920
- get(context) {
1921
- return generations.get(localEnvironment(context));
1922
- },
1923
- ready(context) {
1924
- const state = readiness.get(localEnvironment(context));
1925
- if (state) state.ready = true;
1926
- },
1927
- async reset(context, catalog, failure) {
1928
- const localEnvironmentKey = localEnvironment(context);
1929
- const generation = generations.get(localEnvironmentKey);
1930
- readiness.delete(localEnvironmentKey);
1931
- closeProviderDeploymentOutputGenerationCapture(generation);
1932
- await resetProviderDeploymentOutputs(catalog, failure, generation);
1933
- }
1934
- };
1935
- }
1936
- async function resetProviderDeploymentOutputs(catalog, failure, generation) {
1937
- if (!catalog) return;
1938
- const completedReset = providerDeploymentOutputCompletedResets.get(catalog);
1939
- if (completedReset && failure !== void 0 && completedReset.failures.has(failure)) {
1940
- if (generation) catalog.resetDeploymentContributions(generation);
1941
- await completedReset.promise;
1942
- return;
1943
- }
1944
- if (completedReset) providerDeploymentOutputCompletedResets.delete(catalog);
1945
- if (generation) catalog.resetDeploymentContributions(generation);
1946
- const active = providerDeploymentOutputFinalizations.get(catalog);
1947
- if (active?.reset) {
1948
- if (failure !== void 0 && !active.reset.failures.has(failure)) {
1949
- active.reset.failures.add(failure);
1950
- if (!generation) catalog.resetDeploymentContributions();
1951
- }
1952
- providerDeploymentOutputCompletedResets.set(catalog, active.reset);
1953
- await active.reset.promise;
1954
- return;
1955
- }
1956
- if (!generation) catalog.resetDeploymentContributions();
1957
- if (active && (!generation || active.state.generations.has(generation))) {
1958
- active.state.rollback = true;
1959
- active.controller.abort(/* @__PURE__ */ new Error("Provider Output finalization reset"));
1960
- active.reset = {
1961
- failures: new Set([failure]),
1962
- promise: active.promise.catch(() => void 0)
1963
- };
1964
- providerDeploymentOutputCompletedResets.set(catalog, active.reset);
1965
- await active.reset.promise;
1966
- } else if (failure !== void 0) providerDeploymentOutputCompletedResets.set(catalog, {
1967
- failures: new Set([failure]),
1968
- promise: Promise.resolve()
1969
- });
1970
- }
1971
- async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
1972
- if (!catalog) return;
1973
- const existing = providerDeploymentOutputFinalizations.get(catalog);
1974
- if (existing) {
1975
- try {
1976
- await existing.promise;
1977
- } catch (error) {
1978
- if (!catalog.hasDeploymentContributions()) throw error;
1979
- existing.handoff ??= (async () => {
1980
- await existing.promise.catch(() => void 0);
1981
- if (providerDeploymentOutputFinalizations.get(catalog) === existing) providerDeploymentOutputFinalizations.delete(catalog);
1982
- await finalizeProviderDeploymentOutputs(catalog, options);
1983
- })();
1984
- await existing.handoff;
1985
- return;
1986
- }
1987
- if (providerDeploymentOutputFinalizations.get(catalog) === existing) providerDeploymentOutputFinalizations.delete(catalog);
1988
- if (catalog.hasDeploymentContributions()) await finalizeProviderDeploymentOutputs(catalog, options);
1989
- return;
1990
- }
1991
- const controller = new AbortController();
1992
- const state = {
1993
- generations: /* @__PURE__ */ new Set(),
1994
- rollback: false
1995
- };
1996
- const finalization = (async () => {
1997
- const order = new Map(providerDeploymentOutputOwnerOrder.map((owner, index) => [owner, index]));
1998
- const abort = () => controller.abort(options.signal?.reason);
1999
- if (options.signal?.aborted) abort();
2000
- else options.signal?.addEventListener("abort", abort, { once: true });
2001
- try {
2002
- while (true) {
2003
- const contributions = catalog.takeDeploymentContributions();
2004
- if (!contributions.length) return;
2005
- try {
2006
- if (contributions.some((contribution) => contribution.ready?.() === false)) {
2007
- if (controller.signal.aborted) {
2008
- await catalog.completeDeploymentContributions(contributions);
2009
- throwIfProviderOutputAborted(controller.signal);
2010
- }
2011
- catalog.rollbackDeploymentContributions(contributions);
2012
- return;
2013
- }
2014
- } catch (error) {
2015
- catalog.rollbackDeploymentContributions(contributions);
2016
- throw error;
2017
- }
2018
- for (const contribution of contributions) {
2019
- const generation = catalog.deploymentContributionGeneration(contribution);
2020
- if (generation) state.generations.add(generation);
2021
- }
2022
- contributions.sort((left, right) => order.get(left.owner) - order.get(right.owner));
2023
- const grouped = /* @__PURE__ */ new Map();
2024
- for (const contribution of contributions) {
2025
- const rootDir = resolve(contribution.rootDir);
2026
- const rootContributions = grouped.get(rootDir) ?? [];
2027
- rootContributions.push(contribution);
2028
- grouped.set(rootDir, rootContributions);
2029
- }
2030
- try {
2031
- let decideRoots;
2032
- const rootDecision = new Promise((resolve) => {
2033
- decideRoots = resolve;
2034
- });
2035
- const roots = [...grouped.entries()].map(([rootDir, rootContributions]) => {
2036
- let ready;
2037
- let rejectReady;
2038
- const readiness = new Promise((resolve, reject) => {
2039
- ready = resolve;
2040
- rejectReady = reject;
2041
- });
2042
- const write = withProviderDeploymentOutputRootLock(rootDir, async () => {
2043
- await withProviderDeploymentOutputRootTransaction(rootDir, async (transaction) => {
2044
- try {
2045
- for (const contribution of rootContributions) {
2046
- throwIfProviderOutputAborted(controller.signal);
2047
- await contribution.write({
2048
- readCloudflareState: async (options) => await readCloudflareProviderDeploymentOutputState(rootDir, options),
2049
- signal: controller.signal,
2050
- write: async (writeOptions) => {
2051
- throwIfProviderOutputAborted(controller.signal);
2052
- await writeProviderDeploymentOutputsNow(writeOptions, controller.signal, transaction);
2053
- }
2054
- });
2055
- throwIfProviderOutputAborted(controller.signal);
2056
- }
2057
- ready();
2058
- const rollback = await rootDecision;
2059
- if (rollback !== void 0) throw rollback;
2060
- throwIfProviderOutputAborted(controller.signal);
2061
- } catch (error) {
2062
- controller.abort(error);
2063
- rejectReady(error);
2064
- throw error;
2065
- }
2066
- }, { snapshotInitialRoots: rootContributions.some((contribution) => contribution.owner !== "kv") });
2067
- });
2068
- write.catch(rejectReady);
2069
- return {
2070
- readiness,
2071
- write
2072
- };
2073
- });
2074
- const failedRoot = (await Promise.allSettled(roots.map((root) => root.readiness))).find((result) => result.status === "rejected");
2075
- if (failedRoot) {
2076
- decideRoots(failedRoot.reason);
2077
- await settleWrites(roots.map((root) => root.write));
2078
- }
2079
- try {
2080
- await catalog.prepareDeploymentContributions(contributions);
2081
- throwIfProviderOutputAborted(controller.signal);
2082
- } catch (error) {
2083
- decideRoots(error);
2084
- await settleWrites(roots.map((root) => root.write));
2085
- throw error;
2086
- }
2087
- catalog.commitDeploymentContributions(contributions);
2088
- state.generations.clear();
2089
- decideRoots(void 0);
2090
- await settleWrites(roots.map((root) => root.write));
2091
- await catalog.completeDeploymentContributions(contributions);
2092
- } catch (error) {
2093
- if (state.rollback) catalog.rollbackDeploymentContributions(contributions);
2094
- else await catalog.completeDeploymentContributions(contributions);
2095
- throw error;
2096
- } finally {
2097
- state.generations.clear();
2098
- }
2099
- }
2100
- } finally {
2101
- options.signal?.removeEventListener("abort", abort);
2102
- }
2103
- })();
2104
- const active = {
2105
- controller,
2106
- promise: finalization,
2107
- state
2108
- };
2109
- providerDeploymentOutputFinalizations.set(catalog, active);
2110
- try {
2111
- await finalization;
2112
- } finally {
2113
- if (providerDeploymentOutputFinalizations.get(catalog) === active) providerDeploymentOutputFinalizations.delete(catalog);
2114
- }
2115
- }
2116
- const VITEHUB_MODES = {
2117
- e2e: "e2e",
2118
- blob: "blob",
2119
- chat: "chat",
2120
- db: "db",
2121
- env: "env",
2122
- kv: "kv",
2123
- queue: "queue",
2124
- schedule: "schedule",
2125
- sandbox: "sandbox",
2126
- workspace: "workspace",
2127
- workflow: "workflow"
2128
- };
2129
- function isViteCli(argv) {
2130
- return argv.some((arg) => /(?:^|[/\\])vite(?:\.[cm]?js)?$/.test(arg) || arg === "vite");
2131
- }
2132
- function getViteCliMode(argv = process.argv) {
2133
- if (!isViteCli(argv)) return;
2134
- const modes = new Set(Object.values(VITEHUB_MODES));
2135
- for (let index = 0; index < argv.length; index += 1) {
2136
- const arg = argv[index];
2137
- const mode = arg === "--mode" || arg === "-m" ? argv[index + 1] : arg.startsWith("--mode=") ? arg.slice(7) : void 0;
2138
- if (mode && modes.has(mode)) return mode;
2139
- }
2140
- }
2141
- function getViteMode(env = process.env) {
2142
- return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
2143
- }
2144
- //#endregion
2145
- //#region ../internal/src/build/vercel-runtime-packages.ts
2146
- const runtimeExportConditions = new Set([
2147
- "default",
2148
- "import",
2149
- "module",
2150
- "node",
2151
- "node-addons",
2152
- "require"
2153
- ]);
2154
- let nodeFileTracePromise;
2155
- async function copyVercelFunctionRuntimePackages(options) {
2156
- const serverDir = resolve(options.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir), "functions", options.serverFunctionName ?? "__server.func");
2157
- try {
2158
- await access(serverDir);
2159
- } catch (error) {
2160
- if (error.code === "ENOENT") return;
2161
- throw error;
2162
- }
2163
- const packages = Array.isArray(options.packages) ? options.packages : await options.packages();
2164
- if (!packages.length) return;
2165
- const outputNodeModules = resolve(serverDir, "node_modules");
2166
- const stagingRoot = await mkdtemp(resolve(serverDir, ".vitehub-runtime-packages-"));
2167
- const stagedNodeModules = resolve(stagingRoot, "node_modules");
2168
- const previousNodeModules = resolve(stagingRoot, "previous-node_modules");
2169
- let movedPreviousOutput = false;
2170
- let installedReplacement = false;
2171
- let cleanupStagingRoot = true;
2172
- try {
2173
- try {
2174
- await cp(outputNodeModules, stagedNodeModules, { recursive: true });
2175
- } catch (error) {
2176
- if (error.code !== "ENOENT") throw error;
2177
- }
2178
- await mkdir(stagedNodeModules, { recursive: true });
2179
- await copyNodeRuntimePackages({
2180
- outputNodeModules: stagedNodeModules,
2181
- packages,
2182
- rootDir: options.rootDir
2183
- });
2184
- options.signal?.throwIfAborted();
2185
- try {
2186
- await rename(outputNodeModules, previousNodeModules);
2187
- movedPreviousOutput = true;
2188
- cleanupStagingRoot = false;
2189
- } catch (error) {
2190
- if (error.code !== "ENOENT") throw error;
2191
- }
2192
- try {
2193
- options.signal?.throwIfAborted();
2194
- await rename(stagedNodeModules, outputNodeModules);
2195
- installedReplacement = true;
2196
- options.signal?.throwIfAborted();
2197
- cleanupStagingRoot = true;
2198
- } catch (error) {
2199
- if (installedReplacement) await rm(outputNodeModules, {
2200
- force: true,
2201
- recursive: true
2202
- });
2203
- if (movedPreviousOutput) await rename(previousNodeModules, outputNodeModules);
2204
- cleanupStagingRoot = true;
2205
- throw error;
2206
- }
2207
- } finally {
2208
- if (cleanupStagingRoot) await rm(stagingRoot, {
2209
- force: true,
2210
- recursive: true
2211
- });
2212
- }
2213
- }
2214
- async function copyNodeRuntimePackages(options) {
2215
- if (!options.packages.length) return;
2216
- const copied = /* @__PURE__ */ new Set();
2217
- const expanded = /* @__PURE__ */ new Set();
2218
- for (const runtimePackage of options.packages) {
2219
- const resolveFrom = runtimePackage.resolveFrom ?? join(options.rootDir, "package.json");
2220
- const resolver = createRequire(resolveFrom);
2221
- await copyPackageToNodeModules(runtimePackage.name, resolver, dirname(resolveFrom), options.outputNodeModules, copied, expanded, runtimePackage);
2222
- }
2223
- }
2224
- async function copyPackageToNodeModules(name, resolver, fromDir, outputNodeModules, copied, expanded, options = { name }) {
2225
- const packageJsonPath = await resolvePackageJson(name, resolver, fromDir);
2226
- if (!packageJsonPath) {
2227
- if (options.optional) return;
2228
- throw new Error(`Could not resolve package.json for ${name}.`);
2229
- }
2230
- const resolvedPackageJsonPath = await realpath(packageJsonPath);
2231
- const packageDir = dirname(resolvedPackageJsonPath);
2232
- const packageJson = parsePackageJson(JSON.parse(await readFile(resolvedPackageJsonPath, "utf8")), resolvedPackageJsonPath);
2233
- const packageKey = `${name}\0${resolvedPackageJsonPath}`;
2234
- if (!copied.has(packageKey)) {
2235
- copied.add(packageKey);
2236
- const targetDir = join(outputNodeModules, ...name.split("/"));
2237
- await rm(targetDir, {
2238
- force: true,
2239
- recursive: true
2240
- });
2241
- if (!await copyTracedPackageFiles(name, resolver, packageDir, resolvedPackageJsonPath, packageJson, targetDir)) await copyPackageDirectory(packageDir, targetDir);
2242
- }
2243
- const expansionKey = `${packageKey}\0${options.includePeerDependencies ? "peers" : "dependencies"}`;
2244
- if (expanded.has(expansionKey)) return;
2245
- expanded.add(expansionKey);
2246
- const packageRequire = createRequire(resolvedPackageJsonPath);
2247
- const dependencyNames = new Set(Object.keys(packageJson.dependencies || {}));
2248
- if (options.includePeerDependencies) {
2249
- for (const dependencyName of Object.keys(packageJson.peerDependencies || {})) if (!packageJson.peerDependenciesMeta?.[dependencyName]?.optional) dependencyNames.add(dependencyName);
2250
- }
2251
- for (const dependencyName of dependencyNames) await copyPackageToNodeModules(dependencyName, packageRequire, packageDir, outputNodeModules, copied, expanded, {
2252
- includePeerDependencies: options.includePeerDependencies,
2253
- name: dependencyName
2254
- });
2255
- }
2256
- async function copyTracedPackageFiles(name, resolver, packageDir, packageJsonPath, packageJson, targetDir) {
2257
- const entries = await resolvePackageTraceEntries(name, resolver, packageDir, packageJson);
2258
- if (!entries) return false;
2259
- const { fileList } = await (await loadNodeFileTrace())([...entries], {
2260
- base: packageDir,
2261
- conditions: ["node"],
2262
- exportsOnly: true,
2263
- processCwd: packageDir
2264
- });
2265
- fileList.add(relative(packageDir, packageJsonPath));
2266
- for (const file of fileList) {
2267
- const source = resolve(packageDir, file);
2268
- if (!isInsideDirectory(packageDir, source) || hasNodeModulesSegment(file)) continue;
2269
- if (!(await stat(source)).isFile()) continue;
2270
- const target = resolve(targetDir, file);
2271
- await mkdir(dirname(target), { recursive: true });
2272
- await copyFile(source, target);
2273
- }
2274
- return true;
2275
- }
2276
- async function copyPackageDirectory(packageDir, targetDir) {
2277
- await mkdir(dirname(targetDir), { recursive: true });
2278
- await cp(packageDir, targetDir, {
2279
- dereference: true,
2280
- filter: (source) => !hasNodeModulesSegment(relative(packageDir, source)),
2281
- recursive: true
2282
- });
2283
- }
2284
- async function loadNodeFileTrace() {
2285
- nodeFileTracePromise ??= import("@vercel/nft").then(({ nodeFileTrace }) => nodeFileTrace);
2286
- return nodeFileTracePromise;
2287
- }
2288
- async function resolvePackageTraceEntries(name, resolver, packageDir, packageJson) {
2289
- const entryCandidates = /* @__PURE__ */ new Set();
2290
- if (packageJson.exports) {
2291
- const exportedTargets = collectRuntimeExportTargets(packageJson.exports);
2292
- if (!exportedTargets) return void 0;
2293
- for (const target of exportedTargets) entryCandidates.add(resolve(packageDir, target));
2294
- } else {
2295
- try {
2296
- entryCandidates.add(resolver.resolve(name));
2297
- } catch (error) {
2298
- if (!isPackageResolutionMiss(error)) throw error;
2299
- }
2300
- if (packageJson.main) entryCandidates.add(resolve(packageDir, packageJson.main));
2301
- if (packageJson.module) entryCandidates.add(resolve(packageDir, packageJson.module));
2302
- entryCandidates.add(resolve(packageDir, "index.js"));
2303
- }
2304
- const entries = [];
2305
- for (const candidate of entryCandidates) try {
2306
- const candidateStat = await stat(candidate);
2307
- if (candidateStat.isFile()) entries.push(candidate);
2308
- else if (candidateStat.isDirectory()) return void 0;
2309
- } catch (error) {
2310
- if (error.code !== "ENOENT") throw error;
2311
- }
2312
- return entries.length ? entries : void 0;
2313
- }
2314
- function collectRuntimeExportTargets(exportsValue, condition) {
2315
- if (typeof exportsValue === "string") {
2316
- if (condition === "types") return /* @__PURE__ */ new Set();
2317
- if (exportsValue.includes("*")) return void 0;
2318
- return exportsValue.startsWith("./") ? new Set([exportsValue]) : /* @__PURE__ */ new Set();
2319
- }
2320
- if (Array.isArray(exportsValue)) {
2321
- const targets = /* @__PURE__ */ new Set();
2322
- for (const entry of exportsValue) {
2323
- const entryTargets = collectRuntimeExportTargets(entry, condition);
2324
- if (!entryTargets) return void 0;
2325
- for (const target of entryTargets) targets.add(target);
2326
- }
2327
- return targets;
2328
- }
2329
- if (typeof exportsValue !== "object" || exportsValue === null) return /* @__PURE__ */ new Set();
2330
- const targets = /* @__PURE__ */ new Set();
2331
- for (const [key, value] of Object.entries(exportsValue)) {
2332
- if (key === "types") continue;
2333
- if (!key.startsWith(".") && !runtimeExportConditions.has(key)) continue;
2334
- const entryTargets = collectRuntimeExportTargets(value, key);
2335
- if (!entryTargets) return void 0;
2336
- for (const target of entryTargets) targets.add(target);
2337
- }
2338
- return targets;
2339
- }
2340
- function hasNodeModulesSegment(path) {
2341
- return path.split(/[\\/]/).includes("node_modules");
2342
- }
2343
- function isInsideDirectory(parent, child) {
2344
- const childRelativePath = relative(parent, child);
2345
- return childRelativePath === "" || !childRelativePath.startsWith(`..${sep}`) && childRelativePath !== ".." && !isAbsolute(childRelativePath);
2346
- }
2347
- async function resolvePackageJson(name, resolver, fromDir) {
2348
- try {
2349
- return resolver.resolve(`${name}/package.json`);
2350
- } catch (error) {
2351
- if (!isPackageResolutionMiss(error)) throw error;
2352
- }
2353
- try {
2354
- let current = dirname(resolver.resolve(name));
2355
- while (current !== dirname(current)) {
2356
- const candidate = join(current, "package.json");
2357
- try {
2358
- await access(candidate);
2359
- if (parsePackageJson(JSON.parse(await readFile(candidate, "utf8")), candidate).name === name) return candidate;
2360
- } catch (error) {
2361
- if (error.code !== "ENOENT") throw error;
2362
- }
2363
- current = dirname(current);
2364
- }
2365
- } catch (error) {
2366
- if (!isPackageResolutionMiss(error)) throw error;
2367
- }
2368
- let current = fromDir;
2369
- while (current !== dirname(current)) {
2370
- const candidate = join(current, "node_modules", ...name.split("/"), "package.json");
2371
- try {
2372
- await access(candidate);
2373
- return candidate;
2374
- } catch (error) {
2375
- if (error.code !== "ENOENT") throw error;
2376
- }
2377
- current = dirname(current);
2378
- }
2379
- }
2380
- function isPackageResolutionMiss(error) {
2381
- const code = error?.code;
2382
- return code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED";
2383
- }
2384
- function parsePackageJson(value, path) {
2385
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`Expected ${path} to contain a JSON object.`);
2386
- return value;
2387
- }
2388
- function deploymentPresetFromNitro(value) {
2389
- const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
2390
- if (!normalized) return;
2391
- if (normalized.startsWith("cloudflare")) return "cloudflare";
2392
- if (normalized.startsWith("deno")) return "deno";
2393
- if (normalized.startsWith("netlify")) return "netlify";
2394
- if (normalized === "node" || normalized.startsWith("node-")) return "node";
2395
- if (normalized.startsWith("vercel")) return "vercel";
2396
- }
2397
- //#endregion
2398
- //#region ../internal/src/hosting.ts
2399
- function getHostingProvider(hosting) {
2400
- const preset = deploymentPresetFromNitro(hosting);
2401
- if (preset === "cloudflare" || preset === "netlify" || preset === "vercel") return preset;
2402
- }
2403
- //#endregion
2404
- //#region src/build/assets.ts
2405
- function shouldBundleWorkspaceAssets(assets, name) {
2406
- return assets === void 0 || assets === true || Array.isArray(assets) && assets.includes(name);
2407
- }
2408
- function assetModuleName(workspace, path, content) {
2409
- return `${createHash("sha256").update(`${workspace}\0${path}\0`).update(content).digest("hex").slice(0, 16)}.mjs`;
2410
- }
2411
- function serializeContent(content) {
2412
- if (typeof content === "string") return JSON.stringify(content);
2413
- return `new Uint8Array(${JSON.stringify([...content])})`;
2414
- }
2415
- function generatedViteHubImportAliases(rootDir) {
2416
- const aliases = {};
2417
- for (const [id, path] of Object.entries(createViteHubEnvImportAliases(rootDir))) if (existsSync(path)) aliases[id] = path;
2418
- return aliases;
2419
- }
2420
- const rawImportVirtualModulePrefix = "vitehub:workspace-raw:";
2421
- function staticTextImport(specifier) {
2422
- const markdownTemplate = parseMarkdownTemplateRequest(specifier);
2423
- if (markdownTemplate) return {
2424
- kind: "markdown-template",
2425
- path: markdownTemplate.path
2426
- };
2427
- const queryIndex = specifier.indexOf("?");
2428
- if (queryIndex === -1 || !/(?:^|&)raw(?:&|$)/.test(specifier.slice(queryIndex + 1))) return;
2429
- return {
2430
- kind: "raw",
2431
- path: specifier.slice(0, queryIndex)
2432
- };
2433
- }
2434
- function createRawImportTransformPlugin(importer) {
2435
- function rewriteRawSpecifier(path) {
2436
- if (!importer || path.node.source?.type !== "StringLiteral" || typeof path.node.source.value !== "string") return;
2437
- const textImport = staticTextImport(path.node.source.value);
2438
- if (!textImport) return;
2439
- const reference = Buffer.from(JSON.stringify([
2440
- importer,
2441
- textImport.path,
2442
- textImport.kind
2443
- ])).toString("base64url");
2444
- path.node.source.value = `${rawImportVirtualModulePrefix}${reference}`;
2445
- }
2446
- return () => ({ visitor: {
2447
- ExportAllDeclaration: rewriteRawSpecifier,
2448
- ExportNamedDeclaration: rewriteRawSpecifier,
2449
- ImportDeclaration: rewriteRawSpecifier
2450
- } });
2451
- }
2452
- function createWorkspaceDefinitionTransform() {
2453
- const transformer = createJiti(import.meta.url, { fsCache: false });
2454
- return (options) => ({ code: transformer.transform({
2455
- ...options,
2456
- babel: {
2457
- ...options.babel,
2458
- plugins: [...Array.isArray(options.babel?.plugins) ? options.babel.plugins : [], createRawImportTransformPlugin(options.filename)]
2459
- }
2460
- }) });
2461
- }
2462
- function resolveWorkspaceRawSpecifier(path, rootDir) {
2463
- if (path.startsWith("/@fs/")) return path.slice(5);
2464
- if (!path.startsWith("/")) return path;
2465
- const rootRelativePath = path.slice(1);
2466
- const publicPath = join(rootDir, "public", rootRelativePath);
2467
- return existsSync(publicPath) ? publicPath : join(rootDir, rootRelativePath);
2468
- }
2469
- function createWorkspaceDefinitionLoader(rootDir, alias = {}) {
2470
- let loader;
2471
- const virtualModules = new Proxy(Object.create(null), {
2472
- get(_target, id) {
2473
- if (typeof id !== "string" || !id.startsWith(rawImportVirtualModulePrefix)) return;
2474
- const reference = id.slice(22);
2475
- const [importer, path, kind = "raw"] = JSON.parse(Buffer.from(reference, "base64url").toString("utf8"));
2476
- const specifier = resolveWorkspaceRawSpecifier(path, rootDir);
2477
- const templatePath = fileURLToPath(loader.esmResolve(specifier, pathToFileURL(importer).href));
2478
- const template = readFileSync(templatePath, "utf8");
2479
- return {
2480
- __esModule: true,
2481
- default: kind === "markdown-template" ? (data = {}) => renderMarkdownTemplate(template, {
2482
- data,
2483
- sourceId: templatePath,
2484
- resolveImport(specifier, importer) {
2485
- const importedPath = resolve(dirname(importer), specifier);
2486
- try {
2487
- return {
2488
- id: importedPath,
2489
- template: readFileSync(importedPath, "utf8")
2490
- };
2491
- } catch (error) {
2492
- if (error.code === "ENOENT") return;
2493
- throw error;
2494
- }
2495
- }
2496
- }) : template
2497
- };
2498
- },
2499
- has(_target, id) {
2500
- return typeof id === "string" && id.startsWith(rawImportVirtualModulePrefix);
2501
- }
2502
- });
2503
- loader = createJiti(import.meta.url, {
2504
- alias: {
2505
- ...alias,
2506
- ...generatedViteHubImportAliases(rootDir)
2507
- },
2508
- fsCache: false,
2509
- moduleCache: false,
2510
- transform: createWorkspaceDefinitionTransform(),
2511
- virtualModules
2512
- });
2513
- return loader;
2514
- }
2515
- async function loadDiscoveredWorkspaceDefinition(loader, definition) {
2516
- const mod = await loader.import(definition.path);
2517
- if (!mod.default) throw new TypeError(`[vitehub] Workspace definition "${definition.name}" has no default export.`);
2518
- return mod.default;
2519
- }
2520
- function runtimeAssetsModulePath() {
2521
- return resolveModulePath("../runtime/assets", {
2522
- extensions: [".ts", ".mts"],
2523
- from: import.meta.url,
2524
- try: true
2525
- }) ?? resolveModulePath("@vite-hub/workspace/internal/runtime/assets", {
2526
- extensions: [".js", ".mjs"],
2527
- from: import.meta.url
2528
- });
2529
- }
2530
- async function collectWorkspaceStoreAssetBundle(name, store) {
2531
- const entries = (await store.glob("**/*")).filter((entry) => entry.type === "file");
2532
- const files = [];
2533
- for (const entry of entries) {
2534
- const path = normalizeSafeWorkspacePath(entry.path);
2535
- const file = await store.readFile(path);
2536
- if (file) files.push({
2537
- content: file.content,
2538
- mediaType: file.mediaType,
2539
- metadata: file.metadata,
2540
- path
2541
- });
2542
- }
2543
- files.sort((a, b) => a.path.localeCompare(b.path));
2544
- return {
2545
- files,
2546
- name
2547
- };
2548
- }
2549
- async function syncDiscoveredWorkspaceAssetBundles(definitions, rootDir, options) {
2550
- if (!options) return [];
2551
- const bundles = [];
2552
- const workspaceConfigLoader = createWorkspaceDefinitionLoader(rootDir);
2553
- for (const definition of definitions) {
2554
- if (!shouldBundleWorkspaceAssets(options.assets, definition.name)) continue;
2555
- const workspace = await loadDiscoveredWorkspaceDefinition(workspaceConfigLoader, definition);
2556
- const store = createMemoryWorkspaceStore();
2557
- await syncWorkspaceDefinition({
2558
- ...workspace,
2559
- name: definition.name,
2560
- rootDir: workspace.rootDir || rootDir,
2561
- sourceRootDir: workspace.sourceRootDir ?? definition.sourceRootDir,
2562
- store
2563
- }, store);
2564
- bundles.push(await collectWorkspaceStoreAssetBundle(definition.name, store));
2565
- }
2566
- return bundles;
2567
- }
2568
- async function writeWorkspaceAssetsRegistry(registryFile, bundles) {
2569
- const modulesDir = join(dirname(registryFile), "modules");
2570
- await rm(modulesDir, {
2571
- force: true,
2572
- recursive: true
2573
- });
2574
- await mkdir(modulesDir, { recursive: true });
2575
- const modulePaths = /* @__PURE__ */ new Map();
2576
- for (const bundle of bundles) {
2577
- const workspaceDir = join(modulesDir, encodeURIComponent(bundle.name));
2578
- await mkdir(workspaceDir, { recursive: true });
2579
- for (const file of bundle.files) {
2580
- const modulePath = join(workspaceDir, assetModuleName(bundle.name, file.path, file.content));
2581
- await writeFile(modulePath, `export default ${serializeContent(file.content)}\n`, "utf8");
2582
- modulePaths.set(`${bundle.name}\0${file.path}`, modulePath);
2583
- }
2584
- }
2585
- await mkdir(dirname(registryFile), { recursive: true });
2586
- const contents = createWorkspaceAssetsRegistryContents(registryFile, bundles, modulePaths);
2587
- await writeFile(registryFile, contents, "utf8");
2588
- return contents;
2589
- }
2590
- function createWorkspaceAssetsRegistryContents(registryFile, bundles, modulePaths = /* @__PURE__ */ new Map(), assetsModulePath = runtimeAssetsModulePath()) {
2591
- return [
2592
- `import { createWorkspaceAssets } from ${JSON.stringify(createImportPath(registryFile, assetsModulePath))}`,
2593
- "",
2594
- "const registry = {",
2595
- ...bundles.map((bundle) => {
2596
- const entries = bundle.files.map((file) => {
2597
- const modulePath = modulePaths.get(`${bundle.name}\0${file.path}`);
2598
- const importPath = modulePath ? createImportPath(registryFile, modulePath) : pathToFileURL(file.path).href;
2599
- return ` ${JSON.stringify(file.path)}: { load: async () => (await import(${JSON.stringify(importPath)})).default, mediaType: ${JSON.stringify(file.mediaType)}, metadata: ${JSON.stringify(file.metadata)} },`;
2600
- });
2601
- return [
2602
- ` ${JSON.stringify(bundle.name)}: createWorkspaceAssets({`,
2603
- ...entries,
2604
- " }),"
2605
- ].join("\n");
2606
- }),
2607
- "}",
2608
- "export default registry",
2609
- ""
2610
- ].join("\n");
2611
- }
2612
- //#endregion
2613
- //#region ../internal/src/definition-catalog.ts
2614
- const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
2615
- const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
2616
- const ignoredDirs = new Set([
2617
- "node_modules",
2618
- "dist",
2619
- ".output",
2620
- ".nuxt",
2621
- ".vercel",
2622
- ".git",
2623
- ".vitehub"
2624
- ]);
2625
- function createDirectoryDefinitionSource(source, scanDirs, subdir, options = {}) {
2626
- return {
2627
- ...options,
2628
- kind: "directory",
2629
- scanDirs,
2630
- source,
2631
- subdir
2632
- };
2633
- }
2634
- function createSuffixDefinitionSource(source, roots, pattern, normalizeName, options = {}) {
2635
- return {
2636
- ...options,
2637
- kind: "suffix",
2638
- normalizeName,
2639
- pattern,
2640
- roots,
2641
- source
2642
- };
2643
- }
2644
- function readDirEntries(root) {
2645
- try {
2646
- return readdirSync(root, { withFileTypes: true });
2647
- } catch (error) {
2648
- if (error.code === "ENOENT") return [];
2649
- throw error;
2650
- }
2651
- }
2652
- function isGitRepositoryDirectory(directory) {
2653
- return existsSync(resolve$1(directory, ".git"));
2654
- }
2655
- function listMatchingFiles(root, predicate, options = {}) {
2656
- const files = [];
2657
- for (const entry of readDirEntries(root)) {
2658
- const absolute = resolve$1(root, entry.name);
2659
- if (entry.isDirectory() && !entry.isSymbolicLink()) {
2660
- if (isGitRepositoryDirectory(absolute)) continue;
2661
- if (entry.name.startsWith(".")) continue;
2662
- if (ignoredDirs.has(entry.name)) continue;
2663
- files.push(...listMatchingFiles(absolute, predicate, options));
2664
- continue;
2665
- }
2666
- if (entry.name.startsWith(".") && !options.includeHidden) continue;
2667
- if (entry.isFile() && predicate(entry.name)) files.push(absolute);
2668
- }
2669
- return files.sort();
2670
- }
2671
- function listSourceFiles(root, options = {}) {
2672
- return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
2673
- }
2674
- function normalizePathDefinitionName(rootDir, file) {
2675
- return relative$1(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
2676
- }
2677
- function normalizeSuffixDefinitionName(rootDir, file, pattern, options = {}) {
2678
- const normalized = relative$1(rootDir, file).replace(pattern, "");
2679
- if (options.stripPrefix && normalized.startsWith(options.stripPrefix)) return normalized.slice(options.stripPrefix.length);
2680
- return normalized;
2681
- }
2682
- function sortDefinitions(definitions) {
2683
- return [...definitions.values()].sort((left, right) => left.name.localeCompare(right.name));
2684
- }
2685
- function registerDefinition(definitions, definition, sourceLabel) {
2686
- const existing = definitions.get(definition.name);
2687
- if (existing) throw new Error(`Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}`);
2688
- definitions.set(definition.name, definition);
2689
- }
2690
- function mergeDefinitions(feature, ...sources) {
2691
- const definitions = /* @__PURE__ */ new Map();
2692
- for (const source of sources) {
2693
- if (!source) continue;
2694
- for (const definition of source) {
2695
- const existing = definitions.get(definition.name);
2696
- if (existing && existing.handler !== definition.handler) throw new Error(`Duplicate ${feature} name "${definition.name}" from multiple discovery sources:\n - ${existing.handler} (${existing.source ?? "unknown"})\n - ${definition.handler} (${definition.source ?? "unknown"})`);
2697
- if (!existing) definitions.set(definition.name, definition);
2698
- }
2699
- }
2700
- return sortDefinitions(definitions);
2701
- }
2702
- function createDefinition(source, file, name) {
2703
- if (source.createDefinition) return source.createDefinition({
2704
- file,
2705
- name
2706
- });
2707
- return {
2708
- handler: file,
2709
- name,
2710
- source: source.source
2711
- };
2712
- }
2713
- function scanSuffixDefinitions(feature, source) {
2714
- const definitions = /* @__PURE__ */ new Map();
2715
- for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => source.pattern.test(name), { includeHidden: source.includeHidden })) {
2716
- const name = source.normalizeName(root, file);
2717
- if (!name) continue;
2718
- registerDefinition(definitions, createDefinition(source, file, name), feature);
2719
- }
2720
- return sortDefinitions(definitions);
2721
- }
2722
- function scanDirectoryDefinitions(feature, source) {
2723
- const definitions = /* @__PURE__ */ new Map();
2724
- for (const scanDir of source.scanDirs) {
2725
- const directory = resolve$1(scanDir, source.subdir);
2726
- for (const file of listSourceFiles(directory, { includeHidden: source.includeHidden })) {
2727
- const name = source.normalizeName ? source.normalizeName(directory, file) : normalizePathDefinitionName(directory, file);
2728
- if (!name) continue;
2729
- registerDefinition(definitions, createDefinition(source, file, name), feature);
2730
- }
2731
- }
2732
- return sortDefinitions(definitions);
2733
- }
2734
- function discoverDefinitions$1(feature, sources) {
2735
- return mergeDefinitions(feature, ...sources.map((source) => source.kind === "suffix" ? scanSuffixDefinitions(feature, source) : scanDirectoryDefinitions(feature, source)));
2736
- }
2737
- async function writeFileIfChanged(file, contents) {
2738
- if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
2739
- await mkdir(resolve$1(file, ".."), { recursive: true });
2740
- await writeFile(file, contents, "utf8");
2741
- }
2742
- //#endregion
2743
- //#region src/build/workspace-config.ts
2744
- const workspaceSuffixPattern = /\.workspace\.(?:c|m)?[jt]s$/i;
2745
- const workspaceConfigPattern = /^config\.(?:c|m)?[jt]s$/i;
2746
- const workspaceAgentPattern = /^agent\.(?:c|m)?[jt]s$/i;
2747
- //#endregion
2748
- //#region src/build/discovery.ts
2749
- const configFileNameSet = new Set([
2750
- "config.ts",
2751
- "config.mts",
2752
- "config.cts",
2753
- "config.js",
2754
- "config.mjs",
2755
- "config.cjs"
2756
- ]);
2757
- function stripComments(source) {
2758
- return source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1");
2759
- }
2760
- function isAgentConfig(file) {
2761
- return /\bdefineAgent\s*\(/.test(stripComments(readFileSync(file, "utf8")));
2762
- }
2763
- function isWorkspaceAgentDefinition(file) {
2764
- return /\bdefineAgent\s*\(\s*\{[\s\S]*?\bworkspace\s*:/.test(stripComments(readFileSync(file, "utf8")));
2765
- }
2766
- function collectDirectoriesWithConfig(root) {
2767
- const directories = /* @__PURE__ */ new Set();
2768
- const walk = (current) => {
2769
- let entries;
2770
- try {
2771
- entries = readdirSync(current, { withFileTypes: true });
2772
- } catch (error) {
2773
- if (error.code === "ENOENT") return;
2774
- throw error;
2775
- }
2776
- if (entries.some((entry) => entry.isFile() && configFileNameSet.has(entry.name))) directories.add(current.replace(/\\/g, "/"));
2777
- for (const entry of entries) {
2778
- if (!entry.isDirectory() || entry.isSymbolicLink() || entry.name.startsWith(".")) continue;
2779
- walk(resolve(current, entry.name));
2780
- }
2781
- };
2782
- walk(root);
2783
- return directories;
2784
- }
2785
- function resolveWorkspaceSourceRoot(file) {
2786
- const directory = dirname(file);
2787
- const workspaceDirectory = resolve(directory, "workspace");
2788
- try {
2789
- return statSync(workspaceDirectory).isDirectory() ? workspaceDirectory : directory;
2790
- } catch (error) {
2791
- if (error.code === "ENOENT") return directory;
2792
- throw error;
2793
- }
2794
- }
2795
- function createWorkspaceDefinition(source, file, name) {
2796
- return {
2797
- handler: file,
2798
- name,
2799
- path: file,
2800
- source,
2801
- sourceRootDir: resolveWorkspaceSourceRoot(file)
2802
- };
2803
- }
2804
- function serverWorkspaceSource(rootDir, serverDir = resolve(rootDir, "server")) {
2805
- const workspacesDir = resolve(serverDir, "workspaces");
2806
- const agentsDir = resolve(serverDir, "agents");
2807
- const directoryWorkspaceDirs = collectDirectoriesWithConfig(workspacesDir);
2808
- const normalizeDirectoryName = (workspacesRoot, file) => {
2809
- if (!workspaceConfigPattern.test(basename(file))) return;
2810
- const name = relative(workspacesRoot, dirname(file)).replace(/\\/g, "/");
2811
- return name && name !== "." ? name : void 0;
2812
- };
2813
- const isInsideDirectoryWorkspace = (file) => {
2814
- let current = dirname(file).replace(/\\/g, "/");
2815
- const stop = workspacesDir.replace(/\\/g, "/");
2816
- while (current.startsWith(stop) && current !== stop) {
2817
- if (directoryWorkspaceDirs.has(current)) return true;
2818
- current = dirname(current);
2819
- }
2820
- return false;
2821
- };
2822
- const normalizeFlatName = (workspacesRoot, file) => {
2823
- if (workspaceConfigPattern.test(basename(file))) return;
2824
- if (isInsideDirectoryWorkspace(file)) return;
2825
- return normalizePathDefinitionName(workspacesRoot, file);
2826
- };
2827
- return [
2828
- createDirectoryDefinitionSource("server-workspaces-directory-config", [serverDir], "workspaces", {
2829
- includeHidden: true,
2830
- normalizeName: normalizeDirectoryName,
2831
- createDefinition: ({ file, name }) => {
2832
- if (isAgentConfig(file)) throw new Error(`[vitehub] Workspace config "${file}" must use defineWorkspace(); defineAgent() belongs in server/agents/<name>/agent.ts.`);
2833
- return createWorkspaceDefinition("server-workspaces-directory-config", file, name);
2834
- }
2835
- }),
2836
- createDirectoryDefinitionSource("server-agent-workspaces", [serverDir], "agents", {
2837
- includeHidden: true,
2838
- normalizeName(_agentsRoot, file) {
2839
- if (!workspaceAgentPattern.test(basename(file))) return;
2840
- if (!isWorkspaceAgentDefinition(file)) return;
2841
- const name = relative(agentsDir, dirname(file)).replace(/\\/g, "/");
2842
- return name && name !== "." ? name : void 0;
2843
- },
2844
- createDefinition: ({ file, name }) => createWorkspaceDefinition("server-agent-workspaces", file, name)
2845
- }),
2846
- createDirectoryDefinitionSource("server-workspaces", [serverDir], "workspaces", {
2847
- normalizeName: normalizeFlatName,
2848
- createDefinition: ({ file, name }) => createWorkspaceDefinition("server-workspaces", file, name)
2849
- })
2850
- ];
2851
- }
2852
- function viteWorkspaceSource(rootDir) {
2853
- return [createSuffixDefinitionSource("vite-workspace-suffix", [rootDir], workspaceSuffixPattern, (root, file) => normalizeSuffixDefinitionName(root, file, workspaceSuffixPattern, { stripPrefix: "src/" }), { createDefinition: ({ file, name }) => createWorkspaceDefinition("vite-workspace-suffix", file, name) })];
2854
- }
2855
- function discoverViteWorkspaceDefinitions(rootDir, options = {}) {
2856
- const serverRoot = options.serverRootDir || rootDir;
2857
- const serverSources = options.serverDirs?.flatMap((serverDir) => serverWorkspaceSource(serverRoot, serverDir)) ?? serverWorkspaceSource(serverRoot);
2858
- return mergeDefinitions("workspace", discoverDefinitions$1("workspace", [...viteWorkspaceSource(rootDir)]), discoverDefinitions$1("workspace", serverSources));
2859
- }
2860
- function createWorkspaceRegistryEntry(definition, importExpression, override) {
2861
- const renderedStore = override ? JSON.stringify(override.store) : void 0;
2862
- const defaultValue = [
2863
- "...mod.default",
2864
- ...definition.sourceRootDir ? [`sourceRootDir: mod.default.sourceRootDir ?? ${JSON.stringify(definition.sourceRootDir)}`] : [],
2865
- ...renderedStore ? [`store: ${renderedStore}`, `__vitehubWorkspaceAgentOptions: mod.default.__vitehubWorkspaceAgentOptions && typeof mod.default.__vitehubWorkspaceAgentOptions.workspace === "object" ? { ...mod.default.__vitehubWorkspaceAgentOptions, workspace: { ...mod.default.__vitehubWorkspaceAgentOptions.workspace, store: ${renderedStore} } } : mod.default.__vitehubWorkspaceAgentOptions`] : []
2866
- ].join(", ");
2867
- return [
2868
- ` ${JSON.stringify(definition.name)}: async () => {`,
2869
- ` const mod = await ${importExpression}`,
2870
- definition.sourceRootDir || override ? ` return { ...mod, default: { ${defaultValue} } }` : " return mod",
2871
- " },"
2872
- ].join("\n");
2873
- }
2874
- function createWorkspaceRegistryContents(registryFile, definitions, overrides) {
2875
- const importExpression = (file) => {
2876
- const importPath = relative(resolve(registryFile, ".."), file);
2877
- return `import(${JSON.stringify(importPath.startsWith(".") ? importPath : `./${importPath}`)})`;
2878
- };
2879
- return [
2880
- "const registry = {",
2881
- ...definitions.map((definition) => createWorkspaceRegistryEntry(definition, importExpression(definition.handler), overrides?.get(definition.name))),
2882
- "}",
2883
- "export default registry",
2884
- ""
2885
- ].join("\n");
2886
- }
2887
- function createWorkspaceVirtualRegistryContents(definitions) {
2888
- return [
2889
- "const registry = {",
2890
- ...definitions.map((definition) => createWorkspaceRegistryEntry(definition, `import(${JSON.stringify(pathToFileURL(definition.path).href)})`)),
2891
- "}",
2892
- "export default registry",
2893
- ""
2894
- ].join("\n");
2895
- }
2896
- async function createWorkspaceManifest(definitions) {
2897
- return { workspaces: definitions.map((definition) => ({ name: definition.name })) };
2898
- }
2899
- //#endregion
2900
- //#region src/build/generated-types.ts
2901
- function createWorkspaceTypeAugmentation(definitions) {
2902
- const nameProperties = [...new Set(definitions.map((definition) => definition.name))].sort().map((name) => ` ${JSON.stringify(name)}: true`);
2903
- return [
2904
- "declare global {",
2905
- " interface ViteHubWorkspaceNameMap {",
2906
- ...nameProperties.length ? nameProperties : [" __vitehub_no_workspaces__?: never"],
2907
- " }",
2908
- "",
2909
- " interface ViteHubWorkspaceAssetMap {",
2910
- " __vitehub_no_workspace_assets__?: never",
2911
- " }",
2912
- "}",
2913
- "",
2914
- "export {}",
2915
- ""
2916
- ].join("\n");
2917
- }
2918
- //#endregion
2919
- //#region src/build/integration.ts
2920
- function workspaceAmbientTypesPath(root) {
2921
- return resolve(root, ".vitehub", "types", "workspace.d.ts");
2922
- }
2923
- async function createWorkspaceBuildState(definitions) {
2924
- return {
2925
- manifest: await createWorkspaceManifest(definitions),
2926
- registryContents: createWorkspaceVirtualRegistryContents(definitions)
2927
- };
2928
- }
2929
- async function refreshWorkspaceAmbientTypes(root, definitions) {
2930
- await writeFileIfChanged(workspaceAmbientTypesPath(root), createWorkspaceTypeAugmentation(definitions));
2931
- }
2932
- async function refreshWorkspaceBuildState(root, definitions) {
2933
- const state = await createWorkspaceBuildState(definitions);
2934
- await refreshWorkspaceAmbientTypes(root, definitions);
2935
- return state;
2936
- }
2937
- async function initializeWorkspaceAssetRegistry(assetsRegistryFile, _definitions = [], _rootDir = process.cwd()) {
2938
- await writeWorkspaceAssetsRegistry(assetsRegistryFile, []);
2939
- }
2940
- async function syncWorkspaceBuildAssets(definitions, rootDir, options, assetsRegistryFile) {
2941
- await writeWorkspaceAssetsRegistry(assetsRegistryFile, mergeWorkspaceAssetBundles(await syncDiscoveredWorkspaceAssetBundles(definitions, rootDir, options)));
2942
- }
2943
- function mergeWorkspaceAssetBundles(bundles) {
2944
- const merged = /* @__PURE__ */ new Map();
2945
- for (const bundle of bundles) {
2946
- const existing = merged.get(bundle.name);
2947
- if (!existing) {
2948
- merged.set(bundle.name, {
2949
- files: [...bundle.files],
2950
- name: bundle.name
2951
- });
2952
- continue;
2953
- }
2954
- const files = new Map(existing.files.map((file) => [file.path, file]));
2955
- for (const file of bundle.files) files.set(file.path, file);
2956
- existing.files = [...files.values()].sort((a, b) => a.path.localeCompare(b.path));
2957
- }
2958
- return [...merged.values()].sort((a, b) => a.name.localeCompare(b.name));
2959
- }
2960
- //#endregion
2961
- //#region src/cli.ts
2962
- const workspaceCommandFeedbackIntervalMs = 15e3;
2963
- const workspaceCommandStartedMessage = "[workspace] command started; first run may materialize sources.\n";
2964
- const workspaceCommandWaitingMessage = "[workspace] command still running; sources may still be materializing.\n";
2965
- function startWorkspaceCommandFeedback(context) {
2966
- context.stderr.write(workspaceCommandStartedMessage);
2967
- const timer = setInterval(() => context.stderr.write(workspaceCommandWaitingMessage), workspaceCommandFeedbackIntervalMs);
2968
- timer.unref?.();
2969
- return () => clearInterval(timer);
2970
- }
2971
- function formatDurationMs(durationMs) {
2972
- return durationMs < 1e3 ? `${durationMs}ms` : `${(durationMs / 1e3).toFixed(1)}s`;
2973
- }
2974
- function workspaceDevDataNumber(event, key) {
2975
- const value = event.data?.[key];
2976
- return typeof value === "number" && Number.isFinite(value) ? value : void 0;
2977
- }
2978
- function writeWorkspaceDevProgress(context, event) {
2979
- const duration = typeof event.durationMs === "number" ? ` (${formatDurationMs(event.durationMs)})` : "";
2980
- if (event.status === "started") {
2981
- context.stderr.write(`[workspace] ${event.label}...\n`);
2982
- return;
2983
- }
2984
- if (event.status === "updating") {
2985
- const files = workspaceDevDataNumber(event, "files");
2986
- const bytes = workspaceDevDataNumber(event, "bytes");
2987
- const detail = files === void 0 ? "" : `: ${files} file${files === 1 ? "" : "s"}${bytes === void 0 ? "" : `, ${bytes} bytes`}`;
2988
- context.stderr.write(`[workspace] ${event.label}${detail}\n`);
2989
- return;
2990
- }
2991
- if (event.status === "failed") {
2992
- context.stderr.write(`[workspace] ${event.label} failed${duration}${event.error ? `: ${event.error}` : ""}\n`);
2993
- return;
2994
- }
2995
- context.stderr.write(`[workspace] ${event.label} completed${duration}\n`);
2996
- }
2997
- function isWorkspaceDevStream(response) {
2998
- return response.headers.get("content-type")?.toLowerCase().includes("application/x-ndjson") === true;
2999
- }
3000
- function handleWorkspaceDevStreamLine(line, context) {
3001
- const parsed = JSON.parse(line);
3002
- if (parsed.type === "progress" && parsed.event) {
3003
- writeWorkspaceDevProgress(context, parsed.event);
3004
- return;
3005
- }
3006
- if (parsed.type === "error") {
3007
- context.stderr.write(`${parsed.error || "Workspace Dev command failed."}\n`);
3008
- return {
3009
- exitCode: 1,
3010
- stderr: "",
3011
- stdout: ""
3012
- };
3013
- }
3014
- if (parsed.type === "result") return parsed.result || {};
3015
- }
3016
- async function readWorkspaceDevStream(response, context) {
3017
- const reader = response.body?.getReader();
3018
- if (!reader) return {};
3019
- const decoder = new TextDecoder();
3020
- let buffer = "";
3021
- let result;
3022
- for (;;) {
3023
- const { done, value } = await reader.read();
3024
- buffer += decoder.decode(value, { stream: !done });
3025
- let newline = buffer.indexOf("\n");
3026
- while (newline >= 0) {
3027
- const line = buffer.slice(0, newline).trim();
3028
- buffer = buffer.slice(newline + 1);
3029
- if (line) result = handleWorkspaceDevStreamLine(line, context) ?? result;
3030
- newline = buffer.indexOf("\n");
3031
- }
3032
- if (done) break;
3033
- }
3034
- const line = buffer.trim();
3035
- if (line) result = handleWorkspaceDevStreamLine(line, context) ?? result;
3036
- return result || {};
3037
- }
3038
- function writeWorkspaceDevUsage(context) {
3039
- context.stdout.write([
3040
- "Usage: vitehub workspace dev <workspace> [exec <command...>] [--url <url>] [--timeout <ms>]",
3041
- "",
3042
- "Run Workspace commands through a running Vite Development Server.",
3043
- "Omit exec to open the interactive command loop.",
3044
- "",
3045
- "Options:",
3046
- " --url <url> Compatible Vite Development Server URL. Defaults to http://localhost:5173.",
3047
- " --timeout <ms> Workspace command timeout.",
3048
- " --path <path> Workspace path to materialize for command sessions. Repeatable.",
3049
- " -h, --help Show this help.",
3050
- ""
3051
- ].join("\n"));
3052
- }
3053
- function readOptionValue(args, index, flag) {
3054
- const value = args[index + 1];
3055
- if (!value || value.startsWith("-")) throw new Error(`Missing value for ${flag}.`);
3056
- return value;
3057
- }
3058
- function parseWorkspaceDevArgs(args, env) {
3059
- const parsed = {
3060
- help: false,
3061
- url: env.VITEHUB_DEV_SERVER_URL || "http://localhost:5173"
3062
- };
3063
- for (let index = 0; index < args.length; index += 1) {
3064
- const arg = args[index];
3065
- if (arg === "-h" || arg === "--help") {
3066
- parsed.help = true;
3067
- continue;
3068
- }
3069
- if (arg === "--url" || arg === "--server") {
3070
- parsed.url = readOptionValue(args, index, arg);
3071
- index += 1;
3072
- continue;
3073
- }
3074
- if (arg.startsWith("--url=")) {
3075
- parsed.url = arg.slice(6);
3076
- continue;
3077
- }
3078
- if (arg === "--timeout") {
3079
- const timeout = Number.parseInt(readOptionValue(args, index, arg), 10);
3080
- if (!Number.isFinite(timeout) || timeout <= 0) throw new Error("--timeout must be a positive number.");
3081
- parsed.timeout = timeout;
3082
- index += 1;
3083
- continue;
3084
- }
3085
- if (arg.startsWith("--timeout=")) {
3086
- const timeout = Number.parseInt(arg.slice(10), 10);
3087
- if (!Number.isFinite(timeout) || timeout <= 0) throw new Error("--timeout must be a positive number.");
3088
- parsed.timeout = timeout;
3089
- continue;
3090
- }
3091
- if (arg === "--path") {
3092
- parsed.paths ??= [];
3093
- parsed.paths.push(readOptionValue(args, index, arg));
3094
- index += 1;
3095
- continue;
3096
- }
3097
- if (arg.startsWith("--path=")) {
3098
- parsed.paths ??= [];
3099
- parsed.paths.push(arg.slice(7));
3100
- continue;
3101
- }
3102
- if (arg.startsWith("-") && !parsed.workspace) throw new Error(`Unknown option: ${arg}.`);
3103
- if (!parsed.workspace) {
3104
- parsed.workspace = arg;
3105
- continue;
3106
- }
3107
- if (arg === "exec") {
3108
- const [command, ...commandArgs] = args.slice(index + 1);
3109
- if (!command?.trim()) throw new Error("workspace dev exec requires a command.");
3110
- parsed.command = command;
3111
- if (commandArgs.length) parsed.args = commandArgs;
3112
- break;
3113
- }
3114
- throw new Error(`Unexpected argument: ${arg}. Use exec <command...> for one-shot commands.`);
3115
- }
3116
- return parsed;
3117
- }
3118
- function endpointUrl(baseUrl) {
3119
- return new URL(workspaceDevRoute, baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`).href;
3120
- }
3121
- async function readWorkspaceDiscovery(parsed, context, fetchImpl) {
3122
- if (!parsed.workspace) {
3123
- context.stderr.write("Missing Workspace Dev target.\n");
3124
- return;
3125
- }
3126
- let url;
3127
- try {
3128
- url = endpointUrl(parsed.url);
3129
- } catch {
3130
- context.stderr.write(`Invalid Vite Development Server URL: ${parsed.url}\n`);
3131
- return;
3132
- }
3133
- let response;
3134
- try {
3135
- response = await fetchImpl(url, { headers: {
3136
- accept: "application/json",
3137
- [workspaceDevHeader]: "1"
3138
- } });
3139
- } catch {
3140
- context.stderr.write(`No Compatible Vite Development Server found at ${parsed.url}.\n`);
3141
- return;
3142
- }
3143
- if (!response.ok) {
3144
- context.stderr.write(`No Compatible Vite Development Server found at ${parsed.url}.\n`);
3145
- return;
3146
- }
3147
- const discovery = await response.json().catch(() => ({}));
3148
- if (typeof discovery.root === "string" && discovery.root !== context.rootDir) {
3149
- context.stderr.write(`Compatible Vite Development Server root mismatch: ${discovery.root}\n`);
3150
- return;
3151
- }
3152
- if (!(discovery.workspaces || []).flatMap((workspace) => typeof workspace.name === "string" ? [workspace.name] : []).includes(parsed.workspace)) {
3153
- context.stderr.write(`Unknown Workspace Dev target: ${parsed.workspace}\n`);
3154
- return;
3155
- }
3156
- return {
3157
- tokenOptions: typeof discovery.workspaceDevTokenServerId === "string" ? { serverId: discovery.workspaceDevTokenServerId } : {},
3158
- url
3159
- };
3160
- }
3161
- async function sendWorkspaceCommand(target, parsed, context, fetchImpl) {
3162
- if (!parsed.command) {
3163
- context.stderr.write("Pass a command or run in an interactive terminal.\n");
3164
- return 1;
3165
- }
3166
- const token = await readWorkspaceDevToken(context.rootDir, target.tokenOptions);
3167
- if (!token) {
3168
- context.stderr.write("No private Workspace Dev token found. Start the Compatible Vite Development Server first.\n");
3169
- return 1;
3170
- }
3171
- const startedAt = Date.now();
3172
- const stopFeedback = startWorkspaceCommandFeedback(context);
3173
- try {
3174
- const response = await fetchImpl(target.url, {
3175
- body: JSON.stringify({ workspaceCommand: {
3176
- ...parsed.args ? { args: parsed.args } : {},
3177
- command: parsed.command,
3178
- ...parsed.paths?.length ? { paths: parsed.paths } : {},
3179
- ...parsed.timeout ? { timeout: parsed.timeout } : {},
3180
- workspace: parsed.workspace
3181
- } }),
3182
- headers: {
3183
- accept: "application/x-ndjson, application/json",
3184
- "content-type": "application/json",
3185
- [workspaceDevHeader]: "1",
3186
- [workspaceDevTokenHeader]: token
3187
- },
3188
- method: "POST"
3189
- });
3190
- if (!response.ok) {
3191
- context.stderr.write(`${await response.text()}\n`);
3192
- return 1;
3193
- }
3194
- if (isWorkspaceDevStream(response)) stopFeedback();
3195
- const result = isWorkspaceDevStream(response) ? await readWorkspaceDevStream(response, context) : await response.json().catch(() => ({}));
3196
- if (typeof result.stdout === "string") context.stdout.write(result.stdout);
3197
- if (typeof result.stderr === "string" && result.stderr) context.stderr.write(result.stderr);
3198
- context.stderr.write(`[workspace] command completed (${formatDurationMs(Date.now() - startedAt)})\n`);
3199
- return typeof result.exitCode === "number" ? result.exitCode : 0;
3200
- } finally {
3201
- stopFeedback();
3202
- }
3203
- }
3204
- async function runInteractiveWorkspaceDev(parsed, context, fetchImpl, target) {
3205
- const { createInterface } = await import("node:readline/promises");
3206
- const readline = createInterface({
3207
- input: process.stdin,
3208
- output: process.stdout
3209
- });
3210
- context.stdout.write(`Connected to ${parsed.workspace} at ${parsed.url}\n`);
3211
- try {
3212
- for (;;) {
3213
- const command = (await readline.question("> ")).trim();
3214
- if (!command) continue;
3215
- if (command === ".exit" || command === "exit") return 0;
3216
- const exitCode = await sendWorkspaceCommand(target, {
3217
- ...parsed,
3218
- command
3219
- }, context, fetchImpl);
3220
- if (exitCode !== 0) return exitCode;
3221
- }
3222
- } finally {
3223
- readline.close();
3224
- }
3225
- }
3226
- async function runWorkspaceDevCli(args, context, options = {}) {
3227
- let parsed;
3228
- try {
3229
- parsed = parseWorkspaceDevArgs(args, context.env);
3230
- } catch (error) {
3231
- context.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
3232
- writeWorkspaceDevUsage(context);
3233
- return 1;
3234
- }
3235
- if (parsed.help) {
3236
- writeWorkspaceDevUsage(context);
3237
- return 0;
3238
- }
3239
- const fetchImpl = options.fetch || globalThis.fetch;
3240
- const target = await readWorkspaceDiscovery(parsed, context, fetchImpl);
3241
- if (!target) return 1;
3242
- if (parsed.command) return await sendWorkspaceCommand(target, parsed, context, fetchImpl);
3243
- if (!process.stdin.isTTY) {
3244
- context.stderr.write("Pass a command or run in an interactive terminal.\n");
3245
- return 1;
3246
- }
3247
- return await runInteractiveWorkspaceDev(parsed, context, fetchImpl, target);
3248
- }
3249
- function createWorkspaceCliContributor() {
3250
- return { namespaces: [{
3251
- description: "Workspace development workflows.",
3252
- features: [{
3253
- description: "Run commands through a Workspace Session.",
3254
- name: "dev",
3255
- run: async (args, context) => await runWorkspaceDevCli(args, context),
3256
- usage: "vitehub workspace dev <workspace> [exec <command...>]"
3257
- }],
3258
- name: "workspace"
3259
- }] };
3260
- }
3261
- //#endregion
3262
- //#region ../internal/src/arrays.ts
3263
- function pushUnique(arr, item, key = (value) => value) {
3264
- const id = key(item);
3265
- if (arr.some((entry) => key(entry) === id)) return;
3266
- arr.push(item);
3267
- }
3268
- //#endregion
3269
- //#region src/integrations/cloudflare.ts
3270
- function configureCloudflareArtifacts(target, config) {
3271
- if (!config) return;
3272
- const store = config.store;
3273
- if (store.provider !== "cloudflare-artifacts") return;
3274
- target.cloudflare ||= {};
3275
- target.cloudflare.wrangler ||= {};
3276
- target.cloudflare.wrangler.artifacts ||= [];
3277
- const artifact = {
3278
- binding: store.binding || "WORKSPACE_ARTIFACTS",
3279
- namespace: store.namespace || "vitehub"
3280
- };
3281
- const existing = target.cloudflare.wrangler.artifacts.find((entry) => entry.binding === artifact.binding);
3282
- if (existing && existing.namespace !== artifact.namespace) throw new TypeError(`[vitehub] Cloudflare Artifacts binding "${artifact.binding}" cannot use both namespace "${existing.namespace}" and "${artifact.namespace}". Configure a unique binding for each namespace.`);
3283
- pushUnique(target.cloudflare.wrangler.artifacts, artifact, (entry) => entry.binding);
3284
- }
3285
- //#endregion
3286
- //#region src/hosts/vite/plugin.ts
3287
- const WORKSPACE_PACKAGE_NAME = "@vite-hub/workspace";
3288
- const WORKSPACES_ID = "#vitehub/workspaces";
3289
- const WORKSPACE_PREFIX = "#vitehub/workspaces/";
3290
- const WORKSPACE_ASSETS_REGISTRY_ID = "#vitehub-workspace-assets-registry";
3291
- const WORKSPACE_REGISTRY_ID = "#vitehub-workspace-registry";
3292
- const RESOLVED_WORKSPACES_ID = `\0${WORKSPACES_ID}`;
3293
- const RESOLVED_WORKSPACE_PREFIX = `\0${WORKSPACE_PREFIX}`;
3294
- const RESOLVED_WORKSPACE_REGISTRY_ID = `\0${WORKSPACE_REGISTRY_ID}`;
3295
- const generatedNitroWorkspacePlugin = ".vitehub/nitro/workspace/plugin.ts";
3296
- const generatedNitroWorkspaceRegistry = ".vitehub/nitro/workspace/registry.js";
3297
- const cloudflareArtifactsBindingsFileName = ".vitehub-workspace-artifacts-bindings.json";
3298
- const mergeNoExternal = createNoExternalMerger(WORKSPACE_PACKAGE_NAME);
3299
- const workspacesDirSegment = /[\\/](?:server[\\/])?workspaces(?:[\\/]|$)/;
3300
- const sourceModuleExtensions = [
3301
- ".ts",
3302
- ".mts",
3303
- ".cts",
3304
- ".js",
3305
- ".mjs",
3306
- ".cjs",
3307
- ".tsx",
3308
- ".jsx"
3309
- ];
3310
- async function readSourceModule(file) {
3311
- const candidates = extname(file) ? [file] : [...sourceModuleExtensions.map((extension) => `${file}${extension}`), ...sourceModuleExtensions.map((extension) => resolve(file, `index${extension}`))];
3312
- for (const candidate of candidates) try {
3313
- return {
3314
- file: candidate,
3315
- source: await readFile(candidate, "utf8")
3316
- };
3317
- } catch (error) {
3318
- if (error.code !== "ENOENT") throw error;
3319
- }
3320
- }
3321
- function createSourceModuleResolver(rootDir, aliases, resolveModule) {
3322
- if (!aliases) return resolveModule;
3323
- return async (id, importer) => {
3324
- const resolved = await resolveModule?.(id, importer);
3325
- if (resolved) return resolved;
3326
- for (const [find, replacement] of Object.entries(aliases)) {
3327
- if (id !== find && !id.startsWith(`${find}/`)) continue;
3328
- const aliased = `${replacement}${id.slice(find.length)}`;
3329
- return isAbsolute(aliased) ? aliased : resolve(rootDir, aliased);
3330
- }
3331
- };
3332
- }
3333
- function babelPropertyName(path) {
3334
- return path.node.key?.name ?? path.node.key?.value;
3335
- }
3336
- function babelPathOrBindingIsExported(path, name) {
3337
- if (!name) return babelPathIsExported(path);
3338
- for (let current = path; current; current = current.parentPath) {
3339
- if (current.node.type !== "ExportNamedDeclaration") continue;
3340
- const declaration = current.node.declaration;
3341
- if (declaration?.type === "VariableDeclaration") {
3342
- if (declaration.declarations?.some((item) => item.id?.type === "Identifier" && item.id.name === name)) return true;
3343
- } else if ((declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration") && declaration.id?.name === name) return true;
3344
- }
3345
- return path.scope.getBinding(name)?.referencePaths?.some((reference) => babelBindingIsExportedAs(reference, name, name)) ?? false;
3346
- }
3347
- function babelBindingIsExportedAs(path, localName, exportedName) {
3348
- return path.scope.getBinding(localName)?.referencePaths?.some((reference) => {
3349
- const parent = reference.parentPath?.node;
3350
- if (parent?.type !== "ExportSpecifier" || parent.local !== reference.node) return false;
3351
- return (parent.exported?.name ?? parent.exported?.value) === exportedName;
3352
- }) ?? false;
3353
- }
3354
- function babelPathReachesDefaultExport(path, seen = /* @__PURE__ */ new Set()) {
3355
- if (seen.has(path)) return false;
3356
- seen.add(path);
3357
- for (let current = path; current; current = current.parentPath) {
3358
- if (current.node.type === "ExportDefaultDeclaration") return true;
3359
- if (current.node.type === "AssignmentExpression" && babelMemberIsCommonJsDefaultExport(current.node.left)) return true;
3360
- if (current.node.type === "VariableDeclarator" && current.node.id?.type === "Identifier" && current.node.id.name) {
3361
- if (current.scope.getBinding(current.node.id.name)?.referencePaths?.some((reference) => babelPathReachesDefaultExport(reference, seen))) return true;
3362
- }
3363
- }
3364
- return false;
3365
- }
3366
- function babelMemberIsCommonJsDefaultExport(member) {
3367
- if (member?.type !== "MemberExpression") return false;
3368
- if (member.object?.type === "Identifier" && member.object.name === "module" && member.property?.type === "Identifier" && member.property.name === "exports") return true;
3369
- if ((member.property?.name ?? member.property?.value) !== "default") return false;
3370
- return member.object?.type === "Identifier" && member.object.name === "exports" || member.object?.type === "MemberExpression" && member.object.object?.type === "Identifier" && member.object.object.name === "module" && member.object.property?.type === "Identifier" && member.object.property.name === "exports";
3371
- }
3372
- function babelPathIsDirectDefaultExport(path) {
3373
- const parent = path.parentPath?.node;
3374
- if (parent?.type === "ExportDefaultDeclaration") return true;
3375
- return parent?.type === "AssignmentExpression" && parent.right === path.node && babelMemberIsCommonJsDefaultExport(parent.left);
3376
- }
3377
- function babelPropertyIsTopLevelDefaultExport(path) {
3378
- for (let current = path.parentPath; current; current = current.parentPath) {
3379
- if (current.node.type === "ObjectProperty") return false;
3380
- if (current.node.type === "ExportDefaultDeclaration") return true;
3381
- if (current.node.type === "AssignmentExpression" && babelMemberIsCommonJsDefaultExport(current.node.left)) return true;
3382
- if (current.node.type === "VariableDeclarator" && current.node.id?.type === "Identifier" && current.node.id.name) return current.scope.getBinding(current.node.id.name)?.referencePaths?.some((reference) => babelPathReachesDefaultExport(reference)) ?? false;
3383
- }
3384
- return false;
3385
- }
3386
- function babelPathReachesExportedStore(path, seen = /* @__PURE__ */ new Set()) {
3387
- if (seen.has(path)) return false;
3388
- seen.add(path);
3389
- for (let current = path; current; current = current.parentPath) {
3390
- if (current.node.type === "ObjectProperty" && ![
3391
- "binding",
3392
- "namespace",
3393
- "provider",
3394
- "store"
3395
- ].includes(String(babelPropertyName(current)))) return false;
3396
- if (current.node.type === "ObjectProperty" && babelPropertyName(current) === "store" && babelPropertyIsTopLevelDefaultExport(current)) return true;
3397
- if (current.node.type === "VariableDeclarator" && current.node.id?.type === "Identifier" && current.node.id.name) {
3398
- if (current.scope.getBinding(current.node.id.name)?.referencePaths?.some((reference) => babelPathReachesExportedStore(reference, seen))) return true;
3399
- }
3400
- if (current.node.type === "FunctionDeclaration" && current.node.id?.name) {
3401
- let returned = false;
3402
- for (let descendant = path; descendant && descendant !== current; descendant = descendant.parentPath) {
3403
- if (descendant.node.type === "ReturnStatement") returned = true;
3404
- if (descendant !== path && (descendant.node.type === "FunctionDeclaration" || descendant.node.type === "FunctionExpression" || descendant.node.type === "ArrowFunctionExpression")) break;
3405
- }
3406
- if (!returned) return false;
3407
- if (current.scope.getBinding(current.node.id.name)?.referencePaths?.some((reference) => babelPathReachesExportedStore(reference, seen))) return true;
3408
- }
3409
- }
3410
- return false;
3411
- }
3412
- function babelNamespaceMemberNames(path, reachesRequestedExport, seen = /* @__PURE__ */ new Set()) {
3413
- if (seen.has(path)) return [];
3414
- seen.add(path);
3415
- const parent = path.parentPath;
3416
- if (parent?.node.type === "MemberExpression" && parent.node.object === path.node) {
3417
- if (!reachesRequestedExport(parent)) return [];
3418
- const name = parent.node.property?.name ?? parent.node.property?.value;
3419
- return typeof name === "string" ? [name] : [];
3420
- }
3421
- if (parent?.node.type === "VariableDeclarator" && parent.node.init === path.node && parent.node.id?.type === "ObjectPattern") return parent.node.id.properties?.flatMap((property) => {
3422
- const objectProperty = property;
3423
- if (objectProperty.type !== "ObjectProperty" || objectProperty.value?.type !== "Identifier" || !objectProperty.value.name) return [];
3424
- if (!(parent.scope.getBinding(objectProperty.value.name)?.referencePaths ?? []).some(reachesRequestedExport)) return [];
3425
- const name = objectProperty.key?.name ?? objectProperty.key?.value;
3426
- return typeof name === "string" ? [name] : [];
3427
- }) ?? [];
3428
- if (parent?.node.type === "VariableDeclarator" && parent.node.init === path.node && parent.node.id?.type === "Identifier" && parent.node.id.name) return parent.scope.getBinding(parent.node.id.name)?.referencePaths?.filter(reachesRequestedExport).flatMap((reference) => babelNamespaceMemberNames(reference, reachesRequestedExport, seen)) ?? [];
3429
- return [];
3430
- }
3431
- function babelPathBelongsToExportedStore(path) {
3432
- for (let current = path.parentPath; current; current = current.parentPath) {
3433
- if (current.node.type === "AssignmentExpression" && current.node.left?.type === "MemberExpression" && current.node.left.object?.type === "Identifier" && current.node.left.object.name === "module" && current.node.left.property?.type === "Identifier" && current.node.left.property.name === "exports") {
3434
- if (path.parentPath?.parentPath === current) return true;
3435
- for (let nested = path.parentPath; nested && nested !== current; nested = nested.parentPath) if (nested.node.type === "ObjectProperty" && babelPropertyName(nested) === "default" && nested.parentPath?.node.type === "ObjectExpression" && nested.parentPath.parentPath === current) {
3436
- for (let wrapped = path.parentPath; wrapped && wrapped !== nested; wrapped = wrapped.parentPath) if (wrapped.node.type === "ObjectProperty" && babelPropertyName(wrapped) === "store" && wrapped.parentPath?.node === nested.node.value) return true;
3437
- return false;
3438
- }
3439
- return false;
3440
- }
3441
- if (current.node.type === "ObjectProperty" && babelPropertyName(current) === "store" && babelPropertyIsTopLevelDefaultExport(current)) return true;
3442
- if (current.node.type === "VariableDeclarator" && current.node.id?.type === "Identifier" && (current.node.id.name === "store" && babelPathOrBindingIsExported(current, current.node.id.name) || current.scope.getBinding(current.node.id.name ?? "")?.referencePaths?.some((reference) => babelPathReachesExportedStore(reference)))) return true;
3443
- if (current.node.type === "ExportDefaultDeclaration") return path.parentPath?.parentPath === current;
3444
- if (current.node.type === "FunctionDeclaration") {
3445
- const name = current.node.id?.name;
3446
- if (current.parentPath?.node.type === "ExportDefaultDeclaration") return true;
3447
- return name ? current.scope.getBinding(name)?.referencePaths?.some((reference) => babelPathReachesExportedStore(reference)) ?? false : false;
3448
- }
3449
- if (current.node.type === "FunctionExpression" || current.node.type === "ArrowFunctionExpression") {
3450
- const declarator = current.parentPath;
3451
- if (declarator?.node.type === "ExportDefaultDeclaration") return true;
3452
- if (declarator?.node.type !== "VariableDeclarator" || declarator.node.init !== current.node || declarator.node.id?.type !== "Identifier") return false;
3453
- const name = declarator.node.id.name;
3454
- if (!name) return false;
3455
- return babelPathOrBindingIsExported(declarator, name) || declarator.scope.getBinding(name)?.referencePaths?.some((reference) => babelPathReachesExportedStore(reference)) || false;
3456
- }
3457
- }
3458
- return false;
3459
- }
3460
- function babelPathIsExported(path) {
3461
- for (let current = path.parentPath; current; current = current.parentPath) if (current.node.type === "ExportNamedDeclaration" || current.node.type === "ExportDefaultDeclaration") return true;
3462
- return false;
3463
- }
3464
- function babelPathReachesNamedExport(path, exportedName, seen = /* @__PURE__ */ new Set(), mayCrossValueProperty = true) {
3465
- if (seen.has(path)) return false;
3466
- seen.add(path);
3467
- for (let current = path; current; current = current.parentPath) {
3468
- if (current.node.type === "ObjectProperty" && babelPropertyName(current) === exportedName && current.parentPath && babelPathIsDirectDefaultExport(current.parentPath)) return true;
3469
- if (current.node.type === "ObjectProperty") {
3470
- if (!mayCrossValueProperty) return false;
3471
- mayCrossValueProperty = false;
3472
- }
3473
- if (current.node.type === "AssignmentExpression" && current.node.left?.type === "MemberExpression" && (current.node.left.object?.type === "Identifier" && current.node.left.object.name === "exports" || current.node.left.object?.type === "MemberExpression" && current.node.left.object.object?.type === "Identifier" && current.node.left.object.object.name === "module" && current.node.left.object.property?.type === "Identifier" && current.node.left.object.property.name === "exports") && (current.node.left.property?.name ?? current.node.left.property?.value) === exportedName) return true;
3474
- if (current.node.type === "VariableDeclarator" && current.node.id?.type === "Identifier" && current.node.id.name) {
3475
- const name = current.node.id.name;
3476
- if (name === exportedName && babelPathOrBindingIsExported(current, exportedName) || babelBindingIsExportedAs(current, name, exportedName)) return true;
3477
- if (current.scope.getBinding(name)?.referencePaths?.some((reference) => babelPathReachesNamedExport(reference, exportedName, seen, false))) return true;
3478
- }
3479
- if (current.node.type === "FunctionDeclaration" && current.node.id?.name === exportedName && babelPathOrBindingIsExported(current, exportedName)) return true;
3480
- }
3481
- return false;
3482
- }
3483
- function babelStringValue(node, path, seen = /* @__PURE__ */ new Set()) {
3484
- if (node?.type === "StringLiteral") return node.value;
3485
- if (node?.type === "TSAsExpression" || node?.type === "TSSatisfiesExpression" || node?.type === "TSTypeAssertion") return babelStringValue(node.expression, path, seen);
3486
- if (node?.type === "Identifier" && node.name) {
3487
- const bindingPath = path.scope.getBinding(node.name)?.path;
3488
- if (!bindingPath || seen.has(bindingPath)) return;
3489
- return babelStringValue(bindingPath.node.init, bindingPath, new Set(seen).add(bindingPath));
3490
- }
3491
- if (node?.type === "CallExpression" && node.arguments?.length === 1 && babelStringValue(node.arguments[0], path, seen) === "-" && node.callee?.type === "MemberExpression" && node.callee.object?.type === "ArrayExpression" && node.callee.property?.type === "Identifier" && node.callee.property.name === "join") {
3492
- const values = node.callee.object.elements?.map((element) => babelStringValue(element ?? void 0, path, seen));
3493
- if (values?.every((value) => typeof value === "string")) return values.join("-");
3494
- }
3495
- }
3496
- async function sourceModuleDeclaresCloudflareArtifacts(file, loader, exportedName = "default") {
3497
- const loaded = await readSourceModule(file);
3498
- if (!loaded) return false;
3499
- let declaresCloudflareArtifacts = false;
3500
- loader.transform({
3501
- filename: loaded.file,
3502
- jsx: extname(loaded.file).endsWith("x"),
3503
- source: loaded.source,
3504
- ts: /\.[cm]?tsx?$/.test(loaded.file),
3505
- babel: { plugins: [() => ({ visitor: {
3506
- ObjectProperty(path) {
3507
- const value = path.node.value;
3508
- const belongsToRequestedExport = exportedName === "default" ? babelPathBelongsToExportedStore(path) : babelPathReachesNamedExport(path, exportedName);
3509
- if (babelPropertyName(path) === "provider" && belongsToRequestedExport) {
3510
- const provider = babelStringValue(value, path);
3511
- if (provider === "cloudflare-artifacts" || provider === void 0) declaresCloudflareArtifacts = true;
3512
- }
3513
- },
3514
- VariableDeclarator(path) {
3515
- if (exportedName === "provider" && path.node.id?.type === "Identifier" && path.node.id.name === "provider" && babelPathIsExported(path) && babelStringValue(path.node.init, path) === "cloudflare-artifacts") declaresCloudflareArtifacts = true;
3516
- },
3517
- ExportNamedDeclaration(path) {
3518
- if (exportedName !== "provider") return;
3519
- for (const specifier of path.node.specifiers ?? []) {
3520
- if (specifier.exported?.name !== "provider" || specifier.local?.type !== "Identifier" || !specifier.local.name) continue;
3521
- if (babelStringValue(specifier.local, path) === "cloudflare-artifacts") declaresCloudflareArtifacts = true;
3522
- }
3523
- }
3524
- } })] }
3525
- });
3526
- return declaresCloudflareArtifacts;
3527
- }
3528
- async function sourceModuleMayUseCloudflareArtifacts(file, loader, resolveModule, visited = /* @__PURE__ */ new Set(), exportedName = "default") {
3529
- const loaded = await readSourceModule(file);
3530
- if (!loaded) return false;
3531
- const visitKey = `${loaded.file}\0${exportedName}`;
3532
- if (visited.has(visitKey)) return false;
3533
- visited.add(visitKey);
3534
- if (await sourceModuleDeclaresCloudflareArtifacts(loaded.file, loader, exportedName)) return true;
3535
- for (const { importedName, selectedName, specifier } of sourceImportsFeedingWorkspaceStore(loaded, loader, exportedName)) {
3536
- if (!importedName) return true;
3537
- const resolvedFile = (specifier.startsWith(".") ? resolve(dirname(loaded.file), specifier) : await resolveModule?.(specifier, loaded.file))?.split(/[?#]/, 1)[0];
3538
- if (resolvedFile && extname(resolvedFile) && !sourceModuleExtensions.includes(extname(resolvedFile))) continue;
3539
- const requestedName = selectedName ?? importedName;
3540
- if (resolvedFile && isAbsolute(resolvedFile) && await sourceModuleMayUseCloudflareArtifacts(resolvedFile, loader, resolveModule, visited, requestedName)) return true;
3541
- }
3542
- return false;
3543
- }
3544
- function sourceImportsFeedingWorkspaceStore(loaded, loader, exportedName) {
3545
- const imports = [];
3546
- loader.transform({
3547
- filename: loaded.file,
3548
- jsx: extname(loaded.file).endsWith("x"),
3549
- source: loaded.source,
3550
- ts: /\.[cm]?tsx?$/.test(loaded.file),
3551
- babel: { plugins: [() => ({ visitor: {
3552
- ExportNamedDeclaration(path) {
3553
- const specifier = path.node.source?.value;
3554
- if (typeof specifier !== "string") return;
3555
- for (const exported of path.node.specifiers ?? []) {
3556
- if (String(exported.exported?.name ?? exported.exported?.value) !== exportedName) continue;
3557
- imports.push({
3558
- importedName: String(exported.local?.name ?? exported.local?.value),
3559
- specifier
3560
- });
3561
- }
3562
- },
3563
- ExportAllDeclaration(path) {
3564
- const specifier = path.node.source?.value;
3565
- if (typeof specifier === "string" && exportedName !== "default") imports.push({
3566
- importedName: exportedName,
3567
- specifier
3568
- });
3569
- },
3570
- ImportDeclaration(path) {
3571
- const specifier = path.node.source?.value;
3572
- if (typeof specifier !== "string") return;
3573
- for (const imported of path.node.specifiers ?? []) {
3574
- if (imported.local?.type !== "Identifier" || !imported.local.name) continue;
3575
- const binding = path.scope.getBinding(imported.local.name);
3576
- const referenceReachesRequestedExport = (reference) => exportedName === "default" ? babelPathReachesExportedStore(reference) || babelPathIsDirectDefaultExport(reference) : (() => {
3577
- for (let current = reference; current; current = current.parentPath) {
3578
- if (current.node.type === "ExportSpecifier" && current.node.local === reference.node && (current.node.exported?.name ?? current.node.exported?.value) === exportedName) return true;
3579
- if (current.node.type === "VariableDeclarator" && current.node.id?.name === exportedName && babelPathOrBindingIsExported(current, exportedName)) return true;
3580
- }
3581
- return false;
3582
- })();
3583
- if (imported.type === "ImportNamespaceSpecifier" || imported.type === "ImportDefaultSpecifier") {
3584
- for (const reference of binding?.referencePaths ?? []) {
3585
- const memberNames = babelNamespaceMemberNames(reference, referenceReachesRequestedExport);
3586
- for (const importedName of memberNames) imports.push(imported.type === "ImportDefaultSpecifier" ? {
3587
- importedName: "default",
3588
- localName: imported.local.name,
3589
- selectedName: importedName,
3590
- specifier
3591
- } : {
3592
- importedName,
3593
- localName: imported.local.name,
3594
- specifier
3595
- });
3596
- if (imported.type === "ImportDefaultSpecifier" && !memberNames.length && referenceReachesRequestedExport(reference)) imports.push({
3597
- importedName: "default",
3598
- localName: imported.local.name,
3599
- specifier
3600
- });
3601
- }
3602
- continue;
3603
- }
3604
- if (!(binding?.referencePaths?.filter(referenceReachesRequestedExport) ?? []).length) continue;
3605
- imports.push({
3606
- importedName: imported.type === "ImportDefaultSpecifier" ? "default" : String(imported.imported?.name ?? imported.imported?.value),
3607
- localName: imported.local.name,
3608
- specifier
3609
- });
3610
- }
3611
- },
3612
- AssignmentExpression(path) {
3613
- const right = path.node.right;
3614
- const required = right?.type === "MemberExpression" ? right.object : right;
3615
- if (required?.type !== "CallExpression" || required.callee?.type !== "Identifier" || required.callee.name !== "require" || required.arguments?.length !== 1) return;
3616
- const left = path.node.left;
3617
- const commonJsExportsObject = left?.type === "MemberExpression" && (left.object?.type === "Identifier" && left.object.name === "exports" || left.object?.type === "MemberExpression" && left.object.object?.type === "Identifier" && left.object.object.name === "module" && left.object.property?.type === "Identifier" && left.object.property.name === "exports");
3618
- if ((babelMemberIsCommonJsDefaultExport(left) ? "default" : commonJsExportsObject ? left.property?.name ?? left.property?.value : void 0) !== exportedName) return;
3619
- const specifier = required.arguments[0]?.value;
3620
- if (typeof specifier !== "string") return;
3621
- const importedName = right?.type === "MemberExpression" ? right.property?.name ?? right.property?.value : "default";
3622
- imports.push({
3623
- importedName: typeof importedName === "string" ? importedName : void 0,
3624
- specifier
3625
- });
3626
- },
3627
- VariableDeclarator(path) {
3628
- const selectedDynamicImportName = path.node.init?.type === "MemberExpression" ? path.node.init.property?.name ?? path.node.init.property?.value : void 0;
3629
- const dynamicImportValue = path.node.init?.type === "MemberExpression" ? path.node.init.object : path.node.init;
3630
- const awaitExpression = dynamicImportValue;
3631
- const awaited = dynamicImportValue?.type === "AwaitExpression" ? awaitExpression.argument : dynamicImportValue;
3632
- if (awaited?.type === "CallExpression" && awaited.callee?.type === "Import" && awaited.arguments?.length === 1) {
3633
- const specifier = awaited.arguments[0]?.value;
3634
- if (typeof specifier !== "string") return;
3635
- if (path.node.id?.type === "ObjectPattern") {
3636
- const properties = path.node.id.properties;
3637
- for (const property of properties ?? []) {
3638
- if (property.type !== "ObjectProperty") continue;
3639
- const propertyValue = property.value;
3640
- const localName = (propertyValue?.type === "AssignmentPattern" ? propertyValue.left : propertyValue)?.name;
3641
- if (!localName) continue;
3642
- if (!path.scope.getBinding(localName)?.referencePaths?.some((reference) => exportedName === "default" ? babelPathReachesExportedStore(reference) : babelPathOrBindingIsExported(reference, exportedName))) continue;
3643
- const importedName = property.key?.name ?? property.key?.value;
3644
- imports.push({
3645
- importedName: typeof importedName === "string" ? importedName : void 0,
3646
- localName,
3647
- specifier
3648
- });
3649
- }
3650
- } else if (path.node.id?.type === "Identifier") {
3651
- const localName = path.node.id.name;
3652
- if (!localName) return;
3653
- const binding = path.scope.getBinding(localName);
3654
- const reachesRequestedExport = (reference) => exportedName === "default" ? babelPathReachesExportedStore(reference) : babelPathOrBindingIsExported(reference, exportedName);
3655
- if (typeof selectedDynamicImportName === "string" && binding?.referencePaths?.some(reachesRequestedExport)) imports.push({
3656
- importedName: selectedDynamicImportName,
3657
- localName,
3658
- specifier
3659
- });
3660
- for (const reference of binding?.referencePaths ?? []) {
3661
- const memberNames = babelNamespaceMemberNames(reference, reachesRequestedExport);
3662
- for (const importedName of memberNames) imports.push({
3663
- importedName,
3664
- localName,
3665
- specifier
3666
- });
3667
- }
3668
- }
3669
- return;
3670
- }
3671
- const required = path.node.init?.type === "MemberExpression" ? path.node.init.object : path.node.init;
3672
- if (path.node.id?.type === "ObjectPattern" && required?.type === "CallExpression" && required.callee?.type === "Identifier" && required.callee.name === "require" && required.arguments?.length === 1) {
3673
- const specifier = required.arguments[0]?.value;
3674
- if (typeof specifier !== "string") return;
3675
- const properties = path.node.id.properties;
3676
- for (const property of properties ?? []) {
3677
- const value = property.value;
3678
- const localName = (value?.type === "AssignmentPattern" ? value.left : value)?.name;
3679
- if (property.type !== "ObjectProperty" || !localName) continue;
3680
- if (!path.scope.getBinding(localName)?.referencePaths?.some((reference) => exportedName === "default" ? babelPathReachesExportedStore(reference) : babelPathOrBindingIsExported(reference, exportedName))) continue;
3681
- const key = property.key;
3682
- const importedName = property.computed ? babelStringValue(key, path) : property.key?.name ?? property.key?.value;
3683
- imports.push({
3684
- importedName: typeof importedName === "string" ? importedName : void 0,
3685
- localName,
3686
- specifier
3687
- });
3688
- }
3689
- return;
3690
- }
3691
- if (path.node.id?.type !== "Identifier" || !path.node.id.name) return;
3692
- if (required?.type !== "CallExpression" || required.callee?.type !== "Identifier" || required.callee.name !== "require" || required.arguments?.length !== 1) return;
3693
- const specifier = required.arguments[0]?.value;
3694
- if (typeof specifier !== "string") return;
3695
- const binding = path.scope.getBinding(path.node.id.name);
3696
- const reachesRequestedExport = (reference) => exportedName === "default" ? babelPathReachesExportedStore(reference) || babelPathIsDirectDefaultExport(reference) : babelPathOrBindingIsExported(reference, exportedName);
3697
- const selectedNames = binding?.referencePaths?.flatMap((reference) => babelNamespaceMemberNames(reference, reachesRequestedExport)) ?? [];
3698
- const direct = binding?.referencePaths?.some(reachesRequestedExport);
3699
- if (!direct && !selectedNames.length) return;
3700
- const selectedName = path.node.init?.type === "MemberExpression" ? path.node.init.property?.name ?? path.node.init.property?.value : "default";
3701
- if (typeof selectedName === "string" && direct) imports.push({
3702
- importedName: selectedName,
3703
- specifier
3704
- });
3705
- for (const name of selectedNames) imports.push({
3706
- importedName: name,
3707
- localName: path.node.id.name,
3708
- specifier
3709
- });
3710
- }
3711
- } })] }
3712
- });
3713
- return imports;
3714
- }
3715
- function importedWorkspaceValueKey(localName, selectedName) {
3716
- return selectedName === void 0 ? localName : `${localName}\0${selectedName}`;
3717
- }
3718
- function babelResolveIdentifierAlias(path, name, seen = /* @__PURE__ */ new Set()) {
3719
- const bindingPath = path.scope.getBinding(name)?.path;
3720
- if (!bindingPath || seen.has(bindingPath)) return name;
3721
- seen.add(bindingPath);
3722
- if (bindingPath.node.type !== "VariableDeclarator" || bindingPath.node.init?.type !== "Identifier" || !bindingPath.node.init.name) return name;
3723
- return babelResolveIdentifierAlias(bindingPath, bindingPath.node.init.name, seen);
3724
- }
3725
- function babelEnvironmentKey(node, path, seen = /* @__PURE__ */ new Set()) {
3726
- if (node?.type === "Identifier" && node.name) {
3727
- const bindingPath = path.scope.getBinding(node.name)?.path;
3728
- if (!bindingPath || seen.has(bindingPath)) return;
3729
- return babelEnvironmentKey(bindingPath.node.init, bindingPath, new Set(seen).add(bindingPath));
3730
- }
3731
- if (node?.type !== "MemberExpression" || node.object?.type !== "MemberExpression" || node.object.object?.type !== "Identifier" || node.object.object.name !== "process" || node.object.property?.type !== "Identifier" || node.object.property.name !== "env") return;
3732
- const key = node.property?.name ?? node.property?.value;
3733
- return typeof key === "string" ? key : void 0;
3734
- }
3735
- function babelEnvironmentValue(node, path, env) {
3736
- const key = babelEnvironmentKey(node, path);
3737
- return key === void 0 ? void 0 : env[key];
3738
- }
3739
- function sourceHasUnresolvedWorkspaceRoot(loaded, loader) {
3740
- let unresolved = false;
3741
- loader.transform({
3742
- filename: loaded.file,
3743
- jsx: extname(loaded.file).endsWith("x"),
3744
- source: loaded.source,
3745
- ts: /\.[cm]?tsx?$/.test(loaded.file),
3746
- babel: { plugins: [() => ({ visitor: { ObjectProperty(path) {
3747
- const valueNode = path.node.value;
3748
- if (babelPropertyName(path) === "root" && babelPropertyIsTopLevelDefaultExport(path) && babelStringValue(valueNode, path) === void 0) unresolved = true;
3749
- } } })] }
3750
- });
3751
- return unresolved;
3752
- }
3753
- function sourceInlineWorkspaceStoreOperations(loaded, loader, env) {
3754
- const operations = [];
3755
- loader.transform({
3756
- filename: loaded.file,
3757
- jsx: extname(loaded.file).endsWith("x"),
3758
- source: loaded.source,
3759
- ts: /\.[cm]?tsx?$/.test(loaded.file),
3760
- babel: { plugins: [() => ({ visitor: {
3761
- SpreadElement(path) {
3762
- const argument = path.node.argument;
3763
- const position = path.node.start;
3764
- if (position === void 0 || !babelPathReachesExportedStore(path)) return;
3765
- const localName = argument?.type === "Identifier" ? argument.name : argument?.type === "MemberExpression" && argument.object?.type === "Identifier" ? argument.object.name : void 0;
3766
- const selectedName = argument?.type === "MemberExpression" ? argument.property?.name ?? argument.property?.value : void 0;
3767
- if (!localName || selectedName !== void 0 && typeof selectedName !== "string") return;
3768
- const operation = {
3769
- kind: "spread",
3770
- localName: babelResolveIdentifierAlias(path, localName),
3771
- position
3772
- };
3773
- if (selectedName !== void 0) operation.selectedName = selectedName;
3774
- operations.push(operation);
3775
- },
3776
- ObjectProperty(path) {
3777
- const position = path.node.start;
3778
- if (position === void 0) return;
3779
- if (!babelPathReachesExportedStore(path)) return;
3780
- const name = babelPropertyName(path);
3781
- if (name === "store" && babelPropertyIsTopLevelDefaultExport(path)) return;
3782
- const valueNode = path.node.value;
3783
- let value = babelStringValue(valueNode, path);
3784
- const environmentValue = value === void 0 && babelEnvironmentKey(valueNode, path) !== void 0;
3785
- if (environmentValue) value = babelEnvironmentValue(valueNode, path, env);
3786
- const stringValue = typeof value === "string" ? value : void 0;
3787
- if (typeof name === "string") operations.push({
3788
- kind: "property",
3789
- localName: valueNode?.type === "Identifier" && valueNode.name ? babelResolveIdentifierAlias(path, valueNode.name) : void 0,
3790
- name,
3791
- position,
3792
- environmentValue,
3793
- value: stringValue
3794
- });
3795
- }
3796
- } })] }
3797
- });
3798
- return operations.sort((left, right) => left.position - right.position || (left.kind === "property" && right.kind === "property" ? Number(right.localName !== void 0) - Number(left.localName !== void 0) : 0)).filter((operation, index, sorted) => {
3799
- const previous = sorted[index - 1];
3800
- if (!previous || operation.position !== previous.position || operation.kind !== previous.kind) return true;
3801
- if (operation.kind === "spread" || previous.kind === "spread") return false;
3802
- return operation.name !== previous.name;
3803
- });
3804
- }
3805
- function reconstructCloudflareArtifactStore(operations, importedValues = /* @__PURE__ */ new Map()) {
3806
- let reconstructed = {};
3807
- for (const operation of operations) {
3808
- if (operation.kind === "spread") {
3809
- const imported = importedValues.get(importedWorkspaceValueKey(operation.localName, operation.selectedName));
3810
- reconstructed = isRecord(imported) ? {
3811
- ...reconstructed,
3812
- ...imported
3813
- } : {};
3814
- continue;
3815
- }
3816
- const imported = operation.localName === void 0 ? void 0 : importedValues.get(operation.localName);
3817
- if (typeof imported === "string") {
3818
- reconstructed[operation.name] = imported;
3819
- continue;
3820
- }
3821
- if (operation.value === void 0 && !operation.environmentValue) return;
3822
- reconstructed[operation.name] = operation.value;
3823
- }
3824
- if (reconstructed.provider !== "cloudflare-artifacts") return;
3825
- return reconstructed;
3826
- }
3827
- async function loadFactoredCloudflareArtifactStore(definition, loader, resolveModule, env = process.env) {
3828
- const loaded = await readSourceModule(definition.path);
3829
- if (!loaded) return;
3830
- const operations = sourceInlineWorkspaceStoreOperations(loaded, loader, env);
3831
- const importedValues = /* @__PURE__ */ new Map();
3832
- let importedArtifactStore;
3833
- for (const { importedName, localName, selectedName, specifier } of sourceImportsFeedingWorkspaceStore(loaded, loader, "default")) {
3834
- if (!importedName) continue;
3835
- const resolvedModule = specifier.startsWith(".") ? resolve(dirname(loaded.file), specifier) : await resolveModule?.(specifier, loaded.file);
3836
- if (!resolvedModule) continue;
3837
- try {
3838
- const imported = await loader.import(resolvedModule.split(/[?#]/, 1)[0]);
3839
- const sourceExport = importedName === "default" ? imported.default : imported[importedName];
3840
- const store = selectedName && isRecord(sourceExport) ? sourceExport[selectedName] : sourceExport;
3841
- if (localName) {
3842
- importedValues.set(localName, store);
3843
- if (selectedName) importedValues.set(importedWorkspaceValueKey(localName, selectedName), store);
3844
- }
3845
- if (isRecord(store) && store.provider === "cloudflare-artifacts") importedArtifactStore = store;
3846
- } catch {}
3847
- }
3848
- return operations.length ? reconstructCloudflareArtifactStore(operations, importedValues) : importedArtifactStore;
3849
- }
3850
- function vercelFunctionRuntimePackages() {
3851
- return [{
3852
- name: WORKSPACE_PACKAGE_NAME,
3853
- resolveFrom: import.meta.url
3854
- }];
3855
- }
3856
- function hasCloudflareArtifactBinding(value) {
3857
- return isRecord(value) && typeof value.binding === "string";
3858
- }
3859
- function configuredCloudflareArtifacts(wranglerConfig) {
3860
- if (!isRecord(wranglerConfig) || !Array.isArray(wranglerConfig.artifacts)) return [];
3861
- return wranglerConfig.artifacts.filter(hasCloudflareArtifactBinding);
3862
- }
3863
- function createCloudflareArtifactsWranglerConfig(configs) {
3864
- const target = {};
3865
- for (const config of configs) configureCloudflareArtifacts(target, config);
3866
- const artifacts = target.cloudflare?.wrangler?.artifacts;
3867
- return artifacts?.length ? { artifacts } : void 0;
3868
- }
3869
- function resolveOwnedCloudflareArtifacts(requested, configured, previousBindings) {
3870
- const previous = new Set(previousBindings);
3871
- return requested.filter((artifact) => {
3872
- if (previous.has(artifact.binding)) return true;
3873
- const existing = configured.filter((entry) => entry.binding === artifact.binding);
3874
- const collision = existing.find((entry) => entry.namespace !== artifact.namespace);
3875
- if (collision) throw new TypeError(`[vitehub] Cloudflare Artifacts binding "${artifact.binding}" already exists in Wrangler config with namespace ${JSON.stringify(collision.namespace)}, but Workspace requested namespace "${artifact.namespace}". Configure a unique binding or use the existing namespace.`);
3876
- return existing.length === 0;
3877
- });
3878
- }
3879
- async function resolveDefinitionCloudflareArtifactsConfigs(definitions, rootDir, options, resolveModule, aliases, inspection, resolution, definitionOverrides) {
3880
- const loader = createWorkspaceDefinitionLoader(rootDir, aliases);
3881
- const sourceModuleResolver = createSourceModuleResolver(rootDir, aliases, resolveModule);
3882
- const configs = [];
3883
- for (const definition of definitions) {
3884
- if (!inspection?.artifactsOnly && !await sourceModuleMayUseCloudflareArtifacts(definition.path, loader, sourceModuleResolver)) continue;
3885
- let loaded;
3886
- try {
3887
- loaded = await loadDiscoveredWorkspaceDefinition(loader, definition);
3888
- loaded = loaded.default ?? loaded;
3889
- } catch (error) {
3890
- if (inspection?.artifactsOnly && !await sourceModuleMayUseCloudflareArtifacts(definition.path, loader, sourceModuleResolver)) continue;
3891
- const source = await readSourceModule(definition.path);
3892
- if (source && sourceHasUnresolvedWorkspaceRoot(source, loader)) throw error;
3893
- const store = await loadFactoredCloudflareArtifactStore(definition, loader, sourceModuleResolver, resolution?.env || process.env);
3894
- if (!store) {
3895
- if (inspection?.artifactsOnly) continue;
3896
- throw error;
3897
- }
3898
- loaded = { store };
3899
- }
3900
- const workspace = normalizeWorkspaceDefinition(definition.name, loaded);
3901
- if (!workspace.store || "readFile" in workspace.store) continue;
3902
- const config = normalizeWorkspaceOptions({ store: workspace.store }, {
3903
- dev: false,
3904
- env: resolution?.env || process.env,
3905
- hosting: resolution?.hosting ?? process.env.VITEHUB_HOSTING,
3906
- rootDir: workspace.rootDir || rootDir
3907
- });
3908
- if (config && config.store.provider === "cloudflare-artifacts") {
3909
- configs.push(config);
3910
- definitionOverrides?.set(definition.name, config);
3911
- }
3912
- }
3913
- return configs;
3914
- }
3915
- async function resolveCloudflareArtifactsConfigs(config, definitions, rootDir, options = {}) {
3916
- return [...config.store.provider === "cloudflare-artifacts" ? [config] : [], ...await resolveDefinitionCloudflareArtifactsConfigs(definitions, rootDir, config, options.resolveModule, options.aliases, { artifactsOnly: options.artifactsOnly }, {
3917
- env: options.env,
3918
- hosting: options.hosting
3919
- }, options.definitionOverrides)];
3920
- }
3921
- async function writeCloudflareArtifactsProviderOutput(rootDir, clientOutDir, config, definitions, readCloudflareState, write, resolveModule, aliases) {
3922
- const requestedConfig = createCloudflareArtifactsWranglerConfig(config ? await resolveCloudflareArtifactsConfigs(config, definitions, rootDir, {
3923
- aliases,
3924
- resolveModule
3925
- }) : []);
3926
- const wranglerConfigOwnership = { arrays: { artifacts: {
3927
- key: "binding",
3928
- values: []
3929
- } } };
3930
- const wranglerConfigOwnershipFiles = { artifacts: cloudflareArtifactsBindingsFileName };
3931
- const state = await readCloudflareState({
3932
- wranglerConfigOwnership,
3933
- wranglerConfigOwnershipFiles
3934
- });
3935
- const configuredArtifacts = configuredCloudflareArtifacts(state.wranglerConfig);
3936
- const previousBindings = state.wranglerConfigOwnership?.arrays?.artifacts?.values?.filter((value) => typeof value === "string") ?? [];
3937
- const ownedArtifacts = resolveOwnedCloudflareArtifacts(requestedConfig?.artifacts ?? [], configuredArtifacts, previousBindings);
3938
- const wranglerConfig = ownedArtifacts.length ? { artifacts: ownedArtifacts } : void 0;
3939
- const nextBindings = ownedArtifacts.map((binding) => binding.binding);
3940
- if (!wranglerConfig && !previousBindings.length) return;
3941
- const nextOwnership = { arrays: { artifacts: {
3942
- key: "binding",
3943
- values: nextBindings
3944
- } } };
3945
- await write({
3946
- clientOutDir,
3947
- rootDir,
3948
- ...wranglerConfig ? { cloudflare: {
3949
- wranglerConfig,
3950
- wranglerConfigOwnership: nextOwnership,
3951
- wranglerConfigOwnershipFiles
3952
- } } : { cleanup: { cloudflare: {
3953
- wranglerConfigOwnership: nextOwnership,
3954
- wranglerConfigOwnershipFiles
3955
- } } }
3956
- });
3957
- }
3958
- function resolveWorkspaceHosting(hosting, nitro, env = process.env) {
3959
- return [
3960
- hosting,
3961
- isRecord(nitro) && typeof nitro.preset === "string" ? nitro.preset : void 0,
3962
- env.NITRO_PRESET,
3963
- env.SERVER_PRESET,
3964
- env.VITEHUB_HOSTING
3965
- ].map((value) => value?.trim()).find(Boolean);
3966
- }
3967
- function mergeDedupe(current) {
3968
- if (!current) return [WORKSPACE_PACKAGE_NAME];
3969
- return current.includes(WORKSPACE_PACKAGE_NAME) ? current : [...current, WORKSPACE_PACKAGE_NAME];
3970
- }
3971
- function isWorkspaceFile(file) {
3972
- return workspaceSuffixPattern.test(file) || workspacesDirSegment.test(file);
3973
- }
3974
- function resolveWorkspacePluginRoots(root, workspaceOptions) {
3975
- const resolvedViteRoot = resolve(root);
3976
- return {
3977
- projectRoot: resolveViteHubProjectRoot(resolvedViteRoot, { projectRoot: workspaceOptions ? workspaceOptions.projectRoot : void 0 }),
3978
- viteRoot: resolvedViteRoot
3979
- };
3980
- }
3981
- function discoverDefinitions(roots, serverDirs) {
3982
- return discoverViteWorkspaceDefinitions(roots.viteRoot, {
3983
- serverDirs,
3984
- serverRootDir: roots.projectRoot
3985
- });
3986
- }
3987
- function isRecord(value) {
3988
- return typeof value === "object" && value !== null;
3989
- }
3990
- function isWorkspaceRegistry(value) {
3991
- return isRecord(value) && Object.values(value).every((item) => typeof item === "function");
3992
- }
3993
- function workspaceDefinitionLoaderAliases(aliases) {
3994
- if (!Array.isArray(aliases)) return aliases;
3995
- return Object.fromEntries(aliases.flatMap((alias) => typeof alias.find === "string" ? [[alias.find, alias.replacement]] : []));
3996
- }
3997
- function isHostedWorkspaceStore(store) {
3998
- return store.provider === "cloudflare-artifacts" || store.provider === "github" || store.provider === "vercel-blob";
3999
- }
4000
- function requestOrigin(server, req) {
4001
- const host = Array.isArray(req.headers.host) ? req.headers.host[0] : req.headers.host;
4002
- if (host) {
4003
- const fallback = server.resolvedUrls?.local?.[0] || "http://localhost/";
4004
- return new URL(`${new URL(fallback).protocol}//${host}`).origin;
4005
- }
4006
- const base = server.resolvedUrls?.local?.[0] || `http://localhost:${server.config.server.port || 5173}/`;
4007
- return new URL(base).origin;
4008
- }
4009
- function validateWorkspaceDevRequest(server, req) {
4010
- const header = req.headers[workspaceDevHeader];
4011
- if ((Array.isArray(header) ? header[0] : header) !== "1") return new Response("Forbidden Workspace Dev request.", { status: 403 });
4012
- const origin = Array.isArray(req.headers.origin) ? req.headers.origin[0] : req.headers.origin;
4013
- if (origin && origin !== requestOrigin(server, req)) return new Response("Forbidden Workspace Dev origin.", { status: 403 });
4014
- if (req.method !== "POST") return;
4015
- if (!(Array.isArray(req.headers["content-type"]) ? req.headers["content-type"][0] : req.headers["content-type"])?.toLowerCase().startsWith("application/json")) return new Response("Workspace Dev requests must use application/json.", { status: 415 });
4016
- }
4017
- function acceptsWorkspaceDevStream(req) {
4018
- const accept = Array.isArray(req.headers.accept) ? req.headers.accept.join(",") : req.headers.accept;
4019
- return Boolean(accept?.includes("application/x-ndjson"));
4020
- }
4021
- async function readRequestBody(req) {
4022
- let body = "";
4023
- req.setEncoding("utf8");
4024
- for await (const chunk of req) body += chunk;
4025
- return body;
4026
- }
4027
- function createAbortSignalFromClose(target, message) {
4028
- const controller = new AbortController();
4029
- const abort = () => controller.abort(new Error(message));
4030
- target.once("close", abort);
4031
- return {
4032
- dispose: () => target.off("close", abort),
4033
- signal: controller.signal
4034
- };
4035
- }
4036
- async function writeResponse(res, response) {
4037
- res.statusCode = response.status;
4038
- for (const [name, value] of response.headers) res.setHeader(name, value);
4039
- if (!response.body) {
4040
- res.end();
4041
- return;
4042
- }
4043
- const reader = response.body.getReader();
4044
- try {
4045
- for (;;) {
4046
- const { done, value } = await reader.read();
4047
- if (done) break;
4048
- res.write(Buffer.from(value));
4049
- }
4050
- res.end();
4051
- } finally {
4052
- reader.releaseLock();
4053
- }
4054
- }
4055
- function isWorkspaceDevRoute(req) {
4056
- return new URL(req.url || "/", "http://localhost").pathname === workspaceDevRoute;
4057
- }
4058
- function streamWorkspaceDevCommand(input, closeHost) {
4059
- const encoder = new TextEncoder();
4060
- const stream = new ReadableStream({ async start(controller) {
4061
- const write = (value) => controller.enqueue(encoder.encode(`${JSON.stringify(value)}\n`));
4062
- try {
4063
- write({
4064
- result: await runWorkspaceDevCommand({
4065
- ...input,
4066
- onProgress: async (event) => write({
4067
- event,
4068
- type: "progress"
4069
- })
4070
- }),
4071
- type: "result"
4072
- });
4073
- } catch (error) {
4074
- write({
4075
- error: error instanceof Error ? error.message : String(error),
4076
- type: "error"
4077
- });
4078
- } finally {
4079
- await closeHost();
4080
- controller.close();
4081
- }
4082
- } });
4083
- return new Response(stream, { headers: {
4084
- "cache-control": "no-store",
4085
- "content-type": "application/x-ndjson; charset=utf-8"
4086
- } });
4087
- }
4088
- async function handleWorkspaceDevRequest(server, req, workspaces, tokenOptions, abortSignal) {
4089
- const validation = validateWorkspaceDevRequest(server, req);
4090
- if (validation) return validation;
4091
- if (req.method === "GET") {
4092
- await ensureWorkspaceDevToken(server.config.root, tokenOptions);
4093
- return Response.json({
4094
- root: server.config.root,
4095
- workspaceDevTokenServerId: tokenOptions.serverId,
4096
- workspaces
4097
- });
4098
- }
4099
- if (req.method !== "POST") return new Response("Method Not Allowed", { status: 405 });
4100
- let body;
4101
- try {
4102
- body = JSON.parse(await readRequestBody(req));
4103
- } catch {
4104
- return new Response("Malformed Workspace Dev payload.", { status: 400 });
4105
- }
4106
- const command = isRecord(body) && isRecord(body.workspaceCommand) ? body.workspaceCommand : void 0;
4107
- if (!command || typeof command.workspace !== "string" || typeof command.command !== "string") return new Response("Missing Workspace Dev command.", { status: 400 });
4108
- if (!await validateWorkspaceDevToken(server.config.root, req.headers, tokenOptions)) return new Response("Forbidden Workspace Dev token.", { status: 403 });
4109
- const mod = await server.ssrLoadModule(WORKSPACE_REGISTRY_ID);
4110
- const load = (isWorkspaceRegistry(mod.default) ? mod.default : {})[command.workspace];
4111
- if (!load) return new Response(`Unknown Workspace Dev target: ${command.workspace}`, { status: 404 });
4112
- const definition = (await load()).default;
4113
- if (command.args !== void 0 && (!Array.isArray(command.args) || command.args.some((arg) => typeof arg !== "string"))) return new Response("Workspace Dev command args must be strings.", { status: 400 });
4114
- if (command.paths !== void 0 && (!Array.isArray(command.paths) || command.paths.some((path) => typeof path !== "string"))) return new Response("Workspace Dev command paths must be strings.", { status: 400 });
4115
- const args = command.args;
4116
- const paths = command.paths;
4117
- const timeout = typeof command.timeout === "number" && Number.isFinite(command.timeout) ? command.timeout : void 0;
4118
- const { resolveBox } = await import("@vite-hub/box");
4119
- const host = await (await resolveBox({ runtime: "trusted-host" }, {})).open({ signal: abortSignal });
4120
- const input = {
4121
- abortSignal,
4122
- ...args ? { args } : {},
4123
- command: command.command,
4124
- host,
4125
- ...isRecord(definition) ? { definition: normalizeWorkspaceDefinition(command.workspace, definition) } : {},
4126
- ...paths?.length ? { paths } : {},
4127
- ...timeout ? { timeout } : {},
4128
- workspace: command.workspace
4129
- };
4130
- if (acceptsWorkspaceDevStream(req)) return streamWorkspaceDevCommand(input, () => host.close());
4131
- try {
4132
- return Response.json(await runWorkspaceDevCommand(input));
4133
- } finally {
4134
- await host.close();
4135
- }
4136
- }
4137
- function hasNitroPlugin(value) {
4138
- if (Array.isArray(value)) return value.some(hasNitroPlugin);
4139
- return isRecord(value) && typeof value.name === "string" && value.name.startsWith("nitro:");
4140
- }
4141
- function hasNitroConfig(config) {
4142
- return "nitro" in config || hasNitroPlugin(config.plugins);
4143
- }
4144
- function hasExplicitWorkspaceRuntimeOptions(options) {
4145
- return Boolean(options && (options.root || options.store));
4146
- }
4147
- function shouldInstallNitroWorkspacePlugin(config, options, normalized, definitions) {
4148
- return isHostedWorkspaceStore(normalized.store) || hasExplicitWorkspaceRuntimeOptions(options) || hasNitroConfig(config) && definitions.length > 0;
4149
- }
4150
- function mergeNitroWorkspaceConfig(value) {
4151
- const nitro = isRecord(value) ? { ...value } : {};
4152
- const plugins = Array.isArray(nitro.plugins) ? [...nitro.plugins] : [];
4153
- if (!plugins.includes(generatedNitroWorkspacePlugin)) plugins.push(generatedNitroWorkspacePlugin);
4154
- return {
4155
- ...nitro,
4156
- plugins
4157
- };
4158
- }
4159
- function mergeNitroExternal(value, addition) {
4160
- if (typeof value === "undefined") return [addition];
4161
- if (Array.isArray(value)) return value.includes(addition) ? [...value] : [...value, addition];
4162
- if (typeof value === "string" || value instanceof RegExp) return [value, addition];
4163
- if (typeof value === "function") return (source, importer, isResolved) => source === addition || Boolean(value(source, importer, isResolved));
4164
- return value;
4165
- }
4166
- function configureCloudflareNitroRuntime(nitro) {
4167
- nitro.cloudflare ??= {};
4168
- nitro.cloudflare.wrangler ??= {};
4169
- nitro.cloudflare.nodeCompat = true;
4170
- const rollupConfig = isRecord(nitro.rollupConfig) ? { ...nitro.rollupConfig } : {};
4171
- nitro.rollupConfig = {
4172
- ...rollupConfig,
4173
- external: mergeNitroExternal(rollupConfig.external, "cloudflare:workers")
4174
- };
4175
- }
4176
- function moduleImportSpecifier(fromFile, targetFile) {
4177
- const specifier = relative(dirname(fromFile), targetFile).replace(/\\/g, "/");
4178
- return specifier.startsWith(".") ? specifier : `./${specifier}`;
4179
- }
4180
- function shouldConfigureRuntime(options, normalized) {
4181
- return isHostedWorkspaceStore(normalized.store) || hasExplicitWorkspaceRuntimeOptions(options);
4182
- }
4183
- function renderRuntimeValue(value, depth = 0) {
4184
- if (typeof value === "function") return value.toString();
4185
- if (Array.isArray(value)) {
4186
- if (!value.length) return "[]";
4187
- const indent = " ".repeat(depth + 1);
4188
- const closingIndent = " ".repeat(depth);
4189
- return `[\n${value.map((item) => `${indent}${renderRuntimeValue(item, depth + 1)}`).join(",\n")}\n${closingIndent}]`;
4190
- }
4191
- if (isRecord(value)) {
4192
- const entries = Object.entries(value).filter(([, entry]) => entry !== void 0);
4193
- if (!entries.length) return "{}";
4194
- const indent = " ".repeat(depth + 1);
4195
- const closingIndent = " ".repeat(depth);
4196
- return `{\n${entries.map(([key, entry]) => `${indent}${JSON.stringify(key)}: ${renderRuntimeValue(entry, depth + 1)}`).join(",\n")}\n${closingIndent}}`;
4197
- }
4198
- return JSON.stringify(value);
4199
- }
4200
- function runtimeWorkspaceConfig(config, options, cloudflareRuntime) {
4201
- if (!cloudflareRuntime || !config || config.store.provider !== "github" || !options) return config;
4202
- const store = options.store;
4203
- if (!store || "readFile" in store || store.provider !== "github") return config;
4204
- const runtimeStore = { ...config.store };
4205
- const isAbsent = (value) => typeof value === "undefined" || typeof value === "string" && value.trim().length === 0;
4206
- for (const key of [
4207
- "branch",
4208
- "root",
4209
- "token"
4210
- ]) if (typeof store[key] === "function") runtimeStore[key] = store[key];
4211
- else if (isAbsent(store[key])) delete runtimeStore[key];
4212
- if (typeof store.repository === "function") runtimeStore.repository = store.repository;
4213
- else if (typeof store.repo === "function") {
4214
- runtimeStore.repo = store.repo;
4215
- delete runtimeStore.repository;
4216
- } else if (isAbsent(store.repository) && isAbsent(store.repo)) {
4217
- delete runtimeStore.repository;
4218
- delete runtimeStore.repo;
4219
- }
4220
- return {
4221
- ...config,
4222
- store: runtimeStore
4223
- };
4224
- }
4225
- function renderNitroWorkspacePlugin(config, registryImport, installHostedRuntime, cloudflareRuntime, importBase = WORKSPACE_PACKAGE_NAME) {
4226
- const hostedRuntimeImport = `${importBase}/internal/runtime/hosted`;
4227
- const hostedVercelBlobRuntimeImport = `${importBase}/internal/runtime/hosted-vercel-blob`;
4228
- const runtimeImport = `${importBase}/runtime`;
4229
- const hostedConfig = config && isHostedWorkspaceStore(config.store) ? config : void 0;
4230
- const isVercelBlobStore = hostedConfig?.store.provider === "vercel-blob";
4231
- const runtimeImports = hostedConfig ? [
4232
- isVercelBlobStore ? `import { configureHostedVercelBlobWorkspaceRuntime } from '${hostedVercelBlobRuntimeImport}'` : `import { configureHostedWorkspaceRuntime, installHostedWorkspaceRuntime } from '${hostedRuntimeImport}'`,
4233
- isVercelBlobStore ? `import { installHostedWorkspaceRuntime } from '${hostedRuntimeImport}'` : `import { installHostedVercelBlobWorkspaceRuntime } from '${hostedVercelBlobRuntimeImport}'`,
4234
- `import { setWorkspaceRuntimeRegistry } from '${runtimeImport}'`
4235
- ] : [
4236
- ...installHostedRuntime ? [`import { installHostedWorkspaceRuntime } from '${hostedRuntimeImport}'`] : [],
4237
- ...installHostedRuntime ? [`import { installHostedVercelBlobWorkspaceRuntime } from '${hostedVercelBlobRuntimeImport}'`] : [],
4238
- `import { ${config ? "setWorkspaceRuntimeConfig, " : ""}setWorkspaceRuntimeRegistry } from '${runtimeImport}'`
4239
- ];
4240
- if (cloudflareRuntime) runtimeImports.unshift("import { env as vitehubEnv } from 'cloudflare:workers'", `import { setActiveCloudflareEnv } from '${importBase}/internal/runtime/state'`);
4241
- const runtimeSetup = hostedConfig ? [` ${isVercelBlobStore ? "configureHostedVercelBlobWorkspaceRuntime" : "configureHostedWorkspaceRuntime"}(${renderRuntimeValue({
4242
- root: hostedConfig.root,
4243
- store: hostedConfig.store
4244
- })})`, ` ${isVercelBlobStore ? "installHostedWorkspaceRuntime" : "installHostedVercelBlobWorkspaceRuntime"}()`] : [
4245
- ...installHostedRuntime ? [" installHostedWorkspaceRuntime()"] : [],
4246
- ...installHostedRuntime ? [" installHostedVercelBlobWorkspaceRuntime()"] : [],
4247
- ...config ? [` setWorkspaceRuntimeConfig(${renderRuntimeValue({
4248
- root: config.root,
4249
- store: config.store
4250
- })})`] : []
4251
- ];
4252
- return [
4253
- ...runtimeImports,
4254
- `import registry from ${JSON.stringify(registryImport)}`,
4255
- "",
4256
- "export default function vitehubWorkspacePlugin() {",
4257
- ...cloudflareRuntime ? [" setActiveCloudflareEnv(vitehubEnv)"] : [],
4258
- " setWorkspaceRuntimeRegistry(registry)",
4259
- ...runtimeSetup,
4260
- "}",
4261
- ""
4262
- ].join("\n");
4263
- }
4264
- async function writeNitroWorkspacePlugin(root, config, options, definitions, cloudflareRuntime = false, importBase = WORKSPACE_PACKAGE_NAME, definitionOverrides) {
4265
- const pluginFile = resolve(root, generatedNitroWorkspacePlugin);
4266
- const registryFile = resolve(root, generatedNitroWorkspaceRegistry);
4267
- const runtimeConfig = runtimeWorkspaceConfig(config, options, cloudflareRuntime);
4268
- await Promise.all([mkdir(dirname(pluginFile), { recursive: true }), mkdir(dirname(registryFile), { recursive: true })]);
4269
- await writeFile(registryFile, createWorkspaceRegistryContents(registryFile, definitions, definitionOverrides), "utf8");
4270
- await writeFile(pluginFile, renderNitroWorkspacePlugin(runtimeConfig, moduleImportSpecifier(pluginFile, registryFile), definitions.length > 0 && !(runtimeConfig && isHostedWorkspaceStore(runtimeConfig.store)), cloudflareRuntime, importBase), "utf8");
4271
- }
4272
- async function createWorkspaceNitroConfig(options = {}) {
4273
- const workspaceOptions = stripWorkspaceInternalOptions(options.workspace);
4274
- const roots = resolveWorkspacePluginRoots(options.viteRoot || process.cwd(), workspaceOptions);
4275
- const env = options.env || process.env;
4276
- const hosting = resolveWorkspaceHosting(options.hosting, options.nitro, env);
4277
- const normalized = normalizeWorkspaceOptions(workspaceOptions, {
4278
- dev: options.command !== "build",
4279
- env,
4280
- hosting,
4281
- rootDir: roots.projectRoot
4282
- });
4283
- if (!normalized) return null;
4284
- const definitions = discoverDefinitions(roots);
4285
- if (!isHostedWorkspaceStore(normalized.store) && !hasExplicitWorkspaceRuntimeOptions(workspaceOptions) && definitions.length === 0) return null;
4286
- const definitionOverrides = /* @__PURE__ */ new Map();
4287
- const cloudflareArtifactsConfigs = await resolveCloudflareArtifactsConfigs(normalized, definitions, roots.projectRoot, {
4288
- aliases: options.aliases,
4289
- artifactsOnly: true,
4290
- env: options.env,
4291
- hosting,
4292
- definitionOverrides
4293
- });
4294
- const runtimeConfig = shouldConfigureRuntime(workspaceOptions, normalized) ? normalized : false;
4295
- const cloudflareRuntime = cloudflareArtifactsConfigs.length > 0 || getHostingProvider(hosting) === "cloudflare";
4296
- await writeNitroWorkspacePlugin(roots.projectRoot, runtimeConfig, workspaceOptions, definitions, cloudflareRuntime, WORKSPACE_PACKAGE_NAME, definitionOverrides);
4297
- const nitro = mergeNitroWorkspaceConfig(options.nitro);
4298
- for (const config of cloudflareArtifactsConfigs) configureCloudflareArtifacts(nitro, config);
4299
- if (cloudflareRuntime) configureCloudflareNitroRuntime(nitro);
4300
- return nitro;
4301
- }
4302
- const setWorkspacePluginHosting = Symbol("vitehub.workspace.setHosting");
4303
- function setWorkspaceVitePluginHosting(plugin, hosting) {
4304
- if (!plugin || typeof plugin !== "object") return false;
4305
- const setter = plugin[setWorkspacePluginHosting];
4306
- if (!setter) return false;
4307
- setter(hosting);
4308
- return true;
4309
- }
4310
- function stripWorkspaceInternalOptions(options) {
4311
- if (!options || !Object.hasOwn(options, "hosting") && !Object.hasOwn(options, "importBase")) return options;
4312
- const publicOptions = { ...options };
4313
- delete publicOptions.hosting;
4314
- delete publicOptions.importBase;
4315
- return publicOptions;
4316
- }
4317
- function hubWorkspace(options) {
4318
- let hosting = options?.hosting;
4319
- const importBase = options?.importBase ?? WORKSPACE_PACKAGE_NAME;
4320
- const publicOptions = stripWorkspaceInternalOptions(options);
4321
- let resolved;
4322
- let providerOutput;
4323
- const providerOutputGenerations = createProviderDeploymentOutputGenerationState();
4324
- let resolvedOptions = false;
4325
- let projectRoot;
4326
- let viteRoot;
4327
- let assetsRegistryFile;
4328
- let manifest = { workspaces: [] };
4329
- let registryContents = "export default {}\n";
4330
- let server;
4331
- let serverDirs;
4332
- async function refreshManifest(roots) {
4333
- const definitions = discoverDefinitions(roots, serverDirs);
4334
- const state = await refreshWorkspaceBuildState(roots.projectRoot, definitions);
4335
- manifest = state.manifest;
4336
- registryContents = state.registryContents;
4337
- }
4338
- function invalidateVirtualWorkspaceModules() {
4339
- if (!server) return;
4340
- const moduleGraph = server.moduleGraph;
4341
- const ids = [
4342
- RESOLVED_WORKSPACE_REGISTRY_ID,
4343
- RESOLVED_WORKSPACES_ID,
4344
- ...manifest.workspaces.map((w) => `${RESOLVED_WORKSPACE_PREFIX}${w.name}`)
4345
- ];
4346
- for (const id of ids) {
4347
- const mod = moduleGraph.getModuleById(id);
4348
- if (mod) moduleGraph.invalidateModule(mod);
4349
- }
4350
- }
4351
- async function maybeRefreshTypesForFile(roots, file) {
4352
- if (!isWorkspaceFile(file)) return;
4353
- await refreshManifest(roots);
4354
- invalidateVirtualWorkspaceModules();
4355
- }
4356
- return {
4357
- name: "@vite-hub/workspace/vite",
4358
- enforce: "pre",
4359
- [setWorkspacePluginHosting](value) {
4360
- hosting = value;
4361
- },
4362
- api: { getWorkspaces: () => manifest.workspaces },
4363
- async config(config, env) {
4364
- serverDirs = config["__vitehubServerDirs"] ?? serverDirs;
4365
- const workspaceOptions = stripWorkspaceInternalOptions(config.workspace ?? publicOptions);
4366
- const roots = resolveWorkspacePluginRoots(config.root || process.cwd(), workspaceOptions);
4367
- const resolvedHosting = resolveWorkspaceHosting(typeof hosting === "function" ? hosting() : hosting, config.nitro);
4368
- const normalized = normalizeWorkspaceOptions(workspaceOptions, {
4369
- dev: env?.command !== "build",
4370
- env: process.env,
4371
- hosting: resolvedHosting,
4372
- rootDir: roots.projectRoot
4373
- });
4374
- const runtimeOptions = resolvedHosting && normalized && normalized.store.provider !== "local" ? {
4375
- ...workspaceOptions || {},
4376
- store: workspaceOptions && workspaceOptions.store ? workspaceOptions.store : normalized.store
4377
- } : workspaceOptions;
4378
- const viteConfig = { server: { watch: { ignored: mergeGeneratedViteHubWatchIgnored(config.server?.watch?.ignored) } } };
4379
- const definitions = normalized ? discoverDefinitions(roots, serverDirs) : [];
4380
- if (normalized && shouldInstallNitroWorkspacePlugin(config, runtimeOptions, normalized, definitions)) {
4381
- const runtimeConfig = shouldConfigureRuntime(runtimeOptions, normalized) ? normalized : false;
4382
- const definitionOverrides = /* @__PURE__ */ new Map();
4383
- const artifacts = await resolveCloudflareArtifactsConfigs(normalized, definitions, roots.projectRoot, {
4384
- aliases: config.resolve?.alias ? workspaceDefinitionLoaderAliases(config.resolve.alias) : void 0,
4385
- artifactsOnly: true,
4386
- hosting: resolvedHosting,
4387
- definitionOverrides
4388
- });
4389
- const usesCloudflareRuntime = artifacts.length > 0 || getHostingProvider(resolvedHosting) === "cloudflare";
4390
- await writeNitroWorkspacePlugin(roots.projectRoot, runtimeConfig, runtimeOptions, definitions, usesCloudflareRuntime, importBase, definitionOverrides);
4391
- const nitro = mergeNitroWorkspaceConfig(config.nitro);
4392
- for (const artifactConfig of artifacts) configureCloudflareArtifacts(nitro, artifactConfig);
4393
- if (usesCloudflareRuntime) configureCloudflareNitroRuntime(nitro);
4394
- config.nitro = nitro;
4395
- viteConfig.nitro = nitro;
4396
- }
4397
- return viteConfig;
4398
- },
4399
- async configResolved(config) {
4400
- resolved = config;
4401
- providerOutput = useProviderOutputCatalog(config);
4402
- const workspaceOptions = stripWorkspaceInternalOptions(config.workspace ?? publicOptions);
4403
- const roots = resolveWorkspacePluginRoots(config.root, workspaceOptions);
4404
- projectRoot = roots.projectRoot;
4405
- viteRoot = roots.viteRoot;
4406
- const resolvedHosting = resolveWorkspaceHosting(typeof hosting === "function" ? hosting() : hosting, config.nitro);
4407
- if (config.command !== "build") process.env.VITEHUB_WORKSPACE_DEV = "true";
4408
- else delete process.env.VITEHUB_WORKSPACE_DEV;
4409
- resolvedOptions = normalizeWorkspaceOptions(workspaceOptions, {
4410
- dev: config.command !== "build",
4411
- env: process.env,
4412
- hosting: resolvedHosting,
4413
- rootDir: roots.projectRoot
4414
- });
4415
- assetsRegistryFile = resolve(roots.projectRoot, ".vitehub/vite-runtime/workspace/assets/registry.mjs");
4416
- await initializeWorkspaceAssetRegistry(assetsRegistryFile);
4417
- await refreshManifest(roots);
4418
- },
4419
- configEnvironment(name, config) {
4420
- if (!isServerEnvironment(name, config)) return;
4421
- return { resolve: {
4422
- dedupe: mergeDedupe(config.resolve?.dedupe),
4423
- noExternal: mergeNoExternal(config.resolve?.noExternal)
4424
- } };
4425
- },
4426
- async buildStart() {
4427
- providerOutputGenerations.capture(this, providerOutput);
4428
- if (!resolved) return;
4429
- const roots = {
4430
- projectRoot: projectRoot || resolveViteHubProjectRoot(resolved.root),
4431
- viteRoot: viteRoot || resolve(resolved.root)
4432
- };
4433
- await refreshManifest(roots);
4434
- if (resolved.command !== "build" || !assetsRegistryFile) return;
4435
- await syncWorkspaceBuildAssets(discoverDefinitions(roots, serverDirs), roots.projectRoot, resolvedOptions, assetsRegistryFile);
4436
- },
4437
- async buildEnd(error) {
4438
- if (error) {
4439
- await providerOutputGenerations.reset(this, providerOutput, error);
4440
- return;
4441
- }
4442
- if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
4443
- const roots = {
4444
- projectRoot: projectRoot || resolveViteHubProjectRoot(resolved.root),
4445
- viteRoot: viteRoot || resolve(resolved.root)
4446
- };
4447
- providerOutputGenerations.defer(this, providerOutput, {
4448
- owner: "workspace",
4449
- rootDir: roots.projectRoot,
4450
- write: async ({ readCloudflareState, signal, write }) => {
4451
- const definitions = discoverDefinitions(roots, serverDirs);
4452
- await copyVercelFunctionRuntimePackages({
4453
- packages: vercelFunctionRuntimePackages(),
4454
- rootDir: roots.projectRoot,
4455
- signal
4456
- });
4457
- await writeCloudflareArtifactsProviderOutput(roots.projectRoot, resolved.build?.outDir ?? "dist/client", resolvedOptions, definitions, readCloudflareState, write, resolved.createResolver?.(), resolved.resolve ? workspaceDefinitionLoaderAliases(resolved.resolve.alias) : void 0);
4458
- }
4459
- });
4460
- },
4461
- async renderError(error) {
4462
- await providerOutputGenerations.reset(this, providerOutput, error);
4463
- },
4464
- closeBundle: {
4465
- order: "post",
4466
- sequential: true,
4467
- async handler() {
4468
- if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
4469
- providerOutputGenerations.ready(this);
4470
- await finalizeProviderDeploymentOutputs(providerOutput);
4471
- }
4472
- },
4473
- async configureServer(devServer) {
4474
- server = devServer;
4475
- installHostedWorkspaceRuntime();
4476
- installHostedVercelBlobWorkspaceRuntime();
4477
- const tokenOptions = { serverId: workspaceDevTokenServerId(devServer.config.server.port) };
4478
- await refreshWorkspaceDevToken(devServer.config.root, tokenOptions);
4479
- const roots = {
4480
- projectRoot: projectRoot || resolveViteHubProjectRoot(devServer.config.root),
4481
- viteRoot: viteRoot || resolve(devServer.config.root)
4482
- };
4483
- const refresh = async (file) => await maybeRefreshTypesForFile(roots, file);
4484
- devServer.watcher.on("add", refresh);
4485
- devServer.watcher.on("unlink", refresh);
4486
- devServer.middlewares.use((req, res, next) => {
4487
- if (!isWorkspaceDevRoute(req)) return next();
4488
- const abort = createAbortSignalFromClose(res, "[vitehub] Workspace Dev response closed.");
4489
- handleWorkspaceDevRequest(devServer, req, manifest.workspaces, tokenOptions, abort.signal).then((response) => writeResponse(res, response)).catch((error) => writeResponse(res, new Response(error instanceof Error ? error.message : "Workspace Dev request failed.", { status: 500 }))).finally(abort.dispose);
4490
- });
4491
- },
4492
- vitehub: { cli: async () => {
4493
- return createWorkspaceCliContributor();
4494
- } },
4495
- async handleHotUpdate(ctx) {
4496
- if (!resolved) return;
4497
- await maybeRefreshTypesForFile({
4498
- projectRoot: projectRoot || resolveViteHubProjectRoot(resolved.root),
4499
- viteRoot: viteRoot || resolve(resolved.root)
4500
- }, ctx.file);
4501
- },
4502
- resolveId(id) {
4503
- if (id === WORKSPACE_ASSETS_REGISTRY_ID) return assetsRegistryFile;
4504
- if (id === WORKSPACE_REGISTRY_ID) return RESOLVED_WORKSPACE_REGISTRY_ID;
4505
- if (id === WORKSPACES_ID) return RESOLVED_WORKSPACES_ID;
4506
- if (id.startsWith(WORKSPACE_PREFIX)) return `${RESOLVED_WORKSPACE_PREFIX}${id.slice(20)}`;
4507
- },
4508
- load(id) {
4509
- if (id === RESOLVED_WORKSPACE_REGISTRY_ID) return registryContents;
4510
- if (id === RESOLVED_WORKSPACES_ID) return `export const workspaces = ${JSON.stringify(manifest.workspaces)};\nexport default { workspaces };\n`;
4511
- if (id.startsWith(RESOLVED_WORKSPACE_PREFIX)) {
4512
- const name = id.slice(RESOLVED_WORKSPACE_PREFIX.length);
4513
- const workspace = manifest.workspaces.find((item) => item.name === name);
4514
- return `const manifest = ${JSON.stringify(workspace ? {
4515
- ...workspace,
4516
- entries: []
4517
- } : {
4518
- name,
4519
- entries: []
4520
- })};\nexport default manifest;\n`;
4521
- }
4522
- }
4523
- };
4524
- }
4525
- //#endregion
4526
- export { discoverViteWorkspaceDefinitions as i, hubWorkspace as n, setWorkspaceVitePluginHosting as r, createWorkspaceNitroConfig as t };