@vite-hub/sandbox 0.0.1 → 0.0.2
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/README.md +35 -37
- package/dist/cloudflare-env-2NctU8i7.js +12 -0
- package/dist/index-DiH4OGAU.d.ts +101 -0
- package/dist/index.d.ts +23 -32
- package/dist/index.js +688 -265
- package/dist/module-types-Cjqo67ay.d.ts +91 -0
- package/dist/provider-loader-3ml65ZFy.d.ts +21 -0
- package/dist/runtime/provider-loader.d.ts +2 -17
- package/dist/runtime/provider-loader.js +4 -10
- package/dist/runtime/providers/cloudflare.d.ts +6 -11
- package/dist/runtime/providers/cloudflare.js +14 -11
- package/dist/runtime/providers/vercel.d.ts +5 -12
- package/dist/runtime/providers/vercel.js +16 -30
- package/dist/runtime/state.d.ts +1 -1
- package/dist/vite.d.ts +12 -28
- package/dist/vite.js +2276 -354
- package/package.json +68 -59
- package/dist/_shared-CJ2_pS4E.js +0 -53
- package/dist/cloudflare-retry-Cfra7MvS.js +0 -21
- package/dist/common-CS4FcWrh.d.ts +0 -369
- package/dist/index-B4j3Mvzr.d.ts +0 -146
- package/dist/integration-wkNE8jMO.js +0 -2032
- package/dist/module-types-CUcY8iuI.d.ts +0 -88
- package/dist/nitro.d.ts +0 -19
- package/dist/nitro.js +0 -488
- package/dist/provider-detection-IbezCeoR.js +0 -25
- package/dist/runtime/nitro-plugin.d.ts +0 -4
- package/dist/runtime/nitro-plugin.js +0 -8
- package/dist/sandbox/providers/cloudflare.d.ts +0 -7
- package/dist/sandbox/providers/cloudflare.js +0 -339
- package/dist/sandbox/providers/vercel.d.ts +0 -17
- package/dist/sandbox/providers/vercel.js +0 -538
- package/dist/shared-pqTHYWg1.d.ts +0 -8
- package/dist/utils-V7ODsDW_.js +0 -44
- package/dist/vercel-runtime-BPzvh_6V.js +0 -11
- /package/dist/{module-types-BomzaqnM.js → module-types-Dj1MFmHT.js} +0 -0
package/dist/vite.js
CHANGED
|
@@ -1,9 +1,24 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
|
|
1
|
+
import { t as getSandboxFeatureProvider } from "./module-types-Dj1MFmHT.js";
|
|
2
|
+
import { builtinModules, createRequire } from "node:module";
|
|
3
|
+
import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep } from "pathe";
|
|
4
|
+
import { existsSync, readdirSync, realpathSync } from "node:fs";
|
|
5
|
+
import { dirname as dirname$1, matchesGlob, relative as relative$1, resolve as resolve$1 } from "node:path";
|
|
6
|
+
import { glob, mkdir, readFile, realpath, stat, writeFile } from "node:fs/promises";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { createUnimport } from "unimport";
|
|
9
|
+
import { build } from "esbuild";
|
|
10
|
+
import { resolveModule } from "local-pkg";
|
|
11
|
+
import { resolvePathSync } from "mlly";
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { dirname as dirname$2, join as join$1, normalize as normalize$1 } from "node:path/posix";
|
|
14
|
+
[
|
|
15
|
+
".ts",
|
|
16
|
+
".mts",
|
|
17
|
+
".cts",
|
|
18
|
+
".js",
|
|
19
|
+
".mjs",
|
|
20
|
+
".cjs"
|
|
21
|
+
].flatMap((extension) => [["server", `email${extension}`], [`server.email${extension}`]]);
|
|
7
22
|
function createNoExternalMerger(packageName) {
|
|
8
23
|
return (current) => {
|
|
9
24
|
if (current === true) return true;
|
|
@@ -15,427 +30,2334 @@ function createNoExternalMerger(packageName) {
|
|
|
15
30
|
function isServerEnvironment(name, config) {
|
|
16
31
|
return name === "ssr" || config.consumer === "server";
|
|
17
32
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
db: "db",
|
|
23
|
-
env: "env",
|
|
24
|
-
kv: "kv",
|
|
25
|
-
queue: "queue",
|
|
26
|
-
schedule: "schedule",
|
|
27
|
-
sandbox: "sandbox",
|
|
28
|
-
workspace: "workspace",
|
|
29
|
-
workflow: "workflow"
|
|
30
|
-
};
|
|
31
|
-
function isViteCli(argv) {
|
|
32
|
-
return argv.some((arg) => /(?:^|[/\\])vite(?:\.[cm]?js)?$/.test(arg) || arg === "vite");
|
|
33
|
+
function includesNitroVitePlugin(value) {
|
|
34
|
+
if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
|
|
35
|
+
if (!value || typeof value !== "object") return false;
|
|
36
|
+
return "name" in value && value.name === "nitro:main";
|
|
33
37
|
}
|
|
34
|
-
function
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
38
|
+
function hasNitroVitePlugin(config) {
|
|
39
|
+
return includesNitroVitePlugin(config.plugins);
|
|
40
|
+
}
|
|
41
|
+
function deploymentPresetFromNitro(value) {
|
|
42
|
+
const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
|
|
43
|
+
if (!normalized) return;
|
|
44
|
+
if (normalized.startsWith("cloudflare")) return "cloudflare";
|
|
45
|
+
if (normalized.startsWith("deno")) return "deno";
|
|
46
|
+
if (normalized.startsWith("netlify")) return "netlify";
|
|
47
|
+
if (normalized === "node" || normalized.startsWith("node-")) return "node";
|
|
48
|
+
if (normalized.startsWith("vercel")) return "vercel";
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region ../internal/src/hosting.ts
|
|
52
|
+
function normalizeHosting(hosting) {
|
|
53
|
+
const normalized = hosting?.trim().toLowerCase().replaceAll("_", "-") || "";
|
|
54
|
+
if (normalized === "cloudflare") return "cloudflare-module";
|
|
55
|
+
return normalized;
|
|
56
|
+
}
|
|
57
|
+
function detectHosting(target) {
|
|
58
|
+
return normalizeHosting(target.options.preset || process.env.VITEHUB_HOSTING || "");
|
|
59
|
+
}
|
|
60
|
+
function getHostingProvider(hosting) {
|
|
61
|
+
const preset = deploymentPresetFromNitro(hosting);
|
|
62
|
+
if (preset === "cloudflare" || preset === "netlify" || preset === "vercel") return preset;
|
|
42
63
|
}
|
|
43
|
-
function
|
|
44
|
-
|
|
64
|
+
function getSupportedHostingProvider(hosting, supportedProviders) {
|
|
65
|
+
const provider = getHostingProvider(hosting);
|
|
66
|
+
if (!provider || !supportedProviders.includes(provider)) return void 0;
|
|
67
|
+
return provider;
|
|
45
68
|
}
|
|
46
69
|
//#endregion
|
|
47
|
-
//#region
|
|
48
|
-
function
|
|
49
|
-
|
|
70
|
+
//#region ../internal/src/build/paths.ts
|
|
71
|
+
function generatedDirSegments(productName) {
|
|
72
|
+
return [".vitehub", productName];
|
|
73
|
+
}
|
|
74
|
+
function ensureGeneratedDir(rootDir, productName) {
|
|
75
|
+
return resolve(rootDir, ...generatedDirSegments(productName));
|
|
76
|
+
}
|
|
77
|
+
function createImportPath(fromFile, targetFile) {
|
|
78
|
+
const importPath = relative(realpathIfExists(dirname(fromFile)), realpathIfExists(targetFile));
|
|
79
|
+
return importPath.startsWith(".") ? importPath : `./${importPath}`;
|
|
80
|
+
}
|
|
81
|
+
function realpathIfExists(path) {
|
|
82
|
+
try {
|
|
83
|
+
return realpathSync.native(path);
|
|
84
|
+
} catch {
|
|
85
|
+
return resolve(path);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
//#endregion
|
|
89
|
+
//#region ../internal/src/definition-catalog.ts
|
|
90
|
+
const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
|
|
91
|
+
const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
|
|
92
|
+
const ignoredDirs = new Set([
|
|
93
|
+
"node_modules",
|
|
94
|
+
"dist",
|
|
95
|
+
".output",
|
|
96
|
+
".nuxt",
|
|
97
|
+
".vercel",
|
|
98
|
+
".git",
|
|
99
|
+
".vitehub"
|
|
100
|
+
]);
|
|
101
|
+
function resolveDefinitionScanRoots(rootDir, scanDirs = []) {
|
|
102
|
+
return [...new Set([rootDir, ...scanDirs].filter(Boolean))];
|
|
103
|
+
}
|
|
104
|
+
function createSuffixDefinitionSource(source, roots, pattern, normalizeName, options = {}) {
|
|
50
105
|
return {
|
|
51
|
-
...
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
106
|
+
...options,
|
|
107
|
+
kind: "suffix",
|
|
108
|
+
normalizeName,
|
|
109
|
+
pattern,
|
|
110
|
+
roots,
|
|
111
|
+
source
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function readDirEntries(root) {
|
|
115
|
+
try {
|
|
116
|
+
return readdirSync(root, { withFileTypes: true });
|
|
117
|
+
} catch (error) {
|
|
118
|
+
if (error.code === "ENOENT") return [];
|
|
119
|
+
throw error;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
function listMatchingFiles(root, predicate, options = {}) {
|
|
123
|
+
const files = [];
|
|
124
|
+
for (const entry of readDirEntries(root)) {
|
|
125
|
+
const absolute = resolve(root, entry.name);
|
|
126
|
+
if (entry.isDirectory() && !entry.isSymbolicLink()) {
|
|
127
|
+
if (entry.name.startsWith(".")) continue;
|
|
128
|
+
if (ignoredDirs.has(entry.name)) continue;
|
|
129
|
+
files.push(...listMatchingFiles(absolute, predicate, options));
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (entry.name.startsWith(".") && !options.includeHidden) continue;
|
|
133
|
+
if (entry.isFile() && predicate(entry.name)) files.push(absolute);
|
|
134
|
+
}
|
|
135
|
+
return files.sort();
|
|
136
|
+
}
|
|
137
|
+
function listSourceFiles(root, options = {}) {
|
|
138
|
+
return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
|
|
139
|
+
}
|
|
140
|
+
function normalizePathDefinitionName(rootDir, file) {
|
|
141
|
+
return relative(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
|
|
142
|
+
}
|
|
143
|
+
function normalizeSuffixDefinitionName(rootDir, file, pattern, options = {}) {
|
|
144
|
+
const normalized = relative(rootDir, file).replace(pattern, "");
|
|
145
|
+
if (options.stripPrefix && normalized.startsWith(options.stripPrefix)) return normalized.slice(options.stripPrefix.length);
|
|
146
|
+
return normalized;
|
|
147
|
+
}
|
|
148
|
+
function sortDefinitions(definitions) {
|
|
149
|
+
return [...definitions.values()].sort((left, right) => left.name.localeCompare(right.name));
|
|
150
|
+
}
|
|
151
|
+
function registerDefinition(definitions, definition, sourceLabel) {
|
|
152
|
+
const existing = definitions.get(definition.name);
|
|
153
|
+
if (existing) throw new Error(`Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}`);
|
|
154
|
+
definitions.set(definition.name, definition);
|
|
155
|
+
}
|
|
156
|
+
function mergeDefinitions(feature, ...sources) {
|
|
157
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
158
|
+
for (const source of sources) {
|
|
159
|
+
if (!source) continue;
|
|
160
|
+
for (const definition of source) {
|
|
161
|
+
const existing = definitions.get(definition.name);
|
|
162
|
+
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"})`);
|
|
163
|
+
if (!existing) definitions.set(definition.name, definition);
|
|
64
164
|
}
|
|
165
|
+
}
|
|
166
|
+
return sortDefinitions(definitions);
|
|
167
|
+
}
|
|
168
|
+
function createDefinition(source, file, name) {
|
|
169
|
+
if (source.createDefinition) return source.createDefinition({
|
|
170
|
+
file,
|
|
171
|
+
name
|
|
172
|
+
});
|
|
173
|
+
return {
|
|
174
|
+
handler: file,
|
|
175
|
+
name,
|
|
176
|
+
source: source.source
|
|
65
177
|
};
|
|
66
178
|
}
|
|
179
|
+
function scanSuffixDefinitions(feature, source) {
|
|
180
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
181
|
+
for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => source.pattern.test(name), { includeHidden: source.includeHidden })) {
|
|
182
|
+
const name = source.normalizeName(root, file);
|
|
183
|
+
if (!name) continue;
|
|
184
|
+
registerDefinition(definitions, createDefinition(source, file, name), feature);
|
|
185
|
+
}
|
|
186
|
+
return sortDefinitions(definitions);
|
|
187
|
+
}
|
|
188
|
+
function scanDirectoryDefinitions(feature, source) {
|
|
189
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
190
|
+
for (const scanDir of source.scanDirs) {
|
|
191
|
+
const directory = resolve(scanDir, source.subdir);
|
|
192
|
+
for (const file of listSourceFiles(directory, { includeHidden: source.includeHidden })) {
|
|
193
|
+
const name = source.normalizeName ? source.normalizeName(directory, file) : normalizePathDefinitionName(directory, file);
|
|
194
|
+
if (!name) continue;
|
|
195
|
+
registerDefinition(definitions, createDefinition(source, file, name), feature);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return sortDefinitions(definitions);
|
|
199
|
+
}
|
|
200
|
+
function discoverDefinitions(feature, sources) {
|
|
201
|
+
return mergeDefinitions(feature, ...sources.map((source) => source.kind === "suffix" ? scanSuffixDefinitions(feature, source) : scanDirectoryDefinitions(feature, source)));
|
|
202
|
+
}
|
|
203
|
+
async function writeFileIfChanged(file, contents) {
|
|
204
|
+
if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
|
|
205
|
+
await mkdir(resolve(file, ".."), { recursive: true });
|
|
206
|
+
await writeFile(file, contents, "utf8");
|
|
207
|
+
}
|
|
67
208
|
//#endregion
|
|
68
|
-
//#region src/
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
209
|
+
//#region src/cloudflare.ts
|
|
210
|
+
const defaultCloudflareSandboxBinding = "SANDBOX";
|
|
211
|
+
const defaultCloudflareSandboxClassName = "Sandbox";
|
|
212
|
+
const defaultCloudflareSandboxMaxInstances = 12;
|
|
213
|
+
const require$1 = createRequire(import.meta.url);
|
|
214
|
+
function resolveCloudflareSandboxEntrypoint() {
|
|
215
|
+
try {
|
|
216
|
+
return require$1.resolve("@cloudflare/sandbox");
|
|
217
|
+
} catch {
|
|
218
|
+
throw new Error("[vitehub] The Cloudflare Sandbox provider requires @cloudflare/sandbox. Install a supported version before building.");
|
|
219
|
+
}
|
|
75
220
|
}
|
|
76
|
-
function
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
return
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
...stateFeatureConfig,
|
|
84
|
-
...nitroFeatureConfig
|
|
85
|
-
} } : {}
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
function resolveNitroOptions(rootDir, configKey, state, nitro, featureNitroModule, dev) {
|
|
89
|
-
const distDir = resolve(rootDir, typeof state.extraConfig?.build?.outDir === "string" ? state.extraConfig.build.outDir : "dist");
|
|
90
|
-
const srcDir = existsSync(resolve(rootDir, "src")) ? "src" : void 0;
|
|
91
|
-
const handlers = Array.isArray(nitro?.handlers) ? nitro.handlers : [];
|
|
92
|
-
const modules = [...featureNitroModule ? [featureNitroModule] : [], ...(nitro?.modules ?? []).filter(Boolean)];
|
|
221
|
+
function resolveCloudflareSandboxVersion() {
|
|
222
|
+
const pkg = require$1(join(resolveCloudflareSandboxEntrypoint(), "..", "..", "package.json"));
|
|
223
|
+
if (typeof pkg?.version !== "string") throw new Error("[vitehub] Could not resolve the installed @cloudflare/sandbox version.");
|
|
224
|
+
return pkg.version;
|
|
225
|
+
}
|
|
226
|
+
function resolveCloudflareSandboxEntrypointOptions(options = {}) {
|
|
227
|
+
if (options.className === "ContainerProxy") throw new Error("[vitehub] Cloudflare Sandbox className \"ContainerProxy\" is reserved by @cloudflare/sandbox. Configure a different className.");
|
|
93
228
|
return {
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
handlers,
|
|
99
|
-
imports: nitro?.imports,
|
|
100
|
-
modules,
|
|
101
|
-
plugins: nitro?.plugins,
|
|
102
|
-
preset: process.env.NITRO_PRESET || nitro?.preset || "node-server",
|
|
103
|
-
publicAssets: [{
|
|
104
|
-
baseURL: "/",
|
|
105
|
-
dir: distDir,
|
|
106
|
-
fallthrough: true,
|
|
107
|
-
maxAge: 0
|
|
108
|
-
}, ...(nitro?.publicAssets ?? []).map((asset) => ({
|
|
109
|
-
...asset,
|
|
110
|
-
maxAge: asset.maxAge ?? 0
|
|
111
|
-
}))],
|
|
112
|
-
rootDir,
|
|
113
|
-
runtimeConfig: mergeRuntimeConfig(state.runtimeConfig, nitro?.runtimeConfig, configKey),
|
|
114
|
-
srcDir
|
|
229
|
+
binding: options.binding || "SANDBOX",
|
|
230
|
+
className: options.className || "Sandbox",
|
|
231
|
+
migrationTag: options.migrationTag || "v1",
|
|
232
|
+
name: options.name || void 0
|
|
115
233
|
};
|
|
116
234
|
}
|
|
117
|
-
function
|
|
118
|
-
if (
|
|
119
|
-
return
|
|
235
|
+
function mergeRollupExternal(value, addition) {
|
|
236
|
+
if (typeof value === "undefined") return [addition];
|
|
237
|
+
if (Array.isArray(value)) return value.includes(addition) ? [...value] : [...value, addition];
|
|
238
|
+
if (typeof value === "string" || value instanceof RegExp) return [value, addition];
|
|
239
|
+
if (typeof value === "function") return (source, importer, isResolved) => source === addition || Boolean(value(source, importer, isResolved));
|
|
240
|
+
return value;
|
|
120
241
|
}
|
|
121
|
-
function
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
242
|
+
function configureCloudflareSandbox(target, options = {}) {
|
|
243
|
+
const { binding, className, migrationTag, name } = resolveCloudflareSandboxEntrypointOptions(options);
|
|
244
|
+
if (typeof target.cloudflare?.wrangler?.exports !== "undefined") throw new Error("[vitehub] Cloudflare Sandbox cannot compose legacy migrations with an existing Wrangler exports configuration. Remove exports or configure the Sandbox Durable Object explicitly.");
|
|
245
|
+
const existingMigrations = target.cloudflare?.wrangler?.migrations;
|
|
246
|
+
if (!existingMigrations?.some((entry) => entry.new_sqlite_classes?.includes(className)) && existingMigrations?.some((entry) => entry.tag === migrationTag)) throw new Error(`[vitehub] Cloudflare migration tag ${JSON.stringify(migrationTag)} is already in use. Configure a unique sandbox migrationTag.`);
|
|
247
|
+
if ((target.cloudflare?.wrangler?.durable_objects?.bindings)?.some((entry) => entry.name === binding && entry.class_name !== className)) throw new Error(`[vitehub] Cloudflare Durable Object binding ${JSON.stringify(binding)} is already in use. Configure a unique sandbox binding.`);
|
|
248
|
+
target.cloudflare ||= {};
|
|
249
|
+
target.cloudflare.wrangler ||= {};
|
|
250
|
+
target.cloudflare.wrangler.containers ||= [];
|
|
251
|
+
target.cloudflare.wrangler.durable_objects ||= {};
|
|
252
|
+
target.cloudflare.wrangler.durable_objects.bindings ||= [];
|
|
253
|
+
target.cloudflare.wrangler.migrations ||= [];
|
|
254
|
+
const containers = target.cloudflare.wrangler.containers;
|
|
255
|
+
const image = "./Dockerfile";
|
|
256
|
+
if (!containers.some((entry) => entry.class_name === className)) containers.push({
|
|
257
|
+
class_name: className,
|
|
258
|
+
image,
|
|
259
|
+
instance_type: "lite",
|
|
260
|
+
max_instances: defaultCloudflareSandboxMaxInstances,
|
|
261
|
+
...name ? { name } : {}
|
|
262
|
+
});
|
|
263
|
+
else {
|
|
264
|
+
const container = containers.find((entry) => entry.class_name === className);
|
|
265
|
+
container.image ??= image;
|
|
266
|
+
if (typeof container.max_instances !== "number") container.max_instances = defaultCloudflareSandboxMaxInstances;
|
|
267
|
+
if (name) container.name ??= name;
|
|
268
|
+
}
|
|
269
|
+
const bindings = target.cloudflare.wrangler.durable_objects.bindings;
|
|
270
|
+
if (!bindings.some((entry) => entry.name === binding && entry.class_name === className)) bindings.push({
|
|
271
|
+
name: binding,
|
|
272
|
+
class_name: className
|
|
128
273
|
});
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
}
|
|
134
|
-
async function copyViteBuildOutputToNitroPublicDir(nitro, rootDir, outDir) {
|
|
135
|
-
const distDir = resolve(rootDir, outDir || "dist");
|
|
136
|
-
if (!existsSync(distDir)) return;
|
|
137
|
-
await mkdir(nitro.options.output.publicDir, { recursive: true });
|
|
138
|
-
await cp(distDir, nitro.options.output.publicDir, {
|
|
139
|
-
force: true,
|
|
140
|
-
recursive: true
|
|
274
|
+
const migrations = target.cloudflare.wrangler.migrations;
|
|
275
|
+
if (!migrations.some((entry) => Array.isArray(entry.new_sqlite_classes) && entry.new_sqlite_classes.includes(className))) migrations.push({
|
|
276
|
+
tag: migrationTag,
|
|
277
|
+
new_sqlite_classes: [className]
|
|
141
278
|
});
|
|
142
279
|
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
280
|
+
function createCloudflareSandboxRollupPlugin(options = {}) {
|
|
281
|
+
const { className } = resolveCloudflareSandboxEntrypointOptions(options);
|
|
282
|
+
const cloudflareSandboxEntrypoint = resolveCloudflareSandboxEntrypoint();
|
|
283
|
+
const moduleId = "virtual:vitehub-sandbox-cloudflare-exports";
|
|
284
|
+
const resolvedModuleId = "\0virtual:vitehub-sandbox-cloudflare-exports";
|
|
285
|
+
return {
|
|
286
|
+
name: "vitehub-sandbox-cloudflare-exports",
|
|
287
|
+
buildStart() {
|
|
288
|
+
this.emitFile({
|
|
289
|
+
type: "chunk",
|
|
290
|
+
id: moduleId,
|
|
291
|
+
fileName: "sandbox-cloudflare-exports.mjs"
|
|
292
|
+
});
|
|
293
|
+
},
|
|
294
|
+
resolveId(id) {
|
|
295
|
+
if (id === moduleId) return resolvedModuleId;
|
|
296
|
+
if (id === "@cloudflare/sandbox") return cloudflareSandboxEntrypoint;
|
|
297
|
+
},
|
|
298
|
+
load(id) {
|
|
299
|
+
if (id === resolvedModuleId) return [
|
|
300
|
+
`import { Sandbox as CloudflareSandbox } from '@cloudflare/sandbox'`,
|
|
301
|
+
`export { ContainerProxy } from '@cloudflare/sandbox'`,
|
|
302
|
+
``,
|
|
303
|
+
`export class ${className} extends CloudflareSandbox {}`,
|
|
304
|
+
``
|
|
305
|
+
].join("\n");
|
|
306
|
+
},
|
|
307
|
+
renderChunk(code, chunk) {
|
|
308
|
+
if (!chunk.isEntry) return null;
|
|
309
|
+
const exportedNames = new Set(chunk.exports);
|
|
310
|
+
const missingExports = [className, "ContainerProxy"].filter((name) => !exportedNames.has(name));
|
|
311
|
+
if (!missingExports.length) return null;
|
|
312
|
+
const exportsPath = relative(dirname(chunk.fileName), "sandbox-cloudflare-exports.mjs").replace(/\\/g, "/");
|
|
313
|
+
const importPath = exportsPath.startsWith(".") ? exportsPath : `./${exportsPath}`;
|
|
314
|
+
return {
|
|
315
|
+
code: `${code}\nexport { ${missingExports.join(", ")} } from ${JSON.stringify(importPath)}\n`,
|
|
316
|
+
map: null
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
function installCloudflareSandboxEntrypoint(target, options = {}) {
|
|
322
|
+
const { className } = resolveCloudflareSandboxEntrypointOptions(options);
|
|
323
|
+
target.rollupConfig ||= {};
|
|
324
|
+
const plugins = Array.isArray(target.rollupConfig.plugins) ? target.rollupConfig.plugins : target.rollupConfig.plugins ? [target.rollupConfig.plugins] : [];
|
|
325
|
+
target.rollupConfig.plugins = plugins;
|
|
326
|
+
if (plugins.some((plugin) => typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === `vitehub-sandbox-cloudflare-exports:${className}`)) return;
|
|
327
|
+
const plugin = createCloudflareSandboxRollupPlugin({ className });
|
|
328
|
+
plugin.name = `vitehub-sandbox-cloudflare-exports:${className}`;
|
|
329
|
+
plugins.push(plugin);
|
|
330
|
+
}
|
|
331
|
+
async function writeCloudflareSandboxDockerfile(serverDir) {
|
|
332
|
+
const dockerfilePath = join(serverDir, "Dockerfile");
|
|
333
|
+
await writeFileIfChanged(dockerfilePath, `FROM docker.io/cloudflare/sandbox:${resolveCloudflareSandboxVersion()}\n`);
|
|
334
|
+
return dockerfilePath;
|
|
335
|
+
}
|
|
336
|
+
function relativeWranglerPath(from, to) {
|
|
337
|
+
const path = relative(from, to).replace(/\\/g, "/");
|
|
338
|
+
return path.startsWith(".") ? path : `./${path}`;
|
|
339
|
+
}
|
|
340
|
+
async function configureCloudflareSandboxNitro(targetValue, rootDir, options = {}) {
|
|
341
|
+
const target = targetValue || {};
|
|
342
|
+
const serverDir = resolve(rootDir, target.output?.serverDir || ".output/server");
|
|
343
|
+
const resolvedOptions = resolveCloudflareSandboxEntrypointOptions(options);
|
|
344
|
+
const existingImage = (target.cloudflare?.wrangler?.containers?.find((entry) => entry.class_name === resolvedOptions.className))?.image?.replace(/\\/g, "/");
|
|
345
|
+
configureCloudflareSandbox(target, resolvedOptions);
|
|
346
|
+
const container = target.cloudflare.wrangler.containers.find((entry) => entry.class_name === resolvedOptions.className);
|
|
347
|
+
if (typeof existingImage !== "string" || existingImage.endsWith("/.vitehub/sandbox/Dockerfile")) {
|
|
348
|
+
container.image = relativeWranglerPath(serverDir, await writeCloudflareSandboxDockerfile(resolve(rootDir, ".vitehub/sandbox")));
|
|
349
|
+
container.image_build_context = relativeWranglerPath(serverDir, rootDir);
|
|
150
350
|
}
|
|
151
|
-
|
|
152
|
-
|
|
351
|
+
const wrangler = target.cloudflare.wrangler;
|
|
352
|
+
wrangler.compatibility_flags = Array.isArray(wrangler.compatibility_flags) ? [...wrangler.compatibility_flags] : [];
|
|
353
|
+
if (!wrangler.compatibility_flags.includes("nodejs_compat")) wrangler.compatibility_flags.push("nodejs_compat");
|
|
354
|
+
target.rollupConfig ||= {};
|
|
355
|
+
target.rollupConfig.external = mergeRollupExternal(target.rollupConfig.external, "cloudflare:workers");
|
|
356
|
+
installCloudflareSandboxEntrypoint(target, resolvedOptions);
|
|
357
|
+
return target;
|
|
358
|
+
}
|
|
359
|
+
//#endregion
|
|
360
|
+
//#region src/internal/shared/discovered-definition/bundler.ts
|
|
361
|
+
const builtinModuleSet$1 = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
|
|
362
|
+
function resolveDefinitionLoader(options) {
|
|
363
|
+
let loader = options.loader;
|
|
364
|
+
if (!loader) {
|
|
365
|
+
const f = options.filename;
|
|
366
|
+
if (f.endsWith(".tsx")) loader = "tsx";
|
|
367
|
+
else if (f.endsWith(".jsx")) loader = "jsx";
|
|
368
|
+
else if (f.endsWith(".js") || f.endsWith(".mjs") || f.endsWith(".cjs")) loader = "js";
|
|
369
|
+
else loader = "ts";
|
|
370
|
+
}
|
|
371
|
+
return loader;
|
|
372
|
+
}
|
|
373
|
+
function isJsxDefinitionLoader(options) {
|
|
374
|
+
const loader = resolveDefinitionLoader(options);
|
|
375
|
+
return loader === "tsx" || loader === "jsx";
|
|
376
|
+
}
|
|
377
|
+
async function bundleDiscoveredDefinitionModule(options) {
|
|
378
|
+
const output = (await build({
|
|
379
|
+
alias: options.alias,
|
|
380
|
+
stdin: {
|
|
381
|
+
contents: options.source,
|
|
382
|
+
loader: resolveDefinitionLoader(options),
|
|
383
|
+
resolveDir: dirname(options.filename),
|
|
384
|
+
sourcefile: options.filename
|
|
385
|
+
},
|
|
386
|
+
bundle: true,
|
|
387
|
+
write: false,
|
|
388
|
+
format: "esm",
|
|
389
|
+
platform: "node",
|
|
390
|
+
target: "es2022",
|
|
391
|
+
logLevel: "silent",
|
|
392
|
+
jsx: isJsxDefinitionLoader(options) ? "automatic" : void 0,
|
|
393
|
+
jsxImportSource: isJsxDefinitionLoader(options) ? "react" : void 0,
|
|
394
|
+
packages: options.packages === "external" ? "external" : void 0,
|
|
395
|
+
external: [...builtinModuleSet$1, ...options.external || []],
|
|
396
|
+
plugins: options.plugins
|
|
397
|
+
})).outputFiles?.[0]?.text;
|
|
398
|
+
if (!output) throw new Error(`[vitehub] Failed to bundle discovered definition "${options.filename}".`);
|
|
399
|
+
return output;
|
|
400
|
+
}
|
|
401
|
+
async function bundleDiscoveredDefinitionModuleGraph(options) {
|
|
402
|
+
const outdir = resolve(dirname(options.filename), ".vitehub-discovered-definition");
|
|
403
|
+
const result = await build({
|
|
404
|
+
alias: options.alias,
|
|
405
|
+
stdin: {
|
|
406
|
+
contents: options.source,
|
|
407
|
+
loader: resolveDefinitionLoader(options),
|
|
408
|
+
resolveDir: dirname(options.filename),
|
|
409
|
+
sourcefile: options.filename
|
|
410
|
+
},
|
|
411
|
+
bundle: true,
|
|
412
|
+
splitting: true,
|
|
413
|
+
entryNames: "definition",
|
|
414
|
+
chunkNames: "chunks/[name]-[hash]",
|
|
415
|
+
outdir,
|
|
416
|
+
write: false,
|
|
417
|
+
format: "esm",
|
|
418
|
+
platform: "node",
|
|
419
|
+
target: "es2022",
|
|
420
|
+
logLevel: "silent",
|
|
421
|
+
jsx: isJsxDefinitionLoader(options) ? "automatic" : void 0,
|
|
422
|
+
jsxImportSource: isJsxDefinitionLoader(options) ? "react" : void 0,
|
|
423
|
+
packages: options.packages === "external" ? "external" : void 0,
|
|
424
|
+
external: [...builtinModuleSet$1, ...options.external || []],
|
|
425
|
+
plugins: options.plugins
|
|
153
426
|
});
|
|
427
|
+
const modules = Object.fromEntries((result.outputFiles || []).map((outputFile) => {
|
|
428
|
+
return [relative(outdir, outputFile.path), outputFile.text];
|
|
429
|
+
}));
|
|
430
|
+
if (!modules["definition.js"]) throw new Error(`[vitehub] Failed to bundle discovered definition graph "${options.filename}".`);
|
|
431
|
+
return {
|
|
432
|
+
entry: "definition.js",
|
|
433
|
+
modules
|
|
434
|
+
};
|
|
154
435
|
}
|
|
155
436
|
//#endregion
|
|
156
|
-
//#region src/internal/shared/
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
437
|
+
//#region src/internal/shared/discovered-definition/ast.ts
|
|
438
|
+
const typescript$1 = createRequire(import.meta.url)("typescript");
|
|
439
|
+
function resolveImportLocalName(entry) {
|
|
440
|
+
return entry.as || entry.name;
|
|
441
|
+
}
|
|
442
|
+
function getScriptKind(id) {
|
|
443
|
+
const scriptKind = typescript$1.ScriptKind;
|
|
444
|
+
if (id.endsWith(".tsx")) return typescript$1.ScriptKind.TSX;
|
|
445
|
+
if (id.endsWith(".jsx")) return typescript$1.ScriptKind.JSX;
|
|
446
|
+
if (id.endsWith(".mts")) return scriptKind.MTS ?? typescript$1.ScriptKind.TS;
|
|
447
|
+
if (id.endsWith(".cts")) return scriptKind.CTS ?? typescript$1.ScriptKind.TS;
|
|
448
|
+
if (id.endsWith(".mjs")) return typescript$1.ScriptKind.JS;
|
|
449
|
+
if (id.endsWith(".cjs")) return typescript$1.ScriptKind.JS;
|
|
450
|
+
if (id.endsWith(".js")) return typescript$1.ScriptKind.JS;
|
|
451
|
+
return typescript$1.ScriptKind.TS;
|
|
452
|
+
}
|
|
453
|
+
function createSourceFile(id, source) {
|
|
454
|
+
return typescript$1.createSourceFile(id, source, typescript$1.ScriptTarget.Latest, true, getScriptKind(id));
|
|
455
|
+
}
|
|
456
|
+
function hasModifier(node, kind) {
|
|
457
|
+
return typescript$1.canHaveModifiers(node) && (typescript$1.getModifiers(node)?.some((modifier) => modifier.kind === kind) ?? false);
|
|
458
|
+
}
|
|
459
|
+
function hasExportedType(source, id, name) {
|
|
460
|
+
return createSourceFile(id, source).statements.some((statement) => {
|
|
461
|
+
if ((typescript$1.isInterfaceDeclaration(statement) || typescript$1.isTypeAliasDeclaration(statement)) && statement.name.text === name) return hasModifier(statement, typescript$1.SyntaxKind.ExportKeyword);
|
|
462
|
+
if (!typescript$1.isExportDeclaration(statement) || !statement.exportClause || !typescript$1.isNamedExports(statement.exportClause)) return false;
|
|
463
|
+
return statement.exportClause.elements.some((element) => element.name.text === name && (statement.isTypeOnly || element.isTypeOnly));
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
function collectRuntimeModuleSpecifiers(source, id) {
|
|
467
|
+
const sourceFile = createSourceFile(id, source);
|
|
468
|
+
const specifiers = [];
|
|
469
|
+
let hasNonLiteralDynamicImport = false;
|
|
470
|
+
function addSpecifier(node) {
|
|
471
|
+
if (node && typescript$1.isStringLiteralLike(node)) specifiers.push({
|
|
472
|
+
node,
|
|
473
|
+
specifier: node.text
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
function visit(node) {
|
|
477
|
+
if (typescript$1.isImportDeclaration(node)) {
|
|
478
|
+
const clause = node.importClause;
|
|
479
|
+
const bindings = clause?.namedBindings;
|
|
480
|
+
if (!clause || !clause.isTypeOnly && (Boolean(clause.name) || !bindings || typescript$1.isNamespaceImport(bindings) || bindings.elements.length === 0 || bindings.elements.some((element) => !element.isTypeOnly))) addSpecifier(node.moduleSpecifier);
|
|
481
|
+
} else if (typescript$1.isExportDeclaration(node)) {
|
|
482
|
+
const clause = node.exportClause;
|
|
483
|
+
if (!node.isTypeOnly && (!clause || typescript$1.isNamespaceExport(clause) || clause.elements.length === 0 || clause.elements.some((element) => !element.isTypeOnly))) addSpecifier(node.moduleSpecifier);
|
|
484
|
+
} else if (typescript$1.isCallExpression(node) && node.expression.kind === typescript$1.SyntaxKind.ImportKeyword) {
|
|
485
|
+
const argument = node.arguments[0];
|
|
486
|
+
if (argument && typescript$1.isStringLiteralLike(argument)) addSpecifier(argument);
|
|
487
|
+
else hasNonLiteralDynamicImport = true;
|
|
488
|
+
}
|
|
489
|
+
typescript$1.forEachChild(node, visit);
|
|
490
|
+
}
|
|
491
|
+
visit(sourceFile);
|
|
492
|
+
return {
|
|
493
|
+
hasNonLiteralDynamicImport,
|
|
494
|
+
sourceFile,
|
|
495
|
+
specifiers
|
|
173
496
|
};
|
|
174
|
-
return [
|
|
175
|
-
`const state = ${JSON.stringify(payload, null, 2)}`,
|
|
176
|
-
"export const feature = state.feature",
|
|
177
|
-
"export const configKey = state.configKey",
|
|
178
|
-
"export const config = state.config",
|
|
179
|
-
"export const runtimeConfig = state.runtimeConfig",
|
|
180
|
-
"export const hosting = state.hosting",
|
|
181
|
-
"export const rootDir = state.rootDir",
|
|
182
|
-
"export const mode = state.mode",
|
|
183
|
-
"export const command = state.command",
|
|
184
|
-
"export default state",
|
|
185
|
-
""
|
|
186
|
-
].join("\n");
|
|
187
497
|
}
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
498
|
+
function findRuntimeModuleSpecifiers(source, id) {
|
|
499
|
+
return collectRuntimeModuleSpecifiers(source, id).specifiers.map((entry) => entry.specifier);
|
|
500
|
+
}
|
|
501
|
+
function hasNonLiteralDynamicImport(source, id) {
|
|
502
|
+
return collectRuntimeModuleSpecifiers(source, id).hasNonLiteralDynamicImport;
|
|
503
|
+
}
|
|
504
|
+
function propertyAccessRoot(expression) {
|
|
505
|
+
const properties = [];
|
|
506
|
+
let current = expression;
|
|
507
|
+
while (typescript$1.isPropertyAccessExpression(current) || typescript$1.isElementAccessExpression(current)) {
|
|
508
|
+
if (typescript$1.isPropertyAccessExpression(current)) {
|
|
509
|
+
properties.unshift(current.name.text);
|
|
510
|
+
current = current.expression;
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
const argument = current.argumentExpression;
|
|
514
|
+
properties.unshift(argument && typescript$1.isStringLiteralLike(argument) ? argument.text : "*");
|
|
515
|
+
current = current.expression;
|
|
516
|
+
}
|
|
199
517
|
return {
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
resolvedIds,
|
|
203
|
-
extraConfig: setupResult && "config" in setupResult ? setupResult.config : void 0
|
|
518
|
+
current,
|
|
519
|
+
properties
|
|
204
520
|
};
|
|
205
521
|
}
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
522
|
+
function findCommonJSImportEqualsSpecifiers(source, id) {
|
|
523
|
+
const sourceFile = createSourceFile(id, source);
|
|
524
|
+
const specifiers = [];
|
|
525
|
+
function visit(node) {
|
|
526
|
+
if (typescript$1.isImportEqualsDeclaration(node) && !node.isTypeOnly && typescript$1.isExternalModuleReference(node.moduleReference)) {
|
|
527
|
+
const expression = node.moduleReference.expression;
|
|
528
|
+
specifiers.push({
|
|
529
|
+
path: id,
|
|
530
|
+
specifier: expression && typescript$1.isStringLiteralLike(expression) ? expression.text : void 0,
|
|
531
|
+
syntax: "import-equals"
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
typescript$1.forEachChild(node, visit);
|
|
535
|
+
}
|
|
536
|
+
visit(sourceFile);
|
|
537
|
+
return specifiers;
|
|
538
|
+
}
|
|
539
|
+
function isExecutableIdentifierReference(node) {
|
|
540
|
+
const parent = node.parent;
|
|
541
|
+
if (typescript$1.isImportClause(parent) || typescript$1.isImportSpecifier(parent) || typescript$1.isNamespaceImport(parent) || typescript$1.isNamespaceExport(parent)) return false;
|
|
542
|
+
if (typescript$1.isExportSpecifier(parent)) {
|
|
543
|
+
if (parent.parent.parent.moduleSpecifier) return false;
|
|
544
|
+
return parent.propertyName ? parent.propertyName === node : parent.name === node;
|
|
545
|
+
}
|
|
546
|
+
if (typescript$1.isBindingElement(parent) && (parent.name === node || parent.propertyName === node)) return false;
|
|
547
|
+
if (typescript$1.isPropertyAccessExpression(parent) && parent.name === node) return false;
|
|
548
|
+
if (typescript$1.isLabeledStatement(parent) || typescript$1.isBreakStatement(parent) || typescript$1.isContinueStatement(parent)) return false;
|
|
549
|
+
const namedParent = parent;
|
|
550
|
+
if (!typescript$1.isShorthandPropertyAssignment(parent) && namedParent.name === node) return false;
|
|
551
|
+
return parent.propertyName !== node;
|
|
552
|
+
}
|
|
553
|
+
function findExecutableCommonJSModuleSpecifiers(sources) {
|
|
554
|
+
const executableSources = new Map([...sources].map(([path, source]) => [`/${path.replace(/^[/]+/, "")}`, source]));
|
|
555
|
+
const options = {
|
|
556
|
+
allowJs: true,
|
|
557
|
+
checkJs: false,
|
|
558
|
+
module: typescript$1.ModuleKind.ESNext,
|
|
559
|
+
moduleDetection: typescript$1.ModuleDetectionKind.Force,
|
|
560
|
+
noLib: true,
|
|
561
|
+
noResolve: true,
|
|
562
|
+
target: typescript$1.ScriptTarget.ES2022,
|
|
563
|
+
types: []
|
|
564
|
+
};
|
|
565
|
+
const sourceFiles = /* @__PURE__ */ new Map();
|
|
566
|
+
const program = typescript$1.createProgram({
|
|
567
|
+
host: {
|
|
568
|
+
fileExists: (fileName) => executableSources.has(fileName),
|
|
569
|
+
getCanonicalFileName: (fileName) => fileName,
|
|
570
|
+
getCurrentDirectory: () => "/",
|
|
571
|
+
getDefaultLibFileName: () => "",
|
|
572
|
+
getNewLine: () => "\n",
|
|
573
|
+
getSourceFile(fileName, languageVersion) {
|
|
574
|
+
const source = executableSources.get(fileName);
|
|
575
|
+
if (source === void 0) return void 0;
|
|
576
|
+
let sourceFile = sourceFiles.get(fileName);
|
|
577
|
+
if (!sourceFile) {
|
|
578
|
+
sourceFile = typescript$1.createSourceFile(fileName, source, languageVersion, true, typescript$1.ScriptKind.JS);
|
|
579
|
+
sourceFiles.set(fileName, sourceFile);
|
|
580
|
+
}
|
|
581
|
+
return sourceFile;
|
|
582
|
+
},
|
|
583
|
+
readFile: (fileName) => executableSources.get(fileName),
|
|
584
|
+
useCaseSensitiveFileNames: () => true,
|
|
585
|
+
writeFile: () => {}
|
|
222
586
|
},
|
|
223
|
-
|
|
224
|
-
|
|
587
|
+
options,
|
|
588
|
+
rootNames: [...executableSources.keys()]
|
|
225
589
|
});
|
|
590
|
+
const checker = program.getTypeChecker();
|
|
591
|
+
const specifiers = [];
|
|
592
|
+
function isRuntimeBindingDeclaration(node) {
|
|
593
|
+
return typescript$1.isBindingElement(node) || typescript$1.isClassDeclaration(node) || typescript$1.isClassExpression(node) || typescript$1.isFunctionDeclaration(node) || typescript$1.isFunctionExpression(node) || typescript$1.isImportClause(node) || typescript$1.isImportSpecifier(node) || typescript$1.isNamespaceImport(node) || typescript$1.isParameter(node) || typescript$1.isVariableDeclaration(node);
|
|
594
|
+
}
|
|
595
|
+
function isBound(node) {
|
|
596
|
+
return (typescript$1.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node))?.declarations?.some(isRuntimeBindingDeclaration) ?? false;
|
|
597
|
+
}
|
|
598
|
+
function visit(sourceFile, node) {
|
|
599
|
+
if (typescript$1.isCallExpression(node) && typescript$1.isIdentifier(node.expression) && node.expression.text === "require" && !isBound(node.expression)) {
|
|
600
|
+
const argument = node.arguments[0];
|
|
601
|
+
specifiers.push({
|
|
602
|
+
path: sourceFile.fileName.slice(1),
|
|
603
|
+
specifier: argument && typescript$1.isStringLiteralLike(argument) ? argument.text : void 0,
|
|
604
|
+
syntax: "require"
|
|
605
|
+
});
|
|
606
|
+
} else if (typescript$1.isPropertyAccessExpression(node) || typescript$1.isElementAccessExpression(node)) {
|
|
607
|
+
const { current, properties } = propertyAccessRoot(node);
|
|
608
|
+
if (typescript$1.isIdentifier(current) && current.text === "require" && !isBound(current)) specifiers.push({
|
|
609
|
+
path: sourceFile.fileName.slice(1),
|
|
610
|
+
specifier: properties.join("."),
|
|
611
|
+
syntax: "require-property"
|
|
612
|
+
});
|
|
613
|
+
} else if (typescript$1.isBinaryExpression(node) && node.operatorToken.kind >= typescript$1.SyntaxKind.FirstAssignment && node.operatorToken.kind <= typescript$1.SyntaxKind.LastAssignment) {
|
|
614
|
+
const { current, properties } = propertyAccessRoot(node.left);
|
|
615
|
+
if (typescript$1.isIdentifier(current) && current.text === "module" && !isBound(current) && properties[0] === "exports") specifiers.push({
|
|
616
|
+
path: sourceFile.fileName.slice(1),
|
|
617
|
+
syntax: "module-exports-assignment"
|
|
618
|
+
});
|
|
619
|
+
else if (typescript$1.isIdentifier(current) && current.text === "exports" && !isBound(current) && properties.length) specifiers.push({
|
|
620
|
+
path: sourceFile.fileName.slice(1),
|
|
621
|
+
syntax: "exports-assignment"
|
|
622
|
+
});
|
|
623
|
+
} else if (typescript$1.isIdentifier(node) && (node.text === "module" || node.text === "exports") && isExecutableIdentifierReference(node) && !isBound(node)) specifiers.push({
|
|
624
|
+
path: sourceFile.fileName.slice(1),
|
|
625
|
+
syntax: node.text === "module" ? "module-reference" : "exports-reference"
|
|
626
|
+
});
|
|
627
|
+
typescript$1.forEachChild(node, (child) => visit(sourceFile, child));
|
|
628
|
+
}
|
|
629
|
+
for (const sourceFile of program.getSourceFiles()) visit(sourceFile, sourceFile);
|
|
630
|
+
return specifiers;
|
|
226
631
|
}
|
|
227
|
-
function
|
|
228
|
-
const
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
632
|
+
function rewriteRuntimeRelativeModuleSpecifiers(source, id, rewrite) {
|
|
633
|
+
const { sourceFile, specifiers } = collectRuntimeModuleSpecifiers(source, id);
|
|
634
|
+
const edits = [];
|
|
635
|
+
for (const { node, specifier } of specifiers) {
|
|
636
|
+
if (!/^\.\.?\//.test(specifier)) continue;
|
|
637
|
+
const replacement = rewrite(specifier);
|
|
638
|
+
if (replacement !== specifier) edits.push({
|
|
639
|
+
start: node.getStart(sourceFile),
|
|
640
|
+
end: node.getEnd(),
|
|
641
|
+
replacement: JSON.stringify(replacement)
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
return edits.sort((left, right) => right.start - left.start).reduce((contents, edit) => `${contents.slice(0, edit.start)}${edit.replacement}${contents.slice(edit.end)}`, source);
|
|
645
|
+
}
|
|
646
|
+
function collectExplicitImportNames(sourceFile) {
|
|
647
|
+
const names = /* @__PURE__ */ new Set();
|
|
648
|
+
for (const statement of sourceFile.statements) {
|
|
649
|
+
if (!typescript$1.isImportDeclaration(statement)) continue;
|
|
650
|
+
const clause = statement.importClause;
|
|
651
|
+
if (!clause) continue;
|
|
652
|
+
if (clause.name) names.add(clause.name.text);
|
|
653
|
+
const bindings = clause.namedBindings;
|
|
654
|
+
if (!bindings) continue;
|
|
655
|
+
if (typescript$1.isNamespaceImport(bindings)) {
|
|
656
|
+
names.add(bindings.name.text);
|
|
657
|
+
continue;
|
|
658
|
+
}
|
|
659
|
+
for (const element of bindings.elements) names.add(element.name.text);
|
|
660
|
+
}
|
|
661
|
+
return names;
|
|
662
|
+
}
|
|
663
|
+
function collectDeclaredTypeNames(sourceFile) {
|
|
664
|
+
const names = /* @__PURE__ */ new Set();
|
|
665
|
+
function visit(node) {
|
|
666
|
+
if ((typescript$1.isInterfaceDeclaration(node) || typescript$1.isTypeAliasDeclaration(node) || typescript$1.isClassDeclaration(node) || typescript$1.isEnumDeclaration(node)) && node.name) names.add(node.name.text);
|
|
667
|
+
if ((typescript$1.isFunctionDeclaration(node) || typescript$1.isClassDeclaration(node) || typescript$1.isInterfaceDeclaration(node) || typescript$1.isMethodDeclaration(node) || typescript$1.isArrowFunction(node) || typescript$1.isFunctionExpression(node) || typescript$1.isTypeAliasDeclaration(node)) && node.typeParameters) for (const parameter of node.typeParameters) names.add(parameter.name.text);
|
|
668
|
+
typescript$1.forEachChild(node, visit);
|
|
669
|
+
}
|
|
670
|
+
visit(sourceFile);
|
|
671
|
+
return names;
|
|
672
|
+
}
|
|
673
|
+
function collectTypeReferenceNames(sourceFile) {
|
|
674
|
+
const names = /* @__PURE__ */ new Set();
|
|
675
|
+
function addEntityName(name) {
|
|
676
|
+
if (typescript$1.isIdentifier(name)) names.add(name.text);
|
|
677
|
+
}
|
|
678
|
+
function visit(node) {
|
|
679
|
+
if (typescript$1.isImportTypeNode(node) || typescript$1.isTypeQueryNode(node)) return;
|
|
680
|
+
if (typescript$1.isTypeReferenceNode(node)) {
|
|
681
|
+
addEntityName(node.typeName);
|
|
682
|
+
node.typeArguments?.forEach((argument) => visit(argument));
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
if (typescript$1.isExpressionWithTypeArguments(node)) {
|
|
686
|
+
if (typescript$1.isIdentifier(node.expression)) names.add(node.expression.text);
|
|
687
|
+
node.typeArguments?.forEach((argument) => visit(argument));
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
typescript$1.forEachChild(node, visit);
|
|
691
|
+
}
|
|
692
|
+
visit(sourceFile);
|
|
693
|
+
return names;
|
|
694
|
+
}
|
|
695
|
+
function groupTypeImports(imports) {
|
|
696
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
697
|
+
for (const entry of imports) {
|
|
698
|
+
const from = entry.typeFrom || entry.from;
|
|
699
|
+
const entries = grouped.get(from);
|
|
700
|
+
if (entries) {
|
|
701
|
+
entries.push(entry);
|
|
702
|
+
continue;
|
|
703
|
+
}
|
|
704
|
+
grouped.set(from, [entry]);
|
|
705
|
+
}
|
|
706
|
+
return grouped;
|
|
707
|
+
}
|
|
708
|
+
function stringifyTypeImport(entry) {
|
|
709
|
+
const localName = resolveImportLocalName(entry);
|
|
710
|
+
if (localName === entry.name) return entry.name;
|
|
711
|
+
return `${entry.name} as ${localName}`;
|
|
712
|
+
}
|
|
713
|
+
function injectTypeImports(source, imports, id) {
|
|
714
|
+
if (!imports.length) return source;
|
|
715
|
+
const importStatements = createSourceFile(id, source).statements.filter(typescript$1.isImportDeclaration);
|
|
716
|
+
const groupedImports = groupTypeImports(imports);
|
|
717
|
+
const block = Array.from(groupedImports.entries()).map(([from, entries]) => `import type { ${entries.map(stringifyTypeImport).join(", ")} } from ${JSON.stringify(from)}`).join("\n");
|
|
718
|
+
if (!block) return source;
|
|
719
|
+
const insertAt = importStatements.at(-1)?.end ?? (source.startsWith("#!") ? source.indexOf("\n") + 1 : 0);
|
|
720
|
+
const prefix = source.slice(0, insertAt);
|
|
721
|
+
const suffix = source.slice(insertAt);
|
|
722
|
+
const needsLeadingNewline = insertAt > 0 && !prefix.endsWith("\n");
|
|
723
|
+
const needsTrailingNewline = suffix.length > 0 && !suffix.startsWith("\n");
|
|
724
|
+
return `${prefix}${needsLeadingNewline ? "\n" : ""}${block}${needsTrailingNewline ? "\n" : ""}${suffix}`;
|
|
725
|
+
}
|
|
726
|
+
async function injectTypeImportsFromUnimport(source, id, imports) {
|
|
727
|
+
const sourceFile = createSourceFile(id, source);
|
|
728
|
+
const explicitImports = collectExplicitImportNames(sourceFile);
|
|
729
|
+
const declaredTypes = collectDeclaredTypeNames(sourceFile);
|
|
730
|
+
const usedTypes = collectTypeReferenceNames(sourceFile);
|
|
731
|
+
const pendingImports = [];
|
|
732
|
+
for (const entry of imports) {
|
|
733
|
+
if (!entry.type || entry.disabled) continue;
|
|
734
|
+
const localName = resolveImportLocalName(entry);
|
|
735
|
+
if (!usedTypes.has(localName)) continue;
|
|
736
|
+
if (explicitImports.has(localName) || declaredTypes.has(localName)) continue;
|
|
737
|
+
pendingImports.push(entry);
|
|
738
|
+
explicitImports.add(localName);
|
|
739
|
+
}
|
|
740
|
+
return injectTypeImports(source, pendingImports, id);
|
|
741
|
+
}
|
|
742
|
+
//#endregion
|
|
743
|
+
//#region src/internal/shared/server-imports.ts
|
|
744
|
+
function isServerAutoImportEnabled(imports) {
|
|
745
|
+
return imports !== false && imports?.autoImport !== false;
|
|
746
|
+
}
|
|
747
|
+
//#endregion
|
|
748
|
+
//#region src/internal/shared/discovered-definition.ts
|
|
749
|
+
function normalizeDir(rootDir, dir) {
|
|
750
|
+
if (typeof dir === "string") return isAbsolute(dir) ? dir : resolve(rootDir, dir);
|
|
751
|
+
return {
|
|
752
|
+
...dir,
|
|
753
|
+
glob: isAbsolute(dir.glob) ? dir.glob : resolve(rootDir, dir.glob)
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
function normalizePresetImport(from, entry) {
|
|
757
|
+
if (typeof entry === "string") return {
|
|
758
|
+
from,
|
|
759
|
+
name: entry
|
|
760
|
+
};
|
|
761
|
+
return {
|
|
762
|
+
from,
|
|
763
|
+
name: entry.name,
|
|
764
|
+
...entry.as ? { as: entry.as } : {},
|
|
765
|
+
...entry.type ? { type: true } : {}
|
|
234
766
|
};
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
767
|
+
}
|
|
768
|
+
function normalizeServerImport(entry) {
|
|
769
|
+
return {
|
|
770
|
+
from: entry.from,
|
|
771
|
+
name: entry.name,
|
|
772
|
+
...entry.as ? { as: entry.as } : {},
|
|
773
|
+
...entry.type ? { type: true } : {}
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
function resolveDefaultImportDirs(rootDir, scanRoots) {
|
|
777
|
+
return scanRoots.flatMap((scanRoot) => [normalizeDir(rootDir, join(scanRoot, "server/utils/**/*")), normalizeDir(rootDir, join(scanRoot, "shared/types/**/*"))]);
|
|
778
|
+
}
|
|
779
|
+
function isInlinePreset(value) {
|
|
780
|
+
return !!value && typeof value === "object" && typeof value.from === "string" && Array.isArray(value.imports);
|
|
781
|
+
}
|
|
782
|
+
function isPresetImport(value) {
|
|
783
|
+
return !!value && typeof value === "object" && typeof value.name === "string";
|
|
784
|
+
}
|
|
785
|
+
function normalizePresetImports(presets = []) {
|
|
786
|
+
const normalized = [];
|
|
787
|
+
function collect(from, entry) {
|
|
788
|
+
if (typeof entry === "string") {
|
|
789
|
+
normalized.push(normalizePresetImport(from, entry));
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
if (isInlinePreset(entry)) {
|
|
793
|
+
for (const nested of entry.imports) collect(entry.from, nested);
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
if (isPresetImport(entry)) normalized.push(normalizePresetImport(from, entry));
|
|
240
797
|
}
|
|
241
|
-
const
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
798
|
+
for (const preset of presets) {
|
|
799
|
+
if (!isInlinePreset(preset)) continue;
|
|
800
|
+
for (const entry of preset.imports) collect(preset.from, entry);
|
|
801
|
+
}
|
|
802
|
+
return normalized;
|
|
803
|
+
}
|
|
804
|
+
async function createInitializedUnimport(options) {
|
|
805
|
+
const serverImports = options.serverImports !== false ? options.serverImports : void 0;
|
|
806
|
+
const unimport = createUnimport({
|
|
807
|
+
imports: [...normalizePresetImports(serverImports?.presets), ...(options.featureImports || []).map(normalizeServerImport)],
|
|
808
|
+
dirs: [...resolveDefaultImportDirs(options.rootDir, options.scanRoots), ...(serverImports?.dirs || []).map((dir) => normalizeDir(options.rootDir, dir))]
|
|
809
|
+
});
|
|
810
|
+
await unimport.init();
|
|
811
|
+
return unimport;
|
|
812
|
+
}
|
|
813
|
+
async function createDiscoveredDefinitionCompiler(options = {}) {
|
|
814
|
+
const resolvedOptions = {
|
|
815
|
+
rootDir: options.rootDir || process.cwd(),
|
|
816
|
+
scanRoots: options.scanRoots || [],
|
|
817
|
+
serverImports: options.serverImports,
|
|
818
|
+
featureImports: options.featureImports || []
|
|
819
|
+
};
|
|
820
|
+
if (!isServerAutoImportEnabled(resolvedOptions.serverImports)) return {
|
|
821
|
+
enabled: false,
|
|
822
|
+
async injectSource(source) {
|
|
823
|
+
return source;
|
|
250
824
|
},
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
return { define: { [`__VITEHUB_ENVIRONMENT_${engine.feature.toUpperCase()}__`]: JSON.stringify(name) } };
|
|
825
|
+
async readSource(id) {
|
|
826
|
+
return await readFile(id, "utf8");
|
|
254
827
|
},
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
828
|
+
async bundleModule(bundleOptions) {
|
|
829
|
+
return await bundleDiscoveredDefinitionModule(bundleOptions);
|
|
830
|
+
}
|
|
831
|
+
};
|
|
832
|
+
const unimport = await createInitializedUnimport(resolvedOptions);
|
|
833
|
+
const injectSource = async (source, id) => {
|
|
834
|
+
return await injectTypeImportsFromUnimport((await unimport.injectImports(source, id)).code, id, await unimport.getImports());
|
|
835
|
+
};
|
|
836
|
+
return {
|
|
837
|
+
enabled: true,
|
|
838
|
+
injectSource,
|
|
839
|
+
async readSource(id) {
|
|
840
|
+
return await injectSource(await readFile(id, "utf8"), id);
|
|
259
841
|
},
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
842
|
+
async bundleModule(bundleOptions) {
|
|
843
|
+
return await bundleDiscoveredDefinitionModule(bundleOptions);
|
|
844
|
+
}
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
//#endregion
|
|
848
|
+
//#region src/internal/shared/feature-definitions.ts
|
|
849
|
+
function toTemplateSafeName(name) {
|
|
850
|
+
return name.replace(/[^a-z0-9/_:-]/gi, "_").replace(/\//g, "__").replace(/:/g, "__");
|
|
851
|
+
}
|
|
852
|
+
//#endregion
|
|
853
|
+
//#region src/internal/shared/module-resolve.ts
|
|
854
|
+
function normalizePaths(paths) {
|
|
855
|
+
if (paths?.length) return paths;
|
|
856
|
+
if (typeof process !== "undefined") return [process.cwd()];
|
|
857
|
+
return [];
|
|
858
|
+
}
|
|
859
|
+
function tryResolveFromRuntime(id) {
|
|
860
|
+
const requireResolver = globalThis.require?.resolve;
|
|
861
|
+
if (typeof requireResolver !== "function") return void 0;
|
|
862
|
+
try {
|
|
863
|
+
return requireResolver(id);
|
|
864
|
+
} catch {
|
|
865
|
+
return false;
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
function tryResolveModule(id, options = {}) {
|
|
869
|
+
const paths = normalizePaths(options.paths);
|
|
870
|
+
const runtimeResolved = tryResolveFromRuntime(id);
|
|
871
|
+
if (runtimeResolved === false) return [/* @__PURE__ */ new Error(`Unable to resolve module "${id}" using the active runtime resolver`), void 0];
|
|
872
|
+
if (runtimeResolved) return [null, runtimeResolved];
|
|
873
|
+
const resolved = resolveModule(id, { paths });
|
|
874
|
+
if (resolved) return [null, resolved];
|
|
875
|
+
for (const url of paths) try {
|
|
876
|
+
return [null, resolvePathSync(id, { url })];
|
|
877
|
+
} catch {
|
|
878
|
+
continue;
|
|
879
|
+
}
|
|
880
|
+
return [/* @__PURE__ */ new Error(paths.length > 0 ? `Unable to resolve module "${id}" from ${paths.join(", ")}` : `Unable to resolve module "${id}" without explicit resolution paths`), void 0];
|
|
881
|
+
}
|
|
882
|
+
//#endregion
|
|
883
|
+
//#region src/internal/shared/feature-runtime-path.ts
|
|
884
|
+
function resolveExistingModulePath(path) {
|
|
885
|
+
if (existsSync(path)) return path;
|
|
886
|
+
for (const extension of [
|
|
887
|
+
".ts",
|
|
888
|
+
".mts",
|
|
889
|
+
".js",
|
|
890
|
+
".mjs"
|
|
891
|
+
]) {
|
|
892
|
+
const withExtension = `${path}${extension}`;
|
|
893
|
+
if (existsSync(withExtension)) return withExtension;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
function resolveFeatureRuntimePath(importMetaUrl, packageId, sourceRelativePath, distRelativePath) {
|
|
897
|
+
const importerDir = dirname(fileURLToPath(importMetaUrl));
|
|
898
|
+
const sourcePath = resolve(importerDir, sourceRelativePath);
|
|
899
|
+
const importerUsesDist = importerDir.split(sep).includes("dist");
|
|
900
|
+
const targetsSourceTree = /(?:^|\/)\.\.\/src(?:\/|$)|^\.\/*src(?:\/|$)/.test(sourceRelativePath);
|
|
901
|
+
const resolvedSourcePath = resolveExistingModulePath(sourcePath);
|
|
902
|
+
if ((!importerUsesDist || !targetsSourceTree) && resolvedSourcePath) return resolvedSourcePath;
|
|
903
|
+
const [packageJsonError, packageJsonPath] = tryResolveModule(`${packageId}/package.json`);
|
|
904
|
+
if (!packageJsonError) {
|
|
905
|
+
const resolvedPackageSourcePath = resolveExistingModulePath(join(dirname(packageJsonPath), "src", sourceRelativePath.replace(/^(\.\.\/)+src\//, "").replace(/^\.\//, "")));
|
|
906
|
+
if ((!importerUsesDist || !targetsSourceTree) && resolvedPackageSourcePath) return resolvedPackageSourcePath;
|
|
907
|
+
return join(dirname(packageJsonPath), "dist", distRelativePath);
|
|
908
|
+
}
|
|
909
|
+
const [packageError, packagePath] = tryResolveModule(packageId);
|
|
910
|
+
if (!packageError) return join(dirname(packagePath), distRelativePath);
|
|
911
|
+
return sourcePath;
|
|
912
|
+
}
|
|
913
|
+
//#endregion
|
|
914
|
+
//#region src/project.ts
|
|
915
|
+
const maxTimeout = 2147483647;
|
|
916
|
+
const lockfiles = [
|
|
917
|
+
{
|
|
918
|
+
file: "pnpm-lock.yaml",
|
|
919
|
+
manager: "pnpm"
|
|
920
|
+
},
|
|
921
|
+
{
|
|
922
|
+
file: "package-lock.json",
|
|
923
|
+
manager: "npm"
|
|
924
|
+
},
|
|
925
|
+
{
|
|
926
|
+
file: "yarn.lock",
|
|
927
|
+
manager: "yarn"
|
|
928
|
+
},
|
|
929
|
+
{
|
|
930
|
+
file: "bun.lock",
|
|
931
|
+
manager: "bun"
|
|
932
|
+
}
|
|
933
|
+
];
|
|
934
|
+
const projectFileExcludes = [
|
|
935
|
+
"node_modules/**",
|
|
936
|
+
".git/**",
|
|
937
|
+
"**/.env",
|
|
938
|
+
"**/.env.*",
|
|
939
|
+
"**/.npmrc",
|
|
940
|
+
"bun.lockb"
|
|
941
|
+
];
|
|
942
|
+
function isInside(root, path) {
|
|
943
|
+
const next = relative$1(root, path);
|
|
944
|
+
return next === "" || !next.startsWith("..") && !next.startsWith("/");
|
|
945
|
+
}
|
|
946
|
+
async function isFile(path, root) {
|
|
947
|
+
if (!await stat(path).then((value) => value.isFile(), () => false)) return false;
|
|
948
|
+
if (!isInside(root, await realpath(path))) throw new Error(`[vitehub] Sandbox project file escapes its scan root: ${path}`);
|
|
949
|
+
return true;
|
|
950
|
+
}
|
|
951
|
+
function ancestors(start, root) {
|
|
952
|
+
const paths = [];
|
|
953
|
+
let current = start;
|
|
954
|
+
while (isInside(root, current)) {
|
|
955
|
+
paths.push(current);
|
|
956
|
+
if (current === root) break;
|
|
957
|
+
const parent = dirname$1(current);
|
|
958
|
+
if (parent === current) break;
|
|
959
|
+
current = parent;
|
|
960
|
+
}
|
|
961
|
+
return paths;
|
|
962
|
+
}
|
|
963
|
+
function packageManagerFromField(value) {
|
|
964
|
+
if (typeof value !== "string") return void 0;
|
|
965
|
+
const name = value.split("@", 1)[0];
|
|
966
|
+
return name === "pnpm" || name === "npm" || name === "yarn" || name === "bun" ? name : void 0;
|
|
967
|
+
}
|
|
968
|
+
function packageManagerMajor(value) {
|
|
969
|
+
if (typeof value !== "string") return void 0;
|
|
970
|
+
const version = value.slice(value.indexOf("@") + 1);
|
|
971
|
+
const major = Number.parseInt(version, 10);
|
|
972
|
+
return Number.isFinite(major) ? major : void 0;
|
|
973
|
+
}
|
|
974
|
+
function installArgs(manager, hasLockfile, declaredMajor) {
|
|
975
|
+
if (manager === "npm") return hasLockfile ? ["ci"] : ["install"];
|
|
976
|
+
if (manager === "yarn") return hasLockfile ? ["install", declaredMajor === 1 ? "--frozen-lockfile" : "--immutable"] : ["install"];
|
|
977
|
+
return hasLockfile ? ["install", "--frozen-lockfile"] : ["install"];
|
|
978
|
+
}
|
|
979
|
+
function parseManifest(source, path) {
|
|
980
|
+
try {
|
|
981
|
+
return JSON.parse(source);
|
|
982
|
+
} catch (error) {
|
|
983
|
+
throw new Error(`[vitehub] Sandbox package manifest is invalid JSON: ${path}`, { cause: error });
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
function isPlainObject$1(value) {
|
|
987
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
988
|
+
}
|
|
989
|
+
function parseSandboxProjectOptions(manifest, path) {
|
|
990
|
+
if (typeof manifest.vitehub === "undefined") return void 0;
|
|
991
|
+
if (!isPlainObject$1(manifest.vitehub)) throw new Error(`[vitehub] Sandbox package manifest "vitehub" must be an object: ${path}`);
|
|
992
|
+
const sandbox = manifest.vitehub.sandbox;
|
|
993
|
+
if (typeof sandbox === "undefined") return void 0;
|
|
994
|
+
if (!isPlainObject$1(sandbox)) throw new Error(`[vitehub] Sandbox package manifest "vitehub.sandbox" must be an object: ${path}`);
|
|
995
|
+
const unsupported = Object.keys(sandbox).filter((key) => key !== "timeout");
|
|
996
|
+
if (unsupported.length) throw new Error(`[vitehub] Sandbox package manifest "vitehub.sandbox" has unsupported keys: ${unsupported.join(", ")}.`);
|
|
997
|
+
const timeout = sandbox.timeout;
|
|
998
|
+
if (typeof timeout === "undefined") return void 0;
|
|
999
|
+
if (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout <= 0 || timeout > maxTimeout) throw new Error(`[vitehub] Sandbox package manifest "vitehub.sandbox.timeout" must be a positive integer no greater than ${maxTimeout}.`);
|
|
1000
|
+
return { timeout };
|
|
1001
|
+
}
|
|
1002
|
+
function parsePnpmWorkspacePackages(source) {
|
|
1003
|
+
const patterns = [];
|
|
1004
|
+
let packagesIndent;
|
|
1005
|
+
for (const line of source.split(/\r?\n/)) {
|
|
1006
|
+
if (packagesIndent === void 0) {
|
|
1007
|
+
const inline = /^\s*packages\s*:\s*\[(.*)\]\s*(?:#.*)?$/.exec(line);
|
|
1008
|
+
if (inline) return inline[1].split(",").map((value) => value.trim().replace(/^(['"])(.*)\1$/, "$2")).filter(Boolean);
|
|
1009
|
+
const match = /^(\s*)packages\s*:\s*(?:#.*)?$/.exec(line);
|
|
1010
|
+
if (match) packagesIndent = match[1].length;
|
|
1011
|
+
continue;
|
|
1012
|
+
}
|
|
1013
|
+
if (!line.trim() || /^\s*#/.test(line)) continue;
|
|
1014
|
+
if ((/^\s*/.exec(line)?.[0].length || 0) <= packagesIndent) break;
|
|
1015
|
+
const item = /^\s*-\s*(.+?)\s*$/.exec(line)?.[1];
|
|
1016
|
+
if (!item) continue;
|
|
1017
|
+
const value = item.replace(/\s+#.*$/, "").trim().replace(/^(['"])(.*)\1$/, "$2");
|
|
1018
|
+
if (value) patterns.push(value.replaceAll("\\", "/").replace(/\/$/, ""));
|
|
1019
|
+
}
|
|
1020
|
+
return patterns;
|
|
1021
|
+
}
|
|
1022
|
+
function isWorkspacePackage(path, patterns) {
|
|
1023
|
+
return patterns.filter((pattern) => !pattern.startsWith("!")).some((pattern) => matchesGlob(path, pattern)) && !patterns.filter((pattern) => pattern.startsWith("!")).some((pattern) => matchesGlob(path, pattern.slice(1)));
|
|
1024
|
+
}
|
|
1025
|
+
async function findPnpmWorkspaceRoot(packageRoot, root) {
|
|
1026
|
+
for (const directory of ancestors(packageRoot, root)) {
|
|
1027
|
+
const file = resolve$1(directory, "pnpm-workspace.yaml");
|
|
1028
|
+
if (!await isFile(file, root)) continue;
|
|
1029
|
+
const source = await readFile(file, "utf8");
|
|
1030
|
+
const packagePath = relative$1(directory, packageRoot).replaceAll("\\", "/") || ".";
|
|
1031
|
+
if (directory === packageRoot || isWorkspacePackage(packagePath, parsePnpmWorkspacePackages(source))) return {
|
|
1032
|
+
directory,
|
|
1033
|
+
file,
|
|
1034
|
+
source
|
|
1035
|
+
};
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
async function addProjectFile(files, installRoot, path, scanRoot) {
|
|
1039
|
+
if (!await isFile(path, scanRoot)) return;
|
|
1040
|
+
const mode = (await stat(path)).mode & 511;
|
|
1041
|
+
files[relative$1(installRoot, path).replaceAll("\\", "/")] = {
|
|
1042
|
+
contents: (await readFile(path)).toString("base64"),
|
|
1043
|
+
encoding: "base64",
|
|
1044
|
+
...mode & 73 ? { mode } : {}
|
|
1045
|
+
};
|
|
1046
|
+
}
|
|
1047
|
+
function workspaceDependencyNames(manifest) {
|
|
1048
|
+
const sections = [
|
|
1049
|
+
manifest.dependencies,
|
|
1050
|
+
manifest.devDependencies,
|
|
1051
|
+
manifest.optionalDependencies,
|
|
1052
|
+
manifest.peerDependencies
|
|
1053
|
+
];
|
|
1054
|
+
return [...new Set(sections.flatMap((section) => Object.entries(section || {})).filter(([, specifier]) => specifier.startsWith("workspace:")).map(([name]) => name))];
|
|
1055
|
+
}
|
|
1056
|
+
async function addPnpmWorkspaceDependencies(files, workspaceRoot, scanRoot, patterns, selectedManifest) {
|
|
1057
|
+
const packages = /* @__PURE__ */ new Map();
|
|
1058
|
+
for (const pattern of patterns.filter((pattern) => !pattern.startsWith("!"))) for await (const match of glob(`${pattern}/package.json`, {
|
|
1059
|
+
cwd: workspaceRoot,
|
|
1060
|
+
exclude: ["**/node_modules/**", "**/.git/**"]
|
|
1061
|
+
})) {
|
|
1062
|
+
const manifestPath = resolve$1(workspaceRoot, match);
|
|
1063
|
+
if (!await isFile(manifestPath, scanRoot)) continue;
|
|
1064
|
+
if (!isWorkspacePackage(relative$1(workspaceRoot, dirname$1(manifestPath)).replaceAll("\\", "/") || ".", patterns)) continue;
|
|
1065
|
+
const manifest = parseManifest(await readFile(manifestPath, "utf8"), manifestPath);
|
|
1066
|
+
if (manifest.name) packages.set(manifest.name, {
|
|
1067
|
+
manifest,
|
|
1068
|
+
root: dirname$1(manifestPath)
|
|
1069
|
+
});
|
|
1070
|
+
}
|
|
1071
|
+
const pending = workspaceDependencyNames(selectedManifest);
|
|
1072
|
+
const included = /* @__PURE__ */ new Set();
|
|
1073
|
+
while (pending.length) {
|
|
1074
|
+
const name = pending.shift();
|
|
1075
|
+
if (included.has(name)) continue;
|
|
1076
|
+
const dependency = packages.get(name);
|
|
1077
|
+
if (!dependency) throw new Error(`[vitehub] Sandbox package references missing pnpm workspace dependency "${name}".`);
|
|
1078
|
+
included.add(name);
|
|
1079
|
+
pending.push(...workspaceDependencyNames(dependency.manifest));
|
|
1080
|
+
for await (const match of glob("**/*", {
|
|
1081
|
+
cwd: dependency.root,
|
|
1082
|
+
exclude: projectFileExcludes
|
|
1083
|
+
})) await addProjectFile(files, workspaceRoot, resolve$1(dependency.root, match), scanRoot);
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
async function resolveSandboxProject(definitionFile, scanRoot, options = {}) {
|
|
1087
|
+
const root = await realpath(resolve$1(scanRoot));
|
|
1088
|
+
const definition = await realpath(resolve$1(definitionFile));
|
|
1089
|
+
if (!isInside(root, definition)) throw new Error(`[vitehub] Sandbox Definition is outside its scan root: ${definitionFile}`);
|
|
1090
|
+
const packageRoot = await firstDirectoryWithFile(ancestors(dirname$1(definition), root), "package.json", root);
|
|
1091
|
+
if (!packageRoot) throw new Error(`[vitehub] Sandbox Definition "${definitionFile}" requires a package.json between its directory and "${root}".`);
|
|
1092
|
+
const manifestPath = resolve$1(packageRoot, "package.json");
|
|
1093
|
+
const manifest = parseManifest(await readFile(manifestPath, "utf8"), manifestPath);
|
|
1094
|
+
const sandboxOptions = options.readSandboxOptions ? parseSandboxProjectOptions(manifest, manifestPath) : void 0;
|
|
1095
|
+
const declaredManager = packageManagerFromField(manifest.packageManager);
|
|
1096
|
+
const declaredMajor = packageManagerMajor(manifest.packageManager);
|
|
1097
|
+
const workspace = declaredManager && declaredManager !== "pnpm" ? void 0 : await findPnpmWorkspaceRoot(packageRoot, root);
|
|
1098
|
+
const installRoot = workspace?.directory || packageRoot;
|
|
1099
|
+
const packageLock = await findLockfile([installRoot], root, workspace ? "pnpm" : declaredManager);
|
|
1100
|
+
const manager = declaredManager || packageLock?.manager || (workspace ? "pnpm" : "npm");
|
|
1101
|
+
const lock = packageLock?.manager === manager ? packageLock : void 0;
|
|
1102
|
+
const lockfileMajor = manager === "yarn" && lock && declaredMajor === void 0 ? (await readFile(lock.path, "utf8")).includes("__metadata:") ? 2 : 1 : void 0;
|
|
1103
|
+
const files = {};
|
|
1104
|
+
for await (const match of glob("**/*", {
|
|
1105
|
+
cwd: packageRoot,
|
|
1106
|
+
exclude: projectFileExcludes
|
|
1107
|
+
})) await addProjectFile(files, installRoot, resolve$1(packageRoot, match), root);
|
|
1108
|
+
if (installRoot !== packageRoot) await addProjectFile(files, installRoot, resolve$1(installRoot, "package.json"), root);
|
|
1109
|
+
if (workspace) {
|
|
1110
|
+
await addProjectFile(files, installRoot, workspace.file, root);
|
|
1111
|
+
await addPnpmWorkspaceDependencies(files, installRoot, root, parsePnpmWorkspacePackages(workspace.source), manifest);
|
|
1112
|
+
}
|
|
1113
|
+
if (lock) await addProjectFile(files, installRoot, lock.path, root);
|
|
1114
|
+
const packagePath = relative$1(installRoot, packageRoot).replaceAll("\\", "/") || ".";
|
|
1115
|
+
const identity = JSON.stringify({
|
|
1116
|
+
files,
|
|
1117
|
+
manager,
|
|
1118
|
+
packagePath
|
|
1119
|
+
});
|
|
1120
|
+
return {
|
|
1121
|
+
digest: createHash("sha256").update(identity).digest("hex"),
|
|
1122
|
+
files,
|
|
1123
|
+
install: {
|
|
1124
|
+
args: installArgs(manager, Boolean(lock), declaredManager === manager ? declaredMajor : lockfileMajor),
|
|
1125
|
+
command: manager,
|
|
1126
|
+
cwd: "."
|
|
263
1127
|
},
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
1128
|
+
...sandboxOptions ? { options: sandboxOptions } : {},
|
|
1129
|
+
packagePath
|
|
1130
|
+
};
|
|
1131
|
+
}
|
|
1132
|
+
async function firstDirectoryWithFile(directories, file, root) {
|
|
1133
|
+
for (const directory of directories) if (await isFile(resolve$1(directory, file), root)) return directory;
|
|
1134
|
+
}
|
|
1135
|
+
async function findLockfile(directories, root, manager) {
|
|
1136
|
+
const candidates = manager ? lockfiles.filter((lock) => lock.manager === manager) : lockfiles;
|
|
1137
|
+
for (const directory of directories) for (const candidate of candidates) {
|
|
1138
|
+
const path = resolve$1(directory, candidate.file);
|
|
1139
|
+
if (await isFile(path, root)) return {
|
|
1140
|
+
directory,
|
|
1141
|
+
manager: candidate.manager,
|
|
1142
|
+
path
|
|
1143
|
+
};
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
//#endregion
|
|
1147
|
+
//#region src/internal/package-entry.ts
|
|
1148
|
+
const typescript = createRequire(import.meta.url)("typescript");
|
|
1149
|
+
const runtimeExportConditions = new Set([
|
|
1150
|
+
"default",
|
|
1151
|
+
"import",
|
|
1152
|
+
"module-sync",
|
|
1153
|
+
"node",
|
|
1154
|
+
"node-addons"
|
|
1155
|
+
]);
|
|
1156
|
+
function isExecutableTypeScriptModule(path) {
|
|
1157
|
+
return /\.(?:ts|mts)$/.test(path) && !/\.d\.(?:ts|mts)$/.test(path);
|
|
1158
|
+
}
|
|
1159
|
+
function executablePackageModulePath(path) {
|
|
1160
|
+
const suffixIndex = path.search(/[?#]/);
|
|
1161
|
+
const modulePath = suffixIndex === -1 ? path : path.slice(0, suffixIndex);
|
|
1162
|
+
const suffix = suffixIndex === -1 ? "" : path.slice(suffixIndex);
|
|
1163
|
+
return isExecutableTypeScriptModule(modulePath) ? `${modulePath}.mjs${suffix}` : path;
|
|
1164
|
+
}
|
|
1165
|
+
function projectFileSource(project, path) {
|
|
1166
|
+
const file = project.files[path];
|
|
1167
|
+
if (!file) throw new Error(`[vitehub] Sandbox package project is missing required file: ${path}`);
|
|
1168
|
+
return Buffer.from(file.contents, file.encoding).toString();
|
|
1169
|
+
}
|
|
1170
|
+
function parseRuntimeManifest(project, path) {
|
|
1171
|
+
try {
|
|
1172
|
+
return JSON.parse(projectFileSource(project, path));
|
|
1173
|
+
} catch (error) {
|
|
1174
|
+
throw new Error(`[vitehub] Sandbox package manifest is invalid JSON: ${path}`, { cause: error });
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
function selectedPackageManifest(project) {
|
|
1178
|
+
const path = project.packagePath === "." ? "package.json" : `${project.packagePath}/package.json`;
|
|
1179
|
+
const manifest = parseRuntimeManifest(project, path);
|
|
1180
|
+
if (manifest.type !== "module") throw new Error(`[vitehub] Sandbox package manifest "${path}" must set "type" to "module". Canonical Sandbox package entrypoints are ESM.`);
|
|
1181
|
+
return manifest;
|
|
1182
|
+
}
|
|
1183
|
+
function declaredWorkspaceDependencyNames(manifest) {
|
|
1184
|
+
return [...new Set([
|
|
1185
|
+
manifest.dependencies,
|
|
1186
|
+
manifest.devDependencies,
|
|
1187
|
+
manifest.optionalDependencies,
|
|
1188
|
+
manifest.peerDependencies
|
|
1189
|
+
].flatMap((section) => Object.entries(section || {})).filter(([, specifier]) => specifier.startsWith("workspace:")).map(([name]) => name))];
|
|
1190
|
+
}
|
|
1191
|
+
function runtimeExportTargets(value, patternMatch, allowPackageTarget = false) {
|
|
1192
|
+
if (typeof value === "string") {
|
|
1193
|
+
const target = patternMatch === void 0 ? value : value.replaceAll("*", patternMatch);
|
|
1194
|
+
return target.startsWith("./") || allowPackageTarget ? [target] : [];
|
|
1195
|
+
}
|
|
1196
|
+
if (Array.isArray(value)) {
|
|
1197
|
+
for (const target of value) {
|
|
1198
|
+
const targets = runtimeExportTargets(target, patternMatch, allowPackageTarget);
|
|
1199
|
+
if (targets.length) return targets;
|
|
1200
|
+
}
|
|
1201
|
+
return [];
|
|
1202
|
+
}
|
|
1203
|
+
if (!value || typeof value !== "object") return [];
|
|
1204
|
+
for (const [condition, target] of Object.entries(value)) if (runtimeExportConditions.has(condition)) {
|
|
1205
|
+
const targets = runtimeExportTargets(target, patternMatch, allowPackageTarget);
|
|
1206
|
+
if (targets.length) return targets;
|
|
1207
|
+
}
|
|
1208
|
+
return [];
|
|
1209
|
+
}
|
|
1210
|
+
function runtimeTargetsForPackageSpecifier(manifest, packageName, specifier) {
|
|
1211
|
+
if (manifest.exports !== void 0) {
|
|
1212
|
+
let selected = manifest.exports;
|
|
1213
|
+
let patternMatch;
|
|
1214
|
+
if (selected && typeof selected === "object" && !Array.isArray(selected)) {
|
|
1215
|
+
const entries = selected;
|
|
1216
|
+
if (Object.keys(entries).some((key) => key.startsWith("."))) {
|
|
1217
|
+
const subpath = specifier === packageName ? "." : `.${specifier.slice(packageName.length)}`;
|
|
1218
|
+
if (Object.hasOwn(entries, subpath)) selected = entries[subpath];
|
|
1219
|
+
else {
|
|
1220
|
+
const pattern = Object.keys(entries).filter((key) => {
|
|
1221
|
+
const star = key.indexOf("*");
|
|
1222
|
+
if (star === -1) return false;
|
|
1223
|
+
return subpath.startsWith(key.slice(0, star)) && subpath.endsWith(key.slice(star + 1));
|
|
1224
|
+
}).sort((left, right) => {
|
|
1225
|
+
const leftStar = left.indexOf("*");
|
|
1226
|
+
return right.indexOf("*") - leftStar || right.length - left.length;
|
|
1227
|
+
})[0];
|
|
1228
|
+
if (pattern) {
|
|
1229
|
+
const star = pattern.indexOf("*");
|
|
1230
|
+
patternMatch = subpath.slice(star, subpath.length - (pattern.length - star - 1));
|
|
1231
|
+
selected = entries[pattern];
|
|
1232
|
+
} else selected = void 0;
|
|
297
1233
|
}
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
1234
|
+
} else if (specifier !== packageName) selected = void 0;
|
|
1235
|
+
} else if (specifier !== packageName) selected = void 0;
|
|
1236
|
+
return runtimeExportTargets(selected, patternMatch);
|
|
1237
|
+
}
|
|
1238
|
+
if (specifier !== packageName) return [`.${specifier.slice(packageName.length)}`];
|
|
1239
|
+
return typeof manifest.main === "string" ? [manifest.main] : ["./index.js"];
|
|
1240
|
+
}
|
|
1241
|
+
function runtimeTargetsForPackageImport(manifest, specifier) {
|
|
1242
|
+
if (!manifest.imports || typeof manifest.imports !== "object" || Array.isArray(manifest.imports)) return [];
|
|
1243
|
+
const entries = manifest.imports;
|
|
1244
|
+
let selected = entries[specifier];
|
|
1245
|
+
let patternMatch;
|
|
1246
|
+
if (selected === void 0) {
|
|
1247
|
+
const pattern = Object.keys(entries).filter((key) => {
|
|
1248
|
+
const star = key.indexOf("*");
|
|
1249
|
+
if (star === -1) return false;
|
|
1250
|
+
return specifier.startsWith(key.slice(0, star)) && specifier.endsWith(key.slice(star + 1));
|
|
1251
|
+
}).sort((left, right) => {
|
|
1252
|
+
const leftStar = left.indexOf("*");
|
|
1253
|
+
return right.indexOf("*") - leftStar || right.length - left.length;
|
|
1254
|
+
})[0];
|
|
1255
|
+
if (!pattern) return [];
|
|
1256
|
+
const star = pattern.indexOf("*");
|
|
1257
|
+
patternMatch = specifier.slice(star, specifier.length - (pattern.length - star - 1));
|
|
1258
|
+
selected = entries[pattern];
|
|
1259
|
+
}
|
|
1260
|
+
return runtimeExportTargets(selected, patternMatch, true);
|
|
1261
|
+
}
|
|
1262
|
+
function isTypeScriptRuntimeTarget(path) {
|
|
1263
|
+
const target = path.replace(/[?#].*$/, "");
|
|
1264
|
+
return /\.[cm]?tsx?$/.test(target) && !/\.d\.[cm]?ts$/.test(target);
|
|
1265
|
+
}
|
|
1266
|
+
function validateWorkspaceJavaScriptGraph(project, packageName, manifest, manifestPath, targets) {
|
|
1267
|
+
const pending = targets.filter((target) => /\.(?:js|mjs)$/.test(target.replace(/[?#].*$/, ""))).map((target) => normalize$1(join$1(dirname$2(manifestPath), target.replace(/[?#].*$/, ""))));
|
|
1268
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1269
|
+
const runtimePackages = /* @__PURE__ */ new Set();
|
|
1270
|
+
while (pending.length) {
|
|
1271
|
+
const path = pending.shift();
|
|
1272
|
+
if (visited.has(path) || !Object.hasOwn(project.files, path)) continue;
|
|
1273
|
+
visited.add(path);
|
|
1274
|
+
const source = projectFileSource(project, path);
|
|
1275
|
+
for (const specifier of findRuntimeModuleSpecifiers(source, path)) {
|
|
1276
|
+
if (specifier.startsWith("#")) {
|
|
1277
|
+
for (const aliasTarget of runtimeTargetsForPackageImport(manifest, specifier)) {
|
|
1278
|
+
if (!/^\.\.?\//.test(aliasTarget)) {
|
|
1279
|
+
runtimePackages.add(aliasTarget);
|
|
1280
|
+
continue;
|
|
1281
|
+
}
|
|
1282
|
+
const target = normalize$1(join$1(dirname$2(manifestPath), aliasTarget.replace(/[?#].*$/, "")));
|
|
1283
|
+
if (isTypeScriptRuntimeTarget(target)) throw new Error(`[vitehub] Sandbox workspace dependency "${packageName}" exposes TypeScript runtime target "${aliasTarget}" through package import "${specifier}". Build dependencies to JavaScript before Sandbox execution.`);
|
|
1284
|
+
if (/\.(?:js|mjs)$/.test(target)) pending.push(target);
|
|
310
1285
|
}
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
server.watcher.off("add", scheduleNitroRebuild);
|
|
317
|
-
server.watcher.off("change", scheduleNitroRebuild);
|
|
318
|
-
server.watcher.off("unlink", scheduleNitroRebuild);
|
|
319
|
-
closeNitroDevServer();
|
|
320
|
-
});
|
|
321
|
-
},
|
|
322
|
-
async closeBundle() {
|
|
323
|
-
const nitroConfig = rawConfig.nitro;
|
|
324
|
-
if (!state || !nitroConfig?.handlers?.length || rawEnv.command !== "build" || getViteMode() === VITEHUB_MODES.e2e) return;
|
|
325
|
-
const nitroBuilder = await loadNitroBuilder();
|
|
326
|
-
const nitro = await nitroBuilder.createNitro(resolveNitroOptions(state.rootDir, engine.configKey, state, nitroConfig, plugin.nitro, false));
|
|
327
|
-
try {
|
|
328
|
-
await nitroBuilder.prepare(nitro);
|
|
329
|
-
await nitroBuilder.copyPublicAssets(nitro);
|
|
330
|
-
await nitroBuilder.prerender(nitro);
|
|
331
|
-
await nitroBuilder.build(nitro);
|
|
332
|
-
await copyViteBuildOutputToNitroPublicDir(nitro, state.rootDir, typeof state.extraConfig?.build?.outDir === "string" ? state.extraConfig.build.outDir : void 0);
|
|
333
|
-
} finally {
|
|
334
|
-
await nitro.close();
|
|
1286
|
+
continue;
|
|
1287
|
+
}
|
|
1288
|
+
if (!/^\.\.?\//.test(specifier)) {
|
|
1289
|
+
if (!specifier.startsWith("node:")) runtimePackages.add(specifier);
|
|
1290
|
+
continue;
|
|
335
1291
|
}
|
|
1292
|
+
const target = normalize$1(join$1(dirname$2(path), specifier.replace(/[?#].*$/, "")));
|
|
1293
|
+
if (isTypeScriptRuntimeTarget(target)) throw new Error(`[vitehub] Sandbox workspace dependency "${packageName}" exposes TypeScript runtime target "${specifier}" from "${path}". Build dependencies to JavaScript before Sandbox execution.`);
|
|
1294
|
+
if (/\.(?:js|mjs)$/.test(target)) pending.push(target);
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
return runtimePackages;
|
|
1298
|
+
}
|
|
1299
|
+
function validateWorkspaceRuntimeExports(project, runtimePackages, declaredWorkspacePackages) {
|
|
1300
|
+
const pending = [...runtimePackages];
|
|
1301
|
+
if (!pending.length) return;
|
|
1302
|
+
const workspacePackages = new Set(declaredWorkspacePackages);
|
|
1303
|
+
if (!workspacePackages.size) return;
|
|
1304
|
+
const workspaceFile = project.files["pnpm-workspace.yaml"];
|
|
1305
|
+
if (!workspaceFile) return;
|
|
1306
|
+
const workspacePatterns = parsePnpmWorkspacePackages(Buffer.from(workspaceFile.contents, workspaceFile.encoding).toString());
|
|
1307
|
+
const manifests = /* @__PURE__ */ new Map();
|
|
1308
|
+
for (const path of Object.keys(project.files).filter((path) => path === "package.json" || path.endsWith("/package.json") && isWorkspacePackage(dirname$2(path), workspacePatterns))) {
|
|
1309
|
+
let manifest;
|
|
1310
|
+
try {
|
|
1311
|
+
const value = JSON.parse(projectFileSource(project, path));
|
|
1312
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) continue;
|
|
1313
|
+
manifest = value;
|
|
1314
|
+
} catch {
|
|
1315
|
+
continue;
|
|
1316
|
+
}
|
|
1317
|
+
if (typeof manifest.name === "string") manifests.set(manifest.name, {
|
|
1318
|
+
manifest,
|
|
1319
|
+
path
|
|
1320
|
+
});
|
|
1321
|
+
}
|
|
1322
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1323
|
+
while (pending.length) {
|
|
1324
|
+
const specifier = pending.shift();
|
|
1325
|
+
if (visited.has(specifier)) continue;
|
|
1326
|
+
visited.add(specifier);
|
|
1327
|
+
const packageName = barePackageName(specifier);
|
|
1328
|
+
if (!workspacePackages.has(packageName)) continue;
|
|
1329
|
+
const dependency = manifests.get(packageName);
|
|
1330
|
+
if (!dependency) continue;
|
|
1331
|
+
const targets = runtimeTargetsForPackageSpecifier(dependency.manifest, packageName, specifier);
|
|
1332
|
+
const target = targets.find(isTypeScriptRuntimeTarget);
|
|
1333
|
+
if (target) throw new Error(`[vitehub] Sandbox workspace dependency "${packageName}" exposes TypeScript runtime target "${target}" in "${dependency.path}". Build dependencies to JavaScript before Sandbox execution.`);
|
|
1334
|
+
const runtimePackageEdges = validateWorkspaceJavaScriptGraph(project, packageName, dependency.manifest, dependency.path, targets);
|
|
1335
|
+
for (const name of declaredWorkspaceDependencyNames(dependency.manifest)) workspacePackages.add(name);
|
|
1336
|
+
pending.push(...runtimePackageEdges);
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
function isInsideSelectedPackage(project, path) {
|
|
1340
|
+
if (project.packagePath === ".") return path !== ".." && !path.startsWith("../");
|
|
1341
|
+
return path.startsWith(`${project.packagePath}/`);
|
|
1342
|
+
}
|
|
1343
|
+
function removeTypeOnlyModuleDeclarations(context) {
|
|
1344
|
+
return (sourceFile) => context.factory.updateSourceFile(sourceFile, sourceFile.statements.filter((statement) => {
|
|
1345
|
+
if (typescript.isImportDeclaration(statement)) {
|
|
1346
|
+
const clause = statement.importClause;
|
|
1347
|
+
const bindings = clause?.namedBindings;
|
|
1348
|
+
return !(clause && !clause.name && bindings && typescript.isNamedImports(bindings) && bindings.elements.length > 0 && bindings.elements.every((element) => element.isTypeOnly));
|
|
1349
|
+
}
|
|
1350
|
+
if (typescript.isExportDeclaration(statement)) {
|
|
1351
|
+
const clause = statement.exportClause;
|
|
1352
|
+
return !(clause && typescript.isNamedExports(clause) && clause.elements.length > 0 && clause.elements.every((element) => element.isTypeOnly));
|
|
1353
|
+
}
|
|
1354
|
+
return true;
|
|
1355
|
+
}));
|
|
1356
|
+
}
|
|
1357
|
+
function transpilePackageModule(source, path) {
|
|
1358
|
+
const result = typescript.transpileModule(source, {
|
|
1359
|
+
compilerOptions: {
|
|
1360
|
+
module: typescript.ModuleKind.ESNext,
|
|
1361
|
+
target: typescript.ScriptTarget.ES2022,
|
|
1362
|
+
verbatimModuleSyntax: true
|
|
1363
|
+
},
|
|
1364
|
+
fileName: path,
|
|
1365
|
+
reportDiagnostics: true,
|
|
1366
|
+
transformers: { before: [removeTypeOnlyModuleDeclarations] }
|
|
1367
|
+
});
|
|
1368
|
+
const errors = result.diagnostics?.filter((diagnostic) => diagnostic.category === typescript.DiagnosticCategory.Error) || [];
|
|
1369
|
+
if (errors.length) {
|
|
1370
|
+
const details = errors.map((diagnostic) => typescript.flattenDiagnosticMessageText(diagnostic.messageText, "\n")).join("\n");
|
|
1371
|
+
throw new Error(`[vitehub] Sandbox package module "${path}" could not be transpiled:\n${details}`);
|
|
1372
|
+
}
|
|
1373
|
+
return result.outputText;
|
|
1374
|
+
}
|
|
1375
|
+
function barePackageName(specifier) {
|
|
1376
|
+
const [scopeOrName, name] = specifier.split("/");
|
|
1377
|
+
return scopeOrName.startsWith("@") && name ? `${scopeOrName}/${name}` : scopeOrName;
|
|
1378
|
+
}
|
|
1379
|
+
function isUnsupportedExternalModuleSpecifier(specifier) {
|
|
1380
|
+
return specifier.startsWith("/") || specifier.startsWith("\\") || /^[A-Za-z][A-Za-z\d+.-]*:/.test(specifier) && !specifier.startsWith("node:");
|
|
1381
|
+
}
|
|
1382
|
+
function throwCommonJSSyntax(path, commonJS) {
|
|
1383
|
+
const syntax = {
|
|
1384
|
+
"exports-assignment": "exports assignment",
|
|
1385
|
+
"exports-reference": "exports reference",
|
|
1386
|
+
"import-equals": "import = require()",
|
|
1387
|
+
"module-exports-assignment": "module.exports assignment",
|
|
1388
|
+
"module-reference": "module reference",
|
|
1389
|
+
require: "require()",
|
|
1390
|
+
"require-property": commonJS.specifier ? `require.${commonJS.specifier}` : "require property access"
|
|
1391
|
+
}[commonJS.syntax];
|
|
1392
|
+
const target = commonJS.specifier && commonJS.syntax !== "require-property" ? ` for "${commonJS.specifier}"` : "";
|
|
1393
|
+
throw new Error(`[vitehub] Sandbox package module "${path}" uses CommonJS ${syntax}${target}. Canonical Sandbox package entrypoints are ESM; use import or export syntax.`);
|
|
1394
|
+
}
|
|
1395
|
+
function validatePackageModuleSpecifiers(project, entry, packageName) {
|
|
1396
|
+
const pending = [entry];
|
|
1397
|
+
const runtimePackages = /* @__PURE__ */ new Set();
|
|
1398
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1399
|
+
while (pending.length) {
|
|
1400
|
+
const path = pending.shift();
|
|
1401
|
+
if (visited.has(path)) continue;
|
|
1402
|
+
visited.add(path);
|
|
1403
|
+
const source = projectFileSource(project, path);
|
|
1404
|
+
if (hasNonLiteralDynamicImport(source, path)) throw new Error(`[vitehub] Sandbox package module "${path}" uses a non-literal dynamic import. Canonical Sandbox package entrypoints require literal import() specifiers.`);
|
|
1405
|
+
const importEquals = findCommonJSImportEqualsSpecifiers(source, path)[0];
|
|
1406
|
+
if (importEquals) throwCommonJSSyntax(path, importEquals);
|
|
1407
|
+
const moduleSpecifiers = findRuntimeModuleSpecifiers(source, path);
|
|
1408
|
+
for (const specifier of moduleSpecifiers) {
|
|
1409
|
+
if (specifier.startsWith("#")) throw new Error(`[vitehub] Sandbox package module "${path}" imports package alias "${specifier}". Use an explicit relative ESM import for local Sandbox source.`);
|
|
1410
|
+
if (packageName && (specifier === packageName || specifier.startsWith(`${packageName}/`))) throw new Error(`[vitehub] Sandbox package module "${path}" self-imports "${specifier}". Use an explicit relative ESM import for local Sandbox source.`);
|
|
1411
|
+
if (isUnsupportedExternalModuleSpecifier(specifier)) throw new Error(`[vitehub] Sandbox package module "${path}" imports absolute or URL module "${specifier}". Use a relative module inside the package or a runtime-ready package dependency.`);
|
|
1412
|
+
if (!/^\.\.?\//.test(specifier) && !specifier.startsWith("node:")) runtimePackages.add(specifier);
|
|
1413
|
+
}
|
|
1414
|
+
for (const specifier of moduleSpecifiers.filter((specifier) => /^\.\.?\//.test(specifier))) {
|
|
1415
|
+
const target = normalize$1(join$1(dirname$2(path), specifier.replace(/[?#].*$/, "")));
|
|
1416
|
+
if (!isInsideSelectedPackage(project, target)) throw new Error(`[vitehub] Sandbox package module "${path}" imports "${specifier}" outside its package. Declare runtime-ready JavaScript as a package dependency instead.`);
|
|
1417
|
+
if (!Object.hasOwn(project.files, target)) throw new Error(`[vitehub] Sandbox package module "${path}" imports "${specifier}", which is not an executable package file. Use an explicit extension that resolves to a package file.`);
|
|
1418
|
+
if (/\.(?:cjs|cts)$/.test(target)) throw new Error(`[vitehub] Sandbox package module "${path}" imports CommonJS module "${specifier}". Canonical Sandbox package source must use ESM JavaScript or TypeScript modules.`);
|
|
1419
|
+
if (/\.[cm]?[jt]sx$/.test(target)) throw new Error(`[vitehub] Sandbox package module "${path}" imports JSX module "${specifier}". Canonical Sandbox package source does not compile JSX.`);
|
|
1420
|
+
if (/\.d\.[cm]?ts$/.test(target)) throw new Error(`[vitehub] Sandbox package module "${path}" imports declaration file "${specifier}" at runtime. Use an import type declaration instead.`);
|
|
1421
|
+
if (/\.(?:js|mjs|ts|mts)$/.test(target)) pending.push(target);
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
return {
|
|
1425
|
+
modulePaths: visited,
|
|
1426
|
+
runtimePackages
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
function prepareExecutablePackageProject(project, entry) {
|
|
1430
|
+
const manifest = selectedPackageManifest(project);
|
|
1431
|
+
const { modulePaths, runtimePackages } = validatePackageModuleSpecifiers(project, entry, typeof manifest.name === "string" ? manifest.name : void 0);
|
|
1432
|
+
validateWorkspaceRuntimeExports(project, runtimePackages, declaredWorkspaceDependencyNames(manifest));
|
|
1433
|
+
const generatedFiles = {};
|
|
1434
|
+
const executableSources = /* @__PURE__ */ new Map();
|
|
1435
|
+
const originalPaths = /* @__PURE__ */ new Map();
|
|
1436
|
+
const files = { ...project.files };
|
|
1437
|
+
for (const path of modulePaths) {
|
|
1438
|
+
const file = project.files[path];
|
|
1439
|
+
const source = Buffer.from(file.contents, file.encoding).toString();
|
|
1440
|
+
const rewritten = rewriteRuntimeRelativeModuleSpecifiers(source, path, executablePackageModulePath);
|
|
1441
|
+
if (isExecutableTypeScriptModule(path)) {
|
|
1442
|
+
const executablePath = executablePackageModulePath(path);
|
|
1443
|
+
if (Object.hasOwn(project.files, executablePath)) throw new Error(`[vitehub] Sandbox package module "${path}" conflicts with generated executable "${executablePath}". Rename the existing file.`);
|
|
1444
|
+
const executableSource = transpilePackageModule(rewritten, path);
|
|
1445
|
+
executableSources.set(executablePath, executableSource);
|
|
1446
|
+
originalPaths.set(executablePath, path);
|
|
1447
|
+
generatedFiles[executablePath] = {
|
|
1448
|
+
contents: Buffer.from(executableSource).toString("base64"),
|
|
1449
|
+
encoding: "base64"
|
|
1450
|
+
};
|
|
1451
|
+
} else {
|
|
1452
|
+
executableSources.set(path, rewritten);
|
|
1453
|
+
originalPaths.set(path, path);
|
|
1454
|
+
if (rewritten !== source) generatedFiles[path] = {
|
|
1455
|
+
...file,
|
|
1456
|
+
contents: Buffer.from(rewritten).toString("base64")
|
|
1457
|
+
};
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
const commonJS = findExecutableCommonJSModuleSpecifiers(executableSources)[0];
|
|
1461
|
+
if (commonJS) throwCommonJSSyntax(originalPaths.get(commonJS.path) || commonJS.path, commonJS);
|
|
1462
|
+
if (!Object.keys(generatedFiles).length) return {
|
|
1463
|
+
entry,
|
|
1464
|
+
project
|
|
1465
|
+
};
|
|
1466
|
+
Object.assign(files, generatedFiles);
|
|
1467
|
+
const digest = createHash("sha256").update(JSON.stringify({
|
|
1468
|
+
generatedFiles,
|
|
1469
|
+
project: project.digest
|
|
1470
|
+
})).digest("hex");
|
|
1471
|
+
return {
|
|
1472
|
+
entry: executablePackageModulePath(entry),
|
|
1473
|
+
project: {
|
|
1474
|
+
...project,
|
|
1475
|
+
digest,
|
|
1476
|
+
files
|
|
336
1477
|
}
|
|
337
1478
|
};
|
|
338
|
-
|
|
1479
|
+
}
|
|
1480
|
+
//#endregion
|
|
1481
|
+
//#region src/bundle.ts
|
|
1482
|
+
const SHIM_NAMESPACE = "vitehub-sandbox-runtime-shim";
|
|
1483
|
+
async function bundleSandboxDefinition(source, file, options = {}) {
|
|
1484
|
+
if (options.execution === "module" && options.project) {
|
|
1485
|
+
const entry = `${options.project.packagePath === "." ? "" : `${options.project.packagePath}/`}${basename(file)}`;
|
|
1486
|
+
const executable = prepareExecutablePackageProject(options.project, entry);
|
|
1487
|
+
return {
|
|
1488
|
+
entry: executable.entry,
|
|
1489
|
+
execution: "module",
|
|
1490
|
+
modules: {},
|
|
1491
|
+
project: executable.project
|
|
1492
|
+
};
|
|
1493
|
+
}
|
|
1494
|
+
const bundle = await bundleDiscoveredDefinitionModuleGraph({
|
|
1495
|
+
alias: options.alias,
|
|
1496
|
+
filename: file,
|
|
1497
|
+
packages: options.project ? "external" : "bundle",
|
|
1498
|
+
source,
|
|
1499
|
+
plugins: [{
|
|
1500
|
+
name: SHIM_NAMESPACE,
|
|
1501
|
+
setup(pluginBuild) {
|
|
1502
|
+
pluginBuild.onResolve({ filter: /^@vite-hub\/sandbox(?:\/runtime\/public)?$/ }, () => ({
|
|
1503
|
+
path: "sandbox-runtime-shim",
|
|
1504
|
+
namespace: SHIM_NAMESPACE
|
|
1505
|
+
}));
|
|
1506
|
+
pluginBuild.onLoad({
|
|
1507
|
+
filter: /.*/,
|
|
1508
|
+
namespace: SHIM_NAMESPACE
|
|
1509
|
+
}, () => ({
|
|
1510
|
+
contents: [
|
|
1511
|
+
"function hasStandardValidator(value) {",
|
|
1512
|
+
" return !!value && typeof value === \"object\" && !!value[\"~standard\"] && typeof value[\"~standard\"].validate === \"function\"",
|
|
1513
|
+
"}",
|
|
1514
|
+
"",
|
|
1515
|
+
"function createValidationError(cause) {",
|
|
1516
|
+
" if (cause instanceof Error)",
|
|
1517
|
+
" return cause",
|
|
1518
|
+
" const message = cause && typeof cause === \"object\" && typeof cause.message === \"string\"",
|
|
1519
|
+
" ? cause.message",
|
|
1520
|
+
" : \"Validation failed\"",
|
|
1521
|
+
" return Object.assign(new Error(message), cause && typeof cause === \"object\" ? cause : {})",
|
|
1522
|
+
"}",
|
|
1523
|
+
"",
|
|
1524
|
+
"export async function readValidatedPayload(payload, validate) {",
|
|
1525
|
+
" if (hasStandardValidator(validate)) {",
|
|
1526
|
+
" const result = await validate[\"~standard\"].validate(payload)",
|
|
1527
|
+
" if (result.issues?.length)",
|
|
1528
|
+
" throw createValidationError({ message: \"Validation failed\", issues: result.issues })",
|
|
1529
|
+
" return result.value",
|
|
1530
|
+
" }",
|
|
1531
|
+
" try {",
|
|
1532
|
+
" const result = await validate(payload)",
|
|
1533
|
+
" if (result === false)",
|
|
1534
|
+
" throw createValidationError({ message: \"Validation failed\" })",
|
|
1535
|
+
" return result === true || result == null ? payload : result",
|
|
1536
|
+
" }",
|
|
1537
|
+
" catch (error) {",
|
|
1538
|
+
" throw createValidationError(error)",
|
|
1539
|
+
" }",
|
|
1540
|
+
"}",
|
|
1541
|
+
"",
|
|
1542
|
+
"export function defineSandbox(input) {",
|
|
1543
|
+
" const { run, ...options } = input",
|
|
1544
|
+
" return { run, options: Object.keys(options).length ? options : undefined }",
|
|
1545
|
+
"}"
|
|
1546
|
+
].join("\n"),
|
|
1547
|
+
loader: "js"
|
|
1548
|
+
}));
|
|
1549
|
+
}
|
|
1550
|
+
}]
|
|
1551
|
+
});
|
|
1552
|
+
if (!options.project) return {
|
|
1553
|
+
...bundle,
|
|
1554
|
+
...options.execution ? { execution: options.execution } : {}
|
|
1555
|
+
};
|
|
1556
|
+
const prefix = options.project.packagePath === "." ? ".vitehub-sandbox" : `${options.project.packagePath}/.vitehub-sandbox`;
|
|
1557
|
+
const modules = {
|
|
1558
|
+
[`${prefix}/package.json`]: JSON.stringify({
|
|
1559
|
+
private: true,
|
|
1560
|
+
type: "module"
|
|
1561
|
+
}),
|
|
1562
|
+
...Object.fromEntries(Object.entries(bundle.modules).map(([path, contents]) => [`${prefix}/${path}`, contents]))
|
|
1563
|
+
};
|
|
1564
|
+
const digest = createHash("sha256").update(JSON.stringify({
|
|
1565
|
+
modules,
|
|
1566
|
+
packagePath: options.project.packagePath,
|
|
1567
|
+
project: options.project.digest
|
|
1568
|
+
})).digest("hex");
|
|
339
1569
|
return {
|
|
340
|
-
|
|
341
|
-
|
|
1570
|
+
entry: `${prefix}/${bundle.entry}`,
|
|
1571
|
+
...options.execution ? { execution: options.execution } : {},
|
|
1572
|
+
modules,
|
|
1573
|
+
project: {
|
|
1574
|
+
...options.project,
|
|
1575
|
+
digest
|
|
1576
|
+
}
|
|
342
1577
|
};
|
|
343
1578
|
}
|
|
344
|
-
|
|
345
|
-
|
|
1579
|
+
//#endregion
|
|
1580
|
+
//#region src/definition-options.ts
|
|
1581
|
+
const require = createRequire(import.meta.url);
|
|
1582
|
+
const sandboxDefinitionSyntax = "`defineSandbox({ run, ...options })`";
|
|
1583
|
+
function getTypeScript() {
|
|
1584
|
+
return require("typescript");
|
|
1585
|
+
}
|
|
1586
|
+
function readStaticValue(node) {
|
|
1587
|
+
const ts = getTypeScript();
|
|
1588
|
+
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;
|
|
1589
|
+
if (ts.isNumericLiteral(node)) return Number(node.text);
|
|
1590
|
+
if (node.kind === ts.SyntaxKind.TrueKeyword) return true;
|
|
1591
|
+
if (node.kind === ts.SyntaxKind.FalseKeyword) return false;
|
|
1592
|
+
if (node.kind === ts.SyntaxKind.NullKeyword) return null;
|
|
1593
|
+
if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(node.operand)) return -Number(node.operand.text);
|
|
1594
|
+
if (ts.isParenthesizedExpression(node)) return readStaticValue(node.expression);
|
|
1595
|
+
if (ts.isArrayLiteralExpression(node)) return node.elements.map((element) => {
|
|
1596
|
+
if (!ts.isExpression(element)) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options arrays must use static values.`);
|
|
1597
|
+
return readStaticValue(element);
|
|
1598
|
+
});
|
|
1599
|
+
if (ts.isObjectLiteralExpression(node)) {
|
|
1600
|
+
const value = {};
|
|
1601
|
+
for (const property of node.properties) {
|
|
1602
|
+
if (!ts.isPropertyAssignment(property)) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options must use plain object literals.`);
|
|
1603
|
+
const key = ts.isIdentifier(property.name) ? property.name.text : ts.isStringLiteral(property.name) ? property.name.text : void 0;
|
|
1604
|
+
if (!key) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options only support identifier or string-literal keys.`);
|
|
1605
|
+
value[key] = readStaticValue(property.initializer);
|
|
1606
|
+
}
|
|
1607
|
+
return value;
|
|
1608
|
+
}
|
|
1609
|
+
throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options must use static JSON-serializable values.`);
|
|
1610
|
+
}
|
|
1611
|
+
function readDefinitionObject(sourceFile) {
|
|
1612
|
+
const ts = getTypeScript();
|
|
1613
|
+
for (const statement of sourceFile.statements) {
|
|
1614
|
+
if (!ts.isExportAssignment(statement)) continue;
|
|
1615
|
+
const expression = statement.expression;
|
|
1616
|
+
if (!ts.isCallExpression(expression) || !ts.isIdentifier(expression.expression) || expression.expression.text !== "defineSandbox") continue;
|
|
1617
|
+
if (expression.arguments.length !== 1 || !ts.isObjectLiteralExpression(expression.arguments[0])) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} requires one direct object literal.`);
|
|
1618
|
+
return expression.arguments[0];
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
function propertyName(property) {
|
|
1622
|
+
const ts = getTypeScript();
|
|
1623
|
+
if (!("name" in property) || !property.name) return void 0;
|
|
1624
|
+
return ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) ? property.name.text : void 0;
|
|
1625
|
+
}
|
|
1626
|
+
async function extractSandboxDefinitionOptions(file) {
|
|
1627
|
+
const source = await readFile(file, "utf8");
|
|
1628
|
+
const ts = getTypeScript();
|
|
1629
|
+
const input = readDefinitionObject(ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS));
|
|
1630
|
+
if (!input) return void 0;
|
|
1631
|
+
const options = {};
|
|
1632
|
+
let hasRun = false;
|
|
1633
|
+
for (const property of input.properties) {
|
|
1634
|
+
const key = propertyName(property);
|
|
1635
|
+
if (key === "run" && ts.isShorthandPropertyAssignment(property)) {
|
|
1636
|
+
hasRun = true;
|
|
1637
|
+
continue;
|
|
1638
|
+
}
|
|
1639
|
+
if (!key || !ts.isPropertyAssignment(property) && !ts.isMethodDeclaration(property)) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} requires explicit object properties.`);
|
|
1640
|
+
if (key === "run") {
|
|
1641
|
+
hasRun = true;
|
|
1642
|
+
continue;
|
|
1643
|
+
}
|
|
1644
|
+
if (!ts.isPropertyAssignment(property)) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} options must use static values.`);
|
|
1645
|
+
options[key] = readStaticValue(property.initializer);
|
|
1646
|
+
}
|
|
1647
|
+
if (!hasRun) throw new Error(`[vitehub] ${sandboxDefinitionSyntax} requires a \`run\` handler.`);
|
|
1648
|
+
return Object.keys(options).length ? options : void 0;
|
|
346
1649
|
}
|
|
347
1650
|
//#endregion
|
|
348
|
-
//#region src/
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
"
|
|
352
|
-
"
|
|
353
|
-
|
|
1651
|
+
//#region src/type-template.ts
|
|
1652
|
+
function createDefinitionContract(definition) {
|
|
1653
|
+
const module = `typeof import(${JSON.stringify(definition.handler)})`;
|
|
1654
|
+
if (definition.kind === "definition") return `{ payload: Parameters<${module}['default']['run']>[0], result: Awaited<ReturnType<${module}['default']['run']>> }`;
|
|
1655
|
+
return `SandboxPackageContract<${module}['default'], ${definition.hasPayloadType ? `import(${JSON.stringify(definition.handler)}).SandboxPayload` : "unknown"}>`;
|
|
1656
|
+
}
|
|
1657
|
+
function createSandboxTypeTemplateContents(definitions) {
|
|
1658
|
+
return [
|
|
1659
|
+
`declare module '#vitehub-sandbox-registry' {`,
|
|
1660
|
+
` type SandboxPackageContract<TDefault, TFallbackPayload> = TDefault extends (...args: infer TArgs) => infer TResult`,
|
|
1661
|
+
` ? { payload: TArgs extends [] ? unknown : TArgs[0], result: Awaited<TResult> }`,
|
|
1662
|
+
` : { payload: TFallbackPayload, result: Awaited<TDefault> }`,
|
|
1663
|
+
` export interface SandboxDefinitionModules {`,
|
|
1664
|
+
...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: ${createDefinitionContract(definition)},`),
|
|
1665
|
+
` }`,
|
|
1666
|
+
` const sandboxRegistry: {`,
|
|
1667
|
+
...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: () => Promise<{ default?: { bundle: import('@vite-hub/sandbox').SandboxDefinitionBundle, options?: import('@vite-hub/sandbox').SandboxDefinitionOptions } }>,`),
|
|
1668
|
+
` }`,
|
|
1669
|
+
` export default sandboxRegistry`,
|
|
1670
|
+
`}`,
|
|
1671
|
+
``
|
|
1672
|
+
].join("\n");
|
|
1673
|
+
}
|
|
1674
|
+
//#endregion
|
|
1675
|
+
//#region src/feature.ts
|
|
1676
|
+
const sandboxRuntimeDependencyByProvider = {
|
|
1677
|
+
cloudflare: "@cloudflare/sandbox",
|
|
1678
|
+
vercel: "@vercel/sandbox"
|
|
1679
|
+
};
|
|
1680
|
+
function resolveSandboxProviderLoaderTarget(provider, deps) {
|
|
1681
|
+
if (provider) return provider;
|
|
1682
|
+
const hasCloudflareSandbox = Boolean(deps["@cloudflare/sandbox"]);
|
|
1683
|
+
if (hasCloudflareSandbox === Boolean(deps["@vercel/sandbox"])) return void 0;
|
|
1684
|
+
return hasCloudflareSandbox ? "cloudflare" : "vercel";
|
|
1685
|
+
}
|
|
1686
|
+
const sandboxProviderLoaderSpecifiers = [
|
|
1687
|
+
"vitehub-sandbox-provider-loader",
|
|
1688
|
+
"@vite-hub/sandbox/runtime/provider-loader",
|
|
1689
|
+
"virtual:vitehub-sandbox-provider-loader",
|
|
1690
|
+
"#vitehub-sandbox-provider-loader"
|
|
354
1691
|
];
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
return
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
const
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
1692
|
+
function createSandboxProviderLoaderAliases(defaultProviderName) {
|
|
1693
|
+
const keys = sandboxProviderLoaderSpecifiers;
|
|
1694
|
+
if (defaultProviderName) return keys.map((key) => ({
|
|
1695
|
+
key,
|
|
1696
|
+
artifactKey: "sandbox-provider-loader"
|
|
1697
|
+
}));
|
|
1698
|
+
const providerLoaderPath = resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox", "./runtime/provider-loader", "runtime/provider-loader.js");
|
|
1699
|
+
return keys.map((key) => ({
|
|
1700
|
+
key,
|
|
1701
|
+
value: providerLoaderPath
|
|
1702
|
+
}));
|
|
1703
|
+
}
|
|
1704
|
+
function createSandboxManifest(aliasPath, typeTemplate) {
|
|
365
1705
|
return {
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
1706
|
+
alias: "@vite-hub/sandbox",
|
|
1707
|
+
aliasPath,
|
|
1708
|
+
imports: [
|
|
1709
|
+
{
|
|
1710
|
+
name: "defineSandbox",
|
|
1711
|
+
from: "@vite-hub/sandbox",
|
|
1712
|
+
meta: { description: "Define a free-form sandbox resource." }
|
|
1713
|
+
},
|
|
1714
|
+
{
|
|
1715
|
+
name: "readValidatedPayload",
|
|
1716
|
+
as: "readValidatedSandboxPayload",
|
|
1717
|
+
from: "@vite-hub/sandbox",
|
|
1718
|
+
meta: { description: "Validate sandbox payload input before execution." }
|
|
1719
|
+
},
|
|
1720
|
+
{
|
|
1721
|
+
name: "runSandbox",
|
|
1722
|
+
from: "@vite-hub/sandbox",
|
|
1723
|
+
meta: { description: "Run a named sandbox definition." }
|
|
1724
|
+
},
|
|
1725
|
+
{
|
|
1726
|
+
name: "SandboxDefinition",
|
|
1727
|
+
as: "SandboxDefinition",
|
|
1728
|
+
from: "@vite-hub/sandbox",
|
|
1729
|
+
type: true
|
|
1730
|
+
},
|
|
1731
|
+
{
|
|
1732
|
+
name: "SandboxRunResult",
|
|
1733
|
+
as: "SandboxRunResult",
|
|
1734
|
+
from: "@vite-hub/sandbox",
|
|
1735
|
+
type: true
|
|
1736
|
+
}
|
|
1737
|
+
],
|
|
1738
|
+
typeTemplate: {
|
|
1739
|
+
filename: "runtime/sandbox.d.ts",
|
|
1740
|
+
contents: typeTemplate
|
|
1741
|
+
}
|
|
1742
|
+
};
|
|
1743
|
+
}
|
|
1744
|
+
function normalizeSandboxDefinitionOptions(name, options) {
|
|
1745
|
+
if (!options) return void 0;
|
|
1746
|
+
try {
|
|
1747
|
+
return JSON.parse(JSON.stringify(options));
|
|
1748
|
+
} catch (error) {
|
|
1749
|
+
throw new Error(`[vitehub] Sandbox definition "${name}" options must be JSON-serializable.`, { cause: error });
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
async function loadSandboxDefinitionMetadata(definitions, rootDir) {
|
|
1753
|
+
return await Promise.all(definitions.map(async (definition) => {
|
|
1754
|
+
const project = await resolveSandboxProject(definition.handler, rootDir, { readSandboxOptions: definition.kind === "package-entry" });
|
|
1755
|
+
const source = definition.kind === "package-entry" ? await readFile(definition.handler, "utf8") : void 0;
|
|
1756
|
+
return {
|
|
1757
|
+
hasPayloadType: source ? hasExportedType(source, definition.handler, "SandboxPayload") : false,
|
|
1758
|
+
kind: definition.kind,
|
|
1759
|
+
name: definition.name,
|
|
1760
|
+
options: definition.kind === "package-entry" ? project.options : normalizeSandboxDefinitionOptions(definition.name, await extractSandboxDefinitionOptions(definition.handler)),
|
|
1761
|
+
project
|
|
1762
|
+
};
|
|
1763
|
+
}));
|
|
1764
|
+
}
|
|
1765
|
+
function createSandboxRegistryContents(definitions) {
|
|
1766
|
+
return [
|
|
1767
|
+
"const registry = {",
|
|
1768
|
+
...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: async () => import(${JSON.stringify(definition.definitionModulePath)}),`),
|
|
1769
|
+
"}",
|
|
1770
|
+
"export default registry",
|
|
1771
|
+
""
|
|
1772
|
+
].join("\n");
|
|
1773
|
+
}
|
|
1774
|
+
function createSandboxProviderLoaderContents(provider) {
|
|
1775
|
+
const providerLoaderPath = resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox", `./runtime/providers/${provider}`, `runtime/providers/${provider}.js`);
|
|
1776
|
+
return [
|
|
1777
|
+
`import { resolveSandboxBox } from ${JSON.stringify(providerLoaderPath)}`,
|
|
1778
|
+
"",
|
|
1779
|
+
"export async function loadSandboxRuntimeProvider(selectedProvider) {",
|
|
1780
|
+
` if (selectedProvider !== ${JSON.stringify(provider)})`,
|
|
1781
|
+
" throw new Error(`[vitehub] Unsupported sandbox provider for this hosted build: ${selectedProvider}`)",
|
|
1782
|
+
" return {",
|
|
1783
|
+
" resolveSandboxBox,",
|
|
1784
|
+
" }",
|
|
1785
|
+
"}",
|
|
1786
|
+
""
|
|
1787
|
+
].join("\n");
|
|
1788
|
+
}
|
|
1789
|
+
function resolveSandboxFeatureConfig(sandboxConfig, hosting) {
|
|
1790
|
+
if (getSandboxFeatureProvider(sandboxConfig)?.provider) return { ...sandboxConfig };
|
|
1791
|
+
const config = { ...sandboxConfig };
|
|
1792
|
+
const hostedProvider = getSupportedHostingProvider(hosting, ["cloudflare", "vercel"]);
|
|
1793
|
+
if (hostedProvider) return {
|
|
1794
|
+
...config,
|
|
1795
|
+
provider: hostedProvider
|
|
1796
|
+
};
|
|
1797
|
+
const unsupportedHostedProvider = deploymentPresetFromNitro(hosting);
|
|
1798
|
+
if (unsupportedHostedProvider) throw new TypeError("[vitehub] Sandbox hosting inference does not support " + unsupportedHostedProvider + ". An explicit `sandbox.provider` is required.");
|
|
1799
|
+
return config;
|
|
1800
|
+
}
|
|
1801
|
+
async function createSandboxFeaturePlan(sandboxConfig, definitions, paths, deps, hosting, discoveredDefinitionOptions = {}) {
|
|
1802
|
+
const resolvedConfig = definitions.length > 0 ? resolveSandboxFeatureConfig(sandboxConfig, hosting) : { ...sandboxConfig };
|
|
1803
|
+
const sandboxDefinitions = definitions.map((definition) => ({
|
|
1804
|
+
...definition,
|
|
1805
|
+
definitionArtifactKey: `sandbox-definition:${definition.name}`,
|
|
1806
|
+
definitionFilename: `runtime/sandbox-definitions/${toTemplateSafeName(definition.name)}.mjs`
|
|
1807
|
+
}));
|
|
1808
|
+
const definitionFileByName = /* @__PURE__ */ new Map();
|
|
1809
|
+
for (const definition of sandboxDefinitions) {
|
|
1810
|
+
const existing = definitionFileByName.get(definition.definitionFilename);
|
|
1811
|
+
if (existing) throw new Error(`[vitehub] Sandbox definitions "${existing}" and "${definition.name}" generate the same artifact path "${definition.definitionFilename}".`);
|
|
1812
|
+
definitionFileByName.set(definition.definitionFilename, definition.name);
|
|
1813
|
+
}
|
|
1814
|
+
const definitionMetadata = await loadSandboxDefinitionMetadata(definitions, discoveredDefinitionOptions.rootDir || process.cwd());
|
|
1815
|
+
const metadataByName = new Map(definitionMetadata.map((definition) => [definition.name, definition]));
|
|
1816
|
+
const manifest = createSandboxManifest(paths.aliasPath, createSandboxTypeTemplateContents(definitions.map((definition) => {
|
|
1817
|
+
const metadata = metadataByName.get(definition.name);
|
|
1818
|
+
return {
|
|
1819
|
+
handler: definition.handler,
|
|
1820
|
+
hasPayloadType: metadata?.hasPayloadType ?? false,
|
|
1821
|
+
kind: definition.kind,
|
|
1822
|
+
name: definition.name
|
|
1823
|
+
};
|
|
1824
|
+
})));
|
|
1825
|
+
const { bundleAlias, featureImports = manifest.imports, ...definitionCompilerOptions } = discoveredDefinitionOptions;
|
|
1826
|
+
const definitionCompiler = await createDiscoveredDefinitionCompiler({
|
|
1827
|
+
...definitionCompilerOptions,
|
|
1828
|
+
featureImports
|
|
1829
|
+
});
|
|
1830
|
+
const defaultProvider = getSandboxFeatureProvider(resolvedConfig);
|
|
1831
|
+
const defaultProviderName = defaultProvider?.provider;
|
|
1832
|
+
const sandboxArtifacts = sandboxDefinitions.map((definition) => ({
|
|
1833
|
+
key: definition.definitionArtifactKey,
|
|
1834
|
+
filename: definition.definitionFilename,
|
|
1835
|
+
async getContents() {
|
|
1836
|
+
const source = await definitionCompiler.readSource(definition._meta.sourcePath);
|
|
1837
|
+
const metadata = metadataByName.get(definition.name);
|
|
1838
|
+
const bundle = await bundleSandboxDefinition(source, definition._meta.sourcePath, {
|
|
1839
|
+
alias: bundleAlias,
|
|
1840
|
+
execution: metadata?.kind === "package-entry" ? "module" : "definition",
|
|
1841
|
+
project: metadata?.project
|
|
374
1842
|
});
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
1843
|
+
return `export default ${JSON.stringify({
|
|
1844
|
+
bundle,
|
|
1845
|
+
options: metadata?.options
|
|
1846
|
+
})}\n`;
|
|
1847
|
+
}
|
|
1848
|
+
}));
|
|
1849
|
+
const providerLoaderTarget = resolveSandboxProviderLoaderTarget(defaultProviderName, deps);
|
|
1850
|
+
const cloudflareOptions = defaultProvider?.provider === "cloudflare" ? {
|
|
1851
|
+
binding: typeof defaultProvider.binding === "string" ? defaultProvider.binding : defaultCloudflareSandboxBinding,
|
|
1852
|
+
className: typeof defaultProvider.className === "string" ? defaultProvider.className : defaultCloudflareSandboxClassName,
|
|
1853
|
+
migrationTag: typeof defaultProvider.migrationTag === "string" ? defaultProvider.migrationTag : "v1",
|
|
1854
|
+
name: typeof defaultProvider.name === "string" ? defaultProvider.name : void 0
|
|
1855
|
+
} : void 0;
|
|
1856
|
+
return {
|
|
1857
|
+
manifest,
|
|
1858
|
+
aliases: [{
|
|
1859
|
+
key: "#vitehub-sandbox-registry",
|
|
1860
|
+
artifactKey: "sandbox-registry"
|
|
1861
|
+
}, ...createSandboxProviderLoaderAliases(providerLoaderTarget)],
|
|
1862
|
+
artifacts: [
|
|
1863
|
+
...sandboxArtifacts,
|
|
1864
|
+
{
|
|
1865
|
+
key: "sandbox-registry",
|
|
1866
|
+
filename: "runtime/sandbox-registry.mjs",
|
|
1867
|
+
getContents(emitted) {
|
|
1868
|
+
return createSandboxRegistryContents(sandboxDefinitions.map((definition) => {
|
|
1869
|
+
const artifact = emitted.get(definition.definitionArtifactKey);
|
|
1870
|
+
if (!artifact) throw new Error(`[vitehub] Missing generated sandbox definition module for "${definition.name}".`);
|
|
1871
|
+
return {
|
|
1872
|
+
name: definition.name,
|
|
1873
|
+
definitionModulePath: artifact.dst
|
|
1874
|
+
};
|
|
1875
|
+
}));
|
|
1876
|
+
}
|
|
1877
|
+
},
|
|
1878
|
+
...providerLoaderTarget ? [{
|
|
1879
|
+
key: "sandbox-provider-loader",
|
|
1880
|
+
filename: "runtime/sandbox-provider-loader.mjs",
|
|
1881
|
+
getContents: () => createSandboxProviderLoaderContents(providerLoaderTarget)
|
|
1882
|
+
}] : []
|
|
1883
|
+
],
|
|
1884
|
+
cloudflare: cloudflareOptions
|
|
1885
|
+
};
|
|
1886
|
+
}
|
|
1887
|
+
//#endregion
|
|
1888
|
+
//#region ../internal/src/object.ts
|
|
1889
|
+
function isPlainObject(value) {
|
|
1890
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
1891
|
+
}
|
|
1892
|
+
//#endregion
|
|
1893
|
+
//#region src/discovery.ts
|
|
1894
|
+
const sandboxSuffixPattern = /\.sandbox\.(?:c|m)?[jt]s$/i;
|
|
1895
|
+
const sandboxEntrypointFilenames = [
|
|
1896
|
+
"index.ts",
|
|
1897
|
+
"index.mts",
|
|
1898
|
+
"index.js",
|
|
1899
|
+
"index.mjs"
|
|
1900
|
+
];
|
|
1901
|
+
function createDiscoveredSandboxDefinition(source, kind) {
|
|
1902
|
+
return (context) => ({
|
|
1903
|
+
handler: context.file,
|
|
1904
|
+
kind,
|
|
1905
|
+
name: context.name,
|
|
1906
|
+
source,
|
|
1907
|
+
_meta: {
|
|
1908
|
+
filename: context.name,
|
|
1909
|
+
sourcePath: context.file
|
|
1910
|
+
}
|
|
1911
|
+
});
|
|
1912
|
+
}
|
|
1913
|
+
function isServerSandboxFile(rootDir, file) {
|
|
1914
|
+
const path = relative(rootDir, file).replace(/\\/g, "/");
|
|
1915
|
+
return path.startsWith("server/sandboxes/") || path.startsWith("src/server/sandboxes/");
|
|
1916
|
+
}
|
|
1917
|
+
function normalizeSuffixSandboxName(rootDir, file) {
|
|
1918
|
+
if (isServerSandboxFile(rootDir, file)) return void 0;
|
|
1919
|
+
return normalizeSuffixDefinitionName(rootDir, file, sandboxSuffixPattern, { stripPrefix: "src/" });
|
|
1920
|
+
}
|
|
1921
|
+
function normalizeDirectorySandboxName(directory, file) {
|
|
1922
|
+
return normalizePathDefinitionName(directory, file).replace(/\.sandbox$/, "");
|
|
1923
|
+
}
|
|
1924
|
+
function isNestedDirectory(parent, candidate) {
|
|
1925
|
+
const path = relative(parent, candidate).replace(/\\/g, "/");
|
|
1926
|
+
return path !== "" && path !== ".." && !path.startsWith("../");
|
|
1927
|
+
}
|
|
1928
|
+
function discoverServerSandboxDefinitions(scanDirs) {
|
|
1929
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
1930
|
+
const createDefinition = createDiscoveredSandboxDefinition("server-sandboxes", "package-entry");
|
|
1931
|
+
for (const scanDir of scanDirs) {
|
|
1932
|
+
const directory = resolve(scanDir, "sandboxes");
|
|
1933
|
+
const packageRoots = listMatchingFiles(directory, (name) => name === "package.json").map((manifest) => dirname(manifest)).sort((left, right) => {
|
|
1934
|
+
return relative(directory, left).split(/[\\/]/).length - relative(directory, right).split(/[\\/]/).length || left.localeCompare(right);
|
|
1935
|
+
});
|
|
1936
|
+
const entrypoints = new Map(packageRoots.map((packageRoot) => [packageRoot, sandboxEntrypointFilenames.map((filename) => resolve(packageRoot, filename)).filter((file) => existsSync(file))]));
|
|
1937
|
+
const selectedRoots = [];
|
|
1938
|
+
for (const packageRoot of packageRoots) {
|
|
1939
|
+
if (selectedRoots.some((root) => isNestedDirectory(root, packageRoot))) continue;
|
|
1940
|
+
const packageEntrypoints = entrypoints.get(packageRoot);
|
|
1941
|
+
if (packageEntrypoints.length > 1) throw new Error(`[vitehub] Sandbox package "${packageRoot}" has multiple entrypoints: ${packageEntrypoints.join(", ")}.`);
|
|
1942
|
+
if (packageEntrypoints.length === 0) continue;
|
|
1943
|
+
const file = packageEntrypoints[0];
|
|
1944
|
+
registerDefinition(definitions, createDefinition({
|
|
1945
|
+
file,
|
|
1946
|
+
name: normalizeDirectorySandboxName(directory, file)
|
|
1947
|
+
}), "sandbox");
|
|
1948
|
+
selectedRoots.push(packageRoot);
|
|
1949
|
+
}
|
|
1950
|
+
for (const packageRoot of packageRoots) {
|
|
1951
|
+
if (entrypoints.get(packageRoot).length > 0) continue;
|
|
1952
|
+
if (selectedRoots.some((root) => isNestedDirectory(packageRoot, root) || isNestedDirectory(root, packageRoot))) continue;
|
|
1953
|
+
throw new Error(`[vitehub] Sandbox package "${packageRoot}" requires one ESM entrypoint: ${sandboxEntrypointFilenames.join(", ")}.`);
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
return sortDefinitions(definitions);
|
|
1957
|
+
}
|
|
1958
|
+
function discoverSandboxDefinitions(options) {
|
|
1959
|
+
if (options.mode === "server-sandboxes") return discoverServerSandboxDefinitions(options.scanDirs);
|
|
1960
|
+
const roots = resolveDefinitionScanRoots(options.rootDir, options.scanDirs);
|
|
1961
|
+
const serverScanDirs = roots.map((root) => resolve(root, "server"));
|
|
1962
|
+
return mergeDefinitions("sandbox", discoverDefinitions("sandbox", [createSuffixDefinitionSource("vite-suffix", roots, sandboxSuffixPattern, normalizeSuffixSandboxName, { createDefinition: createDiscoveredSandboxDefinition("vite-suffix", "definition") })]), discoverServerSandboxDefinitions(serverScanDirs));
|
|
1963
|
+
}
|
|
1964
|
+
//#endregion
|
|
1965
|
+
//#region src/internal/runtime-preparation.ts
|
|
1966
|
+
const SANDBOX_PACKAGE_ID$1 = "@vite-hub/sandbox";
|
|
1967
|
+
const SANDBOX_REGISTRY_ID = "#vitehub-sandbox-registry";
|
|
1968
|
+
const builtinModuleSet = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
|
|
1969
|
+
function normalizeSandboxOptions(options) {
|
|
1970
|
+
if (options === false) return false;
|
|
1971
|
+
if (!isPlainObject(options)) throw new TypeError("[vitehub] `sandbox` must be a plain object.");
|
|
1972
|
+
return { ...options };
|
|
1973
|
+
}
|
|
1974
|
+
function createSandboxRuntimeConfig(config, hosting) {
|
|
1975
|
+
const provider = getSandboxFeatureProvider(config);
|
|
1976
|
+
const sandbox = provider?.provider === "vercel" ? {
|
|
1977
|
+
...config,
|
|
1978
|
+
token: provider.token ?? "",
|
|
1979
|
+
teamId: provider.teamId ?? "",
|
|
1980
|
+
projectId: provider.projectId ?? ""
|
|
1981
|
+
} : config;
|
|
1982
|
+
return {
|
|
1983
|
+
...hosting ? { hosting } : {},
|
|
1984
|
+
sandbox
|
|
1985
|
+
};
|
|
1986
|
+
}
|
|
1987
|
+
async function readSandboxWorkspaceDeps(rootDir) {
|
|
1988
|
+
const packageJson = JSON.parse(await readFile(resolve(rootDir, "package.json"), "utf8"));
|
|
1989
|
+
return {
|
|
1990
|
+
...packageJson.dependencies,
|
|
1991
|
+
...packageJson.devDependencies
|
|
1992
|
+
};
|
|
1993
|
+
}
|
|
1994
|
+
async function resolveSandboxViteContext(integrationOptions, userConfig, env, hasDefinitions) {
|
|
1995
|
+
const configOptions = userConfig.sandbox;
|
|
1996
|
+
const options = normalizeSandboxOptions(typeof configOptions === "undefined" ? integrationOptions ?? {} : configOptions);
|
|
1997
|
+
const nitro = isPlainObject(userConfig.nitro) ? userConfig.nitro : {};
|
|
1998
|
+
const hosting = detectHosting({ options: { preset: typeof userConfig.preset === "string" ? userConfig.preset : typeof nitro.preset === "string" ? nitro.preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET } }) || void 0;
|
|
1999
|
+
const config = options === false ? false : hasDefinitions ? resolveSandboxFeatureConfig(options, hosting) : { ...options };
|
|
2000
|
+
const runtimeSandboxConfig = config !== false && (hasDefinitions || getSandboxFeatureProvider(config)?.provider) ? config : false;
|
|
2001
|
+
const rootDir = resolve(process.cwd(), typeof userConfig.root === "string" ? userConfig.root : ".");
|
|
2002
|
+
return {
|
|
2003
|
+
rootDir,
|
|
2004
|
+
config,
|
|
2005
|
+
deps: hasDefinitions ? await readSandboxWorkspaceDeps(rootDir) : {},
|
|
2006
|
+
runtimeConfig: createSandboxRuntimeConfig(runtimeSandboxConfig, hosting),
|
|
2007
|
+
hosting,
|
|
2008
|
+
command: env.command,
|
|
2009
|
+
mode: env.mode
|
|
2010
|
+
};
|
|
2011
|
+
}
|
|
2012
|
+
function createSandboxStateModuleContents(context) {
|
|
2013
|
+
const state = {
|
|
2014
|
+
config: context.config,
|
|
2015
|
+
runtimeConfig: context.runtimeConfig,
|
|
2016
|
+
hosting: context.hosting,
|
|
2017
|
+
rootDir: context.rootDir,
|
|
2018
|
+
mode: context.mode,
|
|
2019
|
+
command: context.command
|
|
2020
|
+
};
|
|
2021
|
+
return [
|
|
2022
|
+
`const state = ${JSON.stringify(state, null, 2)}`,
|
|
2023
|
+
"export const config = state.config",
|
|
2024
|
+
"export const runtimeConfig = state.runtimeConfig",
|
|
2025
|
+
"export const hosting = state.hosting",
|
|
2026
|
+
"export const rootDir = state.rootDir",
|
|
2027
|
+
"export const mode = state.mode",
|
|
2028
|
+
"export const command = state.command",
|
|
2029
|
+
"export default state",
|
|
2030
|
+
""
|
|
2031
|
+
].join("\n");
|
|
2032
|
+
}
|
|
2033
|
+
function readAliasEntries(alias) {
|
|
2034
|
+
if (Array.isArray(alias)) return alias;
|
|
2035
|
+
if (!alias || typeof alias !== "object") return [];
|
|
2036
|
+
return Object.entries(alias).filter((entry) => typeof entry[1] === "string").map(([find, replacement]) => ({
|
|
2037
|
+
find,
|
|
2038
|
+
replacement
|
|
2039
|
+
}));
|
|
2040
|
+
}
|
|
2041
|
+
function resolveStringAliases(alias) {
|
|
2042
|
+
const aliases = {};
|
|
2043
|
+
for (const entry of readAliasEntries(alias)) {
|
|
2044
|
+
if (typeof entry.find !== "string" || typeof entry.replacement !== "string") continue;
|
|
2045
|
+
const find = entry.find.replace(/\/$/, "");
|
|
2046
|
+
if (builtinModuleSet.has(entry.find) || builtinModuleSet.has(find)) continue;
|
|
2047
|
+
if (!find) continue;
|
|
2048
|
+
aliases[find] = entry.replacement;
|
|
2049
|
+
}
|
|
2050
|
+
return aliases;
|
|
2051
|
+
}
|
|
2052
|
+
function readResolveOptions(config) {
|
|
2053
|
+
if (!config || typeof config !== "object" || !("resolve" in config)) return {};
|
|
2054
|
+
const resolveOptions = config.resolve;
|
|
2055
|
+
return resolveOptions && typeof resolveOptions === "object" ? resolveOptions : {};
|
|
2056
|
+
}
|
|
2057
|
+
function createSandboxRuntimeFacadeContents(file, runtimeConfig, registryFile) {
|
|
2058
|
+
const stateFile = resolveFeatureRuntimePath(import.meta.url, SANDBOX_PACKAGE_ID$1, "./runtime/state", "runtime/state.js");
|
|
2059
|
+
const packageIndexFile = resolveFeatureRuntimePath(import.meta.url, SANDBOX_PACKAGE_ID$1, "./index", "index.js");
|
|
2060
|
+
return [
|
|
2061
|
+
`import sandboxRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
|
|
2062
|
+
`import { setSandboxRuntimeConfig, setSandboxRuntimeRegistry } from ${JSON.stringify(createImportPath(file, stateFile))}`,
|
|
2063
|
+
"",
|
|
2064
|
+
`setSandboxRuntimeConfig(${JSON.stringify(runtimeConfig, null, 2)})`,
|
|
2065
|
+
"setSandboxRuntimeRegistry(sandboxRegistry)",
|
|
2066
|
+
"",
|
|
2067
|
+
`export * from ${JSON.stringify(createImportPath(file, packageIndexFile))}`,
|
|
2068
|
+
""
|
|
2069
|
+
].join("\n");
|
|
2070
|
+
}
|
|
2071
|
+
function createGeneratedAliasMap(rootDir, plan) {
|
|
2072
|
+
const generatedDir = ensureGeneratedDir(rootDir, "sandbox");
|
|
2073
|
+
const artifactPaths = new Map((plan.artifacts || []).map((artifact) => [artifact.key, resolve(generatedDir, artifact.filename)]));
|
|
2074
|
+
const aliases = { [SANDBOX_PACKAGE_ID$1]: plan.manifest.aliasPath };
|
|
2075
|
+
for (const alias of plan.aliases || []) {
|
|
2076
|
+
if (alias.value) {
|
|
2077
|
+
aliases[alias.key] = alias.value;
|
|
2078
|
+
continue;
|
|
378
2079
|
}
|
|
2080
|
+
if (alias.artifactKey && artifactPaths.has(alias.artifactKey)) aliases[alias.key] = artifactPaths.get(alias.artifactKey);
|
|
2081
|
+
}
|
|
2082
|
+
return aliases;
|
|
2083
|
+
}
|
|
2084
|
+
async function writeSandboxArtifacts(rootDir, plan) {
|
|
2085
|
+
const generatedDir = ensureGeneratedDir(rootDir, "sandbox");
|
|
2086
|
+
const emitted = /* @__PURE__ */ new Map();
|
|
2087
|
+
const typeTemplate = plan.manifest.typeTemplate;
|
|
2088
|
+
if (typeTemplate) await writeFileIfChanged(resolve(generatedDir, typeTemplate.filename), typeTemplate.contents);
|
|
2089
|
+
for (const artifact of plan.artifacts || []) {
|
|
2090
|
+
const dst = resolve(generatedDir, artifact.filename);
|
|
2091
|
+
const contents = artifact.contents ?? await artifact.getContents?.(emitted);
|
|
2092
|
+
if (typeof contents !== "string") throw new Error(`[vitehub] Sandbox generated artifact "${artifact.key}" did not return contents.`);
|
|
2093
|
+
emitted.set(artifact.key, {
|
|
2094
|
+
...artifact,
|
|
2095
|
+
contents,
|
|
2096
|
+
dst
|
|
2097
|
+
});
|
|
2098
|
+
await writeFileIfChanged(dst, contents);
|
|
2099
|
+
}
|
|
2100
|
+
return emitted;
|
|
2101
|
+
}
|
|
2102
|
+
async function prepareSandboxRuntime(options) {
|
|
2103
|
+
const rootDir = options.resolvedConfig?.root || resolve(process.cwd(), typeof options.userConfig.root === "string" ? options.userConfig.root : ".");
|
|
2104
|
+
const configOptions = options.userConfig.sandbox;
|
|
2105
|
+
const definitions = (typeof configOptions === "undefined" ? options.integrationOptions === false : configOptions === false) ? [] : discoverSandboxDefinitions({ rootDir });
|
|
2106
|
+
const resolvedNitro = options.resolvedConfig?.nitro;
|
|
2107
|
+
const context = await resolveSandboxViteContext(options.integrationOptions, {
|
|
2108
|
+
...options.userConfig,
|
|
2109
|
+
...isPlainObject(resolvedNitro) ? { nitro: resolvedNitro } : {},
|
|
2110
|
+
root: rootDir
|
|
2111
|
+
}, options.env, definitions.length > 0);
|
|
2112
|
+
const stateModule = createSandboxStateModuleContents(context);
|
|
2113
|
+
if (!context.config) return {
|
|
2114
|
+
aliases: {},
|
|
2115
|
+
definitions: [],
|
|
2116
|
+
files: [],
|
|
2117
|
+
hosting: context.hosting,
|
|
2118
|
+
provider: void 0,
|
|
2119
|
+
stateModule
|
|
2120
|
+
};
|
|
2121
|
+
const facadeFile = resolve(ensureGeneratedDir(rootDir, "sandbox"), "runtime/sandbox.mjs");
|
|
2122
|
+
const plan = await createSandboxFeaturePlan(context.config, definitions, { aliasPath: facadeFile }, context.deps, context.hosting, {
|
|
2123
|
+
bundleAlias: resolveStringAliases(options.resolvedConfig?.resolve.alias ?? readResolveOptions(options.userConfig).alias),
|
|
2124
|
+
rootDir,
|
|
2125
|
+
scanRoots: [rootDir],
|
|
2126
|
+
serverImports: { presets: [] }
|
|
2127
|
+
});
|
|
2128
|
+
const aliases = createGeneratedAliasMap(rootDir, plan);
|
|
2129
|
+
if (options.writeArtifacts === false) return {
|
|
2130
|
+
aliases,
|
|
2131
|
+
cloudflare: plan.cloudflare,
|
|
2132
|
+
definitions,
|
|
2133
|
+
files: [],
|
|
2134
|
+
hosting: context.hosting,
|
|
2135
|
+
provider: getSandboxFeatureProvider(context.config)?.provider,
|
|
2136
|
+
stateModule
|
|
2137
|
+
};
|
|
2138
|
+
const emitted = await writeSandboxArtifacts(rootDir, plan);
|
|
2139
|
+
await writeFileIfChanged(facadeFile, createSandboxRuntimeFacadeContents(facadeFile, context.runtimeConfig.sandbox, aliases[SANDBOX_REGISTRY_ID]));
|
|
2140
|
+
return {
|
|
2141
|
+
aliases,
|
|
2142
|
+
cloudflare: plan.cloudflare,
|
|
2143
|
+
definitions,
|
|
2144
|
+
files: [facadeFile, ...Array.from(emitted.values(), (artifact) => artifact.dst)],
|
|
2145
|
+
hosting: context.hosting,
|
|
2146
|
+
provider: getSandboxFeatureProvider(context.config)?.provider,
|
|
2147
|
+
stateModule
|
|
379
2148
|
};
|
|
380
2149
|
}
|
|
381
2150
|
//#endregion
|
|
382
2151
|
//#region src/vite.ts
|
|
2152
|
+
const SANDBOX_PACKAGE_ID = "@vite-hub/sandbox";
|
|
383
2153
|
const SANDBOX_PROVIDER_LOADER_ID = "vitehub-sandbox-provider-loader";
|
|
2154
|
+
const SANDBOX_STATE_ID = "#vitehub/sandbox";
|
|
2155
|
+
const RESOLVED_SANDBOX_STATE_ID = "\0vitehub:sandbox:state";
|
|
2156
|
+
function mergeSandboxNitroProviderAliases(nitro, aliases) {
|
|
2157
|
+
const providerAliases = Object.fromEntries(sandboxProviderLoaderSpecifiers.flatMap((specifier) => {
|
|
2158
|
+
const replacement = aliases[specifier];
|
|
2159
|
+
return replacement ? [[specifier, replacement]] : [];
|
|
2160
|
+
}));
|
|
2161
|
+
if (!Object.keys(providerAliases).length) return;
|
|
2162
|
+
nitro.alias = {
|
|
2163
|
+
...nitro.alias && typeof nitro.alias === "object" && !Array.isArray(nitro.alias) ? nitro.alias : {},
|
|
2164
|
+
...providerAliases
|
|
2165
|
+
};
|
|
2166
|
+
}
|
|
2167
|
+
function mergeSandboxNitroNoExternals(nitro, provider) {
|
|
2168
|
+
if (provider !== "cloudflare" && provider !== "vercel") return;
|
|
2169
|
+
const existing = nitro.noExternals;
|
|
2170
|
+
if (existing === true) return;
|
|
2171
|
+
const existingEntries = Array.isArray(existing) ? existing : [];
|
|
2172
|
+
const additions = [SANDBOX_PACKAGE_ID, sandboxRuntimeDependencyByProvider[provider]];
|
|
2173
|
+
nitro.noExternals = [...existingEntries, ...additions.filter((addition) => !existingEntries.includes(addition))];
|
|
2174
|
+
}
|
|
384
2175
|
function sandboxProviderLoaderFallback() {
|
|
385
2176
|
return resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox", "./runtime/provider-loader", "runtime/provider-loader.js");
|
|
386
2177
|
}
|
|
387
|
-
function
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
2178
|
+
function sandboxPackageRuntime() {
|
|
2179
|
+
return dirname(resolveFeatureRuntimePath(import.meta.url, "@vite-hub/sandbox", "./index", "index.js"));
|
|
2180
|
+
}
|
|
2181
|
+
function toSandboxAliasEntries(aliases) {
|
|
2182
|
+
return Object.entries(aliases).map(([find, replacement]) => ({
|
|
2183
|
+
find: find === SANDBOX_PACKAGE_ID ? /^@vite-hub\/sandbox$/ : find,
|
|
391
2184
|
replacement
|
|
392
|
-
}
|
|
393
|
-
return {
|
|
394
|
-
...alias && typeof alias === "object" ? alias : {},
|
|
395
|
-
[SANDBOX_PROVIDER_LOADER_ID]: replacement
|
|
396
|
-
};
|
|
2185
|
+
}));
|
|
397
2186
|
}
|
|
398
|
-
function
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
2187
|
+
function withoutSandboxPackageAlias(aliases) {
|
|
2188
|
+
const { [SANDBOX_PACKAGE_ID]: _sandboxAlias, ...rest } = aliases;
|
|
2189
|
+
return rest;
|
|
2190
|
+
}
|
|
2191
|
+
function isSandboxSourceFile(file) {
|
|
2192
|
+
return /\.(?:c|m)?[jt]s$/i.test(file) && !/\.d\.(?:c|m)?[jt]s$/i.test(file);
|
|
2193
|
+
}
|
|
2194
|
+
function isLocalSourceFile(file, rootDir) {
|
|
2195
|
+
if (!rootDir) return false;
|
|
2196
|
+
const path = normalize(relative(rootDir, file));
|
|
2197
|
+
return path !== "" && !path.startsWith("../") && !path.startsWith("/") && !path.startsWith("node_modules/") && !path.startsWith(".vitehub/");
|
|
2198
|
+
}
|
|
2199
|
+
function isSandboxProjectManifestUpdate(file, rootDir) {
|
|
2200
|
+
if (basename(file) !== "package.json" || !isLocalSourceFile(file, rootDir)) return false;
|
|
2201
|
+
const path = normalize(relative(rootDir, file));
|
|
2202
|
+
return /(?:^|\/)(?:src\/)?server\/sandboxes\//.test(path);
|
|
2203
|
+
}
|
|
2204
|
+
function isSandboxProjectFileUpdate(file, rootDir) {
|
|
2205
|
+
if (!isLocalSourceFile(file, rootDir)) return false;
|
|
2206
|
+
const path = normalize(relative(rootDir, file));
|
|
2207
|
+
return /(?:^|\/)(?:src\/)?server\/sandboxes\//.test(path) || /^(?:pnpm-workspace\.yaml|pnpm-lock\.yaml|package-lock\.json|yarn\.lock|bun\.lock)$/.test(path);
|
|
2208
|
+
}
|
|
2209
|
+
function isSandboxDefinitionUpdate(file, definitions, generatedFiles, rootDir) {
|
|
2210
|
+
const changedFile = normalize(file);
|
|
2211
|
+
if (definitions.some((definition) => normalize(definition.handler) === changedFile)) return true;
|
|
2212
|
+
if (generatedFiles.some((file) => normalize(file) === changedFile)) return false;
|
|
2213
|
+
if (isSandboxProjectManifestUpdate(changedFile, rootDir)) return true;
|
|
2214
|
+
if (isSandboxProjectFileUpdate(changedFile, rootDir)) return true;
|
|
2215
|
+
if (!isSandboxSourceFile(changedFile)) return false;
|
|
2216
|
+
return /\.sandbox\.(?:c|m)?[jt]s$/i.test(changedFile) || /(?:^|\/)(?:src\/)?server\/sandboxes\//.test(changedFile) || isLocalSourceFile(changedFile, rootDir);
|
|
2217
|
+
}
|
|
2218
|
+
function invalidateGeneratedSandboxModules(files, moduleGraph) {
|
|
2219
|
+
for (const file of new Set(files.map((file) => normalize(file)))) {
|
|
2220
|
+
const module = moduleGraph.getModuleById(file);
|
|
2221
|
+
if (module) moduleGraph.invalidateModule(module);
|
|
2222
|
+
}
|
|
402
2223
|
}
|
|
403
2224
|
function hubSandbox(options) {
|
|
404
|
-
const
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
2225
|
+
const internalOptions = options;
|
|
2226
|
+
const integrationOptions = options && typeof options === "object" ? Object.fromEntries(Object.entries(options).filter(([key]) => key !== "providerImportAliases" && key !== "providerImportSpecifier")) : options;
|
|
2227
|
+
const mergeSandboxNoExternal = createNoExternalMerger("@vite-hub/sandbox");
|
|
2228
|
+
let generatedAliases = {};
|
|
2229
|
+
let generatedFiles = [];
|
|
2230
|
+
let definitions = [];
|
|
2231
|
+
let sandboxStateModule;
|
|
2232
|
+
let rawConfig = {};
|
|
2233
|
+
let rawEnv = {
|
|
2234
|
+
command: "serve",
|
|
2235
|
+
mode: "development"
|
|
2236
|
+
};
|
|
2237
|
+
let resolvedConfig;
|
|
2238
|
+
let selectedProvider;
|
|
2239
|
+
let earlyNitroTarget;
|
|
2240
|
+
let earlyNitroSnapshot;
|
|
2241
|
+
let composedCloudflareEarly = false;
|
|
2242
|
+
const sandboxNitroModule = (nitro) => {
|
|
2243
|
+
mergeSandboxNitroNoExternals(nitro.options, selectedProvider);
|
|
2244
|
+
if (selectedProvider) mergeSandboxNitroProviderAliases(nitro.options, generatedAliases);
|
|
2245
|
+
nitro.hooks.hook("build:before", () => {
|
|
2246
|
+
mergeSandboxNitroNoExternals(nitro.options, selectedProvider);
|
|
2247
|
+
if (selectedProvider) mergeSandboxNitroProviderAliases(nitro.options, generatedAliases);
|
|
2248
|
+
});
|
|
2249
|
+
};
|
|
2250
|
+
function cloneConfigValue(value) {
|
|
2251
|
+
if (Array.isArray(value)) return value.map(cloneConfigValue);
|
|
2252
|
+
if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, cloneConfigValue(entry)]));
|
|
2253
|
+
return value;
|
|
2254
|
+
}
|
|
2255
|
+
async function prepareCurrentSandboxRuntime(writeArtifacts = true) {
|
|
2256
|
+
const prepared = await prepareSandboxRuntime({
|
|
2257
|
+
integrationOptions,
|
|
2258
|
+
userConfig: rawConfig,
|
|
2259
|
+
env: rawEnv,
|
|
2260
|
+
resolvedConfig,
|
|
2261
|
+
writeArtifacts
|
|
2262
|
+
});
|
|
2263
|
+
sandboxStateModule = prepared.stateModule;
|
|
2264
|
+
return prepared;
|
|
2265
|
+
}
|
|
2266
|
+
async function refreshSandboxRuntime() {
|
|
2267
|
+
const prepared = await prepareCurrentSandboxRuntime();
|
|
2268
|
+
generatedAliases = prepared.aliases;
|
|
2269
|
+
generatedFiles = prepared.files;
|
|
2270
|
+
definitions = prepared.definitions;
|
|
2271
|
+
if (internalOptions?.providerImportAliases && internalOptions.providerImportSpecifier) {
|
|
2272
|
+
const facade = generatedAliases[SANDBOX_PACKAGE_ID];
|
|
2273
|
+
if (facade) {
|
|
2274
|
+
internalOptions.providerImportAliases[internalOptions.providerImportSpecifier] = facade;
|
|
2275
|
+
internalOptions.providerImportAliases[SANDBOX_PACKAGE_ID] = sandboxPackageRuntime();
|
|
2276
|
+
} else {
|
|
2277
|
+
delete internalOptions.providerImportAliases[internalOptions.providerImportSpecifier];
|
|
2278
|
+
delete internalOptions.providerImportAliases[SANDBOX_PACKAGE_ID];
|
|
2279
|
+
}
|
|
2280
|
+
for (const specifier of sandboxProviderLoaderSpecifiers) {
|
|
2281
|
+
const providerLoader = generatedAliases[specifier];
|
|
2282
|
+
if (providerLoader) internalOptions.providerImportAliases[specifier] = providerLoader;
|
|
2283
|
+
else delete internalOptions.providerImportAliases[specifier];
|
|
2284
|
+
}
|
|
409
2285
|
}
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
2286
|
+
return prepared;
|
|
2287
|
+
}
|
|
2288
|
+
async function composeCloudflareSandbox(config, prepared) {
|
|
2289
|
+
if (!prepared.cloudflare || !hasNitroVitePlugin(config) || getHostingProvider(prepared.hosting) !== "cloudflare") return false;
|
|
2290
|
+
config.nitro = await configureCloudflareSandboxNitro(config.nitro, typeof config.root === "string" ? config.root : process.cwd(), prepared.cloudflare);
|
|
2291
|
+
return true;
|
|
2292
|
+
}
|
|
414
2293
|
return {
|
|
415
|
-
|
|
2294
|
+
name: "@vite-hub/sandbox/vite",
|
|
2295
|
+
enforce: "pre",
|
|
2296
|
+
nitro: {
|
|
2297
|
+
name: "@vite-hub/sandbox/provider-runtime",
|
|
2298
|
+
setup: sandboxNitroModule
|
|
2299
|
+
},
|
|
416
2300
|
async config(config, env) {
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
2301
|
+
rawConfig = config;
|
|
2302
|
+
rawEnv = env;
|
|
2303
|
+
const prepared = await prepareCurrentSandboxRuntime(false);
|
|
2304
|
+
generatedAliases = prepared.aliases;
|
|
2305
|
+
generatedFiles = prepared.files;
|
|
2306
|
+
definitions = prepared.definitions;
|
|
2307
|
+
selectedProvider = prepared.provider;
|
|
2308
|
+
const nitro = config.nitro;
|
|
2309
|
+
if (nitro && typeof nitro === "object") {
|
|
2310
|
+
earlyNitroTarget = nitro;
|
|
2311
|
+
earlyNitroSnapshot = cloneConfigValue(earlyNitroTarget);
|
|
2312
|
+
}
|
|
2313
|
+
composedCloudflareEarly = await composeCloudflareSandbox(config, prepared);
|
|
2314
|
+
return { resolve: { alias: toSandboxAliasEntries({
|
|
2315
|
+
[SANDBOX_PROVIDER_LOADER_ID]: sandboxProviderLoaderFallback(),
|
|
2316
|
+
...withoutSandboxPackageAlias(generatedAliases)
|
|
2317
|
+
}) } };
|
|
2318
|
+
},
|
|
2319
|
+
resolveId(id) {
|
|
2320
|
+
if (!sandboxStateModule) return;
|
|
2321
|
+
if (id === SANDBOX_STATE_ID) return RESOLVED_SANDBOX_STATE_ID;
|
|
2322
|
+
if (id === RESOLVED_SANDBOX_STATE_ID) return id;
|
|
2323
|
+
},
|
|
2324
|
+
load(id) {
|
|
2325
|
+
if (id === SANDBOX_STATE_ID || id === RESOLVED_SANDBOX_STATE_ID) return sandboxStateModule;
|
|
2326
|
+
},
|
|
2327
|
+
async configResolved(config) {
|
|
2328
|
+
resolvedConfig = config;
|
|
2329
|
+
const prepared = await refreshSandboxRuntime();
|
|
2330
|
+
selectedProvider = prepared.provider;
|
|
2331
|
+
if (!await composeCloudflareSandbox(config, prepared) && composedCloudflareEarly && earlyNitroTarget && earlyNitroSnapshot) for (const key of ["cloudflare", "rollupConfig"]) if (key in earlyNitroSnapshot) earlyNitroTarget[key] = earlyNitroSnapshot[key];
|
|
2332
|
+
else delete earlyNitroTarget[key];
|
|
2333
|
+
},
|
|
2334
|
+
async handleHotUpdate(context) {
|
|
2335
|
+
if (!isSandboxDefinitionUpdate(context.file, definitions, generatedFiles, resolvedConfig?.root)) return;
|
|
2336
|
+
const previousFiles = [...generatedFiles, ...Object.values(generatedAliases)];
|
|
2337
|
+
const prepared = await refreshSandboxRuntime();
|
|
2338
|
+
selectedProvider = prepared.provider;
|
|
2339
|
+
if (resolvedConfig) await composeCloudflareSandbox(resolvedConfig, prepared);
|
|
2340
|
+
invalidateGeneratedSandboxModules([
|
|
2341
|
+
...previousFiles,
|
|
2342
|
+
...generatedFiles,
|
|
2343
|
+
...Object.values(generatedAliases)
|
|
2344
|
+
], context.server.moduleGraph);
|
|
425
2345
|
},
|
|
426
2346
|
configEnvironment(name, config) {
|
|
427
|
-
const result =
|
|
2347
|
+
const result = config.consumer === "server" ? { define: { __VITEHUB_ENVIRONMENT_SANDBOX__: JSON.stringify(name) } } : void 0;
|
|
428
2348
|
if (!isServerEnvironment(name, config)) return result;
|
|
429
2349
|
return {
|
|
430
2350
|
...result,
|
|
431
2351
|
resolve: {
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
2352
|
+
alias: toSandboxAliasEntries({
|
|
2353
|
+
[SANDBOX_PROVIDER_LOADER_ID]: sandboxProviderLoaderFallback(),
|
|
2354
|
+
...generatedAliases
|
|
2355
|
+
}),
|
|
2356
|
+
noExternal: mergeSandboxNoExternal(config.resolve?.noExternal)
|
|
435
2357
|
}
|
|
436
2358
|
};
|
|
437
2359
|
}
|
|
438
2360
|
};
|
|
439
2361
|
}
|
|
440
2362
|
//#endregion
|
|
441
|
-
export {
|
|
2363
|
+
export { hubSandbox };
|