@nativescript/compiler-angular 0.0.0-stage → 9.2.0-alpha.9
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.
- package/dist/angular-libraries.js +173 -0
- package/dist/angular.js +2895 -0
- package/dist/component-bases.js +746 -0
- package/dist/core-api.js +8 -0
- package/dist/entry.js +118 -0
- package/dist/index.js +157 -0
- package/dist/kotlin.js +280 -0
- package/dist/modules.js +698 -0
- package/dist/ng-modules.js +66 -0
- package/dist/package.js +15 -0
- package/dist/refusals.js +5 -0
- package/dist/semantics.js +213 -0
- package/dist/swift.js +340 -0
- package/kit-android/fromcore/AngularAPI.kt +172 -0
- package/kit-android/fromcore/AngularRouter.kt +587 -0
- package/kit-android/handport/Router.kt +151 -0
- package/kit-android/main/AngularChangeDetection.kt +250 -0
- package/kit-android/main/AngularCore.kt +685 -0
- package/kit-android/main/AngularHttp.kt +431 -0
- package/kit-android/main/AngularRouterValues.kt +154 -0
- package/kit-android/main/AngularRx.kt +224 -0
- package/kit-apple/AngularAPI.swift +224 -0
- package/kit-apple/AngularChangeDetection.swift +248 -0
- package/kit-apple/AngularCore.swift +764 -0
- package/kit-apple/AngularHttp.swift +467 -0
- package/kit-apple/AngularRouter.swift +626 -0
- package/kit-apple/AngularRouterValues.swift +285 -0
- package/kit-apple/AngularRx.swift +246 -0
- package/kit-apple/kit-index.json +739 -0
- package/package.json +53 -4
- package/runtime/angular-forms.ts +3099 -0
- package/runtime/angular-rx.ts +550 -0
- package/runtime/angular.ts +826 -0
- package/README.md +0 -3
package/dist/angular.js
ADDED
|
@@ -0,0 +1,2895 @@
|
|
|
1
|
+
import * as ng from '@angular/compiler';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { existsSync, readFileSync } 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, 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
|
+
* A NativeScript Angular standalone component (`@Component` with a template
|
|
51
|
+
* of @nativescript/core elements, signals, `input()`/`output()`, `inject()`)
|
|
52
|
+
* as a virtual class: the component's own source with one method appended
|
|
53
|
+
* per template expression. The class keeps Angular's API; the translator
|
|
54
|
+
* knows what `signal()`, `computed()`, `input()`, `output()` and `inject()` mean.
|
|
55
|
+
*/
|
|
56
|
+
export function angularComponent(path, text, selectors, options = {}) {
|
|
57
|
+
const written = text;
|
|
58
|
+
let sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
59
|
+
let cls = sf.statements.find((s) => ts.isClassDeclaration(s) && !!decorator(s, 'Component'));
|
|
60
|
+
if (!cls || !cls.name)
|
|
61
|
+
return null;
|
|
62
|
+
const others = sf.statements.filter((s) => s !== cls && ts.isClassDeclaration(s) && !!decorator(s, 'Component'));
|
|
63
|
+
if (others.length)
|
|
64
|
+
throw new Error(`${path}: ${others.length + 1} components in one file; a compiled release takes one @Component per file`);
|
|
65
|
+
const asWritten = cls;
|
|
66
|
+
const flat = flattenComponent(path, text, cls.name.text);
|
|
67
|
+
const opened = openStatics(flat ?? text, flat === null ? cls : ts.createSourceFile(path, flat, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS).statements.find((s) => ts.isClassDeclaration(s) && !!decorator(s, 'Component')));
|
|
68
|
+
if (opened !== text) {
|
|
69
|
+
text = opened;
|
|
70
|
+
sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
71
|
+
cls = sf.statements.find((s) => ts.isClassDeclaration(s) && !!decorator(s, 'Component'));
|
|
72
|
+
}
|
|
73
|
+
// A class with decorated inputs and outputs, or constructor injection, as the signal-style class the translator reads.
|
|
74
|
+
const classic = classicClass(path, text, cls);
|
|
75
|
+
if (classic) {
|
|
76
|
+
text = classic.text;
|
|
77
|
+
sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
78
|
+
cls = sf.statements.find((s) => ts.isClassDeclaration(s) && !!decorator(s, 'Component'));
|
|
79
|
+
}
|
|
80
|
+
const meta = decorator(cls, 'Component').arguments[0];
|
|
81
|
+
const prop = (name) => meta.properties.find((p) => ts.isPropertyAssignment(p) && p.name.text === name)?.initializer;
|
|
82
|
+
for (const p of meta.properties) {
|
|
83
|
+
const key = ts.isPropertyAssignment(p) && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) ? p.name.text : null;
|
|
84
|
+
if (key === null)
|
|
85
|
+
throw new Error(`${path}: @Component's ${p.getText().split('\n')[0]} is read as \`name: value\` in a release build`);
|
|
86
|
+
if (key === 'preserveWhitespaces' && p.initializer.kind !== ts.SyntaxKind.FalseKeyword)
|
|
87
|
+
throw new Error(`${path}: @Component's preserveWhitespaces is not supported in a release build yet`);
|
|
88
|
+
if (!COMPONENT_META.has(key))
|
|
89
|
+
throw new Error(`${path}: @Component's ${key} is not supported in a release build yet`);
|
|
90
|
+
}
|
|
91
|
+
const providers = prop('providers');
|
|
92
|
+
if (providers) {
|
|
93
|
+
if (flat !== null)
|
|
94
|
+
throw new Error(`${path}: @Component's providers on a class that extends another are not supported in a release build yet`);
|
|
95
|
+
refuseScopedInjection(path, asWritten);
|
|
96
|
+
text = withInjector(path, text, cls, providers);
|
|
97
|
+
sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
98
|
+
cls = sf.statements.find((s) => ts.isClassDeclaration(s) && !!decorator(s, 'Component'));
|
|
99
|
+
}
|
|
100
|
+
const selector = prop('selector')?.text ?? cls.name.text;
|
|
101
|
+
const inline = prop('template');
|
|
102
|
+
const templateUrl = prop('templateUrl')?.text;
|
|
103
|
+
const template = inline && (ts.isNoSubstitutionTemplateLiteral(inline) || ts.isStringLiteral(inline)) ? inline.text : templateUrl && existsSync(join(dirname(path), templateUrl)) ? readFileSync(join(dirname(path), templateUrl), 'utf8') : '';
|
|
104
|
+
// Angular 22's default strategy is OnPush.
|
|
105
|
+
const strategy = prop('changeDetection')?.getText();
|
|
106
|
+
const onPush = !!options.zone && strategy !== 'ChangeDetectionStrategy.Default' && strategy !== 'ChangeDetectionStrategy.Eager';
|
|
107
|
+
/** A tag as @nativescript/angular's registry knows it: by its name, lowercased, or kebab-cased (`grid-layout`). */
|
|
108
|
+
const registered = new Map();
|
|
109
|
+
for (const [tag, cls] of options.elements ?? [])
|
|
110
|
+
for (const k of [tag, tag.toLowerCase(), tag.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()])
|
|
111
|
+
registered.set(k, cls);
|
|
112
|
+
const elementOf = (name) => core.canonical(name) ?? core.canonical(name.replace(/-/g, '')) ?? registered.get(name) ?? registered.get(name.toLowerCase()) ?? undefined;
|
|
113
|
+
const metas = new Map();
|
|
114
|
+
for (const [tag, keys] of options.elementMeta ?? [])
|
|
115
|
+
for (const k of [tag, tag.toLowerCase(), tag.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()])
|
|
116
|
+
metas.set(k, keys);
|
|
117
|
+
/**
|
|
118
|
+
* A plugin tag registered with a `ViewClassMeta` (`registerElement('Drawer', () => Drawer, meta)`): its renderer hooks
|
|
119
|
+
* decide where the element and its children go, and the release build runs none of them yet.
|
|
120
|
+
*/
|
|
121
|
+
const checkMeta = (n) => {
|
|
122
|
+
if (core.canonical(n.name) || core.canonical(n.name.replace(/-/g, '')))
|
|
123
|
+
return;
|
|
124
|
+
const keys = metas.has(n.name) ? metas.get(n.name) : metas.get(n.name.toLowerCase());
|
|
125
|
+
if (keys === undefined)
|
|
126
|
+
return;
|
|
127
|
+
if (keys === null)
|
|
128
|
+
throw new Error(`${path}: <${n.name}> is registered with a ViewClassMeta the build cannot read (not an object literal in the registering file)`);
|
|
129
|
+
if (keys.includes('skipAddToDom'))
|
|
130
|
+
throw new Error(`${path}: <${n.name}> is registered with skipAddToDom, which a release build does not support yet`);
|
|
131
|
+
const hooks = keys.filter((k) => ['insertChild', 'removeChild', 'insertInvisibleNode', 'removeInvisibleNode'].includes(k));
|
|
132
|
+
if (hooks.length && n.children.some((c) => !(c instanceof ng.TmplAstText) || c.value.trim())) {
|
|
133
|
+
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`);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
const { members, props, optional, outputs, inputAliases } = publicMembers(path, cls, classic);
|
|
137
|
+
const scope = { names: new Map([...members].map((m) => [m, classic?.inputs.has(m) ? `this.${m}()` : `this.${m}`])) };
|
|
138
|
+
const init = cls.members.find((m) => ts.isMethodDeclaration(m) && m.name.getText() === 'ngOnInit');
|
|
139
|
+
/** A lifecycle hook the class implements: a method of that name, taking nothing. */
|
|
140
|
+
const hook = (name) => {
|
|
141
|
+
const m = cls.members.find((x) => ts.isMethodDeclaration(x) && x.name.getText() === name);
|
|
142
|
+
if (m?.parameters.length)
|
|
143
|
+
throw new Error(`${path}: ${name} takes no parameters`);
|
|
144
|
+
return !!m;
|
|
145
|
+
};
|
|
146
|
+
if (init && init.parameters.length)
|
|
147
|
+
throw new Error(`${path}: ngOnInit takes no parameters`);
|
|
148
|
+
const methods = [];
|
|
149
|
+
let next = 0;
|
|
150
|
+
const params = (loops) => loops.map((l) => l.param).join(', ');
|
|
151
|
+
const args = (loops) => loops.flatMap((l) => (l.index === undefined ? [l.item] : [l.item, l.index])).join(', ');
|
|
152
|
+
/** `*ngIf="x as y"`: names a structural directive binds, in the template it renders. */
|
|
153
|
+
const aliases = new Map();
|
|
154
|
+
const local = (loops) => {
|
|
155
|
+
const names = new Map(scope.names);
|
|
156
|
+
for (const [k, v] of aliases)
|
|
157
|
+
names.set(k, v);
|
|
158
|
+
for (const l of loops) {
|
|
159
|
+
names.delete(l.item);
|
|
160
|
+
if (l.index !== undefined)
|
|
161
|
+
names.delete(l.index);
|
|
162
|
+
for (const [k, v] of Object.entries(l.names ?? {}))
|
|
163
|
+
names.set(k, v);
|
|
164
|
+
}
|
|
165
|
+
return { names };
|
|
166
|
+
};
|
|
167
|
+
/**
|
|
168
|
+
* Each `| name` in the template is one pipe per view it renders in, as Angular's `ɵɵpipe` creates them: a local of the
|
|
169
|
+
* view (`$pN`), and for a pure pipe the arguments it last transformed (`$cN`), so `transform` runs only when one changes.
|
|
170
|
+
*/
|
|
171
|
+
const sites = new Map();
|
|
172
|
+
const imported = new Map();
|
|
173
|
+
let usesRuntime = false;
|
|
174
|
+
/** The class a pipe's name resolves to, imported into the component's file under a name of its own. */
|
|
175
|
+
const pipeClass = (name) => {
|
|
176
|
+
const decl = options.pipes?.get(name) ?? COMMON_PIPES[name];
|
|
177
|
+
if (!decl)
|
|
178
|
+
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` : ''}`);
|
|
179
|
+
const from = decl.file === RUNTIME ? (usesRuntime = true, options.runtimeModule ?? RUNTIME) : decl.file;
|
|
180
|
+
const names = imported.get(from) ?? new Map();
|
|
181
|
+
imported.set(from, names);
|
|
182
|
+
if (!names.has(decl.className))
|
|
183
|
+
names.set(decl.className, `$Pipe_${decl.className}`);
|
|
184
|
+
return { alias: names.get(decl.className), decl };
|
|
185
|
+
};
|
|
186
|
+
/**
|
|
187
|
+
* The pipes in a node's own expressions, as locals of the view around it: the loops its methods take, and the node
|
|
188
|
+
* wrapped in them. A pipe class with constructor parameters is made through the `$create` the build adds to it,
|
|
189
|
+
* which injects them; one with `ngOnDestroy` is destroyed with its view.
|
|
190
|
+
*/
|
|
191
|
+
const withPipes = (asts, loops) => {
|
|
192
|
+
const found = asts.flatMap((a) => (a ? allPipes(a instanceof ng.ASTWithSource ? a.ast : a) : [])).filter((p) => !sites.has(p));
|
|
193
|
+
if (!found.length)
|
|
194
|
+
return { loops, wrap: (body) => body };
|
|
195
|
+
const made = [];
|
|
196
|
+
let inner = loops;
|
|
197
|
+
for (const p of found) {
|
|
198
|
+
const { alias, decl } = pipeClass(p.name);
|
|
199
|
+
const k = sites.size;
|
|
200
|
+
const pipe = `$p${k}`;
|
|
201
|
+
const make = expr(decl.create ? `${alias}.$create()` : `new ${alias}()`, inner);
|
|
202
|
+
inner = [...inner, { item: pipe, param: `${pipe}: ${alias}` }];
|
|
203
|
+
const destroy = decl.destroy ? handlerOf(`${pipe}.ngOnDestroy()`, inner) : undefined;
|
|
204
|
+
made.push({ name: pipe, make, ...(destroy ? { destroy } : {}) });
|
|
205
|
+
let cache = null;
|
|
206
|
+
if (decl.pure) {
|
|
207
|
+
cache = `$c${k}`;
|
|
208
|
+
made.push({ name: cache, make: expr('new $PurePipeCache()', inner) });
|
|
209
|
+
inner = [...inner, { item: cache, param: `${cache}: $PurePipeCache` }];
|
|
210
|
+
}
|
|
211
|
+
sites.set(p, { pipe, cache });
|
|
212
|
+
}
|
|
213
|
+
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) };
|
|
214
|
+
};
|
|
215
|
+
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);
|
|
216
|
+
/** The pipes and keyword-named member reads in an expression, outermost first (not those inside a pipe). */
|
|
217
|
+
const specialsIn = (node) => {
|
|
218
|
+
const found = [];
|
|
219
|
+
const visit = (n) => {
|
|
220
|
+
if (n instanceof ng.BindingPipe || keywordRead(n)) {
|
|
221
|
+
found.push(n);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
if (!(n instanceof ng.AST))
|
|
225
|
+
return;
|
|
226
|
+
for (const v of Object.values(n))
|
|
227
|
+
Array.isArray(v) ? v.forEach(visit) : visit(v);
|
|
228
|
+
};
|
|
229
|
+
if (node instanceof ng.BindingPipe || keywordRead(node))
|
|
230
|
+
return [node];
|
|
231
|
+
for (const v of Object.values(node))
|
|
232
|
+
Array.isArray(v) ? v.forEach(visit) : visit(v);
|
|
233
|
+
return found;
|
|
234
|
+
};
|
|
235
|
+
const code = (value, _loops) => {
|
|
236
|
+
const root = value instanceof ng.ASTWithSource ? value.ast : value;
|
|
237
|
+
// `text="How {{ x }}"`: Angular renders the literal text with each expression's value, undefined and null as ''.
|
|
238
|
+
const interpolation = root instanceof ng.Interpolation ? root : null;
|
|
239
|
+
if (!specialsIn(root).length && !interpolation)
|
|
240
|
+
return value instanceof ng.ASTWithSource ? sourceOf(value) : template.slice(value.sourceSpan.start, value.sourceSpan.end);
|
|
241
|
+
const textOf = (node) => {
|
|
242
|
+
// A member named like a keyword (`continue()`): read on the component, which the expression's text cannot say.
|
|
243
|
+
if (keywordRead(node))
|
|
244
|
+
return `this.${node.name}`;
|
|
245
|
+
if (node instanceof ng.BindingPipe) {
|
|
246
|
+
const site = sites.get(node);
|
|
247
|
+
if (!site)
|
|
248
|
+
throw new Error(`${path}: the ${node.name} pipe where the release build gives it no view (in ${template.slice(node.sourceSpan.start, node.sourceSpan.end)})`);
|
|
249
|
+
const given = [node.exp, ...node.args].map(textOf);
|
|
250
|
+
if (!site.cache)
|
|
251
|
+
return `${site.pipe}.transform(${given.join(', ')})`;
|
|
252
|
+
if (given.length > 5)
|
|
253
|
+
throw new Error(`${path}: the ${node.name} pipe with more than 4 arguments is not supported in a release build yet`);
|
|
254
|
+
const xs = given.map((_, i) => `$x${i}`);
|
|
255
|
+
return `${site.cache}.pure${given.length}(${given.map((g) => `(${g})`).join(', ')}, (${xs.join(', ')}) => ${site.pipe}.transform(${xs.join(', ')}))`;
|
|
256
|
+
}
|
|
257
|
+
const at = node.sourceSpan.start;
|
|
258
|
+
let out = template.slice(at, node.sourceSpan.end);
|
|
259
|
+
for (const p of specialsIn(node).sort((a, b) => b.sourceSpan.start - a.sourceSpan.start)) {
|
|
260
|
+
out = out.slice(0, p.sourceSpan.start - at) + textOf(p) + out.slice(p.sourceSpan.end - at);
|
|
261
|
+
}
|
|
262
|
+
return out;
|
|
263
|
+
};
|
|
264
|
+
if (interpolation)
|
|
265
|
+
return '`' + interpolation.strings.map((s, i) => s.replace(/[`\\$]/g, (x) => '\\' + x) + (i < interpolation.expressions.length ? `\${(${textOf(interpolation.expressions[i])}) ?? ''}` : '')).join('') + '`';
|
|
266
|
+
return textOf(root);
|
|
267
|
+
};
|
|
268
|
+
// `$any(x)` is Angular's escape from template type checking; the release build is typed by the component's code,
|
|
269
|
+
// except `$any($event)`, whose event data the handler reads as the type it declares.
|
|
270
|
+
// A string literal a template writes across lines is one string in the template's expression, and must stay one in TypeScript.
|
|
271
|
+
const clean = (code) => code
|
|
272
|
+
.replace(/(['"])(?:\\.|(?!\1)[\s\S])*?\1/g, (s) => s.replace(/\r?\n/g, '\\n').replace(/\r/g, '\\r'))
|
|
273
|
+
.replace(/\$any\(\s*\$event\s*\)/g, '($event as any)')
|
|
274
|
+
.replace(/\$any\(/g, '(');
|
|
275
|
+
/** The template line (0-based) of the binding being compiled, and each template method's (by its index in `methods`). */
|
|
276
|
+
let here = null;
|
|
277
|
+
const located = new Map();
|
|
278
|
+
const at = (span) => { if (span)
|
|
279
|
+
here = span.start.line; };
|
|
280
|
+
const add = (method) => {
|
|
281
|
+
methods.push(method);
|
|
282
|
+
if (here !== null)
|
|
283
|
+
located.set(methods.length - 1, here);
|
|
284
|
+
};
|
|
285
|
+
const expr = (code, loops, untyped = false) => {
|
|
286
|
+
const m = `$b${next++}`;
|
|
287
|
+
add(` ${m}(${params(loops)})${untyped ? ': any' : ''} { return ${core.rewrite(clean(code), local(loops))}; }`);
|
|
288
|
+
return m;
|
|
289
|
+
};
|
|
290
|
+
/** A method of statements over the names in scope (a pipe's `ngOnDestroy`). */
|
|
291
|
+
const handlerOf = (statements, loops) => {
|
|
292
|
+
const m = `$e${next++}`;
|
|
293
|
+
add(` ${m}(${params(loops)}) { ${statements}; }`);
|
|
294
|
+
return m;
|
|
295
|
+
};
|
|
296
|
+
// 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.
|
|
297
|
+
const test = (code, loops) => expr(`!!(${code})`, loops);
|
|
298
|
+
// A component's output gives its handler the emitted value as `$event`; a view's event gives the event data.
|
|
299
|
+
const handler = (code, loops, payload = false) => {
|
|
300
|
+
const m = `$e${next++}`;
|
|
301
|
+
add(` ${m}(${[params(loops), `$event: ${payload ? 'any' : '$EventData'}`].filter(Boolean).join(', ')}) { ${core.rewrite(clean(code), local(loops), 'statements')}; }`);
|
|
302
|
+
return m;
|
|
303
|
+
};
|
|
304
|
+
/**
|
|
305
|
+
* The view queries an element or a component's host matches (`#ref`, or the component's class), as the methods that
|
|
306
|
+
* set and clear each one's field: an ElementRef of the view, the component itself, or the view read as its class.
|
|
307
|
+
* The field is set when the view is made and cleared when it goes, as a query's next refresh finds it gone.
|
|
308
|
+
*/
|
|
309
|
+
const queryHooks = (refs, component, tag, loops) => {
|
|
310
|
+
const hooks = [];
|
|
311
|
+
for (const q of queries) {
|
|
312
|
+
if (q.ref ? !refs.includes(q.ref) : q.type !== component && q.type !== tag)
|
|
313
|
+
continue;
|
|
314
|
+
const instance = !!component && (q.read === null || q.read === component);
|
|
315
|
+
const wrapped = q.read === 'ElementRef' || (q.read === null && !component);
|
|
316
|
+
if (wrapped)
|
|
317
|
+
usesElementRef = true;
|
|
318
|
+
// The made node as its own class (the component, the element's view class), else untyped and read as the query's class.
|
|
319
|
+
const own = instance ? component : !wrapped && q.read === tag ? tag : null;
|
|
320
|
+
const value = wrapped ? 'new $ElementRef($q)' : own || !q.read ? '$q' : `($q as ${q.read})`;
|
|
321
|
+
const inner = [...loops, { item: '$q', param: `$q: ${own ?? 'any'}` }];
|
|
322
|
+
// A single query keeps its match once the match's view goes, which Angular's next refresh would clear.
|
|
323
|
+
const set = handlerOf(q.many ? `this.${q.field}.$add($q, ${value})` : `this.${q.field} = ${value}`, inner);
|
|
324
|
+
const unset = q.many ? handlerOf(`this.${q.field}.$remove($q)`, inner) : undefined;
|
|
325
|
+
hooks.push({ set, ...(unset ? { unset } : {}), on: instance ? 'instance' : 'view' });
|
|
326
|
+
}
|
|
327
|
+
return hooks;
|
|
328
|
+
};
|
|
329
|
+
let usesElementRef = false;
|
|
330
|
+
let usesUnset = false;
|
|
331
|
+
const queries = classic?.queries ?? [];
|
|
332
|
+
/** The `#refs` of the template's own elements, outside any embedded view: what a static query can resolve. */
|
|
333
|
+
const staticRefs = new Set();
|
|
334
|
+
/** The static queries not yet resolved where the template walk is; ngOnInit waits for them. */
|
|
335
|
+
const staticQueries = new Set();
|
|
336
|
+
let lateInit = false;
|
|
337
|
+
/**
|
|
338
|
+
* The app's directives in the component's scope, by their selectors, as Angular's compiler matches them: those its
|
|
339
|
+
* `imports` name, directly or through an NgModule's exports, and those of an NgModule declaring it.
|
|
340
|
+
*/
|
|
341
|
+
const inScope = new Set();
|
|
342
|
+
const expand = (names) => {
|
|
343
|
+
for (const n of names) {
|
|
344
|
+
if (inScope.has(n))
|
|
345
|
+
continue;
|
|
346
|
+
inScope.add(n);
|
|
347
|
+
expand(options.ngModules?.get(n) ?? []);
|
|
348
|
+
}
|
|
349
|
+
};
|
|
350
|
+
const importsMeta = prop('imports');
|
|
351
|
+
expand(importsMeta && ts.isArrayLiteralExpression(importsMeta) ? importsMeta.elements.filter(ts.isIdentifier).map((e) => e.text) : []);
|
|
352
|
+
for (const [, names] of options.ngModules ?? [])
|
|
353
|
+
if (names.includes(cls.name.text))
|
|
354
|
+
expand(names);
|
|
355
|
+
const matcher = new ng.SelectorMatcher();
|
|
356
|
+
for (const d of options.directives ?? [])
|
|
357
|
+
if (inScope.has(d.className))
|
|
358
|
+
matcher.addSelectables(ng.CssSelector.parse(d.selector), d);
|
|
359
|
+
/** The directives an element matches: its name, attributes, bound inputs and outputs, as Angular matches them. */
|
|
360
|
+
const matched = (name, attributes, bound) => {
|
|
361
|
+
const css = new ng.CssSelector();
|
|
362
|
+
css.setElement(name);
|
|
363
|
+
for (const [k, v] of attributes) {
|
|
364
|
+
css.addAttribute(k, v);
|
|
365
|
+
if (k === 'class')
|
|
366
|
+
for (const c of v.split(/\s+/).filter(Boolean))
|
|
367
|
+
css.addClassName(c);
|
|
368
|
+
}
|
|
369
|
+
for (const b of bound)
|
|
370
|
+
css.addAttribute(b, '');
|
|
371
|
+
const found = [];
|
|
372
|
+
matcher.match(css, (_s, d) => { if (!found.includes(d))
|
|
373
|
+
found.push(d); });
|
|
374
|
+
return found;
|
|
375
|
+
};
|
|
376
|
+
const hostMatcher = new ng.SelectorMatcher();
|
|
377
|
+
for (const h of options.hosts ?? [])
|
|
378
|
+
if (inScope.has(h.name))
|
|
379
|
+
hostMatcher.addSelectables(ng.CssSelector.parse(h.selector), h);
|
|
380
|
+
/** The component in scope an element hosts, matched as directives are. */
|
|
381
|
+
const hostedBy = (n) => {
|
|
382
|
+
const css = new ng.CssSelector();
|
|
383
|
+
css.setElement(n.name);
|
|
384
|
+
for (const a of n.attributes) {
|
|
385
|
+
css.addAttribute(a.name, a.value);
|
|
386
|
+
if (a.name === 'class')
|
|
387
|
+
for (const c of a.value.split(/\s+/).filter(Boolean))
|
|
388
|
+
css.addClassName(c);
|
|
389
|
+
}
|
|
390
|
+
for (const b of [...n.inputs.map((i) => i.name), ...n.outputs.map((o) => o.name)])
|
|
391
|
+
css.addAttribute(b, '');
|
|
392
|
+
const found = [];
|
|
393
|
+
hostMatcher.match(css, (_s, h) => { if (!found.includes(h))
|
|
394
|
+
found.push(h); });
|
|
395
|
+
if (found.length > 1)
|
|
396
|
+
throw new Error(`${path}: <${n.name}> matches the components ${found.map((h) => h.name).join(' and ')}; an element hosts one`);
|
|
397
|
+
return found[0];
|
|
398
|
+
};
|
|
399
|
+
let directiveCount = 0;
|
|
400
|
+
/**
|
|
401
|
+
* A directive on an element, one per view of it: made with the element as its ElementRef, its inputs set from the
|
|
402
|
+
* element's bindings and attributes of their names (the bindings then are the directive's, not the view's), its
|
|
403
|
+
* host listeners and bindings on the element, and its hooks.
|
|
404
|
+
*/
|
|
405
|
+
const directiveUse = (d, n, loops, consumed) => {
|
|
406
|
+
const names = imported.get(d.file) ?? new Map();
|
|
407
|
+
imported.set(d.file, names);
|
|
408
|
+
if (!names.has(d.className))
|
|
409
|
+
names.set(d.className, `$Dir_${d.className}`);
|
|
410
|
+
const alias = names.get(d.className);
|
|
411
|
+
const name = `$d${directiveCount++}`;
|
|
412
|
+
const make = expr(d.create ? `${alias}.$create()` : `new ${alias}()`, loops);
|
|
413
|
+
const inner = [...loops, { item: name, param: `${name}: ${alias}` }];
|
|
414
|
+
const valued = [...inner, { item: '$v', param: '$v: any' }];
|
|
415
|
+
const own = { names: new Map(d.members.map((m) => [m, `${name}.${m}`])) };
|
|
416
|
+
const setter = (input, member) => handlerOf(`${name}.${member}${d.signals.has(member) ? '.$assign($v)' : ' = $v'}${d.hooks.has('ngOnChanges') ? `; ${name}.$change(${JSON.stringify(member)}, $v)` : ''}`, valued);
|
|
417
|
+
const inputs = [];
|
|
418
|
+
for (const [input, member] of d.inputs) {
|
|
419
|
+
const b = n.inputs.find((i) => i.name === input && i.type === ng.BindingType.Property);
|
|
420
|
+
const a = n.attributes.find((x) => x.name === input);
|
|
421
|
+
if (b) {
|
|
422
|
+
at(b.sourceSpan);
|
|
423
|
+
consumed.add(input);
|
|
424
|
+
inputs.push({ set: setter(input, member), method: expr(code(b.value, loops), loops, true) });
|
|
425
|
+
}
|
|
426
|
+
else if (a)
|
|
427
|
+
inputs.push({ set: setter(input, member), value: a.value });
|
|
428
|
+
}
|
|
429
|
+
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' }]) }));
|
|
430
|
+
const bindings = d.bindings.map((b) => ({ prop: b.prop, method: expr(core.rewrite(b.code, own), inner, true) }));
|
|
431
|
+
const hook = (h) => (d.hooks.has(h) ? handlerOf(`${name}.${h}()`, inner) : undefined);
|
|
432
|
+
const init = hook('ngOnInit'), destroy = hook('ngOnDestroy'), afterViewInit = hook('ngAfterViewInit');
|
|
433
|
+
return { name, make, inputs, listeners, bindings, ...(init ? { init } : {}), ...(destroy ? { destroy } : {}), ...(afterViewInit ? { afterViewInit } : {}), ...(d.hooks.has('ngOnChanges') ? { changes: true } : {}), attributes: d.attributes };
|
|
434
|
+
};
|
|
435
|
+
/** A function or class of the build's Angular runtime module, imported into the component's file under a name of its own. */
|
|
436
|
+
const fromRuntime = (name) => {
|
|
437
|
+
usesRuntime = true;
|
|
438
|
+
const from = options.runtimeModule ?? RUNTIME;
|
|
439
|
+
const names = imported.get(from) ?? new Map();
|
|
440
|
+
imported.set(from, names);
|
|
441
|
+
if (!names.has(name))
|
|
442
|
+
names.set(name, `$Ng_${name}`);
|
|
443
|
+
return names.get(name);
|
|
444
|
+
};
|
|
445
|
+
/**
|
|
446
|
+
* An element's static `class` and `[class.x]` toggles as one bound `class` from the runtime's ngClassNames. With NgClass (`[ngClass]` or
|
|
447
|
+
* `ngClass="a b"`), the runtime's NgClass directive, returned, which takes all three; on a component, whose root
|
|
448
|
+
* view it can't host, one bound `class` from the runtime's ngClassNames.
|
|
449
|
+
*/
|
|
450
|
+
const classAttr = (n, attrs, loops, ngClass, shared = false) => {
|
|
451
|
+
const toggles = n.inputs.filter((i) => i.type === ng.BindingType.Class);
|
|
452
|
+
if (!toggles.length && !ngClass)
|
|
453
|
+
return null;
|
|
454
|
+
at((ngClass ?? toggles[0]).sourceSpan);
|
|
455
|
+
const fixed = attrs.findIndex((a) => a.name === 'class');
|
|
456
|
+
const base = fixed >= 0 ? attrs.splice(fixed, 1)[0].value ?? '' : '';
|
|
457
|
+
const pairs = toggles.flatMap((t) => [JSON.stringify(t.name), `(${code(t.value, loops)})`]);
|
|
458
|
+
// Beside the forms runtime's ng-* classes the toggles go through NgClass, which keeps the classes they share.
|
|
459
|
+
if (!ngClass && !shared) {
|
|
460
|
+
attrs.push({ name: 'class', method: expr(`${fromRuntime('ngClassNames')}(${JSON.stringify(base)}, null, [${pairs.join(', ')}])`, loops) });
|
|
461
|
+
return null;
|
|
462
|
+
}
|
|
463
|
+
if (n.inputs.some((i) => i.name === 'class' && i.type === ng.BindingType.Property))
|
|
464
|
+
throw new Error(`${path}: [class] beside [ngClass] on <${n.name}> is not supported in a release build yet`);
|
|
465
|
+
const value = ngClass instanceof ng.TmplAstBoundAttribute ? code(ngClass.value, loops) : ngClass ? JSON.stringify(ngClass.value) : 'null';
|
|
466
|
+
if (selectors.has(n.name)) {
|
|
467
|
+
attrs.push({ name: 'class', method: expr(`${fromRuntime('ngClassNames')}(${JSON.stringify(base)}, ${value}, [${pairs.join(', ')}])`, loops) });
|
|
468
|
+
return null;
|
|
469
|
+
}
|
|
470
|
+
const alias = fromRuntime('NgClass');
|
|
471
|
+
const name = `$d${directiveCount++}`;
|
|
472
|
+
const inner = [...loops, { item: name, param: `${name}: ${alias}` }];
|
|
473
|
+
return {
|
|
474
|
+
name,
|
|
475
|
+
make: expr(`new ${alias}()`, loops),
|
|
476
|
+
inputs: [{ set: handlerOf(`${name}.apply($v)`, [...inner, { item: '$v', param: '$v: any' }]), method: expr(`[${JSON.stringify(base)}, ${value}, [${pairs.join(', ')}]] as any[]`, loops, true) }],
|
|
477
|
+
listeners: [],
|
|
478
|
+
bindings: [],
|
|
479
|
+
attributes: [],
|
|
480
|
+
};
|
|
481
|
+
};
|
|
482
|
+
/**
|
|
483
|
+
* `[ngStyle]`, or an element's `[style.x]` bindings as one NgStyle object (each set by the renderer's setStyle, removed
|
|
484
|
+
* when null), as the runtime's NgStyle directive on the element. A static `style` moves into the first, set before its
|
|
485
|
+
* first styles, as Angular sets the attribute when it makes the element.
|
|
486
|
+
*/
|
|
487
|
+
const styleBindings = (n) => n.inputs.filter((i) => i.type === ng.BindingType.Style && i.name !== 'style');
|
|
488
|
+
// Angular's parser namespaces a bound CSS variable (`--%NS%gap`) for view encapsulation, which NativeScript's styles don't have.
|
|
489
|
+
const styleKey = (i) => JSON.stringify(i.name.replace(/^--%NS%/, '--') + (i.unit ? `.${i.unit}` : ''));
|
|
490
|
+
const styleBindingsUse = (bound, attrs, loops) => ngStyleUse(bound[0], `{ ${bound.map((i) => `${styleKey(i)}: (${code(i.value, loops)})`).join(', ')} }`, attrs, loops);
|
|
491
|
+
const ngStyleUse = (b, value, attrs, loops) => {
|
|
492
|
+
at(b.sourceSpan);
|
|
493
|
+
const alias = fromRuntime('NgStyle');
|
|
494
|
+
usesUnset = true;
|
|
495
|
+
const name = `$d${directiveCount++}`;
|
|
496
|
+
const inner = [...loops, { item: name, param: `${name}: ${alias}` }];
|
|
497
|
+
const fixed = attrs.findIndex((a) => a.name === 'style' && 'value' in a);
|
|
498
|
+
const attributes = fixed >= 0 ? [attrs.splice(fixed, 1)[0]] : [];
|
|
499
|
+
return {
|
|
500
|
+
name,
|
|
501
|
+
make: expr(`new ${alias}($unsetValue)`, loops),
|
|
502
|
+
inputs: [{ set: handlerOf(`${name}.apply($v)`, [...inner, { item: '$v', param: '$v: any' }]), method: expr(`[${value}] as any[]`, loops, true) }],
|
|
503
|
+
listeners: [],
|
|
504
|
+
bindings: [],
|
|
505
|
+
attributes,
|
|
506
|
+
};
|
|
507
|
+
};
|
|
508
|
+
/** The expressions a node evaluates in the view it is in (its children's are theirs): where its pipes are. */
|
|
509
|
+
const ownExpressions = (n) => {
|
|
510
|
+
if (n instanceof ng.TmplAstElement) {
|
|
511
|
+
if (!selectors.has(n.name) && stubbedElement(n.name))
|
|
512
|
+
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);
|
|
513
|
+
return [...n.inputs.map((i) => i.value), ...n.children.flatMap((c) => (c instanceof ng.TmplAstBoundText ? [c.value] : []))];
|
|
514
|
+
}
|
|
515
|
+
// `*ngFor` on an element: the element's own inputs are the template's, evaluated in each view it renders.
|
|
516
|
+
if (n instanceof ng.TmplAstTemplate)
|
|
517
|
+
return [...n.templateAttrs, ...(n.tagName === 'ng-template' ? n.inputs : [])].flatMap((a) => (a instanceof ng.TmplAstBoundAttribute ? [a.value] : []));
|
|
518
|
+
if (n instanceof ng.TmplAstIfBlock)
|
|
519
|
+
return n.branches.flatMap((b) => (b.expression ? [b.expression] : []));
|
|
520
|
+
if (n instanceof ng.TmplAstForLoopBlock)
|
|
521
|
+
return [n.expression];
|
|
522
|
+
if (n instanceof ng.TmplAstSwitchBlock)
|
|
523
|
+
return [n.expression, ...n.groups.flatMap((g) => g.cases.flatMap((c) => (c.expression ? [c.expression] : [])))];
|
|
524
|
+
return [];
|
|
525
|
+
};
|
|
526
|
+
/**
|
|
527
|
+
* The directives of @angular/forms, @angular/common and @angular/router an element's bindings, attributes and outputs
|
|
528
|
+
* select, and events of a global target or an animation, none of which a release build runs: `taken` names those
|
|
529
|
+
* that select an app directive or a hosted component instead.
|
|
530
|
+
*/
|
|
531
|
+
const refuseUnbound = (n, taken) => {
|
|
532
|
+
const written = [
|
|
533
|
+
...n.inputs.map((i) => ({ name: i.name, as: i.type === ng.BindingType.TwoWay ? `[(${i.name})]` : i.type === ng.BindingType.Property ? `[${i.name}]` : null })),
|
|
534
|
+
...n.attributes.map((a) => ({ name: a.name, as: a.name })),
|
|
535
|
+
...n.outputs.filter((o) => o.type === ng.ParsedEventType.Regular && !o.target).map((o) => ({ name: o.name, as: `(${o.name})` })),
|
|
536
|
+
];
|
|
537
|
+
for (const w of written) {
|
|
538
|
+
const what = FORMS_DIRECTIVES.has(w.name) ? '@angular/forms' : UNSUPPORTED_DIRECTIVES[w.name];
|
|
539
|
+
if (w.as && what && !taken(w.name))
|
|
540
|
+
throw new Error(`${path}: ${w.as} (${what}) on <${n.name}> is not supported in a release build yet`);
|
|
541
|
+
}
|
|
542
|
+
for (const o of n.outputs) {
|
|
543
|
+
if (o.type === ng.ParsedEventType.LegacyAnimation)
|
|
544
|
+
throw new Error(`${path}: the animation event (@${o.name}${o.phase ? `.${o.phase}` : ''}) on <${n.name}> is not supported in a release build yet`);
|
|
545
|
+
if (o.type === ng.ParsedEventType.Animation)
|
|
546
|
+
throw new Error(`${path}: the animation event (${o.name}) on <${n.name}> is not supported in a release build yet`);
|
|
547
|
+
if (o.target)
|
|
548
|
+
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`);
|
|
549
|
+
}
|
|
550
|
+
};
|
|
551
|
+
// ---- @angular/forms ----
|
|
552
|
+
/** A forms directive's class, imported into the component's file from @angular/forms (the build's forms runtime). */
|
|
553
|
+
const fromForms = (name) => {
|
|
554
|
+
const names = imported.get('@angular/forms') ?? new Map();
|
|
555
|
+
imported.set('@angular/forms', names);
|
|
556
|
+
if (!names.has(name))
|
|
557
|
+
names.set(name, `$F_${name}`);
|
|
558
|
+
return names.get(name);
|
|
559
|
+
};
|
|
560
|
+
const formsMatcher = new ng.SelectorMatcher();
|
|
561
|
+
for (const [d, selector] of FORMS_SELECTORS)
|
|
562
|
+
formsMatcher.addSelectables(ng.CssSelector.parse(selector), d);
|
|
563
|
+
/** The forms directives an element selects, in the order Angular runs them, as its selectors match. */
|
|
564
|
+
const formsMatched = (n) => {
|
|
565
|
+
const css = new ng.CssSelector();
|
|
566
|
+
css.setElement(n.name);
|
|
567
|
+
for (const a of n.attributes)
|
|
568
|
+
css.addAttribute(a.name, a.value);
|
|
569
|
+
for (const b of [...n.inputs.map((i) => i.name), ...n.outputs.map((o) => o.name)])
|
|
570
|
+
css.addAttribute(b, '');
|
|
571
|
+
const found = new Set();
|
|
572
|
+
formsMatcher.match(css, (_s, d) => { found.add(d); });
|
|
573
|
+
return FORMS_SELECTORS.map(([d]) => d).filter((d) => found.has(d));
|
|
574
|
+
};
|
|
575
|
+
/** The form directives around the element being compiled, innermost last: what Angular injects as its ControlContainer. */
|
|
576
|
+
const formContainers = [];
|
|
577
|
+
/** A member of the component holding a writable signal (`name = signal('')`): `[(ngModel)]` sets it, as Angular's two-way binding does. */
|
|
578
|
+
const signalMember = (name) => cls.members.some((m) => ts.isPropertyDeclaration(m) && m.name.getText() === name
|
|
579
|
+
&& ((!!m.initializer && ts.isCallExpression(m.initializer) && /^(signal|model(\.required)?|linkedSignal)$/.test(m.initializer.expression.getText()))
|
|
580
|
+
|| (!!m.type && /^(WritableSignal|ModelSignal)\b/.test(m.type.getText()))));
|
|
581
|
+
/**
|
|
582
|
+
* The forms directives an element selects, as directive uses after its others: its @nativescript/angular value
|
|
583
|
+
* accessor, validator directives, NgModel, FormControlDirective or FormControlName, form or group directive, and
|
|
584
|
+
* NgControlStatus or NgControlStatusGroup. Each is made with what Angular's injector gives it, the form directive
|
|
585
|
+
* above it found from the template, and each is in scope for what the template compiles after it (`scope`), which
|
|
586
|
+
* is how the directives below it reach a form directive and a template reference names one. Null when it selects none.
|
|
587
|
+
*/
|
|
588
|
+
const formsUses = (n, loops) => {
|
|
589
|
+
// A directive whose module the component doesn't import isn't Angular's on this element: its name is left to the
|
|
590
|
+
// element's other directives, else refused as a binding nothing takes.
|
|
591
|
+
const templateDriven = inScope.has('FormsModule') || inScope.has('NativeScriptFormsModule');
|
|
592
|
+
const reactive = inScope.has('ReactiveFormsModule');
|
|
593
|
+
const found = formsMatched(n).filter((d) => (FORMS_TEMPLATE_DRIVEN.has(d) ? templateDriven : FORMS_VALIDATORS[d] || d === 'DefaultValueAccessor' ? templateDriven || reactive : reactive));
|
|
594
|
+
if (!found.some((d) => FORMS_CONTROLS.has(d) || FORMS_CONTAINERS.has(d) || d === 'DefaultValueAccessor'))
|
|
595
|
+
return null;
|
|
596
|
+
const where = `on <${n.name}>`;
|
|
597
|
+
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);
|
|
598
|
+
/** The input or attribute that selects a directive. */
|
|
599
|
+
const trigger = (d) => d === 'NgModel' ? 'ngModel' : d === 'FormControlDirective' ? 'formControl' : d === 'FormControlName' ? 'formControlName' : d === 'NgForm' ? 'ngForm' : d === 'FormGroupDirective' ? 'formGroup'
|
|
600
|
+
: d === 'FormArrayDirective' ? 'formArray' : d === 'FormGroupName' ? 'formGroupName' : d === 'FormArrayName' ? 'formArrayName' : d === 'NgModelGroup' ? 'ngModelGroup' : FORMS_VALIDATORS[d] ?? '';
|
|
601
|
+
const describe = (d) => {
|
|
602
|
+
const w = writes(trigger(d));
|
|
603
|
+
return !w ? d : w instanceof ng.TmplAstTextAttribute ? w.name : w.type === ng.BindingType.TwoWay ? `[(${w.name})]` : `[${w.name}]`;
|
|
604
|
+
};
|
|
605
|
+
if (found.includes('DefaultValueAccessor'))
|
|
606
|
+
throw new Error(`${path}: ngDefaultControl (@angular/forms' DefaultValueAccessor, which writes an HTML input's value) ${where} is not supported in a release build yet`);
|
|
607
|
+
if (selectors.has(n.name) || hostedBy(n))
|
|
608
|
+
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)`);
|
|
609
|
+
const controls = found.filter((d) => FORMS_CONTROLS.has(d));
|
|
610
|
+
const containers = found.filter((d) => FORMS_CONTAINERS.has(d));
|
|
611
|
+
if (controls.length > 1 || containers.length > 1)
|
|
612
|
+
throw new Error(`${path}: ${[...controls, ...containers].map(describe).join(' and ')} together ${where} are not supported in a release build yet`);
|
|
613
|
+
const control = controls[0];
|
|
614
|
+
const container = containers[0];
|
|
615
|
+
const parent = formContainers.at(-1);
|
|
616
|
+
const consumedInputs = new Set(found.map(trigger));
|
|
617
|
+
if (n.inputs.some((i) => i.name === 'class' && i.type === ng.BindingType.Property))
|
|
618
|
+
throw new Error(`${path}: [class] beside ${describe(found[0])} ${where} is not supported in a release build yet: it would replace the ng-* classes`);
|
|
619
|
+
const consumedOutputs = new Set();
|
|
620
|
+
const refs = new Set();
|
|
621
|
+
const uses = [];
|
|
622
|
+
let scope = loops;
|
|
623
|
+
/** The code of an input's value: its binding's, its attribute's (a string), else undefined. */
|
|
624
|
+
const value = (name) => {
|
|
625
|
+
const w = writes(name);
|
|
626
|
+
if (!w)
|
|
627
|
+
return 'undefined';
|
|
628
|
+
consumedInputs.add(name);
|
|
629
|
+
return w instanceof ng.TmplAstTextAttribute ? JSON.stringify(w.value) : `(${code(w.value, loops)})`;
|
|
630
|
+
};
|
|
631
|
+
const bound = (...names) => `[${names.map((x) => String(!!writes(x))).join(', ')}]`;
|
|
632
|
+
const use = (kind, className, args, extra = () => ({})) => {
|
|
633
|
+
const alias = fromForms(className);
|
|
634
|
+
const name = `$d${directiveCount++}`;
|
|
635
|
+
// A template reference to it by its exportAs (`#f="ngForm"`) names it wherever it is in scope, its own bindings too.
|
|
636
|
+
const named = n.references.filter((r) => kind !== 'accessor' && kind !== 'status' && !!r.value && FORMS_EXPORT_AS[kind] === r.value);
|
|
637
|
+
for (const r of named)
|
|
638
|
+
refs.add(r.name);
|
|
639
|
+
const loop = { item: name, param: `${name}: ${alias}`, ...(named.length ? { names: Object.fromEntries(named.map((r) => [r.name, name])) } : {}) };
|
|
640
|
+
const inner = [...scope, loop];
|
|
641
|
+
const u = { name, make: expr(`new ${alias}(${args(name)})`, scope), inputs: [], listeners: [], bindings: [], attributes: [], exposed: true, ...extra(name, inner) };
|
|
642
|
+
uses.push(u);
|
|
643
|
+
scope = inner;
|
|
644
|
+
return name;
|
|
645
|
+
};
|
|
646
|
+
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) }];
|
|
647
|
+
/** The handlers of the template's `(output)` and `[(input)]` bindings, on the directive's emitter `emitter`. */
|
|
648
|
+
const outputs = (output, emitter, inner) => n.outputs.filter((o) => o.name === output).map((o) => {
|
|
649
|
+
at(o.sourceSpan);
|
|
650
|
+
consumedOutputs.add(o);
|
|
651
|
+
const target = code(o.handler, loops);
|
|
652
|
+
const statement = o.type !== ng.ParsedEventType.TwoWay ? target : /^[A-Za-z_$][\w$]*$/.test(target) && signalMember(target) ? `${target}.set($event)` : `${target} = $event`;
|
|
653
|
+
return { name: emitter, method: handler(statement, inner, true) };
|
|
654
|
+
});
|
|
655
|
+
const unset = () => {
|
|
656
|
+
usesUnset = true;
|
|
657
|
+
return '$unsetValue';
|
|
658
|
+
};
|
|
659
|
+
// The value accessor and the validator directives a control's directive is given.
|
|
660
|
+
let accessorName = null;
|
|
661
|
+
const validatorNames = [];
|
|
662
|
+
if (control) {
|
|
663
|
+
const tag = core.canonical(n.name);
|
|
664
|
+
const accessor = FORMS_ACCESSORS[tag];
|
|
665
|
+
const name = control === 'NgModel' ? 'ngModel' : control === 'FormControlName' ? 'formControlName' : 'formControl';
|
|
666
|
+
const viaAccessor = accessor && (inScope.has('NativeScriptFormsModule') || inScope.has(accessor.accessor));
|
|
667
|
+
if (!viaAccessor) {
|
|
668
|
+
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`}`);
|
|
669
|
+
}
|
|
670
|
+
accessorName = use('accessor', 'NsValueAccessor', () => `${fromRuntime('hostView')}(), ${JSON.stringify(accessor.kind)}, ${unset()}`, (self, inner) => ({
|
|
671
|
+
listeners: [
|
|
672
|
+
{ event: accessor.event, method: handlerOf(`${self}.onChange($event.value)`, [...inner, { item: '$event', param: '$event: any' }]) },
|
|
673
|
+
...(accessor.kind === 'text' ? [{ event: 'blur', method: handlerOf(`${self}.onTouched()`, [...inner, { item: '$event', param: '$event: any' }]) }] : []),
|
|
674
|
+
],
|
|
675
|
+
...(accessor.kind === 'selectedIndex' ? { afterViewInit: handlerOf(`${self}.ngAfterViewInit()`, inner) } : {}),
|
|
676
|
+
}));
|
|
677
|
+
for (const d of found) {
|
|
678
|
+
const input = FORMS_VALIDATORS[d];
|
|
679
|
+
if (!input)
|
|
680
|
+
continue;
|
|
681
|
+
const before = scope;
|
|
682
|
+
validatorNames.push(use(d, d, () => 'true', (self, inner) => ({ inputs: applies([value(input)], self, inner, before) })));
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
const validators = `[${validatorNames.join(', ')}]`;
|
|
686
|
+
/** The structural rules Angular checks when the directives are made, as build errors (its messages). */
|
|
687
|
+
const parentKind = parent?.kind;
|
|
688
|
+
if (control === 'FormControlName' && (!parentKind || !FORMS_REACTIVE_PARENTS.has(parentKind))) {
|
|
689
|
+
if (parentKind === 'NgModelGroup' || parentKind === 'NgForm')
|
|
690
|
+
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.`);
|
|
691
|
+
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).`);
|
|
692
|
+
}
|
|
693
|
+
if ((container === 'FormGroupName' || container === 'FormArrayName') && (!parentKind || !FORMS_REACTIVE_PARENTS.has(parentKind))) {
|
|
694
|
+
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).`);
|
|
695
|
+
}
|
|
696
|
+
if (container === 'NgModelGroup' && parentKind !== 'NgForm' && parentKind !== 'NgModelGroup') {
|
|
697
|
+
throw new Error(`${path}: ngModelGroup ${where}: NG01353: ngModelGroup ${parentKind ? 'cannot be used with a parent formGroup directive' : 'must be used inside an ngForm'}.`);
|
|
698
|
+
}
|
|
699
|
+
const ngModelOptions = writes('ngModelOptions');
|
|
700
|
+
const standalone = !!ngModelOptions && ngModelOptions instanceof ng.TmplAstBoundAttribute && /\bstandalone\s*:\s*true\b/.test(code(ngModelOptions.value, loops));
|
|
701
|
+
if (control === 'NgModel' && parentKind && FORMS_REACTIVE_PARENTS.has(parentKind) && !standalone) {
|
|
702
|
+
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.`);
|
|
703
|
+
}
|
|
704
|
+
if (control === 'NgModel' && parentKind && !FORMS_REACTIVE_PARENTS.has(parentKind) && !writes('name') && !ngModelOptions) {
|
|
705
|
+
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.`);
|
|
706
|
+
}
|
|
707
|
+
const parentRef = control === 'NgModel' && standalone ? 'null' : parent ? parent.name : 'null';
|
|
708
|
+
let controlName = null;
|
|
709
|
+
if (control) {
|
|
710
|
+
const before = scope;
|
|
711
|
+
const acc = accessorName;
|
|
712
|
+
if (control === 'NgModel') {
|
|
713
|
+
controlName = use('NgModel', 'NgModel', () => `${parentRef}, ${validators}, [], ${acc}, ${fromRuntime('viewChecker')}(), ${bound('ngModel', 'name', 'ngModelOptions', 'disabled')}`, (self, inner) => ({
|
|
714
|
+
inputs: applies([value('ngModel'), value('name'), value('ngModelOptions'), value('disabled')], self, inner, before),
|
|
715
|
+
outputs: outputs('ngModelChange', 'update', inner),
|
|
716
|
+
destroy: handlerOf(`${self}.ngOnDestroy()`, inner),
|
|
717
|
+
}));
|
|
718
|
+
}
|
|
719
|
+
else if (control === 'FormControlDirective') {
|
|
720
|
+
consumedInputs.add('disabled');
|
|
721
|
+
controlName = use(control, 'FormControlDirective', () => `${validators}, [], ${acc}, 'always', ${bound('formControl', 'ngModel')}`, (self, inner) => ({
|
|
722
|
+
inputs: applies([value('formControl'), value('ngModel')], self, inner, before),
|
|
723
|
+
outputs: outputs('ngModelChange', 'update', inner),
|
|
724
|
+
destroy: handlerOf(`${self}.ngOnDestroy()`, inner),
|
|
725
|
+
}));
|
|
726
|
+
}
|
|
727
|
+
else {
|
|
728
|
+
consumedInputs.add('disabled');
|
|
729
|
+
controlName = use(control, 'FormControlName', () => `${parent.name}, ${validators}, [], ${acc}, ${bound('formControlName', 'ngModel')}`, (self, inner) => ({
|
|
730
|
+
inputs: applies([value('formControlName'), value('ngModel')], self, inner, before),
|
|
731
|
+
outputs: outputs('ngModelChange', 'update', inner),
|
|
732
|
+
destroy: handlerOf(`${self}.ngOnDestroy()`, inner),
|
|
733
|
+
}));
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
let containerName = null;
|
|
737
|
+
if (container) {
|
|
738
|
+
const before = scope;
|
|
739
|
+
if (container === 'NgForm') {
|
|
740
|
+
containerName = use(container, 'NgForm', () => `[], [], 'always', ${bound('ngFormOptions')}`, (self, inner) => ({
|
|
741
|
+
inputs: applies([value('ngFormOptions')], self, inner, before),
|
|
742
|
+
outputs: outputs('ngSubmit', 'ngSubmit', inner),
|
|
743
|
+
afterViewInit: handlerOf(`${self}.ngAfterViewInit()`, inner),
|
|
744
|
+
}));
|
|
745
|
+
}
|
|
746
|
+
else if (container === 'FormGroupDirective' || container === 'FormArrayDirective') {
|
|
747
|
+
const input = container === 'FormGroupDirective' ? 'formGroup' : 'formArray';
|
|
748
|
+
containerName = use(container, container, () => `[], [], 'always', ${JSON.stringify(input)}, ${bound(input)}`, (self, inner) => ({
|
|
749
|
+
inputs: applies([value(input)], self, inner, before),
|
|
750
|
+
outputs: outputs('ngSubmit', 'ngSubmit', inner),
|
|
751
|
+
destroy: handlerOf(`${self}.ngOnDestroy()`, inner),
|
|
752
|
+
}));
|
|
753
|
+
}
|
|
754
|
+
else {
|
|
755
|
+
const input = container === 'NgModelGroup' ? 'ngModelGroup' : container === 'FormGroupName' ? 'formGroupName' : 'formArrayName';
|
|
756
|
+
containerName = use(container, container, () => `${parent.name}, [], [], ${container === 'FormArrayName'}, ${bound(input)}`, (self, inner) => ({
|
|
757
|
+
inputs: applies([value(input)], self, inner, before),
|
|
758
|
+
init: handlerOf(`${self}.ngOnInit()`, inner),
|
|
759
|
+
destroy: handlerOf(`${self}.ngOnDestroy()`, inner),
|
|
760
|
+
}));
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
// NgControlStatus and NgControlStatusGroup: the ng-* classes, checked with the view.
|
|
764
|
+
const statusOf = controlName ?? containerName;
|
|
765
|
+
if (statusOf) {
|
|
766
|
+
use('status', 'NgControlStatus', () => `${fromRuntime('hostView')}(), ${fromRuntime('viewChecker')}(), ${statusOf}, ${!controlName}`, (self, inner) => ({
|
|
767
|
+
inputs: [{ set: handlerOf(`${self}.check()`, [...inner, { item: '$v', param: '$v: any' }]), method: expr('[] as any[]', inner.slice(0, -1), true) }],
|
|
768
|
+
destroy: handlerOf(`${self}.destroy()`, inner),
|
|
769
|
+
}));
|
|
770
|
+
}
|
|
771
|
+
return { uses, scope, consumedInputs, consumedOutputs, refs, container: containerName ? { kind: container, name: containerName } : null, status: !!statusOf };
|
|
772
|
+
};
|
|
773
|
+
const nodes = (list, loops) => {
|
|
774
|
+
const out = [];
|
|
775
|
+
// `@let name = expression`: the expression wherever the name is read after it in this block.
|
|
776
|
+
const declared = [];
|
|
777
|
+
for (let k = 0; k < list.length; k++) {
|
|
778
|
+
const n = list[k];
|
|
779
|
+
if (n instanceof ng.TmplAstLetDeclaration) {
|
|
780
|
+
at(n.sourceSpan);
|
|
781
|
+
// A pipe in a `@let` is one per view: the rest of the block is in its scope.
|
|
782
|
+
const piped = withPipes([n.value], loops);
|
|
783
|
+
aliases.set(n.name, core.rewrite(clean(code(n.value, piped.loops)), local(piped.loops)));
|
|
784
|
+
declared.push(n.name);
|
|
785
|
+
if (piped.loops !== loops) {
|
|
786
|
+
out.push(...piped.wrap(nodes(list.slice(k + 1), piped.loops)));
|
|
787
|
+
break;
|
|
788
|
+
}
|
|
789
|
+
continue;
|
|
790
|
+
}
|
|
791
|
+
const piped = withPipes(ownExpressions(n), loops);
|
|
792
|
+
if (piped.loops !== loops) {
|
|
793
|
+
out.push(...piped.wrap(nodes([n], piped.loops)));
|
|
794
|
+
continue;
|
|
795
|
+
}
|
|
796
|
+
if (n instanceof ng.TmplAstElement && !selectors.has(n.name) && PLATFORM_FILTERS[n.name]) {
|
|
797
|
+
at(n.startSourceSpan);
|
|
798
|
+
// @nativescript/angular's AndroidFilterComponent and its kin: `@if (show) { <ng-content> }` in a ProxyViewContainer.
|
|
799
|
+
if (n.attributes.length || n.inputs.length || n.outputs.length || n.references.length)
|
|
800
|
+
throw new Error(`${path}: <${n.name}> takes no attributes or bindings in a release build`);
|
|
801
|
+
if (PLATFORM_FILTERS[n.name].includes(options.platform ?? 'ios'))
|
|
802
|
+
out.push(...nodes(n.children, loops));
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
if (n instanceof ng.TmplAstElement && n.name === 'ng-container') {
|
|
806
|
+
at(n.startSourceSpan);
|
|
807
|
+
out.push(...container(n, loops));
|
|
808
|
+
continue;
|
|
809
|
+
}
|
|
810
|
+
if (n instanceof ng.TmplAstElement && !selectors.has(n.name) && stubbedElement(n.name)) {
|
|
811
|
+
at(n.startSourceSpan);
|
|
812
|
+
const attrs = [];
|
|
813
|
+
for (const a of n.attributes)
|
|
814
|
+
if (STUB_LAYOUT_ATTRS.has(a.name))
|
|
815
|
+
attrs.push({ name: a.name, value: a.value });
|
|
816
|
+
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'));
|
|
817
|
+
const styled = n.inputs.find((i) => i.name === 'ngStyle' && i.type === ng.BindingType.Property);
|
|
818
|
+
const stubDirectives = [...(classed ? [classed] : []), ...(styled ? [ngStyleUse(styled, code(styled.value, loops), attrs, loops)] : [])];
|
|
819
|
+
if (styleBindings(n).length)
|
|
820
|
+
stubDirectives.push(styleBindingsUse(styleBindings(n), attrs, loops));
|
|
821
|
+
for (const i of n.inputs) {
|
|
822
|
+
if (i.type === ng.BindingType.Class || i.type === ng.BindingType.Style)
|
|
823
|
+
continue;
|
|
824
|
+
if ((i.type === ng.BindingType.Property || i.type === ng.BindingType.Attribute) && STUB_LAYOUT_ATTRS.has(i.name)) {
|
|
825
|
+
at(i.sourceSpan);
|
|
826
|
+
const root = i.value instanceof ng.ASTWithSource ? i.value.ast : i.value;
|
|
827
|
+
const chained = root instanceof ng.SafePropertyRead || root instanceof ng.SafeKeyedRead || root instanceof ng.SafeCall;
|
|
828
|
+
attrs.push({ name: i.name, method: expr(code(i.value, loops), loops, chained) });
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
const refs = n.references.map((r) => r.name);
|
|
832
|
+
const hooks = queryHooks(refs, null, 'ContentView', loops);
|
|
833
|
+
const statics = hooks.length ? queries.filter((q) => q.static && q.ref && refs.includes(q.ref) && staticRefs.has(q.ref)) : [];
|
|
834
|
+
for (const q of statics)
|
|
835
|
+
staticQueries.delete(q);
|
|
836
|
+
const late = statics.length > 0 && staticQueries.size === 0;
|
|
837
|
+
out.push({ kind: 'element', tag: 'ContentView', attrs, events: [], children: [], ...(hooks.length ? { queries: hooks } : {}), ...(late ? { init: true } : {}), ...(stubDirectives.length ? { directives: stubDirectives } : {}) });
|
|
838
|
+
if (late)
|
|
839
|
+
lateInit = true;
|
|
840
|
+
continue;
|
|
841
|
+
}
|
|
842
|
+
if (n instanceof ng.TmplAstElement) {
|
|
843
|
+
at(n.startSourceSpan);
|
|
844
|
+
const attrs = [];
|
|
845
|
+
const events = [];
|
|
846
|
+
// A ListView, or a plugin view taking item templates (`<Pager>` with `<ng-template let-item>`), renders rows from templates.
|
|
847
|
+
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));
|
|
848
|
+
// The component an attribute selects renders its template into the element; its inputs and outputs are bound
|
|
849
|
+
// on it, the element's properties and events beside them.
|
|
850
|
+
const hosted = selectors.has(n.name) ? undefined : hostedBy(n);
|
|
851
|
+
const hostProps = [];
|
|
852
|
+
const hostEvents = [];
|
|
853
|
+
if (hosted) {
|
|
854
|
+
const unsupported = (what) => new Error(`${path}: ${what} on <${n.name}>, the host of ${hosted.name}, is not supported in a release build yet`);
|
|
855
|
+
if (hosted.readsHost)
|
|
856
|
+
throw unsupported(`${hosted.name}'s own ElementRef or host bindings`);
|
|
857
|
+
if (isList)
|
|
858
|
+
throw unsupported('item templates');
|
|
859
|
+
if (n.children.some((c) => !(c instanceof ng.TmplAstText) || c.value.trim()))
|
|
860
|
+
throw unsupported('content');
|
|
861
|
+
for (const i of n.inputs)
|
|
862
|
+
if (hosted.inputs.has(i.name) && i.type === ng.BindingType.TwoWay)
|
|
863
|
+
throw unsupported(`[(${i.name})]`);
|
|
864
|
+
for (const o of n.outputs)
|
|
865
|
+
if (hosted.models.has(o.name.replace(/Change$/, '')))
|
|
866
|
+
throw unsupported(`(${o.name})`);
|
|
867
|
+
}
|
|
868
|
+
// @angular/forms' directives, made after the element's others: what the template compiles after each reads it.
|
|
869
|
+
const forms = formsUses(n, loops);
|
|
870
|
+
const scoped = forms?.scope ?? loops;
|
|
871
|
+
const link = routerLink(n, scoped);
|
|
872
|
+
if (link)
|
|
873
|
+
events.push(link);
|
|
874
|
+
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)]);
|
|
875
|
+
// An app directive or the hosted component taking NgClass's or NgStyle's input name is what that binding sets.
|
|
876
|
+
const appOwns = (name) => found.some((d) => d.inputs.has(name)) || !!hosted?.inputs.has(name);
|
|
877
|
+
for (const a of n.attributes) {
|
|
878
|
+
if (link && ROUTER_LINK_INPUTS.has(a.name))
|
|
879
|
+
continue;
|
|
880
|
+
if (a.name === 'ngClass' && !appOwns('ngClass'))
|
|
881
|
+
continue;
|
|
882
|
+
// A static attribute is the element's too, as Angular writes every one to its host.
|
|
883
|
+
attrs.push({ name: a.name, value: a.value });
|
|
884
|
+
if (hosted?.inputs.has(a.name))
|
|
885
|
+
hostProps.push({ name: a.name, value: a.value });
|
|
886
|
+
}
|
|
887
|
+
for (const c of n.children) {
|
|
888
|
+
if (c instanceof ng.TmplAstText && c.value.trim())
|
|
889
|
+
attrs.push({ name: 'text', value: c.value });
|
|
890
|
+
if (c instanceof ng.TmplAstBoundText) {
|
|
891
|
+
at(c.sourceSpan);
|
|
892
|
+
attrs.push({ name: 'text', method: expr(code(c.value, scoped), scoped) });
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
// The static classes, `[class.on]="cond"` toggles and NgClass: one bound `class` naming them all.
|
|
896
|
+
const ngClass = appOwns('ngClass') ? undefined : n.inputs.find((i) => i.name === 'ngClass' && i.type === ng.BindingType.Property) ?? n.attributes.find((a) => a.name === 'ngClass');
|
|
897
|
+
const ngClassUse = classAttr(n, attrs, loops, ngClass, !!forms?.status);
|
|
898
|
+
const ngStyle = appOwns('ngStyle') || selectors.has(n.name) ? undefined : n.inputs.find((i) => i.name === 'ngStyle' && i.type === ng.BindingType.Property);
|
|
899
|
+
// NgSwitch on any element: the cases below it, in its subtree, compare with its value.
|
|
900
|
+
const switched = n.inputs.find((i) => i.name === 'ngSwitch');
|
|
901
|
+
if (found.length && selectors.has(n.name))
|
|
902
|
+
throw new Error(`${path}: the directive ${found[0].className} on the component <${n.name}> is not supported in a release build yet`);
|
|
903
|
+
const consumed = new Set();
|
|
904
|
+
const directives = found.map((d) => {
|
|
905
|
+
if (d.structural)
|
|
906
|
+
throw new Error(`${path}: the structural directive ${d.className} without its template (*) is not supported in a release build yet`);
|
|
907
|
+
return directiveUse(d, n, loops, consumed);
|
|
908
|
+
});
|
|
909
|
+
refuseUnbound(n, (name) => found.some((d) => d.inputs.has(name)) || !!hosted?.inputs.has(name) || !!hosted?.outputs.has(name) || (name === 'ngClass' && !!ngClass) || (name === 'ngStyle' && !!ngStyle)
|
|
910
|
+
|| !!forms?.consumedInputs.has(name) || [...(forms?.consumedOutputs ?? [])].some((o) => o.name === name));
|
|
911
|
+
if (ngClassUse)
|
|
912
|
+
directives.push(ngClassUse);
|
|
913
|
+
if (ngStyle)
|
|
914
|
+
directives.push(ngStyleUse(ngStyle, code(ngStyle.value, loops), attrs, loops));
|
|
915
|
+
if (!selectors.has(n.name) && styleBindings(n).length)
|
|
916
|
+
directives.push(styleBindingsUse(styleBindings(n), attrs, loops));
|
|
917
|
+
if (forms)
|
|
918
|
+
directives.push(...forms.uses);
|
|
919
|
+
if (!selectors.has(n.name) && !hosted) {
|
|
920
|
+
const ref = n.references.find((r) => r.value && !forms?.refs.has(r.name));
|
|
921
|
+
if (ref)
|
|
922
|
+
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`);
|
|
923
|
+
}
|
|
924
|
+
for (const i of n.inputs) {
|
|
925
|
+
if (i === switched || i === ngClass || i === ngStyle || 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)))
|
|
926
|
+
continue;
|
|
927
|
+
at(i.sourceSpan);
|
|
928
|
+
if (hosted?.inputs.has(i.name) && i.type === ng.BindingType.Property) {
|
|
929
|
+
hostProps.push({ name: i.name, method: expr(code(i.value, scoped), scoped) });
|
|
930
|
+
continue;
|
|
931
|
+
}
|
|
932
|
+
if (i.type === ng.BindingType.Style && i.name !== 'style' && !selectors.has(n.name))
|
|
933
|
+
continue;
|
|
934
|
+
// `[attr.name]`: the renderer's setAttribute, which on a NativeScript view sets the property of that name.
|
|
935
|
+
if (i.type === ng.BindingType.Attribute && !selectors.has(n.name)) {
|
|
936
|
+
attrs.push({ name: i.name, method: expr(code(i.value, scoped), scoped, true) });
|
|
937
|
+
continue;
|
|
938
|
+
}
|
|
939
|
+
if (i.type !== ng.BindingType.Property && i.type !== ng.BindingType.TwoWay)
|
|
940
|
+
throw new Error(`${path}: the [${ng.BindingType[i.type].toLowerCase()}.${i.name}] binding is not supported in a release build yet`);
|
|
941
|
+
// `[text]="person()?.name"`: the view takes undefined where the chain stops, as the renderer passes it, whatever the type says.
|
|
942
|
+
const root = i.value instanceof ng.ASTWithSource ? i.value.ast : i.value;
|
|
943
|
+
const chained = i.type === ng.BindingType.Property && !selectors.has(n.name) && (root instanceof ng.SafePropertyRead || root instanceof ng.SafeKeyedRead || root instanceof ng.SafeCall);
|
|
944
|
+
attrs.push({ name: i.name, method: expr(code(i.value, scoped), scoped, chained) });
|
|
945
|
+
}
|
|
946
|
+
for (const o of n.outputs) {
|
|
947
|
+
if (forms?.consumedOutputs.has(o))
|
|
948
|
+
continue;
|
|
949
|
+
at(o.sourceSpan);
|
|
950
|
+
if (hosted?.outputs.has(o.name)) {
|
|
951
|
+
hostEvents.push({ name: o.name, method: handler(code(o.handler, scoped), scoped, true), payload: true });
|
|
952
|
+
continue;
|
|
953
|
+
}
|
|
954
|
+
events.push({ name: o.name, method: handler(code(o.handler, scoped), scoped, selectors.has(n.name)), ...(selectors.has(n.name) ? { payload: true } : {}) });
|
|
955
|
+
}
|
|
956
|
+
const component = selectors.get(n.name);
|
|
957
|
+
const refs = n.references.map((r) => r.name);
|
|
958
|
+
if (component) {
|
|
959
|
+
const hooks = queryHooks(refs, component, null, loops);
|
|
960
|
+
out.push({ kind: 'component', name: component, props: attrs, events, ...(hooks.length ? { queries: hooks } : {}) });
|
|
961
|
+
continue;
|
|
962
|
+
}
|
|
963
|
+
if (n.name === 'page-router-outlet') {
|
|
964
|
+
// The outlet's Frame takes its name, and the static attributes @nativescript/angular sets on that Frame.
|
|
965
|
+
const passed = (a) => a.name === 'actionBarVisibility' || a.name === 'class';
|
|
966
|
+
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}"`)];
|
|
967
|
+
if (other.length)
|
|
968
|
+
throw new Error(`${path}: ${other[0]} on <page-router-outlet> is not supported in a release build yet`);
|
|
969
|
+
// `actionBarVisibility="auto"` is the Frame's default.
|
|
970
|
+
const frameAttrs = n.attributes.filter((a) => passed(a) && !(a.name === 'actionBarVisibility' && a.value === 'auto')).map((a) => ({ name: a.name, value: a.value }));
|
|
971
|
+
out.push({ kind: 'element', tag: 'Frame', attrs: [{ name: 'router', value: n.attributes.find((a) => a.name === 'name')?.value ?? 'primary' }, ...frameAttrs], events: [], children: [] });
|
|
972
|
+
continue;
|
|
973
|
+
}
|
|
974
|
+
const tag = elementOf(n.name);
|
|
975
|
+
if (!tag)
|
|
976
|
+
throw new Error(`${path}: <${n.name}> is not a @nativescript/core element the release build knows`);
|
|
977
|
+
checkMeta(n);
|
|
978
|
+
const sections = isList && isSectioned(n);
|
|
979
|
+
// A reference on a host names its component; ElementRef and the view's class read the element.
|
|
980
|
+
const matches = queryHooks(refs.filter((r) => !forms?.refs.has(r)), hosted?.name ?? null, tag, loops);
|
|
981
|
+
const hooks = matches.filter((h) => h.on !== 'instance');
|
|
982
|
+
const own = matches.filter((h) => h.on === 'instance');
|
|
983
|
+
const below = () => (isList ? listTemplates(n, attrs, scoped) : hosted ? [{ kind: 'component', name: hosted.name, props: hostProps, events: hostEvents, ...(own.length ? { queries: own } : {}) }] : nodes(n.children, scoped));
|
|
984
|
+
// A form or group directive is the ControlContainer of the forms directives below it.
|
|
985
|
+
const children = () => {
|
|
986
|
+
if (forms?.container)
|
|
987
|
+
formContainers.push(forms.container);
|
|
988
|
+
try {
|
|
989
|
+
return below();
|
|
990
|
+
}
|
|
991
|
+
finally {
|
|
992
|
+
if (forms?.container)
|
|
993
|
+
formContainers.pop();
|
|
994
|
+
}
|
|
995
|
+
};
|
|
996
|
+
// A static query is resolved when the template's views are made, before ngOnInit: ngOnInit runs once the last element one names is.
|
|
997
|
+
const statics = matches.length ? queries.filter((q) => q.static && q.ref && refs.includes(q.ref) && staticRefs.has(q.ref)) : [];
|
|
998
|
+
for (const q of statics)
|
|
999
|
+
staticQueries.delete(q);
|
|
1000
|
+
const late = statics.length > 0 && staticQueries.size === 0;
|
|
1001
|
+
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 } : {}) });
|
|
1002
|
+
if (late)
|
|
1003
|
+
lateInit = true;
|
|
1004
|
+
// The nodes after it read its forms directives too (a template reference to one), as the codegen scopes them.
|
|
1005
|
+
if (forms) {
|
|
1006
|
+
out.push(...nodes(list.slice(k + 1), scoped));
|
|
1007
|
+
break;
|
|
1008
|
+
}
|
|
1009
|
+
continue;
|
|
1010
|
+
}
|
|
1011
|
+
if (n instanceof ng.TmplAstIfBlock) {
|
|
1012
|
+
out.push({ kind: 'if', branches: n.branches.map((b) => {
|
|
1013
|
+
at(b.startSourceSpan);
|
|
1014
|
+
// `@if (x; as y)`: y is the condition's value in the branch.
|
|
1015
|
+
const alias = b.expressionAlias;
|
|
1016
|
+
// The condition is read before its alias exists: `@if (person(); as person)` names the value of the `person` it reads.
|
|
1017
|
+
const cond = b.expression ? test(code(b.expression, loops), loops) : null;
|
|
1018
|
+
if (alias && b.expression)
|
|
1019
|
+
aliases.set(alias.name, core.rewrite(clean(code(b.expression, loops)), local(loops)));
|
|
1020
|
+
const branch = { cond, body: nodes(b.children, loops) };
|
|
1021
|
+
if (alias)
|
|
1022
|
+
aliases.delete(alias.name);
|
|
1023
|
+
return branch;
|
|
1024
|
+
}) });
|
|
1025
|
+
continue;
|
|
1026
|
+
}
|
|
1027
|
+
if (n instanceof ng.TmplAstForLoopBlock) {
|
|
1028
|
+
at(n.startSourceSpan);
|
|
1029
|
+
const item = n.item.name;
|
|
1030
|
+
// The index is a parameter of its own: nested loops each have a `$index`.
|
|
1031
|
+
const index = `$i${loops.length}`;
|
|
1032
|
+
const items = expr(code(n.expression, loops), loops);
|
|
1033
|
+
const count = `this.${items}(${args(loops)}).length`;
|
|
1034
|
+
const context = { $index: index, $count: count, $first: `(${index} === 0)`, $last: `(${index} === ${count} - 1)`, $even: `(${index} % 2 === 0)`, $odd: `(${index} % 2 !== 0)` };
|
|
1035
|
+
const names = {};
|
|
1036
|
+
for (const v of n.contextVariables)
|
|
1037
|
+
names[v.name] = context[v.value];
|
|
1038
|
+
const loop = { item, index, param: `${item} = this.${items}(${args(loops)})[0], ${index} = 0`, names };
|
|
1039
|
+
const inner = [...loops, loop];
|
|
1040
|
+
out.push({ kind: 'for', items, key: expr(sourceOf(n.trackBy), inner), item, index, body: nodes(n.children, inner) });
|
|
1041
|
+
if (n.empty) {
|
|
1042
|
+
at(n.empty.startSourceSpan);
|
|
1043
|
+
out.push({ kind: 'if', branches: [{ cond: test(`${count} === 0`, loops), body: nodes(n.empty.children, loops) }] });
|
|
1044
|
+
}
|
|
1045
|
+
continue;
|
|
1046
|
+
}
|
|
1047
|
+
if (n instanceof ng.TmplAstTemplate && n.templateAttrs.some((a) => a.name === 'tabItem')) {
|
|
1048
|
+
out.push(tabItem(n, loops));
|
|
1049
|
+
continue;
|
|
1050
|
+
}
|
|
1051
|
+
if (n instanceof ng.TmplAstTemplate) {
|
|
1052
|
+
out.push(...structural(n, loops));
|
|
1053
|
+
continue;
|
|
1054
|
+
}
|
|
1055
|
+
if (n instanceof ng.TmplAstSwitchBlock) {
|
|
1056
|
+
const subject = code(n.expression, loops);
|
|
1057
|
+
at(n.startSourceSpan);
|
|
1058
|
+
const branches = n.groups.map((g) => {
|
|
1059
|
+
const tests = g.cases.filter((c) => c.expression).map((c) => `(${subject}) === (${code(c.expression, loops)})`);
|
|
1060
|
+
return { cond: tests.length ? expr(tests.join(' || '), loops) : null, body: nodes(g.children, loops) };
|
|
1061
|
+
});
|
|
1062
|
+
// The default group renders when no case matches, wherever it is written.
|
|
1063
|
+
out.push({ kind: 'if', branches: [...branches.filter((b) => b.cond), ...branches.filter((b) => !b.cond)] });
|
|
1064
|
+
continue;
|
|
1065
|
+
}
|
|
1066
|
+
// Text in an element is its `text` (@nativescript/angular's renderer sets it on the parent): a template's text nodes bind there.
|
|
1067
|
+
if (n instanceof ng.TmplAstText || n instanceof ng.TmplAstBoundText)
|
|
1068
|
+
continue;
|
|
1069
|
+
throw new Error(`${path}: ${n.constructor.name} in a template is not supported in a release build yet`);
|
|
1070
|
+
}
|
|
1071
|
+
for (const name of declared)
|
|
1072
|
+
aliases.delete(name);
|
|
1073
|
+
return out;
|
|
1074
|
+
};
|
|
1075
|
+
/**
|
|
1076
|
+
* `<ListView [items]>` with `<ng-template let-item let-i="index" nsTemplateKey="…">` children, as
|
|
1077
|
+
* @nativescript/angular's ListViewComponent renders them: the first template is also the default, and
|
|
1078
|
+
* `[itemTemplateSelector]` is called with `(item, index, items)`. A `<Pager>` (@nstudio/nativescript-ui-pager's
|
|
1079
|
+
* PagerComponent) is the same with `pagerTemplateKey`.
|
|
1080
|
+
*/
|
|
1081
|
+
const listTemplates = (n, attrs, loops) => {
|
|
1082
|
+
const host = elementOf(n.name) ?? n.name;
|
|
1083
|
+
const keyName = host === 'Pager' ? 'pagerTemplateKey' : 'nsTemplateKey';
|
|
1084
|
+
const items = attrs.find((a) => a.name === 'items');
|
|
1085
|
+
if (!items || !('method' in items))
|
|
1086
|
+
throw new Error(`${path}: <${host}> needs [items]`);
|
|
1087
|
+
const list = `this.${items.method}(${args(loops)})`;
|
|
1088
|
+
// A sectioned ListView's items are sections (`{ title, items }`); a row's item is one of a section's.
|
|
1089
|
+
const sectioned = isSectioned(n);
|
|
1090
|
+
const rows = sectioned ? `${list}[0].items` : list;
|
|
1091
|
+
const selector = n.inputs.find((i) => i.name === 'itemTemplateSelector');
|
|
1092
|
+
if (selector) {
|
|
1093
|
+
const m = `$b${next++}`;
|
|
1094
|
+
const p = [params(loops), `$item = ${rows}[0]`, '$index = 0'].filter(Boolean).join(', ');
|
|
1095
|
+
// Called as core calls it, with (item, index, items): a method of the component that declares fewer takes the ones it declares.
|
|
1096
|
+
const name = sourceOf(selector.value).trim();
|
|
1097
|
+
const member = cls.members.find((x) => (ts.isMethodDeclaration(x) || ts.isPropertyDeclaration(x)) && x.name.getText() === name);
|
|
1098
|
+
// A method, or a property holding an arrow (`rowTemplate = (row) => …`): the parameters it declares.
|
|
1099
|
+
const fn = member && ts.isMethodDeclaration(member) ? member : member && ts.isPropertyDeclaration(member) && member.initializer && (ts.isArrowFunction(member.initializer) || ts.isFunctionExpression(member.initializer)) ? member.initializer : undefined;
|
|
1100
|
+
const given = ['$item', '$index', list].slice(0, fn ? fn.parameters.length : 3);
|
|
1101
|
+
at(selector.sourceSpan);
|
|
1102
|
+
add(` ${m}(${p}): string { return ${core.rewrite(clean(sourceOf(selector.value)), local(loops))}(${given.join(', ')}); }`);
|
|
1103
|
+
attrs.push({ name: 'itemTemplateSelector', method: m });
|
|
1104
|
+
}
|
|
1105
|
+
const out = [];
|
|
1106
|
+
for (const t of n.children) {
|
|
1107
|
+
if (t instanceof ng.TmplAstText)
|
|
1108
|
+
continue;
|
|
1109
|
+
if (!(t instanceof ng.TmplAstTemplate) || t.tagName !== 'ng-template')
|
|
1110
|
+
throw new Error(`${path}: a ${host}'s children are <ng-template let-item> item templates`);
|
|
1111
|
+
const bound = t.inputs.find((i) => i.name === keyName);
|
|
1112
|
+
const key = t.attributes.find((a) => a.name === keyName)?.value ?? (bound ? literalKey(sourceOf(bound.value), path) : out.length ? null : 'default');
|
|
1113
|
+
if (key === null)
|
|
1114
|
+
throw new Error(`${path}: a ${host}'s second and later <ng-template>s need a ${keyName}`);
|
|
1115
|
+
if (t.inputs.some((i) => i.name === 'nsTemplateKeys'))
|
|
1116
|
+
throw new Error(`${path}: nsTemplateKeys is not supported in a release build yet`);
|
|
1117
|
+
const named = (v) => t.variables.find((x) => (x.value || '$implicit') === v)?.name;
|
|
1118
|
+
const item = named('$implicit') ?? named('item') ?? `$item${loops.length}`;
|
|
1119
|
+
const index = named('index') ?? `$i${loops.length}`;
|
|
1120
|
+
const names = {};
|
|
1121
|
+
for (const v of t.variables) {
|
|
1122
|
+
const what = v.value || '$implicit';
|
|
1123
|
+
if ((what === '$implicit' || what === 'item') && v.name !== item)
|
|
1124
|
+
names[v.name] = item;
|
|
1125
|
+
else if (what === 'even')
|
|
1126
|
+
names[v.name] = `(${index} % 2 === 0)`;
|
|
1127
|
+
else if (what === 'odd')
|
|
1128
|
+
names[v.name] = `(${index} % 2 !== 0)`;
|
|
1129
|
+
else if (!['$implicit', 'item', 'index'].includes(what))
|
|
1130
|
+
throw new Error(`${path}: a ${host} template's "${what}" is not part of its context`);
|
|
1131
|
+
}
|
|
1132
|
+
// Keyed templates tell apart the kinds of row a list mixes (`Person | typeof BYLINE_ROW`): each reads its row
|
|
1133
|
+
// untyped, as Angular types an ng-template's context.
|
|
1134
|
+
const keyed = n.children.filter((c) => c instanceof ng.TmplAstTemplate).length > 1;
|
|
1135
|
+
const loop = { item, index, param: `${item}${keyed ? ': any' : ''} = ${rows}[0], ${index} = 0`, names };
|
|
1136
|
+
out.push({ kind: 'template', key, item, index, body: nodes(t.children, [...loops, loop]) });
|
|
1137
|
+
}
|
|
1138
|
+
const header = attrs.findIndex((a) => a.name === 'stickyHeaderTemplate');
|
|
1139
|
+
if (header >= 0) {
|
|
1140
|
+
attrs.splice(header, 1);
|
|
1141
|
+
if (sectioned)
|
|
1142
|
+
out.push(stickyHeader(n, list, loops));
|
|
1143
|
+
}
|
|
1144
|
+
return out;
|
|
1145
|
+
};
|
|
1146
|
+
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');
|
|
1147
|
+
/**
|
|
1148
|
+
* `[stickyHeaderTemplate]` naming a field that holds NativeScript XML (core parses it with `Builder.parse`
|
|
1149
|
+
* and binds it to the section): the XML as a header template whose `{{ path }}` bindings read the section.
|
|
1150
|
+
*/
|
|
1151
|
+
const stickyHeader = (n, list, loops) => {
|
|
1152
|
+
const input = n.inputs.find((i) => i.name === 'stickyHeaderTemplate');
|
|
1153
|
+
const name = input && sourceOf(input.value).trim().replace(/^this\./, '');
|
|
1154
|
+
const field = name ? cls.members.find((m) => ts.isPropertyDeclaration(m) && m.name.getText() === name) : undefined;
|
|
1155
|
+
const init = field?.initializer;
|
|
1156
|
+
const xml = n.attributes.find((a) => a.name === 'stickyHeaderTemplate')?.value
|
|
1157
|
+
?? (init && (ts.isStringLiteral(init) || ts.isNoSubstitutionTemplateLiteral(init)) ? init.text : undefined);
|
|
1158
|
+
if (xml === undefined)
|
|
1159
|
+
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`);
|
|
1160
|
+
const section = `$section${loops.length}`;
|
|
1161
|
+
const read = (e) => {
|
|
1162
|
+
if (!/^\s*[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*\s*$/.test(e))
|
|
1163
|
+
throw new Error(`${path}: the sticky header binding {{${e}}} is not supported in a release build yet (a property path is)`);
|
|
1164
|
+
return `${section}.${e.trim()}`;
|
|
1165
|
+
};
|
|
1166
|
+
const bound = xml.replace(/([\w.-]+)\s*=\s*(['"])([^'"]*\{\{[^'"]*)\2/g, (_m, attr, _q, value) => {
|
|
1167
|
+
const parts = value.split(/\{\{(.*?)\}\}/);
|
|
1168
|
+
const whole = parts.length === 3 && !parts[0] && !parts[2];
|
|
1169
|
+
const code = whole ? read(parts[1]) : '`' + parts.map((p, i) => (i % 2 ? '${' + read(p) + '}' : p.replace(/[`\\$]/g, (x) => '\\' + x))).join('') + '`';
|
|
1170
|
+
return `[${attr}]="${code}"`;
|
|
1171
|
+
});
|
|
1172
|
+
// XML closes any element with `/>`; Angular's parser only void and custom ones.
|
|
1173
|
+
const closed = bound.replace(/<([A-Za-z][\w.-]*)((?:\s+[^<>]*?)?)\s*\/>/g, '<$1$2></$1>');
|
|
1174
|
+
if (bound.includes('{{'))
|
|
1175
|
+
throw new Error(`${path}: a stickyHeaderTemplate binds attributes only in a release build`);
|
|
1176
|
+
const parsed = ng.parseTemplate(closed, path + '.stickyHeader.html', { preserveWhitespaces: false });
|
|
1177
|
+
// Its spans are the header string's, not the template's: its methods keep the template line of the list.
|
|
1178
|
+
const saved = here;
|
|
1179
|
+
const first = methods.length;
|
|
1180
|
+
if (parsed.errors?.length)
|
|
1181
|
+
throw new Error(`${path}: stickyHeaderTemplate: ${parsed.errors[0]}`);
|
|
1182
|
+
const loop = { item: section, index: `$s${loops.length}`, param: `${section} = ${list}[0], $s${loops.length} = 0` };
|
|
1183
|
+
const body = nodes(parsed.nodes, [...loops, loop]);
|
|
1184
|
+
for (let k = first; k < methods.length; k++)
|
|
1185
|
+
if (saved === null)
|
|
1186
|
+
located.delete(k);
|
|
1187
|
+
else
|
|
1188
|
+
located.set(k, saved);
|
|
1189
|
+
here = saved;
|
|
1190
|
+
if (body.length !== 1 || body[0].kind !== 'element')
|
|
1191
|
+
throw new Error(`${path}: a stickyHeaderTemplate needs exactly one root element`);
|
|
1192
|
+
return { kind: 'template', key: '$header', item: section, index: loop.index, body, header: true, xml };
|
|
1193
|
+
};
|
|
1194
|
+
/** `*tabItem="{ title, iconSource, … }"` (TabViewItemDirective): a TabViewItem with those properties around the element. */
|
|
1195
|
+
const tabItem = (t, loops) => {
|
|
1196
|
+
at(t.startSourceSpan);
|
|
1197
|
+
const bound = t.templateAttrs.find((a) => a instanceof ng.TmplAstBoundAttribute && a.name === 'tabItem');
|
|
1198
|
+
const root = bound && (bound.value instanceof ng.ASTWithSource ? bound.value.ast : bound.value);
|
|
1199
|
+
if (!(root instanceof ng.LiteralMap))
|
|
1200
|
+
throw new Error(`${path}: *tabItem takes an object literal in a release build`);
|
|
1201
|
+
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) }));
|
|
1202
|
+
return { kind: 'element', tag: 'TabViewItem', attrs, events: [], children: nodes(t.children, loops) };
|
|
1203
|
+
};
|
|
1204
|
+
/**
|
|
1205
|
+
* `<ng-container>`, a comment in Angular's view: its children join its parent, and its attributes only select
|
|
1206
|
+
* directives. `[ngSwitch]` and `[ngTemplateOutlet]` are the directives it takes; the outlet's view follows the
|
|
1207
|
+
* container's own children, as a ViewContainerRef inserts at its anchor.
|
|
1208
|
+
*/
|
|
1209
|
+
const container = (n, loops) => {
|
|
1210
|
+
if (n.outputs.length)
|
|
1211
|
+
throw new Error(`${path}: (${n.outputs[0].name}) on <ng-container> is not supported in a release build yet`);
|
|
1212
|
+
if (n.references.length)
|
|
1213
|
+
throw new Error(`${path}: #${n.references[0].name} on <ng-container> is not supported in a release build yet`);
|
|
1214
|
+
refuseUnbound(n, (name) => ['ngTemplateOutlet', 'ngTemplateOutletContext'].includes(name));
|
|
1215
|
+
const selected = matched('ng-container', n.attributes.map((a) => [a.name, a.value]), n.inputs.map((i) => i.name));
|
|
1216
|
+
if (selected.length)
|
|
1217
|
+
throw new Error(`${path}: the directive ${selected[0].className} on <ng-container> is not supported in a release build yet`);
|
|
1218
|
+
const bound = new Map(n.inputs.map((i) => [i.name, i]));
|
|
1219
|
+
for (const name of bound.keys()) {
|
|
1220
|
+
if (!['ngSwitch', 'ngTemplateOutlet', 'ngTemplateOutletContext'].includes(name))
|
|
1221
|
+
throw new Error(`${path}: [${name}] on <ng-container> is not supported in a release build yet`);
|
|
1222
|
+
}
|
|
1223
|
+
if (bound.has('ngTemplateOutletContext') && !bound.has('ngTemplateOutlet'))
|
|
1224
|
+
throw new Error(`${path}: [ngTemplateOutletContext] without [ngTemplateOutlet]`);
|
|
1225
|
+
const children = () => nodes(n.children, loops);
|
|
1226
|
+
const own = bound.has('ngSwitch') ? switching(n, bound.get('ngSwitch').value, loops, children) : children();
|
|
1227
|
+
const outletted = bound.has('ngTemplateOutlet') ? outlet(bound.get('ngTemplateOutlet').value, bound.get('ngTemplateOutletContext')?.value, loops) : [];
|
|
1228
|
+
return [...own, ...outletted];
|
|
1229
|
+
};
|
|
1230
|
+
/** The open `[ngSwitch]`es, innermost last: the method reading each one's value, and its cases' values as written. */
|
|
1231
|
+
const switches = [];
|
|
1232
|
+
/** Renders a `[ngSwitch]` element's children, its `ngSwitchCase`s comparing with `===` and `ngSwitchDefault` rendering when none matches. */
|
|
1233
|
+
const switching = (n, value, loops, render) => {
|
|
1234
|
+
const cases = [];
|
|
1235
|
+
const scan = (list, deeper) => {
|
|
1236
|
+
for (const c of list) {
|
|
1237
|
+
if (c instanceof ng.TmplAstElement && c.inputs.some((i) => i.name === 'ngSwitch'))
|
|
1238
|
+
continue;
|
|
1239
|
+
if (c instanceof ng.TmplAstTemplate) {
|
|
1240
|
+
const given = [...c.templateAttrs, ...c.inputs].find((a) => a instanceof ng.TmplAstBoundAttribute && a.name === 'ngSwitchCase');
|
|
1241
|
+
if (given) {
|
|
1242
|
+
if (deeper)
|
|
1243
|
+
throw new Error(`${path}: an ngSwitchCase inside a loop of its [ngSwitch] is not supported in a release build yet`);
|
|
1244
|
+
cases.push(given.value);
|
|
1245
|
+
}
|
|
1246
|
+
const loop = [...c.templateAttrs, ...c.inputs].some((a) => a.name === 'ngForOf');
|
|
1247
|
+
scan(c.children, deeper || loop);
|
|
1248
|
+
continue;
|
|
1249
|
+
}
|
|
1250
|
+
if (c instanceof ng.TmplAstForLoopBlock) {
|
|
1251
|
+
scan(c.children, true);
|
|
1252
|
+
continue;
|
|
1253
|
+
}
|
|
1254
|
+
if (c instanceof ng.TmplAstElement)
|
|
1255
|
+
scan(c.children, deeper || core.canonical(c.name) === 'ListView');
|
|
1256
|
+
else if (c instanceof ng.TmplAstIfBlock)
|
|
1257
|
+
for (const b of c.branches)
|
|
1258
|
+
scan(b.children, deeper);
|
|
1259
|
+
else if (c instanceof ng.TmplAstSwitchBlock)
|
|
1260
|
+
for (const g of c.groups)
|
|
1261
|
+
scan(g.children, deeper);
|
|
1262
|
+
}
|
|
1263
|
+
};
|
|
1264
|
+
scan(n.children, false);
|
|
1265
|
+
switches.push({ subject: expr(code(value, loops), loops), loops, cases });
|
|
1266
|
+
try {
|
|
1267
|
+
return render();
|
|
1268
|
+
}
|
|
1269
|
+
finally {
|
|
1270
|
+
switches.pop();
|
|
1271
|
+
}
|
|
1272
|
+
};
|
|
1273
|
+
/** `*ngSwitchCase="v"` and `*ngSwitchDefault`: an `if` on the nearest `[ngSwitch]` above it. */
|
|
1274
|
+
const switchCase = (t, given, loops) => {
|
|
1275
|
+
const sw = switches.at(-1);
|
|
1276
|
+
if (!sw)
|
|
1277
|
+
throw new Error(`${path}: ${given ? 'ngSwitchCase' : 'ngSwitchDefault'} outside an element with [ngSwitch]`);
|
|
1278
|
+
const subject = `this.${sw.subject}(${args(sw.loops)})`;
|
|
1279
|
+
const cond = given
|
|
1280
|
+
? expr(`(${subject}) === (${code(given.value, loops)})`, loops)
|
|
1281
|
+
: expr(sw.cases.length ? `!(${sw.cases.map((c) => `(${subject}) === (${code(c, sw.loops)})`).join(' || ')})` : 'true', loops);
|
|
1282
|
+
return [{ kind: 'if', branches: [{ cond, body: nodes(t.children, loops) }] }];
|
|
1283
|
+
};
|
|
1284
|
+
/**
|
|
1285
|
+
* `[ngTemplateOutlet]` (NgTemplateOutlet): the `<ng-template #name>` it names, rendered here with its `let-` variables
|
|
1286
|
+
* read from the context's properties (`let-x` from `$implicit`) whenever a binding reads them, as its view's context is
|
|
1287
|
+
* the latest one given. A template chosen by a condition (`a ? one : two`) is an `if`; null renders nothing.
|
|
1288
|
+
*/
|
|
1289
|
+
const outlet = (tpl, context, loops) => {
|
|
1290
|
+
const root = tpl instanceof ng.ASTWithSource ? tpl.ast : tpl;
|
|
1291
|
+
const given = context instanceof ng.ASTWithSource ? context.ast : context;
|
|
1292
|
+
// A context written as an object literal gives each variable its property's expression.
|
|
1293
|
+
const fields = given instanceof ng.LiteralMap ? new Map(given.keys.map((k, i) => [k.kind === 'property' ? k.key : undefined, given.values[i]])) : null;
|
|
1294
|
+
const ctx = context && !fields ? core.rewrite(clean(code(context, loops)), local(loops)) : null;
|
|
1295
|
+
const read = (key) => {
|
|
1296
|
+
if (fields) {
|
|
1297
|
+
const v = fields.get(key);
|
|
1298
|
+
return v ? `(${core.rewrite(clean(code(v, loops)), local(loops))})` : 'undefined';
|
|
1299
|
+
}
|
|
1300
|
+
return ctx === null ? 'undefined' : `(${ctx})?.${/^[A-Za-z_$][\w$]*$/.test(key) ? key : `[${JSON.stringify(key)}]`}`;
|
|
1301
|
+
};
|
|
1302
|
+
const render = (ast) => {
|
|
1303
|
+
if (ast instanceof ng.LiteralPrimitive && ast.value == null)
|
|
1304
|
+
return [];
|
|
1305
|
+
if (ast instanceof ng.Conditional)
|
|
1306
|
+
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) }] }];
|
|
1307
|
+
const name = ast instanceof ng.PropertyRead && ast.receiver instanceof ng.ImplicitReceiver ? ast.name : null;
|
|
1308
|
+
const t = name !== null ? references.get(name) : undefined;
|
|
1309
|
+
if (!t || t.tagName !== 'ng-template')
|
|
1310
|
+
throw new Error(`${path}: ngTemplateOutlet renders an <ng-template #name> of this template in a release build (given ${template.slice(ast.sourceSpan.start, ast.sourceSpan.end)})`);
|
|
1311
|
+
const saved = new Map(t.variables.map((v) => [v.name, aliases.get(v.name)]));
|
|
1312
|
+
for (const v of t.variables)
|
|
1313
|
+
aliases.set(v.name, read(v.value || '$implicit'));
|
|
1314
|
+
try {
|
|
1315
|
+
return nodes(t.children, loops);
|
|
1316
|
+
}
|
|
1317
|
+
finally {
|
|
1318
|
+
for (const [k, v] of saved)
|
|
1319
|
+
if (v === undefined)
|
|
1320
|
+
aliases.delete(k);
|
|
1321
|
+
else
|
|
1322
|
+
aliases.set(k, v);
|
|
1323
|
+
}
|
|
1324
|
+
};
|
|
1325
|
+
return render(root);
|
|
1326
|
+
};
|
|
1327
|
+
/**
|
|
1328
|
+
* `nsRouterLink` (@nativescript/angular's NSRouterLink) on any element: a tap handler navigating with its commands,
|
|
1329
|
+
* a single command as a one-command array, relative to the component's route unless `relativeTo` is given. The
|
|
1330
|
+
* route is the component's own, read when it is constructed: the router's current route changes as pages are made.
|
|
1331
|
+
*/
|
|
1332
|
+
let routed = false;
|
|
1333
|
+
const routerLink = (n, loops) => {
|
|
1334
|
+
const bound = new Map(n.inputs.map((i) => [i.name, i]));
|
|
1335
|
+
const fixed = new Map(n.attributes.map((a) => [a.name, a.value]));
|
|
1336
|
+
if (bound.has('nsRouterLinkActive') || fixed.has('nsRouterLinkActive'))
|
|
1337
|
+
throw new Error(`${path}: nsRouterLinkActive is not supported in a release build yet`);
|
|
1338
|
+
if (!bound.has('nsRouterLink') && !fixed.has('nsRouterLink'))
|
|
1339
|
+
return null;
|
|
1340
|
+
at(bound.get('nsRouterLink')?.sourceSpan ?? n.attributes.find((a) => a.name === 'nsRouterLink')?.sourceSpan);
|
|
1341
|
+
for (const name of ROUTER_LINK_INPUTS) {
|
|
1342
|
+
if (!ROUTER_LINK_SUPPORTED.has(name) && (bound.has(name) || fixed.has(name)))
|
|
1343
|
+
throw new Error(`${path}: nsRouterLink's ${name} is not supported in a release build yet`);
|
|
1344
|
+
}
|
|
1345
|
+
const value = (name) => (bound.has(name) ? `(${code(bound.get(name).value, loops)})` : fixed.has(name) ? JSON.stringify(fixed.get(name)) : null);
|
|
1346
|
+
routed = true;
|
|
1347
|
+
const body = [];
|
|
1348
|
+
const given = bound.get('nsRouterLink');
|
|
1349
|
+
const root = given && (given.value instanceof ng.ASTWithSource ? given.value.ast : given.value);
|
|
1350
|
+
let commands;
|
|
1351
|
+
if (root instanceof ng.LiteralArray)
|
|
1352
|
+
commands = code(given.value, loops);
|
|
1353
|
+
else if (!given)
|
|
1354
|
+
commands = `[${value('nsRouterLink')}]`;
|
|
1355
|
+
else {
|
|
1356
|
+
body.push(`const $commands: any = ${value('nsRouterLink')}`, 'if ($commands == null) return');
|
|
1357
|
+
commands = 'Array.isArray($commands) ? $commands : [$commands]';
|
|
1358
|
+
}
|
|
1359
|
+
const extras = [`relativeTo: ${value('relativeTo') ?? 'this.$route'}`];
|
|
1360
|
+
const transition = value('pageTransition');
|
|
1361
|
+
const duration = value('pageTransitionDuration');
|
|
1362
|
+
const constant = (name) => {
|
|
1363
|
+
if (fixed.has(name))
|
|
1364
|
+
return fixed.get(name);
|
|
1365
|
+
const v = bound.get(name)?.value;
|
|
1366
|
+
const ast = v instanceof ng.ASTWithSource ? v.ast : v;
|
|
1367
|
+
return ast instanceof ng.LiteralPrimitive && ast.value !== undefined ? ast.value : undefined;
|
|
1368
|
+
};
|
|
1369
|
+
// NSRouterLink.getTransition: a boolean is `animated`; 'none' and 'false' turn animation off; another string names the transition.
|
|
1370
|
+
const known = constant('pageTransition');
|
|
1371
|
+
if (!duration && (typeof known === 'boolean' || typeof known === 'string')) {
|
|
1372
|
+
if (known === false || known === 'none' || known === 'false')
|
|
1373
|
+
extras.push('animated: false');
|
|
1374
|
+
else if (typeof known === 'string')
|
|
1375
|
+
extras.push(`transition: { name: ${JSON.stringify(known)} }`);
|
|
1376
|
+
}
|
|
1377
|
+
else if (transition || duration) {
|
|
1378
|
+
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; }`);
|
|
1379
|
+
if (duration)
|
|
1380
|
+
body.push(`const $duration = +${duration}`, 'if (!isNaN($duration)) { $transition = $transition ?? {}; $transition.duration = $duration; }');
|
|
1381
|
+
extras.push('animated: $animated', 'transition: $transition');
|
|
1382
|
+
}
|
|
1383
|
+
const clear = value('clearHistory');
|
|
1384
|
+
const clearing = constant('clearHistory');
|
|
1385
|
+
if (clearing !== undefined)
|
|
1386
|
+
extras.push(`clearHistory: ${clearing === true || clearing === 'true'}`);
|
|
1387
|
+
else if (clear) {
|
|
1388
|
+
body.push(`const $clear: any = ${clear}`);
|
|
1389
|
+
extras.push(`clearHistory: $clear === true || $clear === 'true'`);
|
|
1390
|
+
}
|
|
1391
|
+
body.push(`this.$router.navigate(${commands}, { ${extras.join(', ')} })`);
|
|
1392
|
+
return { name: 'tap', method: handler(body.join('; '), loops) };
|
|
1393
|
+
};
|
|
1394
|
+
/** `*ngIf` (with `else` and `as`) and `*ngFor` (with `trackBy`, `index`, `even`, `odd`) on an element, `<ng-container>` or `<ng-template>`. */
|
|
1395
|
+
const structural = (t, loops) => {
|
|
1396
|
+
at(t.startSourceSpan);
|
|
1397
|
+
// `*ngIf` binds the directive through templateAttrs (the template's inputs are its element's); `<ng-template [ngIf]>` through inputs.
|
|
1398
|
+
const directive = t.tagName === 'ng-template' ? [...t.templateAttrs, ...t.inputs] : t.templateAttrs;
|
|
1399
|
+
const bound = (name) => directive.find((a) => a instanceof ng.TmplAstBoundAttribute && a.name === name);
|
|
1400
|
+
const ngIf = bound('ngIf');
|
|
1401
|
+
const ngForOf = bound('ngForOf');
|
|
1402
|
+
const outletOf = bound('ngTemplateOutlet');
|
|
1403
|
+
if (outletOf) {
|
|
1404
|
+
for (const a of directive)
|
|
1405
|
+
if (!['ngTemplateOutlet', 'ngTemplateOutletContext'].includes(a.name))
|
|
1406
|
+
throw new Error(`${path}: *ngTemplateOutlet's ${a.name} is not supported in a release build yet`);
|
|
1407
|
+
// The element `*ngTemplateOutlet` is written on is the directive's own template, which it never renders.
|
|
1408
|
+
return outlet(outletOf.value, bound('ngTemplateOutletContext')?.value, loops);
|
|
1409
|
+
}
|
|
1410
|
+
const caseOf = bound('ngSwitchCase');
|
|
1411
|
+
if (caseOf || directive.some((a) => a.name === 'ngSwitchDefault')) {
|
|
1412
|
+
if (directive.length !== 1)
|
|
1413
|
+
throw new Error(`${path}: ${directive.map((a) => a.name).join(', ')} on one template is not supported in a release build yet`);
|
|
1414
|
+
return switchCase(t, caseOf, loops);
|
|
1415
|
+
}
|
|
1416
|
+
const structuralDirective = matched(t.tagName ?? 'ng-template', [], directive.map((a) => a.name)).find((d) => d.structural);
|
|
1417
|
+
if (structuralDirective)
|
|
1418
|
+
throw new Error(`${path}: the structural directive ${structuralDirective.className} (TemplateRef, ViewContainerRef) is not supported in a release build yet`);
|
|
1419
|
+
if (!ngIf && !ngForOf) {
|
|
1420
|
+
// An `<ng-template #name>` renders only where an `else` names it.
|
|
1421
|
+
if (t.tagName === 'ng-template' && t.references.length && !directive.length)
|
|
1422
|
+
return [];
|
|
1423
|
+
throw new Error(`${path}: <${t.tagName}> with ${directive.map((a) => a.name).join(', ') || 'no directive'} is not supported in a release build yet`);
|
|
1424
|
+
}
|
|
1425
|
+
if (ngIf) {
|
|
1426
|
+
for (const a of directive)
|
|
1427
|
+
if (!['ngIf', 'ngIfElse'].includes(a.name))
|
|
1428
|
+
throw new Error(`${path}: *ngIf's ${a.name} is not supported in a release build yet`);
|
|
1429
|
+
const condition = code(ngIf.value, loops);
|
|
1430
|
+
const elseName = bound('ngIfElse');
|
|
1431
|
+
const otherwise = elseName ? references.get(sourceOf(elseName.value).trim()) : undefined;
|
|
1432
|
+
if (elseName && !otherwise)
|
|
1433
|
+
throw new Error(`${path}: *ngIf's else names no <ng-template #${sourceOf(elseName.value).trim()}>`);
|
|
1434
|
+
const renamed = t.variables.map((v) => {
|
|
1435
|
+
if (v.value !== 'ngIf')
|
|
1436
|
+
throw new Error(`${path}: *ngIf's ${v.value} is not supported in a release build yet`);
|
|
1437
|
+
return v.name;
|
|
1438
|
+
});
|
|
1439
|
+
const cond = test(condition, loops);
|
|
1440
|
+
for (const v of renamed)
|
|
1441
|
+
aliases.set(v, core.rewrite(clean(condition), local(loops)));
|
|
1442
|
+
const body = nodes(t.children, loops);
|
|
1443
|
+
for (const v of renamed)
|
|
1444
|
+
aliases.delete(v);
|
|
1445
|
+
return [{ kind: 'if', branches: [{ cond, body }, ...(otherwise ? [{ cond: null, body: nodes(otherwise.children, loops) }] : [])] }];
|
|
1446
|
+
}
|
|
1447
|
+
for (const a of directive)
|
|
1448
|
+
if (!['ngFor', 'ngForOf', 'ngForTrackBy'].includes(a.name))
|
|
1449
|
+
throw new Error(`${path}: *ngFor's ${a.name} is not supported in a release build yet`);
|
|
1450
|
+
const item = t.variables.find((v) => (v.value || '$implicit') === '$implicit')?.name ?? `$item${loops.length}`;
|
|
1451
|
+
const index = t.variables.find((v) => v.value === 'index')?.name ?? `$i${loops.length}`;
|
|
1452
|
+
const names = {};
|
|
1453
|
+
for (const v of t.variables) {
|
|
1454
|
+
if (v.name === item || v.name === index)
|
|
1455
|
+
continue;
|
|
1456
|
+
if (v.value === 'even')
|
|
1457
|
+
names[v.name] = `(${index} % 2 === 0)`;
|
|
1458
|
+
else if (v.value === 'odd')
|
|
1459
|
+
names[v.name] = `(${index} % 2 !== 0)`;
|
|
1460
|
+
else
|
|
1461
|
+
throw new Error(`${path}: *ngFor's ${v.value} is not supported in a release build yet`);
|
|
1462
|
+
}
|
|
1463
|
+
// NgForOf renders no rows for null, which an async pipe gives before its first value.
|
|
1464
|
+
const source = code(ngForOf.value, loops);
|
|
1465
|
+
const items = expr(source === sourceOf(ngForOf.value) ? source : `(${source}) ?? []`, loops);
|
|
1466
|
+
const loop = { item, index, param: `${item} = this.${items}(${args(loops)})[0], ${index} = 0`, names };
|
|
1467
|
+
const inner = [...loops, loop];
|
|
1468
|
+
// NgForOf keeps rows by identity, or by what its trackBy function returns for (index, item).
|
|
1469
|
+
const trackBy = bound('ngForTrackBy');
|
|
1470
|
+
const key = trackBy ? expr(`(${sourceOf(trackBy.value)})(${index}, ${item})`, inner) : null;
|
|
1471
|
+
return [{ kind: 'for', items, key, item, index, body: nodes(t.children, inner) }];
|
|
1472
|
+
};
|
|
1473
|
+
const parsed = ng.parseTemplate(template, path + '.html', { preserveWhitespaces: false });
|
|
1474
|
+
if (parsed.errors?.length)
|
|
1475
|
+
throw new Error(`${path}: ${parsed.errors[0]}`);
|
|
1476
|
+
const references = new Map();
|
|
1477
|
+
const findReferences = (list) => {
|
|
1478
|
+
for (const n of list) {
|
|
1479
|
+
if (n instanceof ng.TmplAstTemplate)
|
|
1480
|
+
for (const r of n.references)
|
|
1481
|
+
references.set(r.name, n);
|
|
1482
|
+
if (n instanceof ng.TmplAstElement || n instanceof ng.TmplAstTemplate || n instanceof ng.TmplAstForLoopBlock)
|
|
1483
|
+
findReferences(n.children);
|
|
1484
|
+
if (n instanceof ng.TmplAstIfBlock)
|
|
1485
|
+
for (const b of n.branches)
|
|
1486
|
+
findReferences(b.children);
|
|
1487
|
+
if (n instanceof ng.TmplAstForLoopBlock && n.empty)
|
|
1488
|
+
findReferences(n.empty.children);
|
|
1489
|
+
if (n instanceof ng.TmplAstSwitchBlock)
|
|
1490
|
+
for (const g of n.groups)
|
|
1491
|
+
findReferences(g.children);
|
|
1492
|
+
}
|
|
1493
|
+
};
|
|
1494
|
+
findReferences(parsed.nodes);
|
|
1495
|
+
const ownElements = (list) => {
|
|
1496
|
+
for (const n of list) {
|
|
1497
|
+
if (!(n instanceof ng.TmplAstElement))
|
|
1498
|
+
continue;
|
|
1499
|
+
for (const r of n.references)
|
|
1500
|
+
staticRefs.add(r.name);
|
|
1501
|
+
ownElements(n.children);
|
|
1502
|
+
}
|
|
1503
|
+
};
|
|
1504
|
+
ownElements(parsed.nodes);
|
|
1505
|
+
for (const q of queries)
|
|
1506
|
+
if (q.static && q.ref && staticRefs.has(q.ref))
|
|
1507
|
+
staticQueries.add(q);
|
|
1508
|
+
const tree = nodes(parsed.nodes, []);
|
|
1509
|
+
// The component's source, with the template's methods added to its class and the event type imported.
|
|
1510
|
+
const end = cls.members.end;
|
|
1511
|
+
// ngOnChanges: the parent's bindings record each input they set (`$change`), and one check after them calls the hook
|
|
1512
|
+
// with what changed since it last ran, the first time before ngOnInit.
|
|
1513
|
+
const onChanges = cls.members.find((m) => ts.isMethodDeclaration(m) && m.name.getText() === 'ngOnChanges');
|
|
1514
|
+
if (onChanges) {
|
|
1515
|
+
if (onChanges.parameters.length > 1)
|
|
1516
|
+
throw new Error(`${path}: ngOnChanges takes one parameter`);
|
|
1517
|
+
methods.push(...changesMembers(onChanges.parameters.length > 0));
|
|
1518
|
+
}
|
|
1519
|
+
const cached = [...sites.values()].some((x) => x.cache);
|
|
1520
|
+
let imports = `${cached ? "import { PurePipeCache as $PurePipeCache } from '@angular#kit';\n" : ''}import { type EventData as $EventData } from '@nativescript/release';\n`;
|
|
1521
|
+
if (usesElementRef)
|
|
1522
|
+
imports += `import { ElementRef as $ElementRef } from '@angular/core';\n`;
|
|
1523
|
+
if (usesUnset)
|
|
1524
|
+
imports += `import { unsetValue as $unsetValue } from '@nativescript/core';\n`;
|
|
1525
|
+
if (providers)
|
|
1526
|
+
imports += `import { NodeInjector } from '@angular#kit';\n`;
|
|
1527
|
+
if (onChanges) {
|
|
1528
|
+
imports += `import { SimpleChange as $SimpleChange } from '@angular/core';\n`;
|
|
1529
|
+
if (!importsAs(sf, 'signal', '@angular/core')) {
|
|
1530
|
+
if (declares(sf, 'signal'))
|
|
1531
|
+
throw new Error(`${path}: ngOnChanges needs Angular's signal, which this file's own "signal" hides`);
|
|
1532
|
+
imports += `import { signal } from '@angular/core';\n`;
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
if (queries.some((q) => q.many)) {
|
|
1536
|
+
usesRuntime = true;
|
|
1537
|
+
const from = options.runtimeModule ?? RUNTIME;
|
|
1538
|
+
imports += `import { QueryList as $QueryList } from '${isAbsolute(from) ? relativeSpecifier(dirname(path), from) : from}';\n`;
|
|
1539
|
+
}
|
|
1540
|
+
for (const [from, names] of imported) {
|
|
1541
|
+
const spec = isAbsolute(from) ? relativeSpecifier(dirname(path), from) : from;
|
|
1542
|
+
imports += `import { ${[...names].map(([c, a]) => `${c} as ${a}`).join(', ')} } from '${spec}';\n`;
|
|
1543
|
+
}
|
|
1544
|
+
if (routed) {
|
|
1545
|
+
// The translator knows `inject` by its name, and a framework token through any alias.
|
|
1546
|
+
if (!importsAs(sf, 'inject', '@angular/core')) {
|
|
1547
|
+
if (declares(sf, 'inject'))
|
|
1548
|
+
throw new Error(`${path}: nsRouterLink needs Angular's inject, which this file's own "inject" hides`);
|
|
1549
|
+
imports += `import { inject } from '@angular/core';\n`;
|
|
1550
|
+
}
|
|
1551
|
+
imports += `import { ActivatedRoute as $ActivatedRoute } from '@angular/router';\nimport { RouterExtensions as $RouterExtensions } from '@nativescript/angular';\n`;
|
|
1552
|
+
methods.push(' readonly $router = inject($RouterExtensions);', ' readonly $route = inject($ActivatedRoute);');
|
|
1553
|
+
}
|
|
1554
|
+
const head = imports + text.slice(0, end) + '\n';
|
|
1555
|
+
const source = head + methods.join('\n') + '\n' + text.slice(end);
|
|
1556
|
+
// Each template method's lines in the virtual file, at its binding's line in the template it was written in.
|
|
1557
|
+
const inlineAt = templateUrl ? 0 : written.indexOf(template);
|
|
1558
|
+
const templateFile = templateUrl ? join(dirname(path), templateUrl) : path;
|
|
1559
|
+
const firstLine = inlineAt > 0 ? written.slice(0, inlineAt).split('\n').length - 1 : 0;
|
|
1560
|
+
const lines = [];
|
|
1561
|
+
let line = head.split('\n').length - 1;
|
|
1562
|
+
methods.forEach((m, k) => {
|
|
1563
|
+
const span = m.split('\n').length;
|
|
1564
|
+
const at = located.get(k);
|
|
1565
|
+
if (at !== undefined && inlineAt >= 0)
|
|
1566
|
+
for (let j = 0; j < span; j++)
|
|
1567
|
+
lines.push([line + j, firstLine + at + 1]);
|
|
1568
|
+
line += span;
|
|
1569
|
+
});
|
|
1570
|
+
const { styles, scope: styleScope } = angularStyles(path, prop);
|
|
1571
|
+
const scoped = styleScope ? core.scopeTemplate(tree, styleScope.content).map((n) => (n.kind === 'element' ? { ...n, attrs: [...n.attrs, { name: styleScope.host, value: '' }] } : n)) : tree;
|
|
1572
|
+
return { name: cls.name.text, file: path.replace(/\.ts$/, '.release.ts'), source, ...(usesRuntime ? { usesRuntime } : {}), props, optional, outputs, template: scoped, selector, styles, ...(init ? { init: 'ngOnInit' } : {}), ...(init && lateInit ? { lateInit } : {}), ...(hook('ngAfterViewInit') ? { afterViewInit: 'ngAfterViewInit' } : {}), ...(hook('ngOnDestroy') ? { destroy: 'ngOnDestroy' } : {}), ...(onChanges ? { changes: true } : {}), ...(onPush ? { onPush } : {}), ...(classic?.host ? { host: '$host' } : {}), ...(providers ? { injector: '$injector' } : {}), ...(classic?.setters.size ? { setters: [...classic.setters] } : {}), ...(Object.keys(inputAliases).length ? { propAliases: inputAliases } : {}), ...(lines.length ? { templateLines: { file: templateFile, lines } } : {}) };
|
|
1573
|
+
}
|
|
1574
|
+
/**
|
|
1575
|
+
* The component's `styles`, `styleUrl` and `styleUrls`, as NativeScript Angular adds them: Sass compiled by the app's own
|
|
1576
|
+
* `sass`, and, unless `encapsulation: ViewEncapsulation.None`, each selector limited to the component's elements
|
|
1577
|
+
* (`_ngcontent-<id>`, which its renderer sets on each element the component creates) and `:host` to `_nghost-<id>`. The
|
|
1578
|
+
* compiled component has no host view of its own: its top-level elements carry the host attribute.
|
|
1579
|
+
*/
|
|
1580
|
+
function angularStyles(path, prop) {
|
|
1581
|
+
const texts = [];
|
|
1582
|
+
const literal = (e) => (ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e) ? e.text : null);
|
|
1583
|
+
const inline = prop('styles');
|
|
1584
|
+
for (const e of inline ? (ts.isArrayLiteralExpression(inline) ? [...inline.elements] : [inline]) : []) {
|
|
1585
|
+
const css = literal(e);
|
|
1586
|
+
if (css === null)
|
|
1587
|
+
throw new Error(`${path}: styles must be string literals in a compiled release`);
|
|
1588
|
+
texts.push({ css, lang: 'css', from: path });
|
|
1589
|
+
}
|
|
1590
|
+
const urls = [prop('styleUrl'), ...(() => { const u = prop('styleUrls'); return u && ts.isArrayLiteralExpression(u) ? [...u.elements] : []; })()].filter((e) => !!e);
|
|
1591
|
+
for (const e of urls) {
|
|
1592
|
+
const url = literal(e);
|
|
1593
|
+
if (url === null)
|
|
1594
|
+
throw new Error(`${path}: styleUrl must be a string literal in a compiled release`);
|
|
1595
|
+
const file = join(dirname(path), url);
|
|
1596
|
+
if (!existsSync(file))
|
|
1597
|
+
throw new Error(`${path}: styleUrl ${url} not found`);
|
|
1598
|
+
texts.push({ css: readFileSync(file, 'utf8'), lang: extname(file).slice(1), from: file });
|
|
1599
|
+
}
|
|
1600
|
+
if (!texts.length)
|
|
1601
|
+
return { styles: [], scope: null };
|
|
1602
|
+
const none = prop('encapsulation')?.getText() === 'ViewEncapsulation.None';
|
|
1603
|
+
const id = `c${createHash('sha256').update(path).digest('hex').slice(0, 8)}`;
|
|
1604
|
+
const styles = texts.map((t, k) => {
|
|
1605
|
+
let css = t.css;
|
|
1606
|
+
if (t.lang === 'scss' || t.lang === 'sass')
|
|
1607
|
+
css = createRequire(path)('sass').compileString(css, { loadPaths: [dirname(t.from)], syntax: t.lang === 'sass' ? 'indented' : 'scss' }).css;
|
|
1608
|
+
else if (t.lang !== 'css')
|
|
1609
|
+
throw new Error(`${t.from}: ${t.lang} stylesheets are not supported in a compiled release yet`);
|
|
1610
|
+
return { file: `${path}.style${k}.css`, css: none ? css : ng.encapsulateStyle(css, id) };
|
|
1611
|
+
});
|
|
1612
|
+
return { styles, scope: none ? null : { content: `_ngcontent-${id}`, host: `_nghost-${id}` } };
|
|
1613
|
+
}
|
|
1614
|
+
/** Every `BindingPipe` in an expression, those inside another pipe's arguments too. */
|
|
1615
|
+
function allPipes(node) {
|
|
1616
|
+
const found = [];
|
|
1617
|
+
const visit = (n) => {
|
|
1618
|
+
if (!(n instanceof ng.AST))
|
|
1619
|
+
return;
|
|
1620
|
+
if (n instanceof ng.BindingPipe)
|
|
1621
|
+
found.push(n);
|
|
1622
|
+
for (const v of Object.values(n))
|
|
1623
|
+
Array.isArray(v) ? v.forEach(visit) : visit(v);
|
|
1624
|
+
};
|
|
1625
|
+
visit(node);
|
|
1626
|
+
return found;
|
|
1627
|
+
}
|
|
1628
|
+
/** A module specifier for `file` (a .ts path) from a file in `dir`. */
|
|
1629
|
+
function relativeSpecifier(dir, file) {
|
|
1630
|
+
const r = relative(dir, file.replace(/\.tsx?$/, ''));
|
|
1631
|
+
return r.startsWith('.') ? r : './' + r;
|
|
1632
|
+
}
|
|
1633
|
+
/**
|
|
1634
|
+
* The `@Pipe` classes of the app's and its libraries' files, by the name templates use: whether each is pure (Angular's
|
|
1635
|
+
* default) and what making one takes.
|
|
1636
|
+
*/
|
|
1637
|
+
export function angularPipes(files, read) {
|
|
1638
|
+
const out = new Map();
|
|
1639
|
+
for (const file of files) {
|
|
1640
|
+
const text = read(file);
|
|
1641
|
+
if (!text.includes('@Pipe'))
|
|
1642
|
+
continue;
|
|
1643
|
+
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
|
|
1644
|
+
for (const st of sf.statements) {
|
|
1645
|
+
if (!ts.isClassDeclaration(st) || !st.name)
|
|
1646
|
+
continue;
|
|
1647
|
+
const meta = decorator(st, 'Pipe')?.arguments[0];
|
|
1648
|
+
if (!meta || !ts.isObjectLiteralExpression(meta))
|
|
1649
|
+
continue;
|
|
1650
|
+
const get = (k) => meta.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === k)?.initializer;
|
|
1651
|
+
const name = get('name');
|
|
1652
|
+
if (!name || !ts.isStringLiteralLike(name))
|
|
1653
|
+
throw new Error(`${file}: @Pipe needs a string name in a release build`);
|
|
1654
|
+
if (!(ts.getModifiers(st) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword))
|
|
1655
|
+
throw new Error(`${file}: the pipe ${st.name.text} is not exported`);
|
|
1656
|
+
const pure = get('pure');
|
|
1657
|
+
const ctor = st.members.find(ts.isConstructorDeclaration);
|
|
1658
|
+
out.set(name.text, {
|
|
1659
|
+
className: st.name.text, file, pure: pure?.kind !== ts.SyntaxKind.FalseKeyword,
|
|
1660
|
+
...(ctor?.parameters.length ? { create: true } : {}),
|
|
1661
|
+
...(st.members.some((m) => ts.isMethodDeclaration(m) && m.name.getText() === 'ngOnDestroy') ? { destroy: true } : {}),
|
|
1662
|
+
});
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
return out;
|
|
1666
|
+
}
|
|
1667
|
+
/**
|
|
1668
|
+
* What ngOnChanges takes in a component or directive: the template records each input it sets (`$change`), and one
|
|
1669
|
+
* check after its inputs' calls `$flushChanges`, which calls the hook with what changed since it last ran.
|
|
1670
|
+
*/
|
|
1671
|
+
const changesMembers = (hasParam) => [
|
|
1672
|
+
' readonly $changed = signal(0);',
|
|
1673
|
+
' readonly $changes = new Map<string, $SimpleChange>();',
|
|
1674
|
+
' readonly $previous = new Map<string, any>();',
|
|
1675
|
+
' $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); }',
|
|
1676
|
+
hasParam
|
|
1677
|
+
? ' $flushChanges(): void { if (!this.$changes.size) return; const changes = Object.fromEntries(this.$changes); this.$changes.clear(); this.ngOnChanges(changes); }'
|
|
1678
|
+
: ' $flushChanges(): void { if (!this.$changes.size) return; this.$changes.clear(); this.ngOnChanges(); }',
|
|
1679
|
+
];
|
|
1680
|
+
/** The `@Directive` classes of the app's files. */
|
|
1681
|
+
export function angularDirectives(files, read) {
|
|
1682
|
+
const out = [];
|
|
1683
|
+
for (const file of files) {
|
|
1684
|
+
const text = read(file);
|
|
1685
|
+
if (!text.includes('@Directive'))
|
|
1686
|
+
continue;
|
|
1687
|
+
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
|
|
1688
|
+
for (const st of sf.statements) {
|
|
1689
|
+
if (!ts.isClassDeclaration(st) || !st.name)
|
|
1690
|
+
continue;
|
|
1691
|
+
const call = decorator(st, 'Directive');
|
|
1692
|
+
const meta = call?.arguments[0];
|
|
1693
|
+
if (!call)
|
|
1694
|
+
continue;
|
|
1695
|
+
const where = `${file}: the directive ${st.name.text}`;
|
|
1696
|
+
if (!meta || !ts.isObjectLiteralExpression(meta))
|
|
1697
|
+
throw new Error(`${where} needs a selector`);
|
|
1698
|
+
const get = (k) => meta.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === k)?.initializer;
|
|
1699
|
+
const selector = get('selector');
|
|
1700
|
+
if (!selector || !ts.isStringLiteralLike(selector))
|
|
1701
|
+
throw new Error(`${where} needs a string selector in a release build`);
|
|
1702
|
+
if (!(ts.getModifiers(st) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword))
|
|
1703
|
+
throw new Error(`${where} is not exported`);
|
|
1704
|
+
const d = { className: st.name.text, file, 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] : [])) };
|
|
1705
|
+
for (const p of meta.properties) {
|
|
1706
|
+
const key = ts.isPropertyAssignment(p) ? p.name.getText() : p.getText();
|
|
1707
|
+
if (!['selector', 'inputs', 'host', 'standalone', 'jit'].includes(key))
|
|
1708
|
+
throw new Error(`${where}: its ${key} ${PLURAL_FIELDS.has(key) ? 'are' : 'is'} not supported in a release build yet`);
|
|
1709
|
+
}
|
|
1710
|
+
const inputs = get('inputs');
|
|
1711
|
+
for (const e of inputs && ts.isArrayLiteralExpression(inputs) ? inputs.elements : []) {
|
|
1712
|
+
if (!ts.isStringLiteralLike(e))
|
|
1713
|
+
throw new Error(`${where}: inputs are names in a release build`);
|
|
1714
|
+
const [member, alias] = e.text.split(':').map((x) => x.trim());
|
|
1715
|
+
d.inputs.set(alias ?? member, member);
|
|
1716
|
+
}
|
|
1717
|
+
const host = get('host');
|
|
1718
|
+
for (const p of host && ts.isObjectLiteralExpression(host) ? host.properties : []) {
|
|
1719
|
+
if (!ts.isPropertyAssignment(p) || !ts.isStringLiteralLike(p.initializer))
|
|
1720
|
+
throw new Error(`${where}: host entries are strings in a release build`);
|
|
1721
|
+
const key = ts.isStringLiteralLike(p.name) ? p.name.text : p.name.getText();
|
|
1722
|
+
const value = p.initializer.text;
|
|
1723
|
+
if (/^\(.*\)$/.test(key))
|
|
1724
|
+
d.listeners.push({ event: key.slice(1, -1), code: value });
|
|
1725
|
+
else if (/^\[.*\]$/.test(key))
|
|
1726
|
+
d.bindings.push({ prop: key.slice(1, -1), code: value });
|
|
1727
|
+
else
|
|
1728
|
+
d.attributes.push({ name: key, value });
|
|
1729
|
+
}
|
|
1730
|
+
for (const m of st.members) {
|
|
1731
|
+
const name = m.name && (ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)) ? m.name.text : undefined;
|
|
1732
|
+
const made = ts.isPropertyDeclaration(m) && m.initializer && ts.isCallExpression(m.initializer) ? m.initializer.expression.getText() : '';
|
|
1733
|
+
if (made === 'input' && name) {
|
|
1734
|
+
const options = m.initializer.arguments[1];
|
|
1735
|
+
const bad = options && (!ts.isObjectLiteralExpression(options) ? options : options.properties.find((p) => !ts.isPropertyAssignment(p) || !['alias', 'debugName'].includes(p.name.getText())));
|
|
1736
|
+
if (bad)
|
|
1737
|
+
throw new Error(`${where}: input()'s ${ts.isObjectLiteralElementLike(bad) && bad.name ? bad.name.getText() : bad.getText()} (${name}) is not supported in a release build yet`);
|
|
1738
|
+
const alias = options && ts.isObjectLiteralExpression(options) ? options.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'alias')?.initializer : undefined;
|
|
1739
|
+
d.inputs.set(alias && ts.isStringLiteralLike(alias) ? alias.text : name, name);
|
|
1740
|
+
d.signals.add(name);
|
|
1741
|
+
}
|
|
1742
|
+
else if (/^(input|model|output|viewChild|viewChildren|contentChild|contentChildren)(\.required)?$/.test(made))
|
|
1743
|
+
throw new Error(`${where}: ${made}() (${name}) in a directive is not supported in a release build yet`);
|
|
1744
|
+
if (ts.isMethodDeclaration(m) && name && /^ng(OnInit|OnChanges|AfterViewInit|OnDestroy|DoCheck|AfterContentInit|AfterContentChecked|AfterViewChecked)$/.test(name)) {
|
|
1745
|
+
if (!['ngOnInit', 'ngOnChanges', 'ngAfterViewInit', 'ngOnDestroy'].includes(name))
|
|
1746
|
+
throw new Error(`${where}: ${name} is not supported in a release build yet`);
|
|
1747
|
+
d.hooks.add(name);
|
|
1748
|
+
}
|
|
1749
|
+
for (const dec of ts.canHaveDecorators(m) ? ts.getDecorators(m) ?? [] : []) {
|
|
1750
|
+
const e = dec.expression;
|
|
1751
|
+
const which = ts.isCallExpression(e) ? e.expression.getText() : e.getText();
|
|
1752
|
+
const arg = ts.isCallExpression(e) ? e.arguments[0] : undefined;
|
|
1753
|
+
if (!name)
|
|
1754
|
+
throw new Error(`${where}: a decorated member without a plain name`);
|
|
1755
|
+
if (which === 'Input') {
|
|
1756
|
+
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;
|
|
1757
|
+
d.inputs.set(alias ?? name, name);
|
|
1758
|
+
}
|
|
1759
|
+
else if (which === 'HostListener') {
|
|
1760
|
+
if (!arg || !ts.isStringLiteralLike(arg) || !ts.isMethodDeclaration(m))
|
|
1761
|
+
throw new Error(`${where}: @HostListener takes an event name, on a method`);
|
|
1762
|
+
const given = ts.isCallExpression(e) ? e.arguments[1] : undefined;
|
|
1763
|
+
const args = given && ts.isArrayLiteralExpression(given) ? given.elements.map((x) => (ts.isStringLiteralLike(x) ? x.text : x.getText())) : [];
|
|
1764
|
+
if (arg.text.includes(':'))
|
|
1765
|
+
throw new Error(`${where}: @HostListener('${arg.text}'), a global target, is not supported in a release build yet`);
|
|
1766
|
+
d.listeners.push({ event: arg.text, code: `${name}(${args.join(', ')})` });
|
|
1767
|
+
}
|
|
1768
|
+
else if (which === 'HostBinding') {
|
|
1769
|
+
const prop = arg && ts.isStringLiteralLike(arg) ? arg.text : name;
|
|
1770
|
+
d.bindings.push({ prop, code: name });
|
|
1771
|
+
}
|
|
1772
|
+
else
|
|
1773
|
+
throw new Error(`${where}: @${which} is not supported in a release build yet`);
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
for (const b of d.bindings)
|
|
1777
|
+
if (/^(class|style|attr)\./.test(b.prop))
|
|
1778
|
+
throw new Error(`${where}: the host binding [${b.prop}] is not supported in a release build yet`);
|
|
1779
|
+
const ctor = st.members.find(ts.isConstructorDeclaration);
|
|
1780
|
+
d.create = !!ctor?.parameters.length;
|
|
1781
|
+
d.structural = /\bTemplateRef\b/.test(ctor?.getText() ?? '') || /inject\(\s*TemplateRef\b/.test(st.getText());
|
|
1782
|
+
out.push(d);
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
return out;
|
|
1786
|
+
}
|
|
1787
|
+
/**
|
|
1788
|
+
* A file of `@Pipe` (and `@Directive`) classes as the release build compiles it: the class decorators, which only
|
|
1789
|
+
* Angular's compiler reads, left out, and a class whose constructor takes parameters given a `static $create()` that
|
|
1790
|
+
* injects them, as Angular's factory does (`@Inject(TOKEN)` the token, `@Optional()` optionally). Null when the file has
|
|
1791
|
+
* no such class.
|
|
1792
|
+
*/
|
|
1793
|
+
export function declarableSource(path, text) {
|
|
1794
|
+
if (!/@(Pipe|Directive)\b/.test(text))
|
|
1795
|
+
return null;
|
|
1796
|
+
const sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true);
|
|
1797
|
+
const edits = [];
|
|
1798
|
+
let injects = false;
|
|
1799
|
+
let changes = false;
|
|
1800
|
+
for (const st of sf.statements) {
|
|
1801
|
+
if (!ts.isClassDeclaration(st) || !st.name)
|
|
1802
|
+
continue;
|
|
1803
|
+
const own = ts.getDecorators(st)?.find((d) => ts.isCallExpression(d.expression) && ['Pipe', 'Directive'].includes(d.expression.expression.getText()));
|
|
1804
|
+
if (!own)
|
|
1805
|
+
continue;
|
|
1806
|
+
edits.push({ start: own.getStart(), end: own.getEnd(), text: '' });
|
|
1807
|
+
// A directive's member decorators (@Input, @HostListener, @HostBinding) are the template compiler's to read.
|
|
1808
|
+
for (const m of st.members)
|
|
1809
|
+
for (const d of ts.canHaveDecorators(m) ? ts.getDecorators(m) ?? [] : [])
|
|
1810
|
+
edits.push({ start: d.getStart(), end: d.getEnd(), text: '' });
|
|
1811
|
+
const onChanges = st.members.find((m) => ts.isMethodDeclaration(m) && m.name.getText() === 'ngOnChanges');
|
|
1812
|
+
if (onChanges) {
|
|
1813
|
+
changes = true;
|
|
1814
|
+
edits.push({ start: st.members.end, end: st.members.end, text: '\n' + changesMembers(onChanges.parameters.length > 0).join('\n') + '\n' });
|
|
1815
|
+
}
|
|
1816
|
+
const ctor = st.members.find(ts.isConstructorDeclaration);
|
|
1817
|
+
if (!ctor?.parameters.length)
|
|
1818
|
+
continue;
|
|
1819
|
+
const given = ctor.parameters.map((p) => {
|
|
1820
|
+
const ref = p.type && ts.isTypeReferenceNode(p.type)
|
|
1821
|
+
? p.type
|
|
1822
|
+
: p.type && ts.isUnionTypeNode(p.type)
|
|
1823
|
+
? p.type.types.find(ts.isTypeReferenceNode)
|
|
1824
|
+
: undefined;
|
|
1825
|
+
let token = ref ? ref.typeName.getText() : undefined;
|
|
1826
|
+
let optional = !!(p.questionToken || p.initializer);
|
|
1827
|
+
let skipSelf = false;
|
|
1828
|
+
for (const d of ts.getDecorators(p) ?? []) {
|
|
1829
|
+
const e = d.expression;
|
|
1830
|
+
const which = ts.isCallExpression(e) ? e.expression.getText() : e.getText();
|
|
1831
|
+
if (which === 'Inject' && ts.isCallExpression(e) && e.arguments[0])
|
|
1832
|
+
token = e.arguments[0].getText();
|
|
1833
|
+
else if (which === 'Optional')
|
|
1834
|
+
optional = true;
|
|
1835
|
+
else if (which === 'SkipSelf')
|
|
1836
|
+
skipSelf = true;
|
|
1837
|
+
else if (!['Self', 'Host'].includes(which))
|
|
1838
|
+
throw new Error(`${path}: @${which} on ${st.name.text}'s constructor parameter ${p.name.getText()} is not supported in a release build yet`);
|
|
1839
|
+
edits.push({ start: d.getStart(), end: d.getEnd(), text: '' });
|
|
1840
|
+
}
|
|
1841
|
+
if (optional && skipSelf)
|
|
1842
|
+
return 'undefined as any';
|
|
1843
|
+
if (!token)
|
|
1844
|
+
throw new Error(`${path}: ${st.name.text}'s constructor parameter ${p.name.getText()} needs a class type or @Inject(token) in a release build`);
|
|
1845
|
+
injects = true;
|
|
1846
|
+
return `inject(${token}${optional ? ', { optional: true }' : ''})`;
|
|
1847
|
+
});
|
|
1848
|
+
const close = st.members.end;
|
|
1849
|
+
edits.push({ start: close, end: close, text: `\n static $create(): ${st.name.text} { return new ${st.name.text}(${given.join(', ')}); }\n` });
|
|
1850
|
+
}
|
|
1851
|
+
if (!edits.length)
|
|
1852
|
+
return null;
|
|
1853
|
+
let out = text;
|
|
1854
|
+
for (const e of edits.sort((a, b) => b.start - a.start))
|
|
1855
|
+
out = out.slice(0, e.start) + e.text + out.slice(e.end);
|
|
1856
|
+
if (changes) {
|
|
1857
|
+
if (!importsAs(sf, 'signal', '@angular/core') && declares(sf, 'signal'))
|
|
1858
|
+
throw new Error(`${path}: ngOnChanges needs Angular's signal, which this file's own "signal" hides`);
|
|
1859
|
+
out = `import { ${importsAs(sf, 'signal', '@angular/core') ? '' : 'signal, '}SimpleChange as $SimpleChange } from '@angular/core';\n` + out;
|
|
1860
|
+
}
|
|
1861
|
+
if (injects && !importsAs(sf, 'inject', '@angular/core')) {
|
|
1862
|
+
if (declares(sf, 'inject'))
|
|
1863
|
+
throw new Error(`${path}: a pipe's constructor is injected with Angular's inject, which this file's own "inject" hides`);
|
|
1864
|
+
out = `import { inject } from '@angular/core';\n` + out;
|
|
1865
|
+
}
|
|
1866
|
+
return out;
|
|
1867
|
+
}
|
|
1868
|
+
/**
|
|
1869
|
+
* A component written with decorators: `@Input() x: T` (or `= init`) is `input<T>()`, read as
|
|
1870
|
+
* `this.x()` and written, by the component itself, with `$assign`; `@Input() set x(v)` is a
|
|
1871
|
+
* `$set_x(v)` method, called as Angular calls the setter; `@Output() e = new EventEmitter<T>()` is
|
|
1872
|
+
* `output<T>()`; constructor parameter properties are `inject()`ed fields, set before the other
|
|
1873
|
+
* fields as TypeScript sets them. Null when the class has none of these.
|
|
1874
|
+
*/
|
|
1875
|
+
function classicClass(path, text, cls) {
|
|
1876
|
+
const edits = [];
|
|
1877
|
+
const inputs = new Set();
|
|
1878
|
+
const setters = new Set();
|
|
1879
|
+
const aliases = new Map();
|
|
1880
|
+
const optional = new Set();
|
|
1881
|
+
const queries = [];
|
|
1882
|
+
const used = new Set();
|
|
1883
|
+
const injected = [];
|
|
1884
|
+
let ctor;
|
|
1885
|
+
const locals = [];
|
|
1886
|
+
let host = /\binject\(\s*ElementRef\s*\)/.test(cls.getText());
|
|
1887
|
+
const decoratorsOf = (m) => (ts.canHaveDecorators(m) ? ts.getDecorators(m) ?? [] : []).map((d) => d.expression);
|
|
1888
|
+
/** `@Input()`, `@Input('alias')`, `@Input({ alias, required })`: the name the parent binds and whether it must. */
|
|
1889
|
+
const inputOptions = (d, name) => {
|
|
1890
|
+
const a = d.arguments[0];
|
|
1891
|
+
if (!a)
|
|
1892
|
+
return { required: false };
|
|
1893
|
+
if (ts.isStringLiteralLike(a))
|
|
1894
|
+
return { alias: a.text, required: false };
|
|
1895
|
+
if (!ts.isObjectLiteralExpression(a) || d.arguments.length > 1)
|
|
1896
|
+
throw new Error(`${path}: @Input(${a.getText()}) ${name} is not supported in a release build yet`);
|
|
1897
|
+
const out = { required: false };
|
|
1898
|
+
for (const p of a.properties) {
|
|
1899
|
+
const key = p.name?.getText();
|
|
1900
|
+
const value = ts.isPropertyAssignment(p) ? p.initializer : undefined;
|
|
1901
|
+
if (key === 'alias' && value && ts.isStringLiteralLike(value))
|
|
1902
|
+
out.alias = value.text;
|
|
1903
|
+
else if (key === 'required' && value && (value.kind === ts.SyntaxKind.TrueKeyword || value.kind === ts.SyntaxKind.FalseKeyword))
|
|
1904
|
+
out.required = value.kind === ts.SyntaxKind.TrueKeyword;
|
|
1905
|
+
else
|
|
1906
|
+
throw new Error(`${path}: @Input's ${p.getText()} (${name}) is not supported in a release build yet`);
|
|
1907
|
+
}
|
|
1908
|
+
return out;
|
|
1909
|
+
};
|
|
1910
|
+
for (const m of cls.members) {
|
|
1911
|
+
const decorators = decoratorsOf(m);
|
|
1912
|
+
if (ts.isPropertyDeclaration(m) && decorators.length) {
|
|
1913
|
+
const name = m.name.getText();
|
|
1914
|
+
const d = decorators[0];
|
|
1915
|
+
const which = ts.isCallExpression(d) ? d.expression.getText() : d.getText();
|
|
1916
|
+
if (decorators.length > 1 || !ts.isCallExpression(d))
|
|
1917
|
+
throw new Error(`${path}: @${d.getText()} ${name} is not supported in a release build yet`);
|
|
1918
|
+
if (which === 'Input') {
|
|
1919
|
+
const { alias, required } = inputOptions(d, name);
|
|
1920
|
+
const type = m.type?.getText() ?? literalType(m.initializer);
|
|
1921
|
+
if (!type)
|
|
1922
|
+
throw new Error(`${path}: @Input() ${name} needs a type`);
|
|
1923
|
+
// An input the parent leaves out keeps its initializer, or is undefined, as Angular leaves the field; one declared
|
|
1924
|
+
// definitely assigned (`x!: T`) or `required` is one the parent gives.
|
|
1925
|
+
const given = required || !!m.exclamationToken;
|
|
1926
|
+
const init = m.initializer ? `input<${type}>(${m.initializer.getText()})` : !given ? `input<${type} | undefined>(undefined)` : `input.required<${type}>()`;
|
|
1927
|
+
edits.push({ start: m.getStart(), end: m.getEnd(), text: `readonly ${name} = ${init};` });
|
|
1928
|
+
inputs.add(name);
|
|
1929
|
+
if (alias)
|
|
1930
|
+
aliases.set(name, alias);
|
|
1931
|
+
if (!given)
|
|
1932
|
+
optional.add(name);
|
|
1933
|
+
used.add('input');
|
|
1934
|
+
}
|
|
1935
|
+
else if (which === 'Output') {
|
|
1936
|
+
if (d.arguments.length)
|
|
1937
|
+
throw new Error(`${path}: @${d.getText()} ${name} is not supported in a release build yet`);
|
|
1938
|
+
const init = m.initializer;
|
|
1939
|
+
if (!init || !ts.isNewExpression(init) || init.expression.getText() !== 'EventEmitter')
|
|
1940
|
+
throw new Error(`${path}: @Output() ${name} needs = new EventEmitter<T>()`);
|
|
1941
|
+
edits.push({ start: m.getStart(), end: m.getEnd(), text: `readonly ${name} = output<${init.typeArguments?.[0]?.getText() ?? 'void'}>();` });
|
|
1942
|
+
used.add('output');
|
|
1943
|
+
}
|
|
1944
|
+
else if (which === 'ViewChild' || which === 'ViewChildren') {
|
|
1945
|
+
const [what, options] = d.arguments;
|
|
1946
|
+
const query = { field: name, read: null, static: false, many: which === 'ViewChildren' };
|
|
1947
|
+
if (what && ts.isStringLiteralLike(what)) {
|
|
1948
|
+
if (what.text.includes(','))
|
|
1949
|
+
throw new Error(`${path}: @${which}('${what.text}'), a query of several names, is not supported in a release build yet`);
|
|
1950
|
+
query.ref = what.text.trim();
|
|
1951
|
+
}
|
|
1952
|
+
else if (what && ts.isIdentifier(what))
|
|
1953
|
+
query.type = what.text;
|
|
1954
|
+
else
|
|
1955
|
+
throw new Error(`${path}: @${d.getText()} ${name} is not supported in a release build yet`);
|
|
1956
|
+
for (const p of options && ts.isObjectLiteralExpression(options) ? options.properties : []) {
|
|
1957
|
+
const key = p.name?.getText();
|
|
1958
|
+
const value = ts.isPropertyAssignment(p) ? p.initializer : undefined;
|
|
1959
|
+
if (key === 'static' && value)
|
|
1960
|
+
query.static = value.kind === ts.SyntaxKind.TrueKeyword;
|
|
1961
|
+
else if (key === 'read' && value && ts.isIdentifier(value))
|
|
1962
|
+
query.read = value.text;
|
|
1963
|
+
else
|
|
1964
|
+
throw new Error(`${path}: @${which}'s ${p.getText()} (${name}) is not supported in a release build yet`);
|
|
1965
|
+
}
|
|
1966
|
+
if (options && !ts.isObjectLiteralExpression(options))
|
|
1967
|
+
throw new Error(`${path}: @${d.getText()} ${name} is not supported in a release build yet`);
|
|
1968
|
+
if (query.read && /^(ViewContainerRef|TemplateRef|ChangeDetectorRef|Injector)$/.test(query.read))
|
|
1969
|
+
throw new Error(`${path}: @${which}'s read: ${query.read} (${name}) is not supported in a release build yet`);
|
|
1970
|
+
queries.push(query);
|
|
1971
|
+
const decorator = ts.getDecorators(m)[0];
|
|
1972
|
+
if (query.many) {
|
|
1973
|
+
// A QueryList the template's matches are added to and removed from, in the order they render.
|
|
1974
|
+
edits.push({ start: m.getStart(), end: m.getEnd(), text: `readonly ${name} = new $QueryList();` });
|
|
1975
|
+
}
|
|
1976
|
+
else
|
|
1977
|
+
edits.push({ start: decorator.getStart(), end: decorator.getEnd(), text: '' });
|
|
1978
|
+
}
|
|
1979
|
+
else
|
|
1980
|
+
throw new Error(`${path}: @${which} is not supported in a release build yet`);
|
|
1981
|
+
continue;
|
|
1982
|
+
}
|
|
1983
|
+
if (ts.isAccessor(m) && decorators.length) {
|
|
1984
|
+
const name = m.name.getText();
|
|
1985
|
+
const d = decorators[0];
|
|
1986
|
+
if (decorators.length > 1 || !ts.isCallExpression(d) || d.expression.getText() !== 'Input')
|
|
1987
|
+
throw new Error(`${path}: @${d.getText()} on the accessor ${name} is not supported in a release build yet`);
|
|
1988
|
+
const { alias } = inputOptions(d, name);
|
|
1989
|
+
// The decorator may be on either accessor; the setter is what the parent's binding calls.
|
|
1990
|
+
const set = cls.members.find((x) => ts.isSetAccessorDeclaration(x) && x.name.getText() === name);
|
|
1991
|
+
if (!set)
|
|
1992
|
+
throw new Error(`${path}: @Input() on the getter ${name}, which has no setter`);
|
|
1993
|
+
const decorator = ts.getDecorators(m)[0];
|
|
1994
|
+
edits.push({ start: decorator.getStart(), end: decorator.getEnd(), text: '' });
|
|
1995
|
+
const head = set.getChildren().find((c) => c.kind === ts.SyntaxKind.SetKeyword);
|
|
1996
|
+
edits.push({ start: head.getStart(), end: set.name.getEnd(), text: `$set_${name}` });
|
|
1997
|
+
setters.add(name);
|
|
1998
|
+
if (alias)
|
|
1999
|
+
aliases.set(name, alias);
|
|
2000
|
+
optional.add(name);
|
|
2001
|
+
continue;
|
|
2002
|
+
}
|
|
2003
|
+
if (decorators.length)
|
|
2004
|
+
throw new Error(`${path}: @${decorators[0].getText()} is not supported in a release build yet`);
|
|
2005
|
+
if (ts.isConstructorDeclaration(m)) {
|
|
2006
|
+
// A body without parameters is the translator's: it runs after the field initializers, as TypeScript runs it.
|
|
2007
|
+
if (!m.parameters.length)
|
|
2008
|
+
continue;
|
|
2009
|
+
for (const p of m.parameters) {
|
|
2010
|
+
const modifiers = (ts.getModifiers(p) ?? []).map((x) => x.getText());
|
|
2011
|
+
// Angular's factory injects each parameter: its class, or the token `@Inject` names, optionally with `@Optional()`.
|
|
2012
|
+
const ref = p.type && ts.isTypeReferenceNode(p.type)
|
|
2013
|
+
? p.type
|
|
2014
|
+
: p.type && ts.isUnionTypeNode(p.type)
|
|
2015
|
+
? p.type.types.find(ts.isTypeReferenceNode)
|
|
2016
|
+
: undefined;
|
|
2017
|
+
let token = ref ? ref.typeName.getText() : undefined;
|
|
2018
|
+
let optional = !!(p.questionToken || p.initializer);
|
|
2019
|
+
let skipSelf = false;
|
|
2020
|
+
for (const d of decoratorsOf(p)) {
|
|
2021
|
+
const which = ts.isCallExpression(d) ? d.expression.getText() : d.getText();
|
|
2022
|
+
if (which === 'Inject' && ts.isCallExpression(d) && d.arguments[0])
|
|
2023
|
+
token = d.arguments[0].getText();
|
|
2024
|
+
else if (which === 'Optional')
|
|
2025
|
+
optional = true;
|
|
2026
|
+
else if (which === 'SkipSelf')
|
|
2027
|
+
skipSelf = true;
|
|
2028
|
+
else if (!['Self', 'Host'].includes(which))
|
|
2029
|
+
throw new Error(`${path}: @${which} on the constructor parameter ${p.name.getText()} is not supported in a release build yet`);
|
|
2030
|
+
}
|
|
2031
|
+
if (!token && !(optional && skipSelf))
|
|
2032
|
+
throw new Error(`${path}: constructor parameter ${p.getText()} needs a class type or @Inject(token)`);
|
|
2033
|
+
// The component's own ElementRef is its host: the template's root view, set once it is made.
|
|
2034
|
+
if (token === 'ElementRef')
|
|
2035
|
+
host = true;
|
|
2036
|
+
const value = optional && skipSelf
|
|
2037
|
+
? 'undefined as any'
|
|
2038
|
+
: token === 'ElementRef'
|
|
2039
|
+
? 'this.$host'
|
|
2040
|
+
: (used.add('inject'), `inject(${token}${optional ? ', { optional: true }' : ''})`);
|
|
2041
|
+
const typed = p.type ? `: ${p.type.getText()}` : '';
|
|
2042
|
+
// A parameter property is a field; a plain parameter is a local of the constructor's body.
|
|
2043
|
+
if (modifiers.length) {
|
|
2044
|
+
injected.push(` ${modifiers.join(' ')} ${p.name.getText()}${typed} = ${value};\n`);
|
|
2045
|
+
// The constructor's body may still name the parameter, which is now the field.
|
|
2046
|
+
if (m.body && new RegExp(`(?<![.\\w$])${p.name.getText()}\\b`).test(m.body.getText()))
|
|
2047
|
+
locals.push(`const ${p.name.getText()} = this.${p.name.getText()};`);
|
|
2048
|
+
}
|
|
2049
|
+
else
|
|
2050
|
+
locals.push(`const ${p.name.getText()}${typed} = ${value};`);
|
|
2051
|
+
}
|
|
2052
|
+
ctor = m;
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
if (!edits.length && !ctor && !host)
|
|
2056
|
+
return null;
|
|
2057
|
+
if (host) {
|
|
2058
|
+
injected.unshift(` readonly $host = new ElementRef(undefined);\n`);
|
|
2059
|
+
used.add('ElementRef');
|
|
2060
|
+
for (const m of cls.members) {
|
|
2061
|
+
const visit = (n) => {
|
|
2062
|
+
if (ts.isCallExpression(n) && n.expression.getText() === 'inject' && n.arguments.length === 1 && n.arguments[0].getText() === 'ElementRef')
|
|
2063
|
+
edits.push({ start: n.getStart(), end: n.getEnd(), text: 'this.$host' });
|
|
2064
|
+
else
|
|
2065
|
+
ts.forEachChild(n, visit);
|
|
2066
|
+
};
|
|
2067
|
+
if (m !== ctor)
|
|
2068
|
+
visit(m);
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
if (injected.length)
|
|
2072
|
+
edits.push({ start: cls.members[0].getFullStart(), end: cls.members[0].getFullStart(), text: '\n' + injected.join('') });
|
|
2073
|
+
// `this.input` reads the input's signal and writes it with `$assign`; `this.setter = v` calls the setter's method.
|
|
2074
|
+
const isInput = (n) => ts.isPropertyAccessExpression(n) && n.expression.kind === ts.SyntaxKind.ThisKeyword && (inputs.has(n.name.text) || setters.has(n.name.text));
|
|
2075
|
+
/** The text of `n` with the reads and writes inside it rewritten. */
|
|
2076
|
+
const rewritten = (n) => {
|
|
2077
|
+
const inner = [];
|
|
2078
|
+
collect(n, inner);
|
|
2079
|
+
let t = text.slice(n.getStart(), n.getEnd());
|
|
2080
|
+
for (const e of inner.sort((a, b) => b.start - a.start))
|
|
2081
|
+
t = t.slice(0, e.start - n.getStart()) + e.text + t.slice(e.end - n.getStart());
|
|
2082
|
+
return t;
|
|
2083
|
+
};
|
|
2084
|
+
const collect = (n, into) => {
|
|
2085
|
+
const write = (target, value, at) => {
|
|
2086
|
+
const name = target.name.text;
|
|
2087
|
+
into.push({ start: at.getStart(), end: at.getEnd(), text: setters.has(name) ? `this.$set_${name}(${value})` : `this.${name}.$assign(${value})` });
|
|
2088
|
+
};
|
|
2089
|
+
if (ts.isBinaryExpression(n) && isInput(n.left) && n.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && n.operatorToken.kind <= ts.SyntaxKind.LastAssignment) {
|
|
2090
|
+
const op = n.operatorToken.getText().slice(0, -1);
|
|
2091
|
+
if (op && setters.has(n.left.name.text))
|
|
2092
|
+
throw new Error(`${path}: ${n.getText()} on the input setter ${n.left.name.text} is not supported in a release build yet`);
|
|
2093
|
+
write(n.left, op ? `this.${n.left.name.text}() ${op} (${rewritten(n.right)})` : rewritten(n.right), n);
|
|
2094
|
+
return;
|
|
2095
|
+
}
|
|
2096
|
+
if ((ts.isPrefixUnaryExpression(n) || ts.isPostfixUnaryExpression(n)) && isInput(n.operand) && (n.operator === ts.SyntaxKind.PlusPlusToken || n.operator === ts.SyntaxKind.MinusMinusToken)) {
|
|
2097
|
+
if (setters.has(n.operand.name.text) || !ts.isExpressionStatement(n.parent))
|
|
2098
|
+
throw new Error(`${path}: ${n.getText()} on an input is not supported in a release build yet`);
|
|
2099
|
+
write(n.operand, `this.${n.operand.name.text}() ${n.operator === ts.SyntaxKind.PlusPlusToken ? '+' : '-'} 1`, n);
|
|
2100
|
+
return;
|
|
2101
|
+
}
|
|
2102
|
+
if (isInput(n) && inputs.has(n.name.text)) {
|
|
2103
|
+
into.push({ start: n.getEnd(), end: n.getEnd(), text: '()' });
|
|
2104
|
+
return;
|
|
2105
|
+
}
|
|
2106
|
+
ts.forEachChild(n, (c) => collect(c, into));
|
|
2107
|
+
};
|
|
2108
|
+
for (const m of cls.members)
|
|
2109
|
+
if (m !== ctor && !(ts.isPropertyDeclaration(m) && inputs.has(m.name.getText())))
|
|
2110
|
+
collect(m, edits);
|
|
2111
|
+
if (ctor)
|
|
2112
|
+
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(' ')} }` : '' });
|
|
2113
|
+
let out = text;
|
|
2114
|
+
for (const e of edits.sort((a, b) => b.start - a.start || b.end - a.end))
|
|
2115
|
+
out = out.slice(0, e.start) + e.text + out.slice(e.end);
|
|
2116
|
+
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) : []));
|
|
2117
|
+
const missing = [...used].filter((u) => !imported.has(u));
|
|
2118
|
+
return { text: (missing.length ? `import { ${missing.join(', ')} } from '@angular/core';\n` : '') + out, inputs, setters, aliases, optional, queries, host };
|
|
2119
|
+
}
|
|
2120
|
+
function literalType(e) {
|
|
2121
|
+
if (!e)
|
|
2122
|
+
return undefined;
|
|
2123
|
+
if (ts.isNumericLiteral(e))
|
|
2124
|
+
return 'number';
|
|
2125
|
+
if (ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e))
|
|
2126
|
+
return 'string';
|
|
2127
|
+
if (e.kind === ts.SyntaxKind.TrueKeyword || e.kind === ts.SyntaxKind.FalseKeyword)
|
|
2128
|
+
return 'boolean';
|
|
2129
|
+
return undefined;
|
|
2130
|
+
}
|
|
2131
|
+
function literalKey(code, path) {
|
|
2132
|
+
const m = /^\s*(['"])(.*)\1\s*$/.exec(code);
|
|
2133
|
+
if (!m)
|
|
2134
|
+
throw new Error(`${path}: [nsTemplateKey]="${code}" needs a string literal in a release build`);
|
|
2135
|
+
return m[2];
|
|
2136
|
+
}
|
|
2137
|
+
/**
|
|
2138
|
+
* A file's `@Pipe` classes, and each `@NgModule` with the names its `declarations`, `imports` and `exports` list. A
|
|
2139
|
+
* library's directives are left out: its Angular wrappers are written against the view internals a compiled template
|
|
2140
|
+
* replaces.
|
|
2141
|
+
*/
|
|
2142
|
+
export function declarablesIn(path, text, app = false) {
|
|
2143
|
+
const classes = [];
|
|
2144
|
+
const modules = new Map();
|
|
2145
|
+
if (!/@(Pipe|NgModule)\b/.test(text))
|
|
2146
|
+
return { classes, modules };
|
|
2147
|
+
const sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true);
|
|
2148
|
+
for (const st of sf.statements) {
|
|
2149
|
+
if (!ts.isClassDeclaration(st) || !st.name)
|
|
2150
|
+
continue;
|
|
2151
|
+
if (decorator(st, 'Pipe'))
|
|
2152
|
+
classes.push(st.name.text);
|
|
2153
|
+
const meta = decorator(st, 'NgModule')?.arguments[0];
|
|
2154
|
+
if (meta && ts.isObjectLiteralExpression(meta)) {
|
|
2155
|
+
// Its `imports` and `providers` are walked where the module is imported (`ngModuleDef`); `bootstrap` is the entry's, the rest only steer Angular's compiler.
|
|
2156
|
+
for (const p of app ? meta.properties : []) {
|
|
2157
|
+
const key = ts.isPropertyAssignment(p) ? p.name.getText() : p.getText();
|
|
2158
|
+
if (!['declarations', 'imports', 'exports', 'providers', 'bootstrap', 'schemas', 'id', 'jit', 'entryComponents'].includes(key))
|
|
2159
|
+
throw new Error(`${path}: the NgModule ${st.name.text}'s ${key} ${PLURAL_FIELDS.has(key) ? 'are' : 'is'} not supported in a release build yet`);
|
|
2160
|
+
}
|
|
2161
|
+
modules.set(st.name.text, meta.properties.flatMap((p) => (ts.isPropertyAssignment(p) && ['declarations', 'imports', 'exports'].includes(p.name.getText()) && ts.isArrayLiteralExpression(p.initializer)
|
|
2162
|
+
? p.initializer.elements.filter(ts.isIdentifier).map((e) => e.text) : [])));
|
|
2163
|
+
}
|
|
2164
|
+
}
|
|
2165
|
+
return { classes, modules };
|
|
2166
|
+
}
|
|
2167
|
+
/** A component class's members, and its inputs (by field, with the names its parent binds where they differ) and outputs. */
|
|
2168
|
+
function publicMembers(path, cls, classic) {
|
|
2169
|
+
const members = new Set();
|
|
2170
|
+
const props = [];
|
|
2171
|
+
const optional = [];
|
|
2172
|
+
const outputs = [];
|
|
2173
|
+
const inputAliases = {};
|
|
2174
|
+
for (const m of cls.members) {
|
|
2175
|
+
if (!m.name || !ts.isIdentifier(m.name))
|
|
2176
|
+
continue;
|
|
2177
|
+
members.add(m.name.text);
|
|
2178
|
+
if (ts.isPropertyDeclaration(m) && m.initializer && ts.isCallExpression(m.initializer)) {
|
|
2179
|
+
const callee = m.initializer.expression.getText();
|
|
2180
|
+
if (/^(viewChild|viewChildren|contentChild|contentChildren)(\.required)?$/.test(callee))
|
|
2181
|
+
throw new Error(`${path}: the signal query ${callee}() (${m.name.text}) is not supported in a release build yet`);
|
|
2182
|
+
const optionsOf = (k, allowed) => {
|
|
2183
|
+
const o = m.initializer.arguments[k];
|
|
2184
|
+
if (!o)
|
|
2185
|
+
return undefined;
|
|
2186
|
+
const bad = !ts.isObjectLiteralExpression(o) ? o : o.properties.find((p) => !ts.isPropertyAssignment(p) || !allowed.includes(p.name.getText()));
|
|
2187
|
+
if (bad)
|
|
2188
|
+
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`);
|
|
2189
|
+
return o;
|
|
2190
|
+
};
|
|
2191
|
+
if (callee === 'output')
|
|
2192
|
+
optionsOf(0, []);
|
|
2193
|
+
if (callee === 'input' || callee === 'input.required' || callee === 'model' || callee === 'model.required') {
|
|
2194
|
+
props.push(m.name.text);
|
|
2195
|
+
// `input(init, { alias })`, `input.required({ alias })`: the name the parent binds.
|
|
2196
|
+
const options = optionsOf(callee === 'input' || callee === 'model' ? 1 : 0, ['alias', 'debugName']);
|
|
2197
|
+
const alias = options && ts.isObjectLiteralExpression(options) ? options.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'alias')?.initializer : undefined;
|
|
2198
|
+
if (alias && ts.isStringLiteralLike(alias))
|
|
2199
|
+
inputAliases[m.name.text] = alias.text;
|
|
2200
|
+
}
|
|
2201
|
+
// An input with a default value (or `input<T>()` with implicit undefined) is one a parent may leave out.
|
|
2202
|
+
if (callee === 'input' || callee === 'model')
|
|
2203
|
+
optional.push(m.name.text);
|
|
2204
|
+
if (callee === 'output' || callee === 'model' || callee === 'model.required')
|
|
2205
|
+
outputs.push(m.name.text);
|
|
2206
|
+
}
|
|
2207
|
+
}
|
|
2208
|
+
for (const [field, alias] of classic?.aliases ?? [])
|
|
2209
|
+
inputAliases[field] = alias;
|
|
2210
|
+
for (const name of classic?.setters ?? []) {
|
|
2211
|
+
props.push(name);
|
|
2212
|
+
optional.push(name);
|
|
2213
|
+
}
|
|
2214
|
+
return { members, props, optional, outputs, inputAliases };
|
|
2215
|
+
}
|
|
2216
|
+
/** A file's component as an element hosting it sees it, when its selector names attributes. */
|
|
2217
|
+
export function hostedComponent(path, text) {
|
|
2218
|
+
const found = componentOf(path, text);
|
|
2219
|
+
if (!found?.selector || !ng.CssSelector.parse(found.selector).some((s) => s.attrs.length || s.classNames.length))
|
|
2220
|
+
return null;
|
|
2221
|
+
let sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
2222
|
+
const named = (f) => f.statements.find((s) => ts.isClassDeclaration(s) && s.name?.text === found.name);
|
|
2223
|
+
let cls = named(sf);
|
|
2224
|
+
const meta = decorator(cls, 'Component').arguments[0];
|
|
2225
|
+
const hostMeta = !!meta && ts.isObjectLiteralExpression(meta) && meta.properties.some((p) => p.name?.getText() === 'host');
|
|
2226
|
+
const hostDecorators = cls.members.some((m) => (ts.canHaveDecorators(m) ? ts.getDecorators(m) ?? [] : []).some((d) => /^(HostBinding|HostListener)\b/.test(d.expression.getText())));
|
|
2227
|
+
const classic = classicClass(path, text, cls);
|
|
2228
|
+
if (classic)
|
|
2229
|
+
cls = named((sf = ts.createSourceFile(path, classic.text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)));
|
|
2230
|
+
const api = publicMembers(path, cls, classic);
|
|
2231
|
+
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());
|
|
2232
|
+
return {
|
|
2233
|
+
name: found.name,
|
|
2234
|
+
selector: found.selector,
|
|
2235
|
+
inputs: new Set(api.props.map((p) => api.inputAliases[p] ?? p)),
|
|
2236
|
+
outputs: new Set(api.outputs),
|
|
2237
|
+
models: new Set(models),
|
|
2238
|
+
readsHost: hostMeta || hostDecorators || !!classic?.host || /\binject\(\s*ElementRef\b/.test(cls.getText()),
|
|
2239
|
+
};
|
|
2240
|
+
}
|
|
2241
|
+
/** The element names a component's selector matches (`resource, [talkResource]` is `<resource>`; its attribute is `hostedComponent`'s). */
|
|
2242
|
+
export function selectorElements(selector) {
|
|
2243
|
+
return ng.CssSelector.parse(selector).flatMap((s) => (s.element && s.element !== '*' && !s.attrs.length && !s.classNames.length && !s.notSelectors.length ? [s.element] : []));
|
|
2244
|
+
}
|
|
2245
|
+
/** A file's `@Component` class and the selector it declares. */
|
|
2246
|
+
export function componentOf(path, text) {
|
|
2247
|
+
if (!text.includes('@Component'))
|
|
2248
|
+
return null;
|
|
2249
|
+
const sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
2250
|
+
for (const st of sf.statements) {
|
|
2251
|
+
const meta = ts.isClassDeclaration(st) && st.name ? decorator(st, 'Component')?.arguments[0] : undefined;
|
|
2252
|
+
if (!meta)
|
|
2253
|
+
continue;
|
|
2254
|
+
const selector = ts.isObjectLiteralExpression(meta) ? meta.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'selector')?.initializer : undefined;
|
|
2255
|
+
return { name: st.name.text, selector: selector && ts.isStringLiteralLike(selector) ? selector.text : undefined };
|
|
2256
|
+
}
|
|
2257
|
+
return null;
|
|
2258
|
+
}
|
|
2259
|
+
/** @nativescript/angular's platform filters (`<android>`, `<ios>`, `<apple>`) and the platforms each renders its content on. */
|
|
2260
|
+
const PLATFORM_FILTERS = { android: ['android'], ios: ['ios'], apple: ['ios'] };
|
|
2261
|
+
/** Words a template's expression can name as a member that TypeScript reads as a keyword. */
|
|
2262
|
+
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']);
|
|
2263
|
+
/** NSRouterLink's inputs: on an element with `nsRouterLink` they are the directive's, not the view's. */
|
|
2264
|
+
const ROUTER_LINK_INPUTS = new Set(['nsRouterLink', 'relativeTo', 'clearHistory', 'pageTransition', 'pageTransitionDuration', 'queryParams', 'fragment', 'queryParamsHandling', 'state', 'info', 'preserveFragment', 'skipLocationChange', 'replaceUrl']);
|
|
2265
|
+
const ROUTER_LINK_SUPPORTED = new Set(['nsRouterLink', 'relativeTo', 'clearHistory', 'pageTransition', 'pageTransitionDuration']);
|
|
2266
|
+
/**
|
|
2267
|
+
* `@Component({ providers })`: the component's own injector, made by its first field and current until its constructor
|
|
2268
|
+
* returns, so that its fields and constructor inject from it as its view does.
|
|
2269
|
+
*/
|
|
2270
|
+
function withInjector(path, text, cls, providers) {
|
|
2271
|
+
// A base class's fields are made before the component's first field.
|
|
2272
|
+
if (cls.heritageClauses?.some((h) => h.token === ts.SyntaxKind.ExtendsKeyword))
|
|
2273
|
+
throw new Error(`${path}: @Component's providers on a class that extends another are not supported in a release build yet`);
|
|
2274
|
+
if (!ts.isArrayLiteralExpression(providers))
|
|
2275
|
+
throw new Error(`${path}: @Component's providers are read as an array literal in a release build`);
|
|
2276
|
+
for (const e of providers.elements)
|
|
2277
|
+
checkProvider(path, e);
|
|
2278
|
+
const leave = 'this.$injector.leave();';
|
|
2279
|
+
const edits = [{ at: cls.members.pos, text: `\n readonly $injector = NodeInjector.enter(${providers.getText()});` }];
|
|
2280
|
+
const ctor = cls.members.find((m) => ts.isConstructorDeclaration(m) && !!m.body);
|
|
2281
|
+
if (ctor?.body) {
|
|
2282
|
+
const returns = (n) => {
|
|
2283
|
+
if (ts.isFunctionLike(n) || ts.isClassLike(n))
|
|
2284
|
+
return;
|
|
2285
|
+
if (ts.isReturnStatement(n))
|
|
2286
|
+
edits.push({ at: n.getStart(), text: `{ ${leave} ` }, { at: n.getEnd(), text: ' }' });
|
|
2287
|
+
else
|
|
2288
|
+
ts.forEachChild(n, returns);
|
|
2289
|
+
};
|
|
2290
|
+
ctor.body.statements.forEach(returns);
|
|
2291
|
+
edits.push({ at: ctor.body.getEnd() - 1, text: `${leave} ` });
|
|
2292
|
+
}
|
|
2293
|
+
else
|
|
2294
|
+
edits.push({ at: cls.members.end, text: `\n constructor() { ${leave} }\n` });
|
|
2295
|
+
let out = text;
|
|
2296
|
+
for (const e of edits.sort((a, b) => b.at - a.at))
|
|
2297
|
+
out = out.slice(0, e.at) + e.text + out.slice(e.at);
|
|
2298
|
+
return out;
|
|
2299
|
+
}
|
|
2300
|
+
/**
|
|
2301
|
+
* `@Self()`, `@SkipSelf()`, `@Host()` and their `inject()` options in a component with providers: which injector they
|
|
2302
|
+
* start or stop at is not modelled, so a component's own provider would answer where Angular asks its parent.
|
|
2303
|
+
*/
|
|
2304
|
+
function refuseScopedInjection(path, cls) {
|
|
2305
|
+
const visit = (n) => {
|
|
2306
|
+
if (ts.isDecorator(n) && ts.isCallExpression(n.expression) && ['Self', 'SkipSelf', 'Host'].includes(n.expression.expression.getText())) {
|
|
2307
|
+
throw new Error(`${path}: @${n.expression.expression.getText()}() in a component with providers is not supported in a release build yet`);
|
|
2308
|
+
}
|
|
2309
|
+
if (ts.isCallExpression(n) && n.expression.getText() === 'inject' && n.arguments[1] && ts.isObjectLiteralExpression(n.arguments[1])) {
|
|
2310
|
+
const scoped = n.arguments[1].properties.find((p) => ['self', 'skipSelf', 'host'].includes(p.name?.getText() ?? ''));
|
|
2311
|
+
if (scoped)
|
|
2312
|
+
throw new Error(`${path}: inject()'s ${scoped.name.getText()} in a component with providers is not supported in a release build yet`);
|
|
2313
|
+
}
|
|
2314
|
+
ts.forEachChild(n, visit);
|
|
2315
|
+
};
|
|
2316
|
+
cls.members.forEach(visit);
|
|
2317
|
+
}
|
|
2318
|
+
/** A component provider the release build makes: a class, or `{ provide, useClass | useValue | useFactory (and deps) | useExisting }`. */
|
|
2319
|
+
function checkProvider(path, e) {
|
|
2320
|
+
const what = `${path}: the provider ${e.getText().split('\n')[0]} in @Component's providers`;
|
|
2321
|
+
if (ts.isIdentifier(e))
|
|
2322
|
+
return;
|
|
2323
|
+
if (!ts.isObjectLiteralExpression(e))
|
|
2324
|
+
throw new Error(`${what} is not supported in a release build yet`);
|
|
2325
|
+
const fields = new Map();
|
|
2326
|
+
for (const p of e.properties) {
|
|
2327
|
+
if (ts.isPropertyAssignment(p) && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)))
|
|
2328
|
+
fields.set(p.name.text, p.initializer);
|
|
2329
|
+
else if (ts.isShorthandPropertyAssignment(p))
|
|
2330
|
+
fields.set(p.name.text, p.name);
|
|
2331
|
+
else
|
|
2332
|
+
throw new Error(`${what} is read as \`{ provide: token, useClass: X }\` in a release build`);
|
|
2333
|
+
}
|
|
2334
|
+
for (const k of fields.keys())
|
|
2335
|
+
if (!['provide', 'useClass', 'useValue', 'useFactory', 'useExisting', 'deps'].includes(k))
|
|
2336
|
+
throw new Error(`${what}: its ${k} is not supported in a release build yet`);
|
|
2337
|
+
const uses = ['useClass', 'useValue', 'useFactory', 'useExisting'].filter((k) => fields.has(k));
|
|
2338
|
+
if (!fields.has('provide') || uses.length !== 1)
|
|
2339
|
+
throw new Error(`${what} needs provide and one of useClass, useValue, useFactory or useExisting`);
|
|
2340
|
+
const deps = fields.get('deps');
|
|
2341
|
+
if (deps && (uses[0] !== 'useFactory' || !ts.isArrayLiteralExpression(deps) || deps.elements.some((d) => !ts.isIdentifier(d) && !ts.isPropertyAccessExpression(d)))) {
|
|
2342
|
+
throw new Error(`${what}: deps other than a list of tokens for useFactory are not supported in a release build yet`);
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
/**
|
|
2346
|
+
* The `@Component` fields a release build reads, and those it may leave unread: `standalone`, `schemas`, `moduleId` and
|
|
2347
|
+
* `jit` only steer Angular's compiler, `exportAs` names the component a reference gets anyway, `animations` only
|
|
2348
|
+
* declares triggers (binding one is refused), and `preserveWhitespaces: false` is how templates are parsed.
|
|
2349
|
+
*/
|
|
2350
|
+
const COMPONENT_META = new Set([
|
|
2351
|
+
'selector', 'template', 'templateUrl', 'styles', 'styleUrl', 'styleUrls', 'imports', 'changeDetection', 'encapsulation',
|
|
2352
|
+
'standalone', 'schemas', 'moduleId', 'jit', 'exportAs', 'animations', 'preserveWhitespaces', 'providers',
|
|
2353
|
+
]);
|
|
2354
|
+
/** Decorator fields named in the plural, for messages. */
|
|
2355
|
+
const PLURAL_FIELDS = new Set(['providers', 'viewProviders', 'inputs', 'outputs', 'queries', 'hostDirectives', 'animations', 'schemas']);
|
|
2356
|
+
/** The directives of @angular/forms an element can select, in the order Angular runs them on one, and their selectors. */
|
|
2357
|
+
const FORMS_SELECTORS = [
|
|
2358
|
+
['RequiredValidator', ':not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]'],
|
|
2359
|
+
['MinLengthValidator', '[minlength][formControlName],[minlength][formControl],[minlength][ngModel]'],
|
|
2360
|
+
['MaxLengthValidator', '[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]'],
|
|
2361
|
+
['PatternValidator', '[pattern][formControlName],[pattern][formControl],[pattern][ngModel]'],
|
|
2362
|
+
['EmailValidator', '[email][formControlName],[email][formControl],[email][ngModel]'],
|
|
2363
|
+
['NgModel', '[ngModel]:not([formControlName]):not([formControl])'],
|
|
2364
|
+
['NgModelGroup', '[ngModelGroup]'],
|
|
2365
|
+
['NgForm', 'form:not([ngNoForm]):not([formGroup]):not([formArray]),ng-form,[ngForm]'],
|
|
2366
|
+
['FormControlDirective', '[formControl]'],
|
|
2367
|
+
['FormGroupDirective', '[formGroup]'],
|
|
2368
|
+
['FormArrayDirective', '[formArray]'],
|
|
2369
|
+
['FormControlName', '[formControlName]'],
|
|
2370
|
+
['FormGroupName', '[formGroupName]'],
|
|
2371
|
+
['FormArrayName', '[formArrayName]'],
|
|
2372
|
+
['DefaultValueAccessor', 'input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]'],
|
|
2373
|
+
];
|
|
2374
|
+
const FORMS_VALIDATORS = { RequiredValidator: 'required', MinLengthValidator: 'minlength', MaxLengthValidator: 'maxlength', PatternValidator: 'pattern', EmailValidator: 'email' };
|
|
2375
|
+
const FORMS_CONTROLS = new Set(['NgModel', 'FormControlDirective', 'FormControlName']);
|
|
2376
|
+
const FORMS_CONTAINERS = new Set(['NgForm', 'FormGroupDirective', 'FormArrayDirective', 'FormGroupName', 'FormArrayName', 'NgModelGroup']);
|
|
2377
|
+
const FORMS_TEMPLATE_DRIVEN = new Set(['NgModel', 'NgForm', 'NgModelGroup']);
|
|
2378
|
+
const FORMS_REACTIVE_PARENTS = new Set(['FormGroupDirective', 'FormArrayDirective', 'FormGroupName', 'FormArrayName']);
|
|
2379
|
+
/** A directive's exportAs, the name a template reference (`#f="ngForm"`) takes it by. */
|
|
2380
|
+
const FORMS_EXPORT_AS = { NgModel: 'ngModel', NgForm: 'ngForm', NgModelGroup: 'ngModelGroup', FormGroupDirective: 'ngForm', FormArrayDirective: 'ngForm', FormControlDirective: 'ngForm' };
|
|
2381
|
+
/**
|
|
2382
|
+
* @nativescript/angular's value accessors (NativeScriptFormsModule), by the element they select: the view's property
|
|
2383
|
+
* they write (`text` and `selectedIndex` have their own rules) and the event that changes it.
|
|
2384
|
+
*/
|
|
2385
|
+
const FORMS_ACCESSORS = {
|
|
2386
|
+
TextField: { kind: 'text', event: 'textChange', accessor: 'TextValueAccessor' },
|
|
2387
|
+
TextView: { kind: 'text', event: 'textChange', accessor: 'TextValueAccessor' },
|
|
2388
|
+
SearchBar: { kind: 'text', event: 'textChange', accessor: 'TextValueAccessor' },
|
|
2389
|
+
Switch: { kind: 'checked', event: 'checkedChange', accessor: 'CheckedValueAccessor' },
|
|
2390
|
+
DatePicker: { kind: 'date', event: 'dateChange', accessor: 'DateValueAccessor' },
|
|
2391
|
+
TimePicker: { kind: 'time', event: 'timeChange', accessor: 'TimeValueAccessor' },
|
|
2392
|
+
Slider: { kind: 'value', event: 'valueChange', accessor: 'NumberValueAccessor' },
|
|
2393
|
+
SegmentedBar: { kind: 'selectedIndex', event: 'selectedIndexChange', accessor: 'SelectedIndexValueAccessor' },
|
|
2394
|
+
ListPicker: { kind: 'selectedIndex', event: 'selectedIndexChange', accessor: 'SelectedIndexValueAccessor' },
|
|
2395
|
+
TabView: { kind: 'selectedIndex', event: 'selectedIndexChange', accessor: 'SelectedIndexValueAccessor' },
|
|
2396
|
+
};
|
|
2397
|
+
/** What selects a directive of @angular/forms (with @nativescript/angular's value accessors) on an element. */
|
|
2398
|
+
const FORMS_DIRECTIVES = new Set([
|
|
2399
|
+
'ngModel', 'ngModelChange', 'ngModelOptions', 'ngModelGroup', 'ngForm', 'ngFormOptions', 'ngNoForm', 'ngSubmit',
|
|
2400
|
+
'formGroup', 'formGroupName', 'formControl', 'formControlName', 'formArray', 'formArrayName',
|
|
2401
|
+
]);
|
|
2402
|
+
/** 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. */
|
|
2403
|
+
const UNSUPPORTED_DIRECTIVES = {
|
|
2404
|
+
ngClass: "@angular/common's NgClass",
|
|
2405
|
+
ngStyle: "@angular/common's NgStyle",
|
|
2406
|
+
ngPlural: "@angular/common's NgPlural",
|
|
2407
|
+
ngPluralCase: "@angular/common's NgPluralCase",
|
|
2408
|
+
ngComponentOutlet: "@angular/common's NgComponentOutlet",
|
|
2409
|
+
ngTemplateOutlet: "@angular/common's NgTemplateOutlet, which a release build runs on <ng-container>",
|
|
2410
|
+
ngTemplateOutletContext: "@angular/common's NgTemplateOutlet, which a release build runs on <ng-container>",
|
|
2411
|
+
ngIf: '@angular/common\'s NgIf without its template (*ngIf)',
|
|
2412
|
+
ngIfElse: '@angular/common\'s NgIf without its template (*ngIf)',
|
|
2413
|
+
ngIfThen: '@angular/common\'s NgIf without its template (*ngIf)',
|
|
2414
|
+
ngForOf: '@angular/common\'s NgForOf without its template (*ngFor)',
|
|
2415
|
+
ngForTrackBy: '@angular/common\'s NgForOf without its template (*ngFor)',
|
|
2416
|
+
ngSwitchCase: '@angular/common\'s NgSwitchCase without its template (*ngSwitchCase)',
|
|
2417
|
+
ngSwitchDefault: '@angular/common\'s NgSwitchDefault without its template (*ngSwitchDefault)',
|
|
2418
|
+
routerLink: "@angular/router's RouterLink; nsRouterLink is supported",
|
|
2419
|
+
routerLinkActive: "@angular/router's RouterLinkActive",
|
|
2420
|
+
routerLinkActiveOptions: "@angular/router's RouterLinkActive",
|
|
2421
|
+
nsRouterLinkActiveOptions: "@nativescript/angular's NSRouterLinkActive",
|
|
2422
|
+
'animate.enter': "Angular's enter animation",
|
|
2423
|
+
'animate.leave': "Angular's leave animation",
|
|
2424
|
+
};
|
|
2425
|
+
/** Whether the file imports `name` from `module` under its own name. */
|
|
2426
|
+
function importsAs(sf, name, module) {
|
|
2427
|
+
return sf.statements.some((s) => ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.moduleSpecifier.text === module && !s.importClause?.isTypeOnly
|
|
2428
|
+
&& !!s.importClause?.namedBindings && ts.isNamedImports(s.importClause.namedBindings)
|
|
2429
|
+
&& s.importClause.namedBindings.elements.some((e) => e.name.text === name && (e.propertyName?.text ?? name) === name && !e.isTypeOnly));
|
|
2430
|
+
}
|
|
2431
|
+
/** Whether a top-level import or declaration of the file binds `name`. */
|
|
2432
|
+
function declares(sf, name) {
|
|
2433
|
+
return sf.statements.some((s) => {
|
|
2434
|
+
if (ts.isImportDeclaration(s)) {
|
|
2435
|
+
const c = s.importClause;
|
|
2436
|
+
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)));
|
|
2437
|
+
}
|
|
2438
|
+
if (ts.isVariableStatement(s))
|
|
2439
|
+
return s.declarationList.declarations.some((d) => ts.isIdentifier(d.name) && d.name.text === name);
|
|
2440
|
+
return (ts.isFunctionDeclaration(s) || ts.isClassDeclaration(s)) && s.name?.text === name;
|
|
2441
|
+
});
|
|
2442
|
+
}
|
|
2443
|
+
function sourceOf(ast) {
|
|
2444
|
+
const s = ast.source;
|
|
2445
|
+
if (s == null)
|
|
2446
|
+
throw new Error('an Angular expression without source text');
|
|
2447
|
+
return s;
|
|
2448
|
+
}
|
|
2449
|
+
/**
|
|
2450
|
+
* The route fields a release build reads, and those it may leave unread: `title` (a native screen has no window title
|
|
2451
|
+
* for it) and `runGuardsAndResolvers` (with no guards or resolvers, nothing it steers runs).
|
|
2452
|
+
*/
|
|
2453
|
+
const ROUTE_FIELDS = new Set(['path', 'pathMatch', 'component', 'loadComponent', 'redirectTo', 'outlet', 'children', 'loadChildren', 'data', 'title', 'runGuardsAndResolvers']);
|
|
2454
|
+
const ROUTE_GUARDS = new Set(['canActivate', 'canActivateChild', 'canDeactivate', 'canMatch', 'canLoad']);
|
|
2455
|
+
/** The guards the release build's router runs, each with the arguments Angular calls it with. */
|
|
2456
|
+
const RUN_GUARDS = { canActivate: 2, canActivateChild: 2, canDeactivate: 4, canMatch: 2 };
|
|
2457
|
+
const lineOf = (n) => ts.getLineAndCharacterOfPosition(n.getSourceFile(), n.getStart()).line + 1;
|
|
2458
|
+
/** A literal's value, undefined for anything else. */
|
|
2459
|
+
function literalConstant(e) {
|
|
2460
|
+
return ts.isStringLiteralLike(e) ? e.text : undefined;
|
|
2461
|
+
}
|
|
2462
|
+
/**
|
|
2463
|
+
* An expression of a route file as the value it always has: literals, `const` names, enum members, templates and `+`
|
|
2464
|
+
* over them, followed through the file's imports. Undefined when it is not a compile-time constant.
|
|
2465
|
+
*/
|
|
2466
|
+
function routeConstant(file, e, parse, fileOf, depth = 0) {
|
|
2467
|
+
if (depth > 20)
|
|
2468
|
+
return undefined;
|
|
2469
|
+
const of = (f, x) => routeConstant(f, x, parse, fileOf, depth + 1);
|
|
2470
|
+
while (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e) || ts.isNonNullExpression(e))
|
|
2471
|
+
e = e.expression;
|
|
2472
|
+
if (ts.isStringLiteralLike(e))
|
|
2473
|
+
return e.text;
|
|
2474
|
+
if (ts.isNumericLiteral(e))
|
|
2475
|
+
return Number(e.text);
|
|
2476
|
+
if (ts.isPrefixUnaryExpression(e) && e.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(e.operand))
|
|
2477
|
+
return -Number(e.operand.text);
|
|
2478
|
+
if (e.kind === ts.SyntaxKind.TrueKeyword)
|
|
2479
|
+
return true;
|
|
2480
|
+
if (e.kind === ts.SyntaxKind.FalseKeyword)
|
|
2481
|
+
return false;
|
|
2482
|
+
if (e.kind === ts.SyntaxKind.NullKeyword)
|
|
2483
|
+
return null;
|
|
2484
|
+
if (ts.isTemplateExpression(e)) {
|
|
2485
|
+
let text = e.head.text;
|
|
2486
|
+
for (const span of e.templateSpans) {
|
|
2487
|
+
const v = of(file, span.expression);
|
|
2488
|
+
if (v === undefined)
|
|
2489
|
+
return undefined;
|
|
2490
|
+
text += String(v) + span.literal.text;
|
|
2491
|
+
}
|
|
2492
|
+
return text;
|
|
2493
|
+
}
|
|
2494
|
+
if (ts.isBinaryExpression(e) && e.operatorToken.kind === ts.SyntaxKind.PlusToken) {
|
|
2495
|
+
const a = of(file, e.left), b = of(file, e.right);
|
|
2496
|
+
if (a === undefined || b === undefined)
|
|
2497
|
+
return undefined;
|
|
2498
|
+
return typeof a === 'string' || typeof b === 'string' ? String(a) + String(b) : typeof a === 'number' && typeof b === 'number' ? a + b : undefined;
|
|
2499
|
+
}
|
|
2500
|
+
if (ts.isIdentifier(e)) {
|
|
2501
|
+
const d = declarationOf(file, e.text, parse, fileOf);
|
|
2502
|
+
const list = d && ts.isVariableDeclaration(d) ? d.parent : undefined;
|
|
2503
|
+
return d && ts.isVariableDeclaration(d) && list && ts.isVariableDeclarationList(list) && list.flags & ts.NodeFlags.Const && d.initializer ? of(d.getSourceFile().fileName, d.initializer) : undefined;
|
|
2504
|
+
}
|
|
2505
|
+
if (ts.isPropertyAccessExpression(e) && ts.isIdentifier(e.expression)) {
|
|
2506
|
+
const d = declarationOf(file, e.expression.text, parse, fileOf);
|
|
2507
|
+
if (!d || !ts.isEnumDeclaration(d) || d.modifiers?.some((m) => m.kind === ts.SyntaxKind.DeclareKeyword))
|
|
2508
|
+
return undefined;
|
|
2509
|
+
let next = 0;
|
|
2510
|
+
for (const m of d.members) {
|
|
2511
|
+
const v = m.initializer ? of(d.getSourceFile().fileName, m.initializer) : next;
|
|
2512
|
+
if (m.name.getText() === e.name.text || (ts.isStringLiteral(m.name) && m.name.text === e.name.text))
|
|
2513
|
+
return v;
|
|
2514
|
+
next = typeof v === 'number' ? v + 1 : undefined;
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
2517
|
+
return undefined;
|
|
2518
|
+
}
|
|
2519
|
+
/** A route's `data` as its entries in order, each value a compile-time constant; undefined when it is anything else. */
|
|
2520
|
+
function routeData(e, constant) {
|
|
2521
|
+
while (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e))
|
|
2522
|
+
e = e.expression;
|
|
2523
|
+
if (!ts.isObjectLiteralExpression(e))
|
|
2524
|
+
return undefined;
|
|
2525
|
+
const entries = new Map();
|
|
2526
|
+
for (const p of e.properties) {
|
|
2527
|
+
if (!ts.isPropertyAssignment(p) || !(ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)))
|
|
2528
|
+
return undefined;
|
|
2529
|
+
const v = constant(p.initializer);
|
|
2530
|
+
if (v === undefined)
|
|
2531
|
+
return undefined;
|
|
2532
|
+
entries.set(p.name.text, v);
|
|
2533
|
+
}
|
|
2534
|
+
return [...entries];
|
|
2535
|
+
}
|
|
2536
|
+
/** A route's fields, each one the release build reads as Angular's router does, or may leave unread. */
|
|
2537
|
+
function routeFields(file, route, guards = false, constant = literalConstant) {
|
|
2538
|
+
const pathOf = route.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'path')?.initializer;
|
|
2539
|
+
const pathText = pathOf && constant(pathOf);
|
|
2540
|
+
const named = typeof pathText === 'string' ? ` on '${pathText}'` : '';
|
|
2541
|
+
for (const p of route.properties) {
|
|
2542
|
+
const at = `${file}:${lineOf(p)}`;
|
|
2543
|
+
if (!ts.isPropertyAssignment(p) || !(ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)))
|
|
2544
|
+
throw new Error(`${at}: a route's ${p.getText().split('\n')[0]} is read as \`name: value\` in a release build`);
|
|
2545
|
+
const key = p.name.text;
|
|
2546
|
+
const v = p.initializer;
|
|
2547
|
+
if (ROUTE_GUARDS.has(key) && !(guards && key in RUN_GUARDS))
|
|
2548
|
+
throw new Error(`${at}: route guards (${key}${named}) are not supported in a release build yet`);
|
|
2549
|
+
if (key in RUN_GUARDS && !ts.isArrayLiteralExpression(v))
|
|
2550
|
+
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`);
|
|
2551
|
+
if (key === 'canMatch' && route.properties.some((q) => q.name?.getText() === 'redirectTo'))
|
|
2552
|
+
throw new Error(`${at}: canMatch on a redirect${named} is not supported in a release build yet`);
|
|
2553
|
+
if (key === 'resolve')
|
|
2554
|
+
throw new Error(`${at}: route resolvers (resolve${named}) are not supported in a release build yet`);
|
|
2555
|
+
if (!ROUTE_FIELDS.has(key) && !(key in RUN_GUARDS))
|
|
2556
|
+
throw new Error(`${at}: a route's ${key}${named} is not supported in a release build yet`);
|
|
2557
|
+
if (['path', 'pathMatch', 'redirectTo', 'outlet'].includes(key) && typeof constant(v) !== 'string')
|
|
2558
|
+
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`);
|
|
2559
|
+
if (key === 'data' && !routeData(v, constant)) {
|
|
2560
|
+
const bad = ts.isObjectLiteralExpression(v) ? v.properties.find((q) => !ts.isPropertyAssignment(q) || !routeData(ts.factory.createObjectLiteralExpression([q]), constant)) : undefined;
|
|
2561
|
+
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`);
|
|
2562
|
+
}
|
|
2563
|
+
if (key === 'component' && !ts.isIdentifier(v))
|
|
2564
|
+
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`);
|
|
2565
|
+
}
|
|
2566
|
+
}
|
|
2567
|
+
/**
|
|
2568
|
+
* The router's options beside its routes: `withPreloading` (lazy routes are linked in) and `withDebugTracing` (only logs)
|
|
2569
|
+
* change nothing a release build does, and of forRoot's options `enableTracing`, `useHash`, `preloadingStrategy` and the
|
|
2570
|
+
* scrolling ones, which a native page has no use for.
|
|
2571
|
+
*/
|
|
2572
|
+
function routerOptions(file, call) {
|
|
2573
|
+
const at = `${file}:${lineOf(call)}`;
|
|
2574
|
+
if (/(^|\.)forRoot$/.test(call.expression.getText())) {
|
|
2575
|
+
const options = call.arguments[1];
|
|
2576
|
+
if (!options)
|
|
2577
|
+
return;
|
|
2578
|
+
if (!ts.isObjectLiteralExpression(options))
|
|
2579
|
+
throw new Error(`${at}: the router's options (${options.getText()}) are not supported in a release build yet`);
|
|
2580
|
+
for (const p of options.properties) {
|
|
2581
|
+
const key = p.name?.getText() ?? p.getText();
|
|
2582
|
+
if (!['enableTracing', 'useHash', 'preloadingStrategy', 'scrollPositionRestoration', 'anchorScrolling', 'scrollOffset'].includes(key))
|
|
2583
|
+
throw new Error(`${at}: the router option ${key} is not supported in a release build yet`);
|
|
2584
|
+
}
|
|
2585
|
+
return;
|
|
2586
|
+
}
|
|
2587
|
+
for (const f of call.arguments.slice(1)) {
|
|
2588
|
+
const name = ts.isCallExpression(f) ? f.expression.getText() : f.getText();
|
|
2589
|
+
if (!['withPreloading', 'withDebugTracing'].includes(name))
|
|
2590
|
+
throw new Error(`${at}: the router feature ${name}() is not supported in a release build yet`);
|
|
2591
|
+
}
|
|
2592
|
+
}
|
|
2593
|
+
/** What a class or function name resolves to across the app's files: the declaration, else null (a package's, or not found). */
|
|
2594
|
+
function declarationOf(file, name, parse, fileOf, seen = new Set()) {
|
|
2595
|
+
if (seen.has(`${file}#${name}`))
|
|
2596
|
+
return null;
|
|
2597
|
+
seen.add(`${file}#${name}`);
|
|
2598
|
+
const sf = parse(file);
|
|
2599
|
+
for (const st of sf.statements) {
|
|
2600
|
+
if ((ts.isClassDeclaration(st) || ts.isFunctionDeclaration(st) || ts.isEnumDeclaration(st)) && st.name?.text === name)
|
|
2601
|
+
return st;
|
|
2602
|
+
if (ts.isVariableStatement(st)) {
|
|
2603
|
+
const d = st.declarationList.declarations.find((x) => ts.isIdentifier(x.name) && x.name.text === name);
|
|
2604
|
+
if (d)
|
|
2605
|
+
return d;
|
|
2606
|
+
}
|
|
2607
|
+
if ((ts.isImportDeclaration(st) || ts.isExportDeclaration(st)) && st.moduleSpecifier && ts.isStringLiteral(st.moduleSpecifier)) {
|
|
2608
|
+
const bindings = ts.isImportDeclaration(st) ? st.importClause?.namedBindings : st.exportClause;
|
|
2609
|
+
if (!bindings || ts.isNamespaceImport(bindings) || ts.isNamespaceExport(bindings))
|
|
2610
|
+
continue;
|
|
2611
|
+
const el = bindings.elements.find((e) => e.name.text === name);
|
|
2612
|
+
const target = el ? fileOf(file, st.moduleSpecifier.text) : undefined;
|
|
2613
|
+
if (el)
|
|
2614
|
+
return target ? declarationOf(target, (el.propertyName ?? el.name).text, parse, fileOf, seen) : null;
|
|
2615
|
+
}
|
|
2616
|
+
}
|
|
2617
|
+
return null;
|
|
2618
|
+
}
|
|
2619
|
+
/** The top-level names a node refers to, in value and type positions. */
|
|
2620
|
+
function namesIn(node, into = new Set()) {
|
|
2621
|
+
const visit = (n) => {
|
|
2622
|
+
if (ts.isIdentifier(n)) {
|
|
2623
|
+
const p = n.parent;
|
|
2624
|
+
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);
|
|
2625
|
+
if (!member)
|
|
2626
|
+
into.add(n.text);
|
|
2627
|
+
}
|
|
2628
|
+
ts.forEachChild(n, visit);
|
|
2629
|
+
};
|
|
2630
|
+
visit(node);
|
|
2631
|
+
return into;
|
|
2632
|
+
}
|
|
2633
|
+
/** A specifier as written in `from`, for a module in `appDir`. */
|
|
2634
|
+
function respecify(from, spec, appDir) {
|
|
2635
|
+
if (!spec.startsWith('.'))
|
|
2636
|
+
return spec;
|
|
2637
|
+
const r = relative(appDir, join(dirname(from), spec)).split('\\').join('/');
|
|
2638
|
+
return r.startsWith('.') ? r : './' + r;
|
|
2639
|
+
}
|
|
2640
|
+
function guardModule(file, sf, guards) {
|
|
2641
|
+
// The route file's imports and declarations the guards need, followed through the declarations they need in turn.
|
|
2642
|
+
const needed = new Set();
|
|
2643
|
+
const pending = guards.map((g) => g.expr);
|
|
2644
|
+
const declared = new Map();
|
|
2645
|
+
for (const st of sf.statements) {
|
|
2646
|
+
const names = ts.isVariableStatement(st) ? st.declarationList.declarations.flatMap((d) => (ts.isIdentifier(d.name) ? [d.name.text] : []))
|
|
2647
|
+
: (ts.isFunctionDeclaration(st) || ts.isClassDeclaration(st) || ts.isInterfaceDeclaration(st) || ts.isTypeAliasDeclaration(st) || ts.isEnumDeclaration(st)) && st.name ? [st.name.text] : [];
|
|
2648
|
+
for (const n of names)
|
|
2649
|
+
declared.set(n, st);
|
|
2650
|
+
}
|
|
2651
|
+
const copied = new Set();
|
|
2652
|
+
// The translators name imported kit declarations by their own names, so no alias: a class guard's inject is the route
|
|
2653
|
+
// file's own import of it when it has one.
|
|
2654
|
+
if (guards.some((g) => g.inject))
|
|
2655
|
+
needed.add('inject');
|
|
2656
|
+
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));
|
|
2657
|
+
while (pending.length) {
|
|
2658
|
+
for (const n of namesIn(pending.pop())) {
|
|
2659
|
+
if (needed.has(n))
|
|
2660
|
+
continue;
|
|
2661
|
+
needed.add(n);
|
|
2662
|
+
const st = declared.get(n);
|
|
2663
|
+
if (st && !copied.has(st)) {
|
|
2664
|
+
copied.add(st);
|
|
2665
|
+
pending.push(st);
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
}
|
|
2669
|
+
return {
|
|
2670
|
+
file,
|
|
2671
|
+
source(appDir, platform) {
|
|
2672
|
+
const lines = [];
|
|
2673
|
+
for (const st of sf.statements) {
|
|
2674
|
+
if (!ts.isImportDeclaration(st) || !ts.isStringLiteral(st.moduleSpecifier) || !st.importClause)
|
|
2675
|
+
continue;
|
|
2676
|
+
const c = st.importClause;
|
|
2677
|
+
const spec = JSON.stringify(respecify(file, st.moduleSpecifier.text, appDir));
|
|
2678
|
+
const type = c.isTypeOnly ? 'type ' : '';
|
|
2679
|
+
if (c.name && needed.has(c.name.text))
|
|
2680
|
+
lines.push(`import ${type}${c.name.text} from ${spec};`);
|
|
2681
|
+
if (c.namedBindings && ts.isNamespaceImport(c.namedBindings) && needed.has(c.namedBindings.name.text))
|
|
2682
|
+
lines.push(`import ${type}* as ${c.namedBindings.name.text} from ${spec};`);
|
|
2683
|
+
if (c.namedBindings && ts.isNamedImports(c.namedBindings)) {
|
|
2684
|
+
const els = c.namedBindings.elements.filter((e) => needed.has(e.name.text)).map((e) => e.getText());
|
|
2685
|
+
if (els.length)
|
|
2686
|
+
lines.push(`import ${type}{ ${els.join(', ')} } from ${spec};`);
|
|
2687
|
+
}
|
|
2688
|
+
}
|
|
2689
|
+
lines.push("import { KitRouter } from '@angular#kit';");
|
|
2690
|
+
if (guards.some((g) => g.inject) && !importsInject)
|
|
2691
|
+
lines.push("import { inject } from '@angular/core';");
|
|
2692
|
+
// A compiled rxjs Observable is the app's own class on iOS, which the kit can't read: firstValueFrom there.
|
|
2693
|
+
if (platform === 'ios')
|
|
2694
|
+
lines.push("import { ɵguardResult } from '@angular/router';");
|
|
2695
|
+
lines.push(...sf.statements.filter((st) => copied.has(st)).map((st) => st.getText()));
|
|
2696
|
+
const settle = (e) => (platform === 'ios' ? `ɵguardResult(${e})` : e);
|
|
2697
|
+
const params = ['a', 'b', 'c', 'd'];
|
|
2698
|
+
const all = params.map((p) => `${p}: any`).join(', ');
|
|
2699
|
+
guards.forEach((g, i) => {
|
|
2700
|
+
const arity = RUN_GUARDS[g.kind];
|
|
2701
|
+
if (g.inject) {
|
|
2702
|
+
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(', ')})`)});`);
|
|
2703
|
+
}
|
|
2704
|
+
else {
|
|
2705
|
+
// Evaluated once, as Angular reads its route configuration once: a guard factory's call runs at startup.
|
|
2706
|
+
lines.push(`const ɵguard${i}: (${params.slice(0, arity).map((p) => `${p}: any`).join(', ')}) => any = ${g.expr.getText()};`);
|
|
2707
|
+
lines.push(`KitRouter.shared.addGuard(${g.route}, '${g.kind}', (${all}): any => ${settle(`ɵguard${i}(${params.slice(0, arity).join(', ')})`)});`);
|
|
2708
|
+
}
|
|
2709
|
+
});
|
|
2710
|
+
return lines.join('\n') + '\n';
|
|
2711
|
+
},
|
|
2712
|
+
};
|
|
2713
|
+
}
|
|
2714
|
+
/**
|
|
2715
|
+
* The router configuration the entry provides (`provideNativeScriptRouter(routes)`,
|
|
2716
|
+
* `NativeScriptRouterModule.forRoot(routes)`), followed through `loadChildren` and
|
|
2717
|
+
* `loadComponent` into the files they import. A route whose component is `NSEmptyOutletComponent` is marked
|
|
2718
|
+
* `emptyOutlet`: its children render in a frame of their own, on a page of the outlet the route names.
|
|
2719
|
+
*/
|
|
2720
|
+
export function angularRouteTree(entry, read, aliased = () => undefined) {
|
|
2721
|
+
const files = new Set();
|
|
2722
|
+
const parsed = new Map();
|
|
2723
|
+
const parse = (f) => parsed.get(f) ?? parsed.set(f, ts.createSourceFile(f, read(f), ts.ScriptTarget.Latest, true)).get(f);
|
|
2724
|
+
const guards = new Map();
|
|
2725
|
+
let guardIds = 0;
|
|
2726
|
+
/** A relative specifier, or one of the app's path aliases (`~/app/x`), as the file it names. */
|
|
2727
|
+
const fileOf = (from, spec) => {
|
|
2728
|
+
const base = spec.startsWith('.') ? join(dirname(from), spec) : aliased(spec);
|
|
2729
|
+
return base === undefined ? undefined : [base + '.ts', join(base, 'index.ts')].find((p) => existsSync(p));
|
|
2730
|
+
};
|
|
2731
|
+
/** The array a name declares in a file, or imports into it. */
|
|
2732
|
+
const arrayNamed = (file, name) => {
|
|
2733
|
+
const sf = parse(file);
|
|
2734
|
+
for (const st of sf.statements) {
|
|
2735
|
+
if (ts.isVariableStatement(st)) {
|
|
2736
|
+
for (const d of st.declarationList.declarations) {
|
|
2737
|
+
if (ts.isIdentifier(d.name) && d.name.text === name && d.initializer && ts.isArrayLiteralExpression(d.initializer))
|
|
2738
|
+
return { file, array: d.initializer };
|
|
2739
|
+
}
|
|
2740
|
+
}
|
|
2741
|
+
if (ts.isImportDeclaration(st) && st.importClause?.namedBindings && ts.isNamedImports(st.importClause.namedBindings) && ts.isStringLiteral(st.moduleSpecifier)) {
|
|
2742
|
+
const el = st.importClause.namedBindings.elements.find((e) => e.name.text === name);
|
|
2743
|
+
const target = el ? fileOf(file, st.moduleSpecifier.text) : undefined;
|
|
2744
|
+
if (target)
|
|
2745
|
+
return arrayNamed(target, (el.propertyName ?? el.name).text);
|
|
2746
|
+
}
|
|
2747
|
+
}
|
|
2748
|
+
return null;
|
|
2749
|
+
};
|
|
2750
|
+
/** `() => import('./x').then((m) => m.Name)`: the file and the name. */
|
|
2751
|
+
const lazy = (file, e) => {
|
|
2752
|
+
const body = ts.isArrowFunction(e) && !ts.isBlock(e.body) ? e.body : undefined;
|
|
2753
|
+
const then = body && ts.isCallExpression(body) && ts.isPropertyAccessExpression(body.expression) && body.expression.name.text === 'then' ? body : undefined;
|
|
2754
|
+
const load = then && ts.isCallExpression(then.expression.expression) && then.expression.expression.expression.kind === ts.SyntaxKind.ImportKeyword ? then.expression.expression : undefined;
|
|
2755
|
+
const pick = then?.arguments[0];
|
|
2756
|
+
const name = pick && ts.isArrowFunction(pick) && ts.isPropertyAccessExpression(pick.body) ? pick.body.name.text : undefined;
|
|
2757
|
+
const spec = load?.arguments[0];
|
|
2758
|
+
const target = spec && ts.isStringLiteral(spec) ? fileOf(file, spec.text) : undefined;
|
|
2759
|
+
if (!target || !name)
|
|
2760
|
+
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`);
|
|
2761
|
+
return { file: target, name };
|
|
2762
|
+
};
|
|
2763
|
+
const routesOf = (file, array, parent) => {
|
|
2764
|
+
files.add(file);
|
|
2765
|
+
return array.elements.map((el) => {
|
|
2766
|
+
if (!ts.isObjectLiteralExpression(el))
|
|
2767
|
+
throw new Error(`${file}: a route is an object literal in a release build`);
|
|
2768
|
+
const constant = (e) => routeConstant(file, e, parse, fileOf);
|
|
2769
|
+
routeFields(file, el, true, constant);
|
|
2770
|
+
const get = (k) => el.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === k)?.initializer;
|
|
2771
|
+
const text = (k) => { const v = get(k); const c = v && constant(v); return typeof c === 'string' ? c : undefined; };
|
|
2772
|
+
const node = { path: text('path') ?? '' };
|
|
2773
|
+
for (const kind of Object.keys(RUN_GUARDS)) {
|
|
2774
|
+
const list = get(kind);
|
|
2775
|
+
if (!list?.elements.length)
|
|
2776
|
+
continue;
|
|
2777
|
+
node.guards ??= guardIds++;
|
|
2778
|
+
if (kind === 'canDeactivate')
|
|
2779
|
+
node.deactivate = true;
|
|
2780
|
+
for (const g of list.elements) {
|
|
2781
|
+
let inject;
|
|
2782
|
+
if (ts.isIdentifier(g)) {
|
|
2783
|
+
const d = declarationOf(file, g.text, parse, fileOf);
|
|
2784
|
+
if (!d)
|
|
2785
|
+
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`);
|
|
2786
|
+
if (ts.isClassDeclaration(d)) {
|
|
2787
|
+
const method = d.members.find((m) => ts.isMethodDeclaration(m) && m.name.getText() === kind);
|
|
2788
|
+
inject = { name: g.text, arity: method ? method.parameters.length : RUN_GUARDS[kind] };
|
|
2789
|
+
}
|
|
2790
|
+
}
|
|
2791
|
+
else if (ts.isSpreadElement(g)) {
|
|
2792
|
+
throw new Error(`${file}:${lineOf(g)}: a spread in a route's ${kind} is not supported in a release build yet`);
|
|
2793
|
+
}
|
|
2794
|
+
guards.set(file, [...(guards.get(file) ?? []), { route: node.guards, kind, expr: g, inject }]);
|
|
2795
|
+
}
|
|
2796
|
+
}
|
|
2797
|
+
const component = get('component');
|
|
2798
|
+
if (component && ts.isIdentifier(component)) {
|
|
2799
|
+
if (component.text === 'NSEmptyOutletComponent')
|
|
2800
|
+
node.emptyOutlet = true;
|
|
2801
|
+
else
|
|
2802
|
+
node.component = component.text;
|
|
2803
|
+
}
|
|
2804
|
+
const loadComponent = get('loadComponent');
|
|
2805
|
+
if (loadComponent)
|
|
2806
|
+
node.component = lazy(file, loadComponent).name;
|
|
2807
|
+
if (text('redirectTo') !== undefined)
|
|
2808
|
+
node.redirectTo = text('redirectTo');
|
|
2809
|
+
if (text('pathMatch') === 'full')
|
|
2810
|
+
node.full = true;
|
|
2811
|
+
if (text('outlet'))
|
|
2812
|
+
node.outlet = text('outlet');
|
|
2813
|
+
const inherited = parent?.data && (node.path === '' || (!parent.component && !parent.emptyOutlet)) ? parent.data : [];
|
|
2814
|
+
const own = get('data');
|
|
2815
|
+
const data = new Map([...inherited, ...(own ? routeData(own, constant) : [])]);
|
|
2816
|
+
if (data.size)
|
|
2817
|
+
node.data = [...data];
|
|
2818
|
+
const children = get('children');
|
|
2819
|
+
if (children && ts.isArrayLiteralExpression(children))
|
|
2820
|
+
node.children = routesOf(file, children, node);
|
|
2821
|
+
else if (children) {
|
|
2822
|
+
const named = ts.isIdentifier(children) ? arrayNamed(file, children.text) : null;
|
|
2823
|
+
if (!named)
|
|
2824
|
+
throw new Error(`${file}:${lineOf(children)}: a route's children are an array in a release build (given ${children.getText()})`);
|
|
2825
|
+
node.children = routesOf(named.file, named.array, node);
|
|
2826
|
+
}
|
|
2827
|
+
const loadChildren = get('loadChildren');
|
|
2828
|
+
if (loadChildren) {
|
|
2829
|
+
const { file: target, name } = lazy(file, loadChildren);
|
|
2830
|
+
const found = arrayNamed(target, name);
|
|
2831
|
+
if (!found)
|
|
2832
|
+
throw new Error(`${target}: no route array ${name}`);
|
|
2833
|
+
node.children = [...(node.children ?? []), ...routesOf(found.file, found.array, node)];
|
|
2834
|
+
}
|
|
2835
|
+
return node;
|
|
2836
|
+
});
|
|
2837
|
+
};
|
|
2838
|
+
const sf = parse(entry);
|
|
2839
|
+
let found = null;
|
|
2840
|
+
const visit = (n) => {
|
|
2841
|
+
if (found)
|
|
2842
|
+
return;
|
|
2843
|
+
if (ts.isCallExpression(n) && /(^|\.)(provideNativeScriptRouter|provideRouter|forRoot)$/.test(n.expression.getText()) && n.arguments[0] && ts.isIdentifier(n.arguments[0])) {
|
|
2844
|
+
routerOptions(entry, n);
|
|
2845
|
+
found = arrayNamed(entry, n.arguments[0].text);
|
|
2846
|
+
}
|
|
2847
|
+
ts.forEachChild(n, visit);
|
|
2848
|
+
};
|
|
2849
|
+
visit(sf);
|
|
2850
|
+
if (!found)
|
|
2851
|
+
return null;
|
|
2852
|
+
const { file, array } = found;
|
|
2853
|
+
const routes = routesOf(file, array);
|
|
2854
|
+
return { routes, files, guards: [...guards].map(([f, list]) => guardModule(f, parse(f), list)) };
|
|
2855
|
+
}
|
|
2856
|
+
/** The components a route tree names. */
|
|
2857
|
+
export function routedComponents(routes) {
|
|
2858
|
+
return routes.flatMap((r) => [...(r.component ? [r.component] : []), ...routedComponents(r.children ?? [])]);
|
|
2859
|
+
}
|
|
2860
|
+
/** The route table: path → component, and where the app starts. */
|
|
2861
|
+
export function angularRoutes(text, file = 'routes.ts') {
|
|
2862
|
+
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
|
|
2863
|
+
const routes = [];
|
|
2864
|
+
let initial = '';
|
|
2865
|
+
const visit = (n) => {
|
|
2866
|
+
if (ts.isCallExpression(n) && /(^|\.)forRoot$/.test(n.expression.getText()))
|
|
2867
|
+
routerOptions(file, n);
|
|
2868
|
+
const keys = ts.isObjectLiteralExpression(n) ? n.properties.map((p) => p.name?.getText()) : [];
|
|
2869
|
+
if (ts.isObjectLiteralExpression(n) && keys.includes('path') && keys.some((k) => !!k && (ROUTE_GUARDS.has(k) || ['component', 'loadComponent', 'redirectTo', 'children', 'loadChildren', 'pathMatch', 'resolve'].includes(k)))) {
|
|
2870
|
+
if (keys.includes('data'))
|
|
2871
|
+
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`);
|
|
2872
|
+
routeFields(file, n);
|
|
2873
|
+
// Only a flat table of paths: nested and lazy routes need provideNativeScriptRouter(routes) in the entry.
|
|
2874
|
+
const nested = keys.find((k) => k === 'children' || k === 'loadChildren' || k === 'loadComponent' || k === 'outlet');
|
|
2875
|
+
if (nested)
|
|
2876
|
+
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`);
|
|
2877
|
+
const path = n.properties.find((p) => p.name?.getText() === 'path');
|
|
2878
|
+
if (keys.includes('redirectTo') && path.initializer.text !== '')
|
|
2879
|
+
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`);
|
|
2880
|
+
}
|
|
2881
|
+
if (ts.isObjectLiteralExpression(n)) {
|
|
2882
|
+
const get = (k) => n.properties.find((p) => ts.isPropertyAssignment(p) && p.name.text === k)?.initializer;
|
|
2883
|
+
const path = get('path')?.text;
|
|
2884
|
+
const component = get('component');
|
|
2885
|
+
const redirect = get('redirectTo')?.text;
|
|
2886
|
+
if (path !== undefined && component && ts.isIdentifier(component))
|
|
2887
|
+
routes.push({ path, component: component.text });
|
|
2888
|
+
if (path === '' && redirect)
|
|
2889
|
+
initial = redirect;
|
|
2890
|
+
}
|
|
2891
|
+
ts.forEachChild(n, visit);
|
|
2892
|
+
};
|
|
2893
|
+
visit(sf);
|
|
2894
|
+
return { routes, initial: initial || '/' + (routes[0]?.path ?? '') };
|
|
2895
|
+
}
|