embedded-react 0.11.1 → 0.13.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.
@@ -0,0 +1,281 @@
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
+ // Build-time glyph-coverage check: a character the app renders but the bake has no glyph for is
18
+ // silently substituted with '?' by the engine (font_glyph() in engine/font/font_bitmap.c), so the
19
+ // only way to find out used to be looking at the device. Every bake path (build, pack, sim, hot
20
+ // reload, AOT) runs this over the app source and warns with the `assets.config.js` line that fixes it.
21
+ //
22
+ // The check is source-driven: it reads string and template literals (plus JSX element text, for the
23
+ // unbundled `.jsx` the AOT flow compiles). Non-ASCII from a runtime source — a fetched string,
24
+ // String.fromCharCode — can't be seen here. Comments are skipped: an em dash in prose is not text.
25
+ import {
26
+ ASCII_FIRST,
27
+ ASCII_LAST,
28
+ BUILTIN_EXTRAS,
29
+ loadGlyphProbe,
30
+ } from './bake-font.mjs';
31
+
32
+ /** Name used for the engine's fallback font in warnings (it has no family of its own). */
33
+ export const BUILTIN_FAMILY = 'the built-in font';
34
+
35
+ // Comments first so an apostrophe inside one can't open a bogus string; then the three literal
36
+ // forms. Bundled output is machine-generated, so the simple form is enough (a regex literal
37
+ // containing a lone quote is the only realistic misread, and it costs at most a stray sample).
38
+ const LITERALS =
39
+ /\/\/[^\n]*|\/\*[\s\S]*?\*\/|'(?:[^'\\\n]|\\[\s\S])*'|"(?:[^"\\\n]|\\[\s\S])*"|`(?:[^`\\]|\\[\s\S])*`/g;
40
+
41
+ const SIMPLE_ESCAPES = {n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', v: '\v'};
42
+
43
+ /** Resolves the \u{...}, \uXXXX, \xNN and simple escapes a bundler emits back to characters. */
44
+ function decodeEscapes(body) {
45
+ return body.replace(
46
+ /\\u\{([0-9a-fA-F]{1,6})\}|\\u([0-9a-fA-F]{4})|\\x([0-9a-fA-F]{2})|\\([\s\S])/g,
47
+ (_m, braced, u, x, other) => {
48
+ if (braced !== undefined) {
49
+ const cp = parseInt(braced, 16);
50
+ return cp <= 0x10ffff ? String.fromCodePoint(cp) : '';
51
+ }
52
+ if (u !== undefined) return String.fromCharCode(parseInt(u, 16));
53
+ if (x !== undefined) return String.fromCharCode(parseInt(x, 16));
54
+ return SIMPLE_ESCAPES[other] ?? other; // \\ \' \" \` and friends: the character itself
55
+ },
56
+ );
57
+ }
58
+
59
+ /** Invisible/formatting characters that are never baked and never render — not worth warning about. */
60
+ function ignorable(cp) {
61
+ return (
62
+ (cp >= 0x7f && cp <= 0x9f) || // DEL + C1 controls
63
+ (cp >= 0x200b && cp <= 0x200f) || // zero-width + bidi marks
64
+ (cp >= 0x2028 && cp <= 0x202e) || // line/paragraph separators + bidi overrides
65
+ (cp >= 0xfe00 && cp <= 0xfe0f) || // variation selectors
66
+ cp === 0xfeff // BOM
67
+ );
68
+ }
69
+
70
+ // Text between two tags in unbundled JSX: `<Text>24° out</Text>`. Braces are excluded so an
71
+ // expression child stays out of it — its own literals are already covered by LITERALS.
72
+ const JSX_TEXT = />([^<>{}]+)</g;
73
+
74
+ /**
75
+ * Collects every non-ASCII character that appears in the app's rendered text.
76
+ *
77
+ * @param {string} source JS source (a bundle, a chunk, or a single component file).
78
+ * @param {object} [opts]
79
+ * @param {boolean} [opts.jsx] Also read JSX element text. Set it for unbundled `.jsx` — a bundler
80
+ * has already turned element text into string literals, and on bundled output the extra
81
+ * pass would only misread `a > b` comparisons.
82
+ * @returns {Map<number, string>} Codepoint → a short excerpt of the text it was found in.
83
+ */
84
+ export function scanTextCodepoints(source, {jsx = false} = {}) {
85
+ const found = new Map();
86
+ const collect = text => {
87
+ let i = 0;
88
+ for (const ch of text) {
89
+ const cp = ch.codePointAt(0);
90
+ if (cp > ASCII_LAST && !ignorable(cp) && !found.has(cp))
91
+ found.set(cp, excerpt(text, i, ch.length));
92
+ i += ch.length;
93
+ }
94
+ };
95
+
96
+ // Blank each token out as it is read, so the JSX pass below sees neither strings (already
97
+ // collected) nor comments (never rendered) — only real element text.
98
+ const bare = source.replace(LITERALS, tok => {
99
+ if (tok[0] !== '/') collect(decodeEscapes(tok.slice(1, -1)));
100
+ return ' '.repeat(tok.length);
101
+ });
102
+ if (jsx) for (const m of bare.matchAll(JSX_TEXT)) collect(m[1]);
103
+ return found;
104
+ }
105
+
106
+ /**
107
+ * Compact signature of the non-ASCII characters a source renders. Watch loops fold this into their
108
+ * "did the asset inputs change?" key so new text is re-checked, not just new fonts.
109
+ *
110
+ * @param {string} source JS source to scan.
111
+ * @param {object} [opts] Passed through to scanTextCodepoints (e.g. `{jsx: true}`).
112
+ * @returns {string} Sorted codepoints, comma-joined.
113
+ */
114
+ export function textSignature(source, opts) {
115
+ return [...scanTextCodepoints(source, opts).keys()]
116
+ .sort((a, b) => a - b)
117
+ .join(',');
118
+ }
119
+
120
+ /** A one-line, printable window of `text` around the character at `at` (a UTF-16 index). */
121
+ function excerpt(text, at, len) {
122
+ const start = Math.max(0, at - 12);
123
+ const end = Math.min(text.length, at + len + 12);
124
+ const body = text
125
+ .slice(start, end)
126
+ .replace(/[\n\r\t]/g, ' ')
127
+ .replace(/^[\udc00-\udfff]|[\ud800-\udbff]$/g, '') // a pair split by the window
128
+ .trim();
129
+ return `${start > 0 ? '…' : ''}${body}${end < text.length ? '…' : ''}`;
130
+ }
131
+
132
+ /** The set of codepoints a baked font can render: the dense ASCII range plus its baked extras. */
133
+ function coverageOf(baked) {
134
+ const size = baked.sizes?.[0];
135
+ const covered = new Set();
136
+ const first = size ? size.first : ASCII_FIRST;
137
+ const last = size ? size.last : ASCII_LAST;
138
+ for (let cp = first; cp <= last; cp++) covered.add(cp);
139
+ for (const e of size?.extras ?? []) covered.add(e.codepoint);
140
+ return covered;
141
+ }
142
+
143
+ /** The engine's fallback font, shaped like a bakeFont() result so both go through one code path. */
144
+ function builtinFont() {
145
+ return {
146
+ family: BUILTIN_FAMILY,
147
+ sizes: [
148
+ {
149
+ first: ASCII_FIRST,
150
+ last: ASCII_LAST,
151
+ extras: BUILTIN_EXTRAS.map(codepoint => ({codepoint})),
152
+ },
153
+ ],
154
+ };
155
+ }
156
+
157
+ /**
158
+ * Finds the characters the app renders that some font in the bake has no glyph for.
159
+ *
160
+ * Which fonts are checked follows what the app can actually draw with: with imported fonts, each
161
+ * baked font is checked (text using that family is the whole reason it was imported, and a
162
+ * character the app's own font lacks is exactly the bug worth reporting); with none, the engine's
163
+ * built-in fallback is checked instead.
164
+ *
165
+ * @param {object} opts
166
+ * @param {string} opts.source App/bundle JS to scan for rendered text.
167
+ * @param {Array<object>} [opts.fonts] bakeFont() results; empty means built-in font only.
168
+ * @param {boolean} [opts.jsx] Source is unbundled JSX — read element text too.
169
+ * @returns {Array<{codepoint:number, char:string, sample:string, missingFrom:string[],
170
+ * noGlyphIn:string[]}>} Sorted by codepoint. `noGlyphIn` narrows `missingFrom` to the
171
+ * fonts whose file has no glyph for the character at all — baking it there can't help.
172
+ */
173
+ export function findMissingGlyphs({source, fonts = [], jsx = false}) {
174
+ const checked = fonts.length ? fonts : [builtinFont()];
175
+ const coverage = checked.map(f => ({
176
+ family: f.family,
177
+ path: f.path,
178
+ covered: coverageOf(f),
179
+ }));
180
+ // Opened lazily and only for a font with a gap: most builds have none and pay nothing.
181
+ const probes = new Map();
182
+ const hasGlyph = (font, cp) => {
183
+ if (!font.path) return true; // the built-in font's coverage is its bake, nothing more to ask
184
+ if (!probes.has(font.path))
185
+ probes.set(font.path, loadGlyphProbe(font.path));
186
+ return probes.get(font.path)(cp);
187
+ };
188
+
189
+ const missing = [];
190
+ for (const [cp, sample] of scanTextCodepoints(source, {jsx})) {
191
+ const gaps = coverage.filter(c => !c.covered.has(cp));
192
+ if (!gaps.length) continue;
193
+ missing.push({
194
+ codepoint: cp,
195
+ char: String.fromCodePoint(cp),
196
+ sample,
197
+ missingFrom: gaps.map(g => g.family),
198
+ noGlyphIn: gaps.filter(g => !hasGlyph(g, cp)).map(g => g.family),
199
+ });
200
+ }
201
+ return missing.sort((a, b) => a.codepoint - b.codepoint);
202
+ }
203
+
204
+ const MAX_LISTED = 12;
205
+
206
+ /**
207
+ * Renders findMissingGlyphs() output as a developer-facing warning, ending with the config change
208
+ * that fixes it.
209
+ *
210
+ * @param {Array<object>} missing Result of findMissingGlyphs().
211
+ * @param {Array<object>} [fonts] The same bakeFont() results, for the suggested config line.
212
+ * @returns {string} The warning text (empty when nothing is missing).
213
+ */
214
+ export function formatMissingGlyphs(missing, fonts = []) {
215
+ if (!missing.length) return '';
216
+ const lines = missing.slice(0, MAX_LISTED).map(m => {
217
+ const hex = m.codepoint.toString(16).toUpperCase().padStart(4, '0');
218
+ const note = m.noGlyphIn.length
219
+ ? ` (the font file itself has no glyph for it — pick a font that covers it)`
220
+ : '';
221
+ return ` U+${hex} '${m.char}' missing from ${m.missingFrom.join(', ')}${note} in "${m.sample}"`;
222
+ });
223
+ if (missing.length > MAX_LISTED)
224
+ lines.push(` … and ${missing.length - MAX_LISTED} more`);
225
+
226
+ // One config entry per font, listing only what baking it there would actually fix.
227
+ const perFamily = fonts
228
+ .map(f => {
229
+ const chars = missing
230
+ .filter(
231
+ m =>
232
+ m.missingFrom.includes(f.family) && !m.noGlyphIn.includes(f.family),
233
+ )
234
+ .map(m => m.char)
235
+ .join('');
236
+ // A family is a file basename, so it often needs quoting to be a valid key ('Inter-Regular').
237
+ const key = /^[A-Za-z_$][\w$]*$/.test(f.family)
238
+ ? f.family
239
+ : JSON.stringify(f.family);
240
+ return chars ? `${key}: {extraGlyphs: ${JSON.stringify(chars)}}` : null;
241
+ })
242
+ .filter(Boolean);
243
+
244
+ const fix = perFamily.length
245
+ ? ` fix: assets.config.js → fonts: {${perFamily.join(', ')}}`
246
+ : fonts.length
247
+ ? ` fix: bake these from a font that has them (assets.config.js → fonts: {<Family>: {extraGlyphs: ...}})`
248
+ : ` fix: the built-in font covers ASCII + common symbols only — import a .ttf/.otf and bake the\n` +
249
+ ` rest with assets.config.js → fonts: {<Family>: {extraGlyphs: ${JSON.stringify(missing.map(m => m.char).join(''))}}}`;
250
+
251
+ return (
252
+ `embedded-react: ${missing.length} character(s) in the app's text have no baked glyph and will ` +
253
+ `render as '?':\n${lines.join('\n')}\n${fix}`
254
+ );
255
+ }
256
+
257
+ let lastWarning = null; // dev loops re-bake on every save — don't reprint an unchanged warning
258
+
259
+ /**
260
+ * Checks glyph coverage and warns. Repeats are suppressed while the warning is unchanged, so a
261
+ * watch/hot-reload loop reports each gap once rather than on every save.
262
+ *
263
+ * @param {object} opts
264
+ * @param {string} opts.source App/bundle JS to scan for rendered text.
265
+ * @param {Array<object>} [opts.fonts] bakeFont() results; empty means built-in font only.
266
+ * @param {boolean} [opts.jsx] Source is unbundled JSX — read element text too.
267
+ * @param {Function} [opts.log] Sink for the warning (default console.warn).
268
+ * @returns {Array<object>} The missing-glyph records (empty when coverage is complete).
269
+ */
270
+ export function warnMissingGlyphs({
271
+ source,
272
+ fonts = [],
273
+ jsx = false,
274
+ log = console.warn,
275
+ }) {
276
+ const missing = findMissingGlyphs({source, fonts, jsx});
277
+ const text = formatMissingGlyphs(missing, fonts);
278
+ if (text && text !== lastWarning) log(text);
279
+ lastWarning = text || null;
280
+ return missing;
281
+ }
package/assets/index.mjs CHANGED
@@ -23,6 +23,8 @@ import {bakeImage} from './bake-image.mjs';
23
23
  import {bakeFont} from './bake-font.mjs';
24
24
  import {emitAssetsC} from './emit-c.mjs';
25
25
  import {emitAssetPack} from './emit-pack.mjs';
26
+ import {warnMissingGlyphs} from './glyph-coverage.mjs';
27
+ import {warnFontSizes} from './font-sizes.mjs';
26
28
 
27
29
  /**
28
30
  * Bakes the given assets and writes assets.generated.{c,h} into outDir.
@@ -30,14 +32,25 @@ import {emitAssetPack} from './emit-pack.mjs';
30
32
  * @param {object} opts
31
33
  * @param {Array<{path:string,name:string,format?:string}>} [opts.images] Discovered image
32
34
  * imports; format 'rgb565' bakes 16-bit (see bake-image.mjs), default ARGB8888.
33
- * @param {Array<{path:string,family:string,sizes:number[],bpp:number,glyphs:any}>} [opts.fonts]
34
- * Discovered font imports with their resolved size/bpp/glyph config.
35
+ * @param {Array<{path:string,family:string,sizes:number[],bpp:number,glyphs:any,extraGlyphs:any}>}
36
+ * [opts.fonts] Discovered font imports with their resolved size/bpp/glyph config.
35
37
  * @param {string} opts.outDir Directory to write the generated files into.
38
+ * @param {string} [opts.source] Bundled app JS — scanned for text the bake has no glyph for.
39
+ * @param {{sizes:number[],dynamic:Array<object>}} [opts.usedSizes] analyzeFontSizes() result,
40
+ * checked against what was baked so an unbaked size is reported rather than silently snapped.
36
41
  * @returns {{cPath:string, hPath:string, images:number, fonts:number}}
37
42
  */
38
- export function bakeAssets({images = [], fonts = [], outDir}) {
43
+ export function bakeAssets({
44
+ images = [],
45
+ fonts = [],
46
+ outDir,
47
+ source,
48
+ usedSizes,
49
+ }) {
39
50
  const bakedImages = images.map(i => bakeImage(i));
40
51
  const bakedFonts = fonts.map(f => bakeFont(f));
52
+ if (source) warnMissingGlyphs({source, fonts: bakedFonts});
53
+ if (usedSizes) warnFontSizes({used: usedSizes, fonts: bakedFonts});
41
54
 
42
55
  const headerName = 'assets.generated.h';
43
56
  const {c, h} = emitAssetsC({
@@ -62,13 +75,24 @@ export function bakeAssets({images = [], fonts = [], outDir}) {
62
75
  *
63
76
  * @param {object} opts
64
77
  * @param {Array<{path:string,name:string}>} [opts.images]
65
- * @param {Array<{path:string,family:string,sizes:number[],bpp:number,glyphs:any}>} [opts.fonts]
78
+ * @param {Array<{path:string,family:string,sizes:number[],bpp:number,glyphs:any,extraGlyphs:any}>}
79
+ * [opts.fonts]
66
80
  * @param {string} opts.outPath Path to write the .pack file.
81
+ * @param {string} [opts.source] Bundled app JS — scanned for text the bake has no glyph for.
82
+ * @param {{sizes:number[],dynamic:Array<object>}} [opts.usedSizes] analyzeFontSizes() result.
67
83
  * @returns {{path:string, bytes:number, images:number, fonts:number}}
68
84
  */
69
- export function bakeAssetPack({images = [], fonts = [], outPath}) {
85
+ export function bakeAssetPack({
86
+ images = [],
87
+ fonts = [],
88
+ outPath,
89
+ source,
90
+ usedSizes,
91
+ }) {
70
92
  const bakedImages = images.map(i => bakeImage(i));
71
93
  const bakedFonts = fonts.map(f => bakeFont(f));
94
+ if (source) warnMissingGlyphs({source, fonts: bakedFonts});
95
+ if (usedSizes) warnFontSizes({used: usedSizes, fonts: bakedFonts});
72
96
  const pack = emitAssetPack({images: bakedImages, fonts: bakedFonts});
73
97
  fs.mkdirSync(path.dirname(outPath), {recursive: true});
74
98
  fs.writeFileSync(outPath, pack);
package/build.mjs CHANGED
@@ -31,6 +31,8 @@ import {fileURLToPath, pathToFileURL} from 'node:url';
31
31
  import {dirname, resolve, basename} from 'node:path';
32
32
  import {existsSync, readdirSync, readFileSync} from 'node:fs';
33
33
  import {bakeAssets} from './assets/index.mjs';
34
+ import {resolveFontJobs} from './assets/font-config.mjs';
35
+ import {analyzeFontSizes} from './assets/font-sizes.mjs';
34
36
  import {registerSvgVectorLoader} from './assets/svg-loader.mjs';
35
37
 
36
38
  const here = dirname(fileURLToPath(import.meta.url)); // bridges/quickjs/js
@@ -119,20 +121,15 @@ await build({
119
121
  console.log(`Bundled demo "${demo}" -> dist/app.bundle.js`);
120
122
 
121
123
  // --- Bake imported assets ---------------------------------------------------------------------
122
- // Fonts are pre-rasterized at fixed sizes (the engine has no runtime rasterizer), so bake exactly
123
- // the literal fontSize values the bundle uses. Computed/dynamic sizes can't be discovered statically
124
- // and will snap to the nearest baked size at runtime; pin them via assets.config.js if needed.
124
+ // Fonts are pre-rasterized at fixed sizes (the engine has no runtime rasterizer), so bake exactly the
125
+ // fontSize values the bundle uses — constants and token scales folded, not just literals. A size that
126
+ // only exists at runtime can't be discovered; the bake reports those rather than snapping silently.
125
127
  const bundleSrc = readFileSync(bundlePath, 'utf8');
126
- const discoveredSizes = [
127
- ...new Set(
128
- [...bundleSrc.matchAll(/\bfontSize\s*:\s*(\d+(?:\.\d+)?)/g)].map(m =>
129
- Math.round(Number(m[1])),
130
- ),
131
- ),
132
- ].sort((a, b) => a - b);
128
+ const usedSizes = analyzeFontSizes(bundleSrc);
133
129
 
134
130
  // Optional per-demo overrides: demos/<demo>/assets.config.js
135
- // export default { fonts: { 'Family': { sizes: [..], bpp: 4, glyphs: 'ascii'|'common'|[cps] } } }
131
+ // export default { fonts: { 'Family': { sizes: [..], bpp: 4, glyphs: 'ascii'|'common'|[cps],
132
+ // extraGlyphs: '°±' } } }
136
133
  let config = {};
137
134
  const configPath = resolve(demoDir, 'assets.config.js');
138
135
  if (existsSync(configPath)) {
@@ -141,16 +138,7 @@ if (existsSync(configPath)) {
141
138
  const fontConfig = config.fonts || {};
142
139
  const imageConfig = config.images || {};
143
140
 
144
- const fontJobs = [...fonts.entries()].map(([family, path]) => {
145
- const fc = fontConfig[family] || {};
146
- const sizes =
147
- fc.sizes && fc.sizes.length
148
- ? fc.sizes
149
- : discoveredSizes.length
150
- ? discoveredSizes
151
- : [16];
152
- return {path, family, sizes, bpp: fc.bpp ?? 4, glyphs: fc.glyphs ?? 'ascii'};
153
- });
141
+ const fontJobs = resolveFontJobs(fonts, fontConfig, usedSizes.sizes);
154
142
  const imageJobs = [...images.entries()].map(([name, path]) => ({
155
143
  path,
156
144
  name,
@@ -161,6 +149,8 @@ const summary = bakeAssets({
161
149
  images: imageJobs,
162
150
  fonts: fontJobs,
163
151
  outDir: distDir,
152
+ source: bundleSrc,
153
+ usedSizes,
164
154
  });
165
155
  const fontDesc = fontJobs.length
166
156
  ? fontJobs
package/cli.mjs CHANGED
@@ -368,6 +368,9 @@ async function buildAot(cwd, explicit, outDir, screen) {
368
368
  }
369
369
  const {compileSource, bakeSvgArtifacts} = await import('./aot/compile.mjs');
370
370
  const {bakeAssets} = await import('./assets/index.mjs');
371
+ const {warnMissingGlyphs} = await import('./assets/glyph-coverage.mjs');
372
+ const {analyzeFontSizes, warnFontSizes} =
373
+ await import('./assets/font-sizes.mjs');
371
374
  const appPath = resolveAppComponent(cwd, explicit);
372
375
  const appDir = dirname(appPath);
373
376
  const src = readFileSync(appPath, 'utf8');
@@ -402,6 +405,10 @@ async function buildAot(cwd, explicit, outDir, screen) {
402
405
  process.exit(1);
403
406
  }
404
407
  }
408
+ // Flow B renders everything in the engine's built-in font (no font imports) — check the app's text
409
+ // and its font sizes against what that font actually covers.
410
+ warnMissingGlyphs({source: src, jsx: true});
411
+ warnFontSizes({used: analyzeFontSizes(src)});
405
412
  const baked = bakeAssets({images: imageJobs, fonts: [], outDir});
406
413
  console.log(
407
414
  `✓ Flow B (AOT) → ${relative(cwd, outDir) || '.'}/app.gen.c (+ app.gen.h, assets.generated.c — ${baked.images} image(s))`,
@@ -428,7 +435,12 @@ async function buildContainer(cwd, explicit, outDir) {
428
435
 
429
436
  // Release artifact: strip the embedded source text + debug tables from the bytecode (~8x smaller
430
437
  // erpkg; stack traces lose line numbers). The dev loop (`embedded-react dev`) keeps them.
431
- const vendor = await packVendor({libSrc: lib, nodePaths: paths, simDir, strip: true});
438
+ const vendor = await packVendor({
439
+ libSrc: lib,
440
+ nodePaths: paths,
441
+ simDir,
442
+ strip: true,
443
+ });
432
444
  const app = await packApp({
433
445
  entry,
434
446
  projectRoot: cwd,
@@ -0,0 +1,71 @@
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
+ // compile-bin.mjs — finds the QuickJS bytecode precompiler (er-bridge-quickjs-compile).
18
+ //
19
+ // pack-container.mjs needs it to turn a bundle into the bytecode a container carries, and parity.mjs
20
+ // preflights it because Flow A renders from a packed container. Both look in the same build dirs and
21
+ // honour the same ER_COMPILE_BIN override, so the search lives here instead of in each caller.
22
+
23
+ import {existsSync} from 'node:fs';
24
+ import {dirname, resolve} from 'node:path';
25
+ import {fileURLToPath} from 'node:url';
26
+
27
+ const here = dirname(fileURLToPath(import.meta.url)); // bridges/quickjs/js
28
+ const repoRoot = resolve(here, '../../..');
29
+ const exe = process.platform === 'win32' ? '.exe' : '';
30
+
31
+ const SEARCH_DIRS = [
32
+ 'bridges/quickjs/build',
33
+ 'examples/linux/build/bridges/quickjs',
34
+ 'tools/simulator/build/bridges/quickjs',
35
+ ];
36
+
37
+ /**
38
+ * Returns the precompiler's path, or null when there isn't one.
39
+ *
40
+ * ER_COMPILE_BIN wins, but it still has to point at a file that exists: an override with a typo in it
41
+ * used to sail through every caller's check and only fail later, deep in a build, as a bare ENOENT
42
+ * from spawn. Returning null instead routes it to compileBinHelp(), which names the real problem.
43
+ */
44
+ export function findCompileBin() {
45
+ const override = process.env.ER_COMPILE_BIN;
46
+ if (override) {
47
+ return existsSync(override) ? override : null;
48
+ }
49
+ return (
50
+ SEARCH_DIRS.map(d =>
51
+ resolve(repoRoot, d, `er-bridge-quickjs-compile${exe}`),
52
+ ).find(existsSync) || null
53
+ );
54
+ }
55
+
56
+ /** What to print when findCompileBin() comes back null — a bad override is a different problem. */
57
+ export function compileBinHelp() {
58
+ const override = process.env.ER_COMPILE_BIN;
59
+ if (override) {
60
+ return (
61
+ `ER_COMPILE_BIN is set to "${override}", but there is no file there.\n` +
62
+ 'Point it at a built er-bridge-quickjs-compile, or unset it to search the usual build dirs.'
63
+ );
64
+ }
65
+ return [
66
+ 'Bytecode precompiler (er-bridge-quickjs-compile) not found. Build it once:',
67
+ ' cmake -S bridges/quickjs -B bridges/quickjs/build',
68
+ ' cmake --build bridges/quickjs/build --target er-bridge-quickjs-compile',
69
+ '(or set ER_COMPILE_BIN to the binary path)',
70
+ ].join('\n');
71
+ }
@@ -57,6 +57,10 @@ export async function packAppContainer({
57
57
  const esbuild = require('esbuild');
58
58
  const {bakeImage} = await import('../assets/bake-image.mjs');
59
59
  const {bakeFont} = await import('../assets/bake-font.mjs');
60
+ const {resolveFontJobs} = await import('../assets/font-config.mjs');
61
+ const {analyzeFontSizes, warnFontSizes} =
62
+ await import('../assets/font-sizes.mjs');
63
+ const {warnMissingGlyphs} = await import('../assets/glyph-coverage.mjs');
60
64
  const {emitAssetPack} = await import('../assets/emit-pack.mjs');
61
65
  const {emitContainer} = await import('../assets/emit-container.mjs');
62
66
  const {registerSvgVectorLoader} = await import('../assets/svg-loader.mjs');
@@ -145,33 +149,14 @@ export async function packAppContainer({
145
149
 
146
150
  const bytecode = await compileToBytecode(bundleSrc, simDir, {strip});
147
151
 
148
- const discoveredSizes = [
149
- ...new Set(
150
- [...bundleSrc.matchAll(/\bfontSize\s*:\s*(\d+(?:\.\d+)?)/g)].map(m =>
151
- Math.round(Number(m[1])),
152
- ),
153
- ),
154
- ].sort((a, b) => a - b);
152
+ const usedSizes = analyzeFontSizes(bundleSrc);
155
153
  let cfg = {};
156
154
  const cp = resolve(projectRoot, 'assets.config.js');
157
155
  if (existsSync(cp))
158
156
  cfg = (await import(pathToFileURL(cp).href)).default || {};
159
157
  const fontConfig = cfg.fonts || {};
160
158
  const imageConfig = cfg.images || {};
161
- const fontJobs = [...fonts.entries()].map(([family, path]) => {
162
- const fc = fontConfig[family] || {};
163
- return {
164
- path,
165
- family,
166
- sizes: fc.sizes?.length
167
- ? fc.sizes
168
- : discoveredSizes.length
169
- ? discoveredSizes
170
- : [16],
171
- bpp: fc.bpp ?? 4,
172
- glyphs: fc.glyphs ?? 'ascii',
173
- };
174
- });
159
+ const fontJobs = resolveFontJobs(fonts, fontConfig, usedSizes.sizes);
175
160
  const imageJobs = [...images.entries()].map(([name, path]) => ({
176
161
  path,
177
162
  name,
@@ -179,6 +164,8 @@ export async function packAppContainer({
179
164
  }));
180
165
  const bakedImages = imageJobs.map(bakeImage);
181
166
  const bakedFonts = fontJobs.map(bakeFont);
167
+ warnMissingGlyphs({source: bundleSrc, fonts: bakedFonts});
168
+ warnFontSizes({used: usedSizes, fonts: bakedFonts});
182
169
  const assetPack =
183
170
  bakedImages.length || bakedFonts.length
184
171
  ? emitAssetPack({images: bakedImages, fonts: bakedFonts})
@@ -118,9 +118,8 @@ function makeAssetPlugin({images, fonts, persistHooks, projectRoot}) {
118
118
  return {
119
119
  name: 'embedded-react-assets',
120
120
  async setup(b) {
121
- const {registerSvgVectorLoader} = await import(
122
- '../assets/svg-loader.mjs'
123
- );
121
+ const {registerSvgVectorLoader} =
122
+ await import('../assets/svg-loader.mjs');
124
123
  if (persistHooks) {
125
124
  b.onLoad({filter: /\.(jsx?|tsx?)$/}, a => {
126
125
  const {transformPersist, shouldPersist, projNorm} = persistHooks;
@@ -180,9 +179,8 @@ export async function bundleAppSource({
180
179
 
181
180
  let persistHooks = null;
182
181
  if (persist) {
183
- const {transformPersist, shouldPersist} = await import(
184
- '../persist-transform.mjs'
185
- );
182
+ const {transformPersist, shouldPersist} =
183
+ await import('../persist-transform.mjs');
186
184
  persistHooks = {
187
185
  transformPersist,
188
186
  shouldPersist,
@@ -203,15 +201,13 @@ export async function bundleAppSource({
203
201
  async function bakeAssets({images, fonts, source, projectRoot}) {
204
202
  const {bakeImage} = await import('../assets/bake-image.mjs');
205
203
  const {bakeFont} = await import('../assets/bake-font.mjs');
204
+ const {resolveFontJobs} = await import('../assets/font-config.mjs');
205
+ const {analyzeFontSizes, warnFontSizes} =
206
+ await import('../assets/font-sizes.mjs');
207
+ const {warnMissingGlyphs} = await import('../assets/glyph-coverage.mjs');
206
208
  const {emitAssetPack} = await import('../assets/emit-pack.mjs');
207
209
 
208
- const discoveredSizes = [
209
- ...new Set(
210
- [...source.matchAll(/\bfontSize\s*:\s*(\d+(?:\.\d+)?)/g)].map(m =>
211
- Math.round(Number(m[1])),
212
- ),
213
- ),
214
- ].sort((a, b) => a - b);
210
+ const usedSizes = analyzeFontSizes(source);
215
211
 
216
212
  let cfg = {};
217
213
  const cp = resolve(projectRoot, 'assets.config.js');
@@ -220,20 +216,7 @@ async function bakeAssets({images, fonts, source, projectRoot}) {
220
216
  const fontConfig = cfg.fonts || {};
221
217
  const imageConfig = cfg.images || {};
222
218
 
223
- const fontJobs = [...fonts.entries()].map(([family, path]) => {
224
- const fc = fontConfig[family] || {};
225
- return {
226
- path,
227
- family,
228
- sizes: fc.sizes?.length
229
- ? fc.sizes
230
- : discoveredSizes.length
231
- ? discoveredSizes
232
- : [16],
233
- bpp: fc.bpp ?? 4,
234
- glyphs: fc.glyphs ?? 'ascii',
235
- };
236
- });
219
+ const fontJobs = resolveFontJobs(fonts, fontConfig, usedSizes.sizes);
237
220
  const imageJobs = [...images.entries()].map(([name, path]) => ({
238
221
  path,
239
222
  name,
@@ -241,6 +224,8 @@ async function bakeAssets({images, fonts, source, projectRoot}) {
241
224
  }));
242
225
  const bakedImages = imageJobs.map(bakeImage);
243
226
  const bakedFonts = fontJobs.map(bakeFont);
227
+ warnMissingGlyphs({source, fonts: bakedFonts});
228
+ warnFontSizes({used: usedSizes, fonts: bakedFonts});
244
229
  return bakedImages.length || bakedFonts.length
245
230
  ? emitAssetPack({images: bakedImages, fonts: bakedFonts})
246
231
  : null;