@vite-hub/web-container 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +220 -2
- package/dist/connect.d.ts +55 -0
- package/dist/connect.js +97 -0
- package/dist/env.d.ts +10 -0
- package/dist/env.js +13 -0
- package/dist/error-diagnostics-DDPkdBo-.js +53 -0
- package/dist/index.d.ts +134 -0
- package/dist/index.js +435 -0
- package/dist/links-Dts2hWjR.js +78 -0
- package/dist/snapshot.d.ts +43 -0
- package/dist/snapshot.js +272 -0
- package/dist/vite.d.ts +21 -0
- package/dist/vite.js +45 -0
- package/dist/vue.d.ts +102 -0
- package/dist/vue.js +334 -0
- package/package.json +101 -3
package/dist/snapshot.js
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { t as webContainerErrorDiagnostics } from "./error-diagnostics-DDPkdBo-.js";
|
|
2
|
+
import { r as snapshotLinksFile, t as linkStaysInside } from "./links-Dts2hWjR.js";
|
|
3
|
+
import { defineDiagnostics } from "nostics";
|
|
4
|
+
import { execFile } from "node:child_process";
|
|
5
|
+
import { access, cp, lstat, readFile, readdir, readlink, rm, stat, writeFile } from "node:fs/promises";
|
|
6
|
+
import { join, relative, sep } from "node:path";
|
|
7
|
+
import { promisify } from "node:util";
|
|
8
|
+
import { gzipSync } from "node:zlib";
|
|
9
|
+
import { encode } from "@msgpack/msgpack";
|
|
10
|
+
//#region ../internal/src/invariant.ts
|
|
11
|
+
const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
12
|
+
docsBase: "https://vitehub.dev/docs/development/diagnostics",
|
|
13
|
+
codes: { INTERNAL_INVARIANT_FAILED: {
|
|
14
|
+
why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
|
|
15
|
+
fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
|
|
16
|
+
} }
|
|
17
|
+
});
|
|
18
|
+
/**
|
|
19
|
+
* The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
|
|
20
|
+
* Use a code from the package catalog when a developer can cause the error or fix it.
|
|
21
|
+
*/
|
|
22
|
+
function invariantError(what) {
|
|
23
|
+
return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
|
|
24
|
+
}
|
|
25
|
+
/** Throws `INTERNAL_INVARIANT_FAILED` when `condition` is falsy. */
|
|
26
|
+
function invariant(condition, what) {
|
|
27
|
+
if (!condition) throw invariantError(what);
|
|
28
|
+
}
|
|
29
|
+
//#endregion
|
|
30
|
+
//#region src/lockfile.ts
|
|
31
|
+
/** Dependencies named like this install a wasm build. They are aliases, so the lockfile pins them with the rest. */
|
|
32
|
+
const aliasPrefix = "vitehub-wasm-";
|
|
33
|
+
function aliasName(target, version) {
|
|
34
|
+
return `${aliasPrefix}${target.replace(/^@/, "").replace("/", "-")}-${version}`;
|
|
35
|
+
}
|
|
36
|
+
function withoutAliases(dependencies = {}) {
|
|
37
|
+
return Object.fromEntries(Object.entries(dependencies).filter(([name]) => !name.startsWith(aliasPrefix)));
|
|
38
|
+
}
|
|
39
|
+
/** The aliases that the root of a lockfile depends on: optional dependencies, or regular ones in an older lockfile. */
|
|
40
|
+
function lockedAliases(lockfile) {
|
|
41
|
+
const lock = JSON.parse(lockfile);
|
|
42
|
+
const root = isObject(lock) && isObject(lock.packages) && isObject(lock.packages[""]) ? lock.packages[""] : {};
|
|
43
|
+
const entries = [root.dependencies, root.optionalDependencies].flatMap((field) => isObject(field) ? Object.entries(field) : []);
|
|
44
|
+
return Object.fromEntries(entries.filter((entry) => entry[0].startsWith("vitehub-wasm-") && typeof entry[1] === "string"));
|
|
45
|
+
}
|
|
46
|
+
function isObject(value) {
|
|
47
|
+
return !!value && typeof value === "object";
|
|
48
|
+
}
|
|
49
|
+
function sameRecord(a, b) {
|
|
50
|
+
const keys = Object.keys(a);
|
|
51
|
+
return keys.length === Object.keys(b).length && keys.every((key) => a[key] === b[key]);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The tarballs of `file:` dependencies, such as packed workspace packages, change with each build. Their integrity in
|
|
55
|
+
* the lockfile would fail `npm ci` after a rebuild, so leave it out; registry packages keep theirs.
|
|
56
|
+
*/
|
|
57
|
+
function withoutTarballIntegrity(lockfile) {
|
|
58
|
+
const lock = JSON.parse(lockfile);
|
|
59
|
+
for (const entry of Object.values(lock.packages ?? {})) if (entry.resolved?.startsWith("file:")) delete entry.integrity;
|
|
60
|
+
return `${JSON.stringify(lock, null, 2)}\n`;
|
|
61
|
+
}
|
|
62
|
+
/** The `file:` paths that the lockfile installs, such as `tarballs/vite-hub-forge-0.1.0.tgz`, relative to the app. */
|
|
63
|
+
function lockedFiles(lockfile) {
|
|
64
|
+
const lock = JSON.parse(lockfile);
|
|
65
|
+
return (isObject(lock) && isObject(lock.packages) ? Object.values(lock.packages) : []).flatMap((entry) => isObject(entry) && typeof entry.resolved === "string" && entry.resolved.startsWith("file:") ? [entry.resolved.slice(5)] : []);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The lockfile without its `file:` packages. npm keeps the dependencies that a lockfile records for a tarball, so an
|
|
69
|
+
* update would still install a package that a packed workspace package no longer depends on. Without the entries, npm
|
|
70
|
+
* reads each tarball again and keeps the registry versions.
|
|
71
|
+
*/
|
|
72
|
+
function withoutFilePackages(lockfile) {
|
|
73
|
+
const lock = JSON.parse(lockfile);
|
|
74
|
+
const packages = lock.packages ?? {};
|
|
75
|
+
for (const [path, entry] of Object.entries(packages)) if (entry.resolved?.startsWith("file:")) delete packages[path];
|
|
76
|
+
return `${JSON.stringify(lock, null, 2)}\n`;
|
|
77
|
+
}
|
|
78
|
+
//#endregion
|
|
79
|
+
//#region src/tree.ts
|
|
80
|
+
/** Reads `dir` into a snapshot tree, one file at a time. Symlinks and executable files go into `links`, relative to `root`. Source maps are left out. */
|
|
81
|
+
async function readTree(root, dir, links) {
|
|
82
|
+
const tree = {};
|
|
83
|
+
for (const entry of (await readdir(dir)).sort()) {
|
|
84
|
+
const path = join(dir, entry);
|
|
85
|
+
const stats = await lstat(path);
|
|
86
|
+
if (stats.isSymbolicLink()) {
|
|
87
|
+
const link = relative(root, path).split(sep).join("/");
|
|
88
|
+
const target = await readlink(path);
|
|
89
|
+
if (await stat(path).then(() => true, () => false) && linkStaysInside(link, target.split(sep).join("/"))) links.links.push([link, target]);
|
|
90
|
+
} else if (stats.isDirectory()) tree[entry] = { d: await readTree(root, path, links) };
|
|
91
|
+
else if (stats.isFile() && !entry.endsWith(".map")) {
|
|
92
|
+
if (stats.mode & 73) links.executables.push(relative(root, path).split(sep).join("/"));
|
|
93
|
+
tree[entry] = { f: { c: await readFile(path) } };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return tree;
|
|
97
|
+
}
|
|
98
|
+
//#endregion
|
|
99
|
+
//#region src/snapshot.ts
|
|
100
|
+
const run = promisify(execFile);
|
|
101
|
+
const npmFlags = [
|
|
102
|
+
"--ignore-scripts",
|
|
103
|
+
"--no-audit",
|
|
104
|
+
"--no-fund",
|
|
105
|
+
"--no-progress"
|
|
106
|
+
];
|
|
107
|
+
/**
|
|
108
|
+
* Packages that npm in a WebContainer replaces with their wasm build of the same version.
|
|
109
|
+
* A probe of `npm install` in a WebContainer shows the swap: `node_modules/esbuild` holds `esbuild-wasm`.
|
|
110
|
+
*/
|
|
111
|
+
const wasmBuilds = {
|
|
112
|
+
"esbuild": "esbuild-wasm",
|
|
113
|
+
"lightningcss": "lightningcss-wasm",
|
|
114
|
+
"@libsql/client": "@libsql/client-wasm"
|
|
115
|
+
};
|
|
116
|
+
/** rolldown is not swapped. In a WebContainer it installs this binding into `/tmp` on first use, which takes seconds. */
|
|
117
|
+
const wasmBindings = { rolldown: "@rolldown/binding-wasm32-wasi" };
|
|
118
|
+
/**
|
|
119
|
+
* Installs the dependencies of an app on this machine as npm in a WebContainer does, and returns a snapshot that holds
|
|
120
|
+
* only `node_modules`. Mount it with `bootWebContainer({ snapshot })`, so the container skips `npm install`.
|
|
121
|
+
*
|
|
122
|
+
* Native binaries are left out: the install uses `--cpu=wasm32`, swaps packages for their wasm builds, and adds the
|
|
123
|
+
* wasm binding of rolldown. Install scripts do not run. Source maps are dropped.
|
|
124
|
+
* The snapshot cannot hold symlinks or executable bits, so it lists them, and `bootWebContainer` restores them.
|
|
125
|
+
* It is encoded with msgpack directly: @webcontainer/snapshot runs out of memory on large trees
|
|
126
|
+
* (https://github.com/stackblitz/webcontainer-core/issues/2187).
|
|
127
|
+
* Creation requires a POSIX host (Linux, macOS, or WSL); Windows npm shims cannot be restored as POSIX bin links.
|
|
128
|
+
*/
|
|
129
|
+
async function createNodeModulesSnapshot(options) {
|
|
130
|
+
if (process.platform === "win32") throw webContainerErrorDiagnostics.WEB_CONTAINER_SNAPSHOT_POSIX_REQUIRED();
|
|
131
|
+
const { dir } = options;
|
|
132
|
+
const modules = join(dir, "node_modules");
|
|
133
|
+
const manifestPath = join(dir, "package.json");
|
|
134
|
+
const lockPath = join(dir, "package-lock.json");
|
|
135
|
+
const originalManifest = await readFile(manifestPath);
|
|
136
|
+
const manifest = JSON.parse(originalManifest.toString("utf8"));
|
|
137
|
+
const frozen = options.lockfile !== void 0 && options.frozenLockfile !== false;
|
|
138
|
+
let aliases = options.lockfile === void 0 ? {} : lockedAliases(options.lockfile);
|
|
139
|
+
if (frozen && options.lockfile !== void 0) {
|
|
140
|
+
for (const file of lockedFiles(options.lockfile)) if (!await access(join(dir, file)).then(() => true, () => false)) throw webContainerErrorDiagnostics.WEB_CONTAINER_SNAPSHOT_LOCKFILE_MISMATCH({
|
|
141
|
+
file,
|
|
142
|
+
wasm: false
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
try {
|
|
146
|
+
if (options.lockfile !== void 0) await writeFile(lockPath, frozen ? options.lockfile : withoutFilePackages(options.lockfile));
|
|
147
|
+
else await rm(lockPath, { force: true });
|
|
148
|
+
for (let round = 0;; round++) {
|
|
149
|
+
await writeFile(manifestPath, `${JSON.stringify({
|
|
150
|
+
...manifest,
|
|
151
|
+
dependencies: withoutAliases(manifest.dependencies),
|
|
152
|
+
optionalDependencies: {
|
|
153
|
+
...withoutAliases(manifest.optionalDependencies),
|
|
154
|
+
...aliases
|
|
155
|
+
}
|
|
156
|
+
}, null, 2)}\n`);
|
|
157
|
+
await rm(modules, {
|
|
158
|
+
recursive: true,
|
|
159
|
+
force: true
|
|
160
|
+
});
|
|
161
|
+
try {
|
|
162
|
+
await run("npm", [
|
|
163
|
+
frozen ? "ci" : "install",
|
|
164
|
+
"--cpu=wasm32",
|
|
165
|
+
"--include=optional",
|
|
166
|
+
...options.dev ? [] : ["--omit=dev"],
|
|
167
|
+
...npmFlags
|
|
168
|
+
], {
|
|
169
|
+
cwd: dir,
|
|
170
|
+
maxBuffer: 64 * 2 ** 20
|
|
171
|
+
});
|
|
172
|
+
} catch (error) {
|
|
173
|
+
if (frozen && error instanceof Error && "stderr" in error && typeof error.stderr === "string" && error.stderr.includes("code EUSAGE") && error.stderr.includes("`npm ci` can only install packages when your package.json and package-lock.json or npm-shrinkwrap.json are in sync.")) throw webContainerErrorDiagnostics.WEB_CONTAINER_SNAPSHOT_LOCKFILE_MISMATCH({
|
|
174
|
+
cause: error,
|
|
175
|
+
wasm: false
|
|
176
|
+
});
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
const needed = await neededAliases(modules);
|
|
180
|
+
if (sameRecord(needed, aliases)) break;
|
|
181
|
+
if (frozen) throw webContainerErrorDiagnostics.WEB_CONTAINER_SNAPSHOT_LOCKFILE_MISMATCH({ wasm: true });
|
|
182
|
+
invariant(round <= 1, "the second install pins every wasm alias, so the wasm builds settle on one set of versions");
|
|
183
|
+
aliases = needed;
|
|
184
|
+
}
|
|
185
|
+
for (const { name, path } of await packageDirs(modules)) {
|
|
186
|
+
const wasm = wasmBuilds[name];
|
|
187
|
+
const target = wasm ?? wasmBindings[name];
|
|
188
|
+
if (!target) continue;
|
|
189
|
+
const alias = join(modules, aliasName(target, await packageVersion(path)));
|
|
190
|
+
const destination = wasm ? path : join(path, "node_modules", target);
|
|
191
|
+
if (wasm) await rm(path, {
|
|
192
|
+
recursive: true,
|
|
193
|
+
force: true
|
|
194
|
+
});
|
|
195
|
+
await cp(alias, destination, {
|
|
196
|
+
recursive: true,
|
|
197
|
+
verbatimSymlinks: true
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
for (const alias of Object.keys(aliases)) await rm(join(modules, alias), {
|
|
201
|
+
recursive: true,
|
|
202
|
+
force: true
|
|
203
|
+
});
|
|
204
|
+
const links = {
|
|
205
|
+
links: [],
|
|
206
|
+
executables: []
|
|
207
|
+
};
|
|
208
|
+
const tree = await readTree(dir, modules, links);
|
|
209
|
+
tree[snapshotLinksFile] = { f: { c: new TextEncoder().encode(JSON.stringify(links)) } };
|
|
210
|
+
return {
|
|
211
|
+
snapshot: encode({ d: { node_modules: { d: tree } } }),
|
|
212
|
+
lockfile: withoutTarballIntegrity(await readFile(lockPath, "utf8"))
|
|
213
|
+
};
|
|
214
|
+
} finally {
|
|
215
|
+
await writeFile(manifestPath, originalManifest);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
/** An alias for each wasm build or binding that the installed packages need, such as `npm:esbuild-wasm@0.28.2`. */
|
|
219
|
+
async function neededAliases(modules) {
|
|
220
|
+
const needed = {};
|
|
221
|
+
for (const { name, path } of await packageDirs(modules)) {
|
|
222
|
+
const target = wasmBuilds[name] ?? wasmBindings[name];
|
|
223
|
+
if (!target) continue;
|
|
224
|
+
const version = await packageVersion(path);
|
|
225
|
+
needed[aliasName(target, version)] = `npm:${target}@${version}`;
|
|
226
|
+
}
|
|
227
|
+
return needed;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Compresses a snapshot with gzip and splits it into parts of at most `partBytes`, for hosts that limit the size of a
|
|
231
|
+
* static file, such as the 25 MiB of Cloudflare Workers assets. `fetchSnapshot` joins the parts again.
|
|
232
|
+
*/
|
|
233
|
+
function packSnapshot(data, options = {}) {
|
|
234
|
+
const partBytes = options.partBytes ?? 20 * 2 ** 20;
|
|
235
|
+
if (!Number.isSafeInteger(partBytes) || partBytes <= 0) throw webContainerErrorDiagnostics.WEB_CONTAINER_SNAPSHOT_PART_BYTES_INVALID();
|
|
236
|
+
const compressed = gzipSync(data, { level: 9 });
|
|
237
|
+
const parts = [];
|
|
238
|
+
for (let offset = 0; offset < compressed.byteLength; offset += partBytes) parts.push(compressed.subarray(offset, offset + partBytes));
|
|
239
|
+
return parts;
|
|
240
|
+
}
|
|
241
|
+
async function packageVersion(path) {
|
|
242
|
+
const manifest = JSON.parse(await readFile(join(path, "package.json"), "utf8"));
|
|
243
|
+
const version = manifest && typeof manifest === "object" && "version" in manifest ? manifest.version : void 0;
|
|
244
|
+
invariant(typeof version === "string", `npm writes a version into every installed package.json, but ${path}/package.json has none`);
|
|
245
|
+
return version;
|
|
246
|
+
}
|
|
247
|
+
/** Every package folder below `modules`, with its name. `nested` also walks the node_modules of each package. */
|
|
248
|
+
async function packageDirs(modules, nested = true) {
|
|
249
|
+
const found = [];
|
|
250
|
+
const entries = await readdir(modules, { withFileTypes: true }).catch((error) => {
|
|
251
|
+
if (error.code === "ENOENT") return [];
|
|
252
|
+
throw error;
|
|
253
|
+
});
|
|
254
|
+
for (const entry of entries) {
|
|
255
|
+
if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
|
|
256
|
+
const path = join(modules, entry.name);
|
|
257
|
+
const packages = entry.name.startsWith("@") ? (await readdir(path, { withFileTypes: true })).filter((scoped) => scoped.isDirectory()).map((scoped) => ({
|
|
258
|
+
name: `${entry.name}/${scoped.name}`,
|
|
259
|
+
path: join(path, scoped.name)
|
|
260
|
+
})) : [{
|
|
261
|
+
name: entry.name,
|
|
262
|
+
path
|
|
263
|
+
}];
|
|
264
|
+
for (const item of packages) {
|
|
265
|
+
found.push(item);
|
|
266
|
+
if (nested) found.push(...await packageDirs(join(item.path, "node_modules")));
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return found;
|
|
270
|
+
}
|
|
271
|
+
//#endregion
|
|
272
|
+
export { createNodeModulesSnapshot, packSnapshot };
|
package/dist/vite.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Plugin } from "vite";
|
|
2
|
+
//#region src/vite.d.ts
|
|
3
|
+
/** The headers that make a page cross-origin isolated, which a WebContainer needs. */
|
|
4
|
+
export declare const webContainerHeaders: Readonly<Record<string, string>>;
|
|
5
|
+
export interface WebContainerVitePluginOptions {
|
|
6
|
+
/**
|
|
7
|
+
* Pages that boot a WebContainer. `/playground` matches that path only. `/playground/**` matches it and every path below it.
|
|
8
|
+
* Other pages keep their headers, so cross-origin embeds there keep working.
|
|
9
|
+
*/
|
|
10
|
+
routes: readonly string[];
|
|
11
|
+
}
|
|
12
|
+
/** Returns true when `pathname` matches one of the route patterns. */
|
|
13
|
+
export declare function matchesWebContainerRoute(pathname: string, routes: readonly string[]): boolean;
|
|
14
|
+
/**
|
|
15
|
+
* Sets the cross-origin isolation headers on the configured routes in `vite dev` and `vite preview`.
|
|
16
|
+
*
|
|
17
|
+
* In production, set the same headers with Nitro route rules:
|
|
18
|
+
* `routeRules: { "/playground/**": { headers: webContainerHeaders } }`.
|
|
19
|
+
*/
|
|
20
|
+
export declare function hubWebContainer(options: WebContainerVitePluginOptions): Plugin;
|
|
21
|
+
//#endregion
|
package/dist/vite.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { t as webContainerErrorDiagnostics } from "./error-diagnostics-DDPkdBo-.js";
|
|
2
|
+
//#region src/vite.ts
|
|
3
|
+
/** The headers that make a page cross-origin isolated, which a WebContainer needs. */
|
|
4
|
+
const webContainerHeaders = Object.freeze({
|
|
5
|
+
"Cross-Origin-Embedder-Policy": "credentialless",
|
|
6
|
+
"Cross-Origin-Opener-Policy": "same-origin"
|
|
7
|
+
});
|
|
8
|
+
/** Returns true when `pathname` matches one of the route patterns. */
|
|
9
|
+
function matchesWebContainerRoute(pathname, routes) {
|
|
10
|
+
const path = pathname.length > 1 ? pathname.replace(/\/+$/, "") : pathname;
|
|
11
|
+
return routes.some((route) => {
|
|
12
|
+
if (route.endsWith("/**")) {
|
|
13
|
+
const base = route.slice(0, -3) || "/";
|
|
14
|
+
return base === "/" || path === base || path.startsWith(`${base}/`);
|
|
15
|
+
}
|
|
16
|
+
return path === (route.length > 1 ? route.replace(/\/+$/, "") : route);
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Sets the cross-origin isolation headers on the configured routes in `vite dev` and `vite preview`.
|
|
21
|
+
*
|
|
22
|
+
* In production, set the same headers with Nitro route rules:
|
|
23
|
+
* `routeRules: { "/playground/**": { headers: webContainerHeaders } }`.
|
|
24
|
+
*/
|
|
25
|
+
function hubWebContainer(options) {
|
|
26
|
+
const routes = [...options.routes];
|
|
27
|
+
if (!routes.length) throw webContainerErrorDiagnostics.WEB_CONTAINER_ROUTES_MISSING();
|
|
28
|
+
for (const route of routes) if (!route.startsWith("/")) throw webContainerErrorDiagnostics.WEB_CONTAINER_ROUTE_INVALID({ route });
|
|
29
|
+
function setHeaders(request, response, next) {
|
|
30
|
+
const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
|
|
31
|
+
if (matchesWebContainerRoute(pathname, routes)) for (const [name, value] of Object.entries(webContainerHeaders)) response.setHeader(name, value);
|
|
32
|
+
next();
|
|
33
|
+
}
|
|
34
|
+
return {
|
|
35
|
+
name: "@vite-hub/web-container/vite",
|
|
36
|
+
configureServer(server) {
|
|
37
|
+
server.middlewares.use(setHeaders);
|
|
38
|
+
},
|
|
39
|
+
configurePreviewServer(server) {
|
|
40
|
+
server.middlewares.use(setHeaders);
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
//#endregion
|
|
45
|
+
export { hubWebContainer, matchesWebContainerRoute, webContainerHeaders };
|
package/dist/vue.d.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { FileSystemAPI, ViteHubWebContainer, WebContainerCommand, WebContainerStage, WebContainerStep, WebContainerSupport } from "./index.js";
|
|
2
|
+
import { ComputedRef, MaybeRefOrGetter, Ref, ShallowRef } from "vue";
|
|
3
|
+
//#region src/vue.d.ts
|
|
4
|
+
/** Text files of the app, keyed by a relative path such as `server/routes/index.ts`. */
|
|
5
|
+
export type WebContainerFiles = Record<string, string>;
|
|
6
|
+
/** Output chunks in order. `offset` is the number of characters evicted from the start of the stream. */
|
|
7
|
+
export type WebContainerLogs = readonly string[] & {
|
|
8
|
+
readonly offset?: number;
|
|
9
|
+
};
|
|
10
|
+
/** `idle` comes before the first `boot()`. The other stages come from `@vite-hub/web-container`. */
|
|
11
|
+
export type UseWebContainerStatus = "idle" | WebContainerStage;
|
|
12
|
+
/** Why the workspace stopped. The UI picks its copy and its recovery action from `kind`. */
|
|
13
|
+
export type WebContainerFailure = {
|
|
14
|
+
kind: "unsupported";
|
|
15
|
+
error: Error;
|
|
16
|
+
} | {
|
|
17
|
+
kind: "boot";
|
|
18
|
+
error: Error;
|
|
19
|
+
} | {
|
|
20
|
+
kind: "install";
|
|
21
|
+
error: Error;
|
|
22
|
+
exitCode?: number;
|
|
23
|
+
} | {
|
|
24
|
+
kind: "server";
|
|
25
|
+
error: Error;
|
|
26
|
+
exitCode?: number;
|
|
27
|
+
};
|
|
28
|
+
export interface UseWebContainerOptions {
|
|
29
|
+
/** The files to mount. `reset()` goes back to them. */
|
|
30
|
+
files: WebContainerFiles;
|
|
31
|
+
/**
|
|
32
|
+
* A snapshot from `container.export()` or `fetchSnapshot()`, mounted before `files`. Use it to skip a cold install.
|
|
33
|
+
* A function runs on each boot, while the WebContainer boots, so a page downloads the snapshot only when it boots.
|
|
34
|
+
*/
|
|
35
|
+
snapshot?: Uint8Array | ArrayBuffer | (() => Promise<Uint8Array | ArrayBuffer>);
|
|
36
|
+
/**
|
|
37
|
+
* The install command. `false` skips the install, for example when the snapshot has `node_modules`.
|
|
38
|
+
* @default "install"
|
|
39
|
+
*/
|
|
40
|
+
install?: WebContainerCommand | false;
|
|
41
|
+
/**
|
|
42
|
+
* The command that starts the dev server. `false` boots and installs only.
|
|
43
|
+
* @default "dev"
|
|
44
|
+
*/
|
|
45
|
+
start?: WebContainerCommand | false;
|
|
46
|
+
/**
|
|
47
|
+
* The port that the dev server listens on, such as `3000` for `vite --port 3000`. The dev server gets it as `PORT`.
|
|
48
|
+
* Only the server on this port, or on `env.PORT`, becomes the preview. Other servers, such as Nitro workers, do not.
|
|
49
|
+
* @default 3000
|
|
50
|
+
*/
|
|
51
|
+
port?: number;
|
|
52
|
+
/** JavaScript that runs first in every HTML page of the preview. See `bootWebContainer({ previewScript })`. */
|
|
53
|
+
previewScript?: string;
|
|
54
|
+
/** Environment variables for the install and start processes, such as `connectEnv(connect, credentials)`. Read again on each run. */
|
|
55
|
+
env?: MaybeRefOrGetter<Record<string, string> | undefined>;
|
|
56
|
+
/**
|
|
57
|
+
* Boot when the calling component mounts. Set `false` to boot on a click with `boot()`.
|
|
58
|
+
* @default true
|
|
59
|
+
*/
|
|
60
|
+
immediate?: boolean;
|
|
61
|
+
}
|
|
62
|
+
export interface SetFilesOptions {
|
|
63
|
+
/** `merge` writes the given files and keeps the others. `replace` also removes files that are not given. */
|
|
64
|
+
mode?: "merge" | "replace";
|
|
65
|
+
}
|
|
66
|
+
export interface UseWebContainerReturn {
|
|
67
|
+
status: Readonly<Ref<UseWebContainerStatus>>;
|
|
68
|
+
/** Every stage so far, with its timing. */
|
|
69
|
+
steps: Readonly<ShallowRef<readonly WebContainerStep[]>>;
|
|
70
|
+
/** Set after the first support check, on the client only. */
|
|
71
|
+
support: Readonly<ShallowRef<WebContainerSupport | undefined>>;
|
|
72
|
+
failure: Readonly<ShallowRef<WebContainerFailure | undefined>>;
|
|
73
|
+
error: ComputedRef<Error | undefined>;
|
|
74
|
+
/** The current files, including edits. */
|
|
75
|
+
files: Readonly<ShallowRef<Readonly<WebContainerFiles>>>;
|
|
76
|
+
/** Paths whose contents differ from `options.files`, sorted. */
|
|
77
|
+
modified: ComputedRef<readonly string[]>;
|
|
78
|
+
/** The WebContainer file system, after mount. */
|
|
79
|
+
fs: Readonly<ShallowRef<FileSystemAPI | undefined>>;
|
|
80
|
+
container: Readonly<ShallowRef<ViteHubWebContainer | undefined>>;
|
|
81
|
+
previewUrl: Readonly<Ref<string | undefined>>;
|
|
82
|
+
/** Recent output in order, limited to 65,536 characters and 1,000 chunks. The array is replaced when new output comes. */
|
|
83
|
+
logs: Readonly<ShallowRef<WebContainerLogs>>;
|
|
84
|
+
/** `navigator.onLine`. An offline reader keeps their edits, but install needs a connection. */
|
|
85
|
+
online: Readonly<Ref<boolean>>;
|
|
86
|
+
boot: () => Promise<void>;
|
|
87
|
+
/** Runs the install again, then starts the dev server. */
|
|
88
|
+
install: () => Promise<void>;
|
|
89
|
+
/** Stops the dev server, if it runs, and starts it again. */
|
|
90
|
+
restart: () => Promise<void>;
|
|
91
|
+
/** Writes the files to the container. Rejects when a write fails. The logs show the error too. */
|
|
92
|
+
setFiles: (files: WebContainerFiles, options?: SetFilesOptions) => Promise<void>;
|
|
93
|
+
/** Puts back the original files. Rejects when a write fails. */
|
|
94
|
+
reset: () => Promise<void>;
|
|
95
|
+
teardown: () => void;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Runs an app in a WebContainer and keeps its state in Vue refs, for the workspace components of `@vite-hub/ui/workspace`
|
|
99
|
+
* or your own. Only one WebContainer runs per page.
|
|
100
|
+
*/
|
|
101
|
+
export declare function useWebContainer(options: UseWebContainerOptions): UseWebContainerReturn;
|
|
102
|
+
//#endregion
|