@rangular-framework/cli 0.0.0-stage → 1.0.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 (36) hide show
  1. package/dist/cli/src/cli.js +1217 -0
  2. package/dist/compiler/src/catalog.js +198 -0
  3. package/dist/compiler/src/class/formInit.js +370 -0
  4. package/dist/compiler/src/class/parseComponent.js +430 -0
  5. package/dist/compiler/src/class/parseDirective.js +227 -0
  6. package/dist/compiler/src/class/parseRoutes.js +163 -0
  7. package/dist/compiler/src/codegen/generate.js +3466 -0
  8. package/dist/compiler/src/codegen/methods.js +975 -0
  9. package/dist/compiler/src/codegen/sourceMap.js +77 -0
  10. package/dist/compiler/src/compile.js +775 -0
  11. package/dist/compiler/src/diagnostics.js +113 -0
  12. package/dist/compiler/src/doctor.js +144 -0
  13. package/dist/compiler/src/fix.js +44 -0
  14. package/dist/compiler/src/index.js +38 -0
  15. package/dist/compiler/src/preview/renderPreview.js +7158 -0
  16. package/dist/compiler/src/preview/styleSnapshot.js +268 -0
  17. package/dist/compiler/src/propTable.js +107 -0
  18. package/dist/compiler/src/style/css.js +161 -0
  19. package/dist/compiler/src/template/ast.js +19 -0
  20. package/dist/compiler/src/template/evaluate.js +151 -0
  21. package/dist/compiler/src/template/expr.js +360 -0
  22. package/dist/compiler/src/template/forms.js +80 -0
  23. package/dist/compiler/src/template/literal.js +248 -0
  24. package/dist/compiler/src/template/parser.js +230 -0
  25. package/dist/compiler/src/template/pipes.js +225 -0
  26. package/dist/compiler/src/template/printAst.js +38 -0
  27. package/dist/compiler/src/template/structural.js +51 -0
  28. package/dist/runtime/src/index.js +1197 -0
  29. package/dist/ui/src/chart.js +196 -0
  30. package/dist/ui/src/datetime.js +240 -0
  31. package/dist/ui/src/icons.js +310 -0
  32. package/dist/ui/src/mask.js +103 -0
  33. package/dist/ui/src/palette.js +141 -0
  34. package/dist/ui/src/tokens.js +173 -0
  35. package/package.json +28 -4
  36. package/README.md +0 -3
@@ -0,0 +1,3466 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EVENT_PROPS = exports.TAG_MAP = void 0;
4
+ exports.isLiteralInitializer = isLiteralInitializer;
5
+ exports.verbatimInitFields = verbatimInitFields;
6
+ exports.styleKeyName = styleKeyName;
7
+ exports.componentFunctionName = componentFunctionName;
8
+ exports.outputPropName = outputPropName;
9
+ exports.eventPropName = eventPropName;
10
+ exports.isAssignmentExpression = isAssignmentExpression;
11
+ exports.classToggleOf = classToggleOf;
12
+ exports.isClassStyleBindingName = isClassStyleBindingName;
13
+ exports.generateComponent = generateComponent;
14
+ const icons_1 = require("../../../ui/src/icons");
15
+ const datetime_1 = require("../../../ui/src/datetime");
16
+ const chart_1 = require("../../../ui/src/chart");
17
+ const parseDirective_1 = require("../class/parseDirective");
18
+ const formInit_1 = require("../class/formInit");
19
+ const diagnostics_1 = require("../diagnostics");
20
+ const propTable_1 = require("../propTable");
21
+ const css_1 = require("../style/css");
22
+ const expr_1 = require("../template/expr");
23
+ const pipes_1 = require("../template/pipes");
24
+ const forms_1 = require("../template/forms");
25
+ const literal_1 = require("../template/literal");
26
+ const structural_1 = require("../template/structural");
27
+ const methods_1 = require("./methods");
28
+ const sourceMap_1 = require("./sourceMap");
29
+ /**
30
+ * The tag -> generated-component contract. Single source of truth:
31
+ * codegen renders from this table and the catalog is generated from it.
32
+ */
33
+ exports.TAG_MAP = {
34
+ // Plain containers compile to RgSection, the stack primitive: a
35
+ // column with the rhythm gap, so blocks inside a section are spaced
36
+ // exactly like blocks directly under the screen. They used to
37
+ // compile to a bare View with no gap, and every routed screen
38
+ // (rooted in a section) rendered its cards attached edge to edge.
39
+ div: { component: 'RgSection', fromUi: true },
40
+ section: { component: 'RgSection', fromUi: true },
41
+ header: { component: 'RgSection', fromUi: true },
42
+ span: { component: 'Text', fromUi: false },
43
+ // Text with a meaning compiles to RgText (default polish pass):
44
+ // the primitive applies the token type step (size, line height,
45
+ // weight) and the theme's on-surface colour, so the app renders
46
+ // the same type scale the preview shows. Plain RN Text ignored
47
+ // the variant prop, so headings reached the phone unstyled.
48
+ // <span> stays plain Text: it is the inline element, nested inside
49
+ // a text block and inheriting from it.
50
+ p: { component: 'RgText', fromUi: true, variant: 'bodyLarge' },
51
+ label: { component: 'RgText', fromUi: true, variant: 'label' },
52
+ h1: { component: 'RgText', fromUi: true, variant: 'display' },
53
+ h2: { component: 'RgText', fromUi: true, variant: 'heading' },
54
+ h3: { component: 'RgText', fromUi: true, variant: 'title' },
55
+ button: { component: 'RgButton', fromUi: true },
56
+ screen: { component: 'RgScreen', fromUi: true },
57
+ appbar: { component: 'RgAppbar', fromUi: true },
58
+ gradient: { component: 'RgGradient', fromUi: true },
59
+ card: { component: 'RgCard', fromUi: true },
60
+ list: { component: 'RgList', fromUi: true },
61
+ row: { component: 'RgRow', fromUi: true },
62
+ fab: { component: 'RgFab', fromUi: true },
63
+ icon: { component: 'RgIcon', fromUi: true },
64
+ 'icon-button': { component: 'RgIconButton', fromUi: true },
65
+ switch: { component: 'RgSwitch', fromUi: true },
66
+ switcher: { component: 'RgSwitcher', fromUi: true },
67
+ option: { component: 'RgOption', fromUi: true },
68
+ checkbox: { component: 'RgCheckbox', fromUi: true },
69
+ 'radio-group': { component: 'RgRadioGroup', fromUi: true },
70
+ radio: { component: 'RgRadio', fromUi: true },
71
+ input: { component: 'RgInput', fromUi: true },
72
+ form: { component: 'RgSection', fromUi: true },
73
+ 'router-outlet': { component: 'RgOutlet', fromUi: true },
74
+ sheet: { component: 'RgSheet', fromUi: true },
75
+ dialog: { component: 'RgDialog', fromUi: true },
76
+ actions: { component: 'RgActions', fromUi: true },
77
+ 'datetime-picker': { component: 'RgDateTimePicker', fromUi: true },
78
+ tabs: { component: 'RgTabs', fromUi: true },
79
+ tab: { component: 'RgTab', fromUi: true },
80
+ accordion: { component: 'RgAccordion', fromUi: true },
81
+ panel: { component: 'RgPanel', fromUi: true },
82
+ table: { component: 'RgTable', fromUi: true },
83
+ column: { component: 'RgColumn', fromUi: true },
84
+ slider: { component: 'RgSlider', fromUi: true },
85
+ 'progress-bar': { component: 'RgProgressBar', fromUi: true },
86
+ spinner: { component: 'RgSpinner', fromUi: true },
87
+ chips: { component: 'RgChips', fromUi: true },
88
+ chip: { component: 'RgChip', fromUi: true },
89
+ // Stage 14: the Material components the audit found missing.
90
+ menu: { component: 'RgMenu', fromUi: true },
91
+ 'menu-item': { component: 'RgMenuItem', fromUi: true },
92
+ drawer: { component: 'RgDrawer', fromUi: true },
93
+ select: { component: 'RgSelect', fromUi: true },
94
+ stepper: { component: 'RgStepper', fromUi: true },
95
+ step: { component: 'RgStep', fromUi: true },
96
+ 'grid-list': { component: 'RgGridList', fromUi: true },
97
+ 'grid-tile': { component: 'RgGridTile', fromUi: true },
98
+ tree: { component: 'RgTree', fromUi: true },
99
+ 'tree-node': { component: 'RgTreeNode', fromUi: true },
100
+ divider: { component: 'RgDivider', fromUi: true },
101
+ // Stage 15: the pieces real apps use that Angular never shipped
102
+ // (the beyond-Angular audit). Screen and list patterns first:
103
+ // the bottom navigation bar and its destination declarations,
104
+ // the skeleton placeholder, and swipe actions declared inside a
105
+ // row (row itself is above; its action marker lives here).
106
+ 'bottom-nav': { component: 'RgBottomNav', fromUi: true },
107
+ 'nav-item': { component: 'RgNavItem', fromUi: true },
108
+ skeleton: { component: 'RgSkeleton', fromUi: true },
109
+ 'row-action': { component: 'RgRowAction', fromUi: true },
110
+ // Controls, each on the Stage 6 [value] / (change) contract.
111
+ rating: { component: 'RgRating', fromUi: true },
112
+ otp: { component: 'RgOtp', fromUi: true },
113
+ 'file-picker': { component: 'RgFilePicker', fromUi: true },
114
+ 'color-picker': { component: 'RgColorPicker', fromUi: true },
115
+ editor: { component: 'RgEditor', fromUi: true },
116
+ // Containers and display.
117
+ carousel: { component: 'RgCarousel', fromUi: true },
118
+ timeline: { component: 'RgTimeline', fromUi: true },
119
+ 'timeline-item': { component: 'RgTimelineItem', fromUi: true },
120
+ calendar: { component: 'RgCalendar', fromUi: true },
121
+ avatar: { component: 'RgAvatar', fromUi: true },
122
+ 'avatar-group': { component: 'RgAvatarGroup', fromUi: true },
123
+ 'empty-state': { component: 'RgEmptyState', fromUi: true },
124
+ chart: { component: 'RgChart', fromUi: true },
125
+ image: { component: 'RgImage', fromUi: true },
126
+ lightbox: { component: 'RgLightbox', fromUi: true },
127
+ breadcrumbs: { component: 'RgBreadcrumbs', fromUi: true },
128
+ crumb: { component: 'RgCrumb', fromUi: true },
129
+ // Tutorial round (2026-11-13): the code block.
130
+ code: { component: 'RgCode', fromUi: true },
131
+ };
132
+ /** True when an initializer source text is a plain literal we may hoist. */
133
+ function isLiteralInitializer(init) {
134
+ return (0, literal_1.isLiteralSource)(init);
135
+ }
136
+ /**
137
+ * Fields the generated component declares by emitting their initializer
138
+ * verbatim as a plain const (proof fix): a field whose initializer is
139
+ * not a literal and not a reactive form instance, which no method
140
+ * assigns (mutation calls included), and whose initializer does not
141
+ * reference `this` (a generated function component has no `this` to
142
+ * resolve). The classic case is `today = new Date()` read by a date
143
+ * pipe: before this fix it warned GEN_FIELD, emitted only a TODO
144
+ * comment, and the generated code referenced a name it never declared.
145
+ * The preview rebuilds exactly these fields from their initializer
146
+ * source, so the two sides cannot drift.
147
+ */
148
+ function verbatimInitFields(component) {
149
+ const mutated = (0, methods_1.analyzeMutatedFields)(component);
150
+ const out = [];
151
+ for (const field of component.fields) {
152
+ if (field.isInput || field.isOutput)
153
+ continue;
154
+ if (!field.initializer)
155
+ continue;
156
+ if (isLiteralInitializer(field.initializer))
157
+ continue;
158
+ if ((0, formInit_1.isFormInitializer)(field.initializer, (0, formInit_1.builderDepsOf)(component)))
159
+ continue;
160
+ if (mutated.has(field.name))
161
+ continue;
162
+ if ((0, literal_1.initializerUsesThis)(field.initializer))
163
+ continue;
164
+ out.push({ name: field.name, initializer: field.initializer });
165
+ }
166
+ return out;
167
+ }
168
+ /** StyleSheet keys must be valid JS identifiers: `card-note` -> `cardNote`. */
169
+ function styleKeyName(key) {
170
+ return key.replace(/-([a-zA-Z])/g, (_, c) => c.toUpperCase());
171
+ }
172
+ function componentFunctionName(className) {
173
+ return className.endsWith('Component') ? className.slice(0, -'Component'.length) : className;
174
+ }
175
+ /** @Output field name -> generated callback prop name: `saved` -> `onSaved`. */
176
+ function outputPropName(fieldName) {
177
+ return 'on' + fieldName.charAt(0).toUpperCase() + fieldName.slice(1);
178
+ }
179
+ /**
180
+ * Security (audit, 2026-11-12): plain text and static strings in a
181
+ * template are data, never code. The helpers below keep them inside
182
+ * their literal context in the generated .tsx:
183
+ * - a static text part containing JSX-special characters ({, }, <, >)
184
+ * is emitted as a {'...'} string expression instead of raw JSX text,
185
+ * where a { would otherwise open an expression container;
186
+ * - a static attribute value is entity-escaped so a quote inside it
187
+ * cannot end the JSX attribute string and inject extra props;
188
+ * - author-controlled strings placed inside generated comments are
189
+ * flattened so a newline cannot end a // comment and a star-slash
190
+ * cannot end a block comment.
191
+ * Text and values without special characters are emitted exactly as
192
+ * before, so existing examples are unchanged.
193
+ */
194
+ function escapeJsxAttrValue(value) {
195
+ return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;');
196
+ }
197
+ const JSX_TEXT_SPECIALS = /[{}<>]/;
198
+ function jsxTextPart(value) {
199
+ return JSX_TEXT_SPECIALS.test(value) ? `{${JSON.stringify(value)}}` : value;
200
+ }
201
+ function forLineComment(s) {
202
+ return s.replace(/[\r\n]+/g, ' ');
203
+ }
204
+ function forBlockComment(s) {
205
+ return forLineComment(s).replace(/\*\//g, '* /');
206
+ }
207
+ /** Template (event) name -> React Native prop name, for known events. */
208
+ exports.EVENT_PROPS = {
209
+ click: 'onPress',
210
+ change: 'onChange',
211
+ submit: 'onSubmit',
212
+ blur: 'onBlur',
213
+ close: 'onClose',
214
+ focus: 'onFocus',
215
+ toggle: 'onToggle',
216
+ remove: 'onRemove',
217
+ optionSelected: 'onOptionSelected',
218
+ // Stage 15: the scroller events of screens and lists (pull to
219
+ // refresh, infinite scroll). Neither carries a value; the
220
+ // handler just runs.
221
+ refresh: 'onRefresh',
222
+ endReached: 'onEndReached',
223
+ // Gradient shell round (2026-11-17): the trailing action of a
224
+ // row and of an app bar, and the app bar's back chevron. Naming
225
+ // them here makes them known events, so they map without the
226
+ // fallback comment.
227
+ action: 'onAction',
228
+ leading: 'onLeading',
229
+ back: 'onBack',
230
+ // Long press round (2026-11-29): a held press on the pressable
231
+ // primitives (row, section), React Native's onLongPress. On a
232
+ // row that also carries a tooltip, the author's handler wins
233
+ // over the tooltip's long press (see RgRow).
234
+ longpress: 'onLongPress',
235
+ };
236
+ /** Map a template (event) to its React Native prop name. */
237
+ function eventPropName(eventName, tag) {
238
+ if (eventName === 'input') {
239
+ return tag.toLowerCase() === 'input'
240
+ ? { prop: 'onChangeText', known: true }
241
+ : { prop: 'onInput', known: false };
242
+ }
243
+ const known = exports.EVENT_PROPS[eventName];
244
+ if (known)
245
+ return { prop: known, known: true };
246
+ return { prop: 'on' + eventName.charAt(0).toUpperCase() + eventName.slice(1), known: false };
247
+ }
248
+ /**
249
+ * True when an event binding's expression is an assignment statement,
250
+ * e.g. `(close)="sheetOpen = false"` or `(click)="count += 1"`
251
+ * (Stage 10). Evidence from the code: the template expression grammar
252
+ * (template/expr.ts) has no assignment operator at all, its tokenizer
253
+ * does not even produce a bare `=` token, so such a binding cannot be
254
+ * translated; before Stage 10 codegen silently fell back to the raw
255
+ * source, emitting `onClose={() => sheetOpen = false}` against a
256
+ * const state binding, which compiles and then throws at runtime.
257
+ * Assignment bindings are therefore detected explicitly and dropped
258
+ * with a GEN_EVENT_ASSIGNMENT warning: authors write a method
259
+ * (`closeSheet() { this.sheetOpen = false; }`) and bind that instead,
260
+ * the pattern the Stage 6 controls already document.
261
+ */
262
+ function isAssignmentExpression(source) {
263
+ const src = source.trim();
264
+ try {
265
+ (0, expr_1.parseExpression)(src);
266
+ return false; // it parses as an expression: a call, a bare ref, a comparison
267
+ }
268
+ catch {
269
+ // Did not parse. An assignment is the common cause; look for a
270
+ // bare `=` (not ==, <=, >=, !=) or a compound assignment operator.
271
+ return /(^|[^=!<>])=(?![=])/.test(src) || /[+\-*/%]+=(?![=])/.test(src);
272
+ }
273
+ }
274
+ const HTTP_CLIENT = 'HttpClient';
275
+ /**
276
+ * The class name a [class.name] toggle binding names, or undefined
277
+ * when the binding name is not a class toggle. Class names follow the
278
+ * CSS subset's class selector grammar (a plain identifier, hyphens
279
+ * allowed), the same shape parseCss accepts for a `.class` key.
280
+ */
281
+ function classToggleOf(bindingName) {
282
+ const match = /^class\.([A-Za-z_-][A-Za-z0-9_-]*)$/.exec(bindingName);
283
+ return match ? match[1] : undefined;
284
+ }
285
+ /**
286
+ * True for every binding name that carries class, style or HTML
287
+ * attribute intent: [class], [class.name], [ngClass], [style],
288
+ * [style.prop] (with or without a unit suffix), [ngStyle] and
289
+ * [attr.x]. None of these is a prop of any generated component:
290
+ * [class.name] over a class declared in the component styles is wired
291
+ * through the element's style (see styleFor), and every other form is
292
+ * diagnosed and dropped by the binding scan in generateComponent.
293
+ * Before the gap fix the generic prop loops emitted them verbatim
294
+ * (class.hot={hot}, style.color={colour}, attr.class={...}), props
295
+ * the primitives ignore, so the styling silently never appeared; a
296
+ * [style] object or a static style attribute could even collide with
297
+ * the generated style prop and produce a duplicate-prop JSX error.
298
+ */
299
+ function isClassStyleBindingName(bindingName) {
300
+ return bindingName === 'class'
301
+ || bindingName === 'ngClass'
302
+ || bindingName === 'ngStyle'
303
+ || bindingName === 'style'
304
+ || bindingName.startsWith('class.')
305
+ || bindingName.startsWith('style.')
306
+ || bindingName.startsWith('attr.');
307
+ }
308
+ /**
309
+ * Blocks whose renderers never emit a style, so a [class.name] toggle
310
+ * on them has nothing to attach to: the icon (its renderer reads only
311
+ * name, size, color and badge), the table column declaration (it
312
+ * renders nothing itself), the router outlet and ng-content.
313
+ */
314
+ const STYLELESS_TAGS = new Set(['icon', 'column', 'router-outlet', 'ng-content']);
315
+ class Generator {
316
+ diagnostics = [];
317
+ sourceMapOut;
318
+ usedRn = new Set();
319
+ usedUi = new Set();
320
+ usedRuntime = new Set();
321
+ reactImports = new Set();
322
+ childBySelector = new Map();
323
+ childByClassName = new Map();
324
+ rootServices = new Map();
325
+ allServices = [];
326
+ /** Literal module constants carried from classless files (0.6.5). */
327
+ moduleConsts = [];
328
+ /** The resolved route table (Stage 9), when a routes file was resolved. */
329
+ routes;
330
+ /** Third-party imports to carry into the module (from the context). */
331
+ externalImports;
332
+ /**
333
+ * True when a route table exists AND routing is used somewhere in the
334
+ * compilation (Stage 9): only then are the module-level navigator and
335
+ * router emitted and the outlet and links wired to them.
336
+ */
337
+ routingActive = false;
338
+ /** GEN_ROUTER_NO_OUTLET fires once per compilation, not per screen. */
339
+ routerNoOutletReported = false;
340
+ /**
341
+ * True when any component in the compilation injects SnackBar
342
+ * (Stage 10): only then is the module-level snackbar service
343
+ * emitted and the entry component given its host state.
344
+ */
345
+ snackActive = false;
346
+ /** Custom @Pipe classes by pipe name (Stage 12), with their instance vars. */
347
+ pipesByName = new Map();
348
+ pipeInstances = new Map();
349
+ /**
350
+ * Attribute directives by attribute name (Stage 12), with their
351
+ * extracted style assignments. A directive whose logic is outside
352
+ * the subset carries `unsupported` and applies no styles; generate()
353
+ * reports it once with DIR_UNSUPPORTED.
354
+ */
355
+ directivesByAttr = new Map();
356
+ styles = [];
357
+ /** Source map bookkeeping (Stage 5): element records keyed by marker id. */
358
+ smConfig;
359
+ smRecords = [];
360
+ smUnits = [];
361
+ constructor(context) {
362
+ this.smConfig = context.sourceMap;
363
+ this.routes = context.routes;
364
+ this.externalImports = context.externalImports;
365
+ this.moduleConsts = context.consts ?? [];
366
+ for (const child of context.children ?? []) {
367
+ if (child.info.selector)
368
+ this.childBySelector.set(child.info.selector, child.info);
369
+ this.childByClassName.set(child.info.className, child.info);
370
+ }
371
+ this.allServices = context.services ?? [];
372
+ for (const svc of this.allServices) {
373
+ if (svc.providedInRoot)
374
+ this.rootServices.set(svc.className, svc);
375
+ }
376
+ for (const pipe of context.pipes ?? []) {
377
+ if (this.pipesByName.has(pipe.pipeName))
378
+ continue;
379
+ this.pipesByName.set(pipe.pipeName, pipe);
380
+ this.pipeInstances.set(pipe.pipeName, `__pipe${pipe.className}`);
381
+ }
382
+ for (const directive of context.directives ?? []) {
383
+ if (!directive.attrName || this.directivesByAttr.has(directive.attrName))
384
+ continue;
385
+ const styles = (0, parseDirective_1.directiveStyles)(directive);
386
+ this.directivesByAttr.set(directive.attrName, {
387
+ info: directive,
388
+ assignments: styles.assignments,
389
+ unsupported: styles.unsupported,
390
+ });
391
+ }
392
+ }
393
+ /** The generated instance variable for a custom pipe class: `__pipe` + class name. */
394
+ pipeInstanceVar(pipeName) {
395
+ return this.pipeInstances.get(pipeName);
396
+ }
397
+ generate(entry, ast, css, children) {
398
+ const serviceBlocks = [];
399
+ for (const svc of this.allServices) {
400
+ if (!svc.providedInRoot)
401
+ continue;
402
+ serviceBlocks.push(this.generateService(svc));
403
+ }
404
+ // Custom pipes (Stage 12): every resolved @Pipe class is emitted
405
+ // as a plain class plus one shared instance, next to the services.
406
+ // A directive outside the supported subset is reported once here,
407
+ // whether or not any template uses it: the class was resolved, so
408
+ // its author expects it to work.
409
+ const pipeBlocks = [];
410
+ for (const pipe of this.pipesByName.values()) {
411
+ pipeBlocks.push(this.generatePipeClass(pipe));
412
+ }
413
+ for (const [attr, entry2] of this.directivesByAttr) {
414
+ if (!entry2.unsupported)
415
+ continue;
416
+ this.diagnostics.push((0, diagnostics_1.warning)('DIR_UNSUPPORTED', `Directive '${entry2.info.className}' ([${attr}]) is outside the supported subset: ${entry2.unsupported}; it applies no styles`, undefined, undefined, 'Keep the directive to @Input fields, an ElementRef, and ngOnInit or setter bodies made only of this.el.nativeElement.style.<prop> = <expr over inputs and literals> statements'));
417
+ }
418
+ const registrations = this.registrationLines(entry, children);
419
+ // --- Routing activation (Stage 9) --------------------------------------
420
+ // The navigator and router exist in the output only when a route
421
+ // table was resolved AND routing is used: an outlet or routerLink
422
+ // in any template of the compilation, or a Router / ActivatedRoute
423
+ // injection in any unit. The entry template's outlet also gives the
424
+ // entry component its navigation state (see generateUnit).
425
+ const templateUsage = (nodes) => {
426
+ const usage = { outlet: false, used: false };
427
+ const walk = (list) => {
428
+ for (const n of list) {
429
+ if (n.type !== 'element')
430
+ continue;
431
+ if (n.tag.toLowerCase() === 'router-outlet') {
432
+ usage.outlet = true;
433
+ usage.used = true;
434
+ }
435
+ if (n.attrs['routerLink'] !== undefined
436
+ || n.propBindings.some((b) => b.name === 'routerLink'))
437
+ usage.used = true;
438
+ walk(n.children);
439
+ }
440
+ };
441
+ walk(nodes);
442
+ return usage;
443
+ };
444
+ const entryUsage = templateUsage(ast.children);
445
+ const childUsage = children.map((c) => templateUsage(c.ast.children));
446
+ const injectsRouter = [entry, ...children.map((c) => c.info)]
447
+ .some((info) => (info.constructorDeps ?? []).some((d) => d.typeName === 'Router' || d.typeName === 'ActivatedRoute'));
448
+ this.routingActive = this.routes !== undefined
449
+ && (entryUsage.used || childUsage.some((u) => u.used) || injectsRouter);
450
+ const navLines = [];
451
+ if (this.routingActive) {
452
+ this.usedRuntime.add('RgNavigator');
453
+ this.usedRuntime.add('Router');
454
+ const defs = (this.routes ?? []).map((r) => (r.redirectTo !== undefined
455
+ ? { path: r.path, redirectTo: r.redirectTo }
456
+ : { path: r.path }));
457
+ navLines.push(`const __navigator = new RgNavigator(${JSON.stringify(defs)});`);
458
+ navLines.push('const __router = new Router(__navigator);');
459
+ }
460
+ // --- Snackbar activation (Stage 10) ------------------------------------
461
+ // One module-level SnackBar instance serves the whole app, like
462
+ // the navigator: components inject it and call open(); the entry
463
+ // component mirrors its state and renders the host pill. It is
464
+ // emitted only when some component actually injects the token.
465
+ this.snackActive = [entry, ...children.map((c) => c.info)]
466
+ .some((info) => (info.constructorDeps ?? []).some((d) => d.typeName === 'SnackBar'));
467
+ const snackModuleLines = [];
468
+ if (this.snackActive) {
469
+ this.usedRuntime.add('SnackBar');
470
+ snackModuleLines.push('const __snackBar = new SnackBar();');
471
+ }
472
+ const childBlocks = [];
473
+ children.forEach((child, i) => {
474
+ this.smUnits.push({
475
+ fnName: componentFunctionName(child.info.className),
476
+ exportKw: 'export function',
477
+ tsFile: child.fileName,
478
+ templateFile: child.templateFile,
479
+ classLine: child.info.sourceLine,
480
+ });
481
+ childBlocks.push(this.generateUnit(child.info, child.ast, child.css, {
482
+ entry: false,
483
+ stylePrefix: stylePrefixOf(child.info),
484
+ order: i,
485
+ tsFile: child.fileName,
486
+ templateFile: child.templateFile,
487
+ }));
488
+ });
489
+ this.smUnits.push({
490
+ fnName: componentFunctionName(entry.className),
491
+ exportKw: 'export default function',
492
+ tsFile: this.smConfig?.entryTsFile,
493
+ templateFile: this.smConfig?.entryTemplateFile,
494
+ classLine: entry.sourceLine,
495
+ });
496
+ const entryBlock = this.generateUnit(entry, ast, css, {
497
+ entry: true,
498
+ stylePrefix: '',
499
+ order: -1,
500
+ hasOutlet: entryUsage.outlet,
501
+ tsFile: this.smConfig?.entryTsFile,
502
+ templateFile: this.smConfig?.entryTemplateFile,
503
+ });
504
+ const importLines = [];
505
+ if (this.reactImports.size) {
506
+ importLines.push(`import { ${[...this.reactImports].sort().join(', ')} } from 'react';`);
507
+ }
508
+ if (this.usedRn.size) {
509
+ const rn = [...this.usedRn].filter((n) => n !== 'StyleSheet').sort();
510
+ const all = this.usedRn.has('StyleSheet') ? [...rn, 'StyleSheet'] : rn;
511
+ if (all.length)
512
+ importLines.push(`import { ${all.join(', ')} } from 'react-native';`);
513
+ }
514
+ if (this.usedUi.size)
515
+ importLines.push(`import { ${[...this.usedUi].sort().join(', ')} } from '@rangular-framework/ui';`);
516
+ if (this.usedRuntime.size) {
517
+ importLines.push(`import { ${[...this.usedRuntime].sort().join(', ')} } from '@rangular-framework/runtime';`);
518
+ }
519
+ // Third-party imports carried from the contributing source files
520
+ // (compile.ts merged them): emitted with the framework lines, one
521
+ // statement per specifier. A binding whose local name this module
522
+ // already defines (a generated class or component function, a
523
+ // module-level const, or one of the framework imports above) is
524
+ // dropped with a GEN_IMPORT_COLLISION warning and a TODO note in
525
+ // its place, never emitted as a duplicate name.
526
+ const reserved = new Set([
527
+ ...this.reactImports,
528
+ ...this.usedRn,
529
+ ...this.usedUi,
530
+ ...this.usedRuntime,
531
+ ...this.rootServices.keys(),
532
+ componentFunctionName(entry.className),
533
+ ...children.map((c) => componentFunctionName(c.info.className)),
534
+ ]);
535
+ for (const p of this.pipesByName.values())
536
+ reserved.add(p.className);
537
+ for (const v of this.pipeInstances.values())
538
+ reserved.add(v);
539
+ for (const c of this.moduleConsts)
540
+ reserved.add(c.name);
541
+ if (registrations.length)
542
+ reserved.add('__container');
543
+ if (navLines.length) {
544
+ reserved.add('__navigator');
545
+ reserved.add('__router');
546
+ }
547
+ if (snackModuleLines.length)
548
+ reserved.add('__snackBar');
549
+ if (this.styles.length)
550
+ reserved.add('styles');
551
+ const carried = this.externalImportLines(reserved);
552
+ importLines.push(...carried.lines);
553
+ const styleBlock = [];
554
+ if (this.styles.length) {
555
+ styleBlock.push('', 'const styles = StyleSheet.create({');
556
+ for (const entry2 of this.styles) {
557
+ styleBlock.push(` ${entry2.key}: ${JSON.stringify(entry2.styleObj)},`);
558
+ }
559
+ styleBlock.push('});');
560
+ }
561
+ const lines = [
562
+ `// Generated by Rangular from ${entry.className} (${forLineComment(entry.selector ?? 'no selector')}). Do not edit by hand.`,
563
+ ...importLines,
564
+ ...carried.notes,
565
+ '',
566
+ ];
567
+ // Literal module constants carried from classless files (0.6.5):
568
+ // emitted verbatim at module level, ahead of the services whose
569
+ // constructors and fields read them.
570
+ for (const c of this.moduleConsts)
571
+ lines.push(c.text);
572
+ if (this.moduleConsts.length)
573
+ lines.push('');
574
+ for (const block of serviceBlocks)
575
+ lines.push(...block, '');
576
+ for (const block of pipeBlocks)
577
+ lines.push(...block, '');
578
+ if (registrations.length)
579
+ lines.push(...registrations, '');
580
+ if (navLines.length)
581
+ lines.push(...navLines, '');
582
+ if (snackModuleLines.length)
583
+ lines.push(...snackModuleLines, '');
584
+ for (const block of childBlocks)
585
+ lines.push(...block, '');
586
+ lines.push(...entryBlock, ...styleBlock, '');
587
+ if (this.smConfig)
588
+ this.finishSourceMap(lines);
589
+ return lines.join('\n');
590
+ }
591
+ /**
592
+ * Render the carried third-party imports as import statements, one
593
+ * per specifier, bindings in first-declared order. A specifier's
594
+ * bindings merge into one statement (a default plus named entries,
595
+ * type-only entries keeping their `type` marker); a namespace
596
+ * binding always takes its own statement, as does every default
597
+ * binding after the first (a statement holds only one). A specifier
598
+ * with only type bindings becomes an `import type` statement, and a
599
+ * specifier declared only for its side effects becomes a bare
600
+ * `import 'x';` (skipped when the specifier also carries bindings,
601
+ * which load the module anyway). Bindings named in `reserved` are
602
+ * dropped with a GEN_IMPORT_COLLISION warning and a TODO note.
603
+ */
604
+ externalImportLines(reserved) {
605
+ const lines = [];
606
+ const notes = [];
607
+ const ext = this.externalImports;
608
+ if (!ext)
609
+ return { lines, notes };
610
+ const kept = [];
611
+ for (const b of ext.bindings) {
612
+ if (reserved.has(b.local)) {
613
+ this.diagnostics.push({
614
+ ...(0, diagnostics_1.warning)('GEN_IMPORT_COLLISION', `Import of '${b.local}' from '${b.from}' in '${b.file}' was dropped: the generated module already defines the name '${b.local}' (a generated class, component function, module-level value or one of its framework imports), and emitting the import would duplicate the name and break the module`, undefined, undefined, `Give the import in '${b.file}' a different local name (an 'as' alias on a named import, or a different name on a default import) and use that name in the code`),
615
+ file: b.file,
616
+ });
617
+ notes.push(`// TODO(Rangular): the import of '${forLineComment(b.local)}' from '${forLineComment(b.from)}' was dropped: the name is already defined by this module, see GEN_IMPORT_COLLISION`);
618
+ continue;
619
+ }
620
+ kept.push(b);
621
+ }
622
+ const quote = (s) => `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
623
+ const specOrder = [];
624
+ const bySpec = new Map();
625
+ for (const b of kept) {
626
+ let arr = bySpec.get(b.from);
627
+ if (!arr) {
628
+ arr = [];
629
+ bySpec.set(b.from, arr);
630
+ specOrder.push(b.from);
631
+ }
632
+ arr.push(b);
633
+ }
634
+ for (const s of ext.sideEffects) {
635
+ if (!bySpec.has(s.from) && !specOrder.includes(s.from))
636
+ specOrder.push(s.from);
637
+ }
638
+ const namedText = (b, asType) => {
639
+ const base = b.imported === b.local ? b.local : `${b.imported} as ${b.local}`;
640
+ return asType ? `type ${base}` : base;
641
+ };
642
+ for (const spec of specOrder) {
643
+ const bs = bySpec.get(spec) ?? [];
644
+ if (!bs.length) {
645
+ lines.push(`import ${quote(spec)};`);
646
+ continue;
647
+ }
648
+ const ns = bs.filter((b) => b.imported === '*');
649
+ const defs = bs.filter((b) => b.imported === 'default');
650
+ const named = bs.filter((b) => b.imported !== '*' && b.imported !== 'default');
651
+ const valueDefs = defs.filter((d) => !d.typeOnly);
652
+ const typeDefs = defs.filter((d) => d.typeOnly);
653
+ const typeNamed = named.filter((b) => b.typeOnly);
654
+ if (valueDefs.length || named.some((b) => !b.typeOnly)) {
655
+ const parts = [];
656
+ if (valueDefs.length)
657
+ parts.push(valueDefs[0].local);
658
+ if (named.length)
659
+ parts.push(`{ ${named.map((b) => namedText(b, b.typeOnly)).join(', ')} }`);
660
+ lines.push(`import ${parts.join(', ')} from ${quote(spec)};`);
661
+ for (const d of valueDefs.slice(1))
662
+ lines.push(`import ${d.local} from ${quote(spec)};`);
663
+ for (const d of typeDefs)
664
+ lines.push(`import type ${d.local} from ${quote(spec)};`);
665
+ }
666
+ else if (typeDefs.length || typeNamed.length) {
667
+ const parts = [];
668
+ if (typeDefs.length)
669
+ parts.push(typeDefs[0].local);
670
+ if (typeNamed.length)
671
+ parts.push(`{ ${typeNamed.map((b) => namedText(b, false)).join(', ')} }`);
672
+ lines.push(`import type ${parts.join(', ')} from ${quote(spec)};`);
673
+ for (const d of typeDefs.slice(1))
674
+ lines.push(`import type ${d.local} from ${quote(spec)};`);
675
+ }
676
+ for (const b of ns) {
677
+ lines.push(`import ${b.typeOnly ? 'type ' : ''}* as ${b.local} from ${quote(spec)};`);
678
+ }
679
+ }
680
+ return { lines, notes };
681
+ }
682
+ /**
683
+ * Source map finalisation (Stage 5): the renderers left marker comment
684
+ * lines (a JSX comment holding "@sm:N") in front of every element's
685
+ * generated lines.
686
+ * Each marker maps the NEXT kept line (the element's JSX start, or its
687
+ * *ngIf wrapper line) back to the element's template position. Marker
688
+ * lines are removed, so the emitted code is unchanged apart from the
689
+ * map itself. Component function starts are found by their signature
690
+ * lines and mapped to the class declarations.
691
+ */
692
+ finishSourceMap(lines) {
693
+ const segments = [];
694
+ const sources = [];
695
+ const indexOf = new Map();
696
+ const idxFor = (file) => {
697
+ let i = indexOf.get(file);
698
+ if (i === undefined) {
699
+ i = sources.length;
700
+ sources.push(file);
701
+ indexOf.set(file, i);
702
+ }
703
+ return i;
704
+ };
705
+ const cleaned = [];
706
+ let pending = [];
707
+ for (const line of lines) {
708
+ const marker = line.match(/@sm:(\d+)@/);
709
+ if (marker) {
710
+ const rec = this.smRecords[Number(marker[1])];
711
+ if (rec)
712
+ pending.push(rec);
713
+ continue;
714
+ }
715
+ const genLine = cleaned.length;
716
+ for (const rec of pending) {
717
+ const lt = line.indexOf('<');
718
+ segments.push({
719
+ generatedLine: genLine,
720
+ generatedColumn: lt >= 0 ? lt : line.length - line.trimStart().length,
721
+ sourceIndex: idxFor(rec.templateFile),
722
+ sourceLine: rec.el.pos.line - 1,
723
+ sourceColumn: rec.el.pos.column - 1,
724
+ });
725
+ }
726
+ pending = [];
727
+ cleaned.push(line);
728
+ }
729
+ let searchFrom = 0;
730
+ for (const unit of this.smUnits) {
731
+ if (!unit.tsFile)
732
+ continue;
733
+ const sig = `${unit.exportKw} ${unit.fnName}(`;
734
+ let found = -1;
735
+ for (let i = searchFrom; i < cleaned.length; i++) {
736
+ if (cleaned[i].startsWith(sig)) {
737
+ found = i;
738
+ break;
739
+ }
740
+ }
741
+ if (found >= 0) {
742
+ segments.push({
743
+ generatedLine: found,
744
+ generatedColumn: 0,
745
+ sourceIndex: idxFor(unit.tsFile),
746
+ sourceLine: (unit.classLine ?? 1) - 1,
747
+ sourceColumn: 0,
748
+ });
749
+ searchFrom = found + 1;
750
+ }
751
+ }
752
+ lines.length = 0;
753
+ lines.push(...cleaned);
754
+ this.sourceMapOut = (0, sourceMap_1.makeSourceMap)(sources, segments, {
755
+ sourcesContent: sources.map((s) => this.smConfig.contents.get(s) ?? null),
756
+ });
757
+ }
758
+ // --- Services (M6) --------------------------------------------------------
759
+ validateDeps(owner, deps, allowSnackBar = false) {
760
+ for (const dep of deps) {
761
+ if (dep.typeName === HTTP_CLIENT || dep.typeName === 'FormBuilder' || this.rootServices.has(dep.typeName))
762
+ continue;
763
+ if (this.routingActive && (dep.typeName === 'Router' || dep.typeName === 'ActivatedRoute'))
764
+ continue;
765
+ // SnackBar is a component-level built-in (Stage 10): components
766
+ // receive the module-level instance; a service injecting it has
767
+ // no host to render through, so it stays an unknown token there.
768
+ if (allowSnackBar && dep.typeName === 'SnackBar')
769
+ continue;
770
+ this.diagnostics.push((0, diagnostics_1.error)('DI_UNKNOWN_TOKEN', `${owner}: no provider for '${dep.typeName}' (injected as '${dep.propertyName}'), it is not an @Injectable({ providedIn: 'root' }) service in this compilation and not a built-in token`, undefined, undefined, `Make '${dep.typeName}' an @Injectable({ providedIn: 'root' }) class and import it from the component file (imports are followed transitively), or inject a built-in: HttpClient, FormBuilder, Router / ActivatedRoute in a routed app, or SnackBar in a component`));
771
+ }
772
+ }
773
+ generateService(svc) {
774
+ this.usedRuntime.add('ReactiveService');
775
+ this.validateDeps(`Service ${svc.className}`, svc.constructorDeps);
776
+ const lines = [`export class ${svc.className} extends ReactiveService {`];
777
+ for (const field of svc.fields) {
778
+ if (field.initializer && isLiteralInitializer(field.initializer)) {
779
+ lines.push(` ${field.name}${field.type ? `: ${field.type}` : ''} = ${field.initializer};`);
780
+ }
781
+ else if (field.initializer && (0, formInit_1.isSignalInitializer)(field.initializer)) {
782
+ // Signals adoption: a service is a real class, so a signal or
783
+ // computed field is emitted verbatim as a class field; its
784
+ // arrow bodies keep this.<field> reads, which are correct
785
+ // against the instance. The runtime name joins the import.
786
+ this.usedRuntime.add((0, formInit_1.signalKindOf)(field.initializer) === 'computed' ? 'computed' : 'signal');
787
+ lines.push(` ${field.name}${field.type ? `: ${field.type}` : ''} = ${field.initializer};`);
788
+ }
789
+ else if (field.initializer) {
790
+ this.diagnostics.push((0, diagnostics_1.warning)('GEN_FIELD', `Service '${svc.className}': field '${field.name}' has a non-literal initializer; not hoisted`, undefined, undefined, `Initialise '${field.name}' with a literal (including arrays/objects of literals) or assign it in the constructor`));
791
+ lines.push(` // TODO: field '${forLineComment(field.name)}' has a non-literal initializer (${forLineComment(field.initializer)}), not hoisted; wire it up manually for now.`);
792
+ }
793
+ else if (field.type) {
794
+ lines.push(` ${field.name}: ${field.type};`);
795
+ }
796
+ }
797
+ if (svc.constructorDeps.length || svc.constructorBody) {
798
+ const params = svc.constructorDeps.map((d) => `private ${d.propertyName}: ${d.typeName}`).join(', ');
799
+ lines.push(` constructor(${params}) {`);
800
+ lines.push(' super();');
801
+ if (svc.constructorBody) {
802
+ const host = {
803
+ fields: svc.fields,
804
+ methods: svc.methods,
805
+ methodDetails: [{
806
+ name: 'constructor',
807
+ params: svc.constructorDeps.map((d) => ({
808
+ name: d.propertyName,
809
+ text: `private ${d.propertyName}: ${d.typeName}`,
810
+ })),
811
+ body: svc.constructorBody,
812
+ }],
813
+ };
814
+ const { methods, diagnostics } = (0, methods_1.translateMethods)(host, 'service', new Set(svc.fields.map((f) => f.name)));
815
+ this.diagnostics.push(...diagnostics);
816
+ for (const line of methods[0]?.lines ?? [])
817
+ lines.push(line ? ` ${line}` : line);
818
+ }
819
+ lines.push(' }');
820
+ }
821
+ const { methods, diagnostics } = (0, methods_1.translateMethods)(svc, 'service', new Set(svc.fields.map((f) => f.name)));
822
+ this.diagnostics.push(...diagnostics);
823
+ // Signals adoption: an effect created by a service (a root
824
+ // singleton) lives for the app's life, which matches Angular; it
825
+ // only needs the runtime name in the file's import.
826
+ if (svc.methodDetails.some((m) => m.body && /\beffect\s*\(/.test(m.body)) || (svc.constructorBody && /\beffect\s*\(/.test(svc.constructorBody))) {
827
+ this.usedRuntime.add('effect');
828
+ }
829
+ for (const m of methods) {
830
+ lines.push(` ${m.name}(${m.paramTexts.join(', ')}) {`);
831
+ for (const line of m.lines)
832
+ lines.push(line ? ` ${line}` : line);
833
+ lines.push(' }');
834
+ }
835
+ lines.push('}');
836
+ return lines;
837
+ }
838
+ /**
839
+ * Emit one custom @Pipe class (Stage 12): a plain class (no
840
+ * ReactiveService base, no container), its literal fields, its
841
+ * constructor when it has one, and its methods translated in 'pipe'
842
+ * mode (this. survives, no notify). One shared instance follows:
843
+ * pipes are pure by convention, exactly Angular's assumption.
844
+ */
845
+ generatePipeClass(pipe) {
846
+ const lines = [`export class ${pipe.className} {`];
847
+ for (const field of pipe.fields) {
848
+ if (field.initializer && isLiteralInitializer(field.initializer)) {
849
+ lines.push(` ${field.name}${field.type ? `: ${field.type}` : ''} = ${field.initializer};`);
850
+ }
851
+ else if (field.initializer) {
852
+ this.diagnostics.push((0, diagnostics_1.warning)('GEN_FIELD', `Pipe '${pipe.className}': field '${field.name}' has a non-literal initializer; not hoisted`, undefined, undefined, `Initialise '${field.name}' with a literal (including arrays/objects of literals) or assign it in the constructor`));
853
+ lines.push(` // TODO: field '${forLineComment(field.name)}' has a non-literal initializer (${forLineComment(field.initializer)}), not hoisted; wire it up manually for now.`);
854
+ }
855
+ else if (field.type) {
856
+ lines.push(` ${field.name}: ${field.type};`);
857
+ }
858
+ }
859
+ if (pipe.constructorDeps.length || pipe.constructorBody) {
860
+ const params = pipe.constructorDeps.map((d) => `private ${d.propertyName}: ${d.typeName}`).join(', ');
861
+ lines.push(` constructor(${params}) {`);
862
+ if (pipe.constructorBody) {
863
+ const host = {
864
+ fields: pipe.fields,
865
+ methods: pipe.methods,
866
+ methodDetails: [{
867
+ name: 'constructor',
868
+ params: pipe.constructorDeps.map((d) => ({
869
+ name: d.propertyName,
870
+ text: `private ${d.propertyName}: ${d.typeName}`,
871
+ })),
872
+ body: pipe.constructorBody,
873
+ }],
874
+ };
875
+ const { methods, diagnostics } = (0, methods_1.translateMethods)(host, 'pipe', new Set(pipe.fields.map((f) => f.name)));
876
+ this.diagnostics.push(...diagnostics);
877
+ for (const line of methods[0]?.lines ?? [])
878
+ lines.push(line ? ` ${line}` : line);
879
+ }
880
+ lines.push(' }');
881
+ }
882
+ const { methods, diagnostics } = (0, methods_1.translateMethods)(pipe, 'pipe', new Set(pipe.fields.map((f) => f.name)));
883
+ this.diagnostics.push(...diagnostics);
884
+ for (const m of methods) {
885
+ lines.push(` ${m.name}(${m.paramTexts.join(', ')}) {`);
886
+ for (const line of m.lines)
887
+ lines.push(line ? ` ${line}` : line);
888
+ lines.push(' }');
889
+ }
890
+ lines.push('}');
891
+ const instance = this.pipeInstanceVar(pipe.pipeName);
892
+ if (instance) {
893
+ if (pipe.constructorDeps.length) {
894
+ // A pipe with constructor dependencies cannot be instantiated
895
+ // honestly in this version (Angular would inject services);
896
+ // the error names it instead of emitting a silent wrong call.
897
+ this.diagnostics.push((0, diagnostics_1.error)('DI_UNKNOWN_TOKEN', `Pipe '${pipe.className}': constructor dependencies (${pipe.constructorDeps.map((d) => d.typeName).join(', ')}) are not wired for @Pipe classes in this version; the shared instance is created with no arguments`, undefined, undefined, 'Keep @Pipe classes dependency-free (pure transforms of their arguments), or move the shared logic into an @Injectable service the component injects'));
898
+ lines.push(`const ${instance} = new ${pipe.className}(); // TODO(Rangular): pipe constructor dependencies are not wired, see DI_UNKNOWN_TOKEN`);
899
+ }
900
+ else {
901
+ lines.push(`const ${instance} = new ${pipe.className}();`);
902
+ }
903
+ }
904
+ return lines;
905
+ }
906
+ /** Container registrations, dependency-ordered (a service's deps register first). */
907
+ registrationLines(entry, children) {
908
+ const needsHttp = [entry, ...children.map((c) => c.info), ...this.allServices]
909
+ .some((host) => (host.constructorDeps ?? []).some((d) => d.typeName === HTTP_CLIENT));
910
+ const needsFormBuilder = [entry, ...children.map((c) => c.info), ...this.allServices]
911
+ .some((host) => (host.constructorDeps ?? []).some((d) => d.typeName === 'FormBuilder'));
912
+ if (!this.rootServices.size && !needsHttp && !needsFormBuilder)
913
+ return [];
914
+ this.usedRuntime.add('Container');
915
+ if (needsHttp)
916
+ this.usedRuntime.add(HTTP_CLIENT);
917
+ if (needsFormBuilder)
918
+ this.usedRuntime.add('FormBuilder');
919
+ const order = [];
920
+ const done = new Set();
921
+ const visiting = new Set();
922
+ let cycleReported = false;
923
+ const visit = (name) => {
924
+ if (done.has(name))
925
+ return;
926
+ if (visiting.has(name)) {
927
+ if (!cycleReported) {
928
+ cycleReported = true;
929
+ this.diagnostics.push((0, diagnostics_1.error)('DI_CYCLE', `Service dependency cycle detected at '${name}', registrations cannot be ordered`, undefined, undefined, 'Break the cycle: have one service stop injecting the other (pass the value through a method call instead)'));
930
+ }
931
+ return;
932
+ }
933
+ visiting.add(name);
934
+ const svc = this.rootServices.get(name);
935
+ if (svc) {
936
+ for (const dep of svc.constructorDeps) {
937
+ if (this.rootServices.has(dep.typeName))
938
+ visit(dep.typeName);
939
+ }
940
+ }
941
+ visiting.delete(name);
942
+ done.add(name);
943
+ order.push(name);
944
+ };
945
+ for (const name of this.rootServices.keys())
946
+ visit(name);
947
+ const lines = ['const __container = new Container();'];
948
+ // Built-ins register first: HttpClient has no dependencies, and a root
949
+ // service may inject it, which resolves during that service's own
950
+ // registration line. Registering it after the services made such an
951
+ // app crash at startup with "no provider registered for token".
952
+ if (needsHttp)
953
+ lines.push(`__container.register(HttpClient, new HttpClient());`);
954
+ if (needsFormBuilder)
955
+ lines.push(`__container.register(FormBuilder, new FormBuilder());`);
956
+ for (const name of order) {
957
+ const svc = this.rootServices.get(name);
958
+ const args = svc.constructorDeps.map((d) => {
959
+ if (d.typeName === HTTP_CLIENT)
960
+ return `__container.get<HttpClient>(HttpClient)`;
961
+ if (d.typeName === 'FormBuilder')
962
+ return `__container.get<FormBuilder>(FormBuilder)`;
963
+ if (this.rootServices.has(d.typeName))
964
+ return `__container.get<${d.typeName}>(${d.typeName})`;
965
+ return 'undefined';
966
+ });
967
+ lines.push(`__container.register(${name}, new ${name}(${args.join(', ')}));`);
968
+ }
969
+ return lines;
970
+ }
971
+ // --- Components (M3/M4 + M5/M6) --------------------------------------------
972
+ generateUnit(component, ast, css, opts) {
973
+ const diagnostics = this.diagnostics;
974
+ diagnostics.push(...css.diagnostics);
975
+ // Controls have declaration children (Stage 6): option only belongs
976
+ // in switcher, radio only belongs in radio-group, and each group
977
+ // accepts only its own declaration element.
978
+ const validateControlNesting = (nodes, parentTag) => {
979
+ for (const node of nodes) {
980
+ if (node.type !== 'element')
981
+ continue;
982
+ const tag = node.tag.toLowerCase();
983
+ if (tag === 'option' && parentTag !== 'switcher' && parentTag !== 'radio-group' && parentTag !== 'select') {
984
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', '<option> is outside <switcher>; it declares one segment and has no meaning on its own', node.pos.line, node.pos.column, 'Move the option inside a switcher: <switcher [value]="view" (change)="onView($event)"><option value="list">List</option></switcher>, or inside a select: <select [value]="city" (change)="onCity($event)"><option value="ktm">Kathmandu</option></select>'));
985
+ }
986
+ // Stage 14 declarations: step belongs in stepper, menu-item
987
+ // belongs in menu, grid-tile belongs in grid-list, tree-node
988
+ // belongs in tree or in another tree-node; and stepper, menu,
989
+ // grid-list and tree accept only their own declarations (a
990
+ // menu also takes dividers between its items).
991
+ if (tag === 'step' && parentTag !== 'stepper') {
992
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', '<step> is outside <stepper>; it declares one step page and has no meaning on its own', node.pos.line, node.pos.column, 'Move the step inside a stepper: <stepper><step label="Cart">...</step></stepper>'));
993
+ }
994
+ if (parentTag === 'stepper' && tag !== 'step') {
995
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', `<${node.tag}> is inside <stepper>; only <step> declarations belong there`, node.pos.line, node.pos.column, 'Replace it with <step label="...">...</step>, or move the element outside the stepper'));
996
+ }
997
+ if (tag === 'menu-item' && parentTag !== 'menu') {
998
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', '<menu-item> is outside <menu>; it declares one menu row and has no meaning on its own', node.pos.line, node.pos.column, 'Move the item inside a menu: <menu [open]="menuOpen" (close)="closeMenu()"><menu-item (click)="rename()">Rename</menu-item></menu>'));
999
+ }
1000
+ if (parentTag === 'menu' && tag !== 'menu-item' && tag !== 'divider') {
1001
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', `<${node.tag}> is inside <menu>; only <menu-item> declarations (and <divider> between them) belong there`, node.pos.line, node.pos.column, 'Replace it with <menu-item (click)="...">Label</menu-item>, or move the element outside the menu'));
1002
+ }
1003
+ if (tag === 'grid-tile' && parentTag !== 'grid-list') {
1004
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', '<grid-tile> is outside <grid-list>; it declares one grid cell and has no meaning on its own', node.pos.line, node.pos.column, 'Move the tile inside a grid list: <grid-list cols="2"><grid-tile>...</grid-tile></grid-list>'));
1005
+ }
1006
+ if (parentTag === 'grid-list' && tag !== 'grid-tile') {
1007
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', `<${node.tag}> is inside <grid-list>; only <grid-tile> declarations belong there`, node.pos.line, node.pos.column, 'Replace it with <grid-tile>...</grid-tile>, or move the element outside the grid list'));
1008
+ }
1009
+ if (tag === 'tree-node' && parentTag !== 'tree' && parentTag !== 'tree-node') {
1010
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', '<tree-node> is outside <tree>; it declares one tree row and has no meaning on its own', node.pos.line, node.pos.column, 'Move the node inside a tree: <tree><tree-node label="Inbox"></tree-node></tree>'));
1011
+ }
1012
+ if (parentTag === 'tree' && tag !== 'tree-node') {
1013
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', `<${node.tag}> is inside <tree>; only <tree-node> declarations belong there`, node.pos.line, node.pos.column, 'Replace it with <tree-node label="...">...</tree-node>, or move the element outside the tree'));
1014
+ }
1015
+ if (parentTag === 'select' && tag !== 'option') {
1016
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', `<${node.tag}> is inside <select>; only <option> declarations belong there`, node.pos.line, node.pos.column, 'Replace it with <option value="...">Label</option>, or move the element outside the select'));
1017
+ }
1018
+ // Stage 15 declarations: nav-item belongs in bottom-nav,
1019
+ // row-action belongs in row, timeline-item belongs in
1020
+ // timeline, avatar belongs in avatar-group (when grouped),
1021
+ // crumb belongs in breadcrumbs; and bottom-nav, timeline,
1022
+ // avatar-group and breadcrumbs accept only their own
1023
+ // declarations.
1024
+ if (tag === 'nav-item' && parentTag !== 'bottom-nav') {
1025
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', '<nav-item> is outside <bottom-nav>; it declares one bottom navigation destination and has no meaning on its own', node.pos.line, node.pos.column, 'Move the item inside a bottom navigation bar: <bottom-nav><nav-item icon="home" label="Home" routerLink="/home"></nav-item></bottom-nav>'));
1026
+ }
1027
+ if (parentTag === 'bottom-nav' && tag !== 'nav-item') {
1028
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', `<${node.tag}> is inside <bottom-nav>; only <nav-item> declarations belong there`, node.pos.line, node.pos.column, 'Replace it with <nav-item icon="..." label="..."></nav-item>, or move the element outside the bottom navigation bar'));
1029
+ }
1030
+ if (tag === 'row-action' && parentTag !== 'row') {
1031
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', '<row-action> is outside <row>; it declares one swipe action for its row and has no meaning on its own', node.pos.line, node.pos.column, 'Move the action inside its row: <row title="Mail"><row-action icon="delete" (click)="remove()">Delete</row-action></row>'));
1032
+ }
1033
+ if (tag === 'timeline-item' && parentTag !== 'timeline') {
1034
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', '<timeline-item> is outside <timeline>; it declares one event on the rail and has no meaning on its own', node.pos.line, node.pos.column, 'Move the item inside a timeline: <timeline><timeline-item title="Ordered">...</timeline-item></timeline>'));
1035
+ }
1036
+ if (parentTag === 'timeline' && tag !== 'timeline-item') {
1037
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', `<${node.tag}> is inside <timeline>; only <timeline-item> declarations belong there`, node.pos.line, node.pos.column, 'Replace it with <timeline-item title="...">...</timeline-item>, or move the element outside the timeline'));
1038
+ }
1039
+ if (parentTag === 'avatar-group' && tag !== 'avatar') {
1040
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', `<${node.tag}> is inside <avatar-group>; only <avatar> declarations belong there`, node.pos.line, node.pos.column, 'Replace it with <avatar text="..."></avatar>, or move the element outside the avatar group'));
1041
+ }
1042
+ if (tag === 'crumb' && parentTag !== 'breadcrumbs') {
1043
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', '<crumb> is outside <breadcrumbs>; it declares one step of the path and has no meaning on its own', node.pos.line, node.pos.column, 'Move the crumb inside breadcrumbs: <breadcrumbs><crumb routerLink="/settings">Settings</crumb><crumb>Profile</crumb></breadcrumbs>'));
1044
+ }
1045
+ if (parentTag === 'breadcrumbs' && tag !== 'crumb') {
1046
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', `<${node.tag}> is inside <breadcrumbs>; only <crumb> declarations belong there`, node.pos.line, node.pos.column, 'Replace it with <crumb>...</crumb>, or move the element outside the breadcrumbs'));
1047
+ }
1048
+ if (tag === 'radio' && parentTag !== 'radio-group' && parentTag !== 'switcher') {
1049
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', '<radio> is outside <radio-group>; it declares one choice and has no meaning on its own', node.pos.line, node.pos.column, 'Move the radio inside a radio group: <radio-group [value]="size" (change)="onSize($event)"><radio value="m">Medium</radio></radio-group>'));
1050
+ }
1051
+ if (parentTag === 'switcher' && tag !== 'option') {
1052
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', `<${node.tag}> is inside <switcher>; only <option> declarations belong there`, node.pos.line, node.pos.column, 'Replace it with <option value="...">Label</option>, or move the element outside the switcher'));
1053
+ }
1054
+ if (parentTag === 'radio-group' && tag !== 'radio') {
1055
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', `<${node.tag}> is inside <radio-group>; only <radio> declarations belong there`, node.pos.line, node.pos.column, 'Replace it with <radio value="...">Label</radio>, or move the element outside the radio group'));
1056
+ }
1057
+ // Data display declarations (Stage 11): tab belongs in tabs,
1058
+ // column belongs in table, and tabs, table and accordion each
1059
+ // accept only their own declaration element. A panel outside
1060
+ // an accordion is fine (panels work standalone); a tab or a
1061
+ // column outside its group declares nothing and renders
1062
+ // nothing, so the author hears about it.
1063
+ if (tag === 'tab' && parentTag !== 'tabs') {
1064
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', '<tab> is outside <tabs>; it declares one tab page and has no meaning on its own', node.pos.line, node.pos.column, 'Move the tab inside tabs: <tabs [index]="tabIndex" (change)="onTab($event)"><tab label="Overview">...</tab></tabs>'));
1065
+ }
1066
+ if (tag === 'column' && parentTag !== 'table') {
1067
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', '<column> is outside <table>; it declares one table column and has no meaning on its own', node.pos.line, node.pos.column, 'Move the column inside a table: <table [data]="rows"><column name="sender" header="From"></column></table>'));
1068
+ }
1069
+ if (parentTag === 'tabs' && tag !== 'tab') {
1070
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', `<${node.tag}> is inside <tabs>; only <tab> declarations belong there`, node.pos.line, node.pos.column, 'Replace it with <tab label="...">...</tab>, or move the element outside the tabs'));
1071
+ }
1072
+ if (parentTag === 'table' && tag !== 'column') {
1073
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', `<${node.tag}> is inside <table>; only <column> declarations belong there`, node.pos.line, node.pos.column, 'Replace it with <column name="..." header="..."></column>, or move the element outside the table'));
1074
+ }
1075
+ if (parentTag === 'accordion' && tag !== 'panel') {
1076
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CONTROL_NESTING', `<${node.tag}> is inside <accordion>; only <panel> declarations belong there`, node.pos.line, node.pos.column, 'Replace it with <panel title="...">...</panel>, or move the element outside the accordion'));
1077
+ }
1078
+ validateControlNesting(node.children, tag);
1079
+ }
1080
+ };
1081
+ // Verification fortification (2026-11-26): two author mistakes that
1082
+ // used to stay silent until runtime are compile errors now. A template
1083
+ // event binding that names a method the component does not have fails
1084
+ // here (TPL_HANDLER) instead of at tap time, and an attribute or
1085
+ // binding that is not one of the element's props fails here
1086
+ // (GEN_UNKNOWN_PROP) instead of passing through to be ignored.
1087
+ const methodNames = new Set(component.methods);
1088
+ const fieldNames = new Set(component.fields.map((f) => f.name));
1089
+ const nearProp = (name, allowed) => {
1090
+ let best;
1091
+ let bestDist = 3;
1092
+ for (const cand of allowed) {
1093
+ let d = Math.abs(cand.length - name.length);
1094
+ for (let i = 0; i < Math.min(cand.length, name.length); i++)
1095
+ if (cand[i] !== name[i])
1096
+ d++;
1097
+ if (d < bestDist) {
1098
+ bestDist = d;
1099
+ best = cand;
1100
+ }
1101
+ }
1102
+ return best;
1103
+ };
1104
+ const directiveNames = new Set();
1105
+ for (const [attr, entry3] of this.directivesByAttr) {
1106
+ directiveNames.add(attr);
1107
+ for (const inp of entry3.info.inputs)
1108
+ directiveNames.add(inp.name);
1109
+ }
1110
+ // List scroll contracts in this template (runtime prevention
1111
+ // round, 2026-11-29, points 3 and 4): a screen lends its
1112
+ // refresh handling to one list and its end-reached handling to
1113
+ // one list; the counters name the second list that declares
1114
+ // the same contract in one template.
1115
+ const listContractsSeen = { refresh: 0, endReached: 0 };
1116
+ const validateBindings = (nodes, screenDepth = 0) => {
1117
+ for (const node of nodes) {
1118
+ if (node.type !== 'element')
1119
+ continue;
1120
+ // A screen inside a screen (nested-screen round,
1121
+ // 2026-11-27): the runtime renders it embedded, a flat
1122
+ // themed region with no scroller, which is a supported
1123
+ // shape for themed regions but a silent surprise when the
1124
+ // author meant a page. Name it, as a warning: the shape
1125
+ // is legal, the lost scroll settings are the cost.
1126
+ if (node.tag.toLowerCase() === 'screen' && screenDepth > 0) {
1127
+ diagnostics.push((0, diagnostics_1.warning)('TPL_NESTED_SCREEN', `This <screen> sits inside another <screen>; it renders embedded, as a flat themed region with no scroller of its own, and its scroll, refresh and end-reached settings have no effect`, node.pos.line, node.pos.column, `Keep it if a themed region is what you want; a nested screen keeps its theme. If it was meant to be its own page, move it to the root of a component template`));
1128
+ }
1129
+ for (const ev of node.eventBindings) {
1130
+ const expr = ev.expression.trim();
1131
+ const m = /^([A-Za-z_$][\w$]*)\s*\(/.exec(expr) ?? /^([A-Za-z_$][\w$]*)$/.exec(expr);
1132
+ if (m && !methodNames.has(m[1]) && !fieldNames.has(m[1])) {
1133
+ diagnostics.push((0, diagnostics_1.error)('TPL_HANDLER', `(${ev.name})="${ev.expression}" names method '${m[1]}', which ${component.className} does not have; the handler would fail when the event fires`, node.pos.line, node.pos.column, `Add a method named ${m[1]}() to ${component.className}, or change the binding to one of its methods: ${component.methods.slice(0, 6).join(', ') || '(none yet)'}`));
1134
+ }
1135
+ }
1136
+ const tag = node.tag.toLowerCase();
1137
+ const mapping = exports.TAG_MAP[tag];
1138
+ if (tag === 'list') {
1139
+ const events = new Set(node.eventBindings.map((e) => e.name));
1140
+ const hasRefresh = events.has('refresh');
1141
+ const hasEnd = events.has('endReached');
1142
+ if (hasRefresh && hasEnd) {
1143
+ diagnostics.push((0, diagnostics_1.warning)('GEN_LIST_CONTRACT_CLASH', `This <list> declares both (refresh) and (endReached); a list keeps only one scroll contract, so its pull-to-refresh never engages and only the end-reached handler runs`, node.pos.line, node.pos.column, `Split the work: one list with (refresh), or one list with (endReached), or move one contract to the <screen> element`));
1144
+ }
1145
+ if (hasRefresh) {
1146
+ listContractsSeen.refresh += 1;
1147
+ if (listContractsSeen.refresh === 2) {
1148
+ diagnostics.push((0, diagnostics_1.warning)('GEN_LIST_DUPLICATE', `A second <list> in this template declares (refresh); a screen lends its pull-to-refresh to one list, and the last list to register wins, so the first list's pull silently stops working`, node.pos.line, node.pos.column, `Keep one (refresh) list per page, or put the second list on its own page`));
1149
+ }
1150
+ }
1151
+ if (hasEnd) {
1152
+ listContractsSeen.endReached += 1;
1153
+ if (listContractsSeen.endReached === 2) {
1154
+ diagnostics.push((0, diagnostics_1.warning)('GEN_LIST_DUPLICATE', `A second <list> in this template declares (endReached); a screen lends its end-reached handling to one list, and the last list to register wins, so the first list's paging silently stops working`, node.pos.line, node.pos.column, `Keep one (endReached) list per page, or put the second list on its own page`));
1155
+ }
1156
+ }
1157
+ }
1158
+ if (mapping?.fromUi && propTable_1.ELEMENT_PROPS[tag]) {
1159
+ const allowed = [...propTable_1.ELEMENT_PROPS[tag], ...(propTable_1.ELEMENT_EXTRA_PROPS[tag] ?? []), ...propTable_1.GLOBAL_ATTRS, ...propTable_1.CODEGEN_ATTRS];
1160
+ const allowedSet = new Set(allowed);
1161
+ const names = [...Object.keys(node.attrs), ...node.booleanAttrs, ...node.propBindings.map((b) => b.name), ...node.twoWayBindings.map((b) => b.name)];
1162
+ for (const name of names) {
1163
+ if (name.startsWith('data-') || name.startsWith('aria-'))
1164
+ continue;
1165
+ if (name.startsWith('class.'))
1166
+ continue; // [class.x] toggles: GEN_CLASS_BINDING judges the class name
1167
+ if (directiveNames.has(name))
1168
+ continue;
1169
+ if (allowedSet.has(name))
1170
+ continue;
1171
+ const near = nearProp(name, allowed);
1172
+ diagnostics.push((0, diagnostics_1.error)('GEN_UNKNOWN_PROP', `'${name}' is not a prop of <${tag}>; it would be passed through and ignored`, node.pos.line, node.pos.column, near ? `Did you mean '${near}'?` : `See the catalog entry for <${tag}> for the props it accepts`));
1173
+ }
1174
+ }
1175
+ if (!mapping) {
1176
+ // A child component's props (runtime prevention round,
1177
+ // 2026-11-29, point 8): the fortification checked the
1178
+ // built-in elements only, so a misspelled or invented
1179
+ // binding on a child component compiled clean and the
1180
+ // child received nothing for it. The child's declared
1181
+ // @Input fields are the allowed set, the same rule as
1182
+ // the built-in elements, under the same code.
1183
+ const childInfo = this.childBySelector.get(node.tag);
1184
+ if (childInfo) {
1185
+ const allowed = [...childInfo.fields.filter((f) => f.isInput).map((f) => f.name), ...propTable_1.GLOBAL_ATTRS, ...propTable_1.CODEGEN_ATTRS];
1186
+ const allowedSet = new Set(allowed);
1187
+ const names = [...Object.keys(node.attrs), ...node.booleanAttrs, ...node.propBindings.map((b) => b.name), ...node.twoWayBindings.map((b) => b.name)];
1188
+ for (const name of names) {
1189
+ if (name.startsWith('data-') || name.startsWith('aria-'))
1190
+ continue;
1191
+ if (name.startsWith('class.'))
1192
+ continue;
1193
+ if (directiveNames.has(name))
1194
+ continue;
1195
+ if (allowedSet.has(name))
1196
+ continue;
1197
+ const near = nearProp(name, allowed);
1198
+ diagnostics.push((0, diagnostics_1.error)('GEN_UNKNOWN_PROP', `'${name}' is not an @Input of <${node.tag}> (${childInfo.className}); it would be passed through and ignored, and the child receives nothing for it`, node.pos.line, node.pos.column, near ? `Did you mean '${near}'?` : `See the @Input fields of ${childInfo.className} for the props it accepts`));
1199
+ }
1200
+ }
1201
+ }
1202
+ validateBindings(node.children, node.tag.toLowerCase() === 'screen' ? screenDepth + 1 : screenDepth);
1203
+ }
1204
+ };
1205
+ validateBindings(ast.children);
1206
+ validateControlNesting(ast.children);
1207
+ // Overlays (Stage 10): a <sheet> or <dialog> is driven by its
1208
+ // [open] binding; without one it can only ever render statically
1209
+ // open (the primitives treat a missing open as shown), so the
1210
+ // author hears about it instead of wondering why it never closes.
1211
+ const validateOverlays = (nodes) => {
1212
+ for (const node of nodes) {
1213
+ if (node.type !== 'element')
1214
+ continue;
1215
+ const tag = node.tag.toLowerCase();
1216
+ if ((tag === 'sheet' || tag === 'dialog' || tag === 'menu' || tag === 'drawer' || tag === 'lightbox')
1217
+ && node.attrs['open'] === undefined
1218
+ && !node.booleanAttrs.includes('open')
1219
+ && !node.propBindings.some((b) => b.name === 'open')) {
1220
+ diagnostics.push((0, diagnostics_1.warning)('GEN_OVERLAY_OPEN', `<${tag}> has no [open] binding; it renders statically open and cannot be opened or closed from the component`, node.pos.line, node.pos.column, `Bind it to a boolean field and flip the field in methods: <${tag} [open]="confirmOpen" (close)="closeConfirm()"> with closeConfirm() { this.confirmOpen = false; }`));
1221
+ }
1222
+ validateOverlays(node.children);
1223
+ }
1224
+ };
1225
+ validateOverlays(ast.children);
1226
+ // Stage 15 static checks, the picker mode pattern: a chart
1227
+ // type outside the three the engine draws is an error (the
1228
+ // primitive would otherwise silently draw bars), and an OTP
1229
+ // length outside the 4 to 8 the control supports warns and
1230
+ // clamps in the primitive, so the author hears about it here.
1231
+ const validateStage15 = (nodes) => {
1232
+ for (const node of nodes) {
1233
+ if (node.type !== 'element')
1234
+ continue;
1235
+ const tag = node.tag.toLowerCase();
1236
+ if (tag === 'chart' && node.attrs['type'] !== undefined
1237
+ && !chart_1.CHART_TYPES.includes(node.attrs['type'])) {
1238
+ diagnostics.push((0, diagnostics_1.error)('GEN_CHART_TYPE', `<chart> type '${node.attrs['type']}' is not a chart type; the chart would draw bars instead`, node.pos.line, node.pos.column, 'Use type="bar", type="line" or type="pie" (bar is the default and can be omitted)'));
1239
+ }
1240
+ if (tag === 'otp' && node.attrs['length'] !== undefined) {
1241
+ const raw = Number(node.attrs['length']);
1242
+ if (!Number.isFinite(raw) || raw < 4 || raw > 8) {
1243
+ diagnostics.push((0, diagnostics_1.warning)('GEN_OTP_LENGTH', `<otp> length '${node.attrs['length']}' is outside the supported 4 to 8; the generated control uses the nearest of the two`, node.pos.line, node.pos.column, 'Use length="4", length="6" or length="8" (6 is the default); the control clamps anything else into 4 to 8'));
1244
+ }
1245
+ }
1246
+ validateStage15(node.children);
1247
+ }
1248
+ };
1249
+ validateStage15(ast.children);
1250
+ // Chips (Stage 11): a chip's leading icon names the Stage 7 icon
1251
+ // set, so a static icon attribute is validated exactly like an
1252
+ // <icon> name (GEN_ICON_UNKNOWN, the JSON form carries the valid
1253
+ // list). A [icon] binding passes through unchecked, its value is
1254
+ // only known at runtime.
1255
+ const validateChipIcons = (nodes) => {
1256
+ for (const node of nodes) {
1257
+ if (node.type !== 'element')
1258
+ continue;
1259
+ if (node.tag.toLowerCase() === 'chip' && node.attrs['icon'] !== undefined
1260
+ && !(node.attrs['icon'] in icons_1.ICON_PATHS) && !(node.attrs['icon'] in icons_1.BRAND_MARKS)) {
1261
+ diagnostics.push({
1262
+ severity: 'error',
1263
+ code: 'GEN_ICON_UNKNOWN',
1264
+ message: `Unknown icon name '${node.attrs['icon']}' in a <chip> icon attribute: it is not in the Rangular icon set`,
1265
+ line: node.pos.line,
1266
+ column: node.pos.column,
1267
+ fix: 'Use one of the names listed under Icons in catalog.md, e.g. <chip icon="star">Starred</chip>',
1268
+ validIcons: icons_1.ICON_NAMES,
1269
+ });
1270
+ }
1271
+ if (node.tag.toLowerCase() === 'icon-button' && node.attrs['name'] !== undefined
1272
+ && !(node.attrs['name'] in icons_1.ICON_PATHS) && !(node.attrs['name'] in icons_1.BRAND_MARKS)) {
1273
+ diagnostics.push({
1274
+ severity: 'error',
1275
+ code: 'GEN_ICON_UNKNOWN',
1276
+ message: `Unknown icon name '${node.attrs['name']}' in an <icon-button> name attribute: it is not in the Rangular icon set`,
1277
+ line: node.pos.line,
1278
+ column: node.pos.column,
1279
+ fix: 'Use one of the names listed under Icons in catalog.md, e.g. <icon-button name="chevron-left" routerLink="/home"></icon-button>',
1280
+ validIcons: icons_1.ICON_NAMES,
1281
+ });
1282
+ }
1283
+ validateChipIcons(node.children);
1284
+ }
1285
+ };
1286
+ validateChipIcons(ast.children);
1287
+ // --- Forms analysis (Stage 8) --------------------------------------------
1288
+ // Reactive form fields: initialised with new FormGroup(...) or
1289
+ // new FormControl(...); they are stable instances, never state.
1290
+ const formFields = new Map();
1291
+ for (const field of component.fields) {
1292
+ if (field.isInput || field.isOutput)
1293
+ continue;
1294
+ if ((0, formInit_1.isFormInitializer)(field.initializer, (0, formInit_1.builderDepsOf)(component))) {
1295
+ formFields.set(field.name, (0, formInit_1.analyzeFormInitializer)(field.initializer, (0, formInit_1.builderDepsOf)(component)));
1296
+ }
1297
+ }
1298
+ // Stream fields (RxJS adoption): a field initialised with
1299
+ // new Subject(...) (or BehaviorSubject, ReplaySubject or
1300
+ // AsyncSubject, imported from 'rxjs') is one stable instance
1301
+ // like a form field. It is held in a ref below, never state and
1302
+ // never a per-render const, or every render would replace the
1303
+ // subject and orphan its subscribers.
1304
+ const streamFields = new Set();
1305
+ for (const field of component.fields) {
1306
+ if (field.isInput || field.isOutput)
1307
+ continue;
1308
+ if ((0, formInit_1.isStreamInitializer)(field.initializer))
1309
+ streamFields.add(field.name);
1310
+ }
1311
+ // Signal fields (signals adoption): a field initialised with
1312
+ // signal(...) or computed(...) from '@angular/core' is one stable
1313
+ // reactive value for the component's whole life, held in a ref
1314
+ // like a stream field. Reads and writes in methods and templates
1315
+ // route through the ref, so the author's Angular syntax
1316
+ // (count(), count.set(...), double()) survives word for word.
1317
+ const signalFields = new Map();
1318
+ for (const field of component.fields) {
1319
+ if (field.isInput || field.isOutput)
1320
+ continue;
1321
+ const kind = (0, formInit_1.signalKindOf)(field.initializer);
1322
+ if (kind)
1323
+ signalFields.set(field.name, kind);
1324
+ }
1325
+ // ngModel belongs on <input> only in this version, and a two-way
1326
+ // ngModel field becomes state by definition (Angular semantics: the
1327
+ // binding itself writes the field).
1328
+ const ngModelStateFields = new Set();
1329
+ const walkNgModel = (nodes) => {
1330
+ for (const node of nodes) {
1331
+ if (node.type !== 'element')
1332
+ continue;
1333
+ if (node.tag.toLowerCase() === 'input') {
1334
+ const tw = node.twoWayBindings.find((b) => b.name === 'ngModel');
1335
+ const field = tw ? (0, forms_1.plainFieldOf)(tw.expression) : undefined;
1336
+ if (field)
1337
+ ngModelStateFields.add(field);
1338
+ }
1339
+ else if ((0, forms_1.hasNgModelSurface)(node)) {
1340
+ diagnostics.push((0, diagnostics_1.error)('GEN_NGMODEL_TARGET', `ngModel is used on <${node.tag}>; in this version ngModel binds <input> only (selection controls already have their [checked]/[value] plus (change) contract)`, node.pos.line, node.pos.column, 'Move [(ngModel)] to an <input>, or bind the control explicitly: <switch [checked]="wifiOn" (change)="onWifi($event)"></switch>'));
1341
+ }
1342
+ walkNgModel(node.children);
1343
+ }
1344
+ };
1345
+ walkNgModel(ast.children);
1346
+ // --- State analysis (M3) -------------------------------------------------
1347
+ const mutated = (0, methods_1.analyzeMutatedFields)(component);
1348
+ const stateFields = new Set();
1349
+ for (const field of component.fields) {
1350
+ if (field.isInput || field.isOutput)
1351
+ continue;
1352
+ if (formFields.has(field.name))
1353
+ continue;
1354
+ if (streamFields.has(field.name))
1355
+ continue;
1356
+ if (signalFields.has(field.name))
1357
+ continue;
1358
+ if (field.initializer && isLiteralInitializer(field.initializer)
1359
+ && (mutated.has(field.name) || ngModelStateFields.has(field.name))) {
1360
+ stateFields.add(field.name);
1361
+ }
1362
+ else if (mutated.has(field.name) && field.initializer && !isLiteralInitializer(field.initializer)) {
1363
+ diagnostics.push((0, diagnostics_1.warning)('GEN_FIELD_STATE', `Field '${field.name}' is assigned in a method but has a non-literal initializer; it cannot be hoisted to useState yet`, undefined, undefined, `Initialise '${field.name}' with a literal (0, 'text', true, [ ... ], { ... }) so it can become state, e.g. ${field.name} = 0;`));
1364
+ }
1365
+ }
1366
+ if (stateFields.size)
1367
+ this.reactImports.add('useState');
1368
+ // Per-form and per-input binding modes, walked with the form stack
1369
+ // so formControlName finds its [formGroup] and submit buttons find
1370
+ // the touched keys they must set.
1371
+ const fieldByName = new Map(component.fields.map((f) => [f.name, f]));
1372
+ const formInfos = new Map();
1373
+ const inputInfos = new Map();
1374
+ const modelInfos = [];
1375
+ const modelKeys = new Set();
1376
+ const inputInfoOf = (el, form, arrayCtx) => {
1377
+ const validators = (0, forms_1.validatorsOf)(el);
1378
+ const refName = el.ref && el.refExport === 'ngModel' ? el.ref : undefined;
1379
+ const info = { mode: 'plain', validators, refName };
1380
+ const boundFcn = el.propBindings.find((b) => b.name === 'formControlName');
1381
+ if (boundFcn) {
1382
+ if (arrayCtx) {
1383
+ // A row of a FormArray: the binding is the row index, most
1384
+ // often the *ngFor loop variable.
1385
+ info.mode = 'reactive';
1386
+ info.groupField = arrayCtx.groupField;
1387
+ info.arrayName = arrayCtx.arrayName;
1388
+ info.indexExpr = boundFcn.expression;
1389
+ return info;
1390
+ }
1391
+ diagnostics.push((0, diagnostics_1.warning)('GEN_FORM_CONTROL', 'formControlName is written as a [formControlName] binding; it must be a static attribute naming a control of the enclosing [formGroup]', el.pos.line, el.pos.column, 'Write formControlName="email" (no brackets) on the input, or bind [formControlName] to a row index inside a formArrayName container'));
1392
+ }
1393
+ const fcn = el.attrs['formControlName'];
1394
+ if (fcn !== undefined && arrayCtx) {
1395
+ if (/^\d+$/.test(fcn)) {
1396
+ info.mode = 'reactive';
1397
+ info.groupField = arrayCtx.groupField;
1398
+ info.arrayName = arrayCtx.arrayName;
1399
+ info.indexExpr = fcn;
1400
+ return info;
1401
+ }
1402
+ diagnostics.push((0, diagnostics_1.error)('GEN_FORM_ARRAY', `formControlName="${fcn}" sits inside formArrayName="${arrayCtx.arrayName}", whose rows are numbered, not named; there is no row called '${fcn}'`, el.pos.line, el.pos.column, 'Bind the row index instead: [formControlName]="i" with let i = index in the *ngFor over the array controls'));
1403
+ return info;
1404
+ }
1405
+ if (fcn !== undefined) {
1406
+ if (!form?.groupField) {
1407
+ diagnostics.push((0, diagnostics_1.error)('GEN_FORM_CONTROL', `formControlName="${fcn}" is not inside a <form> with a [formGroup] binding, so there is no control to bind`, el.pos.line, el.pos.column, `Wrap the input in <form [formGroup]="profileForm"> ... </form> and give the group a control named '${fcn}'`));
1408
+ return info;
1409
+ }
1410
+ info.mode = 'reactive';
1411
+ info.groupField = form.groupField;
1412
+ info.controlName = fcn;
1413
+ const names = formFields.get(form.groupField)?.controlNames ?? [];
1414
+ if (names.length && !names.includes(fcn)) {
1415
+ diagnostics.push((0, diagnostics_1.error)('GEN_FORM_CONTROL', `formControlName="${fcn}" does not match any control of the form group '${form.groupField}' (controls: ${names.join(', ')})`, el.pos.line, el.pos.column, `Use one of the group's controls (${names.join(', ')}), or add a '${fcn}' FormControl to the group`));
1416
+ }
1417
+ return info;
1418
+ }
1419
+ const ng = (0, forms_1.ngModelBindingOf)(el);
1420
+ if (ng) {
1421
+ info.expression = ng.expression;
1422
+ info.twoWay = ng.mode === 'twoWay';
1423
+ const field = (0, forms_1.plainFieldOf)(ng.expression);
1424
+ const fieldInfo = field ? fieldByName.get(field) : undefined;
1425
+ if (field && fieldInfo && !fieldInfo.isInput && !fieldInfo.isOutput
1426
+ && fieldInfo.initializer && isLiteralInitializer(fieldInfo.initializer)) {
1427
+ info.mode = 'ngmodel';
1428
+ info.field = field;
1429
+ if (validators.length || refName)
1430
+ info.key = refName ?? field;
1431
+ }
1432
+ else {
1433
+ info.mode = 'valueOnly';
1434
+ diagnostics.push((0, diagnostics_1.warning)('GEN_NGMODEL_EXPR', `ngModel is bound to '${ng.expression}', which is not a plain component field with a literal initial value; the value is bound one way, with no write-back and no validation state`, el.pos.line, el.pos.column, `Bind ngModel to a plain field with a literal initial value, e.g. email = ''; in the component class`));
1435
+ }
1436
+ }
1437
+ return info;
1438
+ };
1439
+ const walkForms = (nodes, formStack, arrayStack) => {
1440
+ for (const node of nodes) {
1441
+ if (node.type !== 'element')
1442
+ continue;
1443
+ const tag = node.tag.toLowerCase();
1444
+ let stack = formStack;
1445
+ let childArrays = arrayStack;
1446
+ if (tag === 'form') {
1447
+ const info = { touchedKeys: [] };
1448
+ info.submit = node.eventBindings.find((b) => b.name === 'submit' || b.name === 'ngSubmit');
1449
+ const fg = node.propBindings.find((b) => b.name === 'formGroup');
1450
+ if (fg) {
1451
+ const name = (0, forms_1.plainFieldOf)(fg.expression);
1452
+ const target = name ? formFields.get(name) : undefined;
1453
+ const named = name ? fieldByName.get(name) : undefined;
1454
+ if (name && target?.kind === 'group') {
1455
+ info.groupField = name;
1456
+ }
1457
+ else if (name && named && !named.isInput && !named.isOutput) {
1458
+ diagnostics.push((0, diagnostics_1.error)('GEN_FORMGROUP_TYPE', `[formGroup] is bound to '${name}', which is not a field initialised with new FormGroup(...)`, node.pos.line, node.pos.column, `Initialise the field as a form group: ${name} = new FormGroup({ email: new FormControl('') });`));
1459
+ }
1460
+ else {
1461
+ diagnostics.push((0, diagnostics_1.warning)('GEN_FORMGROUP_TYPE', `[formGroup] expression '${fg.expression}' cannot be verified as a field initialised with new FormGroup(...); its formControlName inputs cannot be wired`, node.pos.line, node.pos.column, 'Bind [formGroup] to a plain field initialised with new FormGroup({ ... })'));
1462
+ // groupField stays unset: wiring inputs to a ref that is
1463
+ // never generated would be broken code, so the inputs
1464
+ // report GEN_FORM_CONTROL instead.
1465
+ }
1466
+ }
1467
+ formInfos.set(node, info);
1468
+ stack = [...formStack, info];
1469
+ }
1470
+ const arrayNameAttr = node.attrs['formArrayName'];
1471
+ if (arrayNameAttr !== undefined) {
1472
+ const form = stack[stack.length - 1];
1473
+ let ctx;
1474
+ if (!form?.groupField) {
1475
+ diagnostics.push((0, diagnostics_1.error)('GEN_FORM_ARRAY', `formArrayName="${arrayNameAttr}" is not inside a <form> with a [formGroup] binding, so there is no form array to bind`, node.pos.line, node.pos.column, `Wrap the container in <form [formGroup]="profileForm"> ... </form> and give the group a FormArray control named '${arrayNameAttr}'`));
1476
+ }
1477
+ else {
1478
+ const gf = formFields.get(form.groupField);
1479
+ const names = gf?.controlNames ?? [];
1480
+ if (names.length && !names.includes(arrayNameAttr)) {
1481
+ diagnostics.push((0, diagnostics_1.error)('GEN_FORM_ARRAY', `formArrayName="${arrayNameAttr}" does not match any control of the form group '${form.groupField}' (controls: ${names.join(', ')})`, node.pos.line, node.pos.column, `Use one of the group's controls (${names.join(', ')}), or add a '${arrayNameAttr}' FormArray to the group`));
1482
+ }
1483
+ else if (gf && gf.controlKinds[arrayNameAttr] && gf.controlKinds[arrayNameAttr] !== 'array') {
1484
+ diagnostics.push((0, diagnostics_1.error)('GEN_FORM_ARRAY', `formArrayName="${arrayNameAttr}" names the '${form.groupField}' control '${arrayNameAttr}', which is a ${gf.controlKinds[arrayNameAttr]}, not a FormArray`, node.pos.line, node.pos.column, `Initialise '${arrayNameAttr}' as a FormArray: ${arrayNameAttr}: new FormArray([new FormControl('')])`));
1485
+ }
1486
+ else {
1487
+ ctx = { groupField: form.groupField, arrayName: arrayNameAttr };
1488
+ }
1489
+ }
1490
+ childArrays = [...arrayStack, ctx];
1491
+ }
1492
+ if (tag === 'input') {
1493
+ const info = inputInfoOf(node, stack[stack.length - 1], childArrays[childArrays.length - 1]);
1494
+ inputInfos.set(node, info);
1495
+ if (info.key) {
1496
+ if (!modelKeys.has(info.key)) {
1497
+ modelKeys.add(info.key);
1498
+ modelInfos.push(info);
1499
+ }
1500
+ const form = stack[stack.length - 1];
1501
+ if (form && !form.touchedKeys.includes(info.key))
1502
+ form.touchedKeys.push(info.key);
1503
+ }
1504
+ }
1505
+ walkForms(node.children, stack, childArrays);
1506
+ }
1507
+ };
1508
+ walkForms(ast.children, [], []);
1509
+ const styleKeys = new Set(Object.keys(css.styles));
1510
+ for (const [key, styleObj] of Object.entries(css.styles)) {
1511
+ this.styles.push({ key: styleKeyFor(opts.stylePrefix, key), styleObj: styleObj });
1512
+ }
1513
+ const styleFor = (el) => {
1514
+ const refs = [];
1515
+ if (styleKeys.has(el.tag))
1516
+ refs.push(`styles.${styleKeyFor(opts.stylePrefix, el.tag)}`);
1517
+ const classes = (el.attrs['class'] ?? '').split(/\s+/).filter(Boolean);
1518
+ for (const cls of classes)
1519
+ if (styleKeys.has(cls))
1520
+ refs.push(`styles.${styleKeyFor(opts.stylePrefix, cls)}`);
1521
+ // [class.name] toggles over classes the component styles declare
1522
+ // (gap fix): the entry is conditional, so the class style joins
1523
+ // the array only while the expression holds, after the static
1524
+ // classes (a directive style still merges after this, in
1525
+ // renderCore, and wins). Undeclared classes and styleless hosts
1526
+ // are diagnosed by the binding scan below and never reach here.
1527
+ for (const b of el.propBindings) {
1528
+ const toggle = classToggleOf(b.name);
1529
+ if (toggle !== undefined && styleKeys.has(toggle) && !STYLELESS_TAGS.has(el.tag.toLowerCase())) {
1530
+ refs.push(`${codeExpr(b.expression)} ? styles.${styleKeyFor(opts.stylePrefix, toggle)} : undefined`);
1531
+ }
1532
+ }
1533
+ if (!refs.length)
1534
+ return undefined;
1535
+ this.usedRn.add('StyleSheet');
1536
+ return refs.length === 1 ? refs[0] : `[${refs.join(', ')}]`;
1537
+ };
1538
+ // Class, style and attribute bindings scan (gap fix). Every
1539
+ // binding of these shapes is either wired ([class.name] over a
1540
+ // declared class on a block that takes a style, handled by
1541
+ // styleFor) or diagnosed here and stripped by the renderers'
1542
+ // prop loops, so no form is ever emitted as an inert prop or
1543
+ // dropped without a word. The scan runs once per unit over the
1544
+ // whole template, so dedicated renderers (icon, input, picker,
1545
+ // slider, ...) are covered exactly like the generic path.
1546
+ const scanClassStyleBindings = (nodes) => {
1547
+ for (const node of nodes) {
1548
+ if (node.type !== 'element')
1549
+ continue;
1550
+ const tag = node.tag.toLowerCase();
1551
+ if (node.attrs['style'] !== undefined) {
1552
+ diagnostics.push((0, diagnostics_1.warning)('GEN_STYLE_BINDING', `<${node.tag}> carries a static style attribute ("${node.attrs['style']}"), which is not supported; the attribute was dropped`, node.pos.line, node.pos.column, 'Move the declarations into the component styles under a class and apply it with class="name", or toggle it with [class.name]="cond"'));
1553
+ }
1554
+ for (const b of node.propBindings) {
1555
+ const toggle = classToggleOf(b.name);
1556
+ if (toggle !== undefined) {
1557
+ if (STYLELESS_TAGS.has(tag)) {
1558
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CLASS_BINDING', `[class.${toggle}] on <${node.tag}> cannot apply: this block takes no style, so the binding was dropped`, node.pos.line, node.pos.column, `Put the [class.${toggle}] toggle on a block that takes a style (a <p>, <div>, <card> or <button>), with .${toggle} declared in the component styles`));
1559
+ }
1560
+ else if (!styleKeys.has(toggle)) {
1561
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CLASS_BINDING', `[class.${toggle}] names a class the component styles do not declare; the binding was dropped`, node.pos.line, node.pos.column, `Declare .${toggle} in the component styles (styles: ['.${toggle} { ... }']), or remove the binding`));
1562
+ }
1563
+ continue;
1564
+ }
1565
+ if (b.name === 'class' || b.name === 'ngClass') {
1566
+ diagnostics.push((0, diagnostics_1.warning)('GEN_CLASS_BINDING', `[${b.name}] on <${node.tag}> binds a whole dynamic class value, which cannot be resolved to StyleSheet entries at compile time; the binding was dropped`, node.pos.line, node.pos.column, 'Toggle one declared class with [class.name]="cond", or put static classes in the plain class attribute and swap pre-styled elements with *ngIf'));
1567
+ continue;
1568
+ }
1569
+ if (b.name === 'style' || b.name === 'ngStyle' || b.name.startsWith('style.')) {
1570
+ diagnostics.push((0, diagnostics_1.warning)('GEN_STYLE_BINDING', `[${b.name}] on <${node.tag}> binds raw CSS values, which bypass the token-snapped component styles; the binding was dropped`, node.pos.line, node.pos.column, 'Declare a class in the component styles and apply it with class="name", toggle it with [class.name]="cond", or fold a directive style with an attribute directive'));
1571
+ continue;
1572
+ }
1573
+ if (b.name.startsWith('attr.')) {
1574
+ diagnostics.push((0, diagnostics_1.warning)('GEN_ATTR_BINDING', `[${b.name}] on <${node.tag}> targets an HTML attribute; React Native elements have no arbitrary attributes, so the binding was dropped`, node.pos.line, node.pos.column, 'Use the plain attribute when this block supports one, or the specific [prop] binding the block documents in catalog.md'));
1575
+ }
1576
+ }
1577
+ scanClassStyleBindings(node.children);
1578
+ }
1579
+ };
1580
+ scanClassStyleBindings(ast.children);
1581
+ // Template expressions (Stage 8): reactive form fields read through
1582
+ // their ref (profileForm -> profileFormRef.current), and member
1583
+ // chains rooted at an ngModel template reference read from the
1584
+ // generated model object (email.invalid -> emailModel.invalid).
1585
+ const identRenames = new Map();
1586
+ for (const name of formFields.keys())
1587
+ identRenames.set(name, `${name}Ref.current`);
1588
+ for (const name of streamFields)
1589
+ identRenames.set(name, `${name}Ref.current`);
1590
+ for (const name of signalFields.keys())
1591
+ identRenames.set(name, `${name}Ref.current`);
1592
+ const refBases = new Map();
1593
+ for (const info of modelInfos) {
1594
+ if (info.refName)
1595
+ refBases.set(info.refName, `${info.key}Model`);
1596
+ }
1597
+ // Pipes (Stage 12): one expression-options object per unit, shared
1598
+ // by every codeExpr call below. customPipes rewrites a pipe use to
1599
+ // the generated instance's transform; asyncVars rewrites a hoisted
1600
+ // `expr | async` to its subscription hook variable. The scan that
1601
+ // fills both runs before any rendering, so codegen sees the final
1602
+ // maps everywhere.
1603
+ const customPipes = new Map();
1604
+ for (const [name] of this.pipesByName) {
1605
+ const instance = this.pipeInstanceVar(name);
1606
+ if (instance)
1607
+ customPipes.set(name, instance);
1608
+ }
1609
+ const exprOptions = {
1610
+ renames: identRenames,
1611
+ refBases,
1612
+ customPipes,
1613
+ asyncVars: new Map(),
1614
+ };
1615
+ const codeExpr = (source) => {
1616
+ const code = (0, expr_1.exprToCode)(source, exprOptions);
1617
+ if (code.includes("pipe('"))
1618
+ this.usedRuntime.add('pipe');
1619
+ return code;
1620
+ };
1621
+ // --- Pipe scan (Stage 12) ---------------------------------------------
1622
+ // Walk every expression this unit will compile (interpolations,
1623
+ // bindings, event handlers, structural conditions and sources) and
1624
+ // collect its pipe uses: an unknown name is a PIPE_UNKNOWN error
1625
+ // naming the element, and every distinct async input earns a
1626
+ // subscription hook (asyncLines, assembled with the unit's lines).
1627
+ const asyncInputs = [];
1628
+ {
1629
+ const reportedUnknown = new Set();
1630
+ const knownList = [...pipes_1.BUILTIN_PIPES, ...this.pipesByName.keys()].join(', ');
1631
+ const scanExpr = (source, el) => {
1632
+ let parsed;
1633
+ try {
1634
+ parsed = (0, expr_1.parseExpression)(source);
1635
+ }
1636
+ catch {
1637
+ return; // a broken expression is reported by its own path
1638
+ }
1639
+ const walkExpr = (e) => {
1640
+ if (e.type === 'pipe') {
1641
+ if (!(0, pipes_1.isBuiltinPipe)(e.name) && !this.pipesByName.has(e.name)) {
1642
+ const key = `${e.name}@${el.pos.line}:${el.pos.column}`;
1643
+ if (!reportedUnknown.has(key)) {
1644
+ reportedUnknown.add(key);
1645
+ diagnostics.push((0, diagnostics_1.error)('PIPE_UNKNOWN', `Unknown pipe '${e.name}' on <${el.tag}>; known pipes: ${knownList}`, el.pos.line, el.pos.column, `Use a built-in pipe (${pipes_1.BUILTIN_PIPES.join(', ')}), or define a @Pipe class with name '${e.name}' and import it from the component file`));
1646
+ }
1647
+ }
1648
+ if (e.name === 'async') {
1649
+ const inputCode = (0, expr_1.exprAstToCode)(e.input, exprOptions);
1650
+ if (!exprOptions.asyncVars.has(inputCode)) {
1651
+ const varName = `__async${asyncInputs.length}`;
1652
+ exprOptions.asyncVars.set(inputCode, varName);
1653
+ asyncInputs.push({ code: inputCode, varName });
1654
+ }
1655
+ }
1656
+ }
1657
+ switch (e.type) {
1658
+ case 'member':
1659
+ walkExpr(e.object);
1660
+ break;
1661
+ case 'index':
1662
+ walkExpr(e.object);
1663
+ walkExpr(e.index);
1664
+ break;
1665
+ case 'call':
1666
+ walkExpr(e.callee);
1667
+ e.args.forEach(walkExpr);
1668
+ break;
1669
+ case 'unary':
1670
+ walkExpr(e.argument);
1671
+ break;
1672
+ case 'binary':
1673
+ walkExpr(e.left);
1674
+ walkExpr(e.right);
1675
+ break;
1676
+ case 'conditional':
1677
+ walkExpr(e.test);
1678
+ walkExpr(e.consequent);
1679
+ walkExpr(e.alternate);
1680
+ break;
1681
+ case 'array':
1682
+ e.elements.forEach(walkExpr);
1683
+ break;
1684
+ case 'pipe':
1685
+ walkExpr(e.input);
1686
+ e.args.forEach(walkExpr);
1687
+ break;
1688
+ default: break;
1689
+ }
1690
+ };
1691
+ walkExpr(parsed);
1692
+ };
1693
+ const scanNodes = (nodes) => {
1694
+ for (const node of nodes) {
1695
+ if (node.type === 'text') {
1696
+ for (const part of node.parts) {
1697
+ if (part.type === 'expr') {
1698
+ // A text node has no element position of its own here;
1699
+ // attribute it to the enclosing scan through a dummy
1700
+ // element anchored at the text position.
1701
+ scanExpr(part.expression, {
1702
+ type: 'element', tag: '#text', attrs: {}, booleanAttrs: [],
1703
+ propBindings: [], twoWayBindings: [], eventBindings: [],
1704
+ children: [], pos: node.pos,
1705
+ });
1706
+ }
1707
+ }
1708
+ continue;
1709
+ }
1710
+ for (const b of node.propBindings)
1711
+ scanExpr(b.expression, node);
1712
+ for (const b of node.twoWayBindings)
1713
+ scanExpr(b.expression, node);
1714
+ for (const ev of node.eventBindings)
1715
+ scanExpr(ev.expression, node);
1716
+ if (node.structural?.name === 'ngIf') {
1717
+ scanExpr((0, structural_1.parseNgIf)(node.structural.expression).condition, node);
1718
+ }
1719
+ else if (node.structural?.name === 'ngFor') {
1720
+ const { parts } = (0, structural_1.parseNgFor)(node.structural.expression);
1721
+ if (parts)
1722
+ scanExpr(parts.source, node);
1723
+ }
1724
+ scanNodes(node.children);
1725
+ }
1726
+ };
1727
+ scanNodes(ast.children);
1728
+ }
1729
+ const asyncLines = [];
1730
+ if (asyncInputs.length) {
1731
+ this.reactImports.add('useState');
1732
+ this.reactImports.add('useEffect');
1733
+ for (const input of asyncInputs) {
1734
+ asyncLines.push(` const [${input.varName}, ${(0, methods_1.setterName)(input.varName)}] = useState<any>(null);`);
1735
+ asyncLines.push(' useEffect(() => {');
1736
+ asyncLines.push(` const __obs = (${input.code}) as any;`);
1737
+ asyncLines.push(" if (!__obs || typeof __obs.subscribe !== 'function') return;");
1738
+ asyncLines.push(` const __sub = __obs.subscribe((__v: any) => ${(0, methods_1.setterName)(input.varName)}(__v));`);
1739
+ asyncLines.push(" return () => { if (__sub && typeof __sub.unsubscribe === 'function') __sub.unsubscribe(); };");
1740
+ asyncLines.push(' }, []);');
1741
+ }
1742
+ }
1743
+ /**
1744
+ * Assignment guard for event bindings (Stage 10): true (and a
1745
+ * GEN_EVENT_ASSIGNMENT warning recorded) when the binding is an
1746
+ * assignment statement. The binding is dropped by the caller; see
1747
+ * isAssignmentExpression for why assignments cannot be translated.
1748
+ */
1749
+ const isAssignmentBinding = (el, ev) => {
1750
+ if (!isAssignmentExpression(ev.expression))
1751
+ return false;
1752
+ diagnostics.push((0, diagnostics_1.warning)('GEN_EVENT_ASSIGNMENT', `Event binding (${ev.name}) on <${el.tag}> holds an assignment ('${ev.expression.trim()}'); template event bindings take a method call, so the binding was dropped`, el.pos.line, el.pos.column, `Call a method instead and assign inside it: (${ev.name})="onEvent()" in the template, onEvent() { this.field = false; } in the class`));
1753
+ return true;
1754
+ };
1755
+ /**
1756
+ * Attribute directives on one element (Stage 12): the directives
1757
+ * whose attribute name the element carries, plus the attribute and
1758
+ * input names they consume (those never become host props).
1759
+ */
1760
+ const directivesOn = (el) => {
1761
+ const active = [];
1762
+ for (const [attr, d] of this.directivesByAttr) {
1763
+ if (el.attrs[attr] !== undefined
1764
+ || el.propBindings.some((b) => b.name === attr)
1765
+ || el.booleanAttrs.includes(attr)) {
1766
+ active.push({ attr, info: d.info, assignments: d.assignments, unsupported: d.unsupported });
1767
+ }
1768
+ }
1769
+ return active;
1770
+ };
1771
+ const directiveConsumedNames = (el) => {
1772
+ const names = new Set();
1773
+ for (const d of directivesOn(el)) {
1774
+ names.add(d.attr);
1775
+ for (const input of d.info.inputs)
1776
+ names.add(input.name);
1777
+ }
1778
+ return names;
1779
+ };
1780
+ /**
1781
+ * The merged style object a host element's directives compute, as
1782
+ * generated code: each assignment's right-hand side with the
1783
+ * element's bound values substituted for the input names. Bound
1784
+ * inputs win over static attributes, which win over the declared
1785
+ * default; an unbound input with no default reads as undefined,
1786
+ * exactly Angular's initial value.
1787
+ */
1788
+ const directiveStyleCode = (el) => {
1789
+ const entries = [];
1790
+ for (const d of directivesOn(el)) {
1791
+ if (d.unsupported)
1792
+ continue;
1793
+ const renames = new Map();
1794
+ for (const input of d.info.inputs) {
1795
+ const binding = el.propBindings.find((b) => b.name === input.name);
1796
+ if (binding)
1797
+ renames.set(input.name, codeExpr(binding.expression));
1798
+ else if (el.attrs[input.name] !== undefined)
1799
+ renames.set(input.name, JSON.stringify(el.attrs[input.name]));
1800
+ else if (el.booleanAttrs.includes(input.name))
1801
+ renames.set(input.name, 'true');
1802
+ else if (input.initializer)
1803
+ renames.set(input.name, input.initializer);
1804
+ else
1805
+ renames.set(input.name, 'undefined');
1806
+ }
1807
+ for (const a of d.assignments) {
1808
+ entries.push(`${a.prop}: ${(0, expr_1.exprToCode)(a.rhs, { renames })}`);
1809
+ }
1810
+ }
1811
+ return entries.length ? `{ ${entries.join(', ')} }` : undefined;
1812
+ };
1813
+ const renderText = (node, indent) => {
1814
+ const parts = node.parts.map((p) => {
1815
+ if (p.type === 'static')
1816
+ return jsxTextPart(p.value);
1817
+ return `{${codeExpr(p.expression)}}`;
1818
+ });
1819
+ return indent + parts.join('');
1820
+ };
1821
+ /**
1822
+ * Render an <icon> element (Stage 7). Icons are validated here, at
1823
+ * compile time, against the curated set in @rangular-framework/ui icons.ts:
1824
+ * an unknown static name is an error (the JSON diagnostic carries
1825
+ * the full valid list in validIcons), a missing name is an error,
1826
+ * and an off-scale size warns and snaps to the icon size scale,
1827
+ * the same warn-and-snap behaviour the style translator uses. A
1828
+ * [name] binding is passed through unvalidated, its value is only
1829
+ * known at runtime. Only name, size and color exist in v1; any
1830
+ * other attribute or binding on <icon> is ignored.
1831
+ */
1832
+ const renderIcon = (el, depth, extraProps) => {
1833
+ const indent = ' '.repeat(depth + 2);
1834
+ this.usedUi.add('RgIcon');
1835
+ const props = [...extraProps];
1836
+ const nameBinding = el.propBindings.find((b) => b.name === 'name');
1837
+ const sizeBinding = el.propBindings.find((b) => b.name === 'size');
1838
+ const colorBinding = el.propBindings.find((b) => b.name === 'color');
1839
+ const staticName = el.attrs['name'];
1840
+ if (staticName !== undefined) {
1841
+ if (staticName in icons_1.ICON_PATHS || staticName in icons_1.BRAND_MARKS) {
1842
+ props.push(`name="${escapeJsxAttrValue(staticName)}"`);
1843
+ }
1844
+ else {
1845
+ diagnostics.push({
1846
+ severity: 'error',
1847
+ code: 'GEN_ICON_UNKNOWN',
1848
+ message: `Unknown icon name '${staticName}': it is not in the Rangular icon set`,
1849
+ line: el.pos.line,
1850
+ column: el.pos.column,
1851
+ fix: 'Use one of the names listed under Icons in catalog.md, e.g. <icon name="search"></icon>',
1852
+ validIcons: icons_1.ICON_NAMES,
1853
+ });
1854
+ props.push(`name="${escapeJsxAttrValue(staticName)}"`);
1855
+ }
1856
+ }
1857
+ else if (nameBinding) {
1858
+ props.push(`name={${codeExpr(nameBinding.expression)}}`);
1859
+ }
1860
+ else {
1861
+ diagnostics.push((0, diagnostics_1.error)('GEN_ICON_NAME', '<icon> has no name attribute and no [name] binding; there is nothing to draw', el.pos.line, el.pos.column, 'Add a name from the icon set, e.g. <icon name="search"></icon>; the full set is listed under Icons in catalog.md'));
1862
+ }
1863
+ // Brand marks are pictures, not glyphs: any size passes
1864
+ // through unsnapped and unwarned. The scale governs icons.
1865
+ const isBrand = staticName !== undefined && staticName in icons_1.BRAND_MARKS;
1866
+ const snapIconSize = (raw) => {
1867
+ const snapped = (0, css_1.nearestOnScale)(icons_1.ICON_SIZES, raw);
1868
+ if (snapped !== raw) {
1869
+ diagnostics.push((0, diagnostics_1.warning)('GEN_ICON_SIZE', `Icon size ${raw} is off the icon size scale (${icons_1.ICON_SIZES.join(', ')}); the generated code uses ${snapped}`, el.pos.line, el.pos.column, `Use size="${snapped}" (the icon size scale is ${icons_1.ICON_SIZES.join(', ')})`));
1870
+ }
1871
+ return snapped;
1872
+ };
1873
+ if (el.attrs['size'] !== undefined) {
1874
+ const raw = Number(el.attrs['size']);
1875
+ if (Number.isFinite(raw)) {
1876
+ props.push(`size={${isBrand ? raw : snapIconSize(raw)}}`);
1877
+ }
1878
+ else {
1879
+ diagnostics.push((0, diagnostics_1.warning)('GEN_ICON_SIZE', `Icon size '${el.attrs['size']}' is not a number; the generated code uses the default size ${icons_1.DEFAULT_ICON_SIZE}`, el.pos.line, el.pos.column, `Use size="20", size="24" or size="28"`));
1880
+ props.push(`size={${icons_1.DEFAULT_ICON_SIZE}}`);
1881
+ }
1882
+ }
1883
+ else if (sizeBinding) {
1884
+ const literal = /^-?\d+(\.\d+)?$/.test(sizeBinding.expression.trim())
1885
+ ? Number(sizeBinding.expression.trim())
1886
+ : undefined;
1887
+ props.push(literal !== undefined
1888
+ ? `size={${isBrand ? literal : snapIconSize(literal)}}`
1889
+ : `size={${codeExpr(sizeBinding.expression)}}`);
1890
+ }
1891
+ if (el.attrs['color'] !== undefined) {
1892
+ props.push(`color="${escapeJsxAttrValue(el.attrs['color'])}"`);
1893
+ }
1894
+ else if (colorBinding) {
1895
+ props.push(`color={${codeExpr(colorBinding.expression)}}`);
1896
+ }
1897
+ // Badge (Stage 11): <icon> is one of the three badge hosts, so a
1898
+ // badge attribute or [badge] binding becomes the badge prop the
1899
+ // RgIcon primitive draws as a count dot (see renderCore for the
1900
+ // other two hosts and the GEN_BADGE_HOST warning elsewhere).
1901
+ if (el.attrs['badge'] !== undefined) {
1902
+ props.push(`badge="${escapeJsxAttrValue(el.attrs['badge'])}"`);
1903
+ }
1904
+ else {
1905
+ const badgeBinding = el.propBindings.find((b) => b.name === 'badge');
1906
+ if (badgeBinding)
1907
+ props.push(`badge={${codeExpr(badgeBinding.expression)}}`);
1908
+ }
1909
+ return [`${indent}<RgIcon${props.length ? ' ' + props.join(' ') : ''} />`];
1910
+ };
1911
+ // Attributes of <input> that are forms machinery, never RgInput
1912
+ // props: the validators, the reactive name, the ngModel options, and
1913
+ // `type`/`name` (type is translated to secure/keyboardType below;
1914
+ // Angular's `name` keys controls inside an NgForm, which Rangular
1915
+ // does not track, refs and fields do that job here).
1916
+ const INPUT_DROP_ATTRS = new Set([
1917
+ 'required', 'minlength', 'maxlength', 'email', 'pattern',
1918
+ 'name', 'formControlName', 'ngModelOptions', 'type',
1919
+ ]);
1920
+ /**
1921
+ * Render an <input> (Stage 8). The binding mode comes from the forms
1922
+ * analysis: ngModel inputs get value plus write-back (and a touched
1923
+ * hook feeding their validation model), reactive inputs wire to
1924
+ * their FormControl (setValue on change, markAsTouched on blur),
1925
+ * plain inputs keep the Stage 2 value/event behaviour. Handler
1926
+ * expressions receive the text as $event, the Stage 6 control
1927
+ * pattern. Validator attributes, formControlName and ngModelOptions
1928
+ * are consumed, never emitted as props.
1929
+ */
1930
+ const renderInput = (el, depth, extraProps) => {
1931
+ const indent = ' '.repeat(depth + 2);
1932
+ const info = inputInfos.get(el);
1933
+ this.usedUi.add('RgInput');
1934
+ const lines = [];
1935
+ const props = [...extraProps];
1936
+ const typeAttr = el.attrs['type'];
1937
+ if (typeAttr === 'password')
1938
+ props.push('secure');
1939
+ else if (typeAttr === 'email')
1940
+ props.push('keyboardType="email-address"');
1941
+ else if (typeAttr === 'number')
1942
+ props.push('keyboardType="numeric"');
1943
+ for (const [name, value] of Object.entries(el.attrs)) {
1944
+ // A static style attribute is diagnosed by the binding scan
1945
+ // (GEN_STYLE_BINDING) and dropped, never emitted as a string
1946
+ // style prop next to the generated one.
1947
+ if (name === 'class' || name === 'style' || INPUT_DROP_ATTRS.has(name))
1948
+ continue;
1949
+ props.push(`${name}="${escapeJsxAttrValue(value)}"`);
1950
+ }
1951
+ for (const b of el.booleanAttrs) {
1952
+ if (INPUT_DROP_ATTRS.has(b))
1953
+ continue;
1954
+ props.push(b);
1955
+ }
1956
+ /** A handler binding in $event call form: bare ref -> fn($event). */
1957
+ const callOf = (src) => {
1958
+ const trimmed = src.trim();
1959
+ let bare = false;
1960
+ try {
1961
+ bare = (0, expr_1.parseExpression)(trimmed).type === 'identifier';
1962
+ }
1963
+ catch { /* raw fallback */ }
1964
+ return bare ? `${trimmed}($event)` : codeExpr(src);
1965
+ };
1966
+ const textCalls = [];
1967
+ const blurCalls = [];
1968
+ const selectCalls = [];
1969
+ if (info?.mode === 'ngmodel' && info.field) {
1970
+ props.push(info.twoWay
1971
+ ? `value={${info.field}}`
1972
+ : `value={${codeExpr(info.expression ?? info.field)}}`);
1973
+ if (info.twoWay)
1974
+ textCalls.push(`${(0, methods_1.setterName)(info.field)}($event)`);
1975
+ if (info.twoWay && info.key)
1976
+ textCalls.push(`${(0, methods_1.setterName)(`${info.key}Dirty`)}(true)`);
1977
+ if (info.key)
1978
+ blurCalls.push(`${(0, methods_1.setterName)(`${info.key}Touched`)}(true)`);
1979
+ }
1980
+ else if (info?.mode === 'valueOnly') {
1981
+ props.push(`value={${codeExpr(info.expression ?? '')}}`);
1982
+ lines.push(`${indent}{/* TODO(Rangular forms): ngModel target "${forBlockComment(info.expression ?? '')}" is not a plain field, the value is one-way only */}`);
1983
+ }
1984
+ else if (info?.mode === 'reactive' && info.groupField && (info.controlName || info.arrayName)) {
1985
+ const group = `${info.groupField}Ref.current`;
1986
+ const resolver = info.arrayName
1987
+ ? `${group}.get('${info.arrayName}').at(${codeExpr(info.indexExpr ?? '0')})`
1988
+ : `${group}.get('${info.controlName}')`;
1989
+ props.push(`value={${resolver}.value}`);
1990
+ textCalls.push(`${resolver}.setValue($event)`);
1991
+ blurCalls.push(info.arrayName ? `${resolver}.markAsTouched?.()` : `${resolver}.markAsTouched()`);
1992
+ blurCalls.push('setFormVersion((v) => v + 1)');
1993
+ }
1994
+ const consumedEvents = new Set(['input', 'change', 'blur', 'ngModelChange', 'optionSelected']);
1995
+ for (const ev of el.eventBindings) {
1996
+ if (isAssignmentBinding(el, ev)) {
1997
+ lines.push(`${indent}{/* TODO(Rangular): (${ev.name}) assignment handler dropped, see GEN_EVENT_ASSIGNMENT */}`);
1998
+ continue;
1999
+ }
2000
+ if (ev.name === 'ngModelChange' && info?.mode !== 'reactive') {
2001
+ textCalls.push(callOf(ev.expression));
2002
+ }
2003
+ else if (ev.name === 'optionSelected') {
2004
+ // Autocomplete (Stage 11): the chosen option string is the
2005
+ // $event, the Stage 6 control pattern, like (change).
2006
+ selectCalls.push(callOf(ev.expression));
2007
+ }
2008
+ else if (ev.name === 'input' || ev.name === 'change') {
2009
+ textCalls.push(callOf(ev.expression));
2010
+ }
2011
+ else if (ev.name === 'blur') {
2012
+ const trimmed = ev.expression.trim();
2013
+ let bare = false;
2014
+ try {
2015
+ bare = (0, expr_1.parseExpression)(trimmed).type === 'identifier';
2016
+ }
2017
+ catch { /* raw fallback */ }
2018
+ blurCalls.push(bare ? `${trimmed}()` : codeExpr(ev.expression));
2019
+ }
2020
+ }
2021
+ if (textCalls.length) {
2022
+ props.push(textCalls.length === 1
2023
+ ? `onChangeText={($event) => ${textCalls[0]}}`
2024
+ : `onChangeText={($event) => { ${textCalls.join('; ')}; }}`);
2025
+ }
2026
+ if (blurCalls.length) {
2027
+ props.push(blurCalls.length === 1
2028
+ ? `onBlur={() => ${blurCalls[0]}}`
2029
+ : `onBlur={() => { ${blurCalls.join('; ')}; }}`);
2030
+ }
2031
+ if (selectCalls.length) {
2032
+ props.push(selectCalls.length === 1
2033
+ ? `onOptionSelected={($event) => ${selectCalls[0]}}`
2034
+ : `onOptionSelected={($event) => { ${selectCalls.join('; ')}; }}`);
2035
+ }
2036
+ // [options] is autocomplete machinery (Stage 11), consumed by
2037
+ // name here and emitted explicitly as the RgInput options prop;
2038
+ // it stays in consumedProps so the generic loop never doubles it.
2039
+ const consumedProps = new Set(['ngModel', 'ngModelOptions', 'formControlName', 'options']);
2040
+ const optionsBinding = el.propBindings.find((b) => b.name === 'options');
2041
+ if (optionsBinding)
2042
+ props.push(`options={${codeExpr(optionsBinding.expression)}}`);
2043
+ if (info && info.mode !== 'plain')
2044
+ consumedProps.add('value');
2045
+ for (const p of el.propBindings) {
2046
+ if (consumedProps.has(p.name))
2047
+ continue;
2048
+ // Class, style and [attr.x] bindings are wired by styleFor or
2049
+ // diagnosed by the binding scan; never emitted as props.
2050
+ if (isClassStyleBindingName(p.name))
2051
+ continue;
2052
+ if (p.name === 'type') {
2053
+ lines.push(`${indent}{/* TODO(Rangular forms): a [type] binding on <input> is not supported, use a static type="password|email|number" attribute */}`);
2054
+ continue;
2055
+ }
2056
+ props.push(`${p.name}={${codeExpr(p.expression)}}`);
2057
+ }
2058
+ // Remaining events keep the generic mapping (e.g. (focus)).
2059
+ for (const ev of el.eventBindings) {
2060
+ if (consumedEvents.has(ev.name))
2061
+ continue;
2062
+ if (isAssignmentBinding(el, ev)) {
2063
+ lines.push(`${indent}{/* TODO(Rangular): (${ev.name}) assignment handler dropped, see GEN_EVENT_ASSIGNMENT */}`);
2064
+ continue;
2065
+ }
2066
+ const src = ev.expression.trim();
2067
+ let isBareRef = false;
2068
+ try {
2069
+ isBareRef = (0, expr_1.parseExpression)(src).type === 'identifier';
2070
+ }
2071
+ catch { /* raw fallback */ }
2072
+ const { prop, known } = eventPropName(ev.name, el.tag);
2073
+ if (!known) {
2074
+ lines.push(`${indent}{/* (${ev.name}) has no standard RN prop, mapped to ${prop} */}`);
2075
+ }
2076
+ props.push(isBareRef ? `${prop}={${src}}` : `${prop}={${src.includes('$event') ? '($event)' : '()'} => ${codeExpr(src)}}`);
2077
+ }
2078
+ const style = styleFor(el);
2079
+ if (style)
2080
+ props.push(`style={${style}}`);
2081
+ // A forms ref (#email="ngModel") is a template-level validation
2082
+ // object, not a DOM ref; only plain inputs keep the ref prop.
2083
+ if (el.ref && (!info || info.mode === 'plain'))
2084
+ props.push(`ref={${el.ref}Ref}`);
2085
+ lines.push(`${indent}<RgInput${props.length ? ' ' + props.join(' ') : ''} />`);
2086
+ return lines;
2087
+ };
2088
+ /**
2089
+ * Render a <router-outlet> (Stage 9). Only the entry component may
2090
+ * host one: nested outlets belong to child routes, which are not in
2091
+ * this version (GEN_ROUTE_UNSUPPORTED). The outlet renders the
2092
+ * route component whose pattern equals the navigator's current
2093
+ * routePath; each route component is keyed by the concrete path, so
2094
+ * navigating to the same component with new parameters remounts it
2095
+ * (the stated v1 simplification) and its ActivatedRoute, created
2096
+ * here per render, always carries the current entry's params.
2097
+ * Redirect-only routes render nothing. With no route table in the
2098
+ * compilation the outlet renders empty; compile.ts has already
2099
+ * reported GEN_ROUTES_MISSING for the entry template, and a child
2100
+ * template's outlet earns that warning here.
2101
+ */
2102
+ const renderOutlet = (el, depth) => {
2103
+ const indent = ' '.repeat(depth + 2);
2104
+ this.usedUi.add('RgOutlet');
2105
+ if (!opts.entry) {
2106
+ if (this.routingActive) {
2107
+ diagnostics.push((0, diagnostics_1.warning)('GEN_ROUTE_UNSUPPORTED', '<router-outlet> appears in a child component; nested outlets belong to child routes, which Rangular routing does not support yet', el.pos.line, el.pos.column, 'Keep the single <router-outlet> in the root component; child routes are on the roadmap in docs/ROADMAP.md'));
2108
+ }
2109
+ else {
2110
+ diagnostics.push((0, diagnostics_1.warning)('GEN_ROUTES_MISSING', '<router-outlet> appears in a child component template, but no routes file was resolved for this compilation', el.pos.line, el.pos.column, "Create app.routes.ts next to the root component: export const routes: Routes = [{ path: 'home', component: HomeComponent }];"));
2111
+ }
2112
+ return [`${indent}<RgOutlet />`];
2113
+ }
2114
+ if (!this.routingActive)
2115
+ return [`${indent}<RgOutlet />`];
2116
+ const lines = [`${indent}<RgOutlet>`];
2117
+ for (const route of this.routes ?? []) {
2118
+ if (!route.componentName)
2119
+ continue;
2120
+ const info = this.childByClassName.get(route.componentName);
2121
+ if (!info)
2122
+ continue;
2123
+ const fn = componentFunctionName(route.componentName);
2124
+ this.usedRuntime.add('ActivatedRoute');
2125
+ this.usedUi.add('ActivatedRouteContext');
2126
+ lines.push(`${indent} {__route.routePath === ${JSON.stringify(route.path)} && (`);
2127
+ lines.push(`${indent} <ActivatedRouteContext.Provider value={new ActivatedRoute(__route.params, __navigator)}>`);
2128
+ lines.push(`${indent} <${fn} key={__route.path} />`);
2129
+ lines.push(`${indent} </ActivatedRouteContext.Provider>`);
2130
+ lines.push(`${indent} )}`);
2131
+ }
2132
+ lines.push(`${indent}</RgOutlet>`);
2133
+ return lines;
2134
+ };
2135
+ /**
2136
+ * Render a <datetime-picker> (Stage 10). The picker is a dedicated
2137
+ * block with a small validated surface: mode (date, time or
2138
+ * datetime; a static value outside the three is a GEN_PICKER_MODE
2139
+ * error, a [mode] binding passes through unchecked), label,
2140
+ * minuteInterval (1 or 5; anything else warns GEN_PICKER_INTERVAL
2141
+ * and snaps to the nearest, the icon size pattern), [value] in
2142
+ * and (change) out with the ISO string as $event, wired like the
2143
+ * Stage 6 controls. presentation (sheet or modal; a static value
2144
+ * outside the two is a GEN_PICKER_PRESENTATION error, a
2145
+ * [presentation] binding passes through unchecked) chooses the
2146
+ * container the wheels open in. Children are meaningless on a
2147
+ * picker and are ignored. The wheels and formatting live in the primitive and
2148
+ * the shared helpers in @rangular-framework/ui datetime.ts.
2149
+ */
2150
+ const renderDateTimePicker = (el, depth, extraProps) => {
2151
+ const indent = ' '.repeat(depth + 2);
2152
+ this.usedUi.add('RgDateTimePicker');
2153
+ const lines = [];
2154
+ const props = [...extraProps];
2155
+ const snapInterval = (raw) => {
2156
+ const snapped = (0, css_1.nearestOnScale)([1, 5], raw);
2157
+ if (snapped !== raw) {
2158
+ diagnostics.push((0, diagnostics_1.warning)('GEN_PICKER_INTERVAL', `minuteInterval ${raw} is not 1 or 5; the generated code uses ${snapped}`, el.pos.line, el.pos.column, `Use minuteInterval="1" or minuteInterval="5"`));
2159
+ }
2160
+ return snapped;
2161
+ };
2162
+ const modeBinding = el.propBindings.find((b) => b.name === 'mode');
2163
+ if (el.attrs['mode'] !== undefined) {
2164
+ const mode = el.attrs['mode'];
2165
+ if (!datetime_1.PICKER_MODES.includes(mode)) {
2166
+ diagnostics.push((0, diagnostics_1.error)('GEN_PICKER_MODE', `<datetime-picker> mode '${mode}' is not a picker mode; the picker treats it as datetime`, el.pos.line, el.pos.column, 'Use mode="date", mode="time" or mode="datetime" (datetime is the default and can be omitted)'));
2167
+ }
2168
+ props.push(`mode="${escapeJsxAttrValue(mode)}"`);
2169
+ }
2170
+ else if (modeBinding) {
2171
+ props.push(`mode={${codeExpr(modeBinding.expression)}}`);
2172
+ }
2173
+ if (el.attrs['minuteInterval'] !== undefined) {
2174
+ const raw = Number(el.attrs['minuteInterval']);
2175
+ if (Number.isFinite(raw)) {
2176
+ props.push(`minuteInterval={${snapInterval(raw)}}`);
2177
+ }
2178
+ else {
2179
+ diagnostics.push((0, diagnostics_1.warning)('GEN_PICKER_INTERVAL', `minuteInterval '${el.attrs['minuteInterval']}' is not a number; the generated code uses the default 1`, el.pos.line, el.pos.column, 'Use minuteInterval="1" or minuteInterval="5"'));
2180
+ props.push('minuteInterval={1}');
2181
+ }
2182
+ }
2183
+ else {
2184
+ const intervalBinding = el.propBindings.find((b) => b.name === 'minuteInterval');
2185
+ if (intervalBinding) {
2186
+ const literal = /^-?\d+(\.\d+)?$/.test(intervalBinding.expression.trim())
2187
+ ? Number(intervalBinding.expression.trim())
2188
+ : undefined;
2189
+ props.push(literal !== undefined
2190
+ ? `minuteInterval={${snapInterval(literal)}}`
2191
+ : `minuteInterval={${codeExpr(intervalBinding.expression)}}`);
2192
+ }
2193
+ }
2194
+ // Presentation is gone (his word, 2026-11-20): the sheet
2195
+ // form of the picker was superfluous, the picker always
2196
+ // opens in a modal, and a presentation attribute or binding
2197
+ // is an error rather than a silent drop.
2198
+ if (el.attrs['presentation'] !== undefined || el.propBindings.some((b) => b.name === 'presentation')) {
2199
+ diagnostics.push((0, diagnostics_1.error)('GEN_PICKER_PRESENTATION', '<datetime-picker> takes no presentation; the picker always opens in a modal', el.pos.line, el.pos.column, 'Remove the presentation attribute; the picker always opens in a modal'));
2200
+ }
2201
+ const consumedAttrs = new Set(['class', 'style', 'mode', 'minuteInterval', 'presentation']);
2202
+ for (const [name, value] of Object.entries(el.attrs)) {
2203
+ if (consumedAttrs.has(name))
2204
+ continue;
2205
+ props.push(`${name}="${escapeJsxAttrValue(value)}"`);
2206
+ }
2207
+ for (const b of el.booleanAttrs)
2208
+ props.push(b);
2209
+ const consumedProps = new Set(['mode', 'minuteInterval', 'presentation']);
2210
+ for (const p of el.propBindings) {
2211
+ if (consumedProps.has(p.name))
2212
+ continue;
2213
+ if (isClassStyleBindingName(p.name))
2214
+ continue;
2215
+ props.push(`${p.name}={${codeExpr(p.expression)}}`);
2216
+ }
2217
+ for (const ev of el.eventBindings) {
2218
+ if (isAssignmentBinding(el, ev)) {
2219
+ lines.push(`${indent}{/* TODO(Rangular): (${ev.name}) assignment handler dropped, see GEN_EVENT_ASSIGNMENT */}`);
2220
+ continue;
2221
+ }
2222
+ const src = ev.expression.trim();
2223
+ let isBareRef = false;
2224
+ try {
2225
+ isBareRef = (0, expr_1.parseExpression)(src).type === 'identifier';
2226
+ }
2227
+ catch { /* raw fallback */ }
2228
+ if (ev.name === 'change') {
2229
+ // The picker emits the ISO string as $event (the Stage 6
2230
+ // control pattern): the wrapper must receive it.
2231
+ props.push(isBareRef ? `onChange={${src}}` : `onChange={($event) => ${codeExpr(src)}}`);
2232
+ continue;
2233
+ }
2234
+ const { prop, known } = eventPropName(ev.name, el.tag);
2235
+ if (!known) {
2236
+ lines.push(`${indent}{/* (${ev.name}) has no standard RN prop, mapped to ${prop} */}`);
2237
+ }
2238
+ props.push(isBareRef ? `${prop}={${src}}` : `${prop}={${src.includes('$event') ? '($event)' : '()'} => ${codeExpr(src)}}`);
2239
+ }
2240
+ const style = styleFor(el);
2241
+ if (style)
2242
+ props.push(`style={${style}}`);
2243
+ if (el.ref)
2244
+ props.push(`ref={${el.ref}Ref}`);
2245
+ lines.push(`${indent}<RgDateTimePicker${props.length ? ' ' + props.join(' ') : ''} />`);
2246
+ return lines;
2247
+ };
2248
+ /**
2249
+ * Render a <column> (Stage 11). A column is a declaration inside
2250
+ * <table>: its `name` attribute names the row property it displays
2251
+ * (the name of a matColumnDef in Angular Material's table) and
2252
+ * `header` is the header cell text, defaulting to the name. React
2253
+ * reserves the JSX `key` prop (it is extracted by React and never
2254
+ * reaches the component), so `name` is the documented attribute; a
2255
+ * `key` attribute is accepted as an alias and normalised to the
2256
+ * same name prop. Children and other attributes are meaningless on
2257
+ * a column and are ignored. A column with neither name nor key is
2258
+ * a GEN_TABLE_COLUMN error: the table cannot read its cells.
2259
+ */
2260
+ const renderColumn = (el, depth, extraProps) => {
2261
+ const indent = ' '.repeat(depth + 2);
2262
+ this.usedUi.add('RgColumn');
2263
+ const props = [...extraProps];
2264
+ const name = el.attrs['name'] ?? el.attrs['key'];
2265
+ if (name === undefined) {
2266
+ diagnostics.push((0, diagnostics_1.error)('GEN_TABLE_COLUMN', '<column> has no name attribute; a column declares which row property it displays by name', el.pos.line, el.pos.column, 'Add the row property name: <column name="sender" header="From"></column> (key="sender" works as an alias)'));
2267
+ }
2268
+ else {
2269
+ props.push(`name="${escapeJsxAttrValue(name)}"`);
2270
+ }
2271
+ if (el.attrs['header'] !== undefined) {
2272
+ props.push(`header="${escapeJsxAttrValue(el.attrs['header'])}"`);
2273
+ }
2274
+ return [`${indent}<RgColumn${props.length ? ' ' + props.join(' ') : ''} />`];
2275
+ };
2276
+ /**
2277
+ * Render a <slider> (Stage 11), the mat-slider adaptation: [value]
2278
+ * in, (change) out with the snapped number as $event (the Stage 6
2279
+ * control pattern), plus min, max and step. Range validation runs
2280
+ * here whenever values are statically known (static attributes or
2281
+ * literal bindings): min at or above max is a GEN_SLIDER_RANGE
2282
+ * error, a step at or below zero warns GEN_SLIDER_RANGE and the
2283
+ * generated code uses 1, and a non-numeric static min, max or step
2284
+ * warns and drops the attribute so the primitive default applies.
2285
+ * Field bindings pass through unchecked; the primitive clamps and
2286
+ * snaps at runtime. Children are meaningless and ignored.
2287
+ */
2288
+ const renderSlider = (el, depth, extraProps) => {
2289
+ const indent = ' '.repeat(depth + 2);
2290
+ this.usedUi.add('RgSlider');
2291
+ const lines = [];
2292
+ const props = [...extraProps];
2293
+ const staticNumber = (name) => {
2294
+ if (el.attrs[name] === undefined)
2295
+ return undefined;
2296
+ const raw = Number(el.attrs[name]);
2297
+ return Number.isFinite(raw) ? raw : undefined;
2298
+ };
2299
+ const literalNumber = (name) => {
2300
+ const b = el.propBindings.find((x) => x.name === name);
2301
+ if (!b)
2302
+ return undefined;
2303
+ const text = b.expression.trim();
2304
+ return /^-?\d+(\.\d+)?$/.test(text) ? Number(text) : undefined;
2305
+ };
2306
+ const knownNumber = (name) => staticNumber(name) ?? literalNumber(name);
2307
+ const emitNumberProp = (name, forced) => {
2308
+ if (forced !== undefined) {
2309
+ props.push(`${name}={${forced}}`);
2310
+ return;
2311
+ }
2312
+ if (el.attrs[name] !== undefined) {
2313
+ const stat = staticNumber(name);
2314
+ if (stat !== undefined) {
2315
+ props.push(`${name}={${stat}}`);
2316
+ return;
2317
+ }
2318
+ diagnostics.push((0, diagnostics_1.warning)('GEN_SLIDER_RANGE', `<slider> ${name}="${el.attrs[name]}" is not a number; the attribute is dropped and the primitive default applies`, el.pos.line, el.pos.column, `Use a number for ${name}, e.g. ${name}="0"`));
2319
+ return;
2320
+ }
2321
+ const b = el.propBindings.find((x) => x.name === name);
2322
+ if (b)
2323
+ props.push(`${name}={${codeExpr(b.expression)}}`);
2324
+ };
2325
+ const minKnown = knownNumber('min');
2326
+ const maxKnown = knownNumber('max');
2327
+ if (minKnown !== undefined && maxKnown !== undefined && minKnown >= maxKnown) {
2328
+ diagnostics.push((0, diagnostics_1.error)('GEN_SLIDER_RANGE', `<slider> min (${minKnown}) must be below max (${maxKnown}); the slider cannot move`, el.pos.line, el.pos.column, 'Give the slider a range with room to move, e.g. min="0" max="100" step="1"'));
2329
+ }
2330
+ emitNumberProp('min');
2331
+ emitNumberProp('max');
2332
+ const stepKnown = knownNumber('step');
2333
+ if (stepKnown !== undefined && stepKnown <= 0) {
2334
+ diagnostics.push((0, diagnostics_1.warning)('GEN_SLIDER_RANGE', `<slider> step (${stepKnown}) must be above zero; the generated code uses step 1`, el.pos.line, el.pos.column, 'Use a positive step, e.g. step="1"'));
2335
+ emitNumberProp('step', 1);
2336
+ }
2337
+ else {
2338
+ emitNumberProp('step');
2339
+ }
2340
+ const consumedAttrs = new Set(['class', 'style', 'min', 'max', 'step']);
2341
+ for (const [name, value] of Object.entries(el.attrs)) {
2342
+ if (consumedAttrs.has(name))
2343
+ continue;
2344
+ props.push(`${name}="${escapeJsxAttrValue(value)}"`);
2345
+ }
2346
+ for (const b of el.booleanAttrs)
2347
+ props.push(b);
2348
+ const consumedProps = new Set(['min', 'max', 'step']);
2349
+ for (const p of el.propBindings) {
2350
+ if (consumedProps.has(p.name))
2351
+ continue;
2352
+ if (isClassStyleBindingName(p.name))
2353
+ continue;
2354
+ props.push(`${p.name}={${codeExpr(p.expression)}}`);
2355
+ }
2356
+ for (const ev of el.eventBindings) {
2357
+ if (isAssignmentBinding(el, ev)) {
2358
+ lines.push(`${indent}{/* TODO(Rangular): (${ev.name}) assignment handler dropped, see GEN_EVENT_ASSIGNMENT */}`);
2359
+ continue;
2360
+ }
2361
+ const src = ev.expression.trim();
2362
+ let isBareRef = false;
2363
+ try {
2364
+ isBareRef = (0, expr_1.parseExpression)(src).type === 'identifier';
2365
+ }
2366
+ catch { /* raw fallback */ }
2367
+ if (ev.name === 'change') {
2368
+ props.push(isBareRef ? `onChange={${src}}` : `onChange={($event) => ${codeExpr(src)}}`);
2369
+ continue;
2370
+ }
2371
+ const { prop, known } = eventPropName(ev.name, el.tag);
2372
+ if (!known) {
2373
+ lines.push(`${indent}{/* (${ev.name}) has no standard RN prop, mapped to ${prop} */}`);
2374
+ }
2375
+ props.push(isBareRef ? `${prop}={${src}}` : `${prop}={${src.includes('$event') ? '($event)' : '()'} => ${codeExpr(src)}}`);
2376
+ }
2377
+ const style = styleFor(el);
2378
+ if (style)
2379
+ props.push(`style={${style}}`);
2380
+ if (el.ref)
2381
+ props.push(`ref={${el.ref}Ref}`);
2382
+ lines.push(`${indent}<RgSlider${props.length ? ' ' + props.join(' ') : ''} />`);
2383
+ return lines;
2384
+ };
2385
+ /**
2386
+ * Render a <progress-bar> (Stage 11), the mat-progress-bar
2387
+ * adaptation: [value] from 0 to 100 in determinate mode (the
2388
+ * default), mode="indeterminate" for the animated form. A
2389
+ * statically known value outside the range warns
2390
+ * GEN_PROGRESS_RANGE and the generated code carries the clamped
2391
+ * number; a field binding passes through and the primitive clamps
2392
+ * at runtime. An unknown static mode is passed through and the
2393
+ * primitive treats anything but indeterminate as determinate.
2394
+ * Children are meaningless and ignored.
2395
+ */
2396
+ const renderProgressBar = (el, depth, extraProps) => {
2397
+ const indent = ' '.repeat(depth + 2);
2398
+ this.usedUi.add('RgProgressBar');
2399
+ const props = [...extraProps];
2400
+ const clampValue = (raw) => {
2401
+ const clamped = Math.min(100, Math.max(0, raw));
2402
+ if (clamped !== raw) {
2403
+ diagnostics.push((0, diagnostics_1.warning)('GEN_PROGRESS_RANGE', `<progress-bar> value ${raw} is outside 0 to 100; the generated code uses ${clamped}`, el.pos.line, el.pos.column, 'Bind [value] to a number from 0 to 100, e.g. [value]="82"'));
2404
+ }
2405
+ return clamped;
2406
+ };
2407
+ if (el.attrs['mode'] !== undefined) {
2408
+ props.push(`mode="${escapeJsxAttrValue(el.attrs['mode'])}"`);
2409
+ }
2410
+ else {
2411
+ const modeBinding = el.propBindings.find((b) => b.name === 'mode');
2412
+ if (modeBinding)
2413
+ props.push(`mode={${codeExpr(modeBinding.expression)}}`);
2414
+ }
2415
+ if (el.attrs['value'] !== undefined) {
2416
+ const raw = Number(el.attrs['value']);
2417
+ if (Number.isFinite(raw))
2418
+ props.push(`value={${clampValue(raw)}}`);
2419
+ else
2420
+ props.push(`value="${escapeJsxAttrValue(el.attrs['value'])}"`);
2421
+ }
2422
+ else {
2423
+ const valueBinding = el.propBindings.find((b) => b.name === 'value');
2424
+ if (valueBinding) {
2425
+ const text = valueBinding.expression.trim();
2426
+ props.push(/^-?\d+(\.\d+)?$/.test(text)
2427
+ ? `value={${clampValue(Number(text))}}`
2428
+ : `value={${codeExpr(valueBinding.expression)}}`);
2429
+ }
2430
+ }
2431
+ const consumedAttrs = new Set(['class', 'style', 'mode', 'value']);
2432
+ for (const [name, value] of Object.entries(el.attrs)) {
2433
+ if (consumedAttrs.has(name))
2434
+ continue;
2435
+ props.push(`${name}="${escapeJsxAttrValue(value)}"`);
2436
+ }
2437
+ for (const b of el.booleanAttrs)
2438
+ props.push(b);
2439
+ for (const p of el.propBindings) {
2440
+ if (p.name === 'mode' || p.name === 'value')
2441
+ continue;
2442
+ if (isClassStyleBindingName(p.name))
2443
+ continue;
2444
+ props.push(`${p.name}={${codeExpr(p.expression)}}`);
2445
+ }
2446
+ const style = styleFor(el);
2447
+ if (style)
2448
+ props.push(`style={${style}}`);
2449
+ if (el.ref)
2450
+ props.push(`ref={${el.ref}Ref}`);
2451
+ return [`${indent}<RgProgressBar${props.length ? ' ' + props.join(' ') : ''} />`];
2452
+ };
2453
+ /**
2454
+ * Render a <spinner> (Stage 11), the mat-progress-spinner
2455
+ * adaptation: a small rotating arc drawn from one SVG path, the
2456
+ * same drawing in the app (react-native-svg, like the icons) and
2457
+ * in the preview (inline SVG, static there). The size sits on the
2458
+ * icon size scale (20, 24, 28) and an off-scale size warns
2459
+ * GEN_SPINNER_SIZE and snaps, the icon rule; color names a theme
2460
+ * colour role and defaults to the primary role in the primitive.
2461
+ * Children are meaningless and ignored.
2462
+ */
2463
+ const renderSpinner = (el, depth, extraProps) => {
2464
+ const indent = ' '.repeat(depth + 2);
2465
+ this.usedUi.add('RgSpinner');
2466
+ const props = [...extraProps];
2467
+ const snapSpinnerSize = (raw) => {
2468
+ const snapped = (0, css_1.nearestOnScale)(icons_1.ICON_SIZES, raw);
2469
+ if (snapped !== raw) {
2470
+ diagnostics.push((0, diagnostics_1.warning)('GEN_SPINNER_SIZE', `Spinner size ${raw} is off the icon size scale (${icons_1.ICON_SIZES.join(', ')}); the generated code uses ${snapped}`, el.pos.line, el.pos.column, `Use size="${snapped}" (the icon size scale is ${icons_1.ICON_SIZES.join(', ')})`));
2471
+ }
2472
+ return snapped;
2473
+ };
2474
+ if (el.attrs['size'] !== undefined) {
2475
+ const raw = Number(el.attrs['size']);
2476
+ if (Number.isFinite(raw)) {
2477
+ props.push(`size={${snapSpinnerSize(raw)}}`);
2478
+ }
2479
+ else {
2480
+ diagnostics.push((0, diagnostics_1.warning)('GEN_SPINNER_SIZE', `Spinner size '${el.attrs['size']}' is not a number; the generated code uses the default size ${icons_1.DEFAULT_ICON_SIZE}`, el.pos.line, el.pos.column, 'Use size="20", size="24" or size="28"'));
2481
+ props.push(`size={${icons_1.DEFAULT_ICON_SIZE}}`);
2482
+ }
2483
+ }
2484
+ else {
2485
+ const sizeBinding = el.propBindings.find((b) => b.name === 'size');
2486
+ if (sizeBinding) {
2487
+ const literal = /^-?\d+(\.\d+)?$/.test(sizeBinding.expression.trim())
2488
+ ? Number(sizeBinding.expression.trim())
2489
+ : undefined;
2490
+ props.push(literal !== undefined
2491
+ ? `size={${snapSpinnerSize(literal)}}`
2492
+ : `size={${codeExpr(sizeBinding.expression)}}`);
2493
+ }
2494
+ }
2495
+ if (el.attrs['color'] !== undefined) {
2496
+ props.push(`color="${escapeJsxAttrValue(el.attrs['color'])}"`);
2497
+ }
2498
+ else {
2499
+ const colorBinding = el.propBindings.find((b) => b.name === 'color');
2500
+ if (colorBinding)
2501
+ props.push(`color={${codeExpr(colorBinding.expression)}}`);
2502
+ }
2503
+ const style = styleFor(el);
2504
+ if (style)
2505
+ props.push(`style={${style}}`);
2506
+ if (el.ref)
2507
+ props.push(`ref={${el.ref}Ref}`);
2508
+ return [`${indent}<RgSpinner${props.length ? ' ' + props.join(' ') : ''} />`];
2509
+ };
2510
+ /** Render one element without its structural directive (handled by renderElement). */
2511
+ const renderCore = (el, depth, extraProps, formCtx) => {
2512
+ // Content projection (Stage 12): <ng-content> in a child
2513
+ // component's template is where the children written inside the
2514
+ // child's tag in the host template land; they arrive as the
2515
+ // generated function's React children prop. A select attribute
2516
+ // (multi-slot projection) is not supported: it warns and the
2517
+ // element behaves as the default slot.
2518
+ if (el.tag.toLowerCase() === 'ng-content') {
2519
+ const indent = ' '.repeat(depth + 2);
2520
+ if (el.attrs['select'] !== undefined) {
2521
+ diagnostics.push((0, diagnostics_1.warning)('PROJECTION_SELECT_UNSUPPORTED', `<ng-content select="${el.attrs['select']}"> uses multi-slot projection, which is not supported yet; the element behaves as the default slot and receives all projected children`, el.pos.line, el.pos.column, 'Use a single <ng-content></ng-content> with no select attribute; every child written inside the component tag lands there'));
2522
+ }
2523
+ return [`${indent}{children}`];
2524
+ }
2525
+ // Dedicated renderers have no style merge point, so a directive
2526
+ // on one of their hosts warns instead of silently doing nothing.
2527
+ if (['icon', 'input', 'datetime-picker'].includes(el.tag.toLowerCase())) {
2528
+ for (const d of directivesOn(el)) {
2529
+ diagnostics.push((0, diagnostics_1.warning)('DIR_UNSUPPORTED', `Directive [${d.attr}] sits on <${el.tag}>, which has a dedicated renderer with no host style to merge into; it applied no styles`, el.pos.line, el.pos.column, `Move [${d.attr}] onto a plain element (a <p>, <div>, <span> or <card>)`));
2530
+ }
2531
+ }
2532
+ if (el.tag.toLowerCase() === 'router-outlet')
2533
+ return renderOutlet(el, depth);
2534
+ if (el.tag.toLowerCase() === 'icon')
2535
+ return renderIcon(el, depth, extraProps);
2536
+ if (el.tag.toLowerCase() === 'input')
2537
+ return renderInput(el, depth, extraProps);
2538
+ if (el.tag.toLowerCase() === 'datetime-picker')
2539
+ return renderDateTimePicker(el, depth, extraProps);
2540
+ if (el.tag.toLowerCase() === 'column')
2541
+ return renderColumn(el, depth, extraProps);
2542
+ if (el.tag.toLowerCase() === 'slider')
2543
+ return renderSlider(el, depth, extraProps);
2544
+ if (el.tag.toLowerCase() === 'progress-bar')
2545
+ return renderProgressBar(el, depth, extraProps);
2546
+ if (el.tag.toLowerCase() === 'spinner')
2547
+ return renderSpinner(el, depth, extraProps);
2548
+ const indent = ' '.repeat(depth + 2);
2549
+ const lines = [];
2550
+ const mapping = exports.TAG_MAP[el.tag.toLowerCase()];
2551
+ const childInfo = !mapping ? this.childBySelector.get(el.tag) : undefined;
2552
+ let componentName;
2553
+ if (mapping) {
2554
+ componentName = mapping.component;
2555
+ (mapping.fromUi ? this.usedUi : this.usedRn).add(mapping.component);
2556
+ }
2557
+ else if (childInfo) {
2558
+ componentName = componentFunctionName(childInfo.className);
2559
+ }
2560
+ else if (/^[A-Z]/.test(el.tag) || el.tag.includes('-')) {
2561
+ // A component-looking tag: keep it, the app's own registry resolves it.
2562
+ componentName = el.tag;
2563
+ }
2564
+ else {
2565
+ diagnostics.push((0, diagnostics_1.warning)('GEN_UNKNOWN_TAG', `Unknown tag <${el.tag}>, emitted as <View>. Use a known block or a component tag.`, el.pos.line, el.pos.column, 'Known blocks: screen, appbar, gradient, card, list, row, fab, button, input, form, switch, switcher, checkbox, radio-group, tabs, accordion, panel, table, slider, progress-bar, spinner, chips, chip, sheet, dialog, datetime-picker, menu, menu-item, drawer, select, stepper, step, grid-list, grid-tile, tree, tree-node, divider, bottom-nav, nav-item, skeleton, row-action, rating, otp, file-picker, color-picker, editor, carousel, timeline, timeline-item, calendar, avatar, avatar-group, empty-state, chart, image, lightbox, breadcrumbs, crumb, h1, h2, h3, p, span, label, code, div, section, header, or use a Capitalised component tag'));
2566
+ componentName = 'View';
2567
+ this.usedRn.add('View');
2568
+ }
2569
+ // Routing links (Stage 9): routerLink and [routerLink] are
2570
+ // consumed here, never emitted as props. They become navigation
2571
+ // in the element's onPress below: an array expression goes
2572
+ // through Router.navigate (the Angular commands form), anything
2573
+ // else through navigateByUrl. On a child component tag a link has
2574
+ // nowhere to attach (the child renders its own root), so it is
2575
+ // dropped with a GEN_ROUTE_UNSUPPORTED warning. Without an active
2576
+ // route table the attributes are consumed silently in the entry
2577
+ // unit (compile.ts already reported GEN_ROUTES_MISSING) and earn
2578
+ // that warning in child units, whose usage compile.ts cannot see
2579
+ // before codegen.
2580
+ const linkAttr = el.attrs['routerLink'];
2581
+ const linkBinding = el.propBindings.find((b) => b.name === 'routerLink');
2582
+ let navCall;
2583
+ if (linkAttr !== undefined || linkBinding) {
2584
+ if (childInfo) {
2585
+ diagnostics.push((0, diagnostics_1.warning)('GEN_ROUTE_UNSUPPORTED', `routerLink on the component tag <${el.tag}> is not supported; a link belongs on a tappable block of the template`, el.pos.line, el.pos.column, 'Put routerLink on a <button> or <row>, or handle the tap inside the component and call this.router.navigate([...]) from its class'));
2586
+ }
2587
+ else if (this.routingActive) {
2588
+ if (linkAttr !== undefined) {
2589
+ navCall = `__router.navigateByUrl(${JSON.stringify(linkAttr)})`;
2590
+ }
2591
+ else if (linkBinding) {
2592
+ let isArrayForm = false;
2593
+ try {
2594
+ isArrayForm = (0, expr_1.parseExpression)(linkBinding.expression).type === 'array';
2595
+ }
2596
+ catch { /* raw fallback: treated as a URL */ }
2597
+ navCall = isArrayForm
2598
+ ? `__router.navigate(${codeExpr(linkBinding.expression)})`
2599
+ : `__router.navigateByUrl(${codeExpr(linkBinding.expression)})`;
2600
+ }
2601
+ }
2602
+ else if (!opts.entry) {
2603
+ diagnostics.push((0, diagnostics_1.warning)('GEN_ROUTES_MISSING', 'routerLink appears in a child component template, but no routes file was resolved for this compilation', el.pos.line, el.pos.column, "Create app.routes.ts next to the root component: export const routes: Routes = [{ path: 'home', component: HomeComponent }];"));
2604
+ }
2605
+ }
2606
+ // Badge (Stage 11): matBadge as an attribute. <button> and <row>
2607
+ // are hosts (the third host, <icon>, is handled in renderIcon);
2608
+ // on them the generic attribute and binding loops below emit
2609
+ // badge as a prop untouched, and the primitives draw the dot.
2610
+ // Stage 15 adds a fourth host: <nav-item>, whose bar draws the
2611
+ // same dot over the item's icon. On any other element the badge
2612
+ // has nowhere to sit: warn GEN_BADGE_HOST and strip it from
2613
+ // both loops so no stray badge prop reaches the output.
2614
+ const badgeUsed = el.attrs['badge'] !== undefined
2615
+ || el.propBindings.some((b) => b.name === 'badge');
2616
+ const badgeHost = el.tag.toLowerCase() === 'button' || el.tag.toLowerCase() === 'row'
2617
+ || el.tag.toLowerCase() === 'nav-item';
2618
+ const dropBadge = badgeUsed && !badgeHost;
2619
+ if (dropBadge) {
2620
+ diagnostics.push((0, diagnostics_1.warning)('GEN_BADGE_HOST', `badge on <${el.tag}> cannot render; badges sit on <button>, <row>, <icon> and <nav-item> in this version, so the badge was dropped`, el.pos.line, el.pos.column, 'Move the badge to a button, row, icon or nav item: <button badge="3">Inbox</button>, or bind it: <row [badge]="unread"></row>'));
2621
+ }
2622
+ // Tooltip (Stage 14): matTooltip as an attribute. The hosts
2623
+ // are the pressable blocks, <button>, <row> and <icon-button>:
2624
+ // on them the generic loops below emit tooltip as a prop and
2625
+ // the primitives show the bubble on long press. On any other
2626
+ // element the tooltip has no host: warn GEN_TOOLTIP_HOST and
2627
+ // strip it, the badge rule.
2628
+ const tooltipUsed = el.attrs['tooltip'] !== undefined
2629
+ || el.propBindings.some((b) => b.name === 'tooltip');
2630
+ const tooltipHost = ['button', 'row', 'icon-button'].includes(el.tag.toLowerCase());
2631
+ const dropTooltip = tooltipUsed && !tooltipHost;
2632
+ if (dropTooltip) {
2633
+ diagnostics.push((0, diagnostics_1.warning)('GEN_TOOLTIP_HOST', `tooltip on <${el.tag}> cannot render; tooltips sit on <button>, <row> and <icon-button> in this version, so the tooltip was dropped`, el.pos.line, el.pos.column, 'Move the tooltip to a button, row or icon button: <icon-button name="settings" tooltip="Settings"></icon-button>'));
2634
+ }
2635
+ // Attribute directives (Stage 12): a directive's attribute and
2636
+ // its input attributes are consumed by the directive (they feed
2637
+ // the merged style below), never emitted as host props. On a
2638
+ // child component tag there is no host element to style, so a
2639
+ // directive there warns DIR_UNSUPPORTED and applies nothing.
2640
+ const consumedByDirective = directiveConsumedNames(el);
2641
+ if (childInfo && consumedByDirective.size) {
2642
+ for (const d of directivesOn(el)) {
2643
+ diagnostics.push((0, diagnostics_1.warning)('DIR_UNSUPPORTED', `Directive [${d.attr}] sits on the component tag <${el.tag}>; attribute directives style plain host elements in this version, so it applied no styles`, el.pos.line, el.pos.column, `Move [${d.attr}] onto a plain element inside the component's template (a <p>, <div>, <span> or <card>), or style the component through its @Input props`));
2644
+ }
2645
+ }
2646
+ const props = [...extraProps];
2647
+ if (mapping?.variant)
2648
+ props.push(`variant="${mapping.variant}"`);
2649
+ const isFormEl = el.tag.toLowerCase() === 'form';
2650
+ const isButtonEl = el.tag.toLowerCase() === 'button';
2651
+ // A button's color role (primary by default, secondary for
2652
+ // the light member, danger for a destructive action, warning,
2653
+ // success, neutral for a cancelling one) is a small validated
2654
+ // surface: a static value outside the six is a
2655
+ // GEN_BUTTON_COLOR error, a [color] binding passes through.
2656
+ if (isButtonEl && el.attrs['color'] !== undefined) {
2657
+ const color = el.attrs['color'];
2658
+ if (color !== 'primary' && color !== 'secondary' && color !== 'danger' && color !== 'warning' && color !== 'success' && color !== 'neutral') {
2659
+ diagnostics.push((0, diagnostics_1.error)('GEN_BUTTON_COLOR', `<button> color '${color}' is not a button colour role; the button keeps the primary colour`, el.pos.line, el.pos.column, 'Use color="primary" (the default), color="secondary" for the light member, color="danger" for a destructive action, color="warning", color="success", or color="neutral" for a cancelling one'));
2660
+ }
2661
+ }
2662
+ // A switch's color role (primary by default, success for a
2663
+ // green on state) is the same small validated surface: a
2664
+ // static value outside the two is a GEN_SWITCH_COLOR error,
2665
+ // a [color] binding passes through.
2666
+ const isSwitchEl = el.tag.toLowerCase() === 'switch';
2667
+ if (isSwitchEl && el.attrs['color'] !== undefined) {
2668
+ const color = el.attrs['color'];
2669
+ if (color !== 'primary' && color !== 'success') {
2670
+ diagnostics.push((0, diagnostics_1.error)('GEN_SWITCH_COLOR', `<switch> color '${color}' is not a switch colour role; the switch keeps the primary colour`, el.pos.line, el.pos.column, 'Use color="primary" (the default), or color="success" for a green on state'));
2671
+ }
2672
+ }
2673
+ for (const [name, value] of Object.entries(el.attrs)) {
2674
+ if (name === 'class')
2675
+ continue;
2676
+ // A static style attribute is diagnosed by the binding scan
2677
+ // (GEN_STYLE_BINDING) and dropped; emitted verbatim it would
2678
+ // sit next to the generated style prop as a duplicate.
2679
+ if (name === 'style')
2680
+ continue;
2681
+ if (name === 'routerLink')
2682
+ continue;
2683
+ // formArrayName is forms machinery (forms completion pass): it
2684
+ // scopes the rows of a FormArray for the inputs inside, never a prop.
2685
+ if (name === 'formArrayName')
2686
+ continue;
2687
+ if (consumedByDirective.has(name))
2688
+ continue;
2689
+ if (name === 'badge' && dropBadge)
2690
+ continue;
2691
+ if (name === 'tooltip' && dropTooltip)
2692
+ continue;
2693
+ // A button's type is forms machinery (Stage 8): type="submit"
2694
+ // is consumed by the submit rewrite below, never a prop.
2695
+ if (isButtonEl && name === 'type')
2696
+ continue;
2697
+ props.push(`${name}="${escapeJsxAttrValue(value)}"`);
2698
+ }
2699
+ for (const b of el.booleanAttrs) {
2700
+ if (consumedByDirective.has(b))
2701
+ continue;
2702
+ props.push(b);
2703
+ }
2704
+ for (const p of el.propBindings) {
2705
+ // [formGroup] is the reactive binding mechanism, not a View prop.
2706
+ if (isFormEl && p.name === 'formGroup')
2707
+ continue;
2708
+ if (p.name === 'routerLink')
2709
+ continue;
2710
+ // Class, style and [attr.x] bindings are wired through the
2711
+ // style prop ([class.name], see styleFor) or diagnosed and
2712
+ // dropped by the binding scan; they are never props.
2713
+ if (isClassStyleBindingName(p.name))
2714
+ continue;
2715
+ if (consumedByDirective.has(p.name))
2716
+ continue;
2717
+ if (p.name === 'badge' && dropBadge)
2718
+ continue;
2719
+ if (p.name === 'tooltip' && dropTooltip)
2720
+ continue;
2721
+ props.push(`${p.name}={${codeExpr(p.expression)}}`);
2722
+ }
2723
+ // Form submit (Stage 8): a <button type="submit"> statically
2724
+ // nested in a form with a (submit) handler calls that handler
2725
+ // directly (there is no DOM form to submit in React Native). A
2726
+ // submit attempt first marks every ngModel input in the form
2727
+ // touched, so validation errors appear on save, the standard UX.
2728
+ let submitPress;
2729
+ if (isButtonEl && el.attrs['type'] === 'submit' && formCtx?.submit
2730
+ && !el.eventBindings.some((b) => b.name === 'click')) {
2731
+ const src = formCtx.submit.expression.trim();
2732
+ let bare = false;
2733
+ try {
2734
+ bare = (0, expr_1.parseExpression)(src).type === 'identifier';
2735
+ }
2736
+ catch { /* raw fallback */ }
2737
+ const call = bare ? `${src}()` : codeExpr(formCtx.submit.expression);
2738
+ const parts = [
2739
+ ...formCtx.touchedKeys.map((k) => `${(0, methods_1.setterName)(`${k}Touched`)}(true)`),
2740
+ ...(formCtx.groupField
2741
+ ? [`${formCtx.groupField}Ref.current.markAllAsTouched()`, 'setFormVersion((v) => v + 1)']
2742
+ : []),
2743
+ call,
2744
+ ];
2745
+ submitPress = parts.length === 1
2746
+ ? `() => ${call}`
2747
+ : `${formCtx.submit.expression.includes('$event') ? '($event)' : '()'} => { ${parts.join('; ')}; }`;
2748
+ }
2749
+ // Event bindings (M3): (click) -> onPress={() => handler()} etc.
2750
+ // On a child component, an event named after one of its @Output fields
2751
+ // becomes that output's callback prop instead (M5).
2752
+ let navComposed = false;
2753
+ for (const ev of el.eventBindings) {
2754
+ // A form's own (submit)/(ngSubmit) is consumed by the rewrite
2755
+ // above; it is not a prop on the generated View.
2756
+ if (isFormEl && (ev.name === 'submit' || ev.name === 'ngSubmit'))
2757
+ continue;
2758
+ // Assignment handlers (Stage 10) are dropped with a warning:
2759
+ // the expression grammar has no assignment operator, and the
2760
+ // raw fallback used to emit an assignment against a const.
2761
+ if (isAssignmentBinding(el, ev)) {
2762
+ lines.push(`${indent}{/* TODO(Rangular): (${ev.name}) assignment handler dropped, see GEN_EVENT_ASSIGNMENT */}`);
2763
+ continue;
2764
+ }
2765
+ const src = ev.expression.trim();
2766
+ let isBareRef = false;
2767
+ try {
2768
+ isBareRef = (0, expr_1.parseExpression)(src).type === 'identifier';
2769
+ }
2770
+ catch { /* raw fallback below */ }
2771
+ if (childInfo && childInfo.fields.some((f) => f.isOutput && f.name === ev.name)) {
2772
+ const cb = outputPropName(ev.name);
2773
+ props.push(isBareRef ? `${cb}={${src}}` : `${cb}={($event) => ${codeExpr(src)}}`);
2774
+ continue;
2775
+ }
2776
+ const controlTag = ['switch', 'checkbox', 'switcher', 'radio-group', 'tabs', 'select', 'stepper',
2777
+ // Stage 15 controls carry (change) the same way: the value
2778
+ // arrives as $event, so the handler must be wrapped to
2779
+ // receive it (the Stage 14 lesson).
2780
+ 'bottom-nav', 'rating', 'otp', 'carousel', 'calendar', 'color-picker', 'file-picker', 'editor',
2781
+ ].includes(el.tag.toLowerCase());
2782
+ if (controlTag && ev.name === 'change') {
2783
+ // Controls emit their next value as $event (Stage 6). Unlike
2784
+ // the generic event path, the generated wrapper must receive
2785
+ // that value and pass it to the Angular style handler call.
2786
+ // Tabs joined the contract in Stage 11: (change) emits the
2787
+ // newly selected tab index. Select and stepper joined in
2788
+ // Stage 14 with the same contract; without them here, their
2789
+ // handlers generated an arrow that referenced $event
2790
+ // without ever receiving it.
2791
+ props.push(isBareRef ? `onChange={${src}}` : `onChange={($event) => ${codeExpr(src)}}`);
2792
+ continue;
2793
+ }
2794
+ if (el.tag.toLowerCase() === 'panel' && ev.name === 'toggle') {
2795
+ // Panels emit their next open state as $event (Stage 11),
2796
+ // the same control pattern as (change) above.
2797
+ props.push(isBareRef ? `onToggle={${src}}` : `onToggle={($event) => ${codeExpr(src)}}`);
2798
+ continue;
2799
+ }
2800
+ if (ev.name === 'click' && navCall) {
2801
+ // A tap that both handles and navigates (Stage 9): the
2802
+ // handler runs first, then the navigation, one onPress.
2803
+ props.push(isBareRef
2804
+ ? `onPress={() => { ${src}(); ${navCall}; }}`
2805
+ : `onPress={() => { ${codeExpr(src)}; ${navCall}; }}`);
2806
+ navComposed = true;
2807
+ continue;
2808
+ }
2809
+ const { prop, known } = eventPropName(ev.name, el.tag);
2810
+ if (!known) {
2811
+ lines.push(`${indent}{/* (${ev.name}) has no standard RN prop, mapped to ${prop} */}`);
2812
+ }
2813
+ props.push(isBareRef ? `${prop}={${src}}` : `${prop}={${src.includes('$event') ? '($event)' : '()'} => ${codeExpr(src)}}`);
2814
+ }
2815
+ if (submitPress)
2816
+ props.push(`onPress={${submitPress}}`);
2817
+ // A link with no (click) of its own navigates on tap (Stage 9).
2818
+ // A submit button keeps its submit onPress; the link is dropped
2819
+ // there, a form submit and a navigation are two different intents.
2820
+ if (navCall && !navComposed && !submitPress) {
2821
+ props.push(`onPress={() => ${navCall}}`);
2822
+ }
2823
+ const style = styleFor(el);
2824
+ // Directive styles merge after the element's own style, so a
2825
+ // directive wins over the class style for the same property,
2826
+ // the way a directive's inline style beats a stylesheet rule.
2827
+ const dirStyle = childInfo ? undefined : directiveStyleCode(el);
2828
+ if (style && dirStyle)
2829
+ props.push(`style={[${style}, ${dirStyle}]}`);
2830
+ else if (dirStyle)
2831
+ props.push(`style={${dirStyle}}`);
2832
+ else if (style)
2833
+ props.push(`style={${style}}`);
2834
+ if (el.ref)
2835
+ props.push(`ref={${el.ref}Ref}`);
2836
+ // Scroll key on the entry screen (Gmail light round,
2837
+ // 2026-11-17; persistence, seamless round follow-up,
2838
+ // 2026-11-18): in a routed app the root screen wraps the
2839
+ // outlet, so every route shares one ScrollView and it keeps
2840
+ // the last screen's scroll offset: a lesson opened from a
2841
+ // scrolled list landed mid-page. The first fix keyed the
2842
+ // screen by the concrete path, remounting the whole shell
2843
+ // per navigation: correct scroll, but on a phone the
2844
+ // remount rebuilt the safe area, the scroll view and both
2845
+ // slots on every tab switch, which read as jitter. The
2846
+ // screen now persists and takes the path as a scrollKey
2847
+ // instead: RgScreen scrolls to the top when the key
2848
+ // changes, and the pages inside the outlet still remount
2849
+ // by their own keys.
2850
+ if (el.tag.toLowerCase() === 'screen' && opts.entry && this.routingActive) {
2851
+ props.unshift('scrollKey={__route.path}');
2852
+ // The scroll key reads __route, and only the entry unit's
2853
+ // outlet state defines it: generateUnit creates the
2854
+ // [__route, __setRoute] state only when the entry template
2855
+ // hosts a <router-outlet>. A routed root screen with no
2856
+ // outlet therefore reads a name that is never defined and
2857
+ // the app throws at startup (guardrail test finding,
2858
+ // 2026-11-29: a root component that injects Router, carries
2859
+ // a screen and declares routes, but hosts no outlet,
2860
+ // passed rg verify and crashed with a ReferenceError in
2861
+ // the web export). Name the shape here, at the read site,
2862
+ // once per compilation. Child units never reach this
2863
+ // branch (opts.entry is false), so a routed page component
2864
+ // with its own screen and no outlet, the tutorial shape,
2865
+ // stays silent, as do a root screen with routing off and a
2866
+ // routed root template with no screen (no read is emitted).
2867
+ if (!opts.hasOutlet && !this.routerNoOutletReported) {
2868
+ this.routerNoOutletReported = true;
2869
+ diagnostics.push((0, diagnostics_1.error)('GEN_ROUTER_NO_OUTLET', 'The root component carries a <screen> and routing is on, but its template has no <router-outlet>; the generated screen reads the current route for its scroll key, and only the outlet creates that route value, so the app throws at startup and shows a blank page', el.pos.line, el.pos.column, 'Add <router-outlet></router-outlet> inside the root component template, where the routed pages should render; if the app does not use routing, remove the Router or ActivatedRoute injection and any routerLink uses instead'));
2870
+ }
2871
+ }
2872
+ const open = `${indent}<${componentName}${props.length ? ' ' + props.join(' ') : ''}`;
2873
+ const childLines = [];
2874
+ // The form context flows to descendants (submit buttons and
2875
+ // reactive inputs find their form); it stops at child components,
2876
+ // whose templates render as their own units.
2877
+ const childForm = isFormEl ? formInfos.get(el) : formCtx;
2878
+ for (const child of el.children) {
2879
+ if (child.type === 'text')
2880
+ childLines.push(renderText(child, ''));
2881
+ else
2882
+ childLines.push(...renderElement(child, depth + 1, childForm));
2883
+ }
2884
+ if (!childLines.length) {
2885
+ lines.push(`${open} />`);
2886
+ return lines;
2887
+ }
2888
+ // Text-only children stay on one line, JSX-style.
2889
+ if (el.children.every((c) => c.type === 'text')) {
2890
+ const inner = el.children
2891
+ .map((c) => renderText(c, '').trim())
2892
+ .join(' ');
2893
+ lines.push(`${open}>${inner}</${componentName}>`);
2894
+ return lines;
2895
+ }
2896
+ lines.push(`${open}>`);
2897
+ for (const cl of childLines)
2898
+ lines.push(cl);
2899
+ lines.push(`${indent}</${componentName}>`);
2900
+ return lines;
2901
+ };
2902
+ /** Render an element, applying *ngIf / *ngFor wrapping when present (M4). */
2903
+ const renderElementInnerCore = (el, depth, formCtx) => {
2904
+ const indent = ' '.repeat(depth + 2);
2905
+ if (!el.structural)
2906
+ return renderCore(el, depth, [], formCtx);
2907
+ const stripped = { ...el, structural: undefined };
2908
+ if (el.structural.name === 'ngIf') {
2909
+ const parts = (0, structural_1.parseNgIf)(el.structural.expression);
2910
+ if (parts.elseRef || parts.thenRef) {
2911
+ diagnostics.push((0, diagnostics_1.warning)('GEN_NGIF_ELSE_TODO', `*ngIf with 'else'/'then' microsyntax is not generated yet, element emitted unconditionally`, el.pos.line, el.pos.column, 'Split it into two elements: one with *ngIf="cond" and a second with *ngIf="!(cond)"'));
2912
+ return [
2913
+ `${indent}{/* TODO(M5+): *ngIf else/then, "${forBlockComment(el.structural.expression)}" */}`,
2914
+ ...renderCore(stripped, depth, [], formCtx),
2915
+ ];
2916
+ }
2917
+ const inner = renderCore(stripped, depth + 1, [], formCtx);
2918
+ // The condition is coerced with !! on purpose: emitted
2919
+ // bare, a numeric or string condition leaks its falsy
2920
+ // value (0 or '') into the tree as a child, and React
2921
+ // Native throws "Text strings must be rendered within a
2922
+ // <Text> component" for it (lesson 88's rating demo,
2923
+ // his phone 2026-11-21: *ngIf="score" with score 0).
2924
+ return [
2925
+ `${indent}{!!(${codeExpr(parts.condition)}) && (`,
2926
+ ...inner,
2927
+ `${indent})}`,
2928
+ ];
2929
+ }
2930
+ if (el.structural.name === 'ngFor') {
2931
+ const { parts, diagnostics: forDiags } = (0, structural_1.parseNgFor)(el.structural.expression, el.pos.line, el.pos.column);
2932
+ diagnostics.push(...forDiags);
2933
+ if (!parts) {
2934
+ return [
2935
+ `${indent}{/* TODO: unparseable *ngFor="${forBlockComment(el.structural.expression)}", element emitted once */}`,
2936
+ ...renderCore(stripped, depth, [], formCtx),
2937
+ ];
2938
+ }
2939
+ const indexName = parts.indexVar ?? 'index';
2940
+ const keyExpr = parts.trackBy
2941
+ ? `${parts.trackBy}(${parts.itemVar})`
2942
+ : `${parts.itemVar}?.id ?? ${indexName}`;
2943
+ const inner = renderCore(stripped, depth + 1, [`key={${keyExpr}}`], formCtx);
2944
+ return [
2945
+ `${indent}{${codeExpr(parts.source)}.map((${parts.itemVar}, ${indexName}) => (`,
2946
+ ...inner,
2947
+ `${indent}))}`,
2948
+ ];
2949
+ }
2950
+ diagnostics.push((0, diagnostics_1.warning)('GEN_STRUCTURAL_TODO', `*${el.structural.name} is not supported yet, element emitted unconditionally`, el.pos.line, el.pos.column, 'Only *ngIf and *ngFor are supported, rewrite the element with one of those'));
2951
+ return [
2952
+ `${indent}{/* TODO: *${el.structural.name}="${forBlockComment(el.structural.expression)}" */}`,
2953
+ ...renderCore(stripped, depth, [], formCtx),
2954
+ ];
2955
+ };
2956
+ /**
2957
+ * renderElementInnerCore plus the TODO comments for structural
2958
+ * directives the parser dropped (one structural directive per
2959
+ * element, TPL_STRUCTURAL_MULTIPLE): the warning names the drop,
2960
+ * and the generated code carries the same note at the element, so
2961
+ * the loss is visible in both places instead of silent.
2962
+ */
2963
+ const renderElementInner = (el, depth, formCtx) => {
2964
+ const lines = renderElementInnerCore(el, depth, formCtx);
2965
+ if (!el.droppedStructural?.length)
2966
+ return lines;
2967
+ const indent = ' '.repeat(depth + 2);
2968
+ const todos = el.droppedStructural.map((d) => `${indent}{/* TODO: *${d.name}="${forBlockComment(d.expression)}" dropped, one structural directive per element, see TPL_STRUCTURAL_MULTIPLE */}`);
2969
+ return [...todos, ...lines];
2970
+ };
2971
+ /**
2972
+ * Source map wrapper (Stage 5): with a map requested, every element's
2973
+ * lines are preceded by a marker comment that finishSourceMap turns
2974
+ * into a segment and removes. Without a map this is a pass-through,
2975
+ * so default output is byte identical to before.
2976
+ */
2977
+ const renderElement = (el, depth, formCtx) => {
2978
+ const lines = renderElementInner(el, depth, formCtx);
2979
+ if (!this.smConfig || !opts.templateFile)
2980
+ return lines;
2981
+ const id = this.smRecords.length;
2982
+ this.smRecords.push({ templateFile: opts.templateFile, el });
2983
+ const indent = ' '.repeat(depth + 2);
2984
+ return [`${indent}{/*@sm:${id}@*/}`, ...lines];
2985
+ };
2986
+ const bodyLines = [];
2987
+ for (const node of ast.children) {
2988
+ if (node.type === 'text') {
2989
+ this.usedRn.add('Text');
2990
+ bodyLines.push(` <Text>${renderText(node, '').trim()}</Text>`);
2991
+ }
2992
+ else {
2993
+ bodyLines.push(...renderElement(node, 0));
2994
+ }
2995
+ }
2996
+ const fnName = componentFunctionName(component.className);
2997
+ const inputs = component.fields.filter((f) => f.isInput);
2998
+ const outputs = component.fields.filter((f) => f.isOutput);
2999
+ // Content projection (Stage 12): a template that places
3000
+ // <ng-content> receives the host's children as the React children
3001
+ // prop; without one the generated signature stays exactly as before.
3002
+ const usesProjection = (() => {
3003
+ let found = false;
3004
+ const walk = (nodes) => {
3005
+ for (const n of nodes) {
3006
+ if (n.type !== 'element')
3007
+ continue;
3008
+ if (n.tag.toLowerCase() === 'ng-content')
3009
+ found = true;
3010
+ walk(n.children);
3011
+ }
3012
+ };
3013
+ walk(ast.children);
3014
+ return found;
3015
+ })();
3016
+ // Routing (Stage 9): a component injecting ActivatedRoute reads
3017
+ // the instance from ActivatedRouteContext, which the outlet
3018
+ // provides around the routed subtree. It is not an @Input and
3019
+ // never appears in author templates.
3020
+ let propsDecl = '';
3021
+ if (inputs.length || outputs.length || usesProjection) {
3022
+ const destructured = [];
3023
+ const types = [];
3024
+ if (usesProjection) {
3025
+ destructured.push('children');
3026
+ types.push('children?: any');
3027
+ }
3028
+ for (const f of inputs) {
3029
+ const def = f.initializer && isLiteralInitializer(f.initializer) ? ` = ${f.initializer}` : '';
3030
+ destructured.push(`${f.name}${def}`);
3031
+ types.push(`${f.name}?: any`);
3032
+ }
3033
+ for (const f of outputs) {
3034
+ destructured.push(outputPropName(f.name));
3035
+ types.push(`${outputPropName(f.name)}?: (value: any) => void`);
3036
+ }
3037
+ propsDecl = `{ ${destructured.join(', ')} }: { ${types.join('; ')} }`;
3038
+ }
3039
+ // --- Dependency injection (M6): constructor deps -> container lookups.
3040
+ const depLines = [];
3041
+ for (const dep of component.constructorDeps ?? []) {
3042
+ if (dep.typeName === HTTP_CLIENT) {
3043
+ this.usedRuntime.add('Container');
3044
+ this.usedRuntime.add(HTTP_CLIENT);
3045
+ depLines.push(` const ${dep.propertyName} = __container.get<HttpClient>(HttpClient);`);
3046
+ }
3047
+ else if (this.routingActive && dep.typeName === 'Router') {
3048
+ depLines.push(` const ${dep.propertyName} = __router;`);
3049
+ }
3050
+ else if (this.routingActive && dep.typeName === 'ActivatedRoute') {
3051
+ this.reactImports.add('useContext');
3052
+ this.usedUi.add('ActivatedRouteContext');
3053
+ this.usedRuntime.add('ActivatedRoute');
3054
+ depLines.push(` const ${dep.propertyName} = useContext(ActivatedRouteContext) ?? new ActivatedRoute({});`);
3055
+ }
3056
+ else if (dep.typeName === 'SnackBar') {
3057
+ depLines.push(` const ${dep.propertyName} = __snackBar;`);
3058
+ }
3059
+ else if (dep.typeName === 'FormBuilder') {
3060
+ this.usedRuntime.add('Container');
3061
+ this.usedRuntime.add('FormBuilder');
3062
+ depLines.push(` const ${dep.propertyName} = __container.get<FormBuilder>(FormBuilder);`);
3063
+ }
3064
+ else if (this.rootServices.has(dep.typeName)) {
3065
+ this.usedRuntime.add('Container');
3066
+ this.reactImports.add('useSyncExternalStore');
3067
+ depLines.push(` const ${dep.propertyName} = __container.get<${dep.typeName}>(${dep.typeName});`);
3068
+ depLines.push(` useSyncExternalStore((cb) => ${dep.propertyName}.__subscribe(cb), () => ${dep.propertyName}.__getVersion());`);
3069
+ }
3070
+ else {
3071
+ this.validateDeps(`Component ${component.className}`, [dep], true);
3072
+ depLines.push(` // TODO(Rangular DI): no provider for '${forLineComment(dep.typeName)}', '${forLineComment(dep.propertyName)}' is unavailable.`);
3073
+ }
3074
+ }
3075
+ // --- Fields: state hoisting (M3) ------------------------------------------
3076
+ // A non-literal initializer that is never assigned and does not
3077
+ // reference `this` is emitted verbatim as a plain const (proof
3078
+ // fix): `today = new Date()` becomes `const today = new Date();`.
3079
+ // Anything else non-literal still cannot be placed, but it is
3080
+ // ALWAYS declared, as undefined with a TODO, so generated code
3081
+ // never references a name it does not declare.
3082
+ const verbatimInits = new Map(verbatimInitFields(component).map((f) => [f.name, f.initializer]));
3083
+ const fieldLines = [];
3084
+ for (const field of component.fields) {
3085
+ if (field.isInput || field.isOutput)
3086
+ continue;
3087
+ if (formFields.has(field.name))
3088
+ continue; // Stage 8: a ref below, not state.
3089
+ if (streamFields.has(field.name))
3090
+ continue; // RxJS adoption: a ref below, not a per-render const.
3091
+ if (signalFields.has(field.name))
3092
+ continue; // Signals adoption: a ref below, not a per-render const.
3093
+ if (field.initializer && isLiteralInitializer(field.initializer)) {
3094
+ if (stateFields.has(field.name)) {
3095
+ fieldLines.push(` const [${field.name}, ${(0, methods_1.setterName)(field.name)}] = useState(${field.initializer});`);
3096
+ }
3097
+ else {
3098
+ fieldLines.push(` const ${field.name} = ${field.initializer};`);
3099
+ }
3100
+ }
3101
+ else if (field.initializer && verbatimInits.has(field.name)) {
3102
+ fieldLines.push(` const ${field.name} = ${verbatimInits.get(field.name)};`);
3103
+ }
3104
+ else if (field.initializer) {
3105
+ fieldLines.push(` // TODO: field '${forLineComment(field.name)}' has a non-literal initializer (${forLineComment(field.initializer)}) that cannot be emitted verbatim; it is declared as undefined so this file still compiles, wire the value up manually for now.`);
3106
+ fieldLines.push(` const ${field.name} = undefined;`);
3107
+ diagnostics.push((0, diagnostics_1.warning)('GEN_FIELD', `Field '${field.name}' has a non-literal initializer that cannot be emitted verbatim (it references 'this', or the field is assigned in a method); it is declared as undefined in the generated component`, undefined, undefined, `Initialise '${field.name}' with a literal (including arrays/objects of literals), or with a value that does not reference 'this' (for example new Date() or Date.now()), or wire the value up manually in the generated component`));
3108
+ }
3109
+ }
3110
+ // A computed() initializer's arrow reads its inputs through this:
3111
+ // this.<signal field> becomes the field's ref, and this.<dep>
3112
+ // becomes the generated dep local (a service's signals track
3113
+ // through the render tracker like the component's own). Anything
3114
+ // else on this (a plain field, a method) cannot be tracked, so it
3115
+ // is reported and the caller degrades the field.
3116
+ const rewriteComputedInitializer = (init) => {
3117
+ let text = init;
3118
+ const refNames = [...formFields.keys(), ...streamFields, ...signalFields.keys()];
3119
+ for (const name of refNames) {
3120
+ text = text.replace(new RegExp(`this\\.${name}\\b`, 'g'), `${name}Ref.current`);
3121
+ }
3122
+ for (const dep of component.constructorDeps ?? []) {
3123
+ text = text.replace(new RegExp(`this\\.${dep.propertyName}\\b`, 'g'), dep.propertyName);
3124
+ }
3125
+ const bad = /\bthis\.([A-Za-z_$][\w$]*)/.exec(text);
3126
+ if (bad)
3127
+ return { badRef: bad[1] };
3128
+ return { text };
3129
+ };
3130
+ // --- Reactive form instances (Stage 8) -----------------------------------
3131
+ // A FormGroup/FormControl field is one stable instance per component
3132
+ // instance, held in a ref with its initializer verbatim (the author's
3133
+ // own @angular/forms code, re-homed to the runtime classes). Control
3134
+ // value changes bump a version counter through valueChanges, so the
3135
+ // component re-renders and template reads like
3136
+ // profileForm.get('email').invalid stay live, the same notify shape
3137
+ // services use.
3138
+ const formLines = [];
3139
+ if (formFields.size || streamFields.size || signalFields.size) {
3140
+ this.reactImports.add('useRef');
3141
+ this.reactImports.add('useState');
3142
+ this.reactImports.add('useEffect');
3143
+ for (const field of component.fields) {
3144
+ const info = formFields.get(field.name);
3145
+ if (info) {
3146
+ const initText = info.builderDep && field.initializer
3147
+ ? (0, formInit_1.rewriteBuilderInitializer)(field.initializer, info.builderDep)
3148
+ : field.initializer;
3149
+ formLines.push(` const ${field.name}Ref = useRef(${initText});`);
3150
+ }
3151
+ else if (streamFields.has(field.name) && field.initializer) {
3152
+ formLines.push(` const ${field.name}Ref = useRef(${field.initializer});`);
3153
+ }
3154
+ else if (signalFields.has(field.name) && field.initializer) {
3155
+ // Signals adoption: the ref holds the one signal or computed
3156
+ // instance; the runtime name joins the file's runtime import.
3157
+ if (signalFields.get(field.name) === 'signal') {
3158
+ this.usedRuntime.add('signal');
3159
+ formLines.push(` const ${field.name}Ref = useRef(${field.initializer});`);
3160
+ }
3161
+ else {
3162
+ const rewritten = rewriteComputedInitializer(field.initializer);
3163
+ if (rewritten.text) {
3164
+ this.usedRuntime.add('computed');
3165
+ formLines.push(` const ${field.name}Ref = useRef(${rewritten.text});`);
3166
+ }
3167
+ else {
3168
+ diagnostics.push((0, diagnostics_1.warning)('GEN_SIGNAL_SCOPE', `Field '${field.name}': the computed() initializer reads 'this.${rewritten.badRef}', which is not a signal or computed field or an injected service; a computed value can only track signals, so the field is declared as undefined in the generated component`, undefined, undefined, `Read only signal and computed fields (and signals on injected services) inside computed(); derive from a plain field with a method instead, which the template calls fresh on every render`));
3169
+ formLines.push(` // TODO: computed field '${forLineComment(field.name)}' reads 'this.${forLineComment(rewritten.badRef ?? '')}', which a computed value cannot track; it is declared as undefined so this file still compiles.`);
3170
+ formLines.push(` const ${field.name}Ref = useRef(undefined);`);
3171
+ }
3172
+ }
3173
+ }
3174
+ }
3175
+ if (formFields.size) {
3176
+ const formTexts = [];
3177
+ for (const field of component.fields) {
3178
+ if (formFields.has(field.name) && field.initializer)
3179
+ formTexts.push(field.initializer);
3180
+ }
3181
+ for (const m of component.methodDetails)
3182
+ if (m.body)
3183
+ formTexts.push(m.body);
3184
+ for (const name of ['FormGroup', 'FormControl', 'FormArray', 'FormBuilder', 'Validators']) {
3185
+ if (formTexts.some((t) => new RegExp(`\\b${name}\\b`).test(t)))
3186
+ this.usedRuntime.add(name);
3187
+ }
3188
+ formLines.push(' const [, setFormVersion] = useState(0);');
3189
+ formLines.push(' useEffect(() => {');
3190
+ formLines.push(' const subs = [');
3191
+ for (const field of component.fields) {
3192
+ const info = formFields.get(field.name);
3193
+ if (!info)
3194
+ continue;
3195
+ if (info.kind === 'group') {
3196
+ formLines.push(` ...Object.values(${field.name}Ref.current.controls).map((control) => control.valueChanges.subscribe(() => setFormVersion((v) => v + 1))),`);
3197
+ }
3198
+ else {
3199
+ formLines.push(` ${field.name}Ref.current.valueChanges.subscribe(() => setFormVersion((v) => v + 1)),`);
3200
+ }
3201
+ }
3202
+ formLines.push(' ];');
3203
+ formLines.push(' return () => { subs.forEach((sub) => sub.unsubscribe()); };');
3204
+ formLines.push(' }, []);');
3205
+ }
3206
+ }
3207
+ // --- Template-driven validation models (Stage 8) -------------------------
3208
+ // One model per ngModel input that declares validators or an
3209
+ // #ref="ngModel": a touched state (set on blur), a dirty state
3210
+ // (set when the user changes the value) plus an errors object
3211
+ // recomputed from the field on every render by the runtime
3212
+ // validators. The model is what a template reference reads
3213
+ // (email.invalid, email.touched, email.dirty, email.errors), via
3214
+ // the chain-root rewrite in
3215
+ // exprToCode.
3216
+ const modelLines = [];
3217
+ for (const info of modelInfos) {
3218
+ const key = info.key;
3219
+ const field = info.field;
3220
+ this.reactImports.add('useState');
3221
+ modelLines.push(` const [${key}Touched, ${(0, methods_1.setterName)(`${key}Touched`)}] = useState(false);`);
3222
+ modelLines.push(` const [${key}Dirty, ${(0, methods_1.setterName)(`${key}Dirty`)}] = useState(false);`);
3223
+ const validSpecs = info.validators.filter((v) => !v.argInvalid);
3224
+ for (const v of info.validators) {
3225
+ if (!v.argInvalid)
3226
+ continue;
3227
+ diagnostics.push((0, diagnostics_1.warning)('GEN_VALIDATOR_ARG', `The ${v.fn} validator on the '${field}' input has a static attribute value that is not a plain number; the validator was dropped (static attribute text is never emitted into generated code)`, undefined, undefined, `Write the length as a plain number, e.g. minlength="3", or bind it: [minlength]="3"`));
3228
+ }
3229
+ if (validSpecs.length) {
3230
+ this.usedRuntime.add('Validators');
3231
+ this.usedRuntime.add('validateValue');
3232
+ const calls = validSpecs
3233
+ .map((v) => (v.argSource !== undefined ? `Validators.${v.fn}(${v.argSource})` : `Validators.${v.fn}`))
3234
+ .join(', ');
3235
+ modelLines.push(` const ${key}Errors = validateValue(${field}, [${calls}]);`);
3236
+ }
3237
+ else {
3238
+ modelLines.push(` const ${key}Errors = null;`);
3239
+ }
3240
+ modelLines.push(` const ${key}Model = { value: ${field}, errors: ${key}Errors, valid: ${key}Errors === null, invalid: ${key}Errors !== null, touched: ${key}Touched, dirty: ${key}Dirty, pristine: !${key}Dirty, untouched: !${key}Touched };`);
3241
+ }
3242
+ // --- Methods: translation (M3) --------------------------------------------
3243
+ const outputCallbacks = new Map();
3244
+ for (const f of outputs)
3245
+ outputCallbacks.set(f.name, outputPropName(f.name));
3246
+ const { methods: translated, diagnostics: methodDiags } = (0, methods_1.translateMethods)(component, 'react', stateFields, {
3247
+ outputCallbacks,
3248
+ formFields: new Set([...formFields.keys(), ...streamFields, ...signalFields.keys()]),
3249
+ });
3250
+ diagnostics.push(...methodDiags);
3251
+ // A method named like a generated setter (set + a state field's
3252
+ // name, or a form field's touched setter) would be declared
3253
+ // twice in the generated function, the later one winning. That
3254
+ // collision used to be silent (the capstone's setMinutes); it
3255
+ // is an error now, with the rename as the fix.
3256
+ const generatedSetters = new Set();
3257
+ for (const f of stateFields)
3258
+ generatedSetters.add((0, methods_1.setterName)(f));
3259
+ for (const info of modelInfos) {
3260
+ if (info.key)
3261
+ generatedSetters.add((0, methods_1.setterName)(`${info.key}Touched`));
3262
+ if (info.key)
3263
+ generatedSetters.add((0, methods_1.setterName)(`${info.key}Dirty`));
3264
+ }
3265
+ for (const m of translated) {
3266
+ if (generatedSetters.has(m.name)) {
3267
+ diagnostics.push((0, diagnostics_1.error)('GEN_SETTER_COLLISION', `Method '${m.name}' has the same name as a generated state setter in this component; the generated code would declare '${m.name}' twice and one would overwrite the other`, undefined, undefined, `Rename the method to say what it does, e.g. a method that chooses a value by hand can be named pick${m.name.slice(3)} or update${m.name.slice(3)}; the setter name (set + the field name) belongs to the generated code`));
3268
+ }
3269
+ }
3270
+ const methodLines = [];
3271
+ for (const m of translated) {
3272
+ methodLines.push(` const ${m.name} = (${m.paramTexts.join(', ')}) => {`);
3273
+ for (const line of m.lines)
3274
+ methodLines.push(line ? ` ${line}` : line);
3275
+ methodLines.push(' };');
3276
+ }
3277
+ // --- Constructor body (0.6.5): runs once on mount, before ngOnInit ----
3278
+ // A component constructor used to be read for its DI parameters
3279
+ // only; its statements were dropped silently. Now the body is
3280
+ // translated like a method body and runs in the mount effect,
3281
+ // ahead of ngOnInit, which is Angular's order.
3282
+ let ctorLines = [];
3283
+ if (component.constructorBody) {
3284
+ const ctorHost = {
3285
+ fields: component.fields,
3286
+ methods: component.methods,
3287
+ methodDetails: [{
3288
+ name: 'constructor',
3289
+ params: (component.constructorDeps ?? []).map((d) => ({
3290
+ name: d.propertyName,
3291
+ text: `private ${d.propertyName}: ${d.typeName}`,
3292
+ })),
3293
+ body: component.constructorBody,
3294
+ }],
3295
+ };
3296
+ const { methods: ctorTranslated, diagnostics: ctorDiags } = (0, methods_1.translateMethods)(ctorHost, 'react', stateFields, {
3297
+ outputCallbacks,
3298
+ formFields: new Set([...formFields.keys(), ...streamFields, ...signalFields.keys()]),
3299
+ });
3300
+ diagnostics.push(...ctorDiags);
3301
+ ctorLines = ctorTranslated[0]?.lines ?? [];
3302
+ }
3303
+ // --- Signals: effect placement (signals adoption) -----------------------
3304
+ // effect() calls in the constructor or ngOnInit are created inside
3305
+ // an effect scope opened by the mount effect below, so the cleanup
3306
+ // the scope returns destroys them on unmount. effect() anywhere
3307
+ // else still runs, but nothing destroys it with the component;
3308
+ // that earns one warning per method.
3309
+ const EFFECT_CALL_RE = /\beffect\s*\(/;
3310
+ const ngOnInitBody = component.methodDetails.find((m) => m.name === 'ngOnInit')?.body ?? '';
3311
+ const lifecycleUsesEffect = EFFECT_CALL_RE.test(component.constructorBody ?? '') || EFFECT_CALL_RE.test(ngOnInitBody);
3312
+ if (lifecycleUsesEffect || component.methodDetails.some((m) => m.body && EFFECT_CALL_RE.test(m.body))) {
3313
+ this.usedRuntime.add('effect');
3314
+ }
3315
+ if (lifecycleUsesEffect) {
3316
+ this.usedRuntime.add('beginEffectScope');
3317
+ this.usedRuntime.add('endEffectScope');
3318
+ }
3319
+ for (const m of component.methodDetails) {
3320
+ if (m.name === 'ngOnInit' || !m.body || !EFFECT_CALL_RE.test(m.body))
3321
+ continue;
3322
+ diagnostics.push((0, diagnostics_1.warning)('GEN_SIGNAL_EFFECT_CONTEXT', `Method '${m.name}' calls effect(); an effect created outside the constructor or ngOnInit is not destroyed when the component is destroyed`, undefined, undefined, 'Move the effect() call into the constructor or ngOnInit; effects created there are destroyed with the component'));
3323
+ }
3324
+ // --- Lifecycle (M6): ngOnInit / ngOnDestroy -> useEffect ----------------
3325
+ const lifecycleLines = [];
3326
+ const translatedNames = new Set(translated.map((m) => m.name));
3327
+ const hasInit = translatedNames.has('ngOnInit');
3328
+ const hasDestroy = translatedNames.has('ngOnDestroy');
3329
+ if (hasInit || hasDestroy || ctorLines.length) {
3330
+ this.reactImports.add('useEffect');
3331
+ lifecycleLines.push(' useEffect(() => {');
3332
+ if (lifecycleUsesEffect)
3333
+ lifecycleLines.push(' beginEffectScope();');
3334
+ for (const line of ctorLines)
3335
+ lifecycleLines.push(line ? ` ${line}` : line);
3336
+ if (hasInit)
3337
+ lifecycleLines.push(' ngOnInit();');
3338
+ if (lifecycleUsesEffect)
3339
+ lifecycleLines.push(' const __endEffects = endEffectScope();');
3340
+ if (hasDestroy && lifecycleUsesEffect) {
3341
+ lifecycleLines.push(' return () => {');
3342
+ lifecycleLines.push(' __endEffects();');
3343
+ lifecycleLines.push(' ngOnDestroy();');
3344
+ lifecycleLines.push(' };');
3345
+ }
3346
+ else if (hasDestroy) {
3347
+ lifecycleLines.push(' return () => {');
3348
+ lifecycleLines.push(' ngOnDestroy();');
3349
+ lifecycleLines.push(' };');
3350
+ }
3351
+ else if (lifecycleUsesEffect) {
3352
+ lifecycleLines.push(' return () => {');
3353
+ lifecycleLines.push(' __endEffects();');
3354
+ lifecycleLines.push(' };');
3355
+ }
3356
+ lifecycleLines.push(' }, []);');
3357
+ }
3358
+ // Snackbar host (Stage 10): only the entry component renders it,
3359
+ // as the last sibling inside the returned tree, so an app with a
3360
+ // snackbar always returns a fragment even for a single root.
3361
+ if (opts.entry && this.snackActive) {
3362
+ this.usedUi.add('RgSnackbar');
3363
+ bodyLines.push(' {__snack && (<RgSnackbar message={__snack.message} actionLabel={__snack.actionLabel} onAction={() => __snackBar.pressAction()} />)}');
3364
+ }
3365
+ // A template whose root is a structural directive (or several roots)
3366
+ // cannot be returned bare, `{cond && (...)}` alone is not valid JSX,
3367
+ // so it is wrapped in a fragment. A single plain element root (the
3368
+ // common <screen> shape) is returned as-is, exactly as in Stage 2.
3369
+ // --- Signals: the render tracker (signals adoption) ---------------------
3370
+ // Every generated component carries a render tracker. begin() runs
3371
+ // just before the returned view is evaluated and end() right after
3372
+ // (the try/finally around the return below), so every signal the
3373
+ // view reads, directly, through a method it calls, or through an
3374
+ // injected service, subscribes exactly this component, and a write
3375
+ // to any of them re-renders it. The tracker is disposed on unmount.
3376
+ this.reactImports.add('useRef');
3377
+ this.reactImports.add('useReducer');
3378
+ this.reactImports.add('useEffect');
3379
+ this.usedRuntime.add('SignalRenderTracker');
3380
+ const signalLines = [
3381
+ ' const [, __sigBump] = useReducer((n: number) => n + 1, 0);',
3382
+ ' const __sigTracker = useRef(new SignalRenderTracker(__sigBump));',
3383
+ ' useEffect(() => () => { __sigTracker.current.dispose(); }, []);',
3384
+ ];
3385
+ const only = ast.children.length === 1 ? ast.children[0] : undefined;
3386
+ const bareRoot = !!only && (only.type === 'text' || !only.structural) && !(opts.entry && this.snackActive);
3387
+ const returnLines = [
3388
+ ' __sigTracker.current.begin();',
3389
+ ' try {',
3390
+ ...(bareRoot
3391
+ ? [' return (', ...bodyLines.map((l) => (l ? ` ${l}` : l)), ' );']
3392
+ : [
3393
+ ' return (',
3394
+ ' <>',
3395
+ ...bodyLines.map((l) => (l ? ` ${l}` : l)),
3396
+ ' </>',
3397
+ ' );',
3398
+ ]),
3399
+ ' } finally {',
3400
+ ' __sigTracker.current.end();',
3401
+ ' }',
3402
+ ];
3403
+ // --- Navigation state (Stage 9) ------------------------------------------
3404
+ // The entry component hosting the outlet mirrors the navigator's
3405
+ // current entry in state, so a navigation re-renders it and the
3406
+ // outlet swaps the route component. The subscription is the
3407
+ // useEffect cleanup, the same shape lifecycle uses.
3408
+ const navLines = [];
3409
+ if (opts.entry && opts.hasOutlet && this.routingActive) {
3410
+ this.reactImports.add('useState');
3411
+ this.reactImports.add('useEffect');
3412
+ navLines.push(' const [__route, __setRoute] = useState(__navigator.current);');
3413
+ navLines.push(' useEffect(() => __navigator.subscribe(() => __setRoute(__navigator.current)), []);');
3414
+ }
3415
+ // Snackbar state (Stage 10): the entry component mirrors the
3416
+ // module-level service's current bar in React state. The service
3417
+ // owns timing and action callbacks; this bridge only renders the
3418
+ // host while a bar is open.
3419
+ const snackLines = [];
3420
+ if (opts.entry && this.snackActive) {
3421
+ this.reactImports.add('useState');
3422
+ this.reactImports.add('useEffect');
3423
+ snackLines.push(' const [__snack, __setSnack] = useState(__snackBar.current);');
3424
+ snackLines.push(' useEffect(() => __snackBar.subscribe(() => __setSnack(__snackBar.current)), []);');
3425
+ }
3426
+ const exportKw = opts.entry ? 'export default function' : 'export function';
3427
+ return [
3428
+ `${exportKw} ${fnName}(${propsDecl}) {`,
3429
+ ...depLines,
3430
+ ...navLines,
3431
+ ...snackLines,
3432
+ ...signalLines,
3433
+ ...fieldLines,
3434
+ ...formLines,
3435
+ ...modelLines,
3436
+ ...asyncLines,
3437
+ ...methodLines,
3438
+ ...lifecycleLines,
3439
+ ...returnLines,
3440
+ '}',
3441
+ ];
3442
+ }
3443
+ }
3444
+ function stylePrefixOf(info) {
3445
+ const fn = componentFunctionName(info.className);
3446
+ return fn.charAt(0).toLowerCase() + fn.slice(1);
3447
+ }
3448
+ /** StyleSheet key for a component's CSS rule, namespaced per child component. */
3449
+ function styleKeyFor(prefix, key) {
3450
+ const base = styleKeyName(key);
3451
+ if (!prefix)
3452
+ return base;
3453
+ return prefix + base.charAt(0).toUpperCase() + base.slice(1);
3454
+ }
3455
+ /**
3456
+ * Generate a React Native .tsx from a parsed component, its template AST
3457
+ * and its parsed styles. Stage 3: the optional context carries the child
3458
+ * components and services resolved through the entry's imports, everything
3459
+ * is emitted into the same file (see the Generator note above).
3460
+ */
3461
+ function generateComponent(component, ast, css, context = {}) {
3462
+ const generator = new Generator(context);
3463
+ const children = context.children ?? [];
3464
+ const code = generator.generate(component, ast, css, children);
3465
+ return { code, diagnostics: generator.diagnostics, sourceMap: generator.sourceMapOut };
3466
+ }