@litz-sim/litz 0.1.0 → 0.2.1

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,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
package/README.md CHANGED
@@ -1,159 +1,227 @@
1
- # litz
1
+ # @litz-sim/litz
2
2
 
3
- A deterministic electronics and firmware simulator in one WebAssembly module. It runs a board, its firmware, the parts wired around it and the electrical rules between them, and it advances only when you ask it to — the same input produces the same run, byte for byte, on every machine.
3
+ `@litz-sim/litz` is the JavaScript binding for Litz, a deterministic electronics and firmware simulator. The package loads `litz_wasm.wasm`, opens a session on one board from a `diagram.json` and an application image, and exposes serial output, part state, pins, probes, decoders, displays and electrical conflicts as plain objects. It has no DOM code, no workers and no runtime dependencies, and it advances only when the host calls `run` or `advance`.
4
4
 
5
- The module has no imports and no host bindings: it is linear memory plus integers, loaded with `WebAssembly.instantiate` and driven through this package's small JavaScript API. No DOM, no worker requirements, no network.
5
+ ## Install
6
6
 
7
7
  ```sh
8
8
  npm install @litz-sim/litz
9
9
  ```
10
10
 
11
- ## Quick start
11
+ The package is an ES module for Node 18 or newer and for browsers. It ships `index.js`, `index.d.ts`, `src/` and the compiled `litz_wasm.wasm`, about 5.5 MB uncompressed.
12
+
13
+ ## First session
14
+
15
+ `loadLitz` reads, compiles and instantiates the module and returns a `Litz`. `createSession` opens one board, selected by the board named in the diagram. `advance` moves simulated time, `serial.take` drains the console and `close` releases the session. The sample below reads the repository's `blinky` example. In a checkout, `npm run example` runs it from `js/examples/blinky.mjs`, where Node resolves the package name through the enclosing `js/package.json`. In another project, install the package and pass that project's diagram and image.
12
16
 
13
17
  ```js
14
18
  import { readFile } from "node:fs/promises";
15
19
  import { loadLitz } from "@litz-sim/litz";
16
20
 
17
21
  const litz = await loadLitz();
18
-
19
22
  const session = litz.createSession({
20
- diagram: await readFile("diagram.json", "utf8"),
21
- app: new Uint8Array(await readFile("firmware.bin")),
23
+ diagram: await readFile("../examples/blinky/diagram.json", "utf8"),
24
+ app: new Uint8Array(await readFile("../examples/blinky/firmware/blinky.bin")),
22
25
  });
23
26
 
24
- for (let i = 0; i < 20; i += 1) {
25
- session.run(400_000); // scheduling steps, not milliseconds
26
- process.stdout.write(session.serial.take());
27
- }
28
-
29
- console.log(session.ms, "simulated ms");
30
- console.log(session.parts()); // [{ id, code, kind, state, value }, ...]
27
+ session.advance(300);
28
+ process.stdout.write(session.serial.take());
29
+ console.log(session.chip().name, session.ms, session.stop);
31
30
  session.close();
31
+ litz.close();
32
32
  ```
33
33
 
34
- In a browser the same code works; `loadLitz()` fetches `litz_wasm.wasm` from beside the module.
35
-
36
- ## The diagram
34
+ `run(steps)` executes at most `steps` scheduling steps and returns the simulated clock in milliseconds. A step is a unit of the scheduler rather than a fixed span of time, so `advance(ms)` repeats `run` in chunks until the clock reaches the target. Both calls are synchronous and bounded.
35
+
36
+ ## Session surface
37
+
38
+ | Member | Kind | Description |
39
+ |---|---|---|
40
+ | `run(steps?)` | method | Advance at most `steps` scheduling steps; returns simulated milliseconds. Default `DEFAULT_STEPS`. |
41
+ | `advance(ms, options?)` | method | Advance until the clock has moved `ms` milliseconds; returns the clock. Throws when `maxSteps` is exhausted. |
42
+ | `ms` | getter | Simulated milliseconds since reset. |
43
+ | `chip()` | method | The booted backend: `{ name, cpuHz, flash }`. |
44
+ | `stop` | getter | How the last `run` ended: `budget`, `idle`, `halted`, `trap`, `reset` or `breakpoint`. |
45
+ | `fault` | getter | The backend's trap text, or `null`. |
46
+ | `heap()` | method | The firmware's free heap in bytes, or `null` when it cannot be asked. |
47
+ | `serial.take()` | method | Drain the console since the last call; returns UTF-8 text. |
48
+ | `serial.write(data)` | method | Deliver a string or bytes to the board's UART0 receiver. |
49
+ | `trace.start()` | method | Begin recording net transitions. |
50
+ | `trace.transitions` | getter | Number of transitions recorded so far. |
51
+ | `trace.vcd()` | method | The recording as a VCD document. |
52
+ | `probe.add(name, point)` | method | Watch `<board>:<GPIO>` or `<part>:<pin>`; samples appear in `scope()`. |
53
+ | `decode.add(spec)` | method | Add a UART, I2C or SPI decoder over probes. |
54
+ | `scope()` | method | Every probe's samples and every decoder's frames. |
55
+ | `parts()` | method | Every part the diagram declares, with current state. |
56
+ | `part(id)` | method | One part by id, including board-expanded ids such as `esp/led_pwr`; `null` when absent. |
57
+ | `press(id, pressed?)` | method | Press or release a pushbutton; defaults to pressed. |
58
+ | `setControl(id, permille)` | method | Move a control through 0 to 1000 permille of its travel. |
59
+ | `setNamedControl(id, name, value)` | method | Set a named control such as a sensor's `temperature` or `lux`. |
60
+ | `partPin(id, pin?)` | method | The level on a part pin, or `null`; the first pin when `pin` is omitted. |
61
+ | `gpio(pin)` | method | The level the chip sees on one of its own pads, by GPIO number. |
62
+ | `display()` | method | The panel, or `null` when the circuit has none. |
63
+ | `touch(x, y, down?)` | method | Deliver a touch at panel pixels; `false` without a panel. |
64
+ | `conflicts()` | method | Electrical conflicts, oldest first. |
65
+ | `handle` | getter | The handle inside the module; `0` is never a session. |
66
+ | `close()` | method | Drop the session and release its module memory. |
67
+
68
+ `Display` carries `width`, `height`, a `version` that grows when pixels change, and `pixels()`, which returns RGBA8888 bytes sized `width * height * 4`.
69
+
70
+ ## Session options
71
+
72
+ | Field | Type | Default | Description |
73
+ |---|---|---|---|
74
+ | `diagram` | `string` | required | The `diagram.json` text. Its board selects the chip. |
75
+ | `app` | `Uint8Array \| ArrayBuffer \| ArrayBufferView` | required | The application image. |
76
+ | `rom` | bytes or `null` | `null` | Mask ROM for firmware that needs one. |
77
+ | `boot` | bytes or `null` | `null` | Second-stage bootloader; the module accepts it only with `ptable`. |
78
+ | `ptable` | bytes or `null` | `null` | Partition table; the module accepts it only with `boot`. |
79
+ | `flashSize` | `number` or `null` | board manifest, then module default | Flash size in bytes; must be a positive whole number. |
80
+ | `mac` | `string` or `null` | module default | The station MAC, for example `24:0a:c4:12:34:56`. |
81
+ | `analog` | `boolean` | `false` | Solve the analog network instead of treating every net as digital. |
82
+ | `manifests` | `Array<string \| { toml, schematic }>` | `[]` | Catalog manifests as TOML text; a board with an internal schematic uses `{ toml, schematic }`. |
83
+ | `parts` | `Record<string, () => HostPart>` | `{}` | Wasm part factories keyed by the module name in the part manifest. |
84
+ | `boards` | `Record<string, (host) => HostChip>` | `{}` | Wasm chip factories keyed by the module name in the board manifest. |
85
+
86
+ ## Chips and firmware images
87
+
88
+ The board named in `diagram.json` selects the backend. The shipped module boots ESP32-C3, ESP32-C6, ESP32-P4 and ESP32-S31 (RISC-V), the ATmega328P on Arduino Uno, Nano and Pro Mini boards, and the RP2040 on Raspberry Pi Pico boards. The classic ESP32 and ESP32-S3 run on Xtensa, whose simulator executes guest blocks through a host JIT that this module does not carry; `createSession` throws a `LitzError` that names the chip and the supported alternatives.
89
+
90
+ `app` is the application image. `rom` adds a mask ROM. `boot` and `ptable` add the second-stage bootloader and partition table and are supplied together. A merged ESP image is recognised and written at the bootloader offset; a bare application is written at the chip's application offset. `chip().flash` reports where the images landed.
91
+
92
+ ## Custom parts and boards with jco
93
+
94
+ A catalog part or board can be a WebAssembly Component. Browsers cannot instantiate a component directly, so transpile it once with [jco](https://github.com/bytecodealliance/jco):
37
95
 
38
- `diagram.json` is the wiring: parts, their attributes and the connections between their pins. It is the same file the editor and the `litz` CLI read.
39
-
40
- ```json
41
- {
42
- "version": 1,
43
- "parts": [
44
- { "id": "esp", "type": "board-esp32-c3-devkitm-1", "attrs": {} },
45
- { "id": "r1", "type": "litz-resistor", "attrs": { "value": "220" } },
46
- { "id": "led1", "type": "litz-led", "attrs": { "color": "green" } }
47
- ],
48
- "connections": [
49
- ["esp:GPIO8", "r1:1", "green", []],
50
- ["r1:2", "led1:A", "green", []],
51
- ["led1:C", "esp:GND.1", "black", []],
52
- ["esp:TX", "$serialMonitor:RX", "", []]
53
- ]
54
- }
96
+ ```sh
97
+ npx jco transpile 74hc595.wasm -o out --instantiation sync
55
98
  ```
56
99
 
57
- ## Running
58
-
59
- A call to `run(steps)` advances the machine by at most `steps` scheduling steps and returns the simulated clock in milliseconds. A step is one unit of the simulator's scheduler, not a fixed span of time, so a host that wants a deadline should use `advance(ms)`:
100
+ The generated JavaScript exports `instantiate(getCoreModule, imports)`. Pass the generated modules to `partFromJco` with `partImports`, or to `chipFromJco` with `chipImports`. The part sample below uses the shipped `74hc595` fixture; save it as `demo-part.mjs` in `js/` and run it from that directory.
60
101
 
61
102
  ```js
62
- session.advance(500); // run until the simulated clock reaches +500 ms
63
- session.ms; // 500
64
- ```
65
-
66
- Both calls are synchronous and bounded, which is what makes them usable inside a `requestAnimationFrame` loop or a tight server loop.
67
-
68
- ## Serial
103
+ import { readFile } from "node:fs/promises";
104
+ import { loadLitz, partFromJco, partImports } from "@litz-sim/litz";
105
+ import { instantiate } from "./test/fixtures/74hc595/74hc595.js";
106
+
107
+ const core = new WebAssembly.Module(await readFile("./test/fixtures/74hc595/74hc595.core.wasm"));
108
+ const diagram = JSON.stringify({
109
+ version: 1,
110
+ parts: [
111
+ { id: "esp", type: "board-esp32-c3-devkitm-1", attrs: {} },
112
+ { id: "sh", type: "litz-74hc595", attrs: {} },
113
+ { id: "r1", type: "litz-resistor", attrs: { value: "220" } },
114
+ { id: "led1", type: "litz-led", attrs: { color: "green" } },
115
+ ],
116
+ connections: [
117
+ ["esp:GPIO8", "sh:SHCP", "", []],
118
+ ["esp:GPIO8", "sh:STCP", "", []],
119
+ ["esp:3V3", "sh:DS", "", []],
120
+ ["esp:3V3", "sh:MR", "", []],
121
+ ["esp:GND.1", "sh:OE", "", []],
122
+ ["sh:Q0", "r1:1", "", []],
123
+ ["r1:2", "led1:A", "", []],
124
+ ["led1:C", "esp:GND.1", "", []],
125
+ ],
126
+ });
69
127
 
70
- The console is collected automatically and capped at 1 MiB inside the module, oldest bytes dropped first, so a firmware that prints in a loop cannot exhaust memory.
128
+ const litz = await loadLitz();
129
+ const session = litz.createSession({
130
+ diagram,
131
+ app: new Uint8Array(await readFile("../examples/blinky/firmware/blinky.bin")),
132
+ parts: {
133
+ "74hc595.wasm": () => partFromJco(instantiate(() => core, partImports())),
134
+ },
135
+ });
71
136
 
72
- ```js
73
- session.serial.take(); // drain what the firmware printed, as UTF-8
74
- session.serial.write("hello\r");// deliver bytes to the board's UART0 receiver
137
+ session.advance(500);
138
+ console.log(session.part("led1"));
139
+ session.close();
140
+ litz.close();
75
141
  ```
76
142
 
77
- ## Parts and controls
143
+ The factory is called once per part instance while the board is built, and the session keeps the instance until it is closed. `parts` and `boards` are keyed by the module name in the part or board manifest. A chip factory receives the guest's host object:
78
144
 
79
145
  ```js
80
- session.parts(); // every part the diagram declares
81
- session.part("led1"); // { id, code, kind, state, value }
82
- session.press("btn1", true); // hold a pushbutton
83
- session.setControl("pot1", 500);// 0 to 1000 permille of travel
146
+ import { readFileSync } from "node:fs";
147
+ import { chipFromJco, chipImports } from "@litz-sim/litz";
148
+ import { instantiate } from "./test/fixtures/board-v2/board-v2.js";
149
+
150
+ const cores = new Map();
151
+ const getCoreModule = (name) => {
152
+ if (!cores.has(name)) {
153
+ cores.set(name, new WebAssembly.Module(readFileSync(`./test/fixtures/board-v2/${name}`)));
154
+ }
155
+ return cores.get(name);
156
+ };
157
+
158
+ const boards = {
159
+ "board-v2.wasm": (host) => chipFromJco(instantiate(getCoreModule, chipImports(host))),
160
+ };
84
161
  ```
85
162
 
86
- `state` is a word — `off`, `on`, `up`, `down`, `silent`, `sounding`, `position`, `mask`, `state` — and `kind` says what the part is. A board instance reports `state: null`; `part()` returns `null` for an id the diagram does not have. `value` carries the number behind the state: servo degrees, a segment mask, a knob's position.
163
+ Pass `boards` with the board manifest in `manifests`; [the JavaScript reference](../docs/javascript.md#a-custom-litzmcu020-chip) has a complete bootable example.
87
164
 
88
- ## Display and touch
165
+ ## The `litz:mcu` bridge
89
166
 
90
- ```js
91
- const panel = session.display(); // null when the circuit has no display
92
- if (panel) {
93
- panel.width; panel.height; panel.version; // version changes when pixels do
94
- const rgba = panel.pixels(); // Uint8Array, width * height * 4
95
- }
96
- session.touch(x, y, true); // false when the board has no panel
97
- ```
167
+ Both `litz:mcu@0.1.0` and `litz:mcu@0.2.0` chips are bridged in full. The 0.1 contract covers images, pins, console and fault. The 0.2 contract adds analog reads, I2C, SPI and UART transactions, Wi-Fi scan, join and resolve with TCP and UDP, BLE scanning, advertising and GATT, and the raw radio. Every 0.2 call reaches the circuit through the module's `litz_guest_call` export, answered by the same host state the native runner uses. `chipImports(host)` turns each contract function into a `host.call(op, args)` request where `op` is the contract's camelCase name and `args` is a plain JSON object; a call the circuit refuses throws `LitzError`.
98
168
 
99
- ## Logic analyser
169
+ ## Errors
170
+
171
+ Every failing loader or session call throws `LitzError`. The message is the reason the module gave, so a bad diagram reports the parse error and a bad pin reports the pin. `LitzError` extends `Error`, sets `name` to `"LitzError"` and accepts an `options` object with a `cause`.
100
172
 
101
173
  ```js
102
- session.probe.add("tx", "esp:TX"); // <board>:<GPIO> or <part>:<pin>
103
- session.trace.start();
104
- session.advance(200);
174
+ import { loadLitz, LitzError } from "@litz-sim/litz";
105
175
 
106
- session.scope(); // { ms, probes, decodes } — samples and measurements
107
- session.trace.vcd(); // the same recording as a VCD document
108
- session.decode.add("uart:rx=tx,baud=115200");
176
+ const litz = await loadLitz();
177
+ try {
178
+ litz.createSession({ diagram: "{}", app: new Uint8Array([1, 2, 3, 4]) });
179
+ } catch (error) {
180
+ if (error instanceof LitzError) console.error(error.message);
181
+ } finally {
182
+ litz.close();
183
+ }
109
184
  ```
110
185
 
111
- Every probe carries `digital` (`[tick_ns, level]`), `volts` (`[tick_ns, volts]`) and the measurements the run can derive from them: edges, high and low time, frequency, duty, minimum and maximum volts.
186
+ `partFromJco` and `chipFromJco` throw `TypeError` when the transpiled module does not export the expected interface. A factory that returns the wrong shape, or that throws, is reported as a `LitzError` naming the module during `createSession`.
112
187
 
113
- ## Faults
188
+ ## Loading the module
114
189
 
115
- A short across a supply, two outputs fighting over a net, a part on the wrong rail: the board resolves the net and records a conflict rather than guessing.
190
+ `loadLitz` accepts bytes, a URL, a `Response` or an already compiled `WebAssembly.Module`. Without `wasm` it reads the file shipped beside the package, exported as `wasmUrl`. A relative string is resolved against the loader's own module URL, so pass an absolute URL or bytes when the working directory differs.
116
191
 
117
192
  ```js
118
- session.conflicts(); // array of fault descriptions
119
- ```
193
+ import { readFile } from "node:fs/promises";
194
+ import { loadLitz, wasmUrl } from "@litz-sim/litz";
120
195
 
121
- ## Loading options
196
+ const bytes = new Uint8Array(await readFile(new URL(wasmUrl)));
197
+ const fromBytes = await loadLitz({ wasm: bytes });
198
+ const fromModule = await loadLitz({ wasm: new WebAssembly.Module(bytes) });
199
+ const fromUrl = await loadLitz({ wasm: wasmUrl });
122
200
 
123
- ```js
124
- await loadLitz(); // the file beside this package
125
- await loadLitz({ wasm: bytes }); // Uint8Array or ArrayBuffer
126
- await loadLitz({ wasm: "/assets/litz_wasm.wasm" });// fetched
127
- await loadLitz({ wasm: module }); // a compiled WebAssembly.Module
201
+ fromBytes.close();
202
+ fromModule.close();
203
+ fromUrl.close();
128
204
  ```
129
205
 
130
- Bundlers that cannot copy arbitrary assets should read the file themselves and pass `wasm` as bytes. The module is about 2.4 MB uncompressed and compresses to roughly a third of that.
206
+ `imports` is merged into the module's import object. The `litz_host` namespace holds this package's part and chip bridge and is merged with the built-in runtime; other namespaces are passed through. The shipped module imports only `litz_host`.
131
207
 
132
- ## Errors
208
+ ## Browser and Node
133
209
 
134
- Every failing call throws `LitzError` with the reason the module gave, so a bad diagram reports the parse error and a bad pin reports the pin.
210
+ In Node, the default source is a `file:` URL and the loader reads it with `node:fs/promises`. In a browser, the default source is fetched from the package URL; pass a `Response` or an absolute URL when the asset lives elsewhere. Bundlers that do not copy arbitrary assets can read the wasm themselves and pass `wasm` as bytes or a compiled module. The package uses standard web APIs and, on Node, `node:fs/promises` for `file:` sources; it contains no DOM access.
135
211
 
136
- ```js
137
- import { LitzError } from "@litz-sim/litz";
138
- try {
139
- litz.createSession({ diagram, app });
140
- } catch (error) {
141
- if (error instanceof LitzError) console.error(error.message);
142
- }
143
- ```
144
-
145
- ## Firmware images
212
+ ## Building and testing
146
213
 
147
- This build runs ESP32-C3 images: an application image, optionally with a second-stage bootloader and partition table, and with a mask ROM when the firmware needs one. `createSession` takes `rom`, `boot` and `ptable` alongside `app`.
214
+ `npm run build` compiles `crates/litz-wasm` for `wasm32-unknown-unknown`, copies `litz_wasm.wasm` next to `index.js`, and checks that the module imports only `litz_host` and exports every name the wrapper requires. The Rust target must be installed in the toolchain. `npm test` runs `node --test` over `test/*.test.js` against the shipped module and the repository's example firmware.
148
215
 
149
- ```js
150
- litz.createSession({ diagram, rom, boot, ptable, app });
216
+ ```sh
217
+ npm run build
218
+ npm test
151
219
  ```
152
220
 
153
- Other chips are in the simulator's native builds but not in this module yet.
221
+ ## Reference
154
222
 
155
- The `litz` CLI builds firmware, runs the test files and can export a project. It is a separate Rust tool, not part of this package.
223
+ The full API reference, including every type, lifecycle rule, host import name and a complete custom `litz:mcu@0.2.0` chip, is in [docs/javascript.md](../docs/javascript.md).
156
224
 
157
225
  ## License
158
226
 
159
- MIT OR Apache-2.0.
227
+ Apache-2.0.