embedded-react 0.19.0 → 0.21.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 (148) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +8 -3
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +180 -90
  5. package/aot/compiler/animations.mjs +568 -317
  6. package/aot/compiler/boot.mjs +97 -35
  7. package/aot/compiler/branch-merge.mjs +4 -3
  8. package/aot/compiler/check.mjs +70 -18
  9. package/aot/compiler/collect.mjs +787 -288
  10. package/aot/compiler/contexts.mjs +391 -0
  11. package/aot/compiler/control-flow.mjs +439 -268
  12. package/aot/compiler/custom-hooks.mjs +686 -0
  13. package/aot/compiler/diagnostics.mjs +22 -25
  14. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  15. package/aot/compiler/elements/button.mjs +182 -0
  16. package/aot/compiler/elements/dial.mjs +91 -77
  17. package/aot/compiler/elements/flat-list.mjs +24 -22
  18. package/aot/compiler/elements/image-background.mjs +76 -0
  19. package/aot/compiler/elements/image.mjs +52 -50
  20. package/aot/compiler/elements/modal.mjs +31 -30
  21. package/aot/compiler/elements/props.mjs +61 -26
  22. package/aot/compiler/elements/rewrite.mjs +118 -0
  23. package/aot/compiler/elements/section-list.mjs +370 -0
  24. package/aot/compiler/elements/switch.mjs +42 -34
  25. package/aot/compiler/elements/text-input.mjs +34 -32
  26. package/aot/compiler/expressions.mjs +1685 -392
  27. package/aot/compiler/handlers.mjs +2029 -547
  28. package/aot/compiler/helper-values.mjs +312 -0
  29. package/aot/compiler/ir/functions.mjs +11 -1
  30. package/aot/compiler/ir/nodes.mjs +43 -4
  31. package/aot/compiler/ir/reads.mjs +223 -22
  32. package/aot/compiler/ir/text.mjs +5 -1
  33. package/aot/compiler/ir/types.mjs +26 -14
  34. package/aot/compiler/ir/vectors.mjs +5 -1
  35. package/aot/compiler/kept-states.mjs +177 -0
  36. package/aot/compiler/keyboard.mjs +17 -7
  37. package/aot/compiler/list-items.mjs +226 -0
  38. package/aot/compiler/list-order.mjs +586 -0
  39. package/aot/compiler/list-split.mjs +259 -0
  40. package/aot/compiler/loops.mjs +582 -0
  41. package/aot/compiler/lower.mjs +246 -111
  42. package/aot/compiler/native-files.mjs +439 -0
  43. package/aot/compiler/native-header.mjs +335 -0
  44. package/aot/compiler/native-modules.mjs +1173 -0
  45. package/aot/compiler/nodes.mjs +195 -172
  46. package/aot/compiler/options.mjs +37 -31
  47. package/aot/compiler/out.mjs +32 -23
  48. package/aot/compiler/package/animations.mjs +779 -0
  49. package/aot/compiler/package/arena.mjs +252 -0
  50. package/aot/compiler/package/assemble.mjs +175 -0
  51. package/aot/compiler/package/bytecode.mjs +315 -0
  52. package/aot/compiler/package/checks.mjs +1026 -0
  53. package/aot/compiler/package/codegen.mjs +2168 -0
  54. package/aot/compiler/package/enums.mjs +148 -0
  55. package/aot/compiler/package/format.mjs +771 -0
  56. package/aot/compiler/package/layouts.mjs +136 -0
  57. package/aot/compiler/package/lower.mjs +2103 -0
  58. package/aot/compiler/package/props.mjs +118 -0
  59. package/aot/compiler/package/string-caps.mjs +515 -0
  60. package/aot/compiler/package/tables.mjs +127 -0
  61. package/aot/compiler/package/vectors.mjs +502 -0
  62. package/aot/compiler/package/writer.mjs +686 -0
  63. package/aot/compiler/pan-responder.mjs +69 -61
  64. package/aot/compiler/parse.mjs +23 -21
  65. package/aot/compiler/record-shapes.mjs +246 -0
  66. package/aot/compiler/records.mjs +654 -0
  67. package/aot/compiler/reducers.mjs +272 -0
  68. package/aot/compiler/static-eval.mjs +340 -30
  69. package/aot/compiler/style-text.mjs +178 -174
  70. package/aot/compiler/svg.mjs +480 -251
  71. package/aot/compiler/switch-cases.mjs +198 -0
  72. package/aot/compiler/tagged-records.mjs +450 -0
  73. package/aot/compiler/typing.mjs +307 -0
  74. package/aot/compiler/updaters.mjs +320 -0
  75. package/aot/compiler/window-dimensions.mjs +94 -0
  76. package/aot/compiler/worked-values.mjs +319 -0
  77. package/aot/demo-file.mjs +30 -0
  78. package/aot/screenshot-smoke.mjs +54 -40
  79. package/aot/style-map.mjs +152 -92
  80. package/assets/bake-font.mjs +123 -77
  81. package/assets/bake-image.mjs +39 -22
  82. package/assets/bake-svg.mjs +361 -262
  83. package/assets/build-builtin-font.mjs +11 -7
  84. package/assets/emit-c.mjs +77 -58
  85. package/assets/emit-container.mjs +123 -37
  86. package/assets/emit-pack.mjs +77 -67
  87. package/assets/font-config.mjs +9 -6
  88. package/assets/font-sizes.mjs +163 -123
  89. package/assets/glyph-coverage.mjs +74 -54
  90. package/assets/index.mjs +31 -9
  91. package/assets/rasterize.mjs +126 -99
  92. package/assets/svg-loader.mjs +8 -8
  93. package/build.mjs +23 -13
  94. package/cli.mjs +402 -172
  95. package/compile-bin.mjs +3 -3
  96. package/flash.mjs +537 -0
  97. package/hotreload/dev-device.mjs +90 -33
  98. package/hotreload/pack-app.mjs +55 -43
  99. package/hotreload/pack-split.mjs +62 -64
  100. package/hotreload/package-transfer.mjs +175 -0
  101. package/hotreload/protocol.mjs +50 -37
  102. package/hotreload/uploader.mjs +38 -27
  103. package/hotreload/watch-tree.mjs +19 -19
  104. package/pack-container.mjs +37 -21
  105. package/package.json +7 -8
  106. package/persist-transform.mjs +34 -28
  107. package/qjsc-wasm.mjs +25 -14
  108. package/sim/embedded-react.cjs +1 -1
  109. package/sim/embedded-react.js +1 -1
  110. package/sim/embedded-react.wasm +0 -0
  111. package/sim/index.html +94 -85
  112. package/sim-server.mjs +113 -94
  113. package/src/embedded-react/Animated.js +24 -24
  114. package/src/embedded-react/Dimensions.js +37 -0
  115. package/src/embedded-react/Easing.js +1 -1
  116. package/src/embedded-react/FlatList.js +3 -3
  117. package/src/embedded-react/LayoutAnimation.js +8 -5
  118. package/src/embedded-react/PanResponder.js +75 -71
  119. package/src/embedded-react/Pressable.js +2 -8
  120. package/src/embedded-react/SectionList.js +7 -9
  121. package/src/embedded-react/StyleSheet.js +4 -3
  122. package/src/embedded-react/TouchableOpacity.js +13 -8
  123. package/src/embedded-react/index.d.ts +88 -8
  124. package/src/embedded-react/index.js +2 -0
  125. package/src/embedded-react/layout-anim-config.js +10 -4
  126. package/src/embedded-react/list-child.js +5 -5
  127. package/src/embedded-react/named-colors.js +1 -1
  128. package/src/embedded-react/nativeModule.js +462 -0
  129. package/src/embedded-react/split-style.js +11 -11
  130. package/src/embedded-react/svg-ops.js +760 -593
  131. package/src/embedded-react/useHostValue.js +3 -3
  132. package/src/embedded-react/usePersistentState.js +6 -6
  133. package/src/embedded-react/warn-props.js +1 -1
  134. package/src/host-config.js +60 -53
  135. package/src/props.js +49 -41
  136. package/src/renderer.js +7 -4
  137. package/aot/compiler/assemble.mjs +0 -944
  138. package/aot/compiler/c/animations.mjs +0 -436
  139. package/aot/compiler/c/boot.mjs +0 -127
  140. package/aot/compiler/c/expressions.mjs +0 -270
  141. package/aot/compiler/c/functions.mjs +0 -268
  142. package/aot/compiler/c/keyboard.mjs +0 -96
  143. package/aot/compiler/c/nodes.mjs +0 -303
  144. package/aot/compiler/c/pan-responder.mjs +0 -136
  145. package/aot/compiler/c/statements.mjs +0 -319
  146. package/aot/compiler/c/text.mjs +0 -83
  147. package/aot/compiler/c/vectors.mjs +0 -381
  148. package/aot/compiler/c-syntax.mjs +0 -127
package/compile-bin.mjs CHANGED
@@ -26,7 +26,7 @@ import {fileURLToPath} from 'node:url';
26
26
 
27
27
  const here = dirname(fileURLToPath(import.meta.url)); // packages/embedded-react
28
28
  const repoRoot = resolve(here, '../..');
29
- const exe = process.platform === 'win32' ? '.exe' : '';
29
+ const exeSuffix = process.platform === 'win32' ? '.exe' : '';
30
30
 
31
31
  const SEARCH_DIRS = [
32
32
  'bridges/quickjs/build',
@@ -47,8 +47,8 @@ export function findCompileBin() {
47
47
  return existsSync(override) ? override : null;
48
48
  }
49
49
  return (
50
- SEARCH_DIRS.map(d =>
51
- resolve(repoRoot, d, `er-bridge-quickjs-compile${exe}`),
50
+ SEARCH_DIRS.map(searchDir =>
51
+ resolve(repoRoot, searchDir, `er-bridge-quickjs-compile${exeSuffix}`),
52
52
  ).find(existsSync) || null
53
53
  );
54
54
  }
package/flash.mjs ADDED
@@ -0,0 +1,537 @@
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
+ // flash — writes a Flow B package into one of a board's two package slots.
18
+ //
19
+ // A slot holds a header in an erase sector of its own, then the package. The firmware
20
+ // (runtime/erb_package_slots.c) runs the valid slot with the newest sequence and falls back to the other, so a
21
+ // new package always goes in the slot that isn't the newest, with the next sequence. `flash` reads the board's
22
+ // headers and writes the package, then the header, so its own write cut short never leaves the newest sequence on
23
+ // a partial package. `pack` writes the image to a file instead, for a factory line or a drag-and-drop UF2, which
24
+ // can't promise that order, so `flash` also checks the newest slot's package before it writes over the other.
25
+
26
+ import {spawnSync} from 'node:child_process';
27
+ import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';
28
+ import {tmpdir} from 'node:os';
29
+ import {join} from 'node:path';
30
+ import {crc32} from './assets/emit-container.mjs';
31
+
32
+ export const SLOT_HEADER_BYTES = 4096; // bytes before the package: one erase sector
33
+ const SLOT_HEADER_PAGE_BYTES = 256; // the part of it that is written
34
+ const SEQUENCE_MAX = 0xffffffff;
35
+ const ERASED_BYTE = 0xff;
36
+ const SLOT_MAGIC = 0x53425245; // "ERBS", little-endian
37
+ const SLOT_MAGIC_AT = 0;
38
+ const SLOT_SEQUENCE_AT = 4;
39
+ const SLOT_PACKAGE_LENGTH_AT = 8;
40
+ const SLOT_HEADER_CHECKED_BYTES = 12;
41
+ const SLOT_HEADER_CRC_BYTES = 4;
42
+ const SLOT_NAMES = ['a', 'b'];
43
+
44
+ const CONTAINER_MAGIC = 'ERCF';
45
+ const CONTAINER_MAGIC_BYTES = 4;
46
+ const CONTAINER_CRC_AT = 8;
47
+ const CONTAINER_CRC_END = 12;
48
+ const CONTAINER_TAG_AT = 12;
49
+ const CONTAINER_TAG_LENGTH_BYTES = 2;
50
+ const PACKAGE_TAG = 'erb';
51
+
52
+ const ESP_PARTITION_TABLE_AT = 0x8000;
53
+ const ESP_PARTITION_TABLE_BYTES = 0xc00;
54
+ const ESP_PARTITION_ENTRY_BYTES = 32;
55
+ const ESP_PARTITION_MAGIC = 0x50aa;
56
+ const ESP_PARTITION_OFFSET_AT = 4;
57
+ const ESP_PARTITION_SIZE_AT = 8;
58
+ const ESP_PARTITION_LABEL_AT = 12;
59
+ const ESP_PARTITION_LABEL_BYTES = 16;
60
+ const ESP_SLOT_LABELS = ['erb_a', 'erb_b'];
61
+
62
+ const PICO_REBOOT_TIMEOUT_MS = 10000;
63
+ const PICO_READY_TRIES = 40;
64
+ const PICO_READY_WAIT_MS = 250;
65
+
66
+ const UF2_BLOCK_BYTES = 512;
67
+ const UF2_PAYLOAD_BYTES = 256;
68
+ const UF2_MAGIC_START_0 = 0x0a324655;
69
+ const UF2_MAGIC_START_1 = 0x9e5d5157;
70
+ const UF2_MAGIC_END = 0x0ab16f30;
71
+ const UF2_FLAG_FAMILY = 0x2000;
72
+ const UF2_FAMILY_RP2040 = 0xe48bff56;
73
+ const UF2_MAGIC_START_1_AT = 4;
74
+ const UF2_FLAGS_AT = 8;
75
+ const UF2_ADDRESS_AT = 12;
76
+ const UF2_PAYLOAD_SIZE_AT = 16;
77
+ const UF2_BLOCK_NUMBER_AT = 20;
78
+ const UF2_BLOCK_COUNT_AT = 24;
79
+ const UF2_FAMILY_AT = 28;
80
+ const UF2_PAYLOAD_AT = 32;
81
+ const UF2_MAGIC_END_AT = 508;
82
+
83
+ /**
84
+ * Where each board example keeps its slots. An ESP32 board's `flash` reads them from the partition table on the
85
+ * board instead, so this is what `pack` prints for it. Keep it in step with the example's partitions.csv or
86
+ * CMakeLists.txt: flash.unit.test.mjs checks that it is.
87
+ */
88
+ export const BOARDS = {
89
+ 'esp32-2432s028r': {
90
+ tool: 'esptool',
91
+ chip: 'esp32',
92
+ slots: [
93
+ {address: 0x180000, bytes: 0x140000},
94
+ {address: 0x2c0000, bytes: 0x140000},
95
+ ],
96
+ },
97
+ 'esp32-s3': {
98
+ tool: 'esptool',
99
+ chip: 'esp32s3',
100
+ slots: [
101
+ {address: 0x510000, bytes: 0x200000},
102
+ {address: 0x710000, bytes: 0x200000},
103
+ ],
104
+ },
105
+ 'rp2040-touch-lcd-1.69': {
106
+ tool: 'picotool',
107
+ slots: [
108
+ {address: 0x10100000, bytes: 0x80000},
109
+ {address: 0x10180000, bytes: 0x80000},
110
+ ],
111
+ },
112
+ };
113
+
114
+ const hex = value => `0x${value.toString(16)}`;
115
+
116
+ /** The board for a --board value; throws naming the ones there are. */
117
+ export function boardByName(name) {
118
+ const board = BOARDS[name];
119
+ if (!board) {
120
+ throw new Error(
121
+ `${name ? `Unknown board "${name}"` : 'No board given'}: pass --board with one of ${Object.keys(BOARDS).join(', ')}.`,
122
+ );
123
+ }
124
+ return board;
125
+ }
126
+
127
+ /** Checks the bytes are a whole Flow B package, so a stale or Flow A file never reaches a slot. */
128
+ export function checkPackage(bytes) {
129
+ if (
130
+ bytes.length < CONTAINER_TAG_AT + CONTAINER_TAG_LENGTH_BYTES ||
131
+ bytes.toString('latin1', 0, CONTAINER_MAGIC_BYTES) !== CONTAINER_MAGIC
132
+ ) {
133
+ throw new Error('Not a package: no ERCF container in this file.');
134
+ }
135
+ if (
136
+ bytes.readUInt32LE(CONTAINER_CRC_AT) !==
137
+ crc32(bytes.subarray(CONTAINER_CRC_END))
138
+ ) {
139
+ throw new Error('This package is corrupt: its CRC does not match.');
140
+ }
141
+ const tagBytes = bytes.readUInt16LE(CONTAINER_TAG_AT);
142
+ const tag = bytes.toString(
143
+ 'latin1',
144
+ CONTAINER_TAG_AT + CONTAINER_TAG_LENGTH_BYTES,
145
+ CONTAINER_TAG_AT + CONTAINER_TAG_LENGTH_BYTES + tagBytes,
146
+ );
147
+ if (tag !== PACKAGE_TAG) {
148
+ throw new Error(
149
+ `This is a Flow A container (built for ${tag}), not a Flow B package. Build one with: embedded-react build --aot`,
150
+ );
151
+ }
152
+ }
153
+
154
+ /** Whether the bytes are a whole Flow B package. */
155
+ function isWholePackage(bytes) {
156
+ try {
157
+ checkPackage(bytes);
158
+ return true;
159
+ } catch {
160
+ return false;
161
+ }
162
+ }
163
+
164
+ /** A slot's header page. */
165
+ export function slotHeader(packageLength, sequence) {
166
+ const header = Buffer.alloc(SLOT_HEADER_PAGE_BYTES, ERASED_BYTE);
167
+ header.writeUInt32LE(SLOT_MAGIC, SLOT_MAGIC_AT);
168
+ header.writeUInt32LE(sequence, SLOT_SEQUENCE_AT);
169
+ header.writeUInt32LE(packageLength, SLOT_PACKAGE_LENGTH_AT);
170
+ header.writeUInt32LE(
171
+ crc32(header.subarray(0, SLOT_HEADER_CHECKED_BYTES)),
172
+ SLOT_HEADER_CHECKED_BYTES,
173
+ );
174
+ return header;
175
+ }
176
+
177
+ /** A slot's whole image: the header in its sector, then the package. */
178
+ export function slotImage(packageBytes, sequence) {
179
+ const headerSector = Buffer.alloc(SLOT_HEADER_BYTES, ERASED_BYTE);
180
+ slotHeader(packageBytes.length, sequence).copy(headerSector);
181
+ return Buffer.concat([headerSector, packageBytes]);
182
+ }
183
+
184
+ /** What a slot's first bytes say: its sequence and package length, or null when it has no valid header. */
185
+ export function readSlotHeader(bytes, slotBytes) {
186
+ if (
187
+ bytes.length < SLOT_HEADER_CHECKED_BYTES + SLOT_HEADER_CRC_BYTES ||
188
+ bytes.readUInt32LE(SLOT_MAGIC_AT) !== SLOT_MAGIC ||
189
+ bytes.readUInt32LE(SLOT_HEADER_CHECKED_BYTES) !==
190
+ crc32(bytes.subarray(0, SLOT_HEADER_CHECKED_BYTES))
191
+ ) {
192
+ return null;
193
+ }
194
+ const packageBytes = bytes.readUInt32LE(SLOT_PACKAGE_LENGTH_AT);
195
+ if (packageBytes === 0 || packageBytes > slotBytes - SLOT_HEADER_BYTES) {
196
+ return null;
197
+ }
198
+ return {sequence: bytes.readUInt32LE(SLOT_SEQUENCE_AT), packageBytes};
199
+ }
200
+
201
+ /** A slot's sequence from its first bytes, or null when it has no valid header. */
202
+ export function readSlotSequence(bytes, slotBytes) {
203
+ return readSlotHeader(bytes, slotBytes)?.sequence ?? null;
204
+ }
205
+
206
+ /**
207
+ * Picks the slot for a new package from the two slots' sequences (null for none): the one that isn't the
208
+ * newest, with the next sequence. The firmware makes the same choice (erb_package_slots_boot).
209
+ */
210
+ export function pickSlot([first, second]) {
211
+ // A signed difference, so the order survives the sequence wrapping.
212
+ const secondIsNewer =
213
+ second !== null && (first === null || (second - first) << 0 > 0);
214
+ const newest = secondIsNewer ? 1 : 0;
215
+ const newestSequence = secondIsNewer ? second : first;
216
+ if (newestSequence === null) return {slot: 0, sequence: 1, lastGood: null};
217
+ return {
218
+ slot: 1 - newest,
219
+ sequence: (newestSequence + 1) >>> 0,
220
+ lastGood: newest,
221
+ };
222
+ }
223
+
224
+ /**
225
+ * Runs of bytes as UF2 blocks, in the order given, for a drag-and-drop onto an RP2040 in BOOTSEL mode.
226
+ *
227
+ * @param {{address: number, bytes: Buffer}[]} runs What to write where.
228
+ */
229
+ export function uf2(runs) {
230
+ const pages = runs.flatMap(({address, bytes}) =>
231
+ Array.from(
232
+ {length: Math.ceil(bytes.length / UF2_PAYLOAD_BYTES)},
233
+ (_, page) => ({
234
+ address: address + page * UF2_PAYLOAD_BYTES,
235
+ bytes: bytes.subarray(
236
+ page * UF2_PAYLOAD_BYTES,
237
+ (page + 1) * UF2_PAYLOAD_BYTES,
238
+ ),
239
+ }),
240
+ ),
241
+ );
242
+ const blockCount = pages.length;
243
+ const blocks = Buffer.alloc(blockCount * UF2_BLOCK_BYTES);
244
+ for (let block = 0; block < blockCount; block++) {
245
+ const at = block * UF2_BLOCK_BYTES;
246
+ blocks.writeUInt32LE(UF2_MAGIC_START_0, at);
247
+ blocks.writeUInt32LE(UF2_MAGIC_START_1, at + UF2_MAGIC_START_1_AT);
248
+ blocks.writeUInt32LE(UF2_FLAG_FAMILY, at + UF2_FLAGS_AT);
249
+ blocks.writeUInt32LE(pages[block].address, at + UF2_ADDRESS_AT);
250
+ blocks.writeUInt32LE(UF2_PAYLOAD_BYTES, at + UF2_PAYLOAD_SIZE_AT);
251
+ blocks.writeUInt32LE(block, at + UF2_BLOCK_NUMBER_AT);
252
+ blocks.writeUInt32LE(blockCount, at + UF2_BLOCK_COUNT_AT);
253
+ blocks.writeUInt32LE(UF2_FAMILY_RP2040, at + UF2_FAMILY_AT);
254
+ // A short last page is padded as erased flash, since the bootrom programs whole pages.
255
+ blocks.fill(
256
+ ERASED_BYTE,
257
+ at + UF2_PAYLOAD_AT,
258
+ at + UF2_PAYLOAD_AT + UF2_PAYLOAD_BYTES,
259
+ );
260
+ pages[block].bytes.copy(blocks, at + UF2_PAYLOAD_AT);
261
+ blocks.writeUInt32LE(UF2_MAGIC_END, at + UF2_MAGIC_END_AT);
262
+ }
263
+ return blocks;
264
+ }
265
+
266
+ /** The package slots in an ESP32 partition table's bytes, or null when the firmware on the board has none. */
267
+ export function slotsFromPartitionTable(table) {
268
+ const slots = [null, null];
269
+ for (
270
+ let at = 0;
271
+ at + ESP_PARTITION_ENTRY_BYTES <= table.length;
272
+ at += ESP_PARTITION_ENTRY_BYTES
273
+ ) {
274
+ if (table.readUInt16LE(at) !== ESP_PARTITION_MAGIC) break;
275
+ const labelEnd = at + ESP_PARTITION_LABEL_AT + ESP_PARTITION_LABEL_BYTES;
276
+ const label = table
277
+ .toString('latin1', at + ESP_PARTITION_LABEL_AT, labelEnd)
278
+ .replace(/\0.*$/, '');
279
+ const index = ESP_SLOT_LABELS.indexOf(label);
280
+ if (index >= 0) {
281
+ slots[index] = {
282
+ address: table.readUInt32LE(at + ESP_PARTITION_OFFSET_AT),
283
+ bytes: table.readUInt32LE(at + ESP_PARTITION_SIZE_AT),
284
+ };
285
+ }
286
+ }
287
+ return slots.every(Boolean) ? slots : null;
288
+ }
289
+
290
+ /** Runs the first of a tool's names that exists; throws with its output when it fails. */
291
+ function runTool(names, args, {run, install, inherit = false, timeoutMs}) {
292
+ for (const name of names) {
293
+ const result = run(name, args, inherit, timeoutMs);
294
+ if (result.error?.code === 'ENOENT') continue;
295
+ if (result.error) throw result.error;
296
+ if (result.status !== 0) {
297
+ throw new Error(
298
+ `${name} ${args.join(' ')} failed:\n${result.stderr ?? ''}${result.stdout ?? ''}`.trimEnd(),
299
+ );
300
+ }
301
+ return;
302
+ }
303
+ throw new Error(`${names[0]} wasn't found. ${install}`);
304
+ }
305
+
306
+ const sleepMs = ms =>
307
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
308
+
309
+ const defaultRun = (command, args, inherit, timeoutMs) =>
310
+ spawnSync(command, args, {
311
+ encoding: 'utf8',
312
+ stdio: inherit ? 'inherit' : 'pipe',
313
+ timeout: timeoutMs,
314
+ });
315
+
316
+ const espAccess = ({chip, port, run}) => {
317
+ const names = process.env.ESPTOOL
318
+ ? [process.env.ESPTOOL]
319
+ : ['esptool', 'esptool.py'];
320
+ const common = ['--chip', chip, ...(port ? ['--port', port] : [])];
321
+ const options = {
322
+ run,
323
+ install: 'Export ESP-IDF first (. $IDF_PATH/export.sh), or set ESPTOOL.',
324
+ };
325
+ // The underscored commands: esptool 4 takes only these, and esptool 5 still does.
326
+ const read = (address, bytes, file) =>
327
+ runTool(
328
+ names,
329
+ [...common, 'read_flash', hex(address), hex(bytes), file],
330
+ options,
331
+ );
332
+ return {
333
+ read,
334
+ slots: dir => {
335
+ const file = join(dir, 'partitions.bin');
336
+ read(ESP_PARTITION_TABLE_AT, ESP_PARTITION_TABLE_BYTES, file);
337
+ const slots = slotsFromPartitionTable(readFileSync(file));
338
+ if (!slots) {
339
+ throw new Error(
340
+ "The board's partition table has no erb_a and erb_b partitions. Flash this example's Flow B firmware first.",
341
+ );
342
+ }
343
+ return slots;
344
+ },
345
+ write: (address, file) =>
346
+ runTool(names, [...common, 'write_flash', hex(address), file], {
347
+ ...options,
348
+ inherit: true,
349
+ }),
350
+ begin: () => {},
351
+ finish: () => {}, // esptool resets the board itself after each command
352
+ };
353
+ };
354
+
355
+ const picoAccess = ({board, run, sleep}) => {
356
+ const names = process.env.PICOTOOL ? [process.env.PICOTOOL] : ['picotool'];
357
+ const options = {
358
+ run,
359
+ install:
360
+ "Install one with USB support, such as Homebrew's, or set PICOTOOL. The copy a Pico SDK build fetches has none.",
361
+ };
362
+ // libusb on macOS can deadlock as the board detaches, leaving picotool stuck after the reboot worked. What comes
363
+ // next shows whether it did, so a reboot that outlives the timeout isn't a failure.
364
+ const reboot = args => {
365
+ try {
366
+ runTool(names, args, {...options, timeoutMs: PICO_REBOOT_TIMEOUT_MS});
367
+ } catch (error) {
368
+ if (error.code !== 'ETIMEDOUT') throw error;
369
+ }
370
+ };
371
+ return {
372
+ // The board stays in BOOTSEL for the whole write: a command straight after a -f one finds it still rebooting.
373
+ // -f takes a running board there through its USB serial, and a board already there stays.
374
+ begin: () => {
375
+ reboot(['reboot', '-u', '-f']);
376
+ for (let tries = 1; ; tries++) {
377
+ try {
378
+ runTool(names, ['info'], {
379
+ ...options,
380
+ timeoutMs: PICO_REBOOT_TIMEOUT_MS,
381
+ });
382
+ return;
383
+ } catch (error) {
384
+ if (tries === PICO_READY_TRIES) throw error;
385
+ sleep(PICO_READY_WAIT_MS);
386
+ }
387
+ }
388
+ },
389
+ // Addresses are memory addresses for both commands: load's -o defaults to 0x10000000, the start of flash.
390
+ read: (address, bytes, file) =>
391
+ runTool(
392
+ names,
393
+ ['save', '-r', hex(address), hex(address + bytes), file, '-t', 'bin'],
394
+ options,
395
+ ),
396
+ slots: () => board.slots,
397
+ write: (address, file) =>
398
+ runTool(names, ['load', file, '-t', 'bin', '-o', hex(address)], {
399
+ ...options,
400
+ inherit: true,
401
+ }),
402
+ finish: () => reboot(['reboot']),
403
+ };
404
+ };
405
+
406
+ /**
407
+ * Writes a package's slot image to a file, for a line or a drag-and-drop. Nothing here knows what the board holds,
408
+ * so it is for an empty board, or a slot and sequence you already know.
409
+ *
410
+ * @returns {{file: string, address: number, sequence: number, slot: string}}
411
+ */
412
+ export function packSlot({
413
+ packageBytes,
414
+ board,
415
+ boardName,
416
+ slotName = 'a',
417
+ sequence = 1,
418
+ outDir,
419
+ }) {
420
+ const slot = SLOT_NAMES.indexOf(slotName);
421
+ if (slot < 0) throw new Error(`--slot takes a or b, got: ${slotName}`);
422
+ // 0 is valid: it is what comes after the sequence wraps.
423
+ if (!Number.isInteger(sequence) || sequence < 0 || sequence > SEQUENCE_MAX) {
424
+ throw new Error(
425
+ `--sequence takes a whole number from 0 to ${SEQUENCE_MAX}, got: ${sequence}`,
426
+ );
427
+ }
428
+ checkPackage(packageBytes);
429
+ const {address, bytes} = board.slots[slot];
430
+ const image = slotImage(packageBytes, sequence);
431
+ if (image.length > bytes) {
432
+ throw new Error(
433
+ `The package takes ${image.length} B with its header, and ${boardName}'s slots hold ${bytes} B.`,
434
+ );
435
+ }
436
+ const isUf2 = board.tool === 'picotool';
437
+ const file = join(outDir, `app.slot-${slotName}.${isUf2 ? 'uf2' : 'bin'}`);
438
+ writeFileSync(
439
+ file,
440
+ isUf2
441
+ ? uf2([
442
+ {address: address + SLOT_HEADER_BYTES, bytes: packageBytes},
443
+ {address, bytes: slotHeader(packageBytes.length, sequence)},
444
+ ])
445
+ : image,
446
+ );
447
+ return {file, address, sequence, slot: slotName};
448
+ }
449
+
450
+ /**
451
+ * Writes a package to a board: reads its slots, and writes the one that isn't the newest.
452
+ *
453
+ * @returns {{address: number, sequence: number, slot: string, lastGood: string|null}}
454
+ */
455
+ export function flashSlot({
456
+ packageBytes,
457
+ board,
458
+ port,
459
+ run = defaultRun,
460
+ log = () => {},
461
+ sleep = sleepMs,
462
+ }) {
463
+ checkPackage(packageBytes);
464
+ const access =
465
+ board.tool === 'picotool'
466
+ ? picoAccess({board, run, sleep})
467
+ : espAccess({chip: board.chip, port, run});
468
+ const scratchDir = mkdtempSync(join(tmpdir(), 'er-flash-'));
469
+ let begun = false;
470
+ try {
471
+ access.begin();
472
+ begun = true;
473
+ const slots = access.slots(scratchDir);
474
+ const headers = slots.map((slot, index) => {
475
+ const file = join(scratchDir, `header-${index}.bin`);
476
+ access.read(slot.address, SLOT_HEADER_PAGE_BYTES, file);
477
+ return readSlotHeader(readFileSync(file), slot.bytes);
478
+ });
479
+ let {slot, sequence, lastGood} = pickSlot(
480
+ headers.map(header => header?.sequence ?? null),
481
+ );
482
+ // The newest slot is what this write leaves as the fallback, so it has to be whole. A write cut short can leave
483
+ // a header over part of a package, and no boot may have cleared it yet.
484
+ if (lastGood !== null) {
485
+ const file = join(scratchDir, 'newest.bin');
486
+ access.read(
487
+ slots[lastGood].address + SLOT_HEADER_BYTES,
488
+ headers[lastGood].packageBytes,
489
+ file,
490
+ );
491
+ if (!isWholePackage(readFileSync(file))) {
492
+ log(
493
+ `Slot ${SLOT_NAMES[lastGood]} holds a partial package, so it goes first`,
494
+ );
495
+ const other = 1 - lastGood;
496
+ slot = lastGood;
497
+ lastGood = headers[other] ? other : null;
498
+ }
499
+ }
500
+ const {address, bytes} = slots[slot];
501
+ const slotBytesUsed = SLOT_HEADER_BYTES + packageBytes.length;
502
+ if (slotBytesUsed > bytes) {
503
+ throw new Error(
504
+ `The package takes ${slotBytesUsed} B with its header, and this board's slots hold ${bytes} B.`,
505
+ );
506
+ }
507
+ const packageFile = join(scratchDir, 'package.bin');
508
+ const headerFile = join(scratchDir, 'header.bin');
509
+ writeFileSync(packageFile, packageBytes);
510
+ writeFileSync(headerFile, slotHeader(packageBytes.length, sequence));
511
+ log(
512
+ `Writing slot ${SLOT_NAMES[slot]} at ${hex(address)}, sequence ${sequence} (${slotBytesUsed} B)`,
513
+ );
514
+ // The header last. Until then the slot still has its older sequence, or none, so it stays the one to write
515
+ // over if this is cut short, and the other slot stays the newest.
516
+ access.write(address + SLOT_HEADER_BYTES, packageFile);
517
+ access.write(address, headerFile);
518
+ begun = false;
519
+ access.finish();
520
+ return {
521
+ address,
522
+ sequence,
523
+ slot: SLOT_NAMES[slot],
524
+ lastGood: lastGood === null ? null : SLOT_NAMES[lastGood],
525
+ };
526
+ } catch (error) {
527
+ // Out of BOOTSEL if it can, without hiding what went wrong.
528
+ if (begun) {
529
+ try {
530
+ access.finish();
531
+ } catch {}
532
+ }
533
+ throw error;
534
+ } finally {
535
+ rmSync(scratchDir, {recursive: true, force: true});
536
+ }
537
+ }