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