embedded-react 0.5.3 → 0.7.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.
- package/assets/emit-container.mjs +16 -5
- package/cli.mjs +188 -104
- package/hotreload/dev-device.mjs +260 -0
- package/hotreload/pack-app.mjs +187 -0
- package/hotreload/pack-split.mjs +311 -0
- package/hotreload/protocol.mjs +172 -0
- package/hotreload/uploader.mjs +200 -0
- package/hotreload/watch-tree.mjs +103 -0
- package/package.json +6 -1
- package/sim/embedded-react.wasm +0 -0
- package/src/embedded-react/AppRegistry.js +10 -2
|
@@ -32,13 +32,17 @@
|
|
|
32
32
|
// qjs_tag u16 len + bytes — QuickJS release the bytecode targets (loader rejects mismatch)
|
|
33
33
|
// section_count u32
|
|
34
34
|
// sections[section_count]: type u32, len u32, bytes
|
|
35
|
-
// type 1 = QuickJS bytecode (run last)
|
|
35
|
+
// type 1 = QuickJS bytecode (the app — run last)
|
|
36
36
|
// type 2 = ERPK asset pack (registered before the app mounts)
|
|
37
|
+
// type 3 = QuickJS vendor bytecode (react + reconciler + lib — run FIRST, before the app). Optional;
|
|
38
|
+
// present only for the vendor/app split used by incremental hot reload. A container with no
|
|
39
|
+
// type-3 section is a plain monolithic app, loaded exactly as before (backwards-compatible).
|
|
37
40
|
|
|
38
41
|
const FORMAT_VERSION = 1;
|
|
39
42
|
|
|
40
43
|
export const SECTION_BYTECODE = 1;
|
|
41
44
|
export const SECTION_ASSET_PACK = 2;
|
|
45
|
+
export const SECTION_VENDOR_BYTECODE = 3;
|
|
42
46
|
|
|
43
47
|
/**
|
|
44
48
|
* CRC-32/IEEE (zlib polynomial 0xEDB88320), computed without a lookup table to match the C loader's
|
|
@@ -90,12 +94,16 @@ class Writer {
|
|
|
90
94
|
* Serializes a compiled app + assets into an ERCF container.
|
|
91
95
|
*
|
|
92
96
|
* @param {object} opts
|
|
93
|
-
* @param {Buffer|Uint8Array} opts.bytecode
|
|
94
|
-
* @param {Buffer|Uint8Array} [opts.
|
|
95
|
-
*
|
|
97
|
+
* @param {Buffer|Uint8Array} opts.bytecode QuickJS bytecode blob (.qbc) for the app — required.
|
|
98
|
+
* @param {Buffer|Uint8Array} [opts.vendorBytecode] QuickJS bytecode for the vendor chunk (react + reconciler
|
|
99
|
+
* + lib). When present, the loader runs it BEFORE the app
|
|
100
|
+
* (it installs the module registry the app require()s). Omit
|
|
101
|
+
* for a monolithic app — output is then byte-identical to before.
|
|
102
|
+
* @param {Buffer|Uint8Array} [opts.assetPack] ERPK asset pack bytes; omitted/empty → no asset section.
|
|
103
|
+
* @param {string} opts.qjsTag QuickJS release tag the bytecode targets (e.g. "v0.15.0").
|
|
96
104
|
* @returns {Buffer} The container bytes.
|
|
97
105
|
*/
|
|
98
|
-
export function emitContainer({bytecode, assetPack, qjsTag}) {
|
|
106
|
+
export function emitContainer({bytecode, vendorBytecode, assetPack, qjsTag}) {
|
|
99
107
|
if (!bytecode || !bytecode.length)
|
|
100
108
|
throw new Error('emitContainer: bytecode is required');
|
|
101
109
|
if (!qjsTag) throw new Error('emitContainer: qjsTag is required');
|
|
@@ -104,6 +112,9 @@ export function emitContainer({bytecode, assetPack, qjsTag}) {
|
|
|
104
112
|
const body = new Writer();
|
|
105
113
|
body.str(qjsTag);
|
|
106
114
|
const sections = [];
|
|
115
|
+
// Order matters: vendor runs first (registers modules), assets register, then the app runs last.
|
|
116
|
+
if (vendorBytecode && vendorBytecode.length)
|
|
117
|
+
sections.push([SECTION_VENDOR_BYTECODE, vendorBytecode]);
|
|
107
118
|
if (assetPack && assetPack.length)
|
|
108
119
|
sections.push([SECTION_ASSET_PACK, assetPack]);
|
|
109
120
|
sections.push([SECTION_BYTECODE, bytecode]);
|
package/cli.mjs
CHANGED
|
@@ -30,14 +30,19 @@ import {
|
|
|
30
30
|
readFileSync,
|
|
31
31
|
writeFileSync,
|
|
32
32
|
} from 'node:fs';
|
|
33
|
-
import {
|
|
34
|
-
import {
|
|
35
|
-
import {basename, dirname, relative, resolve} from 'node:path';
|
|
33
|
+
import {fileURLToPath} from 'node:url';
|
|
34
|
+
import {dirname, relative, resolve} from 'node:path';
|
|
36
35
|
import {tmpdir} from 'node:os';
|
|
37
36
|
import {buildApp, runDevServer} from './sim-server.mjs';
|
|
37
|
+
import {
|
|
38
|
+
packVendor,
|
|
39
|
+
packApp,
|
|
40
|
+
emitBootContainer,
|
|
41
|
+
} from './hotreload/pack-split.mjs';
|
|
42
|
+
import {runDeviceDevServer} from './hotreload/dev-device.mjs';
|
|
43
|
+
import {detectDevicePorts, preferCalloutPath} from './hotreload/uploader.mjs';
|
|
38
44
|
|
|
39
45
|
const PKG_ROOT = dirname(fileURLToPath(import.meta.url));
|
|
40
|
-
const require = createRequire(import.meta.url);
|
|
41
46
|
|
|
42
47
|
// QuickJS release the bytecode container targets — MUST match bridges/quickjs/CMakeLists.txt and
|
|
43
48
|
// ER_QUICKJS_TAG in er_runtime.c (the device loader rejects a mismatch). The wasm that compiles the
|
|
@@ -49,6 +54,9 @@ function usage() {
|
|
|
49
54
|
|
|
50
55
|
Usage:
|
|
51
56
|
embedded-react dev [entry] [--port <n>] Run the WASM simulator with hot reload
|
|
57
|
+
embedded-react dev [entry] --device [port] Hot-reload on a real board over USB (Flow A): re-pack
|
|
58
|
+
the app and stream it on every save. Omit <port> (or
|
|
59
|
+
pass 'auto') to auto-detect the ESP32 USB-Serial-JTAG.
|
|
52
60
|
embedded-react export [entry] [--out <dir>] Build a self-contained static playground (no server)
|
|
53
61
|
embedded-react build [entry] [--out <dir>] Build the device artifact:
|
|
54
62
|
default → app.erpkg (Flow A: QuickJS bytecode + assets,
|
|
@@ -126,16 +134,158 @@ function resolveEntry(cwd, explicit) {
|
|
|
126
134
|
process.exit(1);
|
|
127
135
|
}
|
|
128
136
|
|
|
137
|
+
function optValue(args, flag) {
|
|
138
|
+
const idx = args.indexOf(flag);
|
|
139
|
+
if (idx < 0) return null;
|
|
140
|
+
const value = args[idx + 1];
|
|
141
|
+
if (!value || value.startsWith('--')) {
|
|
142
|
+
console.error(`Missing value for ${flag}\n`);
|
|
143
|
+
usage();
|
|
144
|
+
process.exit(1);
|
|
145
|
+
}
|
|
146
|
+
return {value, idx, valueIdx: idx + 1};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Like optValue, but the value is OPTIONAL: `--flag` alone → {value: null}; `--flag x` → {value: 'x'}. */
|
|
150
|
+
function optFlagMaybeValue(args, flag) {
|
|
151
|
+
const idx = args.indexOf(flag);
|
|
152
|
+
if (idx < 0) return null;
|
|
153
|
+
const next = args[idx + 1];
|
|
154
|
+
const hasValue = next != null && !next.startsWith('--');
|
|
155
|
+
return {
|
|
156
|
+
value: hasValue ? next : null,
|
|
157
|
+
idx,
|
|
158
|
+
valueIdx: hasValue ? idx + 1 : -1,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** A token that names a serial port rather than an app entry file (so `--device App.jsx` isn't a port). */
|
|
163
|
+
const looksLikeDevicePath = s =>
|
|
164
|
+
/^(\/dev\/|com\d|\\\\\.\\)/i.test(s) ||
|
|
165
|
+
/(tty|usbmodem|usbserial|cu\.)/i.test(s);
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Resolve the `--device` port. An explicit path is the universal, board-agnostic mechanism (any serial
|
|
169
|
+
* port, any board). With no path we auto-detect — but only the ESP32-S3/C3 built-in USB-Serial-JTAG has a
|
|
170
|
+
* fixed USB id to match on, so auto-detect is ESP32-only (at least for now); other boards fall through to the
|
|
171
|
+
* explicit path. Prints an actionable message and exits when the serialport is missing, nothing matches, or
|
|
172
|
+
* it's ambiguous.
|
|
173
|
+
*/
|
|
174
|
+
async function resolveDevicePortOrExit(explicit) {
|
|
175
|
+
if (explicit && explicit !== 'auto') return preferCalloutPath(explicit);
|
|
176
|
+
|
|
177
|
+
const {matches, all, serialportMissing} = await detectDevicePorts();
|
|
178
|
+
if (serialportMissing) {
|
|
179
|
+
console.error(
|
|
180
|
+
"✗ on-device hot reload needs the 'serialport' package.\n" +
|
|
181
|
+
' Install it in your project: npm i serialport',
|
|
182
|
+
);
|
|
183
|
+
process.exit(1);
|
|
184
|
+
}
|
|
185
|
+
if (matches.length === 1) {
|
|
186
|
+
const p = matches[0];
|
|
187
|
+
const path = preferCalloutPath(p.path);
|
|
188
|
+
console.log(
|
|
189
|
+
`✓ auto-detected ESP32 USB-Serial-JTAG at ${path}` +
|
|
190
|
+
(p.serialNumber ? ` (SN ${p.serialNumber})` : ''),
|
|
191
|
+
);
|
|
192
|
+
return path;
|
|
193
|
+
}
|
|
194
|
+
if (matches.length === 0) {
|
|
195
|
+
console.error("✗ couldn't auto-detect a board to hot-reload.");
|
|
196
|
+
console.error(
|
|
197
|
+
' Auto-detect only covers the ESP32-S3/C3 built-in USB-Serial-JTAG (USB 303a:1001) — the one',
|
|
198
|
+
);
|
|
199
|
+
console.error(
|
|
200
|
+
' board with a fixed USB id. For any other board (STM32, RP2040, …) pass the port explicitly:',
|
|
201
|
+
);
|
|
202
|
+
console.error(' embedded-react dev --device <port>');
|
|
203
|
+
if (all.length) {
|
|
204
|
+
console.error('\n Serial ports seen (pick yours):');
|
|
205
|
+
for (const p of all)
|
|
206
|
+
console.error(
|
|
207
|
+
` ${p.path}` +
|
|
208
|
+
(p.vendorId && p.productId
|
|
209
|
+
? ` [${p.vendorId}:${p.productId}]`
|
|
210
|
+
: '') +
|
|
211
|
+
(p.manufacturer ? ` ${p.manufacturer}` : ''),
|
|
212
|
+
);
|
|
213
|
+
} else {
|
|
214
|
+
console.error(
|
|
215
|
+
'\n (no serial ports detected at all — is anything connected? is the cable data-capable?)',
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
console.error(
|
|
219
|
+
'\n On an ESP32, if auto-detect should have worked: use its NATIVE USB port (not the flashing UART),',
|
|
220
|
+
);
|
|
221
|
+
console.error(
|
|
222
|
+
' and make sure the firmware has on-device hot reload enabled.',
|
|
223
|
+
);
|
|
224
|
+
process.exit(1);
|
|
225
|
+
}
|
|
226
|
+
console.error(
|
|
227
|
+
`✗ found ${matches.length} ESP32 USB-Serial-JTAG ports; pass one explicitly with --device <port>:`,
|
|
228
|
+
);
|
|
229
|
+
for (const p of matches)
|
|
230
|
+
console.error(
|
|
231
|
+
` ${preferCalloutPath(p.path)}${p.serialNumber ? ` (SN ${p.serialNumber})` : ''}`,
|
|
232
|
+
);
|
|
233
|
+
process.exit(1);
|
|
234
|
+
}
|
|
235
|
+
|
|
129
236
|
async function dev(args) {
|
|
130
237
|
const cwd = process.cwd();
|
|
131
|
-
const
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
)
|
|
238
|
+
const deviceOpt = optFlagMaybeValue(args, '--device');
|
|
239
|
+
|
|
240
|
+
// --device [port] → stream the app to a real board over USB on every save (on-device hot reload).
|
|
241
|
+
// With no port (or `auto`), the ESP32 USB-Serial-JTAG is auto-detected. Otherwise → the WASM simulator.
|
|
242
|
+
if (deviceOpt) {
|
|
243
|
+
// The token-after --device is normally the port. But `--device App.jsx` means "auto-detect + this
|
|
244
|
+
// entry": if the value names an existing file (and isn't a device path), treat it as the entry.
|
|
245
|
+
let deviceValue = deviceOpt.value;
|
|
246
|
+
let entryFromDeviceSlot = null;
|
|
247
|
+
if (
|
|
248
|
+
deviceValue &&
|
|
249
|
+
deviceValue !== 'auto' &&
|
|
250
|
+
!looksLikeDevicePath(deviceValue) &&
|
|
251
|
+
existsSync(resolve(cwd, deviceValue))
|
|
252
|
+
) {
|
|
253
|
+
entryFromDeviceSlot = deviceValue;
|
|
254
|
+
deviceValue = null; // fall through to auto-detect
|
|
255
|
+
}
|
|
256
|
+
const explicit =
|
|
257
|
+
entryFromDeviceSlot ??
|
|
258
|
+
args.find(
|
|
259
|
+
(a, i) =>
|
|
260
|
+
!a.startsWith('--') &&
|
|
261
|
+
i !== deviceOpt.idx &&
|
|
262
|
+
i !== deviceOpt.valueIdx,
|
|
263
|
+
);
|
|
264
|
+
|
|
265
|
+
const simDir = simDirOrExit();
|
|
266
|
+
const entry = resolveEntry(cwd, explicit);
|
|
267
|
+
const device = await resolveDevicePortOrExit(deviceValue);
|
|
268
|
+
|
|
269
|
+
await runDeviceDevServer({
|
|
270
|
+
entry,
|
|
271
|
+
projectRoot: cwd,
|
|
272
|
+
libSrc: libSrc(),
|
|
273
|
+
nodePaths: nodePaths(cwd),
|
|
274
|
+
simDir,
|
|
275
|
+
device,
|
|
276
|
+
label: entry,
|
|
277
|
+
});
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const portOpt = optValue(args, '--port');
|
|
282
|
+
const consumed = new Set(portOpt ? [portOpt.idx, portOpt.valueIdx] : []);
|
|
283
|
+
const explicit = args.find((a, i) => !a.startsWith('--') && !consumed.has(i));
|
|
136
284
|
|
|
137
285
|
const simDir = simDirOrExit();
|
|
138
286
|
const entry = resolveEntry(cwd, explicit);
|
|
287
|
+
|
|
288
|
+
const port = portOpt ? parseInt(portOpt.value, 10) : 3333;
|
|
139
289
|
const outDir = resolve(tmpdir(), 'embedded-react-sim');
|
|
140
290
|
mkdirSync(outDir, {recursive: true});
|
|
141
291
|
|
|
@@ -243,116 +393,50 @@ async function buildAot(cwd, explicit, outDir) {
|
|
|
243
393
|
);
|
|
244
394
|
}
|
|
245
395
|
|
|
246
|
-
/**
|
|
396
|
+
/**
|
|
397
|
+
* Flow A (default): bundle → QuickJS bytecode (via the prebuilt wasm) + baked assets → app.erpkg.
|
|
398
|
+
*
|
|
399
|
+
* The artifact is the vendor/app SPLIT: a vendor section (react + reconciler + the embedded-react lib,
|
|
400
|
+
* ~94% of the bytecode) plus an app section. The device runs the vendor first, then the app — and on a
|
|
401
|
+
* hot reload it keeps the resident vendor and swaps just the ~6% app section. The same firmware boots
|
|
402
|
+
* this for production and hot-reloads it. The loader still accepts a plain monolithic container, so older
|
|
403
|
+
* artifacts keep booting unchanged.
|
|
404
|
+
*/
|
|
247
405
|
async function buildContainer(cwd, explicit, outDir) {
|
|
248
|
-
const esbuild = require('esbuild');
|
|
249
|
-
const {bakeImage} = await import('./assets/bake-image.mjs');
|
|
250
|
-
const {bakeFont} = await import('./assets/bake-font.mjs');
|
|
251
|
-
const {emitAssetPack} = await import('./assets/emit-pack.mjs');
|
|
252
|
-
const {emitContainer} = await import('./assets/emit-container.mjs');
|
|
253
|
-
const {registerSvgVectorLoader} = await import('./assets/svg-loader.mjs');
|
|
254
|
-
const {compileToBytecode} = await import('./qjsc-wasm.mjs');
|
|
255
|
-
|
|
256
406
|
const simDir = simDirOrExit();
|
|
257
407
|
const entry = resolveEntry(cwd, explicit);
|
|
408
|
+
const lib = libSrc();
|
|
409
|
+
const paths = nodePaths(cwd);
|
|
258
410
|
|
|
259
|
-
|
|
260
|
-
const
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
const n = basename(a.path).replace(/\.[^.]+$/, '');
|
|
267
|
-
images.set(n, a.path);
|
|
268
|
-
return {
|
|
269
|
-
contents: `module.exports = ${JSON.stringify(n)};`,
|
|
270
|
-
loader: 'js',
|
|
271
|
-
};
|
|
272
|
-
});
|
|
273
|
-
b.onLoad({filter: /\.(ttf|otf)$/i}, a => {
|
|
274
|
-
const f = basename(a.path).replace(/\.[^.]+$/, '');
|
|
275
|
-
fonts.set(f, a.path);
|
|
276
|
-
return {
|
|
277
|
-
contents: `module.exports = ${JSON.stringify(f)};`,
|
|
278
|
-
loader: 'js',
|
|
279
|
-
};
|
|
280
|
-
});
|
|
281
|
-
registerSvgVectorLoader(b, (name, p) => images.set(name, p)); // raster-fallback SVGs join the image pack
|
|
282
|
-
},
|
|
283
|
-
};
|
|
284
|
-
// The bundle is an intermediate (it becomes bytecode in the .erpkg) — keep it out of the user's outDir
|
|
285
|
-
// so `dist/` ends up holding only app.erpkg.
|
|
286
|
-
const tmp = resolve(tmpdir(), 'embedded-react-build');
|
|
287
|
-
mkdirSync(tmp, {recursive: true});
|
|
288
|
-
const bundlePath = resolve(tmp, 'app.bundle.js');
|
|
289
|
-
await esbuild.build({
|
|
290
|
-
entryPoints: [entry],
|
|
291
|
-
bundle: true,
|
|
292
|
-
format: 'iife',
|
|
293
|
-
outfile: bundlePath,
|
|
294
|
-
platform: 'neutral',
|
|
295
|
-
target: 'es2020',
|
|
296
|
-
jsx: 'automatic',
|
|
297
|
-
alias: {'embedded-react': libSrc()},
|
|
298
|
-
nodePaths: nodePaths(cwd),
|
|
299
|
-
plugins: [assetPlugin],
|
|
300
|
-
define: {'process.env.NODE_ENV': '"production"'},
|
|
301
|
-
legalComments: 'none',
|
|
302
|
-
logLevel: 'silent',
|
|
411
|
+
const vendor = await packVendor({libSrc: lib, nodePaths: paths, simDir});
|
|
412
|
+
const app = await packApp({
|
|
413
|
+
entry,
|
|
414
|
+
projectRoot: cwd,
|
|
415
|
+
libSrc: lib,
|
|
416
|
+
nodePaths: paths,
|
|
417
|
+
simDir,
|
|
303
418
|
});
|
|
304
|
-
const
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
// Bake imported images/fonts into an ERPK pack (font sizes discovered from the bundle).
|
|
310
|
-
const discoveredSizes = [
|
|
311
|
-
...new Set(
|
|
312
|
-
[...bundleSrc.matchAll(/\bfontSize\s*:\s*(\d+(?:\.\d+)?)/g)].map(m =>
|
|
313
|
-
Math.round(Number(m[1])),
|
|
314
|
-
),
|
|
315
|
-
),
|
|
316
|
-
].sort((a, b) => a - b);
|
|
317
|
-
let cfg = {};
|
|
318
|
-
const cp = resolve(cwd, 'assets.config.js');
|
|
319
|
-
if (existsSync(cp))
|
|
320
|
-
cfg = (await import(pathToFileURL(cp).href)).default || {};
|
|
321
|
-
const fontConfig = cfg.fonts || {};
|
|
322
|
-
const fontJobs = [...fonts.entries()].map(([family, path]) => {
|
|
323
|
-
const fc = fontConfig[family] || {};
|
|
324
|
-
return {
|
|
325
|
-
path,
|
|
326
|
-
family,
|
|
327
|
-
sizes: fc.sizes?.length
|
|
328
|
-
? fc.sizes
|
|
329
|
-
: discoveredSizes.length
|
|
330
|
-
? discoveredSizes
|
|
331
|
-
: [16],
|
|
332
|
-
bpp: fc.bpp ?? 4,
|
|
333
|
-
glyphs: fc.glyphs ?? 'ascii',
|
|
334
|
-
};
|
|
419
|
+
const container = await emitBootContainer({
|
|
420
|
+
vendorBytecode: vendor.bytecode,
|
|
421
|
+
appBytecode: app.bytecode,
|
|
422
|
+
assetPack: app.assetPack,
|
|
335
423
|
});
|
|
336
|
-
|
|
337
|
-
const bakedImages = imageJobs.map(bakeImage);
|
|
338
|
-
const bakedFonts = fontJobs.map(bakeFont);
|
|
339
|
-
const assetPack =
|
|
340
|
-
bakedImages.length || bakedFonts.length
|
|
341
|
-
? emitAssetPack({images: bakedImages, fonts: bakedFonts})
|
|
342
|
-
: null;
|
|
343
|
-
|
|
344
|
-
const container = emitContainer({bytecode, assetPack, qjsTag: QJS_TAG});
|
|
424
|
+
|
|
345
425
|
const outPath = resolve(outDir, 'app.erpkg');
|
|
346
426
|
writeFileSync(outPath, container);
|
|
347
427
|
const kb = n => `${(n / 1024).toFixed(1)} KB`;
|
|
348
428
|
console.log(
|
|
349
|
-
`✓ Flow A → ${relative(cwd, outPath) || 'app.erpkg'} (${kb(container.length)}; qjs ${QJS_TAG},
|
|
350
|
-
(
|
|
429
|
+
`✓ Flow A → ${relative(cwd, outPath) || 'app.erpkg'} (${kb(container.length)}; qjs ${QJS_TAG}, ` +
|
|
430
|
+
`vendor ${kb(vendor.bytecodeLen)} + app ${kb(app.bytecodeLen)}` +
|
|
431
|
+
(app.assetsLen ? `, assets ${kb(app.assetsLen)}` : '') +
|
|
351
432
|
')',
|
|
352
433
|
);
|
|
353
434
|
console.log(
|
|
354
435
|
" Upload app.erpkg to your device's config region (er_runtime_load_container), or run it on the desktop host.",
|
|
355
436
|
);
|
|
437
|
+
console.log(
|
|
438
|
+
' Tip: `embedded-react dev --device <port>` hot-reloads this app live over USB on every save.',
|
|
439
|
+
);
|
|
356
440
|
}
|
|
357
441
|
|
|
358
442
|
/** `embedded-react build [--aot] [entry] [--out dir]` — produce the device artifact. */
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright 2026 Cory Lamming
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
// dev-device — the on-device hot-reload dev loop (`embedded-react dev --device <port>`).
|
|
18
|
+
//
|
|
19
|
+
// Watches the project, re-packs the app to an .erpkg on every save (the same Flow A build the device
|
|
20
|
+
// boots from), streams it over the serial/USB port as an ERHR frame, and prints the device's logs that
|
|
21
|
+
// come back. The firmware swaps the new config in live — no reflash, no reboot. State written with
|
|
22
|
+
// usePersistentState (or plain useState in this dev mode) survives the reload, like the simulator.
|
|
23
|
+
|
|
24
|
+
import {relative} from 'node:path';
|
|
25
|
+
import {packApp, emitAppFrame} from './pack-split.mjs';
|
|
26
|
+
import {SerialUploader, listSerialPorts} from './uploader.mjs';
|
|
27
|
+
import {watchTree} from './watch-tree.mjs';
|
|
28
|
+
|
|
29
|
+
const kb = n => `${(n / 1024).toFixed(1)} KB`;
|
|
30
|
+
|
|
31
|
+
/** Debounce: coalesce a burst of file events (editors often write several) into one rebuild. */
|
|
32
|
+
function debounce(fn, ms) {
|
|
33
|
+
let t = null;
|
|
34
|
+
return (...args) => {
|
|
35
|
+
if (t) clearTimeout(t);
|
|
36
|
+
t = setTimeout(() => {
|
|
37
|
+
t = null;
|
|
38
|
+
fn(...args);
|
|
39
|
+
}, ms);
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Run the device hot-reload dev loop until interrupted.
|
|
45
|
+
*
|
|
46
|
+
* @param {object} o
|
|
47
|
+
* @param {string} o.entry, o.projectRoot, o.libSrc, o.simDir, o.label, o.device
|
|
48
|
+
* @param {string[]} o.nodePaths
|
|
49
|
+
*/
|
|
50
|
+
export async function runDeviceDevServer({
|
|
51
|
+
entry,
|
|
52
|
+
projectRoot,
|
|
53
|
+
libSrc,
|
|
54
|
+
nodePaths,
|
|
55
|
+
simDir,
|
|
56
|
+
device,
|
|
57
|
+
label,
|
|
58
|
+
}) {
|
|
59
|
+
// Each push ends with exactly one terminal line in the device's log stream:
|
|
60
|
+
// "hot reload: ok (...)" → loaded and running
|
|
61
|
+
// "hot reload: <reason>" → loaded but the container was rejected (an app/runtime error)
|
|
62
|
+
// "dropped frame: <reason>" → the upload was corrupt / overran the device's RX buffer (transport)
|
|
63
|
+
// We watch for it to gate the next send (so a second push can't land while the device is still
|
|
64
|
+
// applying — which would overrun its RX buffer and corrupt that frame) and to resend after a drop.
|
|
65
|
+
let settleOutcome = null;
|
|
66
|
+
// Track whether the board is alive at all (any log line) and whether a hot-reload RECEIVER is actually
|
|
67
|
+
// running (it prints a "hot reload: …" or "dropped frame: …" line per frame). Firmware built WITHOUT
|
|
68
|
+
// ER_HOTRELOAD still prints normal logs but never those — that's how we flag a disabled build below.
|
|
69
|
+
let sawAnyLog = false;
|
|
70
|
+
let sawReceiverAck = false;
|
|
71
|
+
let closing = false; // set on Ctrl-C so we don't surface errors from a write canceled by the shutdown
|
|
72
|
+
const onDeviceLog = line => {
|
|
73
|
+
if (closing) return;
|
|
74
|
+
sawAnyLog = true;
|
|
75
|
+
console.log(` ▸ ${line}`);
|
|
76
|
+
if (/dropped frame/i.test(line) || /hot reload:/i.test(line))
|
|
77
|
+
sawReceiverAck = true;
|
|
78
|
+
if (!settleOutcome) return;
|
|
79
|
+
if (/dropped frame/i.test(line)) settleOutcome('dropped');
|
|
80
|
+
else if (/hot reload:\s*ok\b/i.test(line)) settleOutcome('ok');
|
|
81
|
+
else if (/hot reload:/i.test(line)) settleOutcome('rejected');
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const uploader = new SerialUploader({device, onLog: onDeviceLog});
|
|
85
|
+
|
|
86
|
+
try {
|
|
87
|
+
await uploader.open();
|
|
88
|
+
} catch (e) {
|
|
89
|
+
console.error(`✗ ${e.message}`);
|
|
90
|
+
const ports = await listSerialPorts();
|
|
91
|
+
if (ports.length) {
|
|
92
|
+
console.error('\nAvailable ports:');
|
|
93
|
+
for (const p of ports)
|
|
94
|
+
console.error(
|
|
95
|
+
` ${p.path}${p.manufacturer ? ` (${p.manufacturer})` : ''}`,
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
process.exit(1);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
console.log(`embedded-react on-device hot reload → ${device}`);
|
|
102
|
+
console.log(
|
|
103
|
+
`watching ${relative(projectRoot, entry) || label} — edit & save to push. Ctrl-C to quit.`,
|
|
104
|
+
);
|
|
105
|
+
console.log(
|
|
106
|
+
' sending app-only frames; the device must be running a split build (embedded-react build) so the vendor is resident.',
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
const APPLY_TIMEOUT_MS = 15000; // a normal reload settles in ~3-4 s; this only catches a stuck device
|
|
110
|
+
const PROBE_TIMEOUT_MS = 8000; // initial push: shorter, so a hot-reload-disabled board is flagged fast
|
|
111
|
+
const MAX_RESENDS = 2;
|
|
112
|
+
|
|
113
|
+
/** Resolves with the device's terminal status ('ok' | 'rejected' | 'dropped' | 'timeout') for the
|
|
114
|
+
* push currently in flight. */
|
|
115
|
+
const nextOutcome = (timeoutMs = APPLY_TIMEOUT_MS) =>
|
|
116
|
+
new Promise(resolve => {
|
|
117
|
+
let done = false;
|
|
118
|
+
const finish = r => {
|
|
119
|
+
if (done) return;
|
|
120
|
+
done = true;
|
|
121
|
+
settleOutcome = null;
|
|
122
|
+
clearTimeout(timer);
|
|
123
|
+
resolve(r);
|
|
124
|
+
};
|
|
125
|
+
const timer = setTimeout(() => finish('timeout'), timeoutMs);
|
|
126
|
+
settleOutcome = finish; // armed before the send so the terminal log can't be missed
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
/** Send a container and wait for the device to apply it, resending on a transport drop/timeout. */
|
|
130
|
+
const sendAndConfirm = async (
|
|
131
|
+
container,
|
|
132
|
+
{
|
|
133
|
+
timeoutMs = APPLY_TIMEOUT_MS,
|
|
134
|
+
maxResends = MAX_RESENDS,
|
|
135
|
+
probe = false,
|
|
136
|
+
} = {},
|
|
137
|
+
) => {
|
|
138
|
+
for (let attempt = 0; ; attempt++) {
|
|
139
|
+
const outcome = nextOutcome(timeoutMs);
|
|
140
|
+
uploader.send(container).catch(err => {
|
|
141
|
+
if (closing) return;
|
|
142
|
+
if (settleOutcome) settleOutcome('senderr');
|
|
143
|
+
else console.error(`✗ send failed: ${err.message}`);
|
|
144
|
+
});
|
|
145
|
+
const result = await outcome;
|
|
146
|
+
if (result === 'ok' || result === 'rejected') return result;
|
|
147
|
+
// On the initial probe, a timeout / write stall means nothing is consuming frames — don't spin.
|
|
148
|
+
if (probe && (result === 'timeout' || result === 'senderr'))
|
|
149
|
+
return result;
|
|
150
|
+
if (attempt >= maxResends) {
|
|
151
|
+
console.error(
|
|
152
|
+
`✗ reload ${result} after ${attempt + 1} attempts — save again to retry`,
|
|
153
|
+
);
|
|
154
|
+
return result;
|
|
155
|
+
}
|
|
156
|
+
console.log(`↻ ${result}; resending (${attempt + 1}/${maxResends})…`);
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
// Single-flight: one build→send→apply cycle at a time. A save that lands mid-cycle just re-arms it, so
|
|
161
|
+
// we rebuild and resend the latest source once the current reload settles — pushes never overlap.
|
|
162
|
+
let inFlight = false;
|
|
163
|
+
let queued = false;
|
|
164
|
+
const reloadCycle = async ({probe = false} = {}) => {
|
|
165
|
+
if (inFlight) {
|
|
166
|
+
queued = true;
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
inFlight = true;
|
|
170
|
+
try {
|
|
171
|
+
let firstSend = probe; // the probe timeout applies to the initial push only
|
|
172
|
+
do {
|
|
173
|
+
queued = false;
|
|
174
|
+
const started = Date.now();
|
|
175
|
+
let container, bytecodeLen, assetsLen;
|
|
176
|
+
try {
|
|
177
|
+
const app = await packApp({
|
|
178
|
+
entry,
|
|
179
|
+
projectRoot,
|
|
180
|
+
libSrc,
|
|
181
|
+
nodePaths,
|
|
182
|
+
simDir,
|
|
183
|
+
persist: true,
|
|
184
|
+
});
|
|
185
|
+
container = await emitAppFrame({
|
|
186
|
+
appBytecode: app.bytecode,
|
|
187
|
+
assetPack: app.assetPack,
|
|
188
|
+
});
|
|
189
|
+
bytecodeLen = app.bytecodeLen;
|
|
190
|
+
assetsLen = app.assetsLen;
|
|
191
|
+
} catch (e) {
|
|
192
|
+
console.error(`✗ build failed: ${e.message}`);
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
const result = await sendAndConfirm(
|
|
196
|
+
container,
|
|
197
|
+
firstSend ? {timeoutMs: PROBE_TIMEOUT_MS, probe: true} : {},
|
|
198
|
+
);
|
|
199
|
+
firstSend = false;
|
|
200
|
+
if (result === 'ok') {
|
|
201
|
+
console.log(
|
|
202
|
+
`↻ reloaded app ${kb(container.length)} (bytecode ${kb(bytecodeLen)}` +
|
|
203
|
+
(assetsLen ? `, assets ${kb(assetsLen)}` : '') +
|
|
204
|
+
`) in ${Date.now() - started} ms`,
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
} while (queued);
|
|
208
|
+
} finally {
|
|
209
|
+
inFlight = false;
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
// Before flooding the port with a frame, give the board a moment to prove it's alive (one log line is
|
|
214
|
+
// enough). Flooding a firmware that never drains its RX can congest the link, so we sample liveness
|
|
215
|
+
// first — this is also what tells "hot reload disabled" apart from "dead/wrong port" if no ack comes.
|
|
216
|
+
for (let i = 0; i < 30 && !sawAnyLog; i++)
|
|
217
|
+
await new Promise(r => setTimeout(r, 100));
|
|
218
|
+
|
|
219
|
+
await reloadCycle({probe: true});
|
|
220
|
+
if (!sawReceiverAck) {
|
|
221
|
+
console.warn('');
|
|
222
|
+
console.warn('⚠ the board never acknowledged the hot-reload frame.');
|
|
223
|
+
if (sawAnyLog) {
|
|
224
|
+
console.warn(
|
|
225
|
+
' It IS sending logs, so the port is right — but nothing is consuming reload frames.',
|
|
226
|
+
);
|
|
227
|
+
console.warn(
|
|
228
|
+
" Its firmware likely doesn't have the on-device hot-reload receiver enabled.",
|
|
229
|
+
);
|
|
230
|
+
} else {
|
|
231
|
+
console.warn(
|
|
232
|
+
' No logs are coming back either — check the USB cable/port, and that the app is running.',
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
console.warn(' (still watching — fix it and save again to retry)');
|
|
236
|
+
console.warn('');
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const onChange = debounce(reloadCycle, 120);
|
|
240
|
+
const onWatchEvent = (_event, file) => {
|
|
241
|
+
if (!file) return;
|
|
242
|
+
// Ignore churn that can't affect the bundle (build output, deps, VCS, editor temp files).
|
|
243
|
+
if (/(^|\/)(node_modules|dist|\.git)(\/|$)/.test(file)) return;
|
|
244
|
+
if (/\.(erpkg|map)$|~$|\.swp$/.test(file)) return;
|
|
245
|
+
onChange();
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
// Recursively watch the project so edits under src/** push too — on every platform, including ones
|
|
249
|
+
// where fs.watch's native {recursive:true} isn't available (older Linux/Node).
|
|
250
|
+
const watcher = watchTree(projectRoot, onWatchEvent);
|
|
251
|
+
|
|
252
|
+
const shutdown = async () => {
|
|
253
|
+
closing = true;
|
|
254
|
+
watcher.close();
|
|
255
|
+
await uploader.close();
|
|
256
|
+
process.exit(0);
|
|
257
|
+
};
|
|
258
|
+
process.on('SIGINT', shutdown);
|
|
259
|
+
process.on('SIGTERM', shutdown);
|
|
260
|
+
}
|