embedded-react 0.15.0 → 0.17.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 (62) hide show
  1. package/aot/compile.mjs +173 -8272
  2. package/aot/compiler/animations.mjs +1001 -0
  3. package/aot/compiler/assemble.mjs +922 -0
  4. package/aot/compiler/boot.mjs +441 -0
  5. package/aot/compiler/branch-merge.mjs +319 -0
  6. package/aot/compiler/c/animations.mjs +362 -0
  7. package/aot/compiler/c/boot.mjs +127 -0
  8. package/aot/compiler/c/expressions.mjs +270 -0
  9. package/aot/compiler/c/functions.mjs +268 -0
  10. package/aot/compiler/c/keyboard.mjs +96 -0
  11. package/aot/compiler/c/nodes.mjs +294 -0
  12. package/aot/compiler/c/pan-responder.mjs +136 -0
  13. package/aot/compiler/c/statements.mjs +271 -0
  14. package/aot/compiler/c/text.mjs +83 -0
  15. package/aot/compiler/c/vectors.mjs +381 -0
  16. package/aot/compiler/c-syntax.mjs +127 -0
  17. package/aot/compiler/check.mjs +165 -0
  18. package/aot/compiler/collect.mjs +785 -0
  19. package/aot/compiler/control-flow.mjs +696 -0
  20. package/aot/compiler/diagnostics.mjs +137 -0
  21. package/aot/compiler/elements/activity-indicator.mjs +160 -0
  22. package/aot/compiler/elements/dial.mjs +346 -0
  23. package/aot/compiler/elements/flat-list.mjs +139 -0
  24. package/aot/compiler/elements/image.mjs +151 -0
  25. package/aot/compiler/elements/modal.mjs +158 -0
  26. package/aot/compiler/elements/props.mjs +474 -0
  27. package/aot/compiler/elements/switch.mjs +183 -0
  28. package/aot/compiler/elements/text-input.mjs +171 -0
  29. package/aot/compiler/expressions.mjs +1579 -0
  30. package/aot/compiler/handlers.mjs +1072 -0
  31. package/aot/compiler/ir/animations.mjs +16 -0
  32. package/aot/compiler/ir/app.mjs +16 -0
  33. package/aot/compiler/ir/boot.mjs +16 -0
  34. package/aot/compiler/ir/expressions.mjs +16 -0
  35. package/aot/compiler/ir/functions.mjs +16 -0
  36. package/aot/compiler/ir/keyboard.mjs +16 -0
  37. package/aot/compiler/ir/nodes.mjs +107 -0
  38. package/aot/compiler/ir/pan-responder.mjs +16 -0
  39. package/aot/compiler/ir/reads.mjs +351 -0
  40. package/aot/compiler/ir/source.mjs +16 -0
  41. package/aot/compiler/ir/statements.mjs +16 -0
  42. package/aot/compiler/ir/text.mjs +16 -0
  43. package/aot/compiler/ir/types.mjs +185 -0
  44. package/aot/compiler/ir/vectors.mjs +16 -0
  45. package/aot/compiler/keyboard.mjs +152 -0
  46. package/aot/compiler/lower.mjs +311 -0
  47. package/aot/compiler/nodes.mjs +688 -0
  48. package/aot/compiler/options.mjs +55 -0
  49. package/aot/compiler/out.mjs +94 -0
  50. package/aot/compiler/pan-responder.mjs +354 -0
  51. package/aot/compiler/parse.mjs +300 -0
  52. package/aot/compiler/static-eval.mjs +454 -0
  53. package/aot/compiler/style-text.mjs +807 -0
  54. package/aot/compiler/svg.mjs +1167 -0
  55. package/aot/compiler/types.mjs +16 -0
  56. package/aot/screenshot-smoke.mjs +95 -55
  57. package/aot/style-map.mjs +366 -304
  58. package/cli.mjs +5 -8
  59. package/package.json +14 -6
  60. package/sim/embedded-react.wasm +0 -0
  61. package/src/embedded-react/FlatList.js +4 -4
  62. package/src/props.js +1 -1
@@ -0,0 +1,785 @@
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
+ - Imports
18
+ ---------------------------------------------------------------------------------------------------------------------*/
19
+ import { checkNumber } from './check.mjs';
20
+ import { parse } from '@babel/parser';
21
+ import { readFileSync, existsSync } from 'node:fs';
22
+ import { resolve } from 'node:path';
23
+ import { aotError } from './diagnostics.mjs';
24
+ import { mergeBranchElements } from './branch-merge.mjs';
25
+ import { bootCheckpoint, foldBoot, isBoot, nameBootValues, screenBinding, } from './boot.mjs';
26
+ import { evalStaticOrThrow, evalStatic, withUndefined } from './static-eval.mjs';
27
+ import { cConstant, cTypeOfValue } from './c-syntax.mjs';
28
+ /*----------------------------------------------------------------------------------------------------------------------
29
+ - Constants
30
+ ---------------------------------------------------------------------------------------------------------------------*/
31
+ /** No state or ref slot widened to 64 bits — the collectors' default. */
32
+ export const NO_WIDE = new Map();
33
+ /**
34
+ * What a whole-number initial value needs beyond an int slot, typed as a constant of its size is: nothing in
35
+ * the int range, a 64-bit number past it, a float past 64 bits.
36
+ *
37
+ * @param value The initial value.
38
+ *
39
+ * @returns 'number' for a 64-bit slot, 'float' for a float one, or null for an int.
40
+ */
41
+ export const wideInitial = (value) => typeof value !== 'number' || !Number.isInteger(value)
42
+ ? null
43
+ : value < -(2 ** 63) || value >= 2 ** 63
44
+ ? 'float'
45
+ : value < -(2 ** 31) || value > 2 ** 31 - 1
46
+ ? 'number'
47
+ : null;
48
+ const IMAGE_EXT_RE = /\.(png|jpe?g|webp|gif|bmp)$/i;
49
+ /*----------------------------------------------------------------------------------------------------------------------
50
+ - Implementation
51
+ ---------------------------------------------------------------------------------------------------------------------*/
52
+ /**
53
+ * Whether a node is a function the compiler can compile or inline.
54
+ *
55
+ * @param node Any node, or nothing.
56
+ *
57
+ * @returns Whether it is a function declaration, a function expression, or an arrow.
58
+ */
59
+ export const isFn = (node) => (node &&
60
+ (node.type === 'FunctionDeclaration' ||
61
+ node.type === 'FunctionExpression' ||
62
+ node.type === 'ArrowFunctionExpression'));
63
+ /**
64
+ * Finds the app's root component: `function App` or `const App = …`, exported or not.
65
+ *
66
+ * @param program The parsed module.
67
+ *
68
+ * @returns The App function.
69
+ */
70
+ export function findComponent(program) {
71
+ for (const stmt of program.body) {
72
+ const declaration = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt;
73
+ if (!declaration)
74
+ continue;
75
+ if (declaration.type === 'FunctionDeclaration' &&
76
+ declaration.id?.name === 'App') {
77
+ return declaration;
78
+ }
79
+ if (declaration.type === 'VariableDeclaration') {
80
+ for (const decl of declaration.declarations) {
81
+ if (decl.id?.name === 'App' && isFn(decl.init)) {
82
+ return decl.init;
83
+ }
84
+ }
85
+ }
86
+ }
87
+ throw new Error('AOT: no `App` component found (expected `export function App() { ... }`)');
88
+ }
89
+ /**
90
+ * Every name a variable declaration directly in `body` binds, destructuring included. In JS each one
91
+ * shadows a module binding of that name for the whole function body, not only from its declaration on.
92
+ *
93
+ * @param body A function body's statements.
94
+ *
95
+ * @returns The names.
96
+ */
97
+ export function declaredNames(body) {
98
+ // Walk a binding pattern down to the identifiers it binds.
99
+ const names = [];
100
+ const walk = (pattern) => {
101
+ if (!pattern)
102
+ return;
103
+ if (pattern.type === 'Identifier') {
104
+ names.push(pattern.name);
105
+ }
106
+ else if (pattern.type === 'ArrayPattern') {
107
+ pattern.elements.forEach(walk);
108
+ }
109
+ else if (pattern.type === 'ObjectPattern') {
110
+ pattern.properties.forEach(property => walk(property.type === 'RestElement' ? property.argument : property.value));
111
+ }
112
+ else if (pattern.type === 'AssignmentPattern') {
113
+ walk(pattern.left);
114
+ }
115
+ else if (pattern.type === 'RestElement') {
116
+ walk(pattern.argument);
117
+ }
118
+ };
119
+ // Collect identifiers from each top-level variable declaration, including destructured bindings.
120
+ for (const stmt of body) {
121
+ if (stmt.type === 'VariableDeclaration') {
122
+ for (const decl of stmt.declarations) {
123
+ walk(decl.id);
124
+ }
125
+ }
126
+ }
127
+ return names;
128
+ }
129
+ /**
130
+ * A const's folded value, with the boot values in it named after the const.
131
+ *
132
+ * @param name The const's name.
133
+ * @param value Its folded value.
134
+ *
135
+ * @returns The value.
136
+ */
137
+ export function bindConst(name, value) {
138
+ nameBootValues(value, name);
139
+ return value;
140
+ }
141
+ /**
142
+ * The module's compile-time scope: `screen`, the seed, and every module-level `const` that folds. A const
143
+ * derived from `screen` is a boot value (see BootValue).
144
+ *
145
+ * @param program The parsed module.
146
+ * @param screen The panel size in this build folds its layout at.
147
+ * @param seed Bindings folded in first, so a const can reference them (image imports).
148
+ *
149
+ * @returns The scope.
150
+ */
151
+ export function moduleScope(program, screen, seed = {}) {
152
+ // Seed the scope (image imports as asset names) before folding module consts, so a const can reference them.
153
+ const scope = { screen: screenBinding(screen), ...seed };
154
+ // Fold module variables in order so later ones see earlier ones; skip functions, destructuring and non-folds.
155
+ for (const stmt of program.body) {
156
+ const declaration = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt;
157
+ if (declaration?.type !== 'VariableDeclaration')
158
+ continue;
159
+ for (const decl of declaration.declarations) {
160
+ if (!decl.id ||
161
+ decl.id.type !== 'Identifier' ||
162
+ !decl.init ||
163
+ isFn(decl.init)) {
164
+ continue;
165
+ }
166
+ try {
167
+ scope[decl.id.name] = bindConst(decl.id.name, evalStatic(decl.init, withUndefined(scope), 'boot'));
168
+ }
169
+ catch {
170
+ /* not a static const — skip */
171
+ }
172
+ }
173
+ }
174
+ return scope;
175
+ }
176
+ /**
177
+ * Infers a C struct shape from a list-state's initial elements (objects of strings/numbers).
178
+ *
179
+ * @param items The folded initial value.
180
+ * @param name The state's name, for errors.
181
+ *
182
+ * @returns The struct: one field per key of the first element.
183
+ */
184
+ function inferItemStruct(items, name) {
185
+ // Require a non-empty array so the first element can define the list state's fixed item shape.
186
+ const shapeHint = 'a list state is a fixed-shape struct array: each element must be an OBJECT with the same string/number fields, ' +
187
+ 'e.g. useState([{ title: "A", n: 1 }, { title: "B", n: 2 }]). The first element defines the columns.';
188
+ if (!Array.isArray(items) || !items.length) {
189
+ throw aotError(`AOT: list state "${name}" needs ≥1 initial element to infer its item shape`, shapeHint);
190
+ }
191
+ // Require the first list element to be a plain object so its keys can define the item struct.
192
+ const first = items[0];
193
+ if (typeof first !== 'object' || first === null || Array.isArray(first)) {
194
+ throw aotError(`AOT: list state "${name}" elements must be objects`, shapeHint);
195
+ }
196
+ // Type each field from the first element's value: a string, an int or a float.
197
+ const fields = Object.keys(first).map((key) => {
198
+ const fieldValue = first[key];
199
+ if (typeof fieldValue === 'string')
200
+ return { key, kind: 'string' };
201
+ if (typeof fieldValue === 'number') {
202
+ return { key, kind: Number.isInteger(fieldValue) ? 'int' : 'float' };
203
+ }
204
+ throw aotError(`AOT: list state "${name}" field "${key}" must be a string or number`, shapeHint);
205
+ });
206
+ return { fields };
207
+ }
208
+ /**
209
+ * Collects a component's useState declarations → state descriptors keyed by JS name (reads) and setter
210
+ * name (writes). `prefix` namespaces the C STORAGE so each inlined child instance gets its own slots: the
211
+ * lookup keys stay the bare JS names (`count`), but the C field / array / count derive from `cField`
212
+ * (`<prefix>count`). prefix='' (the App) keeps the storage names exactly the JS names.
213
+ * `caps` are the compiler's resolved caps (see resolveOptions); a list state takes its capacity from it.
214
+ *
215
+ * @param fnBody The component's body.
216
+ * @param scope Compile-time constants the initial values fold against.
217
+ * @param caps The compile's caps.
218
+ * @param prefix The C storage prefix: none for the App, `c<n>_` for an inlined instance.
219
+ * @param wide Slots to declare 64-bit (see compileWidened).
220
+ *
221
+ * @returns The component's state table.
222
+ */
223
+ export function collectState(fnBody, scope, caps, prefix = '', wide = NO_WIDE) {
224
+ // Index each state by its JS name and, when it has one, by its setter's name.
225
+ const byName = new Map();
226
+ const bySetter = new Map();
227
+ // Scan the body's top-level declarations for useState and useHostValue calls.
228
+ for (const stmt of fnBody.body) {
229
+ if (stmt.type !== 'VariableDeclaration')
230
+ continue;
231
+ // Inspect each declaration in the statement so multiple hook bindings in one `const` are collected independently.
232
+ for (const decl of stmt.declarations) {
233
+ // Only hook-style call declarations can define collected state; plain variables and other initializers are skipped.
234
+ const init = decl.init;
235
+ if (init?.type !== 'CallExpression')
236
+ continue;
237
+ // useHostValue is a host-fed scalar: an s_state field like useState, written only via er_app_set_<name>().
238
+ const isHost = init.callee.name === 'useHostValue';
239
+ if (init.callee.name !== 'useState' && !isHost) {
240
+ continue;
241
+ }
242
+ // Accept useHostValue(name) as a direct scalar binding, while useState must keep the usual [value, setter] tuple pattern.
243
+ if (isHost ? decl.id.type !== 'Identifier' : decl.id.type !== 'ArrayPattern') {
244
+ continue;
245
+ }
246
+ // Derive the read name and optional setter from the binding shape: host values bind directly, while useState binds [value, setter].
247
+ const name = isHost
248
+ ? decl.id.name
249
+ : decl.id.elements[0]
250
+ ?.name;
251
+ const setter = isHost
252
+ ? undefined
253
+ : decl.id.elements[1]
254
+ ?.name;
255
+ if (!name)
256
+ continue;
257
+ // Build either a list-state record from an array initializer or a scalar record from the folded initial value.
258
+ const cField = prefix + name; // C storage name (== name for the App; instance-unique for a child)
259
+ const initArg = init.arguments[0];
260
+ let record;
261
+ if (!isHost && initArg?.type === 'ArrayExpression') {
262
+ // List state → a fixed-capacity C struct array + a count (s_<name>[CAP], s_<name>_count).
263
+ const items = evalStaticOrThrow(initArg, scope, `AOT: the initial value of list state "${name}" must be a compile-time constant array`, 'useState([...]) initial must be a literal array of objects/numbers/strings — no ' +
264
+ 'runtime values or function calls in the initial.');
265
+ // Infer the item struct, pinning any error to the initial value since this pass adds no location.
266
+ let struct;
267
+ try {
268
+ struct = inferItemStruct(items, name);
269
+ }
270
+ catch (error) {
271
+ if (initArg.loc && !error.aotLoc) {
272
+ error.aotLoc = initArg.loc.start; // collectState isn't withLoc-wrapped
273
+ }
274
+ throw error;
275
+ }
276
+ record = {
277
+ name,
278
+ cField,
279
+ setter,
280
+ kind: 'list',
281
+ struct,
282
+ items,
283
+ cap: caps.listCap,
284
+ cTypeName: `ErItem_${cField}`,
285
+ arrayName: `s_${cField}`,
286
+ countMember: `s_${cField}_count`,
287
+ };
288
+ }
289
+ else {
290
+ // Scalar state → one s_state field. Fold the initial value; no argument starts it at 0.
291
+ const initValue = initArg
292
+ ? evalStaticOrThrow(initArg, scope, `AOT: the initial value of state "${name}" must be a compile-time constant`, 'useState(x) initial must be a literal or a constant expression (number, string, ' +
293
+ 'bool, or arithmetic over consts) — not a runtime value or function call.')
294
+ : 0;
295
+ // A host value must be a finite number; check it directly, since cTypeOfValue maps non-numbers to int.
296
+ if (isHost && !Number.isFinite(initValue)) {
297
+ throw aotError(`AOT: useHostValue("${name}") must be a number — its initial value evaluated to ` +
298
+ `${JSON.stringify(initValue)}`, 'useHostValue(0) / useHostValue(0.0) — the host feeds an int or float; booleans, ' +
299
+ 'strings, and objects are not supported.');
300
+ }
301
+ // Refuse undefined, null and non-finite initials here; they would fold into invalid C with no location.
302
+ if (initValue === undefined ||
303
+ initValue === null ||
304
+ (typeof initValue === 'number' && !Number.isFinite(initValue))) {
305
+ const error = aotError(`AOT: the initial value of state "${name}" is ${initValue === undefined ? 'undefined' : String(initValue)}`, "give it a concrete starting value: useState(0), useState(''), useState(false).");
306
+ if (initArg?.loc) {
307
+ error.aotLoc = initArg.loc.start;
308
+ }
309
+ throw error;
310
+ }
311
+ // Pick the slot's C type from the initial value.
312
+ let cType = cTypeOfValue(initValue);
313
+ // Flag booleans: cTypeOfValue makes them int, but text lowering must render false differently from 0.
314
+ const isBool = typeof initValue === 'boolean';
315
+ // A literal written like 70.0 forces a float slot so the state can hold fractions (a smooth drag).
316
+ if (cType === 'int' &&
317
+ initArg?.type === 'NumericLiteral' &&
318
+ typeof initArg.extra?.raw === 'string' &&
319
+ /[.eE]/.test(initArg.extra.raw)) {
320
+ cType = 'float';
321
+ }
322
+ // A whole number past the int range starts it 64-bit (past 64 bits, a float), as does a setter that
323
+ // stores a timestamp or such a number in it (see compileWidened).
324
+ const initialWidth = cType === 'int' ? wideInitial(initValue) : null;
325
+ if (initialWidth === 'float') {
326
+ cType = 'float';
327
+ }
328
+ const widened = cType === 'int' && !isBool
329
+ ? (wide.get(cField) ??
330
+ (initialWidth === 'number' ? 'number' : undefined))
331
+ : undefined;
332
+ if (widened) {
333
+ cType = 'i64';
334
+ }
335
+ // String scalar → a fixed char buffer in ErAppState; setters snprintf into it (see scalarAssign).
336
+ const initial = cType === 'string' ? String(initValue) : Number(initValue);
337
+ if (cType === 'float') {
338
+ checkNumber(initial);
339
+ }
340
+ else if (cType === 'i64') {
341
+ cConstant(initial, cType); // BigInt refuses a value that is not a whole number
342
+ }
343
+ record = {
344
+ name,
345
+ cField,
346
+ setter,
347
+ kind: 'scalar',
348
+ cType,
349
+ isBool,
350
+ cMember: `s_state.${cField}`,
351
+ initial,
352
+ host: isHost, // host-fed → also emit a public er_app_set_<name>() setter
353
+ ...(widened ? { widened } : {}),
354
+ };
355
+ }
356
+ // Register the state for reads by name and for writes through its setter.
357
+ byName.set(name, record);
358
+ if (setter) {
359
+ bySetter.set(setter, record);
360
+ }
361
+ }
362
+ }
363
+ return { byName, bySetter };
364
+ }
365
+ /**
366
+ * The JSX a component body returns. A top-level `if` whose test folds is decided at compile time, so a
367
+ * responsive layout returns the branch for this build's screen. When the test depends on the panel and both
368
+ * outcomes return elements of one shape, they merge into one element whose values boot picks.
369
+ *
370
+ * @param fnBody The component's body.
371
+ * @param scope Compile-time constants the `if` tests fold against.
372
+ *
373
+ * @returns The returned element.
374
+ */
375
+ export function findReturnJSX(fnBody, scope = {}) {
376
+ const statementsOf = (branch) => branch.type === 'BlockStatement' ? branch.body : [branch];
377
+ // Fold top-level `if (staticCond) return …` at compile time — responsive layouts switch on `screen`.
378
+ const scan = (statements) => {
379
+ for (const [index, stmt] of statements.entries()) {
380
+ // A top-level `if` must fold; only the branch it takes is scanned.
381
+ if (stmt.type === 'IfStatement') {
382
+ let testValue;
383
+ try {
384
+ testValue = evalStatic(stmt.test, scope, 'boot');
385
+ }
386
+ catch {
387
+ throw new Error('AOT: a top-level `if` in the component must have a compile-time-constant test (e.g. ' +
388
+ 'on the `screen` global) — runtime layout branching is not supported');
389
+ }
390
+ // A test that depends on the panel needs no variant when both outcomes have one shape.
391
+ if (isBoot(testValue)) {
392
+ const merged = mergeOutcomes(stmt, statements.slice(index + 1));
393
+ if (merged)
394
+ return merged;
395
+ testValue = foldBoot(testValue);
396
+ }
397
+ // Follow only the statically selected branch and keep scanning it until a JSX return is found.
398
+ const branch = testValue ? stmt.consequent : stmt.alternate;
399
+ if (branch) {
400
+ const branchJSX = scan(statementsOf(branch));
401
+ if (branchJSX)
402
+ return branchJSX;
403
+ }
404
+ continue;
405
+ }
406
+ // A `return` with a value ends the scan and must return a single JSX element.
407
+ if (stmt.type === 'ReturnStatement' && stmt.argument) {
408
+ if (stmt.argument.type === 'JSXElement')
409
+ return stmt.argument;
410
+ throw new Error(`AOT: the component must return a single JSX element (got ${stmt.argument.type})`);
411
+ }
412
+ }
413
+ return null;
414
+ };
415
+ // What each outcome of an `if` returns (a branch that does not return falls through), merged when it can be.
416
+ const mergeOutcomes = (stmt, rest) => {
417
+ const restore = bootCheckpoint();
418
+ try {
419
+ const whenTrue = scan(statementsOf(stmt.consequent)) ?? scan(rest);
420
+ const whenFalse = (stmt.alternate && scan(statementsOf(stmt.alternate))) ?? scan(rest);
421
+ const merged = whenTrue && whenFalse
422
+ ? mergeBranchElements(stmt.test, whenTrue, whenFalse)
423
+ : null;
424
+ if (merged)
425
+ return merged;
426
+ }
427
+ catch {
428
+ /* an outcome that does not compile here is left to the fold, which reports it if it is taken */
429
+ }
430
+ restore();
431
+ return null;
432
+ };
433
+ // Scan the body; a component that never returns is an error.
434
+ const returnJSX = scan(fnBody.body);
435
+ if (!returnJSX) {
436
+ throw new Error('AOT: component has no return statement');
437
+ }
438
+ return returnJSX;
439
+ }
440
+ /**
441
+ * Returns the JSX a function component returns (arrow expression body or a block's return).
442
+ *
443
+ * @param fn The component.
444
+ * @param scope Compile-time constants its top-level `if` tests fold against.
445
+ *
446
+ * @returns The returned element.
447
+ */
448
+ export function componentReturnJSX(fn, scope = {}) {
449
+ if (fn.body.type === 'JSXElement')
450
+ return fn.body;
451
+ if (fn.body.type === 'BlockStatement')
452
+ return findReturnJSX(fn.body, scope);
453
+ throw new Error('AOT: component body must return a JSX element');
454
+ }
455
+ /**
456
+ * Whether a function returns JSX (a component) rather than a value (a helper).
457
+ *
458
+ * @param fn The function.
459
+ *
460
+ * @returns Whether its body is JSX or has a top-level `return <…/>`.
461
+ */
462
+ const fnReturnsJSX = (fn) => fn.body.type === 'JSXElement' ||
463
+ (fn.body.type === 'BlockStatement' &&
464
+ fn.body.body.some(statement => statement.type === 'ReturnStatement' &&
465
+ statement.argument?.type === 'JSXElement'));
466
+ /**
467
+ * Resolves a component definition expression to its function node, unwrapping memo(fn) / React.memo(fn).
468
+ *
469
+ * @param node The definition's initializer.
470
+ *
471
+ * @returns The function, or null when it is not one.
472
+ */
473
+ function asComponentFn(node) {
474
+ if (isFn(node))
475
+ return node;
476
+ // Treat memo(...) and React.memo(...) wrappers as transparent when they wrap a component function.
477
+ if (node?.type === 'CallExpression' &&
478
+ isFn(node.arguments[0]) &&
479
+ (node.callee.name === 'memo' ||
480
+ (node.callee.type === 'MemberExpression' &&
481
+ node.callee.property?.name === 'memo'))) {
482
+ return node.arguments[0];
483
+ }
484
+ return null;
485
+ }
486
+ /**
487
+ * Collects top-level function components (name → fn node), excluding the `App` entry component.
488
+ *
489
+ * @param program The parsed module.
490
+ *
491
+ * @returns The components, by name.
492
+ */
493
+ export function collectComponents(program) {
494
+ const components = new Map();
495
+ for (const stmt of program.body) {
496
+ const declaration = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt;
497
+ if (!declaration)
498
+ continue;
499
+ // `function Card() { return <…/>; }`
500
+ if (declaration.type === 'FunctionDeclaration' &&
501
+ declaration.id &&
502
+ declaration.id.name !== 'App' &&
503
+ fnReturnsJSX(declaration)) {
504
+ components.set(declaration.id.name, declaration);
505
+ }
506
+ // `const Card = (…) => <…/>`, optionally wrapped in memo(…).
507
+ if (declaration.type === 'VariableDeclaration') {
508
+ for (const decl of declaration.declarations) {
509
+ if (decl.id?.type !== 'Identifier' || decl.id.name === 'App')
510
+ continue;
511
+ const fn = asComponentFn(decl.init); // unwrap memo(...)
512
+ if (fn && fnReturnsJSX(fn)) {
513
+ components.set(decl.id.name, fn);
514
+ }
515
+ }
516
+ }
517
+ }
518
+ return components;
519
+ }
520
+ /**
521
+ * Collects callable HELPER functions (non-component, non-hook) a handler can inline: module-level
522
+ * `function f(){}` / `const f = () => {}` and the component's own local `const f = (args) => {…}` arrows.
523
+ * A helper is any function that does NOT return JSX (those are components) and is a plain function (not a
524
+ * useCallback/useMemo/useState call). Returns Map (name → fn node). Re-collected per component (cheap).
525
+ *
526
+ * @param componentBody The component's body.
527
+ * @param program The parsed module.
528
+ *
529
+ * @returns The helpers, by name.
530
+ */
531
+ export function collectHelpers(componentBody, program) {
532
+ // Record a binding as a helper when it holds a function that does not return JSX.
533
+ const helpers = new Map();
534
+ const addHelper = (name, fn) => {
535
+ if (name && name !== 'App' && isFn(fn) && !fnReturnsJSX(fn)) {
536
+ helpers.set(name, fn);
537
+ }
538
+ };
539
+ // Module-level function declarations and function-valued variables.
540
+ for (const stmt of program.body) {
541
+ const declaration = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt;
542
+ if (!declaration)
543
+ continue;
544
+ if (declaration.type === 'FunctionDeclaration' && declaration.id) {
545
+ addHelper(declaration.id.name, declaration);
546
+ }
547
+ if (declaration.type === 'VariableDeclaration') {
548
+ for (const decl of declaration.declarations) {
549
+ if (decl.id?.type === 'Identifier') {
550
+ addHelper(decl.id.name, decl.init);
551
+ }
552
+ }
553
+ }
554
+ }
555
+ // The component's own top-level arrows and functions (a hook call is not a function, so it is skipped).
556
+ if (componentBody.type === 'BlockStatement') {
557
+ for (const stmt of componentBody.body) {
558
+ if (stmt.type !== 'VariableDeclaration')
559
+ continue;
560
+ for (const decl of stmt.declarations) {
561
+ if (decl.id?.type === 'Identifier') {
562
+ addHelper(decl.id.name, decl.init);
563
+ }
564
+ }
565
+ }
566
+ }
567
+ return helpers;
568
+ }
569
+ /**
570
+ * Collects image imports — `import wxSun from './assets/wx_sun.png'` → Map (local → { name, importPath }).
571
+ * `name` is the file's basename without extension (the asset key `<Image source>` resolves to and that the
572
+ * Flow A bundler also uses); `importPath` is the source-relative path the CLI bakes from. Mirrors the Flow A
573
+ * esbuild asset plugin so the same `import → basename` convention holds in both flows.
574
+ *
575
+ * @param program The parsed module.
576
+ *
577
+ * @returns The image imports, by local name.
578
+ */
579
+ export function collectImageImports(program) {
580
+ // Map each default import of an image file to the file's basename.
581
+ const byLocal = new Map();
582
+ for (const stmt of program.body) {
583
+ if (stmt.type !== 'ImportDeclaration' ||
584
+ typeof stmt.source.value !== 'string') {
585
+ continue;
586
+ }
587
+ const importPath = stmt.source.value;
588
+ if (!IMAGE_EXT_RE.test(importPath))
589
+ continue;
590
+ const name = importPath.split(/[\\/]/).pop().replace(IMAGE_EXT_RE, '');
591
+ for (const specifier of stmt.specifiers) {
592
+ if (specifier.type === 'ImportDefaultSpecifier') {
593
+ byLocal.set(specifier.local.name, { name, importPath });
594
+ }
595
+ }
596
+ }
597
+ return byLocal;
598
+ }
599
+ /**
600
+ * Collects `import x from './foo.svg'` → Map(localName → { name, importPath }). Unlike an image (whose
601
+ * bytes the CLI bakes AFTER compile, so compile only needs its asset name), an <Svg source> needs the
602
+ * GEOMETRY during compile — so the CLI bakes the .svg to a vector artifact up front (bakeSvgArtifacts) and
603
+ * passes it in as opts.svgArtifacts, keyed by `name`. emitSvgSource resolves the local → name → artifact.
604
+ *
605
+ * @param program The parsed module.
606
+ *
607
+ * @returns The .svg imports, by local name.
608
+ */
609
+ export function collectSvgImports(program) {
610
+ // Map each default import of a .svg file to the file's basename.
611
+ const byLocal = new Map();
612
+ for (const stmt of program.body) {
613
+ if (stmt.type !== 'ImportDeclaration' ||
614
+ typeof stmt.source.value !== 'string') {
615
+ continue;
616
+ }
617
+ const importPath = stmt.source.value;
618
+ if (!/\.svg$/i.test(importPath))
619
+ continue;
620
+ const name = importPath
621
+ .split(/[\\/]/)
622
+ .pop()
623
+ .replace(/\.svg$/i, '');
624
+ for (const specifier of stmt.specifiers) {
625
+ if (specifier.type === 'ImportDefaultSpecifier') {
626
+ byLocal.set(specifier.local.name, { name, importPath });
627
+ }
628
+ }
629
+ }
630
+ return byLocal;
631
+ }
632
+ /**
633
+ * Bakes a Flow B app's <Svg source> imports → { assetName: artifact } via the SAME baker Flow A's esbuild
634
+ * .svg loader uses (svgToVector). This is the I/O half (reads .svg files) kept OUT of the pure compileSource;
635
+ * both CLI entries (aot/compile.mts and the consumer cli.mjs) call it and hand the result to opts.svgArtifacts.
636
+ *
637
+ * @param src App.jsx source text.
638
+ * @param baseDir Directory the import paths are resolved against (the app's dir).
639
+ *
640
+ * @returns Each import's artifact, by asset name: its op-tape, or a PNG for one the vector baker cannot draw.
641
+ */
642
+ export async function bakeSvgArtifacts(src, baseDir) {
643
+ // Parse with the TS plugin too (harmless for plain JSX), so a .tsx app's <Svg source> imports are found.
644
+ const program = parse(src, {
645
+ sourceType: 'module',
646
+ plugins: ['jsx', 'typescript'],
647
+ }).program;
648
+ const imports = collectSvgImports(program);
649
+ if (imports.size === 0)
650
+ return {};
651
+ // Load the baker only when there is something to bake.
652
+ const { svgToVector, svgToRaster, writeRasterPng } = await import('../../assets/bake-svg.mjs');
653
+ // Read each imported file and bake it to a vector op-tape.
654
+ const artifacts = {};
655
+ for (const [, svgImport] of imports) {
656
+ const svgPath = resolve(baseDir, svgImport.importPath);
657
+ if (!existsSync(svgPath)) {
658
+ throw new Error(`AOT: <Svg source> asset "${svgImport.name}" not found at ${svgPath}`);
659
+ }
660
+ // Rasterize an SVG the vector baker cannot fully draw to a PNG, so it renders as an Image instead of dropping.
661
+ const svgText = readFileSync(svgPath, 'utf8');
662
+ const artifact = (await svgToVector(svgText));
663
+ if (artifact.dropped && artifact.dropped.length) {
664
+ console.warn(`embedded-react: ${svgImport.name}.svg uses unsupported SVG feature(s) [${artifact.dropped.join(', ')}] — ` +
665
+ `rasterizing it as a fallback image (Flow B bakes the PNG into assets.generated.c). Simplify the SVG ` +
666
+ `to keep it a live vector.`);
667
+ const { width, height, png } = await svgToRaster(svgText);
668
+ artifacts[svgImport.name] = {
669
+ kind: 'raster',
670
+ name: svgImport.name,
671
+ width,
672
+ height,
673
+ png: writeRasterPng(svgImport.name, png),
674
+ };
675
+ }
676
+ else {
677
+ artifacts[svgImport.name] = artifact;
678
+ }
679
+ }
680
+ return artifacts;
681
+ }
682
+ /**
683
+ * Collects `const fn = useCallback((...) => {...}, deps)` → Map (name → arrow fn node). Deps are ignored:
684
+ * the AOT re-renders via its own dependency tracking, so useCallback only names a shared C handler.
685
+ *
686
+ * @param fnBody The component's body.
687
+ *
688
+ * @returns The callbacks, by name.
689
+ */
690
+ export function collectCallbacks(fnBody) {
691
+ const callbacks = new Map();
692
+ if (fnBody.type !== 'BlockStatement')
693
+ return callbacks;
694
+ // Collect top-level useCallback bindings whose first argument is an inline function, keyed by the variable name.
695
+ for (const stmt of fnBody.body) {
696
+ if (stmt.type !== 'VariableDeclaration')
697
+ continue;
698
+ for (const decl of stmt.declarations) {
699
+ const init = decl.init;
700
+ if (init?.type === 'CallExpression' &&
701
+ init.callee.name === 'useCallback' &&
702
+ decl.id.type === 'Identifier' &&
703
+ isFn(init.arguments[0])) {
704
+ callbacks.set(decl.id.name, init.arguments[0]);
705
+ }
706
+ }
707
+ }
708
+ return callbacks;
709
+ }
710
+ /**
711
+ * Collects `const m = useMemo(() => expr, deps)` → Map (name → the memo's expression node).
712
+ *
713
+ * @param fnBody The component's body.
714
+ *
715
+ * @returns Each memo's expression, by name.
716
+ */
717
+ export function collectMemos(fnBody) {
718
+ const memos = new Map();
719
+ if (fnBody.type !== 'BlockStatement')
720
+ return memos;
721
+ // Collect expression-bodied useMemo bindings; block-bodied memos are rejected until statement-bodied folding is supported.
722
+ for (const stmt of fnBody.body) {
723
+ if (stmt.type !== 'VariableDeclaration')
724
+ continue;
725
+ for (const decl of stmt.declarations) {
726
+ const init = decl.init;
727
+ if (init?.type === 'CallExpression' &&
728
+ init.callee.name === 'useMemo' &&
729
+ decl.id.type === 'Identifier' &&
730
+ isFn(init.arguments[0])) {
731
+ const body = init.arguments[0].body;
732
+ if (body.type === 'BlockStatement') {
733
+ throw new Error(`AOT: useMemo for "${decl.id.name}" must be a single expression (for now)`);
734
+ }
735
+ memos.set(decl.id.name, body);
736
+ }
737
+ }
738
+ }
739
+ return memos;
740
+ }
741
+ /**
742
+ * Collects `useEffect(() => {…}, deps)` calls → { fn, deps, node }. Dep validity is checked at compile time.
743
+ *
744
+ * @param fnBody The component's body.
745
+ *
746
+ * @returns The effects, in source order.
747
+ */
748
+ export function collectEffects(fnBody) {
749
+ const effects = [];
750
+ if (fnBody.type !== 'BlockStatement')
751
+ return effects;
752
+ // Collect top-level useEffect calls, requiring an inline function so the effect body can be lowered later with its deps.
753
+ for (const stmt of fnBody.body) {
754
+ if (stmt.type !== 'ExpressionStatement')
755
+ continue;
756
+ const call = stmt.expression;
757
+ if (call?.type === 'CallExpression' &&
758
+ call.callee.type === 'Identifier' &&
759
+ call.callee.name === 'useEffect') {
760
+ if (!isFn(call.arguments[0])) {
761
+ throw aotError('AOT: useEffect must take an inline function', 'write useEffect(() => { … }, []).');
762
+ }
763
+ effects.push({
764
+ fn: call.arguments[0],
765
+ deps: call.arguments[1],
766
+ node: call,
767
+ });
768
+ }
769
+ }
770
+ return effects;
771
+ }
772
+ /**
773
+ * True if a function component declares any useState (per-instance child state — not yet supported).
774
+ *
775
+ * @param fn The component.
776
+ *
777
+ * @returns Whether its body calls useState.
778
+ */
779
+ export function usesState(fn) {
780
+ if (fn.body.type !== 'BlockStatement')
781
+ return false;
782
+ return fn.body.body.some(statement => statement.type === 'VariableDeclaration' &&
783
+ statement.declarations.some(decl => decl.init?.type === 'CallExpression' &&
784
+ decl.init.callee.name === 'useState'));
785
+ }