@volter/browser-python 0.1.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.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +14 -0
  3. package/dist/asgi-bridge.d.ts +3 -0
  4. package/dist/asgi-bridge.d.ts.map +1 -0
  5. package/dist/asgi-bridge.js +307 -0
  6. package/dist/asgi-bridge.js.map +1 -0
  7. package/dist/command.d.ts +20 -0
  8. package/dist/command.d.ts.map +1 -0
  9. package/dist/command.js +154 -0
  10. package/dist/command.js.map +1 -0
  11. package/dist/filesystem.d.ts +9 -0
  12. package/dist/filesystem.d.ts.map +1 -0
  13. package/dist/filesystem.js +96 -0
  14. package/dist/filesystem.js.map +1 -0
  15. package/dist/index.d.ts +4 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +3 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/package-manager.d.ts +8 -0
  20. package/dist/package-manager.d.ts.map +1 -0
  21. package/dist/package-manager.js +103 -0
  22. package/dist/package-manager.js.map +1 -0
  23. package/dist/process-host.d.ts +27 -0
  24. package/dist/process-host.d.ts.map +1 -0
  25. package/dist/process-host.js +326 -0
  26. package/dist/process-host.js.map +1 -0
  27. package/dist/protocol.d.ts +169 -0
  28. package/dist/protocol.d.ts.map +1 -0
  29. package/dist/protocol.js +2 -0
  30. package/dist/protocol.js.map +1 -0
  31. package/dist/pyodide-runtime.d.ts +37 -0
  32. package/dist/pyodide-runtime.d.ts.map +1 -0
  33. package/dist/pyodide-runtime.js +13 -0
  34. package/dist/pyodide-runtime.js.map +1 -0
  35. package/dist/server-host.d.ts +21 -0
  36. package/dist/server-host.d.ts.map +1 -0
  37. package/dist/server-host.js +526 -0
  38. package/dist/server-host.js.map +1 -0
  39. package/dist/sqlite-coherence.d.ts +19 -0
  40. package/dist/sqlite-coherence.d.ts.map +1 -0
  41. package/dist/sqlite-coherence.js +167 -0
  42. package/dist/sqlite-coherence.js.map +1 -0
  43. package/dist/subprocess-bridge.d.ts +12 -0
  44. package/dist/subprocess-bridge.d.ts.map +1 -0
  45. package/dist/subprocess-bridge.js +407 -0
  46. package/dist/subprocess-bridge.js.map +1 -0
  47. package/dist/worker.d.ts +2 -0
  48. package/dist/worker.d.ts.map +1 -0
  49. package/dist/worker.js +251 -0
  50. package/dist/worker.js.map +1 -0
  51. package/dist/wsgi-bridge.d.ts +21 -0
  52. package/dist/wsgi-bridge.d.ts.map +1 -0
  53. package/dist/wsgi-bridge.js +268 -0
  54. package/dist/wsgi-bridge.js.map +1 -0
  55. package/package.json +23 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Volter Browser Substrate contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,14 @@
1
+ # `@volter/browser-python`
2
+
3
+ The Pyodide execution engine for Browser Substrate. It registers `python`,
4
+ `python3`, `pip`, `pip3`, and `uvicorn` with the shared process host and keeps
5
+ the browser workspace coherent across its worker boundary.
6
+
7
+ Supported application paths include scripts, `python -c`, hash-resolved
8
+ Micropip installs, static HTTP servers, Flask/WSGI, ASGI HTTP streaming and
9
+ WebSockets, lifecycle events, SQLite file coherence, and routed subprocesses.
10
+ Virtual servers use the same port and sandbox bridge as Node and WALI; they do
11
+ not open a host-machine listener.
12
+
13
+ Arbitrary Python socket listeners, editable/VCS installs, and direct wheel URLs
14
+ are outside the current scope and fail explicitly.
@@ -0,0 +1,3 @@
1
+ /** Python-side ASGI lifecycle, HTTP, streaming, and WebSocket adapter. */
2
+ export declare const ASGI_BRIDGE: string;
3
+ //# sourceMappingURL=asgi-bridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"asgi-bridge.d.ts","sourceRoot":"","sources":["../src/asgi-bridge.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,eAAO,MAAM,WAAW,QAgTvB,CAAC"}
@@ -0,0 +1,307 @@
1
+ /** Python-side ASGI lifecycle, HTTP, streaming, and WebSocket adapter. */
2
+ export const ASGI_BRIDGE = String.raw `
3
+ import asyncio, base64, json
4
+ from urllib.parse import urlsplit
5
+
6
+ async def __browser_runtime_start_asgi_lifespan():
7
+ queue = asyncio.Queue()
8
+ ready = asyncio.Event()
9
+ shutdown_ready = asyncio.Event()
10
+ outcome = {"startup_error": None, "shutdown_error": None, "responded": False, "unsupported": False}
11
+ lifespan_state = {}
12
+
13
+ async def receive():
14
+ return await queue.get()
15
+
16
+ async def send(message):
17
+ outcome["responded"] = True
18
+ kind = message.get("type")
19
+ if kind == "lifespan.startup.complete":
20
+ ready.set()
21
+ elif kind == "lifespan.startup.failed":
22
+ outcome["startup_error"] = str(message.get("message", "ASGI lifespan startup failed"))
23
+ ready.set()
24
+ elif kind == "lifespan.shutdown.complete":
25
+ shutdown_ready.set()
26
+ elif kind == "lifespan.shutdown.failed":
27
+ outcome["shutdown_error"] = str(message.get("message", "ASGI lifespan shutdown failed"))
28
+ shutdown_ready.set()
29
+
30
+ async def run():
31
+ try:
32
+ await globals()["__browser_runtime_asgi_app"](
33
+ {"type": "lifespan", "asgi": {"version": "3.0", "spec_version": "2.0"}, "state": lifespan_state},
34
+ receive,
35
+ send,
36
+ )
37
+ except BaseException as error:
38
+ if outcome["responded"]:
39
+ outcome["startup_error"] = str(error)
40
+ else:
41
+ outcome["unsupported"] = True
42
+ ready.set()
43
+ shutdown_ready.set()
44
+
45
+ task = asyncio.create_task(run())
46
+ globals()["__browser_runtime_asgi_lifespan_task"] = task
47
+ globals()["__browser_runtime_asgi_lifespan_queue"] = queue
48
+ globals()["__browser_runtime_asgi_lifespan_outcome"] = outcome
49
+ globals()["__browser_runtime_asgi_lifespan_shutdown_ready"] = shutdown_ready
50
+ globals()["__browser_runtime_asgi_lifespan_state"] = lifespan_state
51
+ await queue.put({"type": "lifespan.startup"})
52
+ try:
53
+ await asyncio.wait_for(ready.wait(), timeout=5)
54
+ except TimeoutError:
55
+ task.cancel()
56
+ raise RuntimeError("ASGI lifespan startup timed out")
57
+ if outcome["startup_error"] is not None:
58
+ task.cancel()
59
+ raise RuntimeError(outcome["startup_error"])
60
+
61
+ async def __browser_runtime_stop_asgi_lifespan():
62
+ task = globals().get("__browser_runtime_asgi_lifespan_task")
63
+ queue = globals().get("__browser_runtime_asgi_lifespan_queue")
64
+ outcome = globals().get("__browser_runtime_asgi_lifespan_outcome", {})
65
+ shutdown_ready = globals().get("__browser_runtime_asgi_lifespan_shutdown_ready")
66
+ if task is None or queue is None or shutdown_ready is None or outcome.get("unsupported") or task.done():
67
+ return
68
+ await queue.put({"type": "lifespan.shutdown"})
69
+ try:
70
+ await asyncio.wait_for(shutdown_ready.wait(), timeout=5)
71
+ except TimeoutError:
72
+ task.cancel()
73
+ raise RuntimeError("ASGI lifespan shutdown timed out")
74
+ if outcome.get("shutdown_error") is not None:
75
+ task.cancel()
76
+ raise RuntimeError(outcome["shutdown_error"])
77
+ await asyncio.wait_for(task, timeout=5)
78
+
79
+ __browser_runtime_asgi_sockets = {}
80
+
81
+ async def __browser_runtime_stop_asgi_websockets():
82
+ sockets = list(globals()["__browser_runtime_asgi_sockets"].values())
83
+ if not sockets:
84
+ return
85
+ for socket in sockets:
86
+ await socket["queue"].put({"type": "websocket.disconnect", "code": 1001, "reason": "Server shutdown"})
87
+ tasks = [socket["task"] for socket in sockets]
88
+ try:
89
+ await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), timeout=2)
90
+ except TimeoutError:
91
+ for task in tasks:
92
+ if not task.done():
93
+ task.cancel()
94
+
95
+ async def __browser_runtime_open_asgi_websocket(payload_json):
96
+ payload = json.loads(payload_json)
97
+ connection_id = int(payload["connectionId"])
98
+ parsed = urlsplit(payload["path"])
99
+ protocols = [str(value) for value in payload.get("protocols", [])]
100
+ queue = asyncio.Queue()
101
+ state = {"accepted": False, "closed": False}
102
+
103
+ async def receive():
104
+ return await queue.get()
105
+
106
+ async def send(message):
107
+ kind = message.get("type")
108
+ if kind == "websocket.accept":
109
+ if state["accepted"] or state["closed"]:
110
+ raise RuntimeError("ASGI WebSocket accepted more than once")
111
+ state["accepted"] = True
112
+ globals()["__browser_runtime_asgi_websocket_callback"](json.dumps({
113
+ "type": "opened",
114
+ "connectionId": connection_id,
115
+ "protocol": str(message.get("subprotocol") or ""),
116
+ }))
117
+ elif kind == "websocket.send":
118
+ if not state["accepted"] or state["closed"]:
119
+ raise RuntimeError("ASGI WebSocket sent data before accept or after close")
120
+ if message.get("bytes") is not None:
121
+ frame = {
122
+ "type": "message",
123
+ "connectionId": connection_id,
124
+ "kind": "binary",
125
+ "base64": base64.b64encode(bytes(message["bytes"])).decode("ascii"),
126
+ }
127
+ else:
128
+ frame = {
129
+ "type": "message",
130
+ "connectionId": connection_id,
131
+ "kind": "text",
132
+ "text": str(message.get("text", "")),
133
+ }
134
+ globals()["__browser_runtime_asgi_websocket_callback"](json.dumps(frame))
135
+ elif kind == "websocket.close":
136
+ if state["closed"]:
137
+ return
138
+ state["closed"] = True
139
+ globals()["__browser_runtime_asgi_websocket_callback"](json.dumps({
140
+ "type": "close",
141
+ "connectionId": connection_id,
142
+ "code": int(message.get("code", 1000)),
143
+ "reason": str(message.get("reason", "")),
144
+ "clean": True,
145
+ }))
146
+
147
+ async def run():
148
+ try:
149
+ scope = {
150
+ "type": "websocket",
151
+ "asgi": {"version": "3.0", "spec_version": "2.3"},
152
+ "scheme": "ws",
153
+ "path": parsed.path,
154
+ "raw_path": parsed.path.encode("utf-8"),
155
+ "query_string": parsed.query.encode("ascii"),
156
+ "root_path": "",
157
+ "headers": [],
158
+ "server": ("localhost", int(globals()["__browser_runtime_asgi_port"])),
159
+ "client": ("127.0.0.1", 0),
160
+ "subprotocols": protocols,
161
+ "state": dict(globals().get("__browser_runtime_asgi_lifespan_state", {})),
162
+ }
163
+ await globals()["__browser_runtime_asgi_app"](scope, receive, send)
164
+ except BaseException as error:
165
+ globals()["__browser_runtime_asgi_websocket_callback"](json.dumps({
166
+ "type": "error",
167
+ "connectionId": connection_id,
168
+ "error": str(error),
169
+ }))
170
+ if not state["closed"]:
171
+ state["closed"] = True
172
+ globals()["__browser_runtime_asgi_websocket_callback"](json.dumps({
173
+ "type": "close",
174
+ "connectionId": connection_id,
175
+ "code": 1011,
176
+ "reason": "Python ASGI WebSocket failed",
177
+ "clean": False,
178
+ }))
179
+ finally:
180
+ if not state["closed"]:
181
+ state["closed"] = True
182
+ globals()["__browser_runtime_asgi_websocket_callback"](json.dumps({
183
+ "type": "close",
184
+ "connectionId": connection_id,
185
+ "code": 1000,
186
+ "reason": "",
187
+ "clean": True,
188
+ }))
189
+ globals()["__browser_runtime_asgi_sockets"].pop(connection_id, None)
190
+
191
+ task = asyncio.create_task(run())
192
+ globals()["__browser_runtime_asgi_sockets"][connection_id] = {"queue": queue, "task": task}
193
+ await queue.put({"type": "websocket.connect"})
194
+ await asyncio.sleep(0)
195
+
196
+ async def __browser_runtime_asgi_websocket_event(payload_json):
197
+ payload = json.loads(payload_json)
198
+ connection_id = int(payload["connectionId"])
199
+ socket = globals()["__browser_runtime_asgi_sockets"].get(connection_id)
200
+ if socket is None:
201
+ return
202
+ if payload["type"] == "websocket-message":
203
+ data = payload["data"]
204
+ if data["kind"] == "binary":
205
+ event = {"type": "websocket.receive", "bytes": base64.b64decode(data.get("base64", ""))}
206
+ else:
207
+ event = {"type": "websocket.receive", "text": str(data.get("text", ""))}
208
+ else:
209
+ event = {
210
+ "type": "websocket.disconnect",
211
+ "code": int(payload.get("code", 1000)),
212
+ "reason": str(payload.get("reason", "")),
213
+ }
214
+ await socket["queue"].put(event)
215
+ await asyncio.sleep(0)
216
+
217
+ def __browser_runtime_asgi_headers(response_start):
218
+ response_headers = {}
219
+ for raw_name, raw_value in response_start.get("headers", []):
220
+ name = bytes(raw_name).decode("latin-1")
221
+ value = bytes(raw_value).decode("latin-1")
222
+ if name in response_headers:
223
+ existing = response_headers[name]
224
+ response_headers[name] = existing + [value] if isinstance(existing, list) else [existing, value]
225
+ else:
226
+ response_headers[name] = value
227
+ return response_headers
228
+
229
+ async def __browser_runtime_handle_asgi(payload_json, streaming=False):
230
+ payload = json.loads(payload_json)
231
+ parsed = urlsplit(payload["url"])
232
+ body = base64.b64decode(payload.get("bodyBase64", ""))
233
+ request_headers = [
234
+ (str(name).lower().encode("latin-1"), str(value).encode("latin-1"))
235
+ for name, value in payload.get("headers", {}).items()
236
+ ]
237
+ scope = {
238
+ "type": "http",
239
+ "asgi": {"version": "3.0", "spec_version": "2.3"},
240
+ "http_version": "1.1",
241
+ "method": payload["method"],
242
+ "scheme": "http",
243
+ "path": parsed.path,
244
+ "raw_path": parsed.path.encode("utf-8"),
245
+ "query_string": parsed.query.encode("ascii"),
246
+ "root_path": "",
247
+ "headers": request_headers,
248
+ "server": ("localhost", int(globals()["__browser_runtime_asgi_port"])),
249
+ "client": ("127.0.0.1", 0),
250
+ "state": dict(globals().get("__browser_runtime_asgi_lifespan_state", {})),
251
+ }
252
+ received = False
253
+ response_start = None
254
+ response_chunks = []
255
+ stream_started = False
256
+
257
+ def start_stream():
258
+ nonlocal response_start, stream_started
259
+ if stream_started:
260
+ return
261
+ response_start = response_start or {"status": 500, "headers": []}
262
+ globals()["__browser_runtime_asgi_stream_callback"](json.dumps({
263
+ "type": "start",
264
+ "statusCode": int(response_start["status"]),
265
+ "statusMessage": "",
266
+ "headers": __browser_runtime_asgi_headers(response_start),
267
+ }))
268
+ stream_started = True
269
+
270
+ async def receive():
271
+ nonlocal received
272
+ if received:
273
+ return {"type": "http.disconnect"}
274
+ received = True
275
+ return {"type": "http.request", "body": body, "more_body": False}
276
+
277
+ async def send(message):
278
+ nonlocal response_start
279
+ if message["type"] == "http.response.start":
280
+ response_start = message
281
+ if streaming:
282
+ start_stream()
283
+ elif message["type"] == "http.response.body":
284
+ chunk = bytes(message.get("body", b""))
285
+ if streaming:
286
+ start_stream()
287
+ if chunk:
288
+ globals()["__browser_runtime_asgi_stream_callback"](json.dumps({
289
+ "type": "chunk",
290
+ "bodyBase64": base64.b64encode(chunk).decode("ascii"),
291
+ }))
292
+ else:
293
+ response_chunks.append(chunk)
294
+
295
+ await globals()["__browser_runtime_asgi_app"](scope, receive, send)
296
+ response_start = response_start or {"status": 500, "headers": []}
297
+ if streaming:
298
+ start_stream()
299
+ return "{}"
300
+ return json.dumps({
301
+ "statusCode": int(response_start["status"]),
302
+ "statusMessage": "",
303
+ "headers": __browser_runtime_asgi_headers(response_start),
304
+ "bodyBase64": base64.b64encode(b"".join(response_chunks)).decode("ascii"),
305
+ })
306
+ `;
307
+ //# sourceMappingURL=asgi-bridge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"asgi-bridge.js","sourceRoot":"","sources":["../src/asgi-bridge.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,MAAM,CAAC,MAAM,WAAW,GAAG,MAAM,CAAC,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgTpC,CAAC"}
@@ -0,0 +1,20 @@
1
+ import type { BrowserFileSystem } from "@volter/browser-runtime/browser-filesystem.js";
2
+ import type { BrowserProcessResult, BrowserProcessRunOptions } from "@volter/browser-runtime/browser-process.js";
3
+ import type { PythonServerAttachment } from "./protocol.js";
4
+ export interface BrowserPythonCommandOptions {
5
+ cwd?: string;
6
+ env?: Readonly<Record<string, string>>;
7
+ server: PythonServerAttachment;
8
+ onFilesystemCommit?(filesystem: BrowserFileSystem): void | Promise<void>;
9
+ }
10
+ /** Runs CPython/Pyodide in a worker against the shared project and process host. */
11
+ export declare class BrowserPythonCommand {
12
+ private readonly filesystem;
13
+ private readonly options;
14
+ private filesystemCommitTail;
15
+ constructor(filesystem: BrowserFileSystem, options: BrowserPythonCommandOptions);
16
+ run: (argv: readonly string[], options?: BrowserProcessRunOptions) => Promise<BrowserProcessResult>;
17
+ private applyResult;
18
+ private persistFilesystem;
19
+ }
20
+ //# sourceMappingURL=command.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command.d.ts","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAA6B,MAAM,+CAA+C,CAAC;AAKlH,OAAO,KAAK,EACV,oBAAoB,EACpB,wBAAwB,EACzB,MAAM,4CAA4C,CAAC;AACpD,OAAO,KAAK,EAAoB,sBAAsB,EAAuB,MAAM,eAAe,CAAC;AAUnG,MAAM,WAAW,2BAA2B;IAC1C,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACvC,MAAM,EAAE,sBAAsB,CAAC;IAC/B,kBAAkB,CAAC,CAAC,UAAU,EAAE,iBAAiB,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1E;AAED,oFAAoF;AACpF,qBAAa,oBAAoB;IAI7B,OAAO,CAAC,QAAQ,CAAC,UAAU;IAC3B,OAAO,CAAC,QAAQ,CAAC,OAAO;IAJ1B,OAAO,CAAC,oBAAoB,CAAoC;gBAG7C,UAAU,EAAE,iBAAiB,EAC7B,OAAO,EAAE,2BAA2B;IAGvD,GAAG,GAAU,MAAM,SAAS,MAAM,EAAE,EAAE,UAAS,wBAA6B,KAAG,OAAO,CAAC,oBAAoB,CAAC,CAyF1G;YAEY,WAAW;YAaX,iBAAiB;CAKhC"}
@@ -0,0 +1,154 @@
1
+ import { applyProcessFilesystemPatch, createProcessFilesystemPatch, } from "@volter/browser-runtime/browser-process-filesystem.js";
2
+ import { createBrowserFileLockChannel, sharedBrowserFileLockCoordinator, } from "@volter/browser-runtime/browser-file-locks.js";
3
+ import { createBrowserFileCoherenceChannel, sharedBrowserFileCoherenceCoordinator, } from "@volter/browser-runtime/browser-file-coherence.js";
4
+ /** Runs CPython/Pyodide in a worker against the shared project and process host. */
5
+ export class BrowserPythonCommand {
6
+ filesystem;
7
+ options;
8
+ filesystemCommitTail = Promise.resolve();
9
+ constructor(filesystem, options) {
10
+ this.filesystem = filesystem;
11
+ this.options = options;
12
+ }
13
+ run = async (argv, options = {}) => {
14
+ if (options.signal?.aborted)
15
+ return Promise.resolve({ stdout: "", stderr: "", exitCode: 130 });
16
+ const stdin = await collectStdin(options);
17
+ if (options.signal?.aborted)
18
+ return { stdout: "", stderr: "", exitCode: 130 };
19
+ const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module", name: "browser-python" });
20
+ const channel = new MessageChannel();
21
+ const releaseServer = this.options.server.attach(channel.port1);
22
+ const lockOwner = `python:${crypto.randomUUID()}`;
23
+ const lockChannel = createBrowserFileLockChannel();
24
+ const releaseFileLocks = sharedBrowserFileLockCoordinator.attach(lockChannel.server, lockOwner);
25
+ const coherenceChannel = createBrowserFileCoherenceChannel();
26
+ const releaseFileCoherence = sharedBrowserFileCoherenceCoordinator.attach(coherenceChannel.server, this.filesystem, () => this.persistFilesystem());
27
+ const before = this.filesystem.toSnapshot();
28
+ let synchronized = before;
29
+ let commitQueue = Promise.resolve();
30
+ let stdout = "";
31
+ let stderr = "";
32
+ return new Promise((resolve) => {
33
+ let finished = false;
34
+ let abortTimeout;
35
+ const finish = (result) => {
36
+ if (finished)
37
+ return;
38
+ finished = true;
39
+ if (abortTimeout !== undefined)
40
+ clearTimeout(abortTimeout);
41
+ options.signal?.removeEventListener("abort", abort);
42
+ releaseServer();
43
+ worker.terminate();
44
+ releaseFileCoherence();
45
+ releaseFileLocks();
46
+ resolve(result);
47
+ };
48
+ const abort = () => {
49
+ worker.postMessage({ type: "shutdown" });
50
+ abortTimeout = setTimeout(() => finish({ stdout, stderr, exitCode: 130 }), 12_000);
51
+ };
52
+ options.signal?.addEventListener("abort", abort, { once: true });
53
+ worker.onmessage = (event) => {
54
+ const message = event.data;
55
+ if (message.type === "stdout") {
56
+ stdout += message.chunk;
57
+ options.onStdout?.(message.chunk);
58
+ return;
59
+ }
60
+ if (message.type === "stderr") {
61
+ stderr += message.chunk;
62
+ options.onStderr?.(message.chunk);
63
+ return;
64
+ }
65
+ if (!("filesystem" in message))
66
+ return;
67
+ const previous = synchronized;
68
+ synchronized = message.filesystem;
69
+ commitQueue = commitQueue.then(() => this.applyResult(previous, message.filesystem));
70
+ if (message.type === "commit") {
71
+ void commitQueue.then(() => worker.postMessage({ type: "commit-ack", commitId: message.commitId }), (cause) => worker.postMessage({
72
+ type: "commit-ack",
73
+ commitId: message.commitId,
74
+ error: cause instanceof Error ? cause.message : String(cause),
75
+ }));
76
+ return;
77
+ }
78
+ if (message.type !== "result")
79
+ return;
80
+ void commitQueue.then(() => {
81
+ if (!finished)
82
+ finish({
83
+ stdout,
84
+ stderr: message.error ? `${stderr}${message.error}\n` : stderr,
85
+ exitCode: message.exitCode,
86
+ });
87
+ }, (error) => finish({ stdout, stderr: `${stderr}${String(error)}\n`, exitCode: 1 }));
88
+ };
89
+ worker.onerror = (event) => finish({ stdout, stderr: `${stderr}${event.message}\n`, exitCode: 1 });
90
+ const request = {
91
+ type: "run",
92
+ argv: [...argv],
93
+ cwd: options.cwd ?? this.options.cwd ?? "/workspace",
94
+ env: { ...this.options.env, ...options.env },
95
+ filesystem: before,
96
+ stdinBase64: encodeBase64(stdin),
97
+ serverPort: channel.port2,
98
+ fileLocks: { channel: lockChannel.client, owner: lockOwner },
99
+ fileCoherence: coherenceChannel.client,
100
+ };
101
+ worker.postMessage(request, [
102
+ request.serverPort,
103
+ request.fileLocks.channel.port,
104
+ request.fileCoherence.port,
105
+ ]);
106
+ });
107
+ };
108
+ async applyResult(before, after) {
109
+ const commit = this.filesystemCommitTail.then(async () => {
110
+ applyProcessFilesystemPatch(this.filesystem, createProcessFilesystemPatch(before, after), before);
111
+ await this.options.onFilesystemCommit?.(this.filesystem);
112
+ });
113
+ this.filesystemCommitTail = commit.catch(() => undefined);
114
+ await commit;
115
+ }
116
+ async persistFilesystem() {
117
+ const commit = this.filesystemCommitTail.then(() => this.options.onFilesystemCommit?.(this.filesystem));
118
+ this.filesystemCommitTail = commit.then(() => undefined, () => undefined);
119
+ await commit;
120
+ }
121
+ }
122
+ async function collectStdin(options) {
123
+ const chunks = [];
124
+ let length = 0;
125
+ if (options.stdin) {
126
+ const chunk = new TextEncoder().encode(options.stdin);
127
+ chunks.push(chunk);
128
+ length += chunk.byteLength;
129
+ }
130
+ if (options.stdinStream) {
131
+ for await (const source of options.stdinStream) {
132
+ const chunk = source.slice();
133
+ length += chunk.byteLength;
134
+ if (length > 16 * 1024 * 1024)
135
+ throw new Error("Python stdin exceeds 16 MiB.");
136
+ chunks.push(chunk);
137
+ }
138
+ }
139
+ const result = new Uint8Array(length);
140
+ let offset = 0;
141
+ for (const chunk of chunks) {
142
+ result.set(chunk, offset);
143
+ offset += chunk.byteLength;
144
+ }
145
+ return result;
146
+ }
147
+ function encodeBase64(value) {
148
+ let binary = "";
149
+ for (let offset = 0; offset < value.byteLength; offset += 0x8000) {
150
+ binary += String.fromCharCode(...value.subarray(offset, offset + 0x8000));
151
+ }
152
+ return btoa(binary);
153
+ }
154
+ //# sourceMappingURL=command.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command.js","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":"AACA,OAAO,EACL,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,uDAAuD,CAAC;AAM/D,OAAO,EACL,4BAA4B,EAC5B,gCAAgC,GACjC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,iCAAiC,EACjC,qCAAqC,GACtC,MAAM,mDAAmD,CAAC;AAS3D,oFAAoF;AACpF,MAAM,OAAO,oBAAoB;IAIZ;IACA;IAJX,oBAAoB,GAAkB,OAAO,CAAC,OAAO,EAAE,CAAC;IAEhE,YACmB,UAA6B,EAC7B,OAAoC;QADpC,eAAU,GAAV,UAAU,CAAmB;QAC7B,YAAO,GAAP,OAAO,CAA6B;IACpD,CAAC;IAEJ,GAAG,GAAG,KAAK,EAAE,IAAuB,EAAE,UAAoC,EAAE,EAAiC,EAAE;QAC7G,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO;YAAE,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,CAAC,CAAC;QAC/F,MAAM,KAAK,GAAG,MAAM,YAAY,CAAC,OAAO,CAAC,CAAC;QAC1C,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO;YAAE,OAAO,EAAE,MAAM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AE,GAAG,IAAI,GAAG,IAAI;gBAAE,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;YAC/E,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACrB,CAAC;IACH,CAAC;IACD,MAAM,MAAM,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;IACtC,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAAC,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAAC,MAAM,IAAI,KAAK,CAAC,UAAU,CAAC;IAAC,CAAC;IACtF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,YAAY,CAAC,KAAiB;IACrC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC,UAAU,EAAE,MAAM,IAAI,MAAM,EAAE,CAAC;QACjE,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,GAAG,KAAK,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC;IAC5E,CAAC;IACD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AACtB,CAAC"}
@@ -0,0 +1,9 @@
1
+ import type { BrowserFileSystemSnapshot } from "@volter/browser-runtime/browser-filesystem.js";
2
+ import { type PyodideFileSystem } from "./pyodide-runtime.js";
3
+ export declare function restorePythonSnapshot(fs: PyodideFileSystem, value: BrowserFileSystemSnapshot): void;
4
+ export declare function snapshotPythonFilesystem(fs: PyodideFileSystem, original: BrowserFileSystemSnapshot): BrowserFileSystemSnapshot;
5
+ export declare function absolutePythonPath(path: string, cwd: string): string;
6
+ export declare function pythonBasename(path: string): string;
7
+ export declare function encodeBase64(value: Uint8Array): string;
8
+ export declare function decodeBase64(value: string): Uint8Array;
9
+ //# sourceMappingURL=filesystem.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"filesystem.d.ts","sourceRoot":"","sources":["../src/filesystem.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,+CAA+C,CAAC;AAE/F,OAAO,EAAoB,KAAK,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEhF,wBAAgB,qBAAqB,CAAC,EAAE,EAAE,iBAAiB,EAAE,KAAK,EAAE,yBAAyB,GAAG,IAAI,CAkBnG;AAED,wBAAgB,wBAAwB,CAAC,EAAE,EAAE,iBAAiB,EAAE,QAAQ,EAAE,yBAAyB,GAAG,yBAAyB,CAM9H;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAQpE;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAkD;AAEtG,wBAAgB,YAAY,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAMtD;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,CAGtD"}
@@ -0,0 +1,96 @@
1
+ import { PYTHON_WORKSPACE } from "./pyodide-runtime.js";
2
+ export function restorePythonSnapshot(fs, value) {
3
+ clearTree(fs, PYTHON_WORKSPACE);
4
+ fs.mkdirTree(PYTHON_WORKSPACE);
5
+ const entries = value.files.slice().sort((left, right) => depth(left.path) - depth(right.path));
6
+ for (const entry of entries) {
7
+ if (entry.path !== PYTHON_WORKSPACE && !entry.path.startsWith(`${PYTHON_WORKSPACE}/`))
8
+ continue;
9
+ if (entry.type === "directory")
10
+ fs.mkdirTree(entry.path);
11
+ else {
12
+ fs.mkdirTree(entry.path.slice(0, entry.path.lastIndexOf("/")) || "/");
13
+ fs.writeFile(entry.path, decodeBase64(entry.content ?? ""));
14
+ }
15
+ }
16
+ for (const source of entries) {
17
+ const entry = source;
18
+ if (entry.path !== PYTHON_WORKSPACE && !entry.path.startsWith(`${PYTHON_WORKSPACE}/`))
19
+ continue;
20
+ if (entry.mode !== undefined)
21
+ fs.chmod(entry.path, entry.mode);
22
+ if (entry.mtimeMs !== undefined)
23
+ fs.utime(entry.path, entry.mtimeMs, entry.mtimeMs);
24
+ }
25
+ }
26
+ export function snapshotPythonFilesystem(fs, original) {
27
+ const retained = original.files.filter((entry) => entry.path !== PYTHON_WORKSPACE
28
+ && !entry.path.startsWith(`${PYTHON_WORKSPACE}/`));
29
+ const files = [...retained];
30
+ walk(fs, PYTHON_WORKSPACE, files);
31
+ return { files };
32
+ }
33
+ export function absolutePythonPath(path, cwd) {
34
+ const source = path.startsWith("/") ? path : `${cwd}/${path}`;
35
+ const parts = [];
36
+ for (const part of source.split("/")) {
37
+ if (!part || part === ".")
38
+ continue;
39
+ if (part === "..")
40
+ parts.pop();
41
+ else
42
+ parts.push(part);
43
+ }
44
+ return `/${parts.join("/")}`;
45
+ }
46
+ export function pythonBasename(path) { return path.slice(path.lastIndexOf("/") + 1); }
47
+ export function encodeBase64(value) {
48
+ let binary = "";
49
+ for (let offset = 0; offset < value.byteLength; offset += 0x8000) {
50
+ binary += String.fromCharCode(...value.subarray(offset, offset + 0x8000));
51
+ }
52
+ return btoa(binary);
53
+ }
54
+ export function decodeBase64(value) {
55
+ const binary = atob(value);
56
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));
57
+ }
58
+ function walk(fs, path, files) {
59
+ const stat = fs.stat(path);
60
+ const metadata = pythonMetadata(stat);
61
+ files.push({ path, type: "directory", ...metadata });
62
+ for (const name of fs.readdir(path)) {
63
+ if (name === "." || name === "..")
64
+ continue;
65
+ const child = `${path}/${name}`;
66
+ const childStat = fs.stat(child);
67
+ if ((childStat.mode & 0o170000) === 0o040000)
68
+ walk(fs, child, files);
69
+ else
70
+ files.push({ path: child, type: "file", content: encodeBase64(fs.readFile(child)), ...pythonMetadata(childStat) });
71
+ }
72
+ }
73
+ function clearTree(fs, path) {
74
+ if (!fs.analyzePath(path).exists)
75
+ return;
76
+ for (const name of fs.readdir(path)) {
77
+ if (name === "." || name === "..")
78
+ continue;
79
+ const child = `${path}/${name}`;
80
+ if ((fs.stat(child).mode & 0o170000) === 0o040000) {
81
+ clearTree(fs, child);
82
+ fs.rmdir(child);
83
+ }
84
+ else
85
+ fs.unlink(child);
86
+ }
87
+ }
88
+ function depth(path) { return path.split("/").length; }
89
+ function pythonMetadata(stat) {
90
+ const mtimeMs = stat.mtime instanceof Date ? stat.mtime.getTime() : stat.mtime;
91
+ return {
92
+ mode: stat.mode & 0o7777,
93
+ ...(typeof mtimeMs === "number" && Number.isFinite(mtimeMs) ? { mtimeMs } : {}),
94
+ };
95
+ }
96
+ //# sourceMappingURL=filesystem.js.map