petitpy 0.0.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,290 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025-2026 Stefane Fermigier
4
+ Copyright (c) 2013-2025 Damien P. George and the MicroPython contributors
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in
14
+ all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ THE SOFTWARE.
23
+
24
+ --------------------------------------------------------------------------------
25
+
26
+ petitpy builds on MicroPython (https://micropython.org/), whose code is under
27
+ the MIT license above.
28
+
29
+ The modules heapq, bisect and types (nanopython-lib/heapq.py, bisect.py and
30
+ types.py) are verbatim copies from micropython-lib
31
+ (https://github.com/micropython/micropython-lib, commit 381ac746), which
32
+ derives them from CPython. They are under the Python license below, as
33
+ micropython-lib distributes them.
34
+
35
+ =============== Python License ===============
36
+
37
+ A. HISTORY OF THE SOFTWARE
38
+ ==========================
39
+
40
+ Python was created in the early 1990s by Guido van Rossum at Stichting
41
+ Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
42
+ as a successor of a language called ABC. Guido remains Python's
43
+ principal author, although it includes many contributions from others.
44
+
45
+ In 1995, Guido continued his work on Python at the Corporation for
46
+ National Research Initiatives (CNRI, see http://www.cnri.reston.va.us)
47
+ in Reston, Virginia where he released several versions of the
48
+ software.
49
+
50
+ In May 2000, Guido and the Python core development team moved to
51
+ BeOpen.com to form the BeOpen PythonLabs team. In October of the same
52
+ year, the PythonLabs team moved to Digital Creations (now Zope
53
+ Corporation, see http://www.zope.com). In 2001, the Python Software
54
+ Foundation (PSF, see http://www.python.org/psf/) was formed, a
55
+ non-profit organization created specifically to own Python-related
56
+ Intellectual Property. Zope Corporation is a sponsoring member of
57
+ the PSF.
58
+
59
+ All Python releases are Open Source (see http://www.opensource.org for
60
+ the Open Source Definition). Historically, most, but not all, Python
61
+ releases have also been GPL-compatible; the table below summarizes
62
+ the various releases.
63
+
64
+ Release Derived Year Owner GPL-
65
+ from compatible? (1)
66
+
67
+ 0.9.0 thru 1.2 1991-1995 CWI yes
68
+ 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
69
+ 1.6 1.5.2 2000 CNRI no
70
+ 2.0 1.6 2000 BeOpen.com no
71
+ 1.6.1 1.6 2001 CNRI yes (2)
72
+ 2.1 2.0+1.6.1 2001 PSF no
73
+ 2.0.1 2.0+1.6.1 2001 PSF yes
74
+ 2.1.1 2.1+2.0.1 2001 PSF yes
75
+ 2.1.2 2.1.1 2002 PSF yes
76
+ 2.1.3 2.1.2 2002 PSF yes
77
+ 2.2 and above 2.1.1 2001-now PSF yes
78
+
79
+ Footnotes:
80
+
81
+ (1) GPL-compatible doesn't mean that we're distributing Python under
82
+ the GPL. All Python licenses, unlike the GPL, let you distribute
83
+ a modified version without making your changes open source. The
84
+ GPL-compatible licenses make it possible to combine Python with
85
+ other software that is released under the GPL; the others don't.
86
+
87
+ (2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
88
+ because its license has a choice of law clause. According to
89
+ CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
90
+ is "not incompatible" with the GPL.
91
+
92
+ Thanks to the many outside volunteers who have worked under Guido's
93
+ direction to make these releases possible.
94
+
95
+
96
+ B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
97
+ ===============================================================
98
+
99
+ PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
100
+ --------------------------------------------
101
+
102
+ 1. This LICENSE AGREEMENT is between the Python Software Foundation
103
+ ("PSF"), and the Individual or Organization ("Licensee") accessing and
104
+ otherwise using this software ("Python") in source or binary form and
105
+ its associated documentation.
106
+
107
+ 2. Subject to the terms and conditions of this License Agreement, PSF hereby
108
+ grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
109
+ analyze, test, perform and/or display publicly, prepare derivative works,
110
+ distribute, and otherwise use Python alone or in any derivative version,
111
+ provided, however, that PSF's License Agreement and PSF's notice of copyright,
112
+ i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
113
+ 2011, 2012, 2013 Python Software Foundation; All Rights Reserved" are retained
114
+ in Python alone or in any derivative version prepared by Licensee.
115
+
116
+ 3. In the event Licensee prepares a derivative work that is based on
117
+ or incorporates Python or any part thereof, and wants to make
118
+ the derivative work available to others as provided herein, then
119
+ Licensee hereby agrees to include in any such work a brief summary of
120
+ the changes made to Python.
121
+
122
+ 4. PSF is making Python available to Licensee on an "AS IS"
123
+ basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
124
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
125
+ DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
126
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
127
+ INFRINGE ANY THIRD PARTY RIGHTS.
128
+
129
+ 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
130
+ FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
131
+ A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
132
+ OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
133
+
134
+ 6. This License Agreement will automatically terminate upon a material
135
+ breach of its terms and conditions.
136
+
137
+ 7. Nothing in this License Agreement shall be deemed to create any
138
+ relationship of agency, partnership, or joint venture between PSF and
139
+ Licensee. This License Agreement does not grant permission to use PSF
140
+ trademarks or trade name in a trademark sense to endorse or promote
141
+ products or services of Licensee, or any third party.
142
+
143
+ 8. By copying, installing or otherwise using Python, Licensee
144
+ agrees to be bound by the terms and conditions of this License
145
+ Agreement.
146
+
147
+
148
+ BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
149
+ -------------------------------------------
150
+
151
+ BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
152
+
153
+ 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
154
+ office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
155
+ Individual or Organization ("Licensee") accessing and otherwise using
156
+ this software in source or binary form and its associated
157
+ documentation ("the Software").
158
+
159
+ 2. Subject to the terms and conditions of this BeOpen Python License
160
+ Agreement, BeOpen hereby grants Licensee a non-exclusive,
161
+ royalty-free, world-wide license to reproduce, analyze, test, perform
162
+ and/or display publicly, prepare derivative works, distribute, and
163
+ otherwise use the Software alone or in any derivative version,
164
+ provided, however, that the BeOpen Python License is retained in the
165
+ Software, alone or in any derivative version prepared by Licensee.
166
+
167
+ 3. BeOpen is making the Software available to Licensee on an "AS IS"
168
+ basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
169
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
170
+ DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
171
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
172
+ INFRINGE ANY THIRD PARTY RIGHTS.
173
+
174
+ 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
175
+ SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
176
+ AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
177
+ DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
178
+
179
+ 5. This License Agreement will automatically terminate upon a material
180
+ breach of its terms and conditions.
181
+
182
+ 6. This License Agreement shall be governed by and interpreted in all
183
+ respects by the law of the State of California, excluding conflict of
184
+ law provisions. Nothing in this License Agreement shall be deemed to
185
+ create any relationship of agency, partnership, or joint venture
186
+ between BeOpen and Licensee. This License Agreement does not grant
187
+ permission to use BeOpen trademarks or trade names in a trademark
188
+ sense to endorse or promote products or services of Licensee, or any
189
+ third party. As an exception, the "BeOpen Python" logos available at
190
+ http://www.pythonlabs.com/logos.html may be used according to the
191
+ permissions granted on that web page.
192
+
193
+ 7. By copying, installing or otherwise using the software, Licensee
194
+ agrees to be bound by the terms and conditions of this License
195
+ Agreement.
196
+
197
+
198
+ CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
199
+ ---------------------------------------
200
+
201
+ 1. This LICENSE AGREEMENT is between the Corporation for National
202
+ Research Initiatives, having an office at 1895 Preston White Drive,
203
+ Reston, VA 20191 ("CNRI"), and the Individual or Organization
204
+ ("Licensee") accessing and otherwise using Python 1.6.1 software in
205
+ source or binary form and its associated documentation.
206
+
207
+ 2. Subject to the terms and conditions of this License Agreement, CNRI
208
+ hereby grants Licensee a nonexclusive, royalty-free, world-wide
209
+ license to reproduce, analyze, test, perform and/or display publicly,
210
+ prepare derivative works, distribute, and otherwise use Python 1.6.1
211
+ alone or in any derivative version, provided, however, that CNRI's
212
+ License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
213
+ 1995-2001 Corporation for National Research Initiatives; All Rights
214
+ Reserved" are retained in Python 1.6.1 alone or in any derivative
215
+ version prepared by Licensee. Alternately, in lieu of CNRI's License
216
+ Agreement, Licensee may substitute the following text (omitting the
217
+ quotes): "Python 1.6.1 is made available subject to the terms and
218
+ conditions in CNRI's License Agreement. This Agreement together with
219
+ Python 1.6.1 may be located on the Internet using the following
220
+ unique, persistent identifier (known as a handle): 1895.22/1013. This
221
+ Agreement may also be obtained from a proxy server on the Internet
222
+ using the following URL: http://hdl.handle.net/1895.22/1013".
223
+
224
+ 3. In the event Licensee prepares a derivative work that is based on
225
+ or incorporates Python 1.6.1 or any part thereof, and wants to make
226
+ the derivative work available to others as provided herein, then
227
+ Licensee hereby agrees to include in any such work a brief summary of
228
+ the changes made to Python 1.6.1.
229
+
230
+ 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
231
+ basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
232
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
233
+ DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
234
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
235
+ INFRINGE ANY THIRD PARTY RIGHTS.
236
+
237
+ 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
238
+ 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
239
+ A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
240
+ OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
241
+
242
+ 6. This License Agreement will automatically terminate upon a material
243
+ breach of its terms and conditions.
244
+
245
+ 7. This License Agreement shall be governed by the federal
246
+ intellectual property law of the United States, including without
247
+ limitation the federal copyright law, and, to the extent such
248
+ U.S. federal law does not apply, by the law of the Commonwealth of
249
+ Virginia, excluding Virginia's conflict of law provisions.
250
+ Notwithstanding the foregoing, with regard to derivative works based
251
+ on Python 1.6.1 that incorporate non-separable material that was
252
+ previously distributed under the GNU General Public License (GPL), the
253
+ law of the Commonwealth of Virginia shall govern this License
254
+ Agreement only as to issues arising under or with respect to
255
+ Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
256
+ License Agreement shall be deemed to create any relationship of
257
+ agency, partnership, or joint venture between CNRI and Licensee. This
258
+ License Agreement does not grant permission to use CNRI trademarks or
259
+ trade name in a trademark sense to endorse or promote products or
260
+ services of Licensee, or any third party.
261
+
262
+ 8. By clicking on the "ACCEPT" button where indicated, or by copying,
263
+ installing or otherwise using Python 1.6.1, Licensee agrees to be
264
+ bound by the terms and conditions of this License Agreement.
265
+
266
+ ACCEPT
267
+
268
+
269
+ CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
270
+ --------------------------------------------------
271
+
272
+ Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
273
+ The Netherlands. All rights reserved.
274
+
275
+ Permission to use, copy, modify, and distribute this software and its
276
+ documentation for any purpose and without fee is hereby granted,
277
+ provided that the above copyright notice appear in all copies and that
278
+ both that copyright notice and this permission notice appear in
279
+ supporting documentation, and that the name of Stichting Mathematisch
280
+ Centrum or CWI not be used in advertising or publicity pertaining to
281
+ distribution of the software without specific, written prior
282
+ permission.
283
+
284
+ STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
285
+ THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
286
+ FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
287
+ FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
288
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
289
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
290
+ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -1 +1,21 @@
1
1
  # petitpy
2
+
3
+ petitpy is a small Python runtime for the browser and Node (developed as nanopython): written in Zig, with direct DOM access from Python through the `js` module, building on MicroPython, whose `.mpy` bytecode it shares. The wasm is about 333 KB (164 KB gzipped).
4
+
5
+ ```js
6
+ import { loadPetitpy } from "petitpy";
7
+
8
+ const py = await loadPetitpy();
9
+ const { stdout, stderr, exitCode } = await py.run('print("hello from", 6 * 7)');
10
+ ```
11
+
12
+ `loadPetitpy()` compiles `petitpy.wasm` once; pass `{ wasm }` (a URL, a `Response`, bytes or a `WebAssembly.Module`) to load it from elsewhere. Each `run(source, options)` gets a fresh instance:
13
+
14
+ - `stdin`: text for `input()`.
15
+ - `files`: extra files by path; modules under `lib/` are importable.
16
+ - `argv`: `sys.argv[1:]`.
17
+ - `onStdout`, `onStderr`: called per printed line, also after `run()` returns, for programs that keep running through JS callbacks.
18
+
19
+ From Python, `import js` reaches the page: `js.document.getElementById("out").textContent = "hi"`.
20
+
21
+ This is an alpha. The language is close to CPython (Unicode strings, `match`, floats, exception chaining) with MicroPython's limits: no arbitrary-precision integers in the browser build, dicts are not insertion-ordered, `upper()`/`lower()` are ASCII-only. See the [differences from CPython](https://petitpy.lab.abilian.com/differences/) and the [playground](https://petitpy.lab.abilian.com/play/demos/playground/).
package/index.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ export interface RunOptions {
2
+ /** Text read by input() and sys.stdin. */
3
+ stdin?: string;
4
+ /** Extra files, by path; put importable modules under "lib/". */
5
+ files?: Record<string, string | Uint8Array>;
6
+ /** Arguments after the script name (sys.argv[1:]). */
7
+ argv?: string[];
8
+ /** Called with each line printed to stdout, including after run() returns. */
9
+ onStdout?: (line: string) => void;
10
+ /** Called with each line printed to stderr. */
11
+ onStderr?: (line: string) => void;
12
+ }
13
+
14
+ export interface RunResult {
15
+ stdout: string;
16
+ stderr: string;
17
+ exitCode: number;
18
+ /** The live instance, for programs that keep running through JS callbacks. */
19
+ instance: WebAssembly.Instance;
20
+ }
21
+
22
+ export interface Petitpy {
23
+ module: WebAssembly.Module;
24
+ run(source: string, options?: RunOptions): Promise<RunResult>;
25
+ }
26
+
27
+ /** Compile petitpy.wasm once (default: the file shipped next to this module). */
28
+ export function loadPetitpy(options?: {
29
+ wasm?: URL | string | Response | ArrayBuffer | ArrayBufferView | WebAssembly.Module;
30
+ }): Promise<Petitpy>;
package/index.js ADDED
@@ -0,0 +1,72 @@
1
+ // petitpy for the browser and Node: run Python source on the wasm build.
2
+ //
3
+ // import { loadPetitpy } from "petitpy";
4
+ // const py = await loadPetitpy();
5
+ // const { stdout, stderr, exitCode } = await py.run('print("hello")');
6
+ //
7
+ // Each run gets a fresh instance of the compiled module, over a virtual
8
+ // filesystem holding the program at /main.py and any `files` you pass
9
+ // (put modules under "lib/" to import them). The instance stays alive
10
+ // after run() returns, so a program that registers JS callbacks (DOM
11
+ // events, timers through the `js` module) keeps running; their output
12
+ // goes to onStdout / onStderr.
13
+
14
+ import { WASI, File, Directory, OpenFile, PreopenDirectory, ConsoleStdout } from "@bjorn3/browser_wasi_shim";
15
+ import { makeJsBridge } from "./js-bridge.js";
16
+ import { addFile } from "./wasi-fs.js";
17
+
18
+ const DEFAULT_WASM = new URL("./petitpy.wasm", import.meta.url);
19
+
20
+
21
+ async function compile(wasm) {
22
+ if (wasm instanceof WebAssembly.Module) return wasm;
23
+ if (wasm instanceof ArrayBuffer || ArrayBuffer.isView(wasm)) return WebAssembly.compile(wasm);
24
+ const resp = wasm instanceof Response ? wasm : await fetch(wasm);
25
+ if (!resp.ok) throw new Error(`petitpy: fetching the wasm failed (${resp.status})`);
26
+ return WebAssembly.compileStreaming
27
+ ? WebAssembly.compileStreaming(resp)
28
+ : WebAssembly.compile(await resp.arrayBuffer());
29
+ }
30
+
31
+ /**
32
+ * Compile petitpy.wasm once; `wasm` is a URL, a Response, bytes or a
33
+ * WebAssembly.Module (default: the file next to this module).
34
+ */
35
+ export async function loadPetitpy({ wasm = DEFAULT_WASM } = {}) {
36
+ const module = await compile(wasm);
37
+ const encoder = new TextEncoder();
38
+
39
+ async function run(source, { stdin = "", files = {}, argv = [], onStdout, onStderr } = {}) {
40
+ let stdout = "";
41
+ let stderr = "";
42
+ const fsMap = new Map([["main.py", new File(encoder.encode(source), { readonly: true })]]);
43
+ for (const [path, content] of Object.entries(files)) {
44
+ const bytes = typeof content === "string" ? encoder.encode(content) : content;
45
+ addFile(fsMap, path, new File(bytes, { readonly: true }), Directory);
46
+ }
47
+ const fds = [
48
+ new OpenFile(new File(encoder.encode(stdin), { readonly: true })),
49
+ ConsoleStdout.lineBuffered((line) => {
50
+ stdout += line + "\n";
51
+ onStdout?.(line);
52
+ }),
53
+ ConsoleStdout.lineBuffered((line) => {
54
+ stderr += line + "\n";
55
+ onStderr?.(line);
56
+ }),
57
+ new PreopenDirectory("/", fsMap),
58
+ ];
59
+ const wasi = new WASI(["petitpy", "/main.py", ...argv], ["PETITPY_LIB=/lib"], fds, { debug: false });
60
+ const bridge = makeJsBridge();
61
+ const instance = await WebAssembly.instantiate(module, {
62
+ wasi_snapshot_preview1: wasi.wasiImport,
63
+ env: bridge.imports,
64
+ });
65
+ bridge.attachMemory(instance.exports.memory);
66
+ bridge.attachExports(instance.exports);
67
+ const exitCode = wasi.start(instance);
68
+ return { stdout, stderr, exitCode, instance };
69
+ }
70
+
71
+ return { module, run };
72
+ }
package/js-bridge.js ADDED
@@ -0,0 +1,197 @@
1
+ // ADR-006 J3 — JS-side bridge.
2
+ //
3
+ // Maintains a handle table mapping wasm-side u32 IDs to JS object references.
4
+ // Provides the imports object that nanopython.wasm expects under the
5
+ // `nanopython_js` namespace alongside the WASI `wasi_snapshot_preview1`
6
+ // imports. The Zig side declares the externs in js_bridge.zig with the
7
+ // default `env` module-name convention; the playground loader merges them
8
+ // into both `env` and `nanopython_js` namespaces so either resolution
9
+ // path works depending on how the compiler emitted the wasm import.
10
+ //
11
+ // Handle 0 is reserved for null / undefined; allocation starts at 1.
12
+ //
13
+ // J4 — `this` binding for method calls. When `js_get_attr` resolves to a
14
+ // function value, we store a {receiver, fn} bound-method record in the
15
+ // handle table rather than the bare function. `js_call` then invokes via
16
+ // `fn.apply(receiver, ...)` so `document.getElementById("x")` (and any
17
+ // other method that depends on `this`) sees the correct receiver. Bare
18
+ // functions (e.g. `js.parseInt`) are still called without a `this`.
19
+
20
+ export function makeJsBridge() {
21
+ const handles = new Map();
22
+ let nextHandle = 1;
23
+
24
+ // Pre-populate handle 0 with null/undefined so a fresh `js_get_global`
25
+ // of a missing property returns 0 -> null (consistent with the Python
26
+ // proxy's __str__ → "undefined" path).
27
+ handles.set(0, null);
28
+
29
+ function newHandle(value) {
30
+ // Reuse handle 0 for null/undefined so cleanup doesn't have to
31
+ // double-track them.
32
+ if (value === null || value === undefined) return 0;
33
+ const h = nextHandle++;
34
+ handles.set(h, value);
35
+ return h;
36
+ }
37
+
38
+ function newBoundMethod(receiver, fn) {
39
+ const h = nextHandle++;
40
+ handles.set(h, { __bound: true, receiver, fn });
41
+ return h;
42
+ }
43
+
44
+ // Resolve a handle to the underlying JS value. Bound-method records
45
+ // unwrap to their `fn` — callers that need to invoke with the receiver
46
+ // (i.e. js_call) inspect the record directly; everywhere else (passing
47
+ // as argument, set_attr, to_string) the JS-visible value is the fn.
48
+ function valueOf(handle) {
49
+ const v = handles.get(handle);
50
+ if (v && typeof v === "object" && v.__bound === true) return v.fn;
51
+ return v;
52
+ }
53
+
54
+ function readMemString(memory, ptr, len) {
55
+ const bytes = new Uint8Array(memory.buffer, ptr, len);
56
+ return new TextDecoder().decode(bytes);
57
+ }
58
+
59
+ let memory; // bound after WebAssembly.instantiate.
60
+ let wasmExports; // bound after WebAssembly.instantiate (for export callbacks).
61
+
62
+ const imports = {
63
+ js_get_global(namePtr, nameLen) {
64
+ const name = readMemString(memory, namePtr, nameLen);
65
+ return newHandle(globalThis[name]);
66
+ },
67
+ js_get_attr(handle, namePtr, nameLen) {
68
+ const obj = valueOf(handle);
69
+ if (obj == null) return 0;
70
+ const name = readMemString(memory, namePtr, nameLen);
71
+ const v = obj[name];
72
+ // Functions get remembered with their receiver so `this` is bound
73
+ // correctly when called. Non-function values use a plain handle.
74
+ if (typeof v === "function") return newBoundMethod(obj, v);
75
+ return newHandle(v);
76
+ },
77
+ js_set_attr(handle, namePtr, nameLen, valueHandle) {
78
+ const obj = valueOf(handle);
79
+ if (obj == null) return;
80
+ const name = readMemString(memory, namePtr, nameLen);
81
+ obj[name] = valueOf(valueHandle);
82
+ },
83
+ js_call(handle, argsPtr, argsCount) {
84
+ const entry = handles.get(handle);
85
+ const argsView = new Uint32Array(memory.buffer, argsPtr, argsCount);
86
+ const args = Array.from(argsView).map((h) => valueOf(h));
87
+ if (entry && typeof entry === "object" && entry.__bound === true) {
88
+ return newHandle(entry.fn.apply(entry.receiver, args));
89
+ }
90
+ if (typeof entry !== "function") {
91
+ throw new Error(`js_call: handle ${handle} is not a function`);
92
+ }
93
+ return newHandle(entry(...args));
94
+ },
95
+ js_release(handle) {
96
+ if (handle === 0) return;
97
+ handles.delete(handle);
98
+ },
99
+ js_create_string(ptr, len) {
100
+ return newHandle(readMemString(memory, ptr, len));
101
+ },
102
+ js_create_int(value) {
103
+ return newHandle(value);
104
+ },
105
+ js_to_string_len(handle) {
106
+ const s = String(valueOf(handle));
107
+ return new TextEncoder().encode(s).length;
108
+ },
109
+ js_to_string(handle, outPtr, outMax) {
110
+ const s = String(valueOf(handle));
111
+ const bytes = new TextEncoder().encode(s);
112
+ const len = Math.min(bytes.length, outMax);
113
+ new Uint8Array(memory.buffer, outPtr, len).set(bytes.subarray(0, len));
114
+ return len;
115
+ },
116
+ js_to_int(handle) {
117
+ const v = valueOf(handle);
118
+ return v | 0;
119
+ },
120
+ js_bridge_present() {
121
+ return 1;
122
+ },
123
+ // J5a — Python registered a callable; mint a JS function that, when
124
+ // called, fires npy_dispatch_callback(id, args_ptr, args_count) back
125
+ // into wasm. The JS function's argument values are first allocated
126
+ // as bridge handles, then their handles are spilled into wasm memory
127
+ // as a u32 array on the wasm stack (via `__npy_alloc_arg_buf` if
128
+ // available; otherwise we accept a hard limit and use a scratch
129
+ // region from `npy_dispatch_alloc`/free pair). For the first cut
130
+ // we use a static scratch slab in wasm memory exposed by the runtime
131
+ // — but to keep the bridge JS self-contained we instead allocate a
132
+ // small Uint32Array attached to the wasm linear memory via a fresh
133
+ // `WebAssembly.Memory.grow`-free strategy: copy into a fixed offset
134
+ // in the existing memory's data segment that's set aside by the
135
+ // runtime. For now we cap at 8 args and use a JS-side TypedArray
136
+ // backed by wasm memory at a runtime-provided scratch ptr. To avoid
137
+ // the scratch-ptr lookup complexity for the J5a slice we use a
138
+ // simpler shape: we allocate args by writing into the existing
139
+ // bridge `handles` map and pass a synthetic ptr=0 with the args
140
+ // count = 0 when there are no args. With args > 0 we write to a
141
+ // freshly grown region. To stay simple, J5a supports zero-arg
142
+ // callbacks (the common `addEventListener("click", py_fn)`
143
+ // shape) — multi-arg event handlers will land with a Python-side
144
+ // event marshaler in a follow-up.
145
+ js_create_callback(callbackId) {
146
+ const fn = function (...args) {
147
+ if (!wasmExports || !wasmExports.npy_dispatch_callback) return undefined;
148
+ // Marshal JS args to bridge handles first.
149
+ const argHandles = args.map((a) => newHandle(a));
150
+ let resultHandle;
151
+ if (argHandles.length === 0) {
152
+ resultHandle = wasmExports.npy_dispatch_callback(callbackId, 0, 0);
153
+ } else {
154
+ // Stage the handle array into wasm linear memory using the
155
+ // MicroPython GC allocator (`m_malloc` is exported from the
156
+ // runtime). We don't free — the allocation is a tiny u32[] per
157
+ // dispatch and the runtime's GC reclaims it; trading a
158
+ // negligible leak for not having to export m_free here.
159
+ //
160
+ // Until this landed, the bridge probed for `malloc`/`free` (not
161
+ // exported by nanopython) and fell through to dropping args,
162
+ // which made Promise.then(cb) callbacks appear to never fire —
163
+ // the dispatch ran but Python's `cb` raised TypeError "missing
164
+ // 1 required argument" (the resolved value) and the dispatcher's
165
+ // broad `except Exception` swallowed it.
166
+ if (wasmExports.m_malloc) {
167
+ const ptr = wasmExports.m_malloc(argHandles.length * 4);
168
+ new Uint32Array(memory.buffer, ptr, argHandles.length).set(argHandles);
169
+ resultHandle = wasmExports.npy_dispatch_callback(callbackId, ptr, argHandles.length);
170
+ } else if (wasmExports.malloc && wasmExports.free) {
171
+ const ptr = wasmExports.malloc(argHandles.length * 4);
172
+ new Uint32Array(memory.buffer, ptr, argHandles.length).set(argHandles);
173
+ resultHandle = wasmExports.npy_dispatch_callback(callbackId, ptr, argHandles.length);
174
+ wasmExports.free(ptr);
175
+ } else {
176
+ // No allocator available — drop args. The Python callback
177
+ // receives zero proxies. addEventListener("click", fn) works
178
+ // (no args needed); event-object access requires an allocator.
179
+ resultHandle = wasmExports.npy_dispatch_callback(callbackId, 0, 0);
180
+ }
181
+ }
182
+ return valueOf(resultHandle);
183
+ };
184
+ return newHandle(fn);
185
+ },
186
+ };
187
+
188
+ function attachMemory(wasmMemory) {
189
+ memory = wasmMemory;
190
+ }
191
+
192
+ function attachExports(exports) {
193
+ wasmExports = exports;
194
+ }
195
+
196
+ return { imports, attachMemory, attachExports, handles };
197
+ }
package/package.json CHANGED
@@ -1,6 +1,21 @@
1
- {
2
- "name": "petitpy",
3
- "version": "0.0.1",
4
- "description": "A small Python runtime for the browser (placeholder; first release soon).",
5
- "license": "MIT"
6
- }
1
+ {
2
+ "name": "petitpy",
3
+ "version": "0.8.0",
4
+ "description": "A small Python runtime for the browser: MicroPython-compatible, written in Zig, 333 KB of wasm with direct DOM access.",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "types": "./index.d.ts",
8
+ "exports": {
9
+ ".": { "types": "./index.d.ts", "default": "./index.js" },
10
+ "./petitpy.wasm": "./petitpy.wasm",
11
+ "./js-bridge.js": "./js-bridge.js"
12
+ },
13
+ "files": ["index.js", "index.d.ts", "js-bridge.js", "wasi-fs.js", "petitpy.wasm", "README.md", "LICENSE"],
14
+ "dependencies": {
15
+ "@bjorn3/browser_wasi_shim": "^0.4.2"
16
+ },
17
+ "keywords": ["python", "micropython", "wasm", "webassembly", "interpreter", "browser"],
18
+ "license": "MIT AND PSF-2.0",
19
+ "homepage": "https://petitpy.lab.abilian.com/",
20
+ "repository": { "type": "git", "url": "https://github.com/abilian/petitpy" }
21
+ }
package/petitpy.wasm ADDED
Binary file
package/wasi-fs.js ADDED
@@ -0,0 +1,17 @@
1
+ // The browser WASI shim keys a directory's entries by name, so "lib/x.py"
2
+ // needs a "lib" Directory holding "x.py"; a flat "lib/x.py" key is never
3
+ // found. `Directory` is the shim's class, passed in so this module works
4
+ // with the shim from a CDN (the pages) or from npm (the package).
5
+ export function addFile(root, path, file, Directory) {
6
+ const parts = path.split("/").filter(Boolean);
7
+ let dir = root;
8
+ for (const name of parts.slice(0, -1)) {
9
+ let sub = dir.get(name);
10
+ if (!(sub instanceof Directory)) {
11
+ sub = new Directory(new Map());
12
+ dir.set(name, sub);
13
+ }
14
+ dir = sub.contents;
15
+ }
16
+ dir.set(parts[parts.length - 1], file);
17
+ }