gwchq-textjam 0.1.111 → 0.1.112

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.
@@ -1,652 +1,747 @@
1
- /* eslint-disable @typescript-eslint/no-empty-function */
2
- /* global globalThis, importScripts, loadPyodide, SharedArrayBuffer, Atomics, pygal */
3
-
4
- function toAbsoluteFromOrigin(url) {
5
- if (url.startsWith("http") || url.startsWith("/")) return url;
6
- // eslint-disable-next-line no-restricted-globals
7
- return new URL(url, self.location.origin).href;
8
- }
9
-
10
- // removing submodules (matplotlib.pyplot = matplotlib)
11
- const normalizeImportName = (name) => name.split(".")[0];
12
-
13
- const WORKING_DIR = "/home/pyodide";
14
-
15
- // Nest the PyodideWorker function inside a globalThis object so we control when its initialised.
16
- const PyodideWorker = () => {
17
- let assets;
18
- let packageApiUrl;
19
-
20
- const handleInit = (data) => {
21
- assets = data.assets;
22
- packageApiUrl = data.packageApiUrl;
23
-
24
- // Import scripts dynamically based on the environment
25
- console.log("PyodideWorker", "importing scripts");
26
- importScripts(toAbsoluteFromOrigin(assets.pygalUrl));
27
-
28
- assets.pyodideBaseUrl = `${packageApiUrl}/pyodide.js`;
29
- importScripts(toAbsoluteFromOrigin(assets.pyodideBaseUrl));
30
-
31
- initialisePyodide();
32
- };
33
-
34
- const supportsAllFeatures = typeof SharedArrayBuffer !== "undefined";
35
-
36
- // eslint-disable-next-line no-restricted-globals
37
- if (!supportsAllFeatures && name !== "incremental-features") {
38
- console.warn(
39
- [
40
- "The code editor will not be able to capture standard input or stop execution because these HTTP headers are not set:",
41
- " - Cross-Origin-Opener-Policy: same-origin",
42
- " - Cross-Origin-Embedder-Policy: require-corp",
43
- "",
44
- "If your app can cope with or without these features, please initialize the web worker with { name: 'incremental-features' } to silence this warning.",
45
- "You can then check for the presence of { stdinBuffer, interruptBuffer } in the handleLoaded message to check whether these features are supported.",
46
- "",
47
- "If you definitely need these features, either configure your server to respond with the HTTP headers above, or register a service worker.",
48
- "Once the HTTP headers are set, the browser will block cross-domain resources so you will need to add 'crossorigin' to <script> and other tags.",
49
- "You may wish to scope the HTTP headers to only those pages that host the code editor to make the browser restriction easier to deal with.",
50
- "",
51
- "Please refer to these code snippets for registering a service worker:",
52
- " - https://github.com/RaspberryPiFoundation/python-execution-prototypes/blob/fd2c50e032cba3bb0e92e19a88eb62e5b120fe7a/pyodide/index.html#L92-L98",
53
- " - https://github.com/RaspberryPiFoundation/python-execution-prototypes/blob/fd2c50e032cba3bb0e92e19a88eb62e5b120fe7a/pyodide/serviceworker.js",
54
- ].join("\n"),
55
- );
56
- }
57
- let pyodide, pyodidePromise, stdinBuffer, interruptBuffer, stopped;
58
- /** When true, input() uses postMessage + run_sync(getInputAsync) instead of setStdin (requires JSPI). */
59
- let useMessageStdin = false;
60
- /** Used when SharedArrayBuffer is unavailable: resolve for the pending input() call. */
61
- let pendingStdinResolve = null;
62
- // Until Pyodide is fully initialised, keep stdout/stderr in the dev console only.
63
- // After initialisation, route them to the UI via postMessage.
64
- let userStdStreamsEnabled = false;
65
- // When true, suppress internal library / package loader logs from the UI console.
66
- let suppressInternalStdStreams = false;
67
-
68
- const onmessage = async ({ data }) => {
69
- if (data.method !== "init") {
70
- pyodide = await pyodidePromise;
71
- }
72
-
73
- switch (data.method) {
74
- case "stdinResponse":
75
- if (pendingStdinResolve) {
76
- let content = data.ctrlD ? null : data.content ?? "";
77
- if (content && content.endsWith("\n")) {
78
- content = content.slice(0, -1);
79
- }
80
- pendingStdinResolve(content);
81
- pendingStdinResolve = null;
82
- }
83
- break;
84
- case "init":
85
- handleInit(data);
86
- break;
87
- case "createDirectories":
88
- if (Array.isArray(data.dirs)) {
89
- for (const dir of data.dirs) {
90
- try {
91
- pyodide.FS.mkdirTree(`${WORKING_DIR}/${dir}`);
92
- } catch (e) {
93
- console.error(`Failed to create directory ${dir}:`, e);
94
- }
95
- }
96
- }
97
- break;
98
- case "writeFile":
99
- const encoder = new TextEncoder();
100
- pyodide.FS.writeFile(
101
- `${WORKING_DIR}/${data.filename}`,
102
- encoder.encode(data.content),
103
- );
104
- break;
105
- case "runPython":
106
- runPython(data.python, data.userModuleNames);
107
- break;
108
- case "stopPython":
109
- // Mark as stopped so future checks can raise KeyboardInterrupt.
110
- stopped = true;
111
- // If Python is currently blocked in input() via run_sync(getInputAsync),
112
- // resolve the pending stdin promise with EOF so execution can unwind
113
- // and clearPyodideData can run.
114
- if (pendingStdinResolve) {
115
- pendingStdinResolve(null);
116
- pendingStdinResolve = null;
117
- }
118
- break;
119
- default:
120
- throw new Error(`Unsupported method: ${data.method}`);
121
- }
122
- };
123
-
124
- // eslint-disable-next-line no-restricted-globals
125
- addEventListener("message", async (event) => {
126
- onmessage(event);
127
- });
128
-
129
- const runPython = async (python, userModuleNames) => {
130
- stopped = false;
131
-
132
- // When stdin uses postMessage (no SharedArrayBuffer), run_sync() in input() requires
133
- // runPythonAsync so that JSPI stack switching can suspend until the main thread sends stdinResponse.
134
- const runUserCode = useMessageStdin
135
- ? () => pyodide.runPythonAsync(python)
136
- : () => pyodide.runPython(python);
137
-
138
- try {
139
- await withSupportForPackages(python, async () => {
140
- await runUserCode();
141
- });
142
- } catch (error) {
143
- if (!(error instanceof pyodide.ffi.PythonError)) {
144
- throw error;
145
- }
146
- const parsed = parsePythonError(error);
147
- // Stop resolves stdin with EOF so input() raises EOFError; show as interrupt, not error.
148
- if (stopped && parsed.type === "EOFError") {
149
- postMessage({
150
- method: "handleError",
151
- ...parsed,
152
- type: "KeyboardInterrupt",
153
- info: "Execution interrupted",
154
- });
155
- } else {
156
- postMessage({ method: "handleError", ...parsed });
157
- }
158
- }
159
-
160
- await clearPyodideData(userModuleNames);
161
- };
162
-
163
- const checkIfStopped = () => {
164
- if (stopped) {
165
- throw new pyodide.ffi.PythonError("KeyboardInterrupt");
166
- }
167
- };
168
-
169
- const withSupportForPackages = async (
170
- python,
171
- runPythonFn = async () => {},
172
- ) => {
173
- // Suppress internal loader output (e.g. "Loading pyodide-http") from the
174
- // user console while resolving imports and loading packages.
175
- suppressInternalStdStreams = true;
176
- const imports = await pyodide._api.pyodide_code.find_imports(python).toJs();
177
- await Promise.all(imports.map((name) => loadDependency(name)));
178
-
179
- checkIfStopped();
180
- await pyodide.loadPackagesFromImports(python);
181
-
182
- checkIfStopped();
183
- await pyodide.runPythonAsync(
184
- `
185
- import basthon
186
- import builtins
187
- import os
188
-
189
- MAX_FILES = 100
190
- MAX_FILE_SIZE = 8500000
191
-
192
- def _custom_open(filename, mode="r", *args, **kwargs):
193
- if "x" in mode and os.path.exists(filename):
194
- raise FileExistsError(f"File '{filename}' already exists")
195
- if ("w" in mode or "a" in mode or "x" in mode) and "b" not in mode:
196
- if len(os.listdir()) > MAX_FILES and not os.path.exists(filename):
197
- raise OSError(f"File system limit reached, no more than {MAX_FILES} files allowed")
198
- class CustomFile:
199
- def __init__(self, filename):
200
- self.filename = filename
201
- self.content = ""
202
-
203
- def write(self, content):
204
- self.content += content
205
- if len(self.content) > MAX_FILE_SIZE:
206
- raise OSError(f"File '{self.filename}' exceeds maximum file size of {MAX_FILE_SIZE} bytes")
207
- with _original_open(self.filename, mode) as f:
208
- f.write(self.content)
209
- basthon.kernel.write_file({ "filename": self.filename, "content": self.content, "mode": mode })
210
-
211
- def close(self):
212
- pass
213
-
214
- def __enter__(self):
215
- return self
216
-
217
- def __exit__(self, exc_type, exc_val, exc_tb):
218
- self.close()
219
-
220
- return CustomFile(filename)
221
- else:
222
- return _original_open(filename, mode, *args, **kwargs)
223
-
224
- # Override the built-in open function
225
- builtins.open = _custom_open
226
- `,
227
- { filename: "__custom_open__.py" },
228
- );
229
-
230
- // Re-enable user-visible stdout / stderr for the actual user code run.
231
- suppressInternalStdStreams = false;
232
-
233
- await runPythonFn();
234
-
235
- for (let name of imports) {
236
- checkIfStopped();
237
- const pkgName = normalizeImportName(name);
238
- await vendoredPackages[pkgName]?.after();
239
- }
240
- };
241
-
242
- const loadDependency = async (name) => {
243
- checkIfStopped();
244
-
245
- const pkgName = normalizeImportName(name);
246
- // If the import is for another user file then open it and load its dependencies.
247
- if (pyodide.FS.readdir(WORKING_DIR).includes(`${pkgName}.py`)) {
248
- const fileContent = pyodide.FS.readFile(`${WORKING_DIR}/${pkgName}.py`, {
249
- encoding: "utf8",
250
- });
251
- await withSupportForPackages(fileContent);
252
- return;
253
- }
254
-
255
- // If the import is for a vendored package then run its .before() hook.
256
- const vendoredPackage = vendoredPackages[pkgName];
257
- await vendoredPackage?.before();
258
- if (vendoredPackage) {
259
- return;
260
- }
261
-
262
- // If the import is for a module built into Python then do nothing.
263
- try {
264
- const pythonModule = pyodide.pyimport(pkgName);
265
- if (pythonModule) {
266
- return;
267
- }
268
- } catch (_) {}
269
-
270
- // If the import is for a package built into Pyodide then load it.
271
- // Built-ins: https://pyodide.org/en/stable/usage/packages-in-pyodide.html
272
- try {
273
- await pyodide.loadPackage(pkgName);
274
-
275
- const pyodidePackage = pyodide.pyimport(pkgName);
276
- if (pyodidePackage) {
277
- return;
278
- }
279
- } catch (_) {}
280
-
281
- // Ensure micropip is loaded which can fetch packages from PyPi.
282
- // See: https://pyodide.org/en/stable/usage/loading-packages.html
283
- if (!pyodide.micropip) {
284
- await pyodide.loadPackage("micropip");
285
- pyodide.micropip = pyodide.pyimport("micropip");
286
- }
287
-
288
- // If the import is for a PyPi package then load it.
289
- // Otherwise, don't error now so that we get an error later from Python.
290
- await pyodide.micropip.install(pkgName).catch(() => {});
291
- };
292
-
293
- const vendoredPackages = {
294
- // Support for https://pypi.org/project/py-enigma/ due to package not having a whl file on PyPi.
295
- enigma: {
296
- before: async () => {
297
- await pyodide.loadPackage(toAbsoluteFromOrigin(assets.enigmaWhlUrl));
298
- },
299
- after: () => {},
300
- },
301
- turtle: {
302
- before: async () => {
303
- pyodide.registerJsModule("basthon", fakeBasthonPackage);
304
- await pyodide.loadPackage(toAbsoluteFromOrigin(assets.turtleWhlUrl));
305
- },
306
- after: () =>
307
- pyodide.runPython(`
308
- import turtle
309
- import basthon
310
-
311
- svg_dict = turtle.Screen().show_scene()
312
- basthon.kernel.display_event({ "display_type": "turtle", "content": svg_dict })
313
- turtle.restart()
314
- `),
315
- },
316
- p5: {
317
- before: async () => {
318
- pyodide.registerJsModule("basthon", fakeBasthonPackage);
319
- await pyodide.loadPackage([
320
- "setuptools",
321
- toAbsoluteFromOrigin(assets.p5WhlUrl),
322
- ]);
323
- },
324
- after: () => {},
325
- },
326
- pygal: {
327
- before: () => {
328
- pyodide.registerJsModule("pygal", { ...pygal });
329
- pygal.config.renderChart = (content) => {
330
- postMessage({ method: "handleVisual", origin: "pygal", content });
331
- };
332
- },
333
- after: () => {},
334
- },
335
- matplotlib: {
336
- before: async () => {
337
- pyodide.registerJsModule("basthon", fakeBasthonPackage);
338
- // Patch the document object to prevent matplotlib from trying to render. Since we are running in a web worker,
339
- // the document object is not available. We will instead capture the image and send it back to the main thread.
340
- pyodide.runPython(`
341
- import js
342
-
343
- class __DummyDocument__:
344
- def __init__(self, *args, **kwargs) -> None:
345
- return
346
- def __getattr__(self, __name: str):
347
- return __DummyDocument__
348
- js.document = __DummyDocument__()
349
- `);
350
- await pyodide.loadPackage("matplotlib")?.catch(() => {});
351
- let pyodidePackage;
352
- try {
353
- pyodidePackage = pyodide.pyimport("matplotlib");
354
- } catch (_) {}
355
- if (pyodidePackage) {
356
- pyodide.runPython(`
357
- import matplotlib.pyplot as plt
358
- import io
359
- import basthon
360
-
361
- def show_chart():
362
- bytes_io = io.BytesIO()
363
- plt.savefig(bytes_io, format='jpg')
364
- bytes_io.seek(0)
365
- basthon.kernel.display_event({ "display_type": "matplotlib", "content": bytes_io.read() })
366
- plt.show = show_chart
367
- `);
368
- return;
369
- }
370
- },
371
- after: () => {
372
- pyodide.runPython(`
373
- import matplotlib.pyplot as plt
374
- plt.clf()
375
- `);
376
- },
377
- },
378
- seaborn: {
379
- before: async () => {
380
- pyodide.registerJsModule("basthon", fakeBasthonPackage);
381
- // Patch the document object to prevent matplotlib from trying to render. Since we are running in a web worker,
382
- // the document object is not available. We will instead capture the image and send it back to the main thread.
383
- pyodide.runPython(`
384
- import js
385
-
386
- class __DummyDocument__:
387
- def __init__(self, *args, **kwargs) -> None:
388
- return
389
- def __getattr__(self, __name: str):
390
- return __DummyDocument__
391
- js.document = __DummyDocument__()
392
- `);
393
-
394
- // Ensure micropip is loaded which can fetch packages from PyPi.
395
- // See: https://pyodide.org/en/stable/usage/loading-packages.html
396
- if (!pyodide.micropip) {
397
- await pyodide.loadPackage("micropip");
398
- pyodide.micropip = pyodide.pyimport("micropip");
399
- }
400
-
401
- // If the import is for a PyPi package then load it.
402
- // Otherwise, don't error now so that we get an error later from Python.
403
- await pyodide.micropip.install("seaborn").catch(() => {});
404
- },
405
- after: () => {
406
- pyodide.runPython(`
407
- import matplotlib.pyplot as plt
408
- import io
409
- import basthon
410
-
411
- def is_plot_empty():
412
- fig = plt.gcf()
413
- for ax in fig.get_axes():
414
- # Check if the axes contain any lines, patches, collections, etc.
415
- if ax.lines or ax.patches or ax.collections or ax.images or ax.texts:
416
- return False
417
- return True
418
-
419
- if not is_plot_empty():
420
- bytes_io = io.BytesIO()
421
- plt.savefig(bytes_io, format='jpg')
422
- bytes_io.seek(0)
423
- basthon.kernel.display_event({ "display_type": "matplotlib", "content": bytes_io.read() })
424
-
425
- plt.clf()
426
- `);
427
- },
428
- },
429
- plotly: {
430
- before: async () => {
431
- if (!pyodide.micropip) {
432
- await pyodide.loadPackage("micropip");
433
- pyodide.micropip = pyodide.pyimport("micropip");
434
- }
435
-
436
- // If the import is for a PyPi package then load it.
437
- // Otherwise, don't error now so that we get an error later from Python.
438
- await pyodide.micropip.install("plotly").catch(() => {});
439
- await pyodide.micropip.install("pandas").catch(() => {});
440
- pyodide.registerJsModule("basthon", fakeBasthonPackage);
441
- pyodide.runPython(`
442
- import plotly.graph_objs as go
443
-
444
- def _hacked_show(self, *args, **kwargs):
445
- basthon.kernel.display_event({
446
- "display_type": "plotly",
447
- "content": self.to_json()
448
- })
449
-
450
- go.Figure.show = _hacked_show
451
- `);
452
- },
453
- after: () => {},
454
- },
455
- };
456
-
457
- const fakeBasthonPackage = {
458
- kernel: {
459
- display_event: (event) => {
460
- const origin = event.toJs().get("display_type");
461
- const content = event.toJs().get("content");
462
-
463
- postMessage({ method: "handleVisual", origin, content });
464
- },
465
- write_file: (event) => {
466
- const filename = event.toJs().get("filename");
467
- const content = event.toJs().get("content");
468
- const mode = event.toJs().get("mode");
469
- postMessage({ method: "handleFileWrite", filename, content, mode });
470
- },
471
- locals: () => pyodide.runPython("globals()"),
472
- /**
473
- * Returns a Promise that resolves with the next line of stdin when the main thread
474
- * sends stdinResponse. Resolves with null on EOF (e.g. Ctrl+D).
475
- * Used when SharedArrayBuffer is unavailable (no COOP/COEP) so we cannot block via Atomics.wait.
476
- * Requires JSPI and runPythonAsync() for run_sync() to work.
477
- */
478
- getInputAsync: () => {
479
- const promise = new Promise((resolve) => {
480
- pendingStdinResolve = resolve;
481
- });
482
- postMessage({ method: "handleInput" });
483
- return promise;
484
- },
485
- },
486
- };
487
-
488
- const clearPyodideData = async (userModuleNames) => {
489
- postMessage({ method: "handleLoading" });
490
- try {
491
- await pyodide.runPythonAsync(`
492
- # Clear all user-defined variables and modules
493
- for name in list(globals()):
494
- if not name.startswith('_') and not name=='basthon':
495
- del globals()[name]
496
-
497
- import sys
498
- # Remove user modules from sys.modules
499
- user_modules = ${JSON.stringify(userModuleNames)}
500
- for name in user_modules:
501
- if name in sys.modules:
502
- del sys.modules[name]
503
- `);
504
- } catch (error) {
505
- console.error("Error while clearing Pyodide data:", error);
506
- }
507
- console.log("clearPyodideData done");
508
- postMessage({ method: "handleLoaded", stdinBuffer, interruptBuffer });
509
- };
510
-
511
- const initialisePyodide = async () => {
512
- postMessage({ method: "handleLoading" });
513
-
514
- pyodidePromise = loadPyodide({
515
- stdout: (content) => {
516
- if (stopped) return;
517
- if (userStdStreamsEnabled && !suppressInternalStdStreams) {
518
- postMessage({ method: "handleOutput", stream: "stdout", content });
519
- } else {
520
- console.log(content);
521
- }
522
- },
523
- stderr: (content) => {
524
- if (stopped) return;
525
- if (userStdStreamsEnabled && !suppressInternalStdStreams) {
526
- postMessage({ method: "handleOutput", stream: "stderr", content });
527
- } else {
528
- console.error(content);
529
- }
530
- },
531
- });
532
-
533
- pyodide = await pyodidePromise;
534
-
535
- pyodide.registerJsModule("basthon", fakeBasthonPackage);
536
-
537
- // When SharedArrayBuffer is unavailable, always use the postMessage-based
538
- // stdin path. JSPI / run_sync will raise at runtime if the environment
539
- // cannot stack-switch, but in JSPI-capable browsers this enables
540
- // interactive input() without COOP/COEP.
541
- useMessageStdin = !supportsAllFeatures;
542
- pyodide.globals.set("__stdin_via_message__", useMessageStdin);
543
-
544
- await pyodide.runPythonAsync(`
545
- import builtins
546
- from pyodide.ffi import run_sync as __run_sync__
547
-
548
- __old_input__ = builtins.input
549
- def __patched_input__(prompt=None):
550
- if prompt is not None:
551
- print(prompt)
552
- if __stdin_via_message__:
553
- result = __run_sync__(basthon.kernel.getInputAsync())
554
- if result is None:
555
- raise EOFError("EOF when reading a line")
556
- return result
557
- return __old_input__()
558
- builtins.input = __patched_input__
559
- `);
560
-
561
- await pyodide.runPythonAsync(`
562
- import builtins
563
- # Save the original open function
564
- _original_open = builtins.open
565
- `);
566
-
567
- await pyodide.loadPackage("pyodide-http");
568
- await pyodide.runPythonAsync(`
569
- import pyodide_http
570
- pyodide_http.patch_all()
571
- `);
572
-
573
- if (supportsAllFeatures) {
574
- stdinBuffer =
575
- stdinBuffer || new Int32Array(new SharedArrayBuffer(1024 * 1024)); // 1 MiB
576
- stdinBuffer[0] = 1; // Store the length of content in the buffer at index 0.
577
- pyodide.setStdin({ isatty: true, read: readFromStdin });
578
-
579
- interruptBuffer =
580
- interruptBuffer || new Uint8Array(new SharedArrayBuffer(1));
581
- pyodide.setInterruptBuffer(interruptBuffer);
582
- }
583
-
584
- // From this point on, anything written to stdout / stderr is considered
585
- // user-visible and will be forwarded to the UI.
586
- userStdStreamsEnabled = true;
587
-
588
- postMessage({ method: "handleLoaded", stdinBuffer, interruptBuffer });
589
- };
590
-
591
- const readFromStdin = (bufferToWrite) => {
592
- const previousLength = stdinBuffer[0];
593
- postMessage({ method: "handleInput" });
594
-
595
- while (true) {
596
- pyodide.checkInterrupt();
597
- const result = Atomics.wait(stdinBuffer, 0, previousLength, 100);
598
- if (result === "not-equal") {
599
- break;
600
- }
601
- }
602
-
603
- const currentLength = stdinBuffer[0];
604
- if (currentLength === -1) {
605
- return 0;
606
- } // Signals that stdin was closed.
607
-
608
- const addedBytes = stdinBuffer.slice(previousLength, currentLength);
609
- bufferToWrite.set(addedBytes);
610
-
611
- return addedBytes.length;
612
- };
613
-
614
- const parsePythonError = (error) => {
615
- const type = error.type;
616
- const [trace, info] = error.message.split(`${type}:`).map((s) => s?.trim());
617
-
618
- const lines = trace.split("\n");
619
-
620
- // if the third from last line matches /File "__custom_open__\.py", line (\d+)/g then strip off the last three lines
621
- if (
622
- lines.length > 3 &&
623
- /File "__custom_open__\.py", line (\d+)/g.test(lines[lines.length - 3])
624
- ) {
625
- lines.splice(-3, 3);
626
- }
627
-
628
- const snippetLine = lines[lines.length - 2]; // print("hi")invalid
629
- const caretLine = lines[lines.length - 1]; // ^^^^^^^
630
-
631
- const showsMistake = caretLine.includes("^");
632
- const mistake = showsMistake
633
- ? [snippetLine.slice(4), caretLine.slice(4)].join("\n")
634
- : "";
635
-
636
- const matches = [
637
- ...trace.matchAll(/File "(?!__custom_open__\.py)(.*)", line (\d+)/g),
638
- ];
639
- const match = matches[matches.length - 1];
640
-
641
- const path = match ? match[1] : "";
642
- const base = path.split("/").reverse()[0];
643
- const file = base === "<exec>" ? "main.py" : base;
644
-
645
- const line = match ? parseInt(match[2], 10) : "";
646
-
647
- return { file, line, mistake, type, info };
648
- };
649
- };
650
-
651
- globalThis.PyodideWorker = PyodideWorker;
652
- PyodideWorker();
1
+ /* eslint-disable @typescript-eslint/no-empty-function */
2
+ /* global globalThis, importScripts, loadPyodide, SharedArrayBuffer, Atomics, pygal */
3
+
4
+ function toAbsoluteFromOrigin(url) {
5
+ if (url.startsWith("http") || url.startsWith("/")) return url;
6
+ // eslint-disable-next-line no-restricted-globals
7
+ return new URL(url, self.location.origin).href;
8
+ }
9
+
10
+ const WORKING_DIR = "/home/pyodide";
11
+
12
+ const toStructuredCloneable = (value) => {
13
+ if (value == null) return value;
14
+
15
+ if (
16
+ typeof value === "string" ||
17
+ typeof value === "number" ||
18
+ typeof value === "boolean"
19
+ ) {
20
+ return value;
21
+ }
22
+
23
+ if (value instanceof Uint8Array) {
24
+ return value.slice();
25
+ }
26
+
27
+ if (ArrayBuffer.isView(value)) {
28
+ return new Uint8Array(
29
+ value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength),
30
+ );
31
+ }
32
+
33
+ if (value instanceof ArrayBuffer) {
34
+ return value.slice(0);
35
+ }
36
+
37
+ if (value instanceof Map) {
38
+ return Object.fromEntries(
39
+ [...value.entries()].map(([k, v]) => [k, toStructuredCloneable(v)]),
40
+ );
41
+ }
42
+
43
+ if (Array.isArray(value)) {
44
+ return value.map(toStructuredCloneable);
45
+ }
46
+
47
+ if (typeof value?.toJs === "function") {
48
+ try {
49
+ const converted = value.toJs({ dict_converter: Object.fromEntries });
50
+ return toStructuredCloneable(converted);
51
+ } catch (_) {
52
+ try {
53
+ const converted = value.toJs();
54
+ return toStructuredCloneable(converted);
55
+ } catch (_) {
56
+ return String(value);
57
+ }
58
+ }
59
+ }
60
+
61
+ if (typeof value === "object") {
62
+ const result = {};
63
+ for (const [key, val] of Object.entries(value)) {
64
+ result[key] = toStructuredCloneable(val);
65
+ }
66
+ return result;
67
+ }
68
+
69
+ return String(value);
70
+ };
71
+
72
+ // Nest the PyodideWorker function inside a globalThis object so we control when its initialised.
73
+ const PyodideWorker = () => {
74
+ let assets;
75
+ let packageApiUrl;
76
+
77
+ const handleInit = (data) => {
78
+ assets = data.assets;
79
+ packageApiUrl = data.packageApiUrl;
80
+
81
+ // Import scripts dynamically based on the environment
82
+ console.log("PyodideWorker", "importing scripts");
83
+ importScripts(toAbsoluteFromOrigin(assets.pygalUrl));
84
+
85
+ assets.pyodideBaseUrl = `${packageApiUrl}/pyodide.js`;
86
+ importScripts(toAbsoluteFromOrigin(assets.pyodideBaseUrl));
87
+
88
+ initialisePyodide();
89
+ };
90
+
91
+ const supportsAllFeatures = typeof SharedArrayBuffer !== "undefined";
92
+
93
+ // eslint-disable-next-line no-restricted-globals
94
+ if (!supportsAllFeatures && name !== "incremental-features") {
95
+ console.warn(
96
+ [
97
+ "The code editor will not be able to capture standard input or stop execution because these HTTP headers are not set:",
98
+ " - Cross-Origin-Opener-Policy: same-origin",
99
+ " - Cross-Origin-Embedder-Policy: require-corp",
100
+ "",
101
+ "If your app can cope with or without these features, please initialize the web worker with { name: 'incremental-features' } to silence this warning.",
102
+ "You can then check for the presence of { stdinBuffer, interruptBuffer } in the handleLoaded message to check whether these features are supported.",
103
+ "",
104
+ "If you definitely need these features, either configure your server to respond with the HTTP headers above, or register a service worker.",
105
+ "Once the HTTP headers are set, the browser will block cross-domain resources so you will need to add 'crossorigin' to <script> and other tags.",
106
+ "You may wish to scope the HTTP headers to only those pages that host the code editor to make the browser restriction easier to deal with.",
107
+ "",
108
+ "Please refer to these code snippets for registering a service worker:",
109
+ " - https://github.com/RaspberryPiFoundation/python-execution-prototypes/blob/fd2c50e032cba3bb0e92e19a88eb62e5b120fe7a/pyodide/index.html#L92-L98",
110
+ " - https://github.com/RaspberryPiFoundation/python-execution-prototypes/blob/fd2c50e032cba3bb0e92e19a88eb62e5b120fe7a/pyodide/serviceworker.js",
111
+ ].join("\n"),
112
+ );
113
+ }
114
+ let pyodide, pyodidePromise, stdinBuffer, interruptBuffer, stopped;
115
+ /** When true, input() uses postMessage + run_sync(getInputAsync) instead of setStdin (requires JSPI). */
116
+ let useMessageStdin = false;
117
+ /** Used when SharedArrayBuffer is unavailable: resolve for the pending input() call. */
118
+ let pendingStdinResolve = null;
119
+ // Until Pyodide is fully initialised, keep stdout/stderr in the dev console only.
120
+ // After initialisation, route them to the UI via postMessage.
121
+ let userStdStreamsEnabled = false;
122
+ // When true, suppress internal library / package loader logs from the UI console.
123
+ let suppressInternalStdStreams = false;
124
+
125
+ const onmessage = async ({ data }) => {
126
+ pyodide = await pyodidePromise;
127
+ let encoder = new TextEncoder();
128
+
129
+ switch (data.method) {
130
+ case "stdinResponse":
131
+ if (pendingStdinResolve) {
132
+ let content = data.ctrlD ? null : data.content ?? "";
133
+ if (content && content.endsWith("\n")) {
134
+ content = content.slice(0, -1);
135
+ }
136
+ pendingStdinResolve(content);
137
+ pendingStdinResolve = null;
138
+ }
139
+ break;
140
+ case "init":
141
+ handleInit(data);
142
+ break;
143
+ case "createDirectories":
144
+ if (Array.isArray(data.dirs)) {
145
+ for (const dir of data.dirs) {
146
+ try {
147
+ pyodide.FS.mkdirTree(`${WORKING_DIR}/${dir}`);
148
+ } catch (e) {
149
+ console.error(`Failed to create directory ${dir}:`, e);
150
+ }
151
+ }
152
+ }
153
+ break;
154
+ case "writeFile":
155
+ pyodide.FS.writeFile(
156
+ `${WORKING_DIR}/${data.filename}`,
157
+ encoder.encode(data.content),
158
+ );
159
+ break;
160
+ case "runPython":
161
+ runPython(data.python, data.userModuleNames);
162
+ break;
163
+ case "stopPython":
164
+ // Mark as stopped so future checks can raise KeyboardInterrupt.
165
+ stopped = true;
166
+ // If Python is currently blocked in input() via run_sync(getInputAsync),
167
+ // resolve the pending stdin promise with EOF so execution can unwind
168
+ // and clearPyodideData can run.
169
+ if (pendingStdinResolve) {
170
+ pendingStdinResolve(null);
171
+ pendingStdinResolve = null;
172
+ }
173
+ break;
174
+ default:
175
+ throw new Error(`Unsupported method: ${data.method}`);
176
+ }
177
+ };
178
+
179
+ // eslint-disable-next-line no-restricted-globals
180
+ addEventListener("message", async (event) => {
181
+ onmessage(event);
182
+ });
183
+
184
+ const runPython = async (python, userModuleNames) => {
185
+ stopped = false;
186
+
187
+ // When stdin uses postMessage (no SharedArrayBuffer), run_sync() in input() requires
188
+ // runPythonAsync so that JSPI stack switching can suspend until the main thread sends stdinResponse.
189
+ const runUserCode = useMessageStdin
190
+ ? () => pyodide.runPythonAsync(python)
191
+ : () => pyodide.runPython(python);
192
+
193
+ try {
194
+ await withSupportForPackages(python, async () => {
195
+ await runUserCode();
196
+ });
197
+ } catch (error) {
198
+ if (!(error instanceof pyodide.ffi.PythonError)) {
199
+ throw error;
200
+ }
201
+ const parsed = parsePythonError(error);
202
+ // Stop resolves stdin with EOF so input() raises EOFError; show as interrupt, not error.
203
+ if (stopped && parsed.type === "EOFError") {
204
+ postMessage({
205
+ method: "handleError",
206
+ ...parsed,
207
+ type: "KeyboardInterrupt",
208
+ info: "Execution interrupted",
209
+ });
210
+ } else {
211
+ postMessage({ method: "handleError", ...parsed });
212
+ }
213
+ }
214
+
215
+ await clearPyodideData(userModuleNames);
216
+ };
217
+
218
+ const checkIfStopped = () => {
219
+ if (stopped) {
220
+ throw new pyodide.ffi.PythonError("KeyboardInterrupt");
221
+ }
222
+ };
223
+
224
+ const withSupportForPackages = async (
225
+ python,
226
+ runPythonFn = async () => {},
227
+ ) => {
228
+ // Suppress internal loader output (e.g. "Loading pyodide-http") from the
229
+ // user console while resolving imports and loading packages.
230
+ suppressInternalStdStreams = true;
231
+ const imports = await pyodide._api.pyodide_code.find_imports(python).toJs();
232
+ await Promise.all(imports.map((name) => loadDependency(name)));
233
+
234
+ checkIfStopped();
235
+ await pyodide.loadPackagesFromImports(python);
236
+
237
+ checkIfStopped();
238
+ await pyodide.runPythonAsync(
239
+ `
240
+ import basthon
241
+ import builtins
242
+ import os
243
+
244
+ MAX_FILES = 100
245
+ MAX_FILE_SIZE = 8500000
246
+ PROJECT_ROOT = os.path.abspath("${WORKING_DIR}")
247
+
248
+ def _is_project_file(filename):
249
+ abs_path = os.path.abspath(filename)
250
+ return abs_path == PROJECT_ROOT or abs_path.startswith(PROJECT_ROOT + os.sep)
251
+
252
+ def _to_project_relative(filename):
253
+ abs_path = os.path.abspath(filename)
254
+ return os.path.relpath(abs_path, PROJECT_ROOT)
255
+
256
+ def _custom_open(filename, mode="r", *args, **kwargs):
257
+ abs_path = os.path.abspath(filename)
258
+
259
+ if "x" in mode and os.path.exists(abs_path):
260
+ raise FileExistsError(f"File '{filename}' already exists")
261
+
262
+ is_text_write = ("w" in mode or "a" in mode or "x" in mode) and "b" not in mode
263
+ is_project_file = _is_project_file(abs_path)
264
+
265
+ if is_text_write and is_project_file:
266
+ if len(os.listdir(PROJECT_ROOT)) > MAX_FILES and not os.path.exists(abs_path):
267
+ raise OSError(f"File system limit reached, no more than {MAX_FILES} files allowed")
268
+ class CustomFile:
269
+ def __init__(self, filename):
270
+ self.filename = filename
271
+ self.content = ""
272
+
273
+ def write(self, content):
274
+ self.content += content
275
+ if len(self.content) > MAX_FILE_SIZE:
276
+ raise OSError(f"File '{self.filename}' exceeds maximum file size of {MAX_FILE_SIZE} bytes")
277
+ with _original_open(self.filename, mode, *args, **kwargs) as f:
278
+ f.write(self.content)
279
+ basthon.kernel.write_file({
280
+ "filename": _to_project_relative(self.filename),
281
+ "content": self.content,
282
+ "mode": mode
283
+ })
284
+
285
+ def close(self):
286
+ pass
287
+
288
+ def __enter__(self):
289
+ return self
290
+
291
+ def __exit__(self, exc_type, exc_val, exc_tb):
292
+ self.close()
293
+
294
+ return CustomFile(abs_path)
295
+ else:
296
+ return _original_open(filename, mode, *args, **kwargs)
297
+
298
+ # Override the built-in open function
299
+ builtins.open = _custom_open
300
+ `,
301
+ { filename: "__custom_open__.py" },
302
+ );
303
+
304
+ // Re-enable user-visible stdout / stderr for the actual user code run.
305
+ suppressInternalStdStreams = false;
306
+
307
+ await runPythonFn();
308
+
309
+ for (let name of imports) {
310
+ checkIfStopped();
311
+ await vendoredPackages[name]?.after();
312
+ }
313
+ };
314
+
315
+ const loadDependency = async (name) => {
316
+ checkIfStopped();
317
+
318
+ // If the import is for another user file then open it and load its dependencies.
319
+ if (pyodide.FS.readdir(WORKING_DIR).includes(`${name}.py`)) {
320
+ const fileContent = pyodide.FS.readFile(`${WORKING_DIR}/${name}.py`, {
321
+ encoding: "utf8",
322
+ });
323
+ await withSupportForPackages(fileContent);
324
+ return;
325
+ }
326
+
327
+ // If the import is for a vendored package then run its .before() hook.
328
+ const vendoredPackage = vendoredPackages[name];
329
+ await vendoredPackage?.before();
330
+ if (vendoredPackage) {
331
+ return;
332
+ }
333
+
334
+ // If the import is for a module built into Python then do nothing.
335
+ let pythonModule;
336
+ try {
337
+ pythonModule = pyodide.pyimport(name);
338
+ } catch (_) {}
339
+ if (pythonModule) {
340
+ return;
341
+ }
342
+
343
+ // If the import is for a package built into Pyodide then load it.
344
+ // Built-ins: https://pyodide.org/en/stable/usage/packages-in-pyodide.html
345
+ await pyodide.loadPackage(name)?.catch(() => {});
346
+ let pyodidePackage;
347
+ try {
348
+ pyodidePackage = pyodide.pyimport(name);
349
+ } catch (_) {}
350
+ if (pyodidePackage) {
351
+ return;
352
+ }
353
+
354
+ // Ensure micropip is loaded which can fetch packages from PyPi.
355
+ // See: https://pyodide.org/en/stable/usage/loading-packages.html
356
+ if (!pyodide.micropip) {
357
+ await pyodide.loadPackage("micropip");
358
+ pyodide.micropip = pyodide.pyimport("micropip");
359
+ }
360
+
361
+ // If the import is for a PyPi package then load it.
362
+ // Otherwise, don't error now so that we get an error later from Python.
363
+ await pyodide.micropip.install(name).catch(() => {});
364
+ };
365
+
366
+ const vendoredPackages = {
367
+ // Support for https://pypi.org/project/py-enigma/ due to package not having a whl file on PyPi.
368
+ enigma: {
369
+ before: async () => {
370
+ await pyodide.loadPackage(toAbsoluteFromOrigin(assets.enigmaWhlUrl));
371
+ },
372
+ after: () => {},
373
+ },
374
+ turtle: {
375
+ before: async () => {
376
+ pyodide.registerJsModule("basthon", fakeBasthonPackage);
377
+ await pyodide.loadPackage(toAbsoluteFromOrigin(assets.turtleWhlUrl));
378
+ },
379
+ after: () =>
380
+ pyodide.runPython(`
381
+ import turtle
382
+ import basthon
383
+
384
+ svg_dict = turtle.Screen().show_scene()
385
+ basthon.kernel.display_event({ "display_type": "turtle", "content": svg_dict })
386
+ turtle.restart()
387
+ `),
388
+ },
389
+ p5: {
390
+ before: async () => {
391
+ pyodide.registerJsModule("basthon", fakeBasthonPackage);
392
+ await pyodide.loadPackage([
393
+ "setuptools",
394
+ toAbsoluteFromOrigin(assets.p5WhlUrl),
395
+ ]);
396
+ },
397
+ after: () => {},
398
+ },
399
+ pygal: {
400
+ before: () => {
401
+ pyodide.registerJsModule("pygal", { ...pygal });
402
+ pygal.config.renderChart = (content) => {
403
+ postMessage({ method: "handleVisual", origin: "pygal", content });
404
+ };
405
+ },
406
+ after: () => {},
407
+ },
408
+ matplotlib: {
409
+ before: async () => {
410
+ pyodide.registerJsModule("basthon", fakeBasthonPackage);
411
+ // Patch the document object to prevent matplotlib from trying to render. Since we are running in a web worker,
412
+ // the document object is not available. We will instead capture the image and send it back to the main thread.
413
+ pyodide.runPython(`
414
+ import js
415
+
416
+ class __DummyDocument__:
417
+ def __init__(self, *args, **kwargs) -> None:
418
+ return
419
+ def __getattr__(self, __name: str):
420
+ return __DummyDocument__
421
+ js.document = __DummyDocument__()
422
+ `);
423
+ await pyodide.loadPackage("matplotlib")?.catch(() => {});
424
+ let pyodidePackage;
425
+ try {
426
+ pyodidePackage = pyodide.pyimport("matplotlib");
427
+ } catch (_) {}
428
+ if (pyodidePackage) {
429
+ pyodide.runPython(`
430
+ import matplotlib.pyplot as plt
431
+ import io
432
+ import basthon
433
+
434
+ def show_chart():
435
+ bytes_io = io.BytesIO()
436
+ plt.savefig(bytes_io, format='jpg')
437
+ bytes_io.seek(0)
438
+ basthon.kernel.display_event({ "display_type": "matplotlib", "content": bytes_io.read() })
439
+ plt.show = show_chart
440
+ `);
441
+ return;
442
+ }
443
+ },
444
+ after: () => {
445
+ pyodide.runPython(`
446
+ import matplotlib.pyplot as plt
447
+ plt.clf()
448
+ `);
449
+ },
450
+ },
451
+ seaborn: {
452
+ before: async () => {
453
+ pyodide.registerJsModule("basthon", fakeBasthonPackage);
454
+ // Patch the document object to prevent matplotlib from trying to render. Since we are running in a web worker,
455
+ // the document object is not available. We will instead capture the image and send it back to the main thread.
456
+ pyodide.runPython(`
457
+ import js
458
+
459
+ class __DummyDocument__:
460
+ def __init__(self, *args, **kwargs) -> None:
461
+ return
462
+ def __getattr__(self, __name: str):
463
+ return __DummyDocument__
464
+ js.document = __DummyDocument__()
465
+ `);
466
+
467
+ // Ensure micropip is loaded which can fetch packages from PyPi.
468
+ // See: https://pyodide.org/en/stable/usage/loading-packages.html
469
+ if (!pyodide.micropip) {
470
+ await pyodide.loadPackage("micropip");
471
+ pyodide.micropip = pyodide.pyimport("micropip");
472
+ }
473
+
474
+ // If the import is for a PyPi package then load it.
475
+ // Otherwise, don't error now so that we get an error later from Python.
476
+ await pyodide.micropip.install("seaborn").catch(() => {});
477
+ },
478
+ after: () => {
479
+ pyodide.runPython(`
480
+ import matplotlib.pyplot as plt
481
+ import io
482
+ import basthon
483
+
484
+ def is_plot_empty():
485
+ fig = plt.gcf()
486
+ for ax in fig.get_axes():
487
+ # Check if the axes contain any lines, patches, collections, etc.
488
+ if ax.lines or ax.patches or ax.collections or ax.images or ax.texts:
489
+ return False
490
+ return True
491
+
492
+ if not is_plot_empty():
493
+ bytes_io = io.BytesIO()
494
+ plt.savefig(bytes_io, format='jpg')
495
+ bytes_io.seek(0)
496
+ basthon.kernel.display_event({ "display_type": "matplotlib", "content": bytes_io.read() })
497
+
498
+ plt.clf()
499
+ `);
500
+ },
501
+ },
502
+ plotly: {
503
+ before: async () => {
504
+ if (!pyodide.micropip) {
505
+ await pyodide.loadPackage("micropip");
506
+ pyodide.micropip = pyodide.pyimport("micropip");
507
+ }
508
+
509
+ // If the import is for a PyPi package then load it.
510
+ // Otherwise, don't error now so that we get an error later from Python.
511
+ await pyodide.micropip.install("plotly").catch(() => {});
512
+ await pyodide.micropip.install("pandas").catch(() => {});
513
+ pyodide.registerJsModule("basthon", fakeBasthonPackage);
514
+ pyodide.runPython(`
515
+ import plotly.graph_objs as go
516
+
517
+ def _hacked_show(self, *args, **kwargs):
518
+ basthon.kernel.display_event({
519
+ "display_type": "plotly",
520
+ "content": self.to_json()
521
+ })
522
+
523
+ go.Figure.show = _hacked_show
524
+ `);
525
+ },
526
+ after: () => {},
527
+ },
528
+ };
529
+
530
+ const fakeBasthonPackage = {
531
+ kernel: {
532
+ display_event: (event) => {
533
+ let payload;
534
+ try {
535
+ payload = event.toJs({ dict_converter: Object.fromEntries });
536
+ } catch (_) {
537
+ payload = event.toJs();
538
+ }
539
+
540
+ const origin = String(payload.display_type);
541
+ const content = toStructuredCloneable(payload.content);
542
+
543
+ postMessage({ method: "handleVisual", origin, content });
544
+ },
545
+ write_file: (event) => {
546
+ let payload;
547
+ try {
548
+ payload = event.toJs({ dict_converter: Object.fromEntries });
549
+ } catch (_) {
550
+ payload = event.toJs();
551
+ }
552
+
553
+ const filename = String(payload.filename);
554
+ const content =
555
+ typeof payload.content === "string"
556
+ ? payload.content
557
+ : toStructuredCloneable(payload.content);
558
+ const mode = String(payload.mode);
559
+
560
+ postMessage({ method: "handleFileWrite", filename, content, mode });
561
+ },
562
+ locals: () => pyodide.runPython("globals()"),
563
+ /**
564
+ * Returns a Promise that resolves with the next line of stdin when the main thread
565
+ * sends stdinResponse. Resolves with null on EOF (e.g. Ctrl+D).
566
+ * Used when SharedArrayBuffer is unavailable (no COOP/COEP) so we cannot block via Atomics.wait.
567
+ * Requires JSPI and runPythonAsync() for run_sync() to work.
568
+ */
569
+ getInputAsync: () => {
570
+ const promise = new Promise((resolve) => {
571
+ pendingStdinResolve = resolve;
572
+ });
573
+ postMessage({ method: "handleInput" });
574
+ return promise;
575
+ },
576
+ },
577
+ };
578
+
579
+ const clearPyodideData = async (userModuleNames) => {
580
+ postMessage({ method: "handleLoading" });
581
+ try {
582
+ await pyodide.runPythonAsync(`
583
+ # Clear all user-defined variables and modules
584
+ for name in list(globals()):
585
+ if not name.startswith('_') and not name=='basthon':
586
+ del globals()[name]
587
+
588
+ import sys
589
+ # Remove user modules from sys.modules
590
+ user_modules = ${JSON.stringify(userModuleNames)}
591
+ for name in user_modules:
592
+ if name in sys.modules:
593
+ del sys.modules[name]
594
+ `);
595
+ } catch (error) {
596
+ console.error("Error while clearing Pyodide data:", error);
597
+ }
598
+ console.log("clearPyodideData done");
599
+ postMessage({ method: "handleLoaded", stdinBuffer, interruptBuffer });
600
+ };
601
+
602
+ const initialisePyodide = async () => {
603
+ postMessage({ method: "handleLoading" });
604
+
605
+ pyodidePromise = loadPyodide({
606
+ stdout: (content) => {
607
+ if (userStdStreamsEnabled && !suppressInternalStdStreams) {
608
+ postMessage({ method: "handleOutput", stream: "stdout", content });
609
+ } else {
610
+ console.log(content);
611
+ }
612
+ },
613
+ stderr: (content) => {
614
+ if (userStdStreamsEnabled && !suppressInternalStdStreams) {
615
+ postMessage({ method: "handleOutput", stream: "stderr", content });
616
+ } else {
617
+ console.error(content);
618
+ }
619
+ },
620
+ });
621
+
622
+ pyodide = await pyodidePromise;
623
+
624
+ pyodide.registerJsModule("basthon", fakeBasthonPackage);
625
+
626
+ // When SharedArrayBuffer is unavailable, always use the postMessage-based
627
+ // stdin path. JSPI / run_sync will raise at runtime if the environment
628
+ // cannot stack-switch, but in JSPI-capable browsers this enables
629
+ // interactive input() without COOP/COEP.
630
+ useMessageStdin = !supportsAllFeatures;
631
+ pyodide.globals.set("__stdin_via_message__", useMessageStdin);
632
+
633
+ await pyodide.runPythonAsync(`
634
+ import builtins
635
+ from pyodide.ffi import run_sync as __run_sync__
636
+
637
+ __old_input__ = builtins.input
638
+ def __patched_input__(prompt=None):
639
+ if prompt is not None:
640
+ print(prompt)
641
+ if __stdin_via_message__:
642
+ result = __run_sync__(basthon.kernel.getInputAsync())
643
+ if result is None:
644
+ raise EOFError("EOF when reading a line")
645
+ return result
646
+ return __old_input__()
647
+ builtins.input = __patched_input__
648
+ `);
649
+
650
+ await pyodide.runPythonAsync(`
651
+ import builtins
652
+ # Save the original open function
653
+ _original_open = builtins.open
654
+ `);
655
+
656
+ await pyodide.loadPackage("pyodide-http");
657
+ await pyodide.runPythonAsync(`
658
+ import pyodide_http
659
+ pyodide_http.patch_all()
660
+ `);
661
+
662
+ if (supportsAllFeatures) {
663
+ stdinBuffer =
664
+ stdinBuffer || new Int32Array(new SharedArrayBuffer(1024 * 1024)); // 1 MiB
665
+ stdinBuffer[0] = 1; // Store the length of content in the buffer at index 0.
666
+ pyodide.setStdin({ isatty: true, read: readFromStdin });
667
+
668
+ interruptBuffer =
669
+ interruptBuffer || new Uint8Array(new SharedArrayBuffer(1));
670
+ pyodide.setInterruptBuffer(interruptBuffer);
671
+ }
672
+
673
+ // From this point on, anything written to stdout / stderr is considered
674
+ // user-visible and will be forwarded to the UI.
675
+ userStdStreamsEnabled = true;
676
+
677
+ postMessage({ method: "handleLoaded", stdinBuffer, interruptBuffer });
678
+ };
679
+
680
+ const readFromStdin = (bufferToWrite) => {
681
+ const previousLength = stdinBuffer[0];
682
+ postMessage({ method: "handleInput" });
683
+
684
+ while (true) {
685
+ pyodide.checkInterrupt();
686
+ const result = Atomics.wait(stdinBuffer, 0, previousLength, 100);
687
+ if (result === "not-equal") {
688
+ break;
689
+ }
690
+ }
691
+
692
+ const currentLength = stdinBuffer[0];
693
+ if (currentLength === -1) {
694
+ return 0;
695
+ } // Signals that stdin was closed.
696
+
697
+ const addedBytes = stdinBuffer.slice(previousLength, currentLength);
698
+ bufferToWrite.set(addedBytes);
699
+
700
+ return addedBytes.length;
701
+ };
702
+
703
+ const parsePythonError = (error) => {
704
+ const type = error.type;
705
+ const [trace, info] = error.message.split(`${type}:`).map((s) => s?.trim());
706
+
707
+ const lines = trace.split("\n");
708
+
709
+ // if the third from last line matches /File "__custom_open__\.py", line (\d+)/g then strip off the last three lines
710
+ if (
711
+ lines.length > 3 &&
712
+ /File "__custom_open__\.py", line (\d+)/g.test(lines[lines.length - 3])
713
+ ) {
714
+ lines.splice(-3, 3);
715
+ }
716
+
717
+ const snippetLine = lines[lines.length - 2]; // print("hi")invalid
718
+ const caretLine = lines[lines.length - 1]; // ^^^^^^^
719
+
720
+ const showsMistake = caretLine.includes("^");
721
+ const mistake = showsMistake
722
+ ? [snippetLine.slice(4), caretLine.slice(4)].join("\n")
723
+ : "";
724
+
725
+ const matches = [
726
+ ...trace.matchAll(/File "(?!__custom_open__\.py)(.*)", line (\d+)/g),
727
+ ];
728
+ const match = matches[matches.length - 1];
729
+
730
+ const path = match ? match[1] : "";
731
+ const base = path.split("/").reverse()[0];
732
+ const file = base === "<exec>" ? "main.py" : base;
733
+
734
+ const line = match ? parseInt(match[2], 10) : "";
735
+
736
+ return { file, line, mistake, type, info };
737
+ };
738
+
739
+ // return {
740
+ // postMessage,
741
+ // onmessage,
742
+ // };
743
+ };
744
+
745
+ globalThis.PyodideWorker = PyodideWorker;
746
+ PyodideWorker();
747
+ // export default PyodideWorker;