@seanhogg/builderforce-webcontainers 2026.10.7 → 2026.10.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets.js +3 -3
- package/dist/cdnModules.d.ts +16 -0
- package/dist/cdnModules.d.ts.map +1 -0
- package/dist/cdnModules.js +25 -0
- package/dist/cdnModules.js.map +1 -0
- package/dist/componentCompilers.d.ts +5 -5
- package/dist/componentCompilers.d.ts.map +1 -1
- package/dist/componentCompilers.js +5 -23
- package/dist/componentCompilers.js.map +1 -1
- package/dist/host.d.ts +17 -3
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js +36 -22
- package/dist/host.js.map +1 -1
- package/dist/index.d.ts +9 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/node/childRelay.d.ts +22 -0
- package/dist/node/childRelay.d.ts.map +1 -0
- package/dist/node/childRelay.js +54 -0
- package/dist/node/childRelay.js.map +1 -0
- package/dist/node/index.d.ts +4 -8
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -25
- package/dist/node/index.js.map +1 -1
- package/dist/node/portResponder.d.ts +45 -0
- package/dist/node/portResponder.d.ts.map +1 -0
- package/dist/node/portResponder.js +136 -0
- package/dist/node/portResponder.js.map +1 -0
- package/dist/node/processHost.d.ts +13 -2
- package/dist/node/processHost.d.ts.map +1 -1
- package/dist/node/processHost.js +79 -47
- package/dist/node/processHost.js.map +1 -1
- package/dist/node/protocol.d.ts +69 -13
- package/dist/node/protocol.d.ts.map +1 -1
- package/dist/node/protocol.js.map +1 -1
- package/dist/node/responseWire.d.ts +27 -0
- package/dist/node/responseWire.d.ts.map +1 -0
- package/dist/node/responseWire.js +99 -0
- package/dist/node/responseWire.js.map +1 -0
- package/dist/node/worker.js +145 -126
- package/dist/node/workerProcess.d.ts +3 -1
- package/dist/node/workerProcess.d.ts.map +1 -1
- package/dist/node/workerProcess.js +79 -22
- package/dist/node/workerProcess.js.map +1 -1
- package/dist/previewBridge.d.ts +37 -0
- package/dist/previewBridge.d.ts.map +1 -0
- package/dist/previewBridge.js +116 -0
- package/dist/previewBridge.js.map +1 -0
- package/dist/previewMessages.d.ts +5 -0
- package/dist/previewMessages.d.ts.map +1 -1
- package/dist/previewMessages.js +18 -11
- package/dist/previewMessages.js.map +1 -1
- package/dist/previewUpdates.d.ts +10 -0
- package/dist/previewUpdates.d.ts.map +1 -0
- package/dist/previewUpdates.js +27 -0
- package/dist/previewUpdates.js.map +1 -0
- package/dist/process-worker.js +145 -126
- package/dist/protocol.d.ts +25 -3
- package/dist/protocol.d.ts.map +1 -1
- package/dist/protocol.js +10 -2
- package/dist/protocol.js.map +1 -1
- package/dist/relay.html +1 -1
- package/dist/snapshotStore.d.ts +30 -0
- package/dist/snapshotStore.d.ts.map +1 -0
- package/dist/snapshotStore.js +115 -0
- package/dist/snapshotStore.js.map +1 -0
- package/dist/styleCompilers.d.ts +19 -0
- package/dist/styleCompilers.d.ts.map +1 -0
- package/dist/styleCompilers.js +22 -0
- package/dist/styleCompilers.js.map +1 -0
- package/dist/sw.js +1 -1
- package/dist/swRouter.d.ts +8 -1
- package/dist/swRouter.d.ts.map +1 -1
- package/dist/swRouter.js +40 -5
- package/dist/swRouter.js.map +1 -1
- package/dist/transport.d.ts +3 -2
- package/dist/transport.d.ts.map +1 -1
- package/dist/transport.js +4 -4
- package/dist/transport.js.map +1 -1
- package/dist/worker.d.ts +6 -2
- package/dist/worker.d.ts.map +1 -1
- package/dist/worker.js +5 -5
- package/dist/worker.js.map +1 -1
- package/package.json +3 -2
- package/src/cdnModules.ts +34 -0
- package/src/componentCompilers.ts +8 -32
- package/src/host.ts +51 -25
- package/src/index.ts +9 -2
- package/src/node/childRelay.ts +63 -0
- package/src/node/index.ts +4 -23
- package/src/node/portResponder.ts +175 -0
- package/src/node/processHost.ts +96 -46
- package/src/node/protocol.ts +46 -9
- package/src/node/responseWire.ts +97 -0
- package/src/node/workerProcess.ts +88 -28
- package/src/previewBridge.ts +148 -0
- package/src/previewMessages.ts +17 -9
- package/src/previewUpdates.ts +28 -0
- package/src/protocol.ts +37 -3
- package/src/relay.ts +6 -5
- package/src/snapshotStore.ts +135 -0
- package/src/styleCompilers.ts +45 -0
- package/src/sw.ts +2 -0
- package/src/swRouter.ts +35 -6
- package/src/transport.ts +7 -6
- package/src/worker.ts +5 -5
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seanhogg/builderforce-webcontainers",
|
|
3
|
-
"version": "2026.10.
|
|
3
|
+
"version": "2026.10.9",
|
|
4
4
|
"description": "BuilderForce WebContainers — browser runtime. Boots an in-browser dev server for a project held in memory and serves it to an iframe through a service worker. Open source, no COOP/COEP, no session caps.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.js",
|
|
@@ -65,11 +65,12 @@
|
|
|
65
65
|
},
|
|
66
66
|
"dependencies": {
|
|
67
67
|
"esbuild-wasm": "^0.24.0",
|
|
68
|
-
"@seanhogg/builderforce-webcontainers-core": "^2026.10.
|
|
68
|
+
"@seanhogg/builderforce-webcontainers-core": "^2026.10.9"
|
|
69
69
|
},
|
|
70
70
|
"devDependencies": {
|
|
71
71
|
"@vue/compiler-sfc": "^3.5.0",
|
|
72
72
|
"esbuild": "^0.24.0",
|
|
73
|
+
"fake-indexeddb": "^6.0.0",
|
|
73
74
|
"svelte": "^5.0.0",
|
|
74
75
|
"typescript": "^5.5.0",
|
|
75
76
|
"vitest": "^2.1.0"
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { isRegistryRange } from '@seanhogg/builderforce-webcontainers-core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Loading a compiler (Vue, Svelte, Sass, Less) from a CDN the first time a
|
|
5
|
+
* project needs it — nothing is downloaded for a project that doesn't — pinned
|
|
6
|
+
* to the project's own range, so compiler and runtime agree.
|
|
7
|
+
*/
|
|
8
|
+
export type ImportModule = (url: string) => Promise<unknown>;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* `import()` of a runtime URL. The magic comments stop the host app's bundler
|
|
12
|
+
* (webpack, Vite) from trying to resolve the CDN URL at build time.
|
|
13
|
+
*/
|
|
14
|
+
export const nativeImport: ImportModule = (url) => import(/* webpackIgnore: true */ /* @vite-ignore */ url);
|
|
15
|
+
|
|
16
|
+
/** The project's range for `name` when the CDN can fetch it, else `fallback`. */
|
|
17
|
+
export function rangeOf(dependencies: Readonly<Record<string, string>>, name: string, fallback: string): string {
|
|
18
|
+
const range = dependencies[name];
|
|
19
|
+
return range && isRegistryRange(range) ? range : fallback;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** One load per URL; a failed download is forgotten so the next request retries. */
|
|
23
|
+
export function memoizedLoader<T>(load: ImportModule): (url: string, make: (module: unknown) => T) => Promise<T> {
|
|
24
|
+
const cache = new Map<string, Promise<T>>();
|
|
25
|
+
return (url, make) => {
|
|
26
|
+
let hit = cache.get(url);
|
|
27
|
+
if (!hit) {
|
|
28
|
+
hit = load(url).then(make);
|
|
29
|
+
hit.catch(() => cache.delete(url));
|
|
30
|
+
cache.set(url, hit);
|
|
31
|
+
}
|
|
32
|
+
return hit;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
@@ -1,19 +1,18 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createSvelteCompiler,
|
|
3
3
|
createVueCompiler,
|
|
4
|
-
isRegistryRange,
|
|
5
4
|
type ComponentCompiler,
|
|
6
5
|
type ComponentCompilers,
|
|
7
6
|
type SvelteCompilerLike,
|
|
8
7
|
type VueCompilerSfcLike,
|
|
9
8
|
} from '@seanhogg/builderforce-webcontainers-core';
|
|
9
|
+
import { memoizedLoader, nativeImport, rangeOf, type ImportModule } from './cdnModules.js';
|
|
10
10
|
|
|
11
11
|
/**
|
|
12
12
|
* The Vue and Svelte compilers, fetched from a CDN the first time a project
|
|
13
|
-
* needs one
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
* the runtime is served by esm.sh from the same range, so the compiler is too.)
|
|
13
|
+
* needs one, pinned to the project's own framework range. (Svelte's compiled
|
|
14
|
+
* output calls internal runtime functions that change between minors; the
|
|
15
|
+
* runtime is served by esm.sh from the same range, so the compiler is too.)
|
|
17
16
|
*/
|
|
18
17
|
export interface CdnComponentCompilerOptions {
|
|
19
18
|
/** The ES module URL of `@vue/compiler-sfc`'s browser build for a `vue` range. */
|
|
@@ -21,7 +20,7 @@ export interface CdnComponentCompilerOptions {
|
|
|
21
20
|
/** The ES module URL of `svelte/compiler` for a `svelte` range. */
|
|
22
21
|
svelteCompilerUrl?: (range: string) => string;
|
|
23
22
|
/** Loads a module by URL. Default: native `import()`. */
|
|
24
|
-
importModule?:
|
|
23
|
+
importModule?: ImportModule;
|
|
25
24
|
}
|
|
26
25
|
|
|
27
26
|
/** Self-contained ESM build the official Vue SFC playground loads. */
|
|
@@ -30,37 +29,14 @@ export const defaultVueCompilerUrl = (range: string) =>
|
|
|
30
29
|
|
|
31
30
|
export const defaultSvelteCompilerUrl = (range: string) => `https://esm.sh/svelte@${range}/compiler`;
|
|
32
31
|
|
|
33
|
-
/**
|
|
34
|
-
* `import()` of a runtime URL. The magic comments stop the host app's bundler
|
|
35
|
-
* (webpack, Vite) from trying to resolve the CDN URL at build time.
|
|
36
|
-
*/
|
|
37
|
-
const nativeImport = (url: string): Promise<unknown> => import(/* webpackIgnore: true */ /* @vite-ignore */ url);
|
|
38
|
-
|
|
39
|
-
function rangeOf(dependencies: Readonly<Record<string, string>>, name: string, fallback: string): string {
|
|
40
|
-
const range = dependencies[name];
|
|
41
|
-
return range && isRegistryRange(range) ? range : fallback;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
32
|
export function createCdnComponentCompilers(options: CdnComponentCompilerOptions = {}): ComponentCompilers {
|
|
45
|
-
const load = options.importModule ?? nativeImport;
|
|
46
|
-
const cache = new Map<string, Promise<ComponentCompiler>>();
|
|
47
|
-
|
|
48
|
-
const memo = (url: string, make: (module: unknown) => ComponentCompiler): Promise<ComponentCompiler> => {
|
|
49
|
-
let hit = cache.get(url);
|
|
50
|
-
if (!hit) {
|
|
51
|
-
hit = load(url).then(make);
|
|
52
|
-
hit.catch(() => cache.delete(url)); // a failed download may be retried
|
|
53
|
-
cache.set(url, hit);
|
|
54
|
-
}
|
|
55
|
-
return hit;
|
|
56
|
-
};
|
|
57
|
-
|
|
33
|
+
const load = memoizedLoader<ComponentCompiler>(options.importModule ?? nativeImport);
|
|
58
34
|
return (extension, dependencies) => {
|
|
59
35
|
if (extension === '.vue') {
|
|
60
36
|
const url = (options.vueCompilerUrl ?? defaultVueCompilerUrl)(rangeOf(dependencies, 'vue', '3'));
|
|
61
|
-
return
|
|
37
|
+
return load(url, (module) => createVueCompiler(module as VueCompilerSfcLike));
|
|
62
38
|
}
|
|
63
39
|
const url = (options.svelteCompilerUrl ?? defaultSvelteCompilerUrl)(rangeOf(dependencies, 'svelte', '5'));
|
|
64
|
-
return
|
|
40
|
+
return load(url, (module) => createSvelteCompiler(module as SvelteCompilerLike));
|
|
65
41
|
};
|
|
66
42
|
}
|
package/src/host.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
DevServer,
|
|
3
|
+
PortCookieJars,
|
|
3
4
|
VirtualFileSystem,
|
|
4
5
|
buildProject,
|
|
5
6
|
exportZip,
|
|
@@ -14,15 +15,19 @@ import {
|
|
|
14
15
|
type ProjectProfile,
|
|
15
16
|
type RuntimeProcess,
|
|
16
17
|
type ServerAddress,
|
|
18
|
+
type StyleCompilers,
|
|
17
19
|
type Transformer,
|
|
18
20
|
type ZipExportOptions,
|
|
19
21
|
} from '@seanhogg/builderforce-webcontainers-core';
|
|
20
|
-
import { PREVIEW_ID, isPortPath, isWireRequest, previewBase, type
|
|
21
|
-
import {
|
|
22
|
+
import { PREVIEW_ID, isPortPath, isWireCancel, isWireRequest, previewBase, type WireReply, type WireResponse } from './protocol.js';
|
|
23
|
+
import { createPortResponder, createProcessHost, type NodeRuntimeOptions, type ProcessInfo } from './node/index.js';
|
|
22
24
|
import { listenToPreview, type PreviewConsoleMessage, type PreviewError } from './previewMessages.js';
|
|
25
|
+
import { listenToPreviewBridge } from './previewBridge.js';
|
|
23
26
|
import { relayTransport, sameOriginTransport } from './transport.js';
|
|
24
27
|
import { createEsbuildWasmBundler, createEsbuildWasmTransformer } from './esbuildWasm.js';
|
|
25
28
|
import { createCdnComponentCompilers } from './componentCompilers.js';
|
|
29
|
+
import { createCdnStyleCompilers } from './styleCompilers.js';
|
|
30
|
+
import { watchForPreviewUpdates } from './previewUpdates.js';
|
|
26
31
|
|
|
27
32
|
/** Serve previews on THIS page's origin. Only for code the page's own user trusts. */
|
|
28
33
|
export interface SameOriginOptions {
|
|
@@ -54,23 +59,28 @@ export interface CommonRuntimeOptions {
|
|
|
54
59
|
cdn?: PackageCdnFactory;
|
|
55
60
|
/** `.vue` / `.svelte` compilers. Default: the official ones, fetched from a CDN on first use. */
|
|
56
61
|
components?: ComponentCompilers;
|
|
62
|
+
/** Sass / Less compilers. Default: the official pure-JS builds, fetched from a CDN on first use. */
|
|
63
|
+
styles?: StyleCompilers;
|
|
57
64
|
/** Bundler for `build()`. Default: esbuild-wasm (the same instance as the compiler). */
|
|
58
65
|
bundler?: Bundler;
|
|
59
66
|
/** Stable id (e.g. the project id; `[A-Za-z0-9_-]`) — keeps the preview URL stable across reloads. */
|
|
60
67
|
id?: string;
|
|
61
68
|
/** The "Built with Builderforce.ai" badge in the preview. Default true — please keep it. */
|
|
62
69
|
attribution?: boolean;
|
|
63
|
-
/**
|
|
70
|
+
/** Update open previews when files change. Default true. */
|
|
64
71
|
liveReload?: boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Apply edits in place where possible: stylesheets swap and React components
|
|
74
|
+
* re-render keeping their state (Fast Refresh); anything else reloads. `false`
|
|
75
|
+
* reloads on every edit. Default true.
|
|
76
|
+
*/
|
|
77
|
+
hot?: boolean;
|
|
65
78
|
/** Your scripts (JavaScript source), run in every preview page before the app — analytics, test hooks, a mock `fetch`. */
|
|
66
79
|
previewScripts?: string[];
|
|
67
80
|
/** The Node runtime behind `run` (process workers, npm registry). */
|
|
68
81
|
node?: NodeRuntimeOptions;
|
|
69
82
|
}
|
|
70
83
|
|
|
71
|
-
/** Edits arrive in bursts (a save, an agent writing several files): reload once per burst. */
|
|
72
|
-
const RELOAD_DEBOUNCE_MS = 120;
|
|
73
|
-
|
|
74
84
|
export interface RuntimeBuildOptions {
|
|
75
85
|
/** Where the site will be served from. Default `./` (works from any directory). */
|
|
76
86
|
base?: string;
|
|
@@ -84,7 +94,7 @@ export interface PreviewRuntime {
|
|
|
84
94
|
readonly url: string;
|
|
85
95
|
readonly fs: VirtualFileSystem;
|
|
86
96
|
readonly server: DevServer;
|
|
87
|
-
/** Write files into the runtime (nested or flat; see `FileTree`), under `at` (default `/`). Open previews
|
|
97
|
+
/** Write files into the runtime (nested or flat; see `FileTree`), under `at` (default `/`). Open previews update. */
|
|
88
98
|
writeTree(files: FileTree, at?: string): void;
|
|
89
99
|
/** The project as a zip — "Download project" with `exclude: ['node_modules']`, or a full snapshot to restore later. */
|
|
90
100
|
exportZip(options?: ZipExportOptions): Uint8Array;
|
|
@@ -119,6 +129,12 @@ export interface PreviewRuntime {
|
|
|
119
129
|
onPortChange(listener: (change: PortChange) => void): () => void;
|
|
120
130
|
/** Processes still running, with the ports their servers listen on. */
|
|
121
131
|
listProcesses(): ProcessInfo[];
|
|
132
|
+
/**
|
|
133
|
+
* Cookies virtual servers set, per port. A service worker cannot set cookies,
|
|
134
|
+
* so the runtime keeps them and sends them back on later requests (and
|
|
135
|
+
* WebSocket handshakes); inspect or `clear()` them here.
|
|
136
|
+
*/
|
|
137
|
+
readonly cookies: PortCookieJars;
|
|
122
138
|
dispose(): void;
|
|
123
139
|
}
|
|
124
140
|
|
|
@@ -153,10 +169,13 @@ export async function startPreviewRuntime(options: PreviewRuntimeOptions): Promi
|
|
|
153
169
|
const base = previewBase(transport.scope, id);
|
|
154
170
|
const fs = new VirtualFileSystem();
|
|
155
171
|
const components = options.components ?? createCdnComponentCompilers();
|
|
172
|
+
const styles = options.styles ?? createCdnStyleCompilers();
|
|
173
|
+
/** Run in every preview page: dev-server documents and pages virtual servers serve alike. */
|
|
174
|
+
let previewScripts: string[] = [...(options.previewScripts ?? [])];
|
|
156
175
|
let server: DevServer;
|
|
157
176
|
try {
|
|
158
177
|
const transformer = options.transformer ?? (await createEsbuildWasmTransformer());
|
|
159
|
-
server = new DevServer({ fs, transformer, base, cdn: options.cdn, components, attribution: options.attribution, previewScripts: options.
|
|
178
|
+
server = new DevServer({ fs, transformer, base, cdn: options.cdn, components, styles, attribution: options.attribution, previewScripts, hot: options.hot });
|
|
160
179
|
} catch (error) {
|
|
161
180
|
transport.dispose();
|
|
162
181
|
throw error;
|
|
@@ -167,15 +186,22 @@ export async function startPreviewRuntime(options: PreviewRuntimeOptions): Promi
|
|
|
167
186
|
const node = { ...options.node, createWorker: options.node?.createWorker ?? transport.createWorker?.bind(transport) };
|
|
168
187
|
const processes = createProcessHost({ fs, base, origin: transport.origin, previewUrl, options: node });
|
|
169
188
|
|
|
170
|
-
const
|
|
171
|
-
|
|
189
|
+
const cookies = new PortCookieJars();
|
|
190
|
+
let responder: ReturnType<typeof createPortResponder> | undefined;
|
|
172
191
|
|
|
173
192
|
const attach = () => {
|
|
174
193
|
const channel = new MessageChannel();
|
|
194
|
+
const reply = (message: WireReply, transfer: Transferable[]) => channel.port1.postMessage(message, transfer);
|
|
195
|
+
// Virtual servers' responses stream (one responder per channel: request ids are per worker).
|
|
196
|
+
responder?.dispose();
|
|
197
|
+
const ports = (responder = createPortResponder(processes, { cookies, scripts: () => previewScripts }));
|
|
175
198
|
channel.port1.onmessage = async (event) => {
|
|
199
|
+
if (isWireCancel(event.data)) return ports.cancel(event.data.reqId);
|
|
176
200
|
if (!isWireRequest(event.data)) return;
|
|
177
|
-
const
|
|
178
|
-
|
|
201
|
+
const request = event.data;
|
|
202
|
+
if (isPortPath(request.path)) return ports.serve(request, reply);
|
|
203
|
+
const { message, transfer } = toWire(request.reqId, await server.handle(request.path, request.search));
|
|
204
|
+
reply(message, transfer);
|
|
179
205
|
};
|
|
180
206
|
transport.attach(id, channel.port2);
|
|
181
207
|
};
|
|
@@ -184,16 +210,13 @@ export async function startPreviewRuntime(options: PreviewRuntimeOptions): Promi
|
|
|
184
210
|
if (wanted === id) attach();
|
|
185
211
|
});
|
|
186
212
|
|
|
187
|
-
//
|
|
188
|
-
|
|
189
|
-
const stopWatching = options.liveReload === false
|
|
190
|
-
? undefined
|
|
191
|
-
: fs.watch(() => {
|
|
192
|
-
clearTimeout(reloadTimer);
|
|
193
|
-
reloadTimer = setTimeout(() => transport.reload(base), RELOAD_DEBOUNCE_MS);
|
|
194
|
-
});
|
|
213
|
+
// Every frame showing this preview hears what each burst of edits changed.
|
|
214
|
+
const reload = () => transport.send(base, { type: 'reload' });
|
|
215
|
+
const stopWatching = options.liveReload === false ? undefined : watchForPreviewUpdates(fs, server, (update) => transport.send(base, update));
|
|
195
216
|
|
|
196
217
|
const previewMessages = listenToPreview(window, transport.origin, base);
|
|
218
|
+
// WebSockets and document.cookie for virtual servers, which a service worker cannot carry.
|
|
219
|
+
const bridge = listenToPreviewBridge(window, transport.origin, base, { upgrade: (port, request) => processes.upgrade(port, request), cookies });
|
|
197
220
|
|
|
198
221
|
return {
|
|
199
222
|
id,
|
|
@@ -203,26 +226,29 @@ export async function startPreviewRuntime(options: PreviewRuntimeOptions): Promi
|
|
|
203
226
|
writeTree: (files, at) => fs.writeTree(files, at),
|
|
204
227
|
exportZip: (zipOptions) => exportZip(fs, zipOptions),
|
|
205
228
|
importZip: (zip, at) => importZip(fs, zip, at),
|
|
206
|
-
reload
|
|
229
|
+
reload,
|
|
207
230
|
profile: () => server.profile(),
|
|
208
231
|
async build(buildOptions = {}) {
|
|
209
232
|
const bundler = options.bundler ?? (await createEsbuildWasmBundler());
|
|
210
|
-
return buildProject({ files: fs, bundler, cdn: options.cdn, components, base: buildOptions.base, minify: buildOptions.minify });
|
|
233
|
+
return buildProject({ files: fs, bundler, cdn: options.cdn, components, styles, base: buildOptions.base, minify: buildOptions.minify });
|
|
211
234
|
},
|
|
212
235
|
onError: (listener) => previewMessages.onError(listener),
|
|
213
236
|
onPreviewConsole: (listener) => previewMessages.onConsole(listener),
|
|
214
237
|
setPreviewScripts(scripts) {
|
|
215
|
-
|
|
216
|
-
|
|
238
|
+
previewScripts = [...scripts];
|
|
239
|
+
server.setPreviewScripts(previewScripts);
|
|
240
|
+
reload();
|
|
217
241
|
},
|
|
218
242
|
run: (command: string, args?: string[] | ProcessOptions, runOptions?: ProcessOptions) => processes.run(command, args as string[], runOptions),
|
|
219
243
|
onServerListening: (listener) => processes.servers.onListening(listener),
|
|
220
244
|
onPortChange: (listener) => processes.servers.onPortChange(listener),
|
|
221
245
|
listProcesses: () => processes.list(),
|
|
246
|
+
cookies,
|
|
222
247
|
dispose() {
|
|
248
|
+
bridge.dispose();
|
|
249
|
+
responder?.dispose();
|
|
223
250
|
processes.dispose();
|
|
224
251
|
previewMessages.dispose();
|
|
225
|
-
clearTimeout(reloadTimer);
|
|
226
252
|
stopWatching?.();
|
|
227
253
|
stopReattach();
|
|
228
254
|
transport.dispose();
|
package/src/index.ts
CHANGED
|
@@ -8,15 +8,22 @@ export type {
|
|
|
8
8
|
RuntimeBuildOptions,
|
|
9
9
|
} from './host.js';
|
|
10
10
|
export { listenToPreview } from './previewMessages.js';
|
|
11
|
+
export { createSnapshotStore } from './snapshotStore.js';
|
|
12
|
+
export type { SnapshotStore, SnapshotStoreOptions } from './snapshotStore.js';
|
|
11
13
|
export type { PreviewError, PreviewConsoleMessage, ConsoleLevel, PreviewMessages } from './previewMessages.js';
|
|
14
|
+
export { listenToPreviewBridge } from './previewBridge.js';
|
|
15
|
+
export type { PreviewBridge, PreviewBridgeOptions, BridgePort } from './previewBridge.js';
|
|
12
16
|
export type { PreviewTransport } from './transport.js';
|
|
13
17
|
export { createEsbuildWasmTransformer, createEsbuildWasmBundler, loadEsbuildWasm } from './esbuildWasm.js';
|
|
14
18
|
export type { EsbuildWasmOptions } from './esbuildWasm.js';
|
|
15
19
|
export { createCdnComponentCompilers, defaultVueCompilerUrl, defaultSvelteCompilerUrl } from './componentCompilers.js';
|
|
16
20
|
export type { CdnComponentCompilerOptions } from './componentCompilers.js';
|
|
21
|
+
export { createCdnStyleCompilers, defaultSassUrl, defaultLessUrl } from './styleCompilers.js';
|
|
22
|
+
export type { CdnStyleCompilerOptions } from './styleCompilers.js';
|
|
23
|
+
export { watchForPreviewUpdates } from './previewUpdates.js';
|
|
17
24
|
export { createCacheStoragePackageCache } from './packageCache.js';
|
|
18
|
-
export { ProcessHost, createWorkerProcess } from './node/index.js';
|
|
19
|
-
export type { NodeRuntimeOptions, ProcessHostOptions, ProcessInfo, WorkerLike } from './node/index.js';
|
|
25
|
+
export { ProcessHost, createWorkerProcess, servePortRequest, createPortResponder, openPortResponse, injectBridge } from './node/index.js';
|
|
26
|
+
export type { NodeRuntimeOptions, ProcessHostOptions, ProcessInfo, WorkerLike, PortResponder, PortResponderOptions, OpenedPortResponse } from './node/index.js';
|
|
20
27
|
export { createSwRouter } from './swRouter.js';
|
|
21
28
|
export type { SwRouter, SwRouterOptions, PortLike, PreviewTarget, RoutedResponse, RequestDetails } from './swRouter.js';
|
|
22
29
|
export { previewBase, previewPrefix, PREVIEW_SEGMENT, PREVIEW_ID, PORT_SEGMENT, isPortPath } from './protocol.js';
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The page side of the children ONE process Worker spawns (a shell running
|
|
3
|
+
* `node`, `child_process.fork`, a `worker_threads` Worker): each is started as a
|
|
4
|
+
* process of its own, and its output, exit and message channel are relayed back
|
|
5
|
+
* to the spawning Worker, keyed by the Worker's own child id.
|
|
6
|
+
*/
|
|
7
|
+
import type { ChildHandle, ProcessOptions } from '@seanhogg/builderforce-webcontainers-core';
|
|
8
|
+
import type { HostToWorker, WorkerToHost } from './protocol.js';
|
|
9
|
+
|
|
10
|
+
type ChildMessage = Extract<WorkerToHost, { type: 'spawn' | 'child-stdin' | 'child-kill' | 'child-resize' | 'child-ipc' | 'child-ipc-disconnect' }>;
|
|
11
|
+
|
|
12
|
+
const CHILD_MESSAGES = new Set<string>(['spawn', 'child-stdin', 'child-kill', 'child-resize', 'child-ipc', 'child-ipc-disconnect']);
|
|
13
|
+
|
|
14
|
+
export function isChildMessage(message: WorkerToHost): message is ChildMessage {
|
|
15
|
+
return CHILD_MESSAGES.has(message.type);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export class ChildRelay {
|
|
19
|
+
private readonly children = new Map<number, ChildHandle>();
|
|
20
|
+
|
|
21
|
+
constructor(
|
|
22
|
+
private readonly spawn: (command: string, args: string[], options: ProcessOptions) => ChildHandle,
|
|
23
|
+
private readonly post: (message: HostToWorker) => void,
|
|
24
|
+
) {}
|
|
25
|
+
|
|
26
|
+
receive(message: ChildMessage): void {
|
|
27
|
+
if (message.type === 'spawn') return this.start(message);
|
|
28
|
+
const child = this.children.get(message.childId);
|
|
29
|
+
switch (message.type) {
|
|
30
|
+
case 'child-stdin':
|
|
31
|
+
if (message.data === null) child?.closeStdin();
|
|
32
|
+
else child?.write(message.data);
|
|
33
|
+
return;
|
|
34
|
+
case 'child-kill':
|
|
35
|
+
return child?.kill(message.signal);
|
|
36
|
+
case 'child-resize':
|
|
37
|
+
return child?.resize?.(message.cols, message.rows);
|
|
38
|
+
case 'child-ipc':
|
|
39
|
+
return child?.ipc?.send(message.data);
|
|
40
|
+
case 'child-ipc-disconnect':
|
|
41
|
+
return child?.ipc?.disconnect();
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
private start(message: Extract<ChildMessage, { type: 'spawn' }>): void {
|
|
46
|
+
const { childId } = message;
|
|
47
|
+
let child: ChildHandle;
|
|
48
|
+
try {
|
|
49
|
+
child = this.spawn(message.command, message.args, { cwd: message.cwd, env: message.env, terminal: message.terminal, ipc: message.ipc, thread: message.thread });
|
|
50
|
+
} catch (error) {
|
|
51
|
+
return this.post({ type: 'child-error', childId, code: (error as { code?: string }).code ?? 'EFAIL', message: (error as Error).message });
|
|
52
|
+
}
|
|
53
|
+
this.children.set(childId, child);
|
|
54
|
+
child.onStdout((data) => this.post({ type: 'child-out', childId, stream: 'stdout', data }));
|
|
55
|
+
child.onStderr((data) => this.post({ type: 'child-out', childId, stream: 'stderr', data }));
|
|
56
|
+
child.ipc?.onMessage((data) => this.post({ type: 'child-ipc', childId, data }));
|
|
57
|
+
child.ipc?.onDisconnect(() => this.post({ type: 'child-ipc-disconnect', childId }));
|
|
58
|
+
void child.exit.then((code) => {
|
|
59
|
+
this.children.delete(childId);
|
|
60
|
+
this.post({ type: 'child-exit', childId, code });
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
}
|
package/src/node/index.ts
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Glue between the preview runtime and the Node process host: options, the
|
|
3
3
|
* default Worker, and answering `/__port/<n>/…` preview requests from the
|
|
4
|
-
* virtual server listening on that port.
|
|
4
|
+
* virtual server listening on that port (portResponder.ts).
|
|
5
5
|
*/
|
|
6
|
-
import {
|
|
7
|
-
import type { WireRequest, WireResponse } from '../protocol.js';
|
|
6
|
+
import type { VirtualFileSystem } from '@seanhogg/builderforce-webcontainers-core';
|
|
8
7
|
import { ProcessHost, type WorkerLike } from './processHost.js';
|
|
9
8
|
|
|
10
9
|
export { ProcessHost } from './processHost.js';
|
|
11
10
|
export type { ProcessHostOptions, ProcessInfo, WorkerLike } from './processHost.js';
|
|
12
11
|
export { createWorkerProcess } from './workerProcess.js';
|
|
12
|
+
export { servePortRequest, createPortResponder, openPortResponse, injectBridge } from './portResponder.js';
|
|
13
|
+
export type { PortResponder, PortResponderOptions, OpenedPortResponse } from './portResponder.js';
|
|
13
14
|
|
|
14
15
|
export interface NodeRuntimeOptions {
|
|
15
16
|
/**
|
|
@@ -47,23 +48,3 @@ export function createProcessHost(args: { fs: VirtualFileSystem; base: string; o
|
|
|
47
48
|
killGraceMs: options.killGraceMs,
|
|
48
49
|
});
|
|
49
50
|
}
|
|
50
|
-
|
|
51
|
-
const TEXT = { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' };
|
|
52
|
-
|
|
53
|
-
/** Answer a preview request addressed to a virtual server. */
|
|
54
|
-
export async function servePortRequest(host: ProcessHost, request: WireRequest): Promise<{ message: WireResponse; transfer: Transferable[] }> {
|
|
55
|
-
const target = parsePortPath(request.path)!;
|
|
56
|
-
const response = await host.request(target.port, {
|
|
57
|
-
method: request.method ?? 'GET',
|
|
58
|
-
url: target.path + request.search,
|
|
59
|
-
headers: request.headers ?? {},
|
|
60
|
-
body: request.body ? new Uint8Array(request.body) : null,
|
|
61
|
-
});
|
|
62
|
-
if (!response) {
|
|
63
|
-
return { message: { type: 'response', reqId: request.reqId, status: 502, headers: TEXT, body: `Nothing is listening on port ${target.port}. Start a server (node server.js) first.` }, transfer: [] };
|
|
64
|
-
}
|
|
65
|
-
const headers: Record<string, string> = {};
|
|
66
|
-
for (const [key, value] of Object.entries(response.headers)) headers[key] = Array.isArray(value) ? value.join(', ') : String(value);
|
|
67
|
-
const body = response.body.slice().buffer as ArrayBuffer;
|
|
68
|
-
return { message: { type: 'response', reqId: request.reqId, status: response.status, headers, body }, transfer: [body] };
|
|
69
|
-
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Answering preview requests addressed to virtual servers (`/__port/<n>/…`).
|
|
3
|
+
* The request reaches the server carrying the cookies the host holds for that
|
|
4
|
+
* port; the response streams back to the service worker as the server writes
|
|
5
|
+
* it (head, then `chunk` messages, then `end`); its `Set-Cookie`s go into the
|
|
6
|
+
* jar (a service worker could not set them); and an HTML page gets the preview
|
|
7
|
+
* bridge — the WebSocket shim and `document.cookie` — injected after `<head>`.
|
|
8
|
+
*/
|
|
9
|
+
import {
|
|
10
|
+
bridgeInsertionPoint,
|
|
11
|
+
drainBody,
|
|
12
|
+
errorBridgeScript,
|
|
13
|
+
scriptTag,
|
|
14
|
+
parsePortPath,
|
|
15
|
+
previewCookieScript,
|
|
16
|
+
previewSocketScript,
|
|
17
|
+
readBody,
|
|
18
|
+
textResponse,
|
|
19
|
+
type CookieJar,
|
|
20
|
+
type PortCookieJars,
|
|
21
|
+
} from '@seanhogg/builderforce-webcontainers-core';
|
|
22
|
+
import type { WireReply, WireRequest, WireResponse } from '../protocol.js';
|
|
23
|
+
import type { ProcessHost } from './processHost.js';
|
|
24
|
+
|
|
25
|
+
export interface PortResponderOptions {
|
|
26
|
+
/** The runtime's cookie jars. Without them, the browser's own `Cookie` header passes through and `Set-Cookie` is lost. */
|
|
27
|
+
cookies?: PortCookieJars;
|
|
28
|
+
/** Inject the preview bridge (errors and console to the host, WebSocket shim, `document.cookie`) into HTML pages. Default true. */
|
|
29
|
+
bridge?: boolean;
|
|
30
|
+
/** The host's preview scripts, read per page so `setPreviewScripts` applies to virtual servers too. */
|
|
31
|
+
scripts?: () => readonly string[];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface OpenedPortResponse {
|
|
35
|
+
status: number;
|
|
36
|
+
/** Flattened for a `Response` (`Set-Cookie` removed — it went to the jar). */
|
|
37
|
+
headers: Record<string, string>;
|
|
38
|
+
body: ReadableStream<Uint8Array>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const NO_STORE = { 'cache-control': 'no-store' };
|
|
42
|
+
|
|
43
|
+
function headerKey(headers: Record<string, unknown>, name: string): string | undefined {
|
|
44
|
+
return Object.keys(headers).find((key) => key.toLowerCase() === name);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Send a preview request to its virtual server; resolves with the head and a body that streams. */
|
|
48
|
+
export async function openPortResponse(host: ProcessHost, request: WireRequest, options: PortResponderOptions = {}): Promise<OpenedPortResponse> {
|
|
49
|
+
const target = parsePortPath(request.path)!;
|
|
50
|
+
const jar = options.cookies?.jar(target.port);
|
|
51
|
+
const headers: Record<string, string> = {};
|
|
52
|
+
for (const [key, value] of Object.entries(request.headers ?? {})) if (!jar || key.toLowerCase() !== 'cookie') headers[key] = value;
|
|
53
|
+
const cookie = jar?.header(target.path);
|
|
54
|
+
if (cookie) headers.cookie = cookie;
|
|
55
|
+
const response =
|
|
56
|
+
(await host.requestStream(target.port, { method: request.method ?? 'GET', url: target.path + request.search, headers, body: request.body ? new Uint8Array(request.body) : null })) ??
|
|
57
|
+
textResponse(502, `Nothing is listening on port ${target.port}. Start a server (node server.js) first.`);
|
|
58
|
+
|
|
59
|
+
const out: Record<string, string> = {};
|
|
60
|
+
const setCookies: string[] = [];
|
|
61
|
+
for (const [key, value] of Object.entries(response.headers)) {
|
|
62
|
+
if (key.toLowerCase() === 'set-cookie') setCookies.push(...(Array.isArray(value) ? value : [value]));
|
|
63
|
+
else out[key] = Array.isArray(value) ? value.join(', ') : String(value);
|
|
64
|
+
}
|
|
65
|
+
if (response.status === 502 && !headerKey(out, 'cache-control')) Object.assign(out, NO_STORE);
|
|
66
|
+
jar?.store(setCookies, target.path);
|
|
67
|
+
|
|
68
|
+
let body = response.body;
|
|
69
|
+
const type = headerKey(out, 'content-type');
|
|
70
|
+
// A compressed body cannot be edited in flight; such a page goes without the bridge.
|
|
71
|
+
const hasBody = request.method !== 'HEAD' && response.status !== 204 && response.status !== 304;
|
|
72
|
+
if (options.bridge !== false && hasBody && type && /^\s*text\/html/i.test(out[type]!) && !headerKey(out, 'content-encoding')) {
|
|
73
|
+
body = injectBridge(body, bridgeFor(jar, target.path, options.scripts?.() ?? []));
|
|
74
|
+
const length = headerKey(out, 'content-length');
|
|
75
|
+
if (length) delete out[length];
|
|
76
|
+
// The bridge pushes a `<meta charset>` past the 1,024-byte prescan; say it in the header instead.
|
|
77
|
+
if (!/charset=/i.test(out[type]!)) out[type] = `${out[type]}; charset=utf-8`;
|
|
78
|
+
}
|
|
79
|
+
return { status: response.status, headers: out, body };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The same bridge a dev-server page gets (errors, console, sockets), plus cookies and the host's scripts. */
|
|
83
|
+
function bridgeFor(jar: CookieJar | undefined, path: string, scripts: readonly string[]): string {
|
|
84
|
+
return [errorBridgeScript(), previewSocketScript(), jar ? previewCookieScript(jar.documentCookie(path)) : '', ...scripts.map(scriptTag)].join('');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Insert `script` into a streamed document, after `<head>` (see `bridgeInsertionPoint`), passing the rest through as it arrives. */
|
|
88
|
+
export function injectBridge(body: ReadableStream<Uint8Array>, script: string): ReadableStream<Uint8Array> {
|
|
89
|
+
// windows-1252 maps every byte to one UTF-16 unit, so string indices are byte offsets.
|
|
90
|
+
const latin1 = new TextDecoder('latin1');
|
|
91
|
+
const bridge = new TextEncoder().encode(script);
|
|
92
|
+
let held = new Uint8Array(0);
|
|
93
|
+
let injected = false;
|
|
94
|
+
const tryInject = (controller: TransformStreamDefaultController<Uint8Array>, complete: boolean) => {
|
|
95
|
+
const at = bridgeInsertionPoint(latin1.decode(held), complete);
|
|
96
|
+
if (at === undefined) return;
|
|
97
|
+
if (at) controller.enqueue(held.subarray(0, at));
|
|
98
|
+
controller.enqueue(bridge);
|
|
99
|
+
if (at < held.byteLength) controller.enqueue(held.subarray(at));
|
|
100
|
+
held = new Uint8Array(0);
|
|
101
|
+
injected = true;
|
|
102
|
+
};
|
|
103
|
+
return body.pipeThrough(
|
|
104
|
+
new TransformStream<Uint8Array, Uint8Array>({
|
|
105
|
+
transform(chunk, controller) {
|
|
106
|
+
if (injected) return controller.enqueue(chunk);
|
|
107
|
+
const joined = new Uint8Array(held.byteLength + chunk.byteLength);
|
|
108
|
+
joined.set(held);
|
|
109
|
+
joined.set(chunk, held.byteLength);
|
|
110
|
+
held = joined;
|
|
111
|
+
tryInject(controller, false);
|
|
112
|
+
},
|
|
113
|
+
flush(controller) {
|
|
114
|
+
if (!injected) tryInject(controller, true);
|
|
115
|
+
},
|
|
116
|
+
}),
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** A transferable copy of a chunk. */
|
|
121
|
+
const transferable = (data: Uint8Array) => new Uint8Array(data).buffer as ArrayBuffer;
|
|
122
|
+
|
|
123
|
+
/** Answer a preview request with the whole body (tests, simple hosts). The preview path streams instead: {@link createPortResponder}. */
|
|
124
|
+
export async function servePortRequest(host: ProcessHost, request: WireRequest, options?: PortResponderOptions): Promise<{ message: WireResponse; transfer: Transferable[] }> {
|
|
125
|
+
const opened = await openPortResponse(host, request, options);
|
|
126
|
+
const body = transferable(await readBody(opened.body));
|
|
127
|
+
return { message: { type: 'response', reqId: request.reqId, status: opened.status, headers: opened.headers, body }, transfer: [body] };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export interface PortResponder {
|
|
131
|
+
/** Answer one preview request: post the head, then the body chunk by chunk as the server writes it. */
|
|
132
|
+
serve(request: WireRequest, post: (reply: WireReply, transfer: Transferable[]) => void): Promise<void>;
|
|
133
|
+
/** The preview stopped reading `reqId`: hang up on the server. */
|
|
134
|
+
cancel(reqId: number): void;
|
|
135
|
+
/** Hang up on every response still streaming. */
|
|
136
|
+
dispose(): void;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** One per service-worker channel (request ids are unique within a channel). */
|
|
140
|
+
export function createPortResponder(host: ProcessHost, options?: PortResponderOptions): PortResponder {
|
|
141
|
+
const streaming = new Map<number, () => void>();
|
|
142
|
+
return {
|
|
143
|
+
async serve(request, post) {
|
|
144
|
+
const { reqId } = request;
|
|
145
|
+
let opened: OpenedPortResponse;
|
|
146
|
+
try {
|
|
147
|
+
opened = await openPortResponse(host, request, options);
|
|
148
|
+
} catch (error) {
|
|
149
|
+
return post({ type: 'response', reqId, status: 500, headers: { 'content-type': 'text/plain; charset=utf-8', ...NO_STORE }, body: String(error instanceof Error ? error.message : error) }, []);
|
|
150
|
+
}
|
|
151
|
+
post({ type: 'response', reqId, status: opened.status, headers: opened.headers, body: null, streaming: true }, []);
|
|
152
|
+
streaming.set(
|
|
153
|
+
reqId,
|
|
154
|
+
drainBody(opened.body, {
|
|
155
|
+
chunk(data) {
|
|
156
|
+
const buffer = transferable(data);
|
|
157
|
+
post({ type: 'chunk', reqId, data: buffer }, [buffer]);
|
|
158
|
+
},
|
|
159
|
+
end(error) {
|
|
160
|
+
streaming.delete(reqId);
|
|
161
|
+
post(error ? { type: 'end', reqId, error } : { type: 'end', reqId }, []);
|
|
162
|
+
},
|
|
163
|
+
}),
|
|
164
|
+
);
|
|
165
|
+
},
|
|
166
|
+
cancel(reqId) {
|
|
167
|
+
streaming.get(reqId)?.();
|
|
168
|
+
streaming.delete(reqId);
|
|
169
|
+
},
|
|
170
|
+
dispose() {
|
|
171
|
+
for (const stop of streaming.values()) stop();
|
|
172
|
+
streaming.clear();
|
|
173
|
+
},
|
|
174
|
+
};
|
|
175
|
+
}
|