@vivari/react 1.0.0 → 1.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 +423 -40
- package/dist/Vivari.d.ts +36 -12
- package/dist/Vivari.d.ts.map +1 -1
- package/dist/VivariPreview.d.ts +27 -0
- package/dist/VivariPreview.d.ts.map +1 -0
- package/dist/context.d.ts +28 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/index.d.ts +14 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +771 -129
- package/dist/useSpawn.d.ts +46 -0
- package/dist/useSpawn.d.ts.map +1 -0
- package/dist/useVivari.d.ts +58 -10
- package/dist/useVivari.d.ts.map +1 -1
- package/dist/useVivariDir.d.ts +30 -0
- package/dist/useVivariDir.d.ts.map +1 -0
- package/dist/useVivariFile.d.ts +29 -0
- package/dist/useVivariFile.d.ts.map +1 -0
- package/package.json +11 -10
package/dist/index.js
CHANGED
|
@@ -1,172 +1,814 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
"use client";
|
|
2
|
+
import { createContext, forwardRef, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
3
|
+
import { Vivari as Vivari$1, VivariError, VivariFsError, isCrossOriginIsolated, isCrossOriginIsolated as isCrossOriginIsolated$1, resetVfs } from "@vivari/core";
|
|
4
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
4
5
|
//#region src/useVivari.ts
|
|
6
|
+
var IDLE = {
|
|
7
|
+
status: "idle",
|
|
8
|
+
vivari: null,
|
|
9
|
+
error: null
|
|
10
|
+
};
|
|
11
|
+
var BOOTING = {
|
|
12
|
+
status: "booting",
|
|
13
|
+
vivari: null,
|
|
14
|
+
error: null
|
|
15
|
+
};
|
|
16
|
+
var registry = /* @__PURE__ */ new Map();
|
|
17
|
+
function entryFor(key) {
|
|
18
|
+
let e = registry.get(key);
|
|
19
|
+
if (!e) {
|
|
20
|
+
e = {
|
|
21
|
+
refs: 0,
|
|
22
|
+
promise: null,
|
|
23
|
+
state: IDLE,
|
|
24
|
+
release: null,
|
|
25
|
+
listeners: /* @__PURE__ */ new Set()
|
|
26
|
+
};
|
|
27
|
+
registry.set(key, e);
|
|
28
|
+
}
|
|
29
|
+
return e;
|
|
30
|
+
}
|
|
31
|
+
function publish(e, state) {
|
|
32
|
+
e.state = state;
|
|
33
|
+
for (const l of [...e.listeners]) l();
|
|
34
|
+
}
|
|
35
|
+
var UNSUPPORTED_MESSAGE = {
|
|
36
|
+
"not-cross-origin-isolated": "Vivari requires a cross-origin isolated page (SharedArrayBuffer). Serve your page with the headers `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`.",
|
|
37
|
+
"no-web-workers": "Vivari requires Web Workers, which this environment does not provide."
|
|
38
|
+
};
|
|
39
|
+
/** The single place to extend when core lands `VivariError` with typed codes. */
|
|
40
|
+
function unsupportedReason() {
|
|
41
|
+
if (typeof Worker === "undefined") return "no-web-workers";
|
|
42
|
+
if (!isCrossOriginIsolated$1()) return "not-cross-origin-isolated";
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
function startBoot(e, options) {
|
|
46
|
+
if (e.promise || e.state.status === "ready") return;
|
|
47
|
+
const reason = unsupportedReason();
|
|
48
|
+
if (reason) {
|
|
49
|
+
publish(e, {
|
|
50
|
+
status: "unsupported",
|
|
51
|
+
vivari: null,
|
|
52
|
+
error: new Error(UNSUPPORTED_MESSAGE[reason]),
|
|
53
|
+
reason
|
|
54
|
+
});
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
const p = Vivari$1.boot(options);
|
|
58
|
+
e.promise = p;
|
|
59
|
+
publish(e, BOOTING);
|
|
60
|
+
p.then((v) => {
|
|
61
|
+
if (e.promise !== p || e.refs === 0) {
|
|
62
|
+
v.teardown();
|
|
63
|
+
if (e.promise === p) {
|
|
64
|
+
e.promise = null;
|
|
65
|
+
publish(e, IDLE);
|
|
66
|
+
}
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
publish(e, {
|
|
70
|
+
status: "ready",
|
|
71
|
+
vivari: v,
|
|
72
|
+
error: null
|
|
73
|
+
});
|
|
74
|
+
}, (err) => {
|
|
75
|
+
if (e.promise !== p) return;
|
|
76
|
+
e.promise = null;
|
|
77
|
+
publish(e, {
|
|
78
|
+
status: "error",
|
|
79
|
+
vivari: null,
|
|
80
|
+
error: err instanceof Error ? err : new Error(String(err))
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
function dispose(key, e) {
|
|
85
|
+
if (e.state.status === "ready") e.state.vivari.teardown();
|
|
86
|
+
e.promise = null;
|
|
87
|
+
publish(e, IDLE);
|
|
88
|
+
if (e.refs === 0 && e.listeners.size === 0) registry.delete(key);
|
|
89
|
+
}
|
|
5
90
|
/**
|
|
6
|
-
* Boot a
|
|
91
|
+
* Boot (or join) a Vivari instance for the lifetime of the component.
|
|
7
92
|
*
|
|
8
|
-
* The instance is
|
|
9
|
-
*
|
|
93
|
+
* The instance is shared and ref-counted per `instanceKey`, so StrictMode's
|
|
94
|
+
* double-mount, an `<Activity>` toggle and sibling components all reuse one
|
|
95
|
+
* kernel. Boot options are read when the boot actually starts; later changes
|
|
96
|
+
* apply on the next `restart()`.
|
|
10
97
|
*/
|
|
11
|
-
function useVivari(options) {
|
|
12
|
-
const
|
|
13
|
-
const
|
|
14
|
-
const [error, setError] = useState(null);
|
|
98
|
+
function useVivari(options = {}) {
|
|
99
|
+
const { instanceKey = "default", autoBoot = true, ...bootOptions } = options;
|
|
100
|
+
const latest = useRef(bootOptions);
|
|
15
101
|
useEffect(() => {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
if (cancelled) {
|
|
22
|
-
v.teardown();
|
|
23
|
-
return;
|
|
24
|
-
}
|
|
25
|
-
setVivari(v);
|
|
26
|
-
setStatus("ready");
|
|
27
|
-
}).catch((e) => {
|
|
28
|
-
if (cancelled) return;
|
|
29
|
-
setError(e instanceof Error ? e : new Error(String(e)));
|
|
30
|
-
setStatus("error");
|
|
31
|
-
});
|
|
102
|
+
latest.current = bootOptions;
|
|
103
|
+
});
|
|
104
|
+
const subscribe = useCallback((cb) => {
|
|
105
|
+
const e = entryFor(instanceKey);
|
|
106
|
+
e.listeners.add(cb);
|
|
32
107
|
return () => {
|
|
33
|
-
|
|
34
|
-
instance?.teardown();
|
|
35
|
-
setVivari(null);
|
|
108
|
+
e.listeners.delete(cb);
|
|
36
109
|
};
|
|
37
|
-
}, []);
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
110
|
+
}, [instanceKey]);
|
|
111
|
+
const state = useSyncExternalStore(subscribe, useCallback(() => registry.get(instanceKey)?.state ?? IDLE, [instanceKey]), () => IDLE);
|
|
112
|
+
useEffect(() => {
|
|
113
|
+
const e = entryFor(instanceKey);
|
|
114
|
+
e.refs++;
|
|
115
|
+
if (e.release) {
|
|
116
|
+
clearTimeout(e.release);
|
|
117
|
+
e.release = null;
|
|
118
|
+
}
|
|
119
|
+
if (autoBoot) startBoot(e, latest.current);
|
|
120
|
+
return () => {
|
|
121
|
+
e.refs--;
|
|
122
|
+
if (e.refs > 0) return;
|
|
123
|
+
e.release = setTimeout(() => {
|
|
124
|
+
e.release = null;
|
|
125
|
+
if (e.refs === 0) dispose(instanceKey, e);
|
|
126
|
+
}, 0);
|
|
127
|
+
};
|
|
128
|
+
}, [instanceKey, autoBoot]);
|
|
129
|
+
const boot = useCallback(() => {
|
|
130
|
+
startBoot(entryFor(instanceKey), latest.current);
|
|
131
|
+
}, [instanceKey]);
|
|
132
|
+
const restart = useCallback(() => {
|
|
133
|
+
const e = entryFor(instanceKey);
|
|
134
|
+
dispose(instanceKey, e);
|
|
135
|
+
startBoot(e, latest.current);
|
|
136
|
+
}, [instanceKey]);
|
|
137
|
+
return useMemo(() => ({
|
|
138
|
+
...state,
|
|
139
|
+
instanceKey,
|
|
140
|
+
boot,
|
|
141
|
+
restart
|
|
142
|
+
}), [
|
|
143
|
+
state,
|
|
144
|
+
instanceKey,
|
|
145
|
+
boot,
|
|
146
|
+
restart
|
|
147
|
+
]);
|
|
148
|
+
}
|
|
149
|
+
//#endregion
|
|
150
|
+
//#region src/context.tsx
|
|
151
|
+
var VivariContext = createContext(null);
|
|
152
|
+
/**
|
|
153
|
+
* Boot an instance and publish it to the subtree. Renders no DOM of its own.
|
|
154
|
+
*
|
|
155
|
+
* <VivariProvider compress={false}>
|
|
156
|
+
* <Editor />
|
|
157
|
+
* <VivariPreview port={5173} />
|
|
158
|
+
* </VivariProvider>
|
|
159
|
+
*/
|
|
160
|
+
function VivariProvider({ children, ...options }) {
|
|
161
|
+
const state = useVivari(options);
|
|
162
|
+
return /* @__PURE__ */ jsx(VivariContext.Provider, {
|
|
163
|
+
value: state,
|
|
164
|
+
children
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
function useVivariContext(options) {
|
|
168
|
+
const ctx = useContext(VivariContext);
|
|
169
|
+
if (!ctx && !options?.optional) throw new Error("useVivariContext() must be used inside a <VivariProvider>.");
|
|
170
|
+
return ctx;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Resolve the instance a hook should act on: an explicitly passed one, else the
|
|
174
|
+
* nearest provider's. Returns `null` until the VM is ready, so hooks can always
|
|
175
|
+
* be called unconditionally and simply idle until there is something to act on.
|
|
176
|
+
*/
|
|
177
|
+
function useVivariInstance(explicit) {
|
|
178
|
+
const ctx = useVivariContext({ optional: true });
|
|
179
|
+
return explicit ?? ctx?.vivari ?? null;
|
|
43
180
|
}
|
|
44
181
|
//#endregion
|
|
182
|
+
//#region src/VivariPreview.tsx
|
|
183
|
+
/**
|
|
184
|
+
* Render an in-VM server's preview.
|
|
185
|
+
*
|
|
186
|
+
* <VivariPreview port={5173} style={{ width: "100%", height: 480, border: 0 }} />
|
|
187
|
+
*
|
|
188
|
+
* Waits for `server-ready`, so a component mounted before the server starts just
|
|
189
|
+
* shows `fallback` until it does. One mounted *after* a server started won't see
|
|
190
|
+
* that event — give it a `reloadKey` bump, or keep it mounted.
|
|
191
|
+
*/
|
|
192
|
+
var VivariPreview = forwardRef(function VivariPreview({ port, path = "/", vivari: explicit, reloadKey, onServerReady, fallback, ...iframeProps }, forwardedRef) {
|
|
193
|
+
const instance = useVivariInstance(explicit);
|
|
194
|
+
const [target, setTarget] = useState(null);
|
|
195
|
+
const [frame, setFrame] = useState(null);
|
|
196
|
+
const cbs = useRef({ onServerReady });
|
|
197
|
+
useEffect(() => {
|
|
198
|
+
cbs.current = { onServerReady };
|
|
199
|
+
});
|
|
200
|
+
const attachRef = useCallback((el) => {
|
|
201
|
+
setFrame(el);
|
|
202
|
+
if (typeof forwardedRef === "function") forwardedRef(el);
|
|
203
|
+
else if (forwardedRef) forwardedRef.current = el;
|
|
204
|
+
}, [forwardedRef]);
|
|
205
|
+
useEffect(() => {
|
|
206
|
+
if (!instance) return;
|
|
207
|
+
return instance.on("server-ready", (p, url) => {
|
|
208
|
+
if (port != null && p !== port) return;
|
|
209
|
+
setTarget((prev) => ({
|
|
210
|
+
port: p,
|
|
211
|
+
url: path === "/" ? url : instance.previewUrl(p, path),
|
|
212
|
+
nonce: (prev?.nonce ?? 0) + 1
|
|
213
|
+
}));
|
|
214
|
+
});
|
|
215
|
+
}, [
|
|
216
|
+
instance,
|
|
217
|
+
port,
|
|
218
|
+
path
|
|
219
|
+
]);
|
|
220
|
+
useEffect(() => {
|
|
221
|
+
if (!instance || !frame) return;
|
|
222
|
+
return instance.attachPreview(frame);
|
|
223
|
+
}, [instance, frame]);
|
|
224
|
+
useEffect(() => {
|
|
225
|
+
if (!frame || !target) return;
|
|
226
|
+
frame.src = target.url;
|
|
227
|
+
cbs.current.onServerReady?.(target.port, target.url);
|
|
228
|
+
}, [
|
|
229
|
+
frame,
|
|
230
|
+
target,
|
|
231
|
+
reloadKey
|
|
232
|
+
]);
|
|
233
|
+
if (!target) return /* @__PURE__ */ jsx(Fragment, { children: fallback });
|
|
234
|
+
return /* @__PURE__ */ jsx("iframe", {
|
|
235
|
+
...iframeProps,
|
|
236
|
+
ref: attachRef,
|
|
237
|
+
title: iframeProps.title ?? "Vivari preview",
|
|
238
|
+
allow: iframeProps.allow ?? "cross-origin-isolated",
|
|
239
|
+
sandbox: iframeProps.sandbox ?? "allow-scripts allow-same-origin allow-forms allow-popups allow-modals"
|
|
240
|
+
});
|
|
241
|
+
});
|
|
242
|
+
//#endregion
|
|
45
243
|
//#region src/Vivari.tsx
|
|
244
|
+
var DEFAULT_INSTALL = ["npm", "install"];
|
|
46
245
|
function toCommand(cmd) {
|
|
47
246
|
const parts = Array.isArray(cmd) ? cmd : cmd.trim().split(/\s+/);
|
|
48
247
|
return [parts[0], parts.slice(1)];
|
|
49
248
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
try {
|
|
67
|
-
const res = await fetch(url, { cache: "no-store" });
|
|
68
|
-
if (res.status !== 502 && res.status !== 503 && res.status !== 504) break;
|
|
69
|
-
} catch {}
|
|
70
|
-
if (Date.now() > deadline) return;
|
|
71
|
-
await sleep(150);
|
|
72
|
-
}
|
|
73
|
-
try {
|
|
74
|
-
const html = await (await fetch(url, { cache: "no-store" })).text();
|
|
75
|
-
const mods = /* @__PURE__ */ new Set(["/@vite/client"]);
|
|
76
|
-
const re = /<script[^>]*type=["']module["'][^>]*src=["']([^"']+)["']/gi;
|
|
77
|
-
for (let m; m = re.exec(html);) if (m[1].startsWith("/")) mods.add(m[1]);
|
|
78
|
-
const origin = new URL(url).origin;
|
|
79
|
-
const base = url.replace(origin, "").replace(/\/$/, "");
|
|
80
|
-
await Promise.all([...mods].map((p) => fetch(origin + base + p, { cache: "no-store" }).catch(() => {})));
|
|
81
|
-
} catch {}
|
|
249
|
+
function FailureNotice({ failure, className, style }) {
|
|
250
|
+
return /* @__PURE__ */ jsx("div", {
|
|
251
|
+
className,
|
|
252
|
+
style,
|
|
253
|
+
role: "alert",
|
|
254
|
+
children: failure.phase === "unsupported" ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("p", { children: failure.error.message }), /* @__PURE__ */ jsxs("pre", { children: [
|
|
255
|
+
"Cross-Origin-Opener-Policy: same-origin",
|
|
256
|
+
"\n",
|
|
257
|
+
"Cross-Origin-Embedder-Policy: require-corp"
|
|
258
|
+
] })] }) : /* @__PURE__ */ jsxs("p", { children: [
|
|
259
|
+
"Vivari failed during ",
|
|
260
|
+
failure.phase,
|
|
261
|
+
": ",
|
|
262
|
+
failure.error.message
|
|
263
|
+
] })
|
|
264
|
+
});
|
|
82
265
|
}
|
|
83
266
|
/**
|
|
84
|
-
*
|
|
85
|
-
*
|
|
267
|
+
* Boots Vivari, mounts `files`, runs `install` then `run`, and renders the
|
|
268
|
+
* resulting dev-server preview in an `<iframe>`.
|
|
86
269
|
*
|
|
87
270
|
* <Vivari files={tree} run="npm run dev" style={{ height: 480 }} />
|
|
88
271
|
*
|
|
89
272
|
* The host page must be cross-origin isolated (COOP + COEP).
|
|
90
273
|
*/
|
|
91
|
-
function Vivari(props) {
|
|
92
|
-
const { files, install =
|
|
93
|
-
const {
|
|
94
|
-
const
|
|
274
|
+
var Vivari = forwardRef(function Vivari(props, ref) {
|
|
275
|
+
const { boot, instanceKey, autoBoot, files, install = DEFAULT_INSTALL, run, onReady, onServerReady, onOutput, onError, showPreview = true, previewPort, previewPath, fallback, renderError, children, ...iframeProps } = props;
|
|
276
|
+
const parent = useVivariContext({ optional: true });
|
|
277
|
+
const state = useVivari({
|
|
278
|
+
...boot,
|
|
279
|
+
instanceKey: instanceKey ?? parent?.instanceKey,
|
|
280
|
+
autoBoot
|
|
281
|
+
});
|
|
282
|
+
const { vivari } = state;
|
|
283
|
+
const [runFailure, setRunFailure] = useState(null);
|
|
95
284
|
const cbs = useRef({
|
|
96
285
|
onReady,
|
|
97
286
|
onServerReady,
|
|
98
|
-
onOutput
|
|
287
|
+
onOutput,
|
|
288
|
+
onError
|
|
99
289
|
});
|
|
100
|
-
cbs.current = {
|
|
101
|
-
onReady,
|
|
102
|
-
onServerReady,
|
|
103
|
-
onOutput
|
|
104
|
-
};
|
|
105
|
-
const startedRef = useRef(false);
|
|
106
|
-
const previewStartedRef = useRef(false);
|
|
107
|
-
const frameRef = useRef(null);
|
|
108
290
|
useEffect(() => {
|
|
109
|
-
|
|
110
|
-
|
|
291
|
+
cbs.current = {
|
|
292
|
+
onReady,
|
|
293
|
+
onServerReady,
|
|
294
|
+
onOutput,
|
|
295
|
+
onError
|
|
296
|
+
};
|
|
297
|
+
});
|
|
298
|
+
const orchestratedFor = useRef(null);
|
|
299
|
+
useEffect(() => {
|
|
300
|
+
if (!vivari || orchestratedFor.current === vivari) return;
|
|
301
|
+
orchestratedFor.current = vivari;
|
|
302
|
+
setRunFailure(null);
|
|
111
303
|
let disposed = false;
|
|
112
|
-
const
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
const offSse = relay("vv-sse");
|
|
304
|
+
const procs = /* @__PURE__ */ new Set();
|
|
305
|
+
const fail = (error, phase) => {
|
|
306
|
+
if (disposed) return;
|
|
307
|
+
const failure = {
|
|
308
|
+
phase,
|
|
309
|
+
error: error instanceof Error ? error : new Error(String(error))
|
|
310
|
+
};
|
|
311
|
+
setRunFailure(failure);
|
|
312
|
+
cbs.current.onError?.(failure);
|
|
313
|
+
};
|
|
123
314
|
const offServer = vivari.on("server-ready", (port, url) => {
|
|
124
|
-
if (disposed
|
|
125
|
-
previewStartedRef.current = true;
|
|
126
|
-
waitForPreview(url).then(() => {
|
|
127
|
-
if (disposed) return;
|
|
128
|
-
setPreviewSrc(url);
|
|
129
|
-
cbs.current.onServerReady?.(port, url);
|
|
130
|
-
});
|
|
315
|
+
if (!disposed) cbs.current.onServerReady?.(port, url);
|
|
131
316
|
});
|
|
132
317
|
const pump = (proc) => proc.output.pipeTo(new WritableStream({ write: (chunk) => cbs.current.onOutput?.(chunk) })).catch(() => {});
|
|
318
|
+
const spawn = async (cmd, phase) => {
|
|
319
|
+
const [bin, args] = toCommand(cmd);
|
|
320
|
+
try {
|
|
321
|
+
const proc = await vivari.spawn(bin, args);
|
|
322
|
+
if (disposed) {
|
|
323
|
+
proc.kill();
|
|
324
|
+
return null;
|
|
325
|
+
}
|
|
326
|
+
procs.add(proc);
|
|
327
|
+
pump(proc);
|
|
328
|
+
return proc;
|
|
329
|
+
} catch (e) {
|
|
330
|
+
fail(e, phase);
|
|
331
|
+
return null;
|
|
332
|
+
}
|
|
333
|
+
};
|
|
133
334
|
(async () => {
|
|
134
|
-
|
|
335
|
+
try {
|
|
336
|
+
if (files) await vivari.mount(files);
|
|
337
|
+
} catch (e) {
|
|
338
|
+
return fail(e, "mount");
|
|
339
|
+
}
|
|
340
|
+
if (disposed) return;
|
|
135
341
|
cbs.current.onReady?.(vivari);
|
|
136
342
|
if (install !== false) {
|
|
137
|
-
const
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
if (
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
pump(proc);
|
|
343
|
+
const proc = await spawn(install, "install");
|
|
344
|
+
if (!proc) return;
|
|
345
|
+
const code = await proc.exit;
|
|
346
|
+
if (disposed) return;
|
|
347
|
+
if (code !== 0) {
|
|
348
|
+
const [bin, args] = toCommand(install);
|
|
349
|
+
return fail(/* @__PURE__ */ new Error(`\`${[bin, ...args].join(" ")}\` exited with code ${code}`), "install");
|
|
350
|
+
}
|
|
146
351
|
}
|
|
147
|
-
|
|
352
|
+
if (run && !disposed) await spawn(run, "run");
|
|
353
|
+
})();
|
|
148
354
|
return () => {
|
|
149
355
|
disposed = true;
|
|
150
356
|
offServer();
|
|
151
|
-
|
|
152
|
-
|
|
357
|
+
for (const p of procs) p.kill();
|
|
358
|
+
procs.clear();
|
|
153
359
|
};
|
|
154
360
|
}, [vivari]);
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
}
|
|
361
|
+
const failure = state.status === "unsupported" ? {
|
|
362
|
+
phase: "unsupported",
|
|
363
|
+
error: state.error,
|
|
364
|
+
reason: state.reason
|
|
365
|
+
} : state.status === "error" ? {
|
|
366
|
+
phase: "boot",
|
|
367
|
+
error: state.error
|
|
368
|
+
} : runFailure;
|
|
369
|
+
if (failure) return /* @__PURE__ */ jsx(Fragment, { children: renderError ? renderError(failure) : /* @__PURE__ */ jsx(FailureNotice, {
|
|
370
|
+
failure,
|
|
371
|
+
className: iframeProps.className,
|
|
372
|
+
style: iframeProps.style
|
|
373
|
+
}) });
|
|
374
|
+
if (children !== void 0) return /* @__PURE__ */ jsx(Fragment, { children: typeof children === "function" ? children(state) : children });
|
|
160
375
|
if (!showPreview) return null;
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
ref
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
allow: "cross-origin-isolated"
|
|
376
|
+
return /* @__PURE__ */ jsx(VivariPreview, {
|
|
377
|
+
...iframeProps,
|
|
378
|
+
ref,
|
|
379
|
+
vivari,
|
|
380
|
+
port: previewPort,
|
|
381
|
+
path: previewPath,
|
|
382
|
+
fallback
|
|
169
383
|
});
|
|
384
|
+
});
|
|
385
|
+
//#endregion
|
|
386
|
+
//#region src/useSpawn.ts
|
|
387
|
+
var NO_ARGS = [];
|
|
388
|
+
/**
|
|
389
|
+
* Spawn `command` in the VM.
|
|
390
|
+
*
|
|
391
|
+
* `command`/`args` are read when a run starts, so an inline array is fine and
|
|
392
|
+
* changing them does not restart anything — call `run()` for that. Any running
|
|
393
|
+
* process is killed on unmount, which is the leak `<Vivari>` used to have.
|
|
394
|
+
*/
|
|
395
|
+
function useSpawn(command, args = NO_ARGS, options = {}) {
|
|
396
|
+
const { auto = false, collect = false, onOutput, onExit, onError, vivari: explicit, ...spawnOptions } = options;
|
|
397
|
+
const instance = useVivariInstance(explicit);
|
|
398
|
+
const [status, setStatus] = useState("idle");
|
|
399
|
+
const [output, setOutput] = useState("");
|
|
400
|
+
const [exitCode, setExitCode] = useState(null);
|
|
401
|
+
const [error, setError] = useState(null);
|
|
402
|
+
const [process, setProcess] = useState(null);
|
|
403
|
+
const cbs = useRef({
|
|
404
|
+
onOutput,
|
|
405
|
+
onExit,
|
|
406
|
+
onError
|
|
407
|
+
});
|
|
408
|
+
const latest = useRef({
|
|
409
|
+
command,
|
|
410
|
+
args,
|
|
411
|
+
spawnOptions,
|
|
412
|
+
collect
|
|
413
|
+
});
|
|
414
|
+
const instanceRef = useRef(instance);
|
|
415
|
+
useEffect(() => {
|
|
416
|
+
cbs.current = {
|
|
417
|
+
onOutput,
|
|
418
|
+
onExit,
|
|
419
|
+
onError
|
|
420
|
+
};
|
|
421
|
+
latest.current = {
|
|
422
|
+
command,
|
|
423
|
+
args,
|
|
424
|
+
spawnOptions,
|
|
425
|
+
collect
|
|
426
|
+
};
|
|
427
|
+
instanceRef.current = instance;
|
|
428
|
+
});
|
|
429
|
+
const procRef = useRef(null);
|
|
430
|
+
const writerRef = useRef(null);
|
|
431
|
+
const mounted = useRef(true);
|
|
432
|
+
/** Supersedes an older run: its tail must not clobber the newer run's state. */
|
|
433
|
+
const runSeq = useRef(0);
|
|
434
|
+
const buffer = useRef([]);
|
|
435
|
+
const flushHandle = useRef(null);
|
|
436
|
+
const flushNow = useCallback(() => {
|
|
437
|
+
if (flushHandle.current !== null) {
|
|
438
|
+
cancelAnimationFrame(flushHandle.current);
|
|
439
|
+
flushHandle.current = null;
|
|
440
|
+
}
|
|
441
|
+
if (!buffer.current.length) return;
|
|
442
|
+
const pending = buffer.current.join("");
|
|
443
|
+
buffer.current.length = 0;
|
|
444
|
+
if (mounted.current) setOutput((prev) => prev + pending);
|
|
445
|
+
}, []);
|
|
446
|
+
const scheduleFlush = useCallback(() => {
|
|
447
|
+
if (flushHandle.current !== null) return;
|
|
448
|
+
flushHandle.current = requestAnimationFrame(() => {
|
|
449
|
+
flushHandle.current = null;
|
|
450
|
+
flushNow();
|
|
451
|
+
});
|
|
452
|
+
}, [flushNow]);
|
|
453
|
+
const kill = useCallback(() => {
|
|
454
|
+
const p = procRef.current;
|
|
455
|
+
if (!p) return;
|
|
456
|
+
try {
|
|
457
|
+
writerRef.current?.releaseLock();
|
|
458
|
+
} catch {}
|
|
459
|
+
writerRef.current = null;
|
|
460
|
+
p.kill();
|
|
461
|
+
}, []);
|
|
462
|
+
const run = useCallback(async (overrides) => {
|
|
463
|
+
const gen = ++runSeq.current;
|
|
464
|
+
const vm = instanceRef.current;
|
|
465
|
+
if (!vm) {
|
|
466
|
+
const err = /* @__PURE__ */ new Error("useSpawn: no Vivari instance — wrap the tree in <VivariProvider> or pass `vivari`.");
|
|
467
|
+
setStatus("error");
|
|
468
|
+
setError(err);
|
|
469
|
+
cbs.current.onError?.(err);
|
|
470
|
+
return null;
|
|
471
|
+
}
|
|
472
|
+
kill();
|
|
473
|
+
setStatus("running");
|
|
474
|
+
setError(null);
|
|
475
|
+
setExitCode(null);
|
|
476
|
+
if (latest.current.collect) {
|
|
477
|
+
buffer.current.length = 0;
|
|
478
|
+
setOutput("");
|
|
479
|
+
}
|
|
480
|
+
let proc;
|
|
481
|
+
try {
|
|
482
|
+
const l = latest.current;
|
|
483
|
+
proc = await vm.spawn(overrides?.command ?? l.command, overrides?.args ?? l.args, overrides?.options ?? l.spawnOptions);
|
|
484
|
+
} catch (e) {
|
|
485
|
+
if (gen !== runSeq.current) return null;
|
|
486
|
+
const err = e instanceof Error ? e : new Error(String(e));
|
|
487
|
+
setStatus("error");
|
|
488
|
+
setError(err);
|
|
489
|
+
cbs.current.onError?.(err);
|
|
490
|
+
return null;
|
|
491
|
+
}
|
|
492
|
+
if (gen !== runSeq.current || !mounted.current) {
|
|
493
|
+
proc.kill();
|
|
494
|
+
return null;
|
|
495
|
+
}
|
|
496
|
+
procRef.current = proc;
|
|
497
|
+
writerRef.current = null;
|
|
498
|
+
setProcess(proc);
|
|
499
|
+
proc.output.pipeTo(new WritableStream({ write: (chunk) => {
|
|
500
|
+
if (gen !== runSeq.current) return;
|
|
501
|
+
cbs.current.onOutput?.(chunk);
|
|
502
|
+
if (latest.current.collect) {
|
|
503
|
+
buffer.current.push(chunk);
|
|
504
|
+
scheduleFlush();
|
|
505
|
+
}
|
|
506
|
+
} })).catch(() => {});
|
|
507
|
+
const code = await proc.exit;
|
|
508
|
+
if (gen !== runSeq.current) return code;
|
|
509
|
+
flushNow();
|
|
510
|
+
procRef.current = null;
|
|
511
|
+
if (mounted.current) {
|
|
512
|
+
setProcess(null);
|
|
513
|
+
setExitCode(code);
|
|
514
|
+
setStatus("exited");
|
|
515
|
+
}
|
|
516
|
+
cbs.current.onExit?.(code);
|
|
517
|
+
return code;
|
|
518
|
+
}, [
|
|
519
|
+
kill,
|
|
520
|
+
flushNow,
|
|
521
|
+
scheduleFlush
|
|
522
|
+
]);
|
|
523
|
+
const write = useCallback((chunk) => {
|
|
524
|
+
const p = procRef.current;
|
|
525
|
+
if (!p) return;
|
|
526
|
+
writerRef.current ??= p.input.getWriter();
|
|
527
|
+
writerRef.current.write(chunk).catch(() => {});
|
|
528
|
+
}, []);
|
|
529
|
+
useEffect(() => {
|
|
530
|
+
mounted.current = true;
|
|
531
|
+
return () => {
|
|
532
|
+
mounted.current = false;
|
|
533
|
+
if (flushHandle.current !== null) cancelAnimationFrame(flushHandle.current);
|
|
534
|
+
runSeq.current++;
|
|
535
|
+
kill();
|
|
536
|
+
};
|
|
537
|
+
}, [kill]);
|
|
538
|
+
const autoRanFor = useRef(null);
|
|
539
|
+
useEffect(() => {
|
|
540
|
+
if (!auto || !instance || autoRanFor.current === instance) return;
|
|
541
|
+
autoRanFor.current = instance;
|
|
542
|
+
run();
|
|
543
|
+
}, [
|
|
544
|
+
auto,
|
|
545
|
+
instance,
|
|
546
|
+
run
|
|
547
|
+
]);
|
|
548
|
+
return {
|
|
549
|
+
status,
|
|
550
|
+
output,
|
|
551
|
+
exitCode,
|
|
552
|
+
error,
|
|
553
|
+
process,
|
|
554
|
+
run,
|
|
555
|
+
kill,
|
|
556
|
+
write
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
//#endregion
|
|
560
|
+
//#region src/useVivariFile.ts
|
|
561
|
+
/**
|
|
562
|
+
* Read/write a UTF-8 file as React state.
|
|
563
|
+
*
|
|
564
|
+
* const [source, setSource, { status, save }] = useVivariFile("/src/App.jsx");
|
|
565
|
+
*
|
|
566
|
+
* Text only, on purpose: binary content isn't editable as a React value, so read
|
|
567
|
+
* it with `vivari.fs.readFile(path)` (no encoding) instead.
|
|
568
|
+
*/
|
|
569
|
+
function useVivariFile(path, options = {}) {
|
|
570
|
+
const { debounce = 250, initialContents, vivari: explicit, onError } = options;
|
|
571
|
+
const instance = useVivariInstance(explicit);
|
|
572
|
+
const [contents, setContents] = useState(initialContents ?? "");
|
|
573
|
+
const [status, setStatus] = useState("idle");
|
|
574
|
+
const [error, setError] = useState(null);
|
|
575
|
+
const latest = useRef({
|
|
576
|
+
debounce,
|
|
577
|
+
initialContents,
|
|
578
|
+
onError
|
|
579
|
+
});
|
|
580
|
+
const instanceRef = useRef(instance);
|
|
581
|
+
const mounted = useRef(true);
|
|
582
|
+
useEffect(() => {
|
|
583
|
+
latest.current = {
|
|
584
|
+
debounce,
|
|
585
|
+
initialContents,
|
|
586
|
+
onError
|
|
587
|
+
};
|
|
588
|
+
instanceRef.current = instance;
|
|
589
|
+
});
|
|
590
|
+
/** The value awaiting a write, or `null` when there is nothing outstanding. */
|
|
591
|
+
const pending = useRef(null);
|
|
592
|
+
const timer = useRef(void 0);
|
|
593
|
+
const clearTimer = useCallback(() => {
|
|
594
|
+
if (timer.current !== void 0) {
|
|
595
|
+
clearTimeout(timer.current);
|
|
596
|
+
timer.current = void 0;
|
|
597
|
+
}
|
|
598
|
+
}, []);
|
|
599
|
+
const fail = useCallback((e) => {
|
|
600
|
+
const err = e instanceof Error ? e : new Error(String(e));
|
|
601
|
+
if (mounted.current) {
|
|
602
|
+
setStatus("error");
|
|
603
|
+
setError(err);
|
|
604
|
+
}
|
|
605
|
+
latest.current.onError?.(err);
|
|
606
|
+
}, []);
|
|
607
|
+
const save = useCallback(async () => {
|
|
608
|
+
const vm = instanceRef.current;
|
|
609
|
+
const next = pending.current;
|
|
610
|
+
clearTimer();
|
|
611
|
+
if (!vm || next === null) return;
|
|
612
|
+
pending.current = null;
|
|
613
|
+
if (mounted.current) setStatus("saving");
|
|
614
|
+
try {
|
|
615
|
+
await vm.fs.writeFile(path, next);
|
|
616
|
+
if (mounted.current) {
|
|
617
|
+
setStatus("saved");
|
|
618
|
+
setError(null);
|
|
619
|
+
}
|
|
620
|
+
} catch (e) {
|
|
621
|
+
fail(e);
|
|
622
|
+
}
|
|
623
|
+
}, [
|
|
624
|
+
path,
|
|
625
|
+
clearTimer,
|
|
626
|
+
fail
|
|
627
|
+
]);
|
|
628
|
+
const reload = useCallback(async () => {
|
|
629
|
+
const vm = instanceRef.current;
|
|
630
|
+
if (!vm) return;
|
|
631
|
+
pending.current = null;
|
|
632
|
+
clearTimer();
|
|
633
|
+
setStatus("loading");
|
|
634
|
+
try {
|
|
635
|
+
const text = await vm.fs.readFile(path, "utf-8");
|
|
636
|
+
if (!mounted.current) return;
|
|
637
|
+
setContents(text);
|
|
638
|
+
setStatus("saved");
|
|
639
|
+
setError(null);
|
|
640
|
+
} catch (e) {
|
|
641
|
+
fail(e);
|
|
642
|
+
}
|
|
643
|
+
}, [
|
|
644
|
+
path,
|
|
645
|
+
clearTimer,
|
|
646
|
+
fail
|
|
647
|
+
]);
|
|
648
|
+
const saveRef = useRef(save);
|
|
649
|
+
useEffect(() => {
|
|
650
|
+
saveRef.current = save;
|
|
651
|
+
});
|
|
652
|
+
const update = useCallback((next) => {
|
|
653
|
+
setContents(next);
|
|
654
|
+
pending.current = next;
|
|
655
|
+
clearTimer();
|
|
656
|
+
if (latest.current.debounce <= 0) {
|
|
657
|
+
saveRef.current();
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
timer.current = setTimeout(() => {
|
|
661
|
+
timer.current = void 0;
|
|
662
|
+
saveRef.current();
|
|
663
|
+
}, latest.current.debounce);
|
|
664
|
+
}, [clearTimer]);
|
|
665
|
+
useEffect(() => {
|
|
666
|
+
mounted.current = true;
|
|
667
|
+
return () => {
|
|
668
|
+
mounted.current = false;
|
|
669
|
+
saveRef.current();
|
|
670
|
+
};
|
|
671
|
+
}, [path]);
|
|
672
|
+
useEffect(() => {
|
|
673
|
+
const vm = instance;
|
|
674
|
+
if (!vm) return;
|
|
675
|
+
let cancelled = false;
|
|
676
|
+
setStatus("loading");
|
|
677
|
+
(async () => {
|
|
678
|
+
try {
|
|
679
|
+
const exists = await vm.fs.exists(path);
|
|
680
|
+
const seed = latest.current.initialContents;
|
|
681
|
+
if (!exists && seed !== void 0) await vm.fs.writeFile(path, seed);
|
|
682
|
+
const text = exists ? await vm.fs.readFile(path, "utf-8") : seed ?? "";
|
|
683
|
+
if (cancelled) return;
|
|
684
|
+
setContents(text);
|
|
685
|
+
setStatus("saved");
|
|
686
|
+
setError(null);
|
|
687
|
+
} catch (e) {
|
|
688
|
+
if (!cancelled) fail(e);
|
|
689
|
+
}
|
|
690
|
+
})();
|
|
691
|
+
return () => {
|
|
692
|
+
cancelled = true;
|
|
693
|
+
};
|
|
694
|
+
}, [
|
|
695
|
+
instance,
|
|
696
|
+
path,
|
|
697
|
+
fail
|
|
698
|
+
]);
|
|
699
|
+
return [
|
|
700
|
+
contents,
|
|
701
|
+
update,
|
|
702
|
+
useMemo(() => ({
|
|
703
|
+
status,
|
|
704
|
+
error,
|
|
705
|
+
save,
|
|
706
|
+
reload
|
|
707
|
+
}), [
|
|
708
|
+
status,
|
|
709
|
+
error,
|
|
710
|
+
save,
|
|
711
|
+
reload
|
|
712
|
+
])
|
|
713
|
+
];
|
|
714
|
+
}
|
|
715
|
+
//#endregion
|
|
716
|
+
//#region src/useVivariDir.ts
|
|
717
|
+
var NO_ENTRIES = [];
|
|
718
|
+
/**
|
|
719
|
+
* List `path`, and keep the listing current as the VFS changes underneath it.
|
|
720
|
+
*
|
|
721
|
+
* const { entries, status } = useVivariDir("/src");
|
|
722
|
+
*
|
|
723
|
+
* The watch is non-recursive: only entries appearing, disappearing or changing
|
|
724
|
+
* directly inside `path` can alter this listing, so a deep write doesn't wake it.
|
|
725
|
+
*/
|
|
726
|
+
function useVivariDir(path, options = {}) {
|
|
727
|
+
const { debounce = 100, vivari: explicit, onError } = options;
|
|
728
|
+
const instance = useVivariInstance(explicit);
|
|
729
|
+
const [entries, setEntries] = useState(NO_ENTRIES);
|
|
730
|
+
const [status, setStatus] = useState("idle");
|
|
731
|
+
const [error, setError] = useState(null);
|
|
732
|
+
const latest = useRef({
|
|
733
|
+
debounce,
|
|
734
|
+
onError
|
|
735
|
+
});
|
|
736
|
+
const instanceRef = useRef(instance);
|
|
737
|
+
const mounted = useRef(true);
|
|
738
|
+
useEffect(() => {
|
|
739
|
+
latest.current = {
|
|
740
|
+
debounce,
|
|
741
|
+
onError
|
|
742
|
+
};
|
|
743
|
+
instanceRef.current = instance;
|
|
744
|
+
});
|
|
745
|
+
/** Supersedes an in-flight read, so a slow one can't overwrite a newer listing. */
|
|
746
|
+
const readSeq = useRef(0);
|
|
747
|
+
const refresh = useCallback(async () => {
|
|
748
|
+
const vm = instanceRef.current;
|
|
749
|
+
if (!vm) return;
|
|
750
|
+
const gen = ++readSeq.current;
|
|
751
|
+
try {
|
|
752
|
+
const next = await vm.fs.readdir(path, { withFileTypes: true });
|
|
753
|
+
if (!mounted.current || gen !== readSeq.current) return;
|
|
754
|
+
setEntries(next);
|
|
755
|
+
setStatus("ready");
|
|
756
|
+
setError(null);
|
|
757
|
+
} catch (e) {
|
|
758
|
+
const err = e instanceof Error ? e : new Error(String(e));
|
|
759
|
+
if (mounted.current && gen === readSeq.current) {
|
|
760
|
+
setStatus("error");
|
|
761
|
+
setError(err);
|
|
762
|
+
}
|
|
763
|
+
latest.current.onError?.(err);
|
|
764
|
+
}
|
|
765
|
+
}, [path]);
|
|
766
|
+
const refreshRef = useRef(refresh);
|
|
767
|
+
useEffect(() => {
|
|
768
|
+
refreshRef.current = refresh;
|
|
769
|
+
});
|
|
770
|
+
useEffect(() => {
|
|
771
|
+
mounted.current = true;
|
|
772
|
+
return () => {
|
|
773
|
+
mounted.current = false;
|
|
774
|
+
};
|
|
775
|
+
}, []);
|
|
776
|
+
useEffect(() => {
|
|
777
|
+
if (!instance) return;
|
|
778
|
+
setStatus("loading");
|
|
779
|
+
refresh();
|
|
780
|
+
let timer;
|
|
781
|
+
const watcher = instance.fs.watch(path, { recursive: false }, () => {
|
|
782
|
+
if (latest.current.debounce <= 0) {
|
|
783
|
+
refreshRef.current();
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
786
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
787
|
+
timer = setTimeout(() => {
|
|
788
|
+
timer = void 0;
|
|
789
|
+
refreshRef.current();
|
|
790
|
+
}, latest.current.debounce);
|
|
791
|
+
});
|
|
792
|
+
return () => {
|
|
793
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
794
|
+
watcher.close();
|
|
795
|
+
};
|
|
796
|
+
}, [
|
|
797
|
+
instance,
|
|
798
|
+
path,
|
|
799
|
+
refresh
|
|
800
|
+
]);
|
|
801
|
+
return useMemo(() => ({
|
|
802
|
+
entries,
|
|
803
|
+
status,
|
|
804
|
+
error,
|
|
805
|
+
refresh
|
|
806
|
+
}), [
|
|
807
|
+
entries,
|
|
808
|
+
status,
|
|
809
|
+
error,
|
|
810
|
+
refresh
|
|
811
|
+
]);
|
|
170
812
|
}
|
|
171
813
|
//#endregion
|
|
172
|
-
export { Vivari, useVivari };
|
|
814
|
+
export { Vivari, VivariError, VivariFsError, VivariPreview, VivariProvider, isCrossOriginIsolated, resetVfs, useSpawn, useVivari, useVivariContext, useVivariDir, useVivariFile, useVivariInstance };
|