embedded-react 0.14.1 → 0.16.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 (61) hide show
  1. package/README.md +51 -486
  2. package/aot/compile.mjs +173 -8272
  3. package/aot/compiler/animations.mjs +1001 -0
  4. package/aot/compiler/assemble.mjs +806 -0
  5. package/aot/compiler/c/animations.mjs +362 -0
  6. package/aot/compiler/c/expressions.mjs +215 -0
  7. package/aot/compiler/c/functions.mjs +268 -0
  8. package/aot/compiler/c/keyboard.mjs +96 -0
  9. package/aot/compiler/c/nodes.mjs +282 -0
  10. package/aot/compiler/c/pan-responder.mjs +136 -0
  11. package/aot/compiler/c/statements.mjs +242 -0
  12. package/aot/compiler/c/text.mjs +83 -0
  13. package/aot/compiler/c/vectors.mjs +381 -0
  14. package/aot/compiler/c-syntax.mjs +127 -0
  15. package/aot/compiler/check.mjs +165 -0
  16. package/aot/compiler/collect.mjs +743 -0
  17. package/aot/compiler/control-flow.mjs +683 -0
  18. package/aot/compiler/diagnostics.mjs +137 -0
  19. package/aot/compiler/elements/activity-indicator.mjs +160 -0
  20. package/aot/compiler/elements/dial.mjs +343 -0
  21. package/aot/compiler/elements/flat-list.mjs +139 -0
  22. package/aot/compiler/elements/image.mjs +151 -0
  23. package/aot/compiler/elements/modal.mjs +158 -0
  24. package/aot/compiler/elements/props.mjs +474 -0
  25. package/aot/compiler/elements/switch.mjs +183 -0
  26. package/aot/compiler/elements/text-input.mjs +171 -0
  27. package/aot/compiler/expressions.mjs +1479 -0
  28. package/aot/compiler/handlers.mjs +1072 -0
  29. package/aot/compiler/ir/animations.mjs +16 -0
  30. package/aot/compiler/ir/app.mjs +16 -0
  31. package/aot/compiler/ir/expressions.mjs +16 -0
  32. package/aot/compiler/ir/functions.mjs +16 -0
  33. package/aot/compiler/ir/keyboard.mjs +16 -0
  34. package/aot/compiler/ir/nodes.mjs +83 -0
  35. package/aot/compiler/ir/pan-responder.mjs +16 -0
  36. package/aot/compiler/ir/source.mjs +16 -0
  37. package/aot/compiler/ir/statements.mjs +16 -0
  38. package/aot/compiler/ir/text.mjs +16 -0
  39. package/aot/compiler/ir/types.mjs +185 -0
  40. package/aot/compiler/ir/vectors.mjs +16 -0
  41. package/aot/compiler/keyboard.mjs +152 -0
  42. package/aot/compiler/lower.mjs +282 -0
  43. package/aot/compiler/nodes.mjs +683 -0
  44. package/aot/compiler/options.mjs +55 -0
  45. package/aot/compiler/out.mjs +94 -0
  46. package/aot/compiler/pan-responder.mjs +354 -0
  47. package/aot/compiler/parse.mjs +300 -0
  48. package/aot/compiler/static-eval.mjs +228 -0
  49. package/aot/compiler/style-text.mjs +648 -0
  50. package/aot/compiler/svg.mjs +1167 -0
  51. package/aot/compiler/types.mjs +16 -0
  52. package/aot/screenshot-smoke.mjs +95 -55
  53. package/aot/style-map.mjs +366 -304
  54. package/cli.mjs +5 -8
  55. package/package.json +14 -6
  56. package/sim/embedded-react.cjs +1 -1
  57. package/sim/embedded-react.js +1 -1
  58. package/sim/embedded-react.wasm +0 -0
  59. package/src/embedded-react/FlatList.js +4 -4
  60. package/src/embedded-react/index.d.ts +2 -1
  61. package/src/props.js +1 -1
@@ -0,0 +1,806 @@
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 { readFileSync } from 'node:fs';
20
+ import { cConstant, cScalarType, stripCLiterals, floatLit, cstr, } from './c-syntax.mjs';
21
+ import { CHECKED_OP } from './expressions.mjs';
22
+ import { lowerApp } from './lower.mjs';
23
+ import { printWaitDeclarations } from './c/animations.mjs';
24
+ import { printAnimationCallback, printDepEffectCheck, printEffectFunction, printHandler, printMountEffect, printStaticDecl, printTimerFunction, } from './c/functions.mjs';
25
+ import { printKeyboard } from './c/keyboard.mjs';
26
+ import { printElementTree, printNode, printNodeUpdate } from './c/nodes.mjs';
27
+ import { printPanDecls, printPanQuery } from './c/pan-responder.mjs';
28
+ import { printVectorBlocks, printVectorRebuild } from './c/vectors.mjs';
29
+ import { isStateDriven, nodesOf, stateDrivenVectorOf } from './ir/nodes.mjs';
30
+ /*----------------------------------------------------------------------------------------------------------------------
31
+ - Constants
32
+ ---------------------------------------------------------------------------------------------------------------------*/
33
+ // The compiler's version, stamped into app.gen.c and asserted against er_version.h, so a mismatch fails to compile.
34
+ const PKG_VERSION = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
35
+ const [PKG_MAJOR, PKG_MINOR] = PKG_VERSION.split('.');
36
+ // libm symbols, and the helpers that call them; any of them in the generated code means it includes <math.h>.
37
+ const LIBM_USE = new RegExp('\\b(sinf|cosf|tanf|sqrtf|fabsf|roundf|floorf|ceilf|fminf|fmaxf|atan2f|powf|fmodf|isfinite|' +
38
+ 'app_roundf|app_ftoa|app_vector_dirty|M_PI)\\b');
39
+ /*----------------------------------------------------------------------------------------------------------------------
40
+ - Implementation
41
+ ---------------------------------------------------------------------------------------------------------------------*/
42
+ /**
43
+ * The `#ifndef` marker a board example guards on, from a demo name. Every character outside [A-Za-z0-9]
44
+ * becomes `_<hex code point>_`, so the result is a C identifier AND the mapping is one-to-one: `foo-bar`
45
+ * is ER_AOT_DEMO_foo_2d_bar and `foo_bar` is ER_AOT_DEMO_foo_5f_bar. Flattening both to `foo_bar` would
46
+ * let a board guard accept the wrong app from either entry point that generates one.
47
+ */
48
+ export const demoMarker = (demo) => `ER_AOT_DEMO_${demo.replace(/[^A-Za-z0-9]/gu, character => `_${character.codePointAt(0).toString(16)}_`)}`;
49
+ /**
50
+ * Compiles a Flow B app's JSX (or TSX) source to C: lowers it (lowerApp) and writes the result as app.gen.c
51
+ * and app.gen.h. Pure (no I/O), so it can be unit-tested directly; compileSource (compile.mts) is the public
52
+ * entry around it.
53
+ *
54
+ * @param src The App.jsx/App.tsx source text.
55
+ * @param demo Demo name (only used in the generated-by header comment).
56
+ * @param opts compileSource's options, resolved (see resolveOptions).
57
+ * @param wide State/ref slots to declare 64-bit (see compileWidened).
58
+ * @param stores Collects every value stored into an int slot.
59
+ *
60
+ * @returns The generated app.gen.c and app.gen.h, and what they contain.
61
+ */
62
+ export const compileSourceImpl = (src, demo, opts, wide, stores) => writeApp(lowerApp(src, opts, wide, stores), demo, opts);
63
+ /**
64
+ * Writes a lowered app as C: file-scope state, declarations and functions, then er_app_build(), in
65
+ * app.gen.c, and the app's public entry points in app.gen.h.
66
+ *
67
+ * @param app The lowered app.
68
+ * @param demo Demo name (only used in the generated-by header comment).
69
+ * @param opts compileSource's options, resolved (see resolveOptions).
70
+ *
71
+ * @returns The generated app.gen.c and app.gen.h, and what they contain.
72
+ */
73
+ export function writeApp(app, demo, opts) {
74
+ const { out } = app;
75
+ // One ERNode* local in er_app_build() per node the tree allocated.
76
+ const nodeDecls = Array.from({ length: out.nodeCount }, (_, nodeIndex) => `n${nodeIndex}`);
77
+ // App state + every inlined child instance's per-instance state (each already namespaced via cField).
78
+ const stateRecords = app.state;
79
+ const scalarRecords = stateRecords.filter(stateRecord => stateRecord.kind === 'scalar');
80
+ const listRecords = stateRecords.filter(stateRecord => stateRecord.kind === 'list');
81
+ // Scalar state → one ErAppState struct. List state → a fixed-capacity struct array + a count each.
82
+ const fieldCDecl = (field) => field.kind === 'string'
83
+ ? ` char ${field.key}[${opts.caps.listStrCap}];`
84
+ : ` ${field.kind} ${field.key};`;
85
+ const itemInit = (item, struct) => {
86
+ const values = struct.fields.map(field => field.kind === 'string'
87
+ ? cstr(String(item[field.key] ?? ''))
88
+ : field.kind === 'float'
89
+ ? floatLit(Number(item[field.key]) || 0)
90
+ : String(Math.round(Number(item[field.key]) || 0)));
91
+ return `{ ${values.join(', ')} }`;
92
+ };
93
+ const listBlocks = listRecords
94
+ .map(listRecord => `typedef struct\n{\n${listRecord.struct.fields.map(fieldCDecl).join('\n')}\n} ${listRecord.cTypeName};\n\n` +
95
+ `static ${listRecord.cTypeName} ${listRecord.arrayName}[${listRecord.cap}] = ` +
96
+ `{${listRecord.items.map(item => '\n ' + itemInit(item, listRecord.struct)).join(',')}\n};\n` +
97
+ `static int ${listRecord.countMember} = ${listRecord.items.length};\n`)
98
+ .join('\n');
99
+ const scalarFieldDecl = (scalarRecord) => scalarRecord.cType === 'string'
100
+ ? ` char ${scalarRecord.cField}[${opts.caps.listStrCap}];`
101
+ : ` ${cScalarType(scalarRecord.cType)} ${scalarRecord.cField};`;
102
+ const scalarBlock = scalarRecords.length
103
+ ? `typedef struct\n{\n${scalarRecords.map(scalarFieldDecl).join('\n')}\n} ` +
104
+ `ErAppState;\n\nstatic ErAppState s_state = ` +
105
+ `{${scalarRecords.map(scalarRecord => ` .${scalarRecord.cField} = ${cConstant(scalarRecord.initial, scalarRecord.cType)}`).join(',')} ` +
106
+ `};\n`
107
+ : '';
108
+ const stateBlock = [scalarBlock, listBlocks].filter(Boolean).join('\n');
109
+ // The nodes er_app_build() creates, each before its children, and what app_update() re-applies to them.
110
+ const nodes = nodesOf(app.root);
111
+ const buildLines = printElementTree(app.root).join('\n');
112
+ const updates = nodes.flatMap(node => printNode(node).update ?? []);
113
+ // A file-scope handle for each node app_update() re-applies, and one for each drawing it rebuilds.
114
+ const handleDecls = nodes
115
+ .flatMap(node => [
116
+ ...(isStateDriven(node) ? [node.id] : []),
117
+ ...(stateDrivenVectorOf(node) ? [node.id] : []),
118
+ ])
119
+ .map(nodeId => `static ERNode* s_${nodeId};`)
120
+ .join('\n');
121
+ // Static per-value ref, skipping refs the C never touches, so consumer builds don't warn about unused statics.
122
+ const refDecls = app.refs
123
+ .filter(refRecord => refRecord.used)
124
+ .map(refRecord => `static ` +
125
+ `${refRecord.kind === 'value' ? cScalarType(refRecord.cType) : refRecord.cType} ` +
126
+ `${refRecord.cVar} = ${refRecord.kind === 'value' ? cConstant(refRecord.initial, refRecord.cType) : 'NULL'};`)
127
+ .join('\n');
128
+ // Vector op-tapes + paint tables, and the build_svgN() functions declared before app_update, which calls them.
129
+ const { data: vectorBlock, builders: vectorBuilderBlock } = printVectorBlocks(out.vectors);
130
+ // Animated values — one engine-side handle each, created at the top of er_app_build (binds reference them).
131
+ const animList = app.animations;
132
+ const animDecls = animList
133
+ .map(animValue => `static ERAnimValueHandle ${animValue.cVar};`)
134
+ .join('\n');
135
+ const animCreate = animList
136
+ .map(animValue => ` ${animValue.cVar} = er_anim_value_create(${floatLit(animValue.initial)});`)
137
+ .join('\n');
138
+ // The app's functions, and what er_app_build() runs last, as C.
139
+ const { hasUpdate } = app;
140
+ const usesWaits = [...out.animWaits.values()].some(record => record.isStarted);
141
+ const handlers = out.handlers.map(printHandler);
142
+ const timerFns = out.timerFns.map(printTimerFunction);
143
+ const animCbs = out.animCbs.flatMap(printAnimationCallback);
144
+ const effectFns = out.effectFns.map(printEffectFunction);
145
+ const mountEffects = out.mountEffects.flatMap(printMountEffect).join('\n');
146
+ // app_update(): re-apply state-driven node props, rebuild state-driven Svgs, then run dep-driven effects.
147
+ const updateBlock = (() => {
148
+ if (!hasUpdate)
149
+ return '';
150
+ const lines = ['static void app_update(void)', '{'];
151
+ if (updates.length) {
152
+ lines.push(' ERProps p;');
153
+ }
154
+ for (const update of updates) {
155
+ lines.push(...printNodeUpdate(update));
156
+ }
157
+ // State-driven Svgs: recompute the op-tape from state and re-upload.
158
+ for (const node of nodes) {
159
+ const vector = stateDrivenVectorOf(node);
160
+ if (vector) {
161
+ lines.push(...printVectorRebuild(node.id, vector));
162
+ }
163
+ }
164
+ // Dep-driven useEffect: run each effect whose dependency value changed since the last app_update.
165
+ for (const effect of out.depEffects) {
166
+ lines.push(printDepEffectCheck(effect));
167
+ }
168
+ lines.push('}');
169
+ return lines.join('\n');
170
+ })();
171
+ // PanResponder gesture state, plus should-set predicates: bool callbacks the engine calls during negotiation.
172
+ const panDeclBlock = out.panResponders.flatMap(printPanDecls).join('\n');
173
+ const queryDefs = out.panResponders
174
+ .flatMap(pan => pan.queries.map(query => printPanQuery(pan, query)))
175
+ .map(query => `static bool ${query.name}(ERNode* node, const EREventData* data, void* ` +
176
+ `user_data)\n{\n (void)node;\n (void)data;\n (void)user_data;\n return ` +
177
+ `${query.expr};\n}`)
178
+ .join('\n\n');
179
+ // Event handlers, each with the engine's event callback signature.
180
+ const handlerDefs = handlers
181
+ .map(handler => `static void ${handler.name}(ERNode* node, const EREventData* data, void* ` +
182
+ `user_data)\n{\n (void)node;\n (void)data;\n ` +
183
+ `(void)user_data;\n${handler.body.join('\n')}\n}`)
184
+ .join('\n\n');
185
+ // Dep-driven effects: a previous-value static per dep, the bodies, and forward decls (app_update comes first).
186
+ const effectDeclsBlock = out.effectDecls
187
+ .flatMap(decl => printStaticDecl(decl, opts.caps.listStrCap))
188
+ .join('\n');
189
+ const effectFwdDecls = effectFns
190
+ .map(effectFn => `static void ${effectFn.name}(void);`)
191
+ .join('\n');
192
+ const effectFnDefs = effectFns
193
+ .map(effectFn => `static void ${effectFn.name}(void)\n{\n${effectFn.body.join('\n')}\n}`)
194
+ .join('\n\n');
195
+ // setInterval/setTimeout: a fixed timer table er_app_tick advances, emitted only when the app uses timers.
196
+ const timerTableBlock = out.usesTimers
197
+ ? `#include <stdbool.h>
198
+
199
+ #ifndef ER_AOT_MAX_TIMERS
200
+ #define ER_AOT_MAX_TIMERS 8
201
+ #endif
202
+
203
+ typedef struct
204
+ {
205
+ int interval_ms;
206
+ int remaining_ms;
207
+ int gen;
208
+ bool repeat;
209
+ bool active;
210
+ void (*fn)(void);
211
+ } ErTimer;
212
+ static ErTimer s_timers[ER_AOT_MAX_TIMERS];
213
+
214
+ /* An id carries the slot AND the generation that owns it, so clearing an id whose timer has already
215
+ finished (a one-shot, or an earlier clear) cannot kill whatever took the slot next. */
216
+ static int er_timer_add(int ms, bool repeat, void (*fn)(void))
217
+ {
218
+ for (int i = 0; i < ER_AOT_MAX_TIMERS; i++)
219
+ {
220
+ if (!s_timers[i].active)
221
+ {
222
+ s_timers[i].interval_ms = ms < 1 ? 1 : ms;
223
+ s_timers[i].remaining_ms = s_timers[i].interval_ms;
224
+ s_timers[i].gen = (s_timers[i].gen + 1) & 0xFFFF;
225
+ s_timers[i].repeat = repeat;
226
+ s_timers[i].active = true;
227
+ s_timers[i].fn = fn;
228
+ return (s_timers[i].gen * ER_AOT_MAX_TIMERS) + i;
229
+ }
230
+ }
231
+ return -1; /* table full (raise ER_AOT_MAX_TIMERS) */
232
+ }`
233
+ : '';
234
+ const timerFnDefs = timerFns
235
+ .map(timerFn => `static void ${timerFn.name}(void)\n{\n${timerFn.body.join('\n')}\n}`)
236
+ .join('\n\n');
237
+ // Forward-declare every timer fn: the handlers and effect fns that register one are defined before it.
238
+ const timerFnFwdDecls = timerFns
239
+ .map(timerFn => `static void ${timerFn.name}(void);`)
240
+ .join('\n');
241
+ // Animated.sequence on_complete callbacks each start the next step, so they are forward-declared.
242
+ const animCbDecls = animCbs
243
+ .map(animCb => `static void ${animCb.name}(bool finished, void* user_data);`)
244
+ .join('\n');
245
+ const animCbDefs = animCbs
246
+ .map(animCb => `static void ${animCb.name}(bool finished, void* user_data)\n{\n (void)finished;\n ` +
247
+ ` (void)user_data;\n${animCb.body.join('\n')}\n}`)
248
+ .join('\n\n');
249
+ // Apply a wall-clock change on the app loop, not in the setter: the host may set it before er_app_build().
250
+ const wallClockRefresh = hasUpdate
251
+ ? ' if (s_wall_clock_changed)\n {\n s_wall_clock_changed = 0;\n app_update();\n }\n'
252
+ : '';
253
+ // er_app_tick(): fire due timers; without timers it only applies a clock change, so a host can always call it.
254
+ // Completion waits count down on the app loop too.
255
+ const waitTick = usesWaits ? ' app_wait_tick(dt_ms);\n' : '';
256
+ const appTickFn = out.usesTimers
257
+ ? `void er_app_tick(int dt_ms)
258
+ {
259
+ ${wallClockRefresh}${waitTick} for (int i = 0; i < ER_AOT_MAX_TIMERS; i++)
260
+ {
261
+ if (!s_timers[i].active)
262
+ {
263
+ continue;
264
+ }
265
+ s_timers[i].remaining_ms -= dt_ms;
266
+ if (s_timers[i].remaining_ms <= 0)
267
+ {
268
+ void (*fn)(void) = s_timers[i].fn;
269
+ if (s_timers[i].repeat)
270
+ {
271
+ s_timers[i].remaining_ms += s_timers[i].interval_ms;
272
+ if (s_timers[i].remaining_ms <= 0)
273
+ {
274
+ s_timers[i].remaining_ms = s_timers[i].interval_ms; /* dt ran long; don't spiral */
275
+ }
276
+ }
277
+ else
278
+ {
279
+ s_timers[i].active = false;
280
+ }
281
+ if (fn)
282
+ {
283
+ fn();
284
+ }
285
+ }
286
+ }
287
+ }`
288
+ : `void er_app_tick(int dt_ms)\n{\n (void)dt_ms;\n${wallClockRefresh}${waitTick}}`;
289
+ // useEffect(fn, []) bodies, run once at the end of er_app_build().
290
+ const mountEffectsBlock = mountEffects
291
+ ? '\n /* useEffect(fn, []) — run once on mount. */\n' +
292
+ mountEffects +
293
+ '\n'
294
+ : '';
295
+ // app_round_dim() when a state-driven style value has to be snapped to a whole pixel at runtime.
296
+ const usesDimRound = /\bapp_round_dim\(/.test([
297
+ updateBlock,
298
+ handlerDefs,
299
+ queryDefs,
300
+ effectFnDefs,
301
+ animCbDefs,
302
+ timerFnDefs,
303
+ mountEffects,
304
+ buildLines,
305
+ ].join('\n'));
306
+ const dimRoundBlock = usesDimRound
307
+ ? `
308
+ /* Snaps a state-driven style value to a whole pixel the way JavaScript's Math.round does — floor(x + 0.5),
309
+ halves UP rather than away from zero. ERProps dimensions are int16 and a plain cast would truncate toward
310
+ zero, which is how the two flows once laid the same app out a pixel apart. Values known at compile time
311
+ are folded with Math.round; this is that rule's runtime twin, and Flow A's bridge applies the same one. */
312
+ static int16_t app_round_dim(double v)
313
+ {
314
+ /* NaN compares false against everything, so it would slip past both clamps into an undefined cast. */
315
+ if (v != v)
316
+ {
317
+ return 0;
318
+ }
319
+ if (v < -32768.0)
320
+ {
321
+ return -32768;
322
+ }
323
+ if (v > 32767.0)
324
+ {
325
+ return 32767;
326
+ }
327
+ const double r = v + 0.5;
328
+ const int32_t t = (int32_t)r; /* truncates toward zero */
329
+ return (int16_t)(((double)t > r) ? t - 1 : t);
330
+ }
331
+ `
332
+ : '';
333
+ // Include <math.h> when the generated code, or a helper it calls, uses a libm symbol.
334
+ const usesMath = out.needsMath ||
335
+ LIBM_USE.test([
336
+ stateBlock,
337
+ refDecls,
338
+ vectorBuilderBlock,
339
+ updateBlock,
340
+ handlerDefs,
341
+ queryDefs,
342
+ animCbDefs,
343
+ timerFnDefs,
344
+ mountEffects,
345
+ buildLines,
346
+ ].join('\n'));
347
+ // Each useHostValue gets a public setter that writes its field and refreshes via app_update(), like a JS setter.
348
+ const hostRecords = scalarRecords.filter(scalarRecord => scalarRecord.host);
349
+ const hostSettersBlock = hostRecords
350
+ .map(hostRecord => `void er_app_set_${hostRecord.name}(${cScalarType(hostRecord.cType)} v)\n{\n ` +
351
+ `${hostRecord.cMember} = v;\n${hasUpdate ? ' app_update();\n' : ''}}`)
352
+ .join('\n\n');
353
+ const hostSetterProtos = hostRecords
354
+ .map(hostRecord => `/** @brief Host-fed input '${hostRecord.name}' (useHostValue): set its value and ` +
355
+ `refresh the display. */\nvoid ` +
356
+ `er_app_set_${hostRecord.name}(${cScalarType(hostRecord.cType)} v);`)
357
+ .join('\n\n');
358
+ // File-local helpers (clock readers, JS-exact math), each emitted only when generated code calls it.
359
+ const APP_HELPERS = [
360
+ [
361
+ 'app_perf_now',
362
+ 'static int64_t app_perf_now(void)\n{\n return (int64_t)er_now_ms64();\n}',
363
+ ],
364
+ [
365
+ 'app_date_now',
366
+ 'static int64_t app_date_now(void)\n{\n return s_wall_offset_ms + (int64_t)er_now_ms64();\n}',
367
+ ],
368
+ ...Object.entries(CHECKED_OP).map(([operator, name]) => [
369
+ name,
370
+ `/* a ${operator} b, saturated to the int range: C leaves a signed overflow undefined. */\n` +
371
+ `static int ${name}(int a, int b)\n{\n const int64_t v = (int64_t)a ${operator} b;\n` +
372
+ ' return v > INT_MAX ? INT_MAX : v < INT_MIN ? INT_MIN : (int)v;\n}',
373
+ ]),
374
+ [
375
+ 'app_neg',
376
+ '/* -a, saturated: -INT_MIN does not fit an int. */\n' +
377
+ 'static int app_neg(int a)\n{\n return a == INT_MIN ? INT_MAX : -a;\n}',
378
+ ],
379
+ [
380
+ 'app_mod',
381
+ "/* a % b as JS computes it, kept whole: the remainder has the dividend's sign, as in C. JS gives NaN\n" +
382
+ ' for b == 0, which is 0 here, and INT_MIN % -1 is 0, where C would overflow. */\n' +
383
+ 'static int app_mod(int a, int b)\n{\n return (b == 0 || b == -1) ? 0 : a % b;\n}',
384
+ ],
385
+ [
386
+ 'app_abs',
387
+ '/* Math.abs of an int, saturated: -INT_MIN does not fit an int. */\n' +
388
+ 'static int app_abs(int v)\n{\n return v >= 0 ? v : v == INT_MIN ? INT_MAX : -v;\n}',
389
+ ],
390
+ [
391
+ 'app_min',
392
+ 'static int app_min(int a, int b)\n{\n return a < b ? a : b;\n}',
393
+ ],
394
+ [
395
+ 'app_max',
396
+ 'static int app_max(int a, int b)\n{\n return a > b ? a : b;\n}',
397
+ ],
398
+ [
399
+ 'app_div',
400
+ '/* a / b as JS computes it, kept whole: truncated toward zero, and saturated where JS gives +-Infinity\n' +
401
+ ' (b == 0) or a result past the int range (INT_MIN / -1). 0 / 0 is NaN, which is 0. */\n' +
402
+ 'static int app_div(int a, int b)\n{\n' +
403
+ ' if (b == 0)\n {\n return a > 0 ? INT_MAX : a < 0 ? INT_MIN : 0;\n }\n' +
404
+ ' if (b == -1)\n {\n return a == INT_MIN ? INT_MAX : -a;\n }\n' +
405
+ ' return a / b;\n}',
406
+ ],
407
+ [
408
+ 'app_floordiv',
409
+ "/* Math.floor(a / b) for two ints, exactly: C's `/` rounds toward zero where floor rounds down, and a float\n" +
410
+ ' quotient would round an operand past 2^24. JS gives +-Infinity for b == 0, which saturates by the sign\n' +
411
+ ' of a (0 / 0 is NaN, which is 0); INT_MIN / -1 saturates too, so the quotient is taken in 64 bits. */\n' +
412
+ 'static int app_floordiv(int a, int b)\n{\n' +
413
+ ' if (b == 0)\n {\n return a > 0 ? INT_MAX : a < 0 ? INT_MIN : 0;\n }\n' +
414
+ ' const int64_t q = (int64_t)a / b;\n' +
415
+ ' const int64_t f = ((int64_t)a % b != 0 && (a < 0) != (b < 0)) ? q - 1 : q;\n' +
416
+ ' return f > INT_MAX ? INT_MAX : (int)f;\n}',
417
+ ],
418
+ [
419
+ 'app_ceildiv',
420
+ '/* Math.ceil(a / b) for two ints, exactly, with the zero divisor and INT_MIN / -1 as ' +
421
+ 'app_floordiv has them. */\n' +
422
+ 'static int app_ceildiv(int a, int b)\n{\n' +
423
+ ' if (b == 0)\n {\n return a > 0 ? INT_MAX : a < 0 ? INT_MIN : 0;\n }\n' +
424
+ ' const int64_t q = (int64_t)a / b;\n' +
425
+ ' const int64_t c = ((int64_t)a % b != 0 && (a < 0) == (b < 0)) ? q + 1 : q;\n' +
426
+ ' return c > INT_MAX ? INT_MAX : (int)c;\n}',
427
+ ],
428
+ [
429
+ 'app_rounddiv',
430
+ '/* Math.round(a / b) for two ints, exactly: floor(a / b + 1/2), halves up as JS rounds, which is\n' +
431
+ ' floor((2a + b) / 2b) once b is made positive. The zero divisor and the range go as in app_floordiv. */\n' +
432
+ 'static int app_rounddiv(int a, int b)\n{\n' +
433
+ ' if (b == 0)\n {\n return a > 0 ? INT_MAX : a < 0 ? INT_MIN : 0;\n }\n' +
434
+ ' const int64_t n = b < 0 ? -(int64_t)a : a;\n' +
435
+ ' const int64_t d = b < 0 ? -(int64_t)b : b;\n' +
436
+ ' const int64_t num = 2 * n + d, den = 2 * d;\n' +
437
+ ' const int64_t q = num / den;\n' +
438
+ ' const int64_t r = (num % den != 0 && num < 0) ? q - 1 : q;\n' +
439
+ ' return r > INT_MAX ? INT_MAX : r < INT_MIN ? INT_MIN : (int)r;\n}',
440
+ ],
441
+ [
442
+ 'app_f2i',
443
+ '/* A float kept as an int: truncated toward zero like a C cast, but saturated at the int range and NaN as\n' +
444
+ ' 0, where the cast would be undefined behavior. */\n' +
445
+ 'static int app_f2i(float v)\n{\n' +
446
+ ' if (v != v)\n {\n return 0;\n }\n' +
447
+ ' if (v >= 2147483648.0f)\n {\n return INT_MAX;\n }\n' +
448
+ ' if (v <= -2147483648.0f)\n {\n return INT_MIN;\n }\n' +
449
+ ' return (int)v;\n}',
450
+ ],
451
+ [
452
+ 'app_roundf',
453
+ "/* Math.round as JS rounds: to the nearest whole number, halves up (toward +Infinity). C's roundf takes\n" +
454
+ ' halves away from zero, which gives -3 for -2.5 where JS gives -2. */\n' +
455
+ 'static float app_roundf(float v)\n{\n' +
456
+ ' const float f = floorf(v);\n return v - f >= 0.5f ? f + 1.0f : f;\n}',
457
+ ],
458
+ [
459
+ 'app_ftoa',
460
+ "/* A float as JS's String() spells it where %g does not: Infinity, -Infinity and NaN for what %g prints as\n" +
461
+ ' inf, -inf and nan, and 0 for negative zero, which %g prints as -0. Anything else is %g, into `buf`,\n' +
462
+ ' which the caller lends (16 chars, room for any float). All ASCII, which every font bakes. */\n' +
463
+ 'static const char* app_ftoa(char* buf, float v)\n{\n' +
464
+ ' if (v != v)\n {\n return "NaN";\n }\n' +
465
+ ' if (isinf(v))\n {\n return v > 0.0f ? "Infinity" : "-Infinity";\n }\n' +
466
+ ' if (v == 0.0f)\n {\n return "0";\n }\n' +
467
+ ' snprintf(buf, 16, "%g", (double)v);\n return buf;\n}',
468
+ ],
469
+ [
470
+ 'app_opacity',
471
+ "/* A state-driven opacity as the engine's 0-255 byte: clamped to 0..1 and rounded, as Flow A's bridge and\n" +
472
+ ' the compile-time fold do, with NaN as 0. */\n' +
473
+ 'static uint8_t app_opacity(float v)\n{\n' +
474
+ ' if (!(v > 0.0f))\n {\n return 0;\n }\n' +
475
+ ' if (v >= 1.0f)\n {\n return 255;\n }\n' +
476
+ ' return (uint8_t)(v * 255.0f + 0.5f);\n}',
477
+ ],
478
+ [
479
+ 'app_add64',
480
+ '/* a + b, saturated to the int64 range: C leaves a signed overflow undefined. */\n' +
481
+ 'static int64_t app_add64(int64_t a, int64_t b)\n{\n' +
482
+ ' if (b > 0 ? a > INT64_MAX - b : a < INT64_MIN - b)\n {\n' +
483
+ ' return b > 0 ? INT64_MAX : INT64_MIN;\n }\n return a + b;\n}',
484
+ ],
485
+ [
486
+ 'app_sub64',
487
+ '/* a - b, saturated to the int64 range: C leaves a signed overflow undefined. */\n' +
488
+ 'static int64_t app_sub64(int64_t a, int64_t b)\n{\n' +
489
+ ' if (b < 0 ? a > INT64_MAX + b : a < INT64_MIN + b)\n {\n' +
490
+ ' return b < 0 ? INT64_MAX : INT64_MIN;\n }\n return a - b;\n}',
491
+ ],
492
+ [
493
+ 'app_mul64',
494
+ '/* a * b, saturated to the int64 range: C leaves a signed overflow undefined. GCC and Clang test for\n' +
495
+ ' the overflow with a builtin; anywhere else (MSVC) the limits are checked by division first. */\n' +
496
+ 'static int64_t app_mul64(int64_t a, int64_t b)\n{\n' +
497
+ '#if defined(__clang__) || (defined(__GNUC__) && __GNUC__ >= 5)\n' +
498
+ ' int64_t v;\n if (!__builtin_mul_overflow(a, b, &v))\n {\n return v;\n }\n' +
499
+ '#else\n' +
500
+ ' if (a == 0 || b == 0 ||\n' +
501
+ ' (a > 0 ? (b > 0 ? a <= INT64_MAX / b : b >= INT64_MIN / a)\n' +
502
+ ' : (b > 0 ? a >= INT64_MIN / b : a >= INT64_MAX / b)))\n {\n' +
503
+ ' return a * b;\n }\n' +
504
+ '#endif\n' +
505
+ ' return (a < 0) == (b < 0) ? INT64_MAX : INT64_MIN;\n}',
506
+ ],
507
+ [
508
+ 'app_neg64',
509
+ '/* -a, saturated: -INT64_MIN does not fit an int64_t. */\n' +
510
+ 'static int64_t app_neg64(int64_t a)\n{\n return a == INT64_MIN ? INT64_MAX : -a;\n}',
511
+ ],
512
+ [
513
+ 'app_floordiv64',
514
+ "/* Math.floor(a / b) in whole numbers: C's `/` rounds toward zero where floor rounds down. JS gives\n" +
515
+ ' +-Infinity for b == 0, which saturates by the sign of a (0 / 0 is NaN, which is 0), and INT64_MIN / -1\n' +
516
+ ' is past the range, so it saturates too. */\n' +
517
+ 'static int64_t app_floordiv64(int64_t a, int64_t b)\n{\n' +
518
+ ' if (b == 0)\n {\n return a > 0 ? INT64_MAX : a < 0 ? INT64_MIN : 0;\n }\n' +
519
+ ' if (b == -1)\n {\n return a == INT64_MIN ? INT64_MAX : -a;\n }\n' +
520
+ ' const int64_t q = a / b;\n return (a % b != 0 && (a < 0) != (b < 0)) ? q - 1 : q;\n}',
521
+ ],
522
+ [
523
+ 'app_ceildiv64',
524
+ '/* Math.ceil(a / b) in whole numbers, with the zero divisor and INT64_MIN / -1 as ' +
525
+ 'app_floordiv64 has them. */\n' +
526
+ 'static int64_t app_ceildiv64(int64_t a, int64_t b)\n{\n' +
527
+ ' if (b == 0)\n {\n return a > 0 ? INT64_MAX : a < 0 ? INT64_MIN : 0;\n }\n' +
528
+ ' if (b == -1)\n {\n return a == INT64_MIN ? INT64_MAX : -a;\n }\n' +
529
+ ' const int64_t q = a / b;\n return (a % b != 0 && (a < 0) == (b < 0)) ? q + 1 : q;\n}',
530
+ ],
531
+ [
532
+ 'app_rounddiv64',
533
+ '/* Math.round(a / b) in whole numbers, halves up as JS rounds: floor(a / b), plus ' +
534
+ 'one when what is left is at\n' +
535
+ ' least half of b. Nothing is doubled, which could overflow; the zero divisor and INT64_MIN / -1 go as in\n' +
536
+ ' app_floordiv64. */\n' +
537
+ 'static int64_t app_rounddiv64(int64_t a, int64_t b)\n{\n' +
538
+ ' if (b == 0)\n {\n return a > 0 ? INT64_MAX : a < 0 ? INT64_MIN : 0;\n }\n' +
539
+ ' if (b == -1)\n {\n return a == INT64_MIN ? INT64_MAX : -a;\n }\n' +
540
+ ' int64_t q = a / b;\n int64_t r = a % b;\n' +
541
+ ' if (r != 0 && (r < 0) != (b < 0))\n {\n q -= 1;\n r += b;\n }\n' +
542
+ ' return (b > 0 ? r >= b - r : r <= b - r) ? q + 1 : q;\n}',
543
+ ],
544
+ [
545
+ 'app_div64',
546
+ '/* Math.trunc(a / b) in whole numbers, with the zero divisor and INT64_MIN / -1 as ' +
547
+ 'app_floordiv64 has them. */\n' +
548
+ 'static int64_t app_div64(int64_t a, int64_t b)\n{\n' +
549
+ ' if (b == 0)\n {\n return a > 0 ? INT64_MAX : a < 0 ? INT64_MIN : 0;\n }\n' +
550
+ ' if (b == -1)\n {\n return a == INT64_MIN ? INT64_MAX : -a;\n }\n' +
551
+ ' return a / b;\n}',
552
+ ],
553
+ [
554
+ 'app_mod64',
555
+ "/* a % b in whole numbers, as JS computes it: the remainder has the dividend's sign, as in C. JS gives NaN\n" +
556
+ ' for b == 0, which is 0 here, and INT64_MIN % -1 is 0, where C would overflow. */\n' +
557
+ 'static int64_t app_mod64(int64_t a, int64_t b)\n{\n return (b == 0 || b == -1) ? 0 : a % b;\n}',
558
+ ],
559
+ [
560
+ 'app_abs64',
561
+ '/* |v|, saturated: -INT64_MIN does not fit an int64_t. */\n' +
562
+ 'static int64_t app_abs64(int64_t v)\n{\n return v >= 0 ? v : v == INT64_MIN ? INT64_MAX : -v;\n}',
563
+ ],
564
+ [
565
+ 'app_min64',
566
+ 'static int64_t app_min64(int64_t a, int64_t b)\n{\n return a < b ? a : b;\n}',
567
+ ],
568
+ [
569
+ 'app_max64',
570
+ 'static int64_t app_max64(int64_t a, int64_t b)\n{\n return a > b ? a : b;\n}',
571
+ ],
572
+ [
573
+ 'app_delay_ms64',
574
+ '/* A timer delay computed from a timestamp: ToInt32 (wrap to 32 bits), then a negative delay is 0 — the\n' +
575
+ " conversion Flow A's setTimeout applies. */\n" +
576
+ 'static int app_delay_ms64(int64_t v)\n{\n const uint32_t u = (uint32_t)v;\n ' +
577
+ 'return u > 0x7FFFFFFFu ? 0 : (int)u;\n}',
578
+ ],
579
+ [
580
+ 'app_delay_msf',
581
+ '/* A timer delay computed as a float, converted as app_delay_ms64 converts one: ToInt32 (NaN and +-Infinity\n' +
582
+ ' are 0), then a negative delay is 0. Past +-2^63 a float is a multiple of 2^32, ' +
583
+ 'which ToInt32 takes to 0. */\n' +
584
+ 'static int app_delay_msf(float v)\n{\n' +
585
+ ' if (!(v > -9223372036854775808.0f && v < 9223372036854775808.0f))\n {\n return 0;\n }\n' +
586
+ ' const uint32_t u = (uint32_t)(int64_t)v;\n return u > 0x7FFFFFFFu ? 0 : (int)u;\n}',
587
+ ],
588
+ [
589
+ 'app_slice_len',
590
+ '/* The length items.slice(0, end) leaves, as JS counts it: a negative end counts back from the length and\n' +
591
+ ' stops at 0, and an end past the length keeps every item. */\n' +
592
+ 'static int app_slice_len(int len, int end)\n{\n' +
593
+ ' if (end < 0)\n {\n return end <= -len ? 0 : len + end;\n }\n' +
594
+ ' return end < len ? end : len;\n}',
595
+ ],
596
+ [
597
+ 'app_vector_dirty',
598
+ "/* updateVector's damage hint from float math. A NaN or infinite edge (a 0/0 in app math) gives no hint,\n" +
599
+ " so the engine's own damage applies (what changed in the tape, or the whole node), where a zero-width\n" +
600
+ ' one would leave the new drawing unpainted. The rest is rounded out to whole pixels and its edges, not\n' +
601
+ ' its lengths, are bounded well inside the int range, so a rect reaching past the bound is not cut\n' +
602
+ " short; the engine clips the rect's corners from there. */\n" +
603
+ 'static void app_vector_dirty(ERNode* node, float x, float y, float w, float h)\n{\n' +
604
+ ' if (!(isfinite(x) && isfinite(y) && isfinite(w) && isfinite(h)))\n {\n return;\n }\n' +
605
+ ' const float e[4] = {floorf(x), floorf(y), ceilf(x + w), ceilf(y + h)};\n int c[4];\n' +
606
+ ' for (int k = 0; k < 4; k++)\n {\n' +
607
+ ' c[k] = (int)(e[k] < -1e9f ? -1e9f : (e[k] > 1e9f ? 1e9f : e[k]));\n }\n' +
608
+ ' er_node_set_vector_dirty_rect(node, c[0], c[1], c[2] - c[0], c[3] - c[1]);\n}',
609
+ ],
610
+ ];
611
+ // Generated code with literals and comments blanked, so only a real call emits a helper (unused statics warn).
612
+ const helperCallers = stripCLiterals([
613
+ stateBlock,
614
+ refDecls,
615
+ vectorBuilderBlock,
616
+ updateBlock,
617
+ handlerDefs,
618
+ queryDefs,
619
+ effectFnDefs,
620
+ animCbDefs,
621
+ timerFnDefs,
622
+ mountEffects,
623
+ buildLines,
624
+ ].join('\n'));
625
+ // The clock state, then each helper the generated code calls.
626
+ const clockBlock = [
627
+ '/* Date.now() is the engine clock plus this offset, so it reads as uptime until the host calls\n' +
628
+ ' er_app_set_wall_clock(). performance.now() is the engine clock alone. */\n' +
629
+ 'static int64_t s_wall_offset_ms;' +
630
+ (hasUpdate
631
+ ? '\n/* Set by er_app_set_wall_clock(); the next er_app_tick() re-applies what reads the clock. */\n' +
632
+ 'static int s_wall_clock_changed;'
633
+ : ''),
634
+ ...APP_HELPERS.filter(([name]) => helperCallers.includes(`${name}(`)).map(([, definition]) => definition),
635
+ ].join('\n\n');
636
+ // <limits.h> when a helper saturates at INT_MAX / INT_MIN.
637
+ const usesLimits = /\bINT_M(?:AX|IN)\b/.test(clockBlock);
638
+ // Animation completion waits: their table, and the helpers the generated code calls.
639
+ const animWaitBlock = usesWaits ? printWaitDeclarations(helperCallers) : '';
640
+ // Emit er_timer_clear only when called; a clearInterval in a dropped mount-effect cleanup leaves no caller.
641
+ const timerClearBlock = out.usesTimers && helperCallers.includes('er_timer_clear(')
642
+ ? `static void er_timer_clear(int id)
643
+ {
644
+ if (id < 0)
645
+ {
646
+ return;
647
+ }
648
+ int i = id % ER_AOT_MAX_TIMERS;
649
+ if (s_timers[i].active && s_timers[i].gen == id / ER_AOT_MAX_TIMERS)
650
+ {
651
+ s_timers[i].active = false;
652
+ }
653
+ }`
654
+ : '';
655
+ // The longer pieces of app.gen.c, named here so the template below stays readable.
656
+ const versionMismatch = `embedded-react version mismatch: app.gen.c was generated by ${PKG_VERSION} but the engine header ` +
657
+ `(er_version.h) is a different major.minor. Regenerate the app with 'npm run aot', or align the engine ` +
658
+ `and npm versions.`;
659
+ const mathInclude = usesMath
660
+ ? '#include <math.h>\n' +
661
+ '/* M_PI is not in ISO C99 <math.h> (only POSIX/GNU); define a fallback so the generated app compiles ' +
662
+ 'under -std=c99 / MSVC. */\n' +
663
+ '#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n'
664
+ : '';
665
+ const limitsInclude = usesLimits ? '#include <limits.h>\n' : '';
666
+ // A blank line sets off each non-empty block before and after.
667
+ const spaced = (block) => (block ? '\n' + block + '\n' : '');
668
+ const keyboard = app.keyboard ? printKeyboard(app.keyboard) : null;
669
+ const declarations = [
670
+ refDecls,
671
+ panDeclBlock,
672
+ effectDeclsBlock,
673
+ vectorBlock,
674
+ vectorBuilderBlock,
675
+ animDecls,
676
+ handleDecls,
677
+ timerTableBlock,
678
+ timerClearBlock,
679
+ animWaitBlock,
680
+ effectFwdDecls,
681
+ updateBlock,
682
+ timerFnFwdDecls,
683
+ animCbDecls,
684
+ handlerDefs,
685
+ queryDefs,
686
+ effectFnDefs,
687
+ animCbDefs,
688
+ timerFnDefs,
689
+ keyboard?.data ?? '',
690
+ ]
691
+ .map(spaced)
692
+ .join('');
693
+ const keyboardSetup = keyboard
694
+ ? keyboard.setup +
695
+ ' /* app-supplied on-screen keyboard layout/appearance */\n'
696
+ : '';
697
+ const initialUpdate = hasUpdate
698
+ ? '\n app_update(); /* apply initial state-dependent props */\n'
699
+ : '';
700
+ // app.gen.c: includes and version pin, then file-scope state, declarations and functions, then er_app_build().
701
+ const body = `/*
702
+ * Generated by the embedded-react Flow B AOT compiler (npm run aot -- ${demo}). DO NOT EDIT.
703
+ * Builds the app's scene graph + state machine directly against er_scene.h — no QuickJS, no JS runtime.
704
+ */
705
+ #include "app.gen.h"
706
+
707
+ #include "er_scene.h"
708
+ #include "er_version.h"
709
+
710
+ #include <stdio.h>
711
+ #include <string.h>
712
+
713
+ /* Every string this file writes goes into a FIXED-SIZE slot (a state buffer, ERProps.text), so an
714
+ over-long value is truncated by design — the app cannot grow the buffer the way JS grows a string.
715
+ GCC's -Wformat-truncation reports exactly that intent for any format combining %s with anything else,
716
+ and ESP-IDF compiles with -Werror, so leaving it on would fail the build for ordinary text like
717
+ {'n=' + name}. Clang does not implement the warning; the guard keeps its "unknown warning group"
718
+ diagnostic from firing there. */
719
+ #if defined(__GNUC__) && !defined(__clang__)
720
+ #pragma GCC diagnostic ignored "-Wformat-truncation"
721
+ #endif
722
+
723
+ /* Version-pin: this file was generated by embedded-react ${PKG_VERSION}. The engine ships LOCKSTEP, so its
724
+ headers must be the same major.minor — otherwise these generated er_scene.h calls may not match the ABI.
725
+ A mismatch fails HERE at compile time (not on-device). Regenerate the app (npm run aot) or align versions. */
726
+ _Static_assert(ER_VERSION_MAJOR == ${PKG_MAJOR} && ER_VERSION_MINOR == ${PKG_MINOR},
727
+ "${versionMismatch}");
728
+ ${mathInclude}${limitsInclude}${dimRoundBlock}\n${clockBlock}\n${stateBlock ? '\n' + stateBlock : ''}${declarations}
729
+ ${appTickFn}
730
+
731
+ void er_app_set_wall_clock(int64_t epoch_ms)
732
+ {
733
+ s_wall_offset_ms = epoch_ms - (int64_t)er_now_ms64();${hasUpdate ? '\n s_wall_clock_changed = 1;' : ''}
734
+ }
735
+ ${hostSettersBlock ? '\n' + hostSettersBlock + '\n' : ''}
736
+ void er_app_build(int screen_w, int screen_h)
737
+ {
738
+ ERProps p;
739
+ ERNode* ${nodeDecls.join(';\n ERNode* ')};
740
+
741
+ /* A screen-sized root the app tree fills (mirrors AppRegistry mounting into a screen-sized host). */
742
+ ERNode* root = er_node_create(ER_NODE_VIEW);
743
+ er_props_default(&p);
744
+ p.width = (int16_t)screen_w;
745
+ p.height = (int16_t)screen_h;
746
+ er_node_set_props(root, &p);
747
+ ${animCreate ? '\n' + animCreate + '\n' : ''}
748
+ ${buildLines}
749
+ er_tree_append_child(root, ${app.root.id});
750
+ er_tree_set_root(root);
751
+ ${keyboardSetup}${initialUpdate}${mountEffectsBlock}}
752
+ `;
753
+ // app.gen.h: what the file was generated for, and the app's public entry points.
754
+ const header = `/* Generated by the embedded-react Flow B AOT compiler. DO NOT EDIT. */
755
+ #ifndef ER_APP_GEN_H
756
+ #define ER_APP_GEN_H
757
+
758
+ #include <stdint.h>
759
+
760
+ /*
761
+ * What this file was generated FOR. er_app_build() takes the screen size at runtime, but a responsive app
762
+ * folds its \`screen.width\`/\`screen.height\` branching at GENERATE time — so the layout in here is already
763
+ * committed to these dimensions and no runtime argument can change it.
764
+ *
765
+ * Every board example consumes the same dist/app.gen.c, so generating for one board and then building
766
+ * another produces firmware that compiles, links, boots, and lays out wrong. Boards \`_Static_assert\` these
767
+ * against their own panel size to turn that into a compile error; see each board example's main.c.
768
+ *
769
+ * WHICH demo is recorded the same way, as a marker macro named ER_AOT_DEMO_<demo> with every character
770
+ * outside [A-Za-z0-9] encoded as _<hex>_ (so \`watch-face\` defines ER_AOT_DEMO_watch_2d_face). The encoding
771
+ * is one-to-one, so no two app names can ever share a marker. A board that
772
+ * needs a particular demo's useHostValue setters guards on \`#ifndef\` of its own marker, which names the
773
+ * mismatch instead of leaving a pile of implicit-declaration errors for those setters.
774
+ */
775
+ #define ER_AOT_SCREEN_W ${opts.screen.width}
776
+ #define ER_AOT_SCREEN_H ${opts.screen.height}
777
+ #define ER_AOT_DEMO ${cstr(demo)}
778
+ #define ${demoMarker(demo)} 1
779
+
780
+ /** @brief Builds the AOT-compiled app's scene graph + state machine (call once after backend init). */
781
+ void er_app_build(int screen_w, int screen_h);
782
+
783
+ /** @brief Advances app timers (setInterval/setTimeout). Call once per frame with the elapsed ms; a no-op
784
+ * for apps that use no timers, so it is always safe to call. */
785
+ void er_app_tick(int dt_ms);
786
+
787
+ /** @brief Tells the app the current time, which Date.now() counts on from. Until it is called Date.now()
788
+ * reads as uptime; a later call re-anchors it, the next er_app_tick() re-applies what reads the
789
+ * clock, and performance.now() never moves with it. Call it from the loop that calls
790
+ * er_app_tick(), before or after er_app_build(); safe whether or not the app reads the clock.
791
+ * @param[in] epoch_ms Current time, in milliseconds since the Unix epoch. */
792
+ void er_app_set_wall_clock(int64_t epoch_ms);
793
+ ${hostSetterProtos ? '\n' + hostSetterProtos + '\n' : ''}
794
+ #endif
795
+ `;
796
+ // The image imports the app references; the CLI resolves each path against the demo dir and bakes them.
797
+ return {
798
+ c: body,
799
+ h: header,
800
+ nodes: out.nodeCount,
801
+ state: stateRecords.length,
802
+ handlers: handlers.length,
803
+ updates: updates.length,
804
+ images: app.images,
805
+ };
806
+ }