@nstudio/nativescript-compiler-angular 0.0.0-stage → 9.2.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4189 @@
1
+ import * as ng from '@angular/compiler';
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
4
+ import { createRequire } from 'node:module';
5
+ import { dirname, extname, isAbsolute, join, relative } from 'node:path';
6
+ import { core, ts } from "./core-api.js";
7
+ import { flattenComponent, inheritedDirectiveClasses, isRealDirectiveBaseChain, openStatics } from "./component-bases.js";
8
+ import { decorator } from "./ng-modules.js";
9
+ /** The elements of the binary-only plugins `release.stubPlugins` can stub, by lowercase tag, and their packages. */
10
+ const STUB_ELEMENTS = {
11
+ radradialgauge: 'nativescript-ui-gauge',
12
+ radlistview: 'nativescript-ui-listview',
13
+ radsidedrawer: 'nativescript-ui-sidedrawer',
14
+ radcalendar: 'nativescript-ui-calendar',
15
+ raddataform: 'nativescript-ui-dataform',
16
+ radautocompletetextview: 'nativescript-ui-autocomplete',
17
+ radcartesianchart: 'nativescript-ui-chart',
18
+ radpiechart: 'nativescript-ui-chart',
19
+ };
20
+ /** What a stubbed element keeps: its place in the layout and its box, which its stand-in, an empty ContentView, takes. */
21
+ const STUB_LAYOUT_ATTRS = new Set([
22
+ 'row', 'col', 'rowSpan', 'colSpan', 'width', 'height', 'minWidth', 'minHeight',
23
+ 'class', 'scaleX', 'scaleY', 'translateX', 'translateY', 'rotate', 'opacity', 'visibility',
24
+ 'horizontalAlignment', 'verticalAlignment',
25
+ 'margin', 'marginTop', 'marginRight', 'marginBottom', 'marginLeft',
26
+ 'padding', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft',
27
+ 'left', 'top', 'dock', 'order', 'flexGrow', 'flexShrink', 'alignSelf',
28
+ 'backgroundColor', 'borderRadius', 'borderWidth', 'borderColor',
29
+ ]);
30
+ const stubbedElement = (tag) => {
31
+ const pkg = STUB_ELEMENTS[tag.replace(/-/g, '').toLowerCase()];
32
+ return !!pkg && core.stubbedPlugins.has(pkg);
33
+ };
34
+ /** The build's own module of the Angular runtime its templates use (`runtime/angular.ts`): @angular/common's pipes, QueryList. */
35
+ export const RUNTIME = '@angular#runtime';
36
+ const COMMON_PIPES = {
37
+ async: { className: 'AsyncPipe', file: '@angular#rx', pure: false },
38
+ date: { className: 'DatePipe', file: RUNTIME, pure: true },
39
+ number: { className: 'DecimalPipe', file: RUNTIME, pure: true },
40
+ percent: { className: 'PercentPipe', file: RUNTIME, pure: true },
41
+ uppercase: { className: 'UpperCasePipe', file: RUNTIME, pure: true },
42
+ lowercase: { className: 'LowerCasePipe', file: RUNTIME, pure: true },
43
+ titlecase: { className: 'TitleCasePipe', file: RUNTIME, pure: true },
44
+ json: { className: 'JsonPipe', file: RUNTIME, pure: false },
45
+ slice: { className: 'SlicePipe', file: RUNTIME, pure: false },
46
+ keyvalue: { className: 'KeyValuePipe', file: RUNTIME, pure: false },
47
+ };
48
+ const UNSUPPORTED_COMMON_PIPES = new Set(['currency', 'i18nPlural', 'i18nSelect']);
49
+ /**
50
+ * Every NativeScript Angular `@Component` class in `path` as a virtual class: the file's own source with one method
51
+ * appended per template expression on each component class. Multiple `@Component` classes in one file share one virtual
52
+ * `.release.ts` file so imports and file-local helpers resolve without duplication.
53
+ */
54
+ export function angularComponents(path, text, selectors, options = {}) {
55
+ if (!text.includes('@Component'))
56
+ return [];
57
+ const initialSf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
58
+ const targets = initialSf.statements
59
+ .filter((s) => ts.isClassDeclaration(s) && !!s.name && !!decorator(s, 'Component'))
60
+ .map((s) => s.name.text);
61
+ if (!targets.length)
62
+ return [];
63
+ let currentText = text;
64
+ const results = [];
65
+ for (const targetName of targets) {
66
+ const beforeLines = currentText.split('\n').length;
67
+ const { component, nextText, prependedLines } = compileOneComponent(path, text, currentText, targetName, selectors, options);
68
+ if (prependedLines > 0) {
69
+ for (const prev of results) {
70
+ if (prev.templateLines)
71
+ prev.templateLines.lines = prev.templateLines.lines.map(([v, src]) => [v + prependedLines, src]);
72
+ }
73
+ }
74
+ void beforeLines;
75
+ currentText = nextText;
76
+ results.push(component);
77
+ }
78
+ const stripped = declarableSource(path, currentText);
79
+ if (stripped)
80
+ currentText = stripped;
81
+ for (const c of results)
82
+ c.source = currentText;
83
+ return results;
84
+ }
85
+ /**
86
+ * A NativeScript Angular standalone component (`@Component` with a template
87
+ * of @nativescript/core elements, signals, `input()`/`output()`, `inject()`)
88
+ * as a virtual class: the component's own source with one method appended
89
+ * per template expression. The class keeps Angular's API; the translator
90
+ * knows what `signal()`, `computed()`, `input()`, `output()` and `inject()` mean.
91
+ */
92
+ export function angularComponent(path, text, selectors, options = {}) {
93
+ return angularComponents(path, text, selectors, options)[0] ?? null;
94
+ }
95
+ function compileOneComponent(path, written, text, targetName, selectors, options) {
96
+ const findTarget = (source) => source.statements.find((s) => ts.isClassDeclaration(s) && s.name?.text === targetName && !!decorator(s, 'Component'));
97
+ let sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
98
+ let cls = findTarget(sf);
99
+ const asWritten = cls;
100
+ let prependedLines = 0;
101
+ const flat = flattenComponent(path, text, cls.name.text, undefined, undefined, options.aliased);
102
+ const opened = openStatics(flat ?? text, flat === null ? cls : findTarget(ts.createSourceFile(path, flat, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)));
103
+ if (opened !== text) {
104
+ text = opened;
105
+ sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
106
+ cls = findTarget(sf);
107
+ }
108
+ // A class with decorated inputs and outputs, or constructor injection, as the signal-style class the translator reads.
109
+ const classic = classicClass(path, text, cls);
110
+ if (classic) {
111
+ prependedLines += classic.prependedLines;
112
+ text = classic.text;
113
+ sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
114
+ cls = findTarget(sf);
115
+ }
116
+ const meta = decorator(cls, 'Component').arguments[0];
117
+ const prop = (name) => meta.properties.find((p) => ts.isPropertyAssignment(p) && p.name.text === name)?.initializer;
118
+ for (const p of meta.properties) {
119
+ const key = ts.isPropertyAssignment(p) && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) ? p.name.text : null;
120
+ if (key === null)
121
+ throw new Error(`${path}: @Component's ${p.getText().split('\n')[0]} is read as \`name: value\` in a release build`);
122
+ if (key === 'preserveWhitespaces' && p.initializer.kind !== ts.SyntaxKind.FalseKeyword)
123
+ throw new Error(`${path}: @Component's preserveWhitespaces is not supported in a release build yet`);
124
+ if (!COMPONENT_META.has(key))
125
+ throw new Error(`${path}: @Component's ${key} is not supported in a release build yet`);
126
+ }
127
+ const providers = prop('providers');
128
+ const viewProviders = prop('viewProviders');
129
+ const hasProviders = !!(providers || viewProviders);
130
+ if (hasProviders) {
131
+ refuseScopedInjection(path, asWritten);
132
+ text = withInjector(path, text, cls, providers, viewProviders);
133
+ sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
134
+ cls = findTarget(sf);
135
+ }
136
+ const hostMeta = prop('host');
137
+ const hostDirectivesMeta = prop('hostDirectives');
138
+ const selector = prop('selector')?.text ?? cls.name.text;
139
+ const inline = prop('template');
140
+ const templateUrl = prop('templateUrl')?.text;
141
+ const template = inline && (ts.isNoSubstitutionTemplateLiteral(inline) || ts.isStringLiteral(inline)) ? inline.text : templateUrl && existsSync(join(dirname(path), templateUrl)) ? readFileSync(join(dirname(path), templateUrl), 'utf8') : '';
142
+ // Angular 22's default strategy is OnPush.
143
+ const strategy = prop('changeDetection')?.getText();
144
+ const onPush = strategy !== 'ChangeDetectionStrategy.Default' && strategy !== 'ChangeDetectionStrategy.Eager';
145
+ /** A tag as @nativescript/angular's registry knows it: by its name, lowercased, or kebab-cased (`grid-layout`). */
146
+ const registered = new Map();
147
+ for (const [tag, cls] of options.elements ?? [])
148
+ for (const k of [tag, tag.toLowerCase(), tag.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()])
149
+ registered.set(k, cls);
150
+ const elementOf = (name) => core.canonical(name) ?? core.canonical(name.replace(/-/g, '')) ?? registered.get(name) ?? registered.get(name.toLowerCase()) ?? undefined;
151
+ const metas = new Map();
152
+ for (const [tag, keys] of options.elementMeta ?? [])
153
+ for (const k of [tag, tag.toLowerCase(), tag.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()])
154
+ metas.set(k, keys);
155
+ /**
156
+ * A plugin tag registered with a `ViewClassMeta` (`registerElement('Drawer', () => Drawer, meta)`): `insertChild` and
157
+ * `removeChild` run at runtime through the kit's `ViewMetaRegistry`; `skipAddToDom` and invisible-node hooks remain refused.
158
+ */
159
+ const checkMeta = (n) => {
160
+ if (core.canonical(n.name) || core.canonical(n.name.replace(/-/g, '')))
161
+ return;
162
+ const keys = metas.has(n.name) ? metas.get(n.name) : metas.get(n.name.toLowerCase());
163
+ if (keys === undefined)
164
+ return;
165
+ if (keys === null)
166
+ throw new Error(`${path}: <${n.name}> is registered with a ViewClassMeta the build cannot read (not an object literal in the registering file)`);
167
+ if (keys.includes('skipAddToDom'))
168
+ throw new Error(`${path}: <${n.name}> is registered with skipAddToDom, which a release build does not support yet`);
169
+ const hooks = keys.filter((k) => ['insertInvisibleNode', 'removeInvisibleNode'].includes(k));
170
+ if (hooks.length && n.children.some((c) => !(c instanceof ng.TmplAstText) || c.value.trim())) {
171
+ throw new Error(`${path}: the children of <${n.name}> join it through its registerElement meta (${hooks.join(', ')}), which a release build does not run yet`);
172
+ }
173
+ };
174
+ const { members, props, optional, outputs, inputAliases, inputTransforms } = publicMembers(path, cls, classic);
175
+ const inheritedSetters = new Set();
176
+ const inheritedBases = flat === null && isRealDirectiveBaseChain(path, sf, cls, options.readFile, options.aliased)
177
+ ? inheritedDirectiveClasses(path, sf, cls, options.readFile, options.aliased)
178
+ : [];
179
+ for (const base of inheritedBases) {
180
+ const bm = publicMembers(base.file, base.cls, null);
181
+ for (const m of bm.members)
182
+ members.add(m);
183
+ for (const p of bm.props)
184
+ if (!props.includes(p))
185
+ props.push(p);
186
+ for (const o of bm.optional)
187
+ if (!optional.includes(o))
188
+ optional.push(o);
189
+ for (const o of bm.outputs)
190
+ if (!outputs.includes(o))
191
+ outputs.push(o);
192
+ for (const [k, v] of Object.entries(bm.inputAliases))
193
+ if (!(k in inputAliases))
194
+ inputAliases[k] = v;
195
+ for (const k of bm.inputTransforms.keys())
196
+ if (!inputTransforms.has(k))
197
+ inheritedSetters.add(k);
198
+ }
199
+ const scope = { names: new Map([...members].map((m) => [m, classic?.inputs.has(m) ? `this.${m}()` : `this.${m}`])) };
200
+ const findLifecycleMethod = (name) => [cls, ...inheritedBases.map((b) => b.cls)]
201
+ .map((c) => c.members.find((x) => ts.isMethodDeclaration(x) && x.name.getText() === name))
202
+ .find(Boolean);
203
+ const init = findLifecycleMethod('ngOnInit');
204
+ /** A lifecycle hook the class implements: a method of that name, taking nothing. */
205
+ const hook = (name) => {
206
+ const m = findLifecycleMethod(name);
207
+ if (m?.parameters.length)
208
+ throw new Error(`${path}: ${name} takes no parameters`);
209
+ return !!m;
210
+ };
211
+ if (init && init.parameters.length)
212
+ throw new Error(`${path}: ngOnInit takes no parameters`);
213
+ const methods = [];
214
+ let next = 0;
215
+ let lets = 0;
216
+ const params = (loops) => loops.map((l) => l.param).join(', ');
217
+ const args = (loops) => loops.flatMap((l) => (l.index === undefined ? [l.item] : [l.item, l.index])).join(', ');
218
+ /** `*ngIf="x as y"`: names a structural directive binds, in the template it renders. */
219
+ const aliases = new Map();
220
+ const local = (loops) => {
221
+ const names = new Map(scope.names);
222
+ for (const [k, v] of aliases)
223
+ names.set(k, v);
224
+ for (const l of loops) {
225
+ names.delete(l.item);
226
+ if (l.index !== undefined)
227
+ names.delete(l.index);
228
+ for (const [k, v] of Object.entries(l.names ?? {}))
229
+ names.set(k, v);
230
+ }
231
+ return { names };
232
+ };
233
+ /**
234
+ * Each `| name` in the template is one pipe per view it renders in, as Angular's `ɵɵpipe` creates them: a local of the
235
+ * view (`$pN`), and for a pure pipe the arguments it last transformed (`$cN`), so `transform` runs only when one changes.
236
+ */
237
+ const sites = new Map();
238
+ const imported = new Map();
239
+ let usesRuntime = false;
240
+ let usesInject = false;
241
+ /** The class a pipe's name resolves to, imported into the component's file under a name of its own. */
242
+ const pipeClass = (name) => {
243
+ const decl = options.pipes?.get(name) ?? COMMON_PIPES[name];
244
+ if (!decl)
245
+ throw new Error(`${path}: the ${name} pipe is not one the release build knows: no @Pipe({ name: '${name}' }) class in the app or the libraries it imports${UNSUPPORTED_COMMON_PIPES.has(name) ? `, and @angular/common's ${name} pipe is not supported in a release build yet` : ''}`);
246
+ const from = decl.file === RUNTIME ? (usesRuntime = true, options.runtimeModule ?? RUNTIME) : decl.file;
247
+ const names = imported.get(from) ?? new Map();
248
+ imported.set(from, names);
249
+ if (!names.has(decl.className))
250
+ names.set(decl.className, `$Pipe_${decl.className}`);
251
+ return { alias: names.get(decl.className), decl };
252
+ };
253
+ /**
254
+ * The pipes in a node's own expressions, as locals of the view around it: the loops its methods take, and the node
255
+ * wrapped in them. A pipe class with constructor parameters is made through the `$create` the build adds to it,
256
+ * which injects them; one with `ngOnDestroy` is destroyed with its view.
257
+ */
258
+ const withPipes = (asts, loops) => {
259
+ const found = asts.flatMap((a) => (a ? allPipes(a instanceof ng.ASTWithSource ? a.ast : a) : [])).filter((p) => !sites.has(p));
260
+ if (!found.length)
261
+ return { loops, wrap: (body) => body };
262
+ const made = [];
263
+ let inner = loops;
264
+ for (const p of found) {
265
+ const { alias, decl } = pipeClass(p.name);
266
+ const k = sites.size;
267
+ const pipe = `$p${k}`;
268
+ let construct;
269
+ if (decl.deps?.length) {
270
+ usesInject = true;
271
+ const depArgs = decl.deps.map((dep) => {
272
+ const names = imported.get(dep.from) ?? new Map();
273
+ imported.set(dep.from, names);
274
+ if (!names.has(dep.name))
275
+ names.set(dep.name, `$PipeDep_${dep.name}`);
276
+ return `inject(${names.get(dep.name)})`;
277
+ });
278
+ construct = `new ${alias}(${depArgs.join(', ')})`;
279
+ }
280
+ else {
281
+ construct = decl.create ? `${alias}.$create()` : `new ${alias}()`;
282
+ }
283
+ const make = expr(construct, inner);
284
+ inner = [...inner, { item: pipe, param: `${pipe}: ${alias}` }];
285
+ const destroy = decl.destroy ? handlerOf(`${pipe}.ngOnDestroy()`, inner) : undefined;
286
+ made.push({ name: pipe, make, ...(destroy ? { destroy } : {}) });
287
+ let cache = null;
288
+ if (decl.pure) {
289
+ cache = `$c${k}`;
290
+ made.push({ name: cache, make: expr('new $PurePipeCache()', inner) });
291
+ inner = [...inner, { item: cache, param: `${cache}: $PurePipeCache` }];
292
+ }
293
+ sites.set(p, { pipe, cache });
294
+ }
295
+ return { loops: inner, wrap: (body) => made.reduceRight((b, l) => [{ kind: 'local', name: l.name, make: l.make, ...(l.destroy ? { destroy: l.destroy } : {}), body: b }], body) };
296
+ };
297
+ const keywordRead = (n) => n instanceof ng.PropertyRead && n.receiver instanceof ng.ImplicitReceiver && !(n.receiver instanceof ng.ThisReceiver) && KEYWORDS.has(n.name) && members.has(n.name);
298
+ /** The pipes and keyword-named member reads in an expression, outermost first (not those inside a pipe). */
299
+ const specialsIn = (node) => {
300
+ const found = [];
301
+ const visit = (n) => {
302
+ if (n instanceof ng.BindingPipe || keywordRead(n)) {
303
+ found.push(n);
304
+ return;
305
+ }
306
+ if (!(n instanceof ng.AST))
307
+ return;
308
+ for (const v of Object.values(n))
309
+ Array.isArray(v) ? v.forEach(visit) : visit(v);
310
+ };
311
+ if (node instanceof ng.BindingPipe || keywordRead(node))
312
+ return [node];
313
+ for (const v of Object.values(node))
314
+ Array.isArray(v) ? v.forEach(visit) : visit(v);
315
+ return found;
316
+ };
317
+ const code = (value, _loops) => {
318
+ const root = value instanceof ng.ASTWithSource ? value.ast : value;
319
+ const rawSrc = value instanceof ng.ASTWithSource && typeof value.source === 'string' ? value.source : null;
320
+ // `text="How {{ x }}"`: Angular renders the literal text with each expression's value, undefined and null as ''.
321
+ const interpolation = root instanceof ng.Interpolation ? root : null;
322
+ if (!specialsIn(root).length && !interpolation)
323
+ return value instanceof ng.ASTWithSource ? sourceOf(value) : template.slice(value.sourceSpan.start, value.sourceSpan.end);
324
+ const textOf = (node) => {
325
+ // A member named like a keyword (`continue()`): read on the component, which the expression's text cannot say.
326
+ if (keywordRead(node))
327
+ return `this.${node.name}`;
328
+ if (node instanceof ng.BindingPipe) {
329
+ const site = sites.get(node);
330
+ if (!site)
331
+ throw new Error(`${path}: the ${node.name} pipe where the release build gives it no view (in ${rawSrc ? rawSrc.slice(node.span.start, node.span.end) : template.slice(node.sourceSpan.start, node.sourceSpan.end)})`);
332
+ const given = [node.exp, ...node.args].map(textOf);
333
+ if (!site.cache)
334
+ return `${site.pipe}.transform(${given.join(', ')})`;
335
+ if (given.length > 5)
336
+ throw new Error(`${path}: the ${node.name} pipe with more than 4 arguments is not supported in a release build yet`);
337
+ const xs = given.map((_, i) => `$x${i}`);
338
+ return `${site.cache}.pure${given.length}(${given.map((g) => `(${g})`).join(', ')}, (${xs.join(', ')}) => ${site.pipe}.transform(${xs.join(', ')}))`;
339
+ }
340
+ const spanOf = (n) => (rawSrc !== null ? n.span : n.sourceSpan);
341
+ const sp = spanOf(node);
342
+ const at = sp.start;
343
+ let out = (rawSrc ?? template).slice(at, sp.end);
344
+ for (const p of specialsIn(node).sort((a, b) => spanOf(b).start - spanOf(a).start)) {
345
+ const ps = spanOf(p);
346
+ out = out.slice(0, ps.start - at) + textOf(p) + out.slice(ps.end - at);
347
+ }
348
+ return out;
349
+ };
350
+ const neverNullish = (n) => {
351
+ if (n instanceof ng.LiteralPrimitive)
352
+ return n.value != null;
353
+ if (n instanceof ng.PrefixNot || n instanceof ng.Unary)
354
+ return true;
355
+ if (n instanceof ng.Binary)
356
+ return !['&&', '||', '??'].includes(n.operation);
357
+ if (n instanceof ng.Conditional)
358
+ return neverNullish(n.trueExp) && neverNullish(n.falseExp);
359
+ return false;
360
+ };
361
+ if (interpolation)
362
+ return '`' + interpolation.strings.map((s, i) => s.replace(/[`\\$]/g, (x) => '\\' + x) + (i < interpolation.expressions.length ? (neverNullish(interpolation.expressions[i]) ? `\${(${textOf(interpolation.expressions[i])})}` : `\${(${textOf(interpolation.expressions[i])}) ?? ''}`) : '')).join('') + '`';
363
+ return textOf(root);
364
+ };
365
+ // `$any(x)` is Angular's escape from template type checking; the release build is typed by the component's code,
366
+ // except `$any($event)`, whose event data the handler reads as the type it declares.
367
+ // A string literal a template writes across lines is one string in the template's expression, and must stay one in TypeScript.
368
+ const clean = (code) => code
369
+ .replace(/(['"])(?:\\.|(?!\1)[\s\S])*?\1/g, (s) => s.replace(/\r?\n/g, '\\n').replace(/\r/g, '\\r'))
370
+ .replace(/\$any\(\s*\$event\s*\)/g, '($event as any)')
371
+ .replace(/\$any\(/g, '(');
372
+ /** The template line (0-based) of the binding being compiled, and each template method's (by its index in `methods`). */
373
+ let here = null;
374
+ const located = new Map();
375
+ const at = (span) => { if (span)
376
+ here = span.start.line; };
377
+ const add = (method) => {
378
+ methods.push(method);
379
+ if (here !== null)
380
+ located.set(methods.length - 1, here);
381
+ };
382
+ /** Pure narrowing guards from enclosing `@if` / `@else` branches so TypeScript narrows discriminated unions inside branch methods. */
383
+ let narrowing = [];
384
+ const guardPrefix = () => (narrowing.length ? `if (!(${narrowing.join(' && ')})) throw new Error(); ` : '');
385
+ const expr = (code, loops, untyped = false) => {
386
+ const m = `$b${next++}`;
387
+ add(` ${m}(${params(loops)})${untyped ? ': any' : ''} { ${guardPrefix()}return ${core.rewrite(clean(code), local(loops))}; }`);
388
+ return m;
389
+ };
390
+ /** A method of statements over the names in scope (a pipe's `ngOnDestroy`). */
391
+ const handlerOf = (statements, loops) => {
392
+ const m = `$e${next++}`;
393
+ add(` ${m}(${params(loops)}) { ${statements}; }`);
394
+ return m;
395
+ };
396
+ // A condition is tested, not held: a value its type says is there (a non-strict app's `signal<Person>(null)`) is read only for its truth.
397
+ const test = (code, loops) => expr(`!!(${code})`, loops);
398
+ // A component's output gives its handler the emitted value as `$event`; a view's event gives the event data.
399
+ const handler = (code, loops, payload = false) => {
400
+ const m = `$e${next++}`;
401
+ add(` ${m}(${[params(loops), `$event: ${payload ? 'any' : '$EventData'}`].filter(Boolean).join(', ')}) { ${guardPrefix()}${core.rewrite(clean(code), local(loops), 'statements')}; }`);
402
+ return m;
403
+ };
404
+ /** Enclosing projected component whose `contentChild`/`contentChildren` queries match nodes inside its slots. */
405
+ const activeContentHost = [];
406
+ const contentQueryHooks = (refs, component, tag, loops) => {
407
+ const host = activeContentHost.at(-1);
408
+ if (!host)
409
+ return [];
410
+ const hooks = [];
411
+ for (const q of host.queries) {
412
+ if (q.descendants === false && host.depth > 0)
413
+ continue;
414
+ if (q.ref ? !refs.includes(q.ref) : q.type !== component && q.type !== tag)
415
+ continue;
416
+ const instance = !!component && (q.read === null || q.read === component);
417
+ const wrapped = q.read === 'ElementRef' || (q.read === null && !component);
418
+ if (wrapped)
419
+ usesElementRef = true;
420
+ const own = instance ? component : !wrapped && q.read === tag ? tag : null;
421
+ const value = wrapped ? 'new $ElementRef($q)' : own || !q.read ? '$q' : `($q as ${q.read})`;
422
+ const inner = [...loops, { item: '$host', param: `$host: ${host.alias}` }, { item: '$q', param: `$q: ${own ?? 'any'}` }];
423
+ const set = q.many && !q.signal
424
+ ? handlerOf(`$host.$cqSet_${q.field}($q, ${value})`, inner)
425
+ : handlerOf(`$host.$cqSet_${q.field}(${value})`, inner);
426
+ const unset = q.signal
427
+ ? handlerOf(`$host.$cqUnset_${q.field}(${value})`, inner)
428
+ : q.many ? handlerOf(`$host.$cqUnset_${q.field}($q)`, inner) : undefined;
429
+ hooks.push({ set, ...(unset ? { unset } : {}), on: instance ? 'instance' : 'view', contentHost: true });
430
+ }
431
+ return hooks;
432
+ };
433
+ const directiveContentHooks = (d, loops) => {
434
+ const host = activeContentHost.at(-1);
435
+ if (!host)
436
+ return [];
437
+ const hooks = [];
438
+ for (const q of host.queries) {
439
+ if (q.descendants === false && host.depth > 0)
440
+ continue;
441
+ if (q.ref || q.type !== d.className)
442
+ continue;
443
+ const inner = [...loops, { item: '$host', param: `$host: ${host.alias}` }, { item: '$q', param: `$q: any` }];
444
+ const set = q.many && !q.signal
445
+ ? handlerOf(`$host.$cqSet_${q.field}($q, $q)`, inner)
446
+ : handlerOf(`$host.$cqSet_${q.field}($q)`, inner);
447
+ const unset = q.signal || q.many ? handlerOf(`$host.$cqUnset_${q.field}($q)`, inner) : undefined;
448
+ hooks.push({ set, ...(unset ? { unset } : {}), on: 'instance', contentHost: true });
449
+ }
450
+ return hooks;
451
+ };
452
+ /**
453
+ * The view queries an element or a component's host matches (`#ref`, or the component's class), as the methods that
454
+ * set and clear each one's field: an ElementRef of the view, the component itself, or the view read as its class.
455
+ * The field is set when the view is made and cleared when it goes, as a query's next refresh finds it gone.
456
+ */
457
+ const queryHooks = (refs, component, tag, loops) => {
458
+ const hooks = [];
459
+ for (const q of queries) {
460
+ if (q.ref ? !refs.includes(q.ref) : q.type !== component && q.type !== tag)
461
+ continue;
462
+ const instance = !!component && (q.read === null || q.read === component);
463
+ const wrapped = q.read === 'ElementRef' || (q.read === null && !component);
464
+ if (wrapped)
465
+ usesElementRef = true;
466
+ // The made node as its own class (the component, the element's view class), else untyped and read as the query's class.
467
+ const own = instance ? component : !wrapped && q.read === tag ? tag : null;
468
+ const value = wrapped ? 'new $ElementRef($q)' : own || !q.read ? '$q' : `($q as ${q.read})`;
469
+ const inner = [...loops, { item: '$q', param: `$q: ${own ?? 'any'}` }];
470
+ // A single query keeps its match once the match's view goes, which Angular's next refresh would clear.
471
+ const set = q.signal
472
+ ? handlerOf(q.many ? `this.${q.field}.update((xs) => [...xs, ${value}])` : `this.${q.field}.set(${value})`, inner)
473
+ : handlerOf(q.many ? `this.${q.field}.$add($q, ${value})` : `this.${q.field} = ${value}`, inner);
474
+ const unset = q.signal
475
+ ? handlerOf(q.many ? `this.${q.field}.update((xs) => xs.filter((x) => x !== ${value}))` : `this.${q.field}.set(undefined as any)`, inner)
476
+ : q.many ? handlerOf(`this.${q.field}.$remove($q)`, inner) : undefined;
477
+ hooks.push({ set, ...(unset ? { unset } : {}), on: instance ? 'instance' : 'view' });
478
+ }
479
+ hooks.push(...contentQueryHooks(refs, component, tag, loops));
480
+ return hooks;
481
+ };
482
+ let usesElementRef = false;
483
+ let usesTemplateRef = false;
484
+ let usesUnset = false;
485
+ const queries = classic?.queries ?? [];
486
+ const contentQueries = classic?.contentQueries ?? [];
487
+ const slotNames = new Set();
488
+ /** The `#refs` of the template's own elements, outside any embedded view: what a static query can resolve. */
489
+ const staticRefs = new Set();
490
+ /** The static queries not yet resolved where the template walk is; ngOnInit waits for them. */
491
+ const staticQueries = new Set();
492
+ let lateInit = false;
493
+ /**
494
+ * The app's directives in the component's scope, by their selectors, as Angular's compiler matches them: those its
495
+ * `imports` name, directly or through an NgModule's exports, and those of an NgModule declaring it.
496
+ */
497
+ const inScope = new Set();
498
+ const expand = (names) => {
499
+ for (const n of names) {
500
+ if (inScope.has(n))
501
+ continue;
502
+ inScope.add(n);
503
+ expand(options.ngModules?.get(n) ?? []);
504
+ }
505
+ };
506
+ const importsMeta = prop('imports');
507
+ expand(importsMeta && ts.isArrayLiteralExpression(importsMeta)
508
+ ? importsMeta.elements.flatMap((e) => ts.isIdentifier(e) ? [e.text] : ts.isSpreadElement(e) && ts.isIdentifier(e.expression) ? [e.expression.text] : [])
509
+ : []);
510
+ for (const [, names] of options.ngModules ?? [])
511
+ if (names.includes(cls.name.text))
512
+ expand(names);
513
+ const matcher = new ng.SelectorMatcher();
514
+ for (const d of options.directives ?? [])
515
+ if (d.selector && inScope.has(d.className))
516
+ matcher.addSelectables(ng.CssSelector.parse(d.selector), d);
517
+ /** The directives an element matches: its name, attributes, bound inputs and outputs, as Angular matches them. */
518
+ const matched = (name, attributes, bound) => {
519
+ const css = new ng.CssSelector();
520
+ css.setElement(name);
521
+ for (const [k, v] of attributes) {
522
+ css.addAttribute(k, v);
523
+ if (k === 'class')
524
+ for (const c of v.split(/\s+/).filter(Boolean))
525
+ css.addClassName(c);
526
+ }
527
+ for (const b of bound)
528
+ css.addAttribute(b, '');
529
+ const found = [];
530
+ matcher.match(css, (_s, d) => { if (!found.includes(d))
531
+ found.push(d); });
532
+ return found;
533
+ };
534
+ const hostMatcher = new ng.SelectorMatcher();
535
+ for (const h of options.hosts ?? [])
536
+ if (inScope.has(h.name))
537
+ hostMatcher.addSelectables(ng.CssSelector.parse(h.selector), h);
538
+ /** The component in scope an element hosts, matched as directives are. */
539
+ const hostedBy = (n) => {
540
+ const css = new ng.CssSelector();
541
+ css.setElement(n.name);
542
+ for (const a of n.attributes) {
543
+ css.addAttribute(a.name, a.value);
544
+ if (a.name === 'class')
545
+ for (const c of a.value.split(/\s+/).filter(Boolean))
546
+ css.addClassName(c);
547
+ }
548
+ for (const b of [...n.inputs.map((i) => i.name), ...n.outputs.map((o) => o.name)])
549
+ css.addAttribute(b, '');
550
+ const found = [];
551
+ hostMatcher.match(css, (_s, h) => { if (!found.includes(h))
552
+ found.push(h); });
553
+ if (found.length > 1)
554
+ throw new Error(`${path}: <${n.name}> matches the components ${found.map((h) => h.name).join(' and ')}; an element hosts one`);
555
+ return found[0];
556
+ };
557
+ let directiveCount = 0;
558
+ /**
559
+ * A directive on an element, one per view of it: made with the element as its ElementRef, its inputs set from the
560
+ * element's bindings and attributes of their names (the bindings then are the directive's, not the view's), its
561
+ * host listeners and bindings on the element, and its hooks.
562
+ */
563
+ const directiveUse = (d, n, loops, consumed, consumedOutputs, dirRefs, dirScopes) => {
564
+ const names = imported.get(d.file) ?? new Map();
565
+ imported.set(d.file, names);
566
+ if (!names.has(d.className))
567
+ names.set(d.className, `$Dir_${d.className}`);
568
+ const alias = names.get(d.className);
569
+ const typeArgs = d.typeParams ? `<${Array(d.typeParams).fill('any').join(', ')}>` : '';
570
+ const name = `$d${directiveCount++}`;
571
+ const namedRefs = n.references.filter((r) => !!r.value && !!d.exportAs?.includes(r.value));
572
+ for (const r of namedRefs)
573
+ dirRefs?.add(r.name);
574
+ const make = expr(d.create ? `${alias}.$create()` : `new ${alias}()`, loops);
575
+ const loopEntry = { item: name, param: `${name}: ${alias}${typeArgs}`, ...(namedRefs.length ? { names: Object.fromEntries(namedRefs.map((r) => [r.name, name])) } : {}) };
576
+ if (namedRefs.length)
577
+ dirScopes?.push(loopEntry);
578
+ const inner = [...loops, loopEntry];
579
+ const valued = [...inner, { item: '$v', param: '$v: any' }];
580
+ const own = { names: new Map(d.members.map((m) => [m, `${name}.${m}`])) };
581
+ const setter = (input, member) => handlerOf(`${d.transforms?.has(member) ? `${name}.$set_${member}($v)` : `${name}.${member}${d.signals.has(member) ? '.$assign($v)' : ' = $v'}`}${d.hooks.has('ngOnChanges') ? `; ${name}.$change(${JSON.stringify(member)}, $v)` : ''}`, valued);
582
+ const inputs = [];
583
+ for (const [input, member] of d.inputs) {
584
+ const b = n.inputs.find((i) => i.name === input && (i.type === ng.BindingType.Property || i.type === ng.BindingType.TwoWay));
585
+ const a = n.attributes.find((x) => x.name === input);
586
+ if (b) {
587
+ at(b.sourceSpan);
588
+ consumed.add(input);
589
+ inputs.push({ set: setter(input, member), method: expr(code(b.value, loops), loops, true) });
590
+ }
591
+ else if (a)
592
+ inputs.push({ set: setter(input, member), value: a.value });
593
+ }
594
+ const dirOutputs = [];
595
+ for (const [outName, member] of d.outputs ?? []) {
596
+ for (const o of n.outputs.filter((x) => x.name === outName)) {
597
+ at(o.sourceSpan);
598
+ consumedOutputs?.add(o);
599
+ const target = code(o.handler, loops);
600
+ const stmt = o.type !== ng.ParsedEventType.TwoWay ? target : /^[A-Za-z_$][\w$]*$/.test(target) && signalMember(target) ? `${target}.set($event)` : `${target} = $event`;
601
+ dirOutputs.push({ name: member, method: handler(stmt, inner, true) });
602
+ }
603
+ }
604
+ const listeners = d.listeners.map((l) => ({ event: l.event, method: handlerOf(core.rewrite(l.code, { names: new Map([...own.names, ['$event', '$event']]) }, 'statements'), [...inner, { item: '$event', param: '$event: any' }]) }));
605
+ const bindings = d.bindings.map((b) => ({ prop: b.prop, method: expr(core.rewrite(b.code, own), inner, true) }));
606
+ const hook = (h) => (d.hooks.has(h) ? handlerOf(`${name}.${h}()`, inner) : undefined);
607
+ const hooks = Object.fromEntries(['init:ngOnInit', 'doCheck:ngDoCheck', 'destroy:ngOnDestroy', 'afterContentInit:ngAfterContentInit', 'afterContentChecked:ngAfterContentChecked', 'afterViewInit:ngAfterViewInit', 'afterViewChecked:ngAfterViewChecked'].flatMap((e) => {
608
+ const [field, h] = e.split(':');
609
+ const m = hook(h);
610
+ return m ? [[field, m]] : [];
611
+ }));
612
+ const dirQueries = directiveContentHooks(d, loops);
613
+ const hasCompanions = !!(d.styleBindings?.length || d.classBindings?.length);
614
+ const uses = [{ name, make, inputs, listeners, bindings, ...hooks, ...(d.hooks.has('ngOnChanges') ? { changes: true } : {}), ...(dirOutputs.length ? { outputs: dirOutputs } : {}), ...(namedRefs.length || hasCompanions ? { exposed: true } : {}), ...(dirQueries.length ? { queries: dirQueries } : {}), attributes: d.attributes }];
615
+ if (d.styleBindings?.length) {
616
+ const sAlias = fromRuntime('NgStyle');
617
+ usesUnset = true;
618
+ const sName = `$d${directiveCount++}`;
619
+ const sInner = [...inner, { item: sName, param: `${sName}: ${sAlias}` }];
620
+ const pairs = d.styleBindings.map((b) => `${JSON.stringify(b.prop)}: (${core.rewrite(b.code, own)})`).join(', ');
621
+ uses.push({ name: sName, make: expr(`new ${sAlias}($unsetValue)`, inner), inputs: [{ set: handlerOf(`${sName}.apply($v)`, [...sInner, { item: '$v', param: '$v: any' }]), method: expr(`[{ ${pairs} }] as any[]`, inner, true) }], listeners: [], bindings: [], attributes: [] });
622
+ }
623
+ if (d.classBindings?.length) {
624
+ const cAlias = fromRuntime('NgClass');
625
+ const cName = `$d${directiveCount++}`;
626
+ const cInner = [...inner, { item: cName, param: `${cName}: ${cAlias}` }];
627
+ const pairs = d.classBindings.flatMap((b) => [JSON.stringify(b.name), `(${core.rewrite(b.code, own)})`]).join(', ');
628
+ uses.push({ name: cName, make: expr(`new ${cAlias}()`, inner), inputs: [{ set: handlerOf(`${cName}.apply($v)`, [...cInner, { item: '$v', param: '$v: any' }]), method: expr(`["", null, [${pairs}]] as any[]`, inner, true) }], listeners: [], bindings: [], attributes: [] });
629
+ }
630
+ return uses;
631
+ };
632
+ /** A function or class of the build's Angular runtime module, imported into the component's file under a name of its own. */
633
+ const fromRuntime = (name) => {
634
+ usesRuntime = true;
635
+ const from = options.runtimeModule ?? RUNTIME;
636
+ const names = imported.get(from) ?? new Map();
637
+ imported.set(from, names);
638
+ if (!names.has(name))
639
+ names.set(name, `$Ng_${name}`);
640
+ return names.get(name);
641
+ };
642
+ /**
643
+ * An element's static `class` and `[class.x]` toggles as one bound `class` from the runtime's ngClassNames. With NgClass (`[ngClass]` or
644
+ * `ngClass="a b"`), the runtime's NgClass directive, returned, which takes all three; on a component, whose root
645
+ * view it can't host, one bound `class` from the runtime's ngClassNames.
646
+ */
647
+ const classAttr = (n, attrs, loops, ngClass, shared = false) => {
648
+ const toggles = n.inputs.filter((i) => i.type === ng.BindingType.Class);
649
+ const boundClass = n.inputs.find((i) => i.name === 'class' && i.type === ng.BindingType.Property);
650
+ const fixedIdx = attrs.findIndex((a) => a.name === 'class');
651
+ // Static `class="a b"` beside `[class]="expr"` (without `[ngClass]`): merge both as Angular does, rather than letting `[class]` wipe static classes.
652
+ if (!toggles.length && !ngClass) {
653
+ if (boundClass && fixedIdx >= 0) {
654
+ at(boundClass.sourceSpan);
655
+ const base = attrs.splice(fixedIdx, 1)[0].value ?? '';
656
+ attrs.push({ name: 'class', method: expr(`${fromRuntime('ngClassNames')}(${JSON.stringify(base)}, (${code(boundClass.value, loops)}), [])`, loops) });
657
+ }
658
+ return null;
659
+ }
660
+ at((ngClass ?? toggles[0]).sourceSpan);
661
+ const fixed = fixedIdx;
662
+ const base = fixed >= 0 ? attrs.splice(fixed, 1)[0].value ?? '' : '';
663
+ const pairs = toggles.flatMap((t) => [JSON.stringify(t.name), `(${code(t.value, loops)})`]);
664
+ // Beside the forms runtime's ng-* classes the toggles go through NgClass, which keeps the classes they share.
665
+ if (!ngClass && !shared) {
666
+ attrs.push({ name: 'class', method: expr(`${fromRuntime('ngClassNames')}(${JSON.stringify(base)}, null, [${pairs.join(', ')}])`, loops) });
667
+ return null;
668
+ }
669
+ if (n.inputs.some((i) => i.name === 'class' && i.type === ng.BindingType.Property))
670
+ throw new Error(`${path}: [class] beside [ngClass] on <${n.name}> is not supported in a release build yet`);
671
+ const value = ngClass instanceof ng.TmplAstBoundAttribute ? code(ngClass.value, loops) : ngClass ? JSON.stringify(ngClass.value) : 'null';
672
+ if (selectors.has(n.name)) {
673
+ attrs.push({ name: 'class', method: expr(`${fromRuntime('ngClassNames')}(${JSON.stringify(base)}, ${value}, [${pairs.join(', ')}])`, loops) });
674
+ return null;
675
+ }
676
+ const alias = fromRuntime('NgClass');
677
+ const name = `$d${directiveCount++}`;
678
+ const inner = [...loops, { item: name, param: `${name}: ${alias}` }];
679
+ return {
680
+ name,
681
+ make: expr(`new ${alias}()`, loops),
682
+ inputs: [{ set: handlerOf(`${name}.apply($v)`, [...inner, { item: '$v', param: '$v: any' }]), method: expr(`[${JSON.stringify(base)}, ${value}, [${pairs.join(', ')}]] as any[]`, loops, true) }],
683
+ listeners: [],
684
+ bindings: [],
685
+ attributes: [],
686
+ };
687
+ };
688
+ /**
689
+ * `[ngStyle]`, or an element's `[style.x]` bindings as one NgStyle object (each set by the renderer's setStyle, removed
690
+ * when null), as the runtime's NgStyle directive on the element. A static `style` moves into the first, set before its
691
+ * first styles, as Angular sets the attribute when it makes the element.
692
+ */
693
+ const styleBindings = (n) => n.inputs.filter((i) => i.type === ng.BindingType.Style && i.name !== 'style');
694
+ // Angular's parser namespaces a bound CSS variable (`--%NS%gap`) for view encapsulation, which NativeScript's styles don't have.
695
+ const styleKey = (i) => JSON.stringify(i.name.replace(/^--%NS%/, '--') + (i.unit ? `.${i.unit}` : ''));
696
+ const styleBindingsUse = (bound, attrs, loops) => ngStyleUse(bound[0], `{ ${bound.map((i) => `${styleKey(i)}: (${code(i.value, loops)})`).join(', ')} }`, attrs, loops);
697
+ const ngStyleUse = (b, value, attrs, loops) => {
698
+ at(b.sourceSpan);
699
+ const alias = fromRuntime('NgStyle');
700
+ usesUnset = true;
701
+ const name = `$d${directiveCount++}`;
702
+ const inner = [...loops, { item: name, param: `${name}: ${alias}` }];
703
+ const fixed = attrs.findIndex((a) => a.name === 'style' && 'value' in a);
704
+ const attributes = fixed >= 0 ? [attrs.splice(fixed, 1)[0]] : [];
705
+ return {
706
+ name,
707
+ make: expr(`new ${alias}($unsetValue)`, loops),
708
+ inputs: [{ set: handlerOf(`${name}.apply($v)`, [...inner, { item: '$v', param: '$v: any' }]), method: expr(`[${value}] as any[]`, loops, true) }],
709
+ listeners: [],
710
+ bindings: [],
711
+ attributes,
712
+ };
713
+ };
714
+ /** The expressions a node evaluates in the view it is in (its children's are theirs): where its pipes are. */
715
+ const ownExpressions = (n) => {
716
+ if (n instanceof ng.TmplAstElement) {
717
+ if (!selectors.has(n.name) && stubbedElement(n.name))
718
+ return n.inputs.filter((i) => STUB_LAYOUT_ATTRS.has(i.name) || i.type === ng.BindingType.Class || i.type === ng.BindingType.Style || i.name === 'ngClass' || i.name === 'ngStyle').map((i) => i.value);
719
+ return [...n.inputs.map((i) => i.value), ...n.children.flatMap((c) => (c instanceof ng.TmplAstBoundText ? [c.value] : []))];
720
+ }
721
+ // `*ngFor` on an element: the element's own inputs are the template's, evaluated in each view it renders.
722
+ if (n instanceof ng.TmplAstTemplate)
723
+ return [...n.templateAttrs, ...(n.tagName === 'ng-template' ? n.inputs : [])].flatMap((a) => (a instanceof ng.TmplAstBoundAttribute ? [a.value] : []));
724
+ if (n instanceof ng.TmplAstIfBlock)
725
+ return n.branches.flatMap((b) => (b.expression ? [b.expression] : []));
726
+ if (n instanceof ng.TmplAstForLoopBlock)
727
+ return [n.expression];
728
+ if (n instanceof ng.TmplAstSwitchBlock)
729
+ return [n.expression, ...n.groups.flatMap((g) => g.cases.flatMap((c) => (c.expression ? [c.expression] : [])))];
730
+ return [];
731
+ };
732
+ /**
733
+ * The directives of @angular/forms, @angular/common and @angular/router an element's bindings, attributes and outputs
734
+ * select, and events of a global target or an animation, none of which a release build runs: `taken` names those
735
+ * that select an app directive or a hosted component instead.
736
+ */
737
+ const refuseUnbound = (n, taken) => {
738
+ const written = [
739
+ ...n.inputs.map((i) => ({ name: i.name, as: i.type === ng.BindingType.TwoWay ? `[(${i.name})]` : i.type === ng.BindingType.Property ? `[${i.name}]` : null })),
740
+ ...n.attributes.map((a) => ({ name: a.name, as: a.name })),
741
+ ...n.outputs.filter((o) => o.type === ng.ParsedEventType.Regular && !o.target).map((o) => ({ name: o.name, as: `(${o.name})` })),
742
+ ];
743
+ for (const w of written) {
744
+ const what = FORMS_DIRECTIVES.has(w.name) ? '@angular/forms' : UNSUPPORTED_DIRECTIVES[w.name];
745
+ if (w.as && what && !taken(w.name))
746
+ throw new Error(`${path}: ${w.as} (${what}) on <${n.name}> is not supported in a release build yet`);
747
+ }
748
+ for (const o of n.outputs) {
749
+ if (o.type === ng.ParsedEventType.LegacyAnimation)
750
+ throw new Error(`${path}: the animation event (@${o.name}${o.phase ? `.${o.phase}` : ''}) on <${n.name}> is not supported in a release build yet`);
751
+ if (o.type === ng.ParsedEventType.Animation)
752
+ throw new Error(`${path}: the animation event (${o.name}) on <${n.name}> is not supported in a release build yet`);
753
+ if (o.target)
754
+ throw new Error(`${path}: (${o.target}:${o.name}), an event of the ${o.target}, on <${n.name}> is not supported in a release build yet`);
755
+ }
756
+ };
757
+ // ---- @angular/forms ----
758
+ /** A forms directive's class, imported into the component's file from @angular/forms (the build's forms runtime). */
759
+ const fromForms = (name) => {
760
+ const names = imported.get('@angular/forms') ?? new Map();
761
+ imported.set('@angular/forms', names);
762
+ if (!names.has(name))
763
+ names.set(name, `$F_${name}`);
764
+ return names.get(name);
765
+ };
766
+ const formsMatcher = new ng.SelectorMatcher();
767
+ for (const [d, selector] of FORMS_SELECTORS)
768
+ formsMatcher.addSelectables(ng.CssSelector.parse(selector), d);
769
+ /** The forms directives an element selects, in the order Angular runs them, as its selectors match. */
770
+ const formsMatched = (n) => {
771
+ const css = new ng.CssSelector();
772
+ css.setElement(n.name);
773
+ for (const a of n.attributes)
774
+ css.addAttribute(a.name, a.value);
775
+ for (const b of [...n.inputs.map((i) => i.name), ...n.outputs.map((o) => o.name)])
776
+ css.addAttribute(b, '');
777
+ const found = new Set();
778
+ formsMatcher.match(css, (_s, d) => { found.add(d); });
779
+ return FORMS_SELECTORS.map(([d]) => d).filter((d) => found.has(d));
780
+ };
781
+ /** The form directives around the element being compiled, innermost last: what Angular injects as its ControlContainer. */
782
+ const formContainers = [];
783
+ /** A member of the component holding a writable signal (`name = signal('')`): `[(ngModel)]` sets it, as Angular's two-way binding does. */
784
+ const signalMember = (name) => cls.members.some((m) => ts.isPropertyDeclaration(m) && m.name.getText() === name
785
+ && ((!!m.initializer && ts.isCallExpression(m.initializer) && /^(signal|model(\.required)?|linkedSignal)$/.test(m.initializer.expression.getText()))
786
+ || (!!m.type && /^(WritableSignal|ModelSignal)\b/.test(m.type.getText()))));
787
+ /**
788
+ * The forms directives an element selects, as directive uses after its others: its @nativescript/angular value
789
+ * accessor, validator directives, NgModel, FormControlDirective or FormControlName, form or group directive, and
790
+ * NgControlStatus or NgControlStatusGroup. Each is made with what Angular's injector gives it, the form directive
791
+ * above it found from the template, and each is in scope for what the template compiles after it (`scope`), which
792
+ * is how the directives below it reach a form directive and a template reference names one. Null when it selects none.
793
+ */
794
+ const formsUses = (n, loops) => {
795
+ // A directive whose module the component doesn't import isn't Angular's on this element: its name is left to the
796
+ // element's other directives, else refused as a binding nothing takes.
797
+ const templateDriven = inScope.has('FormsModule') || inScope.has('NativeScriptFormsModule');
798
+ const reactive = inScope.has('ReactiveFormsModule');
799
+ const found = formsMatched(n).filter((d) => (FORMS_TEMPLATE_DRIVEN.has(d) ? templateDriven : FORMS_VALIDATORS[d] || d === 'DefaultValueAccessor' ? templateDriven || reactive : reactive));
800
+ if (!found.some((d) => FORMS_CONTROLS.has(d) || FORMS_CONTAINERS.has(d) || d === 'DefaultValueAccessor'))
801
+ return null;
802
+ const where = `on <${n.name}>`;
803
+ const writes = (name) => n.inputs.find((i) => i.name === name && (i.type === ng.BindingType.Property || i.type === ng.BindingType.TwoWay)) ?? n.attributes.find((a) => a.name === name);
804
+ /** The input or attribute that selects a directive. */
805
+ const trigger = (d) => d === 'NgModel' ? 'ngModel' : d === 'FormControlDirective' ? 'formControl' : d === 'FormControlName' ? 'formControlName' : d === 'NgForm' ? 'ngForm' : d === 'FormGroupDirective' ? 'formGroup'
806
+ : d === 'FormArrayDirective' ? 'formArray' : d === 'FormGroupName' ? 'formGroupName' : d === 'FormArrayName' ? 'formArrayName' : d === 'NgModelGroup' ? 'ngModelGroup' : FORMS_VALIDATORS[d] ?? '';
807
+ const describe = (d) => {
808
+ const w = writes(trigger(d));
809
+ return !w ? d : w instanceof ng.TmplAstTextAttribute ? w.name : w.type === ng.BindingType.TwoWay ? `[(${w.name})]` : `[${w.name}]`;
810
+ };
811
+ if (found.includes('DefaultValueAccessor'))
812
+ throw new Error(`${path}: ngDefaultControl (@angular/forms' DefaultValueAccessor, which writes an HTML input's value) ${where} is not supported in a release build yet`);
813
+ if (selectors.has(n.name) || hostedBy(n))
814
+ throw new Error(`${path}: ${describe(found.find((d) => !FORMS_VALIDATORS[d]) ?? found[0])} (@angular/forms) ${where}, a component, is not supported in a release build yet: it needs the component's own ControlValueAccessor (NG_VALUE_ACCESSOR)`);
815
+ const controls = found.filter((d) => FORMS_CONTROLS.has(d));
816
+ const containers = found.filter((d) => FORMS_CONTAINERS.has(d));
817
+ if (controls.length > 1 || containers.length > 1)
818
+ throw new Error(`${path}: ${[...controls, ...containers].map(describe).join(' and ')} together ${where} are not supported in a release build yet`);
819
+ const control = controls[0];
820
+ const container = containers[0];
821
+ const parent = formContainers.at(-1);
822
+ const consumedInputs = new Set(found.map(trigger));
823
+ if (n.inputs.some((i) => i.name === 'class' && i.type === ng.BindingType.Property))
824
+ throw new Error(`${path}: [class] beside ${describe(found[0])} ${where} is not supported in a release build yet: it would replace the ng-* classes`);
825
+ const consumedOutputs = new Set();
826
+ const refs = new Set();
827
+ const uses = [];
828
+ let scope = loops;
829
+ /** The code of an input's value: its binding's, its attribute's (a string), else undefined. */
830
+ const value = (name) => {
831
+ const w = writes(name);
832
+ if (!w)
833
+ return 'undefined';
834
+ consumedInputs.add(name);
835
+ return w instanceof ng.TmplAstTextAttribute ? JSON.stringify(w.value) : `(${code(w.value, loops)})`;
836
+ };
837
+ const bound = (...names) => `[${names.map((x) => String(!!writes(x))).join(', ')}]`;
838
+ const use = (kind, className, args, extra = () => ({})) => {
839
+ const alias = fromForms(className);
840
+ const name = `$d${directiveCount++}`;
841
+ // A template reference to it by its exportAs (`#f="ngForm"`) names it wherever it is in scope, its own bindings too.
842
+ const named = n.references.filter((r) => kind !== 'accessor' && kind !== 'status' && !!r.value && FORMS_EXPORT_AS[kind] === r.value);
843
+ for (const r of named)
844
+ refs.add(r.name);
845
+ const loop = { item: name, param: `${name}: ${alias}`, ...(named.length ? { names: Object.fromEntries(named.map((r) => [r.name, name])) } : {}) };
846
+ const inner = [...scope, loop];
847
+ const u = { name, make: expr(`new ${alias}(${args(name)})`, scope), inputs: [], listeners: [], bindings: [], attributes: [], exposed: true, ...extra(name, inner) };
848
+ uses.push(u);
849
+ scope = inner;
850
+ return name;
851
+ };
852
+ const applies = (values, self, inner, before) => [{ set: handlerOf(`${self}.apply($v)`, [...inner, { item: '$v', param: '$v: any' }]), method: expr(`[${values.join(', ')}] as any[]`, before, true) }];
853
+ /** The handlers of the template's `(output)` and `[(input)]` bindings, on the directive's emitter `emitter`. */
854
+ const outputs = (output, emitter, inner) => n.outputs.filter((o) => o.name === output).map((o) => {
855
+ at(o.sourceSpan);
856
+ consumedOutputs.add(o);
857
+ const target = code(o.handler, loops);
858
+ const statement = o.type !== ng.ParsedEventType.TwoWay ? target : /^[A-Za-z_$][\w$]*$/.test(target) && signalMember(target) ? `${target}.set($event)` : `${target} = $event`;
859
+ return { name: emitter, method: handler(statement, inner, true) };
860
+ });
861
+ const unset = () => {
862
+ usesUnset = true;
863
+ return '$unsetValue';
864
+ };
865
+ // The value accessor and the validator directives a control's directive is given.
866
+ let accessorName = null;
867
+ const validatorNames = [];
868
+ if (control) {
869
+ const tag = core.canonical(n.name);
870
+ const accessor = FORMS_ACCESSORS[tag];
871
+ const name = control === 'NgModel' ? 'ngModel' : control === 'FormControlName' ? 'formControlName' : 'formControl';
872
+ const viaAccessor = accessor && (inScope.has('NativeScriptFormsModule') || inScope.has(accessor.accessor));
873
+ if (!viaAccessor) {
874
+ throw new Error(`${path}: ${describe(control)} ${where}: NG01203: No value accessor for form control ${control === 'FormControlName' ? `name: '${writes(name) instanceof ng.TmplAstTextAttribute ? writes(name).value : ''}'` : 'unspecified name attribute'}. ${accessor ? `<${n.name}>'s accessor is @nativescript/angular's ${accessor.accessor}: import NativeScriptFormsModule` : `@nativescript/angular's value accessors take ${Object.keys(FORMS_ACCESSORS).join(', ')}; a component's own (NG_VALUE_ACCESSOR) is not supported in a release build yet`}`);
875
+ }
876
+ accessorName = use('accessor', 'NsValueAccessor', () => `${fromRuntime('hostView')}(), ${JSON.stringify(accessor.kind)}, ${unset()}`, (self, inner) => ({
877
+ listeners: [
878
+ { event: accessor.event, method: handlerOf(`${self}.onChange($event.value)`, [...inner, { item: '$event', param: '$event: any' }]) },
879
+ ...(accessor.kind === 'text' ? [{ event: 'blur', method: handlerOf(`${self}.onTouched()`, [...inner, { item: '$event', param: '$event: any' }]) }] : []),
880
+ ],
881
+ ...(accessor.kind === 'selectedIndex' ? { afterViewInit: handlerOf(`${self}.ngAfterViewInit()`, inner) } : {}),
882
+ }));
883
+ for (const d of found) {
884
+ const input = FORMS_VALIDATORS[d];
885
+ if (!input)
886
+ continue;
887
+ const before = scope;
888
+ validatorNames.push(use(d, d, () => 'true', (self, inner) => ({ inputs: applies([value(input)], self, inner, before) })));
889
+ }
890
+ }
891
+ const validators = `[${validatorNames.join(', ')}]`;
892
+ /** The structural rules Angular checks when the directives are made, as build errors (its messages). */
893
+ const parentKind = parent?.kind;
894
+ if (control === 'FormControlName' && (!parentKind || !FORMS_REACTIVE_PARENTS.has(parentKind))) {
895
+ if (parentKind === 'NgModelGroup' || parentKind === 'NgForm')
896
+ throw new Error(`${path}: formControlName ${where}: NG01051: formControlName cannot be used with an ngModelGroup parent. It is only compatible with parents that also have a "form" prefix: formGroupName, formArrayName, or formGroup.`);
897
+ throw new Error(`${path}: formControlName ${where}: NG01050: formControlName must be used with a parent formGroup or formArray directive. You'll want to add a formGroup/formArray directive and pass it an existing FormGroup/FormArray instance (you can create one in your class).`);
898
+ }
899
+ if ((container === 'FormGroupName' || container === 'FormArrayName') && (!parentKind || !FORMS_REACTIVE_PARENTS.has(parentKind))) {
900
+ throw new Error(`${path}: ${describe(container)} ${where}: NG0105${container === 'FormGroupName' ? '3' : '4'}: ${container === 'FormGroupName' ? 'formGroupName' : 'formArrayName'} must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class).`);
901
+ }
902
+ if (container === 'NgModelGroup' && parentKind !== 'NgForm' && parentKind !== 'NgModelGroup') {
903
+ throw new Error(`${path}: ngModelGroup ${where}: NG01353: ngModelGroup ${parentKind ? 'cannot be used with a parent formGroup directive' : 'must be used inside an ngForm'}.`);
904
+ }
905
+ const ngModelOptions = writes('ngModelOptions');
906
+ const standalone = !!ngModelOptions && ngModelOptions instanceof ng.TmplAstBoundAttribute && /\bstandalone\s*:\s*true\b/.test(code(ngModelOptions.value, loops));
907
+ if (control === 'NgModel' && parentKind && FORMS_REACTIVE_PARENTS.has(parentKind) && !standalone) {
908
+ throw new Error(`${path}: ngModel ${where}: NG0135${parentKind === 'FormGroupDirective' || parentKind === 'FormArrayDirective' ? '0' : '1'}: ngModel cannot be used to register form controls with a parent ${parentKind === 'FormGroupDirective' || parentKind === 'FormArrayDirective' ? 'formGroup' : 'formGroupName or formArrayName'} directive. Use formControlName, or indicate that it's standalone in ngModelOptions.`);
909
+ }
910
+ if (control === 'NgModel' && parentKind && !FORMS_REACTIVE_PARENTS.has(parentKind) && !writes('name') && !ngModelOptions) {
911
+ throw new Error(`${path}: ngModel ${where}: NG01352: If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions.`);
912
+ }
913
+ const parentRef = control === 'NgModel' && standalone ? 'null' : parent ? parent.name : 'null';
914
+ let controlName = null;
915
+ if (control) {
916
+ const before = scope;
917
+ const acc = accessorName;
918
+ if (control === 'NgModel') {
919
+ controlName = use('NgModel', 'NgModel', () => `${parentRef}, ${validators}, [], ${acc}, ${fromRuntime('viewChecker')}(), ${bound('ngModel', 'name', 'ngModelOptions', 'disabled')}`, (self, inner) => ({
920
+ inputs: applies([value('ngModel'), value('name'), value('ngModelOptions'), value('disabled')], self, inner, before),
921
+ outputs: outputs('ngModelChange', 'update', inner),
922
+ destroy: handlerOf(`${self}.ngOnDestroy()`, inner),
923
+ }));
924
+ }
925
+ else if (control === 'FormControlDirective') {
926
+ consumedInputs.add('disabled');
927
+ controlName = use(control, 'FormControlDirective', () => `${validators}, [], ${acc}, 'always', ${bound('formControl', 'ngModel')}`, (self, inner) => ({
928
+ inputs: applies([value('formControl'), value('ngModel')], self, inner, before),
929
+ outputs: outputs('ngModelChange', 'update', inner),
930
+ destroy: handlerOf(`${self}.ngOnDestroy()`, inner),
931
+ }));
932
+ }
933
+ else {
934
+ consumedInputs.add('disabled');
935
+ controlName = use(control, 'FormControlName', () => `${parent.name}, ${validators}, [], ${acc}, ${bound('formControlName', 'ngModel')}`, (self, inner) => ({
936
+ inputs: applies([value('formControlName'), value('ngModel')], self, inner, before),
937
+ outputs: outputs('ngModelChange', 'update', inner),
938
+ destroy: handlerOf(`${self}.ngOnDestroy()`, inner),
939
+ }));
940
+ }
941
+ }
942
+ let containerName = null;
943
+ if (container) {
944
+ const before = scope;
945
+ if (container === 'NgForm') {
946
+ containerName = use(container, 'NgForm', () => `[], [], 'always', ${bound('ngFormOptions')}`, (self, inner) => ({
947
+ inputs: applies([value('ngFormOptions')], self, inner, before),
948
+ outputs: outputs('ngSubmit', 'ngSubmit', inner),
949
+ afterViewInit: handlerOf(`${self}.ngAfterViewInit()`, inner),
950
+ }));
951
+ }
952
+ else if (container === 'FormGroupDirective' || container === 'FormArrayDirective') {
953
+ const input = container === 'FormGroupDirective' ? 'formGroup' : 'formArray';
954
+ containerName = use(container, container, () => `[], [], 'always', ${JSON.stringify(input)}, ${bound(input)}`, (self, inner) => ({
955
+ inputs: applies([value(input)], self, inner, before),
956
+ outputs: outputs('ngSubmit', 'ngSubmit', inner),
957
+ destroy: handlerOf(`${self}.ngOnDestroy()`, inner),
958
+ }));
959
+ }
960
+ else {
961
+ const input = container === 'NgModelGroup' ? 'ngModelGroup' : container === 'FormGroupName' ? 'formGroupName' : 'formArrayName';
962
+ containerName = use(container, container, () => `${parent.name}, [], [], ${container === 'FormArrayName'}, ${bound(input)}`, (self, inner) => ({
963
+ inputs: applies([value(input)], self, inner, before),
964
+ init: handlerOf(`${self}.ngOnInit()`, inner),
965
+ destroy: handlerOf(`${self}.ngOnDestroy()`, inner),
966
+ }));
967
+ }
968
+ }
969
+ // NgControlStatus and NgControlStatusGroup: the ng-* classes, checked with the view.
970
+ const statusOf = controlName ?? containerName;
971
+ if (statusOf) {
972
+ use('status', 'NgControlStatus', () => `${fromRuntime('hostView')}(), ${fromRuntime('viewChecker')}(), ${statusOf}, ${!controlName}`, (self, inner) => ({
973
+ inputs: [{ set: handlerOf(`${self}.check()`, [...inner, { item: '$v', param: '$v: any' }]), method: expr('[] as any[]', inner.slice(0, -1), true) }],
974
+ destroy: handlerOf(`${self}.destroy()`, inner),
975
+ }));
976
+ }
977
+ return { uses, scope, consumedInputs, consumedOutputs, refs, container: containerName ? { kind: container, name: containerName } : null, status: !!statusOf };
978
+ };
979
+ const nodes = (list, loops) => {
980
+ const out = [];
981
+ for (let k = 0; k < list.length; k++) {
982
+ const n = list[k];
983
+ if (n instanceof ng.TmplAstLetDeclaration) {
984
+ at(n.sourceSpan);
985
+ // `@let name = expression`: a slot of the view, the rest of the block in its scope reading `name` from it. A pipe
986
+ // in it is one per view.
987
+ const piped = withPipes([n.value], loops);
988
+ const value = expr(code(n.value, piped.loops), piped.loops);
989
+ const slot = `$l${lets++}`;
990
+ const inner = [...piped.loops, { item: slot, param: `${slot} = $LetSlot.of(this.${value}(${args(piped.loops)}))`, names: { [n.name]: `${slot}.value` } }];
991
+ // Angular reaches a `@let` as a bound node (`ɵɵadvance`), running the hooks before it, where it keeps its value in
992
+ // the view for an embedded view or a listener, or its expression holds a pipe.
993
+ const afterHooks = piped.loops !== loops || readAway(n.name, list.slice(k + 1));
994
+ out.push(...piped.wrap([{ kind: 'let', name: slot, value, ...(afterHooks ? { afterHooks } : {}), body: nodes(list.slice(k + 1), inner) }]));
995
+ break;
996
+ }
997
+ const piped = withPipes(ownExpressions(n), loops);
998
+ if (piped.loops !== loops) {
999
+ out.push(...piped.wrap(nodes([n], piped.loops)));
1000
+ continue;
1001
+ }
1002
+ if (n instanceof ng.TmplAstElement && !selectors.has(n.name) && PLATFORM_FILTERS[n.name]) {
1003
+ at(n.startSourceSpan);
1004
+ // @nativescript/angular's AndroidFilterComponent and its kin: `@if (show) { <ng-content> }` in a ProxyViewContainer.
1005
+ if (n.attributes.length || n.inputs.length || n.outputs.length || n.references.length)
1006
+ throw new Error(`${path}: <${n.name}> takes no attributes or bindings in a release build`);
1007
+ if (PLATFORM_FILTERS[n.name].includes(options.platform ?? 'ios'))
1008
+ out.push(...nodes(n.children, loops));
1009
+ continue;
1010
+ }
1011
+ if (n instanceof ng.TmplAstElement && n.name === 'ng-container') {
1012
+ at(n.startSourceSpan);
1013
+ out.push(...container(n, loops));
1014
+ continue;
1015
+ }
1016
+ if (n instanceof ng.TmplAstElement && !selectors.has(n.name) && n.name.startsWith(':svg:')) {
1017
+ out.push({ kind: 'element', tag: 'ContentView', attrs: [], events: [], children: [] });
1018
+ continue;
1019
+ }
1020
+ if (n instanceof ng.TmplAstElement && !selectors.has(n.name) && stubbedElement(n.name)) {
1021
+ at(n.startSourceSpan);
1022
+ const attrs = [];
1023
+ for (const a of n.attributes)
1024
+ if (STUB_LAYOUT_ATTRS.has(a.name))
1025
+ attrs.push({ name: a.name, value: a.value });
1026
+ const classed = classAttr(n, attrs, loops, n.inputs.find((i) => i.name === 'ngClass' && i.type === ng.BindingType.Property) ?? n.attributes.find((a) => a.name === 'ngClass'));
1027
+ const styled = n.inputs.find((i) => i.name === 'ngStyle' && i.type === ng.BindingType.Property);
1028
+ const stubDirectives = [...(classed ? [classed] : []), ...(styled ? [ngStyleUse(styled, code(styled.value, loops), attrs, loops)] : [])];
1029
+ if (styleBindings(n).length)
1030
+ stubDirectives.push(styleBindingsUse(styleBindings(n), attrs, loops));
1031
+ for (const i of n.inputs) {
1032
+ if (i.type === ng.BindingType.Class || i.type === ng.BindingType.Style)
1033
+ continue;
1034
+ if ((i.type === ng.BindingType.Property || i.type === ng.BindingType.Attribute) && STUB_LAYOUT_ATTRS.has(i.name)) {
1035
+ at(i.sourceSpan);
1036
+ const root = i.value instanceof ng.ASTWithSource ? i.value.ast : i.value;
1037
+ const chained = root instanceof ng.SafePropertyRead || root instanceof ng.SafeKeyedRead || root instanceof ng.SafeCall;
1038
+ attrs.push({ name: i.name, method: expr(code(i.value, loops), loops, chained) });
1039
+ }
1040
+ }
1041
+ const refs = n.references.map((r) => r.name);
1042
+ const hooks = queryHooks(refs, null, 'ContentView', loops);
1043
+ const statics = hooks.length ? queries.filter((q) => q.static && q.ref && refs.includes(q.ref) && staticRefs.has(q.ref)) : [];
1044
+ for (const q of statics)
1045
+ staticQueries.delete(q);
1046
+ const late = statics.length > 0 && staticQueries.size === 0;
1047
+ out.push({ kind: 'element', tag: 'ContentView', attrs, events: [], children: [], ...(hooks.length ? { queries: hooks } : {}), ...(late ? { init: true } : {}), ...(stubDirectives.length ? { directives: stubDirectives } : {}) });
1048
+ if (late)
1049
+ lateInit = true;
1050
+ continue;
1051
+ }
1052
+ if (n instanceof ng.TmplAstElement) {
1053
+ at(n.startSourceSpan);
1054
+ const attrs = [];
1055
+ const events = [];
1056
+ // A ListView, or a plugin view taking item templates (`<Pager>` with `<ng-template let-item>`), renders rows from templates.
1057
+ const isList = core.canonical(n.name) === 'ListView' || (n.inputs.some((i) => i.name === 'items') && n.children.some((c) => c instanceof ng.TmplAstTemplate && c.tagName === 'ng-template' && c.variables.length > 0));
1058
+ // The component an attribute selects renders its template into the element; its inputs and outputs are bound
1059
+ // on it, the element's properties and events beside them.
1060
+ const hosted = selectors.has(n.name) ? undefined : hostedBy(n);
1061
+ const hostProps = [];
1062
+ const hostEvents = [];
1063
+ if (hosted) {
1064
+ const unsupported = (what) => new Error(`${path}: ${what} on <${n.name}>, the host of ${hosted.name}, is not supported in a release build yet`);
1065
+ if (hosted.readsHost)
1066
+ throw unsupported(`${hosted.name}'s own ElementRef or host bindings`);
1067
+ if (isList)
1068
+ throw unsupported('item templates');
1069
+ if (!hosted.slots?.length && n.children.some((c) => !(c instanceof ng.TmplAstText) || c.value.trim()))
1070
+ throw unsupported('content');
1071
+ for (const i of n.inputs)
1072
+ if (hosted.inputs.has(i.name) && i.type === ng.BindingType.TwoWay)
1073
+ throw unsupported(`[(${i.name})]`);
1074
+ for (const o of n.outputs)
1075
+ if (hosted.models.has(o.name.replace(/Change$/, '')))
1076
+ throw unsupported(`(${o.name})`);
1077
+ }
1078
+ // @angular/forms' directives, made after the element's others: what the template compiles after each reads it.
1079
+ const forms = formsUses(n, loops);
1080
+ const scoped = forms?.scope ?? loops;
1081
+ const link = routerLink(n, scoped);
1082
+ if (link)
1083
+ events.push(link);
1084
+ const found = matched(n.name, n.attributes.map((a) => [a.name, a.value]), [...n.inputs.map((i) => i.name), ...n.outputs.map((o) => o.name)]);
1085
+ // An app directive or the hosted component taking NgClass's or NgStyle's input name is what that binding sets.
1086
+ const appOwns = (name) => found.some((d) => d.inputs.has(name)) || !!hosted?.inputs.has(name);
1087
+ for (const a of n.attributes) {
1088
+ if (link && ROUTER_LINK_INPUTS.has(a.name))
1089
+ continue;
1090
+ if (a.name === 'ngClass' && !appOwns('ngClass'))
1091
+ continue;
1092
+ // A static attribute is the element's too, as Angular writes every one to its host.
1093
+ attrs.push({ name: a.name, value: a.value });
1094
+ if (hosted?.inputs.has(a.name))
1095
+ hostProps.push({ name: a.name, value: a.value });
1096
+ }
1097
+ const targetComponent = selectors.get(n.name);
1098
+ const targetSlots = targetComponent ? options.componentSlots?.get(targetComponent) : hosted?.slots;
1099
+ const projectsContent = !!(targetSlots?.length && n.children.some((c) => !(c instanceof ng.TmplAstText) || c.value.trim()));
1100
+ if (!projectsContent) {
1101
+ for (const c of n.children) {
1102
+ if (c instanceof ng.TmplAstText && c.value.trim())
1103
+ attrs.push({ name: 'text', value: c.value });
1104
+ if (c instanceof ng.TmplAstBoundText) {
1105
+ at(c.sourceSpan);
1106
+ attrs.push({ name: 'text', method: expr(code(c.value, scoped), scoped) });
1107
+ }
1108
+ }
1109
+ }
1110
+ // The static classes, `[class.on]="cond"` toggles and NgClass: one bound `class` naming them all.
1111
+ const ngClass = appOwns('ngClass') ? undefined : n.inputs.find((i) => i.name === 'ngClass' && i.type === ng.BindingType.Property) ?? n.attributes.find((a) => a.name === 'ngClass');
1112
+ const mergedBoundClass = !ngClass && !n.inputs.some((i) => i.type === ng.BindingType.Class) && attrs.some((a) => a.name === 'class') ? n.inputs.find((i) => i.name === 'class' && i.type === ng.BindingType.Property) : undefined;
1113
+ const ngClassUse = classAttr(n, attrs, loops, ngClass, !!forms?.status);
1114
+ const ngStyle = appOwns('ngStyle') || selectors.has(n.name) ? undefined : n.inputs.find((i) => i.name === 'ngStyle' && i.type === ng.BindingType.Property);
1115
+ // NgSwitch on any element: the cases below it, in its subtree, compare with its value.
1116
+ const switched = n.inputs.find((i) => i.name === 'ngSwitch');
1117
+ const consumed = new Set();
1118
+ const consumedDirOutputs = new Set();
1119
+ const dirRefs = new Set();
1120
+ const dirScopes = [];
1121
+ const directives = found.flatMap((d) => {
1122
+ if (d.structural)
1123
+ throw new Error(`${path}: the structural directive ${d.className} without its template (*) is not supported in a release build yet`);
1124
+ return directiveUse(d, n, loops, consumed, consumedDirOutputs, dirRefs, dirScopes);
1125
+ });
1126
+ const allScoped = dirScopes.length ? [...scoped, ...dirScopes] : scoped;
1127
+ refuseUnbound(n, (name) => found.some((d) => d.inputs.has(name) || !!d.outputs?.has(name)) || !!hosted?.inputs.has(name) || !!hosted?.outputs.has(name) || (name === 'ngClass' && !!ngClass) || (name === 'ngStyle' && !!ngStyle)
1128
+ || !!forms?.consumedInputs.has(name) || [...(forms?.consumedOutputs ?? [])].some((o) => o.name === name));
1129
+ if (ngClassUse)
1130
+ directives.push(ngClassUse);
1131
+ if (ngStyle)
1132
+ directives.push(ngStyleUse(ngStyle, code(ngStyle.value, loops), attrs, loops));
1133
+ if (!selectors.has(n.name) && styleBindings(n).length)
1134
+ directives.push(styleBindingsUse(styleBindings(n), attrs, loops));
1135
+ if (forms)
1136
+ directives.push(...forms.uses);
1137
+ if (!selectors.has(n.name) && !hosted) {
1138
+ const ref = n.references.find((r) => r.value && !forms?.refs.has(r.name) && !dirRefs.has(r.name));
1139
+ if (ref)
1140
+ throw new Error(`${path}: #${ref.name}="${ref.value}" on <${n.name}>, a reference to a directive's exportAs, is not supported in a release build yet`);
1141
+ }
1142
+ for (const i of n.inputs) {
1143
+ if (i === switched || i === ngClass || i === ngStyle || i === mergedBoundClass || consumed.has(i.name) || forms?.consumedInputs.has(i.name) || i.type === ng.BindingType.Class || (isList && i.name === 'itemTemplateSelector') || (link && ROUTER_LINK_INPUTS.has(i.name)))
1144
+ continue;
1145
+ at(i.sourceSpan);
1146
+ if (hosted?.inputs.has(i.name) && i.type === ng.BindingType.Property) {
1147
+ hostProps.push({ name: i.name, method: expr(code(i.value, allScoped), allScoped) });
1148
+ continue;
1149
+ }
1150
+ if (i.type === ng.BindingType.Style && i.name !== 'style' && !selectors.has(n.name))
1151
+ continue;
1152
+ // `[attr.name]`: the renderer's setAttribute, which on a NativeScript view sets the property of that name.
1153
+ if (i.type === ng.BindingType.Attribute) {
1154
+ attrs.push({ name: i.name, method: expr(code(i.value, allScoped), allScoped, true) });
1155
+ continue;
1156
+ }
1157
+ if (i.type !== ng.BindingType.Property && i.type !== ng.BindingType.TwoWay)
1158
+ throw new Error(`${path}: the [${ng.BindingType[i.type].toLowerCase()}.${i.name}] binding is not supported in a release build yet`);
1159
+ // `[text]="person()?.name"`: the view takes undefined where the chain stops, as the renderer passes it, whatever the type says.
1160
+ const root = i.value instanceof ng.ASTWithSource ? i.value.ast : i.value;
1161
+ const chained = i.type === ng.BindingType.Property && !selectors.has(n.name) && (root instanceof ng.SafePropertyRead || root instanceof ng.SafeKeyedRead || root instanceof ng.SafeCall);
1162
+ attrs.push({ name: i.name, method: expr(code(i.value, allScoped), allScoped, chained) });
1163
+ }
1164
+ for (const o of n.outputs) {
1165
+ if (forms?.consumedOutputs.has(o) || consumedDirOutputs.has(o))
1166
+ continue;
1167
+ at(o.sourceSpan);
1168
+ if (hosted?.outputs.has(o.name)) {
1169
+ hostEvents.push({ name: o.name, method: handler(code(o.handler, allScoped), allScoped, true), payload: true });
1170
+ continue;
1171
+ }
1172
+ events.push({ name: o.name, method: handler(code(o.handler, allScoped), allScoped, selectors.has(n.name) || !core.canonical(n.name) || registered.has(n.name.toLowerCase())), ...(selectors.has(n.name) ? { payload: true } : {}) });
1173
+ }
1174
+ const projectChildren = (compName, declared) => {
1175
+ const meaningful = n.children.filter((c) => !(c instanceof ng.TmplAstText) || c.value.trim());
1176
+ if (!meaningful.length)
1177
+ return undefined;
1178
+ const slotMatcher = new ng.SelectorMatcher();
1179
+ for (const sel of declared ?? []) {
1180
+ if (sel === 'default')
1181
+ continue;
1182
+ try {
1183
+ slotMatcher.addSelectables(ng.CssSelector.parse(sel), sel);
1184
+ }
1185
+ catch { }
1186
+ }
1187
+ const buckets = new Map();
1188
+ const push = (slot, child) => {
1189
+ const list = buckets.get(slot) ?? [];
1190
+ list.push(child);
1191
+ buckets.set(slot, list);
1192
+ };
1193
+ for (const ch of meaningful) {
1194
+ let slot = 'default';
1195
+ if (ch instanceof ng.TmplAstElement) {
1196
+ const projectAs = ch.attributes.find((a) => a.name === 'ngProjectAs')?.value;
1197
+ const cssList = projectAs ? ng.CssSelector.parse(projectAs) : [(() => {
1198
+ const css = new ng.CssSelector();
1199
+ css.setElement(ch.name);
1200
+ for (const a of ch.attributes) {
1201
+ css.addAttribute(a.name, a.value);
1202
+ if (a.name === 'class')
1203
+ for (const c of a.value.split(/\s+/).filter(Boolean))
1204
+ css.addClassName(c);
1205
+ }
1206
+ for (const b of [...ch.inputs.map((i) => i.name), ...ch.outputs.map((o) => o.name)])
1207
+ css.addAttribute(b, '');
1208
+ return css;
1209
+ })()];
1210
+ for (const css of cssList) {
1211
+ slotMatcher.match(css, (_s, matchedSlot) => { if (slot === 'default')
1212
+ slot = matchedSlot; });
1213
+ }
1214
+ }
1215
+ push(slot, ch);
1216
+ }
1217
+ const cqInfo = options.componentContentQueries?.get(compName);
1218
+ let pushedHost = false;
1219
+ if (cqInfo?.queries.length) {
1220
+ let alias = compName;
1221
+ if (compName !== cls.name.text && cqInfo.file !== path) {
1222
+ const releaseFile = cqInfo.file.replace(/\.ts$/, '.release.ts');
1223
+ const names = imported.get(releaseFile) ?? new Map();
1224
+ imported.set(releaseFile, names);
1225
+ if (!names.has(compName))
1226
+ names.set(compName, `$Comp_${compName}`);
1227
+ alias = names.get(compName);
1228
+ }
1229
+ activeContentHost.push({ name: compName, alias, queries: cqInfo.queries, depth: 0 });
1230
+ pushedHost = true;
1231
+ }
1232
+ const slotsOut = {};
1233
+ try {
1234
+ for (const [slotName, asts] of buckets) {
1235
+ const built = [];
1236
+ for (const ch of asts) {
1237
+ if (ch instanceof ng.TmplAstText && ch.value.trim()) {
1238
+ built.push({ kind: 'element', tag: 'Label', attrs: [{ name: 'text', value: ch.value.trim() }], events: [], children: [] });
1239
+ }
1240
+ else if (ch instanceof ng.TmplAstBoundText) {
1241
+ at(ch.sourceSpan);
1242
+ built.push({ kind: 'element', tag: 'Label', attrs: [{ name: 'text', method: expr(code(ch.value, scoped), scoped) }], events: [], children: [] });
1243
+ }
1244
+ else {
1245
+ built.push(...nodes([ch], scoped));
1246
+ }
1247
+ }
1248
+ if (built.length)
1249
+ slotsOut[slotName] = built;
1250
+ }
1251
+ }
1252
+ finally {
1253
+ if (pushedHost)
1254
+ activeContentHost.pop();
1255
+ }
1256
+ return Object.keys(slotsOut).length ? slotsOut : undefined;
1257
+ };
1258
+ const component = selectors.get(n.name);
1259
+ const refs = n.references.map((r) => r.name);
1260
+ if (component) {
1261
+ const hooks = queryHooks(refs, component, null, loops);
1262
+ const projected = projectChildren(component, options.componentSlots?.get(component));
1263
+ out.push({ kind: 'component', name: component, props: attrs, events, ...(hooks.length ? { queries: hooks } : {}), ...(projected ? { slots: projected } : {}), ...(directives.length ? { directives } : {}) });
1264
+ continue;
1265
+ }
1266
+ if (n.name === 'page-router-outlet' || n.name === 'router-outlet') {
1267
+ // The outlet's Frame takes its name, and the static View/Frame attributes @nativescript/angular sets on that Frame.
1268
+ const FRAME_STATIC_ATTRS = new Set(['actionBarVisibility', 'class', 'id', 'style', 'row', 'col', 'rowSpan', 'colSpan', 'dock', 'visibility', 'automationText', 'testID', 'width', 'height', 'backgroundColor']);
1269
+ const passed = (a) => FRAME_STATIC_ATTRS.has(a.name);
1270
+ const other = [...n.inputs.map((i) => `[${i.name}]`), ...n.outputs.map((o) => `(${o.name})`), ...n.references.map((r) => `#${r.name}`), ...n.attributes.filter((a) => a.name !== 'name' && !passed(a)).map((a) => `${a.name}="${a.value}"`)];
1271
+ if (other.length)
1272
+ throw new Error(`${path}: ${other[0]} on <${n.name}> is not supported in a release build yet`);
1273
+ // `actionBarVisibility="auto"` is the Frame's default; `<router-outlet>` is an embedded nested outlet without an ActionBar unless specified.
1274
+ const frameAttrs = n.attributes.filter((a) => passed(a) && !(a.name === 'actionBarVisibility' && a.value === 'auto')).map((a) => ({ name: a.name, value: a.value }));
1275
+ if (n.name === 'router-outlet' && !n.attributes.some((a) => a.name === 'actionBarVisibility'))
1276
+ frameAttrs.push({ name: 'actionBarVisibility', value: 'never' });
1277
+ out.push({ kind: 'element', tag: 'Frame', attrs: [{ name: 'router', value: n.attributes.find((a) => a.name === 'name')?.value ?? 'primary' }, ...frameAttrs], events: [], children: [] });
1278
+ continue;
1279
+ }
1280
+ // An unregistered custom element matched by an in-scope @Directive (e.g. `<hlm-input-group>`) renders as a container host.
1281
+ const tag = elementOf(n.name) ?? (found.length ? (elementOf('div') ?? 'ContentView') : undefined);
1282
+ if (!tag)
1283
+ throw new Error(`${path}: <${n.name}> is not a @nativescript/core element the release build knows`);
1284
+ checkMeta(n);
1285
+ const sections = isList && isSectioned(n);
1286
+ // A reference on a host names its component; ElementRef and the view's class read the element.
1287
+ const matches = queryHooks(refs.filter((r) => !forms?.refs.has(r)), hosted?.name ?? null, tag, loops);
1288
+ const hooks = matches.filter((h) => h.on !== 'instance');
1289
+ for (const r of n.references) {
1290
+ if (r.value || forms?.refs.has(r.name) || dirRefs.has(r.name) || !elementRefFields.has(r.name))
1291
+ continue;
1292
+ const field = elementRefFields.get(r.name);
1293
+ hooks.push({ set: handlerOf(`this.${field} = $q`, [...loops, { item: '$q', param: '$q: any' }]), on: 'view' });
1294
+ }
1295
+ const own = matches.filter((h) => h.on === 'instance');
1296
+ const below = () => {
1297
+ if (isList)
1298
+ return listTemplates(n, attrs, scoped);
1299
+ if (hosted) {
1300
+ const hostedProjected = hosted.slots?.length ? projectChildren(hosted.name, hosted.slots) : undefined;
1301
+ return [{ kind: 'component', name: hosted.name, props: hostProps, events: hostEvents, ...(own.length ? { queries: own } : {}), ...(hostedProjected ? { slots: hostedProjected } : {}) }];
1302
+ }
1303
+ const ch = activeContentHost.at(-1);
1304
+ if (ch)
1305
+ ch.depth++;
1306
+ try {
1307
+ return nodes(n.children, scoped);
1308
+ }
1309
+ finally {
1310
+ if (ch)
1311
+ ch.depth--;
1312
+ }
1313
+ };
1314
+ // A form or group directive is the ControlContainer of the forms directives below it.
1315
+ const children = () => {
1316
+ if (forms?.container)
1317
+ formContainers.push(forms.container);
1318
+ try {
1319
+ return below();
1320
+ }
1321
+ finally {
1322
+ if (forms?.container)
1323
+ formContainers.pop();
1324
+ }
1325
+ };
1326
+ // A static query is resolved when the template's views are made, before ngOnInit: ngOnInit runs once the last element one names is.
1327
+ const statics = matches.length ? queries.filter((q) => q.static && q.ref && refs.includes(q.ref) && staticRefs.has(q.ref)) : [];
1328
+ for (const q of statics)
1329
+ staticQueries.delete(q);
1330
+ const late = statics.length > 0 && staticQueries.size === 0;
1331
+ out.push({ kind: 'element', tag, attrs, events, children: switched ? switching(n, switched.value, scoped, children) : children(), ...(sections ? { sections } : {}), ...(hooks.length ? { queries: hooks } : {}), ...(late ? { init: true } : {}), ...(directives.length ? { directives } : {}) });
1332
+ if (late)
1333
+ lateInit = true;
1334
+ // The nodes after it read its forms directives too (a template reference to one), as the codegen scopes them.
1335
+ if (forms) {
1336
+ out.push(...nodes(list.slice(k + 1), scoped));
1337
+ break;
1338
+ }
1339
+ continue;
1340
+ }
1341
+ if (n instanceof ng.TmplAstIfBlock) {
1342
+ const prevGuards = [];
1343
+ out.push({ kind: 'if', branches: n.branches.map((b) => {
1344
+ at(b.startSourceSpan);
1345
+ // `@if (x; as y)`: y is the condition's value in the branch (non-null because the branch only runs when truthy).
1346
+ const alias = b.expressionAlias;
1347
+ // The condition is read before its alias exists: `@if (person(); as person)` names the value of the `person` it reads.
1348
+ const rawCond = b.expression ? code(b.expression, loops) : null;
1349
+ const cond = rawCond !== null ? test(rawCond, loops) : null;
1350
+ const rewrittenCond = rawCond !== null ? core.rewrite(clean(rawCond), local(loops)) : null;
1351
+ const pureGuard = rewrittenCond !== null && !/[=]|[\w$]\s*\(/.test(rewrittenCond.replace(/[!=]==?/g, '')) && /(?:===|!==|==|!=|\btypeof\b|\binstanceof\b|\bin\b)/.test(rewrittenCond) ? rewrittenCond : null;
1352
+ if (alias && rewrittenCond !== null)
1353
+ aliases.set(alias.name, `(${rewrittenCond})!`);
1354
+ const savedNarrowing = narrowing;
1355
+ narrowing = [...savedNarrowing, ...prevGuards.map((g) => `!(${g})`), ...(pureGuard ? [pureGuard] : [])];
1356
+ let body;
1357
+ try {
1358
+ body = nodes(b.children, loops);
1359
+ }
1360
+ finally {
1361
+ narrowing = savedNarrowing;
1362
+ if (alias)
1363
+ aliases.delete(alias.name);
1364
+ }
1365
+ if (pureGuard)
1366
+ prevGuards.push(pureGuard);
1367
+ return { cond, body };
1368
+ }) });
1369
+ continue;
1370
+ }
1371
+ if (n instanceof ng.TmplAstForLoopBlock) {
1372
+ at(n.startSourceSpan);
1373
+ const item = n.item.name;
1374
+ // The index is a parameter of its own: nested loops each have a `$index`.
1375
+ const index = `$i${loops.length}`;
1376
+ const items = expr(code(n.expression, loops), loops);
1377
+ const count = `this.${items}(${args(loops)}).length`;
1378
+ const context = { $index: index, $count: count, $first: `(${index} === 0)`, $last: `(${index} === ${count} - 1)`, $even: `(${index} % 2 === 0)`, $odd: `(${index} % 2 !== 0)` };
1379
+ const names = {};
1380
+ for (const v of n.contextVariables)
1381
+ names[v.name] = context[v.value];
1382
+ const loop = { item, index, param: `${item} = this.${items}(${args(loops)})[0], ${index} = 0`, names };
1383
+ const inner = [...loops, loop];
1384
+ out.push({ kind: 'for', items, key: expr(sourceOf(n.trackBy), inner), item, index, body: nodes(n.children, inner) });
1385
+ if (n.empty) {
1386
+ at(n.empty.startSourceSpan);
1387
+ out.push({ kind: 'if', branches: [{ cond: test(`${count} === 0`, loops), body: nodes(n.empty.children, loops) }] });
1388
+ }
1389
+ continue;
1390
+ }
1391
+ if (n instanceof ng.TmplAstTemplate && n.templateAttrs.some((a) => a.name === 'tabItem')) {
1392
+ out.push(tabItem(n, loops));
1393
+ continue;
1394
+ }
1395
+ if (n instanceof ng.TmplAstTemplate) {
1396
+ out.push(...structural(n, loops));
1397
+ continue;
1398
+ }
1399
+ if (n instanceof ng.TmplAstSwitchBlock) {
1400
+ const subject = code(n.expression, loops);
1401
+ at(n.startSourceSpan);
1402
+ const branches = n.groups.map((g) => {
1403
+ const tests = g.cases.filter((c) => c.expression).map((c) => `(${subject}) === (${code(c.expression, loops)})`);
1404
+ return { cond: tests.length ? expr(tests.join(' || '), loops) : null, body: nodes(g.children, loops) };
1405
+ });
1406
+ // The default group renders when no case matches, wherever it is written.
1407
+ out.push({ kind: 'if', branches: [...branches.filter((b) => b.cond), ...branches.filter((b) => !b.cond)] });
1408
+ continue;
1409
+ }
1410
+ if (n instanceof ng.TmplAstContent) {
1411
+ at(n.sourceSpan);
1412
+ const name = !n.selector || n.selector === '*' ? 'default' : n.selector;
1413
+ slotNames.add(name);
1414
+ const fallback = n.children?.length ? nodes(n.children, loops) : [];
1415
+ out.push({ kind: 'slot', name, ...(fallback.length ? { fallback } : {}) });
1416
+ continue;
1417
+ }
1418
+ // Text in an element is its `text` (@nativescript/angular's renderer sets it on the parent): a template's text nodes bind there.
1419
+ if (n instanceof ng.TmplAstText || n instanceof ng.TmplAstBoundText)
1420
+ continue;
1421
+ throw new Error(`${path}: ${n.constructor.name} in a template is not supported in a release build yet`);
1422
+ }
1423
+ return out;
1424
+ };
1425
+ /**
1426
+ * `<ListView [items]>` with `<ng-template let-item let-i="index" nsTemplateKey="…">` children, as
1427
+ * @nativescript/angular's ListViewComponent renders them: the first template is also the default, and
1428
+ * `[itemTemplateSelector]` is called with `(item, index, items)`. A `<Pager>` (@nstudio/nativescript-ui-pager's
1429
+ * PagerComponent) is the same with `pagerTemplateKey`.
1430
+ */
1431
+ const listTemplates = (n, attrs, loops) => {
1432
+ const host = elementOf(n.name) ?? n.name;
1433
+ const keyName = host === 'Pager' ? 'pagerTemplateKey' : 'nsTemplateKey';
1434
+ const items = attrs.find((a) => a.name === 'items');
1435
+ if (!items || !('method' in items))
1436
+ throw new Error(`${path}: <${host}> needs [items]`);
1437
+ const list = `this.${items.method}(${args(loops)})`;
1438
+ // A sectioned ListView's items are sections (`{ title, items }`); a row's item is one of a section's.
1439
+ const sectioned = isSectioned(n);
1440
+ const rows = sectioned ? `${list}[0].items` : list;
1441
+ const selector = n.inputs.find((i) => i.name === 'itemTemplateSelector');
1442
+ if (selector) {
1443
+ const m = `$b${next++}`;
1444
+ const p = [params(loops), `$item = ${rows}[0]`, '$index = 0'].filter(Boolean).join(', ');
1445
+ // Called as core calls it, with (item, index, items): a method of the component that declares fewer takes the ones it declares.
1446
+ const name = sourceOf(selector.value).trim();
1447
+ const member = cls.members.find((x) => (ts.isMethodDeclaration(x) || ts.isPropertyDeclaration(x)) && x.name.getText() === name);
1448
+ // A method, or a property holding an arrow (`rowTemplate = (row) => …`): the parameters it declares.
1449
+ const fn = member && ts.isMethodDeclaration(member) ? member : member && ts.isPropertyDeclaration(member) && member.initializer && (ts.isArrowFunction(member.initializer) || ts.isFunctionExpression(member.initializer)) ? member.initializer : undefined;
1450
+ const given = ['$item', '$index', list].slice(0, fn ? fn.parameters.length : 3);
1451
+ at(selector.sourceSpan);
1452
+ add(` ${m}(${p}): string { return ${core.rewrite(clean(sourceOf(selector.value)), local(loops))}(${given.join(', ')}); }`);
1453
+ attrs.push({ name: 'itemTemplateSelector', method: m });
1454
+ }
1455
+ const out = [];
1456
+ for (const t of n.children) {
1457
+ if (t instanceof ng.TmplAstText)
1458
+ continue;
1459
+ if (!(t instanceof ng.TmplAstTemplate) || t.tagName !== 'ng-template')
1460
+ throw new Error(`${path}: a ${host}'s children are <ng-template let-item> item templates`);
1461
+ const bound = t.inputs.find((i) => i.name === keyName);
1462
+ const key = t.attributes.find((a) => a.name === keyName)?.value ?? (bound ? literalKey(sourceOf(bound.value), path) : out.length ? null : 'default');
1463
+ if (key === null)
1464
+ throw new Error(`${path}: a ${host}'s second and later <ng-template>s need a ${keyName}`);
1465
+ if (t.inputs.some((i) => i.name === 'nsTemplateKeys'))
1466
+ throw new Error(`${path}: nsTemplateKeys is not supported in a release build yet`);
1467
+ const named = (v) => t.variables.find((x) => (x.value || '$implicit') === v)?.name;
1468
+ const item = named('$implicit') ?? named('item') ?? `$item${loops.length}`;
1469
+ const index = named('index') ?? `$i${loops.length}`;
1470
+ const names = {};
1471
+ for (const v of t.variables) {
1472
+ const what = v.value || '$implicit';
1473
+ if ((what === '$implicit' || what === 'item') && v.name !== item)
1474
+ names[v.name] = item;
1475
+ else if (what === 'even')
1476
+ names[v.name] = `(${index} % 2 === 0)`;
1477
+ else if (what === 'odd')
1478
+ names[v.name] = `(${index} % 2 !== 0)`;
1479
+ else if (!['$implicit', 'item', 'index'].includes(what))
1480
+ throw new Error(`${path}: a ${host} template's "${what}" is not part of its context`);
1481
+ }
1482
+ // Keyed templates tell apart the kinds of row a list mixes (`Person | typeof BYLINE_ROW`): each reads its row
1483
+ // untyped, as Angular types an ng-template's context.
1484
+ const keyed = n.children.filter((c) => c instanceof ng.TmplAstTemplate).length > 1;
1485
+ const loop = { item, index, param: `${item}${keyed ? ': any' : ''} = ${rows}[0], ${index} = 0`, names };
1486
+ out.push({ kind: 'template', key, item, index, body: nodes(t.children, [...loops, loop]) });
1487
+ }
1488
+ const header = attrs.findIndex((a) => a.name === 'stickyHeaderTemplate');
1489
+ if (header >= 0) {
1490
+ attrs.splice(header, 1);
1491
+ if (sectioned)
1492
+ out.push(stickyHeader(n, list, loops));
1493
+ }
1494
+ return out;
1495
+ };
1496
+ const isSectioned = (n) => n.inputs.some((i) => i.name === 'sectioned' && sourceOf(i.value).trim() === 'true') || n.attributes.some((a) => a.name === 'sectioned' && a.value === 'true');
1497
+ /**
1498
+ * `[stickyHeaderTemplate]` naming a field that holds NativeScript XML (core parses it with `Builder.parse`
1499
+ * and binds it to the section): the XML as a header template whose `{{ path }}` bindings read the section.
1500
+ */
1501
+ const stickyHeader = (n, list, loops) => {
1502
+ const input = n.inputs.find((i) => i.name === 'stickyHeaderTemplate');
1503
+ const name = input && sourceOf(input.value).trim().replace(/^this\./, '');
1504
+ const field = name ? cls.members.find((m) => ts.isPropertyDeclaration(m) && m.name.getText() === name) : undefined;
1505
+ const init = field?.initializer;
1506
+ const xml = n.attributes.find((a) => a.name === 'stickyHeaderTemplate')?.value
1507
+ ?? (init && (ts.isStringLiteral(init) || ts.isNoSubstitutionTemplateLiteral(init)) ? init.text : undefined);
1508
+ if (xml === undefined)
1509
+ throw new Error(`${path}: a ListView's stickyHeaderTemplate is supported as a string of XML (a field initialized with a literal) in a release build`);
1510
+ const section = `$section${loops.length}`;
1511
+ const read = (e) => {
1512
+ if (!/^\s*[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*\s*$/.test(e))
1513
+ throw new Error(`${path}: the sticky header binding {{${e}}} is not supported in a release build yet (a property path is)`);
1514
+ return `${section}.${e.trim()}`;
1515
+ };
1516
+ const bound = xml.replace(/([\w.-]+)\s*=\s*(['"])([^'"]*\{\{[^'"]*)\2/g, (_m, attr, _q, value) => {
1517
+ const parts = value.split(/\{\{(.*?)\}\}/);
1518
+ const whole = parts.length === 3 && !parts[0] && !parts[2];
1519
+ const code = whole ? read(parts[1]) : '`' + parts.map((p, i) => (i % 2 ? '${' + read(p) + '}' : p.replace(/[`\\$]/g, (x) => '\\' + x))).join('') + '`';
1520
+ return `[${attr}]="${code}"`;
1521
+ });
1522
+ // XML closes any element with `/>`; Angular's parser only void and custom ones.
1523
+ const closed = bound.replace(/<([A-Za-z][\w.-]*)((?:\s+[^<>]*?)?)\s*\/>/g, '<$1$2></$1>');
1524
+ if (bound.includes('{{'))
1525
+ throw new Error(`${path}: a stickyHeaderTemplate binds attributes only in a release build`);
1526
+ const parsed = ng.parseTemplate(closed, path + '.stickyHeader.html', { preserveWhitespaces: false });
1527
+ // Its spans are the header string's, not the template's: its methods keep the template line of the list.
1528
+ const saved = here;
1529
+ const first = methods.length;
1530
+ if (parsed.errors?.length)
1531
+ throw new Error(`${path}: stickyHeaderTemplate: ${parsed.errors[0]}`);
1532
+ const loop = { item: section, index: `$s${loops.length}`, param: `${section} = ${list}[0], $s${loops.length} = 0` };
1533
+ const body = nodes(parsed.nodes, [...loops, loop]);
1534
+ for (let k = first; k < methods.length; k++)
1535
+ if (saved === null)
1536
+ located.delete(k);
1537
+ else
1538
+ located.set(k, saved);
1539
+ here = saved;
1540
+ if (body.length !== 1 || body[0].kind !== 'element')
1541
+ throw new Error(`${path}: a stickyHeaderTemplate needs exactly one root element`);
1542
+ return { kind: 'template', key: '$header', item: section, index: loop.index, body, header: true, xml };
1543
+ };
1544
+ /** `*tabItem="{ title, iconSource, … }"` (TabViewItemDirective): a TabViewItem with those properties around the element. */
1545
+ const tabItem = (t, loops) => {
1546
+ at(t.startSourceSpan);
1547
+ const bound = t.templateAttrs.find((a) => a instanceof ng.TmplAstBoundAttribute && a.name === 'tabItem');
1548
+ const root = bound && (bound.value instanceof ng.ASTWithSource ? bound.value.ast : bound.value);
1549
+ if (!(root instanceof ng.LiteralMap))
1550
+ throw new Error(`${path}: *tabItem takes an object literal in a release build`);
1551
+ const attrs = root.keys.map((k, i) => ({ name: k.key, method: expr(template.slice(root.values[i].sourceSpan.start, root.values[i].sourceSpan.end), loops) }));
1552
+ return { kind: 'element', tag: 'TabViewItem', attrs, events: [], children: nodes(t.children, loops) };
1553
+ };
1554
+ /**
1555
+ * `<ng-container>`, a comment in Angular's view: its children join its parent, and its attributes only select
1556
+ * directives. `[ngSwitch]` and `[ngTemplateOutlet]` are the directives it takes; the outlet's view follows the
1557
+ * container's own children, as a ViewContainerRef inserts at its anchor.
1558
+ */
1559
+ const container = (n, loops) => {
1560
+ if (n.outputs.length)
1561
+ throw new Error(`${path}: (${n.outputs[0].name}) on <ng-container> is not supported in a release build yet`);
1562
+ if (n.references.length)
1563
+ throw new Error(`${path}: #${n.references[0].name} on <ng-container> is not supported in a release build yet`);
1564
+ refuseUnbound(n, (name) => ['ngTemplateOutlet', 'ngTemplateOutletContext', 'ngComponentOutlet', 'ngComponentOutletInjector', 'ngComponentOutletInputs'].includes(name));
1565
+ const selected = matched('ng-container', n.attributes.map((a) => [a.name, a.value]), n.inputs.map((i) => i.name));
1566
+ if (selected.length)
1567
+ throw new Error(`${path}: the directive ${selected[0].className} on <ng-container> is not supported in a release build yet`);
1568
+ const bound = new Map(n.inputs.map((i) => [i.name, i]));
1569
+ for (const name of bound.keys()) {
1570
+ if (!['ngSwitch', 'ngTemplateOutlet', 'ngTemplateOutletContext', 'ngComponentOutlet', 'ngComponentOutletInjector', 'ngComponentOutletInputs'].includes(name))
1571
+ throw new Error(`${path}: [${name}] on <ng-container> is not supported in a release build yet`);
1572
+ }
1573
+ if (bound.has('ngTemplateOutletContext') && !bound.has('ngTemplateOutlet'))
1574
+ throw new Error(`${path}: [ngTemplateOutletContext] without [ngTemplateOutlet]`);
1575
+ if ((bound.has('ngComponentOutletInjector') || bound.has('ngComponentOutletInputs')) && !bound.has('ngComponentOutlet'))
1576
+ throw new Error(`${path}: [ngComponentOutletInjector]/[ngComponentOutletInputs] without [ngComponentOutlet]`);
1577
+ const children = () => nodes(n.children, loops);
1578
+ const own = bound.has('ngSwitch') ? switching(n, bound.get('ngSwitch').value, loops, children) : children();
1579
+ const outletted = bound.has('ngTemplateOutlet') ? outlet(bound.get('ngTemplateOutlet').value, bound.get('ngTemplateOutletContext')?.value, loops) : [];
1580
+ const compOutletted = bound.has('ngComponentOutlet')
1581
+ ? [{
1582
+ kind: 'componentOutlet',
1583
+ component: expr(code(bound.get('ngComponentOutlet').value, loops), loops, true),
1584
+ ...(bound.has('ngComponentOutletInjector') ? { injector: expr(code(bound.get('ngComponentOutletInjector').value, loops), loops, true) } : {}),
1585
+ ...(bound.has('ngComponentOutletInputs') ? { inputs: expr(code(bound.get('ngComponentOutletInputs').value, loops), loops, true) } : {}),
1586
+ }]
1587
+ : [];
1588
+ return [...own, ...outletted, ...compOutletted];
1589
+ };
1590
+ /** The open `[ngSwitch]`es, innermost last: the method reading each one's value, and its cases' values as written. */
1591
+ const switches = [];
1592
+ /** Renders a `[ngSwitch]` element's children, its `ngSwitchCase`s comparing with `===` and `ngSwitchDefault` rendering when none matches. */
1593
+ const switching = (n, value, loops, render) => {
1594
+ const cases = [];
1595
+ const scan = (list, deeper) => {
1596
+ for (const c of list) {
1597
+ if (c instanceof ng.TmplAstElement && c.inputs.some((i) => i.name === 'ngSwitch'))
1598
+ continue;
1599
+ if (c instanceof ng.TmplAstTemplate) {
1600
+ const given = [...c.templateAttrs, ...c.inputs].find((a) => a instanceof ng.TmplAstBoundAttribute && a.name === 'ngSwitchCase');
1601
+ if (given) {
1602
+ if (deeper)
1603
+ throw new Error(`${path}: an ngSwitchCase inside a loop of its [ngSwitch] is not supported in a release build yet`);
1604
+ cases.push(given.value);
1605
+ }
1606
+ const loop = [...c.templateAttrs, ...c.inputs].some((a) => a.name === 'ngForOf');
1607
+ scan(c.children, deeper || loop);
1608
+ continue;
1609
+ }
1610
+ if (c instanceof ng.TmplAstForLoopBlock) {
1611
+ scan(c.children, true);
1612
+ continue;
1613
+ }
1614
+ if (c instanceof ng.TmplAstElement)
1615
+ scan(c.children, deeper || core.canonical(c.name) === 'ListView');
1616
+ else if (c instanceof ng.TmplAstIfBlock)
1617
+ for (const b of c.branches)
1618
+ scan(b.children, deeper);
1619
+ else if (c instanceof ng.TmplAstSwitchBlock)
1620
+ for (const g of c.groups)
1621
+ scan(g.children, deeper);
1622
+ }
1623
+ };
1624
+ scan(n.children, false);
1625
+ switches.push({ subject: expr(code(value, loops), loops), loops, cases });
1626
+ try {
1627
+ return render();
1628
+ }
1629
+ finally {
1630
+ switches.pop();
1631
+ }
1632
+ };
1633
+ /** `*ngSwitchCase="v"` and `*ngSwitchDefault`: an `if` on the nearest `[ngSwitch]` above it. */
1634
+ const switchCase = (t, given, loops) => {
1635
+ const sw = switches.at(-1);
1636
+ if (!sw)
1637
+ throw new Error(`${path}: ${given ? 'ngSwitchCase' : 'ngSwitchDefault'} outside an element with [ngSwitch]`);
1638
+ const subject = `this.${sw.subject}(${args(sw.loops)})`;
1639
+ const cond = given
1640
+ ? expr(`(${subject}) === (${code(given.value, loops)})`, loops)
1641
+ : expr(sw.cases.length ? `!(${sw.cases.map((c) => `(${subject}) === (${code(c, sw.loops)})`).join(' || ')})` : 'true', loops);
1642
+ return [{ kind: 'if', branches: [{ cond, body: nodes(t.children, loops) }] }];
1643
+ };
1644
+ const dynamicTemplates = new Map();
1645
+ const dynamicRefNames = new Set();
1646
+ const expandingTemplates = new Set();
1647
+ const ctxLoopFor = (t, ctxVar = '$ctx') => {
1648
+ const ctxNames = {};
1649
+ for (const v of t.variables) {
1650
+ const key = v.value || '$implicit';
1651
+ ctxNames[v.name] = `(${ctxVar} as any)?.${/^[A-Za-z_$][\w$]*$/.test(key) ? key : `[${JSON.stringify(key)}]`}`;
1652
+ }
1653
+ return { item: ctxVar, param: `${ctxVar}: any`, names: ctxNames };
1654
+ };
1655
+ const ensureDynamicTemplate = (refName) => {
1656
+ const field = `$tpl_${refName}`;
1657
+ if (!dynamicTemplates.has(refName) && !dynamicRefNames.has(refName)) {
1658
+ const t = references.get(refName);
1659
+ usesTemplateRef = true;
1660
+ const entry = { field, ctxParam: '$ctx', body: [] };
1661
+ dynamicTemplates.set(refName, entry);
1662
+ methods.push(` readonly ${field} = new $TemplateRef();`);
1663
+ scope.names.set(refName, `this.${field}`);
1664
+ const savedNarrowing = narrowing;
1665
+ narrowing = [];
1666
+ try {
1667
+ entry.body = nodes(t.children, [ctxLoopFor(t)]);
1668
+ }
1669
+ finally {
1670
+ narrowing = savedNarrowing;
1671
+ }
1672
+ }
1673
+ return `this.${field}`;
1674
+ };
1675
+ /**
1676
+ * `[ngTemplateOutlet]` (NgTemplateOutlet): static non-recursive `<ng-template #name>` references inline directly;
1677
+ * dynamic expressions (`rendererFor(...)`, signals, `TemplateRef` inputs) or recursive references lower to `templateOutlet`.
1678
+ */
1679
+ const outlet = (tpl, context, loops) => {
1680
+ const root = tpl instanceof ng.ASTWithSource ? tpl.ast : tpl;
1681
+ const given = context instanceof ng.ASTWithSource ? context.ast : context;
1682
+ // A context written as an object literal gives each variable its property's expression.
1683
+ const fields = given instanceof ng.LiteralMap ? new Map(given.keys.map((k, i) => [k.kind === 'property' ? k.key : undefined, given.values[i]])) : null;
1684
+ const ctx = context && !fields ? core.rewrite(clean(code(context, loops)), local(loops)) : null;
1685
+ const read = (key) => {
1686
+ if (fields) {
1687
+ const v = fields.get(key);
1688
+ return v ? `(${core.rewrite(clean(code(v, loops)), local(loops))})` : 'undefined';
1689
+ }
1690
+ return ctx === null ? 'undefined' : `(${ctx})?.${/^[A-Za-z_$][\w$]*$/.test(key) ? key : `[${JSON.stringify(key)}]`}`;
1691
+ };
1692
+ const render = (ast) => {
1693
+ if (ast instanceof ng.LiteralPrimitive && ast.value == null)
1694
+ return [];
1695
+ if (ast instanceof ng.Conditional)
1696
+ return [{ kind: 'if', branches: [{ cond: test(template.slice(ast.condition.sourceSpan.start, ast.condition.sourceSpan.end), loops), body: render(ast.trueExp) }, { cond: null, body: render(ast.falseExp) }] }];
1697
+ const name = ast instanceof ng.PropertyRead && ast.receiver instanceof ng.ImplicitReceiver ? ast.name : null;
1698
+ const t = name !== null ? references.get(name) : undefined;
1699
+ if (t && t.tagName === 'ng-template' && !dynamicTemplates.has(name) && !dynamicRefNames.has(name) && !expandingTemplates.has(name)) {
1700
+ expandingTemplates.add(name);
1701
+ const saved = new Map(t.variables.map((v) => [v.name, aliases.get(v.name)]));
1702
+ for (const v of t.variables)
1703
+ aliases.set(v.name, read(v.value || '$implicit'));
1704
+ try {
1705
+ return nodes(t.children, loops);
1706
+ }
1707
+ finally {
1708
+ expandingTemplates.delete(name);
1709
+ for (const [k, v] of saved)
1710
+ if (v === undefined)
1711
+ aliases.delete(k);
1712
+ else
1713
+ aliases.set(k, v);
1714
+ }
1715
+ }
1716
+ // Dynamic or recursive template outlet: bind referenced `<ng-template #name>` to a `$tpl_` field and mount via `TemplateOutlet`.
1717
+ if (t && t.tagName === 'ng-template')
1718
+ ensureDynamicTemplate(name);
1719
+ return [{
1720
+ kind: 'templateOutlet',
1721
+ template: expr(code(ast, loops), loops, true),
1722
+ ...(context ? { context: expr(code(context, loops), loops, true) } : {}),
1723
+ }];
1724
+ };
1725
+ return render(root);
1726
+ };
1727
+ /**
1728
+ * `nsRouterLink` (@nativescript/angular's NSRouterLink) on any element: a tap handler navigating with its commands,
1729
+ * a single command as a one-command array, relative to the component's route unless `relativeTo` is given. The
1730
+ * route is the component's own, read when it is constructed: the router's current route changes as pages are made.
1731
+ */
1732
+ let routed = false;
1733
+ const routerLink = (n, loops) => {
1734
+ const bound = new Map(n.inputs.map((i) => [i.name, i]));
1735
+ const fixed = new Map(n.attributes.map((a) => [a.name, a.value]));
1736
+ if (bound.has('nsRouterLinkActive') || fixed.has('nsRouterLinkActive'))
1737
+ throw new Error(`${path}: nsRouterLinkActive is not supported in a release build yet`);
1738
+ if (!bound.has('nsRouterLink') && !fixed.has('nsRouterLink'))
1739
+ return null;
1740
+ at(bound.get('nsRouterLink')?.sourceSpan ?? n.attributes.find((a) => a.name === 'nsRouterLink')?.sourceSpan);
1741
+ for (const name of ROUTER_LINK_INPUTS) {
1742
+ if (!ROUTER_LINK_SUPPORTED.has(name) && (bound.has(name) || fixed.has(name)))
1743
+ throw new Error(`${path}: nsRouterLink's ${name} is not supported in a release build yet`);
1744
+ }
1745
+ const value = (name) => (bound.has(name) ? `(${code(bound.get(name).value, loops)})` : fixed.has(name) ? JSON.stringify(fixed.get(name)) : null);
1746
+ routed = true;
1747
+ const body = [];
1748
+ const given = bound.get('nsRouterLink');
1749
+ const root = given && (given.value instanceof ng.ASTWithSource ? given.value.ast : given.value);
1750
+ let commands;
1751
+ if (root instanceof ng.LiteralArray)
1752
+ commands = code(given.value, loops);
1753
+ else if (!given)
1754
+ commands = `[${value('nsRouterLink')}]`;
1755
+ else {
1756
+ body.push(`const $commands: any = ${value('nsRouterLink')}`, 'if ($commands == null) return');
1757
+ commands = 'Array.isArray($commands) ? $commands : [$commands]';
1758
+ }
1759
+ const extras = [`relativeTo: ${value('relativeTo') ?? 'this.$route'}`];
1760
+ const transition = value('pageTransition');
1761
+ const duration = value('pageTransitionDuration');
1762
+ const constant = (name) => {
1763
+ if (fixed.has(name))
1764
+ return fixed.get(name);
1765
+ const v = bound.get(name)?.value;
1766
+ const ast = v instanceof ng.ASTWithSource ? v.ast : v;
1767
+ return ast instanceof ng.LiteralPrimitive && ast.value !== undefined ? ast.value : undefined;
1768
+ };
1769
+ // NSRouterLink.getTransition: a boolean is `animated`; 'none' and 'false' turn animation off; another string names the transition.
1770
+ const known = constant('pageTransition');
1771
+ if (!duration && (typeof known === 'boolean' || typeof known === 'string')) {
1772
+ if (known === false || known === 'none' || known === 'false')
1773
+ extras.push('animated: false');
1774
+ else if (typeof known === 'string')
1775
+ extras.push(`transition: { name: ${JSON.stringify(known)} }`);
1776
+ }
1777
+ else if (transition || duration) {
1778
+ body.push(`const $given: any = ${transition ?? 'true'}`, 'let $animated = true', 'let $transition: any = undefined', `if (typeof $given === 'boolean') { $animated = $given; } else if (typeof $given === 'string') { if ($given === 'none' || $given === 'false') { $animated = false; } else { $transition = { name: $given }; } } else { $transition = $given; }`);
1779
+ if (duration)
1780
+ body.push(`const $duration = +${duration}`, 'if (!isNaN($duration)) { $transition = $transition ?? {}; $transition.duration = $duration; }');
1781
+ extras.push('animated: $animated', 'transition: $transition');
1782
+ }
1783
+ const clear = value('clearHistory');
1784
+ const clearing = constant('clearHistory');
1785
+ if (clearing !== undefined)
1786
+ extras.push(`clearHistory: ${clearing === true || clearing === 'true'}`);
1787
+ else if (clear) {
1788
+ body.push(`const $clear: any = ${clear}`);
1789
+ extras.push(`clearHistory: $clear === true || $clear === 'true'`);
1790
+ }
1791
+ body.push(`this.$router.navigate(${commands}, { ${extras.join(', ')} })`);
1792
+ return { name: 'tap', method: handler(body.join('; '), loops) };
1793
+ };
1794
+ /** `*ngIf` (with `else` and `as`) and `*ngFor` (with `trackBy`, `index`, `even`, `odd`) on an element, `<ng-container>` or `<ng-template>`. */
1795
+ const structural = (t, loops) => {
1796
+ at(t.startSourceSpan);
1797
+ // `*ngIf` binds the directive through templateAttrs (the template's inputs are its element's); `<ng-template [ngIf]>` through inputs.
1798
+ const directive = t.tagName === 'ng-template' ? [...t.templateAttrs, ...t.inputs] : t.templateAttrs;
1799
+ const bound = (name) => directive.find((a) => a instanceof ng.TmplAstBoundAttribute && a.name === name);
1800
+ const ngIf = bound('ngIf');
1801
+ const ngForOf = bound('ngForOf');
1802
+ const outletOf = bound('ngTemplateOutlet');
1803
+ if (outletOf) {
1804
+ for (const a of directive)
1805
+ if (!['ngTemplateOutlet', 'ngTemplateOutletContext'].includes(a.name))
1806
+ throw new Error(`${path}: *ngTemplateOutlet's ${a.name} is not supported in a release build yet`);
1807
+ // The element `*ngTemplateOutlet` is written on is the directive's own template, which it never renders.
1808
+ return outlet(outletOf.value, bound('ngTemplateOutletContext')?.value, loops);
1809
+ }
1810
+ const compOutletOf = bound('ngComponentOutlet');
1811
+ if (compOutletOf) {
1812
+ for (const a of directive)
1813
+ if (!['ngComponentOutlet', 'ngComponentOutletInjector', 'ngComponentOutletInputs'].includes(a.name))
1814
+ throw new Error(`${path}: *ngComponentOutlet's ${a.name} is not supported in a release build yet`);
1815
+ const inj = bound('ngComponentOutletInjector');
1816
+ const inp = bound('ngComponentOutletInputs');
1817
+ return [{
1818
+ kind: 'componentOutlet',
1819
+ component: expr(code(compOutletOf.value, loops), loops, true),
1820
+ ...(inj ? { injector: expr(code(inj.value, loops), loops, true) } : {}),
1821
+ ...(inp ? { inputs: expr(code(inp.value, loops), loops, true) } : {}),
1822
+ }];
1823
+ }
1824
+ const caseOf = bound('ngSwitchCase');
1825
+ if (caseOf || directive.some((a) => a.name === 'ngSwitchDefault')) {
1826
+ if (directive.length !== 1)
1827
+ throw new Error(`${path}: ${directive.map((a) => a.name).join(', ')} on one template is not supported in a release build yet`);
1828
+ return switchCase(t, caseOf, loops);
1829
+ }
1830
+ const matchedDirs = matched(t.tagName ?? 'ng-template', t.attributes.map((a) => [a.name, a.value]), directive.map((a) => a.name));
1831
+ const structuralDirective = matchedDirs.find((d) => d.structural) ?? (t.tagName !== 'ng-template' ? matchedDirs[0] : undefined);
1832
+ if (structuralDirective) {
1833
+ const names = imported.get(structuralDirective.file) ?? new Map();
1834
+ imported.set(structuralDirective.file, names);
1835
+ if (!names.has(structuralDirective.className))
1836
+ names.set(structuralDirective.className, `$Dir_${structuralDirective.className}`);
1837
+ const alias = names.get(structuralDirective.className);
1838
+ const typeArgs = structuralDirective.typeParams ? `<${Array(structuralDirective.typeParams).fill('any').join(', ')}>` : '';
1839
+ const dName = `$d${directiveCount++}`;
1840
+ const make = expr(structuralDirective.create ? `${alias}.$create()` : `new ${alias}()`, loops);
1841
+ const dInner = [...loops, { item: dName, param: `${dName}: ${alias}${typeArgs}` }];
1842
+ const dValued = [...dInner, { item: '$v', param: '$v: any' }];
1843
+ const setter = (member) => handlerOf(`${structuralDirective.transforms?.has(member) ? `${dName}.$set_${member}($v)` : `${dName}.${member}${structuralDirective.signals.has(member) ? '.$assign($v)' : ' = $v'}`}${structuralDirective.hooks.has('ngOnChanges') ? `; ${dName}.$change(${JSON.stringify(member)}, $v)` : ''}`, dValued);
1844
+ const dInputs = [];
1845
+ for (const [inName, member] of structuralDirective.inputs) {
1846
+ const b = directive.find((a) => a instanceof ng.TmplAstBoundAttribute && a.name === inName);
1847
+ const ta = directive.find((a) => a instanceof ng.TmplAstTextAttribute && a.name === inName);
1848
+ if (b)
1849
+ dInputs.push({ set: setter(member), method: expr(code(b.value, loops), loops, true) });
1850
+ else if (ta)
1851
+ dInputs.push({ set: setter(member), value: ta.value });
1852
+ }
1853
+ const dHook = (h) => (structuralDirective.hooks.has(h) ? handlerOf(`${dName}.${h}()`, dInner) : undefined);
1854
+ const dHooks = Object.fromEntries(['init:ngOnInit', 'doCheck:ngDoCheck', 'destroy:ngOnDestroy', 'afterContentInit:ngAfterContentInit', 'afterContentChecked:ngAfterContentChecked', 'afterViewInit:ngAfterViewInit', 'afterViewChecked:ngAfterViewChecked'].flatMap((e) => {
1855
+ const [field, h] = e.split(':');
1856
+ const m = dHook(h);
1857
+ return m ? [[field, m]] : [];
1858
+ }));
1859
+ const ctxVar = `$ctx${loops.length}`;
1860
+ const ctxNames = {};
1861
+ for (const v of t.variables) {
1862
+ const key = v.value || '$implicit';
1863
+ ctxNames[v.name] = `(${ctxVar} as any)?.${/^[A-Za-z_$][\w$]*$/.test(key) ? key : `[${JSON.stringify(key)}]`}`;
1864
+ }
1865
+ const ctxLoops = [...loops, { item: ctxVar, param: `${ctxVar}: any`, names: ctxNames }];
1866
+ const body = nodes(t.children, ctxLoops);
1867
+ return [{
1868
+ kind: 'structural',
1869
+ directive: { name: dName, make, inputs: dInputs, listeners: [], bindings: [], attributes: [], ...dHooks, ...(structuralDirective.hooks.has('ngOnChanges') ? { changes: true } : {}) },
1870
+ ctxParam: ctxVar,
1871
+ body,
1872
+ }];
1873
+ }
1874
+ if (!ngIf && !ngForOf) {
1875
+ // An `<ng-template #name>` renders only where an `else` names it, or binds its body in-place when dynamically referenced.
1876
+ if (t.tagName === 'ng-template' && t.references.length && !directive.length) {
1877
+ const boundNodes = [];
1878
+ const ctxVar = `$ctx${loops.length}`;
1879
+ for (const r of t.references) {
1880
+ if (!dynamicRefNames.has(r.name))
1881
+ continue;
1882
+ const savedNarrowing = narrowing;
1883
+ narrowing = [];
1884
+ try {
1885
+ boundNodes.push({ kind: 'bindTemplate', field: `$tpl_${r.name}`, ctxParam: ctxVar, body: nodes(t.children, [...loops, ctxLoopFor(t, ctxVar)]) });
1886
+ }
1887
+ finally {
1888
+ narrowing = savedNarrowing;
1889
+ }
1890
+ }
1891
+ return boundNodes;
1892
+ }
1893
+ throw new Error(`${path}: <${t.tagName}> with ${directive.map((a) => a.name).join(', ') || 'no directive'} is not supported in a release build yet`);
1894
+ }
1895
+ if (ngIf) {
1896
+ for (const a of directive)
1897
+ if (!['ngIf', 'ngIfElse'].includes(a.name))
1898
+ throw new Error(`${path}: *ngIf's ${a.name} is not supported in a release build yet`);
1899
+ const condition = code(ngIf.value, loops);
1900
+ const elseName = bound('ngIfElse');
1901
+ const otherwise = elseName ? references.get(sourceOf(elseName.value).trim()) : undefined;
1902
+ if (elseName && !otherwise)
1903
+ throw new Error(`${path}: *ngIf's else names no <ng-template #${sourceOf(elseName.value).trim()}>`);
1904
+ const renamed = t.variables.map((v) => {
1905
+ if (v.value !== 'ngIf')
1906
+ throw new Error(`${path}: *ngIf's ${v.value} is not supported in a release build yet`);
1907
+ return v.name;
1908
+ });
1909
+ const cond = test(condition, loops);
1910
+ for (const v of renamed)
1911
+ aliases.set(v, `(${core.rewrite(clean(condition), local(loops))})!`);
1912
+ const body = nodes(t.children, loops);
1913
+ for (const v of renamed)
1914
+ aliases.delete(v);
1915
+ return [{ kind: 'if', branches: [{ cond, body }, ...(otherwise ? [{ cond: null, body: nodes(otherwise.children, loops) }] : [])] }];
1916
+ }
1917
+ for (const a of directive)
1918
+ if (!['ngFor', 'ngForOf', 'ngForTrackBy'].includes(a.name))
1919
+ throw new Error(`${path}: *ngFor's ${a.name} is not supported in a release build yet`);
1920
+ const item = t.variables.find((v) => (v.value || '$implicit') === '$implicit')?.name ?? `$item${loops.length}`;
1921
+ const index = t.variables.find((v) => v.value === 'index')?.name ?? `$i${loops.length}`;
1922
+ const names = {};
1923
+ for (const v of t.variables) {
1924
+ if (v.name === item || v.name === index)
1925
+ continue;
1926
+ if (v.value === 'even')
1927
+ names[v.name] = `(${index} % 2 === 0)`;
1928
+ else if (v.value === 'odd')
1929
+ names[v.name] = `(${index} % 2 !== 0)`;
1930
+ else
1931
+ throw new Error(`${path}: *ngFor's ${v.value} is not supported in a release build yet`);
1932
+ }
1933
+ // NgForOf renders no rows for null, which an async pipe gives before its first value.
1934
+ const source = code(ngForOf.value, loops);
1935
+ const items = expr(source === sourceOf(ngForOf.value) ? source : `(${source}) ?? []`, loops);
1936
+ const loop = { item, index, param: `${item} = this.${items}(${args(loops)})[0], ${index} = 0`, names };
1937
+ const inner = [...loops, loop];
1938
+ // NgForOf keeps rows by identity, or by what its trackBy function returns for (index, item).
1939
+ const trackBy = bound('ngForTrackBy');
1940
+ const key = trackBy ? expr(`(${sourceOf(trackBy.value)})(${index}, ${item})`, inner) : null;
1941
+ return [{ kind: 'for', items, key, item, index, body: nodes(t.children, inner) }];
1942
+ };
1943
+ const parsed = ng.parseTemplate(template, path + '.html', { preserveWhitespaces: false });
1944
+ if (parsed.errors?.length)
1945
+ throw new Error(`${path}: ${parsed.errors[0]}`);
1946
+ const references = new Map();
1947
+ const findReferences = (list) => {
1948
+ for (const n of list) {
1949
+ if (n instanceof ng.TmplAstTemplate)
1950
+ for (const r of n.references)
1951
+ references.set(r.name, n);
1952
+ if (n instanceof ng.TmplAstElement || n instanceof ng.TmplAstTemplate || n instanceof ng.TmplAstForLoopBlock)
1953
+ findReferences(n.children);
1954
+ if (n instanceof ng.TmplAstIfBlock)
1955
+ for (const b of n.branches)
1956
+ findReferences(b.children);
1957
+ if (n instanceof ng.TmplAstForLoopBlock && n.empty)
1958
+ findReferences(n.empty.children);
1959
+ if (n instanceof ng.TmplAstSwitchBlock)
1960
+ for (const g of n.groups)
1961
+ findReferences(g.children);
1962
+ }
1963
+ };
1964
+ findReferences(parsed.nodes);
1965
+ // Pre-register `<ng-template #name>` refs read inside `@let` expressions, passed to element/directive inputs
1966
+ // (e.g. `[hlmDropdownMenuTrigger]="boardMenu"`), or transitively/recursively referenced, so `bindTemplate` compiles in-place.
1967
+ const collectRefReads = (list, into, includeDirectOutlet) => {
1968
+ const checkSrc = (src) => {
1969
+ for (const refName of references.keys())
1970
+ if (new RegExp(`\\b${refName}\\b`).test(src))
1971
+ into.add(refName);
1972
+ };
1973
+ for (const n of list) {
1974
+ if (n instanceof ng.TmplAstLetDeclaration)
1975
+ checkSrc(sourceOf(n.value));
1976
+ else if (n instanceof ng.TmplAstTemplate) {
1977
+ for (const a of [...n.templateAttrs, ...n.inputs]) {
1978
+ if (!(a instanceof ng.TmplAstBoundAttribute))
1979
+ continue;
1980
+ if (!includeDirectOutlet && (a.name === 'ngIfElse' || a.name === 'ngTemplateOutlet'))
1981
+ continue;
1982
+ checkSrc(sourceOf(a.value));
1983
+ }
1984
+ }
1985
+ else if (n instanceof ng.TmplAstElement) {
1986
+ for (const i of n.inputs) {
1987
+ if (!includeDirectOutlet && i.name === 'ngTemplateOutlet')
1988
+ continue;
1989
+ checkSrc(sourceOf(i.value));
1990
+ }
1991
+ }
1992
+ if (n instanceof ng.TmplAstElement || n instanceof ng.TmplAstTemplate || n instanceof ng.TmplAstForLoopBlock)
1993
+ collectRefReads(n.children, into, includeDirectOutlet);
1994
+ if (n instanceof ng.TmplAstIfBlock)
1995
+ for (const b of n.branches)
1996
+ collectRefReads(b.children, into, includeDirectOutlet);
1997
+ if (n instanceof ng.TmplAstForLoopBlock && n.empty)
1998
+ collectRefReads(n.empty.children, into, includeDirectOutlet);
1999
+ if (n instanceof ng.TmplAstSwitchBlock)
2000
+ for (const g of n.groups)
2001
+ collectRefReads(g.children, into, includeDirectOutlet);
2002
+ }
2003
+ };
2004
+ collectRefReads(parsed.nodes, dynamicRefNames, false);
2005
+ // Transitive closure: any `<ng-template #b>` referenced inside an already-dynamic `<ng-template #a>`, or self-recursive templates.
2006
+ for (const [refName, tpl] of references) {
2007
+ const inside = new Set();
2008
+ collectRefReads(tpl.children, inside, true);
2009
+ if (inside.has(refName))
2010
+ dynamicRefNames.add(refName);
2011
+ }
2012
+ let grew = true;
2013
+ while (grew) {
2014
+ grew = false;
2015
+ for (const refName of [...dynamicRefNames]) {
2016
+ const tpl = references.get(refName);
2017
+ if (!tpl)
2018
+ continue;
2019
+ const inside = new Set();
2020
+ collectRefReads(tpl.children, inside, true);
2021
+ for (const r of inside)
2022
+ if (!dynamicRefNames.has(r)) {
2023
+ dynamicRefNames.add(r);
2024
+ grew = true;
2025
+ }
2026
+ }
2027
+ }
2028
+ for (const refName of dynamicRefNames) {
2029
+ usesTemplateRef = true;
2030
+ const field = `$tpl_${refName}`;
2031
+ methods.push(` readonly ${field} = new $TemplateRef();`);
2032
+ scope.names.set(refName, `this.${field}`);
2033
+ }
2034
+ // Plain element template references (`#promoInput` on `<input>`, read in handlers/bindings like `(click)="apply(promoInput.value)"`).
2035
+ const elementRefFields = new Map();
2036
+ const collectElementRefs = (list) => {
2037
+ for (const n of list) {
2038
+ if (n instanceof ng.TmplAstElement) {
2039
+ for (const r of n.references) {
2040
+ if (!r.value && !references.has(r.name) && !scope.names.has(r.name) && !elementRefFields.has(r.name)) {
2041
+ const field = `$ref_${r.name}`;
2042
+ elementRefFields.set(r.name, field);
2043
+ methods.push(` ${field}: any = undefined;`);
2044
+ scope.names.set(r.name, `this.${field}`);
2045
+ }
2046
+ }
2047
+ }
2048
+ if (n instanceof ng.TmplAstElement || n instanceof ng.TmplAstTemplate || n instanceof ng.TmplAstForLoopBlock)
2049
+ collectElementRefs(n.children);
2050
+ if (n instanceof ng.TmplAstIfBlock)
2051
+ for (const b of n.branches)
2052
+ collectElementRefs(b.children);
2053
+ if (n instanceof ng.TmplAstForLoopBlock && n.empty)
2054
+ collectElementRefs(n.empty.children);
2055
+ if (n instanceof ng.TmplAstSwitchBlock)
2056
+ for (const g of n.groups)
2057
+ collectElementRefs(g.children);
2058
+ }
2059
+ };
2060
+ collectElementRefs(parsed.nodes);
2061
+ const ownElements = (list) => {
2062
+ for (const n of list) {
2063
+ if (!(n instanceof ng.TmplAstElement))
2064
+ continue;
2065
+ for (const r of n.references)
2066
+ staticRefs.add(r.name);
2067
+ ownElements(n.children);
2068
+ }
2069
+ };
2070
+ ownElements(parsed.nodes);
2071
+ for (const q of queries)
2072
+ if (q.static && q.ref && staticRefs.has(q.ref))
2073
+ staticQueries.add(q);
2074
+ const tree = nodes(parsed.nodes, []);
2075
+ // `@Component({ host: { ... } })`: static attributes, property/attribute/class bindings and listeners applied to the component's root element(s).
2076
+ if (hostMeta) {
2077
+ if (!ts.isObjectLiteralExpression(hostMeta))
2078
+ throw new Error(`${path}: @Component's host is read as an object literal in a release build`);
2079
+ const hostStaticAttrs = [];
2080
+ const hostBoundAttrs = [];
2081
+ const hostClassToggles = [];
2082
+ const hostBoundClass = [];
2083
+ const hostEvents = [];
2084
+ for (const p of hostMeta.properties) {
2085
+ if (!ts.isPropertyAssignment(p) || !ts.isStringLiteralLike(p.initializer))
2086
+ throw new Error(`${path}: @Component's host entries are strings in a release build`);
2087
+ const key = ts.isStringLiteralLike(p.name) ? p.name.text : p.name.getText();
2088
+ const val = p.initializer.text;
2089
+ if (/^\(.*\)$/.test(key)) {
2090
+ const ev = key.slice(1, -1);
2091
+ if (ev.includes(':'))
2092
+ throw new Error(`${path}: host listener (${ev}), a global target, is not supported in a release build yet`);
2093
+ hostEvents.push({ name: ev, code: val });
2094
+ }
2095
+ else if (/^\[.*\]$/.test(key)) {
2096
+ const propName = key.slice(1, -1);
2097
+ if (propName === 'class')
2098
+ hostBoundClass.push(val);
2099
+ else if (propName.startsWith('class.'))
2100
+ hostClassToggles.push([propName.slice(6), val]);
2101
+ else if (propName.startsWith('attr.'))
2102
+ hostBoundAttrs.push({ name: propName.slice(5), code: val });
2103
+ else
2104
+ hostBoundAttrs.push({ name: propName, code: val });
2105
+ }
2106
+ else {
2107
+ hostStaticAttrs.push({ name: key, value: val });
2108
+ }
2109
+ }
2110
+ const hostStaticClass = hostStaticAttrs.filter((a) => a.name === 'class').map((a) => a.value).join(' ').trim();
2111
+ const otherHostStatic = hostStaticAttrs.filter((a) => a.name !== 'class');
2112
+ const hostBoundAttrMethods = hostBoundAttrs.map((b) => ({ name: b.name, method: expr(b.code, [], true) }));
2113
+ const hostEventMethods = hostEvents.map((e) => ({ name: e.name, method: handler(e.code, [], true) }));
2114
+ const applyHost = (el) => {
2115
+ for (const a of otherHostStatic)
2116
+ if (!el.attrs.some((x) => x.name === a.name))
2117
+ el.attrs.push({ name: a.name, value: a.value });
2118
+ for (const b of hostBoundAttrMethods)
2119
+ el.attrs.push(b);
2120
+ for (const e of hostEventMethods)
2121
+ el.events.push(e);
2122
+ if (hostStaticClass || hostBoundClass.length || hostClassToggles.length) {
2123
+ const idx = el.attrs.findIndex((a) => a.name === 'class');
2124
+ const existing = idx >= 0 ? el.attrs[idx] : undefined;
2125
+ if (!hostBoundClass.length && !hostClassToggles.length) {
2126
+ if (existing && 'value' in existing)
2127
+ existing.value = [hostStaticClass, existing.value].filter(Boolean).join(' ');
2128
+ else if (!existing)
2129
+ el.attrs.push({ name: 'class', value: hostStaticClass });
2130
+ }
2131
+ else {
2132
+ const base = [hostStaticClass, existing && 'value' in existing ? existing.value : ''].filter(Boolean).join(' ');
2133
+ if (idx >= 0 && existing && 'value' in existing)
2134
+ el.attrs.splice(idx, 1);
2135
+ const dynamicVal = hostBoundClass.length === 1 ? `(${hostBoundClass[0]})` : hostBoundClass.length > 1 ? `[${hostBoundClass.map((c) => `(${c})`).join(', ')}]` : 'null';
2136
+ const pairs = hostClassToggles.flatMap(([k, v]) => [JSON.stringify(k), `(${v})`]);
2137
+ el.attrs.push({ name: 'class', method: expr(`${fromRuntime('ngClassNames')}(${JSON.stringify(base)}, ${dynamicVal}, [${pairs.join(', ')}])`, []) });
2138
+ }
2139
+ }
2140
+ };
2141
+ for (const rootNode of tree)
2142
+ if (rootNode.kind === 'element')
2143
+ applyHost(rootNode);
2144
+ }
2145
+ // `@Component({ hostDirectives: [...] })`: Directive Composition API — attach host directives to root element(s) and forward exposed inputs/outputs.
2146
+ const hdOutputFields = {};
2147
+ let hdNeedsInput = false;
2148
+ let hdNeedsOutput = false;
2149
+ if (hostDirectivesMeta) {
2150
+ if (!ts.isArrayLiteralExpression(hostDirectivesMeta))
2151
+ throw new Error(`${path}: @Component's hostDirectives is read as an array literal in a release build`);
2152
+ const unwrapDir = (e) => {
2153
+ if (ts.isIdentifier(e))
2154
+ return e.text;
2155
+ if (ts.isCallExpression(e) && e.expression.getText() === 'forwardRef' && e.arguments[0] && ts.isArrowFunction(e.arguments[0]) && ts.isIdentifier(e.arguments[0].body)) {
2156
+ return e.arguments[0].body.text;
2157
+ }
2158
+ return null;
2159
+ };
2160
+ const stringList = (e, label) => {
2161
+ if (!e)
2162
+ return [];
2163
+ if (!ts.isArrayLiteralExpression(e))
2164
+ throw new Error(`${path}: hostDirectives ${label} must be an array of string literals in a release build`);
2165
+ return e.elements.map((el) => {
2166
+ if (!ts.isStringLiteralLike(el))
2167
+ throw new Error(`${path}: hostDirectives ${label} entries must be string literals in a release build`);
2168
+ return el.text;
2169
+ });
2170
+ };
2171
+ let hdFieldCount = 0;
2172
+ const hdUses = [];
2173
+ for (const el of hostDirectivesMeta.elements) {
2174
+ let dirName = null;
2175
+ let hdInputs = [];
2176
+ let hdOutputs = [];
2177
+ if (ts.isObjectLiteralExpression(el)) {
2178
+ const get = (k) => el.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === k)?.initializer;
2179
+ const dirExpr = get('directive');
2180
+ dirName = dirExpr ? unwrapDir(dirExpr) : null;
2181
+ hdInputs = stringList(get('inputs'), 'inputs');
2182
+ hdOutputs = stringList(get('outputs'), 'outputs');
2183
+ }
2184
+ else {
2185
+ dirName = unwrapDir(el);
2186
+ }
2187
+ if (!dirName)
2188
+ throw new Error(`${path}: @Component's hostDirectives entry ${el.getText().split('\n')[0]} needs a directive class name in a release build`);
2189
+ const decl = options.directives?.find((d) => d.className === dirName);
2190
+ const hdTypeArgs = decl?.typeParams ? `<${Array(decl.typeParams).fill('any').join(', ')}>` : '';
2191
+ const dName = `$d${directiveCount++}`;
2192
+ const make = expr(decl?.create ? `${dirName}.$create()` : `new ${dirName}()`, []);
2193
+ const inner = [{ item: dName, param: `${dName}: ${dirName}${hdTypeArgs}` }];
2194
+ const valued = [...inner, { item: '$v', param: '$v: any' }];
2195
+ const dirInputs = [];
2196
+ for (const mapping of hdInputs) {
2197
+ const [internal, alias] = mapping.split(':').map((s) => s.trim());
2198
+ const pub = alias || internal;
2199
+ let readExpr;
2200
+ if (members.has(pub)) {
2201
+ readExpr = props.includes(pub) ? `this.${pub}()` : `this.${pub}`;
2202
+ }
2203
+ else {
2204
+ const field = `$hdIn${hdFieldCount++}`;
2205
+ methods.push(` readonly ${field} = input<any>(undefined);`);
2206
+ hdNeedsInput = true;
2207
+ props.push(field);
2208
+ optional.push(field);
2209
+ inputAliases[field] = pub;
2210
+ readExpr = `this.${field}()`;
2211
+ }
2212
+ const member = decl?.inputs.get(internal) ?? internal;
2213
+ const setStmt = decl
2214
+ ? `if ($v !== undefined) { ${dName}.${member}${decl.signals.has(member) ? '.$assign($v)' : ' = $v'}${decl.hooks.has('ngOnChanges') ? `; ${dName}.$change(${JSON.stringify(member)}, $v)` : ''}; }`
2215
+ : `if ($v !== undefined) { const $cur: any = (${dName} as any)[${JSON.stringify(member)}]; if ($cur && typeof $cur.$assign === 'function') { $cur.$assign($v); } else { (${dName} as any)[${JSON.stringify(member)}] = $v; } }`;
2216
+ dirInputs.push({ set: handlerOf(setStmt, valued), method: expr(readExpr, [], true) });
2217
+ }
2218
+ const dirOutputs = [];
2219
+ for (const mapping of hdOutputs) {
2220
+ const [internal, alias] = mapping.split(':').map((s) => s.trim());
2221
+ const pub = alias || internal;
2222
+ const field = `$hdOut${hdFieldCount++}`;
2223
+ methods.push(` readonly ${field} = output<any>();`);
2224
+ hdNeedsOutput = true;
2225
+ outputs.push(pub);
2226
+ hdOutputFields[pub] = field;
2227
+ dirOutputs.push({ name: internal, method: handlerOf(`this.${field}.emit($event)`, [...inner, { item: '$event', param: '$event: any' }]) });
2228
+ }
2229
+ const own = { names: new Map((decl?.members ?? []).map((m) => [m, `${dName}.${m}`])) };
2230
+ const listeners = (decl?.listeners ?? []).map((l) => ({ event: l.event, method: handlerOf(core.rewrite(l.code, { names: new Map([...own.names, ['$event', '$event']]) }, 'statements'), [...inner, { item: '$event', param: '$event: any' }]) }));
2231
+ const bindings = (decl?.bindings ?? []).map((b) => ({ prop: b.prop, method: expr(core.rewrite(b.code, own), inner, true) }));
2232
+ const dHook = (h) => (decl?.hooks.has(h) ? handlerOf(`${dName}.${h}()`, inner) : undefined);
2233
+ const hooks = Object.fromEntries(['init:ngOnInit', 'doCheck:ngDoCheck', 'destroy:ngOnDestroy', 'afterContentInit:ngAfterContentInit', 'afterContentChecked:ngAfterContentChecked', 'afterViewInit:ngAfterViewInit', 'afterViewChecked:ngAfterViewChecked'].flatMap((e) => {
2234
+ const [field, h] = e.split(':');
2235
+ const m = dHook(h);
2236
+ return m ? [[field, m]] : [];
2237
+ }));
2238
+ hdUses.push({
2239
+ name: dName,
2240
+ make,
2241
+ inputs: dirInputs,
2242
+ listeners,
2243
+ bindings,
2244
+ attributes: decl?.attributes ?? [],
2245
+ ...hooks,
2246
+ ...(decl?.hooks.has('ngOnChanges') ? { changes: true } : {}),
2247
+ ...(dirOutputs.length ? { outputs: dirOutputs } : {}),
2248
+ });
2249
+ }
2250
+ if (hdUses.length) {
2251
+ for (const rootNode of tree) {
2252
+ if (rootNode.kind === 'element')
2253
+ rootNode.directives = [...hdUses, ...(rootNode.directives ?? [])];
2254
+ }
2255
+ }
2256
+ }
2257
+ // Content queries (`contentChild` / `contentChildren` / `@ContentChild` / `@ContentChildren`): public setters called by parent slot projections.
2258
+ for (const cq of contentQueries) {
2259
+ const paramType = cq.typeArg ?? 'any';
2260
+ if (cq.signal && !cq.many) {
2261
+ methods.push(` $cqSet_${cq.field}(v: ${paramType}) { this.${cq.field}.set(v); }`);
2262
+ methods.push(` $cqUnset_${cq.field}(_v?: ${paramType}) { this.${cq.field}.set(undefined as any); }`);
2263
+ }
2264
+ else if (cq.signal && cq.many) {
2265
+ methods.push(` $cqSet_${cq.field}(v: ${paramType}) { this.${cq.field}.update((xs) => [...xs, v]); }`);
2266
+ methods.push(` $cqUnset_${cq.field}(v: ${paramType}) { this.${cq.field}.update((xs) => xs.filter((x) => x !== v)); }`);
2267
+ }
2268
+ else if (!cq.many) {
2269
+ methods.push(` $cqSet_${cq.field}(v: any) { this.${cq.field} = v; }`);
2270
+ }
2271
+ else {
2272
+ methods.push(` $cqSet_${cq.field}(k: any, v: any) { this.${cq.field}.$add(k, v); }`);
2273
+ methods.push(` $cqUnset_${cq.field}(k: any) { this.${cq.field}.$remove(k); }`);
2274
+ }
2275
+ }
2276
+ // Signal inputs with `{ transform }`: emit `$set_<prop>` that runs the transform before writing the input signal.
2277
+ for (const [field, fn] of inputTransforms) {
2278
+ const call = /^[A-Za-z_$][\w$.]*$/.test(fn.trim()) ? `${fn.trim()}(value)` : `(${fn})(value)`;
2279
+ methods.push(` $set_${field}(value: any) { this.${field}.$assign(${call}); }`);
2280
+ }
2281
+ // The component's source, with the template's methods added to its class and the event type imported.
2282
+ const end = cls.members.end;
2283
+ // ngOnChanges: the parent's bindings record each input they set (`$change`), and one check after them calls the hook
2284
+ // with what changed since it last ran, the first time before ngOnInit.
2285
+ const onChanges = cls.members.find((m) => ts.isMethodDeclaration(m) && m.name.getText() === 'ngOnChanges');
2286
+ if (onChanges) {
2287
+ if (onChanges.parameters.length > 1)
2288
+ throw new Error(`${path}: ngOnChanges takes one parameter`);
2289
+ methods.push(...changesMembers(onChanges.parameters.length > 0));
2290
+ }
2291
+ const cached = [...sites.values()].some((x) => x.cache);
2292
+ let imports = '';
2293
+ if (cached && !declares(sf, '$PurePipeCache'))
2294
+ imports += "import { PurePipeCache as $PurePipeCache } from '@angular#kit';\n";
2295
+ if (lets && !declares(sf, '$LetSlot'))
2296
+ imports += "import { LetSlot as $LetSlot } from '@angular#kit';\n";
2297
+ if (!declares(sf, '$EventData'))
2298
+ imports += "import { type EventData as $EventData } from '@nativescript/release';\n";
2299
+ if (usesElementRef && !declares(sf, '$ElementRef'))
2300
+ imports += `import { ElementRef as $ElementRef } from '@angular/core';\n`;
2301
+ if (usesUnset && !declares(sf, '$unsetValue'))
2302
+ imports += `import { unsetValue as $unsetValue } from '@nativescript/core';\n`;
2303
+ if (hasProviders && !declares(sf, 'NodeInjector'))
2304
+ imports += `import { NodeInjector } from '@angular#kit';\n`;
2305
+ if (hdNeedsInput && !importsAs(sf, 'input', '@angular/core'))
2306
+ imports += `import { input } from '@angular/core';\n`;
2307
+ if (hdNeedsOutput && !importsAs(sf, 'output', '@angular/core'))
2308
+ imports += `import { output } from '@angular/core';\n`;
2309
+ if (onChanges) {
2310
+ if (!declares(sf, '$SimpleChange'))
2311
+ imports += `import { SimpleChange as $SimpleChange } from '@angular/core';\n`;
2312
+ if (!importsAs(sf, 'signal', '@angular/core')) {
2313
+ if (declares(sf, 'signal'))
2314
+ throw new Error(`${path}: ngOnChanges needs Angular's signal, which this file's own "signal" hides`);
2315
+ imports += `import { signal } from '@angular/core';\n`;
2316
+ }
2317
+ }
2318
+ if ((queries.some((q) => q.many && !q.signal) || contentQueries.some((q) => q.many && !q.signal)) && !declares(sf, '$QueryList')) {
2319
+ usesRuntime = true;
2320
+ const from = options.runtimeModule ?? RUNTIME;
2321
+ imports += `import { QueryList as $QueryList } from '${isAbsolute(from) ? relativeSpecifier(dirname(path), from) : from}';\n`;
2322
+ }
2323
+ for (const [from, names] of imported) {
2324
+ const needed = [...names].filter(([, a]) => !declares(sf, a));
2325
+ if (!needed.length)
2326
+ continue;
2327
+ const spec = isAbsolute(from) ? relativeSpecifier(dirname(path), from) : from;
2328
+ imports += `import { ${needed.map(([c, a]) => `${c} as ${a}`).join(', ')} } from '${spec}';\n`;
2329
+ }
2330
+ if (usesTemplateRef && !declares(sf, '$TemplateRef'))
2331
+ imports += `import { TemplateRef as $TemplateRef } from '@angular/core';\n`;
2332
+ if ((routed || usesInject) && !importsAs(sf, 'inject', '@angular/core')) {
2333
+ if (declares(sf, 'inject'))
2334
+ throw new Error(`${path}: ${routed ? 'nsRouterLink' : 'a pipe constructor'} needs Angular's inject, which this file's own "inject" hides`);
2335
+ imports += `import { inject } from '@angular/core';\n`;
2336
+ }
2337
+ if (routed) {
2338
+ if (!declares(sf, '$ActivatedRoute'))
2339
+ imports += `import { ActivatedRoute as $ActivatedRoute } from '@angular/router';\n`;
2340
+ if (!declares(sf, '$RouterExtensions'))
2341
+ imports += `import { RouterExtensions as $RouterExtensions } from '@nativescript/angular';\n`;
2342
+ methods.push(' readonly $router = inject($RouterExtensions);', ' readonly $route = inject($ActivatedRoute);');
2343
+ }
2344
+ const importLineCount = imports ? imports.split('\n').length - 1 : 0;
2345
+ prependedLines += importLineCount;
2346
+ const head = imports + text.slice(0, end) + '\n';
2347
+ const source = head + methods.join('\n') + '\n' + text.slice(end);
2348
+ // Each template method's lines in the virtual file, at its binding's line in the template it was written in.
2349
+ const inlineAt = templateUrl ? 0 : written.indexOf(template);
2350
+ const templateFile = templateUrl ? join(dirname(path), templateUrl) : path;
2351
+ const firstLine = inlineAt > 0 ? written.slice(0, inlineAt).split('\n').length - 1 : 0;
2352
+ const lines = [];
2353
+ let line = head.split('\n').length - 1;
2354
+ methods.forEach((m, k) => {
2355
+ const span = m.split('\n').length;
2356
+ const at = located.get(k);
2357
+ if (at !== undefined && inlineAt >= 0)
2358
+ for (let j = 0; j < span; j++)
2359
+ lines.push([line + j, firstLine + at + 1]);
2360
+ line += span;
2361
+ });
2362
+ const { styles, scope: styleScope } = angularStyles(path, prop);
2363
+ const scoped = styleScope ? core.scopeTemplate(tree, styleScope.content).map((n) => (n.kind === 'element' ? { ...n, attrs: [...n.attrs, { name: styleScope.host, value: '' }] } : n)) : tree;
2364
+ const allSetters = new Set([...(classic?.setters ?? []), ...inputTransforms.keys(), ...inheritedSetters]);
2365
+ const component = {
2366
+ name: cls.name.text,
2367
+ file: path.replace(/\.ts$/, '.release.ts'),
2368
+ source,
2369
+ ...(usesRuntime ? { usesRuntime } : {}),
2370
+ props,
2371
+ optional,
2372
+ outputs,
2373
+ ...(Object.keys(hdOutputFields).length ? { outputFields: hdOutputFields } : {}),
2374
+ template: scoped,
2375
+ ...(dynamicTemplates.size ? { templates: [...dynamicTemplates.values()] } : {}),
2376
+ selector,
2377
+ styles,
2378
+ ...(slotNames.size ? { slots: [...slotNames] } : {}),
2379
+ ...(init ? { init: 'ngOnInit' } : {}),
2380
+ ...(init && lateInit ? { lateInit } : {}),
2381
+ ...(hook('ngDoCheck') ? { doCheck: 'ngDoCheck' } : {}),
2382
+ ...(hook('ngAfterContentInit') ? { afterContentInit: 'ngAfterContentInit' } : {}),
2383
+ ...(hook('ngAfterContentChecked') ? { afterContentChecked: 'ngAfterContentChecked' } : {}),
2384
+ ...(hook('ngAfterViewInit') ? { afterViewInit: 'ngAfterViewInit' } : {}),
2385
+ ...(hook('ngAfterViewChecked') ? { afterViewChecked: 'ngAfterViewChecked' } : {}),
2386
+ ...(hook('ngOnDestroy') ? { destroy: 'ngOnDestroy' } : {}),
2387
+ ...(onChanges ? { changes: true } : {}),
2388
+ ...(onPush ? { onPush } : {}),
2389
+ ...(classic?.host ? { host: '$host' } : {}),
2390
+ ...(hasProviders ? { injector: '$injector' } : {}),
2391
+ ...(allSetters.size ? { setters: [...allSetters] } : {}),
2392
+ ...(Object.keys(inputAliases).length ? { propAliases: inputAliases } : {}),
2393
+ ...(lines.length ? { templateLines: { file: templateFile, lines } } : {}),
2394
+ };
2395
+ return { component, nextText: source, prependedLines };
2396
+ }
2397
+ /**
2398
+ * The component's `styles`, `styleUrl` and `styleUrls`, as NativeScript Angular adds them: Sass compiled by the app's own
2399
+ * `sass`, and, unless `encapsulation: ViewEncapsulation.None`, each selector limited to the component's elements
2400
+ * (`_ngcontent-<id>`, which its renderer sets on each element the component creates) and `:host` to `_nghost-<id>`. The
2401
+ * compiled component has no host view of its own: its top-level elements carry the host attribute.
2402
+ */
2403
+ function angularStyles(path, prop) {
2404
+ const texts = [];
2405
+ const literal = (e) => (ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e) ? e.text : null);
2406
+ const inline = prop('styles');
2407
+ for (const e of inline ? (ts.isArrayLiteralExpression(inline) ? [...inline.elements] : [inline]) : []) {
2408
+ const css = literal(e);
2409
+ if (css === null)
2410
+ throw new Error(`${path}: styles must be string literals in a compiled release`);
2411
+ texts.push({ css, lang: 'css', from: path });
2412
+ }
2413
+ const urls = [prop('styleUrl'), ...(() => { const u = prop('styleUrls'); return u && ts.isArrayLiteralExpression(u) ? [...u.elements] : []; })()].filter((e) => !!e);
2414
+ for (const e of urls) {
2415
+ const url = literal(e);
2416
+ if (url === null)
2417
+ throw new Error(`${path}: styleUrl must be a string literal in a compiled release`);
2418
+ const file = join(dirname(path), url);
2419
+ if (!existsSync(file))
2420
+ throw new Error(`${path}: styleUrl ${url} not found`);
2421
+ texts.push({ css: readFileSync(file, 'utf8'), lang: extname(file).slice(1), from: file });
2422
+ }
2423
+ if (!texts.length)
2424
+ return { styles: [], scope: null };
2425
+ const none = prop('encapsulation')?.getText() === 'ViewEncapsulation.None';
2426
+ const id = `c${createHash('sha256').update(path).digest('hex').slice(0, 8)}`;
2427
+ const styles = texts.map((t, k) => {
2428
+ let css = t.css;
2429
+ if (t.lang === 'scss' || t.lang === 'sass')
2430
+ css = createRequire(path)('sass').compileString(css, { loadPaths: [dirname(t.from)], syntax: t.lang === 'sass' ? 'indented' : 'scss' }).css;
2431
+ else if (t.lang !== 'css')
2432
+ throw new Error(`${t.from}: ${t.lang} stylesheets are not supported in a compiled release yet`);
2433
+ return { file: `${path}.style${k}.css`, css: none ? css : ng.encapsulateStyle(css, id) };
2434
+ });
2435
+ return { styles, scope: none ? null : { content: `_ngcontent-${id}`, host: `_nghost-${id}` } };
2436
+ }
2437
+ /** Every `BindingPipe` in an expression, those inside another pipe's arguments too. */
2438
+ /** Whether the nodes read `name` in an embedded view or a listener (the template's code outside the view's own update). */
2439
+ function readAway(name, nodes) {
2440
+ let depth = 0;
2441
+ let found = false;
2442
+ const away = (f) => {
2443
+ depth++;
2444
+ try {
2445
+ f();
2446
+ }
2447
+ finally {
2448
+ depth--;
2449
+ }
2450
+ };
2451
+ class Reads extends ng.CombinedRecursiveAstVisitor {
2452
+ visitPropertyRead(ast, context) {
2453
+ if (depth && ast.name === name && ast.receiver instanceof ng.ImplicitReceiver && !(ast.receiver instanceof ng.ThisReceiver))
2454
+ found = true;
2455
+ return super.visitPropertyRead(ast, context);
2456
+ }
2457
+ visitBoundEvent(e) { away(() => super.visitBoundEvent(e)); }
2458
+ visitTemplate(t) { away(() => super.visitTemplate(t)); }
2459
+ visitIfBlockBranch(b) {
2460
+ if (b.expression)
2461
+ this.visit(b.expression);
2462
+ away(() => this.visitAllTemplateNodes(b.children));
2463
+ }
2464
+ visitForLoopBlock(b) {
2465
+ this.visit(b.expression);
2466
+ away(() => this.visitAllTemplateNodes(b.children));
2467
+ if (b.empty)
2468
+ this.visitForLoopBlockEmpty(b.empty);
2469
+ }
2470
+ visitForLoopBlockEmpty(b) { away(() => this.visitAllTemplateNodes(b.children)); }
2471
+ visitSwitchBlockCaseGroup(g) {
2472
+ this.visitAllTemplateNodes(g.cases);
2473
+ away(() => this.visitAllTemplateNodes(g.children));
2474
+ }
2475
+ run(nodes) { this.visitAllTemplateNodes(nodes); }
2476
+ }
2477
+ new Reads().run(nodes);
2478
+ return found;
2479
+ }
2480
+ function allPipes(node) {
2481
+ const found = [];
2482
+ const visit = (n) => {
2483
+ if (!(n instanceof ng.AST))
2484
+ return;
2485
+ if (n instanceof ng.BindingPipe)
2486
+ found.push(n);
2487
+ for (const v of Object.values(n))
2488
+ Array.isArray(v) ? v.forEach(visit) : visit(v);
2489
+ };
2490
+ visit(node);
2491
+ return found;
2492
+ }
2493
+ /** A module specifier for `file` (a .ts path) from a file in `dir`. */
2494
+ function relativeSpecifier(dir, file) {
2495
+ const r = relative(dir, file.replace(/\.tsx?$/, ''));
2496
+ return r.startsWith('.') ? r : './' + r;
2497
+ }
2498
+ /**
2499
+ * The `@Pipe` classes of the app's and its libraries' files, by the name templates use: whether each is pure (Angular's
2500
+ * default) and what making one takes.
2501
+ */
2502
+ export function angularPipes(files, read, modulesDir) {
2503
+ const out = new Map();
2504
+ const importedPkgs = new Set();
2505
+ for (const file of files) {
2506
+ const text = read(file);
2507
+ if (modulesDir) {
2508
+ for (const m of text.matchAll(/\bfrom\s*['"]((?:@[\w.-]+\/)?[\w.-]+(?:\/[\w.-]+)*)['"]/g)) {
2509
+ if (!m[1].startsWith('.') && !m[1].startsWith('@angular/'))
2510
+ importedPkgs.add(m[1]);
2511
+ }
2512
+ }
2513
+ if (!text.includes('@Pipe'))
2514
+ continue;
2515
+ const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
2516
+ for (const st of sf.statements) {
2517
+ if (!ts.isClassDeclaration(st) || !st.name)
2518
+ continue;
2519
+ const meta = decorator(st, 'Pipe')?.arguments[0];
2520
+ if (!meta || !ts.isObjectLiteralExpression(meta))
2521
+ continue;
2522
+ const get = (k) => meta.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === k)?.initializer;
2523
+ const name = get('name');
2524
+ if (!name || !ts.isStringLiteralLike(name))
2525
+ throw new Error(`${file}: @Pipe needs a string name in a release build`);
2526
+ if (!(ts.getModifiers(st) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword))
2527
+ throw new Error(`${file}: the pipe ${st.name.text} is not exported`);
2528
+ const pure = get('pure');
2529
+ const ctor = st.members.find(ts.isConstructorDeclaration);
2530
+ out.set(name.text, {
2531
+ className: st.name.text, file, pure: pure?.kind !== ts.SyntaxKind.FalseKeyword,
2532
+ ...(ctor?.parameters.length ? { create: true } : {}),
2533
+ ...(st.members.some((m) => ts.isMethodDeclaration(m) && m.name.getText() === 'ngOnDestroy') ? { destroy: true } : {}),
2534
+ });
2535
+ }
2536
+ }
2537
+ // Discover compiled Angular library pipes from `.d.ts` `ɵɵPipeDeclaration<ClassName, "pipeName", pure>`.
2538
+ if (modulesDir) {
2539
+ const walkDts = (dir, acc = []) => {
2540
+ if (!existsSync(dir) || !statSync(dir).isDirectory())
2541
+ return acc;
2542
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
2543
+ const p = join(dir, entry.name);
2544
+ if (entry.isDirectory() && entry.name !== 'node_modules')
2545
+ walkDts(p, acc);
2546
+ else if (entry.name.endsWith('.d.ts') && !entry.name.endsWith('.ngtypecheck.d.ts'))
2547
+ acc.push(p);
2548
+ }
2549
+ return acc;
2550
+ };
2551
+ for (const rawSpec of importedPkgs) {
2552
+ const spec = rawSpec.split('?', 1)[0];
2553
+ const pkgDir = join(modulesDir, spec);
2554
+ if (!existsSync(pkgDir) || !statSync(pkgDir).isDirectory())
2555
+ continue;
2556
+ for (const dts of walkDts(pkgDir)) {
2557
+ const dtsText = readFileSync(dts, 'utf8');
2558
+ if (!dtsText.includes('ɵɵPipeDeclaration'))
2559
+ continue;
2560
+ const sf = ts.createSourceFile(dts, dtsText, ts.ScriptTarget.Latest, true);
2561
+ const importSources = new Map();
2562
+ for (const s of sf.statements) {
2563
+ if (ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.importClause?.namedBindings && ts.isNamedImports(s.importClause.namedBindings)) {
2564
+ const from = s.moduleSpecifier.text.startsWith('.') ? spec : s.moduleSpecifier.text;
2565
+ for (const el of s.importClause.namedBindings.elements)
2566
+ importSources.set(el.name.text, from);
2567
+ }
2568
+ }
2569
+ for (const st of sf.statements) {
2570
+ if (!ts.isClassDeclaration(st) || !st.name)
2571
+ continue;
2572
+ const pipeProp = st.members.find((m) => ts.isPropertyDeclaration(m) && m.name.getText() === 'ɵpipe');
2573
+ const pipeMatch = pipeProp?.type && /ɵɵPipeDeclaration<\s*[^,]+,\s*["']([^"']+)["'](?:\s*,\s*(true|false))?/.exec(pipeProp.type.getText(sf));
2574
+ if (!pipeMatch || out.has(pipeMatch[1]))
2575
+ continue;
2576
+ const ctor = st.members.find(ts.isConstructorDeclaration);
2577
+ const deps = ctor?.parameters.map((p) => {
2578
+ const typeName = p.type && ts.isTypeReferenceNode(p.type) ? p.type.typeName.getText(sf) : '';
2579
+ return { name: typeName, from: importSources.get(typeName) ?? spec };
2580
+ }).filter((d) => !!d.name);
2581
+ out.set(pipeMatch[1], {
2582
+ className: st.name.text,
2583
+ file: spec,
2584
+ pure: pipeMatch[2] !== 'false',
2585
+ ...(deps?.length ? { deps } : {}),
2586
+ ...(st.members.some((m) => ts.isMethodDeclaration(m) && m.name.getText() === 'ngOnDestroy') ? { destroy: true } : {}),
2587
+ });
2588
+ }
2589
+ }
2590
+ }
2591
+ }
2592
+ return out;
2593
+ }
2594
+ /**
2595
+ * What ngOnChanges takes in a component or directive: the template records each input it sets (`$change`), and one
2596
+ * check after its inputs' calls `$flushChanges`, which calls the hook with what changed since it last ran.
2597
+ */
2598
+ const changesMembers = (hasParam) => [
2599
+ ' readonly $changed = signal(0);',
2600
+ ' readonly $changes = new Map<string, $SimpleChange>();',
2601
+ ' readonly $previous = new Map<string, any>();',
2602
+ ' $change(name: string, value: any): void { const first = !this.$previous.has(name); this.$changes.set(name, new $SimpleChange(first ? undefined : this.$previous.get(name), value, first)); this.$previous.set(name, value); this.$changed.update((n) => n + 1); }',
2603
+ hasParam
2604
+ ? ' $flushChanges(): void { if (!this.$changes.size) return; const changes = Object.fromEntries(this.$changes); this.$changes.clear(); this.ngOnChanges(changes); }'
2605
+ : ' $flushChanges(): void { if (!this.$changes.size) return; this.$changes.clear(); this.ngOnChanges(); }',
2606
+ ];
2607
+ /** The `@Directive` classes of the app's files. */
2608
+ export function angularDirectives(files, read) {
2609
+ const out = [];
2610
+ for (const file of files) {
2611
+ const text = read(file);
2612
+ if (!text.includes('@Directive'))
2613
+ continue;
2614
+ const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
2615
+ for (const st of sf.statements) {
2616
+ if (!ts.isClassDeclaration(st) || !st.name)
2617
+ continue;
2618
+ const call = decorator(st, 'Directive');
2619
+ const meta = call?.arguments[0];
2620
+ if (!call)
2621
+ continue;
2622
+ const where = `${file}: the directive ${st.name.text}`;
2623
+ if (meta && !ts.isObjectLiteralExpression(meta))
2624
+ throw new Error(`${where} needs a selector`);
2625
+ const get = (k) => (meta && ts.isObjectLiteralExpression(meta) ? meta.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === k)?.initializer : undefined);
2626
+ const selector = get('selector');
2627
+ if (selector && !ts.isStringLiteralLike(selector))
2628
+ throw new Error(`${where} needs a string selector in a release build`);
2629
+ if (!(ts.getModifiers(st) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword))
2630
+ throw new Error(`${where} is not exported`);
2631
+ const exportAsRaw = get('exportAs');
2632
+ const exportAs = exportAsRaw && ts.isStringLiteralLike(exportAsRaw) ? exportAsRaw.text.split(',').map((s) => s.trim()).filter(Boolean) : undefined;
2633
+ const typeParams = (st.typeParameters ?? []).filter((tp) => !tp.default).length;
2634
+ const d = { className: st.name.text, file, selector: selector && ts.isStringLiteralLike(selector) ? selector.text : '', inputs: new Map(), listeners: [], bindings: [], attributes: [], create: false, hooks: new Set(), structural: false, signals: new Set(), members: st.members.flatMap((m) => (m.name && ts.isIdentifier(m.name) ? [m.name.text] : [])), ...(exportAs?.length ? { exportAs } : {}), ...(typeParams ? { typeParams } : {}) };
2635
+ for (const p of meta && ts.isObjectLiteralExpression(meta) ? meta.properties : []) {
2636
+ const key = ts.isPropertyAssignment(p) ? p.name.getText() : p.getText();
2637
+ if (!['selector', 'inputs', 'host', 'standalone', 'jit', 'hostDirectives', 'providers', 'exportAs'].includes(key))
2638
+ throw new Error(`${where}: its ${key} ${PLURAL_FIELDS.has(key) ? 'are' : 'is'} not supported in a release build yet`);
2639
+ }
2640
+ const inputs = get('inputs');
2641
+ for (const e of inputs && ts.isArrayLiteralExpression(inputs) ? inputs.elements : []) {
2642
+ if (!ts.isStringLiteralLike(e))
2643
+ throw new Error(`${where}: inputs are names in a release build`);
2644
+ const [member, alias] = e.text.split(':').map((x) => x.trim());
2645
+ d.inputs.set(alias ?? member, member);
2646
+ }
2647
+ const host = get('host');
2648
+ for (const p of host && ts.isObjectLiteralExpression(host) ? host.properties : []) {
2649
+ if (!ts.isPropertyAssignment(p) || !ts.isStringLiteralLike(p.initializer))
2650
+ throw new Error(`${where}: host entries are strings in a release build`);
2651
+ const key = ts.isStringLiteralLike(p.name) ? p.name.text : p.name.getText();
2652
+ const value = p.initializer.text;
2653
+ if (/^\(.*\)$/.test(key))
2654
+ d.listeners.push({ event: key.slice(1, -1), code: value });
2655
+ else if (/^\[.*\]$/.test(key))
2656
+ d.bindings.push({ prop: key.slice(1, -1), code: value });
2657
+ else
2658
+ d.attributes.push({ name: key, value });
2659
+ }
2660
+ for (const m of st.members) {
2661
+ const name = m.name && (ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)) ? m.name.text : undefined;
2662
+ const made = ts.isPropertyDeclaration(m) && m.initializer && ts.isCallExpression(m.initializer) ? m.initializer.expression.getText() : '';
2663
+ if ((made === 'input' || made === 'input.required' || made === 'model' || made === 'model.required') && name) {
2664
+ const callExpr = m.initializer;
2665
+ const options = callExpr.arguments[made.endsWith('.required') ? 0 : 1];
2666
+ const bad = options && (!ts.isObjectLiteralExpression(options) ? options : options.properties.find((p) => !ts.isPropertyAssignment(p) || !['alias', 'debugName', 'transform'].includes(p.name.getText())));
2667
+ if (bad)
2668
+ throw new Error(`${where}: ${made}()'s ${ts.isObjectLiteralElementLike(bad) && bad.name ? bad.name.getText() : bad.getText()} (${name}) is not supported in a release build yet`);
2669
+ const optProp = (k) => (options && ts.isObjectLiteralExpression(options) ? options.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === k)?.initializer : undefined);
2670
+ const alias = optProp('alias');
2671
+ const pubName = alias && ts.isStringLiteralLike(alias) ? alias.text : name;
2672
+ d.inputs.set(pubName, name);
2673
+ d.signals.add(name);
2674
+ const transform = optProp('transform');
2675
+ if (transform)
2676
+ (d.transforms ??= new Map()).set(name, transform.getText(sf));
2677
+ if (made === 'model' || made === 'model.required')
2678
+ (d.outputs ??= new Map()).set(`${pubName}Change`, name);
2679
+ }
2680
+ else if (made === 'output' && name) {
2681
+ const callExpr = m.initializer;
2682
+ const options = callExpr.arguments[0];
2683
+ const alias = options && ts.isObjectLiteralExpression(options) ? options.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'alias')?.initializer : undefined;
2684
+ (d.outputs ??= new Map()).set(alias && ts.isStringLiteralLike(alias) ? alias.text : name, name);
2685
+ }
2686
+ else if (/^(viewChild|viewChildren|contentChild|contentChildren)(\.required)?$/.test(made) && name) {
2687
+ // Signal queries compile as signals on the directive class.
2688
+ }
2689
+ else if (/^(input|model|output|viewChild|viewChildren|contentChild|contentChildren)(\.required)?$/.test(made)) {
2690
+ throw new Error(`${where}: ${made}() (${name}) in a directive is not supported in a release build yet`);
2691
+ }
2692
+ if (ts.isMethodDeclaration(m) && name && /^ng(OnInit|OnChanges|AfterViewInit|OnDestroy|DoCheck|AfterContentInit|AfterContentChecked|AfterViewChecked)$/.test(name)) {
2693
+ d.hooks.add(name);
2694
+ }
2695
+ for (const dec of ts.canHaveDecorators(m) ? ts.getDecorators(m) ?? [] : []) {
2696
+ const e = dec.expression;
2697
+ const which = ts.isCallExpression(e) ? e.expression.getText() : e.getText();
2698
+ const arg = ts.isCallExpression(e) ? e.arguments[0] : undefined;
2699
+ if (!name)
2700
+ throw new Error(`${where}: a decorated member without a plain name`);
2701
+ if (which === 'Input') {
2702
+ const alias = arg && ts.isStringLiteralLike(arg) ? arg.text : arg && ts.isObjectLiteralExpression(arg) ? arg.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'alias')?.initializer?.text : undefined;
2703
+ d.inputs.set(alias ?? name, name);
2704
+ }
2705
+ else if (which === 'Output') {
2706
+ const alias = arg && ts.isStringLiteralLike(arg) ? arg.text : undefined;
2707
+ (d.outputs ??= new Map()).set(alias ?? name, name);
2708
+ }
2709
+ else if (which === 'HostListener') {
2710
+ if (!arg || !ts.isStringLiteralLike(arg) || !ts.isMethodDeclaration(m))
2711
+ throw new Error(`${where}: @HostListener takes an event name, on a method`);
2712
+ const given = ts.isCallExpression(e) ? e.arguments[1] : undefined;
2713
+ const args = given && ts.isArrayLiteralExpression(given) ? given.elements.map((x) => (ts.isStringLiteralLike(x) ? x.text : x.getText())) : [];
2714
+ if (arg.text.includes(':'))
2715
+ throw new Error(`${where}: @HostListener('${arg.text}'), a global target, is not supported in a release build yet`);
2716
+ d.listeners.push({ event: arg.text, code: `${name}(${args.join(', ')})` });
2717
+ }
2718
+ else if (which === 'HostBinding') {
2719
+ const prop = arg && ts.isStringLiteralLike(arg) ? arg.text : name;
2720
+ d.bindings.push({ prop, code: name });
2721
+ }
2722
+ else if (!['ContentChild', 'ContentChildren', 'ViewChild', 'ViewChildren'].includes(which)) {
2723
+ throw new Error(`${where}: @${which} is not supported in a release build yet`);
2724
+ }
2725
+ }
2726
+ }
2727
+ const plainBindings = [];
2728
+ for (const b of d.bindings) {
2729
+ if (b.prop.startsWith('attr.'))
2730
+ plainBindings.push({ prop: b.prop.slice(5), code: b.code });
2731
+ else if (b.prop.startsWith('style.'))
2732
+ (d.styleBindings ??= []).push({ prop: b.prop.slice(6), code: b.code });
2733
+ else if (b.prop.startsWith('class.'))
2734
+ (d.classBindings ??= []).push({ name: b.prop.slice(6), code: b.code });
2735
+ else
2736
+ plainBindings.push(b);
2737
+ }
2738
+ d.bindings = plainBindings;
2739
+ const ctor = st.members.find(ts.isConstructorDeclaration);
2740
+ d.create = !!ctor?.parameters.length;
2741
+ d.structural = /\bTemplateRef\b/.test(ctor?.getText() ?? '') || /inject\(\s*TemplateRef\b/.test(st.getText());
2742
+ out.push(d);
2743
+ }
2744
+ }
2745
+ return out;
2746
+ }
2747
+ /**
2748
+ * A file of `@Pipe` (and `@Directive`) classes as the release build compiles it: the class decorators, which only
2749
+ * Angular's compiler reads, left out, and a class whose constructor takes parameters given a `static $create()` that
2750
+ * injects them, as Angular's factory does (`@Inject(TOKEN)` the token, `@Optional()` optionally). Null when the file has
2751
+ * no such class.
2752
+ */
2753
+ export function declarableSource(path, text) {
2754
+ if (!/@(Pipe|Directive)\b/.test(text))
2755
+ return null;
2756
+ const sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true);
2757
+ const edits = [];
2758
+ let injects = false;
2759
+ let changes = false;
2760
+ for (const st of sf.statements) {
2761
+ if (!ts.isClassDeclaration(st) || !st.name)
2762
+ continue;
2763
+ const own = ts.getDecorators(st)?.find((d) => ts.isCallExpression(d.expression) && ['Pipe', 'Directive'].includes(d.expression.expression.getText()));
2764
+ if (!own)
2765
+ continue;
2766
+ edits.push({ start: own.getStart(), end: own.getEnd(), text: st.typeParameters?.length ? '/* @ng-declarable */' : '' });
2767
+ // A directive's member decorators (@Input, @HostListener, @HostBinding) are the template compiler's to read,
2768
+ // and a concrete directive's `protected` members must be accessible to host bindings/listeners generated in host components.
2769
+ const isAbstract = (ts.getModifiers(st) ?? []).some((m) => m.kind === ts.SyntaxKind.AbstractKeyword);
2770
+ for (const m of st.members) {
2771
+ for (const d of ts.canHaveDecorators(m) ? ts.getDecorators(m) ?? [] : [])
2772
+ edits.push({ start: d.getStart(), end: d.getEnd(), text: '' });
2773
+ if (!isAbstract) {
2774
+ for (const mod of ts.canHaveModifiers(m) ? ts.getModifiers(m) ?? [] : []) {
2775
+ if (mod.kind === ts.SyntaxKind.ProtectedKeyword)
2776
+ edits.push({ start: mod.getStart(), end: mod.getEnd(), text: 'public' });
2777
+ }
2778
+ }
2779
+ }
2780
+ const onChanges = st.members.find((m) => ts.isMethodDeclaration(m) && m.name.getText() === 'ngOnChanges');
2781
+ if (onChanges) {
2782
+ changes = true;
2783
+ edits.push({ start: st.members.end, end: st.members.end, text: '\n' + changesMembers(onChanges.parameters.length > 0).join('\n') + '\n' });
2784
+ }
2785
+ // Emit `$set_<prop>` helpers for directive signal inputs with `{ transform }`.
2786
+ for (const m of st.members) {
2787
+ if (!ts.isPropertyDeclaration(m) || !m.initializer || !ts.isCallExpression(m.initializer))
2788
+ continue;
2789
+ const made = m.initializer.expression.getText();
2790
+ if (made !== 'input' && made !== 'input.required')
2791
+ continue;
2792
+ const mName = m.name && (ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)) ? m.name.text : undefined;
2793
+ const opts = m.initializer.arguments[made === 'input.required' ? 0 : 1];
2794
+ const tr = opts && ts.isObjectLiteralExpression(opts) ? opts.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'transform')?.initializer : undefined;
2795
+ if (mName && tr) {
2796
+ const fn = tr.getText(sf).trim();
2797
+ const call = /^[A-Za-z_$][\w$.]*$/.test(fn) ? `${fn}(value)` : `(${fn})(value)`;
2798
+ edits.push({ start: st.members.end, end: st.members.end, text: `\n $set_${mName}(value: any): void { this.${mName}.$assign(${call}); }\n` });
2799
+ }
2800
+ }
2801
+ const ctor = st.members.find(ts.isConstructorDeclaration);
2802
+ if (!ctor?.parameters.length)
2803
+ continue;
2804
+ const given = ctor.parameters.map((p) => {
2805
+ const ref = p.type && ts.isTypeReferenceNode(p.type)
2806
+ ? p.type
2807
+ : p.type && ts.isUnionTypeNode(p.type)
2808
+ ? p.type.types.find(ts.isTypeReferenceNode)
2809
+ : undefined;
2810
+ let token = ref ? ref.typeName.getText() : undefined;
2811
+ let optional = !!(p.questionToken || p.initializer);
2812
+ let skipSelf = false;
2813
+ for (const d of ts.getDecorators(p) ?? []) {
2814
+ const e = d.expression;
2815
+ const which = ts.isCallExpression(e) ? e.expression.getText() : e.getText();
2816
+ if (which === 'Inject' && ts.isCallExpression(e) && e.arguments[0])
2817
+ token = e.arguments[0].getText();
2818
+ else if (which === 'Optional')
2819
+ optional = true;
2820
+ else if (which === 'SkipSelf')
2821
+ skipSelf = true;
2822
+ else if (!['Self', 'Host'].includes(which))
2823
+ throw new Error(`${path}: @${which} on ${st.name.text}'s constructor parameter ${p.name.getText()} is not supported in a release build yet`);
2824
+ edits.push({ start: d.getStart(), end: d.getEnd(), text: '' });
2825
+ }
2826
+ if (optional && skipSelf)
2827
+ return 'undefined as any';
2828
+ if (!token)
2829
+ throw new Error(`${path}: ${st.name.text}'s constructor parameter ${p.name.getText()} needs a class type or @Inject(token) in a release build`);
2830
+ injects = true;
2831
+ return `inject(${token}${optional ? ', { optional: true }' : ''})`;
2832
+ });
2833
+ const close = st.members.end;
2834
+ edits.push({ start: close, end: close, text: `\n static $create(): ${st.name.text} { return new ${st.name.text}(${given.join(', ')}); }\n` });
2835
+ }
2836
+ if (!edits.length)
2837
+ return null;
2838
+ let out = text;
2839
+ for (const e of edits.sort((a, b) => b.start - a.start))
2840
+ out = out.slice(0, e.start) + e.text + out.slice(e.end);
2841
+ if (changes) {
2842
+ if (!importsAs(sf, 'signal', '@angular/core') && declares(sf, 'signal'))
2843
+ throw new Error(`${path}: ngOnChanges needs Angular's signal, which this file's own "signal" hides`);
2844
+ out = `import { ${importsAs(sf, 'signal', '@angular/core') ? '' : 'signal, '}SimpleChange as $SimpleChange } from '@angular/core';\n` + out;
2845
+ }
2846
+ if (injects && !importsAs(sf, 'inject', '@angular/core')) {
2847
+ if (declares(sf, 'inject'))
2848
+ throw new Error(`${path}: a pipe's constructor is injected with Angular's inject, which this file's own "inject" hides`);
2849
+ out = `import { inject } from '@angular/core';\n` + out;
2850
+ }
2851
+ return out;
2852
+ }
2853
+ /**
2854
+ * A component written with decorators: `@Input() x: T` (or `= init`) is `input<T>()`, read as
2855
+ * `this.x()` and written, by the component itself, with `$assign`; `@Input() set x(v)` is a
2856
+ * `$set_x(v)` method, called as Angular calls the setter; `@Output() e = new EventEmitter<T>()` is
2857
+ * `output<T>()`; constructor parameter properties are `inject()`ed fields, set before the other
2858
+ * fields as TypeScript sets them. Null when the class has none of these.
2859
+ */
2860
+ function classicClass(path, text, cls) {
2861
+ const edits = [];
2862
+ const inputs = new Set();
2863
+ const setters = new Set();
2864
+ const aliases = new Map();
2865
+ const optional = new Set();
2866
+ const queries = [];
2867
+ const contentQueries = [];
2868
+ const used = new Set();
2869
+ const injected = [];
2870
+ let ctor;
2871
+ const locals = [];
2872
+ let host = /\binject\(\s*ElementRef\s*\)/.test(cls.getText());
2873
+ const decoratorsOf = (m) => (ts.canHaveDecorators(m) ? ts.getDecorators(m) ?? [] : []).map((d) => d.expression);
2874
+ /** `@Input()`, `@Input('alias')`, `@Input({ alias, required })`: the name the parent binds and whether it must. */
2875
+ const inputOptions = (d, name) => {
2876
+ const a = d.arguments[0];
2877
+ if (!a)
2878
+ return { required: false };
2879
+ if (ts.isStringLiteralLike(a))
2880
+ return { alias: a.text, required: false };
2881
+ if (!ts.isObjectLiteralExpression(a) || d.arguments.length > 1)
2882
+ throw new Error(`${path}: @Input(${a.getText()}) ${name} is not supported in a release build yet`);
2883
+ const out = { required: false };
2884
+ for (const p of a.properties) {
2885
+ const key = p.name?.getText();
2886
+ const value = ts.isPropertyAssignment(p) ? p.initializer : undefined;
2887
+ if (key === 'alias' && value && ts.isStringLiteralLike(value))
2888
+ out.alias = value.text;
2889
+ else if (key === 'required' && value && (value.kind === ts.SyntaxKind.TrueKeyword || value.kind === ts.SyntaxKind.FalseKeyword))
2890
+ out.required = value.kind === ts.SyntaxKind.TrueKeyword;
2891
+ else
2892
+ throw new Error(`${path}: @Input's ${p.getText()} (${name}) is not supported in a release build yet`);
2893
+ }
2894
+ return out;
2895
+ };
2896
+ for (const m of cls.members) {
2897
+ const decorators = decoratorsOf(m);
2898
+ if (ts.isPropertyDeclaration(m) && decorators.length) {
2899
+ const name = m.name.getText();
2900
+ const d = decorators[0];
2901
+ const which = ts.isCallExpression(d) ? d.expression.getText() : d.getText();
2902
+ if (decorators.length > 1 || !ts.isCallExpression(d))
2903
+ throw new Error(`${path}: @${d.getText()} ${name} is not supported in a release build yet`);
2904
+ if (which === 'Input') {
2905
+ const { alias, required } = inputOptions(d, name);
2906
+ const type = m.type?.getText() ?? literalType(m.initializer);
2907
+ if (!type)
2908
+ throw new Error(`${path}: @Input() ${name} needs a type`);
2909
+ // An input the parent leaves out keeps its initializer, or is undefined, as Angular leaves the field; one declared
2910
+ // definitely assigned (`x!: T`) or `required` is one the parent gives.
2911
+ const given = required || !!m.exclamationToken;
2912
+ const init = m.initializer ? `input<${type}>(${m.initializer.getText()})` : !given ? `input<${type} | undefined>(undefined)` : `input.required<${type}>()`;
2913
+ edits.push({ start: m.getStart(), end: m.getEnd(), text: `readonly ${name} = ${init};` });
2914
+ inputs.add(name);
2915
+ if (alias)
2916
+ aliases.set(name, alias);
2917
+ if (!given)
2918
+ optional.add(name);
2919
+ used.add('input');
2920
+ }
2921
+ else if (which === 'Output') {
2922
+ if (d.arguments.length)
2923
+ throw new Error(`${path}: @${d.getText()} ${name} is not supported in a release build yet`);
2924
+ const init = m.initializer;
2925
+ if (!init || !ts.isNewExpression(init) || init.expression.getText() !== 'EventEmitter')
2926
+ throw new Error(`${path}: @Output() ${name} needs = new EventEmitter<T>()`);
2927
+ edits.push({ start: m.getStart(), end: m.getEnd(), text: `readonly ${name} = output<${init.typeArguments?.[0]?.getText() ?? 'void'}>();` });
2928
+ used.add('output');
2929
+ }
2930
+ else if (which === 'ViewChild' || which === 'ViewChildren' || which === 'ContentChild' || which === 'ContentChildren') {
2931
+ const isContent = which === 'ContentChild' || which === 'ContentChildren';
2932
+ const [what, options] = d.arguments;
2933
+ const query = { field: name, read: null, static: false, many: which === 'ViewChildren' || which === 'ContentChildren', ...(isContent ? { descendants: which === 'ContentChild' } : {}) };
2934
+ if (what && ts.isStringLiteralLike(what)) {
2935
+ if (what.text.includes(','))
2936
+ throw new Error(`${path}: @${which}('${what.text}'), a query of several names, is not supported in a release build yet`);
2937
+ query.ref = what.text.trim();
2938
+ }
2939
+ else if (what && ts.isIdentifier(what))
2940
+ query.type = what.text;
2941
+ else
2942
+ throw new Error(`${path}: @${d.getText()} ${name} is not supported in a release build yet`);
2943
+ for (const p of options && ts.isObjectLiteralExpression(options) ? options.properties : []) {
2944
+ const key = p.name?.getText();
2945
+ const value = ts.isPropertyAssignment(p) ? p.initializer : undefined;
2946
+ if (key === 'static' && value)
2947
+ query.static = value.kind === ts.SyntaxKind.TrueKeyword;
2948
+ else if (key === 'descendants' && isContent && value)
2949
+ query.descendants = value.kind === ts.SyntaxKind.TrueKeyword;
2950
+ else if (key === 'read' && value && ts.isIdentifier(value))
2951
+ query.read = value.text;
2952
+ else
2953
+ throw new Error(`${path}: @${which}'s ${p.getText()} (${name}) is not supported in a release build yet`);
2954
+ }
2955
+ if (options && !ts.isObjectLiteralExpression(options))
2956
+ throw new Error(`${path}: @${d.getText()} ${name} is not supported in a release build yet`);
2957
+ if (query.read && /^(ViewContainerRef|ChangeDetectorRef|Injector)$/.test(query.read))
2958
+ throw new Error(`${path}: @${which}'s read: ${query.read} (${name}) is not supported in a release build yet`);
2959
+ (isContent ? contentQueries : queries).push(query);
2960
+ const decorator = ts.getDecorators(m)[0];
2961
+ if (query.many) {
2962
+ // A QueryList the template's matches are added to and removed from, in the order they render.
2963
+ edits.push({ start: m.getStart(), end: m.getEnd(), text: `readonly ${name} = new $QueryList();` });
2964
+ }
2965
+ else
2966
+ edits.push({ start: decorator.getStart(), end: decorator.getEnd(), text: '' });
2967
+ }
2968
+ else
2969
+ throw new Error(`${path}: @${which} is not supported in a release build yet`);
2970
+ continue;
2971
+ }
2972
+ if (ts.isAccessor(m) && decorators.length) {
2973
+ const name = m.name.getText();
2974
+ const d = decorators[0];
2975
+ if (decorators.length > 1 || !ts.isCallExpression(d) || d.expression.getText() !== 'Input')
2976
+ throw new Error(`${path}: @${d.getText()} on the accessor ${name} is not supported in a release build yet`);
2977
+ const { alias } = inputOptions(d, name);
2978
+ // The decorator may be on either accessor; the setter is what the parent's binding calls.
2979
+ const set = cls.members.find((x) => ts.isSetAccessorDeclaration(x) && x.name.getText() === name);
2980
+ if (!set)
2981
+ throw new Error(`${path}: @Input() on the getter ${name}, which has no setter`);
2982
+ const decorator = ts.getDecorators(m)[0];
2983
+ edits.push({ start: decorator.getStart(), end: decorator.getEnd(), text: '' });
2984
+ const head = set.getChildren().find((c) => c.kind === ts.SyntaxKind.SetKeyword);
2985
+ edits.push({ start: head.getStart(), end: set.name.getEnd(), text: `$set_${name}` });
2986
+ setters.add(name);
2987
+ if (alias)
2988
+ aliases.set(name, alias);
2989
+ optional.add(name);
2990
+ continue;
2991
+ }
2992
+ if (decorators.length)
2993
+ throw new Error(`${path}: @${decorators[0].getText()} is not supported in a release build yet`);
2994
+ if (ts.isPropertyDeclaration(m) && m.initializer && ts.isCallExpression(m.initializer)) {
2995
+ const callee = m.initializer.expression.getText();
2996
+ if (callee === 'viewChild' || callee === 'viewChild.required' || callee === 'viewChildren' || callee === 'contentChild' || callee === 'contentChild.required' || callee === 'contentChildren') {
2997
+ const isContent = callee.startsWith('content');
2998
+ const isMany = callee === 'viewChildren' || callee === 'contentChildren';
2999
+ const isRequired = callee.endsWith('.required');
3000
+ const name = m.name.getText();
3001
+ const [what, options] = m.initializer.arguments;
3002
+ const query = { field: name, read: null, static: false, many: isMany, signal: true, ...(isContent ? { descendants: !isMany } : {}) };
3003
+ if (what && ts.isStringLiteralLike(what)) {
3004
+ if (what.text.includes(','))
3005
+ throw new Error(`${path}: ${callee}('${what.text}'), a query of several names, is not supported in a release build yet`);
3006
+ query.ref = what.text.trim();
3007
+ }
3008
+ else if (what && ts.isIdentifier(what))
3009
+ query.type = what.text;
3010
+ else
3011
+ throw new Error(`${path}: ${callee}() (${name}) needs a ref name or class in a release build`);
3012
+ for (const p of options && ts.isObjectLiteralExpression(options) ? options.properties : []) {
3013
+ const key = p.name?.getText();
3014
+ const value = ts.isPropertyAssignment(p) ? p.initializer : undefined;
3015
+ if (key === 'read' && value && (ts.isIdentifier(value) || (ts.isExpressionWithTypeArguments(value) && ts.isIdentifier(value.expression)))) {
3016
+ query.read = ts.isIdentifier(value) ? value.text : value.expression.text;
3017
+ }
3018
+ else if (key === 'descendants' && isContent && value) {
3019
+ query.descendants = value.kind === ts.SyntaxKind.TrueKeyword;
3020
+ }
3021
+ else if (key === 'debugName')
3022
+ continue;
3023
+ else
3024
+ throw new Error(`${path}: ${callee}()'s ${p.getText()} (${name}) is not supported in a release build yet`);
3025
+ }
3026
+ if (options && !ts.isObjectLiteralExpression(options))
3027
+ throw new Error(`${path}: ${callee}() (${name}) options are read as an object literal in a release build`);
3028
+ if (query.read && /^(ViewContainerRef|ChangeDetectorRef|Injector)$/.test(query.read))
3029
+ throw new Error(`${path}: ${callee}()'s read: ${query.read} (${name}) is not supported in a release build yet`);
3030
+ const typeArg = m.initializer.typeArguments?.[0]?.getText() ?? (query.read === 'ElementRef' ? 'ElementRef' : query.type ?? 'any');
3031
+ query.typeArg = typeArg;
3032
+ (isContent ? contentQueries : queries).push(query);
3033
+ const sigInit = isMany
3034
+ ? `signal<${typeArg}[]>([])`
3035
+ : isRequired
3036
+ ? `signal<${typeArg}>(undefined as any)`
3037
+ : `signal<${typeArg} | undefined>(undefined)`;
3038
+ edits.push({ start: m.initializer.getStart(), end: m.initializer.getEnd(), text: sigInit });
3039
+ used.add('signal');
3040
+ continue;
3041
+ }
3042
+ }
3043
+ if (ts.isConstructorDeclaration(m)) {
3044
+ // A body without parameters is the translator's: it runs after the field initializers, as TypeScript runs it.
3045
+ if (!m.parameters.length)
3046
+ continue;
3047
+ for (const p of m.parameters) {
3048
+ const modifiers = (ts.getModifiers(p) ?? []).map((x) => x.getText());
3049
+ // Angular's factory injects each parameter: its class, or the token `@Inject` names, optionally with `@Optional()`.
3050
+ const ref = p.type && ts.isTypeReferenceNode(p.type)
3051
+ ? p.type
3052
+ : p.type && ts.isUnionTypeNode(p.type)
3053
+ ? p.type.types.find(ts.isTypeReferenceNode)
3054
+ : undefined;
3055
+ let token = ref ? ref.typeName.getText() : undefined;
3056
+ let optional = !!(p.questionToken || p.initializer);
3057
+ let skipSelf = false;
3058
+ for (const d of decoratorsOf(p)) {
3059
+ const which = ts.isCallExpression(d) ? d.expression.getText() : d.getText();
3060
+ if (which === 'Inject' && ts.isCallExpression(d) && d.arguments[0])
3061
+ token = d.arguments[0].getText();
3062
+ else if (which === 'Optional')
3063
+ optional = true;
3064
+ else if (which === 'SkipSelf')
3065
+ skipSelf = true;
3066
+ else if (!['Self', 'Host'].includes(which))
3067
+ throw new Error(`${path}: @${which} on the constructor parameter ${p.name.getText()} is not supported in a release build yet`);
3068
+ }
3069
+ if (!token && !(optional && skipSelf))
3070
+ throw new Error(`${path}: constructor parameter ${p.getText()} needs a class type or @Inject(token)`);
3071
+ // The component's own ElementRef is its host: the template's root view, set once it is made.
3072
+ if (token === 'ElementRef')
3073
+ host = true;
3074
+ const value = optional && skipSelf
3075
+ ? 'undefined as any'
3076
+ : token === 'ElementRef'
3077
+ ? 'this.$host'
3078
+ : (used.add('inject'), `inject(${token}${optional ? ', { optional: true }' : ''})`);
3079
+ const typed = p.type ? `: ${p.type.getText()}` : '';
3080
+ // A parameter property is a field; a plain parameter is a local of the constructor's body.
3081
+ if (modifiers.length) {
3082
+ injected.push(` ${modifiers.join(' ')} ${p.name.getText()}${typed} = ${value};\n`);
3083
+ // The constructor's body may still name the parameter, which is now the field.
3084
+ if (m.body && new RegExp(`(?<![.\\w$])${p.name.getText()}\\b`).test(m.body.getText()))
3085
+ locals.push(`const ${p.name.getText()} = this.${p.name.getText()};`);
3086
+ }
3087
+ else
3088
+ locals.push(`const ${p.name.getText()}${typed} = ${value};`);
3089
+ }
3090
+ ctor = m;
3091
+ }
3092
+ }
3093
+ if (!edits.length && !ctor && !host)
3094
+ return null;
3095
+ if (host) {
3096
+ injected.unshift(` readonly $host = new ElementRef(undefined);\n`);
3097
+ used.add('ElementRef');
3098
+ for (const m of cls.members) {
3099
+ const visit = (n) => {
3100
+ if (ts.isCallExpression(n) && n.expression.getText() === 'inject' && n.arguments.length === 1 && n.arguments[0].getText() === 'ElementRef')
3101
+ edits.push({ start: n.getStart(), end: n.getEnd(), text: 'this.$host' });
3102
+ else
3103
+ ts.forEachChild(n, visit);
3104
+ };
3105
+ if (m !== ctor)
3106
+ visit(m);
3107
+ }
3108
+ }
3109
+ if (injected.length)
3110
+ edits.push({ start: cls.members[0].getFullStart(), end: cls.members[0].getFullStart(), text: '\n' + injected.join('') });
3111
+ // `this.input` reads the input's signal and writes it with `$assign`; `this.setter = v` calls the setter's method.
3112
+ const isInput = (n) => ts.isPropertyAccessExpression(n) && n.expression.kind === ts.SyntaxKind.ThisKeyword && (inputs.has(n.name.text) || setters.has(n.name.text));
3113
+ /** The text of `n` with the reads and writes inside it rewritten. */
3114
+ const rewritten = (n) => {
3115
+ const inner = [];
3116
+ collect(n, inner);
3117
+ let t = text.slice(n.getStart(), n.getEnd());
3118
+ for (const e of inner.sort((a, b) => b.start - a.start))
3119
+ t = t.slice(0, e.start - n.getStart()) + e.text + t.slice(e.end - n.getStart());
3120
+ return t;
3121
+ };
3122
+ const collect = (n, into) => {
3123
+ const write = (target, value, at) => {
3124
+ const name = target.name.text;
3125
+ into.push({ start: at.getStart(), end: at.getEnd(), text: setters.has(name) ? `this.$set_${name}(${value})` : `this.${name}.$assign(${value})` });
3126
+ };
3127
+ if (ts.isBinaryExpression(n) && isInput(n.left) && n.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && n.operatorToken.kind <= ts.SyntaxKind.LastAssignment) {
3128
+ const op = n.operatorToken.getText().slice(0, -1);
3129
+ if (op && setters.has(n.left.name.text))
3130
+ throw new Error(`${path}: ${n.getText()} on the input setter ${n.left.name.text} is not supported in a release build yet`);
3131
+ write(n.left, op ? `this.${n.left.name.text}() ${op} (${rewritten(n.right)})` : rewritten(n.right), n);
3132
+ return;
3133
+ }
3134
+ if ((ts.isPrefixUnaryExpression(n) || ts.isPostfixUnaryExpression(n)) && isInput(n.operand) && (n.operator === ts.SyntaxKind.PlusPlusToken || n.operator === ts.SyntaxKind.MinusMinusToken)) {
3135
+ if (setters.has(n.operand.name.text) || !ts.isExpressionStatement(n.parent))
3136
+ throw new Error(`${path}: ${n.getText()} on an input is not supported in a release build yet`);
3137
+ write(n.operand, `this.${n.operand.name.text}() ${n.operator === ts.SyntaxKind.PlusPlusToken ? '+' : '-'} 1`, n);
3138
+ return;
3139
+ }
3140
+ if (isInput(n) && inputs.has(n.name.text)) {
3141
+ into.push({ start: n.getEnd(), end: n.getEnd(), text: '()' });
3142
+ return;
3143
+ }
3144
+ ts.forEachChild(n, (c) => collect(c, into));
3145
+ };
3146
+ for (const m of cls.members)
3147
+ if (m !== ctor && !(ts.isPropertyDeclaration(m) && inputs.has(m.name.getText())))
3148
+ collect(m, edits);
3149
+ if (ctor)
3150
+ edits.push({ start: ctor.getFullStart(), end: ctor.getEnd(), text: ctor.body?.statements.length ? `\n constructor() {${locals.length ? ' ' + locals.join(' ') : ''}${rewritten(ctor.body).slice(1)}` : locals.length ? `\n constructor() { ${locals.join(' ')} }` : '' });
3151
+ let out = text;
3152
+ for (const e of edits.sort((a, b) => b.start - a.start || b.end - a.end))
3153
+ out = out.slice(0, e.start) + e.text + out.slice(e.end);
3154
+ const imported = new Set(cls.getSourceFile().statements.flatMap((st) => ts.isImportDeclaration(st) && st.importClause?.namedBindings && ts.isNamedImports(st.importClause.namedBindings) ? st.importClause.namedBindings.elements.map((e) => e.name.text) : []));
3155
+ const missing = [...used].filter((u) => !imported.has(u));
3156
+ const prependedLines = missing.length ? 1 : 0;
3157
+ return { text: (missing.length ? `import { ${missing.join(', ')} } from '@angular/core';\n` : '') + out, prependedLines, inputs, setters, aliases, optional, queries, contentQueries, host };
3158
+ }
3159
+ function literalType(e) {
3160
+ if (!e)
3161
+ return undefined;
3162
+ if (ts.isNumericLiteral(e))
3163
+ return 'number';
3164
+ if (ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e))
3165
+ return 'string';
3166
+ if (e.kind === ts.SyntaxKind.TrueKeyword || e.kind === ts.SyntaxKind.FalseKeyword)
3167
+ return 'boolean';
3168
+ return undefined;
3169
+ }
3170
+ function literalKey(code, path) {
3171
+ const m = /^\s*(['"])(.*)\1\s*$/.exec(code);
3172
+ if (!m)
3173
+ throw new Error(`${path}: [nsTemplateKey]="${code}" needs a string literal in a release build`);
3174
+ return m[2];
3175
+ }
3176
+ /**
3177
+ * A file's `@Pipe` classes, and each `@NgModule` with the names its `declarations`, `imports` and `exports` list. A
3178
+ * library's directives are left out: its Angular wrappers are written against the view internals a compiled template
3179
+ * replaces.
3180
+ */
3181
+ export function declarablesIn(path, text, app = false) {
3182
+ const classes = [];
3183
+ const modules = new Map();
3184
+ const hasImportArrays = /export\s+const\s+\w+\s*=\s*\[/.test(text);
3185
+ if (!/@(Pipe|NgModule)\b/.test(text) && !hasImportArrays)
3186
+ return { classes, modules };
3187
+ const sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true);
3188
+ const unwrap = (e) => (ts.isAsExpression(e) || ts.isSatisfiesExpression(e) || ts.isParenthesizedExpression(e) ? unwrap(e.expression) : e);
3189
+ for (const st of sf.statements) {
3190
+ if (ts.isVariableStatement(st) && (ts.getModifiers(st) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) {
3191
+ for (const d of st.declarationList.declarations) {
3192
+ if (!ts.isIdentifier(d.name) || !d.initializer)
3193
+ continue;
3194
+ const arr = unwrap(d.initializer);
3195
+ if (!ts.isArrayLiteralExpression(arr) || !arr.elements.length)
3196
+ continue;
3197
+ const names = [];
3198
+ let ok = true;
3199
+ for (const el of arr.elements) {
3200
+ if (ts.isIdentifier(el))
3201
+ names.push(el.text);
3202
+ else if (ts.isSpreadElement(el) && ts.isIdentifier(el.expression))
3203
+ names.push(el.expression.text);
3204
+ else {
3205
+ ok = false;
3206
+ break;
3207
+ }
3208
+ }
3209
+ if (ok && names.length)
3210
+ modules.set(d.name.text, names);
3211
+ }
3212
+ continue;
3213
+ }
3214
+ if (!ts.isClassDeclaration(st) || !st.name)
3215
+ continue;
3216
+ if (decorator(st, 'Pipe'))
3217
+ classes.push(st.name.text);
3218
+ const meta = decorator(st, 'NgModule')?.arguments[0];
3219
+ if (meta && ts.isObjectLiteralExpression(meta)) {
3220
+ // Its `imports` and `providers` are walked where the module is imported (`ngModuleDef`); `bootstrap` is the entry's, the rest only steer Angular's compiler.
3221
+ for (const p of app ? meta.properties : []) {
3222
+ const key = ts.isPropertyAssignment(p) ? p.name.getText() : p.getText();
3223
+ if (!['declarations', 'imports', 'exports', 'providers', 'bootstrap', 'schemas', 'id', 'jit', 'entryComponents'].includes(key))
3224
+ throw new Error(`${path}: the NgModule ${st.name.text}'s ${key} ${PLURAL_FIELDS.has(key) ? 'are' : 'is'} not supported in a release build yet`);
3225
+ }
3226
+ modules.set(st.name.text, meta.properties.flatMap((p) => (ts.isPropertyAssignment(p) && ['declarations', 'imports', 'exports'].includes(p.name.getText()) && ts.isArrayLiteralExpression(p.initializer)
3227
+ ? p.initializer.elements.flatMap((e) => ts.isIdentifier(e) ? [e.text] : ts.isSpreadElement(e) && ts.isIdentifier(e.expression) ? [e.expression.text] : []) : [])));
3228
+ }
3229
+ }
3230
+ return { classes, modules };
3231
+ }
3232
+ /** A component class's members, and its inputs (by field, with the names its parent binds where they differ) and outputs. */
3233
+ function publicMembers(path, cls, classic) {
3234
+ const members = new Set();
3235
+ const props = [];
3236
+ const optional = [];
3237
+ const outputs = [];
3238
+ const inputAliases = {};
3239
+ const inputTransforms = new Map();
3240
+ for (const m of cls.members) {
3241
+ if (!m.name || !ts.isIdentifier(m.name))
3242
+ continue;
3243
+ members.add(m.name.text);
3244
+ if (ts.isPropertyDeclaration(m) && m.initializer && ts.isCallExpression(m.initializer)) {
3245
+ const callee = m.initializer.expression.getText();
3246
+ const optionsOf = (k, allowed) => {
3247
+ const o = m.initializer.arguments[k];
3248
+ if (!o)
3249
+ return undefined;
3250
+ const bad = !ts.isObjectLiteralExpression(o) ? o : o.properties.find((p) => !ts.isPropertyAssignment(p) || !allowed.includes(p.name.getText()));
3251
+ if (bad)
3252
+ throw new Error(`${path}: ${callee}()'s ${ts.isObjectLiteralElementLike(bad) && bad.name ? bad.name.getText() : bad.getText()} (${m.name.text}) is not supported in a release build yet`);
3253
+ return o;
3254
+ };
3255
+ if (callee === 'output')
3256
+ optionsOf(0, []);
3257
+ if (callee === 'input' || callee === 'input.required' || callee === 'model' || callee === 'model.required') {
3258
+ props.push(m.name.text);
3259
+ // `input(init, { alias, transform })`, `input.required({ alias, transform })`: the name the parent binds and optional transform.
3260
+ const isInput = callee === 'input' || callee === 'input.required';
3261
+ const options = optionsOf(callee === 'input' || callee === 'model' ? 1 : 0, isInput ? ['alias', 'debugName', 'transform'] : ['alias', 'debugName']);
3262
+ const alias = options && ts.isObjectLiteralExpression(options) ? options.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'alias')?.initializer : undefined;
3263
+ if (alias && ts.isStringLiteralLike(alias))
3264
+ inputAliases[m.name.text] = alias.text;
3265
+ const transform = isInput && options && ts.isObjectLiteralExpression(options) ? options.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'transform')?.initializer : undefined;
3266
+ if (transform)
3267
+ inputTransforms.set(m.name.text, transform.getText());
3268
+ }
3269
+ // An input with a default value (or `input<T>()` with implicit undefined) is one a parent may leave out.
3270
+ if (callee === 'input' || callee === 'model')
3271
+ optional.push(m.name.text);
3272
+ if (callee === 'output' || callee === 'model' || callee === 'model.required')
3273
+ outputs.push(m.name.text);
3274
+ }
3275
+ }
3276
+ for (const [field, alias] of classic?.aliases ?? [])
3277
+ inputAliases[field] = alias;
3278
+ for (const name of classic?.setters ?? []) {
3279
+ props.push(name);
3280
+ optional.push(name);
3281
+ }
3282
+ return { members, props, optional, outputs, inputAliases, inputTransforms };
3283
+ }
3284
+ /** Every attribute-selected component in `path` as an element hosting it sees it. */
3285
+ export function hostedComponents(path, text) {
3286
+ const out = [];
3287
+ for (const found of componentsOf(path, text)) {
3288
+ if (!found.selector || !ng.CssSelector.parse(found.selector).some((s) => s.attrs.length || s.classNames.length))
3289
+ continue;
3290
+ let sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
3291
+ const named = (f) => f.statements.find((s) => ts.isClassDeclaration(s) && s.name?.text === found.name);
3292
+ let cls = named(sf);
3293
+ const meta = decorator(cls, 'Component').arguments[0];
3294
+ const hostMeta = !!meta && ts.isObjectLiteralExpression(meta) && meta.properties.some((p) => p.name?.getText() === 'host');
3295
+ const hostDecorators = cls.members.some((m) => (ts.canHaveDecorators(m) ? ts.getDecorators(m) ?? [] : []).some((d) => /^(HostBinding|HostListener)\b/.test(d.expression.getText())));
3296
+ const classic = classicClass(path, text, cls);
3297
+ if (classic)
3298
+ cls = named((sf = ts.createSourceFile(path, classic.text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)));
3299
+ const api = publicMembers(path, cls, classic);
3300
+ const models = cls.members.filter((m) => ts.isPropertyDeclaration(m) && !!m.initializer && ts.isCallExpression(m.initializer) && /^model(\.required)?$/.test(m.initializer.expression.getText())).map((m) => m.name.getText());
3301
+ out.push({
3302
+ name: found.name,
3303
+ selector: found.selector,
3304
+ inputs: new Set(api.props.map((p) => api.inputAliases[p] ?? p)),
3305
+ outputs: new Set(api.outputs),
3306
+ models: new Set(models),
3307
+ readsHost: hostMeta || hostDecorators || !!classic?.host || /\binject\(\s*ElementRef\b/.test(cls.getText()),
3308
+ ...(found.slots?.length ? { slots: found.slots } : {}),
3309
+ });
3310
+ }
3311
+ return out;
3312
+ }
3313
+ /** A file's component as an element hosting it sees it, when its selector names attributes. */
3314
+ export function hostedComponent(path, text) {
3315
+ return hostedComponents(path, text)[0] ?? null;
3316
+ }
3317
+ /** The element names a component's selector matches (`resource, [talkResource]` is `<resource>`; its attribute is `hostedComponent`'s). */
3318
+ export function selectorElements(selector) {
3319
+ return ng.CssSelector.parse(selector).flatMap((s) => (s.element && s.element !== '*' && !s.attrs.length && !s.classNames.length && !s.notSelectors.length ? [s.element] : []));
3320
+ }
3321
+ /** Extracts `<ng-content>` slot names from a template string. */
3322
+ function templateSlots(path, template) {
3323
+ if (!template.includes('ng-content'))
3324
+ return [];
3325
+ const parsed = ng.parseTemplate(template, path + '.html', { preserveWhitespaces: false });
3326
+ const slots = new Set();
3327
+ const walk = (list) => {
3328
+ for (const n of list) {
3329
+ if (n instanceof ng.TmplAstContent)
3330
+ slots.add(!n.selector || n.selector === '*' ? 'default' : n.selector);
3331
+ if (n instanceof ng.TmplAstElement || n instanceof ng.TmplAstTemplate || n instanceof ng.TmplAstForLoopBlock)
3332
+ walk(n.children);
3333
+ if (n instanceof ng.TmplAstIfBlock)
3334
+ for (const b of n.branches)
3335
+ walk(b.children);
3336
+ if (n instanceof ng.TmplAstForLoopBlock && n.empty)
3337
+ walk(n.empty.children);
3338
+ if (n instanceof ng.TmplAstSwitchBlock)
3339
+ for (const g of n.groups)
3340
+ walk(g.children);
3341
+ }
3342
+ };
3343
+ walk(parsed.nodes);
3344
+ return [...slots];
3345
+ }
3346
+ /** Extracts declared content queries (`contentChild`, `contentChildren`, `@ContentChild`, `@ContentChildren`) on `cls`. */
3347
+ function classContentQueries(cls) {
3348
+ const out = [];
3349
+ for (const m of cls.members) {
3350
+ if (!ts.isPropertyDeclaration(m) || !m.name)
3351
+ continue;
3352
+ const field = m.name.getText();
3353
+ const decs = ts.canHaveDecorators(m) ? ts.getDecorators(m) ?? [] : [];
3354
+ for (const dec of decs) {
3355
+ if (!ts.isCallExpression(dec.expression))
3356
+ continue;
3357
+ const which = dec.expression.expression.getText();
3358
+ if (which !== 'ContentChild' && which !== 'ContentChildren')
3359
+ continue;
3360
+ const [what, opts] = dec.expression.arguments;
3361
+ const q = { field, read: null, static: false, many: which === 'ContentChildren', descendants: which === 'ContentChild' };
3362
+ if (what && ts.isStringLiteralLike(what))
3363
+ q.ref = what.text.trim();
3364
+ else if (what && ts.isIdentifier(what))
3365
+ q.type = what.text;
3366
+ else
3367
+ continue;
3368
+ for (const p of opts && ts.isObjectLiteralExpression(opts) ? opts.properties : []) {
3369
+ const key = p.name?.getText();
3370
+ const value = ts.isPropertyAssignment(p) ? p.initializer : undefined;
3371
+ if (key === 'descendants' && value)
3372
+ q.descendants = value.kind === ts.SyntaxKind.TrueKeyword;
3373
+ else if (key === 'read' && value && ts.isIdentifier(value))
3374
+ q.read = value.text;
3375
+ }
3376
+ out.push(q);
3377
+ }
3378
+ if (m.initializer && ts.isCallExpression(m.initializer)) {
3379
+ const callee = m.initializer.expression.getText();
3380
+ if (callee === 'contentChild' || callee === 'contentChild.required' || callee === 'contentChildren') {
3381
+ const [what, opts] = m.initializer.arguments;
3382
+ const isMany = callee === 'contentChildren';
3383
+ const q = { field, read: null, static: false, many: isMany, signal: true, descendants: !isMany };
3384
+ if (what && ts.isStringLiteralLike(what))
3385
+ q.ref = what.text.trim();
3386
+ else if (what && ts.isIdentifier(what))
3387
+ q.type = what.text;
3388
+ else
3389
+ continue;
3390
+ for (const p of opts && ts.isObjectLiteralExpression(opts) ? opts.properties : []) {
3391
+ const key = p.name?.getText();
3392
+ const value = ts.isPropertyAssignment(p) ? p.initializer : undefined;
3393
+ if (key === 'descendants' && value)
3394
+ q.descendants = value.kind === ts.SyntaxKind.TrueKeyword;
3395
+ else if (key === 'read' && value && (ts.isIdentifier(value) || (ts.isExpressionWithTypeArguments(value) && ts.isIdentifier(value.expression)))) {
3396
+ q.read = ts.isIdentifier(value) ? value.text : value.expression.text;
3397
+ }
3398
+ }
3399
+ out.push(q);
3400
+ }
3401
+ }
3402
+ }
3403
+ return out;
3404
+ }
3405
+ /** Every `@Component` class in `path`, with its selector, declared `<ng-content>` slots, and content queries. */
3406
+ export function componentsOf(path, text) {
3407
+ if (!text.includes('@Component'))
3408
+ return [];
3409
+ const sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
3410
+ const out = [];
3411
+ for (const st of sf.statements) {
3412
+ const meta = ts.isClassDeclaration(st) && st.name ? decorator(st, 'Component')?.arguments[0] : undefined;
3413
+ if (!meta || !ts.isClassDeclaration(st) || !st.name)
3414
+ continue;
3415
+ const get = (k) => (ts.isObjectLiteralExpression(meta) ? meta.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === k)?.initializer : undefined);
3416
+ const selector = get('selector');
3417
+ const inline = get('template');
3418
+ const templateUrl = get('templateUrl');
3419
+ const tpl = inline && ts.isStringLiteralLike(inline) ? inline.text : templateUrl && ts.isStringLiteralLike(templateUrl) && existsSync(join(dirname(path), templateUrl.text)) ? readFileSync(join(dirname(path), templateUrl.text), 'utf8') : '';
3420
+ const slots = templateSlots(path, tpl);
3421
+ const contentQueries = classContentQueries(st);
3422
+ out.push({
3423
+ name: st.name.text,
3424
+ selector: selector && ts.isStringLiteralLike(selector) ? selector.text : undefined,
3425
+ ...(slots.length ? { slots } : {}),
3426
+ ...(contentQueries.length ? { contentQueries } : {}),
3427
+ });
3428
+ }
3429
+ return out;
3430
+ }
3431
+ /** A file's first `@Component` class and the selector it declares. */
3432
+ export function componentOf(path, text) {
3433
+ return componentsOf(path, text)[0] ?? null;
3434
+ }
3435
+ /** @nativescript/angular's platform filters (`<android>`, `<ios>`, `<apple>`) and the platforms each renders its content on. */
3436
+ const PLATFORM_FILTERS = { android: ['android'], ios: ['ios'], apple: ['ios'] };
3437
+ /** Words a template's expression can name as a member that TypeScript reads as a keyword. */
3438
+ const KEYWORDS = new Set(['break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'enum', 'export', 'extends', 'finally', 'for', 'function', 'if', 'import', 'in', 'instanceof', 'new', 'return', 'super', 'switch', 'throw', 'try', 'var', 'void', 'while', 'with', 'yield', 'let', 'static', 'await']);
3439
+ /** NSRouterLink's inputs: on an element with `nsRouterLink` they are the directive's, not the view's. */
3440
+ const ROUTER_LINK_INPUTS = new Set(['nsRouterLink', 'relativeTo', 'clearHistory', 'pageTransition', 'pageTransitionDuration', 'queryParams', 'fragment', 'queryParamsHandling', 'state', 'info', 'preserveFragment', 'skipLocationChange', 'replaceUrl']);
3441
+ const ROUTER_LINK_SUPPORTED = new Set(['nsRouterLink', 'relativeTo', 'clearHistory', 'pageTransition', 'pageTransitionDuration']);
3442
+ /**
3443
+ * `@Component({ providers })`: the component's own injector, made by its first field and current until its constructor
3444
+ * returns, so that its fields and constructor inject from it as its view does.
3445
+ */
3446
+ function withInjector(path, text, cls, providers, viewProviders) {
3447
+ const hasExtends = !!cls.heritageClauses?.some((h) => h.token === ts.SyntaxKind.ExtendsKeyword);
3448
+ const lists = [
3449
+ ...(providers ? [{ expr: providers, field: 'providers' }] : []),
3450
+ ...(viewProviders ? [{ expr: viewProviders, field: 'viewProviders' }] : []),
3451
+ ];
3452
+ const items = [];
3453
+ for (const { expr: list, field } of lists) {
3454
+ if (!ts.isArrayLiteralExpression(list))
3455
+ throw new Error(`${path}: @Component's ${field} are read as an array literal in a release build`);
3456
+ for (const e of list.elements) {
3457
+ checkProvider(path, e, field);
3458
+ items.push(e.getText());
3459
+ }
3460
+ }
3461
+ const leave = 'this.$injector.provideSelf(this); this.$injector.leave();';
3462
+ const edits = [{ at: cls.members.pos, text: `\n readonly $injector = NodeInjector.enter([${items.join(', ')}]);` }];
3463
+ const ctor = cls.members.find((m) => ts.isConstructorDeclaration(m) && !!m.body);
3464
+ if (ctor?.body) {
3465
+ const returns = (n) => {
3466
+ if (ts.isFunctionLike(n) || ts.isClassLike(n))
3467
+ return;
3468
+ if (ts.isReturnStatement(n))
3469
+ edits.push({ at: n.getStart(), text: `{ ${leave} ` }, { at: n.getEnd(), text: ' }' });
3470
+ else
3471
+ ts.forEachChild(n, returns);
3472
+ };
3473
+ ctor.body.statements.forEach(returns);
3474
+ edits.push({ at: ctor.body.getEnd() - 1, text: `${leave} ` });
3475
+ }
3476
+ else
3477
+ edits.push({ at: cls.members.end, text: `\n constructor() { ${hasExtends ? 'super(); ' : ''}${leave} }\n` });
3478
+ let out = text;
3479
+ for (const e of edits.sort((a, b) => b.at - a.at))
3480
+ out = out.slice(0, e.at) + e.text + out.slice(e.at);
3481
+ return out;
3482
+ }
3483
+ /**
3484
+ * `@Self()`, `@SkipSelf()`, `@Host()` and their `inject()` options in a component with providers: which injector they
3485
+ * start or stop at is not modelled, so a component's own provider would answer where Angular asks its parent.
3486
+ */
3487
+ function refuseScopedInjection(path, cls) {
3488
+ const visit = (n) => {
3489
+ if (ts.isDecorator(n) && ts.isCallExpression(n.expression) && ['Self', 'SkipSelf', 'Host'].includes(n.expression.expression.getText())) {
3490
+ throw new Error(`${path}: @${n.expression.expression.getText()}() in a component with providers is not supported in a release build yet`);
3491
+ }
3492
+ if (ts.isCallExpression(n) && n.expression.getText() === 'inject' && n.arguments[1] && ts.isObjectLiteralExpression(n.arguments[1])) {
3493
+ const scoped = n.arguments[1].properties.find((p) => ['self', 'skipSelf', 'host'].includes(p.name?.getText() ?? ''));
3494
+ if (scoped)
3495
+ throw new Error(`${path}: inject()'s ${scoped.name.getText()} in a component with providers is not supported in a release build yet`);
3496
+ }
3497
+ ts.forEachChild(n, visit);
3498
+ };
3499
+ cls.members.forEach(visit);
3500
+ }
3501
+ /** A component provider the release build makes: a class, `{ provide, useClass | useValue | useFactory | useExisting }`, a provider helper call (`provideIcons(...)`), a spread, or a nested array. */
3502
+ function checkProvider(path, e, field = 'providers') {
3503
+ const what = `${path}: the provider ${e.getText().split('\n')[0]} in @Component's ${field}`;
3504
+ if (ts.isIdentifier(e) || ts.isPropertyAccessExpression(e) || ts.isCallExpression(e) || ts.isSpreadElement(e))
3505
+ return;
3506
+ if (ts.isArrayLiteralExpression(e)) {
3507
+ for (const inner of e.elements)
3508
+ checkProvider(path, inner, field);
3509
+ return;
3510
+ }
3511
+ if (!ts.isObjectLiteralExpression(e))
3512
+ throw new Error(`${what} is not supported in a release build yet`);
3513
+ const fields = new Map();
3514
+ for (const p of e.properties) {
3515
+ if (ts.isPropertyAssignment(p) && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)))
3516
+ fields.set(p.name.text, p.initializer);
3517
+ else if (ts.isShorthandPropertyAssignment(p))
3518
+ fields.set(p.name.text, p.name);
3519
+ else
3520
+ throw new Error(`${what} is read as \`{ provide: token, useClass: X }\` in a release build`);
3521
+ }
3522
+ for (const k of fields.keys())
3523
+ if (!['provide', 'useClass', 'useValue', 'useFactory', 'useExisting', 'deps', 'multi'].includes(k))
3524
+ throw new Error(`${what}: its ${k} is not supported in a release build yet`);
3525
+ const uses = ['useClass', 'useValue', 'useFactory', 'useExisting'].filter((k) => fields.has(k));
3526
+ if (!fields.has('provide') || uses.length !== 1)
3527
+ throw new Error(`${what} needs provide and one of useClass, useValue, useFactory or useExisting`);
3528
+ const deps = fields.get('deps');
3529
+ if (deps && (uses[0] !== 'useFactory' || !ts.isArrayLiteralExpression(deps) || deps.elements.some((d) => !ts.isIdentifier(d) && !ts.isPropertyAccessExpression(d)))) {
3530
+ throw new Error(`${what}: deps other than a list of tokens for useFactory are not supported in a release build yet`);
3531
+ }
3532
+ }
3533
+ /**
3534
+ * The `@Component` fields a release build reads, and those it may leave unread: `standalone`, `schemas`, `moduleId` and
3535
+ * `jit` only steer Angular's compiler, `exportAs` names the component a reference gets anyway, `animations` only
3536
+ * declares triggers (binding one is refused), and `preserveWhitespaces: false` is how templates are parsed.
3537
+ */
3538
+ const COMPONENT_META = new Set([
3539
+ 'selector', 'template', 'templateUrl', 'styles', 'styleUrl', 'styleUrls', 'imports', 'changeDetection', 'encapsulation',
3540
+ 'standalone', 'schemas', 'moduleId', 'jit', 'exportAs', 'animations', 'preserveWhitespaces', 'providers', 'viewProviders', 'host', 'hostDirectives',
3541
+ ]);
3542
+ /** Decorator fields named in the plural, for messages. */
3543
+ const PLURAL_FIELDS = new Set(['providers', 'viewProviders', 'inputs', 'outputs', 'queries', 'hostDirectives', 'animations', 'schemas']);
3544
+ /** The directives of @angular/forms an element can select, in the order Angular runs them on one, and their selectors. */
3545
+ const FORMS_SELECTORS = [
3546
+ ['RequiredValidator', ':not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]'],
3547
+ ['MinLengthValidator', '[minlength][formControlName],[minlength][formControl],[minlength][ngModel]'],
3548
+ ['MaxLengthValidator', '[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]'],
3549
+ ['PatternValidator', '[pattern][formControlName],[pattern][formControl],[pattern][ngModel]'],
3550
+ ['EmailValidator', '[email][formControlName],[email][formControl],[email][ngModel]'],
3551
+ ['NgModel', '[ngModel]:not([formControlName]):not([formControl])'],
3552
+ ['NgModelGroup', '[ngModelGroup]'],
3553
+ ['NgForm', 'form:not([ngNoForm]):not([formGroup]):not([formArray]),ng-form,[ngForm]'],
3554
+ ['FormControlDirective', '[formControl]'],
3555
+ ['FormGroupDirective', '[formGroup]'],
3556
+ ['FormArrayDirective', '[formArray]'],
3557
+ ['FormControlName', '[formControlName]'],
3558
+ ['FormGroupName', '[formGroupName]'],
3559
+ ['FormArrayName', '[formArrayName]'],
3560
+ ['DefaultValueAccessor', 'input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]'],
3561
+ ];
3562
+ const FORMS_VALIDATORS = { RequiredValidator: 'required', MinLengthValidator: 'minlength', MaxLengthValidator: 'maxlength', PatternValidator: 'pattern', EmailValidator: 'email' };
3563
+ const FORMS_CONTROLS = new Set(['NgModel', 'FormControlDirective', 'FormControlName']);
3564
+ const FORMS_CONTAINERS = new Set(['NgForm', 'FormGroupDirective', 'FormArrayDirective', 'FormGroupName', 'FormArrayName', 'NgModelGroup']);
3565
+ const FORMS_TEMPLATE_DRIVEN = new Set(['NgModel', 'NgForm', 'NgModelGroup']);
3566
+ const FORMS_REACTIVE_PARENTS = new Set(['FormGroupDirective', 'FormArrayDirective', 'FormGroupName', 'FormArrayName']);
3567
+ /** A directive's exportAs, the name a template reference (`#f="ngForm"`) takes it by. */
3568
+ const FORMS_EXPORT_AS = { NgModel: 'ngModel', NgForm: 'ngForm', NgModelGroup: 'ngModelGroup', FormGroupDirective: 'ngForm', FormArrayDirective: 'ngForm', FormControlDirective: 'ngForm' };
3569
+ /**
3570
+ * @nativescript/angular's value accessors (NativeScriptFormsModule), by the element they select: the view's property
3571
+ * they write (`text` and `selectedIndex` have their own rules) and the event that changes it.
3572
+ */
3573
+ const FORMS_ACCESSORS = {
3574
+ TextField: { kind: 'text', event: 'textChange', accessor: 'TextValueAccessor' },
3575
+ TextView: { kind: 'text', event: 'textChange', accessor: 'TextValueAccessor' },
3576
+ SearchBar: { kind: 'text', event: 'textChange', accessor: 'TextValueAccessor' },
3577
+ Switch: { kind: 'checked', event: 'checkedChange', accessor: 'CheckedValueAccessor' },
3578
+ DatePicker: { kind: 'date', event: 'dateChange', accessor: 'DateValueAccessor' },
3579
+ TimePicker: { kind: 'time', event: 'timeChange', accessor: 'TimeValueAccessor' },
3580
+ Slider: { kind: 'value', event: 'valueChange', accessor: 'NumberValueAccessor' },
3581
+ SegmentedBar: { kind: 'selectedIndex', event: 'selectedIndexChange', accessor: 'SelectedIndexValueAccessor' },
3582
+ ListPicker: { kind: 'selectedIndex', event: 'selectedIndexChange', accessor: 'SelectedIndexValueAccessor' },
3583
+ TabView: { kind: 'selectedIndex', event: 'selectedIndexChange', accessor: 'SelectedIndexValueAccessor' },
3584
+ };
3585
+ /** What selects a directive of @angular/forms (with @nativescript/angular's value accessors) on an element. */
3586
+ const FORMS_DIRECTIVES = new Set([
3587
+ 'ngModel', 'ngModelChange', 'ngModelOptions', 'ngModelGroup', 'ngForm', 'ngFormOptions', 'ngNoForm', 'ngSubmit',
3588
+ 'formGroup', 'formGroupName', 'formControl', 'formControlName', 'formArray', 'formArrayName',
3589
+ ]);
3590
+ /** Directives (and Angular's enter and leave animations) an element can select that the release build does not run, by the input or attribute that selects each. */
3591
+ const UNSUPPORTED_DIRECTIVES = {
3592
+ ngClass: "@angular/common's NgClass",
3593
+ ngStyle: "@angular/common's NgStyle",
3594
+ ngPlural: "@angular/common's NgPlural",
3595
+ ngPluralCase: "@angular/common's NgPluralCase",
3596
+ ngComponentOutlet: "@angular/common's NgComponentOutlet",
3597
+ ngTemplateOutlet: "@angular/common's NgTemplateOutlet, which a release build runs on <ng-container>",
3598
+ ngTemplateOutletContext: "@angular/common's NgTemplateOutlet, which a release build runs on <ng-container>",
3599
+ ngIf: '@angular/common\'s NgIf without its template (*ngIf)',
3600
+ ngIfElse: '@angular/common\'s NgIf without its template (*ngIf)',
3601
+ ngIfThen: '@angular/common\'s NgIf without its template (*ngIf)',
3602
+ ngForOf: '@angular/common\'s NgForOf without its template (*ngFor)',
3603
+ ngForTrackBy: '@angular/common\'s NgForOf without its template (*ngFor)',
3604
+ ngSwitchCase: '@angular/common\'s NgSwitchCase without its template (*ngSwitchCase)',
3605
+ ngSwitchDefault: '@angular/common\'s NgSwitchDefault without its template (*ngSwitchDefault)',
3606
+ routerLink: "@angular/router's RouterLink; nsRouterLink is supported",
3607
+ routerLinkActive: "@angular/router's RouterLinkActive",
3608
+ routerLinkActiveOptions: "@angular/router's RouterLinkActive",
3609
+ nsRouterLinkActiveOptions: "@nativescript/angular's NSRouterLinkActive",
3610
+ 'animate.enter': "Angular's enter animation",
3611
+ 'animate.leave': "Angular's leave animation",
3612
+ };
3613
+ /** Whether the file imports `name` from `module` under its own name. */
3614
+ function importsAs(sf, name, module) {
3615
+ return sf.statements.some((s) => ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.moduleSpecifier.text === module && !s.importClause?.isTypeOnly
3616
+ && !!s.importClause?.namedBindings && ts.isNamedImports(s.importClause.namedBindings)
3617
+ && s.importClause.namedBindings.elements.some((e) => e.name.text === name && (e.propertyName?.text ?? name) === name && !e.isTypeOnly));
3618
+ }
3619
+ /** Whether a top-level import or declaration of the file binds `name`. */
3620
+ function declares(sf, name) {
3621
+ return sf.statements.some((s) => {
3622
+ if (ts.isImportDeclaration(s)) {
3623
+ const c = s.importClause;
3624
+ return c?.name?.text === name || (!!c?.namedBindings && (ts.isNamespaceImport(c.namedBindings) ? c.namedBindings.name.text === name : c.namedBindings.elements.some((e) => e.name.text === name)));
3625
+ }
3626
+ if (ts.isVariableStatement(s))
3627
+ return s.declarationList.declarations.some((d) => ts.isIdentifier(d.name) && d.name.text === name);
3628
+ return (ts.isFunctionDeclaration(s) || ts.isClassDeclaration(s)) && s.name?.text === name;
3629
+ });
3630
+ }
3631
+ function sourceOf(ast) {
3632
+ const s = ast.source;
3633
+ if (s == null)
3634
+ throw new Error('an Angular expression without source text');
3635
+ return s;
3636
+ }
3637
+ /**
3638
+ * The route fields a release build reads, and those it may leave unread: `title` (a native screen has no window title
3639
+ * for it) and `runGuardsAndResolvers` (with no guards or resolvers, nothing it steers runs).
3640
+ */
3641
+ const ROUTE_FIELDS = new Set(['path', 'pathMatch', 'component', 'loadComponent', 'redirectTo', 'outlet', 'children', 'loadChildren', 'data', 'title', 'runGuardsAndResolvers']);
3642
+ const ROUTE_GUARDS = new Set(['canActivate', 'canActivateChild', 'canDeactivate', 'canMatch', 'canLoad']);
3643
+ /** The guards the release build's router runs, each with the arguments Angular calls it with. */
3644
+ const RUN_GUARDS = { canActivate: 2, canActivateChild: 2, canDeactivate: 4, canMatch: 2 };
3645
+ const lineOf = (n) => ts.getLineAndCharacterOfPosition(n.getSourceFile(), n.getStart()).line + 1;
3646
+ /** A literal's value, undefined for anything else. */
3647
+ function literalConstant(e) {
3648
+ return ts.isStringLiteralLike(e) ? e.text : undefined;
3649
+ }
3650
+ /**
3651
+ * An expression of a route file as the value it always has: literals, `const` names, enum members, templates and `+`
3652
+ * over them, followed through the file's imports. Undefined when it is not a compile-time constant.
3653
+ */
3654
+ function routeConstant(file, e, parse, fileOf, depth = 0) {
3655
+ if (depth > 20)
3656
+ return undefined;
3657
+ const of = (f, x) => routeConstant(f, x, parse, fileOf, depth + 1);
3658
+ while (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e) || ts.isNonNullExpression(e))
3659
+ e = e.expression;
3660
+ if (ts.isStringLiteralLike(e))
3661
+ return e.text;
3662
+ if (ts.isNumericLiteral(e))
3663
+ return Number(e.text);
3664
+ if (ts.isPrefixUnaryExpression(e) && e.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(e.operand))
3665
+ return -Number(e.operand.text);
3666
+ if (e.kind === ts.SyntaxKind.TrueKeyword)
3667
+ return true;
3668
+ if (e.kind === ts.SyntaxKind.FalseKeyword)
3669
+ return false;
3670
+ if (e.kind === ts.SyntaxKind.NullKeyword)
3671
+ return null;
3672
+ if (ts.isTemplateExpression(e)) {
3673
+ let text = e.head.text;
3674
+ for (const span of e.templateSpans) {
3675
+ const v = of(file, span.expression);
3676
+ if (v === undefined)
3677
+ return undefined;
3678
+ text += String(v) + span.literal.text;
3679
+ }
3680
+ return text;
3681
+ }
3682
+ if (ts.isBinaryExpression(e) && e.operatorToken.kind === ts.SyntaxKind.PlusToken) {
3683
+ const a = of(file, e.left), b = of(file, e.right);
3684
+ if (a === undefined || b === undefined)
3685
+ return undefined;
3686
+ return typeof a === 'string' || typeof b === 'string' ? String(a) + String(b) : typeof a === 'number' && typeof b === 'number' ? a + b : undefined;
3687
+ }
3688
+ if (ts.isIdentifier(e)) {
3689
+ const d = declarationOf(file, e.text, parse, fileOf);
3690
+ const list = d && ts.isVariableDeclaration(d) ? d.parent : undefined;
3691
+ return d && ts.isVariableDeclaration(d) && list && ts.isVariableDeclarationList(list) && list.flags & ts.NodeFlags.Const && d.initializer ? of(d.getSourceFile().fileName, d.initializer) : undefined;
3692
+ }
3693
+ if (ts.isPropertyAccessExpression(e) && ts.isIdentifier(e.expression)) {
3694
+ const d = declarationOf(file, e.expression.text, parse, fileOf);
3695
+ if (!d || !ts.isEnumDeclaration(d) || d.modifiers?.some((m) => m.kind === ts.SyntaxKind.DeclareKeyword))
3696
+ return undefined;
3697
+ let next = 0;
3698
+ for (const m of d.members) {
3699
+ const v = m.initializer ? of(d.getSourceFile().fileName, m.initializer) : next;
3700
+ if (m.name.getText() === e.name.text || (ts.isStringLiteral(m.name) && m.name.text === e.name.text))
3701
+ return v;
3702
+ next = typeof v === 'number' ? v + 1 : undefined;
3703
+ }
3704
+ }
3705
+ return undefined;
3706
+ }
3707
+ /** A route's `data` as its entries in order, each value a compile-time constant; undefined when it is anything else. */
3708
+ function routeData(e, constant) {
3709
+ while (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e))
3710
+ e = e.expression;
3711
+ if (!ts.isObjectLiteralExpression(e))
3712
+ return undefined;
3713
+ const entries = new Map();
3714
+ for (const p of e.properties) {
3715
+ if (!ts.isPropertyAssignment(p) || !(ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)))
3716
+ return undefined;
3717
+ const v = constant(p.initializer);
3718
+ if (v === undefined)
3719
+ return undefined;
3720
+ entries.set(p.name.text, v);
3721
+ }
3722
+ return [...entries];
3723
+ }
3724
+ /** A route's fields, each one the release build reads as Angular's router does, or may leave unread. */
3725
+ function routeFields(file, route, guards = false, constant = literalConstant) {
3726
+ const pathOf = route.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'path')?.initializer;
3727
+ const pathText = pathOf && constant(pathOf);
3728
+ const named = typeof pathText === 'string' ? ` on '${pathText}'` : '';
3729
+ for (const p of route.properties) {
3730
+ const at = `${file}:${lineOf(p)}`;
3731
+ if (!ts.isPropertyAssignment(p) || !(ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)))
3732
+ throw new Error(`${at}: a route's ${p.getText().split('\n')[0]} is read as \`name: value\` in a release build`);
3733
+ const key = p.name.text;
3734
+ const v = p.initializer;
3735
+ if (ROUTE_GUARDS.has(key) && !(guards && key in RUN_GUARDS))
3736
+ throw new Error(`${at}: route guards (${key}${named}) are not supported in a release build yet`);
3737
+ if (key in RUN_GUARDS && !ts.isArrayLiteralExpression(v))
3738
+ throw new Error(`${at}: a route's ${key} that is not an array (${v.getText().split('\n')[0]}) is not supported in a release build yet`);
3739
+ if (key === 'canMatch' && route.properties.some((q) => q.name?.getText() === 'redirectTo'))
3740
+ throw new Error(`${at}: canMatch on a redirect${named} is not supported in a release build yet`);
3741
+ if (key === 'resolve')
3742
+ throw new Error(`${at}: route resolvers (resolve${named}) are not supported in a release build yet`);
3743
+ if (!ROUTE_FIELDS.has(key) && !(key in RUN_GUARDS))
3744
+ throw new Error(`${at}: a route's ${key}${named} is not supported in a release build yet`);
3745
+ if (['path', 'pathMatch', 'redirectTo', 'outlet'].includes(key) && typeof constant(v) !== 'string')
3746
+ throw new Error(`${at}: a route's ${key} that is not a compile-time string (${v.getText().split('\n')[0]}) is not supported in a release build yet`);
3747
+ if (key === 'data' && !routeData(v, constant)) {
3748
+ const bad = ts.isObjectLiteralExpression(v) ? v.properties.find((q) => !ts.isPropertyAssignment(q) || !routeData(ts.factory.createObjectLiteralExpression([q]), constant)) : undefined;
3749
+ throw new Error(`${at}: a route's data that is not an object of compile-time constants (${(bad ?? v).getText().split('\n')[0]}) is not supported in a release build yet`);
3750
+ }
3751
+ if (key === 'component' && !ts.isIdentifier(v))
3752
+ throw new Error(`${at}: a route's component that is not a class name (${v.getText().split('\n')[0]}) is not supported in a release build yet`);
3753
+ }
3754
+ }
3755
+ /**
3756
+ * The router's options beside its routes: `withPreloading` (lazy routes are linked in) and `withDebugTracing` (only logs)
3757
+ * change nothing a release build does, and of forRoot's options `enableTracing`, `useHash`, `preloadingStrategy` and the
3758
+ * scrolling ones, which a native page has no use for.
3759
+ */
3760
+ function routerOptions(file, call) {
3761
+ const at = `${file}:${lineOf(call)}`;
3762
+ if (/(^|\.)forRoot$/.test(call.expression.getText())) {
3763
+ const options = call.arguments[1];
3764
+ if (!options)
3765
+ return;
3766
+ if (!ts.isObjectLiteralExpression(options))
3767
+ throw new Error(`${at}: the router's options (${options.getText()}) are not supported in a release build yet`);
3768
+ for (const p of options.properties) {
3769
+ const key = p.name?.getText() ?? p.getText();
3770
+ if (!['enableTracing', 'useHash', 'preloadingStrategy', 'scrollPositionRestoration', 'anchorScrolling', 'scrollOffset'].includes(key))
3771
+ throw new Error(`${at}: the router option ${key} is not supported in a release build yet`);
3772
+ }
3773
+ return;
3774
+ }
3775
+ for (const f of call.arguments.slice(1)) {
3776
+ const name = ts.isCallExpression(f) ? f.expression.getText() : f.getText();
3777
+ if (!['withPreloading', 'withDebugTracing'].includes(name))
3778
+ throw new Error(`${at}: the router feature ${name}() is not supported in a release build yet`);
3779
+ }
3780
+ }
3781
+ /** What a class or function name resolves to across the app's files: the declaration, else null (a package's, or not found). */
3782
+ function declarationOf(file, name, parse, fileOf, seen = new Set()) {
3783
+ if (seen.has(`${file}#${name}`))
3784
+ return null;
3785
+ seen.add(`${file}#${name}`);
3786
+ const sf = parse(file);
3787
+ for (const st of sf.statements) {
3788
+ if ((ts.isClassDeclaration(st) || ts.isFunctionDeclaration(st) || ts.isEnumDeclaration(st)) && st.name?.text === name)
3789
+ return st;
3790
+ if (ts.isVariableStatement(st)) {
3791
+ const d = st.declarationList.declarations.find((x) => ts.isIdentifier(x.name) && x.name.text === name);
3792
+ if (d)
3793
+ return d;
3794
+ }
3795
+ if ((ts.isImportDeclaration(st) || ts.isExportDeclaration(st)) && st.moduleSpecifier && ts.isStringLiteral(st.moduleSpecifier)) {
3796
+ const bindings = ts.isImportDeclaration(st) ? st.importClause?.namedBindings : st.exportClause;
3797
+ if (!bindings || ts.isNamespaceImport(bindings) || ts.isNamespaceExport(bindings))
3798
+ continue;
3799
+ const el = bindings.elements.find((e) => e.name.text === name);
3800
+ const target = el ? fileOf(file, st.moduleSpecifier.text) : undefined;
3801
+ if (el)
3802
+ return target ? declarationOf(target, (el.propertyName ?? el.name).text, parse, fileOf, seen) : null;
3803
+ }
3804
+ }
3805
+ return null;
3806
+ }
3807
+ /** The top-level names a node refers to, in value and type positions. */
3808
+ function namesIn(node, into = new Set()) {
3809
+ const visit = (n) => {
3810
+ if (ts.isIdentifier(n)) {
3811
+ const p = n.parent;
3812
+ const member = (ts.isPropertyAccessExpression(p) && p.name === n) || (ts.isQualifiedName(p) && p.right === n) || ((ts.isPropertyAssignment(p) || ts.isMethodDeclaration(p) || ts.isPropertyDeclaration(p) || ts.isPropertySignature(p) || ts.isMethodSignature(p) || ts.isGetAccessor(p) || ts.isSetAccessor(p)) && p.name === n);
3813
+ if (!member)
3814
+ into.add(n.text);
3815
+ }
3816
+ ts.forEachChild(n, visit);
3817
+ };
3818
+ visit(node);
3819
+ return into;
3820
+ }
3821
+ /** A specifier as written in `from`, for a module in `appDir`. */
3822
+ function respecify(from, spec, appDir) {
3823
+ if (!spec.startsWith('.'))
3824
+ return spec;
3825
+ const r = relative(appDir, join(dirname(from), spec)).split('\\').join('/');
3826
+ return r.startsWith('.') ? r : './' + r;
3827
+ }
3828
+ function guardModule(file, sf, guards) {
3829
+ // The route file's imports and declarations the guards need, followed through the declarations they need in turn.
3830
+ const needed = new Set();
3831
+ const pending = guards.map((g) => g.expr);
3832
+ const declared = new Map();
3833
+ for (const st of sf.statements) {
3834
+ const names = ts.isVariableStatement(st) ? st.declarationList.declarations.flatMap((d) => (ts.isIdentifier(d.name) ? [d.name.text] : []))
3835
+ : (ts.isFunctionDeclaration(st) || ts.isClassDeclaration(st) || ts.isInterfaceDeclaration(st) || ts.isTypeAliasDeclaration(st) || ts.isEnumDeclaration(st)) && st.name ? [st.name.text] : [];
3836
+ for (const n of names)
3837
+ declared.set(n, st);
3838
+ }
3839
+ const copied = new Set();
3840
+ // The translators name imported kit declarations by their own names, so no alias: a class guard's inject is the route
3841
+ // file's own import of it when it has one.
3842
+ if (guards.some((g) => g.inject))
3843
+ needed.add('inject');
3844
+ const importsInject = sf.statements.some((st) => ts.isImportDeclaration(st) && ts.isStringLiteral(st.moduleSpecifier) && st.moduleSpecifier.text === '@angular/core' && !!st.importClause?.namedBindings && ts.isNamedImports(st.importClause.namedBindings) && st.importClause.namedBindings.elements.some((e) => e.name.text === 'inject' && !e.propertyName));
3845
+ while (pending.length) {
3846
+ for (const n of namesIn(pending.pop())) {
3847
+ if (needed.has(n))
3848
+ continue;
3849
+ needed.add(n);
3850
+ const st = declared.get(n);
3851
+ if (st && !copied.has(st)) {
3852
+ copied.add(st);
3853
+ pending.push(st);
3854
+ }
3855
+ }
3856
+ }
3857
+ return {
3858
+ file,
3859
+ source(appDir, platform) {
3860
+ const lines = [];
3861
+ for (const st of sf.statements) {
3862
+ if (!ts.isImportDeclaration(st) || !ts.isStringLiteral(st.moduleSpecifier) || !st.importClause)
3863
+ continue;
3864
+ const c = st.importClause;
3865
+ const spec = JSON.stringify(respecify(file, st.moduleSpecifier.text, appDir));
3866
+ const type = c.isTypeOnly ? 'type ' : '';
3867
+ if (c.name && needed.has(c.name.text))
3868
+ lines.push(`import ${type}${c.name.text} from ${spec};`);
3869
+ if (c.namedBindings && ts.isNamespaceImport(c.namedBindings) && needed.has(c.namedBindings.name.text))
3870
+ lines.push(`import ${type}* as ${c.namedBindings.name.text} from ${spec};`);
3871
+ if (c.namedBindings && ts.isNamedImports(c.namedBindings)) {
3872
+ const els = c.namedBindings.elements.filter((e) => needed.has(e.name.text)).map((e) => e.getText());
3873
+ if (els.length)
3874
+ lines.push(`import ${type}{ ${els.join(', ')} } from ${spec};`);
3875
+ }
3876
+ }
3877
+ lines.push("import { KitRouter } from '@angular#kit';");
3878
+ if (guards.some((g) => g.inject) && !importsInject)
3879
+ lines.push("import { inject } from '@angular/core';");
3880
+ // A compiled rxjs Observable is the app's own class on iOS, which the kit can't read: firstValueFrom there.
3881
+ if (platform === 'ios')
3882
+ lines.push("import { ɵguardResult } from '@angular/router';");
3883
+ lines.push(...sf.statements.filter((st) => copied.has(st)).map((st) => st.getText()));
3884
+ const settle = (e) => (platform === 'ios' ? `ɵguardResult(${e})` : e);
3885
+ const params = ['a', 'b', 'c', 'd'];
3886
+ const all = params.map((p) => `${p}: any`).join(', ');
3887
+ guards.forEach((g, i) => {
3888
+ const arity = RUN_GUARDS[g.kind];
3889
+ if (g.inject) {
3890
+ lines.push(`KitRouter.shared.addGuard(${g.route}, '${g.kind}', (${all}): any => ${settle(`inject(${g.inject.name}).${g.kind}(${params.slice(0, Math.min(arity, g.inject.arity)).join(', ')})`)});`);
3891
+ }
3892
+ else {
3893
+ // Evaluated once, as Angular reads its route configuration once: a guard factory's call runs at startup.
3894
+ lines.push(`const ɵguard${i}: (${params.slice(0, arity).map((p) => `${p}: any`).join(', ')}) => any = ${g.expr.getText()};`);
3895
+ lines.push(`KitRouter.shared.addGuard(${g.route}, '${g.kind}', (${all}): any => ${settle(`ɵguard${i}(${params.slice(0, arity).join(', ')})`)});`);
3896
+ }
3897
+ });
3898
+ return lines.join('\n') + '\n';
3899
+ },
3900
+ };
3901
+ }
3902
+ /**
3903
+ * The router configuration the entry provides (`provideNativeScriptRouter(routes)`,
3904
+ * `NativeScriptRouterModule.forRoot(routes)`), followed through `loadChildren` and
3905
+ * `loadComponent` into the files they import. A route whose component is `NSEmptyOutletComponent` is marked
3906
+ * `emptyOutlet`: its children render in a frame of their own, on a page of the outlet the route names.
3907
+ */
3908
+ export function angularRouteTree(entry, read, aliased = () => undefined) {
3909
+ const files = new Set();
3910
+ const parsed = new Map();
3911
+ const parse = (f) => parsed.get(f) ?? parsed.set(f, ts.createSourceFile(f, read(f), ts.ScriptTarget.Latest, true)).get(f);
3912
+ const guards = new Map();
3913
+ let guardIds = 0;
3914
+ /** A relative specifier, or one of the app's path aliases (`~/app/x`), as the file it names. */
3915
+ const fileOf = (from, spec) => {
3916
+ const base = spec.startsWith('.') ? join(dirname(from), spec) : aliased(spec);
3917
+ return base === undefined ? undefined : [base + '.ts', join(base, 'index.ts')].find((p) => existsSync(p));
3918
+ };
3919
+ /** The array a name declares in a file, or imports into it. */
3920
+ const arrayNamed = (file, name) => {
3921
+ const sf = parse(file);
3922
+ for (const st of sf.statements) {
3923
+ if (ts.isVariableStatement(st)) {
3924
+ for (const d of st.declarationList.declarations) {
3925
+ if (ts.isIdentifier(d.name) && d.name.text === name && d.initializer && ts.isArrayLiteralExpression(d.initializer))
3926
+ return { file, array: d.initializer };
3927
+ }
3928
+ }
3929
+ if (ts.isImportDeclaration(st) && st.importClause?.namedBindings && ts.isNamedImports(st.importClause.namedBindings) && ts.isStringLiteral(st.moduleSpecifier)) {
3930
+ const el = st.importClause.namedBindings.elements.find((e) => e.name.text === name);
3931
+ const target = el ? fileOf(file, st.moduleSpecifier.text) : undefined;
3932
+ if (target)
3933
+ return arrayNamed(target, (el.propertyName ?? el.name).text);
3934
+ }
3935
+ }
3936
+ return null;
3937
+ };
3938
+ /** `() => import('./x').then((m) => m.Name)`: the file and the name. */
3939
+ const lazy = (file, e) => {
3940
+ const body = ts.isArrowFunction(e) && !ts.isBlock(e.body) ? e.body : undefined;
3941
+ const then = body && ts.isCallExpression(body) && ts.isPropertyAccessExpression(body.expression) && body.expression.name.text === 'then' ? body : undefined;
3942
+ const load = then && ts.isCallExpression(then.expression.expression) && then.expression.expression.expression.kind === ts.SyntaxKind.ImportKeyword ? then.expression.expression : undefined;
3943
+ const pick = then?.arguments[0];
3944
+ const name = pick && ts.isArrowFunction(pick) && ts.isPropertyAccessExpression(pick.body) ? pick.body.name.text : undefined;
3945
+ const spec = load?.arguments[0];
3946
+ const target = spec && ts.isStringLiteral(spec) ? fileOf(file, spec.text) : undefined;
3947
+ if (!target || !name)
3948
+ throw new Error(`${file}:${ts.getLineAndCharacterOfPosition(e.getSourceFile(), e.getStart()).line + 1}: a lazy route is read as () => import('./file').then((m) => m.Name) in a release build`);
3949
+ return { file: target, name };
3950
+ };
3951
+ const routesOf = (file, array, parent) => {
3952
+ files.add(file);
3953
+ return array.elements.map((el) => {
3954
+ if (!ts.isObjectLiteralExpression(el))
3955
+ throw new Error(`${file}: a route is an object literal in a release build`);
3956
+ const constant = (e) => routeConstant(file, e, parse, fileOf);
3957
+ routeFields(file, el, true, constant);
3958
+ const get = (k) => el.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === k)?.initializer;
3959
+ const text = (k) => { const v = get(k); const c = v && constant(v); return typeof c === 'string' ? c : undefined; };
3960
+ const node = { path: text('path') ?? '' };
3961
+ for (const kind of Object.keys(RUN_GUARDS)) {
3962
+ const list = get(kind);
3963
+ if (!list?.elements.length)
3964
+ continue;
3965
+ node.guards ??= guardIds++;
3966
+ if (kind === 'canDeactivate')
3967
+ node.deactivate = true;
3968
+ for (const g of list.elements) {
3969
+ let inject;
3970
+ if (ts.isIdentifier(g)) {
3971
+ const d = declarationOf(file, g.text, parse, fileOf);
3972
+ if (!d)
3973
+ throw new Error(`${file}:${lineOf(g)}: the ${kind} guard ${g.text}, which the release build can't find in the app's files, is not supported in a release build yet`);
3974
+ if (ts.isClassDeclaration(d)) {
3975
+ const method = d.members.find((m) => ts.isMethodDeclaration(m) && m.name.getText() === kind);
3976
+ inject = { name: g.text, arity: method ? method.parameters.length : RUN_GUARDS[kind] };
3977
+ }
3978
+ }
3979
+ else if (ts.isSpreadElement(g)) {
3980
+ throw new Error(`${file}:${lineOf(g)}: a spread in a route's ${kind} is not supported in a release build yet`);
3981
+ }
3982
+ guards.set(file, [...(guards.get(file) ?? []), { route: node.guards, kind, expr: g, inject }]);
3983
+ }
3984
+ }
3985
+ const component = get('component');
3986
+ if (component && ts.isIdentifier(component)) {
3987
+ if (component.text === 'NSEmptyOutletComponent')
3988
+ node.emptyOutlet = true;
3989
+ else
3990
+ node.component = component.text;
3991
+ }
3992
+ const loadComponent = get('loadComponent');
3993
+ if (loadComponent)
3994
+ node.component = lazy(file, loadComponent).name;
3995
+ if (text('redirectTo') !== undefined)
3996
+ node.redirectTo = text('redirectTo');
3997
+ if (text('pathMatch') === 'full')
3998
+ node.full = true;
3999
+ if (text('outlet'))
4000
+ node.outlet = text('outlet');
4001
+ const inherited = parent?.data && (node.path === '' || (!parent.component && !parent.emptyOutlet)) ? parent.data : [];
4002
+ const own = get('data');
4003
+ const data = new Map([...inherited, ...(own ? routeData(own, constant) : [])]);
4004
+ if (data.size)
4005
+ node.data = [...data];
4006
+ const children = get('children');
4007
+ if (children && ts.isArrayLiteralExpression(children))
4008
+ node.children = routesOf(file, children, node);
4009
+ else if (children) {
4010
+ const named = ts.isIdentifier(children) ? arrayNamed(file, children.text) : null;
4011
+ if (!named)
4012
+ throw new Error(`${file}:${lineOf(children)}: a route's children are an array in a release build (given ${children.getText()})`);
4013
+ node.children = routesOf(named.file, named.array, node);
4014
+ }
4015
+ const loadChildren = get('loadChildren');
4016
+ if (loadChildren) {
4017
+ const { file: target, name } = lazy(file, loadChildren);
4018
+ const found = arrayNamed(target, name);
4019
+ if (!found)
4020
+ throw new Error(`${target}: no route array ${name}`);
4021
+ node.children = [...(node.children ?? []), ...routesOf(found.file, found.array, node)];
4022
+ }
4023
+ return node;
4024
+ });
4025
+ };
4026
+ const sf = parse(entry);
4027
+ let found = null;
4028
+ let hasFileRouter = false;
4029
+ const visit = (n) => {
4030
+ if (found)
4031
+ return;
4032
+ if (ts.isCallExpression(n) && /(^|\.)(provideNativeScriptRouter|provideRouter|forRoot)$/.test(n.expression.getText()) && n.arguments[0] && ts.isIdentifier(n.arguments[0])) {
4033
+ routerOptions(entry, n);
4034
+ found = arrayNamed(entry, n.arguments[0].text);
4035
+ }
4036
+ else if (ts.isCallExpression(n) && /(^|\.)provideFileRouter$/.test(n.expression.getText())) {
4037
+ hasFileRouter = true;
4038
+ }
4039
+ ts.forEachChild(n, visit);
4040
+ };
4041
+ visit(sf);
4042
+ if (!found && hasFileRouter) {
4043
+ return fileRouterTree(dirname(entry), read);
4044
+ }
4045
+ if (!found)
4046
+ return null;
4047
+ const { file, array } = found;
4048
+ const routes = routesOf(file, array);
4049
+ return { routes, files, guards: [...guards].map(([f, list]) => guardModule(f, parse(f), list)) };
4050
+ }
4051
+ /**
4052
+ * AnalogJS-style file-based routing (`provideFileRouter()`): scans `<appDir>/app/pages/**\/*.{page.ts,md}`
4053
+ * following `index`, `[param]`, `[...rest]`, `(group)`, and layout nesting conventions.
4054
+ */
4055
+ function fileRouterTree(appDir, read) {
4056
+ const pagesDir = join(appDir, 'app', 'pages');
4057
+ if (!existsSync(pagesDir))
4058
+ return { routes: [], files: new Set(), guards: [] };
4059
+ const pagePaths = [];
4060
+ const walk = (d) => {
4061
+ for (const e of readdirSync(d, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
4062
+ const p = join(d, e.name);
4063
+ if (e.isDirectory())
4064
+ walk(p);
4065
+ else if (e.name.endsWith('.page.ts') || e.name.endsWith('.md'))
4066
+ pagePaths.push(p);
4067
+ }
4068
+ };
4069
+ walk(pagesDir);
4070
+ if (!pagePaths.length)
4071
+ return { routes: [], files: new Set(), guards: [] };
4072
+ const toRawPath = (f) => f.replace(/^(?:[a-zA-Z]:[\\/])?(.*?)[\\/](?:routes|pages)[\\/]|(\.page\.(js|ts)$)|(\.(ts|md)$)/g, '')
4073
+ .replace(/\[\.{3}.+\]/, '**')
4074
+ .replace(/\[([^\]]+)\]/g, ':$1');
4075
+ const toSegment = (s) => s.replace(/\bindex\b|\(.*?\)/g, '').replace(/\.|\/+/g, '/').replace(/^\/+|\/+$/g, '');
4076
+ const levels = new Map();
4077
+ const atLevel = (lvl) => levels.get(lvl) ?? (levels.set(lvl, new Map()), levels.get(lvl));
4078
+ for (const f of pagePaths) {
4079
+ const rawSegments = toRawPath(f).split('/');
4080
+ const lvl = rawSegments.length - 1;
4081
+ const rawSegment = rawSegments[lvl];
4082
+ atLevel(lvl).set(rawSegments.join('/'), { file: f, rawSegment, ancestors: rawSegments.slice(0, lvl), segment: toSegment(rawSegment), children: [] });
4083
+ }
4084
+ for (let lvl = Math.max(...levels.keys()); lvl > 0; lvl--) {
4085
+ for (const r of atLevel(lvl).values()) {
4086
+ const parentKey = r.ancestors.join('/');
4087
+ const parents = atLevel(lvl - 1);
4088
+ let parent = parents.get(parentKey);
4089
+ if (!parent) {
4090
+ const ps = r.ancestors[lvl - 1];
4091
+ parent = { file: null, rawSegment: ps, ancestors: r.ancestors.slice(0, lvl - 1), segment: toSegment(ps), children: [] };
4092
+ parents.set(parentKey, parent);
4093
+ }
4094
+ parent.children.push(r);
4095
+ }
4096
+ }
4097
+ const deprio = (s) => s.replace(':', '~~').replace('**', '~~~~');
4098
+ const sortRaw = (list) => {
4099
+ list.sort((a, b) => {
4100
+ const sa = (a.children.length ? '~' : '') + deprio(a.segment);
4101
+ const sb = (b.children.length ? '~' : '') + deprio(b.segment);
4102
+ return sa > sb ? 1 : sa < sb ? -1 : 0;
4103
+ });
4104
+ for (const r of list)
4105
+ sortRaw(r.children);
4106
+ };
4107
+ const roots = [...atLevel(0).values()];
4108
+ sortRaw(roots);
4109
+ const toNode = (r) => {
4110
+ const children = r.children.length ? r.children.map(toNode) : undefined;
4111
+ const node = { path: r.segment };
4112
+ if (r.file) {
4113
+ if (r.file.endsWith('.md')) {
4114
+ node.component = 'MarkdownRouteComponent';
4115
+ }
4116
+ else {
4117
+ const text = read(r.file);
4118
+ const comps = componentsOf(r.file, text);
4119
+ if (comps.length) {
4120
+ node.component = comps[0].name;
4121
+ }
4122
+ else {
4123
+ const sf = ts.createSourceFile(r.file, text, ts.ScriptTarget.Latest, true);
4124
+ for (const st of sf.statements) {
4125
+ if (!ts.isVariableStatement(st))
4126
+ continue;
4127
+ for (const d of st.declarationList.declarations) {
4128
+ if (ts.isIdentifier(d.name) && d.name.text === 'routeMeta' && d.initializer && ts.isObjectLiteralExpression(d.initializer)) {
4129
+ for (const p of d.initializer.properties) {
4130
+ if (!ts.isPropertyAssignment(p))
4131
+ continue;
4132
+ const k = p.name.getText();
4133
+ if (k === 'redirectTo' && ts.isStringLiteral(p.initializer))
4134
+ node.redirectTo = p.initializer.text;
4135
+ if (k === 'pathMatch' && ts.isStringLiteral(p.initializer) && p.initializer.text === 'full')
4136
+ node.full = true;
4137
+ }
4138
+ }
4139
+ }
4140
+ }
4141
+ }
4142
+ }
4143
+ }
4144
+ if (children)
4145
+ node.children = children;
4146
+ return node;
4147
+ };
4148
+ return { routes: roots.map(toNode), files: new Set(), guards: [] };
4149
+ }
4150
+ /** The components a route tree names. */
4151
+ export function routedComponents(routes) {
4152
+ return routes.flatMap((r) => [...(r.component ? [r.component] : []), ...routedComponents(r.children ?? [])]);
4153
+ }
4154
+ /** The route table: path → component, and where the app starts. */
4155
+ export function angularRoutes(text, file = 'routes.ts') {
4156
+ const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
4157
+ const routes = [];
4158
+ let initial = '';
4159
+ const visit = (n) => {
4160
+ if (ts.isCallExpression(n) && /(^|\.)forRoot$/.test(n.expression.getText()))
4161
+ routerOptions(file, n);
4162
+ const keys = ts.isObjectLiteralExpression(n) ? n.properties.map((p) => p.name?.getText()) : [];
4163
+ if (ts.isObjectLiteralExpression(n) && keys.includes('path') && keys.some((k) => !!k && (ROUTE_GUARDS.has(k) || ['component', 'loadComponent', 'redirectTo', 'children', 'loadChildren', 'pathMatch', 'resolve'].includes(k)))) {
4164
+ if (keys.includes('data'))
4165
+ throw new Error(`${file}:${lineOf(n)}: a route's data, with the routes given outside the entry, is not supported in a release build yet`);
4166
+ routeFields(file, n);
4167
+ // Only a flat table of paths: nested and lazy routes need provideNativeScriptRouter(routes) in the entry.
4168
+ const nested = keys.find((k) => k === 'children' || k === 'loadChildren' || k === 'loadComponent' || k === 'outlet');
4169
+ if (nested)
4170
+ throw new Error(`${file}:${lineOf(n)}: a route's ${nested}, with the routes given outside the entry, is not supported in a release build yet`);
4171
+ const path = n.properties.find((p) => p.name?.getText() === 'path');
4172
+ if (keys.includes('redirectTo') && path.initializer.text !== '')
4173
+ throw new Error(`${file}:${lineOf(n)}: a redirect from a path other than '', with the routes given outside the entry, is not supported in a release build yet`);
4174
+ }
4175
+ if (ts.isObjectLiteralExpression(n)) {
4176
+ const get = (k) => n.properties.find((p) => ts.isPropertyAssignment(p) && p.name.text === k)?.initializer;
4177
+ const path = get('path')?.text;
4178
+ const component = get('component');
4179
+ const redirect = get('redirectTo')?.text;
4180
+ if (path !== undefined && component && ts.isIdentifier(component))
4181
+ routes.push({ path, component: component.text });
4182
+ if (path === '' && redirect)
4183
+ initial = redirect;
4184
+ }
4185
+ ts.forEachChild(n, visit);
4186
+ };
4187
+ visit(sf);
4188
+ return { routes, initial: initial || '/' + (routes[0]?.path ?? '') };
4189
+ }