embedded-react 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +8 -3
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +180 -90
  5. package/aot/compiler/animations.mjs +568 -317
  6. package/aot/compiler/boot.mjs +97 -35
  7. package/aot/compiler/branch-merge.mjs +4 -3
  8. package/aot/compiler/check.mjs +70 -18
  9. package/aot/compiler/collect.mjs +787 -288
  10. package/aot/compiler/contexts.mjs +391 -0
  11. package/aot/compiler/control-flow.mjs +439 -268
  12. package/aot/compiler/custom-hooks.mjs +686 -0
  13. package/aot/compiler/diagnostics.mjs +22 -25
  14. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  15. package/aot/compiler/elements/button.mjs +182 -0
  16. package/aot/compiler/elements/dial.mjs +91 -77
  17. package/aot/compiler/elements/flat-list.mjs +24 -22
  18. package/aot/compiler/elements/image-background.mjs +76 -0
  19. package/aot/compiler/elements/image.mjs +52 -50
  20. package/aot/compiler/elements/modal.mjs +31 -30
  21. package/aot/compiler/elements/props.mjs +61 -26
  22. package/aot/compiler/elements/rewrite.mjs +118 -0
  23. package/aot/compiler/elements/section-list.mjs +370 -0
  24. package/aot/compiler/elements/switch.mjs +42 -34
  25. package/aot/compiler/elements/text-input.mjs +34 -32
  26. package/aot/compiler/expressions.mjs +1685 -392
  27. package/aot/compiler/handlers.mjs +2029 -547
  28. package/aot/compiler/helper-values.mjs +312 -0
  29. package/aot/compiler/ir/functions.mjs +11 -1
  30. package/aot/compiler/ir/nodes.mjs +43 -4
  31. package/aot/compiler/ir/reads.mjs +223 -22
  32. package/aot/compiler/ir/text.mjs +5 -1
  33. package/aot/compiler/ir/types.mjs +26 -14
  34. package/aot/compiler/ir/vectors.mjs +5 -1
  35. package/aot/compiler/kept-states.mjs +177 -0
  36. package/aot/compiler/keyboard.mjs +17 -7
  37. package/aot/compiler/list-items.mjs +226 -0
  38. package/aot/compiler/list-order.mjs +586 -0
  39. package/aot/compiler/list-split.mjs +259 -0
  40. package/aot/compiler/loops.mjs +582 -0
  41. package/aot/compiler/lower.mjs +246 -111
  42. package/aot/compiler/native-files.mjs +439 -0
  43. package/aot/compiler/native-header.mjs +335 -0
  44. package/aot/compiler/native-modules.mjs +1173 -0
  45. package/aot/compiler/nodes.mjs +195 -172
  46. package/aot/compiler/options.mjs +37 -31
  47. package/aot/compiler/out.mjs +32 -23
  48. package/aot/compiler/package/animations.mjs +779 -0
  49. package/aot/compiler/package/arena.mjs +252 -0
  50. package/aot/compiler/package/assemble.mjs +175 -0
  51. package/aot/compiler/package/bytecode.mjs +315 -0
  52. package/aot/compiler/package/checks.mjs +1026 -0
  53. package/aot/compiler/package/codegen.mjs +2168 -0
  54. package/aot/compiler/package/enums.mjs +148 -0
  55. package/aot/compiler/package/format.mjs +771 -0
  56. package/aot/compiler/package/layouts.mjs +136 -0
  57. package/aot/compiler/package/lower.mjs +2103 -0
  58. package/aot/compiler/package/props.mjs +118 -0
  59. package/aot/compiler/package/string-caps.mjs +515 -0
  60. package/aot/compiler/package/tables.mjs +127 -0
  61. package/aot/compiler/package/vectors.mjs +502 -0
  62. package/aot/compiler/package/writer.mjs +686 -0
  63. package/aot/compiler/pan-responder.mjs +69 -61
  64. package/aot/compiler/parse.mjs +23 -21
  65. package/aot/compiler/record-shapes.mjs +246 -0
  66. package/aot/compiler/records.mjs +654 -0
  67. package/aot/compiler/reducers.mjs +272 -0
  68. package/aot/compiler/static-eval.mjs +340 -30
  69. package/aot/compiler/style-text.mjs +178 -174
  70. package/aot/compiler/svg.mjs +480 -251
  71. package/aot/compiler/switch-cases.mjs +198 -0
  72. package/aot/compiler/tagged-records.mjs +450 -0
  73. package/aot/compiler/typing.mjs +307 -0
  74. package/aot/compiler/updaters.mjs +320 -0
  75. package/aot/compiler/window-dimensions.mjs +94 -0
  76. package/aot/compiler/worked-values.mjs +319 -0
  77. package/aot/demo-file.mjs +30 -0
  78. package/aot/screenshot-smoke.mjs +54 -40
  79. package/aot/style-map.mjs +152 -92
  80. package/assets/bake-font.mjs +123 -77
  81. package/assets/bake-image.mjs +39 -22
  82. package/assets/bake-svg.mjs +361 -262
  83. package/assets/build-builtin-font.mjs +11 -7
  84. package/assets/emit-c.mjs +77 -58
  85. package/assets/emit-container.mjs +123 -37
  86. package/assets/emit-pack.mjs +77 -67
  87. package/assets/font-config.mjs +9 -6
  88. package/assets/font-sizes.mjs +163 -123
  89. package/assets/glyph-coverage.mjs +74 -54
  90. package/assets/index.mjs +31 -9
  91. package/assets/rasterize.mjs +126 -99
  92. package/assets/svg-loader.mjs +8 -8
  93. package/build.mjs +23 -13
  94. package/cli.mjs +402 -172
  95. package/compile-bin.mjs +3 -3
  96. package/flash.mjs +537 -0
  97. package/hotreload/dev-device.mjs +90 -33
  98. package/hotreload/pack-app.mjs +55 -43
  99. package/hotreload/pack-split.mjs +62 -64
  100. package/hotreload/package-transfer.mjs +175 -0
  101. package/hotreload/protocol.mjs +50 -37
  102. package/hotreload/uploader.mjs +38 -27
  103. package/hotreload/watch-tree.mjs +19 -19
  104. package/pack-container.mjs +37 -21
  105. package/package.json +7 -8
  106. package/persist-transform.mjs +34 -28
  107. package/qjsc-wasm.mjs +25 -14
  108. package/sim/embedded-react.cjs +1 -1
  109. package/sim/embedded-react.js +1 -1
  110. package/sim/embedded-react.wasm +0 -0
  111. package/sim/index.html +94 -85
  112. package/sim-server.mjs +113 -94
  113. package/src/embedded-react/Animated.js +24 -24
  114. package/src/embedded-react/Dimensions.js +37 -0
  115. package/src/embedded-react/Easing.js +1 -1
  116. package/src/embedded-react/FlatList.js +3 -3
  117. package/src/embedded-react/LayoutAnimation.js +8 -5
  118. package/src/embedded-react/PanResponder.js +75 -71
  119. package/src/embedded-react/Pressable.js +2 -8
  120. package/src/embedded-react/SectionList.js +7 -9
  121. package/src/embedded-react/StyleSheet.js +4 -3
  122. package/src/embedded-react/TouchableOpacity.js +13 -8
  123. package/src/embedded-react/index.d.ts +88 -8
  124. package/src/embedded-react/index.js +2 -0
  125. package/src/embedded-react/layout-anim-config.js +10 -4
  126. package/src/embedded-react/list-child.js +5 -5
  127. package/src/embedded-react/named-colors.js +1 -1
  128. package/src/embedded-react/nativeModule.js +462 -0
  129. package/src/embedded-react/split-style.js +11 -11
  130. package/src/embedded-react/svg-ops.js +760 -593
  131. package/src/embedded-react/useHostValue.js +3 -3
  132. package/src/embedded-react/usePersistentState.js +6 -6
  133. package/src/embedded-react/warn-props.js +1 -1
  134. package/src/host-config.js +60 -53
  135. package/src/props.js +49 -41
  136. package/src/renderer.js +7 -4
  137. package/aot/compiler/assemble.mjs +0 -944
  138. package/aot/compiler/c/animations.mjs +0 -436
  139. package/aot/compiler/c/boot.mjs +0 -127
  140. package/aot/compiler/c/expressions.mjs +0 -270
  141. package/aot/compiler/c/functions.mjs +0 -268
  142. package/aot/compiler/c/keyboard.mjs +0 -96
  143. package/aot/compiler/c/nodes.mjs +0 -303
  144. package/aot/compiler/c/pan-responder.mjs +0 -136
  145. package/aot/compiler/c/statements.mjs +0 -319
  146. package/aot/compiler/c/text.mjs +0 -83
  147. package/aot/compiler/c/vectors.mjs +0 -381
  148. package/aot/compiler/c-syntax.mjs +0 -127
package/NOTICE CHANGED
@@ -47,6 +47,11 @@ under their own respective licenses and copyrights:
47
47
  Licensed under the MIT License.
48
48
  Used by the Flow A bridge to drive the native engine.
49
49
 
50
+ The float-to-text routine in runtime/erb_float.c follows the Ryu algorithm
51
+ (Ulf Adams, "Ryu: Fast Float-to-String Conversion", PLDI 2018) and the
52
+ structure of its reference implementation (https://github.com/ulfjack/ryu),
53
+ Copyright 2018 Ulf Adams, licensed under the Apache License, Version 2.0.
54
+
50
55
  The embedded-react public API (e.g. the View / Text / Pressable / Animated /
51
56
  StyleSheet modules under packages/embedded-react/src/embedded-react/) is an original,
52
57
  independent reimplementation inspired by the React Native API surface. It is not
package/README.md CHANGED
@@ -36,9 +36,14 @@ The package is the React Native analog: hooks come from `react`, everything else
36
36
  | Command | What it does |
37
37
  |---|---|
38
38
  | `npx embedded-react dev` | Runs your app in the browser simulator with hot reload; the engine `.wasm` ships prebuilt, so there is no native toolchain |
39
- | `npx embedded-react dev --device` | The same, streamed to a connected board over USB (a firmware built with hot reload) |
39
+ | `npx embedded-react dev --device` | The same, streamed to a connected board over USB (a firmware built with hot reload). `--aot` sends Flow B packages |
40
40
  | `npx embedded-react build` | The Flow A device artifact, `dist/app.erpkg` (bytecode + baked assets + CRC) |
41
- | `npx embedded-react build --aot --screen WxH` | The Flow B artifact, `app.gen.c` + `assets.generated.c`, to compile into firmware |
41
+ | `npx embedded-react build --aot` | A Flow B package, `dist/app.erpkg`, for the Flow B runtime to load. State, handlers, timers, effects, lists, animations, PanResponder, `<Svg>` and the keyboard config. It holds every layout the app's breakpoints call for, and `--screen 240x320,320x240` keeps only the ones those sizes pick |
42
+ | `npx embedded-react build --aot --release` | A Flow B package for release, without its debug table, which goes beside it as `dist/app.erdbg` |
43
+ | `npx embedded-react build --aot --bake` | A Flow B package as a C array, `dist/app.erpkg.c`, to link into firmware with no spare partition |
44
+ | `npx embedded-react flash --board NAME` | Writes `dist/app.erpkg` to the board's staging slot, through `esptool` or `picotool`. The last good package stays until the new one passes verification |
45
+ | `npx embedded-react pack --board NAME` | Writes a slot's image to a file, as a UF2 on the RP2040, for a factory line or a board that isn't attached |
46
+ | `npx embedded-react native-header PACKAGE --out DIR` | Writes a C header for each native module a device package or `.ts` file declares, for the firmware to build against |
42
47
  | `npx embedded-react export` | A self-contained static copy of the simulator with your app, for any static host |
43
48
 
44
49
  ## Where to read more
@@ -67,7 +72,7 @@ build one of the apps in `demos/` against the in-repo library, `npm test` runs t
67
72
  ```
68
73
  src/embedded-react/ the public package surface (components, StyleSheet, Animated, PanResponder, hooks)
69
74
  src/host-config.js the react-reconciler host config → NativeUI.* (the C bridge)
70
- aot/ the Flow B JSX→C compiler
75
+ aot/ the Flow B JSX→package compiler
71
76
  assets/ build-time bakers: images, fonts, SVG, the ERPK container writer
72
77
  cli.mjs, sim-server.mjs the `embedded-react` CLI and the shared simulator dev server
73
78
  sim/ the prebuilt engine .wasm the simulator runs
@@ -0,0 +1,116 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /*
17
+ * Flow A's esbuild loader for an app's own files. It gives each nativeModule() call its methods' signatures, which
18
+ * the bundle's erased types can't, and in the simulators its mock, then runs the bundler's own transform when it has
19
+ * one. esbuild runs one onLoad per file, so a bundler that transforms the app's files calls this from its own, and
20
+ * loadDependencyFile for every other file, since a package may declare native modules too.
21
+ */
22
+ /*----------------------------------------------------------------------------------------------------------------------
23
+ - Imports
24
+ ---------------------------------------------------------------------------------------------------------------------*/
25
+ import { existsSync, readFileSync } from 'node:fs';
26
+ import { dirname, relative } from 'node:path';
27
+ /*----------------------------------------------------------------------------------------------------------------------
28
+ - Implementation
29
+ ---------------------------------------------------------------------------------------------------------------------*/
30
+ /**
31
+ * esbuild's loader for one of the app's own files.
32
+ *
33
+ * @param path The file.
34
+ * @param transform The bundler's own transform, if it has one.
35
+ * @param options `mocks` for the simulators: each native module runs its mock (`sensors.mock.ts` beside its
36
+ * interface) instead of the firmware's.
37
+ *
38
+ * @returns What esbuild loads, or undefined to let esbuild read the file itself.
39
+ */
40
+ export async function loadAppFile(path, transform, options = {}) {
41
+ const source = readFileSync(path, 'utf8');
42
+ let contents = source;
43
+ // A mock added later rebuilds the app.
44
+ const watchFiles = [];
45
+ if (/\bnativeModule\b/.test(source)) {
46
+ const { addNativeSignatures } = await import('./compiler/native-modules.mjs');
47
+ const { nativeMockFiles, readNativeFiles } = await import('./compiler/native-files.mjs');
48
+ try {
49
+ let mocks;
50
+ if (options.mocks) {
51
+ mocks = new Map();
52
+ for (const [name, candidates] of nativeMockFiles(source, dirname(path))) {
53
+ watchFiles.push(...candidates);
54
+ const found = candidates.find(candidate => existsSync(candidate));
55
+ mocks.set(name, found
56
+ ? './' + relative(dirname(path), found).replace(/\\/g, '/')
57
+ : null);
58
+ }
59
+ }
60
+ contents = addNativeSignatures(source, readNativeFiles(source, dirname(path)), mocks);
61
+ }
62
+ catch (error) {
63
+ const aotError = error;
64
+ // A syntax error is esbuild's to report.
65
+ if (aotError.code !== 'BABEL_PARSER_SYNTAX_ERROR') {
66
+ if (!aotError.message?.startsWith('AOT:'))
67
+ throw error;
68
+ return {
69
+ errors: [
70
+ {
71
+ text: aotError.message.replace(/^AOT: /, ''),
72
+ location: aotError.aotLoc
73
+ ? {
74
+ file: path,
75
+ line: aotError.aotLoc.line,
76
+ column: aotError.aotLoc.column,
77
+ }
78
+ : null,
79
+ notes: aotError.aotHint ? [{ text: aotError.aotHint }] : [],
80
+ },
81
+ ],
82
+ };
83
+ }
84
+ }
85
+ }
86
+ if (transform) {
87
+ contents = transform(contents);
88
+ }
89
+ else if (contents === source) {
90
+ return undefined;
91
+ }
92
+ return {
93
+ contents,
94
+ loader: /\.[cm]?tsx$/.test(path)
95
+ ? 'tsx'
96
+ : /\.[cm]?ts$/.test(path)
97
+ ? 'ts'
98
+ : 'jsx',
99
+ ...(watchFiles.length ? { watchFiles } : {}),
100
+ };
101
+ }
102
+ /**
103
+ * esbuild's loader for a file that isn't the app's own: a package's .ts file that declares native modules gets their
104
+ * signatures, and in the simulators their mocks, as the app's own files do.
105
+ *
106
+ * @param path The file.
107
+ * @param options `mocks` for the simulators (see loadAppFile).
108
+ *
109
+ * @returns What esbuild loads, or undefined to let esbuild read the file itself.
110
+ */
111
+ export async function loadDependencyFile(path, options = {}) {
112
+ if (!/\.[cm]?tsx?$/.test(path) || /\.d\.[cm]?ts$/.test(path)) {
113
+ return undefined;
114
+ }
115
+ return loadAppFile(path, undefined, options);
116
+ }
package/aot/compile.mjs CHANGED
@@ -14,41 +14,40 @@
14
14
  * limitations under the License.
15
15
  */
16
16
  /*
17
- * `npm run aot [demo]` — the Flow B ahead-of-time compiler (vertical slice).
17
+ * `npm run aot [demo]` — the Flow B ahead-of-time compiler.
18
18
  *
19
- * Compiles a demo's JSX straight to C against er_scene.h: no QuickJS, no JS at runtime. The generated
20
- * app.gen.c builds the engine node tree directly and wires state + events, so it fits an MCU with only
19
+ * Compiles a demo's JSX to a package (dist/app.erpkg) that the Flow B runtime verifies and runs: no QuickJS, no JS
20
+ * at runtime. The program builds the engine node tree and wires state + events, so it fits an MCU with only
21
21
  * internal RAM.
22
22
  *
23
23
  * Supported subset (grows demo by demo; unsupported syntax throws "AOT: ..."):
24
24
  * - View / Text / Pressable / TouchableOpacity / Image / ScrollView elements
25
25
  * - StyleSheet + inline styles → ERProps (static values)
26
26
  * - text with literal + {interpolation} segments (interpolations may reference state)
27
- * - useState(initial) → C state; on* handlers (onPress/onPressIn/onPressOut/onLongPress) → C functions
28
- * - setState(value) and setState(prev => expr); a small C expression subset (literals, identifiers,
27
+ * - useState(initial) → state slots; on* handlers (onPress/onPressIn/onPressOut/onLongPress) → functions
28
+ * - setState(value) and setState(prev => expr); a small expression subset (literals, identifiers,
29
29
  * + - * / %, comparisons, ?:)
30
30
  *
31
31
  * The compiler tracks which nodes depend on which state, so a state change re-sets ONLY the dependent
32
- * nodes (er_node_set_props) — no diffing, no reconciler. See the root README (Flow B).
32
+ * nodes — no diffing, no reconciler. See the root README (Flow B).
33
33
  *
34
34
  * npm run aot # default demo (thermostat) — but use a minimal demo for the slice
35
35
  * npm run aot -- watch-face # a specific demo by folder name
36
+ * npm run aot -- <demo> --screen 240x320 # the panels the package keeps layouts for
36
37
  *
37
- * This file is the entry: compileSource(src) compiles a source string (pure, so it can be unit-tested on
38
- * inline JSX), and the CLI at the bottom reads a demo's App.jsx and writes dist/app.gen.{c,h}. The
38
+ * This file is the entry: compilePackage(src) compiles a source string (pure, so it can be unit-tested on
39
+ * inline JSX), and the CLI at the bottom reads a demo's App.jsx and writes dist/app.erpkg. The
39
40
  * compiler itself lives in compiler/, one module per stage. The pipeline: parse the App.jsx → collect
40
41
  * the module's component, state, hooks & refs → lower each piece (expressions, styles/text, handlers,
41
- * nodes) → write the lowered app as app.gen.c.
42
+ * nodes) → widen the slots that hold 64 bits and type the app → check it → write it as a package.
42
43
  *
43
44
  * compiler/options.mts resolveOptions — screen size + buffer caps, from opts, then ER_AOT_*
44
45
  * compiler/types.mts the types the stages share (Env, StatementContext, state/ref records)
45
46
  * compiler/out.mts Out — the handlers, effects and drawings lowering collects
46
47
  * compiler/diagnostics.mts aotError / withLoc / formatAotError — locate + hint unsupported syntax
47
48
  * compiler/static-eval.mts evalStatic — fold the compile-time-constant subset (styles, initials)
48
- * compiler/c-syntax.mts cstr / floatLit / i64Lit — JS values spelled as C
49
49
  * compiler/expressions.mts lowerExprWide — lower a JS expression (state/props/refs) to the IR
50
50
  * compiler/ir/*.mts the IR the stages lower to (ir/app.mts: the whole lowered app)
51
- * compiler/c/*.mts the C backend: prints the IR as C (emitExpr returns it as a CExpr)
52
51
  * compiler/parse.mts parseApp — JSX/TSX source → AST (types stripped, `undefined` normalized)
53
52
  * compiler/collect.mts moduleScope + collect{State, Components, Callbacks, Memos, Effects}
54
53
  * compiler/animations.mts collect{Anims,Refs}, Easing, interpolate, Animated.start() chains
@@ -60,9 +59,11 @@
60
59
  * compiler/nodes.mts emitNode — the element dispatcher + the generic host node
61
60
  * compiler/elements/*.mts typed components: Dial / Switch / TextInput / Modal / FlatList / …
62
61
  * compiler/keyboard.mts setKeyboardConfig({...}) → the keyboard config
62
+ * compiler/native-modules.mts nativeModule() declarations and their interfaces → native calls
63
63
  * compiler/lower.mts lowerApp — run the stages above over the parsed app
64
- * compiler/check.mts the check pass — the values lowering recorded, checked in order
65
- * compiler/assemble.mts writeApp — write the lowered app as app.gen.{c,h}
64
+ * compiler/typing.mts what lowering holds in place of a typed value, for the typing pass to fill in
65
+ * compiler/check.mts the typing and check passes — what lowering recorded, run in order
66
+ * compiler/package/*.mts the package backend: the IR as a Flow B program, its container and report
66
67
  *
67
68
  * The compiler is TypeScript (.mts), which Node runs by stripping the types. tools/stage-npm-package.mjs
68
69
  * compiles it to JavaScript for the npm package.
@@ -71,97 +72,186 @@
71
72
  - Imports
72
73
  ---------------------------------------------------------------------------------------------------------------------*/
73
74
  import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, } from 'node:fs';
74
- import { resolve, dirname } from 'node:path';
75
+ import { basename, resolve, dirname } from 'node:path';
75
76
  import { fileURLToPath } from 'node:url';
76
- import { bakeAssets } from '../assets/index.mjs';
77
+ import { bakeAssetPackBytes } from '../assets/index.mjs';
77
78
  import { warnMissingGlyphs } from '../assets/glyph-coverage.mjs';
78
79
  import { analyzeFontSizes, warnFontSizes } from '../assets/font-sizes.mjs';
79
80
  import { formatAotError } from './compiler/diagnostics.mjs';
80
81
  import { resolveOptions } from './compiler/options.mjs';
81
82
  import { bakeSvgArtifacts } from './compiler/collect.mjs';
82
- import { demoMarker, compileSourceImpl } from './compiler/assemble.mjs';
83
- import { inferWideSlots, sameSlotWidths } from './compiler/expressions.mjs';
83
+ import { nativeHeaders } from './compiler/native-header.mjs';
84
+ import { readModuleFile, readNativeFiles } from './compiler/native-files.mjs';
85
+ import { demoFile } from './demo-file.mjs';
86
+ import { assemblePackage, bakePackage, compilePanel, packPackage, resourceReport, } from './compiler/package/assemble.mjs';
87
+ import { MAX_LAYOUTS, runCheck } from './compiler/package/checks.mjs';
88
+ import { SizeSearch } from './compiler/package/layouts.mjs';
84
89
  /*----------------------------------------------------------------------------------------------------------------------
85
90
  - Constants
86
91
  ---------------------------------------------------------------------------------------------------------------------*/
87
- const aotDir = dirname(fileURLToPath(import.meta.url)); // packages/embedded-react/aot
88
- const repoRoot = resolve(aotDir, '../../..');
89
- const demosDir = resolve(repoRoot, 'demos');
90
- const distDir = resolve(aotDir, '..', 'dist');
92
+ const aotDirectory = dirname(fileURLToPath(import.meta.url)); // packages/embedded-react/aot
93
+ const repositoryRoot = resolve(aotDirectory, '../../..');
94
+ const demosDirectory = resolve(repositoryRoot, 'demos');
95
+ const distDirectory = resolve(aotDirectory, '..', 'dist');
96
+ /** Where the search for an app's layouts starts. */
97
+ const FIRST_SIZE = { width: 240, height: 320 };
91
98
  /*----------------------------------------------------------------------------------------------------------------------
92
99
  - Implementation
93
100
  ---------------------------------------------------------------------------------------------------------------------*/
94
- export { bakeSvgArtifacts, demoMarker };
101
+ export { bakePackage, bakeSvgArtifacts, nativeHeaders, packPackage, readModuleFile, readNativeFiles, resourceReport, };
95
102
  /**
96
- * A state or ref slot is typed from its initial value, so `useState(0)` is an int until a setter stores
97
- * Date.now() in it. A compile records every value stored into an int slot (env.stores), and the typing pass
98
- * infers from them which slots have to hold 64 bits, following a timestamp through every slot it reaches; the
99
- * app is then compiled again with those slots widened, so every read of a slot sees its final type.
103
+ * Runs a compilation, annotating an AOT error with file:line:col + a source code-frame (+ hint) so the failure
104
+ * points at the exact unsupported construct.
100
105
  *
101
- * @param src The App.jsx/App.tsx source text.
102
- * @param demo Demo name (only used in the generated-by header comment).
103
- * @param opts compileSource's options, resolved (see resolveOptions).
106
+ * @param source The App.jsx/App.tsx source text.
107
+ * @param demo Demo name, for the file the error names when opts has none.
108
+ * @param options The compile's options.
109
+ * @param resolved The same options, resolved.
110
+ * @param compile The compile.
104
111
  *
105
- * @returns The generated app.gen.c and app.gen.h, and what they contain.
112
+ * @returns What the compile produced.
106
113
  */
107
- function compileWidened(src, demo, opts) {
108
- // The slots found so far that need 64 bits; every pass compiles with all of them widened.
109
- let wide = new Map();
110
- for (;;) {
111
- // Run one pass, holding on to its error instead of throwing it straight away.
112
- const stores = [];
113
- let result;
114
- let error;
115
- try {
116
- result = compileSourceImpl(src, demo, opts, wide, stores);
117
- }
118
- catch (caught) {
119
- error = caught;
114
+ function compileLocated(source, demo, options, resolved, compile) {
115
+ try {
116
+ return compile();
117
+ }
118
+ catch (error) {
119
+ // Point an AOT error at its place in the source; any other error passes through unchanged.
120
+ if (error &&
121
+ typeof error.message === 'string' &&
122
+ error.message.startsWith('AOT:')) {
123
+ throw formatAotError(error, source, options.filename || `demos/${demo}/App.jsx`, resolved);
120
124
  }
121
- // Stop once no slot is inferred to widen; a failed pass with new ones may have failed on a narrow type.
122
- const inferred = inferWideSlots(stores, wide);
123
- if (sameSlotWidths(inferred, wide)) {
124
- if (error) {
125
- throw error;
126
- }
127
- return result;
125
+ throw error;
126
+ }
127
+ }
128
+ /**
129
+ * The sizes a package build was told to keep layouts for: options.screens, options.screen or ER_AOT_SCREEN_W/H.
130
+ *
131
+ * @param options The build's options.
132
+ *
133
+ * @returns The sizes, or null to find every layout.
134
+ */
135
+ function requestedScreens(options) {
136
+ if (options.screens?.length)
137
+ return options.screens;
138
+ if (options.screen)
139
+ return [options.screen];
140
+ const fromEnv = (name) => (process.env[name] ?? '').trim() !== '';
141
+ return fromEnv('ER_AOT_SCREEN_W') || fromEnv('ER_AOT_SCREEN_H')
142
+ ? [resolveOptions(options).screen]
143
+ : null;
144
+ }
145
+ /**
146
+ * The error for an app with too many layouts, naming the value that took the most different values across them.
147
+ *
148
+ * @param panels The layouts so far.
149
+ * @param named The build names its panels already.
150
+ *
151
+ * @returns The error.
152
+ */
153
+ function tooManyLayouts(panels, named) {
154
+ const values = new Map();
155
+ for (const { assumptions } of panels) {
156
+ for (const assumption of assumptions) {
157
+ const source = assumption.source ?? 'a value derived from `screen`';
158
+ const seen = values.get(source) ?? new Set();
159
+ seen.add(assumption.kind === 'value' ? assumption.value : seen.size);
160
+ values.set(source, seen);
128
161
  }
129
- wide = inferred;
130
162
  }
163
+ const [worst] = [...values].sort(([, left], [, right]) => right.size - left.size)[0] ?? ['the app'];
164
+ return new Error(`AOT: this app needs more than ${MAX_LAYOUTS} layouts, because \`${worst}\` changes what is compiled at ` +
165
+ 'too many sizes.\n\nA breakpoint picks between a few layouts; a value worked out from `screen` belongs in ' +
166
+ 'a style, which boot works out. ' +
167
+ (named
168
+ ? 'Or name fewer panels.'
169
+ : 'To build for fixed panels, name them: --screen 240x320,800x480.'));
131
170
  }
132
171
  /**
133
- * Public entry: compile JSX source → { c, h, ... }. On an AOT error, annotate it with file:line:col + a
134
- * source code-frame (+ hint) so the failure points at the exact unsupported construct.
172
+ * Public entry for the package output: compile JSX source to a Flow B program section, and its debug section.
135
173
  *
136
- * @param src The App.jsx/App.tsx source text.
137
- * @param demo Demo name (only used in the generated-by header comment).
138
- * @param opts filename, svgArtifacts, ts, and the screen and caps resolveOptions documents.
174
+ * With no sizes named, it finds the app's layouts: it compiles one, finds a size that layout's check rejects, and
175
+ * compiles again until every size has a layout. Named sizes keep only the layouts they pick. An AOT error is annotated
176
+ * with file:line:col + a source code-frame (+ hint), so the failure points at the exact unsupported construct.
139
177
  *
140
- * @returns The generated app.gen.c and app.gen.h, and what they contain.
178
+ * @param source The App.jsx/App.tsx source text.
179
+ * @param demo Demo name, for the file an error names when opts has none.
180
+ * @param compileOptions filename, svgArtifacts, ts, screens, release, and the screen and caps resolveOptions documents.
181
+ *
182
+ * @returns The program and debug sections, and what the package holds.
141
183
  */
142
- export function compileSource(src, demo = 'app', opts = {}) {
143
- const resolved = resolveOptions(opts);
144
- try {
145
- return compileWidened(src, demo, resolved);
184
+ export function compilePackage(source, demo = 'app', compileOptions = {}) {
185
+ const panels = [];
186
+ const checks = () => panels.map(panel => panel.program.panels[0].check);
187
+ const compileAt = (screen, searched) => {
188
+ const options = resolveOptions({ ...compileOptions, screen });
189
+ const resolved = searched
190
+ ? { ...options, screenFrom: 'search' }
191
+ : options;
192
+ panels.push(compileLocated(source, demo, compileOptions, resolved, () => compilePanel(source, resolved)));
193
+ };
194
+ const requested = requestedScreens(compileOptions);
195
+ if (requested) {
196
+ const seen = new Set();
197
+ for (const screen of requested) {
198
+ const { width, height } = resolveOptions({
199
+ ...compileOptions,
200
+ screen,
201
+ }).screen;
202
+ const size = `${width}x${height}`;
203
+ if (seen.has(size)) {
204
+ throw new Error(`AOT: the panel ${size} is listed twice`);
205
+ }
206
+ seen.add(size);
207
+ if (!checks().some(check => runCheck(check, width, height))) {
208
+ if (panels.length === MAX_LAYOUTS)
209
+ throw tooManyLayouts(panels, true);
210
+ compileAt({ width, height }, false);
211
+ }
212
+ }
146
213
  }
147
- catch (error) {
148
- // Point an AOT error at its place in the source; any other error passes through unchanged.
149
- if (error &&
150
- typeof error.message === 'string' &&
151
- error.message.startsWith('AOT:')) {
152
- throw formatAotError(error, src, opts.filename || `demos/${demo}/App.jsx`, resolved);
214
+ else {
215
+ const search = new SizeSearch();
216
+ let next = FIRST_SIZE;
217
+ while (next && next !== 'gave-up') {
218
+ if (panels.length === MAX_LAYOUTS)
219
+ throw tooManyLayouts(panels, false);
220
+ compileAt(next, true);
221
+ if (!runCheck(checks().at(-1), next.width, next.height)) {
222
+ throw new Error(`AOT: the layout for ${next.width}x${next.height} doesn't take that size. This is a compiler bug.`);
223
+ }
224
+ next = search.next(checks());
225
+ }
226
+ if (next === 'gave-up') {
227
+ throw new Error("AOT: can't tell which layouts this app needs: its checks are too intricate to work out for every size. " +
228
+ 'Name the panels it runs on: --screen 240x320,800x480.');
153
229
  }
154
- throw error;
155
230
  }
231
+ return assemblePackage(panels, basename(compileOptions.filename || 'App.jsx'), compileOptions.release);
156
232
  }
157
- // CLI entry (`node aot/compile.mts [demo]`), only when run directly: compile a demo into dist/app.gen.{c,h}.
233
+ // CLI entry (`node aot/compile.mts [demo]`), only when run directly: compile a demo into dist/app.erpkg.
158
234
  if (process.argv[1] &&
159
235
  resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url))) {
160
- // Find the demo's App.jsx, listing the available demos when it is missing.
161
- const demo = process.argv[2] || process.env.DEMO || 'thermostat';
162
- const appPath = resolve(demosDir, demo, 'App.jsx');
163
- const availableDemos = existsSync(demosDir)
164
- ? readdirSync(demosDir, { withFileTypes: true })
236
+ // Find the demo's App.tsx or App.jsx, listing the available demos when it is missing.
237
+ const commandArguments = process.argv.slice(2);
238
+ const screenAt = commandArguments.indexOf('--screen');
239
+ const screens = screenAt < 0
240
+ ? undefined
241
+ : (commandArguments[screenAt + 1] ?? '').split(',').map(size => {
242
+ const match = /^([1-9]\d*)x([1-9]\d*)$/i.exec(size);
243
+ if (!match) {
244
+ console.error(`AOT: --screen expects <width>x<height> (e.g. --screen 240x320), got: ${commandArguments[screenAt + 1] ?? '(nothing)'}`);
245
+ process.exit(1);
246
+ }
247
+ return { width: Number(match[1]), height: Number(match[2]) };
248
+ });
249
+ const demo = commandArguments.find((argument, index) => !argument.startsWith('--') && (screenAt < 0 || index !== screenAt + 1)) ||
250
+ process.env.DEMO ||
251
+ 'thermostat';
252
+ const appPath = demoFile(resolve(demosDirectory, demo), 'App');
253
+ const availableDemos = existsSync(demosDirectory)
254
+ ? readdirSync(demosDirectory, { withFileTypes: true })
165
255
  .filter(entry => entry.isDirectory())
166
256
  .map(entry => entry.name)
167
257
  : [];
@@ -170,13 +260,15 @@ if (process.argv[1] &&
170
260
  process.exit(1);
171
261
  }
172
262
  // Compile the app, baking <Svg source> .svg imports first so the compile itself stays pure (no I/O).
173
- const src = readFileSync(appPath, 'utf8');
263
+ const source = readFileSync(appPath, 'utf8');
174
264
  let result;
175
265
  try {
176
- const svgArtifacts = await bakeSvgArtifacts(src, resolve(demosDir, demo));
177
- result = compileSource(src, demo, {
178
- filename: resolve(demosDir, demo, 'App.jsx'),
179
- svgArtifacts,
266
+ result = compilePackage(source, demo, {
267
+ filename: appPath,
268
+ svgArtifacts: await bakeSvgArtifacts(source, resolve(demosDirectory, demo)),
269
+ nativeFiles: readNativeFiles(source, resolve(demosDirectory, demo)),
270
+ screen: screens?.[0],
271
+ screens,
180
272
  });
181
273
  }
182
274
  catch (error) {
@@ -184,14 +276,10 @@ if (process.argv[1] &&
184
276
  console.error(error && error.aotLoc ? error.message : error?.message || String(error));
185
277
  process.exit(1);
186
278
  }
187
- // Write the generated C.
188
- mkdirSync(distDir, { recursive: true });
189
- writeFileSync(resolve(distDir, 'app.gen.c'), result.c);
190
- writeFileSync(resolve(distDir, 'app.gen.h'), result.h);
191
279
  // Locate the images the app imports; each importPath is source-relative to the demo's App.jsx.
192
280
  const imageJobs = result.images.map(image => ({
193
281
  name: image.name,
194
- path: resolve(demosDir, demo, image.importPath),
282
+ path: resolve(demosDirectory, demo, image.importPath),
195
283
  }));
196
284
  // Stop on an imported image that is not on disk.
197
285
  for (const job of imageJobs) {
@@ -201,10 +289,12 @@ if (process.argv[1] &&
201
289
  }
202
290
  }
203
291
  // Flow B renders all text in the built-in font, so check the app's glyphs and font sizes against it.
204
- warnMissingGlyphs({ source: src, jsx: true });
205
- warnFontSizes({ used: analyzeFontSizes(src) });
206
- // Bake images with Flow A's baker, even with none (a no-op), so the AOT host can always build and call it.
207
- const baked = bakeAssets({ images: imageJobs, fonts: [], outDir: distDir });
208
- console.log(`AOT: compiled demo "${demo}" -> dist/app.gen.c (${result.nodes} nodes, ${result.state} state, ` +
209
- `${result.handlers} handler(s), ${result.updates} dynamic) + ${baked.images} image(s) -> dist/assets.generated.c`);
292
+ warnMissingGlyphs({ source: source, jsx: true });
293
+ warnFontSizes({ used: analyzeFontSizes(source) });
294
+ // The package carries its images as an asset pack.
295
+ const file = packPackage(result, imageJobs.length ? bakeAssetPackBytes({ images: imageJobs }) : undefined);
296
+ mkdirSync(distDirectory, { recursive: true });
297
+ writeFileSync(resolve(distDirectory, 'app.erpkg'), file.bytes);
298
+ console.log(`AOT: compiled demo "${demo}" -> dist/app.erpkg`);
299
+ console.log(resourceReport(result, file).join('\n'));
210
300
  }