@geastack/geatsc-plugin-gea 0.1.6

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 (63) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +37 -0
  3. package/dist/analyze.d.ts +4 -0
  4. package/dist/analyze.js +195 -0
  5. package/dist/cpp-canvas-colors.d.ts +4 -0
  6. package/dist/cpp-canvas-colors.js +226 -0
  7. package/dist/cpp-field-access.d.ts +49 -0
  8. package/dist/cpp-field-access.js +144 -0
  9. package/dist/cpp-ir-dom-style.d.ts +1 -0
  10. package/dist/cpp-ir-dom-style.js +49 -0
  11. package/dist/cpp-ir.d.ts +30 -0
  12. package/dist/cpp-ir.js +2426 -0
  13. package/dist/cpp-keyed-component-diagnostics.d.ts +8 -0
  14. package/dist/cpp-keyed-component-diagnostics.js +74 -0
  15. package/dist/cpp-keyed-list-diagnostics.d.ts +17 -0
  16. package/dist/cpp-keyed-list-diagnostics.js +84 -0
  17. package/dist/cpp-mounted-lowering.d.ts +81 -0
  18. package/dist/cpp-mounted-lowering.js +2235 -0
  19. package/dist/cpp-mounted.d.ts +25 -0
  20. package/dist/cpp-mounted.js +1376 -0
  21. package/dist/cpp-reactive-component-diagnostics.d.ts +2 -0
  22. package/dist/cpp-reactive-component-diagnostics.js +76 -0
  23. package/dist/cpp-reactive-component.d.ts +14 -0
  24. package/dist/cpp-reactive-component.js +349 -0
  25. package/dist/cpp-replacements.d.ts +14 -0
  26. package/dist/cpp-replacements.js +787 -0
  27. package/dist/cpp-source-replacements.d.ts +11 -0
  28. package/dist/cpp-source-replacements.js +257 -0
  29. package/dist/cpp-store-hub.d.ts +7 -0
  30. package/dist/cpp-store-hub.js +160 -0
  31. package/dist/cpp-store-method-body-parser.d.ts +2 -0
  32. package/dist/cpp-store-method-body-parser.js +392 -0
  33. package/dist/cpp-store-method-context.d.ts +48 -0
  34. package/dist/cpp-store-method-context.js +114 -0
  35. package/dist/cpp-store-method-expressions.d.ts +12 -0
  36. package/dist/cpp-store-method-expressions.js +1263 -0
  37. package/dist/cpp-store-method-replacements.d.ts +5 -0
  38. package/dist/cpp-store-method-replacements.js +1521 -0
  39. package/dist/cpp-store-method-targets.d.ts +19 -0
  40. package/dist/cpp-store-method-targets.js +296 -0
  41. package/dist/cpp-store-typed-arrays.d.ts +2 -0
  42. package/dist/cpp-store-typed-arrays.js +655 -0
  43. package/dist/cpp-stores.d.ts +73 -0
  44. package/dist/cpp-stores.js +1739 -0
  45. package/dist/cpp-template-renderer.d.ts +23 -0
  46. package/dist/cpp-template-renderer.js +3530 -0
  47. package/dist/css-style-declaration-shims.d.ts +3 -0
  48. package/dist/css-style-declaration-shims.js +47 -0
  49. package/dist/host-declarations.d.ts +11 -0
  50. package/dist/host-declarations.js +320 -0
  51. package/dist/host-shims.d.ts +3 -0
  52. package/dist/host-shims.js +3217 -0
  53. package/dist/index.d.ts +3 -0
  54. package/dist/index.js +1239 -0
  55. package/dist/load-ir.d.ts +7 -0
  56. package/dist/load-ir.js +40 -0
  57. package/dist/types.d.ts +604 -0
  58. package/dist/types.js +1 -0
  59. package/dist/utils.d.ts +26 -0
  60. package/dist/utils.js +723 -0
  61. package/dist/validate.d.ts +3 -0
  62. package/dist/validate.js +226 -0
  63. package/package.json +57 -0
package/dist/index.js ADDED
@@ -0,0 +1,1239 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
3
+ import { analyzeSourceHostBindings, capabilitiesToAnalyzePatch, mergeAnalyzePatches } from './analyze.js';
4
+ import { generateCppIrAssetForwardDeclarations, generateCppIrMountedSource, generateCppIrNamespaceSource, generateCppIrSource, irUsesCanvas, collectIrConstants, } from './cpp-ir.js';
5
+ import { attachTypedStorageMetadata, enrichConstantInitializerShapes, enrichNamedArrayShapesFromSource, enrichNamedArrayShapesFromTypeSources, reconcileInterfaceStructReuse, storeInstanceGlobalName, synthesizeReactiveComponentStores, } from './cpp-stores.js';
6
+ import { inlineOnlyComponentClassesForIr, rendererReplacementsForIr } from './cpp-replacements.js';
7
+ import { inlineReactiveComponentGetters, insertReactiveRendererForwardDeclarations, insertReactiveSignalSupport, neutralizeReactiveComponentToValue, rewriteReactiveComponentFields, } from './cpp-reactive-component.js';
8
+ import { decideStoreHubEmission, injectStoreSignalHub } from './cpp-store-hub.js';
9
+ import { createGeaHostShims } from './host-shims.js';
10
+ import { loadIr } from './load-ir.js';
11
+ import { sanitizeCppIdentifier } from './utils.js';
12
+ import { validateIr } from './validate.js';
13
+ import { diagnoseNonReactiveLists } from './cpp-keyed-list-diagnostics.js';
14
+ import { diagnoseBoxedKeyedComponentProps } from './cpp-keyed-component-diagnostics.js';
15
+ import { diagnoseUnmountableReactiveComponents } from './cpp-reactive-component-diagnostics.js';
16
+ import { replaceStoreMethodsFromIr, topLevelValueAccessorNamesFromSource } from './cpp-store-method-replacements.js';
17
+ import { applyTypedArrayStorage } from './cpp-store-typed-arrays.js';
18
+ import { foldCanvasColorLiteralsInCpp } from './cpp-canvas-colors.js';
19
+ import { bridgeGeneratedComponentRenderers, replaceOutOfLineGeneratedRenderers } from './cpp-source-replacements.js';
20
+ export function geatscPlugin() {
21
+ let ir = null;
22
+ let irPath = null;
23
+ let loadError = null;
24
+ let entryPath = null;
25
+ return {
26
+ name: 'gea',
27
+ configure(context) {
28
+ entryPath = context.entry;
29
+ const loaded = loadIr(context.options, context.entry);
30
+ ir = loaded.ir;
31
+ irPath = loaded.path;
32
+ loadError = loaded.error;
33
+ // EXPERIMENTAL (ReactiveComponent): a ReactiveComponent IS its own store —
34
+ // synthesize a `selfStore` GeaIrStore from its reactive state so the ONE
35
+ // mounted renderer resolves `this.field` / `this.method()` through the
36
+ // ordinary store machinery; the selfStore flag swaps the leaves to typed
37
+ // (`store->field.get()` readers, per-field Signal subscribe) and keeps the
38
+ // dynamic store-method re-lowering away from the typed class.
39
+ if (ir)
40
+ ir.stores.push(...synthesizeReactiveComponentStores(ir.components));
41
+ // Inline simple getters into template slots (`{this.label}` → `{'n=' +
42
+ // this.count}`) so getter reads lower through the store-field path with
43
+ // the getter's underlying fields as reactive deps. Before any consumer
44
+ // reads the slots, so mountability gate, mount planner, and renderer all
45
+ // see the same inlined template.
46
+ if (ir)
47
+ ir.components = ir.components.map(inlineReactiveComponentGetters);
48
+ // Decide typed-storage metadata once, at IR-load time. Subsequent
49
+ // passes (typed-array rewrite, store-method body lowering, store
50
+ // declaration generation) read from `field.typedStorage` rather than
51
+ // re-running the array-of-object-of-primitives predicate.
52
+ if (ir) {
53
+ enrichNamedArrayShapesFromTypeSources(irSourceFiles(ir), ir.stores);
54
+ enrichConstantInitializerShapes(ir.stores, collectIrConstants(ir), irSourceFiles(ir));
55
+ attachTypedStorageMetadata(ir.stores);
56
+ }
57
+ return {
58
+ allowAny: true,
59
+ hostShims: createGeaHostShims(),
60
+ };
61
+ },
62
+ validate() {
63
+ if (loadError) {
64
+ return [
65
+ {
66
+ kind: 'unsupported',
67
+ code: 'gea-ir',
68
+ message: loadError,
69
+ },
70
+ ];
71
+ }
72
+ if (!ir) {
73
+ return [
74
+ {
75
+ kind: 'unsupported',
76
+ code: 'gea-ir',
77
+ message: 'geatsc gea plugin requires --plugin-option gea.ir=<path-to-gea-ir.json>',
78
+ },
79
+ ];
80
+ }
81
+ const diagnostics = validateIr(ir, irPath ?? '<inline>');
82
+ // Non-fatal: warn about `{x.map(...)}` lists whose source isn't a
83
+ // reactive array-of-objects store field (they silently render nothing on
84
+ // the embedded target).
85
+ diagnostics.push(...diagnoseNonReactiveLists(ir));
86
+ // Fatal: statically typed keyed-list items must not silently cross a
87
+ // child-component boundary through gea_cpp_value when the parent falls
88
+ // off the native renderer path.
89
+ diagnostics.push(...diagnoseBoxedKeyedComponentProps(ir));
90
+ // Fatal: a ReactiveComponent without a typed mounted renderer renders
91
+ // NOTHING at runtime (silent black screen) — fail the build instead.
92
+ diagnostics.push(...diagnoseUnmountableReactiveComponents(ir));
93
+ return diagnostics;
94
+ },
95
+ analyzeHostBindings(context) {
96
+ const loaded = ir ?? loadIr(context.options, context.entry).ir;
97
+ return mergeAnalyzePatches(loaded ? capabilitiesToAnalyzePatch(loaded.hostCapabilities) : {}, analyzeSourceHostBindings(context.entry));
98
+ },
99
+ createCppBackend() {
100
+ return {
101
+ transformGeneratedSources(sources, context) {
102
+ if (!ir)
103
+ return sources;
104
+ const moduleFirst = isModuleFirstCppOutput(sources);
105
+ let workingSources = sources;
106
+ let moduleFirstCompilerRuntimeHeader = null;
107
+ let moduleFirstRuntimeGlobalsHeader = null;
108
+ let moduleFirstNeedsGeaDocumentRuntime = false;
109
+ if (moduleFirst) {
110
+ const activeIr = ir;
111
+ const combinedSource = sources.map((source) => source.source).join('\n');
112
+ const topLevelValueNames = topLevelValueAccessorNamesFromSource(combinedSource);
113
+ moduleFirstCompilerRuntimeHeader = findModuleFirstCompilerRuntimeHeader(sources);
114
+ moduleFirstRuntimeGlobalsHeader = findModuleFirstRuntimeGlobalsHeader(sources) ?? moduleFirstCompilerRuntimeHeader;
115
+ decideStoreHubEmission(combinedSource, activeIr);
116
+ enrichNamedArrayShapesFromSource(combinedSource, activeIr.stores);
117
+ enrichNamedArrayShapesFromTypeSources(irSourceFiles(activeIr), activeIr.stores);
118
+ enrichConstantInitializerShapes(activeIr.stores, collectIrConstants(activeIr), irSourceFiles(activeIr));
119
+ attachTypedStorageMetadata(activeIr.stores);
120
+ reconcileInterfaceStructReuse(combinedSource, activeIr.stores);
121
+ const replacements = rendererReplacementsForIr(activeIr);
122
+ const componentsByClass = new Map(activeIr.components.map((component) => [sanitizeCppIdentifier(component.exportName), component]));
123
+ const removableClassNames = new Set(replacements
124
+ .filter((replacement) => {
125
+ if ((replacement.refFields ?? []).length > 0)
126
+ return false;
127
+ const component = componentsByClass.get(replacement.className);
128
+ if (component?.reactiveState)
129
+ return false;
130
+ return !component || !componentHasRuntimeLifecycle(component);
131
+ })
132
+ .map((replacement) => replacement.className));
133
+ const includeDomInterop = activeIr.hostCapabilities.includes('dom') ||
134
+ replacements.some((replacement) => !removableClassNames.has(replacement.className)) ||
135
+ irUsesCanvas(activeIr, context.modules);
136
+ moduleFirstNeedsGeaDocumentRuntime = needsGeaDocumentRuntime(activeIr, entryPath);
137
+ const typedStoreAccessorTypes = typedStoreAccessorTypesForIr(activeIr);
138
+ mergeTypedStoreAccessorTypes(typedStoreAccessorTypes, typedStoreAccessorTypesFromSource(combinedSource));
139
+ const supportSource = generateModuleFirstGeaIrHeader(activeIr, irPath, context, {
140
+ includeDomInterop,
141
+ includeGeaDocumentRuntime: moduleFirstNeedsGeaDocumentRuntime,
142
+ pluginOptions: context.options,
143
+ });
144
+ const typedGlobalAccessors = typedGlobalAccessorsFromAccessorTypes(typedStoreAccessorTypes);
145
+ const mountedRenderers = generateCppIrMountedSource(activeIr, typedGlobalAccessors);
146
+ const rendererSplit = mountedRenderers ? splitModuleFirstMountedRenderers(activeIr, mountedRenderers) : null;
147
+ const nativeBridgeFiles = new Set();
148
+ const nativeStubFiles = nativeReplacedModuleFiles(activeIr, rendererSplit, context.modules, nativeBridgeFiles);
149
+ const rendererReplacements = rendererReplacementsForIr(activeIr);
150
+ const replacementByClass = new Map(rendererReplacements.map((replacement) => [replacement.className, replacement]));
151
+ const componentClassesByModule = new Map();
152
+ for (const component of activeIr.components) {
153
+ const file = path.resolve(component.module);
154
+ const classes = componentClassesByModule.get(file);
155
+ const className = sanitizeCppIdentifier(component.exportName);
156
+ if (classes)
157
+ classes.push(className);
158
+ else
159
+ componentClassesByModule.set(file, [className]);
160
+ }
161
+ const sourceFileByHeader = invertMap(moduleHeaderFileBySourceFile(context.modules));
162
+ workingSources = [
163
+ ...appendMountedRenderersToModuleSources(stubNativeReplacedModuleSources(workingSources.map((source) => {
164
+ const transformed = transformModuleFirstGeneratedSource(source, activeIr, moduleFirstCompilerRuntimeHeader, moduleFirstRuntimeGlobalsHeader, context.options, topLevelValueNames);
165
+ // On the module-first split the class declaration lives in
166
+ // the module header while its method BODIES are emitted
167
+ // out-of-line in the sibling .cpp. Resolve that .cpp back to
168
+ // the same source module so the boxed template body it holds
169
+ // is rewritten too — the header alone carries only the
170
+ // declaration, so bridging just the header left the boxed
171
+ // renderer fully intact.
172
+ const isModuleCpp = source.fileName.endsWith('.cpp');
173
+ const sourceFile = sourceFileByHeader.get(source.fileName) ??
174
+ (isModuleCpp ? sourceFileByHeader.get(source.fileName.replace(/\.cpp$/, '.hpp')) : undefined);
175
+ if (!sourceFile || !nativeBridgeFiles.has(sourceFile) || !(source.fileName.endsWith('.hpp') || isModuleCpp)) {
176
+ return transformed;
177
+ }
178
+ const bridgeReplacements = (componentClassesByModule.get(sourceFile) ?? [])
179
+ .map((className) => replacementByClass.get(className))
180
+ .filter((replacement) => !!replacement);
181
+ if (bridgeReplacements.length === 0)
182
+ return transformed;
183
+ // The .cpp holds no class body, so the member-inserting
184
+ // bridge must not run there — only the out-of-line rewrite.
185
+ if (isModuleCpp) {
186
+ return {
187
+ ...transformed,
188
+ source: replaceOutOfLineGeneratedRenderers(transformed.source, bridgeReplacements),
189
+ };
190
+ }
191
+ return {
192
+ ...transformed,
193
+ source: bridgeGeneratedComponentRenderers(transformed.source, bridgeReplacements, rendererSplit?.headerSource ?? '', typedStoreAccessorTypes),
194
+ };
195
+ }), context.modules, nativeStubFiles, activeIr), context.modules, rendererSplit, typedGlobalAccessors).map((source) => removeNativeStubTemplateCacheResets(source, nativeStubFiles)),
196
+ {
197
+ fileName: 'modules/gea_ir.hpp',
198
+ source: includeRecordAliasTypeHeaders(appendRendererSharedSourceToGeaIrHeader(supportSource, rendererSplit?.headerSource ?? ''), sources),
199
+ },
200
+ ];
201
+ }
202
+ let externalizedDrainMicrotasks = false;
203
+ const nextSources = workingSources
204
+ .map((source) => {
205
+ if (source.fileName.endsWith('.hpp')) {
206
+ const drained = externalizeDrainMicrotasksDeclaration(source.source, microtasksNamespace(context.options));
207
+ if (drained !== source.source)
208
+ externalizedDrainMicrotasks = true;
209
+ const next = stripInlineFromHeaderFunctionPrototypes(drained);
210
+ return next === source.source ? source : { ...source, source: next };
211
+ }
212
+ return source;
213
+ });
214
+ const needsDrainMicrotasksRuntime = externalizedDrainMicrotasks &&
215
+ !nextSources.some((source) => source.fileName.endsWith('.cpp') && /\bvoid\s+drainMicrotasks\s*\(\s*\)\s*\{/.test(source.source));
216
+ return ensureModuleFirstPluginRuntimeSource(nextSources, {
217
+ includeGeaDocumentRuntime: moduleFirstNeedsGeaDocumentRuntime,
218
+ defineDrainMicrotasks: needsDrainMicrotasksRuntime,
219
+ microtasksNamespace: microtasksNamespace(context.options),
220
+ });
221
+ },
222
+ };
223
+ },
224
+ };
225
+ }
226
+ export default geatscPlugin;
227
+ function isModuleFirstCppOutput(sources) {
228
+ return (sources.some((source) => source.fileName === 'entry.cpp') &&
229
+ sources.some((source) => source.fileName === 'generated_support.hpp') &&
230
+ sources.some((source) => /^modules\/.+\.cpp$/.test(source.fileName)));
231
+ }
232
+ function includeModuleFirstGeaIrHeader(source) {
233
+ if (!/^modules\/.+\.(?:h|hpp)$/.test(source.fileName))
234
+ return source;
235
+ if (source.fileName.endsWith('.types.hpp'))
236
+ return source;
237
+ if (source.fileName === 'modules/gea_ir.hpp')
238
+ return source;
239
+ if (source.source.includes('#include "./gea_ir.hpp"'))
240
+ return source;
241
+ const includeLine = '#include "./gea_ir.hpp"';
242
+ return { ...source, source: insertModuleHeaderInclude(source.source, includeLine) };
243
+ }
244
+ function findModuleFirstCompilerRuntimeHeader(sources) {
245
+ const source = sources.find((candidate) => /^modules\/.+\.(?:h|hpp)$/.test(candidate.fileName) &&
246
+ /\bclass\s+Store\s*(?::[^{]+)?\{/.test(candidate.source));
247
+ return source?.fileName ?? null;
248
+ }
249
+ function findModuleFirstRuntimeGlobalsHeader(sources) {
250
+ const source = sources.find((candidate) => /^modules\/.+\.(?:h|hpp)$/.test(candidate.fileName) &&
251
+ /\b__gea_global_(?:xe|Se|Ce|we|Te|De|Oe|je|Me|Ne|Pe|Fe)\s*\(\s*\)/.test(candidate.source));
252
+ return source?.fileName ?? null;
253
+ }
254
+ function includeModuleFirstCompilerRuntimeHeader(source, compilerRuntimeHeader) {
255
+ if (!compilerRuntimeHeader)
256
+ return source;
257
+ if (!/^modules\/.+\.(?:h|hpp)$/.test(source.fileName))
258
+ return source;
259
+ if (source.fileName.endsWith('.types.hpp'))
260
+ return source;
261
+ if (source.fileName === compilerRuntimeHeader)
262
+ return source;
263
+ if (!/:\s*public\s+Store\b/.test(source.source))
264
+ return source;
265
+ const headerBase = compilerRuntimeHeader.slice(compilerRuntimeHeader.lastIndexOf('/') + 1);
266
+ const includeLine = `#include "./${headerBase}"`;
267
+ if (source.source.includes(includeLine))
268
+ return source;
269
+ return { ...source, source: insertModuleHeaderInclude(source.source, includeLine) };
270
+ }
271
+ function transformModuleFirstGeneratedSource(source, ir, compilerRuntimeHeader, runtimeGlobalsHeader, options, topLevelValueNames) {
272
+ let nextSource = includeModuleFirstGeaIrHeader(source);
273
+ nextSource = includeModuleFirstCompilerRuntimeHeader(nextSource, compilerRuntimeHeader);
274
+ if (!/\.(?:cpp|cxx|cc|h|hpp|hxx)$/.test(nextSource.fileName))
275
+ return nextSource;
276
+ if (nextSource.fileName === 'modules/gea_ir.hpp')
277
+ return nextSource;
278
+ if (nextSource.fileName.endsWith('.types.hpp'))
279
+ return nextSource;
280
+ let next = nextSource.source;
281
+ next = process.env.GEA_SKIP_STORE_RELOWER ? next : replaceStoreMethodsFromIr(next, ir, collectIrConstants(ir), topLevelValueNames);
282
+ next = applyTypedArrayStorage(next, ir);
283
+ next = foldCanvasColorLiteralsInCpp(next, { pixelPanelEndian: pixelPanelEndian(options) });
284
+ const beforeRuntimeGlobals = next;
285
+ next = replaceRuntimeGlobalAccessors(next);
286
+ next = replaceBundledCompilerRuntimeGlobalAccessors(next);
287
+ if (next !== beforeRuntimeGlobals && runtimeGlobalsHeader && nextSource.fileName !== runtimeGlobalsHeader) {
288
+ const headerBase = runtimeGlobalsHeader.slice(runtimeGlobalsHeader.lastIndexOf('/') + 1);
289
+ next = insertModuleHeaderInclude(next, `#include "./${headerBase}"`);
290
+ }
291
+ next = replaceComponentElAccessors(next);
292
+ next = rewriteModuleLocalTemplateBuilderCalls(next);
293
+ next = rewriteReactiveComponentFields(next, ir.components);
294
+ next = neutralizeReactiveComponentToValue(next, ir.components);
295
+ next = insertReactiveSignalSupport(next, ir.components);
296
+ next = insertReactiveRendererForwardDeclarations(next, ir.components);
297
+ next = stripExternalInlineFromMountedRenderers(next);
298
+ next = injectStoreSignalHub(next, ir);
299
+ return next === nextSource.source ? nextSource : { ...nextSource, source: next };
300
+ }
301
+ function generateModuleFirstGeaIrHeader(ir, irPath, context, options) {
302
+ const usesReactiveRuntime = ir.stores.length > 0;
303
+ return [
304
+ '#pragma once',
305
+ '#include "../generated_support.hpp"',
306
+ usesReactiveRuntime ? '#include "gea/reactive_runtime.h"' : '',
307
+ generateCppIrAssetForwardDeclarations(ir),
308
+ generateCppIrSource(ir, irPath, context.modules, microtasksNamespace(options.pluginOptions)),
309
+ options.includeGeaDocumentRuntime ? generateHostDocumentNodeValueDeclaration() : '',
310
+ cppPreludeSource(options.pluginOptions),
311
+ generateCppIrNamespaceSource(ir, context.modules, { includeDomInterop: options.includeDomInterop }),
312
+ ].filter(Boolean).join('\n');
313
+ }
314
+ function insertModuleHeaderInclude(source, includeLine) {
315
+ if (source.includes(includeLine))
316
+ return source;
317
+ const lines = source.split('\n');
318
+ let insertAt = 0;
319
+ while (insertAt < lines.length &&
320
+ (lines[insertAt].startsWith('#pragma ') || lines[insertAt].startsWith('#include ') || lines[insertAt].trim() === '')) {
321
+ insertAt++;
322
+ }
323
+ lines.splice(insertAt, 0, includeLine);
324
+ return lines.join('\n');
325
+ }
326
+ function stripExternalInlineFromMountedRenderers(source) {
327
+ return source.replace(/(^|\n)inline\s+(gea::embedded::ui::NodeHandle\s+mount_[A-Za-z_][A-Za-z0-9_]*\s*\()/g, '$1$2');
328
+ }
329
+ function stripInlineFromHeaderFunctionPrototypes(source) {
330
+ const lines = source.split('\n');
331
+ const out = [];
332
+ for (let i = 0; i < lines.length; i++) {
333
+ const line = lines[i];
334
+ if (!line.startsWith('inline ')) {
335
+ out.push(line);
336
+ continue;
337
+ }
338
+ // A line ending in `;` is a DECLARATION even when it contains `{` — a
339
+ // default argument like `= std::vector<gea_cpp_value>{}` embeds braces
340
+ // that must NOT be mistaken for a function body. Check `;` (declaration)
341
+ // BEFORE `{` (definition); the reverse order left `inline` on prototypes
342
+ // whose definition lives in the .cpp → undefined-inline link failures
343
+ // (three.js utils.js warn/error, defaulted `params` vectors).
344
+ const chunk = [line];
345
+ let sawDeclaration = /;\s*$/.test(line);
346
+ let sawDefinition = !sawDeclaration && line.includes('{');
347
+ let cursor = i;
348
+ while (!sawDefinition && !sawDeclaration && cursor + 1 < lines.length) {
349
+ cursor++;
350
+ chunk.push(lines[cursor]);
351
+ sawDeclaration = /;\s*$/.test(lines[cursor]);
352
+ sawDefinition = !sawDeclaration && lines[cursor].includes('{');
353
+ }
354
+ const joined = chunk.join(' ').replace(/^inline\s+/, '');
355
+ const isFunctionPrototype = sawDeclaration && !sawDefinition && /\(/.test(joined) && /\)\s*(?:const\s*)?(?:->[^;]*)?;\s*$/.test(joined);
356
+ if (isFunctionPrototype) {
357
+ out.push(line.replace(/^inline\s+/, ''));
358
+ for (let j = i + 1; j <= cursor; j++)
359
+ out.push(lines[j]);
360
+ i = cursor;
361
+ continue;
362
+ }
363
+ out.push(line);
364
+ }
365
+ return out.join('\n');
366
+ }
367
+ const MOUNTED_RENDERER_BEGIN_PREFIX = '// @geastack/geatsc-plugin-gea mounted renderer begin ';
368
+ const MOUNTED_RENDERER_END = '// @geastack/geatsc-plugin-gea mounted renderer end';
369
+ function splitModuleFirstMountedRenderers(ir, mountedRenderers) {
370
+ const componentById = new Map(ir.components.map((component) => [component.id, component]));
371
+ const lines = mountedRenderers.split('\n');
372
+ const firstSection = lines.findIndex((line) => line.startsWith(MOUNTED_RENDERER_BEGIN_PREFIX));
373
+ if (firstSection < 0) {
374
+ return {
375
+ headerSource: mountedRenderers.trimEnd(),
376
+ definitionsBySourceFile: new Map(),
377
+ sectionsBySourceFile: new Map(),
378
+ renderedComponentIds: new Set(),
379
+ };
380
+ }
381
+ const sharedLines = lines.slice(0, firstSection);
382
+ const sharedSplit = splitMountedRendererSharedPrelude(ir, sharedLines.join('\n'));
383
+ const sectionsBySourceFile = new Map();
384
+ const renderedComponentIds = new Set();
385
+ let index = firstSection;
386
+ while (index < lines.length) {
387
+ const begin = lines[index];
388
+ if (!begin.startsWith(MOUNTED_RENDERER_BEGIN_PREFIX)) {
389
+ index += 1;
390
+ continue;
391
+ }
392
+ let metadata = null;
393
+ try {
394
+ metadata = JSON.parse(begin.slice(MOUNTED_RENDERER_BEGIN_PREFIX.length));
395
+ }
396
+ catch {
397
+ metadata = null;
398
+ }
399
+ const end = lines.indexOf(MOUNTED_RENDERER_END, index + 1);
400
+ if (end < 0)
401
+ break;
402
+ const component = metadata?.id ? componentById.get(metadata.id) : null;
403
+ if (component) {
404
+ renderedComponentIds.add(component.id);
405
+ const sourceFile = path.resolve(component.module);
406
+ const section = stripExternalInlineFromMountedRenderers(lines.slice(index, end + 1).join('\n')).trimEnd();
407
+ if (section) {
408
+ const existing = sectionsBySourceFile.get(sourceFile);
409
+ if (existing)
410
+ existing.push(section);
411
+ else
412
+ sectionsBySourceFile.set(sourceFile, [section]);
413
+ }
414
+ }
415
+ index = end + 1;
416
+ }
417
+ return {
418
+ headerSource: sharedSplit.headerSource,
419
+ definitionsBySourceFile: sharedSplit.definitionsBySourceFile,
420
+ sectionsBySourceFile,
421
+ renderedComponentIds,
422
+ };
423
+ }
424
+ function splitMountedRendererSharedPrelude(ir, sharedSource) {
425
+ const lines = sharedSource.split('\n');
426
+ const namespaceIndex = lines.findIndex((line) => line.trim() === 'namespace gea_ir {');
427
+ if (namespaceIndex < 0) {
428
+ return { headerSource: sharedSource.trimEnd(), definitionsBySourceFile: new Map() };
429
+ }
430
+ const prefix = lines.slice(0, namespaceIndex);
431
+ const body = lines.slice(namespaceIndex + 1);
432
+ const storeModuleByClass = new Map(ir.stores.map((store) => [sanitizeCppIdentifier(store.className), path.resolve(store.module)]));
433
+ const readerForwardDecls = new Set();
434
+ const headerBody = [];
435
+ const definitionsBySourceFile = new Map();
436
+ for (let index = 0; index < body.length;) {
437
+ const line = body[index];
438
+ const readerMatch = /^inline\s+(.+\s+)(read_([A-Za-z_][A-Za-z0-9_]*)_field_[A-Za-z_][A-Za-z0-9_]*\s*\([^)]*\))\s*\{/.exec(line.trim());
439
+ if (!readerMatch) {
440
+ headerBody.push(line);
441
+ index += 1;
442
+ continue;
443
+ }
444
+ const sectionEnd = findCppFunctionSectionEnd(body, index);
445
+ const storeSourceFile = storeModuleByClass.get(readerMatch[3]);
446
+ if (storeSourceFile) {
447
+ const definition = body.slice(index, sectionEnd + 1).join('\n').replace(/^inline\s+/, '');
448
+ const existing = definitionsBySourceFile.get(storeSourceFile);
449
+ if (existing)
450
+ existing.push(definition);
451
+ else
452
+ definitionsBySourceFile.set(storeSourceFile, [definition]);
453
+ readerForwardDecls.add(`class ${readerMatch[3]};`);
454
+ headerBody.push(`${readerMatch[1]}${readerMatch[2]};`);
455
+ }
456
+ else {
457
+ headerBody.push(...body.slice(index, sectionEnd + 1));
458
+ }
459
+ index = sectionEnd + 1;
460
+ }
461
+ const forwardDecls = [...readerForwardDecls].filter((declaration) => !prefix.some((line) => line.trim() === declaration));
462
+ return {
463
+ headerSource: [...prefix, ...forwardDecls, 'namespace gea_ir {', ...headerBody, '} // namespace gea_ir'].join('\n').trimEnd(),
464
+ definitionsBySourceFile,
465
+ };
466
+ }
467
+ function findCppFunctionSectionEnd(lines, start) {
468
+ let depth = 0;
469
+ let opened = false;
470
+ for (let index = start; index < lines.length; index += 1) {
471
+ const line = lines[index];
472
+ for (const char of line) {
473
+ if (char === '{') {
474
+ depth += 1;
475
+ opened = true;
476
+ }
477
+ else if (char === '}') {
478
+ depth -= 1;
479
+ }
480
+ }
481
+ if (opened && depth <= 0)
482
+ return index;
483
+ }
484
+ return start;
485
+ }
486
+ function appendRendererSharedSourceToGeaIrHeader(headerSource, sharedSource) {
487
+ const shared = sharedSource.trim();
488
+ if (!shared)
489
+ return headerSource;
490
+ return `${headerSource.trimEnd()}\n\n${shared}\n`;
491
+ }
492
+ // Module-first output puts geatsc's record-alias structs (`__gea_type_<Name>`)
493
+ // in per-module `<module>.types.hpp` headers, while the shared gea_ir.hpp can
494
+ // carry INLINE typed-item helpers (`set_typed_field(::__gea_type_X&, …)`,
495
+ // `read_number_field(const ::__gea_type_X&, …)`) whose bodies need the
496
+ // COMPLETE struct. gea_ir.hpp is included by every module header FIRST, so it
497
+ // must pull in the types.hpp that defines each record struct it references.
498
+ // (Single-file output doesn't hit this: the helper block is injected after the
499
+ // `// @geatsc record-alias types end` anchor in the same source.) The types
500
+ // headers are self-contained (#pragma once + generated_support.hpp + other
501
+ // types headers) and never include gea_ir.hpp, so no include cycle.
502
+ function includeRecordAliasTypeHeaders(headerSource, sources) {
503
+ const referenced = new Set();
504
+ const referencePattern = /\b__gea_type_[A-Za-z0-9_]+\b/g;
505
+ let referenceMatch;
506
+ while ((referenceMatch = referencePattern.exec(headerSource)))
507
+ referenced.add(referenceMatch[0]);
508
+ if (referenced.size === 0)
509
+ return headerSource;
510
+ const includes = [];
511
+ for (const source of sources) {
512
+ if (!source.fileName.startsWith('modules/') || !source.fileName.endsWith('.types.hpp'))
513
+ continue;
514
+ for (const name of referenced) {
515
+ // Skip structs the shared header already defines itself (would #include
516
+ // a second definition past #pragma once of a DIFFERENT file → ODR break).
517
+ if (new RegExp(`\\bstruct\\s+${name}\\s*\\{`).test(headerSource))
518
+ continue;
519
+ if (new RegExp(`\\bstruct\\s+${name}\\s*\\{`).test(source.source)) {
520
+ includes.push(`#include "./${source.fileName.slice('modules/'.length)}"`);
521
+ break;
522
+ }
523
+ }
524
+ }
525
+ if (includes.length === 0)
526
+ return headerSource;
527
+ const anchor = '#include "../generated_support.hpp"';
528
+ const anchorIndex = headerSource.indexOf(anchor);
529
+ if (anchorIndex < 0)
530
+ return `${includes.join('\n')}\n${headerSource}`;
531
+ const lineEnd = headerSource.indexOf('\n', anchorIndex);
532
+ if (lineEnd < 0)
533
+ return `${headerSource}\n${includes.join('\n')}\n`;
534
+ return `${headerSource.slice(0, lineEnd + 1)}${includes.join('\n')}\n${headerSource.slice(lineEnd + 1)}`;
535
+ }
536
+ function appendMountedRenderersToModuleSources(sources, modules, rendererSplit, typedGlobalAccessors = new Map()) {
537
+ if (!rendererSplit || rendererSplit.sectionsBySourceFile.size === 0)
538
+ return sources;
539
+ const cppFileBySourceFile = moduleCppFileBySourceFile(modules);
540
+ // An IR component whose module is NOT part of the compile graph (IR built
541
+ // from a wider vite graph, or handed in directly) still needs its renderer
542
+ // DEFINED somewhere — dropping it leaves the gea_ir.hpp prototype dangling
543
+ // and every mount call unresolved. Fall back to the entry module's TU
544
+ // (last in dependency order), mirroring the single-file path that appended
545
+ // everything to program.cpp.
546
+ const entryCppFile = modules.length > 0 ? cppFileBySourceFile.get(path.resolve(modules[modules.length - 1].sourceFile.fileName)) : undefined;
547
+ const cppFileForSourceFile = (sourceFile) => cppFileBySourceFile.get(path.resolve(sourceFile)) ?? entryCppFile;
548
+ const sectionsByCppFile = new Map();
549
+ for (const [sourceFile, definitions] of rendererSplit.definitionsBySourceFile) {
550
+ const cppFile = cppFileForSourceFile(sourceFile);
551
+ if (!cppFile)
552
+ continue;
553
+ const block = `namespace gea_ir {\n\n${definitions.join('\n\n')}\n\n} // namespace gea_ir`;
554
+ const existing = sectionsByCppFile.get(cppFile);
555
+ if (existing)
556
+ existing.push(block);
557
+ else
558
+ sectionsByCppFile.set(cppFile, [block]);
559
+ }
560
+ for (const [sourceFile, sections] of rendererSplit.sectionsBySourceFile) {
561
+ const cppFile = cppFileForSourceFile(sourceFile);
562
+ if (!cppFile)
563
+ continue;
564
+ const existing = sectionsByCppFile.get(cppFile);
565
+ if (existing)
566
+ existing.push(`namespace gea_ir {\n\n${sections.join('\n\n')}\n\n} // namespace gea_ir`);
567
+ else
568
+ sectionsByCppFile.set(cppFile, [`namespace gea_ir {\n\n${sections.join('\n\n')}\n\n} // namespace gea_ir`]);
569
+ }
570
+ if (sectionsByCppFile.size === 0)
571
+ return sources;
572
+ return sources.map((source) => {
573
+ const sections = sectionsByCppFile.get(source.fileName);
574
+ if (!sections || sections.length === 0)
575
+ return source;
576
+ // The appended renderer can dereference typed globals (`__gea_global_x()->
577
+ // method()`) whose classes the HOST module never imported in TS (e.g. a
578
+ // controller singleton only used inside JSX event attributes geatsc
579
+ // stripped from the class). gea_ir.hpp only forward-declares those
580
+ // classes; member access needs the COMPLETE type, so include each
581
+ // defining module header here (cpp → hpp, no cycle; #pragma once dedupes).
582
+ const sectionsText = sections.join('\n');
583
+ const includes = [
584
+ ...accessorClassIncludesForSections(sectionsText, source, sources, typedGlobalAccessors),
585
+ ...globalValueIncludesForSections(sectionsText, source, sources),
586
+ ];
587
+ const body = [
588
+ ...(includes.length > 0 ? [includes.join('\n')] : []),
589
+ source.source.trimEnd(),
590
+ '',
591
+ // Same section anchor the single-TU emission used — tooling and tests
592
+ // locate the renderer definitions by this marker.
593
+ '// @geastack/geatsc-plugin-gea mounted renderers',
594
+ sections.join('\n\n'),
595
+ '',
596
+ ].join('\n');
597
+ return { ...source, source: body };
598
+ });
599
+ }
600
+ // The appended renderer can also read PLAIN VALUE globals defined by another
601
+ // module — not through an accessor, just by bare identifier. JSX style objects
602
+ // are the common case: button-tetris' Controls.tsx writes
603
+ // `style={{ left: LEFT_COL_LEFT, width: BUTTON_WIDTH }}`, where those are
604
+ // `double` globals owned by constants.tsx. geatsc strips those attributes out
605
+ // of the class body and we re-emit them here, so the host module's TS imports
606
+ // no longer explain the reference and no include is generated for it. The TU
607
+ // then fails with "'LEFT_COL_LEFT' was not declared in this scope".
608
+ //
609
+ // accessorClassIncludesForSections above covers only `__gea_global_X()`
610
+ // accessors whose type is `std::shared_ptr<Class>`; plain scalars never match
611
+ // it. Resolve them the same way: find the module layout header that DECLARES
612
+ // the identifier and include it. Layout headers are declaration-only and
613
+ // `#pragma once`, so this adds no definitions and cannot create a cycle.
614
+ function globalValueIncludesForSections(sectionsText, target, sources) {
615
+ const identifiers = new Set(sectionsText.match(/\b[A-Za-z_][A-Za-z0-9_]*\b/g) ?? []);
616
+ if (identifiers.size === 0)
617
+ return [];
618
+ // Include EVERY layout header that declares an identifier these sections read,
619
+ // not just the first one that supplies each name.
620
+ //
621
+ // A minimal-cover variant was tried and measured: it cut the fan-out from ~9
622
+ // extra headers per component .cpp (61 across one app) down to about one, but
623
+ // it BROKE compilation -- button-tetris then failed with "base operand of '->'
624
+ // has non-pointer type 'App'" in the framework's primitives header. The extra
625
+ // headers are load-bearing for how the emitter resolves class storage, not
626
+ // redundant duplicates, so the cheap-looking version is not safe.
627
+ //
628
+ // The cost is bounded by construction: these are .layout.hpp files, which the
629
+ // emitter guarantees never include a full module wrapper (it throws if one
630
+ // does). For button-tetris every layout header in the app totals ~119 KB, so
631
+ // this is nothing like the re-export-barrel pathology that once turned a
632
+ // 39-line file into a 35-minute compile by dragging in 36 façade headers.
633
+ const includes = [];
634
+ for (const candidate of sources) {
635
+ if (!/^modules\/.+\.layout\.hpp$/.test(candidate.fileName))
636
+ continue;
637
+ const includeLine = `#include "./${candidate.fileName.slice('modules/'.length)}"`;
638
+ if (target.source.includes(includeLine) || includes.includes(includeLine))
639
+ continue;
640
+ // `extern <type...> <name>;` -- the declaration form emitted for globals
641
+ // whose initializer runs at module init (window.innerWidth, Math.round...),
642
+ // which is exactly the set that cannot become a header constant.
643
+ const externPattern = /^\s*extern\s+[^;=]*?\b([A-Za-z_][A-Za-z0-9_]*)\s*;/gm;
644
+ let match;
645
+ while ((match = externPattern.exec(candidate.source))) {
646
+ if (!identifiers.has(match[1]))
647
+ continue;
648
+ includes.push(includeLine);
649
+ break;
650
+ }
651
+ }
652
+ return includes;
653
+ }
654
+ function accessorClassIncludesForSections(sectionsText, target, sources, typedGlobalAccessors) {
655
+ if (typedGlobalAccessors.size === 0)
656
+ return [];
657
+ const includes = [];
658
+ const seen = new Set();
659
+ const accessorPattern = /\b(__gea_global_[A-Za-z_][A-Za-z0-9_]*)\s*\(\s*\)/g;
660
+ let match;
661
+ while ((match = accessorPattern.exec(sectionsText))) {
662
+ if (seen.has(match[1]))
663
+ continue;
664
+ seen.add(match[1]);
665
+ const accessorType = typedGlobalAccessors.get(match[1]);
666
+ const payload = accessorType ? /^std::shared_ptr<([A-Za-z_][A-Za-z0-9_]*)>$/.exec(accessorType) : null;
667
+ if (!payload)
668
+ continue;
669
+ const definitionPattern = new RegExp(`\\bclass\\s+${payload[1]}\\s*(?::[^;{]*)?\\{`);
670
+ for (const candidate of sources) {
671
+ if (!/^modules\/.+\.hpp$/.test(candidate.fileName))
672
+ continue;
673
+ if (candidate.fileName.endsWith('.types.hpp') || candidate.fileName === 'modules/gea_ir.hpp')
674
+ continue;
675
+ if (!definitionPattern.test(candidate.source))
676
+ continue;
677
+ const includeLine = `#include "./${candidate.fileName.slice('modules/'.length)}"`;
678
+ if (!target.source.includes(includeLine) && !includes.includes(includeLine))
679
+ includes.push(includeLine);
680
+ break;
681
+ }
682
+ }
683
+ return includes;
684
+ }
685
+ function stubNativeReplacedModuleSources(sources, modules, stubSourceFiles, ir) {
686
+ if (stubSourceFiles.size === 0)
687
+ return sources;
688
+ const sourceFileByCpp = invertMap(moduleCppFileBySourceFile(modules));
689
+ const sourceFileByHeader = invertMap(moduleHeaderFileBySourceFile(modules));
690
+ const storeHeaderIncludes = storeModuleHeaderIncludes(ir, modules);
691
+ return sources.map((source) => {
692
+ const headerSourceFile = sourceFileByHeader.get(source.fileName);
693
+ if (headerSourceFile && stubSourceFiles.has(headerSourceFile)) {
694
+ return { ...source, source: nativeStubHeaderSource(source.fileName, storeHeaderIncludes) };
695
+ }
696
+ const cppSourceFile = sourceFileByCpp.get(source.fileName);
697
+ if (cppSourceFile && stubSourceFiles.has(cppSourceFile)) {
698
+ return { ...source, source: nativeStubCppSource(source.fileName, source.source) };
699
+ }
700
+ return source;
701
+ });
702
+ }
703
+ function nativeStubHeaderSource(fileName, storeHeaderIncludes) {
704
+ const typeHeader = fileName.replace(/\.hpp$/, '.types.hpp').slice(fileName.lastIndexOf('/') + 1);
705
+ return [
706
+ '#pragma once',
707
+ '#include "../generated_support.hpp"',
708
+ `#include "./${typeHeader}"`,
709
+ '#include "./gea_ir.hpp"',
710
+ ...storeHeaderIncludes,
711
+ '',
712
+ ].join('\n');
713
+ }
714
+ function nativeStubCppSource(fileName, originalSource) {
715
+ const header = fileName.replace(/\.cpp$/, '.hpp').slice(fileName.lastIndexOf('/') + 1);
716
+ const initMatch = /\bvoid\s+(__gea_module_\d{4})\s*\(/.exec(originalSource);
717
+ const initName = initMatch?.[1];
718
+ const initSource = initName ? nativeStubModuleInitSource(originalSource, initName) : null;
719
+ return [
720
+ `#include "./${header}"`,
721
+ '',
722
+ ...(initName ? [initSource ?? `void ${initName}() {}`, ''] : []),
723
+ ].join('\n');
724
+ }
725
+ function nativeStubModuleInitSource(originalSource, initName) {
726
+ const pattern = new RegExp(`\\bvoid\\s+${escapeRegExp(initName)}\\s*\\(\\s*\\)\\s*\\{`, 'm');
727
+ const match = pattern.exec(originalSource);
728
+ if (!match)
729
+ return null;
730
+ const open = originalSource.indexOf('{', match.index);
731
+ if (open < 0)
732
+ return null;
733
+ const close = findMatchingBrace(originalSource, open);
734
+ if (close < 0)
735
+ return null;
736
+ const source = originalSource.slice(match.index, close + 1);
737
+ return generatedMountFunctionCallPattern().test(source) ? source : null;
738
+ }
739
+ function removeNativeStubTemplateCacheResets(source, stubSourceFiles) {
740
+ if (stubSourceFiles.size === 0 || source.fileName !== 'entry.cpp')
741
+ return source;
742
+ const next = source.source.replace(/^\s*__gea_global__tpl\d+_root(?:__gm\d+)?\(\)\s*=\s*gea_cpp_key\(gea_cpp_value::null_v\(\)\);\n/gm, '');
743
+ return next === source.source ? source : { ...source, source: next };
744
+ }
745
+ function nativeReplacedModuleFiles(ir, rendererSplit, modules, bridgeFiles = new Set()) {
746
+ const componentFiles = nativeReplacedComponentModuleFiles(ir, rendererSplit, bridgeFiles);
747
+ const files = new Set(componentFiles);
748
+ if (canStubCompilerRuntimeModules(ir, componentFiles, rendererSplit)) {
749
+ for (const module of modules) {
750
+ const fileName = path.resolve(module.sourceFile.fileName);
751
+ if (isExternalCompilerRuntimeModule(fileName) || isExternalRuntimeSymbolsModule(fileName))
752
+ files.add(fileName);
753
+ }
754
+ }
755
+ return files;
756
+ }
757
+ function nativeReplacedComponentModuleFiles(ir, rendererSplit, bridgeFiles = new Set()) {
758
+ const componentById = new Map(ir.components.map((component) => [component.id, component]));
759
+ const inlineOnlyClasses = inlineOnlyComponentClassesForIr(ir);
760
+ const files = new Set();
761
+ for (const module of ir.modules) {
762
+ if (module.stores.length > 0 || module.components.length === 0)
763
+ continue;
764
+ const components = module.components.map((id) => componentById.get(id));
765
+ if (components.some((component) => !component))
766
+ continue;
767
+ if (components.some((component) => component?.reactiveState))
768
+ continue;
769
+ if (components.some((component) => component && componentHasRuntimeLifecycle(component)))
770
+ continue;
771
+ const file = path.resolve(module.file);
772
+ const allComponentsReplaced = components.every((component) => !!component &&
773
+ (rendererSplit?.renderedComponentIds.has(component.id) ||
774
+ inlineOnlyClasses.has(sanitizeCppIdentifier(component.exportName))));
775
+ // Stubbing is module-wide. One mounted renderer cannot justify deleting
776
+ // sibling generated classes which a compatibility parent may instantiate.
777
+ if (!allComponentsReplaced)
778
+ continue;
779
+ files.add(file);
780
+ }
781
+ // A component with runtime lifecycle (onAfterRender/dispose/created) is
782
+ // invoked through the generic render()/dispose() calling convention
783
+ // wherever it's mounted — same-file or cross-file, the compat transform
784
+ // emits that call shape unconditionally regardless of where the mounting
785
+ // JSX lives. The module-wide skip above (line ~783) correctly keeps such a
786
+ // component's OWN file out of full native replacement — a co-located
787
+ // sibling (e.g. the page's own ReaderScreen class) may still need its
788
+ // compat body — but that file is then simply DROPPED from `files`, so it
789
+ // never enters the transitive-closure loop below (which only bridges files
790
+ // that get `.delete()`d FROM `files`, i.e. files that WERE fully replaced).
791
+ // A lifecycle component declared alongside a non-lifecycle sibling in the
792
+ // same source file therefore got NEITHER a native stub NOR a bridge, and
793
+ // its class was left without the render()/dispose() methods its own call
794
+ // sites require — "no member named 'render'" (concretely: a component
795
+ // defined in the same .tsx file as the parent component that mounts it,
796
+ // e.g. PageArt declared inside ReaderScreen.tsx instead of its own file).
797
+ // Seed the bridge directly for any such component that DOES have a native
798
+ // mounted renderer available, independent of the sibling-file transitive
799
+ // closure below.
800
+ for (const module of ir.modules) {
801
+ const components = module.components.map((id) => componentById.get(id)).filter((component) => !!component);
802
+ for (const component of components) {
803
+ if (component.reactiveState || !componentHasRuntimeLifecycle(component))
804
+ continue;
805
+ const className = sanitizeCppIdentifier(component.exportName);
806
+ const hasNativeRenderer = rendererSplit?.renderedComponentIds.has(component.id) || inlineOnlyClasses.has(className);
807
+ if (!hasNativeRenderer)
808
+ continue;
809
+ bridgeFiles.add(path.resolve(module.file));
810
+ }
811
+ }
812
+ // A module that remains class-backed still instantiates mounted child
813
+ // components through the generated C++ class API. Preserve a lightweight
814
+ // bridge class for those children instead of replacing their headers with an
815
+ // empty stub. Propagate this constraint transitively: when a preserved
816
+ // WeatherView mounts WeatherForecast, and WeatherForecast mounts
817
+ // HourList/DayList, every compatibility/native boundary gets a bridge.
818
+ //
819
+ // Without this closure the weather graph could emit a 5-line native stub for
820
+ // CityList while preserving CityManager's `std::make_shared<CityList>()`, which
821
+ // fails later with an incomplete-type error. The renderer replacement itself
822
+ // is still used for independent branches whose parents are also replaced.
823
+ const moduleFilesByExport = new Map();
824
+ for (const component of ir.components) {
825
+ const file = path.resolve(component.module);
826
+ const existing = moduleFilesByExport.get(component.exportName);
827
+ if (existing)
828
+ existing.add(file);
829
+ else
830
+ moduleFilesByExport.set(component.exportName, new Set([file]));
831
+ }
832
+ let changed = true;
833
+ while (changed) {
834
+ changed = false;
835
+ for (const component of ir.components) {
836
+ if (files.has(path.resolve(component.module)))
837
+ continue;
838
+ for (const tag of mountedComponentTags(component.template)) {
839
+ for (const childFile of moduleFilesByExport.get(tag) ?? []) {
840
+ if (!files.delete(childFile))
841
+ continue;
842
+ bridgeFiles.add(childFile);
843
+ changed = true;
844
+ }
845
+ }
846
+ }
847
+ }
848
+ return files;
849
+ }
850
+ function mountedComponentTags(template) {
851
+ const tags = new Set();
852
+ const pending = [template];
853
+ const seen = new Set();
854
+ while (pending.length > 0) {
855
+ const value = pending.pop();
856
+ if (!value || typeof value !== 'object')
857
+ continue;
858
+ if (seen.has(value))
859
+ continue;
860
+ seen.add(value);
861
+ if (Array.isArray(value)) {
862
+ for (const item of value)
863
+ pending.push(item);
864
+ continue;
865
+ }
866
+ const record = value;
867
+ if (record.kind === 'mount') {
868
+ const payload = record.payload;
869
+ if (payload && typeof payload === 'object') {
870
+ const tag = payload.tag;
871
+ if (typeof tag === 'string')
872
+ tags.add(tag);
873
+ }
874
+ }
875
+ for (const child of Object.values(record))
876
+ pending.push(child);
877
+ }
878
+ return tags;
879
+ }
880
+ function canStubCompilerRuntimeModules(ir, nativeReplacedComponentFiles, rendererSplit) {
881
+ if (ir.components.length === 0)
882
+ return false;
883
+ const componentById = new Map(ir.components.map((component) => [component.id, component]));
884
+ for (const module of ir.modules) {
885
+ if (module.components.length === 0)
886
+ continue;
887
+ if (module.stores.length > 0)
888
+ return false;
889
+ const file = path.resolve(module.file);
890
+ if (nativeReplacedComponentFiles.has(file))
891
+ continue;
892
+ const components = module.components.map((id) => componentById.get(id));
893
+ if (components.length === 0 ||
894
+ components.some((component) => !component?.reactiveState) ||
895
+ !rendererSplit?.sectionsBySourceFile.has(file)) {
896
+ return false;
897
+ }
898
+ }
899
+ return true;
900
+ }
901
+ function isExternalCompilerRuntimeModule(fileName) {
902
+ return path.basename(fileName) === 'compiler-runtime.mjs';
903
+ }
904
+ function isExternalRuntimeSymbolsModule(fileName) {
905
+ return path.basename(fileName) === 'symbols.mjs';
906
+ }
907
+ function moduleHeaderFileBySourceFile(modules) {
908
+ const bySourceFile = new Map();
909
+ modules.forEach((module, index) => {
910
+ const base = `${String(index).padStart(4, '0')}_${safeModuleIdentifier(moduleBaseName(module.sourceFile.fileName))}`;
911
+ bySourceFile.set(path.resolve(module.sourceFile.fileName), `modules/${base}.hpp`);
912
+ });
913
+ return bySourceFile;
914
+ }
915
+ function invertMap(map) {
916
+ return new Map([...map.entries()].map(([key, value]) => [value, key]));
917
+ }
918
+ function storeModuleHeaderIncludes(ir, modules) {
919
+ const headerBySourceFile = moduleHeaderFileBySourceFile(modules);
920
+ const includes = new Set();
921
+ for (const store of ir.stores) {
922
+ if (store.selfStore)
923
+ continue;
924
+ const header = headerBySourceFile.get(path.resolve(store.module));
925
+ if (!header)
926
+ continue;
927
+ includes.add(`#include "./${header.slice(header.lastIndexOf('/') + 1)}"`);
928
+ }
929
+ return [...includes].sort();
930
+ }
931
+ function moduleCppFileBySourceFile(modules) {
932
+ const bySourceFile = new Map();
933
+ modules.forEach((module, index) => {
934
+ const base = `${String(index).padStart(4, '0')}_${safeModuleIdentifier(moduleBaseName(module.sourceFile.fileName))}`;
935
+ bySourceFile.set(path.resolve(module.sourceFile.fileName), `modules/${base}.cpp`);
936
+ });
937
+ return bySourceFile;
938
+ }
939
+ function moduleBaseName(fileName) {
940
+ const normalized = fileName.split('\\').join('/');
941
+ return normalized.slice(normalized.lastIndexOf('/') + 1) || 'module';
942
+ }
943
+ function safeModuleIdentifier(value) {
944
+ return sanitizeCppIdentifier(value);
945
+ }
946
+ function cppPreludeSource(options) {
947
+ const file = options['gea.cpp-prelude'];
948
+ const symbol = options['gea.cpp-prelude-symbol'];
949
+ const hasSymbol = typeof symbol === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(symbol);
950
+ if (typeof file !== 'string' || file.length === 0)
951
+ return '';
952
+ const resolved = path.resolve(file);
953
+ const body = fs.existsSync(resolved) ? fs.readFileSync(resolved, 'utf8').trim() : '';
954
+ if (!body && !hasSymbol)
955
+ return '';
956
+ if (hasSymbol) {
957
+ return [
958
+ '',
959
+ '// @geastack/geatsc-plugin-gea C++ prelude',
960
+ `// prelude=${resolved}`,
961
+ `void ${symbol}() {`,
962
+ body ? indent(body, ' ') : '',
963
+ '}',
964
+ '',
965
+ ].filter((line) => line !== '').join('\n');
966
+ }
967
+ // The registration instance must be a C++17 `inline` variable with external
968
+ // linkage — NOT an anonymous-namespace object. This lands in gea_ir.hpp, which
969
+ // every module TU of a split-TU build includes; an anonymous-namespace object
970
+ // gets one copy PER TU, so the whole static CSS tape re-registered once per
971
+ // module (~23x on the weather app = ~3.7 MB of duplicate compiled CSS values in
972
+ // PSRAM, fragmenting the heap until image decodes failed). The inline variable
973
+ // is deduped by the linker to exactly one instance program-wide, so the
974
+ // constructor (and the tape) runs once. Collisions across apps are impossible:
975
+ // named application entry points use the mode above (--cpp-prelude-symbol), so at
976
+ // most one object-mode prelude exists per firmware.
977
+ return [
978
+ '',
979
+ '// @geastack/geatsc-plugin-gea C++ prelude',
980
+ `// prelude=${resolved}`,
981
+ 'struct GeaPluginCppPreludeRegistration {',
982
+ ' GeaPluginCppPreludeRegistration() {',
983
+ indent(body, ' '),
984
+ ' }',
985
+ '};',
986
+ 'inline GeaPluginCppPreludeRegistration gea_plugin_cpp_prelude_registration;',
987
+ '',
988
+ ].join('\n');
989
+ }
990
+ function indent(source, prefix) {
991
+ return source.split(/\r?\n/).map((line) => `${prefix}${line}`).join('\n');
992
+ }
993
+ function needsGeaDocumentRuntime(ir, entry) {
994
+ if (ir.hostCapabilities.includes('dom'))
995
+ return true;
996
+ // `touch` is also a board capability. Direct canvas apps can use display
997
+ // APIs without pulling the DOM/document event runtime.
998
+ if (ir.components.length > 0)
999
+ return true;
1000
+ if (!entry)
1001
+ return false;
1002
+ return analyzeSourceHostBindings(entry).bindings?.includes('dom') ?? false;
1003
+ }
1004
+ function generateHostDocumentNodeValueDeclaration() {
1005
+ return [
1006
+ 'namespace gea_ir {',
1007
+ 'gea_cpp_value hostDocumentNodeValue(gea::embedded::ui::NodeHandle node, double nodeType = 1.0);',
1008
+ '} // namespace gea_ir',
1009
+ ].join('\n');
1010
+ }
1011
+ function microtasksNamespace(options) {
1012
+ const value = options['gea.microtasks-namespace'] ?? options['microtasks-namespace'];
1013
+ return typeof value === 'string' && value.length > 0 ? value : 'gea::framework::app::generated';
1014
+ }
1015
+ function pixelPanelEndian(options) {
1016
+ const value = options['gea.pixel-panel-endian'] ?? options['pixel-panel-endian'] ?? options.pixelPanelEndian;
1017
+ return value === '1' || value === 'true' || value === 'yes';
1018
+ }
1019
+ function typedStoreAccessorTypesForIr(ir) {
1020
+ const accessors = new Map();
1021
+ for (const store of ir.stores) {
1022
+ if (store.selfStore)
1023
+ continue;
1024
+ const name = storeInstanceGlobalName(store);
1025
+ if (!name)
1026
+ continue;
1027
+ accessors.set(sanitizeCppIdentifier(name), `std::shared_ptr<${sanitizeCppIdentifier(store.className)}>`);
1028
+ }
1029
+ return accessors;
1030
+ }
1031
+ function irSourceFiles(ir) {
1032
+ return [ir.entry, ...ir.modules.map((module) => module.file)];
1033
+ }
1034
+ function typedStoreAccessorTypesFromSource(source) {
1035
+ const accessors = new Map();
1036
+ const pattern = /(?:^|\n)([^\n;{}()]+?)\s*&\s*__gea_global_([A-Za-z_][A-Za-z0-9_]*)\s*\(/g;
1037
+ let match;
1038
+ while ((match = pattern.exec(source)) !== null) {
1039
+ const type = match[1].trim();
1040
+ if (type != 'gea_cpp_value')
1041
+ accessors.set(match[2], type);
1042
+ }
1043
+ return accessors;
1044
+ }
1045
+ function mergeTypedStoreAccessorTypes(target, source) {
1046
+ for (const [name, type] of source)
1047
+ target.set(name, type);
1048
+ }
1049
+ function typedGlobalAccessorsFromAccessorTypes(accessors) {
1050
+ const globals = new Map();
1051
+ for (const [name, type] of accessors) {
1052
+ globals.set(`__gea_global_${sanitizeCppIdentifier(name)}`, type);
1053
+ }
1054
+ return globals;
1055
+ }
1056
+ function replaceRuntimeGlobalAccessors(source) {
1057
+ let next = source;
1058
+ for (const [pattern, replacement] of runtimeGlobalCallReplacements) {
1059
+ next = next.replace(pattern, replacement);
1060
+ }
1061
+ for (const [pattern, replacement] of runtimeGlobalValueReplacements) {
1062
+ next = next.replace(pattern, replacement);
1063
+ }
1064
+ return next;
1065
+ }
1066
+ function replaceBundledCompilerRuntimeGlobalAccessors(source) {
1067
+ let next = source;
1068
+ for (const [readable, bundled] of bundledCompilerRuntimeGlobalAccessors) {
1069
+ // Only rename to the bundle's minified accessor when that accessor is
1070
+ // actually DEFINED in this program (a vite-minified bundle emits
1071
+ // `__gea_global_De` from its minified `const De = ...`). A source that
1072
+ // declares the runtime helpers under their READABLE names (unminified
1073
+ // bundles, tests) has no `De` accessor — renaming would point every call
1074
+ // site at an undefined symbol.
1075
+ if (!source.includes(bundled))
1076
+ continue;
1077
+ next = next.replace(new RegExp(`\\b${escapeRegExp(readable)}\\s*\\(\\s*\\)`, 'g'), `${bundled}()`);
1078
+ }
1079
+ return next;
1080
+ }
1081
+ function rewriteModuleLocalTemplateBuilderCalls(source) {
1082
+ const localTemplateBuilders = new Map();
1083
+ for (const match of source.matchAll(/\b(fn___gea_mod_[A-Za-z0-9_]+_x2e__(tpl\d+_create))\b/g)) {
1084
+ if (!localTemplateBuilders.has(match[2]))
1085
+ localTemplateBuilders.set(match[2], match[1]);
1086
+ }
1087
+ if (localTemplateBuilders.size === 0)
1088
+ return source;
1089
+ let next = source;
1090
+ for (const [shortSuffix, longName] of localTemplateBuilders) {
1091
+ next = next.replace(new RegExp(`\\bfn__${escapeRegExp(shortSuffix)}\\s*\\(`, 'g'), `${longName}(`);
1092
+ }
1093
+ return next;
1094
+ }
1095
+ function replaceComponentElAccessors(source) {
1096
+ return source
1097
+ .replace(/\(\[&\]\(\)(?:\s*->\s*decltype\(auto\))?\s*\{\s*\(void\)this->__gea_ctor_return_value\.record_get_literal\("el"\);\s*return this->__gea_ctor_return_value\.record_get_literal\("el"\);\s*\}\)\(\)/g, 'this->__gea_dynamic_props.record_get(gea_cpp_value(std::string("__geawebsym_gea_element")))')
1098
+ .replace(/\(\[&\]\(\)\s*\{\s*return \(\*this\)\.el\(\);\s*\}\)\(\)/g, 'this->__gea_dynamic_props.record_get(gea_cpp_value(std::string("__geawebsym_gea_element")))')
1099
+ // Direct getter-call shape (no ctor-return slot, no IIFE): a transparent-
1100
+ // proxy component emits `this.el` as a plain `(*this).el()` call.
1101
+ .replace(/\(\*this\)\.el\(\)/g, 'this->__gea_dynamic_props.record_get(gea_cpp_value(std::string("__geawebsym_gea_element")))');
1102
+ }
1103
+ function findMatchingBrace(source, open) {
1104
+ let depth = 0;
1105
+ let quote = null;
1106
+ let escaped = false;
1107
+ for (let index = open; index < source.length; index += 1) {
1108
+ const char = source[index];
1109
+ if (quote) {
1110
+ if (escaped)
1111
+ escaped = false;
1112
+ else if (char === '\\')
1113
+ escaped = true;
1114
+ else if (char === quote)
1115
+ quote = null;
1116
+ continue;
1117
+ }
1118
+ if (char === '"' || char === "'") {
1119
+ quote = char;
1120
+ continue;
1121
+ }
1122
+ if (char === '{')
1123
+ depth += 1;
1124
+ else if (char === '}') {
1125
+ depth -= 1;
1126
+ if (depth === 0)
1127
+ return index;
1128
+ }
1129
+ }
1130
+ return -1;
1131
+ }
1132
+ const generatedMountFunctionNamePatternSource = '(?:fn_mount(?:_x24_\\d+)?|fn___gea_mod_[A-Za-z0-9_]+_x2e_mount(?:_x24_\\d+)?)';
1133
+ function generatedMountFunctionCallPattern() {
1134
+ return new RegExp(`\\b${generatedMountFunctionNamePatternSource}\\s*\\(`);
1135
+ }
1136
+ function escapeRegExp(text) {
1137
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1138
+ }
1139
+ const runtimeGlobalCallReplacements = [
1140
+ [/\b_isArr\s*\(/g, '__gea_global__isArr()('],
1141
+ [/\bkebab\s*\(/g, '__gea_global_kebab()('],
1142
+ [/\breactiveAttr\s*\(/g, '__gea_global_reactiveAttr()('],
1143
+ [/\breactiveClass\s*\(/g, '__gea_global_reactiveClass()('],
1144
+ [/\breactiveStyle\s*\(/g, '__gea_global_reactiveStyle()('],
1145
+ [/\breactiveText\s*\(/g, '__gea_global_reactiveText()('],
1146
+ [/\breactiveTextValue\s*\(/g, '__gea_global_reactiveTextValue()('],
1147
+ [/\b_unwrap\s*\(/g, '__gea_global__unwrap()('],
1148
+ [/\bunwrap\s*\(/g, '__gea_global_unwrap()('],
1149
+ ];
1150
+ const runtimeGlobalValueReplacements = [
1151
+ [/\b_priv\b/g, '__gea_global__priv()'],
1152
+ [/\b_active\b/g, '__gea_global__active()'],
1153
+ [/\b_nested\b/g, '__gea_global__nested()'],
1154
+ ];
1155
+ const bundledCompilerRuntimeGlobalAccessors = [
1156
+ ['__gea_global_reactiveTextValue', '__gea_global_xe'],
1157
+ ['__gea_global_reactiveText', '__gea_global_Se'],
1158
+ ['__gea_global_reactiveAttr', '__gea_global_Ce'],
1159
+ ['__gea_global_reactiveHtml', '__gea_global_we'],
1160
+ ['__gea_global_reactiveBoolAttr', '__gea_global_Te'],
1161
+ ['__gea_global_reactiveBool', '__gea_global_Ee'],
1162
+ ['__gea_global_reactiveClass', '__gea_global_De'],
1163
+ ['__gea_global_reactiveClassName', '__gea_global_Oe'],
1164
+ ['__gea_global_kebab', '__gea_global_je'],
1165
+ ['__gea_global_reactiveStyle', '__gea_global_Me'],
1166
+ ['__gea_global_reactiveStyleProp', '__gea_global_Ne'],
1167
+ ['__gea_global_reactiveValueRead', '__gea_global_Pe'],
1168
+ ['__gea_global_reactiveValue', '__gea_global_Fe'],
1169
+ ];
1170
+ function externalizeDrainMicrotasksDeclaration(source, namespaceName) {
1171
+ const pattern = new RegExp(`(namespace\\s+${escapeRegExp(namespaceName)}\\s*\\{\\s*)(?:inline\\s+)?void\\s+drainMicrotasks\\s*\\(\\s*\\)\\s*\\{\\s*gea_cpp_drain_microtasks\\s*\\(\\s*\\)\\s*;\\s*\\}(\\s*\\}\\s*//\\s*namespace\\s+${escapeRegExp(namespaceName)})`, 'm');
1172
+ return source.replace(pattern, '$1void drainMicrotasks();$2');
1173
+ }
1174
+ function ensureModuleFirstPluginRuntimeSource(sources, options) {
1175
+ if (!options.includeGeaDocumentRuntime && !options.defineDrainMicrotasks)
1176
+ return sources;
1177
+ const runtimeFileName = 'modules/gea_plugin_runtime.cpp';
1178
+ const runtimeIndex = sources.findIndex((source) => source.fileName === runtimeFileName);
1179
+ const hostDocumentBridge = options.includeGeaDocumentRuntime
1180
+ ? generateHostDocumentNodeValueDefinition()
1181
+ : '';
1182
+ const drainDefinition = options.defineDrainMicrotasks
1183
+ ? generateDrainMicrotasksRuntimeDefinition(options.microtasksNamespace)
1184
+ : '';
1185
+ if (runtimeIndex < 0) {
1186
+ const lines = ['#include "../generated_support.hpp"'];
1187
+ if (options.includeGeaDocumentRuntime)
1188
+ lines.push('#include "../host_document_gea.cpp"');
1189
+ if (hostDocumentBridge)
1190
+ lines.push('', hostDocumentBridge);
1191
+ if (drainDefinition)
1192
+ lines.push('', drainDefinition);
1193
+ return [...sources, { fileName: runtimeFileName, source: `${lines.join('\n').trimEnd()}\n` }];
1194
+ }
1195
+ const runtime = sources[runtimeIndex];
1196
+ let source = runtime.source;
1197
+ if (options.includeGeaDocumentRuntime) {
1198
+ source = insertModuleHeaderInclude(source, '#include "../host_document_gea.cpp"');
1199
+ }
1200
+ if (hostDocumentBridge && !source.includes('hostDocumentNodeValue(')) {
1201
+ source = `${source.trimEnd()}\n\n${hostDocumentBridge}\n`;
1202
+ }
1203
+ if (drainDefinition)
1204
+ source = `${source.trimEnd()}\n\n${drainDefinition}\n`;
1205
+ if (source === runtime.source)
1206
+ return sources;
1207
+ return sources.map((candidate, index) => index === runtimeIndex ? { ...candidate, source } : candidate);
1208
+ }
1209
+ function generateHostDocumentNodeValueDefinition() {
1210
+ return [
1211
+ 'namespace gea_ir {',
1212
+ 'gea_cpp_value hostDocumentNodeValue(gea::embedded::ui::NodeHandle node, double nodeType) {',
1213
+ ' return gea::runtime::host::domNodeValue(node, nodeType);',
1214
+ '}',
1215
+ '} // namespace gea_ir',
1216
+ ].join('\n');
1217
+ }
1218
+ function generateDrainMicrotasksRuntimeDefinition(namespaceName) {
1219
+ return [
1220
+ `namespace ${namespaceName} {`,
1221
+ 'void drainMicrotasks() {',
1222
+ ' gea_cpp_drain_microtasks();',
1223
+ '}',
1224
+ `} // namespace ${namespaceName}`,
1225
+ ].join('\n');
1226
+ }
1227
+ function componentHasRuntimeLifecycle(component) {
1228
+ if (!component.sourceSpan)
1229
+ return false;
1230
+ let source = '';
1231
+ try {
1232
+ source = fs.readFileSync(component.module, 'utf8');
1233
+ }
1234
+ catch {
1235
+ return false;
1236
+ }
1237
+ const text = source.slice(component.sourceSpan.start, component.sourceSpan.end);
1238
+ return /\b(?:created|onAfterRender|dispose)\s*\(/.test(text);
1239
+ }