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
@@ -13,14 +13,13 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
-
17
16
  // `npm run pack [demo]` — builds a deployable ERCF config container (dist/app.erpkg).
18
17
  //
19
18
  // The full release path for Flow A: bundle the app (esbuild → IIFE), precompile it to QuickJS
20
19
  // bytecode (so the device never ships the parser or source text), bake the imported images/fonts into
21
20
  // an ERPK pack, and wrap both — with a QuickJS version stamp and an integrity CRC — into a single
22
21
  // .erpkg. That one file is "the config": load it with er_runtime_load_container() on the desktop, or
23
- // upload it to a device's config region. See packages/embedded-react/assets/emit-container.mjs for the
22
+ // upload it to a device's config region. See packages/embedded-react/assets/emit-container.mts for the
24
23
  // format, and er_runtime.h for the loader.
25
24
  //
26
25
  // npm run pack # default demo (thermostat)
@@ -28,168 +27,147 @@
28
27
  //
29
28
  // Prereq: the bytecode precompiler (er-bridge-quickjs-compile) must be built. This script searches the
30
29
  // usual build dirs and tells you how to build it if it's missing (override with ER_COMPILE_BIN).
31
- import {build} from 'esbuild';
32
- import {spawnSync} from 'node:child_process';
33
- import {fileURLToPath, pathToFileURL} from 'node:url';
34
- import {dirname, resolve, basename} from 'node:path';
35
- import {
36
- existsSync,
37
- readdirSync,
38
- readFileSync,
39
- writeFileSync,
40
- mkdirSync,
41
- } from 'node:fs';
42
- import {bakeImage} from './assets/bake-image.mjs';
43
- import {bakeFont} from './assets/bake-font.mjs';
44
- import {resolveFontJobs} from './assets/font-config.mjs';
45
- import {analyzeFontSizes, warnFontSizes} from './assets/font-sizes.mjs';
46
- import {warnMissingGlyphs} from './assets/glyph-coverage.mjs';
47
- import {emitAssetPack} from './assets/emit-pack.mjs';
48
- import {emitContainer} from './assets/emit-container.mjs';
49
- import {registerSvgVectorLoader} from './assets/svg-loader.mjs';
50
- import {findCompileBin, compileBinHelp} from './compile-bin.mjs';
51
-
30
+ import { build } from 'esbuild';
31
+ import { spawnSync } from 'node:child_process';
32
+ import { fileURLToPath, pathToFileURL } from 'node:url';
33
+ import { dirname, resolve, basename } from 'node:path';
34
+ import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, } from 'node:fs';
35
+ import { bakeImage } from './assets/bake-image.mjs';
36
+ import { bakeFont } from './assets/bake-font.mjs';
37
+ import { resolveFontJobs } from './assets/font-config.mjs';
38
+ import { analyzeFontSizes, warnFontSizes } from './assets/font-sizes.mjs';
39
+ import { warnMissingGlyphs } from './assets/glyph-coverage.mjs';
40
+ import { emitAssetPack } from './assets/emit-pack.mjs';
41
+ import { emitContainer } from './assets/emit-container.mjs';
42
+ import { registerSvgVectorLoader } from './assets/svg-loader.mjs';
43
+ import { findCompileBin, compileBinHelp } from './compile-bin.mjs';
44
+ import { loadAppFile, loadDependencyFile } from './aot/app-file-loader.mjs';
45
+ import { demoFile } from './aot/demo-file.mjs';
52
46
  // QuickJS release the bytecode targets — MUST match the FetchContent pin in
53
47
  // bridges/quickjs/CMakeLists.txt and ER_QUICKJS_TAG in er_runtime.c. The loader rejects a mismatch.
54
48
  const QUICKJS_TAG = 'v0.15.0';
55
49
  const BYTES_PER_KILOBYTE = 1024;
56
-
57
50
  const here = dirname(fileURLToPath(import.meta.url)); // packages/embedded-react
58
51
  const repoRoot = resolve(here, '../..');
59
52
  const demosDir = resolve(repoRoot, 'demos');
60
53
  const libEntry = resolve(here, 'src/embedded-react/index.js');
61
54
  const nodeModules = resolve(here, 'node_modules');
62
55
  const distDir = resolve(here, 'dist');
63
-
64
56
  const demo = process.argv[2] || process.env.DEMO || 'thermostat';
65
57
  const demoDir = resolve(demosDir, demo);
66
- const entry = resolve(demoDir, 'index.jsx');
58
+ const entry = demoFile(demoDir, 'index');
67
59
  if (!existsSync(entry)) {
68
- const available = existsSync(demosDir)
69
- ? readdirSync(demosDir, {withFileTypes: true})
70
- .filter(entry => entry.isDirectory())
71
- .map(entry => entry.name)
72
- : [];
73
- console.error(`Demo "${demo}" not found (expected ${entry}).`);
74
- console.error(`Available demos: ${available.join(', ') || '(none)'}`);
75
- process.exit(1);
60
+ const available = existsSync(demosDir)
61
+ ? readdirSync(demosDir, { withFileTypes: true })
62
+ .filter(entry => entry.isDirectory())
63
+ .map(entry => entry.name)
64
+ : [];
65
+ console.error(`Demo "${demo}" not found (expected ${entry}).`);
66
+ console.error(`Available demos: ${available.join(', ') || '(none)'}`);
67
+ process.exit(1);
76
68
  }
77
-
78
69
  // --- Locate the bytecode precompiler -----------------------------------------------------------
79
70
  const compileBin = findCompileBin();
80
71
  if (!compileBin) {
81
- console.error(compileBinHelp());
82
- process.exit(1);
72
+ console.error(compileBinHelp());
73
+ process.exit(1);
83
74
  }
84
-
85
- // --- Bundle the app (same import-driven asset discovery as build.mjs) ---------------------------
75
+ // --- Bundle the app (same import-driven asset discovery as build.mts) ---------------------------
86
76
  const images = new Map(); // name -> path
87
77
  const fonts = new Map(); // family -> path
88
78
  const assetPlugin = {
89
- name: 'embedded-react-assets',
90
- setup(pluginBuild) {
91
- pluginBuild.onLoad({filter: /\.(png|jpe?g|webp|gif|bmp)$/i}, args => {
92
- const name = basename(args.path).replace(/\.[^.]+$/, '');
93
- images.set(name, args.path);
94
- return {
95
- contents: `module.exports = ${JSON.stringify(name)};`,
96
- loader: 'js',
97
- };
98
- });
99
- pluginBuild.onLoad({filter: /\.(ttf|otf)$/i}, args => {
100
- const family = basename(args.path).replace(/\.[^.]+$/, '');
101
- fonts.set(family, args.path);
102
- return {
103
- contents: `module.exports = ${JSON.stringify(family)};`,
104
- loader: 'js',
105
- };
106
- });
107
- registerSvgVectorLoader(pluginBuild, (name, svgPath) =>
108
- images.set(name, svgPath),
109
- ); // raster-fallback SVGs join the image pack
110
- },
79
+ name: 'embedded-react-assets',
80
+ setup(pluginBuild) {
81
+ // The demo's own files give its native modules their signatures, and so do a package's.
82
+ pluginBuild.onLoad({ filter: /\.(jsx?|tsx?)$/ }, args => args.path.startsWith(demoDir)
83
+ ? loadAppFile(args.path)
84
+ : loadDependencyFile(args.path));
85
+ pluginBuild.onLoad({ filter: /\.(png|jpe?g|webp|gif|bmp)$/i }, args => {
86
+ const name = basename(args.path).replace(/\.[^.]+$/, '');
87
+ images.set(name, args.path);
88
+ return {
89
+ contents: `module.exports = ${JSON.stringify(name)};`,
90
+ loader: 'js',
91
+ };
92
+ });
93
+ pluginBuild.onLoad({ filter: /\.(ttf|otf)$/i }, args => {
94
+ const family = basename(args.path).replace(/\.[^.]+$/, '');
95
+ fonts.set(family, args.path);
96
+ return {
97
+ contents: `module.exports = ${JSON.stringify(family)};`,
98
+ loader: 'js',
99
+ };
100
+ });
101
+ registerSvgVectorLoader(pluginBuild, (name, svgPath) => images.set(name, svgPath)); // raster-fallback SVGs join the image pack
102
+ },
111
103
  };
112
-
113
- mkdirSync(distDir, {recursive: true});
104
+ mkdirSync(distDir, { recursive: true });
114
105
  const bundlePath = resolve(distDir, 'app.bundle.js');
115
106
  await build({
116
- entryPoints: [entry],
117
- bundle: true,
118
- format: 'iife',
119
- outfile: bundlePath,
120
- platform: 'neutral',
121
- target: 'es2020',
122
- jsx: 'automatic',
123
- // Pin React to THIS package's copy: a demo/consumer project may carry its own node_modules
124
- // (e.g., after `npm install` for device-dev deps), and esbuild resolving `react` from there while
125
- // the library resolves its copy from here yields two React instances — the hook dispatcher is
126
- // null and every component throws. One copy, always.
127
- alias: {
128
- 'embedded-react': libEntry,
129
- react: resolve(nodeModules, 'react'),
130
- 'react-reconciler': resolve(nodeModules, 'react-reconciler'),
131
- scheduler: resolve(nodeModules, 'scheduler'),
132
- },
133
- nodePaths: [nodeModules],
134
- plugins: [assetPlugin],
135
- define: {'process.env.NODE_ENV': '"production"'},
136
- legalComments: 'none',
137
- logLevel: 'info',
107
+ entryPoints: [entry],
108
+ bundle: true,
109
+ format: 'iife',
110
+ outfile: bundlePath,
111
+ platform: 'neutral',
112
+ target: 'es2020',
113
+ jsx: 'automatic',
114
+ // Pin React to THIS package's copy: a demo/consumer project may carry its own node_modules
115
+ // (e.g., after `npm install` for device-dev deps), and esbuild resolving `react` from there while
116
+ // the library resolves its copy from here yields two React instances — the hook dispatcher is
117
+ // null and every component throws. One copy, always.
118
+ alias: {
119
+ 'embedded-react': libEntry,
120
+ react: resolve(nodeModules, 'react'),
121
+ 'react-reconciler': resolve(nodeModules, 'react-reconciler'),
122
+ scheduler: resolve(nodeModules, 'scheduler'),
123
+ },
124
+ nodePaths: [nodeModules],
125
+ plugins: [assetPlugin],
126
+ define: { 'process.env.NODE_ENV': '"production"' },
127
+ legalComments: 'none',
128
+ logLevel: 'info',
138
129
  });
139
130
  console.log(`Bundled demo "${demo}" -> dist/app.bundle.js`);
140
-
141
131
  // --- Precompile to QuickJS bytecode -------------------------------------------------------------
142
132
  const bytecodePath = resolve(distDir, 'app.bundle.qbc');
143
133
  const compileResult = spawnSync(compileBin, [bundlePath, bytecodePath], {
144
- stdio: 'inherit',
134
+ stdio: 'inherit',
145
135
  });
146
136
  if (compileResult.status !== 0) {
147
- console.error('Bytecode compile failed.');
148
- process.exit(1);
137
+ console.error('Bytecode compile failed.');
138
+ process.exit(1);
149
139
  }
150
140
  const bytecode = readFileSync(bytecodePath);
151
-
152
- // --- Bake imported assets into an ERPK pack (same sizing rules as build.mjs / sim.mjs) ----------
141
+ // --- Bake imported assets into an ERPK pack (same sizing rules as build.mts / sim.mts) ----------
153
142
  const bundleSource = readFileSync(bundlePath, 'utf8');
154
143
  const usedSizes = analyzeFontSizes(bundleSource);
155
-
156
144
  let config = {};
157
145
  const configPath = resolve(demoDir, 'assets.config.js');
158
146
  if (existsSync(configPath))
159
- config = (await import(pathToFileURL(configPath).href)).default || {};
147
+ config = (await import(pathToFileURL(configPath).href)).default || {};
160
148
  const fontConfig = config.fonts || {};
161
149
  const imageConfig = config.images || {};
162
-
163
150
  const fontJobs = resolveFontJobs(fonts, fontConfig, usedSizes.sizes);
164
151
  const imageJobs = [...images.entries()].map(([name, path]) => ({
165
- path,
166
- name,
167
- format: imageConfig[name]?.format,
152
+ path,
153
+ name,
154
+ format: imageConfig[name]?.format,
168
155
  }));
169
-
170
156
  const bakedImages = imageJobs.map(imageJob => bakeImage(imageJob));
171
157
  const bakedFonts = fontJobs.map(fontJob => bakeFont(fontJob));
172
- warnMissingGlyphs({source: bundleSource, fonts: bakedFonts});
173
- warnFontSizes({used: usedSizes, fonts: bakedFonts});
174
- const assetPack =
175
- bakedImages.length || bakedFonts.length
176
- ? emitAssetPack({images: bakedImages, fonts: bakedFonts})
158
+ warnMissingGlyphs({ source: bundleSource, fonts: bakedFonts });
159
+ warnFontSizes({ used: usedSizes, fonts: bakedFonts });
160
+ const assetPack = bakedImages.length || bakedFonts.length
161
+ ? emitAssetPack({ images: bakedImages, fonts: bakedFonts })
177
162
  : null;
178
- const fontSizeCount = bakedFonts.reduce(
179
- (count, font) => count + font.sizes.length,
180
- 0,
181
- );
182
-
163
+ const fontSizeCount = bakedFonts.reduce((count, font) => count + font.sizes.length, 0);
183
164
  // --- Wrap into the ERCF container ---------------------------------------------------------------
184
- const container = emitContainer({bytecode, assetPack, qjsTag: QUICKJS_TAG});
165
+ const container = emitContainer({ bytecode, assetPack, qjsTag: QUICKJS_TAG });
185
166
  const outPath = resolve(distDir, 'app.erpkg');
186
167
  writeFileSync(outPath, container);
187
-
188
- const kb = byteCount => `${(byteCount / BYTES_PER_KILOBYTE).toFixed(1)} KB`;
189
- console.log(
190
- `Packed config -> dist/app.erpkg (${kb(container.length)})\n` +
168
+ const kb = (byteCount) => `${(byteCount / BYTES_PER_KILOBYTE).toFixed(1)} KB`;
169
+ console.log(`Packed config -> dist/app.erpkg (${kb(container.length)})\n` +
191
170
  ` qjs ${QUICKJS_TAG} · bytecode ${kb(bytecode.length)}` +
192
171
  (assetPack
193
- ? ` · assets ${kb(assetPack.length)} (${bakedImages.length} image(s), ${fontSizeCount} font size(s))`
194
- : ' · no assets'),
195
- );
172
+ ? ` · assets ${kb(assetPack.length)} (${bakedImages.length} image(s), ${fontSizeCount} font size(s))`
173
+ : ' · no assets'));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "embedded-react",
3
- "version": "0.20.0",
3
+ "version": "0.22.0",
4
4
  "type": "module",
5
5
  "description": "React Native-style component package + reconciler that drives the embedded-react C engine through the QuickJS NativeUI bridge (Flow A).",
6
6
  "license": "Apache-2.0",
@@ -62,27 +62,27 @@
62
62
  "!**/*.test.js"
63
63
  ],
64
64
  "scripts": {
65
- "build": "node build.mjs",
66
- "pack": "node pack-container.mjs",
65
+ "build": "node build.mts",
66
+ "pack": "node pack-container.mts",
67
67
  "aot": "node aot/compile.mts",
68
68
  "aot:smoke": "node aot/screenshot-smoke.mjs",
69
69
  "erb:frames": "node test/erb-frames/erb-frames.mts",
70
70
  "erb:frames:record": "node test/erb-frames/erb-frames.mts --record",
71
- "erb:corpus": "node test/erb-fuzz/make-corpus.mjs",
72
- "parity": "node parity.mjs",
73
- "version:sync": "node ../../tools/sync-version.mjs",
74
- "version:check": "node ../../tools/sync-version.mjs --check",
75
- "release": "node ../../tools/release.mjs",
76
- "build:builtin-font": "node assets/build-builtin-font.mjs",
77
- "sim": "node sim.mjs",
78
- "dev": "node cli.mjs dev",
79
- "create": "node create-embedded-react.mjs",
71
+ "erb:corpus": "node test/erb-fuzz/make-corpus.mts",
72
+ "parity": "node parity.mts",
73
+ "version:sync": "node ../../tools/sync-version.mts",
74
+ "version:check": "node ../../tools/sync-version.mts --check",
75
+ "release": "node ../../tools/release.mts",
76
+ "build:builtin-font": "node assets/build-builtin-font.mts",
77
+ "sim": "node sim.mts",
78
+ "dev": "node cli.mts dev",
79
+ "create": "node create-embedded-react.mts",
80
80
  "test": "vitest run",
81
81
  "test:watch": "vitest",
82
- "test:runtime": "node test/runtime/run.mjs",
83
- "test:bytecode": "node test/runtime/run.mjs --bytecode",
84
- "test:split": "node test/runtime/split-roundtrip.mjs",
85
- "typecheck": "tsc -p tsconfig.types.json && tsc -p tsconfig.aot.json && tsc -p tsconfig.frames.json"
82
+ "test:runtime": "node test/runtime/run.mts",
83
+ "test:bytecode": "node test/runtime/run.mts --bytecode",
84
+ "test:split": "node test/runtime/split-roundtrip.mts",
85
+ "typecheck": "tsc -p tsconfig.types.json && tsc -p tsconfig.aot.json && tsc -p tsconfig.frames.json && tsc -p tsconfig.runtime.json"
86
86
  },
87
87
  "dependencies": {
88
88
  "@babel/code-frame": "^7.29.7",
@@ -102,7 +102,10 @@
102
102
  "@types/babel__code-frame": "^7.27.0",
103
103
  "@types/babel__core": "^7.20.5",
104
104
  "@types/node": "^22.20.4",
105
+ "@types/opentype.js": "^1.3.10",
106
+ "@types/pngjs": "^6.0.5",
105
107
  "@types/react": "18.3.1",
108
+ "@types/react-reconciler": "^0.28.9",
106
109
  "typescript": "^5.5.0",
107
110
  "vitest": "^4.1.11"
108
111
  },
@@ -13,7 +13,6 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
-
17
16
  // Simulator-only Babel transform: rewrites `useState(init)` in app code to a persisting helper so
18
17
  // state transparently survives a hot reload (see tools/simulator/README.md). Plain
19
18
  // `useState` from 'react' just persists in the simulator; on a device (no transform, no __erPersist)
@@ -24,85 +23,74 @@
24
23
  // stable across the edits you make most often (JSX/logic). Adding/removing a useState in a component,
25
24
  // or renaming it, shifts that component's keys and resets its state — press R in the sim for a clean
26
25
  // reset any time.
27
- import {transformSync} from '@babel/core';
26
+ import { transformSync } from '@babel/core';
27
+ // @ts-expect-error The package ships no types.
28
28
  import syntaxJsx from '@babel/plugin-syntax-jsx';
29
-
30
29
  /** Best-effort name of the function/component enclosing a path (for a stable, readable key). */
31
30
  function enclosingName(path) {
32
- const functionPath = path.getFunctionParent();
33
- if (!functionPath) return '_';
34
- if (functionPath.node.id && functionPath.node.id.name)
35
- return functionPath.node.id.name; // function Foo() {}
36
- const parent = functionPath.parentPath && functionPath.parentPath.node;
37
- if (parent) {
38
- if (parent.type === 'VariableDeclarator' && parent.id && parent.id.name)
39
- return parent.id.name; // const Foo = () =>
40
- if (parent.key && parent.key.name) return parent.key.name; // method / property
41
- if (
42
- parent.type === 'AssignmentExpression' &&
43
- parent.left &&
44
- parent.left.name
45
- )
46
- return parent.left.name;
47
- }
48
- return '_';
31
+ const functionPath = path.getFunctionParent();
32
+ if (!functionPath)
33
+ return '_';
34
+ // Read loosely: only some kinds of function and parent have these fields.
35
+ const functionNode = functionPath.node;
36
+ if (functionNode.id && functionNode.id.name)
37
+ return functionNode.id.name; // function Foo() {}
38
+ const parent = functionPath.parentPath && functionPath.parentPath.node;
39
+ if (parent) {
40
+ if (parent.type === 'VariableDeclarator' && parent.id && parent.id.name)
41
+ return parent.id.name; // const Foo = () =>
42
+ if (parent.key && parent.key.name)
43
+ return parent.key.name; // method / property
44
+ if (parent.type === 'AssignmentExpression' &&
45
+ parent.left &&
46
+ parent.left.name)
47
+ return parent.left.name;
48
+ }
49
+ return '_';
49
50
  }
50
-
51
51
  /** Babel plugin: useState(init) → __erPersistState("key", init), importing the helper when used. */
52
- function persistPlugin({types}) {
53
- return {
54
- name: 'er-persist-usestate',
55
- visitor: {
56
- Program: {
57
- enter(_path, state) {
58
- state.erCounters = new Map();
59
- state.erUsed = false;
52
+ function persistPlugin({ types, }) {
53
+ return {
54
+ name: 'er-persist-usestate',
55
+ visitor: {
56
+ Program: {
57
+ enter(_path, state) {
58
+ state.erCounters = new Map();
59
+ state.erUsed = false;
60
+ },
61
+ exit(path, state) {
62
+ if (!state.erUsed)
63
+ return;
64
+ path.unshiftContainer('body', types.importDeclaration([
65
+ types.importSpecifier(types.identifier('__erPersistState'), types.identifier('usePersistentState')),
66
+ ], types.stringLiteral('embedded-react')));
67
+ },
68
+ },
69
+ CallExpression(path, state) {
70
+ if (!types.isIdentifier(path.node.callee, { name: 'useState' }))
71
+ return;
72
+ // Only rewrite the real useState (an imported binding from react / embedded-react).
73
+ const binding = path.scope.getBinding('useState');
74
+ if (!binding || binding.kind !== 'module')
75
+ return;
76
+ const declaration = binding.path.parentPath && binding.path.parentPath.node;
77
+ const source = declaration && declaration.source && declaration.source.value;
78
+ if (source !== 'react' && source !== 'embedded-react')
79
+ return;
80
+ const functionName = enclosingName(path);
81
+ const index = state.erCounters.get(functionName) || 0;
82
+ state.erCounters.set(functionName, index + 1);
83
+ const key = `${state.opts.moduleId}::${functionName}#${index}`;
84
+ path.replaceWith(types.callExpression(types.identifier('__erPersistState'), [
85
+ types.stringLiteral(key),
86
+ ...path.node.arguments,
87
+ ]));
88
+ state.erUsed = true;
89
+ path.skip();
90
+ },
60
91
  },
61
- exit(path, state) {
62
- if (!state.erUsed) return;
63
- path.unshiftContainer(
64
- 'body',
65
- types.importDeclaration(
66
- [
67
- types.importSpecifier(
68
- types.identifier('__erPersistState'),
69
- types.identifier('usePersistentState'),
70
- ),
71
- ],
72
- types.stringLiteral('embedded-react'),
73
- ),
74
- );
75
- },
76
- },
77
- CallExpression(path, state) {
78
- if (!types.isIdentifier(path.node.callee, {name: 'useState'})) return;
79
- // Only rewrite the real useState (an imported binding from react / embedded-react).
80
- const binding = path.scope.getBinding('useState');
81
- if (!binding || binding.kind !== 'module') return;
82
- const declaration =
83
- binding.path.parentPath && binding.path.parentPath.node;
84
- const source =
85
- declaration && declaration.source && declaration.source.value;
86
- if (source !== 'react' && source !== 'embedded-react') return;
87
-
88
- const functionName = enclosingName(path);
89
- const index = state.erCounters.get(functionName) || 0;
90
- state.erCounters.set(functionName, index + 1);
91
- const key = `${state.opts.moduleId}::${functionName}#${index}`;
92
-
93
- path.replaceWith(
94
- types.callExpression(types.identifier('__erPersistState'), [
95
- types.stringLiteral(key),
96
- ...path.node.arguments,
97
- ]),
98
- );
99
- state.erUsed = true;
100
- path.skip();
101
- },
102
- },
103
- };
92
+ };
104
93
  }
105
-
106
94
  /**
107
95
  * Whether `absolutePath` is an app source file that should receive the persist transform: under the project
108
96
  * root, but NOT a dependency. The library itself lives under the project root in a consumer install
@@ -111,46 +99,42 @@ function persistPlugin({types}) {
111
99
  * Excluding `node_modules` is what keeps the helper (and react) untransformed in a published install,
112
100
  * not just in the monorepo (where the library happens to sit outside the demo's project root).
113
101
  *
114
- * @param {string} absolutePath Absolute path of the module esbuild is loading.
115
- * @param {string} projectRootNormalized Project root, forward-slash normalized.
116
- * @returns {boolean}
102
+ * @param absolutePath Absolute path of the module esbuild is loading.
103
+ * @param projectRootNormalized Project root, forward-slash normalized.
117
104
  */
118
105
  export function shouldPersist(absolutePath, projectRootNormalized) {
119
- const normalizedPath = absolutePath.replace(/\\/g, '/');
120
- return (
121
- normalizedPath.startsWith(projectRootNormalized) &&
122
- !normalizedPath.includes('/node_modules/')
123
- );
106
+ const normalizedPath = absolutePath.replace(/\\/g, '/');
107
+ return (normalizedPath.startsWith(projectRootNormalized) &&
108
+ !normalizedPath.includes('/node_modules/'));
124
109
  }
125
-
126
110
  /**
127
111
  * Applies the persist transform to a module's source.
128
112
  *
129
113
  * TypeScript entries (.ts/.tsx) are parsed with the `typescript` plugin enabled; the type syntax is
130
- * preserved in the output and stripped downstream by esbuild's ts/tsx loader (see sim-server.mjs).
114
+ * preserved in the output and stripped downstream by esbuild's ts/tsx loader (see sim-server.mts).
131
115
  *
132
- * @param {string} code Module source (JSX and/or TypeScript allowed).
133
- * @param {string} moduleId Stable module identifier (used in keys; e.g. a path relative to the app).
134
- * @returns {string} Transformed source (JSX/TS preserved for esbuild to handle).
116
+ * @param code Module source (JSX and/or TypeScript allowed).
117
+ * @param moduleId Stable module identifier (used in keys; e.g. a path relative to the app).
118
+ * @returns Transformed source (JSX/TS preserved for esbuild to handle).
135
119
  */
136
120
  export function transformPersist(code, moduleId) {
137
- // Enable the babel parser plugins this module's extension needs. `.tsx` is jsx+typescript; `.ts` is
138
- // typescript-only (the jsx plugin would misparse `<T>` type assertions); everything else is jsx.
139
- const isTs = /\.tsx?$/.test(moduleId);
140
- const isTsx = /\.tsx$/.test(moduleId);
141
- const parserPlugins = isTsx
142
- ? ['jsx', 'typescript']
143
- : isTs
144
- ? ['typescript']
145
- : ['jsx'];
146
- const result = transformSync(code, {
147
- filename: moduleId,
148
- babelrc: false,
149
- configFile: false,
150
- sourceType: 'module',
151
- parserOpts: {plugins: parserPlugins},
152
- // syntaxJsx only enables jsx parsing; for ts/tsx we drive the parser via parserOpts above instead.
153
- plugins: [...(isTs ? [] : [syntaxJsx]), [persistPlugin, {moduleId}]],
154
- });
155
- return result.code;
121
+ // Enable the babel parser plugins this module's extension needs. `.tsx` is jsx+typescript; `.ts` is
122
+ // typescript-only (the jsx plugin would misparse `<T>` type assertions); everything else is jsx.
123
+ const isTs = /\.tsx?$/.test(moduleId);
124
+ const isTsx = /\.tsx$/.test(moduleId);
125
+ const parserPlugins = isTsx
126
+ ? ['jsx', 'typescript']
127
+ : isTs
128
+ ? ['typescript']
129
+ : ['jsx'];
130
+ const result = transformSync(code, {
131
+ filename: moduleId,
132
+ babelrc: false,
133
+ configFile: false,
134
+ sourceType: 'module',
135
+ parserOpts: { plugins: parserPlugins },
136
+ // syntaxJsx only enables jsx parsing; for ts/tsx we drive the parser via parserOpts above instead.
137
+ plugins: [...(isTs ? [] : [syntaxJsx]), [persistPlugin, { moduleId }]],
138
+ });
139
+ return result.code;
156
140
  }