embedded-react 0.19.0 → 0.20.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 (116) hide show
  1. package/README.md +7 -3
  2. package/aot/compile.mjs +178 -58
  3. package/aot/compiler/animations.mjs +290 -281
  4. package/aot/compiler/boot.mjs +70 -33
  5. package/aot/compiler/branch-merge.mjs +4 -3
  6. package/aot/compiler/check.mjs +9 -9
  7. package/aot/compiler/collect.mjs +324 -205
  8. package/aot/compiler/control-flow.mjs +209 -197
  9. package/aot/compiler/diagnostics.mjs +22 -25
  10. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  11. package/aot/compiler/elements/dial.mjs +91 -77
  12. package/aot/compiler/elements/flat-list.mjs +24 -22
  13. package/aot/compiler/elements/image.mjs +51 -50
  14. package/aot/compiler/elements/modal.mjs +31 -30
  15. package/aot/compiler/elements/props.mjs +23 -23
  16. package/aot/compiler/elements/switch.mjs +42 -34
  17. package/aot/compiler/elements/text-input.mjs +34 -32
  18. package/aot/compiler/expressions.mjs +372 -333
  19. package/aot/compiler/handlers.mjs +473 -387
  20. package/aot/compiler/ir/functions.mjs +11 -1
  21. package/aot/compiler/ir/nodes.mjs +4 -4
  22. package/aot/compiler/ir/reads.mjs +19 -19
  23. package/aot/compiler/ir/types.mjs +14 -14
  24. package/aot/compiler/ir/vectors.mjs +5 -1
  25. package/aot/compiler/keyboard.mjs +17 -7
  26. package/aot/compiler/lower.mjs +77 -80
  27. package/aot/compiler/nodes.mjs +169 -152
  28. package/aot/compiler/options.mjs +35 -30
  29. package/aot/compiler/out.mjs +18 -22
  30. package/aot/compiler/package/animations.mjs +669 -0
  31. package/aot/compiler/package/arena.mjs +252 -0
  32. package/aot/compiler/package/assemble.mjs +177 -0
  33. package/aot/compiler/package/bytecode.mjs +286 -0
  34. package/aot/compiler/package/checks.mjs +1022 -0
  35. package/aot/compiler/package/codegen.mjs +1329 -0
  36. package/aot/compiler/package/enums.mjs +138 -0
  37. package/aot/compiler/package/format.mjs +760 -0
  38. package/aot/compiler/package/layouts.mjs +136 -0
  39. package/aot/compiler/package/lower.mjs +1606 -0
  40. package/aot/compiler/package/props.mjs +118 -0
  41. package/aot/compiler/package/tables.mjs +103 -0
  42. package/aot/compiler/package/vectors.mjs +502 -0
  43. package/aot/compiler/package/writer.mjs +664 -0
  44. package/aot/compiler/pan-responder.mjs +69 -61
  45. package/aot/compiler/parse.mjs +21 -21
  46. package/aot/compiler/static-eval.mjs +25 -23
  47. package/aot/compiler/style-text.mjs +161 -172
  48. package/aot/compiler/svg.mjs +477 -251
  49. package/aot/screenshot-smoke.mjs +54 -40
  50. package/aot/style-map.mjs +102 -90
  51. package/assets/bake-font.mjs +123 -77
  52. package/assets/bake-image.mjs +39 -22
  53. package/assets/bake-svg.mjs +361 -262
  54. package/assets/build-builtin-font.mjs +11 -7
  55. package/assets/emit-c.mjs +77 -58
  56. package/assets/emit-container.mjs +123 -37
  57. package/assets/emit-pack.mjs +77 -67
  58. package/assets/font-config.mjs +9 -6
  59. package/assets/font-sizes.mjs +163 -123
  60. package/assets/glyph-coverage.mjs +74 -54
  61. package/assets/index.mjs +31 -9
  62. package/assets/rasterize.mjs +126 -99
  63. package/assets/svg-loader.mjs +8 -8
  64. package/build.mjs +14 -12
  65. package/cli.mjs +359 -172
  66. package/compile-bin.mjs +3 -3
  67. package/flash.mjs +537 -0
  68. package/hotreload/dev-device.mjs +90 -33
  69. package/hotreload/pack-app.mjs +55 -43
  70. package/hotreload/pack-split.mjs +46 -37
  71. package/hotreload/package-transfer.mjs +175 -0
  72. package/hotreload/protocol.mjs +50 -37
  73. package/hotreload/uploader.mjs +38 -27
  74. package/hotreload/watch-tree.mjs +19 -19
  75. package/pack-container.mjs +28 -20
  76. package/package.json +7 -8
  77. package/persist-transform.mjs +34 -28
  78. package/qjsc-wasm.mjs +25 -14
  79. package/sim/embedded-react.cjs +1 -1
  80. package/sim/embedded-react.js +1 -1
  81. package/sim/embedded-react.wasm +0 -0
  82. package/sim/index.html +94 -85
  83. package/sim-server.mjs +101 -82
  84. package/src/embedded-react/Animated.js +24 -24
  85. package/src/embedded-react/Easing.js +1 -1
  86. package/src/embedded-react/FlatList.js +3 -3
  87. package/src/embedded-react/LayoutAnimation.js +8 -5
  88. package/src/embedded-react/PanResponder.js +75 -71
  89. package/src/embedded-react/Pressable.js +2 -8
  90. package/src/embedded-react/SectionList.js +6 -6
  91. package/src/embedded-react/StyleSheet.js +4 -3
  92. package/src/embedded-react/TouchableOpacity.js +13 -8
  93. package/src/embedded-react/index.d.ts +5 -5
  94. package/src/embedded-react/layout-anim-config.js +10 -4
  95. package/src/embedded-react/list-child.js +5 -5
  96. package/src/embedded-react/named-colors.js +1 -1
  97. package/src/embedded-react/split-style.js +11 -11
  98. package/src/embedded-react/svg-ops.js +760 -593
  99. package/src/embedded-react/useHostValue.js +3 -3
  100. package/src/embedded-react/usePersistentState.js +6 -6
  101. package/src/embedded-react/warn-props.js +1 -1
  102. package/src/host-config.js +60 -53
  103. package/src/props.js +49 -41
  104. package/src/renderer.js +7 -4
  105. package/aot/compiler/assemble.mjs +0 -944
  106. package/aot/compiler/c/animations.mjs +0 -436
  107. package/aot/compiler/c/boot.mjs +0 -127
  108. package/aot/compiler/c/expressions.mjs +0 -270
  109. package/aot/compiler/c/functions.mjs +0 -268
  110. package/aot/compiler/c/keyboard.mjs +0 -96
  111. package/aot/compiler/c/nodes.mjs +0 -303
  112. package/aot/compiler/c/pan-responder.mjs +0 -136
  113. package/aot/compiler/c/statements.mjs +0 -319
  114. package/aot/compiler/c/text.mjs +0 -83
  115. package/aot/compiler/c/vectors.mjs +0 -381
  116. package/aot/compiler/c-syntax.mjs +0 -127
package/sim/index.html CHANGED
@@ -150,17 +150,17 @@
150
150
  (async () => {
151
151
  const stage = document.getElementById('stage');
152
152
  const canvas = document.getElementById('screen');
153
- const ctx = canvas.getContext('2d');
153
+ const canvasContext = canvas.getContext('2d');
154
154
  const panel = document.getElementById('panel');
155
155
  const toggle = document.getElementById('toggle');
156
156
  const sizeLabel = document.getElementById('sizeLabel');
157
- const presetSel = document.getElementById('preset');
158
- const wIn = document.getElementById('w');
159
- const hIn = document.getElementById('h');
157
+ const presetSelect = document.getElementById('preset');
158
+ const widthInput = document.getElementById('w');
159
+ const heightInput = document.getElementById('h');
160
160
  const device = document.getElementById('device');
161
- const frameChk = document.getElementById('frame');
161
+ const frameCheckbox = document.getElementById('frame');
162
162
  let framed = false;
163
- const fail = (msg) => { sizeLabel.textContent = msg; panel.classList.remove('collapsed'); };
163
+ const fail = (message) => { sizeLabel.textContent = message; panel.classList.remove('collapsed'); };
164
164
 
165
165
  // "Fit to window" (the full viewport) is the default — the browser's responsive/device toolbar drives
166
166
  // the board directly. Presets lock to a real panel size.
@@ -171,15 +171,15 @@
171
171
  [320, 240],
172
172
  [240, 320],
173
173
  ];
174
- const fitOpt = document.createElement('option');
175
- fitOpt.value = 'fit';
176
- fitOpt.textContent = 'Fit to window';
177
- presetSel.appendChild(fitOpt);
178
- for (const [pw, ph] of PRESETS) {
179
- const o = document.createElement('option');
180
- o.value = `${pw}x${ph}`;
181
- o.textContent = `${pw} × ${ph}`;
182
- presetSel.appendChild(o);
174
+ const fitOption = document.createElement('option');
175
+ fitOption.value = 'fit';
176
+ fitOption.textContent = 'Fit to window';
177
+ presetSelect.appendChild(fitOption);
178
+ for (const [presetWidth, presetHeight] of PRESETS) {
179
+ const option = document.createElement('option');
180
+ option.value = `${presetWidth}x${presetHeight}`;
181
+ option.textContent = `${presetWidth} × ${presetHeight}`;
182
+ presetSelect.appendChild(option);
183
183
  }
184
184
 
185
185
  toggle.addEventListener('click', () => panel.classList.toggle('collapsed'));
@@ -187,9 +187,9 @@
187
187
  let Module;
188
188
  try {
189
189
  Module = await createEmbeddedReact();
190
- } catch (e) {
190
+ } catch (error) {
191
191
  fail('load failed — run build.mjs');
192
- throw e;
192
+ throw error;
193
193
  }
194
194
 
195
195
  const init = Module.cwrap('er_web_init', 'number', ['number', 'number']);
@@ -200,43 +200,52 @@
200
200
  const pump = Module.cwrap('er_web_pump', null, ['number']);
201
201
  const touch = Module.cwrap('er_web_touch', null, ['number', 'number', 'number']);
202
202
  const framebuffer = Module.cwrap('er_web_framebuffer', 'number', []);
203
- const fbWidth = Module.cwrap('er_web_fb_width', 'number', []);
204
- const fbHeight = Module.cwrap('er_web_fb_height', 'number', []);
203
+ const framebufferWidth = Module.cwrap('er_web_framebuffer_width', 'number', []);
204
+ const framebufferHeight = Module.cwrap('er_web_framebuffer_height', 'number', []);
205
205
 
206
- const clamp = (n) => Math.max(64, Math.min(4096, n | 0));
206
+ const MIN_SCREEN_SIZE = 64;
207
+ const MAX_SCREEN_SIZE = 4096;
208
+ const RGBA_BYTES = 4;
209
+ const REFIT_DEBOUNCE_MS = 60;
210
+ // The touch phases er_web_touch() takes.
211
+ const TOUCH_DOWN = 0;
212
+ const TOUCH_MOVE = 1;
213
+ const TOUCH_UP = 2;
214
+
215
+ const clamp = (size) => Math.max(MIN_SCREEN_SIZE, Math.min(MAX_SCREEN_SIZE, size | 0));
207
216
  // The stage is inset:0, so its client size is the full viewport (the floating panel never shrinks it).
208
217
  const stageSize = () => [clamp(stage.clientWidth), clamp(stage.clientHeight)];
209
218
 
210
219
  // Initial size: ?screen=WxH locks to that size; otherwise fit the viewport.
211
220
  const params = new URLSearchParams(location.search);
212
221
  let mode = 'fit';
213
- let [W, H] = stageSize();
222
+ let [screenWidth, screenHeight] = stageSize();
214
223
  const initial = params.get('screen');
215
224
  if (initial) {
216
- const [iw, ih] = initial.split('x').map((n) => parseInt(n, 10) || 0);
217
- if (iw && ih) {
225
+ const [queryWidth, queryHeight] = initial.split('x').map((part) => parseInt(part, 10) || 0);
226
+ if (queryWidth && queryHeight) {
218
227
  mode = 'fixed';
219
- W = clamp(iw);
220
- H = clamp(ih);
228
+ screenWidth = clamp(queryWidth);
229
+ screenHeight = clamp(queryHeight);
221
230
  }
222
231
  }
223
- presetSel.value = mode === 'fit' ? 'fit' : PRESETS.some(([a, b]) => a === W && b === H) ? `${W}x${H}` : 'fit';
232
+ presetSelect.value = mode === 'fit' ? 'fit' : PRESETS.some(([presetWidth, presetHeight]) => presetWidth === screenWidth && presetHeight === screenHeight) ? `${screenWidth}x${screenHeight}` : 'fit';
224
233
 
225
- if (!init(W, H)) {
234
+ if (!init(screenWidth, screenHeight)) {
226
235
  fail('init failed');
227
236
  return;
228
237
  }
229
238
 
230
239
  // Copy bytes into wasm memory, hand the pointer to a C function, then free.
231
- const withWasmBytes = (bytes, fn) => {
232
- const ptr = Module._malloc(bytes.length);
233
- Module.HEAPU8.set(bytes, ptr);
234
- fn(ptr, bytes.length);
235
- Module._free(ptr);
240
+ const withWasmBytes = (bytes, call) => {
241
+ const pointer = Module._malloc(bytes.length);
242
+ Module.HEAPU8.set(bytes, pointer);
243
+ call(pointer, bytes.length);
244
+ Module._free(pointer);
236
245
  };
237
246
  const fetchBytes = async (url) => {
238
- const res = await fetch(url, { cache: 'no-store' });
239
- return res.ok ? new Uint8Array(await res.arrayBuffer()) : null;
247
+ const response = await fetch(url, { cache: 'no-store' });
248
+ return response.ok ? new Uint8Array(await response.arrayBuffer()) : null;
240
249
  };
241
250
 
242
251
  // Load the asset pack (if any) BEFORE the bundle so <Image>/custom-font nodes resolve, then run the
@@ -261,46 +270,46 @@
261
270
  // server) doesn't poll a nonexistent /reload endpoint.
262
271
  if (window.__erHot) {
263
272
  try {
264
- const es = new EventSource('/reload');
265
- es.onmessage = () => loadApp();
266
- es.onerror = () => {};
273
+ const events = new EventSource('/reload');
274
+ events.onmessage = () => loadApp();
275
+ events.onerror = () => {};
267
276
  } catch {
268
277
  /* EventSource unavailable */
269
278
  }
270
279
  }
271
280
 
272
- let w = 0;
273
- let h = 0;
274
- let len = 0;
281
+ let width = 0;
282
+ let height = 0;
283
+ let byteLength = 0;
275
284
  let image = null;
276
285
 
277
286
  const syncCanvas = () => {
278
- w = fbWidth();
279
- h = fbHeight();
280
- len = w * h * 4;
281
- canvas.width = w;
282
- canvas.height = h;
287
+ width = framebufferWidth();
288
+ height = framebufferHeight();
289
+ byteLength = width * height * RGBA_BYTES;
290
+ canvas.width = width;
291
+ canvas.height = height;
283
292
  // Fit: fill the viewport (backing already equals it, so still 1:1). Locked: native size, centered,
284
293
  // scroll if larger than the window. The #device wrapper fills the stage in Fit mode or shrinks to
285
294
  // the canvas (+ bezel when framed) when locked.
286
- canvas.style.width = mode === 'fit' ? '100%' : w + 'px';
287
- canvas.style.height = mode === 'fit' ? '100%' : h + 'px';
295
+ canvas.style.width = mode === 'fit' ? '100%' : width + 'px';
296
+ canvas.style.height = mode === 'fit' ? '100%' : height + 'px';
288
297
  device.style.display = mode === 'fit' ? 'block' : 'inline-block';
289
298
  device.style.width = mode === 'fit' ? '100%' : 'auto';
290
299
  device.style.height = mode === 'fit' ? '100%' : 'auto';
291
300
  device.classList.toggle('framed', framed && mode === 'fixed');
292
- image = ctx.createImageData(w, h);
293
- wIn.value = w;
294
- hIn.value = h;
295
- sizeLabel.textContent = `${w}×${h}${mode === 'fit' ? ' · fit' : ''}`;
301
+ image = canvasContext.createImageData(width, height);
302
+ widthInput.value = width;
303
+ heightInput.value = height;
304
+ sizeLabel.textContent = `${width}×${height}${mode === 'fit' ? ' · fit' : ''}`;
296
305
  };
297
306
  syncCanvas();
298
307
 
299
- const applySize = (nw, nh) => {
300
- nw = clamp(nw);
301
- nh = clamp(nh);
302
- if (nw === w && nh === h) return;
303
- if (resize(nw, nh)) syncCanvas();
308
+ const applySize = (newWidth, newHeight) => {
309
+ newWidth = clamp(newWidth);
310
+ newHeight = clamp(newHeight);
311
+ if (newWidth === width && newHeight === height) return;
312
+ if (resize(newWidth, newHeight)) syncCanvas();
304
313
  };
305
314
 
306
315
  // Debounced refit while the viewport changes (window drag, device toolbar, rotate). Driven by the
@@ -310,62 +319,62 @@
310
319
  const refit = () => {
311
320
  if (mode !== 'fit') return;
312
321
  clearTimeout(resizeTimer);
313
- resizeTimer = setTimeout(() => applySize(...stageSize()), 60);
322
+ resizeTimer = setTimeout(() => applySize(...stageSize()), REFIT_DEBOUNCE_MS);
314
323
  };
315
324
  window.addEventListener('resize', refit);
316
325
  new ResizeObserver(refit).observe(stage);
317
326
  // Initial fit once layout has settled (the first synchronous measure can predate viewport layout).
318
327
  setTimeout(() => mode === 'fit' && applySize(...stageSize()), 0);
319
328
 
320
- presetSel.addEventListener('change', () => {
321
- if (presetSel.value === 'fit') {
329
+ presetSelect.addEventListener('change', () => {
330
+ if (presetSelect.value === 'fit') {
322
331
  mode = 'fit';
323
332
  applySize(...stageSize());
324
333
  } else {
325
334
  mode = 'fixed';
326
- applySize(...presetSel.value.split('x').map((n) => parseInt(n, 10)));
335
+ applySize(...presetSelect.value.split('x').map((part) => parseInt(part, 10)));
327
336
  }
328
337
  syncCanvas();
329
338
  });
330
339
  document.getElementById('apply').addEventListener('click', () => {
331
340
  mode = 'fixed';
332
- presetSel.value = PRESETS.some(([a, b]) => a === +wIn.value && b === +hIn.value)
333
- ? `${+wIn.value}x${+hIn.value}`
341
+ presetSelect.value = PRESETS.some(([presetWidth, presetHeight]) => presetWidth === +widthInput.value && presetHeight === +heightInput.value)
342
+ ? `${+widthInput.value}x${+heightInput.value}`
334
343
  : 'fit';
335
- applySize(+wIn.value, +hIn.value);
344
+ applySize(+widthInput.value, +heightInput.value);
336
345
  syncCanvas();
337
346
  });
338
347
  // Device-frame chrome only makes sense at a locked size, so enabling it locks the current size.
339
- frameChk.addEventListener('change', () => {
340
- framed = frameChk.checked;
348
+ frameCheckbox.addEventListener('change', () => {
349
+ framed = frameCheckbox.checked;
341
350
  if (framed && mode === 'fit') {
342
351
  mode = 'fixed';
343
- presetSel.value = PRESETS.some(([a, b]) => a === w && b === h) ? `${w}x${h}` : 'fit';
352
+ presetSelect.value = PRESETS.some(([presetWidth, presetHeight]) => presetWidth === width && presetHeight === height) ? `${width}x${height}` : 'fit';
344
353
  }
345
354
  syncCanvas();
346
355
  });
347
356
 
348
357
  // Pointer -> touch. Map CSS pixels to framebuffer pixels (the canvas may be stretched in Fit mode).
349
358
  let down = false;
350
- const toFb = (e) => {
351
- const r = canvas.getBoundingClientRect();
352
- const x = Math.round(((e.clientX - r.left) / r.width) * w);
353
- const y = Math.round(((e.clientY - r.top) / r.height) * h);
359
+ const toFb = (event) => {
360
+ const bounds = canvas.getBoundingClientRect();
361
+ const x = Math.round(((event.clientX - bounds.left) / bounds.width) * width);
362
+ const y = Math.round(((event.clientY - bounds.top) / bounds.height) * height);
354
363
  return [x, y];
355
364
  };
356
- canvas.addEventListener('pointerdown', (e) => {
357
- e.preventDefault();
365
+ canvas.addEventListener('pointerdown', (event) => {
366
+ event.preventDefault();
358
367
  down = true;
359
- canvas.setPointerCapture(e.pointerId);
360
- touch(0, ...toFb(e));
368
+ canvas.setPointerCapture(event.pointerId);
369
+ touch(TOUCH_DOWN, ...toFb(event));
361
370
  });
362
- canvas.addEventListener('pointermove', (e) => {
363
- if (down) touch(1, ...toFb(e));
371
+ canvas.addEventListener('pointermove', (event) => {
372
+ if (down) touch(TOUCH_MOVE, ...toFb(event));
364
373
  });
365
- const release = (e) => {
374
+ const release = (event) => {
366
375
  if (!down) return;
367
376
  down = false;
368
- touch(2, ...toFb(e));
377
+ touch(TOUCH_UP, ...toFb(event));
369
378
  };
370
379
  canvas.addEventListener('pointerup', release);
371
380
  canvas.addEventListener('pointercancel', release);
@@ -378,23 +387,23 @@
378
387
  // minutes of throttling is immediately at the right time. Catching up is cheap however long it was:
379
388
  // the physics integrators cap their step count, timing animations clamp to their duration, and each
380
389
  // timer fires once per pass rather than once per period it missed.
381
- const MAX_DT_MS = 2147483647; // INT32_MAX: er_web_pump takes an int, and that is the only bound needed
390
+ const MAX_ELAPSED_MS = 2147483647; // INT32_MAX: er_web_pump takes an int, and that is the only bound needed
382
391
  // No frame for this long means rAF is stalled and the interval below takes over the pump.
383
392
  const RAF_IDLE_MS = 250;
384
393
 
385
- let prev = performance.now();
394
+ let previousTime = performance.now();
386
395
  let lastFrame = performance.now();
387
396
 
388
397
  const step = (paint) => {
389
398
  const now = performance.now();
390
- const dt = Math.min(MAX_DT_MS, now - prev);
391
- prev = now;
392
- pump(Math.round(dt));
399
+ const elapsedMs = Math.min(MAX_ELAPSED_MS, now - previousTime);
400
+ previousTime = now;
401
+ pump(Math.round(elapsedMs));
393
402
  if (!paint) return;
394
403
  // HEAPU8 may detach when WASM memory grows, so wrap a fresh view each frame, then copy into the
395
404
  // persistent ImageData (robust against detach during the copy).
396
- image.data.set(new Uint8ClampedArray(Module.HEAPU8.buffer, framebuffer(), len));
397
- ctx.putImageData(image, 0, 0);
405
+ image.data.set(new Uint8ClampedArray(Module.HEAPU8.buffer, framebuffer(), byteLength));
406
+ canvasContext.putImageData(image, 0, 0);
398
407
  };
399
408
 
400
409
  const frame = () => {
package/sim-server.mjs CHANGED
@@ -56,8 +56,11 @@ const {transformPersist, shouldPersist} = await import(
56
56
 
57
57
  const REACT_PIN = Object.fromEntries(
58
58
  ['react', 'react-reconciler', 'scheduler']
59
- .map(p => [p, resolve(HERE, 'node_modules', p)])
60
- .filter(([, p]) => existsSync(p)),
59
+ .map(packageName => [
60
+ packageName,
61
+ resolve(HERE, 'node_modules', packageName),
62
+ ])
63
+ .filter(([, pinPath]) => existsSync(pinPath)),
61
64
  );
62
65
 
63
66
  const MIME = {
@@ -66,10 +69,10 @@ const MIME = {
66
69
  '.wasm': 'application/wasm',
67
70
  '.pack': 'application/octet-stream',
68
71
  };
69
- const assetName = p => basename(p).replace(/\.[^.]+$/, '');
70
- const mtime = p => {
72
+ const assetName = filePath => basename(filePath).replace(/\.[^.]+$/, '');
73
+ const mtime = filePath => {
71
74
  try {
72
- return statSync(p).mtimeMs;
75
+ return statSync(filePath).mtimeMs;
73
76
  } catch {
74
77
  return 0;
75
78
  }
@@ -97,23 +100,26 @@ function createBundle({
97
100
  }) {
98
101
  const bundlePath = resolve(outDir, 'app.js');
99
102
  const packPath = resolve(outDir, 'assets.pack');
100
- const projNorm = projectRoot.replace(/\\/g, '/');
103
+ const projectRootNormalized = projectRoot.replace(/\\/g, '/');
101
104
  const images = new Map();
102
105
  const fonts = new Map();
103
- let lastAssetSig = null;
106
+ let lastAssetSignature = null;
104
107
 
105
108
  async function bakePack() {
106
- const bundleSrc = readFileSync(bundlePath, 'utf8');
107
- const usedSizes = analyzeFontSizes(bundleSrc);
109
+ const bundleSource = readFileSync(bundlePath, 'utf8');
110
+ const usedSizes = analyzeFontSizes(bundleSource);
108
111
 
109
- let cfg = {};
110
- const cp = resolve(projectRoot, 'assets.config.js');
111
- if (existsSync(cp))
112
- cfg =
113
- (await import(`${pathToFileURL(cp).href}?t=${mtime(cp)}`)).default ||
114
- {};
115
- const fontConfig = cfg.fonts || {};
116
- const imageConfig = cfg.images || {};
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 || {};
117
123
 
118
124
  const fontJobs = resolveFontJobs(fonts, fontConfig, usedSizes.sizes);
119
125
  const imageJobs = [...images.entries()].map(([name, path]) => ({
@@ -124,44 +130,46 @@ function createBundle({
124
130
 
125
131
  // The app's text is an asset input too: new characters and new font sizes must both be
126
132
  // re-checked against the bake even when no font or image file changed.
127
- const sig = JSON.stringify({
128
- t: textSignature(bundleSrc),
129
- z: fontSizeSignature(usedSizes),
130
- i: imageJobs.map(j => [j.name, j.path, mtime(j.path), j.format]).sort(),
131
- f: fontJobs
132
- .map(j => [
133
- j.family,
134
- j.path,
135
- mtime(j.path),
136
- j.sizes,
137
- j.bpp,
138
- j.glyphs,
139
- j.extraGlyphs,
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,
140
148
  ])
141
149
  .sort(),
142
150
  });
143
- if (sig === lastAssetSig) return;
144
- lastAssetSig = sig;
151
+ if (assetSignature === lastAssetSignature) return;
152
+ lastAssetSignature = assetSignature;
145
153
  if (!imageJobs.length && !fontJobs.length) {
146
154
  // Built-in font only → no pack, but its glyph and size coverage still bind.
147
- warnMissingGlyphs({source: bundleSrc});
155
+ warnMissingGlyphs({source: bundleSource});
148
156
  warnFontSizes({used: usedSizes});
149
157
  return;
150
158
  }
151
159
 
152
160
  try {
153
- const s = bakeAssetPack({
161
+ const summary = bakeAssetPack({
154
162
  images: imageJobs,
155
163
  fonts: fontJobs,
156
164
  outPath: packPath,
157
- source: bundleSrc,
165
+ source: bundleSource,
158
166
  usedSizes,
159
167
  });
160
168
  console.log(
161
- ` assets → ${s.images} image(s), ${s.fonts} font size(s), ${s.bytes} B`,
169
+ ` assets → ${summary.images} image(s), ${summary.fonts} font size(s), ${summary.bytes} B`,
162
170
  );
163
- } catch (e) {
164
- console.error(` asset bake failed: ${e.message}`);
171
+ } catch (error) {
172
+ console.error(` asset bake failed: ${error.message}`);
165
173
  }
166
174
  }
167
175
 
@@ -181,52 +189,63 @@ function createBundle({
181
189
  plugins: [
182
190
  {
183
191
  name: 'embedded-react-websim',
184
- setup(b) {
185
- b.onStart(() => {
192
+ setup(pluginBuild) {
193
+ pluginBuild.onStart(() => {
186
194
  images.clear();
187
195
  fonts.clear();
188
196
  });
189
- b.onLoad({filter: /\.(jsx?|tsx?)$/}, a => {
197
+ pluginBuild.onLoad({filter: /\.(jsx?|tsx?)$/}, loadArgs => {
190
198
  // Transform ONLY the app's own source — never dependencies (see shouldPersist: excluding
191
199
  // node_modules is what stops the library's usePersistentState being rewritten to call itself).
192
- if (!persist || !shouldPersist(a.path, projNorm)) return undefined;
200
+ if (
201
+ !persist ||
202
+ !shouldPersist(loadArgs.path, projectRootNormalized)
203
+ )
204
+ return undefined;
193
205
  try {
194
206
  // Match the esbuild loader to the source extension so TS type syntax (preserved by the
195
207
  // persist transform) is stripped: .tsx → tsx, .ts → ts, .jsx/.js → jsx.
196
- const loader = a.path.endsWith('.tsx')
208
+ const loader = loadArgs.path.endsWith('.tsx')
197
209
  ? 'tsx'
198
- : a.path.endsWith('.ts')
210
+ : loadArgs.path.endsWith('.ts')
199
211
  ? 'ts'
200
212
  : 'jsx';
201
213
  return {
202
214
  contents: transformPersist(
203
- readFileSync(a.path, 'utf8'),
204
- relative(projectRoot, a.path).replace(/\\/g, '/'),
215
+ readFileSync(loadArgs.path, 'utf8'),
216
+ relative(projectRoot, loadArgs.path).replace(/\\/g, '/'),
205
217
  ),
206
218
  loader,
207
219
  };
208
- } catch (e) {
209
- return {errors: [{text: `persist transform: ${e.message}`}]};
220
+ } catch (error) {
221
+ return {errors: [{text: `persist transform: ${error.message}`}]};
210
222
  }
211
223
  });
212
- b.onLoad({filter: /\.(png|jpe?g|webp|gif|bmp)$/i}, a => {
213
- images.set(assetName(a.path), a.path);
214
- return {
215
- contents: `module.exports = ${JSON.stringify(assetName(a.path))};`,
216
- loader: 'js',
217
- };
218
- });
219
- b.onLoad({filter: /\.(ttf|otf)$/i}, a => {
220
- fonts.set(assetName(a.path), a.path);
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
+ };
232
+ },
233
+ );
234
+ pluginBuild.onLoad({filter: /\.(ttf|otf)$/i}, loadArgs => {
235
+ fonts.set(assetName(loadArgs.path), loadArgs.path);
221
236
  return {
222
- contents: `module.exports = ${JSON.stringify(assetName(a.path))};`,
237
+ contents: `module.exports = ${JSON.stringify(assetName(loadArgs.path))};`,
223
238
  loader: 'js',
224
239
  };
225
240
  });
226
- registerSvgVectorLoader(b, (name, p) => images.set(name, p)); // raster-fallback SVGs join the image pack
227
- b.onEnd(async r => {
228
- if (r.errors.length) {
229
- console.error(`✗ build failed (${r.errors.length} error(s))`);
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
+ );
230
249
  return;
231
250
  }
232
251
  await bakePack();
@@ -283,7 +302,7 @@ export async function runDevServer({
283
302
  }) {
284
303
  const clients = new Set();
285
304
  const broadcastReload = () => {
286
- for (const res of clients) res.write('data: reload\n\n');
305
+ for (const response of clients) response.write('data: reload\n\n');
287
306
  };
288
307
 
289
308
  const {options} = createBundle({
@@ -299,38 +318,38 @@ export async function runDevServer({
299
318
  },
300
319
  });
301
320
 
302
- const ctx = await esbuild.context(options);
303
- await ctx.rebuild();
304
- await ctx.watch();
321
+ const buildContext = await esbuild.context(options);
322
+ await buildContext.rebuild();
323
+ await buildContext.watch();
305
324
 
306
325
  // Serve the host page; embedded-react.{js,wasm} from simDir, the freshly bundled app.js/assets.pack from
307
326
  // outDir. The page references ./public/<name>. window.__erHot is injected so the page connects to /reload.
308
- const send = async (res, file) => {
327
+ const send = async (response, file) => {
309
328
  try {
310
329
  const body = await readFile(file);
311
- res
330
+ response
312
331
  .writeHead(200, {
313
332
  'content-type': MIME[extname(file)] || 'application/octet-stream',
314
333
  'cache-control': 'no-store',
315
334
  })
316
335
  .end(body);
317
336
  } catch {
318
- res.writeHead(404).end('not found');
337
+ response.writeHead(404).end('not found');
319
338
  }
320
339
  };
321
- const server = createServer(async (req, res) => {
340
+ const server = createServer(async (request, response) => {
322
341
  const path = decodeURIComponent(
323
- new URL(req.url, 'http://localhost').pathname,
342
+ new URL(request.url, 'http://localhost').pathname,
324
343
  );
325
344
  if (path === '/reload') {
326
- res.writeHead(200, {
345
+ response.writeHead(200, {
327
346
  'content-type': 'text/event-stream',
328
347
  'cache-control': 'no-cache',
329
348
  connection: 'keep-alive',
330
349
  });
331
- res.write('retry: 1000\n\n');
332
- clients.add(res);
333
- req.on('close', () => clients.delete(res));
350
+ response.write('retry: 1000\n\n');
351
+ clients.add(response);
352
+ request.on('close', () => clients.delete(response));
334
353
  return;
335
354
  }
336
355
  if (path === '/' || path === '/index.html') {
@@ -339,14 +358,14 @@ export async function runDevServer({
339
358
  '</head>',
340
359
  '<script>window.__erHot=true</script></head>',
341
360
  );
342
- res
361
+ response
343
362
  .writeHead(200, {
344
363
  'content-type': MIME['.html'],
345
364
  'cache-control': 'no-store',
346
365
  })
347
366
  .end(html);
348
367
  } catch {
349
- res.writeHead(404).end('not found');
368
+ response.writeHead(404).end('not found');
350
369
  }
351
370
  return;
352
371
  }
@@ -356,23 +375,23 @@ export async function runDevServer({
356
375
  name === 'embedded-react.js' || name === 'embedded-react.wasm'
357
376
  ? simDir
358
377
  : outDir;
359
- return void send(res, resolve(dir, name));
378
+ return void send(response, resolve(dir, name));
360
379
  }
361
- res.writeHead(404).end('not found');
380
+ response.writeHead(404).end('not found');
362
381
  });
363
382
 
364
- await new Promise(r => server.listen(port, r));
383
+ await new Promise(onListening => server.listen(port, onListening));
365
384
  console.log(`embedded-react WASM sim → http://localhost:${port}/`);
366
385
  console.log(`watching ${label} — edit & save to hot-reload. Ctrl-C to quit.`);
367
386
 
368
387
  const shutdown = async () => {
369
388
  try {
370
- await ctx.dispose();
389
+ await buildContext.dispose();
371
390
  } catch {}
372
391
  server.close();
373
392
  process.exit(0);
374
393
  };
375
394
  process.on('SIGINT', shutdown);
376
395
  process.on('SIGTERM', shutdown);
377
- return {ctx, server};
396
+ return {ctx: buildContext, server};
378
397
  }