embedded-react 0.19.0 → 0.20.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.
Files changed (116) hide show
  1. package/README.md +7 -3
  2. package/aot/compile.mjs +178 -58
  3. package/aot/compiler/animations.mjs +290 -281
  4. package/aot/compiler/boot.mjs +70 -33
  5. package/aot/compiler/branch-merge.mjs +4 -3
  6. package/aot/compiler/check.mjs +9 -9
  7. package/aot/compiler/collect.mjs +324 -205
  8. package/aot/compiler/control-flow.mjs +209 -197
  9. package/aot/compiler/diagnostics.mjs +22 -25
  10. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  11. package/aot/compiler/elements/dial.mjs +91 -77
  12. package/aot/compiler/elements/flat-list.mjs +24 -22
  13. package/aot/compiler/elements/image.mjs +51 -50
  14. package/aot/compiler/elements/modal.mjs +31 -30
  15. package/aot/compiler/elements/props.mjs +23 -23
  16. package/aot/compiler/elements/switch.mjs +42 -34
  17. package/aot/compiler/elements/text-input.mjs +34 -32
  18. package/aot/compiler/expressions.mjs +372 -333
  19. package/aot/compiler/handlers.mjs +473 -387
  20. package/aot/compiler/ir/functions.mjs +11 -1
  21. package/aot/compiler/ir/nodes.mjs +4 -4
  22. package/aot/compiler/ir/reads.mjs +19 -19
  23. package/aot/compiler/ir/types.mjs +14 -14
  24. package/aot/compiler/ir/vectors.mjs +5 -1
  25. package/aot/compiler/keyboard.mjs +17 -7
  26. package/aot/compiler/lower.mjs +77 -80
  27. package/aot/compiler/nodes.mjs +169 -152
  28. package/aot/compiler/options.mjs +35 -30
  29. package/aot/compiler/out.mjs +18 -22
  30. package/aot/compiler/package/animations.mjs +669 -0
  31. package/aot/compiler/package/arena.mjs +252 -0
  32. package/aot/compiler/package/assemble.mjs +177 -0
  33. package/aot/compiler/package/bytecode.mjs +286 -0
  34. package/aot/compiler/package/checks.mjs +1022 -0
  35. package/aot/compiler/package/codegen.mjs +1329 -0
  36. package/aot/compiler/package/enums.mjs +138 -0
  37. package/aot/compiler/package/format.mjs +760 -0
  38. package/aot/compiler/package/layouts.mjs +136 -0
  39. package/aot/compiler/package/lower.mjs +1606 -0
  40. package/aot/compiler/package/props.mjs +118 -0
  41. package/aot/compiler/package/tables.mjs +103 -0
  42. package/aot/compiler/package/vectors.mjs +502 -0
  43. package/aot/compiler/package/writer.mjs +664 -0
  44. package/aot/compiler/pan-responder.mjs +69 -61
  45. package/aot/compiler/parse.mjs +21 -21
  46. package/aot/compiler/static-eval.mjs +25 -23
  47. package/aot/compiler/style-text.mjs +161 -172
  48. package/aot/compiler/svg.mjs +477 -251
  49. package/aot/screenshot-smoke.mjs +54 -40
  50. package/aot/style-map.mjs +102 -90
  51. package/assets/bake-font.mjs +123 -77
  52. package/assets/bake-image.mjs +39 -22
  53. package/assets/bake-svg.mjs +361 -262
  54. package/assets/build-builtin-font.mjs +11 -7
  55. package/assets/emit-c.mjs +77 -58
  56. package/assets/emit-container.mjs +123 -37
  57. package/assets/emit-pack.mjs +77 -67
  58. package/assets/font-config.mjs +9 -6
  59. package/assets/font-sizes.mjs +163 -123
  60. package/assets/glyph-coverage.mjs +74 -54
  61. package/assets/index.mjs +31 -9
  62. package/assets/rasterize.mjs +126 -99
  63. package/assets/svg-loader.mjs +8 -8
  64. package/build.mjs +14 -12
  65. package/cli.mjs +359 -172
  66. package/compile-bin.mjs +3 -3
  67. package/flash.mjs +537 -0
  68. package/hotreload/dev-device.mjs +90 -33
  69. package/hotreload/pack-app.mjs +55 -43
  70. package/hotreload/pack-split.mjs +46 -37
  71. package/hotreload/package-transfer.mjs +175 -0
  72. package/hotreload/protocol.mjs +50 -37
  73. package/hotreload/uploader.mjs +38 -27
  74. package/hotreload/watch-tree.mjs +19 -19
  75. package/pack-container.mjs +28 -20
  76. package/package.json +7 -8
  77. package/persist-transform.mjs +34 -28
  78. package/qjsc-wasm.mjs +25 -14
  79. package/sim/embedded-react.cjs +1 -1
  80. package/sim/embedded-react.js +1 -1
  81. package/sim/embedded-react.wasm +0 -0
  82. package/sim/index.html +94 -85
  83. package/sim-server.mjs +101 -82
  84. package/src/embedded-react/Animated.js +24 -24
  85. package/src/embedded-react/Easing.js +1 -1
  86. package/src/embedded-react/FlatList.js +3 -3
  87. package/src/embedded-react/LayoutAnimation.js +8 -5
  88. package/src/embedded-react/PanResponder.js +75 -71
  89. package/src/embedded-react/Pressable.js +2 -8
  90. package/src/embedded-react/SectionList.js +6 -6
  91. package/src/embedded-react/StyleSheet.js +4 -3
  92. package/src/embedded-react/TouchableOpacity.js +13 -8
  93. package/src/embedded-react/index.d.ts +5 -5
  94. package/src/embedded-react/layout-anim-config.js +10 -4
  95. package/src/embedded-react/list-child.js +5 -5
  96. package/src/embedded-react/named-colors.js +1 -1
  97. package/src/embedded-react/split-style.js +11 -11
  98. package/src/embedded-react/svg-ops.js +760 -593
  99. package/src/embedded-react/useHostValue.js +3 -3
  100. package/src/embedded-react/usePersistentState.js +6 -6
  101. package/src/embedded-react/warn-props.js +1 -1
  102. package/src/host-config.js +60 -53
  103. package/src/props.js +49 -41
  104. package/src/renderer.js +7 -4
  105. package/aot/compiler/assemble.mjs +0 -944
  106. package/aot/compiler/c/animations.mjs +0 -436
  107. package/aot/compiler/c/boot.mjs +0 -127
  108. package/aot/compiler/c/expressions.mjs +0 -270
  109. package/aot/compiler/c/functions.mjs +0 -268
  110. package/aot/compiler/c/keyboard.mjs +0 -96
  111. package/aot/compiler/c/nodes.mjs +0 -303
  112. package/aot/compiler/c/pan-responder.mjs +0 -136
  113. package/aot/compiler/c/statements.mjs +0 -319
  114. package/aot/compiler/c/text.mjs +0 -83
  115. package/aot/compiler/c/vectors.mjs +0 -381
  116. package/aot/compiler/c-syntax.mjs +0 -127
@@ -0,0 +1,175 @@
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
+ // package-transfer — sends a Flow B package to a board, as ERHR frames, one at a time.
18
+ //
19
+ // The device writes each chunk straight into its staging slot, and flash stalls the chip while it does. So this sends
20
+ // one frame and waits for the reply, which keeps a UART with no flow control from losing bytes. The device's side is
21
+ // runtime/erb_package_reload.c, whose header lists the replies.
22
+
23
+ import {
24
+ MSG_PACKAGE_BEGIN,
25
+ MSG_PACKAGE_CHUNK,
26
+ encodeFrame,
27
+ } from './protocol.mjs';
28
+
29
+ const CHUNK_OFFSET_BYTES = 4;
30
+ const BEGIN_RESEND_MS = 1000; // a board that is resetting, or holding a boot error on screen, misses a begin
31
+ const BEGIN_TIMEOUT_MS = 15000;
32
+ const CHUNK_TIMEOUT_MS = 2000;
33
+ const CHUNK_RESENDS = 5;
34
+ const LOAD_TIMEOUT_MS = 15000; // checking a large package from flash takes a slow board a few seconds
35
+
36
+ const READY_LINE = /erb reload: ready (\d+)/;
37
+ const GOT_LINE = /erb reload: got (\d+)/;
38
+
39
+ /** What a line from the device says, or null when it is only a log. */
40
+ export function parseReply(line) {
41
+ const readyMatch = READY_LINE.exec(line);
42
+ if (readyMatch) return {kind: 'ready', value: Number(readyMatch[1])};
43
+ const gotMatch = GOT_LINE.exec(line);
44
+ if (gotMatch) return {kind: 'got', value: Number(gotMatch[1])};
45
+ if (/dropped frame/i.test(line)) return {kind: 'dropped'};
46
+ if (/hot reload:\s*ok\b/i.test(line)) return {kind: 'ok'};
47
+ if (/hot reload:/i.test(line)) return {kind: 'rejected'};
48
+ return null;
49
+ }
50
+
51
+ /** The frame that starts a package. */
52
+ export function beginFrame(packageBytes) {
53
+ const payload = Buffer.alloc(CHUNK_OFFSET_BYTES);
54
+ payload.writeUInt32LE(packageBytes, 0);
55
+ return encodeFrame(payload, {type: MSG_PACKAGE_BEGIN});
56
+ }
57
+
58
+ /** The frame for the bytes of @p packageData at @p offset. */
59
+ export function chunkFrame(packageData, offset, chunkBytes) {
60
+ const chunk = packageData.subarray(offset, offset + chunkBytes);
61
+ const payload = Buffer.alloc(CHUNK_OFFSET_BYTES + chunk.length);
62
+ payload.writeUInt32LE(offset, 0);
63
+ chunk.copy(payload, CHUNK_OFFSET_BYTES);
64
+ return encodeFrame(payload, {type: MSG_PACKAGE_CHUNK});
65
+ }
66
+
67
+ export class PackageTransfer {
68
+ /**
69
+ * @param {object} options
70
+ * @param {(frame: Buffer) => Promise<unknown>} options.write Writes a frame to the device.
71
+ */
72
+ constructor({
73
+ write,
74
+ beginResendMs = BEGIN_RESEND_MS,
75
+ chunkTimeoutMs = CHUNK_TIMEOUT_MS,
76
+ chunkResends = CHUNK_RESENDS,
77
+ loadTimeoutMs = LOAD_TIMEOUT_MS,
78
+ }) {
79
+ this.write = write;
80
+ this.beginResendMs = beginResendMs;
81
+ this.chunkTimeoutMs = chunkTimeoutMs;
82
+ this.chunkResends = chunkResends;
83
+ this.loadTimeoutMs = loadTimeoutMs;
84
+ this._replies = [];
85
+ this._wake = null;
86
+ }
87
+
88
+ /** Takes a line from the device. Returns true when it is part of the transfer and not worth showing. */
89
+ onLine(line) {
90
+ const reply = parseReply(line);
91
+ if (!reply) return false;
92
+ this._replies.push(reply);
93
+ if (this._wake) this._wake();
94
+ return reply.kind === 'ready' || reply.kind === 'got';
95
+ }
96
+
97
+ /** The next reply, or null after @p timeoutMs. */
98
+ async _nextReply(timeoutMs) {
99
+ if (!this._replies.length) {
100
+ await new Promise(resolve => {
101
+ const timer = setTimeout(resolve, timeoutMs);
102
+ this._wake = () => {
103
+ clearTimeout(timer);
104
+ resolve();
105
+ };
106
+ });
107
+ this._wake = null;
108
+ }
109
+ return this._replies.shift() ?? null;
110
+ }
111
+
112
+ /** Starts the package on the device. Returns its chunk size, or the outcome when it never got that far. */
113
+ async _begin(packageData, timeoutMs) {
114
+ const deadline = Date.now() + timeoutMs;
115
+ const frame = beginFrame(packageData.length);
116
+ while (Date.now() < deadline) {
117
+ await this.write(frame);
118
+ const waitUntil = Math.min(Date.now() + this.beginResendMs, deadline);
119
+ for (;;) {
120
+ const reply = await this._nextReply(waitUntil - Date.now());
121
+ if (!reply || reply.kind === 'dropped') break; // send it again
122
+ if (reply.kind === 'ready') return {chunkBytes: reply.value};
123
+ if (reply.kind === 'rejected') return {outcome: 'rejected'};
124
+ }
125
+ }
126
+ return {outcome: 'timeout'};
127
+ }
128
+
129
+ /**
130
+ * Sends one package and waits for the device to load it.
131
+ *
132
+ * @param {Buffer} packageData
133
+ * @param {object} [options]
134
+ * @param {number} [options.beginTimeoutMs] How long a device may take to answer at all.
135
+ * @returns {Promise<'ok'|'rejected'|'dropped'|'timeout'>}
136
+ */
137
+ async send(packageData, {beginTimeoutMs = BEGIN_TIMEOUT_MS} = {}) {
138
+ this._replies = [];
139
+ const begun = await this._begin(packageData, beginTimeoutMs);
140
+ if (begun.outcome) return begun.outcome;
141
+ const {chunkBytes} = begun;
142
+
143
+ let offset = 0;
144
+ let resends = 0;
145
+ while (offset < packageData.length) {
146
+ await this.write(chunkFrame(packageData, offset, chunkBytes));
147
+ const reply = await this._awaitChunkReply();
148
+ if (reply === 'ok' || reply === 'rejected') return reply;
149
+ if (reply === null || reply === 'dropped') {
150
+ if (++resends > this.chunkResends) return reply ?? 'timeout';
151
+ continue;
152
+ }
153
+ // Where the device says it has got to, even if that is behind: a repeated begin starts it over.
154
+ if (reply > offset) resends = 0;
155
+ offset = reply;
156
+ }
157
+
158
+ for (;;) {
159
+ const reply = await this._nextReply(this.loadTimeoutMs);
160
+ if (!reply) return 'timeout';
161
+ if (reply.kind === 'ok' || reply.kind === 'rejected') return reply.kind;
162
+ }
163
+ }
164
+
165
+ /** What the device said about a chunk: its offset, 'ok', 'rejected', 'dropped', or null for nothing. */
166
+ async _awaitChunkReply() {
167
+ const waitUntil = Date.now() + this.chunkTimeoutMs;
168
+ for (;;) {
169
+ const reply = await this._nextReply(waitUntil - Date.now());
170
+ if (!reply) return null;
171
+ if (reply.kind === 'got') return reply.value;
172
+ if (reply.kind !== 'ready') return reply.kind;
173
+ }
174
+ }
175
+ }
@@ -28,7 +28,7 @@
28
28
  //
29
29
  // magic "ERHR" (4 bytes)
30
30
  // proto_version u8 = 1
31
- // msg_type u8 (1 = LOAD_CONTAINER)
31
+ // message_type u8 (1 = LOAD_CONTAINER)
32
32
  // flags u16 = 0 (reserved)
33
33
  // payload_len u32 — bytes of .erpkg that follow the header
34
34
  // payload_crc u32 — CRC-32/IEEE over the payload (same polynomial as ERCF / the C loader)
@@ -43,8 +43,18 @@ export const ERHR_MAGIC = 'ERHR';
43
43
  export const ERHR_PROTO_VERSION = 1;
44
44
  export const ERHR_HEADER_SIZE = 16;
45
45
 
46
+ const MAGIC_BYTES = 4;
47
+ const VERSION_OFFSET = 4;
48
+ const TYPE_OFFSET = 5;
49
+ const FLAGS_OFFSET = 6;
50
+ const PAYLOAD_LENGTH_OFFSET = 8;
51
+ const PAYLOAD_CRC_OFFSET = 12;
52
+ const DEFAULT_MAX_PAYLOAD_BYTES = 32 * 1024 * 1024;
53
+
46
54
  /** Frame message types (room to grow: ping/ack/reset later without a version bump). */
47
55
  export const MSG_LOAD_CONTAINER = 1;
56
+ export const MSG_PACKAGE_BEGIN = 2; // Flow B: see package-transfer.mjs
57
+ export const MSG_PACKAGE_CHUNK = 3;
48
58
 
49
59
  /**
50
60
  * Encodes an .erpkg into an ERHR transport frame ready to write to the device's byte stream.
@@ -60,11 +70,11 @@ export function encodeFrame(erpkg, {type = MSG_LOAD_CONTAINER} = {}) {
60
70
  const payload = Buffer.from(erpkg);
61
71
  const header = Buffer.alloc(ERHR_HEADER_SIZE);
62
72
  header.write(ERHR_MAGIC, 0, 'ascii');
63
- header.writeUInt8(ERHR_PROTO_VERSION, 4);
64
- header.writeUInt8(type & 0xff, 5);
65
- header.writeUInt16LE(0, 6); // flags (reserved)
66
- header.writeUInt32LE(payload.length >>> 0, 8);
67
- header.writeUInt32LE(crc32(payload), 12);
73
+ header.writeUInt8(ERHR_PROTO_VERSION, VERSION_OFFSET);
74
+ header.writeUInt8(type & 0xff, TYPE_OFFSET);
75
+ header.writeUInt16LE(0, FLAGS_OFFSET); // reserved
76
+ header.writeUInt32LE(payload.length >>> 0, PAYLOAD_LENGTH_OFFSET);
77
+ header.writeUInt32LE(crc32(payload), PAYLOAD_CRC_OFFSET);
68
78
  return Buffer.concat([header, payload]);
69
79
  }
70
80
 
@@ -81,7 +91,7 @@ export class FrameDecoder {
81
91
  * @param {(payload: Buffer, meta: {type: number}) => void} [handlers.onFrame] A complete, CRC-valid frame.
82
92
  * @param {(reason: string) => void} [handlers.onError] A framed payload failed validation.
83
93
  */
84
- constructor({onFrame, onError, maxPayload = 32 * 1024 * 1024} = {}) {
94
+ constructor({onFrame, onError, maxPayload = DEFAULT_MAX_PAYLOAD_BYTES} = {}) {
85
95
  this.onFrame = onFrame || (() => {});
86
96
  this.onError = onError || (() => {});
87
97
  this.maxPayload = maxPayload; // guard against a coincidental "ERHR" in noise claiming a huge length
@@ -90,76 +100,79 @@ export class FrameDecoder {
90
100
 
91
101
  _reset() {
92
102
  this._state = 'scan'; // scan magic → header → payload
93
- this._window = Buffer.alloc(4); // rolling 4-byte window for magic resync
94
- this._winLen = 0;
103
+ this._window = Buffer.alloc(MAGIC_BYTES); // rolling 4-byte window for magic resync
104
+ this._windowLength = 0;
95
105
  this._header = Buffer.alloc(ERHR_HEADER_SIZE);
96
- this._headerGot = 4; // magic already in _header once matched
97
- this._payloadLen = 0;
106
+ this._headerReceived = MAGIC_BYTES; // magic already in _header once matched
107
+ this._payloadLength = 0;
98
108
  this._payloadCrc = 0;
99
109
  this._type = 0;
100
110
  this._payload = null;
101
- this._payloadGot = 0;
111
+ this._payloadReceived = 0;
102
112
  }
103
113
 
104
114
  /** Feed a chunk of received bytes. May complete zero, one, or several frames. */
105
115
  push(chunk) {
106
116
  const data = Buffer.from(chunk);
107
- for (let i = 0; i < data.length; i++) this._byte(data[i]);
117
+ for (let index = 0; index < data.length; index++) this._byte(data[index]);
108
118
  }
109
119
 
110
- _byte(b) {
120
+ _byte(byte) {
111
121
  if (this._state === 'scan') {
112
122
  // Slide the byte into a 4-byte window; a full match transitions to header collection. This
113
123
  // naturally handles partial matches and overlaps without backtracking.
114
- if (this._winLen < 4) {
115
- this._window[this._winLen++] = b;
124
+ if (this._windowLength < MAGIC_BYTES) {
125
+ this._window[this._windowLength++] = byte;
116
126
  } else {
117
127
  this._window.copyWithin(0, 1);
118
- this._window[3] = b;
128
+ this._window[MAGIC_BYTES - 1] = byte;
119
129
  }
120
- if (this._winLen === 4 && this._window.toString('ascii') === ERHR_MAGIC) {
121
- this._window.copy(this._header, 0, 0, 4);
122
- this._headerGot = 4;
123
- this._winLen = 0;
130
+ if (
131
+ this._windowLength === MAGIC_BYTES &&
132
+ this._window.toString('ascii') === ERHR_MAGIC
133
+ ) {
134
+ this._window.copy(this._header, 0, 0, MAGIC_BYTES);
135
+ this._headerReceived = MAGIC_BYTES;
136
+ this._windowLength = 0;
124
137
  this._state = 'header';
125
138
  }
126
139
  return;
127
140
  }
128
141
  if (this._state === 'header') {
129
- this._header[this._headerGot++] = b;
130
- if (this._headerGot < ERHR_HEADER_SIZE) return;
131
- const version = this._header.readUInt8(4);
132
- this._type = this._header.readUInt8(5);
133
- this._payloadLen = this._header.readUInt32LE(8);
134
- this._payloadCrc = this._header.readUInt32LE(12);
142
+ this._header[this._headerReceived++] = byte;
143
+ if (this._headerReceived < ERHR_HEADER_SIZE) return;
144
+ const version = this._header.readUInt8(VERSION_OFFSET);
145
+ this._type = this._header.readUInt8(TYPE_OFFSET);
146
+ this._payloadLength = this._header.readUInt32LE(PAYLOAD_LENGTH_OFFSET);
147
+ this._payloadCrc = this._header.readUInt32LE(PAYLOAD_CRC_OFFSET);
135
148
  if (version !== ERHR_PROTO_VERSION) {
136
149
  this.onError(`unsupported protocol version ${version}`);
137
150
  this._reset();
138
151
  return;
139
152
  }
140
- if (this._payloadLen === 0) {
153
+ if (this._payloadLength === 0) {
141
154
  this.onError('empty payload');
142
155
  this._reset();
143
156
  return;
144
157
  }
145
- if (this._payloadLen > this.maxPayload) {
158
+ if (this._payloadLength > this.maxPayload) {
146
159
  // Almost certainly a false magic in noise — drop it and keep scanning, don't allocate.
147
- this.onError(`payload too large (${this._payloadLen} bytes)`);
160
+ this.onError(`payload too large (${this._payloadLength} bytes)`);
148
161
  this._reset();
149
162
  return;
150
163
  }
151
- this._payload = Buffer.alloc(this._payloadLen);
152
- this._payloadGot = 0;
164
+ this._payload = Buffer.alloc(this._payloadLength);
165
+ this._payloadReceived = 0;
153
166
  this._state = 'payload';
154
167
  return;
155
168
  }
156
169
  // payload
157
- this._payload[this._payloadGot++] = b;
158
- if (this._payloadGot < this._payloadLen) return;
159
- const got = crc32(this._payload);
160
- if (got !== this._payloadCrc) {
170
+ this._payload[this._payloadReceived++] = byte;
171
+ if (this._payloadReceived < this._payloadLength) return;
172
+ const actualCrc = crc32(this._payload);
173
+ if (actualCrc !== this._payloadCrc) {
161
174
  this.onError(
162
- `payload CRC mismatch (got ${got.toString(16)}, want ${this._payloadCrc.toString(16)})`,
175
+ `payload CRC mismatch (got ${actualCrc.toString(16)}, want ${this._payloadCrc.toString(16)})`,
163
176
  );
164
177
  this._reset();
165
178
  return;
@@ -23,6 +23,9 @@
23
23
 
24
24
  import {encodeFrame} from './protocol.mjs';
25
25
 
26
+ const DEFAULT_BAUD = 460800;
27
+ const PACED_CHUNK_BYTES = 16 * 1024;
28
+
26
29
  /** Loads the `serialport` package, with a friendly message if it isn't installed. */
27
30
  async function loadSerialPort() {
28
31
  try {
@@ -39,13 +42,13 @@ async function loadSerialPort() {
39
42
  /**
40
43
  * Opens a serial port and streams hot-reload uploads to it.
41
44
  *
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.
45
+ * @param {object} options
46
+ * @param {string} options.device Port path (e.g. /dev/tty.usbmodem1234 or COM5).
47
+ * @param {number} [options.baud] Baud rate. Ignored by true USB-CDC links, required by UART bridges.
48
+ * @param {(line: string) => void} [options.onLog] Called with each line the device prints back.
46
49
  */
47
50
  export class SerialUploader {
48
- constructor({device, baud = 460800, onLog, paced = true} = {}) {
51
+ constructor({device, baud = DEFAULT_BAUD, onLog, paced = true} = {}) {
49
52
  if (!device) throw new Error('SerialUploader: device path is required');
50
53
  this.device = device;
51
54
  this.baud = baud;
@@ -57,42 +60,44 @@ export class SerialUploader {
57
60
  // link's own back-pressure — slightly less setup, but can stall mid-transfer when the device is busy.
58
61
  this.paced = paced;
59
62
  this._port = null;
60
- this._rxLine = '';
63
+ this._pendingLine = '';
61
64
  }
62
65
 
63
66
  /** Opens the port. Resolves once it is ready to accept writes. */
64
67
  async open() {
65
68
  const {SerialPort} = await loadSerialPort();
66
- await new Promise((res, rej) => {
69
+ await new Promise((resolve, reject) => {
67
70
  this._port = new SerialPort(
68
71
  {path: this.device, baudRate: this.baud},
69
- err => (err ? rej(err) : res()),
72
+ error => (error ? reject(error) : resolve()),
70
73
  );
71
74
  });
72
75
  // Surface device logs line-by-line (the data arriving between/around our uploads).
73
76
  this._port.on('data', chunk => this._onData(chunk));
74
- this._port.on('error', err => this.onLog(`[serial error] ${err.message}`));
77
+ this._port.on('error', error =>
78
+ this.onLog(`[serial error] ${error.message}`),
79
+ );
75
80
  }
76
81
 
77
82
  _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
+ this._pendingLine += chunk.toString('utf8');
84
+ let newline;
85
+ while ((newline = this._pendingLine.indexOf('\n')) >= 0) {
86
+ const line = this._pendingLine.slice(0, newline).replace(/\r$/, '');
87
+ this._pendingLine = this._pendingLine.slice(newline + 1);
83
88
  if (line.length) this.onLog(line);
84
89
  }
85
90
  }
86
91
 
87
- _write(buf) {
88
- return new Promise((res, rej) =>
89
- this._port.write(buf, err => (err ? rej(err) : res())),
92
+ _write(data) {
93
+ return new Promise((resolve, reject) =>
94
+ this._port.write(data, error => (error ? reject(error) : resolve())),
90
95
  );
91
96
  }
92
97
 
93
98
  _drain() {
94
- return new Promise((res, rej) =>
95
- this._port.drain(err => (err ? rej(err) : res())),
99
+ return new Promise((resolve, reject) =>
100
+ this._port.drain(error => (error ? reject(error) : resolve())),
96
101
  );
97
102
  }
98
103
 
@@ -119,18 +124,24 @@ export class SerialUploader {
119
124
  return frame.length;
120
125
  }
121
126
 
122
- const CHUNK = 16 * 1024;
123
- for (let off = 0; off < frame.length; off += CHUNK) {
124
- await this._write(frame.subarray(off, off + CHUNK));
127
+ for (let offset = 0; offset < frame.length; offset += PACED_CHUNK_BYTES) {
128
+ await this._write(frame.subarray(offset, offset + PACED_CHUNK_BYTES));
125
129
  await this._drain(); // meter to ~the device's drain rate so its RX buffer isn't overrun
126
130
  }
127
131
  return frame.length;
128
132
  }
129
133
 
134
+ /** Writes a frame that is already encoded, for a transfer that waits for a reply to each. */
135
+ async writeFrame(frame) {
136
+ if (!this._port) throw new Error('SerialUploader: call open() first');
137
+ await this._write(frame);
138
+ await this._drain();
139
+ }
140
+
130
141
  /** Closes the port. */
131
142
  async close() {
132
143
  if (!this._port) return;
133
- await new Promise(res => this._port.close(() => res()));
144
+ await new Promise(resolve => this._port.close(() => resolve()));
134
145
  this._port = null;
135
146
  }
136
147
  }
@@ -155,13 +166,13 @@ export async function listSerialPorts() {
155
166
  export const ESP_USB_JTAG_VID = '303a';
156
167
  export const ESP_USB_JTAG_PID = '1001';
157
168
 
158
- const hex = v => (v == null ? '' : String(v).toLowerCase());
169
+ const hex = value => (value == null ? '' : String(value).toLowerCase());
159
170
 
160
171
  /** True if a `SerialPort.list()` entry is an ESP32-S3/C3 native USB-Serial-JTAG port. */
161
- export function isEspJtagPort(p) {
172
+ export function isEspJtagPort(port) {
162
173
  return (
163
- hex(p?.vendorId) === ESP_USB_JTAG_VID &&
164
- hex(p?.productId) === ESP_USB_JTAG_PID
174
+ hex(port?.vendorId) === ESP_USB_JTAG_VID &&
175
+ hex(port?.productId) === ESP_USB_JTAG_PID
165
176
  );
166
177
  }
167
178
 
@@ -26,7 +26,7 @@ import {join} from 'node:path';
26
26
 
27
27
  // Directories never worth watching (build output, deps, VCS/tool caches). Skipping them keeps the watcher
28
28
  // count low on the per-directory fallback and avoids rebuild storms from generated files.
29
- const IGNORE_DIR =
29
+ const IGNORED_DIRECTORY =
30
30
  /^(node_modules|dist|build|out|coverage|\.git|\.hg|\.svn|\.next|\.cache)$/;
31
31
 
32
32
  /**
@@ -39,8 +39,8 @@ const IGNORE_DIR =
39
39
  */
40
40
  export function watchTree(root, onEvent) {
41
41
  try {
42
- const w = watch(root, {recursive: true}, onEvent);
43
- return {close: () => w.close()};
42
+ const watcher = watch(root, {recursive: true}, onEvent);
43
+ return {close: () => watcher.close()};
44
44
  } catch {
45
45
  // Native recursive watching unavailable (older Linux/Node, or an unsupported FS) — use the fallback.
46
46
  return watchTreePolyfill(root, onEvent);
@@ -57,17 +57,17 @@ export function watchTree(root, onEvent) {
57
57
  * @returns {{close: () => void}}
58
58
  */
59
59
  export function watchTreePolyfill(root, onEvent) {
60
- const watchers = new Map(); // absolute dir path -> FSWatcher
60
+ const watchers = new Map(); // absolute directory path -> FSWatcher
61
61
 
62
- const watchDir = dir => {
63
- if (watchers.has(dir)) return;
64
- let w;
62
+ const watchDirectory = directory => {
63
+ if (watchers.has(directory)) return;
64
+ let watcher;
65
65
  try {
66
- w = watch(dir, {}, (event, name) => {
66
+ watcher = watch(directory, {}, (event, name) => {
67
67
  onEvent(event, name);
68
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);
69
+ if (!name || IGNORED_DIRECTORY.test(name)) return;
70
+ const child = join(directory, name);
71
71
  try {
72
72
  if (statSync(child).isDirectory()) scan(child);
73
73
  } catch {
@@ -75,28 +75,28 @@ export function watchTreePolyfill(root, onEvent) {
75
75
  }
76
76
  });
77
77
  } catch {
78
- return; // dir vanished between scan and watch
78
+ return; // directory vanished between scan and watch
79
79
  }
80
- watchers.set(dir, w);
80
+ watchers.set(directory, watcher);
81
81
  };
82
82
 
83
- const scan = dir => {
84
- watchDir(dir);
83
+ const scan = directory => {
84
+ watchDirectory(directory);
85
85
  let entries;
86
86
  try {
87
- entries = readdirSync(dir, {withFileTypes: true});
87
+ entries = readdirSync(directory, {withFileTypes: true});
88
88
  } catch {
89
89
  return;
90
90
  }
91
- for (const ent of entries)
92
- if (ent.isDirectory() && !IGNORE_DIR.test(ent.name))
93
- scan(join(dir, ent.name));
91
+ for (const entry of entries)
92
+ if (entry.isDirectory() && !IGNORED_DIRECTORY.test(entry.name))
93
+ scan(join(directory, entry.name));
94
94
  };
95
95
 
96
96
  scan(root);
97
97
  return {
98
98
  close() {
99
- for (const w of watchers.values()) w.close();
99
+ for (const watcher of watchers.values()) watcher.close();
100
100
  watchers.clear();
101
101
  },
102
102
  };
@@ -51,7 +51,8 @@ import {findCompileBin, compileBinHelp} from './compile-bin.mjs';
51
51
 
52
52
  // QuickJS release the bytecode targets — MUST match the FetchContent pin in
53
53
  // bridges/quickjs/CMakeLists.txt and ER_QUICKJS_TAG in er_runtime.c. The loader rejects a mismatch.
54
- const QJS_TAG = 'v0.15.0';
54
+ const QUICKJS_TAG = 'v0.15.0';
55
+ const BYTES_PER_KILOBYTE = 1024;
55
56
 
56
57
  const here = dirname(fileURLToPath(import.meta.url)); // packages/embedded-react
57
58
  const repoRoot = resolve(here, '../..');
@@ -66,8 +67,8 @@ const entry = resolve(demoDir, 'index.jsx');
66
67
  if (!existsSync(entry)) {
67
68
  const available = existsSync(demosDir)
68
69
  ? readdirSync(demosDir, {withFileTypes: true})
69
- .filter(d => d.isDirectory())
70
- .map(d => d.name)
70
+ .filter(entry => entry.isDirectory())
71
+ .map(entry => entry.name)
71
72
  : [];
72
73
  console.error(`Demo "${demo}" not found (expected ${entry}).`);
73
74
  console.error(`Available demos: ${available.join(', ') || '(none)'}`);
@@ -86,8 +87,8 @@ const images = new Map(); // name -> path
86
87
  const fonts = new Map(); // family -> path
87
88
  const assetPlugin = {
88
89
  name: 'embedded-react-assets',
89
- setup(b) {
90
- b.onLoad({filter: /\.(png|jpe?g|webp|gif|bmp)$/i}, args => {
90
+ setup(pluginBuild) {
91
+ pluginBuild.onLoad({filter: /\.(png|jpe?g|webp|gif|bmp)$/i}, args => {
91
92
  const name = basename(args.path).replace(/\.[^.]+$/, '');
92
93
  images.set(name, args.path);
93
94
  return {
@@ -95,7 +96,7 @@ const assetPlugin = {
95
96
  loader: 'js',
96
97
  };
97
98
  });
98
- b.onLoad({filter: /\.(ttf|otf)$/i}, args => {
99
+ pluginBuild.onLoad({filter: /\.(ttf|otf)$/i}, args => {
99
100
  const family = basename(args.path).replace(/\.[^.]+$/, '');
100
101
  fonts.set(family, args.path);
101
102
  return {
@@ -103,7 +104,9 @@ const assetPlugin = {
103
104
  loader: 'js',
104
105
  };
105
106
  });
106
- registerSvgVectorLoader(b, (name, p) => images.set(name, p)); // raster-fallback SVGs join the image pack
107
+ registerSvgVectorLoader(pluginBuild, (name, svgPath) =>
108
+ images.set(name, svgPath),
109
+ ); // raster-fallback SVGs join the image pack
107
110
  },
108
111
  };
109
112
 
@@ -136,17 +139,19 @@ await build({
136
139
  console.log(`Bundled demo "${demo}" -> dist/app.bundle.js`);
137
140
 
138
141
  // --- Precompile to QuickJS bytecode -------------------------------------------------------------
139
- const qbcPath = resolve(distDir, 'app.bundle.qbc');
140
- const cc = spawnSync(compileBin, [bundlePath, qbcPath], {stdio: 'inherit'});
141
- if (cc.status !== 0) {
142
+ const bytecodePath = resolve(distDir, 'app.bundle.qbc');
143
+ const compileResult = spawnSync(compileBin, [bundlePath, bytecodePath], {
144
+ stdio: 'inherit',
145
+ });
146
+ if (compileResult.status !== 0) {
142
147
  console.error('Bytecode compile failed.');
143
148
  process.exit(1);
144
149
  }
145
- const bytecode = readFileSync(qbcPath);
150
+ const bytecode = readFileSync(bytecodePath);
146
151
 
147
152
  // --- Bake imported assets into an ERPK pack (same sizing rules as build.mjs / sim.mjs) ----------
148
- const bundleSrc = readFileSync(bundlePath, 'utf8');
149
- const usedSizes = analyzeFontSizes(bundleSrc);
153
+ const bundleSource = readFileSync(bundlePath, 'utf8');
154
+ const usedSizes = analyzeFontSizes(bundleSource);
150
155
 
151
156
  let config = {};
152
157
  const configPath = resolve(demoDir, 'assets.config.js');
@@ -162,25 +167,28 @@ const imageJobs = [...images.entries()].map(([name, path]) => ({
162
167
  format: imageConfig[name]?.format,
163
168
  }));
164
169
 
165
- const bakedImages = imageJobs.map(i => bakeImage(i));
166
- const bakedFonts = fontJobs.map(f => bakeFont(f));
167
- warnMissingGlyphs({source: bundleSrc, fonts: bakedFonts});
170
+ const bakedImages = imageJobs.map(imageJob => bakeImage(imageJob));
171
+ const bakedFonts = fontJobs.map(fontJob => bakeFont(fontJob));
172
+ warnMissingGlyphs({source: bundleSource, fonts: bakedFonts});
168
173
  warnFontSizes({used: usedSizes, fonts: bakedFonts});
169
174
  const assetPack =
170
175
  bakedImages.length || bakedFonts.length
171
176
  ? emitAssetPack({images: bakedImages, fonts: bakedFonts})
172
177
  : null;
173
- const fontSizeCount = bakedFonts.reduce((n, f) => n + f.sizes.length, 0);
178
+ const fontSizeCount = bakedFonts.reduce(
179
+ (count, font) => count + font.sizes.length,
180
+ 0,
181
+ );
174
182
 
175
183
  // --- Wrap into the ERCF container ---------------------------------------------------------------
176
- const container = emitContainer({bytecode, assetPack, qjsTag: QJS_TAG});
184
+ const container = emitContainer({bytecode, assetPack, qjsTag: QUICKJS_TAG});
177
185
  const outPath = resolve(distDir, 'app.erpkg');
178
186
  writeFileSync(outPath, container);
179
187
 
180
- const kb = n => `${(n / 1024).toFixed(1)} KB`;
188
+ const kb = byteCount => `${(byteCount / BYTES_PER_KILOBYTE).toFixed(1)} KB`;
181
189
  console.log(
182
190
  `Packed config -> dist/app.erpkg (${kb(container.length)})\n` +
183
- ` qjs ${QJS_TAG} · bytecode ${kb(bytecode.length)}` +
191
+ ` qjs ${QUICKJS_TAG} · bytecode ${kb(bytecode.length)}` +
184
192
  (assetPack
185
193
  ? ` · assets ${kb(assetPack.length)} (${bakedImages.length} image(s), ${fontSizeCount} font size(s))`
186
194
  : ' · no assets'),