@vite-hub/workspace 0.0.2 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +48 -2
- package/dist/{ai-Cztw4eLk.js → ai-BqCC8BpY.js} +15 -4
- package/dist/{ai-hFdsvDHC.d.ts → ai-CjxvGqM0.d.ts} +1 -1
- package/dist/ai.d.ts +2 -2
- package/dist/ai.js +1 -1
- package/dist/{asset-registry-CaG9b7tf.js → asset-registry-8QI3ML3K.js} +1 -1
- package/dist/chunk-2rV9d50f.js +35 -0
- package/dist/cloudflare.d.ts +4 -2
- package/dist/cloudflare.js +1 -2
- package/dist/collections.d.ts +2 -2
- package/dist/collections.js +1 -1
- package/dist/{config--r5unwPc.js → config-Bc3c4Su1.js} +213 -120
- package/dist/{config-DCQ6y30R.js → config-CHLLWklZ.js} +9 -3
- package/dist/{config-Ca5DM8fF.d.ts → config-DE9xlaIw.d.ts} +1 -1
- package/dist/{file-B2q9NE18.js → file-Bc1X7pco.js} +9 -10
- package/dist/{files-xy0le-_U.js → files-Q6xZjDHA.js} +20 -9
- package/dist/{github-lIO6-2sH.js → github-DHnjxQIX.js} +27 -23
- package/dist/glob-CEZKeZFC.js +18 -0
- package/dist/host-DJH8cuoU.js +1030 -0
- package/dist/{artifacts-store-BAV9jZpd.js → hosted-RPeJOCFz.js} +146 -30
- package/dist/hosted-vercel-blob-d6C8ND5j.js +23580 -0
- package/dist/hosted-vercel-blob.d.ts +1 -1
- package/dist/hosted-vercel-blob.js +1 -25
- package/dist/hosted.d.ts +1 -1
- package/dist/hosted.js +1 -29
- package/dist/index.d.ts +61 -78
- package/dist/index.js +133 -435
- package/dist/lifecycle-LrL3sA4n.js +316 -0
- package/dist/loader.d.ts +1 -1
- package/dist/loader.js +1 -1
- package/dist/metadata-target-B0tOmVW7.js +717 -0
- package/dist/mountx.d.ts +10 -0
- package/dist/mountx.js +143 -0
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +1 -1
- package/dist/nuxt.d.ts +1 -1
- package/dist/nuxt.js +8 -2
- package/dist/{path-CNI6wKIU.js → path-Cp59koVz.js} +28 -4
- package/dist/{provider-CeQciesl.js → provider-B1yLjCJJ.js} +194 -47
- package/dist/providers/github/store.d.ts +1 -1
- package/dist/providers/github/store.js +1 -361
- package/dist/publish.d.ts +1 -1
- package/dist/publish.js +2 -2
- package/dist/registry-D3yzt8HQ.js +127 -0
- package/dist/{registry-CoC9JxVt.d.ts → registry-Uj6IVxes.d.ts} +3 -3
- package/dist/{request-execution-C8qRcReq.js → request-execution-B-dSFlGB.js} +8 -4
- package/dist/runtime/assets.d.ts +1 -1
- package/dist/runtime/assets.js +4 -2
- package/dist/runtime/empty-assets-registry.d.ts +1 -1
- package/dist/runtime/empty-registry.d.ts +1 -1
- package/dist/runtime/state.d.ts +4 -4
- package/dist/runtime/state.js +10 -7
- package/dist/runtime/workspace.d.ts +1 -1
- package/dist/runtime/workspace.js +1 -1
- package/dist/runtime-options-BsPSv5O7.js +13 -0
- package/dist/runtime-type-iEE6BjQJ.js +34 -0
- package/dist/runtime.d.ts +42 -7
- package/dist/runtime.js +276 -100
- package/dist/{search-C4REyHj9.js → search-BpiCF2Tw.js} +2 -2
- package/dist/server.d.ts +2 -2
- package/dist/server.js +24 -51
- package/dist/{shared-BRycRSbo.js → shared-DTR1Hhma.js} +115 -39
- package/dist/source-metadata.d.ts +9 -2
- package/dist/source-metadata.js +34 -2
- package/dist/{state-DSAHEsq6.d.ts → state-tYcRWEh2.d.ts} +13 -12
- package/dist/store-Dt_Jyys3.js +608 -0
- package/dist/{sync-DO42ypji.js → sync-DnTQwt8r.js} +6 -5
- package/dist/test.d.ts +1 -1
- package/dist/test.js +1 -1
- package/dist/token-CVzURBxC.js +61 -0
- package/dist/{types-DHkae7Cb.d.ts → types-CYuwjJ4V.d.ts} +94 -43
- package/dist/{use-d_PlAdOu.js → use-BTNDR5Rd.js} +147 -50
- package/dist/{use-D16tf8Ph.d.ts → use-BiHzt0xA.d.ts} +21 -4
- package/dist/vite-BptCrpv2.js +4526 -0
- package/dist/vite-CtA9guIM.d.ts +66 -0
- package/dist/vite.d.ts +2 -50
- package/dist/vite.js +2 -2
- package/dist/{workspace-n4wBmdaM.js → workspace-Dq08Yn72.js} +224 -545
- package/dist/{workspace-f2DBLmPZ.d.ts → workspace-Xddf4G1B.d.ts} +1 -1
- package/package.json +20 -38
- package/dist/chunk-8H4AJuhK.js +0 -14
- package/dist/cli.d.ts +0 -31
- package/dist/cli.js +0 -303
- package/dist/cloudflare-env-CKxUs2fa.js +0 -20
- package/dist/glob-DeH0dzZX.js +0 -23
- package/dist/host-I-_vDs05.js +0 -370
- package/dist/lifecycle-Lhk3dAMt.js +0 -176
- package/dist/providers/cloudflare/artifacts-store.d.ts +0 -6
- package/dist/providers/cloudflare/artifacts-store.js +0 -2
- package/dist/providers/vercel/blob-store.d.ts +0 -6
- package/dist/providers/vercel/blob-store.js +0 -235
- package/dist/registry-C7DMdBXN.js +0 -74
- package/dist/utils-BPdaCyI6.js +0 -55
- package/dist/vite-NWC9mFjI.js +0 -1882
package/dist/vite-NWC9mFjI.js
DELETED
|
@@ -1,1882 +0,0 @@
|
|
|
1
|
-
import { o as normalizeSafeWorkspacePath } from "./path-CNI6wKIU.js";
|
|
2
|
-
import { t as normalizeWorkspaceOptions } from "./config-DCQ6y30R.js";
|
|
3
|
-
import { s as createMemoryWorkspaceStore } from "./provider-CeQciesl.js";
|
|
4
|
-
import { installHostedWorkspaceRuntime } from "./hosted.js";
|
|
5
|
-
import { t as normalizeWorkspaceDefinition } from "./registry-C7DMdBXN.js";
|
|
6
|
-
import { ensureWorkspaceDevToken, refreshWorkspaceDevToken, runWorkspaceDevCommand, validateWorkspaceDevToken, workspaceDevHeader, workspaceDevRoute, workspaceDevTokenServerId } from "./server.js";
|
|
7
|
-
import { createWorkspaceCliContributor } from "./cli.js";
|
|
8
|
-
import { installHostedVercelBlobWorkspaceRuntime } from "./hosted-vercel-blob.js";
|
|
9
|
-
import { n as syncWorkspaceDefinition } from "./lifecycle-Lhk3dAMt.js";
|
|
10
|
-
import { createRequire } from "node:module";
|
|
11
|
-
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
12
|
-
import { createHash } from "node:crypto";
|
|
13
|
-
import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
14
|
-
import { access, copyFile, cp, mkdir, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
|
|
15
|
-
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
16
|
-
import { renderMarkdownTemplate } from "@vite-hub/markdown-template";
|
|
17
|
-
import { markdownTemplateRegistryId, markdownTemplateRegistryPath, parseMarkdownTemplateRequest } from "@vite-hub/markdown-template/internal/vite";
|
|
18
|
-
import { resolveModulePath } from "exsolve";
|
|
19
|
-
import { createJiti } from "jiti";
|
|
20
|
-
//#region ../internal/src/build/provider-output-config.ts
|
|
21
|
-
function isProviderJsonArray(value, ancestors) {
|
|
22
|
-
if (Object.getPrototypeOf(value) !== Array.prototype || ancestors.has(value)) return false;
|
|
23
|
-
if (Reflect.ownKeys(value).length !== value.length + 1) return false;
|
|
24
|
-
ancestors.add(value);
|
|
25
|
-
try {
|
|
26
|
-
for (let index = 0; index < value.length; index++) {
|
|
27
|
-
const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
|
|
28
|
-
if (!descriptor?.enumerable || !("value" in descriptor) || !isProviderJsonValue(descriptor.value, ancestors)) return false;
|
|
29
|
-
}
|
|
30
|
-
return true;
|
|
31
|
-
} finally {
|
|
32
|
-
ancestors.delete(value);
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
function isProviderJsonRecordValue(value, ancestors) {
|
|
36
|
-
const prototype = Object.getPrototypeOf(value);
|
|
37
|
-
if (prototype !== Object.prototype && prototype !== null || ancestors.has(value)) return false;
|
|
38
|
-
ancestors.add(value);
|
|
39
|
-
try {
|
|
40
|
-
return Reflect.ownKeys(value).every((key) => {
|
|
41
|
-
if (typeof key !== "string") return false;
|
|
42
|
-
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
43
|
-
return descriptor?.enumerable === true && "value" in descriptor && isProviderJsonValue(descriptor.value, ancestors);
|
|
44
|
-
});
|
|
45
|
-
} finally {
|
|
46
|
-
ancestors.delete(value);
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
function isProviderJsonValue(value, ancestors) {
|
|
50
|
-
if (value === null || typeof value === "boolean" || typeof value === "string") return true;
|
|
51
|
-
if (typeof value === "number") return Number.isFinite(value);
|
|
52
|
-
if (Array.isArray(value)) return isProviderJsonArray(value, ancestors);
|
|
53
|
-
return typeof value === "object" && isProviderJsonRecordValue(value, ancestors);
|
|
54
|
-
}
|
|
55
|
-
function isProviderJsonRecord(value) {
|
|
56
|
-
try {
|
|
57
|
-
return typeof value === "object" && value !== null && !Array.isArray(value) && isProviderJsonRecordValue(value, /* @__PURE__ */ new Set());
|
|
58
|
-
} catch {
|
|
59
|
-
return false;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
function assertProviderJsonRecord(value) {
|
|
63
|
-
if (!isProviderJsonRecord(value)) throw new TypeError("[vitehub] Provider output config must be a JSON object.");
|
|
64
|
-
}
|
|
65
|
-
function isFileNotFoundError(error) {
|
|
66
|
-
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
67
|
-
}
|
|
68
|
-
async function readProviderJsonRecord(file) {
|
|
69
|
-
try {
|
|
70
|
-
const parsed = JSON.parse(await readFile(file, "utf8"));
|
|
71
|
-
assertProviderJsonRecord(parsed);
|
|
72
|
-
return parsed;
|
|
73
|
-
} catch (error) {
|
|
74
|
-
if (isFileNotFoundError(error)) return;
|
|
75
|
-
throw error;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
function deleteOwnedFields(value, ownership) {
|
|
79
|
-
const next = { ...value };
|
|
80
|
-
for (const key of ownership.keys ?? []) delete next[key];
|
|
81
|
-
for (const field of Object.keys(ownership.arrays ?? {})) delete next[field];
|
|
82
|
-
return next;
|
|
83
|
-
}
|
|
84
|
-
function getKeyedArrayEntryValue(value, key) {
|
|
85
|
-
if (!isProviderJsonRecord(value)) return;
|
|
86
|
-
const entryValue = value[key];
|
|
87
|
-
return entryValue === null || typeof entryValue === "boolean" || typeof entryValue === "number" || typeof entryValue === "string" ? entryValue : void 0;
|
|
88
|
-
}
|
|
89
|
-
function preserveUnownedKeyedArrayEntries(value, ownership, replacements = []) {
|
|
90
|
-
const current = Array.isArray(value) ? value : [];
|
|
91
|
-
const replacementKeys = replacements.flatMap((entry) => {
|
|
92
|
-
const key = getKeyedArrayEntryValue(entry, ownership.key);
|
|
93
|
-
return key === void 0 ? [] : [key];
|
|
94
|
-
});
|
|
95
|
-
const ownedKeys = new Set([...ownership.values ?? [], ...replacementKeys]);
|
|
96
|
-
return current.filter((entry) => {
|
|
97
|
-
const key = getKeyedArrayEntryValue(entry, ownership.key);
|
|
98
|
-
return key === void 0 || !ownedKeys.has(key);
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
function mergeOwnedArrays(existing, value, arrays) {
|
|
102
|
-
const next = { ...value };
|
|
103
|
-
for (const [field, ownership] of Object.entries(arrays ?? {})) {
|
|
104
|
-
const incoming = Array.isArray(value[field]) ? value[field] : [];
|
|
105
|
-
const merged = [...preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming), ...incoming];
|
|
106
|
-
if (merged.length) next[field] = merged;
|
|
107
|
-
else delete next[field];
|
|
108
|
-
}
|
|
109
|
-
return next;
|
|
110
|
-
}
|
|
111
|
-
async function persistProviderJsonRecord(file, value, removeIfEmpty) {
|
|
112
|
-
if (removeIfEmpty && !Object.keys(value).length) {
|
|
113
|
-
await rm(file, { force: true });
|
|
114
|
-
return;
|
|
115
|
-
}
|
|
116
|
-
await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
117
|
-
}
|
|
118
|
-
async function writeProviderOutputConfig(file, value, ownership = {}, options = {}) {
|
|
119
|
-
await persistProviderJsonRecord(file, mergeProviderOutputConfig(await readProviderJsonRecord(file) ?? {}, value, ownership), options.removeIfEmpty === true);
|
|
120
|
-
}
|
|
121
|
-
function mergeProviderOutputConfig(existing, value, ownership = {}) {
|
|
122
|
-
assertProviderJsonRecord(existing);
|
|
123
|
-
assertProviderJsonRecord(value);
|
|
124
|
-
return {
|
|
125
|
-
...deleteOwnedFields(existing, ownership),
|
|
126
|
-
...mergeOwnedArrays(existing, value, ownership.arrays)
|
|
127
|
-
};
|
|
128
|
-
}
|
|
129
|
-
async function cleanProviderOutputConfig(file, ownership) {
|
|
130
|
-
if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
|
|
131
|
-
const existing = await readProviderJsonRecord(file);
|
|
132
|
-
if (!existing) return;
|
|
133
|
-
const next = deleteOwnedFields(existing, ownership);
|
|
134
|
-
let changed = (ownership.keys ?? []).some((key) => key in existing);
|
|
135
|
-
for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
|
|
136
|
-
if (!(field in existing)) continue;
|
|
137
|
-
const current = existing[field];
|
|
138
|
-
const preserved = preserveUnownedKeyedArrayEntries(current, arrayOwnership);
|
|
139
|
-
changed ||= !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
|
|
140
|
-
if (preserved.length) next[field] = preserved;
|
|
141
|
-
}
|
|
142
|
-
if (!changed) return;
|
|
143
|
-
await persistProviderJsonRecord(file, next, true);
|
|
144
|
-
}
|
|
145
|
-
//#endregion
|
|
146
|
-
//#region ../internal/src/build/user-entry.ts
|
|
147
|
-
function toSafeAppName(rootDir) {
|
|
148
|
-
return basename(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
|
|
149
|
-
}
|
|
150
|
-
//#endregion
|
|
151
|
-
//#region ../internal/src/build/cloudflare.ts
|
|
152
|
-
function createDefaultCloudflareOutputRoot(rootDir) {
|
|
153
|
-
return resolve(rootDir, "dist", toSafeAppName(rootDir));
|
|
154
|
-
}
|
|
155
|
-
async function writeCloudflareWranglerConfig(options) {
|
|
156
|
-
const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
|
|
157
|
-
const configFile = resolve(outputRoot, "wrangler.json");
|
|
158
|
-
if (!options.wranglerConfig) {
|
|
159
|
-
await cleanProviderOutputConfig(configFile, options.wranglerConfigOwnership ?? {});
|
|
160
|
-
return;
|
|
161
|
-
}
|
|
162
|
-
await mkdir(outputRoot, { recursive: true });
|
|
163
|
-
await writeProviderOutputConfig(configFile, options.wranglerConfig, options.wranglerConfigOwnership, { removeIfEmpty: true });
|
|
164
|
-
}
|
|
165
|
-
//#endregion
|
|
166
|
-
//#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
|
|
167
|
-
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
|
|
168
|
-
function normalizeWindowsPath(input = "") {
|
|
169
|
-
if (!input) return input;
|
|
170
|
-
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
|
|
171
|
-
}
|
|
172
|
-
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
|
|
173
|
-
const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
|
|
174
|
-
const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
|
|
175
|
-
function cwd() {
|
|
176
|
-
if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
|
|
177
|
-
return "/";
|
|
178
|
-
}
|
|
179
|
-
const resolve$1 = function(...arguments_) {
|
|
180
|
-
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
|
|
181
|
-
let resolvedPath = "";
|
|
182
|
-
let resolvedAbsolute = false;
|
|
183
|
-
for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
|
|
184
|
-
const path = index >= 0 ? arguments_[index] : cwd();
|
|
185
|
-
if (!path || path.length === 0) continue;
|
|
186
|
-
resolvedPath = `${path}/${resolvedPath}`;
|
|
187
|
-
resolvedAbsolute = isAbsolute$1(path);
|
|
188
|
-
}
|
|
189
|
-
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
|
|
190
|
-
if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
|
|
191
|
-
return resolvedPath.length > 0 ? resolvedPath : ".";
|
|
192
|
-
};
|
|
193
|
-
function normalizeString(path, allowAboveRoot) {
|
|
194
|
-
let res = "";
|
|
195
|
-
let lastSegmentLength = 0;
|
|
196
|
-
let lastSlash = -1;
|
|
197
|
-
let dots = 0;
|
|
198
|
-
let char = null;
|
|
199
|
-
for (let index = 0; index <= path.length; ++index) {
|
|
200
|
-
if (index < path.length) char = path[index];
|
|
201
|
-
else if (char === "/") break;
|
|
202
|
-
else char = "/";
|
|
203
|
-
if (char === "/") {
|
|
204
|
-
if (lastSlash === index - 1 || dots === 1);
|
|
205
|
-
else if (dots === 2) {
|
|
206
|
-
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
|
|
207
|
-
if (res.length > 2) {
|
|
208
|
-
const lastSlashIndex = res.lastIndexOf("/");
|
|
209
|
-
if (lastSlashIndex === -1) {
|
|
210
|
-
res = "";
|
|
211
|
-
lastSegmentLength = 0;
|
|
212
|
-
} else {
|
|
213
|
-
res = res.slice(0, lastSlashIndex);
|
|
214
|
-
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
|
|
215
|
-
}
|
|
216
|
-
lastSlash = index;
|
|
217
|
-
dots = 0;
|
|
218
|
-
continue;
|
|
219
|
-
} else if (res.length > 0) {
|
|
220
|
-
res = "";
|
|
221
|
-
lastSegmentLength = 0;
|
|
222
|
-
lastSlash = index;
|
|
223
|
-
dots = 0;
|
|
224
|
-
continue;
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
if (allowAboveRoot) {
|
|
228
|
-
res += res.length > 0 ? "/.." : "..";
|
|
229
|
-
lastSegmentLength = 2;
|
|
230
|
-
}
|
|
231
|
-
} else {
|
|
232
|
-
if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
|
|
233
|
-
else res = path.slice(lastSlash + 1, index);
|
|
234
|
-
lastSegmentLength = index - lastSlash - 1;
|
|
235
|
-
}
|
|
236
|
-
lastSlash = index;
|
|
237
|
-
dots = 0;
|
|
238
|
-
} else if (char === "." && dots !== -1) ++dots;
|
|
239
|
-
else dots = -1;
|
|
240
|
-
}
|
|
241
|
-
return res;
|
|
242
|
-
}
|
|
243
|
-
const isAbsolute$1 = function(p) {
|
|
244
|
-
return _IS_ABSOLUTE_RE.test(p);
|
|
245
|
-
};
|
|
246
|
-
const relative$1 = function(from, to) {
|
|
247
|
-
const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
|
248
|
-
const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
|
249
|
-
if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
|
|
250
|
-
const _fromCopy = [..._from];
|
|
251
|
-
for (const segment of _fromCopy) {
|
|
252
|
-
if (_to[0] !== segment) break;
|
|
253
|
-
_from.shift();
|
|
254
|
-
_to.shift();
|
|
255
|
-
}
|
|
256
|
-
return [..._from.map(() => ".."), ..._to].join("/");
|
|
257
|
-
};
|
|
258
|
-
const dirname$1 = function(p) {
|
|
259
|
-
const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
|
|
260
|
-
if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
|
|
261
|
-
return segments.join("/") || (isAbsolute$1(p) ? "/" : ".");
|
|
262
|
-
};
|
|
263
|
-
//#endregion
|
|
264
|
-
//#region ../internal/src/build/vite.ts
|
|
265
|
-
const generatedViteHubFilesPattern = "**/.vitehub/**";
|
|
266
|
-
const projectRootDirectoryMarkers = [
|
|
267
|
-
["server", "agents"],
|
|
268
|
-
["server", "schedules"],
|
|
269
|
-
["server", "templates"],
|
|
270
|
-
["server", "workspaces"]
|
|
271
|
-
];
|
|
272
|
-
const projectRootDefinitionFileMarkers = [
|
|
273
|
-
".ts",
|
|
274
|
-
".mts",
|
|
275
|
-
".cts",
|
|
276
|
-
".js",
|
|
277
|
-
".mjs",
|
|
278
|
-
".cjs"
|
|
279
|
-
].flatMap((extension) => [["server", `email${extension}`], [`server.email${extension}`]]);
|
|
280
|
-
const projectRootFileMarkers = [["package.json"]];
|
|
281
|
-
const VITEHUB_ENV_PUBLIC_ID = "#vitehub/env/public";
|
|
282
|
-
const VITEHUB_ENV_SERVER_ID = "#vitehub/env/server";
|
|
283
|
-
function createNoExternalMerger(packageName) {
|
|
284
|
-
return (current) => {
|
|
285
|
-
if (current === true) return true;
|
|
286
|
-
if (!current) return [packageName];
|
|
287
|
-
const values = Array.isArray(current) ? current : [current];
|
|
288
|
-
return values.includes(packageName) ? values : [...values, packageName];
|
|
289
|
-
};
|
|
290
|
-
}
|
|
291
|
-
function isServerEnvironment(name, config) {
|
|
292
|
-
return name === "ssr" || config.consumer === "server";
|
|
293
|
-
}
|
|
294
|
-
function shouldSkipViteProviderBuild(command, mode) {
|
|
295
|
-
return command === "serve" || mode === "e2e";
|
|
296
|
-
}
|
|
297
|
-
function mergeGeneratedViteHubWatchIgnored(ignored) {
|
|
298
|
-
if (!ignored) return [generatedViteHubFilesPattern];
|
|
299
|
-
if (Array.isArray(ignored)) return ignored.includes(generatedViteHubFilesPattern) ? ignored : [...ignored, generatedViteHubFilesPattern];
|
|
300
|
-
return [ignored, generatedViteHubFilesPattern];
|
|
301
|
-
}
|
|
302
|
-
function resolveViteHubProjectRoot(root, options = {}) {
|
|
303
|
-
const resolvedRoot = resolve(root);
|
|
304
|
-
if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
|
|
305
|
-
if (basename(resolvedRoot) === "app") {
|
|
306
|
-
const parent = dirname(resolvedRoot);
|
|
307
|
-
if (hasProjectRootDirectoryMarker(parent) || hasProjectRootDefinitionFileMarker(parent)) return parent;
|
|
308
|
-
}
|
|
309
|
-
let current = resolvedRoot;
|
|
310
|
-
while (true) {
|
|
311
|
-
if (hasProjectRootMarker(current)) return current;
|
|
312
|
-
const parent = dirname(current);
|
|
313
|
-
if (parent === current) return resolvedRoot;
|
|
314
|
-
current = parent;
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
function hasProjectRootDirectoryMarker(root) {
|
|
318
|
-
for (const marker of projectRootDirectoryMarkers) try {
|
|
319
|
-
if (statSync(resolve(root, ...marker)).isDirectory()) return true;
|
|
320
|
-
} catch (error) {
|
|
321
|
-
if (error.code !== "ENOENT") throw error;
|
|
322
|
-
}
|
|
323
|
-
return false;
|
|
324
|
-
}
|
|
325
|
-
function hasProjectRootMarker(root) {
|
|
326
|
-
if (hasProjectRootDirectoryMarker(root)) return true;
|
|
327
|
-
if (hasProjectRootDefinitionFileMarker(root)) return true;
|
|
328
|
-
for (const marker of projectRootFileMarkers) try {
|
|
329
|
-
if (statSync(resolve(root, ...marker)).isFile()) return true;
|
|
330
|
-
} catch (error) {
|
|
331
|
-
if (error.code !== "ENOENT") throw error;
|
|
332
|
-
}
|
|
333
|
-
return false;
|
|
334
|
-
}
|
|
335
|
-
function hasProjectRootDefinitionFileMarker(root) {
|
|
336
|
-
for (const marker of projectRootDefinitionFileMarkers) try {
|
|
337
|
-
if (statSync(resolve(root, ...marker)).isFile()) return true;
|
|
338
|
-
} catch (error) {
|
|
339
|
-
if (error.code !== "ENOENT") throw error;
|
|
340
|
-
}
|
|
341
|
-
return false;
|
|
342
|
-
}
|
|
343
|
-
function viteHubEnvPublicModulePath(root) {
|
|
344
|
-
return resolve(root, ".vitehub", "env", "public.mjs");
|
|
345
|
-
}
|
|
346
|
-
function viteHubEnvServerModulePath(root) {
|
|
347
|
-
return resolve(root, ".vitehub", "env", "server.mjs");
|
|
348
|
-
}
|
|
349
|
-
function createViteHubEnvImportAliases(root) {
|
|
350
|
-
return {
|
|
351
|
-
[VITEHUB_ENV_PUBLIC_ID]: viteHubEnvPublicModulePath(root),
|
|
352
|
-
[VITEHUB_ENV_SERVER_ID]: viteHubEnvServerModulePath(root)
|
|
353
|
-
};
|
|
354
|
-
}
|
|
355
|
-
//#endregion
|
|
356
|
-
//#region ../internal/src/build/deployment-output.ts
|
|
357
|
-
function createDefaultVercelOutputRoot(rootDir) {
|
|
358
|
-
return resolve(rootDir, ".vercel", "output");
|
|
359
|
-
}
|
|
360
|
-
const VITEHUB_MODES = {
|
|
361
|
-
e2e: "e2e",
|
|
362
|
-
blob: "blob",
|
|
363
|
-
chat: "chat",
|
|
364
|
-
db: "db",
|
|
365
|
-
env: "env",
|
|
366
|
-
kv: "kv",
|
|
367
|
-
queue: "queue",
|
|
368
|
-
schedule: "schedule",
|
|
369
|
-
sandbox: "sandbox",
|
|
370
|
-
workspace: "workspace",
|
|
371
|
-
workflow: "workflow"
|
|
372
|
-
};
|
|
373
|
-
function isViteCli(argv) {
|
|
374
|
-
return argv.some((arg) => /(?:^|[/\\])vite(?:\.[cm]?js)?$/.test(arg) || arg === "vite");
|
|
375
|
-
}
|
|
376
|
-
function getViteCliMode(argv = process.argv) {
|
|
377
|
-
if (!isViteCli(argv)) return;
|
|
378
|
-
const modes = new Set(Object.values(VITEHUB_MODES));
|
|
379
|
-
for (let index = 0; index < argv.length; index += 1) {
|
|
380
|
-
const arg = argv[index];
|
|
381
|
-
const mode = arg === "--mode" || arg === "-m" ? argv[index + 1] : arg.startsWith("--mode=") ? arg.slice(7) : void 0;
|
|
382
|
-
if (mode && modes.has(mode)) return mode;
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
function getViteMode(env = process.env) {
|
|
386
|
-
return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
|
|
387
|
-
}
|
|
388
|
-
//#endregion
|
|
389
|
-
//#region ../internal/src/build/vercel-runtime-packages.ts
|
|
390
|
-
const runtimeExportConditions = new Set([
|
|
391
|
-
"default",
|
|
392
|
-
"import",
|
|
393
|
-
"module",
|
|
394
|
-
"node",
|
|
395
|
-
"node-addons",
|
|
396
|
-
"require"
|
|
397
|
-
]);
|
|
398
|
-
let nodeFileTracePromise;
|
|
399
|
-
async function copyVercelFunctionRuntimePackages(options) {
|
|
400
|
-
if (!options.packages.length) return;
|
|
401
|
-
const serverDir = resolve(options.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir), "functions", options.serverFunctionName ?? "__server.func");
|
|
402
|
-
try {
|
|
403
|
-
await access(serverDir);
|
|
404
|
-
} catch (error) {
|
|
405
|
-
if (error.code === "ENOENT") return;
|
|
406
|
-
throw error;
|
|
407
|
-
}
|
|
408
|
-
const copied = /* @__PURE__ */ new Set();
|
|
409
|
-
const outputNodeModules = resolve(serverDir, "node_modules");
|
|
410
|
-
for (const runtimePackage of options.packages) {
|
|
411
|
-
const resolveFrom = runtimePackage.resolveFrom ?? join(options.rootDir, "package.json");
|
|
412
|
-
const resolver = createRequire(resolveFrom);
|
|
413
|
-
await copyPackageToNodeModules(runtimePackage.name, resolver, dirname(resolveFrom), outputNodeModules, copied, runtimePackage);
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
async function copyPackageToNodeModules(name, resolver, fromDir, outputNodeModules, copied, options = { name }) {
|
|
417
|
-
const packageJsonPath = await resolvePackageJson(name, resolver, fromDir);
|
|
418
|
-
if (!packageJsonPath) {
|
|
419
|
-
if (options.optional) return;
|
|
420
|
-
throw new Error(`Could not resolve package.json for ${name}.`);
|
|
421
|
-
}
|
|
422
|
-
const resolvedPackageJsonPath = await realpath(packageJsonPath);
|
|
423
|
-
const packageDir = dirname(resolvedPackageJsonPath);
|
|
424
|
-
const packageJson = JSON.parse(await readFile(resolvedPackageJsonPath, "utf8"));
|
|
425
|
-
const packageKey = `${name}\0${resolvedPackageJsonPath}`;
|
|
426
|
-
if (!copied.has(packageKey)) {
|
|
427
|
-
copied.add(packageKey);
|
|
428
|
-
const targetDir = join(outputNodeModules, ...name.split("/"));
|
|
429
|
-
await rm(targetDir, {
|
|
430
|
-
force: true,
|
|
431
|
-
recursive: true
|
|
432
|
-
});
|
|
433
|
-
if (!await copyTracedPackageFiles(name, resolver, packageDir, resolvedPackageJsonPath, packageJson, targetDir)) await copyPackageDirectory(packageDir, targetDir);
|
|
434
|
-
}
|
|
435
|
-
const packageRequire = createRequire(resolvedPackageJsonPath);
|
|
436
|
-
const dependencyNames = new Set(Object.keys(packageJson.dependencies || {}));
|
|
437
|
-
if (options.includePeerDependencies) {
|
|
438
|
-
for (const dependencyName of Object.keys(packageJson.peerDependencies || {})) if (!packageJson.peerDependenciesMeta?.[dependencyName]?.optional) dependencyNames.add(dependencyName);
|
|
439
|
-
}
|
|
440
|
-
for (const dependencyName of dependencyNames) await copyPackageToNodeModules(dependencyName, packageRequire, packageDir, outputNodeModules, copied, {
|
|
441
|
-
includePeerDependencies: options.includePeerDependencies,
|
|
442
|
-
name: dependencyName
|
|
443
|
-
});
|
|
444
|
-
}
|
|
445
|
-
async function copyTracedPackageFiles(name, resolver, packageDir, packageJsonPath, packageJson, targetDir) {
|
|
446
|
-
const entries = await resolvePackageTraceEntries(name, resolver, packageDir, packageJson);
|
|
447
|
-
if (!entries) return false;
|
|
448
|
-
const { fileList } = await (await loadNodeFileTrace())([...entries], {
|
|
449
|
-
base: packageDir,
|
|
450
|
-
conditions: ["node"],
|
|
451
|
-
exportsOnly: true,
|
|
452
|
-
processCwd: packageDir
|
|
453
|
-
});
|
|
454
|
-
fileList.add(relative(packageDir, packageJsonPath));
|
|
455
|
-
for (const file of fileList) {
|
|
456
|
-
const source = resolve(packageDir, file);
|
|
457
|
-
if (!isInsideDirectory(packageDir, source) || hasNodeModulesSegment(file)) continue;
|
|
458
|
-
if (!(await stat(source)).isFile()) continue;
|
|
459
|
-
const target = resolve(targetDir, file);
|
|
460
|
-
await mkdir(dirname(target), { recursive: true });
|
|
461
|
-
await copyFile(source, target);
|
|
462
|
-
}
|
|
463
|
-
return true;
|
|
464
|
-
}
|
|
465
|
-
async function copyPackageDirectory(packageDir, targetDir) {
|
|
466
|
-
await mkdir(dirname(targetDir), { recursive: true });
|
|
467
|
-
await cp(packageDir, targetDir, {
|
|
468
|
-
dereference: true,
|
|
469
|
-
filter: (source) => !hasNodeModulesSegment(relative(packageDir, source)),
|
|
470
|
-
recursive: true
|
|
471
|
-
});
|
|
472
|
-
}
|
|
473
|
-
async function loadNodeFileTrace() {
|
|
474
|
-
nodeFileTracePromise ??= import("@vercel/nft").then(({ nodeFileTrace }) => nodeFileTrace);
|
|
475
|
-
return nodeFileTracePromise;
|
|
476
|
-
}
|
|
477
|
-
async function resolvePackageTraceEntries(name, resolver, packageDir, packageJson) {
|
|
478
|
-
const entryCandidates = /* @__PURE__ */ new Set();
|
|
479
|
-
if (packageJson.exports) {
|
|
480
|
-
const exportedTargets = collectRuntimeExportTargets(packageJson.exports);
|
|
481
|
-
if (!exportedTargets) return void 0;
|
|
482
|
-
for (const target of exportedTargets) entryCandidates.add(resolve(packageDir, target));
|
|
483
|
-
} else {
|
|
484
|
-
try {
|
|
485
|
-
entryCandidates.add(resolver.resolve(name));
|
|
486
|
-
} catch (error) {
|
|
487
|
-
if (!isPackageResolutionMiss(error)) throw error;
|
|
488
|
-
}
|
|
489
|
-
if (packageJson.main) entryCandidates.add(resolve(packageDir, packageJson.main));
|
|
490
|
-
if (packageJson.module) entryCandidates.add(resolve(packageDir, packageJson.module));
|
|
491
|
-
entryCandidates.add(resolve(packageDir, "index.js"));
|
|
492
|
-
}
|
|
493
|
-
const entries = [];
|
|
494
|
-
for (const candidate of entryCandidates) try {
|
|
495
|
-
const candidateStat = await stat(candidate);
|
|
496
|
-
if (candidateStat.isFile()) entries.push(candidate);
|
|
497
|
-
else if (candidateStat.isDirectory()) return void 0;
|
|
498
|
-
} catch (error) {
|
|
499
|
-
if (error.code !== "ENOENT") throw error;
|
|
500
|
-
}
|
|
501
|
-
return entries.length ? entries : void 0;
|
|
502
|
-
}
|
|
503
|
-
function collectRuntimeExportTargets(exportsValue, condition) {
|
|
504
|
-
if (typeof exportsValue === "string") {
|
|
505
|
-
if (condition === "types") return /* @__PURE__ */ new Set();
|
|
506
|
-
if (exportsValue.includes("*")) return void 0;
|
|
507
|
-
return exportsValue.startsWith("./") ? new Set([exportsValue]) : /* @__PURE__ */ new Set();
|
|
508
|
-
}
|
|
509
|
-
if (Array.isArray(exportsValue)) {
|
|
510
|
-
const targets = /* @__PURE__ */ new Set();
|
|
511
|
-
for (const entry of exportsValue) {
|
|
512
|
-
const entryTargets = collectRuntimeExportTargets(entry, condition);
|
|
513
|
-
if (!entryTargets) return void 0;
|
|
514
|
-
for (const target of entryTargets) targets.add(target);
|
|
515
|
-
}
|
|
516
|
-
return targets;
|
|
517
|
-
}
|
|
518
|
-
if (typeof exportsValue !== "object" || exportsValue === null) return /* @__PURE__ */ new Set();
|
|
519
|
-
const targets = /* @__PURE__ */ new Set();
|
|
520
|
-
for (const [key, value] of Object.entries(exportsValue)) {
|
|
521
|
-
if (key === "types") continue;
|
|
522
|
-
if (!key.startsWith(".") && !runtimeExportConditions.has(key)) continue;
|
|
523
|
-
const entryTargets = collectRuntimeExportTargets(value, key);
|
|
524
|
-
if (!entryTargets) return void 0;
|
|
525
|
-
for (const target of entryTargets) targets.add(target);
|
|
526
|
-
}
|
|
527
|
-
return targets;
|
|
528
|
-
}
|
|
529
|
-
function hasNodeModulesSegment(path) {
|
|
530
|
-
return path.split(/[\\/]/).includes("node_modules");
|
|
531
|
-
}
|
|
532
|
-
function isInsideDirectory(parent, child) {
|
|
533
|
-
const childRelativePath = relative(parent, child);
|
|
534
|
-
return childRelativePath === "" || !childRelativePath.startsWith(`..${sep}`) && childRelativePath !== ".." && !isAbsolute(childRelativePath);
|
|
535
|
-
}
|
|
536
|
-
async function resolvePackageJson(name, resolver, fromDir) {
|
|
537
|
-
try {
|
|
538
|
-
return resolver.resolve(`${name}/package.json`);
|
|
539
|
-
} catch (error) {
|
|
540
|
-
if (!isPackageResolutionMiss(error)) throw error;
|
|
541
|
-
}
|
|
542
|
-
try {
|
|
543
|
-
let current = dirname(resolver.resolve(name));
|
|
544
|
-
while (current !== dirname(current)) {
|
|
545
|
-
const candidate = join(current, "package.json");
|
|
546
|
-
try {
|
|
547
|
-
await access(candidate);
|
|
548
|
-
if (JSON.parse(await readFile(candidate, "utf8")).name === name) return candidate;
|
|
549
|
-
} catch (error) {
|
|
550
|
-
if (error.code !== "ENOENT") throw error;
|
|
551
|
-
}
|
|
552
|
-
current = dirname(current);
|
|
553
|
-
}
|
|
554
|
-
} catch (error) {
|
|
555
|
-
if (!isPackageResolutionMiss(error)) throw error;
|
|
556
|
-
}
|
|
557
|
-
let current = fromDir;
|
|
558
|
-
while (current !== dirname(current)) {
|
|
559
|
-
const candidate = join(current, "node_modules", ...name.split("/"), "package.json");
|
|
560
|
-
try {
|
|
561
|
-
await access(candidate);
|
|
562
|
-
return candidate;
|
|
563
|
-
} catch (error) {
|
|
564
|
-
if (error.code !== "ENOENT") throw error;
|
|
565
|
-
}
|
|
566
|
-
current = dirname(current);
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
function isPackageResolutionMiss(error) {
|
|
570
|
-
const code = error?.code;
|
|
571
|
-
return code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED";
|
|
572
|
-
}
|
|
573
|
-
//#endregion
|
|
574
|
-
//#region ../internal/src/build/paths.ts
|
|
575
|
-
function createImportPath(fromFile, targetFile) {
|
|
576
|
-
const importPath = relative$1(realpathIfExists(dirname$1(fromFile)), realpathIfExists(targetFile));
|
|
577
|
-
return importPath.startsWith(".") ? importPath : `./${importPath}`;
|
|
578
|
-
}
|
|
579
|
-
function realpathIfExists(path) {
|
|
580
|
-
try {
|
|
581
|
-
return realpathSync.native(path);
|
|
582
|
-
} catch {
|
|
583
|
-
return resolve$1(path);
|
|
584
|
-
}
|
|
585
|
-
}
|
|
586
|
-
//#endregion
|
|
587
|
-
//#region src/build/assets.ts
|
|
588
|
-
function shouldBundleWorkspaceAssets(assets, name) {
|
|
589
|
-
return assets === void 0 || assets === true || Array.isArray(assets) && assets.includes(name);
|
|
590
|
-
}
|
|
591
|
-
function assetModuleName(workspace, path, content) {
|
|
592
|
-
return `${createHash("sha256").update(`${workspace}\0${path}\0`).update(content).digest("hex").slice(0, 16)}.mjs`;
|
|
593
|
-
}
|
|
594
|
-
function serializeContent(content) {
|
|
595
|
-
if (typeof content === "string") return JSON.stringify(content);
|
|
596
|
-
return `new Uint8Array(${JSON.stringify([...content])})`;
|
|
597
|
-
}
|
|
598
|
-
function generatedViteHubImportAliases(rootDir) {
|
|
599
|
-
const aliases = {};
|
|
600
|
-
for (const [id, path] of Object.entries(createViteHubEnvImportAliases(rootDir))) if (existsSync(path)) aliases[id] = path;
|
|
601
|
-
const templates = resolve(rootDir, markdownTemplateRegistryPath);
|
|
602
|
-
if (existsSync(templates)) aliases[markdownTemplateRegistryId] = templates;
|
|
603
|
-
return aliases;
|
|
604
|
-
}
|
|
605
|
-
const rawImportVirtualModulePrefix = "vitehub:workspace-raw:";
|
|
606
|
-
function staticTextImport(specifier) {
|
|
607
|
-
const markdownTemplate = parseMarkdownTemplateRequest(specifier);
|
|
608
|
-
if (markdownTemplate) return {
|
|
609
|
-
kind: "markdown-template",
|
|
610
|
-
path: markdownTemplate.path
|
|
611
|
-
};
|
|
612
|
-
const queryIndex = specifier.indexOf("?");
|
|
613
|
-
if (queryIndex === -1 || !/(?:^|&)raw(?:&|$)/.test(specifier.slice(queryIndex + 1))) return;
|
|
614
|
-
return {
|
|
615
|
-
kind: "raw",
|
|
616
|
-
path: specifier.slice(0, queryIndex)
|
|
617
|
-
};
|
|
618
|
-
}
|
|
619
|
-
function createRawImportTransformPlugin(importer) {
|
|
620
|
-
function rewriteRawSpecifier(path) {
|
|
621
|
-
if (!importer || path.node.source?.type !== "StringLiteral" || typeof path.node.source.value !== "string") return;
|
|
622
|
-
const textImport = staticTextImport(path.node.source.value);
|
|
623
|
-
if (!textImport) return;
|
|
624
|
-
const reference = Buffer.from(JSON.stringify([
|
|
625
|
-
importer,
|
|
626
|
-
textImport.path,
|
|
627
|
-
textImport.kind
|
|
628
|
-
])).toString("base64url");
|
|
629
|
-
path.node.source.value = `${rawImportVirtualModulePrefix}${reference}`;
|
|
630
|
-
}
|
|
631
|
-
return () => ({ visitor: {
|
|
632
|
-
ExportAllDeclaration: rewriteRawSpecifier,
|
|
633
|
-
ExportNamedDeclaration: rewriteRawSpecifier,
|
|
634
|
-
ImportDeclaration: rewriteRawSpecifier
|
|
635
|
-
} });
|
|
636
|
-
}
|
|
637
|
-
function createWorkspaceDefinitionTransform() {
|
|
638
|
-
const transformer = createJiti(import.meta.url, { fsCache: false });
|
|
639
|
-
return (options) => ({ code: transformer.transform({
|
|
640
|
-
...options,
|
|
641
|
-
babel: {
|
|
642
|
-
...options.babel,
|
|
643
|
-
plugins: [...Array.isArray(options.babel?.plugins) ? options.babel.plugins : [], createRawImportTransformPlugin(options.filename)]
|
|
644
|
-
}
|
|
645
|
-
}) });
|
|
646
|
-
}
|
|
647
|
-
function resolveWorkspaceRawSpecifier(path, rootDir) {
|
|
648
|
-
if (path.startsWith("/@fs/")) return path.slice(5);
|
|
649
|
-
if (!path.startsWith("/")) return path;
|
|
650
|
-
const rootRelativePath = path.slice(1);
|
|
651
|
-
const publicPath = join(rootDir, "public", rootRelativePath);
|
|
652
|
-
return existsSync(publicPath) ? publicPath : join(rootDir, rootRelativePath);
|
|
653
|
-
}
|
|
654
|
-
function createWorkspaceDefinitionLoader(rootDir, alias = {}) {
|
|
655
|
-
let loader;
|
|
656
|
-
const virtualModules = new Proxy(Object.create(null), {
|
|
657
|
-
get(_target, id) {
|
|
658
|
-
if (typeof id !== "string" || !id.startsWith(rawImportVirtualModulePrefix)) return;
|
|
659
|
-
const reference = id.slice(22);
|
|
660
|
-
const [importer, path, kind = "raw"] = JSON.parse(Buffer.from(reference, "base64url").toString("utf8"));
|
|
661
|
-
const specifier = resolveWorkspaceRawSpecifier(path, rootDir);
|
|
662
|
-
const templatePath = fileURLToPath(loader.esmResolve(specifier, pathToFileURL(importer).href));
|
|
663
|
-
const template = readFileSync(templatePath, "utf8");
|
|
664
|
-
return {
|
|
665
|
-
__esModule: true,
|
|
666
|
-
default: kind === "markdown-template" ? (data = {}) => renderMarkdownTemplate(template, {
|
|
667
|
-
data,
|
|
668
|
-
sourceId: templatePath,
|
|
669
|
-
resolveImport(specifier, importer) {
|
|
670
|
-
const importedPath = resolve(dirname(importer), specifier);
|
|
671
|
-
try {
|
|
672
|
-
return {
|
|
673
|
-
id: importedPath,
|
|
674
|
-
template: readFileSync(importedPath, "utf8")
|
|
675
|
-
};
|
|
676
|
-
} catch (error) {
|
|
677
|
-
if (error.code === "ENOENT") return;
|
|
678
|
-
throw error;
|
|
679
|
-
}
|
|
680
|
-
}
|
|
681
|
-
}) : template
|
|
682
|
-
};
|
|
683
|
-
},
|
|
684
|
-
has(_target, id) {
|
|
685
|
-
return typeof id === "string" && id.startsWith(rawImportVirtualModulePrefix);
|
|
686
|
-
}
|
|
687
|
-
});
|
|
688
|
-
loader = createJiti(import.meta.url, {
|
|
689
|
-
alias: {
|
|
690
|
-
...alias,
|
|
691
|
-
...generatedViteHubImportAliases(rootDir)
|
|
692
|
-
},
|
|
693
|
-
fsCache: false,
|
|
694
|
-
moduleCache: false,
|
|
695
|
-
transform: createWorkspaceDefinitionTransform(),
|
|
696
|
-
virtualModules
|
|
697
|
-
});
|
|
698
|
-
return loader;
|
|
699
|
-
}
|
|
700
|
-
async function loadDiscoveredWorkspaceDefinition(loader, definition) {
|
|
701
|
-
const mod = await loader.import(definition.path);
|
|
702
|
-
if (!mod.default) throw new TypeError(`[vitehub] Workspace definition "${definition.name}" has no default export.`);
|
|
703
|
-
return mod.default;
|
|
704
|
-
}
|
|
705
|
-
function runtimeAssetsModulePath() {
|
|
706
|
-
return resolveModulePath("../runtime/assets", {
|
|
707
|
-
extensions: [".ts", ".mts"],
|
|
708
|
-
from: import.meta.url,
|
|
709
|
-
try: true
|
|
710
|
-
}) ?? resolveModulePath("@vite-hub/workspace/internal/runtime/assets", {
|
|
711
|
-
extensions: [".js", ".mjs"],
|
|
712
|
-
from: import.meta.url
|
|
713
|
-
});
|
|
714
|
-
}
|
|
715
|
-
async function collectWorkspaceStoreAssetBundle(name, store) {
|
|
716
|
-
const entries = (await store.glob("**/*")).filter((entry) => entry.type === "file");
|
|
717
|
-
const files = [];
|
|
718
|
-
for (const entry of entries) {
|
|
719
|
-
const path = normalizeSafeWorkspacePath(entry.path);
|
|
720
|
-
const file = await store.readFile(path);
|
|
721
|
-
if (file) files.push({
|
|
722
|
-
content: file.content,
|
|
723
|
-
mediaType: file.mediaType,
|
|
724
|
-
metadata: file.metadata,
|
|
725
|
-
path
|
|
726
|
-
});
|
|
727
|
-
}
|
|
728
|
-
files.sort((a, b) => a.path.localeCompare(b.path));
|
|
729
|
-
return {
|
|
730
|
-
files,
|
|
731
|
-
name
|
|
732
|
-
};
|
|
733
|
-
}
|
|
734
|
-
async function syncDiscoveredWorkspaceAssetBundles(definitions, rootDir, options) {
|
|
735
|
-
if (!options) return [];
|
|
736
|
-
const bundles = [];
|
|
737
|
-
const workspaceConfigLoader = createWorkspaceDefinitionLoader(rootDir);
|
|
738
|
-
for (const definition of definitions) {
|
|
739
|
-
if (!shouldBundleWorkspaceAssets(options.assets, definition.name)) continue;
|
|
740
|
-
const workspace = await loadDiscoveredWorkspaceDefinition(workspaceConfigLoader, definition);
|
|
741
|
-
const store = createMemoryWorkspaceStore();
|
|
742
|
-
await syncWorkspaceDefinition({
|
|
743
|
-
...workspace,
|
|
744
|
-
name: definition.name,
|
|
745
|
-
rootDir: workspace.rootDir || rootDir,
|
|
746
|
-
sourceRootDir: workspace.sourceRootDir ?? definition.sourceRootDir,
|
|
747
|
-
store
|
|
748
|
-
}, store);
|
|
749
|
-
bundles.push(await collectWorkspaceStoreAssetBundle(definition.name, store));
|
|
750
|
-
}
|
|
751
|
-
return bundles;
|
|
752
|
-
}
|
|
753
|
-
async function writeWorkspaceAssetsRegistry(registryFile, bundles) {
|
|
754
|
-
const modulesDir = join(dirname(registryFile), "modules");
|
|
755
|
-
await rm(modulesDir, {
|
|
756
|
-
force: true,
|
|
757
|
-
recursive: true
|
|
758
|
-
});
|
|
759
|
-
await mkdir(modulesDir, { recursive: true });
|
|
760
|
-
const modulePaths = /* @__PURE__ */ new Map();
|
|
761
|
-
for (const bundle of bundles) {
|
|
762
|
-
const workspaceDir = join(modulesDir, encodeURIComponent(bundle.name));
|
|
763
|
-
await mkdir(workspaceDir, { recursive: true });
|
|
764
|
-
for (const file of bundle.files) {
|
|
765
|
-
const modulePath = join(workspaceDir, assetModuleName(bundle.name, file.path, file.content));
|
|
766
|
-
await writeFile(modulePath, `export default ${serializeContent(file.content)}\n`, "utf8");
|
|
767
|
-
modulePaths.set(`${bundle.name}\0${file.path}`, modulePath);
|
|
768
|
-
}
|
|
769
|
-
}
|
|
770
|
-
await mkdir(dirname(registryFile), { recursive: true });
|
|
771
|
-
const contents = createWorkspaceAssetsRegistryContents(registryFile, bundles, modulePaths);
|
|
772
|
-
await writeFile(registryFile, contents, "utf8");
|
|
773
|
-
return contents;
|
|
774
|
-
}
|
|
775
|
-
function createWorkspaceAssetsRegistryContents(registryFile, bundles, modulePaths = /* @__PURE__ */ new Map(), assetsModulePath = runtimeAssetsModulePath()) {
|
|
776
|
-
return [
|
|
777
|
-
`import { createWorkspaceAssets } from ${JSON.stringify(createImportPath(registryFile, assetsModulePath))}`,
|
|
778
|
-
"",
|
|
779
|
-
"const registry = {",
|
|
780
|
-
...bundles.map((bundle) => {
|
|
781
|
-
const entries = bundle.files.map((file) => {
|
|
782
|
-
const modulePath = modulePaths.get(`${bundle.name}\0${file.path}`);
|
|
783
|
-
const importPath = modulePath ? createImportPath(registryFile, modulePath) : pathToFileURL(file.path).href;
|
|
784
|
-
return ` ${JSON.stringify(file.path)}: { load: async () => (await import(${JSON.stringify(importPath)})).default, mediaType: ${JSON.stringify(file.mediaType)}, metadata: ${JSON.stringify(file.metadata)} },`;
|
|
785
|
-
});
|
|
786
|
-
return [
|
|
787
|
-
` ${JSON.stringify(bundle.name)}: createWorkspaceAssets({`,
|
|
788
|
-
...entries,
|
|
789
|
-
" }),"
|
|
790
|
-
].join("\n");
|
|
791
|
-
}),
|
|
792
|
-
"}",
|
|
793
|
-
"export default registry",
|
|
794
|
-
""
|
|
795
|
-
].join("\n");
|
|
796
|
-
}
|
|
797
|
-
//#endregion
|
|
798
|
-
//#region ../internal/src/definition-catalog.ts
|
|
799
|
-
const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
|
|
800
|
-
const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
|
|
801
|
-
const ignoredDirs = new Set([
|
|
802
|
-
"node_modules",
|
|
803
|
-
"dist",
|
|
804
|
-
".output",
|
|
805
|
-
".nuxt",
|
|
806
|
-
".vercel",
|
|
807
|
-
".git",
|
|
808
|
-
".vitehub"
|
|
809
|
-
]);
|
|
810
|
-
function createDirectoryDefinitionSource(source, scanDirs, subdir, options = {}) {
|
|
811
|
-
return {
|
|
812
|
-
...options,
|
|
813
|
-
kind: "directory",
|
|
814
|
-
scanDirs,
|
|
815
|
-
source,
|
|
816
|
-
subdir
|
|
817
|
-
};
|
|
818
|
-
}
|
|
819
|
-
function createSuffixDefinitionSource(source, roots, pattern, normalizeName, options = {}) {
|
|
820
|
-
return {
|
|
821
|
-
...options,
|
|
822
|
-
kind: "suffix",
|
|
823
|
-
normalizeName,
|
|
824
|
-
pattern,
|
|
825
|
-
roots,
|
|
826
|
-
source
|
|
827
|
-
};
|
|
828
|
-
}
|
|
829
|
-
function readDirEntries(root) {
|
|
830
|
-
try {
|
|
831
|
-
return readdirSync(root, { withFileTypes: true });
|
|
832
|
-
} catch (error) {
|
|
833
|
-
if (error.code === "ENOENT") return [];
|
|
834
|
-
throw error;
|
|
835
|
-
}
|
|
836
|
-
}
|
|
837
|
-
function listMatchingFiles(root, predicate, options = {}) {
|
|
838
|
-
const files = [];
|
|
839
|
-
for (const entry of readDirEntries(root)) {
|
|
840
|
-
const absolute = resolve$1(root, entry.name);
|
|
841
|
-
if (entry.isDirectory() && !entry.isSymbolicLink()) {
|
|
842
|
-
if (entry.name.startsWith(".")) continue;
|
|
843
|
-
if (ignoredDirs.has(entry.name)) continue;
|
|
844
|
-
files.push(...listMatchingFiles(absolute, predicate, options));
|
|
845
|
-
continue;
|
|
846
|
-
}
|
|
847
|
-
if (entry.name.startsWith(".") && !options.includeHidden) continue;
|
|
848
|
-
if (entry.isFile() && predicate(entry.name)) files.push(absolute);
|
|
849
|
-
}
|
|
850
|
-
return files.sort();
|
|
851
|
-
}
|
|
852
|
-
function listSourceFiles(root, options = {}) {
|
|
853
|
-
return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
|
|
854
|
-
}
|
|
855
|
-
function normalizePathDefinitionName(rootDir, file) {
|
|
856
|
-
return relative$1(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
|
|
857
|
-
}
|
|
858
|
-
function normalizeSuffixDefinitionName(rootDir, file, pattern, options = {}) {
|
|
859
|
-
const normalized = relative$1(rootDir, file).replace(pattern, "");
|
|
860
|
-
if (options.stripPrefix && normalized.startsWith(options.stripPrefix)) return normalized.slice(options.stripPrefix.length);
|
|
861
|
-
return normalized;
|
|
862
|
-
}
|
|
863
|
-
function sortDefinitions(definitions) {
|
|
864
|
-
return [...definitions.values()].sort((left, right) => left.name.localeCompare(right.name));
|
|
865
|
-
}
|
|
866
|
-
function registerDefinition(definitions, definition, sourceLabel) {
|
|
867
|
-
const existing = definitions.get(definition.name);
|
|
868
|
-
if (existing) throw new Error(`Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}`);
|
|
869
|
-
definitions.set(definition.name, definition);
|
|
870
|
-
}
|
|
871
|
-
function mergeDefinitions(feature, ...sources) {
|
|
872
|
-
const definitions = /* @__PURE__ */ new Map();
|
|
873
|
-
for (const source of sources) {
|
|
874
|
-
if (!source) continue;
|
|
875
|
-
for (const definition of source) {
|
|
876
|
-
const existing = definitions.get(definition.name);
|
|
877
|
-
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"})`);
|
|
878
|
-
if (!existing) definitions.set(definition.name, definition);
|
|
879
|
-
}
|
|
880
|
-
}
|
|
881
|
-
return sortDefinitions(definitions);
|
|
882
|
-
}
|
|
883
|
-
function createDefinition(source, file, name) {
|
|
884
|
-
if (source.createDefinition) return source.createDefinition({
|
|
885
|
-
file,
|
|
886
|
-
name
|
|
887
|
-
});
|
|
888
|
-
return {
|
|
889
|
-
handler: file,
|
|
890
|
-
name,
|
|
891
|
-
source: source.source
|
|
892
|
-
};
|
|
893
|
-
}
|
|
894
|
-
function scanSuffixDefinitions(feature, source) {
|
|
895
|
-
const definitions = /* @__PURE__ */ new Map();
|
|
896
|
-
for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => source.pattern.test(name), { includeHidden: source.includeHidden })) {
|
|
897
|
-
const name = source.normalizeName(root, file);
|
|
898
|
-
if (!name) continue;
|
|
899
|
-
registerDefinition(definitions, createDefinition(source, file, name), feature);
|
|
900
|
-
}
|
|
901
|
-
return sortDefinitions(definitions);
|
|
902
|
-
}
|
|
903
|
-
function scanDirectoryDefinitions(feature, source) {
|
|
904
|
-
const definitions = /* @__PURE__ */ new Map();
|
|
905
|
-
for (const scanDir of source.scanDirs) {
|
|
906
|
-
const directory = resolve$1(scanDir, source.subdir);
|
|
907
|
-
for (const file of listSourceFiles(directory, { includeHidden: source.includeHidden })) {
|
|
908
|
-
const name = source.normalizeName ? source.normalizeName(directory, file) : normalizePathDefinitionName(directory, file);
|
|
909
|
-
if (!name) continue;
|
|
910
|
-
registerDefinition(definitions, createDefinition(source, file, name), feature);
|
|
911
|
-
}
|
|
912
|
-
}
|
|
913
|
-
return sortDefinitions(definitions);
|
|
914
|
-
}
|
|
915
|
-
function discoverDefinitions$1(feature, sources) {
|
|
916
|
-
return mergeDefinitions(feature, ...sources.map((source) => source.kind === "suffix" ? scanSuffixDefinitions(feature, source) : scanDirectoryDefinitions(feature, source)));
|
|
917
|
-
}
|
|
918
|
-
async function writeFileIfChanged(file, contents) {
|
|
919
|
-
if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
|
|
920
|
-
await mkdir(resolve$1(file, ".."), { recursive: true });
|
|
921
|
-
await writeFile(file, contents, "utf8");
|
|
922
|
-
}
|
|
923
|
-
//#endregion
|
|
924
|
-
//#region src/build/workspace-config.ts
|
|
925
|
-
const workspaceSuffixPattern = /\.workspace\.(?:c|m)?[jt]s$/i;
|
|
926
|
-
const workspaceConfigPattern = /^config\.(?:c|m)?[jt]s$/i;
|
|
927
|
-
const workspaceAgentPattern = /^agent\.(?:c|m)?[jt]s$/i;
|
|
928
|
-
//#endregion
|
|
929
|
-
//#region src/build/discovery.ts
|
|
930
|
-
const configFileNameSet = new Set([
|
|
931
|
-
"config.ts",
|
|
932
|
-
"config.mts",
|
|
933
|
-
"config.cts",
|
|
934
|
-
"config.js",
|
|
935
|
-
"config.mjs",
|
|
936
|
-
"config.cjs"
|
|
937
|
-
]);
|
|
938
|
-
function stripComments(source) {
|
|
939
|
-
return source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1");
|
|
940
|
-
}
|
|
941
|
-
function isAgentConfig(file) {
|
|
942
|
-
return /\bdefineAgent\s*\(/.test(stripComments(readFileSync(file, "utf8")));
|
|
943
|
-
}
|
|
944
|
-
function isWorkspaceAgentDefinition(file) {
|
|
945
|
-
return /\bdefineAgent\s*\(\s*\{[\s\S]*?\bworkspace\s*:/.test(stripComments(readFileSync(file, "utf8")));
|
|
946
|
-
}
|
|
947
|
-
function collectDirectoriesWithConfig(root) {
|
|
948
|
-
const directories = /* @__PURE__ */ new Set();
|
|
949
|
-
const walk = (current) => {
|
|
950
|
-
let entries;
|
|
951
|
-
try {
|
|
952
|
-
entries = readdirSync(current, { withFileTypes: true });
|
|
953
|
-
} catch (error) {
|
|
954
|
-
if (error.code === "ENOENT") return;
|
|
955
|
-
throw error;
|
|
956
|
-
}
|
|
957
|
-
if (entries.some((entry) => entry.isFile() && configFileNameSet.has(entry.name))) directories.add(current.replace(/\\/g, "/"));
|
|
958
|
-
for (const entry of entries) {
|
|
959
|
-
if (!entry.isDirectory() || entry.isSymbolicLink() || entry.name.startsWith(".")) continue;
|
|
960
|
-
walk(resolve(current, entry.name));
|
|
961
|
-
}
|
|
962
|
-
};
|
|
963
|
-
walk(root);
|
|
964
|
-
return directories;
|
|
965
|
-
}
|
|
966
|
-
function resolveWorkspaceSourceRoot(file) {
|
|
967
|
-
const directory = dirname(file);
|
|
968
|
-
const workspaceDirectory = resolve(directory, "workspace");
|
|
969
|
-
try {
|
|
970
|
-
return statSync(workspaceDirectory).isDirectory() ? workspaceDirectory : directory;
|
|
971
|
-
} catch (error) {
|
|
972
|
-
if (error.code === "ENOENT") return directory;
|
|
973
|
-
throw error;
|
|
974
|
-
}
|
|
975
|
-
}
|
|
976
|
-
function createWorkspaceDefinition(source, file, name) {
|
|
977
|
-
return {
|
|
978
|
-
handler: file,
|
|
979
|
-
name,
|
|
980
|
-
path: file,
|
|
981
|
-
source,
|
|
982
|
-
sourceRootDir: resolveWorkspaceSourceRoot(file)
|
|
983
|
-
};
|
|
984
|
-
}
|
|
985
|
-
function serverWorkspaceSource(rootDir) {
|
|
986
|
-
const workspacesDir = resolve(rootDir, "server", "workspaces");
|
|
987
|
-
const agentsDir = resolve(rootDir, "server", "agents");
|
|
988
|
-
const directoryWorkspaceDirs = collectDirectoriesWithConfig(workspacesDir);
|
|
989
|
-
const normalizeDirectoryName = (workspacesRoot, file) => {
|
|
990
|
-
if (!workspaceConfigPattern.test(basename(file))) return;
|
|
991
|
-
const name = relative(workspacesRoot, dirname(file)).replace(/\\/g, "/");
|
|
992
|
-
return name && name !== "." ? name : void 0;
|
|
993
|
-
};
|
|
994
|
-
const isInsideDirectoryWorkspace = (file) => {
|
|
995
|
-
let current = dirname(file).replace(/\\/g, "/");
|
|
996
|
-
const stop = workspacesDir.replace(/\\/g, "/");
|
|
997
|
-
while (current.startsWith(stop) && current !== stop) {
|
|
998
|
-
if (directoryWorkspaceDirs.has(current)) return true;
|
|
999
|
-
current = dirname(current);
|
|
1000
|
-
}
|
|
1001
|
-
return false;
|
|
1002
|
-
};
|
|
1003
|
-
const normalizeFlatName = (workspacesRoot, file) => {
|
|
1004
|
-
if (workspaceConfigPattern.test(basename(file))) return;
|
|
1005
|
-
if (isInsideDirectoryWorkspace(file)) return;
|
|
1006
|
-
return normalizePathDefinitionName(workspacesRoot, file);
|
|
1007
|
-
};
|
|
1008
|
-
return [
|
|
1009
|
-
createDirectoryDefinitionSource("server-workspaces-directory-config", [resolve(rootDir, "server")], "workspaces", {
|
|
1010
|
-
includeHidden: true,
|
|
1011
|
-
normalizeName: normalizeDirectoryName,
|
|
1012
|
-
createDefinition: ({ file, name }) => {
|
|
1013
|
-
if (isAgentConfig(file)) throw new Error(`[vitehub] Workspace config "${file}" must use defineWorkspace(); defineAgent() belongs in server/agents/<name>/agent.ts.`);
|
|
1014
|
-
return createWorkspaceDefinition("server-workspaces-directory-config", file, name);
|
|
1015
|
-
}
|
|
1016
|
-
}),
|
|
1017
|
-
createDirectoryDefinitionSource("server-agent-workspaces", [resolve(rootDir, "server")], "agents", {
|
|
1018
|
-
includeHidden: true,
|
|
1019
|
-
normalizeName(_agentsRoot, file) {
|
|
1020
|
-
if (!workspaceAgentPattern.test(basename(file))) return;
|
|
1021
|
-
if (!isWorkspaceAgentDefinition(file)) return;
|
|
1022
|
-
const name = relative(agentsDir, dirname(file)).replace(/\\/g, "/");
|
|
1023
|
-
return name && name !== "." ? name : void 0;
|
|
1024
|
-
},
|
|
1025
|
-
createDefinition: ({ file, name }) => createWorkspaceDefinition("server-agent-workspaces", file, name)
|
|
1026
|
-
}),
|
|
1027
|
-
createDirectoryDefinitionSource("server-workspaces", [resolve(rootDir, "server")], "workspaces", {
|
|
1028
|
-
normalizeName: normalizeFlatName,
|
|
1029
|
-
createDefinition: ({ file, name }) => createWorkspaceDefinition("server-workspaces", file, name)
|
|
1030
|
-
})
|
|
1031
|
-
];
|
|
1032
|
-
}
|
|
1033
|
-
function viteWorkspaceSource(rootDir) {
|
|
1034
|
-
return [createSuffixDefinitionSource("vite-workspace-suffix", [rootDir], workspaceSuffixPattern, (root, file) => normalizeSuffixDefinitionName(root, file, workspaceSuffixPattern, { stripPrefix: "src/" }), { createDefinition: ({ file, name }) => createWorkspaceDefinition("vite-workspace-suffix", file, name) })];
|
|
1035
|
-
}
|
|
1036
|
-
function discoverViteWorkspaceDefinitions(rootDir, options = {}) {
|
|
1037
|
-
return mergeDefinitions("workspace", discoverDefinitions$1("workspace", [...viteWorkspaceSource(rootDir)]), discoverDefinitions$1("workspace", [...serverWorkspaceSource(options.serverRootDir || rootDir)]));
|
|
1038
|
-
}
|
|
1039
|
-
function createWorkspaceRegistryEntry(definition, importExpression, override) {
|
|
1040
|
-
const renderedStore = override ? JSON.stringify(override.store) : void 0;
|
|
1041
|
-
const defaultValue = [
|
|
1042
|
-
"...mod.default",
|
|
1043
|
-
...definition.sourceRootDir ? [`sourceRootDir: mod.default.sourceRootDir ?? ${JSON.stringify(definition.sourceRootDir)}`] : [],
|
|
1044
|
-
...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`] : []
|
|
1045
|
-
].join(", ");
|
|
1046
|
-
return [
|
|
1047
|
-
` ${JSON.stringify(definition.name)}: async () => {`,
|
|
1048
|
-
` const mod = await ${importExpression}`,
|
|
1049
|
-
definition.sourceRootDir || override ? ` return { ...mod, default: { ${defaultValue} } }` : " return mod",
|
|
1050
|
-
" },"
|
|
1051
|
-
].join("\n");
|
|
1052
|
-
}
|
|
1053
|
-
function createWorkspaceRegistryContents(registryFile, definitions, overrides) {
|
|
1054
|
-
const importExpression = (file) => {
|
|
1055
|
-
const importPath = relative(resolve(registryFile, ".."), file);
|
|
1056
|
-
return `import(${JSON.stringify(importPath.startsWith(".") ? importPath : `./${importPath}`)})`;
|
|
1057
|
-
};
|
|
1058
|
-
return [
|
|
1059
|
-
"const registry = {",
|
|
1060
|
-
...definitions.map((definition) => createWorkspaceRegistryEntry(definition, importExpression(definition.handler), overrides?.get(definition.name))),
|
|
1061
|
-
"}",
|
|
1062
|
-
"export default registry",
|
|
1063
|
-
""
|
|
1064
|
-
].join("\n");
|
|
1065
|
-
}
|
|
1066
|
-
function createWorkspaceVirtualRegistryContents(definitions) {
|
|
1067
|
-
return [
|
|
1068
|
-
"const registry = {",
|
|
1069
|
-
...definitions.map((definition) => createWorkspaceRegistryEntry(definition, `import(${JSON.stringify(pathToFileURL(definition.path).href)})`)),
|
|
1070
|
-
"}",
|
|
1071
|
-
"export default registry",
|
|
1072
|
-
""
|
|
1073
|
-
].join("\n");
|
|
1074
|
-
}
|
|
1075
|
-
async function createWorkspaceManifest(definitions) {
|
|
1076
|
-
return { workspaces: definitions.map((definition) => ({ name: definition.name })) };
|
|
1077
|
-
}
|
|
1078
|
-
//#endregion
|
|
1079
|
-
//#region src/build/generated-types.ts
|
|
1080
|
-
function createWorkspaceTypeAugmentation(definitions) {
|
|
1081
|
-
const nameProperties = [...new Set(definitions.map((definition) => definition.name))].sort().map((name) => ` ${JSON.stringify(name)}: true`);
|
|
1082
|
-
return [
|
|
1083
|
-
"declare global {",
|
|
1084
|
-
" interface ViteHubWorkspaceNameMap {",
|
|
1085
|
-
...nameProperties.length ? nameProperties : [" __vitehub_no_workspaces__?: never"],
|
|
1086
|
-
" }",
|
|
1087
|
-
"",
|
|
1088
|
-
" interface ViteHubWorkspaceAssetMap {",
|
|
1089
|
-
" __vitehub_no_workspace_assets__?: never",
|
|
1090
|
-
" }",
|
|
1091
|
-
"}",
|
|
1092
|
-
"",
|
|
1093
|
-
"export {}",
|
|
1094
|
-
""
|
|
1095
|
-
].join("\n");
|
|
1096
|
-
}
|
|
1097
|
-
//#endregion
|
|
1098
|
-
//#region src/build/integration.ts
|
|
1099
|
-
function workspaceAmbientTypesPath(root) {
|
|
1100
|
-
return resolve(root, ".vitehub", "types", "workspace.d.ts");
|
|
1101
|
-
}
|
|
1102
|
-
function legacyWorkspaceAmbientTypesPaths(root) {
|
|
1103
|
-
return [resolve(root, "vitehub-workspace.d.ts"), resolve(root, "src", "vitehub-workspace.d.ts")];
|
|
1104
|
-
}
|
|
1105
|
-
async function createWorkspaceBuildState(definitions) {
|
|
1106
|
-
return {
|
|
1107
|
-
manifest: await createWorkspaceManifest(definitions),
|
|
1108
|
-
registryContents: createWorkspaceVirtualRegistryContents(definitions)
|
|
1109
|
-
};
|
|
1110
|
-
}
|
|
1111
|
-
async function refreshWorkspaceAmbientTypes(root, definitions) {
|
|
1112
|
-
await Promise.all([writeFileIfChanged(workspaceAmbientTypesPath(root), createWorkspaceTypeAugmentation(definitions)), ...legacyWorkspaceAmbientTypesPaths(root).map((path) => rm(path, { force: true }))]);
|
|
1113
|
-
}
|
|
1114
|
-
async function refreshWorkspaceBuildState(root, definitions) {
|
|
1115
|
-
const state = await createWorkspaceBuildState(definitions);
|
|
1116
|
-
await refreshWorkspaceAmbientTypes(root, definitions);
|
|
1117
|
-
return state;
|
|
1118
|
-
}
|
|
1119
|
-
async function initializeWorkspaceAssetRegistry(assetsRegistryFile, _definitions = [], _rootDir = process.cwd()) {
|
|
1120
|
-
await writeWorkspaceAssetsRegistry(assetsRegistryFile, []);
|
|
1121
|
-
}
|
|
1122
|
-
async function syncWorkspaceBuildAssets(definitions, rootDir, options, assetsRegistryFile) {
|
|
1123
|
-
await writeWorkspaceAssetsRegistry(assetsRegistryFile, mergeWorkspaceAssetBundles(await syncDiscoveredWorkspaceAssetBundles(definitions, rootDir, options)));
|
|
1124
|
-
}
|
|
1125
|
-
function mergeWorkspaceAssetBundles(bundles) {
|
|
1126
|
-
const merged = /* @__PURE__ */ new Map();
|
|
1127
|
-
for (const bundle of bundles) {
|
|
1128
|
-
const existing = merged.get(bundle.name);
|
|
1129
|
-
if (!existing) {
|
|
1130
|
-
merged.set(bundle.name, {
|
|
1131
|
-
files: [...bundle.files],
|
|
1132
|
-
name: bundle.name
|
|
1133
|
-
});
|
|
1134
|
-
continue;
|
|
1135
|
-
}
|
|
1136
|
-
const files = new Map(existing.files.map((file) => [file.path, file]));
|
|
1137
|
-
for (const file of bundle.files) files.set(file.path, file);
|
|
1138
|
-
existing.files = [...files.values()].sort((a, b) => a.path.localeCompare(b.path));
|
|
1139
|
-
}
|
|
1140
|
-
return [...merged.values()].sort((a, b) => a.name.localeCompare(b.name));
|
|
1141
|
-
}
|
|
1142
|
-
//#endregion
|
|
1143
|
-
//#region ../internal/src/arrays.ts
|
|
1144
|
-
function pushUnique(arr, item, key = (value) => value) {
|
|
1145
|
-
const id = key(item);
|
|
1146
|
-
if (arr.some((entry) => key(entry) === id)) return;
|
|
1147
|
-
arr.push(item);
|
|
1148
|
-
}
|
|
1149
|
-
//#endregion
|
|
1150
|
-
//#region src/integrations/cloudflare.ts
|
|
1151
|
-
function configureCloudflareArtifacts(target, config) {
|
|
1152
|
-
if (!config) return;
|
|
1153
|
-
const store = config.store;
|
|
1154
|
-
if (store.provider !== "cloudflare-artifacts") return;
|
|
1155
|
-
target.cloudflare ||= {};
|
|
1156
|
-
target.cloudflare.wrangler ||= {};
|
|
1157
|
-
target.cloudflare.wrangler.artifacts ||= [];
|
|
1158
|
-
const artifact = {
|
|
1159
|
-
binding: store.binding || "WORKSPACE_ARTIFACTS",
|
|
1160
|
-
namespace: store.namespace || "vitehub"
|
|
1161
|
-
};
|
|
1162
|
-
const existing = target.cloudflare.wrangler.artifacts.find((entry) => entry.binding === artifact.binding);
|
|
1163
|
-
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.`);
|
|
1164
|
-
pushUnique(target.cloudflare.wrangler.artifacts, artifact, (entry) => entry.binding);
|
|
1165
|
-
}
|
|
1166
|
-
//#endregion
|
|
1167
|
-
//#region src/hosts/vite/plugin.ts
|
|
1168
|
-
const WORKSPACE_PACKAGE_NAME = "@vite-hub/workspace";
|
|
1169
|
-
const WORKSPACES_ID = "#vitehub/workspaces";
|
|
1170
|
-
const WORKSPACE_PREFIX = "#vitehub/workspaces/";
|
|
1171
|
-
const WORKSPACE_ASSETS_REGISTRY_ID = "#vitehub-workspace-assets-registry";
|
|
1172
|
-
const WORKSPACE_REGISTRY_ID = "#vitehub-workspace-registry";
|
|
1173
|
-
const RESOLVED_WORKSPACES_ID = `\0${WORKSPACES_ID}`;
|
|
1174
|
-
const RESOLVED_WORKSPACE_PREFIX = `\0${WORKSPACE_PREFIX}`;
|
|
1175
|
-
const RESOLVED_WORKSPACE_REGISTRY_ID = `\0${WORKSPACE_REGISTRY_ID}`;
|
|
1176
|
-
const generatedNitroWorkspacePlugin = ".vitehub/nitro/workspace/plugin.ts";
|
|
1177
|
-
const generatedNitroWorkspaceRegistry = ".vitehub/nitro/workspace/registry.js";
|
|
1178
|
-
const cloudflareArtifactsBindingsFileName = ".vitehub-workspace-artifacts-bindings.json";
|
|
1179
|
-
const mergeNoExternal = createNoExternalMerger(WORKSPACE_PACKAGE_NAME);
|
|
1180
|
-
const workspacesDirSegment = /[\\/](?:server[\\/])?workspaces(?:[\\/]|$)/;
|
|
1181
|
-
function hasVercelBlobWorkspaceDefinition(definitions) {
|
|
1182
|
-
return definitions.some((definition) => {
|
|
1183
|
-
if (!definition.source) return false;
|
|
1184
|
-
return /\bprovider\s*:\s*["']vercel-blob["']/.test(definition.source);
|
|
1185
|
-
});
|
|
1186
|
-
}
|
|
1187
|
-
const sourceModuleExtensions = [
|
|
1188
|
-
".ts",
|
|
1189
|
-
".mts",
|
|
1190
|
-
".cts",
|
|
1191
|
-
".js",
|
|
1192
|
-
".mjs",
|
|
1193
|
-
".cjs",
|
|
1194
|
-
".tsx",
|
|
1195
|
-
".jsx"
|
|
1196
|
-
];
|
|
1197
|
-
async function readSourceModule(file) {
|
|
1198
|
-
const candidates = extname(file) ? [file] : [...sourceModuleExtensions.map((extension) => `${file}${extension}`), ...sourceModuleExtensions.map((extension) => resolve(file, `index${extension}`))];
|
|
1199
|
-
for (const candidate of candidates) try {
|
|
1200
|
-
return {
|
|
1201
|
-
file: candidate,
|
|
1202
|
-
source: await readFile(candidate, "utf8")
|
|
1203
|
-
};
|
|
1204
|
-
} catch (error) {
|
|
1205
|
-
if (error.code !== "ENOENT") throw error;
|
|
1206
|
-
}
|
|
1207
|
-
}
|
|
1208
|
-
function babelPropertyName(path) {
|
|
1209
|
-
return path.node.key?.name ?? path.node.key?.value;
|
|
1210
|
-
}
|
|
1211
|
-
function babelStringValue(node) {
|
|
1212
|
-
if (node?.type === "StringLiteral") return node.value;
|
|
1213
|
-
if (node?.type === "TSAsExpression" || node?.type === "TSSatisfiesExpression" || node?.type === "TSTypeAssertion") return babelStringValue(node.expression);
|
|
1214
|
-
}
|
|
1215
|
-
function isExportedWorkspaceStoreProperty(path) {
|
|
1216
|
-
let exported = false;
|
|
1217
|
-
let store = false;
|
|
1218
|
-
for (let current = path.parentPath; current; current = current.parentPath) {
|
|
1219
|
-
if (current.node.type === "ObjectProperty" && babelPropertyName(current) === "store") store = true;
|
|
1220
|
-
if (current.node.type === "ExportDefaultDeclaration") exported = true;
|
|
1221
|
-
}
|
|
1222
|
-
return exported && store;
|
|
1223
|
-
}
|
|
1224
|
-
async function sourceModuleDeclaresCloudflareArtifacts(file, loader) {
|
|
1225
|
-
const loaded = await readSourceModule(file);
|
|
1226
|
-
if (!loaded) return false;
|
|
1227
|
-
let declaresCloudflareArtifacts = false;
|
|
1228
|
-
loader.transform({
|
|
1229
|
-
filename: loaded.file,
|
|
1230
|
-
jsx: /x$/.test(extname(loaded.file)),
|
|
1231
|
-
source: loaded.source,
|
|
1232
|
-
ts: /\.[cm]?tsx?$/.test(loaded.file),
|
|
1233
|
-
babel: { plugins: [() => ({ visitor: { ObjectProperty(path) {
|
|
1234
|
-
const value = path.node.value;
|
|
1235
|
-
if (babelPropertyName(path) === "provider" && babelStringValue(value) === "cloudflare-artifacts" && isExportedWorkspaceStoreProperty(path)) declaresCloudflareArtifacts = true;
|
|
1236
|
-
} } })] }
|
|
1237
|
-
});
|
|
1238
|
-
return declaresCloudflareArtifacts;
|
|
1239
|
-
}
|
|
1240
|
-
async function sourceModuleUsesCloudflareArtifacts(file, resolveModule, visited = /* @__PURE__ */ new Set()) {
|
|
1241
|
-
const loaded = await readSourceModule(file);
|
|
1242
|
-
if (!loaded || visited.has(loaded.file)) return false;
|
|
1243
|
-
visited.add(loaded.file);
|
|
1244
|
-
if (/\bprovider\s*:\s*["']cloudflare-artifacts["']/.test(loaded.source)) return true;
|
|
1245
|
-
for (const match of loaded.source.matchAll(/\b(?:import|export)\s+(?!type\b)(?:([^"']*?)\s+from\s+)?["']([^"']+)["']/g)) {
|
|
1246
|
-
const imports = match[1]?.trim();
|
|
1247
|
-
if (imports?.startsWith("{") && imports.endsWith("}") && imports.slice(1, -1).split(",").map((entry) => entry.trim()).filter(Boolean).every((entry) => /^type\b/.test(entry))) continue;
|
|
1248
|
-
const specifier = match[2];
|
|
1249
|
-
const resolvedFile = (specifier.startsWith(".") ? resolve(dirname(loaded.file), specifier) : await resolveModule?.(specifier, loaded.file))?.split(/[?#]/, 1)[0];
|
|
1250
|
-
if (resolvedFile && isAbsolute(resolvedFile) && await sourceModuleUsesCloudflareArtifacts(resolvedFile, resolveModule, visited)) return true;
|
|
1251
|
-
}
|
|
1252
|
-
return false;
|
|
1253
|
-
}
|
|
1254
|
-
function vercelFunctionRuntimePackages(options, definitions = []) {
|
|
1255
|
-
const hasVercelBlobStore = options && options.store?.provider === "vercel-blob" || hasVercelBlobWorkspaceDefinition(definitions);
|
|
1256
|
-
return [{
|
|
1257
|
-
name: WORKSPACE_PACKAGE_NAME,
|
|
1258
|
-
resolveFrom: import.meta.url
|
|
1259
|
-
}, ...hasVercelBlobStore ? [{ name: "@vercel/blob" }] : []];
|
|
1260
|
-
}
|
|
1261
|
-
function cloudflareArtifactsBindingsFile(rootDir) {
|
|
1262
|
-
return resolve(createDefaultCloudflareOutputRoot(rootDir), cloudflareArtifactsBindingsFileName);
|
|
1263
|
-
}
|
|
1264
|
-
function cloudflareWranglerFile(rootDir) {
|
|
1265
|
-
return resolve(createDefaultCloudflareOutputRoot(rootDir), "wrangler.json");
|
|
1266
|
-
}
|
|
1267
|
-
function hasCloudflareArtifactBinding(value) {
|
|
1268
|
-
return isRecord(value) && typeof value.binding === "string";
|
|
1269
|
-
}
|
|
1270
|
-
async function readConfiguredCloudflareArtifacts(rootDir) {
|
|
1271
|
-
try {
|
|
1272
|
-
const parsed = JSON.parse(await readFile(cloudflareWranglerFile(rootDir), "utf8"));
|
|
1273
|
-
if (!isRecord(parsed) || !Array.isArray(parsed.artifacts)) return [];
|
|
1274
|
-
return parsed.artifacts.filter(hasCloudflareArtifactBinding);
|
|
1275
|
-
} catch (error) {
|
|
1276
|
-
if (error.code === "ENOENT") return [];
|
|
1277
|
-
throw error;
|
|
1278
|
-
}
|
|
1279
|
-
}
|
|
1280
|
-
async function readOwnedCloudflareArtifactsBindings(rootDir) {
|
|
1281
|
-
try {
|
|
1282
|
-
const parsed = JSON.parse(await readFile(cloudflareArtifactsBindingsFile(rootDir), "utf8"));
|
|
1283
|
-
return Array.isArray(parsed) ? parsed.filter((value) => typeof value === "string") : [];
|
|
1284
|
-
} catch (error) {
|
|
1285
|
-
if (error.code === "ENOENT") return [];
|
|
1286
|
-
throw error;
|
|
1287
|
-
}
|
|
1288
|
-
}
|
|
1289
|
-
async function writeOwnedCloudflareArtifactsBindings(rootDir, bindings) {
|
|
1290
|
-
const file = cloudflareArtifactsBindingsFile(rootDir);
|
|
1291
|
-
if (!bindings.length) {
|
|
1292
|
-
await rm(file, { force: true });
|
|
1293
|
-
return;
|
|
1294
|
-
}
|
|
1295
|
-
await mkdir(createDefaultCloudflareOutputRoot(rootDir), { recursive: true });
|
|
1296
|
-
await writeFile(file, `${JSON.stringify([...new Set(bindings)], null, 2)}\n`, "utf8");
|
|
1297
|
-
}
|
|
1298
|
-
function createCloudflareArtifactsWranglerConfig(configs) {
|
|
1299
|
-
const target = {};
|
|
1300
|
-
for (const config of configs) configureCloudflareArtifacts(target, config);
|
|
1301
|
-
const artifacts = target.cloudflare?.wrangler?.artifacts;
|
|
1302
|
-
return artifacts?.length ? { artifacts } : void 0;
|
|
1303
|
-
}
|
|
1304
|
-
function resolveOwnedCloudflareArtifacts(requested, configured, previousBindings) {
|
|
1305
|
-
const previous = new Set(previousBindings);
|
|
1306
|
-
return requested.filter((artifact) => {
|
|
1307
|
-
if (previous.has(artifact.binding)) return true;
|
|
1308
|
-
const existing = configured.filter((entry) => entry.binding === artifact.binding);
|
|
1309
|
-
const collision = existing.find((entry) => entry.namespace !== artifact.namespace);
|
|
1310
|
-
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.`);
|
|
1311
|
-
return existing.length === 0;
|
|
1312
|
-
});
|
|
1313
|
-
}
|
|
1314
|
-
async function resolveDefinitionCloudflareArtifactsConfigs(definitions, rootDir, options, resolveModule, aliases, inspection, resolution, definitionOverrides) {
|
|
1315
|
-
const loader = createWorkspaceDefinitionLoader(rootDir, aliases);
|
|
1316
|
-
const configs = [];
|
|
1317
|
-
for (const definition of definitions) {
|
|
1318
|
-
const bundlesAssets = shouldBundleWorkspaceAssets(options.assets, definition.name);
|
|
1319
|
-
let loaded;
|
|
1320
|
-
try {
|
|
1321
|
-
loaded = await loadDiscoveredWorkspaceDefinition(loader, definition);
|
|
1322
|
-
} catch (error) {
|
|
1323
|
-
if (inspection?.artifactsOnly) {
|
|
1324
|
-
if (await sourceModuleDeclaresCloudflareArtifacts(definition.path, loader)) throw error;
|
|
1325
|
-
continue;
|
|
1326
|
-
}
|
|
1327
|
-
if (bundlesAssets || await sourceModuleUsesCloudflareArtifacts(definition.path, resolveModule)) throw error;
|
|
1328
|
-
continue;
|
|
1329
|
-
}
|
|
1330
|
-
const workspace = normalizeWorkspaceDefinition(definition.name, loaded);
|
|
1331
|
-
if (!workspace.store || "readFile" in workspace.store) continue;
|
|
1332
|
-
const config = normalizeWorkspaceOptions({ store: workspace.store }, {
|
|
1333
|
-
dev: false,
|
|
1334
|
-
env: resolution?.env || process.env,
|
|
1335
|
-
hosting: resolution?.hosting ?? process.env.VITEHUB_HOSTING,
|
|
1336
|
-
rootDir: workspace.rootDir || rootDir
|
|
1337
|
-
});
|
|
1338
|
-
if (config && config.store.provider === "cloudflare-artifacts") {
|
|
1339
|
-
configs.push(config);
|
|
1340
|
-
definitionOverrides?.set(definition.name, config);
|
|
1341
|
-
}
|
|
1342
|
-
}
|
|
1343
|
-
return configs;
|
|
1344
|
-
}
|
|
1345
|
-
async function resolveCloudflareArtifactsConfigs(config, definitions, rootDir, options = {}) {
|
|
1346
|
-
return [...config.store.provider === "cloudflare-artifacts" ? [config] : [], ...await resolveDefinitionCloudflareArtifactsConfigs(definitions, rootDir, config, options.resolveModule, options.aliases, { artifactsOnly: options.artifactsOnly }, {
|
|
1347
|
-
env: options.env,
|
|
1348
|
-
hosting: options.hosting
|
|
1349
|
-
}, options.definitionOverrides)];
|
|
1350
|
-
}
|
|
1351
|
-
async function writeCloudflareArtifactsProviderOutput(rootDir, config, definitions, resolveModule, aliases) {
|
|
1352
|
-
const requestedConfig = createCloudflareArtifactsWranglerConfig(config ? await resolveCloudflareArtifactsConfigs(config, definitions, rootDir, {
|
|
1353
|
-
aliases,
|
|
1354
|
-
resolveModule
|
|
1355
|
-
}) : []);
|
|
1356
|
-
const [configuredArtifacts, previousBindings] = await Promise.all([readConfiguredCloudflareArtifacts(rootDir), readOwnedCloudflareArtifactsBindings(rootDir)]);
|
|
1357
|
-
const ownedArtifacts = resolveOwnedCloudflareArtifacts(requestedConfig?.artifacts ?? [], configuredArtifacts, previousBindings);
|
|
1358
|
-
const wranglerConfig = ownedArtifacts.length ? { artifacts: ownedArtifacts } : void 0;
|
|
1359
|
-
const nextBindings = ownedArtifacts.map((binding) => binding.binding);
|
|
1360
|
-
if (!wranglerConfig && !previousBindings.length) return;
|
|
1361
|
-
await writeCloudflareWranglerConfig({
|
|
1362
|
-
rootDir,
|
|
1363
|
-
wranglerConfigOwnership: { arrays: { artifacts: {
|
|
1364
|
-
key: "binding",
|
|
1365
|
-
values: [...previousBindings, ...nextBindings]
|
|
1366
|
-
} } },
|
|
1367
|
-
...wranglerConfig ? { wranglerConfig } : {}
|
|
1368
|
-
});
|
|
1369
|
-
await writeOwnedCloudflareArtifactsBindings(rootDir, nextBindings);
|
|
1370
|
-
}
|
|
1371
|
-
function mergeDedupe(current) {
|
|
1372
|
-
if (!current) return [WORKSPACE_PACKAGE_NAME];
|
|
1373
|
-
return current.includes(WORKSPACE_PACKAGE_NAME) ? current : [...current, WORKSPACE_PACKAGE_NAME];
|
|
1374
|
-
}
|
|
1375
|
-
function isWorkspaceFile(file) {
|
|
1376
|
-
return workspaceSuffixPattern.test(file) || workspacesDirSegment.test(file);
|
|
1377
|
-
}
|
|
1378
|
-
function resolveWorkspacePluginRoots(root, workspaceOptions) {
|
|
1379
|
-
const resolvedViteRoot = resolve(root);
|
|
1380
|
-
return {
|
|
1381
|
-
projectRoot: resolveViteHubProjectRoot(resolvedViteRoot, { projectRoot: workspaceOptions ? workspaceOptions.projectRoot : void 0 }),
|
|
1382
|
-
viteRoot: resolvedViteRoot
|
|
1383
|
-
};
|
|
1384
|
-
}
|
|
1385
|
-
function discoverDefinitions(roots) {
|
|
1386
|
-
return discoverViteWorkspaceDefinitions(roots.viteRoot, { serverRootDir: roots.projectRoot });
|
|
1387
|
-
}
|
|
1388
|
-
function isRecord(value) {
|
|
1389
|
-
return typeof value === "object" && value !== null;
|
|
1390
|
-
}
|
|
1391
|
-
function isWorkspaceRegistry(value) {
|
|
1392
|
-
return isRecord(value) && Object.values(value).every((item) => typeof item === "function");
|
|
1393
|
-
}
|
|
1394
|
-
function workspaceDefinitionLoaderAliases(aliases) {
|
|
1395
|
-
if (!Array.isArray(aliases)) return aliases;
|
|
1396
|
-
return Object.fromEntries(aliases.flatMap((alias) => typeof alias.find === "string" ? [[alias.find, alias.replacement]] : []));
|
|
1397
|
-
}
|
|
1398
|
-
function isHostedWorkspaceStore(store) {
|
|
1399
|
-
return store.provider === "cloudflare-artifacts" || store.provider === "github" || store.provider === "vercel-blob";
|
|
1400
|
-
}
|
|
1401
|
-
function requestOrigin(server, req) {
|
|
1402
|
-
const host = Array.isArray(req.headers.host) ? req.headers.host[0] : req.headers.host;
|
|
1403
|
-
if (host) {
|
|
1404
|
-
const fallback = server.resolvedUrls?.local?.[0] || "http://localhost/";
|
|
1405
|
-
return new URL(`${new URL(fallback).protocol}//${host}`).origin;
|
|
1406
|
-
}
|
|
1407
|
-
const base = server.resolvedUrls?.local?.[0] || `http://localhost:${server.config.server.port || 5173}/`;
|
|
1408
|
-
return new URL(base).origin;
|
|
1409
|
-
}
|
|
1410
|
-
function validateWorkspaceDevRequest(server, req) {
|
|
1411
|
-
const header = req.headers[workspaceDevHeader];
|
|
1412
|
-
if ((Array.isArray(header) ? header[0] : header) !== "1") return new Response("Forbidden Workspace Dev request.", { status: 403 });
|
|
1413
|
-
const origin = Array.isArray(req.headers.origin) ? req.headers.origin[0] : req.headers.origin;
|
|
1414
|
-
if (origin && origin !== requestOrigin(server, req)) return new Response("Forbidden Workspace Dev origin.", { status: 403 });
|
|
1415
|
-
if (req.method !== "POST") return;
|
|
1416
|
-
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 });
|
|
1417
|
-
}
|
|
1418
|
-
function acceptsWorkspaceDevStream(req) {
|
|
1419
|
-
const accept = Array.isArray(req.headers.accept) ? req.headers.accept.join(",") : req.headers.accept;
|
|
1420
|
-
return Boolean(accept?.includes("application/x-ndjson"));
|
|
1421
|
-
}
|
|
1422
|
-
async function readRequestBody(req) {
|
|
1423
|
-
let body = "";
|
|
1424
|
-
req.setEncoding("utf8");
|
|
1425
|
-
for await (const chunk of req) body += chunk;
|
|
1426
|
-
return body;
|
|
1427
|
-
}
|
|
1428
|
-
function createAbortSignalFromClose(target, message) {
|
|
1429
|
-
const controller = new AbortController();
|
|
1430
|
-
const abort = () => controller.abort(new Error(message));
|
|
1431
|
-
target.once("close", abort);
|
|
1432
|
-
return {
|
|
1433
|
-
dispose: () => target.off("close", abort),
|
|
1434
|
-
signal: controller.signal
|
|
1435
|
-
};
|
|
1436
|
-
}
|
|
1437
|
-
async function writeResponse(res, response) {
|
|
1438
|
-
res.statusCode = response.status;
|
|
1439
|
-
for (const [name, value] of response.headers) res.setHeader(name, value);
|
|
1440
|
-
if (!response.body) {
|
|
1441
|
-
res.end();
|
|
1442
|
-
return;
|
|
1443
|
-
}
|
|
1444
|
-
const reader = response.body.getReader();
|
|
1445
|
-
try {
|
|
1446
|
-
for (;;) {
|
|
1447
|
-
const { done, value } = await reader.read();
|
|
1448
|
-
if (done) break;
|
|
1449
|
-
res.write(Buffer.from(value));
|
|
1450
|
-
}
|
|
1451
|
-
res.end();
|
|
1452
|
-
} finally {
|
|
1453
|
-
reader.releaseLock();
|
|
1454
|
-
}
|
|
1455
|
-
}
|
|
1456
|
-
function isWorkspaceDevRoute(req) {
|
|
1457
|
-
return new URL(req.url || "/", "http://localhost").pathname === workspaceDevRoute;
|
|
1458
|
-
}
|
|
1459
|
-
function streamWorkspaceDevCommand(input, closeHost) {
|
|
1460
|
-
const encoder = new TextEncoder();
|
|
1461
|
-
const stream = new ReadableStream({ async start(controller) {
|
|
1462
|
-
const write = (value) => controller.enqueue(encoder.encode(`${JSON.stringify(value)}\n`));
|
|
1463
|
-
try {
|
|
1464
|
-
write({
|
|
1465
|
-
result: await runWorkspaceDevCommand({
|
|
1466
|
-
...input,
|
|
1467
|
-
onProgress: async (event) => write({
|
|
1468
|
-
event,
|
|
1469
|
-
type: "progress"
|
|
1470
|
-
})
|
|
1471
|
-
}),
|
|
1472
|
-
type: "result"
|
|
1473
|
-
});
|
|
1474
|
-
} catch (error) {
|
|
1475
|
-
write({
|
|
1476
|
-
error: error instanceof Error ? error.message : String(error),
|
|
1477
|
-
type: "error"
|
|
1478
|
-
});
|
|
1479
|
-
} finally {
|
|
1480
|
-
await closeHost();
|
|
1481
|
-
controller.close();
|
|
1482
|
-
}
|
|
1483
|
-
} });
|
|
1484
|
-
return new Response(stream, { headers: {
|
|
1485
|
-
"cache-control": "no-store",
|
|
1486
|
-
"content-type": "application/x-ndjson; charset=utf-8"
|
|
1487
|
-
} });
|
|
1488
|
-
}
|
|
1489
|
-
async function handleWorkspaceDevRequest(server, req, workspaces, tokenOptions, abortSignal) {
|
|
1490
|
-
const validation = validateWorkspaceDevRequest(server, req);
|
|
1491
|
-
if (validation) return validation;
|
|
1492
|
-
if (req.method === "GET") {
|
|
1493
|
-
await ensureWorkspaceDevToken(server.config.root, tokenOptions);
|
|
1494
|
-
return Response.json({
|
|
1495
|
-
root: server.config.root,
|
|
1496
|
-
workspaceDevTokenServerId: tokenOptions.serverId,
|
|
1497
|
-
workspaces
|
|
1498
|
-
});
|
|
1499
|
-
}
|
|
1500
|
-
if (req.method !== "POST") return new Response("Method Not Allowed", { status: 405 });
|
|
1501
|
-
let body;
|
|
1502
|
-
try {
|
|
1503
|
-
body = JSON.parse(await readRequestBody(req));
|
|
1504
|
-
} catch {
|
|
1505
|
-
return new Response("Malformed Workspace Dev payload.", { status: 400 });
|
|
1506
|
-
}
|
|
1507
|
-
const command = body.workspaceCommand;
|
|
1508
|
-
if (!command || typeof command.workspace !== "string" || typeof command.command !== "string") return new Response("Missing Workspace Dev command.", { status: 400 });
|
|
1509
|
-
if (!await validateWorkspaceDevToken(server.config.root, req.headers, tokenOptions)) return new Response("Forbidden Workspace Dev token.", { status: 403 });
|
|
1510
|
-
const mod = await server.ssrLoadModule(WORKSPACE_REGISTRY_ID);
|
|
1511
|
-
const load = (isWorkspaceRegistry(mod.default) ? mod.default : {})[command.workspace];
|
|
1512
|
-
if (!load) return new Response(`Unknown Workspace Dev target: ${command.workspace}`, { status: 404 });
|
|
1513
|
-
const definition = (await load()).default;
|
|
1514
|
-
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 });
|
|
1515
|
-
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 });
|
|
1516
|
-
const args = command.args;
|
|
1517
|
-
const paths = command.paths;
|
|
1518
|
-
const timeout = typeof command.timeout === "number" && Number.isFinite(command.timeout) ? command.timeout : void 0;
|
|
1519
|
-
const { resolveBox, trustedHost } = await import("@vite-hub/box");
|
|
1520
|
-
const host = await (await resolveBox({ runtime: trustedHost() }, {})).open({ signal: abortSignal });
|
|
1521
|
-
const input = {
|
|
1522
|
-
abortSignal,
|
|
1523
|
-
...args ? { args } : {},
|
|
1524
|
-
command: command.command,
|
|
1525
|
-
host,
|
|
1526
|
-
...isRecord(definition) ? { definition: normalizeWorkspaceDefinition(command.workspace, definition) } : {},
|
|
1527
|
-
...paths?.length ? { paths } : {},
|
|
1528
|
-
...timeout ? { timeout } : {},
|
|
1529
|
-
workspace: command.workspace
|
|
1530
|
-
};
|
|
1531
|
-
if (acceptsWorkspaceDevStream(req)) return streamWorkspaceDevCommand(input, () => host.close());
|
|
1532
|
-
try {
|
|
1533
|
-
return Response.json(await runWorkspaceDevCommand(input));
|
|
1534
|
-
} finally {
|
|
1535
|
-
await host.close();
|
|
1536
|
-
}
|
|
1537
|
-
}
|
|
1538
|
-
function hasNitroPlugin(value) {
|
|
1539
|
-
if (Array.isArray(value)) return value.some(hasNitroPlugin);
|
|
1540
|
-
return isRecord(value) && typeof value.name === "string" && value.name.startsWith("nitro:");
|
|
1541
|
-
}
|
|
1542
|
-
function hasNitroConfig(config) {
|
|
1543
|
-
return "nitro" in config || hasNitroPlugin(config.plugins);
|
|
1544
|
-
}
|
|
1545
|
-
function hasExplicitWorkspaceRuntimeOptions(options) {
|
|
1546
|
-
return Boolean(options && (options.root || options.store));
|
|
1547
|
-
}
|
|
1548
|
-
function shouldInstallNitroWorkspacePlugin(config, options, normalized, definitions) {
|
|
1549
|
-
return isHostedWorkspaceStore(normalized.store) || hasExplicitWorkspaceRuntimeOptions(options) || hasNitroConfig(config) && definitions.length > 0;
|
|
1550
|
-
}
|
|
1551
|
-
function mergeNitroWorkspaceConfig(value) {
|
|
1552
|
-
const nitro = isRecord(value) ? { ...value } : {};
|
|
1553
|
-
const plugins = Array.isArray(nitro.plugins) ? [...nitro.plugins] : [];
|
|
1554
|
-
if (!plugins.includes(generatedNitroWorkspacePlugin)) plugins.push(generatedNitroWorkspacePlugin);
|
|
1555
|
-
return {
|
|
1556
|
-
...nitro,
|
|
1557
|
-
plugins
|
|
1558
|
-
};
|
|
1559
|
-
}
|
|
1560
|
-
function mergeNitroExternal(value, addition) {
|
|
1561
|
-
if (typeof value === "undefined") return [addition];
|
|
1562
|
-
if (Array.isArray(value)) return value.includes(addition) ? [...value] : [...value, addition];
|
|
1563
|
-
if (typeof value === "string" || value instanceof RegExp) return [value, addition];
|
|
1564
|
-
if (typeof value === "function") return (source, importer, isResolved) => source === addition || Boolean(value(source, importer, isResolved));
|
|
1565
|
-
return value;
|
|
1566
|
-
}
|
|
1567
|
-
function configureCloudflareArtifactsNitroRuntime(nitro) {
|
|
1568
|
-
nitro.cloudflare ??= {};
|
|
1569
|
-
nitro.cloudflare.wrangler ??= {};
|
|
1570
|
-
const compatibilityFlags = nitro.cloudflare.wrangler.compatibility_flags || [];
|
|
1571
|
-
if (!compatibilityFlags.includes("nodejs_compat")) compatibilityFlags.push("nodejs_compat");
|
|
1572
|
-
nitro.cloudflare.wrangler.compatibility_flags = compatibilityFlags;
|
|
1573
|
-
const rollupConfig = isRecord(nitro.rollupConfig) ? { ...nitro.rollupConfig } : {};
|
|
1574
|
-
nitro.rollupConfig = {
|
|
1575
|
-
...rollupConfig,
|
|
1576
|
-
external: mergeNitroExternal(rollupConfig.external, "cloudflare:workers")
|
|
1577
|
-
};
|
|
1578
|
-
}
|
|
1579
|
-
function moduleImportSpecifier(fromFile, targetFile) {
|
|
1580
|
-
const specifier = relative(dirname(fromFile), targetFile).replace(/\\/g, "/");
|
|
1581
|
-
return specifier.startsWith(".") ? specifier : `./${specifier}`;
|
|
1582
|
-
}
|
|
1583
|
-
function shouldConfigureRuntime(options, normalized) {
|
|
1584
|
-
return isHostedWorkspaceStore(normalized.store) || hasExplicitWorkspaceRuntimeOptions(options);
|
|
1585
|
-
}
|
|
1586
|
-
function renderRuntimeValue(value, depth = 0) {
|
|
1587
|
-
if (typeof value === "function") return value.toString();
|
|
1588
|
-
if (Array.isArray(value)) {
|
|
1589
|
-
if (!value.length) return "[]";
|
|
1590
|
-
const indent = " ".repeat(depth + 1);
|
|
1591
|
-
const closingIndent = " ".repeat(depth);
|
|
1592
|
-
return `[\n${value.map((item) => `${indent}${renderRuntimeValue(item, depth + 1)}`).join(",\n")}\n${closingIndent}]`;
|
|
1593
|
-
}
|
|
1594
|
-
if (isRecord(value)) {
|
|
1595
|
-
const entries = Object.entries(value).filter(([, entry]) => entry !== void 0);
|
|
1596
|
-
if (!entries.length) return "{}";
|
|
1597
|
-
const indent = " ".repeat(depth + 1);
|
|
1598
|
-
const closingIndent = " ".repeat(depth);
|
|
1599
|
-
return `{\n${entries.map(([key, entry]) => `${indent}${JSON.stringify(key)}: ${renderRuntimeValue(entry, depth + 1)}`).join(",\n")}\n${closingIndent}}`;
|
|
1600
|
-
}
|
|
1601
|
-
return JSON.stringify(value);
|
|
1602
|
-
}
|
|
1603
|
-
function runtimeWorkspaceConfig(config, options) {
|
|
1604
|
-
if (!config || config.store.provider !== "github" || !options) return config;
|
|
1605
|
-
const store = options.store;
|
|
1606
|
-
if (!store || "readFile" in store || store.provider !== "github") return config;
|
|
1607
|
-
const runtimeStore = { ...config.store };
|
|
1608
|
-
for (const key of [
|
|
1609
|
-
"branch",
|
|
1610
|
-
"repo",
|
|
1611
|
-
"repository",
|
|
1612
|
-
"root",
|
|
1613
|
-
"token"
|
|
1614
|
-
]) if (typeof store[key] === "function") runtimeStore[key] = store[key];
|
|
1615
|
-
return {
|
|
1616
|
-
...config,
|
|
1617
|
-
store: runtimeStore
|
|
1618
|
-
};
|
|
1619
|
-
}
|
|
1620
|
-
function renderNitroWorkspacePlugin(config, registryImport, installHostedRuntime, cloudflareArtifacts, importBase = WORKSPACE_PACKAGE_NAME) {
|
|
1621
|
-
const hostedRuntimeImport = `${importBase}/internal/runtime/hosted`;
|
|
1622
|
-
const hostedVercelBlobRuntimeImport = `${importBase}/internal/runtime/hosted-vercel-blob`;
|
|
1623
|
-
const runtimeImport = `${importBase}/runtime`;
|
|
1624
|
-
const hostedConfig = config && isHostedWorkspaceStore(config.store) ? config : void 0;
|
|
1625
|
-
const isVercelBlobStore = hostedConfig?.store.provider === "vercel-blob";
|
|
1626
|
-
const runtimeImports = hostedConfig ? [
|
|
1627
|
-
isVercelBlobStore ? `import { configureHostedVercelBlobWorkspaceRuntime } from '${hostedVercelBlobRuntimeImport}'` : `import { configureHostedWorkspaceRuntime, installHostedWorkspaceRuntime } from '${hostedRuntimeImport}'`,
|
|
1628
|
-
isVercelBlobStore ? `import { installHostedWorkspaceRuntime } from '${hostedRuntimeImport}'` : `import { installHostedVercelBlobWorkspaceRuntime } from '${hostedVercelBlobRuntimeImport}'`,
|
|
1629
|
-
`import { setWorkspaceRuntimeRegistry } from '${runtimeImport}'`
|
|
1630
|
-
] : [
|
|
1631
|
-
...installHostedRuntime ? [`import { installHostedWorkspaceRuntime } from '${hostedRuntimeImport}'`] : [],
|
|
1632
|
-
...installHostedRuntime ? [`import { installHostedVercelBlobWorkspaceRuntime } from '${hostedVercelBlobRuntimeImport}'`] : [],
|
|
1633
|
-
`import { ${config ? "setWorkspaceRuntimeConfig, " : ""}setWorkspaceRuntimeRegistry } from '${runtimeImport}'`
|
|
1634
|
-
];
|
|
1635
|
-
if (cloudflareArtifacts) runtimeImports.unshift("import { env as vitehubEnv } from 'cloudflare:workers'", `import { setActiveCloudflareEnv } from '${importBase}/internal/runtime/state'`);
|
|
1636
|
-
const runtimeSetup = hostedConfig ? [` ${isVercelBlobStore ? "configureHostedVercelBlobWorkspaceRuntime" : "configureHostedWorkspaceRuntime"}(${renderRuntimeValue({
|
|
1637
|
-
root: hostedConfig.root,
|
|
1638
|
-
store: hostedConfig.store
|
|
1639
|
-
})})`, ` ${isVercelBlobStore ? "installHostedWorkspaceRuntime" : "installHostedVercelBlobWorkspaceRuntime"}()`] : [
|
|
1640
|
-
...installHostedRuntime ? [" installHostedWorkspaceRuntime()"] : [],
|
|
1641
|
-
...installHostedRuntime ? [" installHostedVercelBlobWorkspaceRuntime()"] : [],
|
|
1642
|
-
...config ? [` setWorkspaceRuntimeConfig(${renderRuntimeValue({
|
|
1643
|
-
root: config.root,
|
|
1644
|
-
store: config.store
|
|
1645
|
-
})})`] : []
|
|
1646
|
-
];
|
|
1647
|
-
return [
|
|
1648
|
-
...runtimeImports,
|
|
1649
|
-
`import registry from ${JSON.stringify(registryImport)}`,
|
|
1650
|
-
"",
|
|
1651
|
-
"export default function vitehubWorkspacePlugin() {",
|
|
1652
|
-
...cloudflareArtifacts ? [" setActiveCloudflareEnv(vitehubEnv)"] : [],
|
|
1653
|
-
" setWorkspaceRuntimeRegistry(registry)",
|
|
1654
|
-
...runtimeSetup,
|
|
1655
|
-
"}",
|
|
1656
|
-
""
|
|
1657
|
-
].join("\n");
|
|
1658
|
-
}
|
|
1659
|
-
async function writeNitroWorkspacePlugin(root, config, options, definitions, cloudflareArtifacts = false, importBase = WORKSPACE_PACKAGE_NAME, definitionOverrides) {
|
|
1660
|
-
const pluginFile = resolve(root, generatedNitroWorkspacePlugin);
|
|
1661
|
-
const registryFile = resolve(root, generatedNitroWorkspaceRegistry);
|
|
1662
|
-
const runtimeConfig = runtimeWorkspaceConfig(config, options);
|
|
1663
|
-
await Promise.all([mkdir(dirname(pluginFile), { recursive: true }), mkdir(dirname(registryFile), { recursive: true })]);
|
|
1664
|
-
await writeFile(registryFile, createWorkspaceRegistryContents(registryFile, definitions, definitionOverrides), "utf8");
|
|
1665
|
-
await writeFile(pluginFile, renderNitroWorkspacePlugin(runtimeConfig, moduleImportSpecifier(pluginFile, registryFile), definitions.length > 0 && !(runtimeConfig && isHostedWorkspaceStore(runtimeConfig.store)), cloudflareArtifacts, importBase), "utf8");
|
|
1666
|
-
}
|
|
1667
|
-
async function createWorkspaceNitroConfig(options = {}) {
|
|
1668
|
-
const workspaceOptions = stripWorkspaceInternalOptions(options.workspace);
|
|
1669
|
-
const roots = resolveWorkspacePluginRoots(options.viteRoot || process.cwd(), workspaceOptions);
|
|
1670
|
-
const normalized = normalizeWorkspaceOptions(workspaceOptions, {
|
|
1671
|
-
dev: options.command !== "build",
|
|
1672
|
-
env: options.env || process.env,
|
|
1673
|
-
hosting: options.hosting ?? process.env.VITEHUB_HOSTING,
|
|
1674
|
-
rootDir: roots.projectRoot
|
|
1675
|
-
});
|
|
1676
|
-
if (!normalized) return null;
|
|
1677
|
-
const definitions = discoverDefinitions(roots);
|
|
1678
|
-
if (!isHostedWorkspaceStore(normalized.store) && !hasExplicitWorkspaceRuntimeOptions(workspaceOptions) && definitions.length === 0) return null;
|
|
1679
|
-
const definitionOverrides = /* @__PURE__ */ new Map();
|
|
1680
|
-
const cloudflareArtifactsConfigs = await resolveCloudflareArtifactsConfigs(normalized, definitions, roots.projectRoot, {
|
|
1681
|
-
aliases: options.aliases,
|
|
1682
|
-
artifactsOnly: true,
|
|
1683
|
-
env: options.env,
|
|
1684
|
-
hosting: options.hosting,
|
|
1685
|
-
definitionOverrides
|
|
1686
|
-
});
|
|
1687
|
-
const runtimeConfig = shouldConfigureRuntime(workspaceOptions, normalized) ? normalized : false;
|
|
1688
|
-
await writeNitroWorkspacePlugin(roots.projectRoot, runtimeConfig, workspaceOptions, definitions, cloudflareArtifactsConfigs.length > 0, WORKSPACE_PACKAGE_NAME, definitionOverrides);
|
|
1689
|
-
const nitro = mergeNitroWorkspaceConfig(options.nitro);
|
|
1690
|
-
for (const config of cloudflareArtifactsConfigs) configureCloudflareArtifacts(nitro, config);
|
|
1691
|
-
if (cloudflareArtifactsConfigs.length > 0) configureCloudflareArtifactsNitroRuntime(nitro);
|
|
1692
|
-
return nitro;
|
|
1693
|
-
}
|
|
1694
|
-
function stripWorkspaceInternalOptions(options) {
|
|
1695
|
-
if (!options || !Object.hasOwn(options, "hosting") && !Object.hasOwn(options, "importBase")) return options;
|
|
1696
|
-
const publicOptions = { ...options };
|
|
1697
|
-
delete publicOptions.hosting;
|
|
1698
|
-
delete publicOptions.importBase;
|
|
1699
|
-
return publicOptions;
|
|
1700
|
-
}
|
|
1701
|
-
function hubWorkspace(options) {
|
|
1702
|
-
const hosting = options?.hosting;
|
|
1703
|
-
const importBase = options?.importBase ?? WORKSPACE_PACKAGE_NAME;
|
|
1704
|
-
const publicOptions = stripWorkspaceInternalOptions(options);
|
|
1705
|
-
let resolved;
|
|
1706
|
-
let resolvedOptions = false;
|
|
1707
|
-
let projectRoot;
|
|
1708
|
-
let viteRoot;
|
|
1709
|
-
let assetsRegistryFile;
|
|
1710
|
-
let manifest = { workspaces: [] };
|
|
1711
|
-
let registryContents = "export default {}\n";
|
|
1712
|
-
let server;
|
|
1713
|
-
async function refreshManifest(roots) {
|
|
1714
|
-
const definitions = discoverDefinitions(roots);
|
|
1715
|
-
const state = await refreshWorkspaceBuildState(roots.projectRoot, definitions);
|
|
1716
|
-
manifest = state.manifest;
|
|
1717
|
-
registryContents = state.registryContents;
|
|
1718
|
-
}
|
|
1719
|
-
function invalidateVirtualWorkspaceModules() {
|
|
1720
|
-
if (!server) return;
|
|
1721
|
-
const moduleGraph = server.moduleGraph;
|
|
1722
|
-
const ids = [
|
|
1723
|
-
RESOLVED_WORKSPACE_REGISTRY_ID,
|
|
1724
|
-
RESOLVED_WORKSPACES_ID,
|
|
1725
|
-
...manifest.workspaces.map((w) => `${RESOLVED_WORKSPACE_PREFIX}${w.name}`)
|
|
1726
|
-
];
|
|
1727
|
-
for (const id of ids) {
|
|
1728
|
-
const mod = moduleGraph.getModuleById(id);
|
|
1729
|
-
if (mod) moduleGraph.invalidateModule(mod);
|
|
1730
|
-
}
|
|
1731
|
-
}
|
|
1732
|
-
async function maybeRefreshTypesForFile(roots, file) {
|
|
1733
|
-
if (!isWorkspaceFile(file)) return;
|
|
1734
|
-
await refreshManifest(roots);
|
|
1735
|
-
invalidateVirtualWorkspaceModules();
|
|
1736
|
-
}
|
|
1737
|
-
return {
|
|
1738
|
-
name: "@vite-hub/workspace/vite",
|
|
1739
|
-
enforce: "pre",
|
|
1740
|
-
api: { getWorkspaces: () => manifest.workspaces },
|
|
1741
|
-
async config(config, env) {
|
|
1742
|
-
const workspaceOptions = stripWorkspaceInternalOptions(config.workspace ?? publicOptions);
|
|
1743
|
-
const roots = resolveWorkspacePluginRoots(config.root || process.cwd(), workspaceOptions);
|
|
1744
|
-
const normalized = normalizeWorkspaceOptions(workspaceOptions, {
|
|
1745
|
-
dev: env?.command !== "build",
|
|
1746
|
-
env: process.env,
|
|
1747
|
-
hosting: hosting ?? process.env.VITEHUB_HOSTING,
|
|
1748
|
-
rootDir: roots.projectRoot
|
|
1749
|
-
});
|
|
1750
|
-
const runtimeOptions = hosting && normalized && normalized.store.provider !== "local" ? {
|
|
1751
|
-
...workspaceOptions || {},
|
|
1752
|
-
store: workspaceOptions && workspaceOptions.store ? workspaceOptions.store : normalized.store
|
|
1753
|
-
} : workspaceOptions;
|
|
1754
|
-
const viteConfig = { server: { watch: { ignored: mergeGeneratedViteHubWatchIgnored(config.server?.watch?.ignored) } } };
|
|
1755
|
-
const definitions = normalized ? discoverDefinitions(roots) : [];
|
|
1756
|
-
if (normalized && shouldInstallNitroWorkspacePlugin(config, runtimeOptions, normalized, definitions)) {
|
|
1757
|
-
const runtimeConfig = shouldConfigureRuntime(runtimeOptions, normalized) ? normalized : false;
|
|
1758
|
-
const definitionOverrides = /* @__PURE__ */ new Map();
|
|
1759
|
-
const artifacts = await resolveCloudflareArtifactsConfigs(normalized, definitions, roots.projectRoot, {
|
|
1760
|
-
aliases: config.resolve?.alias ? workspaceDefinitionLoaderAliases(config.resolve.alias) : void 0,
|
|
1761
|
-
artifactsOnly: true,
|
|
1762
|
-
hosting,
|
|
1763
|
-
definitionOverrides
|
|
1764
|
-
});
|
|
1765
|
-
const usesCloudflareArtifacts = artifacts.length > 0;
|
|
1766
|
-
await writeNitroWorkspacePlugin(roots.projectRoot, runtimeConfig, runtimeOptions, definitions, usesCloudflareArtifacts, importBase, definitionOverrides);
|
|
1767
|
-
const nitro = mergeNitroWorkspaceConfig(config.nitro);
|
|
1768
|
-
for (const artifactConfig of artifacts) configureCloudflareArtifacts(nitro, artifactConfig);
|
|
1769
|
-
if (usesCloudflareArtifacts) configureCloudflareArtifactsNitroRuntime(nitro);
|
|
1770
|
-
config.nitro = nitro;
|
|
1771
|
-
viteConfig.nitro = nitro;
|
|
1772
|
-
}
|
|
1773
|
-
return viteConfig;
|
|
1774
|
-
},
|
|
1775
|
-
async configResolved(config) {
|
|
1776
|
-
resolved = config;
|
|
1777
|
-
const workspaceOptions = stripWorkspaceInternalOptions(config.workspace ?? publicOptions);
|
|
1778
|
-
const roots = resolveWorkspacePluginRoots(config.root, workspaceOptions);
|
|
1779
|
-
projectRoot = roots.projectRoot;
|
|
1780
|
-
viteRoot = roots.viteRoot;
|
|
1781
|
-
if (config.command !== "build") process.env.VITEHUB_WORKSPACE_DEV = "true";
|
|
1782
|
-
else delete process.env.VITEHUB_WORKSPACE_DEV;
|
|
1783
|
-
resolvedOptions = normalizeWorkspaceOptions(workspaceOptions, {
|
|
1784
|
-
dev: config.command !== "build",
|
|
1785
|
-
env: process.env,
|
|
1786
|
-
hosting: hosting ?? process.env.VITEHUB_HOSTING,
|
|
1787
|
-
rootDir: roots.projectRoot
|
|
1788
|
-
});
|
|
1789
|
-
assetsRegistryFile = resolve(roots.projectRoot, ".vitehub/vite-runtime/workspace/assets/registry.mjs");
|
|
1790
|
-
await initializeWorkspaceAssetRegistry(assetsRegistryFile);
|
|
1791
|
-
await refreshManifest(roots);
|
|
1792
|
-
},
|
|
1793
|
-
configEnvironment(name, config) {
|
|
1794
|
-
if (!isServerEnvironment(name, config)) return;
|
|
1795
|
-
return { resolve: {
|
|
1796
|
-
dedupe: mergeDedupe(config.resolve?.dedupe),
|
|
1797
|
-
noExternal: mergeNoExternal(config.resolve?.noExternal)
|
|
1798
|
-
} };
|
|
1799
|
-
},
|
|
1800
|
-
async buildStart() {
|
|
1801
|
-
if (!resolved) return;
|
|
1802
|
-
const roots = {
|
|
1803
|
-
projectRoot: projectRoot || resolveViteHubProjectRoot(resolved.root),
|
|
1804
|
-
viteRoot: viteRoot || resolve(resolved.root)
|
|
1805
|
-
};
|
|
1806
|
-
await refreshManifest(roots);
|
|
1807
|
-
if (resolved.command !== "build" || !assetsRegistryFile) return;
|
|
1808
|
-
await syncWorkspaceBuildAssets(discoverDefinitions(roots), roots.projectRoot, resolvedOptions, assetsRegistryFile);
|
|
1809
|
-
},
|
|
1810
|
-
closeBundle: {
|
|
1811
|
-
order: "post",
|
|
1812
|
-
sequential: true,
|
|
1813
|
-
async handler() {
|
|
1814
|
-
if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
|
|
1815
|
-
const roots = {
|
|
1816
|
-
projectRoot: projectRoot || resolveViteHubProjectRoot(resolved.root),
|
|
1817
|
-
viteRoot: viteRoot || resolve(resolved.root)
|
|
1818
|
-
};
|
|
1819
|
-
const definitions = discoverDefinitions(roots);
|
|
1820
|
-
await Promise.all(definitions.map(async (definition) => {
|
|
1821
|
-
definition.source = await readFile(definition.path, "utf8");
|
|
1822
|
-
}));
|
|
1823
|
-
await Promise.all([copyVercelFunctionRuntimePackages({
|
|
1824
|
-
packages: vercelFunctionRuntimePackages(resolvedOptions, definitions),
|
|
1825
|
-
rootDir: roots.projectRoot
|
|
1826
|
-
}), writeCloudflareArtifactsProviderOutput(roots.projectRoot, resolvedOptions, definitions, resolved.createResolver?.(), resolved.resolve ? workspaceDefinitionLoaderAliases(resolved.resolve.alias) : void 0)]);
|
|
1827
|
-
}
|
|
1828
|
-
},
|
|
1829
|
-
async configureServer(devServer) {
|
|
1830
|
-
server = devServer;
|
|
1831
|
-
installHostedWorkspaceRuntime();
|
|
1832
|
-
installHostedVercelBlobWorkspaceRuntime();
|
|
1833
|
-
const tokenOptions = { serverId: workspaceDevTokenServerId(devServer.config.server.port) };
|
|
1834
|
-
await refreshWorkspaceDevToken(devServer.config.root, tokenOptions);
|
|
1835
|
-
const roots = {
|
|
1836
|
-
projectRoot: projectRoot || resolveViteHubProjectRoot(devServer.config.root),
|
|
1837
|
-
viteRoot: viteRoot || resolve(devServer.config.root)
|
|
1838
|
-
};
|
|
1839
|
-
const refresh = async (file) => await maybeRefreshTypesForFile(roots, file);
|
|
1840
|
-
devServer.watcher.on("add", refresh);
|
|
1841
|
-
devServer.watcher.on("unlink", refresh);
|
|
1842
|
-
devServer.middlewares.use((req, res, next) => {
|
|
1843
|
-
if (!isWorkspaceDevRoute(req)) return next();
|
|
1844
|
-
const abort = createAbortSignalFromClose(res, "[vitehub] Workspace Dev response closed.");
|
|
1845
|
-
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);
|
|
1846
|
-
});
|
|
1847
|
-
},
|
|
1848
|
-
vitehub: { cli: async () => {
|
|
1849
|
-
return createWorkspaceCliContributor();
|
|
1850
|
-
} },
|
|
1851
|
-
async handleHotUpdate(ctx) {
|
|
1852
|
-
if (!resolved) return;
|
|
1853
|
-
await maybeRefreshTypesForFile({
|
|
1854
|
-
projectRoot: projectRoot || resolveViteHubProjectRoot(resolved.root),
|
|
1855
|
-
viteRoot: viteRoot || resolve(resolved.root)
|
|
1856
|
-
}, ctx.file);
|
|
1857
|
-
},
|
|
1858
|
-
resolveId(id) {
|
|
1859
|
-
if (id === WORKSPACE_ASSETS_REGISTRY_ID) return assetsRegistryFile;
|
|
1860
|
-
if (id === WORKSPACE_REGISTRY_ID) return RESOLVED_WORKSPACE_REGISTRY_ID;
|
|
1861
|
-
if (id === WORKSPACES_ID) return RESOLVED_WORKSPACES_ID;
|
|
1862
|
-
if (id.startsWith(WORKSPACE_PREFIX)) return `${RESOLVED_WORKSPACE_PREFIX}${id.slice(20)}`;
|
|
1863
|
-
},
|
|
1864
|
-
load(id) {
|
|
1865
|
-
if (id === RESOLVED_WORKSPACE_REGISTRY_ID) return registryContents;
|
|
1866
|
-
if (id === RESOLVED_WORKSPACES_ID) return `export const workspaces = ${JSON.stringify(manifest.workspaces)};\nexport default { workspaces };\n`;
|
|
1867
|
-
if (id.startsWith(RESOLVED_WORKSPACE_PREFIX)) {
|
|
1868
|
-
const name = id.slice(RESOLVED_WORKSPACE_PREFIX.length);
|
|
1869
|
-
const workspace = manifest.workspaces.find((item) => item.name === name);
|
|
1870
|
-
return `const manifest = ${JSON.stringify(workspace ? {
|
|
1871
|
-
...workspace,
|
|
1872
|
-
entries: []
|
|
1873
|
-
} : {
|
|
1874
|
-
name,
|
|
1875
|
-
entries: []
|
|
1876
|
-
})};\nexport default manifest;\n`;
|
|
1877
|
-
}
|
|
1878
|
-
}
|
|
1879
|
-
};
|
|
1880
|
-
}
|
|
1881
|
-
//#endregion
|
|
1882
|
-
export { hubWorkspace as n, createWorkspaceNitroConfig as t };
|