pyte-cli 0.2.0__py3-none-any.whl

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.
pyte.py ADDED
@@ -0,0 +1,514 @@
1
+ #!/usr/bin/env python3
2
+ """pyte: tiny Vite-like tool for Python in the browser, with its own wasm interpreter."""
3
+ import argparse, hashlib, html, json, mimetypes, shutil, socket, sys
4
+ import threading, time, tomllib, urllib.request
5
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
6
+ from pathlib import Path
7
+ from urllib.parse import unquote, urlsplit
8
+
9
+ CONFIG = "pyte.toml"
10
+ RUNTIME = Path(__file__).resolve().parent / "pyte_runtime"
11
+ RUNTIME_FILES = ("pyte.wasm", "wasm_exec.js", "LICENSE-go.txt")
12
+ DEFAULTS = {
13
+ "project": {"title": "pyte app", "entry": "src/main.py"},
14
+ "server": {"host": "127.0.0.1", "port": 9473},
15
+ "assets": {"dir": "assets", "favicon": "", "touch_icon": ""},
16
+ "build": {"out": "dist"},
17
+ "app": {"mode": "page", "standalone": False},
18
+ "fs": {"enabled": False, "persist": True},
19
+ }
20
+
21
+ PAGE = """<!doctype html>
22
+ <html lang="en">
23
+ <head>
24
+ <meta charset="utf-8">
25
+ <meta name="viewport" content="width=device-width, initial-scale=1">
26
+ <title>__TITLE__</title>
27
+ __ICON__
28
+ <style>
29
+ body { font-family: system-ui, sans-serif; margin: 2rem; }
30
+ #out { white-space: pre-wrap; font-family: ui-monospace, monospace; }
31
+ .err { color: #c00; }
32
+ #line { display: flex; font-family: ui-monospace, monospace; }
33
+ #line[hidden] { display: none; }
34
+ #ps { white-space: pre; }
35
+ #cmd { flex: 1; min-width: 4rem; font: inherit; border: 0; outline: 0; background: transparent; color: inherit; padding: 0; }
36
+ </style>
37
+ </head>
38
+ <body>
39
+ <div id="app"></div>
40
+ <div id="status">Loading Python...</div>
41
+ <div id="out"></div>
42
+ <form id="line" hidden><label id="ps" for="cmd"></label><input id="cmd" autocomplete="off" autocapitalize="off" spellcheck="false"></form>
43
+ <script src="runtime/wasm_exec.js"></script>
44
+ <script>
45
+ const cfg = __CFG__;
46
+ const out = document.getElementById("out");
47
+ const status = document.getElementById("status");
48
+ window.pyteWrite = (text, cls) => {
49
+ const line = document.createElement("div");
50
+ line.textContent = text;
51
+ if (cls) line.className = cls;
52
+ out.appendChild(line);
53
+ };
54
+ window.pyteClear = () => {
55
+ document.getElementById("app").replaceChildren();
56
+ out.replaceChildren();
57
+ line.hidden = true;
58
+ window.pyteBusy = cfg.mode === "cli";
59
+ };
60
+ window.pyteClearOutput = () => out.replaceChildren();
61
+
62
+ // terminal (CLI mode)
63
+ const line = document.getElementById("line");
64
+ const cmd = document.getElementById("cmd");
65
+ const ps = document.getElementById("ps");
66
+ const past = [];
67
+ let at = 0;
68
+ let asking = false;
69
+ window.pyteBusy = cfg.mode === "cli";
70
+ function showLine(text) {
71
+ ps.textContent = text;
72
+ line.hidden = false;
73
+ cmd.focus();
74
+ line.scrollIntoView({ block: "nearest" });
75
+ }
76
+ window.pyteAsk = (question) => { asking = true; window.pyteBusy = true; showLine(question); };
77
+ window.pyteDone = (prompt) => { asking = false; window.pyteBusy = false; showLine(prompt); };
78
+ line.addEventListener("submit", (e) => {
79
+ e.preventDefault();
80
+ const text = cmd.value;
81
+ cmd.value = "";
82
+ window.pyteWrite(ps.textContent + text);
83
+ if (!asking && text.trim()) past.push(text);
84
+ at = past.length;
85
+ asking = false;
86
+ line.hidden = true;
87
+ window.pyteBusy = true;
88
+ setTimeout(() => window.pyteSubmit(text), 0);
89
+ });
90
+ cmd.addEventListener("keydown", (e) => {
91
+ if (e.key === "Tab" && ps.textContent === "... ") {
92
+ e.preventDefault();
93
+ cmd.setRangeText(" ", cmd.selectionStart, cmd.selectionEnd, "end");
94
+ } else if ((e.key === "ArrowUp" || e.key === "ArrowDown") && !asking) {
95
+ e.preventDefault();
96
+ at = Math.max(0, Math.min(past.length, at + (e.key === "ArrowUp" ? -1 : 1)));
97
+ cmd.value = past[at] || "";
98
+ }
99
+ });
100
+
101
+ // files written by Python, kept in this browser
102
+ let memory = null;
103
+ window.pyteSave = (files, dirs) => {
104
+ memory = { files, dirs };
105
+ if (!cfg.persist) return;
106
+ try { localStorage.setItem(cfg.store, JSON.stringify(memory)); }
107
+ catch (e) { window.pyteWrite("could not save files in this browser: " + e.message, "err"); }
108
+ };
109
+ function saved() {
110
+ if (memory || !cfg.persist) return memory;
111
+ try { return JSON.parse(localStorage.getItem(cfg.store)); }
112
+ catch (e) { return null; }
113
+ }
114
+ let ready = false;
115
+ async function load(hash) {
116
+ const res = await fetch("app.json?v=" + hash, { cache: "no-store" });
117
+ if (!res.ok) throw new Error("app.json: HTTP " + res.status);
118
+ return res.json();
119
+ }
120
+ async function main() {
121
+ const go = new Go();
122
+ const started = new Promise((resolve) => { window.pyteReady = resolve; });
123
+ const res = await fetch("runtime/pyte.wasm?v=" + cfg.runtime);
124
+ if (!res.ok) throw new Error("pyte.wasm: HTTP " + res.status);
125
+ const { instance } = await WebAssembly.instantiate(await res.arrayBuffer(), go.importObject);
126
+ go.run(instance).then(() => {
127
+ ready = false;
128
+ window.pyteWrite("Python stopped. Reload page.", "err");
129
+ });
130
+ await started;
131
+ const files = await load(cfg.hash);
132
+ status.remove();
133
+ ready = true;
134
+ window.pyteRun(files, cfg, saved());
135
+ }
136
+ main().catch((e) => { status.remove(); window.pyteWrite(String(e), "err"); });
137
+ </script>
138
+ __RELOAD__
139
+ </body>
140
+ </html>
141
+ """
142
+
143
+ RELOAD = """<script>
144
+ let seen = "__HASH__";
145
+ async function poll() {
146
+ try {
147
+ const r = await fetch("/__pyte/version", { cache: "no-store" });
148
+ const v = await r.json();
149
+ if (v.hash !== seen) {
150
+ // full page reload only if page changed, Python is not running, or a command is unfinished
151
+ if (v.shell !== cfg.shell || !ready || window.pyteBusy) return location.reload();
152
+ const files = await load(v.hash);
153
+ seen = v.hash;
154
+ window.pyteRun(files, cfg, saved());
155
+ }
156
+ } catch (e) {}
157
+ setTimeout(poll, 800);
158
+ }
159
+ poll();
160
+ </script>"""
161
+
162
+
163
+ class PyteError(Exception):
164
+ pass
165
+
166
+
167
+ def load_config(root):
168
+ path = root / CONFIG
169
+ if not path.is_file():
170
+ raise PyteError(f"no {CONFIG} in {root} (run: pyte init)")
171
+ try:
172
+ user = tomllib.loads(path.read_text("utf-8"))
173
+ except tomllib.TOMLDecodeError as e:
174
+ raise PyteError(f"{CONFIG}: {e}")
175
+ cfg = {k: dict(v) for k, v in DEFAULTS.items()}
176
+ for section, values in user.items():
177
+ if section not in cfg or not isinstance(values, dict):
178
+ raise PyteError(f"{CONFIG}: unknown section [{section}]")
179
+ for key, value in values.items():
180
+ if section == "build" and key in ("runtime", "packages"):
181
+ if value not in ("bundle", "cdn", []):
182
+ raise PyteError(f"{CONFIG}: build.{key} no longer supported, remove it")
183
+ continue
184
+ if key not in cfg[section]:
185
+ raise PyteError(f"{CONFIG}: unknown key {section}.{key}")
186
+ if type(value) is not type(cfg[section][key]):
187
+ raise PyteError(f"{CONFIG}: {section}.{key} has wrong type")
188
+ cfg[section][key] = value
189
+ if not 1 <= cfg["server"]["port"] <= 65535:
190
+ raise PyteError("server.port must be 1-65535")
191
+ if cfg["app"]["mode"] not in ("page", "cli"):
192
+ raise PyteError('app.mode must be "page" or "cli"')
193
+ return cfg
194
+
195
+
196
+ def inside(root, rel, label):
197
+ path = (root / rel).resolve()
198
+ if not path.is_relative_to(root.resolve()) or path == root.resolve():
199
+ raise PyteError(f"{label} must be a path inside {root}: {rel!r}")
200
+ return path
201
+
202
+
203
+ def source_files(root, cfg):
204
+ """Only the entry's folder and the assets folder get published."""
205
+ entry = inside(root, cfg["project"]["entry"], "project.entry")
206
+ if not entry.is_file():
207
+ raise PyteError(f"entry not found: {cfg['project']['entry']}")
208
+ if entry.parent == root.resolve():
209
+ raise PyteError("project.entry must live in a subfolder, e.g. src/main.py")
210
+ dirs = [entry.parent, inside(root, cfg["assets"]["dir"], "assets.dir")]
211
+ files = {}
212
+ for d in dirs:
213
+ for p in sorted(d.rglob("*")):
214
+ parts = p.relative_to(d).parts
215
+ if (p.is_file() and "__pycache__" not in parts
216
+ and not any(x.startswith(".") for x in parts)
217
+ and p.resolve().is_relative_to(root.resolve())):
218
+ files[p.relative_to(root.resolve()).as_posix()] = p.read_bytes()
219
+ return files
220
+
221
+
222
+ def render(root, cfg, dev=False):
223
+ """Return {url path: bytes or Path} for the whole site."""
224
+ files = source_files(root, cfg)
225
+ texts = {}
226
+ for name, data in files.items():
227
+ try:
228
+ texts[name] = data.decode("utf-8")
229
+ except UnicodeDecodeError:
230
+ pass # Python can only read text files
231
+ site = {"app.json": json.dumps(texts).encode()}
232
+
233
+ icon_tag = '<link rel="icon" href="data:,">'
234
+ favicon = cfg["assets"]["favicon"]
235
+ if favicon:
236
+ adir = inside(root, cfg["assets"]["dir"], "assets.dir")
237
+ path = inside(adir, favicon, "assets.favicon")
238
+ if not path.is_file():
239
+ raise PyteError(f"favicon not found: {cfg['assets']['dir']}/{favicon}")
240
+ site["favicon.ico"] = path.read_bytes()
241
+ kind = {".png": "image/png", ".svg": "image/svg+xml"}.get(path.suffix.lower(), "image/x-icon")
242
+ stamp = hashlib.sha256(site["favicon.ico"]).hexdigest()[:8]
243
+ icon_tag = f'<link rel="icon" type="{kind}" href="favicon.ico?v={stamp}">'
244
+
245
+ for name in RUNTIME_FILES:
246
+ if not (RUNTIME / name).is_file():
247
+ raise PyteError(f"missing {RUNTIME / name} (reinstall pyte)")
248
+ site[f"runtime/{name}"] = RUNTIME / name
249
+
250
+ stamp = hashlib.sha256((RUNTIME / "pyte.wasm").read_bytes()).hexdigest()[:16]
251
+ boot = {"entry": Path(cfg["project"]["entry"]).as_posix(), "runtime": stamp,
252
+ "mode": cfg["app"]["mode"], "fs": cfg["fs"]["enabled"], "persist": cfg["fs"]["persist"],
253
+ "store": "pyte-fs:" + cfg["project"]["title"]}
254
+ head = [icon_tag]
255
+ if cfg["app"]["standalone"]:
256
+ name = html.escape(cfg["project"]["title"])
257
+ head += ['<meta name="apple-mobile-web-app-capable" content="yes">',
258
+ '<meta name="mobile-web-app-capable" content="yes">',
259
+ f'<meta name="apple-mobile-web-app-title" content="{name}">']
260
+ touch = cfg["assets"]["touch_icon"]
261
+ if touch:
262
+ adir = inside(root, cfg["assets"]["dir"], "assets.dir")
263
+ path = inside(adir, touch, "assets.touch_icon")
264
+ if not path.is_file() or path.suffix.lower() != ".png":
265
+ raise PyteError(f"assets.touch_icon must be a .png file in {cfg['assets']['dir']}")
266
+ site["touch-icon.png"] = path.read_bytes()
267
+ stamp = hashlib.sha256(site["touch-icon.png"]).hexdigest()[:8]
268
+ head.append(f'<link rel="apple-touch-icon" href="touch-icon.png?v={stamp}">')
269
+ icon_tag = "\n".join(head)
270
+
271
+ shell = hashlib.sha256(site.get("favicon.ico", b"") +
272
+ json.dumps([boot, cfg["project"]["title"], icon_tag]).encode()).hexdigest()[:16]
273
+ digest = hashlib.sha256(site["app.json"] + shell.encode()).hexdigest()[:16]
274
+ boot.update(hash=digest, shell=shell)
275
+ # user text goes in last so it can't be mistaken for a placeholder
276
+ page = (PAGE.replace("__RELOAD__", RELOAD.replace("__HASH__", digest) if dev else "")
277
+ )
278
+ before, after = page.split("__CFG__")
279
+ # one pass each, so text inside the title or tags is never treated as a placeholder
280
+ first, rest = before.split("__TITLE__")
281
+ middle, last = rest.split("__ICON__")
282
+ before = first + html.escape(cfg["project"]["title"]) + middle + icon_tag + last
283
+ site["index.html"] = (before + json.dumps(boot).replace("<", "\\u003c") + after).encode()
284
+ return site, digest, shell
285
+
286
+
287
+ def build(root, cfg):
288
+ out = inside(root, cfg["build"]["out"], "build.out")
289
+ for keep in (Path(cfg["project"]["entry"]).parent, Path(cfg["assets"]["dir"])):
290
+ k = (root / keep).resolve()
291
+ if out.is_relative_to(k) or k.is_relative_to(out):
292
+ raise PyteError("build.out must not overlap source or assets folders")
293
+ site = render(root, cfg)[0]
294
+ marker = out / ".pyte-build"
295
+ if out.exists():
296
+ if not out.is_dir() or (any(out.iterdir()) and not marker.is_file()):
297
+ raise PyteError(f"{out} not made by pyte; refusing to delete it")
298
+ shutil.rmtree(out)
299
+ out.mkdir(parents=True)
300
+ marker.touch()
301
+ for name, data in site.items():
302
+ dest = out / name
303
+ dest.parent.mkdir(parents=True, exist_ok=True)
304
+ if isinstance(data, Path):
305
+ shutil.copyfile(data, dest)
306
+ else:
307
+ dest.write_bytes(data)
308
+ size = sum(p.stat().st_size for p in out.rglob("*") if p.is_file())
309
+ print(f"built {out} ({size / 1e6:.1f} MB). Upload folder contents to any static host.")
310
+ print("test locally: pyte preview")
311
+
312
+
313
+ def lan_ip():
314
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
315
+ try:
316
+ s.connect(("10.255.255.255", 1)) # no packet sent
317
+ return s.getsockname()[0]
318
+ except OSError:
319
+ return None
320
+ finally:
321
+ s.close()
322
+
323
+
324
+ def urls(host, port):
325
+ if host in ("0.0.0.0", ""):
326
+ found = [("Local", f"http://127.0.0.1:{port}/")]
327
+ ip = lan_ip()
328
+ if ip:
329
+ found.append(("Network", f"http://{ip}:{port}/"))
330
+ return found
331
+ label = "Local" if host in ("127.0.0.1", "localhost") else "Network"
332
+ return [(label, f"http://{host}:{port}/")]
333
+
334
+
335
+ def make_handler(state):
336
+ class Handler(BaseHTTPRequestHandler):
337
+ def do_GET(self):
338
+ name = unquote(urlsplit(self.path).path).lstrip("/") or "index.html"
339
+ if name == "__pyte/version":
340
+ body = json.dumps({"hash": state["hash"], "shell": state.get("shell"), "pyte": True}).encode()
341
+ return self.reply(200, body, "application/json")
342
+ data = state["get"](name)
343
+ if data is None:
344
+ return self.reply(404, b"not found", "text/plain")
345
+ if isinstance(data, Path):
346
+ data = data.read_bytes()
347
+ kind = {".wasm": "application/wasm", ".mjs": "text/javascript",
348
+ ".js": "text/javascript"}.get(Path(name).suffix)
349
+ self.reply(200, data, kind or mimetypes.guess_type(name)[0] or "application/octet-stream")
350
+
351
+ do_HEAD = do_GET
352
+
353
+ def reply(self, code, body, kind):
354
+ self.send_response(code)
355
+ self.send_header("Content-Type", kind)
356
+ self.send_header("Content-Length", str(len(body)))
357
+ self.send_header("Cache-Control", "no-cache")
358
+ self.end_headers()
359
+ if self.command != "HEAD":
360
+ self.wfile.write(body)
361
+
362
+ def log_message(self, *args):
363
+ pass
364
+
365
+ return Handler
366
+
367
+
368
+ def serve(state, host, port):
369
+ try:
370
+ server = ThreadingHTTPServer((host, port), make_handler(state))
371
+ except OSError as e:
372
+ raise PyteError(f"can't listen on {host}:{port}: {e.strerror or e}")
373
+ for label, url in urls(host, port):
374
+ print(f" {label + ':':9}{url}", flush=True)
375
+ if host not in ("127.0.0.1", "localhost"):
376
+ print(" warning: other devices can reach this server, including your source")
377
+ print(" Ctrl+C to stop", flush=True)
378
+ return server
379
+
380
+
381
+ def dev(root, cfg, host, port):
382
+ site, digest, shell = render(root, cfg, dev=True)
383
+ state = {"hash": digest, "shell": shell, "site": site}
384
+ state["get"] = lambda name: state["site"].get(name)
385
+ server = serve(state, host, port)
386
+ threading.Thread(target=server.serve_forever, daemon=True).start()
387
+ last_error = None
388
+ while True:
389
+ time.sleep(0.5)
390
+ try:
391
+ new_cfg = load_config(root)
392
+ site, digest, shell = render(root, new_cfg, dev=True)
393
+ if digest != state["hash"]:
394
+ state.update(site=site, shell=shell, hash=digest)
395
+ print("reloaded", flush=True)
396
+ if new_cfg["server"] != cfg["server"]:
397
+ print("server settings changed: restart pyte dev", flush=True)
398
+ cfg = new_cfg
399
+ last_error = None
400
+ except (PyteError, OSError) as e:
401
+ if str(e) != last_error:
402
+ print(f"error: {e}", flush=True)
403
+ last_error = str(e)
404
+
405
+
406
+ def preview(root, cfg, host, port):
407
+ out = inside(root, cfg["build"]["out"], "build.out").resolve()
408
+ if not (out / "index.html").is_file():
409
+ raise PyteError("nothing built yet (run: pyte build)")
410
+
411
+ def get(name):
412
+ p = (out / name).resolve()
413
+ return p if p.is_relative_to(out) and p.is_file() else None
414
+
415
+ serve({"hash": "preview", "get": get}, host, port).serve_forever()
416
+
417
+
418
+ def show_url(host, port):
419
+ probe = "127.0.0.1" if host in ("0.0.0.0", "") else host
420
+ try:
421
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
422
+ with opener.open(f"http://{probe}:{port}/__pyte/version", timeout=2) as r:
423
+ running = json.load(r).get("pyte") is True
424
+ except (OSError, ValueError, AttributeError):
425
+ running = False
426
+ print("running" if running else "not running; would serve at")
427
+ for label, url in urls(host, port):
428
+ print(f" {label + ':':9}{url}")
429
+ return 0 if running else 1
430
+
431
+
432
+ def init(root):
433
+ if (root / CONFIG).exists():
434
+ raise PyteError(f"{CONFIG} already exists")
435
+ starter = {
436
+ CONFIG: '''[project]
437
+ title = "My pyte app"
438
+ entry = "src/main.py"
439
+
440
+ [server]
441
+ host = "127.0.0.1" # "0.0.0.0" = reachable by IP from other devices
442
+ port = 9473
443
+
444
+ [assets]
445
+ dir = "assets"
446
+ favicon = "" # file inside assets, e.g. "logo.ico"
447
+ touch_icon = "" # .png in assets for phone home screen
448
+
449
+ [build]
450
+ out = "dist"
451
+
452
+ [app]
453
+ mode = "page" # "cli" = terminal in the page
454
+ standalone = false # true = full screen when added to phone home screen
455
+
456
+ [fs]
457
+ enabled = false # true = Python and terminal can write files
458
+ persist = true # keep written files in the browser between visits
459
+ ''',
460
+ "src/main.py": '''from js import document
461
+
462
+ h1 = document.createElement("h1")
463
+ h1.textContent = "Hello from Python"
464
+ document.getElementById("app").appendChild(h1)
465
+ print("running in wasm")
466
+ ''',
467
+ "assets/.gitkeep": "",
468
+ }
469
+ for name, text in starter.items():
470
+ path = root / name
471
+ path.parent.mkdir(parents=True, exist_ok=True)
472
+ if not path.exists():
473
+ path.write_text(text, "utf-8")
474
+ print(f"created project in {root}\nnext: pyte dev")
475
+
476
+
477
+ def main(argv=None):
478
+ ap = argparse.ArgumentParser(prog="pyte", description="Python in the browser, Vite style")
479
+ sub = ap.add_subparsers(dest="cmd", required=True)
480
+ for name, text in [("init", "create starter project"), ("dev", "dev server with live reload"),
481
+ ("build", "make index.html + wasm for hosting"),
482
+ ("preview", "serve built site"), ("url", "show URL and whether running")]:
483
+ p = sub.add_parser(name, help=text)
484
+ p.add_argument("dir", nargs="?", default=".")
485
+ if name in ("dev", "preview", "url"):
486
+ p.add_argument("--host", help="IP to listen on")
487
+ p.add_argument("--port", type=int)
488
+ args = ap.parse_args(argv)
489
+ root = Path(args.dir).resolve()
490
+ try:
491
+ if args.cmd == "init":
492
+ init(root)
493
+ return 0
494
+ cfg = load_config(root)
495
+ if args.cmd == "build":
496
+ build(root, cfg)
497
+ return 0
498
+ host = args.host if args.host is not None else cfg["server"]["host"]
499
+ port = args.port if args.port is not None else cfg["server"]["port"]
500
+ if not 1 <= port <= 65535:
501
+ raise PyteError("port must be 1-65535")
502
+ if args.cmd == "url":
503
+ return show_url(host, port)
504
+ (dev if args.cmd == "dev" else preview)(root, cfg, host, port)
505
+ except PyteError as e:
506
+ print(f"pyte: {e}", file=sys.stderr)
507
+ return 1
508
+ except KeyboardInterrupt:
509
+ print()
510
+ return 0
511
+
512
+
513
+ if __name__ == "__main__":
514
+ sys.exit(main())
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyte-cli
3
+ Version: 0.2.0
4
+ License: Pyte License 1.0
5
+
6
+ Copyright (c) 2026 Rajveer Jadhav
7
+
8
+ "Software" means pyte: its source code and documentation.
9
+
10
+ 1. Permission. Anyone may use, copy, modify and share the Software free of
11
+ charge, for any purpose, including at work, subject to the terms below.
12
+
13
+ 2. Credit. Copies of the Software, modified or not, must keep this license and
14
+ the copyright line above.
15
+
16
+ 3. Changes. Modified versions you share must say they were changed and must be
17
+ shared under this license, with source code.
18
+
19
+ 4. No selling. You may not sell the Software or a modified version, or charge
20
+ for access to it as a product or service.
21
+
22
+ 5. Your projects. Projects you make with pyte are yours. This license places no
23
+ conditions on your code, your assets, or pyte starter and page code copied
24
+ into your project or build output. You may license or sell your projects as
25
+ you like.
26
+
27
+ 6. Name. Modified versions must use a different name than "pyte".
28
+
29
+ 7. Other software. The Go runtime and wasm_exec.js included in pyte and its
30
+ builds are not covered. Their own license applies.
31
+
32
+ 8. Ending. Breaking these terms ends your permission. It returns if you fix the
33
+ breach within 30 days of learning of it.
34
+
35
+ 9. No warranty. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
36
+ EXPRESS OR IMPLIED. TO THE EXTENT THE LAW ALLOWS, THE AUTHOR IS NOT LIABLE
37
+ FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM THE SOFTWARE OR ITS
38
+ USE.
39
+
40
+ Requires-Python: >=3.11
41
+ License-File: LICENSE
42
+ Dynamic: license-file
@@ -0,0 +1,11 @@
1
+ pyte.py,sha256=JfF6_PoIAfMTdcMCqTuKOzsK4zHlMS5pZBfDrmhFjVY,19575
2
+ pyte_cli-0.2.0.dist-info/licenses/LICENSE,sha256=mgKimtS41Fw2A1r__XuX8ouF5SOt4AOBnTBZ3jYaGTg,1442
3
+ pyte_runtime/LICENSE-go.txt,sha256=kR-PV4KTEyD1uNEWCnY2W4OupkR-5sBPptVZFGfbna0,1453
4
+ pyte_runtime/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ pyte_runtime/pyte.wasm,sha256=4ruhcauPERcs4diBF1cDlbPwslIgdj8aiT_XEaMMeJk,3682848
6
+ pyte_runtime/wasm_exec.js,sha256=DJSfSZb5qJaY5LXFht4yJJw7abe6rbZNIgBzzASsuhQ,16992
7
+ pyte_cli-0.2.0.dist-info/METADATA,sha256=MrVb7uQV9BNptIsV_8Lt1woPRqeR5IIw0alwKT4edc4,1852
8
+ pyte_cli-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ pyte_cli-0.2.0.dist-info/entry_points.txt,sha256=c0TinF0EaH6rsd0XJKpPt0szz42jKSEpyquUAx13H8M,35
10
+ pyte_cli-0.2.0.dist-info/top_level.txt,sha256=7pyGYMb8zleZQnf-HGXx3D5QMBjLYg5bZSbB8K7S58Q,18
11
+ pyte_cli-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pyte = pyte:main
@@ -0,0 +1,35 @@
1
+ Pyte License 1.0
2
+
3
+ Copyright (c) 2026 Rajveer Jadhav
4
+
5
+ "Software" means pyte: its source code and documentation.
6
+
7
+ 1. Permission. Anyone may use, copy, modify and share the Software free of
8
+ charge, for any purpose, including at work, subject to the terms below.
9
+
10
+ 2. Credit. Copies of the Software, modified or not, must keep this license and
11
+ the copyright line above.
12
+
13
+ 3. Changes. Modified versions you share must say they were changed and must be
14
+ shared under this license, with source code.
15
+
16
+ 4. No selling. You may not sell the Software or a modified version, or charge
17
+ for access to it as a product or service.
18
+
19
+ 5. Your projects. Projects you make with pyte are yours. This license places no
20
+ conditions on your code, your assets, or pyte starter and page code copied
21
+ into your project or build output. You may license or sell your projects as
22
+ you like.
23
+
24
+ 6. Name. Modified versions must use a different name than "pyte".
25
+
26
+ 7. Other software. The Go runtime and wasm_exec.js included in pyte and its
27
+ builds are not covered. Their own license applies.
28
+
29
+ 8. Ending. Breaking these terms ends your permission. It returns if you fix the
30
+ breach within 30 days of learning of it.
31
+
32
+ 9. No warranty. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
33
+ EXPRESS OR IMPLIED. TO THE EXTENT THE LAW ALLOWS, THE AUTHOR IS NOT LIABLE
34
+ FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM THE SOFTWARE OR ITS
35
+ USE.
@@ -0,0 +1,2 @@
1
+ pyte
2
+ pyte_runtime
@@ -0,0 +1,27 @@
1
+ Copyright 2009 The Go Authors.
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ * Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+ * Redistributions in binary form must reproduce the above
10
+ copyright notice, this list of conditions and the following disclaimer
11
+ in the documentation and/or other materials provided with the
12
+ distribution.
13
+ * Neither the name of Google LLC nor the names of its
14
+ contributors may be used to endorse or promote products derived from
15
+ this software without specific prior written permission.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
File without changes
pyte_runtime/pyte.wasm ADDED
Binary file
@@ -0,0 +1,575 @@
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ "use strict";
6
+
7
+ (() => {
8
+ const enosys = () => {
9
+ const err = new Error("not implemented");
10
+ err.code = "ENOSYS";
11
+ return err;
12
+ };
13
+
14
+ if (!globalThis.fs) {
15
+ let outputBuf = "";
16
+ globalThis.fs = {
17
+ constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1, O_DIRECTORY: -1 }, // unused
18
+ writeSync(fd, buf) {
19
+ outputBuf += decoder.decode(buf);
20
+ const nl = outputBuf.lastIndexOf("\n");
21
+ if (nl != -1) {
22
+ console.log(outputBuf.substring(0, nl));
23
+ outputBuf = outputBuf.substring(nl + 1);
24
+ }
25
+ return buf.length;
26
+ },
27
+ write(fd, buf, offset, length, position, callback) {
28
+ if (offset !== 0 || length !== buf.length || position !== null) {
29
+ callback(enosys());
30
+ return;
31
+ }
32
+ const n = this.writeSync(fd, buf);
33
+ callback(null, n);
34
+ },
35
+ chmod(path, mode, callback) { callback(enosys()); },
36
+ chown(path, uid, gid, callback) { callback(enosys()); },
37
+ close(fd, callback) { callback(enosys()); },
38
+ fchmod(fd, mode, callback) { callback(enosys()); },
39
+ fchown(fd, uid, gid, callback) { callback(enosys()); },
40
+ fstat(fd, callback) { callback(enosys()); },
41
+ fsync(fd, callback) { callback(null); },
42
+ ftruncate(fd, length, callback) { callback(enosys()); },
43
+ lchown(path, uid, gid, callback) { callback(enosys()); },
44
+ link(path, link, callback) { callback(enosys()); },
45
+ lstat(path, callback) { callback(enosys()); },
46
+ mkdir(path, perm, callback) { callback(enosys()); },
47
+ open(path, flags, mode, callback) { callback(enosys()); },
48
+ read(fd, buffer, offset, length, position, callback) { callback(enosys()); },
49
+ readdir(path, callback) { callback(enosys()); },
50
+ readlink(path, callback) { callback(enosys()); },
51
+ rename(from, to, callback) { callback(enosys()); },
52
+ rmdir(path, callback) { callback(enosys()); },
53
+ stat(path, callback) { callback(enosys()); },
54
+ symlink(path, link, callback) { callback(enosys()); },
55
+ truncate(path, length, callback) { callback(enosys()); },
56
+ unlink(path, callback) { callback(enosys()); },
57
+ utimes(path, atime, mtime, callback) { callback(enosys()); },
58
+ };
59
+ }
60
+
61
+ if (!globalThis.process) {
62
+ globalThis.process = {
63
+ getuid() { return -1; },
64
+ getgid() { return -1; },
65
+ geteuid() { return -1; },
66
+ getegid() { return -1; },
67
+ getgroups() { throw enosys(); },
68
+ pid: -1,
69
+ ppid: -1,
70
+ umask() { throw enosys(); },
71
+ cwd() { throw enosys(); },
72
+ chdir() { throw enosys(); },
73
+ }
74
+ }
75
+
76
+ if (!globalThis.path) {
77
+ globalThis.path = {
78
+ resolve(...pathSegments) {
79
+ return pathSegments.join("/");
80
+ }
81
+ }
82
+ }
83
+
84
+ if (!globalThis.crypto) {
85
+ throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
86
+ }
87
+
88
+ if (!globalThis.performance) {
89
+ throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
90
+ }
91
+
92
+ if (!globalThis.TextEncoder) {
93
+ throw new Error("globalThis.TextEncoder is not available, polyfill required");
94
+ }
95
+
96
+ if (!globalThis.TextDecoder) {
97
+ throw new Error("globalThis.TextDecoder is not available, polyfill required");
98
+ }
99
+
100
+ const encoder = new TextEncoder("utf-8");
101
+ const decoder = new TextDecoder("utf-8");
102
+
103
+ globalThis.Go = class {
104
+ constructor() {
105
+ this.argv = ["js"];
106
+ this.env = {};
107
+ this.exit = (code) => {
108
+ if (code !== 0) {
109
+ console.warn("exit code:", code);
110
+ }
111
+ };
112
+ this._exitPromise = new Promise((resolve) => {
113
+ this._resolveExitPromise = resolve;
114
+ });
115
+ this._pendingEvent = null;
116
+ this._scheduledTimeouts = new Map();
117
+ this._nextCallbackTimeoutID = 1;
118
+
119
+ const setInt64 = (addr, v) => {
120
+ this.mem.setUint32(addr + 0, v, true);
121
+ this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
122
+ }
123
+
124
+ const setInt32 = (addr, v) => {
125
+ this.mem.setUint32(addr + 0, v, true);
126
+ }
127
+
128
+ const getInt64 = (addr) => {
129
+ const low = this.mem.getUint32(addr + 0, true);
130
+ const high = this.mem.getInt32(addr + 4, true);
131
+ return low + high * 4294967296;
132
+ }
133
+
134
+ const loadValue = (addr) => {
135
+ const f = this.mem.getFloat64(addr, true);
136
+ if (f === 0) {
137
+ return undefined;
138
+ }
139
+ if (!isNaN(f)) {
140
+ return f;
141
+ }
142
+
143
+ const id = this.mem.getUint32(addr, true);
144
+ return this._values[id];
145
+ }
146
+
147
+ const storeValue = (addr, v) => {
148
+ const nanHead = 0x7FF80000;
149
+
150
+ if (typeof v === "number" && v !== 0) {
151
+ if (isNaN(v)) {
152
+ this.mem.setUint32(addr + 4, nanHead, true);
153
+ this.mem.setUint32(addr, 0, true);
154
+ return;
155
+ }
156
+ this.mem.setFloat64(addr, v, true);
157
+ return;
158
+ }
159
+
160
+ if (v === undefined) {
161
+ this.mem.setFloat64(addr, 0, true);
162
+ return;
163
+ }
164
+
165
+ let id = this._ids.get(v);
166
+ if (id === undefined) {
167
+ id = this._idPool.pop();
168
+ if (id === undefined) {
169
+ id = this._values.length;
170
+ }
171
+ this._values[id] = v;
172
+ this._goRefCounts[id] = 0;
173
+ this._ids.set(v, id);
174
+ }
175
+ this._goRefCounts[id]++;
176
+ let typeFlag = 0;
177
+ switch (typeof v) {
178
+ case "object":
179
+ if (v !== null) {
180
+ typeFlag = 1;
181
+ }
182
+ break;
183
+ case "string":
184
+ typeFlag = 2;
185
+ break;
186
+ case "symbol":
187
+ typeFlag = 3;
188
+ break;
189
+ case "function":
190
+ typeFlag = 4;
191
+ break;
192
+ }
193
+ this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
194
+ this.mem.setUint32(addr, id, true);
195
+ }
196
+
197
+ const loadSlice = (addr) => {
198
+ const array = getInt64(addr + 0);
199
+ const len = getInt64(addr + 8);
200
+ return new Uint8Array(this._inst.exports.mem.buffer, array, len);
201
+ }
202
+
203
+ const loadSliceOfValues = (addr) => {
204
+ const array = getInt64(addr + 0);
205
+ const len = getInt64(addr + 8);
206
+ const a = new Array(len);
207
+ for (let i = 0; i < len; i++) {
208
+ a[i] = loadValue(array + i * 8);
209
+ }
210
+ return a;
211
+ }
212
+
213
+ const loadString = (addr) => {
214
+ const saddr = getInt64(addr + 0);
215
+ const len = getInt64(addr + 8);
216
+ return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
217
+ }
218
+
219
+ const testCallExport = (a, b) => {
220
+ this._inst.exports.testExport0();
221
+ return this._inst.exports.testExport(a, b);
222
+ }
223
+
224
+ const timeOrigin = Date.now() - performance.now();
225
+ this.importObject = {
226
+ _gotest: {
227
+ add: (a, b) => a + b,
228
+ callExport: testCallExport,
229
+ },
230
+ gojs: {
231
+ // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
232
+ // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
233
+ // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
234
+ // This changes the SP, thus we have to update the SP used by the imported function.
235
+
236
+ // func wasmExit(code int32)
237
+ "runtime.wasmExit": (sp) => {
238
+ sp >>>= 0;
239
+ const code = this.mem.getInt32(sp + 8, true);
240
+ this.exited = true;
241
+ delete this._inst;
242
+ delete this._values;
243
+ delete this._goRefCounts;
244
+ delete this._ids;
245
+ delete this._idPool;
246
+ this.exit(code);
247
+ },
248
+
249
+ // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
250
+ "runtime.wasmWrite": (sp) => {
251
+ sp >>>= 0;
252
+ const fd = getInt64(sp + 8);
253
+ const p = getInt64(sp + 16);
254
+ const n = this.mem.getInt32(sp + 24, true);
255
+ fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
256
+ },
257
+
258
+ // func resetMemoryDataView()
259
+ "runtime.resetMemoryDataView": (sp) => {
260
+ sp >>>= 0;
261
+ this.mem = new DataView(this._inst.exports.mem.buffer);
262
+ },
263
+
264
+ // func nanotime1() int64
265
+ "runtime.nanotime1": (sp) => {
266
+ sp >>>= 0;
267
+ setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
268
+ },
269
+
270
+ // func walltime() (sec int64, nsec int32)
271
+ "runtime.walltime": (sp) => {
272
+ sp >>>= 0;
273
+ const msec = (new Date).getTime();
274
+ setInt64(sp + 8, msec / 1000);
275
+ this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
276
+ },
277
+
278
+ // func scheduleTimeoutEvent(delay int64) int32
279
+ "runtime.scheduleTimeoutEvent": (sp) => {
280
+ sp >>>= 0;
281
+ const id = this._nextCallbackTimeoutID;
282
+ this._nextCallbackTimeoutID++;
283
+ this._scheduledTimeouts.set(id, setTimeout(
284
+ () => {
285
+ this._resume();
286
+ while (this._scheduledTimeouts.has(id)) {
287
+ // for some reason Go failed to register the timeout event, log and try again
288
+ // (temporary workaround for https://github.com/golang/go/issues/28975)
289
+ console.warn("scheduleTimeoutEvent: missed timeout event");
290
+ this._resume();
291
+ }
292
+ },
293
+ getInt64(sp + 8),
294
+ ));
295
+ this.mem.setInt32(sp + 16, id, true);
296
+ },
297
+
298
+ // func clearTimeoutEvent(id int32)
299
+ "runtime.clearTimeoutEvent": (sp) => {
300
+ sp >>>= 0;
301
+ const id = this.mem.getInt32(sp + 8, true);
302
+ clearTimeout(this._scheduledTimeouts.get(id));
303
+ this._scheduledTimeouts.delete(id);
304
+ },
305
+
306
+ // func getRandomData(r []byte)
307
+ "runtime.getRandomData": (sp) => {
308
+ sp >>>= 0;
309
+ crypto.getRandomValues(loadSlice(sp + 8));
310
+ },
311
+
312
+ // func finalizeRef(v ref)
313
+ "syscall/js.finalizeRef": (sp) => {
314
+ sp >>>= 0;
315
+ const id = this.mem.getUint32(sp + 8, true);
316
+ this._goRefCounts[id]--;
317
+ if (this._goRefCounts[id] === 0) {
318
+ const v = this._values[id];
319
+ this._values[id] = null;
320
+ this._ids.delete(v);
321
+ this._idPool.push(id);
322
+ }
323
+ },
324
+
325
+ // func stringVal(value string) ref
326
+ "syscall/js.stringVal": (sp) => {
327
+ sp >>>= 0;
328
+ storeValue(sp + 24, loadString(sp + 8));
329
+ },
330
+
331
+ // func valueGet(v ref, p string) ref
332
+ "syscall/js.valueGet": (sp) => {
333
+ sp >>>= 0;
334
+ const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
335
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
336
+ storeValue(sp + 32, result);
337
+ },
338
+
339
+ // func valueSet(v ref, p string, x ref)
340
+ "syscall/js.valueSet": (sp) => {
341
+ sp >>>= 0;
342
+ Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
343
+ },
344
+
345
+ // func valueDelete(v ref, p string)
346
+ "syscall/js.valueDelete": (sp) => {
347
+ sp >>>= 0;
348
+ Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
349
+ },
350
+
351
+ // func valueIndex(v ref, i int) ref
352
+ "syscall/js.valueIndex": (sp) => {
353
+ sp >>>= 0;
354
+ storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
355
+ },
356
+
357
+ // valueSetIndex(v ref, i int, x ref)
358
+ "syscall/js.valueSetIndex": (sp) => {
359
+ sp >>>= 0;
360
+ Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
361
+ },
362
+
363
+ // func valueCall(v ref, m string, args []ref) (ref, bool)
364
+ "syscall/js.valueCall": (sp) => {
365
+ sp >>>= 0;
366
+ try {
367
+ const v = loadValue(sp + 8);
368
+ const m = Reflect.get(v, loadString(sp + 16));
369
+ const args = loadSliceOfValues(sp + 32);
370
+ const result = Reflect.apply(m, v, args);
371
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
372
+ storeValue(sp + 56, result);
373
+ this.mem.setUint8(sp + 64, 1);
374
+ } catch (err) {
375
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
376
+ storeValue(sp + 56, err);
377
+ this.mem.setUint8(sp + 64, 0);
378
+ }
379
+ },
380
+
381
+ // func valueInvoke(v ref, args []ref) (ref, bool)
382
+ "syscall/js.valueInvoke": (sp) => {
383
+ sp >>>= 0;
384
+ try {
385
+ const v = loadValue(sp + 8);
386
+ const args = loadSliceOfValues(sp + 16);
387
+ const result = Reflect.apply(v, undefined, args);
388
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
389
+ storeValue(sp + 40, result);
390
+ this.mem.setUint8(sp + 48, 1);
391
+ } catch (err) {
392
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
393
+ storeValue(sp + 40, err);
394
+ this.mem.setUint8(sp + 48, 0);
395
+ }
396
+ },
397
+
398
+ // func valueNew(v ref, args []ref) (ref, bool)
399
+ "syscall/js.valueNew": (sp) => {
400
+ sp >>>= 0;
401
+ try {
402
+ const v = loadValue(sp + 8);
403
+ const args = loadSliceOfValues(sp + 16);
404
+ const result = Reflect.construct(v, args);
405
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
406
+ storeValue(sp + 40, result);
407
+ this.mem.setUint8(sp + 48, 1);
408
+ } catch (err) {
409
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
410
+ storeValue(sp + 40, err);
411
+ this.mem.setUint8(sp + 48, 0);
412
+ }
413
+ },
414
+
415
+ // func valueLength(v ref) int
416
+ "syscall/js.valueLength": (sp) => {
417
+ sp >>>= 0;
418
+ setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
419
+ },
420
+
421
+ // valuePrepareString(v ref) (ref, int)
422
+ "syscall/js.valuePrepareString": (sp) => {
423
+ sp >>>= 0;
424
+ const str = encoder.encode(String(loadValue(sp + 8)));
425
+ storeValue(sp + 16, str);
426
+ setInt64(sp + 24, str.length);
427
+ },
428
+
429
+ // valueLoadString(v ref, b []byte)
430
+ "syscall/js.valueLoadString": (sp) => {
431
+ sp >>>= 0;
432
+ const str = loadValue(sp + 8);
433
+ loadSlice(sp + 16).set(str);
434
+ },
435
+
436
+ // func valueInstanceOf(v ref, t ref) bool
437
+ "syscall/js.valueInstanceOf": (sp) => {
438
+ sp >>>= 0;
439
+ this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
440
+ },
441
+
442
+ // func copyBytesToGo(dst []byte, src ref) (int, bool)
443
+ "syscall/js.copyBytesToGo": (sp) => {
444
+ sp >>>= 0;
445
+ const dst = loadSlice(sp + 8);
446
+ const src = loadValue(sp + 32);
447
+ if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
448
+ this.mem.setUint8(sp + 48, 0);
449
+ return;
450
+ }
451
+ const toCopy = src.subarray(0, dst.length);
452
+ dst.set(toCopy);
453
+ setInt64(sp + 40, toCopy.length);
454
+ this.mem.setUint8(sp + 48, 1);
455
+ },
456
+
457
+ // func copyBytesToJS(dst ref, src []byte) (int, bool)
458
+ "syscall/js.copyBytesToJS": (sp) => {
459
+ sp >>>= 0;
460
+ const dst = loadValue(sp + 8);
461
+ const src = loadSlice(sp + 16);
462
+ if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
463
+ this.mem.setUint8(sp + 48, 0);
464
+ return;
465
+ }
466
+ const toCopy = src.subarray(0, dst.length);
467
+ dst.set(toCopy);
468
+ setInt64(sp + 40, toCopy.length);
469
+ this.mem.setUint8(sp + 48, 1);
470
+ },
471
+
472
+ "debug": (value) => {
473
+ console.log(value);
474
+ },
475
+ }
476
+ };
477
+ }
478
+
479
+ async run(instance) {
480
+ if (!(instance instanceof WebAssembly.Instance)) {
481
+ throw new Error("Go.run: WebAssembly.Instance expected");
482
+ }
483
+ this._inst = instance;
484
+ this.mem = new DataView(this._inst.exports.mem.buffer);
485
+ this._values = [ // JS values that Go currently has references to, indexed by reference id
486
+ NaN,
487
+ 0,
488
+ null,
489
+ true,
490
+ false,
491
+ globalThis,
492
+ this,
493
+ ];
494
+ this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
495
+ this._ids = new Map([ // mapping from JS values to reference ids
496
+ [0, 1],
497
+ [null, 2],
498
+ [true, 3],
499
+ [false, 4],
500
+ [globalThis, 5],
501
+ [this, 6],
502
+ ]);
503
+ this._idPool = []; // unused ids that have been garbage collected
504
+ this.exited = false; // whether the Go program has exited
505
+
506
+ // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
507
+ let offset = 4096;
508
+
509
+ const strPtr = (str) => {
510
+ const ptr = offset;
511
+ const bytes = encoder.encode(str + "\0");
512
+ new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
513
+ offset += bytes.length;
514
+ if (offset % 8 !== 0) {
515
+ offset += 8 - (offset % 8);
516
+ }
517
+ return ptr;
518
+ };
519
+
520
+ const argc = this.argv.length;
521
+
522
+ const argvPtrs = [];
523
+ this.argv.forEach((arg) => {
524
+ argvPtrs.push(strPtr(arg));
525
+ });
526
+ argvPtrs.push(0);
527
+
528
+ const keys = Object.keys(this.env).sort();
529
+ keys.forEach((key) => {
530
+ argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
531
+ });
532
+ argvPtrs.push(0);
533
+
534
+ const argv = offset;
535
+ argvPtrs.forEach((ptr) => {
536
+ this.mem.setUint32(offset, ptr, true);
537
+ this.mem.setUint32(offset + 4, 0, true);
538
+ offset += 8;
539
+ });
540
+
541
+ // The linker guarantees global data starts from at least wasmMinDataAddr.
542
+ // Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr.
543
+ const wasmMinDataAddr = 4096 + 8192;
544
+ if (offset >= wasmMinDataAddr) {
545
+ throw new Error("total length of command line and environment variables exceeds limit");
546
+ }
547
+
548
+ this._inst.exports.run(argc, argv);
549
+ if (this.exited) {
550
+ this._resolveExitPromise();
551
+ }
552
+ await this._exitPromise;
553
+ }
554
+
555
+ _resume() {
556
+ if (this.exited) {
557
+ throw new Error("Go program has already exited");
558
+ }
559
+ this._inst.exports.resume();
560
+ if (this.exited) {
561
+ this._resolveExitPromise();
562
+ }
563
+ }
564
+
565
+ _makeFuncWrapper(id) {
566
+ const go = this;
567
+ return function () {
568
+ const event = { id: id, this: this, args: arguments };
569
+ go._pendingEvent = event;
570
+ go._resume();
571
+ return event.result;
572
+ };
573
+ }
574
+ }
575
+ })();