embedded-react 0.5.3 → 0.7.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.
@@ -0,0 +1,200 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ // uploader — writes ERHR-framed .erpkg containers to a device over a serial/USB port, and surfaces the
18
+ // device's log output coming back the other way (CDC is full-duplex, so one port carries both).
19
+ //
20
+ // `serialport` is an optional, lazily-loaded dependency: it has a native binding, so we don't force it
21
+ // on everyone who just wants the simulator or the AOT path. The first time you upload to a device, the
22
+ // CLI asks you to `npm i serialport` if it isn't present.
23
+
24
+ import {encodeFrame} from './protocol.mjs';
25
+
26
+ /** Loads the `serialport` package, with a friendly message if it isn't installed. */
27
+ async function loadSerialPort() {
28
+ try {
29
+ return await import('serialport');
30
+ } catch {
31
+ throw new Error(
32
+ "on-device upload needs the 'serialport' package.\n" +
33
+ ' Install it in your project: npm i serialport\n' +
34
+ ' (it has a native binding, so embedded-react keeps it optional.)',
35
+ );
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Opens a serial port and streams hot-reload uploads to it.
41
+ *
42
+ * @param {object} o
43
+ * @param {string} o.device Port path (e.g. /dev/tty.usbmodem1234 or COM5).
44
+ * @param {number} [o.baud] Baud rate. Ignored by true USB-CDC links, required by UART bridges.
45
+ * @param {(line: string) => void} [o.onLog] Called with each line the device prints back.
46
+ */
47
+ export class SerialUploader {
48
+ constructor({device, baud = 460800, onLog, paced = true} = {}) {
49
+ if (!device) throw new Error('SerialUploader: device path is required');
50
+ this.device = device;
51
+ this.baud = baud;
52
+ this.onLog = onLog || (() => {});
53
+ // paced=true (default): stream the frame in chunks, draining each, so the write is metered to roughly
54
+ // the device's drain rate. Over USB this keeps the host from flooding the RX buffer while the running
55
+ // app competes for the port; on a raw UART bridge (no flow control) it keeps the host under the line
56
+ // rate so bytes aren't dropped. paced=false: stream the whole frame in one write, relying on the
57
+ // link's own back-pressure — slightly less setup, but can stall mid-transfer when the device is busy.
58
+ this.paced = paced;
59
+ this._port = null;
60
+ this._rxLine = '';
61
+ }
62
+
63
+ /** Opens the port. Resolves once it is ready to accept writes. */
64
+ async open() {
65
+ const {SerialPort} = await loadSerialPort();
66
+ await new Promise((res, rej) => {
67
+ this._port = new SerialPort(
68
+ {path: this.device, baudRate: this.baud},
69
+ err => (err ? rej(err) : res()),
70
+ );
71
+ });
72
+ // Surface device logs line-by-line (the data arriving between/around our uploads).
73
+ this._port.on('data', chunk => this._onData(chunk));
74
+ this._port.on('error', err => this.onLog(`[serial error] ${err.message}`));
75
+ }
76
+
77
+ _onData(chunk) {
78
+ this._rxLine += chunk.toString('utf8');
79
+ let nl;
80
+ while ((nl = this._rxLine.indexOf('\n')) >= 0) {
81
+ const line = this._rxLine.slice(0, nl).replace(/\r$/, '');
82
+ this._rxLine = this._rxLine.slice(nl + 1);
83
+ if (line.length) this.onLog(line);
84
+ }
85
+ }
86
+
87
+ _write(buf) {
88
+ return new Promise((res, rej) =>
89
+ this._port.write(buf, err => (err ? rej(err) : res())),
90
+ );
91
+ }
92
+
93
+ _drain() {
94
+ return new Promise((res, rej) =>
95
+ this._port.drain(err => (err ? rej(err) : res())),
96
+ );
97
+ }
98
+
99
+ /**
100
+ * Frames an .erpkg and writes it to the device.
101
+ *
102
+ * Paced path (paced=true, the default): stream the frame in chunks, draining each, so the write is
103
+ * metered to roughly the device's drain rate — over USB that keeps the host from flooding the RX buffer
104
+ * while the running app competes for the port, and on a raw UART bridge (no flow control) it keeps the
105
+ * host under the line rate so bytes aren't dropped.
106
+ *
107
+ * Fast path (paced=false): stream the whole frame in one write, relying on the link's own back-pressure.
108
+ *
109
+ * @param {Buffer|Uint8Array} erpkg Container bytes (from packAppContainer).
110
+ * @returns {Promise<number>} The number of framed bytes written.
111
+ */
112
+ async send(erpkg) {
113
+ if (!this._port) throw new Error('SerialUploader: call open() first');
114
+ const frame = encodeFrame(erpkg);
115
+
116
+ if (!this.paced) {
117
+ await this._write(frame); // rely on the link's back-pressure (USB NAK) to throttle us
118
+ await this._drain();
119
+ return frame.length;
120
+ }
121
+
122
+ const CHUNK = 16 * 1024;
123
+ for (let off = 0; off < frame.length; off += CHUNK) {
124
+ await this._write(frame.subarray(off, off + CHUNK));
125
+ await this._drain(); // meter to ~the device's drain rate so its RX buffer isn't overrun
126
+ }
127
+ return frame.length;
128
+ }
129
+
130
+ /** Closes the port. */
131
+ async close() {
132
+ if (!this._port) return;
133
+ await new Promise(res => this._port.close(() => res()));
134
+ this._port = null;
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Lists serial ports, best-effort, to help the user pick a --device. Returns [] if serialport is absent.
140
+ *
141
+ * @returns {Promise<Array<{path: string, manufacturer?: string}>>}
142
+ */
143
+ export async function listSerialPorts() {
144
+ try {
145
+ const {SerialPort} = await loadSerialPort();
146
+ return await SerialPort.list();
147
+ } catch {
148
+ return [];
149
+ }
150
+ }
151
+
152
+ // The ESP32-S3/C3 built-in USB-Serial-JTAG enumerates with this fixed USB VID:PID, baked into the chip's
153
+ // ROM independently of the board vendor — so it's a stable signal for auto-detecting the hot-reload port.
154
+ // (The CH34x/CP210x/FTDI UART bridge used for *flashing* has a different id, e.g. 1a86:xxxx for WCH.)
155
+ export const ESP_USB_JTAG_VID = '303a';
156
+ export const ESP_USB_JTAG_PID = '1001';
157
+
158
+ const hex = v => (v == null ? '' : String(v).toLowerCase());
159
+
160
+ /** True if a `SerialPort.list()` entry is an ESP32-S3/C3 native USB-Serial-JTAG port. */
161
+ export function isEspJtagPort(p) {
162
+ return (
163
+ hex(p?.vendorId) === ESP_USB_JTAG_VID &&
164
+ hex(p?.productId) === ESP_USB_JTAG_PID
165
+ );
166
+ }
167
+
168
+ /**
169
+ * On macOS a USB serial device appears as both `/dev/tty.*` (dial-in, blocks until carrier-detect) and
170
+ * `/dev/cu.*` (call-out, the one to use for an outgoing link). `SerialPort.list()` reports the tty.* side;
171
+ * map it to cu.* on darwin so an auto-detected port opens without hanging. No-op elsewhere.
172
+ */
173
+ export function preferCalloutPath(path) {
174
+ if (process.platform === 'darwin' && path && path.startsWith('/dev/tty.')) {
175
+ return `/dev/cu.${path.slice('/dev/tty.'.length)}`;
176
+ }
177
+ return path;
178
+ }
179
+
180
+ /**
181
+ * Enumerate serial ports and pick out the ESP32 USB-Serial-JTAG candidates for auto-detecting `--device`.
182
+ * Distinguishes "serialport not installed" from "installed but nothing matched" so the CLI can advise.
183
+ *
184
+ * @returns {Promise<{matches: object[], all: object[], serialportMissing: boolean}>}
185
+ */
186
+ export async function detectDevicePorts() {
187
+ let SerialPort;
188
+ try {
189
+ ({SerialPort} = await import('serialport'));
190
+ } catch {
191
+ return {matches: [], all: [], serialportMissing: true};
192
+ }
193
+ let all = [];
194
+ try {
195
+ all = await SerialPort.list();
196
+ } catch {
197
+ all = [];
198
+ }
199
+ return {matches: all.filter(isEspJtagPort), all, serialportMissing: false};
200
+ }
@@ -0,0 +1,103 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ // watchTree — recursively watch a directory across platforms.
18
+ //
19
+ // fs.watch's `{recursive: true}` is only supported on macOS, Windows, and Node >=20 on Linux; on older
20
+ // Linux/Node it throws. A naive fallback that watches just the root misses edits under src/** — which makes
21
+ // the dev loop look broken. So where native recursive watching isn't available we fall back to a
22
+ // per-directory watcher that also picks up directories created after startup.
23
+
24
+ import {watch, readdirSync, statSync} from 'node:fs';
25
+ import {join} from 'node:path';
26
+
27
+ // Directories never worth watching (build output, deps, VCS/tool caches). Skipping them keeps the watcher
28
+ // count low on the per-directory fallback and avoids rebuild storms from generated files.
29
+ const IGNORE_DIR =
30
+ /^(node_modules|dist|build|out|coverage|\.git|\.hg|\.svn|\.next|\.cache)$/;
31
+
32
+ /**
33
+ * Recursively watch `root`, calling `onEvent(eventType, filename)` on any change beneath it. Uses the
34
+ * native recursive watcher where the platform supports it, else a per-directory fallback.
35
+ *
36
+ * @param {string} root
37
+ * @param {(eventType: string, filename: string|null) => void} onEvent
38
+ * @returns {{close: () => void}}
39
+ */
40
+ export function watchTree(root, onEvent) {
41
+ try {
42
+ const w = watch(root, {recursive: true}, onEvent);
43
+ return {close: () => w.close()};
44
+ } catch {
45
+ // Native recursive watching unavailable (older Linux/Node, or an unsupported FS) — use the fallback.
46
+ return watchTreePolyfill(root, onEvent);
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Per-directory recursive watcher: one non-recursive `fs.watch` per directory under `root`, plus hooks for
52
+ * directories created later. This is what makes `src/**` edits fire on platforms without native recursion.
53
+ * Exported for direct testing (so the fallback can be exercised even where native recursion works).
54
+ *
55
+ * @param {string} root
56
+ * @param {(eventType: string, filename: string|null) => void} onEvent
57
+ * @returns {{close: () => void}}
58
+ */
59
+ export function watchTreePolyfill(root, onEvent) {
60
+ const watchers = new Map(); // absolute dir path -> FSWatcher
61
+
62
+ const watchDir = dir => {
63
+ if (watchers.has(dir)) return;
64
+ let w;
65
+ try {
66
+ w = watch(dir, {}, (event, name) => {
67
+ onEvent(event, name);
68
+ // `mkdir src/components` needs its own watcher — hook any freshly-created subdirectory.
69
+ if (!name || IGNORE_DIR.test(name)) return;
70
+ const child = join(dir, name);
71
+ try {
72
+ if (statSync(child).isDirectory()) scan(child);
73
+ } catch {
74
+ /* a file (not a dir), or created-then-removed — ignore */
75
+ }
76
+ });
77
+ } catch {
78
+ return; // dir vanished between scan and watch
79
+ }
80
+ watchers.set(dir, w);
81
+ };
82
+
83
+ const scan = dir => {
84
+ watchDir(dir);
85
+ let entries;
86
+ try {
87
+ entries = readdirSync(dir, {withFileTypes: true});
88
+ } catch {
89
+ return;
90
+ }
91
+ for (const ent of entries)
92
+ if (ent.isDirectory() && !IGNORE_DIR.test(ent.name))
93
+ scan(join(dir, ent.name));
94
+ };
95
+
96
+ scan(root);
97
+ return {
98
+ close() {
99
+ for (const w of watchers.values()) w.close();
100
+ watchers.clear();
101
+ },
102
+ };
103
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "embedded-react",
3
- "version": "0.5.3",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "description": "React Native-style component package + reconciler that drives the embedded-react C engine through the QuickJS NativeUI bridge (Flow A).",
6
6
  "license": "Apache-2.0",
@@ -45,6 +45,7 @@
45
45
  "src/",
46
46
  "aot/",
47
47
  "assets/",
48
+ "hotreload/",
48
49
  "build.mjs",
49
50
  "pack-container.mjs",
50
51
  "persist-transform.mjs",
@@ -75,6 +76,7 @@
75
76
  "test:watch": "vitest",
76
77
  "test:runtime": "node test/runtime/run.mjs",
77
78
  "test:bytecode": "node test/runtime/run.mjs --bytecode",
79
+ "test:split": "node test/runtime/split-roundtrip.mjs",
78
80
  "typecheck": "tsc -p tsconfig.types.json",
79
81
  "format": "cd ../../.. && prettier --write \"**/*.{js,jsx,mjs,cjs}\"",
80
82
  "format:check": "cd ../../.. && prettier --check \"**/*.{js,jsx,mjs,cjs}\""
@@ -96,6 +98,9 @@
96
98
  "typescript": "^5.5.0",
97
99
  "vitest": "^3.2.4"
98
100
  },
101
+ "optionalDependencies": {
102
+ "serialport": "^12.0.0"
103
+ },
99
104
  "overrides": {
100
105
  "esbuild": "^0.28.1"
101
106
  }
Binary file
@@ -25,6 +25,13 @@ import {createElement} from 'react';
25
25
  import {createRoot} from '../renderer.js';
26
26
 
27
27
  let registered = null;
28
+ // The mounted root is created ONCE and reused on every subsequent registration. On a full reload, the
29
+ // whole context is torn down and recreated, so this is recreated too (a fresh boot). But on an
30
+ // incremental "soft" reload, only the app chunk is re-evaluated into the SAME context — this lib (and
31
+ // therefore `root`) stays resident, so re-registering renders the new app into the existing root and
32
+ // React reconciles old→new in place. Creating a new root each time would instead leak a fiber root per
33
+ // reload and orphan the previous tree's effects.
34
+ let root = null;
28
35
 
29
36
  export const AppRegistry = {
30
37
  /**
@@ -38,12 +45,13 @@ export const AppRegistry = {
38
45
  },
39
46
 
40
47
  /**
41
- * Mounts the registered root component into a fresh screen-sized container.
48
+ * Mounts the registered root component into the screen-sized container, creating it on first use and
49
+ * reusing it thereafter (see `root` above).
42
50
  */
43
51
  runApplication(appKey) {
44
52
  if (!registered) return;
45
53
  if (appKey && appKey !== registered.appKey) return;
46
- const root = createRoot({width: screen.width, height: screen.height});
54
+ if (!root) root = createRoot({width: screen.width, height: screen.height});
47
55
  root.render(createElement(registered.Component));
48
56
  },
49
57
  };