Web target, plan 1: transpiler, snapshot and headless replay
This plan builds slices 1 and 2 of the spec: the Python-to-JavaScript transpiler, the state snapshot, a runtime that runs the transpiled app in Node without rendering, and the replay harness that proves the exported app equals the Python one frame by frame. It ends with the first consumer replaying in its own CI. Rendering with three.js and export --web's page (slice 3) and run --web (slice 4) get their own plans, written against the interfaces this one lands.
manifoldx.web: a type model fed by annotations, the live objects after setup and inference; a transpiler that emits one ES module per app module from the roots; a snapshot of the reached objects; static JS (pyrt.js, manifoldx.js) shipped in the wheel; a replay harness on both sides.
techPython 3.13, ast, numpy; plain ES modules; Node 20+ as a test dependency only (node --test, node --enable-source-maps).
spec.knowledge/analysis/2026-11-06-web-target-design.html
later plansplan 2: three.js rendering, HTML GUI, browser input, export --web's page, visual parity (spec slice 3). Plan 3: run --web (slice 4).
Global constraints
- No app JavaScript: nothing in this plan asks an app author to write JS. Every JS file lives in manifoldx.
- Outside the subset fails: a reached construct the transpiler cannot handle raises
TranspileErrorwithfile.py:line, the construct, and the root that reached it. Never drop code silently. - Exact parity is the default: every subset test compares the Python and Node results with
==after JSON round trip; a tolerance is allowed only where the test names why (float formatting). - Float32 where manifoldx holds float32:
Float32Arrayin JS;Math.froundfor float32 scalar arithmetic in the runtime. - The desktop renderer and ECS do not change.
export_gltf's changes are additive; existing glTF tests keep passing. - Node is a test dependency only: tests that need it skip with
node not foundwhenshutil.which("node")isNone. CI'subuntu-latesthas Node. - CI has no GPU (
tests/conftest.pyturns adapter requests into skips): the example app and every test here run setup without a device. - Gates:
make testandmake lint, verbatim. Commits are conventional; work lands on a branch through a PR. - manifoldx is public: no names of the consumer's repository, people or machines in code, tests, commits or PR text. The consumer is "the first consumer".
Review focus
- Reached code calls a method of a library object (a
Path, adatetime): the export fails naming the root and the line, not aTypeErrorin Node. test in task 7 - An app with no systems (a static scene with only a GUI, or nothing): the export still writes a working folder with empty modules and replays zero-cost frames. test in task 11
- An async startup handler: setup awaits it the way the engine's first frame does, or fails with a message that names it. test in task 11
- Dict keys that are JS prototype names (
"constructor","__proto__","toString"): they round trip through the snapshot and throughin,.getand indexing. test in task 8 - Non-ASCII text (
"Matemática", an emoji) in f-strings,lenandtextwrap.wrap: Python counts code points, JS strings count UTF-16 units, so the runtime must count code points. test in task 5
File structure
| file | responsibility |
|---|---|
| src/manifoldx/web/__init__.py | public names: transpile_app, snapshot, export_web, TranspileError, SnapshotError |
| src/manifoldx/web/types.py | the type model (Ty) and TypeEnv: annotations, live types, inference, call-site propagation |
| src/manifoldx/web/transpile.py | expressions, statements, classes and closures to JS; source maps |
| src/manifoldx/web/reach.py | roots from an engine; reach through types; the root chain for errors |
| src/manifoldx/web/snapshot.py | reached objects to JSON; handles for manifoldx objects; functions and closures |
| src/manifoldx/web/export.py | run the app's setup without a window, then write the output folder |
| src/manifoldx/web/replay.py | ScriptInput, the Python replay, the Node replay, trace comparison |
| src/manifoldx/web/js/pyrt.js | Python semantics JS lacks (the spikes' runtime, grown) |
| src/manifoldx/web/js/manifoldx.js | the engine surface reached code calls; state loading; the frame step |
| src/manifoldx/web/js/replay.mjs | Node entry: load an export folder, replay a script, print the trace as JSON |
| src/manifoldx/engine.py, input.py | Engine.set_material, InputState.capture_pointer |
| src/manifoldx/gltf/engine_export.py, writer.py | entity and material ids in extras; extra materials |
| src/manifoldx/cli.py | manifoldx export --web |
| examples/web_walk.py | the public example the replay runs in CI |
| tests/web/ | one test file per task; tests/web/parity.py runs a snippet on both sides |
Tasks
1Engine APIs: set_material and capture_pointersrc/manifoldx/engine.py · src/manifoldx/input.py · tests/test_web_engine_apis.py
interfaces
- Write the failing tests: after
engine.set_material(h, m),engine.store._components["Material"][h.index, 0] == engine._material_registry.register(m); an int index works like a handle; a dead entity raisesValueError.capture_pointer(True)setspointer_capturedand calls the hookInputState._on_capturewhen one is set; with no window it only sets the flag. - Run
uv run pytest tests/test_web_engine_apis.py -v: fails withAttributeError. - Implement both. On the desktop, the engine sets
input._on_capturewhen it opens a glfw canvas, to a function that sets the cursor mode to disabled or normal on the canvas's window (and raw motion when supported). This moves the first consumer's workaround into manifoldx. - Run the tests: pass. Run
make test: no other test changes. - Commit:
feat(engine): set_material and capture_pointer as public API.
2glTF export: entity and material ids, extra materialssrc/manifoldx/gltf/engine_export.py · writer.py · tests/test_gltf_engine.py
interfaces
"mx": {"entity": int, "material": int} (merged under the app's extras, which keep their keys) · the scene's extras gain "mx_materials": {str(id): gltf_material_index} for every material in engine._material_registry._materials, written even when no node uses it · build_glb(..., extra_materials=list[tuple[int, material]])- Write the failing tests in
tests/test_gltf_engine.py: a node's extras carry its entity index and material id; a material registered but used by no entity appears inmx_materialsand in the glTF'smaterials; an app's extras{"pick": "b1"}survive next to"mx"; existing exports' other fields are unchanged. - Run them: fail.
- Implement in
nodes()andbuild_glb. Materials stay merged by object identity as today;mx_materialsmaps every registry id to the index the writer gave that object. - Run
uv run pytest tests/test_gltf_engine.py tests/test_gltf_writer.py tests/test_gltf_conformance.py -v: pass. - Commit:
feat(gltf): write entity and material ids, and unused materials.
3The parity harness and the core subsetsrc/manifoldx/web/{__init__,types,transpile}.py · js/pyrt.js · tests/web/{conftest,parity,test_core}.py
interfaces
main() in Python and in Node, JSON values) · Ty, TypeEnv in types.py- Write
tests/web/parity.py:run_both(src)writessrcasmod.py, imports it and callsmain(); transpiles it withroots=None(whole module), copiespyrt.jsbeside it, runsnode --input-type=module -ethat importsmainand printsJSON.stringify(main(), replacer), where the replacer turns typed arrays andSets into arrays.tests/web/conftest.pyskips the folder when Node is missing. - Write the failing tests, one per row, each a
main()whose Python and JS results must be equal: Each test also checks that the generated JS has noevaland nowith. - Run
uv run pytest tests/web/test_core.py -v: fail (module missing). - Implement
types.py(Tywith kinds num, int, bool, str, none, list, tuple, dict, set, vec, obj, fn, union, unknown;veccarriesdtype"f64" or "f32") andtranspile.pystarting from the spike's design: locals declared once withletat the top of each function, comprehensions as IIFEs,%throughmod, tests throughtruthyunless both sides are known booleans,and/oron non-booleans throughor_/and_with thunks. Alist.appendispush; a list'spopispop. - Run the tests: pass. Commit:
feat(web): transpiler core and the parity harness.
uv run pytest tests/web/test_core.py -v: 9 passed; with Node off the PATH, 9 skipped with "node not found".
4numpy vectors, float32 and mathsrc/manifoldx/web/{types,transpile}.py · js/pyrt.js · tests/web/test_numpy.py
interfaces
Float32Array- Write the failing parity tests:
inplace_aliaspins numpy's in-place+=:bsees the change. - Run: fail.
- Implement: a value is a vector when its type says so (from
np.array,np.zeros, annp.ndarrayannotation, a live array, or arithmetic on one); arithmetic on vectors goes through thev*helpers;+=on a vector writes in place (viadd(a, b)mutatinga);np.array(x, np.float32)isFloat32Array.from(x); float32 norm isMath.fround(Math.sqrt(...))overfrounded products summed in order.radiansmultiplies byMath.PI / 180computed once. - Run: pass. Commit:
feat(web): numpy vectors and float32 in the transpiler.
5Classes, closures, collections and textsrc/manifoldx/web/transpile.py · js/pyrt.js · tests/web/test_classes.py · tests/web/test_text.py
interfaces
__init__ is reached; a method's first parameter emits as this; __call__ instances are callable (pyrt callable_(obj)); pyrt exports truthy, contains, dget, next_, lrep, str_, fmt, wrap, cplen- Write the failing parity tests: a dataclass with
field(default_factory=...), a@property, a class with__call__called as a function, a closure that captures a loop variable through a default (lambda i=i: i), keyword arguments to a function in another module (two-module variant ofrun_both),hasattrandisinstanceover a value that may be either of two app classes, dicts with string keys and.get, list+and* n,next(x for x in xs if ...). - Write the failing text tests (Review focus):
len("Matemática"),len("a😀b"),f"{x:.1f}"forxin(0.05, 2.25, 12.75, 3.0),str(3.0)andstr(3)through f-strings with no spec,textwrap.wrapof a 60-character Spanish name with accents and of a hyphenated word at widths 10 and 28. JS must equal Python exactly;lenandwrapcount code points (cplen). - Run: fail.
- Implement.
fmtrounds half to even on exact ties (decide the tie with the exact decimal expansion of the double, as Python does);str_prints a float with a fractional part of zero as"3.0", which needs the type: the transpiler passes"float"or"int"tostr_when it knows it and fails on an unknown numeric type in a format with no spec.wrapportstextwrap.TextWrapper._split's hyphen rule and_wrap_chunkswith the defaults. - Run: pass. Commit:
feat(web): classes, closures, collections and text.
6Types from live objects and call sitessrc/manifoldx/web/types.py · tests/web/test_types.py
interfaces
- Write the failing tests: an unannotated
def f(scene, pid): return scene.by_id(pid)called from a root asf(self.scene, self.selected)typessceneas the live class ofself.sceneandpidasstr | None; a field holding aBuildingon one instance and aLandmarkon another types as their union; a+whose operand type stays unknown raisesTranspileErrorwhose message containsannotateand the expression's text; an annotation wins over a live type. - Run: fail.
- Implement the solve as a fixed point: start with annotations and live field types; each pass types locals forward through each reached function, joins argument types at call sites into the callee's parameters, and joins return types into callers; stop when no type changes, at most 20 passes, then report the first operator whose operand is still unknown. Operators that need a type:
+,*,+=,==and!=on non-scalars, f-string fields with no spec,%with a string left side. - Run: pass. Commit:
feat(web): types from live objects and call sites.
7Roots and reachsrc/manifoldx/web/reach.py · tests/web/test_reach.py
interfaces
- Write the failing tests:
find_rootsreturns eachengine.systems._systems[i].func, each handler inengine._event_bus._handlersexcept"startup"and except manifoldx's own (the rulecode_reportuses), and eachValueDisplay._getterfound by walkingengine.gui._panelsand theirchildren. Reach follows a method only on the classes its receiver's type allows (two classes with apartsfield: only the reached one's field is in.fields). Review focus: a root that callsPath("x").exists()raisesTranspileErrornamingpathlib.Path, the line and the root's label. A system whose first parameter (its query) is used raises "component queries are not supported in the browser yet". - Run: fail.
- Implement; a bound method root's owner and a closure's cells become snapshot roots (task 8).
- Run: pass. Commit:
feat(web): roots and reach through types.
8The snapshot and its loadersrc/manifoldx/web/snapshot.py · js/manifoldx.js · tests/web/test_snapshot.py
interfaces
- Write the failing tests, each snapshotting in Python, loading in Node through
loadState, and comparing a JSON view: shared objects stay one object (a.ground === b.terrain); only reached fields are written; float32 arrays load asFloat32Array; a material reached in state but never spawned is registered, so its id is in the registry and task 2's export writes it; a dict with keys"constructor","__proto__"and"toString"round trips andin/.get/indexing find each (Review focus); a dict with an int key raisesSnapshotErrorwhose path reads likeViewer.names; a lambda in aValueDisplaywith a default argument loads as a function that returns the same value as in Python. - Run: fail.
- Implement. Objects load with
Object.create(cls.prototype), never the constructor; a class with__call__loads throughcallable_; dicts load as objects with a null prototype so prototype names are plain keys; the transpiler emits each reached closure as an exported factory__closure_<line>_<col>(cells, defaults). - Run: pass. Commit:
feat(web): state snapshot and loader.
9The headless runtime surfacesrc/manifoldx/web/js/manifoldx.js · tests/web/js/runtime.test.mjs · tests/web/test_node_suites.py
interfaces
- Write the failing Node tests (
node --test):camera.get_forward()equals numpy's float32 result for five fixed position/target pairs (values recorded by a Python test into a JSON fixture);setFramedrives every input getter;set_materialandcapture_pointerappend["material", entity, material_id]and["capture", on]tolog;stepcalls systems in registration order.tests/web/test_node_suites.pyrunsnode --test tests/web/js/from pytest somake testcovers it. - Run: fail.
- Implement.
- Run: pass. Commit:
feat(web): headless runtime surface.
10Source mapssrc/manifoldx/web/transpile.py · tests/web/test_sourcemap.py
interfaces
//# sourceMappingURL=<name>.js.map- Write the failing test: a module whose reached function raises (
xs[5]on a short list isundefinedin JS, so use a call onNone:self.missing.method()) is run withnode --enable-source-maps; the stack trace namesmod.pyand the Python line of that call. - Run: fail.
- Implement the mappings (base64 VLQ, line granularity: each emitted line maps to the Python line of the statement that produced it).
- Run: pass. Commit:
feat(web): source maps to the Python lines.
11export --web (headless output)src/manifoldx/web/export.py · src/manifoldx/cli.py · tests/web/test_export_web.py
interfaces
manifoldx export --web [-m module | app.py] OUTDIR- Write the failing tests: the CLI writes every file above for a small app;
report.jsonlists each root, each transpiled function, and each function left as setup; a transpile error exits 1, printsfile.py:line, and writes nothing; Review focus: an app with no systems and no GUI exports and its folder loads in Node; an app whose startup handler isasync defexports with the handler's effect visible instate.json, or, if the engine's dispatch cannot await outside the loop, fails with "async startup handlers are not supported by export --web yet: <handler>". - Run: fail.
- Implement. Capture the engine the way
cli.exportdoes (patchEngine.run,runpy); fire startup withengine._fire_startup()without creating a device (a handler that needs one, such asload_texture, creates it itself); order: roots, live types, reach, snapshot (which registers reached materials), transpile, thenengine.export_gltf(out / "scene.glb"). Factor the shared capture out ofcli.exportintomanifoldx.web.export.capture_engine(module, script, app_args) -> Engineand use it in both. Shipsrc/manifoldx/web/js/*.jsas package data. - Run: pass. Then
uv buildandunzip -l dist/*.whl | grep web/js: the three JS files are in the wheel. - Commit:
feat(cli): export --web writes the transpiled app and its state.
12The replay harness and the public examplesrc/manifoldx/web/replay.py · js/replay.mjs · examples/web_walk.py · tests/web/fixtures/web_walk_script.json · tests/web/test_replay.py
interfaces
- Write
examples/web_walk.py: a flat ground, six boxes with names, a first-person rig class in the app (walk with WASD, look with the mouse when the pointer is captured, Tab toggles a fly mode), a click that picks the box under the crosshair with a ray test written in the app and marks it withengine.set_material, a GUI panel with aValueDisplayper line naming the picked box. No textures. It is the shape of the first consumer in 150 lines. Writetests/web/fixtures/web_walk_script.json: 600 frames from a seeded generator kept in the test file (the generator writes the fixture when--regenis passed), with clicks, Tab, Escape, right-drag and a resize. - Write the failing test:
compare(replay_python(...), replay_node(...))isNonefor the example withpaths=["rig.pos", "rig.yaw", "rig.mode", "selected"]; the trace has at least 3 distinct non-nullselectedvalues and at least onematerialentry, so the script exercises picking. - Write the three breaking tests: patching the generated JS so the pick returns null, so the camera is a plain array, and dropping the boxes from the snapshot; each must make
comparereturn aMismatch. - Run: fail. Implement. Run
make test: pass. - Commit:
feat(web): replay harness and the web_walk example.
uv run pytest tests/web/test_replay.py -v: 4 passed, and the parity test prints the frame count and the number of distinct selections.
13Docs and the PRknow-how/web-export.md · CHANGELOG.md · AGENTS.md (sub-projects line)
- Write
know-how/web-export.mdwith awhen:line: what reaches the browser, the subset and its errors, annotating when the export asks, the replay harness and how to write a script. - Add a
CHANGELOG.mdentry under[Unreleased]and one line under "Sub-projects in flight" inAGENTS.mdpointing at the spec and this plan. - Run
make testandmake lint: pass. Push the branch, open the PR referencing #93 and #131, and work it until CI is green.
14The first consumer replays in its own CIthe consumer's repository: app code, a replay test, its CI workflow
Runs in the first consumer's repository after the manifoldx PR merges; its own issue, branch and PR. The consumer's agent docs name it.
- Pin manifoldx to the merge commit. Replace the three workarounds with
engine.set_material,engine.input.capture_pointerandengine.input.viewport_size; its desktop tests and--shotstill pass. - Add a replay test:
manifoldx export --webof the app into a temp folder, its own 900-frame script,paths=["rig.pos", "rig.yaw", "rig.pitch", "rig.mode", "selected", "captured"],compareisNone. - CI: install
mesa-vulkan-driversso the startup's textures get a software device, then run the replay test. If the adapter request still fails on the runner, record that under "where this plan departs" and run the replay inmake checkonly. - Its existing hand-written web viewer stays until plan 2 replaces it.
Where this plan departs from the spec
- The spec's slice 1 lists source maps; the overlay that uses them is slice 4. This plan builds the maps (task 10) and tests them through Node's stack traces only.
- Systems whose query parameter is used fail at export (task 7). The spec puts numpy over component arrays out of scope; this makes the boundary an error rather than a wrong app.
Buttonhas no callback in manifoldx (a click is an event), so the roots are systems, handlers andValueDisplaygetters; the spec's "aButton's handler" is a handler root.