@litz-sim/litz 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,159 @@
1
- # Temporary Holding Version
1
+ # litz
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
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.
6
+
7
+ ```sh
8
+ npm install @litz-sim/litz
9
+ ```
10
+
11
+ ## Quick start
12
+
13
+ ```js
14
+ import { readFile } from "node:fs/promises";
15
+ import { loadLitz } from "@litz-sim/litz";
16
+
17
+ const litz = await loadLitz();
18
+
19
+ const session = litz.createSession({
20
+ diagram: await readFile("diagram.json", "utf8"),
21
+ app: new Uint8Array(await readFile("firmware.bin")),
22
+ });
23
+
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 }, ...]
31
+ session.close();
32
+ ```
33
+
34
+ In a browser the same code works; `loadLitz()` fetches `litz_wasm.wasm` from beside the module.
35
+
36
+ ## The diagram
37
+
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
+ }
55
+ ```
56
+
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)`:
60
+
61
+ ```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
69
+
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.
71
+
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
75
+ ```
76
+
77
+ ## Parts and controls
78
+
79
+ ```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
84
+ ```
85
+
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.
87
+
88
+ ## Display and touch
89
+
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
+ ```
98
+
99
+ ## Logic analyser
100
+
101
+ ```js
102
+ session.probe.add("tx", "esp:TX"); // <board>:<GPIO> or <part>:<pin>
103
+ session.trace.start();
104
+ session.advance(200);
105
+
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");
109
+ ```
110
+
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.
112
+
113
+ ## Faults
114
+
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.
116
+
117
+ ```js
118
+ session.conflicts(); // array of fault descriptions
119
+ ```
120
+
121
+ ## Loading options
122
+
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
128
+ ```
129
+
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.
131
+
132
+ ## Errors
133
+
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.
135
+
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
146
+
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`.
148
+
149
+ ```js
150
+ litz.createSession({ diagram, rom, boot, ptable, app });
151
+ ```
152
+
153
+ Other chips are in the simulator's native builds but not in this module yet.
154
+
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.
156
+
157
+ ## License
158
+
159
+ MIT OR Apache-2.0.
package/index.d.ts ADDED
@@ -0,0 +1,180 @@
1
+ /** Loaded Litz module, ready to open sessions. */
2
+ export declare class Litz {
3
+ private constructor();
4
+ /** The raw wasm export object. */
5
+ readonly exports: WebAssembly.Exports;
6
+ /** The instance this runtime was built from. */
7
+ readonly instance: WebAssembly.Instance;
8
+ /** Open a session on one board. */
9
+ createSession(options: SessionOptions): Session;
10
+ /** Release module memory. Sessions must be closed first. */
11
+ close(): void;
12
+ }
13
+
14
+ export interface SessionOptions {
15
+ /** The diagram.json text. */
16
+ diagram: string;
17
+ /** The application image. */
18
+ app: Uint8Array | ArrayBuffer | ArrayBufferView;
19
+ /** Mask ROM, when the firmware needs one. */
20
+ rom?: Uint8Array | ArrayBuffer | ArrayBufferView | null;
21
+ /** Second-stage bootloader; requires `ptable`. */
22
+ boot?: Uint8Array | ArrayBuffer | ArrayBufferView | null;
23
+ /** Partition table; requires `boot`. */
24
+ ptable?: Uint8Array | ArrayBuffer | ArrayBufferView | null;
25
+ }
26
+
27
+ export interface LoadOptions {
28
+ /** Bytes, a URL, a `Response`, or an already compiled module. */
29
+ wasm?: Uint8Array | ArrayBuffer | ArrayBufferView | string | URL | Response | WebAssembly.Module | null;
30
+ /** Passed to `WebAssembly.instantiate`; the release build imports nothing. */
31
+ imports?: WebAssembly.Imports;
32
+ }
33
+
34
+ /** Where the shipped wasm file sits. */
35
+ export declare const wasmUrl: string;
36
+
37
+ /** Scheduling steps per call when the host does not choose. */
38
+ export declare const DEFAULT_STEPS: number;
39
+
40
+ /** Load the module. Without `wasm`, the file next to the module is used. */
41
+ export declare function loadLitz(options?: LoadOptions): Promise<Litz>;
42
+
43
+ export declare class LitzError extends Error {}
44
+
45
+ export type PartStateName =
46
+ | "none"
47
+ | "off"
48
+ | "on"
49
+ | "up"
50
+ | "down"
51
+ | "silent"
52
+ | "sounding"
53
+ | "position"
54
+ | "mask"
55
+ | "state"
56
+ | "unknown";
57
+
58
+ export interface PartState {
59
+ /** The id the diagram gave the part. */
60
+ id: string;
61
+ /** The ABI's state code: 0 none, 1 off, 2 on, 3 up, 4 down. */
62
+ code: number;
63
+ /** `code` as a word; `null` for a part that reports nothing (a board). */
64
+ state: PartStateName | null;
65
+ /** The number behind the state: servo degrees, a segment mask, a tone rate. */
66
+ value: number;
67
+ }
68
+
69
+ export interface Display {
70
+ readonly width: number;
71
+ readonly height: number;
72
+ /** Grows when the pixels change, so a host can skip an unchanged frame. */
73
+ readonly version: number;
74
+ /** The frame as RGBA8888, `width * height * 4` bytes. */
75
+ pixels(): Uint8Array;
76
+ }
77
+
78
+ export interface Serial {
79
+ /** Drain what the firmware printed since the last call. */
80
+ take(): string;
81
+ /** Deliver bytes to the board's UART0 receiver. */
82
+ write(data: string | Uint8Array | ArrayBuffer | ArrayBufferView): void;
83
+ }
84
+
85
+ export interface Trace {
86
+ /** Begin recording net transitions. */
87
+ start(): void;
88
+ /** Recorded transitions so far. */
89
+ readonly transitions: number;
90
+ /** The recording as a VCD document. */
91
+ vcd(): string;
92
+ }
93
+
94
+ export interface Probes {
95
+ /**
96
+ * Watch a point: `<board>:<GPIO>` (`esp:GPIO8`) or `<part>:<pin>`
97
+ * (`led1:A`). Samples appear in `session.scope()`.
98
+ */
99
+ add(name: string, point: string): void;
100
+ }
101
+
102
+ export interface Decoders {
103
+ /** `uart:rx=<probe>[,baud=N]`, `i2c:sda=<probe>,scl=<probe>`,
104
+ * `spi:sck=<probe>,mosi=<probe>,cs=<probe>[,miso=<probe>][,mode=N]`. */
105
+ add(spec: string): void;
106
+ }
107
+
108
+ export interface ProbeRecord {
109
+ name: string;
110
+ point: string;
111
+ /** Net the probe resolves to on the flattened board. */
112
+ net: number;
113
+ /** Level transitions as `[tick_ns, level]`, level 0 low, 1 high, 2 high-Z. */
114
+ digital: Array<[number, number]>;
115
+ /** Voltage samples as `[tick_ns, volts]`. */
116
+ volts: Array<[number, number]>;
117
+ edges: number;
118
+ high_ns: number;
119
+ low_ns: number;
120
+ frequency_hz: number | null;
121
+ duty: number | null;
122
+ min_volts: number | null;
123
+ max_volts: number | null;
124
+ }
125
+
126
+ export interface DecodeRecord {
127
+ spec: string;
128
+ kind: string;
129
+ name: string;
130
+ frames: Array<{ at: number; end: number; text: string; error: boolean | string }>;
131
+ }
132
+
133
+ export interface ScopeDocument {
134
+ /** Simulated ms at the time of the call. */
135
+ ms: number;
136
+ probes: ProbeRecord[];
137
+ decodes: DecodeRecord[];
138
+ }
139
+
140
+ export interface AdvanceOptions {
141
+ /** Steps per inner `run` call. */
142
+ chunkSteps?: number;
143
+ /** Give up after this many steps. */
144
+ maxSteps?: number;
145
+ }
146
+
147
+ /** One running board. */
148
+ export declare class Session {
149
+ private constructor();
150
+ /** The handle inside the module. */
151
+ readonly handle: number;
152
+ /** Advance by at most `steps` scheduling steps; returns the simulated ms. */
153
+ run(steps?: number): number;
154
+ /** Advance until `ms` of simulated time have passed. */
155
+ advance(ms: number, options?: AdvanceOptions): number;
156
+ /** Simulated milliseconds since reset. */
157
+ readonly ms: number;
158
+ readonly serial: Serial;
159
+ readonly trace: Trace;
160
+ readonly probe: Probes;
161
+ readonly decode: Decoders;
162
+ /** Electrical conflicts, oldest first. */
163
+ conflicts(): string[];
164
+ /** Every part the diagram declares. */
165
+ parts(): PartState[];
166
+ /** One part by id, including board-expanded ids such as `esp/led_pwr`. */
167
+ part(id: string): PartState | null;
168
+ /** Press or release a pushbutton wired to a GPIO. */
169
+ press(id: string, pressed?: boolean): void;
170
+ /** Move a control: 0 to 1000 permille of its travel. */
171
+ setControl(id: string, permille: number): void;
172
+ /** The panel, or `null` when the circuit has no display. */
173
+ display(): Display | null;
174
+ /** Deliver a touch at panel pixels. False without a panel. */
175
+ touch(x: number, y: number, down?: boolean): boolean;
176
+ /** Probes' samples and decoders' frames. */
177
+ scope(): ScopeDocument;
178
+ /** Drop the session. */
179
+ close(): void;
180
+ }
package/index.js ADDED
@@ -0,0 +1,661 @@
1
+ // Litz as a headless WebAssembly library.
2
+ //
3
+ // The module next to this file is built from `crates/litz-wasm`, which exposes
4
+ // a C ABI over linear memory: pointers are byte offsets, strings are UTF-8 and
5
+ // every call is synchronous. This file turns that into objects — a session, its
6
+ // serial line, its parts, its display — and nothing else. There is no DOM code
7
+ // here and no host dependency, so the same import runs in Node, in a browser
8
+ // worker and in any bundler that understands `import.meta.url`.
9
+ //
10
+ // A session owns one board, its flash and its peripherals. `session.run(steps)`
11
+ // advances it and returns the simulated clock; the host decides how much time
12
+ // to simulate per call.
13
+
14
+ /** Scheduling steps per call when the host does not choose. */
15
+ export const DEFAULT_STEPS = 400_000;
16
+
17
+ /** Where the wasm file sits when the package is loaded as a module. */
18
+ export const wasmUrl = new URL("./litz_wasm.wasm", import.meta.url).href;
19
+
20
+ const REQUIRED_EXPORTS = [
21
+ "memory",
22
+ "litz_alloc",
23
+ "litz_free",
24
+ "litz_new",
25
+ "litz_drop",
26
+ "litz_last_error",
27
+ "litz_run",
28
+ "litz_ms",
29
+ "litz_conflict_count",
30
+ "litz_conflict",
31
+ "litz_serial_take",
32
+ "litz_serial_write",
33
+ "litz_display_info",
34
+ "litz_display_version",
35
+ "litz_display_rgba",
36
+ "litz_touch",
37
+ "litz_trace_start",
38
+ "litz_trace_len",
39
+ "litz_trace_vcd",
40
+ "litz_probe_add",
41
+ "litz_scope_len",
42
+ "litz_scope_json",
43
+ "litz_decode_add",
44
+ "litz_part_state",
45
+ "litz_part_value",
46
+ "litz_press",
47
+ "litz_set_control",
48
+ "litz_part_count",
49
+ "litz_part_id",
50
+ ];
51
+
52
+ // State codes from `litz_part_state`; `-1` means the diagram has no such id.
53
+ // The code carries both what the part is and what it is doing, which is why
54
+ // the wrapper reports a kind as well as a word.
55
+ const STATE_CODES = [
56
+ { kind: "none", state: "none" },
57
+ { kind: "led", state: "off" },
58
+ { kind: "led", state: "on" },
59
+ { kind: "button", state: "up" },
60
+ { kind: "button", state: "down" },
61
+ { kind: "switch", state: "off" },
62
+ { kind: "switch", state: "on" },
63
+ { kind: "tone", state: "silent" },
64
+ { kind: "tone", state: "sounding" },
65
+ { kind: "servo", state: "position" },
66
+ { kind: "segments", state: "mask" },
67
+ { kind: "knob", state: "position" },
68
+ { kind: "radio", state: "state" },
69
+ ];
70
+
71
+ const ENCODER = new TextEncoder();
72
+ const DECODER = new TextDecoder();
73
+
74
+ export class LitzError extends Error {
75
+ constructor(message, options) {
76
+ super(message, options);
77
+ this.name = "LitzError";
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Load the module and return a runtime that can open sessions.
83
+ *
84
+ * `wasm` takes bytes, a URL, a `Response`, an `ArrayBuffer` or an already
85
+ * instantiated `WebAssembly.Module`; without it the file shipped next to this
86
+ * module is used. `imports` is passed to `WebAssembly.instantiate` unchanged —
87
+ * the release build imports nothing, so it is there for a host that wraps the
88
+ * module with its own glue.
89
+ */
90
+ export async function loadLitz({ wasm = null, imports = {} } = {}) {
91
+ const instance = await instantiate(wasm ?? wasmUrl, imports);
92
+ return new Litz(instance);
93
+ }
94
+
95
+ async function instantiate(source, imports) {
96
+ if (source instanceof WebAssembly.Module) {
97
+ const missing = missingExports(source);
98
+ if (missing.length > 0) throw new LitzError(`the wasm module is missing ${missing.join(", ")}`);
99
+ const instance = await WebAssembly.instantiate(source, imports);
100
+ return instance instanceof WebAssembly.Instance ? instance : instance.instance;
101
+ }
102
+ const bytes = await toBytes(source);
103
+ let module;
104
+ try {
105
+ module = await WebAssembly.compile(bytes);
106
+ } catch (error) {
107
+ throw new LitzError("the wasm module could not be compiled", { cause: error });
108
+ }
109
+ const missing = missingExports(module);
110
+ if (missing.length > 0) {
111
+ throw new LitzError(`the wasm module is missing ${missing.join(", ")}`);
112
+ }
113
+ const result = await WebAssembly.instantiate(module, imports);
114
+ return result instanceof WebAssembly.Instance ? result : result.instance;
115
+ }
116
+
117
+ function missingExports(module) {
118
+ const present = new Set(WebAssembly.Module.exports(module).map((entry) => entry.name));
119
+ return REQUIRED_EXPORTS.filter((name) => !present.has(name));
120
+ }
121
+
122
+ async function toBytes(source) {
123
+ if (source instanceof ArrayBuffer) return new Uint8Array(source.slice(0));
124
+ if (ArrayBuffer.isView(source)) {
125
+ return new Uint8Array(
126
+ source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength),
127
+ );
128
+ }
129
+ if (typeof Response !== "undefined" && source instanceof Response) {
130
+ if (!source.ok) throw new LitzError(`fetching the wasm module failed: ${source.status}`);
131
+ return new Uint8Array(await source.arrayBuffer());
132
+ }
133
+ const url = source instanceof URL ? source : new URL(String(source), import.meta.url);
134
+ if (url.protocol === "file:") {
135
+ const { readFile } = await import("node:fs/promises");
136
+ return new Uint8Array(await readFile(url));
137
+ }
138
+ if (typeof fetch !== "function") {
139
+ throw new LitzError("this host has no fetch; pass `wasm` as bytes or a URL");
140
+ }
141
+ const response = await fetch(url);
142
+ if (!response.ok) {
143
+ throw new LitzError(`fetching ${url.href} failed: ${response.status}`);
144
+ }
145
+ return new Uint8Array(await response.arrayBuffer());
146
+ }
147
+
148
+ /** The loaded module. One of these serves any number of sessions. */
149
+ export class Litz {
150
+ #instance;
151
+ #exports;
152
+ #closed = false;
153
+ #scratchIn = 0;
154
+ #scratchInSize = 0;
155
+ #scratchOut = 0;
156
+ #scratchOutSize = 0;
157
+ #io;
158
+
159
+ constructor(instance) {
160
+ this.#instance = instance;
161
+ this.#exports = instance.exports;
162
+ const litz = this;
163
+ // The memory boundary, handed to sessions so they never reach into this
164
+ // object's state. Buffers are reused between calls and grow on demand.
165
+ this.#io = {
166
+ get exports() {
167
+ return litz.#exports;
168
+ },
169
+ view(ptr, len) {
170
+ return new Uint8Array(litz.#exports.memory.buffer, ptr, len);
171
+ },
172
+ writeIn(bytes) {
173
+ if (bytes.length > litz.#scratchInSize) {
174
+ litz.#release({ ptr: litz.#scratchIn, len: litz.#scratchInSize });
175
+ litz.#scratchInSize = Math.max(bytes.length, 4096);
176
+ litz.#scratchIn = litz.#exports.litz_alloc(litz.#scratchInSize);
177
+ if (litz.#scratchIn === 0) {
178
+ litz.#scratchInSize = 0;
179
+ throw new LitzError(`could not allocate ${bytes.length} bytes in the module`);
180
+ }
181
+ }
182
+ litz.#view(litz.#scratchIn, bytes.length).set(bytes);
183
+ return { ptr: litz.#scratchIn, len: bytes.length };
184
+ },
185
+ writeOut(len) {
186
+ if (len > litz.#scratchOutSize) {
187
+ litz.#release({ ptr: litz.#scratchOut, len: litz.#scratchOutSize });
188
+ litz.#scratchOutSize = Math.max(len, 4096);
189
+ litz.#scratchOut = litz.#exports.litz_alloc(litz.#scratchOutSize);
190
+ if (litz.#scratchOut === 0) {
191
+ litz.#scratchOutSize = 0;
192
+ throw new LitzError(`could not allocate ${len} bytes in the module`);
193
+ }
194
+ }
195
+ return { ptr: litz.#scratchOut, len };
196
+ },
197
+ copyOut(len) {
198
+ return new Uint8Array(litz.#view(litz.#scratchOut, len));
199
+ },
200
+ release(buffer) {
201
+ litz.#release(buffer);
202
+ },
203
+ error(fallback) {
204
+ const cap = litz.#io.writeOut(1024);
205
+ const written = litz.#exports.litz_last_error(cap.ptr, cap.len);
206
+ const text = written ? DECODER.decode(litz.#view(cap.ptr, written)) : "";
207
+ return new LitzError(text || fallback);
208
+ },
209
+ stored() {
210
+ const cap = litz.#io.writeOut(1024);
211
+ const written = litz.#exports.litz_last_error(cap.ptr, cap.len);
212
+ return written ? DECODER.decode(litz.#view(cap.ptr, written)) : "";
213
+ },
214
+ };
215
+ }
216
+
217
+ /** The raw export object, for a host that needs an export this API omits. */
218
+ get exports() {
219
+ return this.#exports;
220
+ }
221
+
222
+ /** The instance this runtime was built from. */
223
+ get instance() {
224
+ return this.#instance;
225
+ }
226
+
227
+ /**
228
+ * Open a session.
229
+ *
230
+ * `diagram` is the diagram.json text and `app` the application image.
231
+ * `rom`, `boot` and `ptable` are optional; giving `boot` without `ptable`
232
+ * (or the reverse) is an error, because the bootloader cannot find the
233
+ * application without the table.
234
+ */
235
+ createSession({ diagram, app, rom = null, boot = null, ptable = null } = {}) {
236
+ this.#assertOpen();
237
+ if (typeof diagram !== "string" || diagram.length === 0) {
238
+ throw new LitzError("createSession needs the diagram.json text as `diagram`");
239
+ }
240
+ const appBytes = bytesOf(app, "app");
241
+ if (appBytes.length === 0) {
242
+ throw new LitzError("createSession needs the application image as `app`");
243
+ }
244
+
245
+ const io = this.#io;
246
+ const diagramBuf = io.writeIn(ENCODER.encode(diagram));
247
+ const romBytes = optionalBytes(rom, "rom");
248
+ const bootBytes = optionalBytes(boot, "boot");
249
+ const ptableBytes = optionalBytes(ptable, "ptable");
250
+ const buffers = [
251
+ hold(io, romBytes),
252
+ hold(io, bootBytes),
253
+ hold(io, ptableBytes),
254
+ hold(io, appBytes),
255
+ ];
256
+ const [romBuf, bootBuf, ptableBuf, appBuf] = buffers;
257
+ let handle;
258
+ try {
259
+ handle = io.exports.litz_new(
260
+ diagramBuf.ptr,
261
+ diagramBuf.len,
262
+ romBuf.ptr,
263
+ romBuf.len,
264
+ bootBuf.ptr,
265
+ bootBuf.len,
266
+ ptableBuf.ptr,
267
+ ptableBuf.len,
268
+ appBuf.ptr,
269
+ appBuf.len,
270
+ );
271
+ } finally {
272
+ for (const buffer of buffers) io.release(buffer);
273
+ }
274
+ if (handle === 0) throw io.error("the session could not be created");
275
+ return new Session(io, handle);
276
+ }
277
+
278
+ /** Release the module memory this runtime holds. Sessions must be closed first. */
279
+ close() {
280
+ if (this.#closed) return;
281
+ this.#closed = true;
282
+ this.#release({ ptr: this.#scratchIn, len: this.#scratchInSize });
283
+ this.#release({ ptr: this.#scratchOut, len: this.#scratchOutSize });
284
+ this.#scratchIn = 0;
285
+ this.#scratchOut = 0;
286
+ this.#scratchInSize = 0;
287
+ this.#scratchOutSize = 0;
288
+ }
289
+
290
+ #assertOpen() {
291
+ if (this.#closed) throw new LitzError("this runtime has been closed");
292
+ }
293
+
294
+ #view(ptr, len) {
295
+ return new Uint8Array(this.#exports.memory.buffer, ptr, len);
296
+ }
297
+
298
+ #release(buffer) {
299
+ // The two reusable buffers belong to the runtime; a caller "releasing" one
300
+ // of them is a no-op, not a free that the next call would then reuse.
301
+ if (buffer.ptr === 0) return;
302
+ if (buffer.ptr === this.#scratchIn || buffer.ptr === this.#scratchOut) return;
303
+ this.#exports.litz_free(buffer.ptr, buffer.len);
304
+ }
305
+ }
306
+
307
+ function hold(io, bytes) {
308
+ if (bytes.length === 0) return { ptr: 0, len: 0 };
309
+ const ptr = io.exports.litz_alloc(bytes.length);
310
+ if (ptr === 0) throw new LitzError(`could not allocate ${bytes.length} bytes in the module`);
311
+ io.view(ptr, bytes.length).set(bytes);
312
+ return { ptr, len: bytes.length };
313
+ }
314
+
315
+ function bytesOf(value, label) {
316
+ if (value instanceof Uint8Array) return value;
317
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
318
+ if (ArrayBuffer.isView(value)) {
319
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
320
+ }
321
+ throw new LitzError(`\`${label}\` must be a Uint8Array`);
322
+ }
323
+
324
+ function optionalBytes(value, label) {
325
+ if (value === null || value === undefined) return new Uint8Array(0);
326
+ return bytesOf(value, label);
327
+ }
328
+
329
+ function decodeChunks(chunks) {
330
+ if (chunks.length === 0) return "";
331
+ if (chunks.length === 1) return DECODER.decode(chunks[0]);
332
+ const total = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
333
+ const joined = new Uint8Array(total);
334
+ let at = 0;
335
+ for (const chunk of chunks) {
336
+ joined.set(chunk, at);
337
+ at += chunk.length;
338
+ }
339
+ return DECODER.decode(joined);
340
+ }
341
+
342
+ /** One running board. */
343
+ export class Session {
344
+ #io;
345
+ #handle;
346
+ #closed = false;
347
+ #serial;
348
+ #trace;
349
+ #probe;
350
+ #decode;
351
+
352
+ /** @internal Sessions come from `Litz.createSession`. */
353
+ constructor(io, handle) {
354
+ this.#io = io;
355
+ this.#handle = handle;
356
+
357
+ const session = this;
358
+ this.#serial = {
359
+ take: () => session.#takeSerial(),
360
+ write: (data) => session.#writeSerial(data),
361
+ };
362
+ this.#trace = Object.freeze({
363
+ start: () => {
364
+ session.#assertOpen();
365
+ session.#x.litz_trace_start(session.#handle);
366
+ },
367
+ get transitions() {
368
+ session.#assertOpen();
369
+ return session.#x.litz_trace_len(session.#handle);
370
+ },
371
+ vcd: () =>
372
+ session.#readText(
373
+ (ptr, cap) => session.#x.litz_trace_vcd(session.#handle, ptr, cap),
374
+ 64 * 1024,
375
+ ),
376
+ });
377
+ this.#probe = Object.freeze({
378
+ add: (name, point) => session.#addProbe(name, point),
379
+ });
380
+ this.#decode = Object.freeze({
381
+ add: (spec) => session.#addDecode(spec),
382
+ });
383
+ }
384
+
385
+ /** The session handle inside the module; 0 is never a session. */
386
+ get handle() {
387
+ return this.#handle;
388
+ }
389
+
390
+ get #x() {
391
+ return this.#io.exports;
392
+ }
393
+
394
+ #assertOpen() {
395
+ if (this.#closed) throw new LitzError("this session has been closed");
396
+ }
397
+
398
+ /** Advance by at most `steps` scheduling steps; returns the simulated ms. */
399
+ run(steps = DEFAULT_STEPS) {
400
+ this.#assertOpen();
401
+ return this.#x.litz_run(this.#handle, steps >>> 0);
402
+ }
403
+
404
+ /**
405
+ * Advance until `ms` of simulated time have passed. A scheduling step is not
406
+ * a fixed unit of time, so this loops in chunks until the clock moves.
407
+ */
408
+ advance(ms, { chunkSteps = 20_000, maxSteps = 200_000_000 } = {}) {
409
+ this.#assertOpen();
410
+ const target = this.ms + Math.max(0, ms | 0);
411
+ let spent = 0;
412
+ while (this.ms < target && spent < maxSteps) {
413
+ this.run(chunkSteps);
414
+ spent += chunkSteps;
415
+ }
416
+ if (this.ms < target) {
417
+ throw new LitzError(`the session did not reach ${target} ms within ${maxSteps} steps`);
418
+ }
419
+ return this.ms;
420
+ }
421
+
422
+ /** Simulated milliseconds since reset. */
423
+ get ms() {
424
+ this.#assertOpen();
425
+ return this.#x.litz_ms(this.#handle);
426
+ }
427
+
428
+ /** The console. `take()` drains what the firmware printed. */
429
+ get serial() {
430
+ return this.#serial;
431
+ }
432
+
433
+ /** Wire recording for VCD export. */
434
+ get trace() {
435
+ return this.#trace;
436
+ }
437
+
438
+ /** Probe points the scope document reports. */
439
+ get probe() {
440
+ return this.#probe;
441
+ }
442
+
443
+ /** Protocol decoders over the probes. */
444
+ get decode() {
445
+ return this.#decode;
446
+ }
447
+
448
+ /** Electrical conflicts: the fault text of each, oldest first. */
449
+ conflicts() {
450
+ this.#assertOpen();
451
+ const count = this.#x.litz_conflict_count(this.#handle);
452
+ const out = [];
453
+ for (let index = 0; index < count; index += 1) {
454
+ out.push(this.#readText((ptr, cap) => this.#x.litz_conflict(this.#handle, index, ptr, cap)));
455
+ }
456
+ return out;
457
+ }
458
+
459
+ /** Every part the diagram declares, with its current state. */
460
+ parts() {
461
+ this.#assertOpen();
462
+ const count = this.#x.litz_part_count(this.#handle);
463
+ const out = [];
464
+ for (let index = 0; index < count; index += 1) {
465
+ const id = this.#readText((ptr, cap) => this.#x.litz_part_id(this.#handle, index, ptr, cap));
466
+ // A board instance reports no runtime state of its own; it still belongs
467
+ // in the list, with `state: null`.
468
+ out.push(this.#state(id) ?? { id, code: -1, kind: "unknown", state: null, value: 0 });
469
+ }
470
+ return out;
471
+ }
472
+
473
+ /** One part by id, including board-expanded ids such as `esp/led_pwr`. */
474
+ part(id) {
475
+ this.#assertOpen();
476
+ if (typeof id !== "string" || id.length === 0) {
477
+ throw new LitzError("part() needs a part id");
478
+ }
479
+ return this.#state(id);
480
+ }
481
+
482
+ /** Press or release a pushbutton wired to a GPIO. */
483
+ press(id, pressed = true) {
484
+ this.#assertOpen();
485
+ const buf = this.#io.writeIn(ENCODER.encode(String(id)));
486
+ try {
487
+ this.#x.litz_press(this.#handle, buf.ptr, buf.len, pressed ? 1 : 0);
488
+ } finally {
489
+ this.#io.release(buf);
490
+ }
491
+ this.#throwStored();
492
+ }
493
+
494
+ /** Move a continuous control: 0 to 1000 permille of its travel. */
495
+ setControl(id, permille) {
496
+ this.#assertOpen();
497
+ const value = Math.round(Number(permille));
498
+ if (!Number.isFinite(value)) throw new LitzError("setControl needs a number");
499
+ const clamped = Math.min(1000, Math.max(0, value));
500
+ const buf = this.#io.writeIn(ENCODER.encode(String(id)));
501
+ try {
502
+ this.#x.litz_set_control(this.#handle, buf.ptr, buf.len, clamped);
503
+ } finally {
504
+ this.#io.release(buf);
505
+ }
506
+ this.#throwStored();
507
+ }
508
+
509
+ /** The panel size and pixels, or `null` when the circuit has no display. */
510
+ display() {
511
+ this.#assertOpen();
512
+ const info = this.#x.litz_display_info(this.#handle);
513
+ if (info === 0) return null;
514
+ const width = info >>> 16;
515
+ const height = info & 0xffff;
516
+ const session = this;
517
+ return {
518
+ width,
519
+ height,
520
+ get version() {
521
+ session.#assertOpen();
522
+ return session.#x.litz_display_version(session.#handle);
523
+ },
524
+ pixels() {
525
+ session.#assertOpen();
526
+ const needed = width * height * 4;
527
+ const cap = session.#io.writeOut(needed);
528
+ const written = session.#x.litz_display_rgba(session.#handle, cap.ptr, cap.len);
529
+ if (written !== needed) {
530
+ throw session.#io.error("the display frame could not be read");
531
+ }
532
+ return session.#io.copyOut(written);
533
+ },
534
+ };
535
+ }
536
+
537
+ /** Deliver a touch at panel pixels. False when the board has no panel. */
538
+ touch(x, y, down = true) {
539
+ this.#assertOpen();
540
+ return this.#x.litz_touch(this.#handle, x >>> 0, y >>> 0, down ? 1 : 0) === 1;
541
+ }
542
+
543
+ /** The scope document: every probe's samples and every decoder's frames. */
544
+ scope() {
545
+ this.#assertOpen();
546
+ const length = this.#x.litz_scope_len(this.#handle);
547
+ const text = this.#readText(
548
+ (ptr, cap) => this.#x.litz_scope_json(this.#handle, ptr, cap),
549
+ length,
550
+ );
551
+ try {
552
+ return JSON.parse(text);
553
+ } catch (error) {
554
+ throw new LitzError("the scope document was not valid JSON", { cause: error });
555
+ }
556
+ }
557
+
558
+ /** Close the session and release its memory in the module. */
559
+ close() {
560
+ if (this.#closed) return;
561
+ this.#closed = true;
562
+ this.#x.litz_drop(this.#handle);
563
+ }
564
+
565
+ /** `using session = ...` support where explicit resource management exists. */
566
+ [Symbol.dispose]() {
567
+ this.close();
568
+ }
569
+
570
+ #state(id) {
571
+ const buf = this.#io.writeIn(ENCODER.encode(id));
572
+ let code;
573
+ let value;
574
+ try {
575
+ code = this.#x.litz_part_state(this.#handle, buf.ptr, buf.len);
576
+ value = this.#x.litz_part_value(this.#handle, buf.ptr, buf.len);
577
+ } finally {
578
+ this.#io.release(buf);
579
+ }
580
+ if (code < 0) return null;
581
+ const entry = STATE_CODES[code] ?? { kind: "unknown", state: "unknown" };
582
+ return { id, code, kind: entry.kind, state: entry.state, value };
583
+ }
584
+
585
+ #takeSerial() {
586
+ this.#assertOpen();
587
+ const chunks = [];
588
+ for (;;) {
589
+ const cap = this.#io.writeOut(64 * 1024);
590
+ const written = this.#x.litz_serial_take(this.#handle, cap.ptr, cap.len);
591
+ if (written === 0) break;
592
+ chunks.push(this.#io.copyOut(written));
593
+ if (written < cap.len) break;
594
+ }
595
+ return decodeChunks(chunks);
596
+ }
597
+
598
+ #writeSerial(data) {
599
+ this.#assertOpen();
600
+ const bytes = typeof data === "string" ? ENCODER.encode(data) : bytesOf(data, "serial data");
601
+ if (bytes.length === 0) return;
602
+ const buf = this.#io.writeIn(bytes);
603
+ try {
604
+ this.#x.litz_serial_write(this.#handle, buf.ptr, buf.len);
605
+ } finally {
606
+ this.#io.release(buf);
607
+ }
608
+ this.#throwStored();
609
+ }
610
+
611
+ #addProbe(name, point) {
612
+ this.#assertOpen();
613
+ // Two strings in one call cannot share the reusable input buffer.
614
+ const nameBuf = hold(this.#io, ENCODER.encode(String(name)));
615
+ const pointBuf = hold(this.#io, ENCODER.encode(String(point)));
616
+ let ok;
617
+ try {
618
+ ok = this.#x.litz_probe_add(
619
+ this.#handle,
620
+ nameBuf.ptr,
621
+ nameBuf.len,
622
+ pointBuf.ptr,
623
+ pointBuf.len,
624
+ );
625
+ } finally {
626
+ this.#io.release(nameBuf);
627
+ this.#io.release(pointBuf);
628
+ }
629
+ if (ok !== 1) throw this.#io.error("the probe point could not be added");
630
+ }
631
+
632
+ #addDecode(spec) {
633
+ this.#assertOpen();
634
+ const buf = this.#io.writeIn(ENCODER.encode(String(spec)));
635
+ let ok;
636
+ try {
637
+ ok = this.#x.litz_decode_add(this.#handle, buf.ptr, buf.len);
638
+ } finally {
639
+ this.#io.release(buf);
640
+ }
641
+ if (ok !== 1) throw this.#io.error("the decoder could not be added");
642
+ }
643
+
644
+ #throwStored() {
645
+ const message = this.#io.stored();
646
+ if (message) throw new LitzError(message);
647
+ }
648
+
649
+ #readText(fill, initial = 256) {
650
+ let capacity = Math.max(64, initial + 1);
651
+ for (;;) {
652
+ const cap = this.#io.writeOut(capacity);
653
+ const written = fill(cap.ptr, cap.len);
654
+ if (written < capacity) return DECODER.decode(this.#io.copyOut(written));
655
+ capacity *= 2;
656
+ if (capacity > 64 * 1024 * 1024) {
657
+ throw new LitzError("a value from the module did not fit in 64 MiB");
658
+ }
659
+ }
660
+ }
661
+ }
package/litz_wasm.wasm ADDED
Binary file
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@litz-sim/litz",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Deterministic electronics and firmware simulator in WebAssembly",
5
+ "keywords": [
6
+ "simulator",
7
+ "emulator",
8
+ "esp32",
9
+ "firmware",
10
+ "electronics",
11
+ "wasm"
12
+ ],
13
+ "license": "MIT OR Apache-2.0",
14
+ "author": "redelectricity",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/Litz-Sim/litz.git",
18
+ "directory": "js"
19
+ },
20
+ "homepage": "https://github.com/Litz-Sim/litz#readme",
21
+ "bugs": "https://github.com/Litz-Sim/litz/issues",
22
+ "type": "module",
23
+ "main": "./index.js",
24
+ "types": "./index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./index.d.ts",
28
+ "default": "./index.js"
29
+ },
30
+ "./litz_wasm.wasm": "./litz_wasm.wasm",
31
+ "./package.json": "./package.json"
32
+ },
33
+ "files": [
34
+ "index.js",
35
+ "index.d.ts",
36
+ "litz_wasm.wasm",
37
+ "README.md"
38
+ ],
39
+ "sideEffects": false,
40
+ "engines": {
41
+ "node": ">=18"
42
+ },
43
+ "scripts": {
44
+ "build": "node scripts/build.mjs",
45
+ "test": "node --test test/*.test.js",
46
+ "prepublishOnly": "node scripts/build.mjs && node --test test/*.test.js"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public"
50
+ }
51
+ }