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/cli.mjs CHANGED
@@ -28,6 +28,7 @@ import {
28
28
  existsSync,
29
29
  mkdirSync,
30
30
  readFileSync,
31
+ statSync,
31
32
  writeFileSync,
32
33
  } from 'node:fs';
33
34
  import {fileURLToPath, pathToFileURL} from 'node:url';
@@ -41,13 +42,17 @@ import {
41
42
  } from './hotreload/pack-split.mjs';
42
43
  import {runDeviceDevServer} from './hotreload/dev-device.mjs';
43
44
  import {detectDevicePorts, preferCalloutPath} from './hotreload/uploader.mjs';
45
+ import {boardByName, flashSlot, packSlot} from './flash.mjs';
44
46
 
45
- const PKG_ROOT = dirname(fileURLToPath(import.meta.url));
47
+ const PACKAGE_ROOT = dirname(fileURLToPath(import.meta.url));
46
48
 
47
49
  // QuickJS release the bytecode container targets — MUST match bridges/quickjs/CMakeLists.txt and
48
50
  // ER_QUICKJS_TAG in er_runtime.c (the device loader rejects a mismatch). The wasm that compiles the
49
51
  // bytecode embeds this same QuickJS.
50
- const QJS_TAG = 'v0.15.0';
52
+ const QUICKJS_TAG = 'v0.15.0';
53
+
54
+ const DEFAULT_PORT = 3333;
55
+ const BYTES_PER_KILOBYTE = 1024;
51
56
 
52
57
  function usage() {
53
58
  console.log(`embedded-react — React Native for embedded MCUs
@@ -57,15 +62,35 @@ Usage:
57
62
  embedded-react dev [entry] --device [port] Hot-reload on a real board over USB (Flow A): re-pack
58
63
  the app and stream it on every save. Omit <port> (or
59
64
  pass 'auto') to auto-detect the ESP32 USB-Serial-JTAG.
65
+ --aot → Flow B: compile a package and send it instead.
60
66
  embedded-react export [entry] [--out <dir>] Build a self-contained static playground (no server)
61
67
  embedded-react build [entry] [--out <dir>] Build the device artifact:
62
68
  default → app.erpkg (Flow A: QuickJS bytecode + assets,
63
69
  upload to the device's config region)
64
- --aot → app.gen.c/.h + assets.generated.c (Flow B:
65
- no QuickJS, compiled into firmware)
66
- --aot --screen <WxH> bake the target panel size so a
67
- responsive app folds to that board's layout
68
- (e.g. --screen 240x320)
70
+ --aot → app.erpkg (Flow B package, for the Flow B
71
+ runtime: write it to a slot with flash)
72
+ It has a layout for every panel size:
73
+ the screen picks one at boot.
74
+ --aot --screen <WxH>,<WxH> keep only the layouts
75
+ those panels pick, to save flash
76
+ --aot --release → a package without its debug
77
+ table, written beside it as app.erdbg
78
+ --aot --bake → app.erpkg.c (the package as a const
79
+ array, for a board with no spare partition)
80
+ embedded-react flash [package] --board <name> [--port <p>]
81
+ Write a package to the board's staging slot. The firmware
82
+ runs it at the next boot if it passes verification, and
83
+ keeps the last good package until then.
84
+ embedded-react pack [package] --board <name> [--slot a|b] [--sequence <n>] [--out <dir>]
85
+ Write a slot's image to a file, for a factory line or a
86
+ drag-and-drop UF2, without a board attached.
87
+ embedded-react native-header <package or file> [--out <dir>]
88
+ Write a C header for each native module a device package
89
+ or a .ts file declares: its records, where each argument
90
+ starts, and an entry for the firmware's table.
91
+
92
+ board esp32-2432s028r, esp32-s3 or rp2040-touch-lcd-1.69
93
+ package defaults to dist/app.erpkg
69
94
 
70
95
  entry dev/export/build use ./index.jsx, ./src/index.jsx, or package.json "main";
71
96
  build --aot uses ./App.jsx or ./src/App.jsx. Pass one to override.
@@ -74,7 +99,7 @@ Usage:
74
99
 
75
100
  /** Locate the package's prebuilt simulator assets (the .wasm ships with this package). */
76
101
  function simDirOrExit() {
77
- const simDir = resolve(PKG_ROOT, 'sim');
102
+ const simDir = resolve(PACKAGE_ROOT, 'sim');
78
103
  if (!existsSync(resolve(simDir, 'embedded-react.wasm'))) {
79
104
  console.error(
80
105
  'The prebuilt simulator (sim/embedded-react.wasm) is missing from this install.',
@@ -87,23 +112,23 @@ function simDirOrExit() {
87
112
  return simDir;
88
113
  }
89
114
 
90
- const libSrc = () => resolve(PKG_ROOT, 'src/embedded-react/index.js');
115
+ const libSrc = () => resolve(PACKAGE_ROOT, 'src/embedded-react/index.js');
91
116
  const nodePaths = cwd => [
92
- resolve(PKG_ROOT, 'node_modules'),
117
+ resolve(PACKAGE_ROOT, 'node_modules'),
93
118
  resolve(cwd, 'node_modules'),
94
119
  ];
95
120
 
96
121
  /** Resolve the app entry: an explicit arg, else common conventions, else package.json "main"/"source". */
97
122
  function resolveEntry(cwd, explicit) {
98
123
  if (explicit) {
99
- const p = resolve(cwd, explicit);
100
- if (!existsSync(p)) {
101
- console.error(`Entry not found: ${p}`);
124
+ const entryPath = resolve(cwd, explicit);
125
+ if (!existsSync(entryPath)) {
126
+ console.error(`Entry not found: ${entryPath}`);
102
127
  process.exit(1);
103
128
  }
104
- return p;
129
+ return entryPath;
105
130
  }
106
- for (const rel of [
131
+ for (const relativePath of [
107
132
  'index.jsx',
108
133
  'src/index.jsx',
109
134
  'index.tsx',
@@ -111,17 +136,17 @@ function resolveEntry(cwd, explicit) {
111
136
  'App.jsx',
112
137
  'src/App.jsx',
113
138
  ]) {
114
- const p = resolve(cwd, rel);
115
- if (existsSync(p)) return p;
139
+ const entryPath = resolve(cwd, relativePath);
140
+ if (existsSync(entryPath)) return entryPath;
116
141
  }
117
- const pkgPath = resolve(cwd, 'package.json');
118
- if (existsSync(pkgPath)) {
142
+ const packageJsonPath = resolve(cwd, 'package.json');
143
+ if (existsSync(packageJsonPath)) {
119
144
  try {
120
- const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
121
- for (const field of [pkg.source, pkg.main]) {
122
- if (field) {
123
- const p = resolve(cwd, field);
124
- if (existsSync(p)) return p;
145
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
146
+ for (const entryField of [packageJson.source, packageJson.main]) {
147
+ if (entryField) {
148
+ const entryPath = resolve(cwd, entryField);
149
+ if (existsSync(entryPath)) return entryPath;
125
150
  }
126
151
  }
127
152
  } catch {
@@ -138,34 +163,34 @@ function resolveEntry(cwd, explicit) {
138
163
  }
139
164
 
140
165
  function optValue(args, flag) {
141
- const idx = args.indexOf(flag);
142
- if (idx < 0) return null;
143
- const value = args[idx + 1];
166
+ const flagIndex = args.indexOf(flag);
167
+ if (flagIndex < 0) return null;
168
+ const value = args[flagIndex + 1];
144
169
  if (!value || value.startsWith('--')) {
145
170
  console.error(`Missing value for ${flag}\n`);
146
171
  usage();
147
172
  process.exit(1);
148
173
  }
149
- return {value, idx, valueIdx: idx + 1};
174
+ return {value, index: flagIndex, valueIndex: flagIndex + 1};
150
175
  }
151
176
 
152
177
  /** Like optValue, but the value is OPTIONAL: `--flag` alone → {value: null}; `--flag x` → {value: 'x'}. */
153
178
  function optFlagMaybeValue(args, flag) {
154
- const idx = args.indexOf(flag);
155
- if (idx < 0) return null;
156
- const next = args[idx + 1];
157
- const hasValue = next != null && !next.startsWith('--');
179
+ const flagIndex = args.indexOf(flag);
180
+ if (flagIndex < 0) return null;
181
+ const nextArg = args[flagIndex + 1];
182
+ const hasValue = nextArg != null && !nextArg.startsWith('--');
158
183
  return {
159
- value: hasValue ? next : null,
160
- idx,
161
- valueIdx: hasValue ? idx + 1 : -1,
184
+ value: hasValue ? nextArg : null,
185
+ index: flagIndex,
186
+ valueIndex: hasValue ? flagIndex + 1 : -1,
162
187
  };
163
188
  }
164
189
 
165
190
  /** A token that names a serial port rather than an app entry file (so `--device App.jsx` isn't a port). */
166
- const looksLikeDevicePath = s =>
167
- /^(\/dev\/|com\d|\\\\\.\\)/i.test(s) ||
168
- /(tty|usbmodem|usbserial|cu\.)/i.test(s);
191
+ const looksLikeDevicePath = token =>
192
+ /^(\/dev\/|com\d|\\\\\.\\)/i.test(token) ||
193
+ /(tty|usbmodem|usbserial|cu\.)/i.test(token);
169
194
 
170
195
  /**
171
196
  * Resolve the `--device` port. An explicit path is the universal, board-agnostic mechanism (any serial
@@ -186,11 +211,11 @@ async function resolveDevicePortOrExit(explicit) {
186
211
  process.exit(1);
187
212
  }
188
213
  if (matches.length === 1) {
189
- const p = matches[0];
190
- const path = preferCalloutPath(p.path);
214
+ const port = matches[0];
215
+ const path = preferCalloutPath(port.path);
191
216
  console.log(
192
217
  `✓ auto-detected ESP32 USB-Serial-JTAG at ${path}` +
193
- (p.serialNumber ? ` (SN ${p.serialNumber})` : ''),
218
+ (port.serialNumber ? ` (SN ${port.serialNumber})` : ''),
194
219
  );
195
220
  return path;
196
221
  }
@@ -205,13 +230,13 @@ async function resolveDevicePortOrExit(explicit) {
205
230
  console.error(' embedded-react dev --device <port>');
206
231
  if (all.length) {
207
232
  console.error('\n Serial ports seen (pick yours):');
208
- for (const p of all)
233
+ for (const port of all)
209
234
  console.error(
210
- ` ${p.path}` +
211
- (p.vendorId && p.productId
212
- ? ` [${p.vendorId}:${p.productId}]`
235
+ ` ${port.path}` +
236
+ (port.vendorId && port.productId
237
+ ? ` [${port.vendorId}:${port.productId}]`
213
238
  : '') +
214
- (p.manufacturer ? ` ${p.manufacturer}` : ''),
239
+ (port.manufacturer ? ` ${port.manufacturer}` : ''),
215
240
  );
216
241
  } else {
217
242
  console.error(
@@ -229,23 +254,31 @@ async function resolveDevicePortOrExit(explicit) {
229
254
  console.error(
230
255
  `✗ found ${matches.length} ESP32 USB-Serial-JTAG ports; pass one explicitly with --device <port>:`,
231
256
  );
232
- for (const p of matches)
257
+ for (const port of matches)
233
258
  console.error(
234
- ` ${preferCalloutPath(p.path)}${p.serialNumber ? ` (SN ${p.serialNumber})` : ''}`,
259
+ ` ${preferCalloutPath(port.path)}${port.serialNumber ? ` (SN ${port.serialNumber})` : ''}`,
235
260
  );
236
261
  process.exit(1);
237
262
  }
238
263
 
239
264
  async function dev(args) {
240
265
  const cwd = process.cwd();
241
- const deviceOpt = optFlagMaybeValue(args, '--device');
266
+ const deviceOption = optFlagMaybeValue(args, '--device');
267
+ const aot = args.includes('--aot');
268
+ if (aot && !deviceOption) {
269
+ console.error(
270
+ '--aot only applies to --device: the simulator runs the app as Flow A.\n',
271
+ );
272
+ usage();
273
+ process.exit(1);
274
+ }
242
275
 
243
276
  // --device [port] → stream the app to a real board over USB on every save (on-device hot reload).
244
277
  // With no port (or `auto`), the ESP32 USB-Serial-JTAG is auto-detected. Otherwise → the WASM simulator.
245
- if (deviceOpt) {
278
+ if (deviceOption) {
246
279
  // The token-after --device is normally the port. But `--device App.jsx` means "auto-detect + this
247
280
  // entry": if the value names an existing file (and isn't a device path), treat it as the entry.
248
- let deviceValue = deviceOpt.value;
281
+ let deviceValue = deviceOption.value;
249
282
  let entryFromDeviceSlot = null;
250
283
  if (
251
284
  deviceValue &&
@@ -259,12 +292,26 @@ async function dev(args) {
259
292
  const explicit =
260
293
  entryFromDeviceSlot ??
261
294
  args.find(
262
- (a, i) =>
263
- !a.startsWith('--') &&
264
- i !== deviceOpt.idx &&
265
- i !== deviceOpt.valueIdx,
295
+ (arg, argIndex) =>
296
+ !arg.startsWith('--') &&
297
+ argIndex !== deviceOption.index &&
298
+ argIndex !== deviceOption.valueIndex,
266
299
  );
267
300
 
301
+ if (aot) {
302
+ const appPath = resolveAppComponent(cwd, explicit);
303
+ const device = await resolveDevicePortOrExit(deviceValue);
304
+ await runDeviceDevServer({
305
+ entry: appPath,
306
+ projectRoot: cwd,
307
+ device,
308
+ label: appPath,
309
+ compilePackage: async () =>
310
+ Buffer.from((await compileAppPackage(cwd, appPath)).file.bytes),
311
+ });
312
+ return;
313
+ }
314
+
268
315
  const simDir = simDirOrExit();
269
316
  const entry = resolveEntry(cwd, explicit);
270
317
  const device = await resolveDevicePortOrExit(deviceValue);
@@ -281,14 +328,18 @@ async function dev(args) {
281
328
  return;
282
329
  }
283
330
 
284
- const portOpt = optValue(args, '--port');
285
- const consumed = new Set(portOpt ? [portOpt.idx, portOpt.valueIdx] : []);
286
- const explicit = args.find((a, i) => !a.startsWith('--') && !consumed.has(i));
331
+ const portOption = optValue(args, '--port');
332
+ const consumed = new Set(
333
+ portOption ? [portOption.index, portOption.valueIndex] : [],
334
+ );
335
+ const explicit = args.find(
336
+ (arg, argIndex) => !arg.startsWith('--') && !consumed.has(argIndex),
337
+ );
287
338
 
288
339
  const simDir = simDirOrExit();
289
340
  const entry = resolveEntry(cwd, explicit);
290
341
 
291
- const port = portOpt ? parseInt(portOpt.value, 10) : 3333;
342
+ const port = portOption ? parseInt(portOption.value, 10) : DEFAULT_PORT;
292
343
  const outDir = resolve(tmpdir(), 'embedded-react-sim');
293
344
  mkdirSync(outDir, {recursive: true});
294
345
 
@@ -307,16 +358,20 @@ async function dev(args) {
307
358
 
308
359
  async function exportApp(args) {
309
360
  const cwd = process.cwd();
310
- const outIdx = args.indexOf('--out');
311
- const outDir = resolve(cwd, outIdx >= 0 ? args[outIdx + 1] : 'sim-export');
361
+ const outIndex = args.indexOf('--out');
362
+ const outDir = resolve(
363
+ cwd,
364
+ outIndex >= 0 ? args[outIndex + 1] : 'sim-export',
365
+ );
312
366
  const explicit = args.find(
313
- (a, i) => !a.startsWith('--') && (outIdx < 0 || i !== outIdx + 1),
367
+ (arg, argIndex) =>
368
+ !arg.startsWith('--') && (outIndex < 0 || argIndex !== outIndex + 1),
314
369
  );
315
370
 
316
371
  const simDir = simDirOrExit();
317
372
  const entry = resolveEntry(cwd, explicit);
318
- const pub = resolve(outDir, 'public');
319
- mkdirSync(pub, {recursive: true});
373
+ const publicDir = resolve(outDir, 'public');
374
+ mkdirSync(publicDir, {recursive: true});
320
375
 
321
376
  // Bundle the app + bake assets into public/, then drop the prebuilt module + host page alongside.
322
377
  await buildApp({
@@ -324,10 +379,10 @@ async function exportApp(args) {
324
379
  projectRoot: cwd,
325
380
  libSrc: libSrc(),
326
381
  nodePaths: nodePaths(cwd),
327
- outDir: pub,
382
+ outDir: publicDir,
328
383
  });
329
- for (const f of ['embedded-react.js', 'embedded-react.wasm'])
330
- copyFileSync(resolve(simDir, f), resolve(pub, f));
384
+ for (const fileName of ['embedded-react.js', 'embedded-react.wasm'])
385
+ copyFileSync(resolve(simDir, fileName), resolve(publicDir, fileName));
331
386
  copyFileSync(resolve(simDir, 'index.html'), resolve(outDir, 'index.html'));
332
387
 
333
388
  console.log(
@@ -339,39 +394,23 @@ async function exportApp(args) {
339
394
  }
340
395
 
341
396
  /** Resolve the root component file for the AOT compiler (App.jsx), distinct from the registry entry. */
342
- /**
343
- * The project identity stamped into app.gen.h as ER_AOT_DEMO / ER_AOT_DEMO_<name>, which a board example
344
- * guards on (see the header's own comment). It is the directory of the nearest package.json at or above
345
- * the App component, so `demos/watch-face/App.jsx` is `watch-face` whether the build runs from that
346
- * directory or names the entry from somewhere else — and a scaffolded `src/App.jsx` reports its project
347
- * folder rather than `src`. Deriving it from the cwd instead would stamp whatever directory you ran from.
348
- */
349
- function projectIdentity(appPath) {
350
- let dir = dirname(appPath);
351
- for (let i = 0; i < 64; i++) {
352
- // A package.json at a filesystem root has no directory name to report — basename('/') is '' — so
353
- // treat it as absent rather than stamp an empty identity (`ER_AOT_DEMO_` with nothing after it).
354
- if (existsSync(resolve(dir, 'package.json')) && basename(dir))
355
- return basename(dir);
356
- const up = dirname(dir);
357
- if (up === dir) break; // filesystem root
358
- dir = up;
359
- }
360
- return basename(dirname(appPath)) || 'app';
361
- }
362
-
363
397
  function resolveAppComponent(cwd, explicit) {
364
398
  if (explicit) {
365
- const p = resolve(cwd, explicit);
366
- if (!existsSync(p)) {
367
- console.error(`Entry not found: ${p}`);
399
+ const entryPath = resolve(cwd, explicit);
400
+ if (!existsSync(entryPath)) {
401
+ console.error(`Entry not found: ${entryPath}`);
368
402
  process.exit(1);
369
403
  }
370
- return p;
404
+ return entryPath;
371
405
  }
372
- for (const rel of ['App.jsx', 'src/App.jsx', 'App.tsx', 'src/App.tsx']) {
373
- const p = resolve(cwd, rel);
374
- if (existsSync(p)) return p;
406
+ for (const relativePath of [
407
+ 'App.jsx',
408
+ 'src/App.jsx',
409
+ 'App.tsx',
410
+ 'src/App.tsx',
411
+ ]) {
412
+ const entryPath = resolve(cwd, relativePath);
413
+ if (existsSync(entryPath)) return entryPath;
375
414
  }
376
415
  console.error(
377
416
  'No App component found. Pass one explicitly: embedded-react build --aot <App.jsx>',
@@ -379,66 +418,111 @@ function resolveAppComponent(cwd, explicit) {
379
418
  process.exit(1);
380
419
  }
381
420
 
382
- /** Flow B (--aot): compile the App component to C (app.gen.{c,h}) + bake assets, to compile into firmware. */
383
- async function buildAot(cwd, explicit, outDir, screen) {
384
- const {compileSource, bakeSvgArtifacts} = await import('./aot/compile.mjs');
385
- const {bakeAssets} = await import('./assets/index.mjs');
421
+ /**
422
+ * Compiles the App component with what goes into the build: its package file and its image jobs.
423
+ * Throws with the reason, so a watch loop can carry on past a bad save.
424
+ */
425
+ async function compileAppPackage(
426
+ cwd,
427
+ appPath,
428
+ {screens = null, release = false} = {},
429
+ ) {
430
+ const {compilePackage, bakeSvgArtifacts, packPackage, readNativeFiles} =
431
+ await import('./aot/compile.mjs');
432
+ const {bakeAssetPackBytes} = await import('./assets/index.mjs');
386
433
  const {warnMissingGlyphs} = await import('./assets/glyph-coverage.mjs');
387
434
  const {analyzeFontSizes, warnFontSizes} =
388
435
  await import('./assets/font-sizes.mjs');
389
- const appPath = resolveAppComponent(cwd, explicit);
390
436
  const appDir = dirname(appPath);
391
- const src = readFileSync(appPath, 'utf8');
392
- let result;
393
- try {
394
- // Bake <Svg source> .svg imports → vector artifacts (incl. gradients), then compile with them in hand.
395
- const svgArtifacts = await bakeSvgArtifacts(src, appDir);
396
- // app.gen.h records WHICH app it came from and a board example guards on that marker, so it must name
397
- // the source project — the same ER_AOT_DEMO_watch_2d_face that `npm run aot -- watch-face` produces.
398
- // The target panel size (--screen <WxH>) folds a responsive app's `screen.width` branch to the one
399
- // that the board renders. Without it, the compiler falls back to ER_AOT_SCREEN_W/H, then 800x480.
400
- result = compileSource(src, projectIdentity(appPath), {
401
- filename: appPath,
402
- svgArtifacts,
403
- screen, // null without --screen
404
- });
405
- } catch (e) {
406
- console.error(e && e.aotLoc ? e.message : e?.message || String(e));
407
- process.exit(1);
408
- }
409
- writeFileSync(resolve(outDir, 'app.gen.c'), result.c);
410
- writeFileSync(resolve(outDir, 'app.gen.h'), result.h);
437
+ const source = readFileSync(appPath, 'utf8');
438
+ // Bake <Svg source> .svg imports → vector artifacts (incl. gradients), then compile with them in hand.
439
+ const svgArtifacts = await bakeSvgArtifacts(source, appDir);
440
+ // A package has every layout the app's breakpoints call for, and --screen <WxH>,<WxH> keeps only those the
441
+ // sizes pick.
442
+ const result = compilePackage(source, basename(dirname(appPath)), {
443
+ filename: appPath,
444
+ svgArtifacts,
445
+ // Native modules and their interfaces in other files and packages, read here so the compile stays pure.
446
+ nativeFiles: readNativeFiles(source, appDir),
447
+ screen: screens?.[0] ?? null, // null without --screen
448
+ screens,
449
+ release,
450
+ });
411
451
 
412
452
  // Optional per-image overrides (same file the JS flows read): assets.config.js
413
453
  // export default { images: { 'bg': { format: 'rgb565' } } }
414
- let cfg = {};
415
- const cp = resolve(cwd, 'assets.config.js');
416
- if (existsSync(cp))
417
- cfg = (await import(pathToFileURL(cp).href)).default || {};
418
- const imageConfig = cfg.images || {};
419
-
420
- const imageJobs = result.images.map(im => ({
421
- name: im.name,
422
- path: resolve(appDir, im.importPath),
423
- format: imageConfig[im.name]?.format,
454
+ let assetsConfig = {};
455
+ const assetsConfigPath = resolve(cwd, 'assets.config.js');
456
+ if (existsSync(assetsConfigPath))
457
+ assetsConfig =
458
+ (
459
+ await import(
460
+ `${pathToFileURL(assetsConfigPath).href}?t=${statSync(assetsConfigPath).mtimeMs}`
461
+ )
462
+ ).default || {};
463
+ const imageConfig = assetsConfig.images || {};
464
+
465
+ const imageJobs = result.images.map(image => ({
466
+ name: image.name,
467
+ path: resolve(appDir, image.importPath),
468
+ format: imageConfig[image.name]?.format,
424
469
  }));
425
- for (const j of imageJobs) {
426
- if (!existsSync(j.path)) {
427
- console.error(`<Image> asset "${j.name}" not found at ${j.path}`);
428
- process.exit(1);
470
+ for (const job of imageJobs) {
471
+ if (!existsSync(job.path)) {
472
+ throw new Error(`<Image> asset "${job.name}" not found at ${job.path}`);
429
473
  }
430
474
  }
431
475
  // Flow B renders everything in the engine's built-in font (no font imports) — check the app's text
432
476
  // and its font sizes against what that font actually covers.
433
- warnMissingGlyphs({source: src, jsx: true});
434
- warnFontSizes({used: analyzeFontSizes(src)});
435
- const baked = bakeAssets({images: imageJobs, fonts: [], outDir});
436
- console.log(
437
- `✓ Flow B (AOT) → ${relative(cwd, outDir) || '.'}/app.gen.c (+ app.gen.h, assets.generated.c — ${baked.images} image(s))`,
477
+ warnMissingGlyphs({source, jsx: true});
478
+ warnFontSizes({used: analyzeFontSizes(source)});
479
+ const file = packPackage(
480
+ result,
481
+ imageJobs.length ? bakeAssetPackBytes({images: imageJobs}) : undefined,
482
+ );
483
+ return {result, file, imageJobs};
484
+ }
485
+
486
+ /**
487
+ * Flow B (--aot): compile the App component to a Flow B package (app.erpkg) with its assets inside, for the Flow B
488
+ * runtime to load: for release without its debug table (app.erdbg beside it), and baked as a const array
489
+ * (app.erpkg.c) to link into the firmware.
490
+ */
491
+ async function buildAot(
492
+ cwd,
493
+ explicit,
494
+ outDir,
495
+ screens,
496
+ {release = false, bake = false} = {},
497
+ ) {
498
+ const {bakePackage, resourceReport} = await import('./aot/compile.mjs');
499
+ const appPath = resolveAppComponent(cwd, explicit);
500
+ let compiled;
501
+ try {
502
+ compiled = await compileAppPackage(cwd, appPath, {screens, release});
503
+ } catch (error) {
504
+ console.error(
505
+ error && error.aotLoc ? error.message : error?.message || String(error),
506
+ );
507
+ process.exit(1);
508
+ }
509
+ const {result, file, imageJobs} = compiled;
510
+ const displayDir = relative(cwd, outDir) || '.';
511
+ const name = bake ? 'app.erpkg.c' : 'app.erpkg';
512
+ writeFileSync(
513
+ resolve(outDir, name),
514
+ bake ? bakePackage(file.bytes) : file.bytes,
438
515
  );
439
516
  console.log(
440
- ' No QuickJS on the device: compile these into your firmware against the engine (er_scene.h).',
517
+ `✓ Flow B package → ${displayDir}/${name} (${release ? 'release' : 'debug'}, ${imageJobs.length} image(s))`,
441
518
  );
519
+ if (release) {
520
+ writeFileSync(resolve(outDir, 'app.erdbg'), result.debug);
521
+ console.log(
522
+ ` Debug table → ${displayDir}/app.erdbg (${result.debug.length} B), to map a fault back to the source`,
523
+ );
524
+ }
525
+ console.log(resourceReport(result, file).join('\n'));
442
526
  }
443
527
 
444
528
  /**
@@ -453,13 +537,13 @@ async function buildAot(cwd, explicit, outDir, screen) {
453
537
  async function buildContainer(cwd, explicit, outDir) {
454
538
  const simDir = simDirOrExit();
455
539
  const entry = resolveEntry(cwd, explicit);
456
- const lib = libSrc();
540
+ const librarySource = libSrc();
457
541
  const paths = nodePaths(cwd);
458
542
 
459
543
  // Release artifact: strip the embedded source text + debug tables from the bytecode (~8x smaller
460
544
  // erpkg; stack traces lose line numbers). The dev loop (`embedded-react dev`) keeps them.
461
545
  const vendor = await packVendor({
462
- libSrc: lib,
546
+ libSrc: librarySource,
463
547
  nodePaths: paths,
464
548
  simDir,
465
549
  strip: true,
@@ -467,7 +551,7 @@ async function buildContainer(cwd, explicit, outDir) {
467
551
  const app = await packApp({
468
552
  entry,
469
553
  projectRoot: cwd,
470
- libSrc: lib,
554
+ libSrc: librarySource,
471
555
  nodePaths: paths,
472
556
  simDir,
473
557
  strip: true,
@@ -480,9 +564,9 @@ async function buildContainer(cwd, explicit, outDir) {
480
564
 
481
565
  const outPath = resolve(outDir, 'app.erpkg');
482
566
  writeFileSync(outPath, container);
483
- const kb = n => `${(n / 1024).toFixed(1)} KB`;
567
+ const kb = byteCount => `${(byteCount / BYTES_PER_KILOBYTE).toFixed(1)} KB`;
484
568
  console.log(
485
- `✓ Flow A → ${relative(cwd, outPath) || 'app.erpkg'} (${kb(container.length)}; qjs ${QJS_TAG}, ` +
569
+ `✓ Flow A → ${relative(cwd, outPath) || 'app.erpkg'} (${kb(container.length)}; qjs ${QUICKJS_TAG}, ` +
486
570
  `vendor ${kb(vendor.bytecodeLen)} + app ${kb(app.bytecodeLen)}` +
487
571
  (app.assetsLen ? `, assets ${kb(app.assetsLen)}` : '') +
488
572
  ')',
@@ -495,18 +579,30 @@ async function buildContainer(cwd, explicit, outDir) {
495
579
  );
496
580
  }
497
581
 
498
- /** `embedded-react build [--aot] [entry] [--out dir] [--screen WxH]` — produce the device artifact. */
582
+ /**
583
+ * `embedded-react build [--aot [--release] [--bake]] [entry] [--out dir] [--screen WxH[,WxH…]]` — produce the
584
+ * device artifact.
585
+ */
499
586
  async function build(args) {
500
587
  const cwd = process.cwd();
501
588
  const aot = args.includes('--aot');
502
- const outIdx = args.indexOf('--out');
503
- const outDir = resolve(cwd, outIdx >= 0 ? args[outIdx + 1] : 'dist');
504
-
505
- // --screen <WxH> (AOT only): the target panel size, baked so a responsive app folds to the branch that
506
- // board renders (e.g., 240x320 → the compact layout). Flow A reads the screen from the host at runtime.
507
- const screenIdx = args.indexOf('--screen');
508
- let screen = null;
509
- if (screenIdx >= 0) {
589
+ const release = args.includes('--release');
590
+ const bake = args.includes('--bake');
591
+ for (const flag of ['--release', '--bake']) {
592
+ if (args.includes(flag) && !aot) {
593
+ console.error(`${flag} only applies to --aot.\n`);
594
+ usage();
595
+ process.exit(1);
596
+ }
597
+ }
598
+ const outIndex = args.indexOf('--out');
599
+ const outDir = resolve(cwd, outIndex >= 0 ? args[outIndex + 1] : 'dist');
600
+
601
+ // --screen <WxH> (AOT only): the panels to keep layouts for, comma-separated. Optional: a package has every
602
+ // layout without it. Flow A reads the screen from the host at runtime.
603
+ const screenIndex = args.indexOf('--screen');
604
+ let screens = null;
605
+ if (screenIndex >= 0) {
510
606
  if (!aot) {
511
607
  console.error(
512
608
  '--screen only applies to --aot (Flow A reads the panel size from the host at runtime).\n',
@@ -514,40 +610,174 @@ async function build(args) {
514
610
  usage();
515
611
  process.exit(1);
516
612
  }
517
- const raw = args[screenIdx + 1];
518
- const m = raw && /^([1-9]\d*)x([1-9]\d*)$/i.exec(raw);
519
- if (!m) {
613
+ const screenList = args[screenIndex + 1];
614
+ const sizes = (screenList ?? '')
615
+ .split(',')
616
+ .map(size => /^([1-9]\d*)x([1-9]\d*)$/i.exec(size));
617
+ if (!screenList || sizes.some(size => !size)) {
520
618
  console.error(
521
- `--screen expects <width>x<height> (e.g. --screen 240x320), got: ${raw ?? '(nothing)'}\n`,
619
+ `--screen expects <width>x<height> (e.g. --screen 240x320), got: ${screenList ?? '(nothing)'}\n`,
522
620
  );
523
621
  usage();
524
622
  process.exit(1);
525
623
  }
526
- screen = {width: Number(m[1]), height: Number(m[2])};
624
+ screens = sizes.map(size => ({
625
+ width: Number(size[1]),
626
+ height: Number(size[2]),
627
+ }));
527
628
  }
528
629
 
529
630
  // Consume the flag VALUES so they aren't mistaken for the entry (which is a bare, non-`--` token).
530
631
  const consumed = new Set();
531
- if (outIdx >= 0) consumed.add(outIdx + 1);
532
- if (screenIdx >= 0) consumed.add(screenIdx + 1);
533
- const explicit = args.find((a, i) => !a.startsWith('--') && !consumed.has(i));
632
+ if (outIndex >= 0) consumed.add(outIndex + 1);
633
+ if (screenIndex >= 0) consumed.add(screenIndex + 1);
634
+ const explicit = args.find(
635
+ (arg, argIndex) => !arg.startsWith('--') && !consumed.has(argIndex),
636
+ );
534
637
 
535
638
  mkdirSync(outDir, {recursive: true});
536
- if (aot) await buildAot(cwd, explicit, outDir, screen);
639
+ if (aot) await buildAot(cwd, explicit, outDir, screens, {release, bake});
537
640
  else await buildContainer(cwd, explicit, outDir);
538
641
  }
539
642
 
540
- const [cmd, ...rest] = process.argv.slice(2);
541
- if (cmd === 'dev') {
542
- await dev(rest);
543
- } else if (cmd === 'export') {
544
- await exportApp(rest);
545
- } else if (cmd === 'build') {
546
- await build(rest);
547
- } else if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') {
643
+ /** Reads the package a `pack` or `flash` names, or dist/app.erpkg; exits saying how to build one when it's missing. */
644
+ function readPackageOrExit(cwd, explicit) {
645
+ const path = resolve(cwd, explicit ?? 'dist/app.erpkg');
646
+ if (!existsSync(path)) {
647
+ console.error(
648
+ `No package at ${path}. Build one with: embedded-react build --aot`,
649
+ );
650
+ process.exit(1);
651
+ }
652
+ return readFileSync(path);
653
+ }
654
+
655
+ /** The bare arguments, once the values of the listed flags are set aside. */
656
+ function bareArgs(args, flagsWithValues) {
657
+ const consumed = new Set();
658
+ for (const flag of flagsWithValues) {
659
+ const flagIndex = args.indexOf(flag);
660
+ if (flagIndex >= 0) consumed.add(flagIndex + 1);
661
+ }
662
+ return args.filter(
663
+ (arg, argIndex) => !arg.startsWith('--') && !consumed.has(argIndex),
664
+ );
665
+ }
666
+
667
+ /** `embedded-react pack [package] --board <name> [--slot a|b] [--sequence n] [--out dir]` */
668
+ function pack(args) {
669
+ const cwd = process.cwd();
670
+ const boardName = optValue(args, '--board')?.value;
671
+ const outDir = resolve(cwd, optValue(args, '--out')?.value ?? 'dist');
672
+ const sequence = Number(optValue(args, '--sequence')?.value ?? 1);
673
+ try {
674
+ const board = boardByName(boardName);
675
+ const [explicit] = bareArgs(args, [
676
+ '--board',
677
+ '--slot',
678
+ '--sequence',
679
+ '--out',
680
+ ]);
681
+ mkdirSync(outDir, {recursive: true});
682
+ const packed = packSlot({
683
+ packageBytes: readPackageOrExit(cwd, explicit),
684
+ board,
685
+ boardName,
686
+ slotName: optValue(args, '--slot')?.value,
687
+ sequence,
688
+ outDir,
689
+ });
690
+ console.log(
691
+ `✓ Slot ${packed.slot}, sequence ${packed.sequence} → ${relative(cwd, packed.file)}, for flash address 0x${packed.address.toString(16)}`,
692
+ );
693
+ } catch (error) {
694
+ console.error(error.message);
695
+ process.exit(1);
696
+ }
697
+ }
698
+
699
+ /** `embedded-react flash [package] --board <name> [--port p]` */
700
+ function flash(args) {
701
+ const cwd = process.cwd();
702
+ const boardName = optValue(args, '--board')?.value;
703
+ try {
704
+ const board = boardByName(boardName);
705
+ const [explicit] = bareArgs(args, ['--board', '--port']);
706
+ const written = flashSlot({
707
+ packageBytes: readPackageOrExit(cwd, explicit),
708
+ board,
709
+ port: optValue(args, '--port')?.value,
710
+ log: line => console.log(line),
711
+ });
712
+ console.log(
713
+ `✓ Package written to slot ${written.slot}, sequence ${written.sequence}. The board runs it at its next boot if it passes verification` +
714
+ (written.lastGood
715
+ ? `, and slot ${written.lastGood} stays as the last good package.`
716
+ : '.'),
717
+ );
718
+ } catch (error) {
719
+ console.error(error.message);
720
+ process.exit(1);
721
+ }
722
+ }
723
+
724
+ /** `embedded-react native-header <package or file> [--out dir]` */
725
+ async function nativeHeader(args) {
726
+ const cwd = process.cwd();
727
+ const outDir = resolve(cwd, optValue(args, '--out')?.value ?? '.');
728
+ const [target] = bareArgs(args, ['--out']);
729
+ if (!target) {
730
+ console.error(
731
+ 'Pass the package or the .ts file that declares the modules.\n',
732
+ );
733
+ usage();
734
+ process.exit(1);
735
+ }
736
+ const {nativeHeaders, readModuleFile} = await import('./aot/compile.mjs');
737
+ let shownFile = target;
738
+ try {
739
+ const {path, source, files} = readModuleFile(target, cwd);
740
+ shownFile = relative(cwd, path);
741
+ const headers = nativeHeaders(source, files);
742
+ mkdirSync(outDir, {recursive: true});
743
+ for (const header of headers) {
744
+ writeFileSync(resolve(outDir, header.file), header.text);
745
+ console.log(
746
+ `✓ ${header.module} → ${relative(cwd, resolve(outDir, header.file))}`,
747
+ );
748
+ }
749
+ } catch (error) {
750
+ const where = error?.aotLoc
751
+ ? `${shownFile}:${error.aotLoc.line}:${error.aotLoc.column + 1}: `
752
+ : '';
753
+ console.error(where + (error?.message || String(error)));
754
+ if (error?.aotHint) console.error(` ${error.aotHint}`);
755
+ process.exit(1);
756
+ }
757
+ }
758
+
759
+ const [command, ...commandArgs] = process.argv.slice(2);
760
+ if (command === 'dev') {
761
+ await dev(commandArgs);
762
+ } else if (command === 'export') {
763
+ await exportApp(commandArgs);
764
+ } else if (command === 'build') {
765
+ await build(commandArgs);
766
+ } else if (command === 'pack') {
767
+ pack(commandArgs);
768
+ } else if (command === 'flash') {
769
+ flash(commandArgs);
770
+ } else if (command === 'native-header') {
771
+ await nativeHeader(commandArgs);
772
+ } else if (
773
+ !command ||
774
+ command === '--help' ||
775
+ command === '-h' ||
776
+ command === 'help'
777
+ ) {
548
778
  usage();
549
779
  } else {
550
- console.error(`Unknown command: ${cmd}\n`);
780
+ console.error(`Unknown command: ${command}\n`);
551
781
  usage();
552
782
  process.exit(1);
553
783
  }