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/sim-server.mjs CHANGED
@@ -13,385 +13,291 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
-
17
- // sim-server.mjs — the shared WASM-simulator bundler + dev server.
16
+ // sim-server.mts — the shared WASM-simulator bundler + dev server.
18
17
  //
19
18
  // esbuild-bundles a JSX app → app.js, bakes its imported images/fonts → assets.pack, and either (a) serves
20
19
  // the prebuilt embedded-react.{js,wasm} host page with live hot reload (runDevServer), or (b) produces those
21
20
  // files once for a static export (buildApp). useState survives a hot reload via the Babel persist transform.
22
21
  //
23
- // Used by the consumer CLI (cli.mjs → `npx embedded-react dev` / `export`) and the repo dev loop
24
- // (tools/web-sim/dev.mjs). The only differences are paths, passed in here.
25
-
26
- import {createServer} from 'node:http';
27
- import {readFile} from 'node:fs/promises';
28
- import {existsSync, readFileSync, statSync} from 'node:fs';
29
- import {createRequire} from 'node:module';
30
- import {pathToFileURL} from 'node:url';
31
- import {basename, dirname, extname, relative, resolve} from 'node:path';
32
-
33
- const HERE = dirname(
34
- new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'),
35
- );
22
+ // Used by the consumer CLI (cli.mts → `npx embedded-react dev` / `export`) and the repo dev loop
23
+ // (tools/web-sim/dev.mts). The only differences are paths, passed in here.
24
+ import { createServer } from 'node:http';
25
+ import { readFile } from 'node:fs/promises';
26
+ import { existsSync, readFileSync, statSync } from 'node:fs';
27
+ import { createRequire } from 'node:module';
28
+ import { pathToFileURL } from 'node:url';
29
+ import { basename, dirname, extname, relative, resolve } from 'node:path';
30
+ const HERE = dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'));
36
31
  const require = createRequire(import.meta.url);
37
32
  const esbuild = require('esbuild');
38
- const {bakeAssetPack} = await import(
39
- pathToFileURL(resolve(HERE, 'assets/index.mjs')).href
40
- );
41
- const {resolveFontJobs} = await import(
42
- pathToFileURL(resolve(HERE, 'assets/font-config.mjs')).href
43
- );
44
- const {analyzeFontSizes, fontSizeSignature, warnFontSizes} = await import(
45
- pathToFileURL(resolve(HERE, 'assets/font-sizes.mjs')).href
46
- );
47
- const {textSignature, warnMissingGlyphs} = await import(
48
- pathToFileURL(resolve(HERE, 'assets/glyph-coverage.mjs')).href
49
- );
50
- const {registerSvgVectorLoader} = await import(
51
- pathToFileURL(resolve(HERE, 'assets/svg-loader.mjs')).href
52
- );
53
- const {transformPersist, shouldPersist} = await import(
54
- pathToFileURL(resolve(HERE, 'persist-transform.mjs')).href
55
- );
56
-
57
- const REACT_PIN = Object.fromEntries(
58
- ['react', 'react-reconciler', 'scheduler']
33
+ const { bakeAssetPack } = await import('./assets/index.mjs');
34
+ const { resolveFontJobs } = await import('./assets/font-config.mjs');
35
+ const { analyzeFontSizes, fontSizeSignature, warnFontSizes } = await import('./assets/font-sizes.mjs');
36
+ const { textSignature, warnMissingGlyphs } = await import('./assets/glyph-coverage.mjs');
37
+ const { registerSvgVectorLoader } = await import('./assets/svg-loader.mjs');
38
+ const { transformPersist, shouldPersist } = await import('./persist-transform.mjs');
39
+ const { loadAppFile, loadDependencyFile } = await import('./aot/app-file-loader.mjs');
40
+ const REACT_PIN = Object.fromEntries(['react', 'react-reconciler', 'scheduler']
59
41
  .map(packageName => [
60
- packageName,
61
- resolve(HERE, 'node_modules', packageName),
62
- ])
63
- .filter(([, pinPath]) => existsSync(pinPath)),
64
- );
65
-
42
+ packageName,
43
+ resolve(HERE, 'node_modules', packageName),
44
+ ])
45
+ .filter(([, pinPath]) => existsSync(pinPath)));
66
46
  const MIME = {
67
- '.html': 'text/html; charset=utf-8',
68
- '.js': 'text/javascript; charset=utf-8',
69
- '.wasm': 'application/wasm',
70
- '.pack': 'application/octet-stream',
47
+ '.html': 'text/html; charset=utf-8',
48
+ '.js': 'text/javascript; charset=utf-8',
49
+ '.wasm': 'application/wasm',
50
+ '.pack': 'application/octet-stream',
71
51
  };
72
- const assetName = filePath => basename(filePath).replace(/\.[^.]+$/, '');
73
- const mtime = filePath => {
74
- try {
75
- return statSync(filePath).mtimeMs;
76
- } catch {
77
- return 0;
78
- }
52
+ const assetName = (filePath) => basename(filePath).replace(/\.[^.]+$/, '');
53
+ const mtime = (filePath) => {
54
+ try {
55
+ return statSync(filePath).mtimeMs;
56
+ }
57
+ catch {
58
+ return 0;
59
+ }
79
60
  };
80
-
81
61
  /**
82
62
  * Build the esbuild config + asset baker for one app bundle. Owns its own asset-discovery state, so it is
83
63
  * safe to use for either a one-shot build or a watching context.
84
- *
85
- * @param {object} o
86
- * @param {string} o.entry, o.projectRoot, o.libSrc, o.outDir
87
- * @param {string[]} o.nodePaths
88
- * @param {boolean} [o.persist] Apply the useState→persist transform (dev hot reload). Default true.
89
- * @param {() => void} [o.onRebuilt] Called after each successful build + asset bake (e.g. broadcast reload).
90
- * @returns {{ options: object, bundlePath: string, packPath: string }}
91
64
  */
92
- function createBundle({
93
- entry,
94
- projectRoot,
95
- libSrc,
96
- nodePaths,
97
- outDir,
98
- persist = true,
99
- onRebuilt,
100
- }) {
101
- const bundlePath = resolve(outDir, 'app.js');
102
- const packPath = resolve(outDir, 'assets.pack');
103
- const projectRootNormalized = projectRoot.replace(/\\/g, '/');
104
- const images = new Map();
105
- const fonts = new Map();
106
- let lastAssetSignature = null;
107
-
108
- async function bakePack() {
109
- const bundleSource = readFileSync(bundlePath, 'utf8');
110
- const usedSizes = analyzeFontSizes(bundleSource);
111
-
112
- let assetsConfig = {};
113
- const assetsConfigPath = resolve(projectRoot, 'assets.config.js');
114
- if (existsSync(assetsConfigPath))
115
- assetsConfig =
116
- (
117
- await import(
118
- `${pathToFileURL(assetsConfigPath).href}?t=${mtime(assetsConfigPath)}`
119
- )
120
- ).default || {};
121
- const fontConfig = assetsConfig.fonts || {};
122
- const imageConfig = assetsConfig.images || {};
123
-
124
- const fontJobs = resolveFontJobs(fonts, fontConfig, usedSizes.sizes);
125
- const imageJobs = [...images.entries()].map(([name, path]) => ({
126
- path,
127
- name,
128
- format: imageConfig[name]?.format,
129
- }));
130
-
131
- // The app's text is an asset input too: new characters and new font sizes must both be
132
- // re-checked against the bake even when no font or image file changed.
133
- const assetSignature = JSON.stringify({
134
- text: textSignature(bundleSource),
135
- fontSizes: fontSizeSignature(usedSizes),
136
- images: imageJobs
137
- .map(job => [job.name, job.path, mtime(job.path), job.format])
138
- .sort(),
139
- fonts: fontJobs
140
- .map(job => [
141
- job.family,
142
- job.path,
143
- mtime(job.path),
144
- job.sizes,
145
- job.bpp,
146
- job.glyphs,
147
- job.extraGlyphs,
148
- ])
149
- .sort(),
150
- });
151
- if (assetSignature === lastAssetSignature) return;
152
- lastAssetSignature = assetSignature;
153
- if (!imageJobs.length && !fontJobs.length) {
154
- // Built-in font only → no pack, but its glyph and size coverage still bind.
155
- warnMissingGlyphs({source: bundleSource});
156
- warnFontSizes({used: usedSizes});
157
- return;
158
- }
159
-
160
- try {
161
- const summary = bakeAssetPack({
162
- images: imageJobs,
163
- fonts: fontJobs,
164
- outPath: packPath,
165
- source: bundleSource,
166
- usedSizes,
167
- });
168
- console.log(
169
- ` assets → ${summary.images} image(s), ${summary.fonts} font size(s), ${summary.bytes} B`,
170
- );
171
- } catch (error) {
172
- console.error(` asset bake failed: ${error.message}`);
65
+ function createBundle({ entry, projectRoot, libSrc, nodePaths, outDir, persist = true, onRebuilt, }) {
66
+ const bundlePath = resolve(outDir, 'app.js');
67
+ const packPath = resolve(outDir, 'assets.pack');
68
+ const projectRootNormalized = projectRoot.replace(/\\/g, '/');
69
+ const images = new Map();
70
+ const fonts = new Map();
71
+ let lastAssetSignature = null;
72
+ async function bakePack() {
73
+ const bundleSource = readFileSync(bundlePath, 'utf8');
74
+ const usedSizes = analyzeFontSizes(bundleSource);
75
+ let assetsConfig = {};
76
+ const assetsConfigPath = resolve(projectRoot, 'assets.config.js');
77
+ if (existsSync(assetsConfigPath))
78
+ assetsConfig =
79
+ (await import(`${pathToFileURL(assetsConfigPath).href}?t=${mtime(assetsConfigPath)}`)).default || {};
80
+ const fontConfig = assetsConfig.fonts || {};
81
+ const imageConfig = assetsConfig.images || {};
82
+ const fontJobs = resolveFontJobs(fonts, fontConfig, usedSizes.sizes);
83
+ const imageJobs = [...images.entries()].map(([name, path]) => ({
84
+ path,
85
+ name,
86
+ format: imageConfig[name]?.format,
87
+ }));
88
+ // The app's text is an asset input too: new characters and new font sizes must both be
89
+ // re-checked against the bake even when no font or image file changed.
90
+ const assetSignature = JSON.stringify({
91
+ text: textSignature(bundleSource),
92
+ fontSizes: fontSizeSignature(usedSizes),
93
+ images: imageJobs
94
+ .map(job => [job.name, job.path, mtime(job.path), job.format])
95
+ .sort(),
96
+ fonts: fontJobs
97
+ .map(job => [
98
+ job.family,
99
+ job.path,
100
+ mtime(job.path),
101
+ job.sizes,
102
+ job.bpp,
103
+ job.glyphs,
104
+ job.extraGlyphs,
105
+ ])
106
+ .sort(),
107
+ });
108
+ if (assetSignature === lastAssetSignature)
109
+ return;
110
+ lastAssetSignature = assetSignature;
111
+ if (!imageJobs.length && !fontJobs.length) {
112
+ // Built-in font only → no pack, but its glyph and size coverage still bind.
113
+ warnMissingGlyphs({ source: bundleSource });
114
+ warnFontSizes({ used: usedSizes });
115
+ return;
116
+ }
117
+ try {
118
+ const summary = bakeAssetPack({
119
+ images: imageJobs,
120
+ fonts: fontJobs,
121
+ outPath: packPath,
122
+ source: bundleSource,
123
+ usedSizes,
124
+ });
125
+ console.log(` assets → ${summary.images} image(s), ${summary.fonts} font size(s), ${summary.bytes} B`);
126
+ }
127
+ catch (error) {
128
+ console.error(` asset bake failed: ${error.message}`);
129
+ }
173
130
  }
174
- }
175
-
176
- const options = {
177
- entryPoints: [entry],
178
- bundle: true,
179
- format: 'iife',
180
- outfile: bundlePath,
181
- platform: 'neutral',
182
- target: 'es2020',
183
- jsx: 'automatic',
184
- alias: {'embedded-react': libSrc, ...REACT_PIN},
185
- nodePaths,
186
- define: {'process.env.NODE_ENV': '"production"'},
187
- legalComments: 'none',
188
- logLevel: 'silent',
189
- plugins: [
190
- {
191
- name: 'embedded-react-websim',
192
- setup(pluginBuild) {
193
- pluginBuild.onStart(() => {
194
- images.clear();
195
- fonts.clear();
196
- });
197
- pluginBuild.onLoad({filter: /\.(jsx?|tsx?)$/}, loadArgs => {
198
- // Transform ONLY the app's own source — never dependencies (see shouldPersist: excluding
199
- // node_modules is what stops the library's usePersistentState being rewritten to call itself).
200
- if (
201
- !persist ||
202
- !shouldPersist(loadArgs.path, projectRootNormalized)
203
- )
204
- return undefined;
205
- try {
206
- // Match the esbuild loader to the source extension so TS type syntax (preserved by the
207
- // persist transform) is stripped: .tsx → tsx, .ts → ts, .jsx/.js → jsx.
208
- const loader = loadArgs.path.endsWith('.tsx')
209
- ? 'tsx'
210
- : loadArgs.path.endsWith('.ts')
211
- ? 'ts'
212
- : 'jsx';
213
- return {
214
- contents: transformPersist(
215
- readFileSync(loadArgs.path, 'utf8'),
216
- relative(projectRoot, loadArgs.path).replace(/\\/g, '/'),
217
- ),
218
- loader,
219
- };
220
- } catch (error) {
221
- return {errors: [{text: `persist transform: ${error.message}`}]};
222
- }
223
- });
224
- pluginBuild.onLoad(
225
- {filter: /\.(png|jpe?g|webp|gif|bmp)$/i},
226
- loadArgs => {
227
- images.set(assetName(loadArgs.path), loadArgs.path);
228
- return {
229
- contents: `module.exports = ${JSON.stringify(assetName(loadArgs.path))};`,
230
- loader: 'js',
231
- };
131
+ const options = {
132
+ entryPoints: [entry],
133
+ bundle: true,
134
+ format: 'iife',
135
+ outfile: bundlePath,
136
+ platform: 'neutral',
137
+ target: 'es2020',
138
+ jsx: 'automatic',
139
+ alias: { 'embedded-react': libSrc, ...REACT_PIN },
140
+ nodePaths,
141
+ define: { 'process.env.NODE_ENV': '"production"' },
142
+ legalComments: 'none',
143
+ logLevel: 'silent',
144
+ plugins: [
145
+ {
146
+ name: 'embedded-react-websim',
147
+ setup(pluginBuild) {
148
+ pluginBuild.onStart(() => {
149
+ images.clear();
150
+ fonts.clear();
151
+ });
152
+ pluginBuild.onLoad({ filter: /\.(jsx?|tsx?)$/ }, async (loadArgs) => {
153
+ // Only the app's own source — never dependencies (see shouldPersist: excluding node_modules is what
154
+ // stops the library's usePersistentState being rewritten to call itself). Native modules get their
155
+ // signatures and mocks, and with persist on, useState persists. A package's native modules get theirs too.
156
+ if (!shouldPersist(loadArgs.path, projectRootNormalized))
157
+ return loadDependencyFile(loadArgs.path, { mocks: true });
158
+ try {
159
+ return await loadAppFile(loadArgs.path, persist
160
+ ? (source) => transformPersist(source, relative(projectRoot, loadArgs.path).replace(/\\/g, '/'))
161
+ : undefined, { mocks: true });
162
+ }
163
+ catch (error) {
164
+ return { errors: [{ text: `persist transform: ${error.message}` }] };
165
+ }
166
+ });
167
+ pluginBuild.onLoad({ filter: /\.(png|jpe?g|webp|gif|bmp)$/i }, loadArgs => {
168
+ images.set(assetName(loadArgs.path), loadArgs.path);
169
+ return {
170
+ contents: `module.exports = ${JSON.stringify(assetName(loadArgs.path))};`,
171
+ loader: 'js',
172
+ };
173
+ });
174
+ pluginBuild.onLoad({ filter: /\.(ttf|otf)$/i }, loadArgs => {
175
+ fonts.set(assetName(loadArgs.path), loadArgs.path);
176
+ return {
177
+ contents: `module.exports = ${JSON.stringify(assetName(loadArgs.path))};`,
178
+ loader: 'js',
179
+ };
180
+ });
181
+ registerSvgVectorLoader(pluginBuild, (name, svgPath) => images.set(name, svgPath)); // raster-fallback SVGs join the image pack
182
+ pluginBuild.onEnd(async (result) => {
183
+ if (result.errors.length) {
184
+ console.error(`✗ build failed (${result.errors.length} error(s))`);
185
+ return;
186
+ }
187
+ await bakePack();
188
+ if (onRebuilt)
189
+ onRebuilt();
190
+ });
191
+ },
232
192
  },
233
- );
234
- pluginBuild.onLoad({filter: /\.(ttf|otf)$/i}, loadArgs => {
235
- fonts.set(assetName(loadArgs.path), loadArgs.path);
236
- return {
237
- contents: `module.exports = ${JSON.stringify(assetName(loadArgs.path))};`,
238
- loader: 'js',
239
- };
240
- });
241
- registerSvgVectorLoader(pluginBuild, (name, svgPath) =>
242
- images.set(name, svgPath),
243
- ); // raster-fallback SVGs join the image pack
244
- pluginBuild.onEnd(async result => {
245
- if (result.errors.length) {
246
- console.error(
247
- `✗ build failed (${result.errors.length} error(s))`,
248
- );
249
- return;
250
- }
251
- await bakePack();
252
- if (onRebuilt) onRebuilt();
253
- });
254
- },
255
- },
256
- ],
257
- };
258
-
259
- return {options, bundlePath, packPath};
193
+ ],
194
+ };
195
+ return { options, bundlePath, packPath };
260
196
  }
261
-
262
197
  /**
263
198
  * One-shot bundle + asset bake into outDir (app.js [+ assets.pack]). For the static export.
264
199
  * Persist transform is off (a static page has no hot reload to preserve state across).
265
200
  */
266
- export async function buildApp({
267
- entry,
268
- projectRoot,
269
- libSrc,
270
- nodePaths,
271
- outDir,
272
- }) {
273
- const {options} = createBundle({
274
- entry,
275
- projectRoot,
276
- libSrc,
277
- nodePaths,
278
- outDir,
279
- persist: false,
280
- });
281
- await esbuild.build(options);
201
+ export async function buildApp({ entry, projectRoot, libSrc, nodePaths, outDir, }) {
202
+ const { options } = createBundle({
203
+ entry,
204
+ projectRoot,
205
+ libSrc,
206
+ nodePaths,
207
+ outDir,
208
+ persist: false,
209
+ });
210
+ await esbuild.build(options);
282
211
  }
283
-
284
212
  /**
285
213
  * Run the simulator dev server: watch + bundle + bake + serve + hot reload.
286
- *
287
- * @param {object} o
288
- * @param {string} o.entry, o.projectRoot, o.libSrc, o.indexHtml, o.simDir, o.outDir, o.label
289
- * @param {string[]} o.nodePaths
290
- * @param {number} o.port
291
214
  */
292
- export async function runDevServer({
293
- entry,
294
- projectRoot,
295
- libSrc,
296
- nodePaths,
297
- indexHtml,
298
- simDir,
299
- outDir,
300
- port,
301
- label,
302
- }) {
303
- const clients = new Set();
304
- const broadcastReload = () => {
305
- for (const response of clients) response.write('data: reload\n\n');
306
- };
307
-
308
- const {options} = createBundle({
309
- entry,
310
- projectRoot,
311
- libSrc,
312
- nodePaths,
313
- outDir,
314
- persist: true,
315
- onRebuilt: () => {
316
- console.log('↻ rebuilt → reloading');
317
- broadcastReload();
318
- },
319
- });
320
-
321
- const buildContext = await esbuild.context(options);
322
- await buildContext.rebuild();
323
- await buildContext.watch();
324
-
325
- // Serve the host page; embedded-react.{js,wasm} from simDir, the freshly bundled app.js/assets.pack from
326
- // outDir. The page references ./public/<name>. window.__erHot is injected so the page connects to /reload.
327
- const send = async (response, file) => {
328
- try {
329
- const body = await readFile(file);
330
- response
331
- .writeHead(200, {
332
- 'content-type': MIME[extname(file)] || 'application/octet-stream',
333
- 'cache-control': 'no-store',
334
- })
335
- .end(body);
336
- } catch {
337
- response.writeHead(404).end('not found');
338
- }
339
- };
340
- const server = createServer(async (request, response) => {
341
- const path = decodeURIComponent(
342
- new URL(request.url, 'http://localhost').pathname,
343
- );
344
- if (path === '/reload') {
345
- response.writeHead(200, {
346
- 'content-type': 'text/event-stream',
347
- 'cache-control': 'no-cache',
348
- connection: 'keep-alive',
349
- });
350
- response.write('retry: 1000\n\n');
351
- clients.add(response);
352
- request.on('close', () => clients.delete(response));
353
- return;
354
- }
355
- if (path === '/' || path === '/index.html') {
356
- try {
357
- const html = (await readFile(indexHtml, 'utf8')).replace(
358
- '</head>',
359
- '<script>window.__erHot=true</script></head>',
360
- );
361
- response
362
- .writeHead(200, {
363
- 'content-type': MIME['.html'],
364
- 'cache-control': 'no-store',
365
- })
366
- .end(html);
367
- } catch {
215
+ export async function runDevServer({ entry, projectRoot, libSrc, nodePaths, indexHtml, simDir, outDir, port, label, }) {
216
+ const clients = new Set();
217
+ const broadcastReload = () => {
218
+ for (const response of clients)
219
+ response.write('data: reload\n\n');
220
+ };
221
+ const { options } = createBundle({
222
+ entry,
223
+ projectRoot,
224
+ libSrc,
225
+ nodePaths,
226
+ outDir,
227
+ persist: true,
228
+ onRebuilt: () => {
229
+ console.log('↻ rebuilt → reloading');
230
+ broadcastReload();
231
+ },
232
+ });
233
+ const buildContext = await esbuild.context(options);
234
+ await buildContext.rebuild();
235
+ await buildContext.watch();
236
+ // Serve the host page; embedded-react.{js,wasm} from simDir, the freshly bundled app.js/assets.pack from
237
+ // outDir. The page references ./public/<name>. window.__erHot is injected so the page connects to /reload.
238
+ const send = async (response, file) => {
239
+ try {
240
+ const body = await readFile(file);
241
+ response
242
+ .writeHead(200, {
243
+ 'content-type': MIME[extname(file)] || 'application/octet-stream',
244
+ 'cache-control': 'no-store',
245
+ })
246
+ .end(body);
247
+ }
248
+ catch {
249
+ response.writeHead(404).end('not found');
250
+ }
251
+ };
252
+ const server = createServer(async (request, response) => {
253
+ const path = decodeURIComponent(new URL(request.url, 'http://localhost').pathname);
254
+ if (path === '/reload') {
255
+ response.writeHead(200, {
256
+ 'content-type': 'text/event-stream',
257
+ 'cache-control': 'no-cache',
258
+ connection: 'keep-alive',
259
+ });
260
+ response.write('retry: 1000\n\n');
261
+ clients.add(response);
262
+ request.on('close', () => clients.delete(response));
263
+ return;
264
+ }
265
+ if (path === '/' || path === '/index.html') {
266
+ try {
267
+ const html = (await readFile(indexHtml, 'utf8')).replace('</head>', '<script>window.__erHot=true</script></head>');
268
+ response
269
+ .writeHead(200, {
270
+ 'content-type': MIME['.html'],
271
+ 'cache-control': 'no-store',
272
+ })
273
+ .end(html);
274
+ }
275
+ catch {
276
+ response.writeHead(404).end('not found');
277
+ }
278
+ return;
279
+ }
280
+ if (path.startsWith('/public/')) {
281
+ const name = basename(path); // flat filename only
282
+ const dir = name === 'embedded-react.js' || name === 'embedded-react.wasm'
283
+ ? simDir
284
+ : outDir;
285
+ return void send(response, resolve(dir, name));
286
+ }
368
287
  response.writeHead(404).end('not found');
369
- }
370
- return;
371
- }
372
- if (path.startsWith('/public/')) {
373
- const name = basename(path); // flat filename only
374
- const dir =
375
- name === 'embedded-react.js' || name === 'embedded-react.wasm'
376
- ? simDir
377
- : outDir;
378
- return void send(response, resolve(dir, name));
379
- }
380
- response.writeHead(404).end('not found');
381
- });
382
-
383
- await new Promise(onListening => server.listen(port, onListening));
384
- console.log(`embedded-react WASM sim → http://localhost:${port}/`);
385
- console.log(`watching ${label} — edit & save to hot-reload. Ctrl-C to quit.`);
386
-
387
- const shutdown = async () => {
388
- try {
389
- await buildContext.dispose();
390
- } catch {}
391
- server.close();
392
- process.exit(0);
393
- };
394
- process.on('SIGINT', shutdown);
395
- process.on('SIGTERM', shutdown);
396
- return {ctx: buildContext, server};
288
+ });
289
+ await new Promise(onListening => server.listen(port, onListening));
290
+ console.log(`embedded-react WASM sim → http://localhost:${port}/`);
291
+ console.log(`watching ${label} — edit & save to hot-reload. Ctrl-C to quit.`);
292
+ const shutdown = async () => {
293
+ try {
294
+ await buildContext.dispose();
295
+ }
296
+ catch { }
297
+ server.close();
298
+ process.exit(0);
299
+ };
300
+ process.on('SIGINT', shutdown);
301
+ process.on('SIGTERM', shutdown);
302
+ return { ctx: buildContext, server };
397
303
  }