embedded-react 0.12.0 → 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,652 @@
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 font-size discovery and coverage check. The engine has no runtime rasterizer: a font is
18
+ // baked at fixed pixel sizes and font_registry_get() (engine/font/font_registry.c) snaps anything
19
+ // else to the nearest baked size, ties going to the larger. So the bake has to know every size the
20
+ // app's text uses, and a size it missed is a silent visual bug.
21
+ //
22
+ // Discovery folds constants, which is what makes a token-driven type scale work:
23
+ // const TYPE = {body: 14, title: 22}; <Text style={{fontSize: TYPE.title}}>
24
+ // A literal-only scan bakes nothing for that app and every size collapses onto one. Folding covers
25
+ // module-level constants, objects (including spreads), arrays, arithmetic, and both arms of a
26
+ // responsive ternary — a `screen.width`-driven scale can't be resolved to one branch at build time,
27
+ // so both branches are baked and either panel renders correctly.
28
+ //
29
+ // What folding can't see is a size that only exists at runtime: a prop, state, a computed key. Those
30
+ // are reported rather than guessed at, because the runtime result is a silent snap, not an error.
31
+ import {parse} from '@babel/parser';
32
+ import {BUILTIN_SIZES} from './bake-font.mjs';
33
+ import {BUILTIN_FAMILY} from './glyph-coverage.mjs';
34
+
35
+ /** Sizes one family may register before the engine starts dropping them (FONT_FAMILY_MAX_SIZES). */
36
+ const MAX_BAKED_SIZES = 16;
37
+
38
+ /** Bounds of the engine's uint8 BitmapFont.pixel_size — a folded value outside them isn't a size. */
39
+ const MIN_PX = 1;
40
+ const MAX_PX = 255;
41
+
42
+ /** The range er_text_measure()/er_text_draw() clamp a requested size into before resolving a font. */
43
+ const RENDER_MIN_PX = 8;
44
+ const RENDER_MAX_PX = 96;
45
+
46
+ // A responsive scale multiplies out (two ternary arms times two more, …). Both limits keep a
47
+ // pathological expression from turning discovery into a combinatorial walk; the cost of clipping is
48
+ // an under-bake that the "could not be read" report below already covers.
49
+ const MAX_CANDIDATES = 12;
50
+ const MAX_DEPTH = 16;
51
+
52
+ // Whole-word `fontSize: <number>` — the pre-folding scan, kept as the fallback for a source the
53
+ // parser chokes on (a future syntax, a mangled bundle). Strictly weaker, never silently preferred.
54
+ const LITERAL_SIZE = /\bfontSize\s*:\s*(\d+(?:\.\d+)?)/g;
55
+
56
+ const PARSER_OPTS = {
57
+ sourceType: 'unambiguous', // an IIFE bundle is a script; an app entry is a module
58
+ errorRecovery: true,
59
+ // Same pair the AOT parser uses: the TS plugin is harmless on plain JS/JSX and lets a .tsx app
60
+ // through unchanged.
61
+ plugins: ['jsx', 'typescript'],
62
+ };
63
+
64
+ /*--- AST walking --------------------------------------------------------------------------------*/
65
+
66
+ // Keys that hold position/comment bookkeeping rather than child nodes. Skipping them is purely a
67
+ // speed matter (they carry no `type`), but on a 300 KB bundle it is most of the walk.
68
+ const NON_NODE_KEYS = new Set([
69
+ 'loc',
70
+ 'start',
71
+ 'end',
72
+ 'range',
73
+ 'extra',
74
+ 'comments',
75
+ 'leadingComments',
76
+ 'trailingComments',
77
+ 'innerComments',
78
+ ]);
79
+
80
+ /** Depth-first visit of every AST node under `node`, in source order. */
81
+ function walk(node, visit) {
82
+ if (Array.isArray(node)) {
83
+ for (const n of node) walk(n, visit);
84
+ return;
85
+ }
86
+ if (!node || typeof node !== 'object' || typeof node.type !== 'string')
87
+ return;
88
+ visit(node);
89
+ for (const key of Object.keys(node)) {
90
+ if (NON_NODE_KEYS.has(key)) continue;
91
+ const child = node[key];
92
+ if (child && typeof child === 'object') walk(child, visit);
93
+ }
94
+ }
95
+
96
+ /** Static name of a non-computed property key, or null when the key isn't a fixed string. */
97
+ function keyName(node) {
98
+ if (node.computed) return null;
99
+ const k = node.key;
100
+ if (!k) return null;
101
+ if (k.type === 'Identifier') return k.name;
102
+ if (k.type === 'StringLiteral') return k.value;
103
+ if (k.type === 'NumericLiteral') return String(k.value);
104
+ return null;
105
+ }
106
+
107
+ /*--- Constant folding ---------------------------------------------------------------------------*/
108
+
109
+ // A folded value is either a number or a Scale: an object/array whose properties are themselves
110
+ // candidate lists, so `TYPE.title` is a lookup and a ternary is a union.
111
+ const scale = props => ({props});
112
+ const isScale = v =>
113
+ v !== null && typeof v === 'object' && v.props instanceof Map;
114
+
115
+ /** Trims a candidate list to the fan-out budget, dropping duplicates first. */
116
+ const cap = values =>
117
+ values.length > MAX_CANDIDATES
118
+ ? [...new Set(values)].slice(0, MAX_CANDIDATES)
119
+ : values;
120
+
121
+ /** The numbers in a candidate list (a Scale is not a size). */
122
+ const numbers = values => values.filter(v => typeof v === 'number');
123
+
124
+ const ARITHMETIC = {
125
+ '+': (a, b) => a + b,
126
+ '-': (a, b) => a - b,
127
+ '*': (a, b) => a * b,
128
+ '/': (a, b) => a / b,
129
+ '%': (a, b) => a % b,
130
+ '**': (a, b) => a ** b,
131
+ };
132
+
133
+ // Rounding is how a ratio-based scale lands on whole pixels (Math.round(base * 1.25)); min/max is
134
+ // how it gets clamped. Anything else on Math is left unresolved rather than guessed.
135
+ const MATH_FNS = {
136
+ round: Math.round,
137
+ floor: Math.floor,
138
+ ceil: Math.ceil,
139
+ abs: Math.abs,
140
+ min: Math.min,
141
+ max: Math.max,
142
+ };
143
+
144
+ /**
145
+ * Statically evaluates an expression to the values it can take.
146
+ *
147
+ * @param {object} node Expression AST node.
148
+ * @param {object} scope Fold scope from buildScope().
149
+ * @param {number} [depth] Recursion guard.
150
+ * @returns {any[]} Candidate values (numbers and/or Scales); empty when nothing can be resolved.
151
+ */
152
+ function evaluate(node, scope, depth = 0) {
153
+ if (!node || depth > MAX_DEPTH) return [];
154
+ const rec = n => evaluate(n, scope, depth + 1);
155
+
156
+ switch (node.type) {
157
+ case 'NumericLiteral':
158
+ return [node.value];
159
+
160
+ case 'Identifier':
161
+ return lookup(node.name, scope, depth);
162
+
163
+ // A parenthesized expression, a TS cast, a `!` assertion: transparent for our purposes.
164
+ case 'ParenthesizedExpression':
165
+ case 'TSAsExpression':
166
+ case 'TSSatisfiesExpression':
167
+ case 'TSNonNullExpression':
168
+ case 'TSTypeAssertion':
169
+ case 'TypeCastExpression':
170
+ return rec(node.expression);
171
+
172
+ case 'UnaryExpression': {
173
+ if (node.operator !== '-' && node.operator !== '+') return [];
174
+ const sign = node.operator === '-' ? -1 : 1;
175
+ return numbers(rec(node.argument)).map(v => sign * v);
176
+ }
177
+
178
+ case 'BinaryExpression': {
179
+ const op = ARITHMETIC[node.operator];
180
+ if (!op) return [];
181
+ const left = numbers(rec(node.left));
182
+ const right = numbers(rec(node.right));
183
+ const out = [];
184
+ for (const a of left) for (const b of right) out.push(op(a, b));
185
+ return cap(out);
186
+ }
187
+
188
+ // Both arms: which one a responsive app takes depends on the panel it boots on, and the same
189
+ // bundle runs on all of them.
190
+ case 'ConditionalExpression':
191
+ return cap([...rec(node.consequent), ...rec(node.alternate)]);
192
+
193
+ // `a ?? b` / `a || b` are the same shape of choice; `&&` can only ever yield its right arm.
194
+ case 'LogicalExpression':
195
+ return node.operator === '&&'
196
+ ? rec(node.right)
197
+ : cap([...rec(node.left), ...rec(node.right)]);
198
+
199
+ case 'ObjectExpression': {
200
+ const props = new Map();
201
+ for (const p of node.properties) {
202
+ if (p.type === 'SpreadElement') {
203
+ for (const base of rec(p.argument).filter(isScale))
204
+ for (const [k, v] of base.props) props.set(k, v);
205
+ continue;
206
+ }
207
+ if (p.type !== 'ObjectProperty') continue; // a method is never a size
208
+ const name = keyName(p);
209
+ if (name === null) continue;
210
+ const values = rec(p.value);
211
+ if (values.length) props.set(name, values);
212
+ }
213
+ return [scale(props)];
214
+ }
215
+
216
+ case 'ArrayExpression': {
217
+ const props = new Map();
218
+ node.elements.forEach((el, i) => {
219
+ if (!el || el.type === 'SpreadElement') return;
220
+ const values = rec(el);
221
+ if (values.length) props.set(String(i), values);
222
+ });
223
+ return [scale(props)];
224
+ }
225
+
226
+ case 'MemberExpression': {
227
+ const objects = rec(node.object).filter(isScale);
228
+ if (!objects.length) return [];
229
+ const key = memberKey(node, scope, depth);
230
+ const out = [];
231
+ for (const obj of objects) {
232
+ // An unresolvable key (`TYPE[variant]`) still narrows things to one scale, and every entry
233
+ // in it is something the app can reach — take the lot rather than nothing.
234
+ if (key === null) {
235
+ for (const v of obj.props.values()) out.push(...v);
236
+ } else {
237
+ out.push(...(obj.props.get(key) ?? []));
238
+ }
239
+ }
240
+ return cap(out);
241
+ }
242
+
243
+ case 'CallExpression': {
244
+ const {callee} = node;
245
+ if (
246
+ callee?.type !== 'MemberExpression' ||
247
+ callee.computed ||
248
+ callee.object?.type !== 'Identifier' ||
249
+ callee.object.name !== 'Math' ||
250
+ callee.property?.type !== 'Identifier'
251
+ )
252
+ return [];
253
+ const fn = MATH_FNS[callee.property.name];
254
+ if (!fn) return [];
255
+ // Every argument must resolve, or the result isn't the one the app computes.
256
+ const args = node.arguments.map(a => numbers(rec(a)));
257
+ if (!args.length || args.some(a => !a.length)) return [];
258
+ return cap(combine(args).map(vals => fn(...vals)));
259
+ }
260
+
261
+ default:
262
+ return [];
263
+ }
264
+ }
265
+
266
+ /** Cartesian product of per-argument candidate lists, clipped to the fan-out budget. */
267
+ function combine(lists) {
268
+ let rows = [[]];
269
+ for (const list of lists) {
270
+ const next = [];
271
+ for (const row of rows)
272
+ for (const v of list) {
273
+ if (next.length >= MAX_CANDIDATES) break;
274
+ next.push([...row, v]);
275
+ }
276
+ rows = next;
277
+ }
278
+ return rows;
279
+ }
280
+
281
+ /** Property name a member expression reads, resolving a computed key when it folds to a constant. */
282
+ function memberKey(node, scope, depth) {
283
+ if (!node.computed)
284
+ return node.property.type === 'Identifier' ? node.property.name : null;
285
+ if (node.property.type === 'StringLiteral') return node.property.value;
286
+ if (node.property.type === 'NumericLiteral')
287
+ return String(node.property.value);
288
+ const folded = numbers(evaluate(node.property, scope, depth + 1));
289
+ return folded.length === 1 ? String(folded[0]) : null;
290
+ }
291
+
292
+ /**
293
+ * Resolves a name to its candidate values, memoizing the answer (including "nothing").
294
+ *
295
+ * Constants come first. A name with no constant behind it may still be a scale that was handed
296
+ * down — see buildScope() — and that is resolved on demand, so the bindings of the thousands of
297
+ * names a bundle contains are only ever evaluated for the handful a fontSize actually reads.
298
+ */
299
+ function lookup(name, scope, depth) {
300
+ const known = scope.env.get(name);
301
+ if (known !== undefined) return known; // a memoized "nothing" is an answer, not a miss
302
+ const bound = scope.bindings.get(name);
303
+ if (!bound || scope.resolving.has(name)) return [];
304
+
305
+ scope.resolving.add(name);
306
+ const values = cap(
307
+ bound.flatMap(node => evaluate(node, scope, depth + 1)).filter(isScale),
308
+ );
309
+ scope.resolving.delete(name);
310
+ scope.env.set(name, values);
311
+ return values;
312
+ }
313
+
314
+ /**
315
+ * Builds the fold scope for one program: the names it binds to a constant, and the names a scale is
316
+ * handed down under.
317
+ *
318
+ * Binding a name once is the whole scoping model for constants — no scope tracking, so a name
319
+ * declared twice (a module constant shadowed by a local, say) is left out rather than resolved to
320
+ * the wrong one. Bundles rename colliding identifiers, so in practice this only skips genuine reuse.
321
+ *
322
+ * The handed-down half is what makes a scale work in a component that did not declare it:
323
+ * `<Dial sz={SZ}>` (or `jsx(Dial, {sz: SZ})` once a bundler has lowered it) against a `sz.big`
324
+ * inside. Only a name passed a *named* value binds — `{sz: SZ}`, not an inline literal — which keeps
325
+ * this to the "pass the scale down" pattern it is for. A name passed different scales in different
326
+ * places resolves to all of them, which over-bakes at worst; declared names always win.
327
+ *
328
+ * @param {object} ast Parsed program.
329
+ * @returns {{env: Map<string,any[]>, bindings: Map<string,object[]>, resolving: Set<string>}}
330
+ */
331
+ function buildScope(ast) {
332
+ const declarations = [];
333
+ const counts = new Map();
334
+ const bindings = new Map();
335
+ const bind = (name, node) => {
336
+ if (node.type !== 'Identifier' && node.type !== 'MemberExpression') return;
337
+ const list = bindings.get(name);
338
+ if (list) list.push(node);
339
+ else bindings.set(name, [node]);
340
+ };
341
+
342
+ walk(ast.program, n => {
343
+ if (n.type === 'VariableDeclarator') {
344
+ if (n.id?.type === 'Identifier' && n.init) {
345
+ declarations.push(n);
346
+ counts.set(n.id.name, (counts.get(n.id.name) ?? 0) + 1);
347
+ }
348
+ return;
349
+ }
350
+ if (
351
+ n.type === 'JSXAttribute' &&
352
+ n.name?.type === 'JSXIdentifier' &&
353
+ n.value?.type === 'JSXExpressionContainer'
354
+ ) {
355
+ bind(n.name.name, n.value.expression);
356
+ return;
357
+ }
358
+ if (n.type === 'ObjectProperty') {
359
+ const name = keyName(n);
360
+ if (name !== null) bind(name, n.value);
361
+ }
362
+ });
363
+
364
+ // Constants fold first, against no bindings at all: lookup() memoizes what it resolves, and a
365
+ // binding consulted mid-fold could cache an answer taken from a half-built environment. Two passes,
366
+ // so a scale that reads a constant declared below it still folds; a third would only help a chain
367
+ // that deep, which no type scale is.
368
+ const scope = {env: new Map(), bindings: new Map(), resolving: new Set()};
369
+ for (let pass = 0; pass < 2; pass++) {
370
+ for (const d of declarations) {
371
+ const name = d.id.name;
372
+ if (counts.get(name) > 1) continue;
373
+ const values = evaluate(d.init, scope);
374
+ if (values.length) scope.env.set(name, values);
375
+ }
376
+ }
377
+ // A declared name resolves to its declaration or to nothing; it never falls through to a binding.
378
+ for (const name of counts.keys()) bindings.delete(name);
379
+ scope.bindings = bindings;
380
+ return scope;
381
+ }
382
+
383
+ /*--- Discovery ----------------------------------------------------------------------------------*/
384
+
385
+ /** Rounds a folded value to a bakeable pixel size, or null when it isn't one. */
386
+ function toPixelSize(value) {
387
+ const px = Math.round(value);
388
+ return Number.isFinite(px) && px >= MIN_PX && px <= MAX_PX ? px : null;
389
+ }
390
+
391
+ /** One-line, length-capped rendering of the expression behind an unresolved fontSize. */
392
+ function snippet(source, node) {
393
+ const raw = source.slice(node.start, node.end).replace(/\s+/g, ' ').trim();
394
+ return raw.length > 48 ? `${raw.slice(0, 47)}…` : raw;
395
+ }
396
+
397
+ /** Literal-only discovery, for a source the parser rejected. */
398
+ function scanLiterals(source) {
399
+ const sizes = new Set();
400
+ for (const m of source.matchAll(LITERAL_SIZE)) {
401
+ const px = toPixelSize(Number(m[1]));
402
+ if (px !== null) sizes.add(px);
403
+ }
404
+ return {sizes: [...sizes].sort((a, b) => a - b), dynamic: []};
405
+ }
406
+
407
+ /**
408
+ * Finds the pixel sizes an app's text renders at, folding constants so a token-driven scale is
409
+ * discovered rather than missed.
410
+ *
411
+ * @param {string} source JS/JSX/TSX source: a bundle, a chunk, or a single app entry.
412
+ * @returns {{sizes: number[], dynamic: Array<{expr:string, count:number}>}} Ascending de-duplicated
413
+ * sizes, plus the `fontSize` expressions that could not be resolved at build time.
414
+ */
415
+ export function analyzeFontSizes(source) {
416
+ if (!source) return {sizes: [], dynamic: []};
417
+ let ast;
418
+ try {
419
+ ast = parse(source, PARSER_OPTS);
420
+ } catch {
421
+ return scanLiterals(source); // never worse than the literal scan this replaced
422
+ }
423
+
424
+ const scope = buildScope(ast);
425
+ const sizes = new Set();
426
+ const dynamic = new Map(); // expression text → occurrences
427
+ walk(ast.program, n => {
428
+ if (n.type !== 'ObjectProperty' || keyName(n) !== 'fontSize') return;
429
+ // A value that resolves but can't be baked (0, negative, past the engine's uint8 pixel_size) is
430
+ // an authoring slip, not a discovery failure: leave it out of the bake and out of the report.
431
+ const resolved = numbers(evaluate(n.value, scope));
432
+ if (resolved.length) {
433
+ for (const value of resolved) {
434
+ const px = toPixelSize(value);
435
+ if (px !== null) sizes.add(px);
436
+ }
437
+ return;
438
+ }
439
+ const expr = snippet(source, n.value);
440
+ dynamic.set(expr, (dynamic.get(expr) ?? 0) + 1);
441
+ });
442
+
443
+ return {
444
+ sizes: [...sizes].sort((a, b) => a - b),
445
+ dynamic: [...dynamic]
446
+ .map(([expr, count]) => ({expr, count}))
447
+ .sort((a, b) => b.count - a.count || a.expr.localeCompare(b.expr)),
448
+ };
449
+ }
450
+
451
+ /**
452
+ * Compact signature of the sizes a source uses. Watch loops fold this into their "did the asset
453
+ * inputs change?" key so a `fontSize` edit re-runs the check below.
454
+ *
455
+ * Without it the check is skipped exactly where it matters most: an app with no imported font has no
456
+ * baked `sizes` in that key at all, so editing a size changes nothing the loop compares and the
457
+ * re-bake never happens. Sizes that resolve and sizes that don't both count — swapping a constant
458
+ * for a runtime value changes what is reported without changing what is baked.
459
+ *
460
+ * @param {{sizes:number[], dynamic:Array<{expr:string}>}} used analyzeFontSizes() result.
461
+ * @returns {string} Sizes and unresolved expressions, joined.
462
+ */
463
+ export function fontSizeSignature(used) {
464
+ const {sizes = [], dynamic = []} = used ?? {};
465
+ return `${sizes.join(',')}|${dynamic.map(d => d.expr).join('\u0000')}`;
466
+ }
467
+
468
+ /*--- Coverage check -----------------------------------------------------------------------------*/
469
+
470
+ /** Pixel sizes a bakeFont() result — or the job that produced it — covers. */
471
+ function bakedSizes(font) {
472
+ return (font.sizes ?? [])
473
+ .map(s => (typeof s === 'number' ? s : s?.pixelSize))
474
+ .filter(px => Number.isFinite(px));
475
+ }
476
+
477
+ /**
478
+ * The size the engine substitutes for an unbaked one: nearest wins, a tie goes to the larger.
479
+ * Mirrors pick_closest() in engine/font/font_registry.c, including the clamp the text renderer
480
+ * applies to the requested size first.
481
+ *
482
+ * @param {number[]} baked Sizes the family is baked at (non-empty).
483
+ * @param {number} wanted The size the app asked for.
484
+ * @returns {number} The size that actually renders.
485
+ */
486
+ export function pickBakedSize(baked, wanted) {
487
+ const target = Math.min(Math.max(wanted, RENDER_MIN_PX), RENDER_MAX_PX);
488
+ let best = baked[0];
489
+ for (const px of baked.slice(1)) {
490
+ const diff = Math.abs(target - px);
491
+ const bestDiff = Math.abs(target - best);
492
+ if (diff < bestDiff || (diff === bestDiff && px > best)) best = px;
493
+ }
494
+ return best;
495
+ }
496
+
497
+ /**
498
+ * Finds the used sizes no font in the bake covers.
499
+ *
500
+ * Which fonts are checked follows what the app can draw with, the same way the glyph check does it:
501
+ * each imported font when there are any (they all render the app's text, and a family missing a size
502
+ * is the bug worth reporting), the engine's built-in font when there are none.
503
+ *
504
+ * @param {object} opts
505
+ * @param {number[]} [opts.sizes] Sizes the app uses (from analyzeFontSizes).
506
+ * @param {Array<object>} [opts.fonts] bakeFont() results or jobs; empty means built-in font only.
507
+ * @returns {{gaps: Array<{size:number, family:string, snapsTo:number, baked:number[]}>,
508
+ * dropped: Array<{family:string, registered:number[], ignored:number[]}>}} `gaps` are sizes
509
+ * that will snap; `dropped` splits a family baked past the engine's per-family limit into
510
+ * the sizes that register and the ones that never do.
511
+ */
512
+ export function findSizeGaps({sizes = [], fonts = []}) {
513
+ const checked = fonts.length
514
+ ? fonts.map(f => ({family: f.family, baked: bakedSizes(f)}))
515
+ : [{family: BUILTIN_FAMILY, baked: [...BUILTIN_SIZES]}];
516
+
517
+ const gaps = [];
518
+ const dropped = [];
519
+ for (const {family, baked} of checked) {
520
+ if (!baked.length) continue;
521
+ // Registration stops at the limit, so anything past it is not merely unbaked but unreachable.
522
+ const live = baked.slice(0, MAX_BAKED_SIZES);
523
+ if (baked.length > live.length)
524
+ dropped.push({
525
+ family,
526
+ registered: live,
527
+ ignored: baked.slice(MAX_BAKED_SIZES),
528
+ });
529
+ for (const size of sizes)
530
+ if (!live.includes(size))
531
+ gaps.push({
532
+ size,
533
+ family,
534
+ snapsTo: pickBakedSize(live, size),
535
+ baked: live,
536
+ });
537
+ }
538
+ return {gaps: gaps.sort((a, b) => a.size - b.size), dropped};
539
+ }
540
+
541
+ const MAX_LISTED = 8;
542
+
543
+ /** `[a, b, c]` as an assets.config.js `sizes` line would spell it. */
544
+ const sizeList = sizes => `[${[...sizes].sort((a, b) => a - b).join(', ')}]`;
545
+
546
+ /** A family name as a valid object key (a family is a file basename — `Inter-Regular` needs quotes). */
547
+ const configKey = family =>
548
+ /^[A-Za-z_$][\w$]*$/.test(family) ? family : JSON.stringify(family);
549
+
550
+ /**
551
+ * Renders the size check as a developer-facing warning, ending with the change that fixes it.
552
+ *
553
+ * @param {object} opts
554
+ * @param {Array<object>} [opts.gaps] From findSizeGaps().
555
+ * @param {Array<object>} [opts.dropped] From findSizeGaps().
556
+ * @param {Array<object>} [opts.dynamic] From analyzeFontSizes().
557
+ * @param {Array<object>} [opts.fonts] The same fonts, for the suggested config line.
558
+ * @returns {string} The warning text (empty when there is nothing to report).
559
+ */
560
+ export function formatFontSizeReport({
561
+ gaps = [],
562
+ dropped = [],
563
+ dynamic = [],
564
+ fonts = [],
565
+ }) {
566
+ const blocks = [];
567
+
568
+ if (gaps.length) {
569
+ const lines = gaps
570
+ .slice(0, MAX_LISTED)
571
+ .map(
572
+ g =>
573
+ ` ${g.size}px → renders at ${g.snapsTo}px in ${g.family} (baked: ${g.baked.join(', ')})`,
574
+ );
575
+ if (gaps.length > MAX_LISTED)
576
+ lines.push(` … and ${gaps.length - MAX_LISTED} more`);
577
+ blocks.push(
578
+ `embedded-react: ${gaps.length} font size(s) the app uses are not baked and will render at the ` +
579
+ `nearest baked size:\n${lines.join('\n')}\n${gapFix(gaps, fonts)}`,
580
+ );
581
+ }
582
+
583
+ if (dynamic.length) {
584
+ const total = dynamic.reduce((n, d) => n + d.count, 0);
585
+ const lines = dynamic.slice(0, MAX_LISTED).map(d => {
586
+ const times = d.count > 1 ? ` (×${d.count})` : '';
587
+ return ` fontSize: ${d.expr}${times}`;
588
+ });
589
+ if (dynamic.length > MAX_LISTED)
590
+ lines.push(` … and ${dynamic.length - MAX_LISTED} more`);
591
+ blocks.push(
592
+ `embedded-react: ${total} fontSize value(s) could not be read at build time, so no size was ` +
593
+ `baked for them (each snaps to the nearest baked size at runtime):\n${lines.join('\n')}\n` +
594
+ ` fix: name the size where it is used, from a module-level constant the bake can fold ` +
595
+ `(const TYPE = {body: 14};\n fontSize: TYPE.body) — one arriving through a prop or ` +
596
+ `state can't be traced. Or pin the sizes:\n assets.config.js → ` +
597
+ `fonts: {${fonts.length ? configKey(fonts[0].family) : '<Family>'}: {sizes: [...]}}`,
598
+ );
599
+ }
600
+
601
+ for (const d of dropped) {
602
+ blocks.push(
603
+ `embedded-react: ${d.family} is baked at more than ${MAX_BAKED_SIZES} sizes — the engine ` +
604
+ `registers the first ${MAX_BAKED_SIZES} and ignores ${sizeList(d.ignored)}, so text at ` +
605
+ `those sizes snaps to one that did register.\n fix: choose the ${MAX_BAKED_SIZES} that ` +
606
+ `matter — assets.config.js → fonts: {${configKey(d.family)}: {sizes: ${sizeList(d.registered)}}}`,
607
+ );
608
+ }
609
+
610
+ return blocks.join('\n');
611
+ }
612
+
613
+ /** The config (or design) change that closes a set of gaps. */
614
+ function gapFix(gaps, fonts) {
615
+ if (!fonts.length) {
616
+ return (
617
+ ` fix: the built-in font is baked at ${sizeList(BUILTIN_SIZES)} — use one of those sizes, or ` +
618
+ `import a .ttf/.otf\n and bake your own (assets.config.js → fonts: ` +
619
+ `{<Family>: {sizes: ${sizeList(new Set(gaps.map(g => g.size)))}}})`
620
+ );
621
+ }
622
+ const perFamily = fonts
623
+ .map(f => {
624
+ const missing = gaps.filter(g => g.family === f.family).map(g => g.size);
625
+ if (!missing.length) return null;
626
+ const wanted = new Set([...bakedSizes(f), ...missing]);
627
+ return `${configKey(f.family)}: {sizes: ${sizeList(wanted)}}`;
628
+ })
629
+ .filter(Boolean);
630
+ return ` fix: assets.config.js → fonts: {${perFamily.join(', ')}}`;
631
+ }
632
+
633
+ let lastWarning = null; // dev loops re-bake on every save — don't reprint an unchanged warning
634
+
635
+ /**
636
+ * Checks size coverage and warns. Repeats are suppressed while the warning is unchanged, so a
637
+ * watch/hot-reload loop reports each gap once rather than on every save.
638
+ *
639
+ * @param {object} opts
640
+ * @param {{sizes:number[], dynamic:Array<object>}} opts.used analyzeFontSizes() result.
641
+ * @param {Array<object>} [opts.fonts] bakeFont() results or jobs; empty means built-in font only.
642
+ * @param {Function} [opts.log] Sink for the warning (default console.warn).
643
+ * @returns {{gaps:Array<object>, dropped:Array<object>}} What was found (both empty when clean).
644
+ */
645
+ export function warnFontSizes({used, fonts = [], log = console.warn}) {
646
+ const {sizes = [], dynamic = []} = used ?? {};
647
+ const {gaps, dropped} = findSizeGaps({sizes, fonts});
648
+ const text = formatFontSizeReport({gaps, dropped, dynamic, fonts});
649
+ if (text && text !== lastWarning) log(text);
650
+ lastWarning = text || null;
651
+ return {gaps, dropped};
652
+ }