embedded-react 0.21.0 → 0.22.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 (99) hide show
  1. package/README.md +2 -2
  2. package/aot/compile.mjs +1 -1
  3. package/aot/compiler/alerts.mjs +604 -0
  4. package/aot/compiler/check.mjs +1 -1
  5. package/aot/compiler/collect.mjs +1 -1
  6. package/aot/compiler/elements/button.mjs +3 -3
  7. package/aot/compiler/elements/image-background.mjs +1 -1
  8. package/aot/compiler/elements/props.mjs +10 -6
  9. package/aot/compiler/elements/section-list.mjs +1 -1
  10. package/aot/compiler/expressions.mjs +29 -2
  11. package/aot/compiler/handlers.mjs +73 -16
  12. package/aot/compiler/keyboard-dismiss.mjs +99 -0
  13. package/aot/compiler/keyboard.mjs +1 -1
  14. package/aot/compiler/lower.mjs +12 -0
  15. package/aot/compiler/nodes.mjs +17 -9
  16. package/aot/compiler/out.mjs +4 -0
  17. package/aot/compiler/package/codegen.mjs +36 -2
  18. package/aot/compiler/package/format.mjs +5 -3
  19. package/aot/compiler/package/lower.mjs +53 -19
  20. package/aot/compiler/scroll-to.mjs +112 -0
  21. package/aot/compiler/style-text.mjs +2 -2
  22. package/aot/compiler/svg.mjs +6 -3
  23. package/aot/compiler/updaters.mjs +1 -0
  24. package/aot/style-map.mjs +44 -1
  25. package/assets/bake-font.mjs +187 -244
  26. package/assets/bake-image.mjs +47 -71
  27. package/assets/bake-svg.mjs +465 -533
  28. package/assets/build-builtin-font.mjs +14 -27
  29. package/assets/emit-c.mjs +124 -204
  30. package/assets/emit-container.mjs +129 -197
  31. package/assets/emit-pack.mjs +92 -136
  32. package/assets/font-config.mjs +19 -27
  33. package/assets/font-sizes.mjs +432 -507
  34. package/assets/glyph-coverage.mjs +170 -214
  35. package/assets/index.mjs +52 -97
  36. package/assets/rasterize.mjs +173 -194
  37. package/assets/svg-loader.mjs +42 -48
  38. package/build.mjs +84 -101
  39. package/cli.mjs +482 -621
  40. package/compile-bin.mjs +24 -36
  41. package/flash.mjs +297 -401
  42. package/hotreload/dev-device.mjs +229 -270
  43. package/hotreload/pack-app.mjs +118 -159
  44. package/hotreload/pack-split.mjs +144 -200
  45. package/hotreload/package-transfer.mjs +128 -131
  46. package/hotreload/protocol.mjs +118 -118
  47. package/hotreload/uploader.mjs +132 -159
  48. package/hotreload/watch-tree.mjs +56 -65
  49. package/pack-container.mjs +93 -123
  50. package/package.json +19 -16
  51. package/persist-transform.mjs +89 -105
  52. package/qjsc-wasm.mjs +47 -72
  53. package/sim/embedded-react.wasm +0 -0
  54. package/sim/index.html +1 -1
  55. package/sim-server.mjs +260 -354
  56. package/src/embedded-react/Alert.mjs +112 -0
  57. package/src/embedded-react/Animated.mjs +412 -0
  58. package/src/embedded-react/{AppRegistry.js → AppRegistry.mjs} +26 -25
  59. package/src/embedded-react/{Button.js → Button.mjs} +29 -53
  60. package/src/embedded-react/{Dimensions.js → Dimensions.mjs} +12 -17
  61. package/src/embedded-react/Easing.mjs +34 -0
  62. package/src/embedded-react/{FlatList.js → FlatList.mjs} +25 -42
  63. package/src/embedded-react/{ImageBackground.js → ImageBackground.mjs} +11 -22
  64. package/src/embedded-react/Keyboard.mjs +82 -0
  65. package/src/embedded-react/{LayoutAnimation.js → LayoutAnimation.mjs} +17 -28
  66. package/src/embedded-react/PanResponder.mjs +256 -0
  67. package/src/embedded-react/{Platform.js → Platform.mjs} +8 -9
  68. package/src/embedded-react/{Pressable.js → Pressable.mjs} +12 -25
  69. package/src/embedded-react/SectionList.mjs +103 -0
  70. package/src/embedded-react/{StyleSheet.js → StyleSheet.mjs} +16 -20
  71. package/src/embedded-react/{TouchableOpacity.js → TouchableOpacity.mjs} +47 -83
  72. package/src/embedded-react/background-image.mjs +321 -0
  73. package/src/embedded-react/{components.js → components.mjs} +1 -3
  74. package/src/embedded-react/{imperative.js → imperative.mjs} +27 -38
  75. package/src/embedded-react/index.d.ts +155 -2
  76. package/src/embedded-react/index.js +26 -19
  77. package/src/embedded-react/layout-anim-config.mjs +85 -0
  78. package/src/embedded-react/{list-child.js → list-child.mjs} +11 -20
  79. package/src/embedded-react/{named-colors.js → named-colors.mjs} +2 -6
  80. package/src/embedded-react/nativeModule.mjs +371 -0
  81. package/src/embedded-react/split-style.mjs +57 -0
  82. package/src/embedded-react/svg-ops.mjs +1075 -0
  83. package/src/embedded-react/{useHostValue.js → useHostValue.mjs} +2 -4
  84. package/src/embedded-react/{usePersistentState.js → usePersistentState.mjs} +34 -38
  85. package/src/embedded-react/{warn-props.js → warn-props.mjs} +32 -39
  86. package/src/host-config.mjs +512 -0
  87. package/src/{native-ui.js → native-ui.mjs} +1 -8
  88. package/src/props.mjs +341 -0
  89. package/src/{renderer.js → renderer.mjs} +30 -44
  90. package/src/embedded-react/Animated.js +0 -440
  91. package/src/embedded-react/Easing.js +0 -39
  92. package/src/embedded-react/PanResponder.js +0 -330
  93. package/src/embedded-react/SectionList.js +0 -146
  94. package/src/embedded-react/layout-anim-config.js +0 -101
  95. package/src/embedded-react/nativeModule.js +0 -462
  96. package/src/embedded-react/split-style.js +0 -58
  97. package/src/embedded-react/svg-ops.js +0 -1295
  98. package/src/host-config.js +0 -548
  99. package/src/props.js +0 -306
package/cli.mjs CHANGED
@@ -14,7 +14,6 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
-
18
17
  // embedded-react — the consumer CLI.
19
18
  //
20
19
  // npx embedded-react dev [entry] [--port 3333]
@@ -22,40 +21,24 @@
22
21
  // Runs the WASM simulator against the app in your current project: bundles your JSX, serves the prebuilt
23
22
  // embedded-react.wasm host page, and hot-reloads on save (useState preserved). No native toolchain — the
24
23
  // .wasm ships prebuilt in this package. See tools/web-sim/README.md.
25
-
26
- import {
27
- copyFileSync,
28
- existsSync,
29
- mkdirSync,
30
- readFileSync,
31
- statSync,
32
- writeFileSync,
33
- } from 'node:fs';
34
- import {fileURLToPath, pathToFileURL} from 'node:url';
35
- import {basename, dirname, relative, resolve} from 'node:path';
36
- import {tmpdir} from 'node:os';
37
- import {buildApp, runDevServer} from './sim-server.mjs';
38
- import {
39
- packVendor,
40
- packApp,
41
- emitBootContainer,
42
- } from './hotreload/pack-split.mjs';
43
- import {runDeviceDevServer} from './hotreload/dev-device.mjs';
44
- import {detectDevicePorts, preferCalloutPath} from './hotreload/uploader.mjs';
45
- import {boardByName, flashSlot, packSlot} from './flash.mjs';
46
-
24
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync, } from 'node:fs';
25
+ import { fileURLToPath, pathToFileURL } from 'node:url';
26
+ import { basename, dirname, relative, resolve } from 'node:path';
27
+ import { tmpdir } from 'node:os';
28
+ import { buildApp, runDevServer } from './sim-server.mjs';
29
+ import { packVendor, packApp, emitBootContainer, } from './hotreload/pack-split.mjs';
30
+ import { runDeviceDevServer } from './hotreload/dev-device.mjs';
31
+ import { detectDevicePorts, preferCalloutPath } from './hotreload/uploader.mjs';
32
+ import { boardByName, flashSlot, packSlot } from './flash.mjs';
47
33
  const PACKAGE_ROOT = dirname(fileURLToPath(import.meta.url));
48
-
49
34
  // QuickJS release the bytecode container targets — MUST match bridges/quickjs/CMakeLists.txt and
50
35
  // ER_QUICKJS_TAG in er_runtime.c (the device loader rejects a mismatch). The wasm that compiles the
51
36
  // bytecode embeds this same QuickJS.
52
37
  const QUICKJS_TAG = 'v0.15.0';
53
-
54
38
  const DEFAULT_PORT = 3333;
55
39
  const BYTES_PER_KILOBYTE = 1024;
56
-
57
40
  function usage() {
58
- console.log(`embedded-react — React Native for embedded MCUs
41
+ console.log(`embedded-react — React Native for embedded MCUs
59
42
 
60
43
  Usage:
61
44
  embedded-react dev [entry] [--port <n>] Run the WASM simulator with hot reload
@@ -96,102 +79,91 @@ Usage:
96
79
  build --aot uses ./App.jsx or ./src/App.jsx. Pass one to override.
97
80
  `);
98
81
  }
99
-
100
82
  /** Locate the package's prebuilt simulator assets (the .wasm ships with this package). */
101
83
  function simDirOrExit() {
102
- const simDir = resolve(PACKAGE_ROOT, 'sim');
103
- if (!existsSync(resolve(simDir, 'embedded-react.wasm'))) {
104
- console.error(
105
- 'The prebuilt simulator (sim/embedded-react.wasm) is missing from this install.',
106
- );
107
- console.error(
108
- 'A published embedded-react package ships it; building from source needs the Emscripten SDK.',
109
- );
110
- process.exit(1);
111
- }
112
- return simDir;
84
+ const simDir = resolve(PACKAGE_ROOT, 'sim');
85
+ if (!existsSync(resolve(simDir, 'embedded-react.wasm'))) {
86
+ console.error('The prebuilt simulator (sim/embedded-react.wasm) is missing from this install.');
87
+ console.error('A published embedded-react package ships it; building from source needs the Emscripten SDK.');
88
+ process.exit(1);
89
+ }
90
+ return simDir;
113
91
  }
114
-
115
92
  const libSrc = () => resolve(PACKAGE_ROOT, 'src/embedded-react/index.js');
116
- const nodePaths = cwd => [
117
- resolve(PACKAGE_ROOT, 'node_modules'),
118
- resolve(cwd, 'node_modules'),
93
+ const nodePaths = (cwd) => [
94
+ resolve(PACKAGE_ROOT, 'node_modules'),
95
+ resolve(cwd, 'node_modules'),
119
96
  ];
120
-
121
97
  /** Resolve the app entry: an explicit arg, else common conventions, else package.json "main"/"source". */
122
98
  function resolveEntry(cwd, explicit) {
123
- if (explicit) {
124
- const entryPath = resolve(cwd, explicit);
125
- if (!existsSync(entryPath)) {
126
- console.error(`Entry not found: ${entryPath}`);
127
- process.exit(1);
99
+ if (explicit) {
100
+ const entryPath = resolve(cwd, explicit);
101
+ if (!existsSync(entryPath)) {
102
+ console.error(`Entry not found: ${entryPath}`);
103
+ process.exit(1);
104
+ }
105
+ return entryPath;
128
106
  }
129
- return entryPath;
130
- }
131
- for (const relativePath of [
132
- 'index.jsx',
133
- 'src/index.jsx',
134
- 'index.tsx',
135
- 'src/index.tsx',
136
- 'App.jsx',
137
- 'src/App.jsx',
138
- ]) {
139
- const entryPath = resolve(cwd, relativePath);
140
- if (existsSync(entryPath)) return entryPath;
141
- }
142
- const packageJsonPath = resolve(cwd, 'package.json');
143
- if (existsSync(packageJsonPath)) {
144
- try {
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;
107
+ for (const relativePath of [
108
+ 'index.jsx',
109
+ 'src/index.jsx',
110
+ 'index.tsx',
111
+ 'src/index.tsx',
112
+ 'App.jsx',
113
+ 'src/App.jsx',
114
+ ]) {
115
+ const entryPath = resolve(cwd, relativePath);
116
+ if (existsSync(entryPath))
117
+ return entryPath;
118
+ }
119
+ const packageJsonPath = resolve(cwd, 'package.json');
120
+ if (existsSync(packageJsonPath)) {
121
+ try {
122
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
123
+ for (const entryField of [packageJson.source, packageJson.main]) {
124
+ if (entryField) {
125
+ const entryPath = resolve(cwd, entryField);
126
+ if (existsSync(entryPath))
127
+ return entryPath;
128
+ }
129
+ }
130
+ }
131
+ catch {
132
+ /* ignore */
150
133
  }
151
- }
152
- } catch {
153
- /* ignore */
154
134
  }
155
- }
156
- console.error(
157
- 'No app entry found. Pass one explicitly: embedded-react dev <entry.jsx>',
158
- );
159
- console.error(
160
- '(looked for ./index.jsx, ./src/index.jsx, … and package.json "main")',
161
- );
162
- process.exit(1);
135
+ console.error('No app entry found. Pass one explicitly: embedded-react dev <entry.jsx>');
136
+ console.error('(looked for ./index.jsx, ./src/index.jsx, … and package.json "main")');
137
+ process.exit(1);
163
138
  }
164
-
165
139
  function optValue(args, flag) {
166
- const flagIndex = args.indexOf(flag);
167
- if (flagIndex < 0) return null;
168
- const value = args[flagIndex + 1];
169
- if (!value || value.startsWith('--')) {
170
- console.error(`Missing value for ${flag}\n`);
171
- usage();
172
- process.exit(1);
173
- }
174
- return {value, index: flagIndex, valueIndex: flagIndex + 1};
140
+ const flagIndex = args.indexOf(flag);
141
+ if (flagIndex < 0)
142
+ return null;
143
+ const value = args[flagIndex + 1];
144
+ if (!value || value.startsWith('--')) {
145
+ console.error(`Missing value for ${flag}\n`);
146
+ usage();
147
+ process.exit(1);
148
+ }
149
+ return { value, index: flagIndex, valueIndex: flagIndex + 1 };
175
150
  }
176
-
177
151
  /** Like optValue, but the value is OPTIONAL: `--flag` alone → {value: null}; `--flag x` → {value: 'x'}. */
178
152
  function optFlagMaybeValue(args, flag) {
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('--');
183
- return {
184
- value: hasValue ? nextArg : null,
185
- index: flagIndex,
186
- valueIndex: hasValue ? flagIndex + 1 : -1,
187
- };
153
+ const flagIndex = args.indexOf(flag);
154
+ if (flagIndex < 0)
155
+ return null;
156
+ const nextArg = args[flagIndex + 1];
157
+ const hasValue = nextArg != null && !nextArg.startsWith('--');
158
+ return {
159
+ value: hasValue ? nextArg : null,
160
+ index: flagIndex,
161
+ valueIndex: hasValue ? flagIndex + 1 : -1,
162
+ };
188
163
  }
189
-
190
164
  /** A token that names a serial port rather than an app entry file (so `--device App.jsx` isn't a port). */
191
- const looksLikeDevicePath = token =>
192
- /^(\/dev\/|com\d|\\\\\.\\)/i.test(token) ||
193
- /(tty|usbmodem|usbserial|cu\.)/i.test(token);
194
-
165
+ const looksLikeDevicePath = (token) => /^(\/dev\/|com\d|\\\\\.\\)/i.test(token) ||
166
+ /(tty|usbmodem|usbserial|cu\.)/i.test(token);
195
167
  /**
196
168
  * Resolve the `--device` port. An explicit path is the universal, board-agnostic mechanism (any serial
197
169
  * port, any board). With no path we auto-detect — but only the ESP32-S3/C3 built-in USB-Serial-JTAG has a
@@ -200,331 +172,242 @@ const looksLikeDevicePath = token =>
200
172
  * it's ambiguous.
201
173
  */
202
174
  async function resolveDevicePortOrExit(explicit) {
203
- if (explicit && explicit !== 'auto') return preferCalloutPath(explicit);
204
-
205
- const {matches, all, serialportMissing} = await detectDevicePorts();
206
- if (serialportMissing) {
207
- console.error(
208
- "✗ on-device hot reload needs the 'serialport' package.\n" +
209
- ' Install it in your project: npm i serialport',
210
- );
211
- process.exit(1);
212
- }
213
- if (matches.length === 1) {
214
- const port = matches[0];
215
- const path = preferCalloutPath(port.path);
216
- console.log(
217
- `✓ auto-detected ESP32 USB-Serial-JTAG at ${path}` +
218
- (port.serialNumber ? ` (SN ${port.serialNumber})` : ''),
219
- );
220
- return path;
221
- }
222
- if (matches.length === 0) {
223
- console.error("✗ couldn't auto-detect a board to hot-reload.");
224
- console.error(
225
- ' Auto-detect only covers the ESP32-S3/C3 built-in USB-Serial-JTAG (USB 303a:1001) — the one',
226
- );
227
- console.error(
228
- ' board with a fixed USB id. For any other board (STM32, RP2040, …) pass the port explicitly:',
229
- );
230
- console.error(' embedded-react dev --device <port>');
231
- if (all.length) {
232
- console.error('\n Serial ports seen (pick yours):');
233
- for (const port of all)
234
- console.error(
235
- ` ${port.path}` +
236
- (port.vendorId && port.productId
237
- ? ` [${port.vendorId}:${port.productId}]`
238
- : '') +
239
- (port.manufacturer ? ` ${port.manufacturer}` : ''),
240
- );
241
- } else {
242
- console.error(
243
- '\n (no serial ports detected at all — is anything connected? is the cable data-capable?)',
244
- );
175
+ if (explicit && explicit !== 'auto')
176
+ return preferCalloutPath(explicit);
177
+ const { matches, all, serialportMissing } = await detectDevicePorts();
178
+ if (serialportMissing) {
179
+ console.error("✗ on-device hot reload needs the 'serialport' package.\n" +
180
+ ' Install it in your project: npm i serialport');
181
+ process.exit(1);
182
+ }
183
+ if (matches.length === 1) {
184
+ const port = matches[0];
185
+ const path = preferCalloutPath(port.path);
186
+ console.log(`✓ auto-detected ESP32 USB-Serial-JTAG at ${path}` +
187
+ (port.serialNumber ? ` (SN ${port.serialNumber})` : ''));
188
+ return path;
245
189
  }
246
- console.error(
247
- '\n On an ESP32, if auto-detect should have worked: use its NATIVE USB port (not the flashing UART),',
248
- );
249
- console.error(
250
- ' and make sure the firmware has on-device hot reload enabled.',
251
- );
190
+ if (matches.length === 0) {
191
+ console.error("✗ couldn't auto-detect a board to hot-reload.");
192
+ console.error(' Auto-detect only covers the ESP32-S3/C3 built-in USB-Serial-JTAG (USB 303a:1001) — the one');
193
+ console.error(' board with a fixed USB id. For any other board (STM32, RP2040, …) pass the port explicitly:');
194
+ console.error(' embedded-react dev --device <port>');
195
+ if (all.length) {
196
+ console.error('\n Serial ports seen (pick yours):');
197
+ for (const port of all)
198
+ console.error(` ${port.path}` +
199
+ (port.vendorId && port.productId
200
+ ? ` [${port.vendorId}:${port.productId}]`
201
+ : '') +
202
+ (port.manufacturer ? ` ${port.manufacturer}` : ''));
203
+ }
204
+ else {
205
+ console.error('\n (no serial ports detected at all — is anything connected? is the cable data-capable?)');
206
+ }
207
+ console.error('\n On an ESP32, if auto-detect should have worked: use its NATIVE USB port (not the flashing UART),');
208
+ console.error(' and make sure the firmware has on-device hot reload enabled.');
209
+ process.exit(1);
210
+ }
211
+ console.error(`✗ found ${matches.length} ESP32 USB-Serial-JTAG ports; pass one explicitly with --device <port>:`);
212
+ for (const port of matches)
213
+ console.error(` ${preferCalloutPath(port.path)}${port.serialNumber ? ` (SN ${port.serialNumber})` : ''}`);
252
214
  process.exit(1);
253
- }
254
- console.error(
255
- `✗ found ${matches.length} ESP32 USB-Serial-JTAG ports; pass one explicitly with --device <port>:`,
256
- );
257
- for (const port of matches)
258
- console.error(
259
- ` ${preferCalloutPath(port.path)}${port.serialNumber ? ` (SN ${port.serialNumber})` : ''}`,
260
- );
261
- process.exit(1);
262
215
  }
263
-
264
216
  async function dev(args) {
265
- const cwd = process.cwd();
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
- }
275
-
276
- // --device [port] → stream the app to a real board over USB on every save (on-device hot reload).
277
- // With no port (or `auto`), the ESP32 USB-Serial-JTAG is auto-detected. Otherwise → the WASM simulator.
278
- if (deviceOption) {
279
- // The token-after --device is normally the port. But `--device App.jsx` means "auto-detect + this
280
- // entry": if the value names an existing file (and isn't a device path), treat it as the entry.
281
- let deviceValue = deviceOption.value;
282
- let entryFromDeviceSlot = null;
283
- if (
284
- deviceValue &&
285
- deviceValue !== 'auto' &&
286
- !looksLikeDevicePath(deviceValue) &&
287
- existsSync(resolve(cwd, deviceValue))
288
- ) {
289
- entryFromDeviceSlot = deviceValue;
290
- deviceValue = null; // fall through to auto-detect
217
+ const cwd = process.cwd();
218
+ const deviceOption = optFlagMaybeValue(args, '--device');
219
+ const aot = args.includes('--aot');
220
+ if (aot && !deviceOption) {
221
+ console.error('--aot only applies to --device: the simulator runs the app as Flow A.\n');
222
+ usage();
223
+ process.exit(1);
291
224
  }
292
- const explicit =
293
- entryFromDeviceSlot ??
294
- args.find(
295
- (arg, argIndex) =>
296
- !arg.startsWith('--') &&
297
- argIndex !== deviceOption.index &&
298
- argIndex !== deviceOption.valueIndex,
299
- );
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;
225
+ // --device [port] → stream the app to a real board over USB on every save (on-device hot reload).
226
+ // With no port (or `auto`), the ESP32 USB-Serial-JTAG is auto-detected. Otherwise → the WASM simulator.
227
+ if (deviceOption) {
228
+ // The token-after --device is normally the port. But `--device App.jsx` means "auto-detect + this
229
+ // entry": if the value names an existing file (and isn't a device path), treat it as the entry.
230
+ let deviceValue = deviceOption.value;
231
+ let entryFromDeviceSlot = null;
232
+ if (deviceValue &&
233
+ deviceValue !== 'auto' &&
234
+ !looksLikeDevicePath(deviceValue) &&
235
+ existsSync(resolve(cwd, deviceValue))) {
236
+ entryFromDeviceSlot = deviceValue;
237
+ deviceValue = null; // fall through to auto-detect
238
+ }
239
+ const explicit = entryFromDeviceSlot ??
240
+ args.find((arg, argIndex) => !arg.startsWith('--') &&
241
+ argIndex !== deviceOption.index &&
242
+ argIndex !== deviceOption.valueIndex);
243
+ if (aot) {
244
+ const appPath = resolveAppComponent(cwd, explicit);
245
+ const device = await resolveDevicePortOrExit(deviceValue);
246
+ await runDeviceDevServer({
247
+ entry: appPath,
248
+ projectRoot: cwd,
249
+ device,
250
+ label: appPath,
251
+ compilePackage: async () => Buffer.from((await compileAppPackage(cwd, appPath)).file.bytes),
252
+ });
253
+ return;
254
+ }
255
+ const simDir = simDirOrExit();
256
+ const entry = resolveEntry(cwd, explicit);
257
+ const device = await resolveDevicePortOrExit(deviceValue);
258
+ await runDeviceDevServer({
259
+ entry,
260
+ projectRoot: cwd,
261
+ libSrc: libSrc(),
262
+ nodePaths: nodePaths(cwd),
263
+ simDir,
264
+ device,
265
+ label: entry,
266
+ });
267
+ return;
313
268
  }
314
-
269
+ const portOption = optValue(args, '--port');
270
+ const consumed = new Set(portOption ? [portOption.index, portOption.valueIndex] : []);
271
+ const explicit = args.find((arg, argIndex) => !arg.startsWith('--') && !consumed.has(argIndex));
315
272
  const simDir = simDirOrExit();
316
273
  const entry = resolveEntry(cwd, explicit);
317
- const device = await resolveDevicePortOrExit(deviceValue);
318
-
319
- await runDeviceDevServer({
320
- entry,
321
- projectRoot: cwd,
322
- libSrc: libSrc(),
323
- nodePaths: nodePaths(cwd),
324
- simDir,
325
- device,
326
- label: entry,
274
+ const port = portOption ? parseInt(portOption.value, 10) : DEFAULT_PORT;
275
+ const outDir = resolve(tmpdir(), 'embedded-react-sim');
276
+ mkdirSync(outDir, { recursive: true });
277
+ await runDevServer({
278
+ entry,
279
+ projectRoot: cwd,
280
+ libSrc: libSrc(),
281
+ nodePaths: nodePaths(cwd),
282
+ indexHtml: resolve(simDir, 'index.html'),
283
+ simDir,
284
+ outDir,
285
+ port,
286
+ label: entry,
327
287
  });
328
- return;
329
- }
330
-
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
- );
338
-
339
- const simDir = simDirOrExit();
340
- const entry = resolveEntry(cwd, explicit);
341
-
342
- const port = portOption ? parseInt(portOption.value, 10) : DEFAULT_PORT;
343
- const outDir = resolve(tmpdir(), 'embedded-react-sim');
344
- mkdirSync(outDir, {recursive: true});
345
-
346
- await runDevServer({
347
- entry,
348
- projectRoot: cwd,
349
- libSrc: libSrc(),
350
- nodePaths: nodePaths(cwd),
351
- indexHtml: resolve(simDir, 'index.html'),
352
- simDir,
353
- outDir,
354
- port,
355
- label: entry,
356
- });
357
288
  }
358
-
359
289
  async function exportApp(args) {
360
- const cwd = process.cwd();
361
- const outIndex = args.indexOf('--out');
362
- const outDir = resolve(
363
- cwd,
364
- outIndex >= 0 ? args[outIndex + 1] : 'sim-export',
365
- );
366
- const explicit = args.find(
367
- (arg, argIndex) =>
368
- !arg.startsWith('--') && (outIndex < 0 || argIndex !== outIndex + 1),
369
- );
370
-
371
- const simDir = simDirOrExit();
372
- const entry = resolveEntry(cwd, explicit);
373
- const publicDir = resolve(outDir, 'public');
374
- mkdirSync(publicDir, {recursive: true});
375
-
376
- // Bundle the app + bake assets into public/, then drop the prebuilt module + host page alongside.
377
- await buildApp({
378
- entry,
379
- projectRoot: cwd,
380
- libSrc: libSrc(),
381
- nodePaths: nodePaths(cwd),
382
- outDir: publicDir,
383
- });
384
- for (const fileName of ['embedded-react.js', 'embedded-react.wasm'])
385
- copyFileSync(resolve(simDir, fileName), resolve(publicDir, fileName));
386
- copyFileSync(resolve(simDir, 'index.html'), resolve(outDir, 'index.html'));
387
-
388
- console.log(
389
- `✓ exported a static playground → ${relative(cwd, outDir) || '.'}/`,
390
- );
391
- console.log(
392
- ` serve it over http (e.g. \`npx serve ${relative(cwd, outDir) || '.'}\`) or deploy the folder to any static host.`,
393
- );
290
+ const cwd = process.cwd();
291
+ const outIndex = args.indexOf('--out');
292
+ const outDir = resolve(cwd, outIndex >= 0 ? args[outIndex + 1] : 'sim-export');
293
+ const explicit = args.find((arg, argIndex) => !arg.startsWith('--') && (outIndex < 0 || argIndex !== outIndex + 1));
294
+ const simDir = simDirOrExit();
295
+ const entry = resolveEntry(cwd, explicit);
296
+ const publicDir = resolve(outDir, 'public');
297
+ mkdirSync(publicDir, { recursive: true });
298
+ // Bundle the app + bake assets into public/, then drop the prebuilt module + host page alongside.
299
+ await buildApp({
300
+ entry,
301
+ projectRoot: cwd,
302
+ libSrc: libSrc(),
303
+ nodePaths: nodePaths(cwd),
304
+ outDir: publicDir,
305
+ });
306
+ for (const fileName of ['embedded-react.js', 'embedded-react.wasm'])
307
+ copyFileSync(resolve(simDir, fileName), resolve(publicDir, fileName));
308
+ copyFileSync(resolve(simDir, 'index.html'), resolve(outDir, 'index.html'));
309
+ console.log(`✓ exported a static playground → ${relative(cwd, outDir) || '.'}/`);
310
+ console.log(` serve it over http (e.g. \`npx serve ${relative(cwd, outDir) || '.'}\`) or deploy the folder to any static host.`);
394
311
  }
395
-
396
312
  /** Resolve the root component file for the AOT compiler (App.jsx), distinct from the registry entry. */
397
313
  function resolveAppComponent(cwd, explicit) {
398
- if (explicit) {
399
- const entryPath = resolve(cwd, explicit);
400
- if (!existsSync(entryPath)) {
401
- console.error(`Entry not found: ${entryPath}`);
402
- process.exit(1);
314
+ if (explicit) {
315
+ const entryPath = resolve(cwd, explicit);
316
+ if (!existsSync(entryPath)) {
317
+ console.error(`Entry not found: ${entryPath}`);
318
+ process.exit(1);
319
+ }
320
+ return entryPath;
403
321
  }
404
- return entryPath;
405
- }
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;
414
- }
415
- console.error(
416
- 'No App component found. Pass one explicitly: embedded-react build --aot <App.jsx>',
417
- );
418
- process.exit(1);
322
+ for (const relativePath of [
323
+ 'App.jsx',
324
+ 'src/App.jsx',
325
+ 'App.tsx',
326
+ 'src/App.tsx',
327
+ ]) {
328
+ const entryPath = resolve(cwd, relativePath);
329
+ if (existsSync(entryPath))
330
+ return entryPath;
331
+ }
332
+ console.error('No App component found. Pass one explicitly: embedded-react build --aot <App.jsx>');
333
+ process.exit(1);
419
334
  }
420
-
421
335
  /**
422
336
  * Compiles the App component with what goes into the build: its package file and its image jobs.
423
337
  * Throws with the reason, so a watch loop can carry on past a bad save.
424
338
  */
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');
433
- const {warnMissingGlyphs} = await import('./assets/glyph-coverage.mjs');
434
- const {analyzeFontSizes, warnFontSizes} =
435
- await import('./assets/font-sizes.mjs');
436
- const appDir = dirname(appPath);
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
- });
451
-
452
- // Optional per-image overrides (same file the JS flows read): assets.config.js
453
- // export default { images: { 'bg': { format: 'rgb565' } } }
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,
469
- }));
470
- for (const job of imageJobs) {
471
- if (!existsSync(job.path)) {
472
- throw new Error(`<Image> asset "${job.name}" not found at ${job.path}`);
339
+ async function compileAppPackage(cwd, appPath, { screens = null, release = false, } = {}) {
340
+ const { compilePackage, bakeSvgArtifacts, packPackage, readNativeFiles } = await import('./aot/compile.mjs');
341
+ const { bakeAssetPackBytes } = await import('./assets/index.mjs');
342
+ const { warnMissingGlyphs } = await import('./assets/glyph-coverage.mjs');
343
+ const { analyzeFontSizes, warnFontSizes } = await import('./assets/font-sizes.mjs');
344
+ const appDir = dirname(appPath);
345
+ const source = readFileSync(appPath, 'utf8');
346
+ // Bake <Svg source> .svg imports → vector artifacts (incl. gradients), then compile with them in hand.
347
+ const svgArtifacts = await bakeSvgArtifacts(source, appDir);
348
+ // A package has every layout the app's breakpoints call for, and --screen <WxH>,<WxH> keeps only those the
349
+ // sizes pick.
350
+ const result = compilePackage(source, basename(dirname(appPath)), {
351
+ filename: appPath,
352
+ svgArtifacts,
353
+ // Native modules and their interfaces in other files and packages, read here so the compile stays pure.
354
+ nativeFiles: readNativeFiles(source, appDir),
355
+ screen: screens?.[0] ?? null, // null without --screen
356
+ screens,
357
+ release,
358
+ });
359
+ // Optional per-image overrides (same file the JS flows read): assets.config.js
360
+ // export default { images: { 'bg': { format: 'rgb565' } } }
361
+ let assetsConfig = {};
362
+ const assetsConfigPath = resolve(cwd, 'assets.config.js');
363
+ if (existsSync(assetsConfigPath))
364
+ assetsConfig =
365
+ (await import(`${pathToFileURL(assetsConfigPath).href}?t=${statSync(assetsConfigPath).mtimeMs}`)).default || {};
366
+ const imageConfig = assetsConfig.images || {};
367
+ const imageJobs = result.images.map(image => ({
368
+ name: image.name,
369
+ path: resolve(appDir, image.importPath),
370
+ format: imageConfig[image.name]?.format,
371
+ }));
372
+ for (const job of imageJobs) {
373
+ if (!existsSync(job.path)) {
374
+ throw new Error(`<Image> asset "${job.name}" not found at ${job.path}`);
375
+ }
473
376
  }
474
- }
475
- // Flow B renders everything in the engine's built-in font (no font imports) — check the app's text
476
- // and its font sizes against what that font actually covers.
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};
377
+ // Flow B renders everything in the engine's built-in font (no font imports) — check the app's text
378
+ // and its font sizes against what that font actually covers.
379
+ warnMissingGlyphs({ source, jsx: true });
380
+ warnFontSizes({ used: analyzeFontSizes(source) });
381
+ const file = packPackage(result, imageJobs.length ? bakeAssetPackBytes({ images: imageJobs }) : undefined);
382
+ return { result, file, imageJobs };
484
383
  }
485
-
486
384
  /**
487
385
  * Flow B (--aot): compile the App component to a Flow B package (app.erpkg) with its assets inside, for the Flow B
488
386
  * runtime to load: for release without its debug table (app.erdbg beside it), and baked as a const array
489
387
  * (app.erpkg.c) to link into the firmware.
490
388
  */
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,
515
- );
516
- console.log(
517
- `✓ Flow B package → ${displayDir}/${name} (${release ? 'release' : 'debug'}, ${imageJobs.length} image(s))`,
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'));
389
+ async function buildAot(cwd, explicit, outDir, screens, { release = false, bake = false } = {}) {
390
+ const { bakePackage, resourceReport } = await import('./aot/compile.mjs');
391
+ const appPath = resolveAppComponent(cwd, explicit);
392
+ let compiled;
393
+ try {
394
+ compiled = await compileAppPackage(cwd, appPath, { screens, release });
395
+ }
396
+ catch (error) {
397
+ console.error(error && error.aotLoc ? error.message : error?.message || String(error));
398
+ process.exit(1);
399
+ }
400
+ const { result, file, imageJobs } = compiled;
401
+ const displayDir = relative(cwd, outDir) || '.';
402
+ const name = bake ? 'app.erpkg.c' : 'app.erpkg';
403
+ writeFileSync(resolve(outDir, name), bake ? bakePackage(file.bytes) : file.bytes);
404
+ console.log(`✓ Flow B package → ${displayDir}/${name} (${release ? 'release' : 'debug'}, ${imageJobs.length} image(s))`);
405
+ if (release) {
406
+ writeFileSync(resolve(outDir, 'app.erdbg'), result.debug);
407
+ console.log(` Debug table → ${displayDir}/app.erdbg (${result.debug.length} B), to map a fault back to the source`);
408
+ }
409
+ console.log(resourceReport(result, file).join('\n'));
526
410
  }
527
-
528
411
  /**
529
412
  * Flow A (default): bundle → QuickJS bytecode (via the prebuilt wasm) + baked assets → app.erpkg.
530
413
  *
@@ -535,249 +418,227 @@ async function buildAot(
535
418
  * artifacts keep booting unchanged.
536
419
  */
537
420
  async function buildContainer(cwd, explicit, outDir) {
538
- const simDir = simDirOrExit();
539
- const entry = resolveEntry(cwd, explicit);
540
- const librarySource = libSrc();
541
- const paths = nodePaths(cwd);
542
-
543
- // Release artifact: strip the embedded source text + debug tables from the bytecode (~8x smaller
544
- // erpkg; stack traces lose line numbers). The dev loop (`embedded-react dev`) keeps them.
545
- const vendor = await packVendor({
546
- libSrc: librarySource,
547
- nodePaths: paths,
548
- simDir,
549
- strip: true,
550
- });
551
- const app = await packApp({
552
- entry,
553
- projectRoot: cwd,
554
- libSrc: librarySource,
555
- nodePaths: paths,
556
- simDir,
557
- strip: true,
558
- });
559
- const container = await emitBootContainer({
560
- vendorBytecode: vendor.bytecode,
561
- appBytecode: app.bytecode,
562
- assetPack: app.assetPack,
563
- });
564
-
565
- const outPath = resolve(outDir, 'app.erpkg');
566
- writeFileSync(outPath, container);
567
- const kb = byteCount => `${(byteCount / BYTES_PER_KILOBYTE).toFixed(1)} KB`;
568
- console.log(
569
- `✓ Flow A → ${relative(cwd, outPath) || 'app.erpkg'} (${kb(container.length)}; qjs ${QUICKJS_TAG}, ` +
570
- `vendor ${kb(vendor.bytecodeLen)} + app ${kb(app.bytecodeLen)}` +
571
- (app.assetsLen ? `, assets ${kb(app.assetsLen)}` : '') +
572
- ')',
573
- );
574
- console.log(
575
- " Upload app.erpkg to your device's config region (er_runtime_load_container), or run it on the desktop host.",
576
- );
577
- console.log(
578
- ' Tip: `embedded-react dev --device <port>` hot-reloads this app live over USB on every save.',
579
- );
421
+ const simDir = simDirOrExit();
422
+ const entry = resolveEntry(cwd, explicit);
423
+ const librarySource = libSrc();
424
+ const paths = nodePaths(cwd);
425
+ // Release artifact: strip the embedded source text + debug tables from the bytecode (~8x smaller
426
+ // erpkg; stack traces lose line numbers). The dev loop (`embedded-react dev`) keeps them.
427
+ const vendor = await packVendor({
428
+ libSrc: librarySource,
429
+ nodePaths: paths,
430
+ simDir,
431
+ strip: true,
432
+ });
433
+ const app = await packApp({
434
+ entry,
435
+ projectRoot: cwd,
436
+ libSrc: librarySource,
437
+ nodePaths: paths,
438
+ simDir,
439
+ strip: true,
440
+ });
441
+ const container = await emitBootContainer({
442
+ vendorBytecode: vendor.bytecode,
443
+ appBytecode: app.bytecode,
444
+ assetPack: app.assetPack,
445
+ });
446
+ const outPath = resolve(outDir, 'app.erpkg');
447
+ writeFileSync(outPath, container);
448
+ const kb = (byteCount) => `${(byteCount / BYTES_PER_KILOBYTE).toFixed(1)} KB`;
449
+ console.log(`✓ Flow A → ${relative(cwd, outPath) || 'app.erpkg'} (${kb(container.length)}; qjs ${QUICKJS_TAG}, ` +
450
+ `vendor ${kb(vendor.bytecodeLen)} + app ${kb(app.bytecodeLen)}` +
451
+ (app.assetsLen ? `, assets ${kb(app.assetsLen)}` : '') +
452
+ ')');
453
+ console.log(" Upload app.erpkg to your device's config region (er_runtime_load_container), or run it on the desktop host.");
454
+ console.log(' Tip: `embedded-react dev --device <port>` hot-reloads this app live over USB on every save.');
580
455
  }
581
-
582
456
  /**
583
457
  * `embedded-react build [--aot [--release] [--bake]] [entry] [--out dir] [--screen WxH[,WxH…]]` — produce the
584
458
  * device artifact.
585
459
  */
586
460
  async function build(args) {
587
- const cwd = process.cwd();
588
- const aot = args.includes('--aot');
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) {
606
- if (!aot) {
607
- console.error(
608
- '--screen only applies to --aot (Flow A reads the panel size from the host at runtime).\n',
609
- );
610
- usage();
611
- process.exit(1);
461
+ const cwd = process.cwd();
462
+ const aot = args.includes('--aot');
463
+ const release = args.includes('--release');
464
+ const bake = args.includes('--bake');
465
+ for (const flag of ['--release', '--bake']) {
466
+ if (args.includes(flag) && !aot) {
467
+ console.error(`${flag} only applies to --aot.\n`);
468
+ usage();
469
+ process.exit(1);
470
+ }
612
471
  }
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)) {
618
- console.error(
619
- `--screen expects <width>x<height> (e.g. --screen 240x320), got: ${screenList ?? '(nothing)'}\n`,
620
- );
621
- usage();
622
- process.exit(1);
472
+ const outIndex = args.indexOf('--out');
473
+ const outDir = resolve(cwd, outIndex >= 0 ? args[outIndex + 1] : 'dist');
474
+ // --screen <WxH> (AOT only): the panels to keep layouts for, comma-separated. Optional: a package has every
475
+ // layout without it. Flow A reads the screen from the host at runtime.
476
+ const screenIndex = args.indexOf('--screen');
477
+ let screens = null;
478
+ if (screenIndex >= 0) {
479
+ if (!aot) {
480
+ console.error('--screen only applies to --aot (Flow A reads the panel size from the host at runtime).\n');
481
+ usage();
482
+ process.exit(1);
483
+ }
484
+ const screenList = args[screenIndex + 1];
485
+ const sizes = (screenList ?? '')
486
+ .split(',')
487
+ .map(size => /^([1-9]\d*)x([1-9]\d*)$/i.exec(size));
488
+ if (!screenList || sizes.some(size => !size)) {
489
+ console.error(`--screen expects <width>x<height> (e.g. --screen 240x320), got: ${screenList ?? '(nothing)'}\n`);
490
+ usage();
491
+ process.exit(1);
492
+ }
493
+ screens = sizes.map(size => ({
494
+ width: Number(size[1]),
495
+ height: Number(size[2]),
496
+ }));
623
497
  }
624
- screens = sizes.map(size => ({
625
- width: Number(size[1]),
626
- height: Number(size[2]),
627
- }));
628
- }
629
-
630
- // Consume the flag VALUES so they aren't mistaken for the entry (which is a bare, non-`--` token).
631
- const consumed = new Set();
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
- );
637
-
638
- mkdirSync(outDir, {recursive: true});
639
- if (aot) await buildAot(cwd, explicit, outDir, screens, {release, bake});
640
- else await buildContainer(cwd, explicit, outDir);
498
+ // Consume the flag VALUES so they aren't mistaken for the entry (which is a bare, non-`--` token).
499
+ const consumed = new Set();
500
+ if (outIndex >= 0)
501
+ consumed.add(outIndex + 1);
502
+ if (screenIndex >= 0)
503
+ consumed.add(screenIndex + 1);
504
+ const explicit = args.find((arg, argIndex) => !arg.startsWith('--') && !consumed.has(argIndex));
505
+ mkdirSync(outDir, { recursive: true });
506
+ if (aot)
507
+ await buildAot(cwd, explicit, outDir, screens, { release, bake });
508
+ else
509
+ await buildContainer(cwd, explicit, outDir);
641
510
  }
642
-
643
511
  /** Reads the package a `pack` or `flash` names, or dist/app.erpkg; exits saying how to build one when it's missing. */
644
512
  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);
513
+ const path = resolve(cwd, explicit ?? 'dist/app.erpkg');
514
+ if (!existsSync(path)) {
515
+ console.error(`No package at ${path}. Build one with: embedded-react build --aot`);
516
+ process.exit(1);
517
+ }
518
+ return readFileSync(path);
653
519
  }
654
-
655
520
  /** The bare arguments, once the values of the listed flags are set aside. */
656
521
  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
- );
522
+ const consumed = new Set();
523
+ for (const flag of flagsWithValues) {
524
+ const flagIndex = args.indexOf(flag);
525
+ if (flagIndex >= 0)
526
+ consumed.add(flagIndex + 1);
527
+ }
528
+ return args.filter((arg, argIndex) => !arg.startsWith('--') && !consumed.has(argIndex));
665
529
  }
666
-
667
530
  /** `embedded-react pack [package] --board <name> [--slot a|b] [--sequence n] [--out dir]` */
668
531
  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
- }
532
+ const cwd = process.cwd();
533
+ const boardName = optValue(args, '--board')?.value;
534
+ const outDir = resolve(cwd, optValue(args, '--out')?.value ?? 'dist');
535
+ const sequence = Number(optValue(args, '--sequence')?.value ?? 1);
536
+ try {
537
+ const board = boardByName(boardName);
538
+ const [explicit] = bareArgs(args, [
539
+ '--board',
540
+ '--slot',
541
+ '--sequence',
542
+ '--out',
543
+ ]);
544
+ mkdirSync(outDir, { recursive: true });
545
+ const packed = packSlot({
546
+ packageBytes: readPackageOrExit(cwd, explicit),
547
+ board,
548
+ boardName,
549
+ slotName: optValue(args, '--slot')?.value,
550
+ sequence,
551
+ outDir,
552
+ });
553
+ console.log(`✓ Slot ${packed.slot}, sequence ${packed.sequence} → ${relative(cwd, packed.file)}, for flash address 0x${packed.address.toString(16)}`);
554
+ }
555
+ catch (error) {
556
+ console.error(error.message);
557
+ process.exit(1);
558
+ }
697
559
  }
698
-
699
560
  /** `embedded-react flash [package] --board <name> [--port p]` */
700
561
  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
- }
562
+ const cwd = process.cwd();
563
+ const boardName = optValue(args, '--board')?.value;
564
+ try {
565
+ const board = boardByName(boardName);
566
+ const [explicit] = bareArgs(args, ['--board', '--port']);
567
+ const written = flashSlot({
568
+ packageBytes: readPackageOrExit(cwd, explicit),
569
+ board,
570
+ port: optValue(args, '--port')?.value,
571
+ log: line => console.log(line),
572
+ });
573
+ console.log(`✓ Package written to slot ${written.slot}, sequence ${written.sequence}. The board runs it at its next boot if it passes verification` +
574
+ (written.lastGood
575
+ ? `, and slot ${written.lastGood} stays as the last good package.`
576
+ : '.'));
577
+ }
578
+ catch (error) {
579
+ console.error(error.message);
580
+ process.exit(1);
581
+ }
722
582
  }
723
-
724
583
  /** `embedded-react native-header <package or file> [--out dir]` */
725
584
  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
- );
585
+ const cwd = process.cwd();
586
+ const outDir = resolve(cwd, optValue(args, '--out')?.value ?? '.');
587
+ const [target] = bareArgs(args, ['--out']);
588
+ if (!target) {
589
+ console.error('Pass the package or the .ts file that declares the modules.\n');
590
+ usage();
591
+ process.exit(1);
592
+ }
593
+ const { nativeHeaders, readModuleFile } = await import('./aot/compile.mjs');
594
+ let shownFile = target;
595
+ try {
596
+ const { path, source, files } = readModuleFile(target, cwd);
597
+ shownFile = relative(cwd, path);
598
+ const headers = nativeHeaders(source, files);
599
+ mkdirSync(outDir, { recursive: true });
600
+ for (const header of headers) {
601
+ writeFileSync(resolve(outDir, header.file), header.text);
602
+ console.log(`✓ ${header.module} → ${relative(cwd, resolve(outDir, header.file))}`);
603
+ }
604
+ }
605
+ catch (error) {
606
+ const where = error?.aotLoc
607
+ ? `${shownFile}:${error.aotLoc.line}:${error.aotLoc.column + 1}: `
608
+ : '';
609
+ console.error(where + (error?.message || String(error)));
610
+ if (error?.aotHint)
611
+ console.error(` ${error.aotHint}`);
612
+ process.exit(1);
748
613
  }
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
614
  }
758
-
759
615
  const [command, ...commandArgs] = process.argv.slice(2);
760
616
  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
- ) {
778
- usage();
779
- } else {
780
- console.error(`Unknown command: ${command}\n`);
781
- usage();
782
- process.exit(1);
617
+ await dev(commandArgs);
618
+ }
619
+ else if (command === 'export') {
620
+ await exportApp(commandArgs);
621
+ }
622
+ else if (command === 'build') {
623
+ await build(commandArgs);
624
+ }
625
+ else if (command === 'pack') {
626
+ pack(commandArgs);
627
+ }
628
+ else if (command === 'flash') {
629
+ flash(commandArgs);
630
+ }
631
+ else if (command === 'native-header') {
632
+ await nativeHeader(commandArgs);
633
+ }
634
+ else if (!command ||
635
+ command === '--help' ||
636
+ command === '-h' ||
637
+ command === 'help') {
638
+ usage();
639
+ }
640
+ else {
641
+ console.error(`Unknown command: ${command}\n`);
642
+ usage();
643
+ process.exit(1);
783
644
  }