@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.
@@ -0,0 +1,66 @@
1
+ // What the back ends read of an Angular app's NgModules and standalone components' imports. Kept apart from the front
2
+ // end so that a back end importing it does not load @angular/compiler.
3
+ import { ts } from "./core-api.js";
4
+ /** The class's decorator of that name, called (`@Component({...})`). */
5
+ export function decorator(node, name) {
6
+ for (const d of ts.getDecorators(node) ?? []) {
7
+ if (ts.isCallExpression(d.expression) && ts.isIdentifier(d.expression.expression) && d.expression.expression.text === name)
8
+ return d.expression;
9
+ }
10
+ return undefined;
11
+ }
12
+ /** A class of the program's sources that carries `@NgModule`. */
13
+ function isNgModuleSource(decl) {
14
+ return !!decl && ts.isClassDeclaration(decl) && !decl.getSourceFile().isDeclarationFile && !!decorator(decl, 'NgModule');
15
+ }
16
+ const metaField = (o, name) => (o && ts.isObjectLiteralExpression(o) ? o.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === name)?.initializer : undefined);
17
+ /**
18
+ * Of an `imports` list, in order, the NgModules the program compiles, the `ModuleWithProviders` calls of their statics
19
+ * (not in a component, where Angular drops their providers), and in place of a standalone component the modules its own
20
+ * `imports` list. The rest (the kit's own modules) has no constructor or providers of its own in a compiled build.
21
+ */
22
+ function ngImports(list, checker, compiles, inComponent, seen) {
23
+ const declOf = (e) => {
24
+ const s = checker.getSymbolAtLocation(e);
25
+ return (s && s.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(s) : s)?.declarations?.[0];
26
+ };
27
+ const compiledNgModule = (decl) => isNgModuleSource(decl) && compiles(decl);
28
+ const kept = (list, inComponent) => {
29
+ if (!list || !ts.isArrayLiteralExpression(list))
30
+ return [];
31
+ return list.elements.flatMap((e) => {
32
+ if (ts.isArrayLiteralExpression(e))
33
+ return kept(e, inComponent);
34
+ const decl = declOf(e);
35
+ if (compiledNgModule(decl))
36
+ return [e];
37
+ if (decl && ts.isClassDeclaration(decl) && !decl.getSourceFile().isDeclarationFile && !seen.has(decl)) {
38
+ const component = decorator(decl, 'Component')?.arguments[0];
39
+ if (component) {
40
+ seen.add(decl);
41
+ return kept(metaField(component, 'imports'), true);
42
+ }
43
+ }
44
+ if (!inComponent && ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && compiledNgModule(declOf(e.expression.expression)))
45
+ return [e];
46
+ return [];
47
+ });
48
+ };
49
+ return kept(list, inComponent);
50
+ }
51
+ /** An `@NgModule` class's metadata as Angular's injector walks it (`walkProviderTree`): its `imports` and `providers`. */
52
+ export function ngModuleDef(cls, checker, compiles) {
53
+ const meta = decorator(cls, 'NgModule')?.arguments[0];
54
+ if (!meta)
55
+ return undefined;
56
+ return { imports: ngImports(metaField(meta, 'imports'), checker, compiles, false, new Set()), providers: metaField(meta, 'providers') };
57
+ }
58
+ /**
59
+ * A standalone component's imports that make it its own environment injector when it is created as a root view
60
+ * (`StandaloneService`); undefined when none of them has a provider in a compiled build.
61
+ */
62
+ export function standaloneImports(cls, checker, compiles) {
63
+ const meta = decorator(cls, 'Component')?.arguments[0];
64
+ const imports = meta && ngImports(metaField(meta, 'imports'), checker, compiles, true, new Set([cls]));
65
+ return imports?.length ? imports : undefined;
66
+ }
@@ -0,0 +1,15 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ /** The adapter's package folder, the nearest holding a package.json: run as TypeScript or from its built dist/ alike. */
5
+ const ROOT = (() => {
6
+ let dir = dirname(fileURLToPath(import.meta.url));
7
+ while (!existsSync(join(dir, 'package.json')))
8
+ dir = dirname(dir);
9
+ return dir;
10
+ })();
11
+ const { name, version } = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'));
12
+ /** The package the adapter ships as. Its runtime is TypeScript, read from the package's own runtime/. */
13
+ export const PACKAGE = { name, version, root: ROOT };
14
+ /** The adapter's TypeScript compiled with an app: @angular/common's pipes and directives, @angular/forms, the Rx-based APIs. */
15
+ export const RUNTIME = join(ROOT, 'runtime');
@@ -0,0 +1,5 @@
1
+ const ISOLATE = 'move the code into a plain function of its own with typed parameters and result, so the rest of the module translates; the refusal then names only that function';
2
+ export const refusals = {
3
+ 'library-injectable': { class: 'gap', title: "an injected class only a library's typings declare", suggestion: ISOLATE },
4
+ 'view-container-ref': { class: 'gap', title: 'an injected ViewContainerRef', suggestion: ISOLATE },
5
+ };
@@ -0,0 +1,213 @@
1
+ import { core, ts } from "./core-api.js";
2
+ export const isStatic = (m) => ts.canHaveModifiers(m) && !!ts.getModifiers(m)?.some((x) => x.kind === ts.SyntaxKind.StaticKeyword);
3
+ export const hasModifier = (n, kind) => ts.canHaveModifiers(n) && !!ts.getModifiers(n)?.some((m) => m.kind === kind);
4
+ /** Tokens the kit provides an instance of (`inject(Router)`); any other is the app's service or the injector's. */
5
+ export const KIT_TOKENS = ['RouterExtensions', 'ActivatedRoute', 'Page', 'DestroyRef', 'ChangeDetectorRef', 'ElementRef', 'NativeDialogRef', 'NativeDialogService', 'Router', 'HttpClient', 'Injector', 'EnvironmentInjector', 'NgZone', 'ErrorHandler', 'Location', 'ViewContainerRef', 'ApplicationRef'];
6
+ /** The code giving a kit token's instance where it is not the token class's own `shared`, per back end. */
7
+ export const INJECTION_TOKENS = {
8
+ RouterExtensions: { swift: 'Router.shared', kotlin: 'Router.shared' },
9
+ EnvironmentInjector: { swift: 'Injector.shared', kotlin: 'Injector.shared' },
10
+ ErrorHandler: { swift: 'Injector.errorHandler', kotlin: 'Injector.errorHandler' },
11
+ ActivatedRoute: { swift: 'ActivatedRoute.current', kotlin: 'ActivatedRoute.current' },
12
+ Page: { swift: 'Page.injected()', kotlin: 'injectedPage()' },
13
+ DestroyRef: { swift: 'DestroyRef.current()', kotlin: 'DestroyRef.current()' },
14
+ ChangeDetectorRef: { swift: 'ChangeDetectorRef.current()', kotlin: 'ChangeDetectorRef.current()' },
15
+ ElementRef: { swift: 'ElementRef.current()', kotlin: 'ElementRef.current()' },
16
+ NativeDialogRef: { swift: 'NativeDialogRef.current', kotlin: 'NativeDialogRef.current' },
17
+ };
18
+ /** What `inject(token)` gives: the kit's instance for a framework token, else the app's service. */
19
+ export function injected(backend, token, shared = 'shared') {
20
+ return Object.hasOwn(INJECTION_TOKENS, token) ? INJECTION_TOKENS[token][backend] : `${token}.${shared}`;
21
+ }
22
+ const CORE_MODULE = /[\\/]@angular[\\/]core[\\/]|^\/__shims__\/_angular_core\.d\.ts$/;
23
+ /** Whether `e` calls @angular/core's `name` (`computed`), by the callee's declaration (the package's, or the compiler's shim of it): a program's own function of that name is an ordinary call. */
24
+ export function angularCall(e, name, checker) {
25
+ if (!e || !ts.isCallExpression(e))
26
+ return false;
27
+ const at = ts.isPropertyAccessExpression(e.expression) ? e.expression.name : e.expression;
28
+ let sym = checker.getSymbolAtLocation(at);
29
+ if (sym && sym.flags & ts.SymbolFlags.Alias)
30
+ sym = checker.getAliasedSymbol(sym);
31
+ return sym?.name === name && !!sym.declarations?.some((d) => CORE_MODULE.test(d.getSourceFile().fileName));
32
+ }
33
+ /**
34
+ * How a backend makes an `@Injectable` class. An app's is a service the injector makes, `'based'` when it extends a
35
+ * class (then translated as any class is). A package's is a plain class, as the providers of its tokens are not compiled,
36
+ * unless it names its own injector (`providedIn`): then `'root'`, a plain class the injector also makes, one per class.
37
+ */
38
+ export function injectableRole(cls, pluginFiles) {
39
+ const decorator = (ts.getDecorators(cls) ?? []).find((d) => d.expression.getText().startsWith('Injectable'));
40
+ if (!decorator)
41
+ return undefined;
42
+ if (pluginFiles.has(cls.getSourceFile().fileName)) {
43
+ const options = ts.isCallExpression(decorator.expression) ? decorator.expression.arguments[0] : undefined;
44
+ const providedIn = options && ts.isObjectLiteralExpression(options)
45
+ ? options.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'providedIn')?.initializer
46
+ : undefined;
47
+ return providedIn && ts.isStringLiteral(providedIn) && ['root', 'platform', 'any'].includes(providedIn.text) ? 'root' : undefined;
48
+ }
49
+ return cls.heritageClauses?.some((h) => h.token === ts.SyntaxKind.ExtendsKeyword) ? 'based' : 'service';
50
+ }
51
+ /**
52
+ * The static a backend reads an `@Injectable` class's root instance from. A package's class, and its subclasses, keep
53
+ * `shared` as a name of their own (a static `shared` of the package's is its member): theirs is the kit's `jsShared`.
54
+ */
55
+ export function injectableShared(cls, pluginFiles, checker) {
56
+ for (let c = cls; c && ts.isClassDeclaration(c) && !c.getSourceFile().isDeclarationFile;) {
57
+ if (injectableRole(c, pluginFiles) === 'root')
58
+ return 'jsShared';
59
+ const h = c.heritageClauses?.find((x) => x.token === ts.SyntaxKind.ExtendsKeyword)?.types[0];
60
+ c = h && checker.getTypeAtLocation(h.expression).getSymbol()?.valueDeclaration;
61
+ }
62
+ return 'shared';
63
+ }
64
+ /** Whether a declaration is a class the injector makes: the app's `@Injectable`, a package's that names its injector, the runtime's services. */
65
+ export function isInjectableClass(decl, pluginFiles) {
66
+ if (!decl || !ts.isClassDeclaration(decl) || decl.getSourceFile().isDeclarationFile)
67
+ return false;
68
+ const fn = decl.getSourceFile().fileName;
69
+ if (core.adapterRuntimeFile(fn) === 'runtime/angular-rx.ts' || core.adapterRuntimeFile(fn) === 'runtime/angular.ts')
70
+ return true;
71
+ // @angular/forms' builders: services whose root instance is their static `shared`.
72
+ if (core.adapterRuntimeFile(fn) === 'runtime/angular-forms.ts')
73
+ return decl.members.some((m) => (ts.isPropertyDeclaration(m) || ts.isGetAccessorDeclaration(m)) && isStatic(m) && m.name.getText() === 'shared');
74
+ if (pluginFiles.has(fn))
75
+ return injectableRole(decl, pluginFiles) === 'root';
76
+ return (ts.getDecorators(decl) ?? []).some((d) => /^Injectable\b/.test(d.expression.getText()));
77
+ }
78
+ /** A constructor parameter's injection as its decorators say: the `@Inject(token)` token, whether it may be absent, whether it skips its own injector. */
79
+ export function parameterDecorators(p) {
80
+ let token;
81
+ let optional = !!(p.questionToken || p.initializer);
82
+ let skipSelf = false;
83
+ for (const d of ts.getDecorators(p) ?? []) {
84
+ const e = d.expression;
85
+ const which = ts.isCallExpression(e) ? e.expression.getText() : e.getText();
86
+ if (which === 'Inject' && ts.isCallExpression(e) && e.arguments[0])
87
+ token = e.arguments[0];
88
+ else if (which === 'Optional')
89
+ optional = true;
90
+ else if (which === 'SkipSelf')
91
+ skipSelf = true;
92
+ }
93
+ return { token, optional, skipSelf };
94
+ }
95
+ /** `forwardRef(() => X)` is `X`. */
96
+ export function forwardRefTarget(e) {
97
+ return ts.isCallExpression(e) && e.expression.getText() === 'forwardRef' && e.arguments[0] && (ts.isArrowFunction(e.arguments[0]) || ts.isFunctionExpression(e.arguments[0])) && !ts.isBlock(e.arguments[0].body) ? e.arguments[0].body : e;
98
+ }
99
+ /** The services `injectThrows` is working out, so that services injecting each other end. */
100
+ const injecting = new Set();
101
+ /**
102
+ * Angular's `inject(token)` makes a root service the first time, throwing what its constructor throws; core's Page
103
+ * is the kit's `Page.injected()`, which can make one.
104
+ */
105
+ function injectThrows(token, t) {
106
+ if (ts.isCallExpression(token))
107
+ token = forwardRefTarget(token);
108
+ let s = t.checker.getSymbolAtLocation(token);
109
+ if (s && s.flags & ts.SymbolFlags.Alias)
110
+ s = t.checker.getAliasedSymbol(s);
111
+ const decl = s?.valueDeclaration;
112
+ if (!decl || !ts.isClassLike(decl))
113
+ return false;
114
+ if (/[\\/]@nativescript[\\/]core[\\/]/.test(decl.getSourceFile().fileName))
115
+ return decl.name?.text === 'Page';
116
+ if (core.adapterRuntimeFile(decl.getSourceFile().fileName) === 'runtime/angular-rx.ts')
117
+ return decl.name?.text === 'ActivatedRoute';
118
+ if (decl.getSourceFile().isDeclarationFile || /[\\/]node_modules[\\/]/.test(decl.getSourceFile().fileName) || injecting.has(decl))
119
+ return false;
120
+ if (ts.isClassDeclaration(decl) && core.adapterRuntimeFile(decl.getSourceFile().fileName) !== 'runtime/angular.ts' && !ts.getDecorators(decl)?.some((d) => /^Injectable\b/.test(d.expression.getText())))
121
+ return false;
122
+ injecting.add(decl);
123
+ try {
124
+ return t.initThrows(decl);
125
+ }
126
+ finally {
127
+ injecting.delete(decl);
128
+ }
129
+ }
130
+ const throwsModel = {
131
+ rethrowing: ['untracked', 'runInInjectionContext', 'PurePipeCache.*', 'NgZone.run', 'NgZone.runOutsideAngular', 'NgZone.runGuarded', 'NgZone.runTask'],
132
+ injectsConstructor: (cls) => ts.isClassDeclaration(cls) && !!ts.getDecorators(cls)?.some((d) => /^Injectable\b/.test(d.expression.getText())),
133
+ injects(p, t) {
134
+ const { token, optional, skipSelf } = parameterDecorators(p);
135
+ if (optional && skipSelf)
136
+ return false;
137
+ if (token)
138
+ return injectThrows(token, t);
139
+ const ref = p.type && ts.isTypeReferenceNode(p.type)
140
+ ? p.type
141
+ : p.type && ts.isUnionTypeNode(p.type)
142
+ ? p.type.types.find(ts.isTypeReferenceNode)
143
+ : undefined;
144
+ return ref ? injectThrows(ref.typeName, t) : false;
145
+ },
146
+ injectCall(decl, args, t) {
147
+ if (!args[0] || !((ts.isFunctionDeclaration(decl) && decl.name?.text === 'inject') || (ts.isMethodDeclaration(decl) && decl.name.getText() === 'get' && ts.isClassDeclaration(decl.parent) && decl.parent.name?.text === 'Injector')))
148
+ return undefined;
149
+ return injectThrows(args[0], t);
150
+ },
151
+ };
152
+ /** Angular's class decorators, as @angular/core (or the compiler's shim of it) declares them. */
153
+ const CLASS_DECORATORS = new Set(['Component', 'Directive', 'Pipe', 'Injectable', 'NgModule']);
154
+ const METHOD_DECORATORS = new Set(['HostListener']);
155
+ const LIFECYCLE_HOOKS = new Set(['ngOnChanges', 'ngOnInit', 'ngDoCheck', 'ngAfterContentInit', 'ngAfterContentChecked', 'ngAfterViewInit', 'ngAfterViewChecked', 'ngOnDestroy']);
156
+ function angularDecorator(d, names, checker) {
157
+ const e = ts.isCallExpression(d.expression) ? d.expression.expression : d.expression;
158
+ let sym = checker.getSymbolAtLocation(e);
159
+ if (sym && sym.flags & ts.SymbolFlags.Alias)
160
+ sym = checker.getAliasedSymbol(sym);
161
+ return !!sym && names.has(sym.name) && !!sym.declarations?.some((x) => /^\/__shims__\/_angular_core\.d\.ts$|[\\/]@angular[\\/]core[\\/]/.test(x.getSourceFile().fileName));
162
+ }
163
+ /**
164
+ * The `equal` options of a signal `signal(v, options)` or `linkedSignal(…)` makes: the call's second argument, or
165
+ * `linkedSignal`'s first where it is given `{ source, computation }`.
166
+ */
167
+ function signalOptions(call, checker) {
168
+ if (angularCall(call, 'signal', checker))
169
+ return { options: call.arguments[1] };
170
+ if (angularCall(call, 'linkedSignal', checker)) {
171
+ const first = call.arguments[0];
172
+ return { options: first && checker.getTypeAtLocation(first).getCallSignatures().length === 0 ? first : call.arguments[1] };
173
+ }
174
+ return undefined;
175
+ }
176
+ /** What both back ends and their analyses read of Angular's API. */
177
+ export const model = {
178
+ plainFields: true,
179
+ wrapsRootViews: true,
180
+ signalTypes: { InputSignal: 'input', ModelSignal: 'model', Signal: 'computed' },
181
+ // `input()` outside a component (a directive's): a signal the template sets.
182
+ signalConstructors: { signal: { equality: 'identity', options: 1 }, model: 'identity', input: { equality: 'identity', typed: true } },
183
+ memos: { computed: '@angular/core' },
184
+ heldSignals: ['toSignal'],
185
+ pure: ['signal', 'computed'],
186
+ classDecorators: ['NgModule', 'Injectable'],
187
+ componentDecorator: 'Component',
188
+ componentValueType: 'ComponentFactory',
189
+ prefixedModules: { rxjs: 'Rx' },
190
+ untypedInterfaces: ['@angular#forms'],
191
+ untypedPackageInterfaces: ['@angular/'],
192
+ throwsModel,
193
+ signalOptions,
194
+ classRole: injectableRole,
195
+ addedStatics: (cls, pluginFiles, checker) => (injectableRole(cls, pluginFiles) ? [injectableShared(cls, pluginFiles, checker), 'jsSharedInstance', 'jsConstruct'] : []),
196
+ frameworkCalled(cls, name, checker) {
197
+ if (!ts.getDecorators(cls).every((d) => angularDecorator(d, CLASS_DECORATORS, checker)))
198
+ return 'a method of a decorated class';
199
+ if (LIFECYCLE_HOOKS.has(name))
200
+ return 'an Angular lifecycle hook';
201
+ // The template glue this compiler writes calls its own methods (`$b3`, `$e4`) with whatever they declare.
202
+ if (name.startsWith('$') && !/^\$[be]\d+$/.test(name))
203
+ return "a template's binding";
204
+ return undefined;
205
+ },
206
+ calledByFramework(cls, m, checker) {
207
+ if (ts.getDecorators(m)?.some((d) => angularDecorator(d, METHOD_DECORATORS, checker)))
208
+ return true;
209
+ if (!ts.getDecorators(cls)?.some((d) => angularDecorator(d, CLASS_DECORATORS, checker)))
210
+ return false;
211
+ return LIFECYCLE_HOOKS.has(m.name.getText()) || !(ts.isPrivateIdentifier(m.name) || ts.getCombinedModifierFlags(m) & ts.ModifierFlags.Private);
212
+ },
213
+ };
package/dist/swift.js ADDED
@@ -0,0 +1,340 @@
1
+ import { core, ts } from "./core-api.js";
2
+ import { ngModuleDef, standaloneImports } from "./ng-modules.js";
3
+ import { KIT_TOKENS, angularCall, forwardRefTarget, injectableRole, injectableShared, injected, isInjectableClass, model, parameterDecorators } from "./semantics.js";
4
+ /** An injection token's name: a framework class by the name it is declared with (`NativeDialog` is `NativeDialogService`), or a compiled class by its emitted name. */
5
+ function tokenName(t, e) {
6
+ const decl = t.resolve(e)?.declarations?.[0];
7
+ if (decl && ts.isClassDeclaration(decl) && decl.name) {
8
+ return decl.getSourceFile().isDeclarationFile ? decl.name.text : t.topName(decl, decl.name.text);
9
+ }
10
+ return e.getText();
11
+ }
12
+ /** What `inject(token)` gives at `at`; a ViewContainerRef has no instance whose views would attach to the component's. */
13
+ function injectedToken(t, token, at, decl) {
14
+ if (token === 'ViewContainerRef')
15
+ throw t.error(at, 'an injected ViewContainerRef', 'view-container-ref');
16
+ return injected('swift', token, decl && ts.isClassDeclaration(decl) ? injectableShared(decl, t.pluginFiles, t.checker) : undefined);
17
+ }
18
+ /** A class only a library's typings declare has no instance in a release build: the library's JavaScript provides it. */
19
+ function refuseTypingsOnlyToken(t, tokenDecl, token, at) {
20
+ if (tokenDecl && ts.isClassDeclaration(tokenDecl) && tokenDecl.getSourceFile().isDeclarationFile && !core.isCoreDeclaration(tokenDecl))
21
+ throw t.error(at, `an injected class only a library's typings declare (${token})`, 'library-injectable');
22
+ }
23
+ function parameterInject(t, p) {
24
+ const { swift } = core;
25
+ const pt = t.typeOf(p.name);
26
+ const { token: given, optional, skipSelf } = parameterDecorators(p);
27
+ if (optional && skipSelf)
28
+ return swift.isOptional(pt) || pt.endsWith('!') || pt === 'Any?' ? 'nil' : t.fromAny('nil', pt);
29
+ const injectArg = given && forwardRefTarget(given);
30
+ if (injectArg) {
31
+ const target = ts.isExpressionWithTypeArguments(injectArg) ? injectArg.expression : injectArg;
32
+ const token = tokenName(t, target);
33
+ if (token === 'NATIVE_DIALOG_DATA')
34
+ return t.fromAny('NativeDialogRef.current.data', pt);
35
+ const tokenDecl = t.resolve(target)?.declarations?.[0];
36
+ if (KIT_TOKENS.includes(token) || isInjectableClass(tokenDecl, t.pluginFiles)) {
37
+ const throws = token === 'Page' || (token === 'ActivatedRoute' && core.adapterRuntimeFile(tokenDecl?.getSourceFile().fileName) === 'runtime/angular-rx.ts') || (tokenDecl && ts.isClassDeclaration(tokenDecl) && core.adapterRuntimeFile(tokenDecl.getSourceFile().fileName) !== 'runtime/angular-rx.ts' && t.throwsInfo.initThrows(tokenDecl));
38
+ return swift.tryIf(throws, injectedToken(t, token, p, tokenDecl));
39
+ }
40
+ refuseTypingsOnlyToken(t, tokenDecl, token, p);
41
+ const raw = `Injector.inject(${t.coerce(injectArg, 'Any?')}${optional ? ', JSObject([("optional", true)])' : ''})`;
42
+ return pt === 'Any?' ? raw : t.fromAny(raw, pt);
43
+ }
44
+ const ref = p.type && ts.isTypeReferenceNode(p.type)
45
+ ? p.type
46
+ : p.type && ts.isUnionTypeNode(p.type)
47
+ ? p.type.types.find(ts.isTypeReferenceNode)
48
+ : undefined;
49
+ if (ref) {
50
+ const token = tokenName(t, ref.typeName);
51
+ const tokenDecl = t.resolve(ref.typeName)?.declarations?.[0];
52
+ if (KIT_TOKENS.includes(token) || isInjectableClass(tokenDecl, t.pluginFiles)) {
53
+ const throws = token === 'Page' || (token === 'ActivatedRoute' && core.adapterRuntimeFile(tokenDecl?.getSourceFile().fileName) === 'runtime/angular-rx.ts') || (tokenDecl && ts.isClassDeclaration(tokenDecl) && core.adapterRuntimeFile(tokenDecl.getSourceFile().fileName) !== 'runtime/angular-rx.ts' && t.throwsInfo.initThrows(tokenDecl));
54
+ return swift.tryIf(throws, injectedToken(t, token, p, tokenDecl));
55
+ }
56
+ if (tokenDecl && ts.isClassDeclaration(tokenDecl)) {
57
+ refuseTypingsOnlyToken(t, tokenDecl, token, p);
58
+ const raw = `Injector.inject(${token}.self${optional ? ', JSObject([("optional", true)])' : ''})`;
59
+ return pt === 'Any?' ? raw : t.fromAny(raw, pt);
60
+ }
61
+ }
62
+ return undefined;
63
+ }
64
+ /** `inject(token)` and `injector.get(token)`: a kit token's instance or the app's service, else what the injector gives. */
65
+ function injection(t, call, given, made) {
66
+ const rawArg0 = forwardRefTarget(given);
67
+ const target = ts.isExpressionWithTypeArguments(rawArg0) ? rawArg0.expression : rawArg0;
68
+ const token = tokenName(t, target);
69
+ if (token === 'NATIVE_DIALOG_DATA')
70
+ return t.fromAny('NativeDialogRef.current.data', t.typeOf(call));
71
+ const tokenDecl = t.resolve(target)?.declarations?.[0];
72
+ if (KIT_TOKENS.includes(token) || isInjectableClass(tokenDecl, t.pluginFiles))
73
+ return injectedToken(t, token, call, tokenDecl);
74
+ refuseTypingsOnlyToken(t, tokenDecl, token, call);
75
+ const raw = made(t.coerce(rawArg0, 'Any?'));
76
+ const type = t.typeOf(call);
77
+ return type === 'Any?' ? raw : t.fromAny(raw, type);
78
+ }
79
+ /** `linkedSignal({ source, computation })`: `computation`'s `previous` is the runtime's pair made the parameter's object. */
80
+ function linkedSignal(t, options, type, equals) {
81
+ const prop = (n) => {
82
+ const p = options.properties.find((q) => q.name && ts.isIdentifier(q.name) && q.name.text === n);
83
+ if (!p)
84
+ return undefined;
85
+ if (ts.isPropertyAssignment(p))
86
+ return p.initializer;
87
+ if (ts.isShorthandPropertyAssignment(p))
88
+ return p.name;
89
+ throw t.error(p, `a \`${n}\` of linkedSignal's options other than a property`);
90
+ };
91
+ const source = prop('source'), computation = prop('computation');
92
+ if (!source || !computation)
93
+ throw t.error(options, 'linkedSignal options without both `source` and `computation`');
94
+ const c = t.checker;
95
+ const sig = c.getResolvedSignature(options.parent);
96
+ const opts = c.getTypeOfSymbol(sig.parameters[0]);
97
+ const s = t.type(c.getTypeOfSymbol(c.getPropertyOfType(opts, 'source')).getCallSignatures()[0].getReturnType(), options);
98
+ const compSig = c.getTypeOfSymbol(c.getPropertyOfType(opts, 'computation')).getCallSignatures()[0];
99
+ const takesPrevious = (c.getTypeAtLocation(computation).getCallSignatures()[0]?.parameters.length ?? 2) > 1;
100
+ const prevParam = takesPrevious ? compSig.parameters[1] : undefined;
101
+ const prevType = prevParam ? t.type(c.getNonNullableType(c.getTypeOfSymbol(prevParam)), options) : undefined;
102
+ const read = t.symbolName(source) === 'WritableSignal' || t.symbolName(source) === 'Signal' ? `{ () throws -> ${s} in try ${t.expr(source)}.value }` : t.expr(source);
103
+ const made = prevType && /^Object_\w+$/.test(prevType) ? `${prevType}(source: p.source, value: p.value)` : 'JSObject([("source", p.source), ("value", p.value)])';
104
+ return `Signal<${type}>(source: ${read}, computation: { (s: ${s}, previous: (source: ${s}, value: ${type})?) throws -> ${type} in try (${t.expr(computation)})(s${prevType ? `, previous.map { p in ${made} }` : ''}) }${equals})`;
105
+ }
106
+ /** Whether a `linkedSignal(…)` call resolves to the overload taking `{ source, computation }` rather than a function. */
107
+ function linkedOptionsOverload(t, e) {
108
+ const first = t.checker.getResolvedSignature(e)?.parameters[0];
109
+ return !!first && t.checker.getTypeOfSymbol(first).getCallSignatures().length === 0;
110
+ }
111
+ /**
112
+ * `linkedSignal(options)` with options other than a literal: `source`, `computation` and `equal` read by name once, as
113
+ * the signal is made, as Angular reads them. `previous` is made the type the options' own `computation` declares, which
114
+ * is what the function held there takes.
115
+ */
116
+ function linkedSignalOptions(t, options, type, reference) {
117
+ const c = t.checker;
118
+ const sig = c.getResolvedSignature(options.parent);
119
+ const opts = c.getTypeOfSymbol(sig.parameters[0]);
120
+ const s = t.type(c.getTypeOfSymbol(c.getPropertyOfType(opts, 'source')).getCallSignatures()[0].getReturnType(), options);
121
+ const held = c.getPropertyOfType(c.getNonNullableType(c.getTypeAtLocation(options)), 'computation');
122
+ const prevParam = held && c.getNonNullableType(c.getTypeOfSymbol(held)).getCallSignatures()[0]?.parameters[1];
123
+ const prevType = prevParam ? t.type(c.getNonNullableType(c.getTypeOfSymbol(prevParam)), options) : 'Any?';
124
+ const previous = t.fromAnyCode('JSObject([("source", p.source), ("value", p.value)])', prevType);
125
+ const fallback = reference ? 'jsSame(a, b)' : core.swift.isFunctionType(type) ? 'false' : 'a == b';
126
+ const equal = `jsEqualOption(__o, default: { (a: ${type}, b: ${type}) -> Bool in ${fallback} })`;
127
+ return `{ (__o: Any?) -> Signal<${type}> in let __source = (try? jsGet(__o, "source")) ?? nil; let __computation = (try? jsGet(__o, "computation")) ?? nil; `
128
+ + `return Signal<${type}>(source: { () throws -> ${s} in let v = try jsCall(__source); return ${t.fromAnyCode('v', s)} }, `
129
+ + `computation: { (s: ${s}, previous: (source: ${s}, value: ${type})?) throws -> ${type} in let p: Any? = previous.map { p in ${previous} }; let v = try jsCall(__computation, s, p); return ${t.fromAnyCode('v', type)} }, `
130
+ + `equals: ${c.getNonNullableType(c.getTypeAtLocation(options)).getProperty('equal') ? equal : `jsReportingEquals(${equal})`}) }(${t.coerce(options, 'Any?')})`;
131
+ }
132
+ function globalCall(t, name, e, decl, lib) {
133
+ const arg = (k) => e.arguments[k];
134
+ const { swift } = core;
135
+ if (name === 'linkedSignal' && lib) {
136
+ const type = t.typeOf(e).replace(/^Signal<(.*)>$/, '$1');
137
+ const reference = !['Double', 'String', 'Bool'].includes(type.replace(/\?$/, '')) && !swift.isFunctionType(type);
138
+ const options = arg(0) && ts.isObjectLiteralExpression(ts.skipOuterExpressions(arg(0))) ? ts.skipOuterExpressions(arg(0)) : undefined;
139
+ const fallback = reference ? ', equals: { jsSame($0, $1) }' : '';
140
+ if (!options && linkedOptionsOverload(t, e))
141
+ return linkedSignalOptions(t, arg(0), type, reference);
142
+ if (!options)
143
+ return `Signal<${type}>(linked: ${t.expr(arg(0))}${t.equalsArg(arg(1), type) ?? fallback})`;
144
+ return linkedSignal(t, options, type, t.equalsArg(options, type) ?? (reference ? fallback : ', equals: { $0 == $1 }'));
145
+ }
146
+ if (name === 'computed' && angularCall(e, 'computed', t.checker) && t.typeOf(e).startsWith('Signal<')) {
147
+ const fn = arg(0);
148
+ const rt = t.typeOf(e).replace(/^Signal<(.*)>$/, '$1');
149
+ if (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn))
150
+ return `Signal<${rt}>(${t.memo(fn, rt, !core.isAsync(fn) && t.throwsInfo.fn(fn))})`;
151
+ const equals = t.equalsArg(arg(1), rt, true);
152
+ return `Signal<${rt}>(Memo<${rt}>(${t.expr(fn)}${equals ?? ''}))`;
153
+ }
154
+ if (name === 'untracked' && lib)
155
+ return `untrack(${t.expr(arg(0))})`;
156
+ if (name === 'runInInjectionContext' && lib) {
157
+ const fn = arg(1);
158
+ if (fn && (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn))) {
159
+ const type = t.typeOf(e);
160
+ const throws = t.throwsInfo.fn(fn);
161
+ return `Injector.runInContext(${t.restArgument(e, arg(0), 'Any?')}) { ()${throws ? ' throws' : ''} -> ${type} in${t.functionBody(fn, type, t.indent).slice(1)}`;
162
+ }
163
+ return `Injector.runInContext(${t.restArgument(e, arg(0), 'Any?')}, ${t.expr(arg(1))})`;
164
+ }
165
+ if ((name === 'forwardRef' || name === 'resolveForwardRef') && lib) {
166
+ const fn = arg(0);
167
+ if (fn && (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) && !ts.isBlock(fn.body))
168
+ return t.expr(fn.body);
169
+ return `resolveForwardRef(${arg(0) ? t.restArgument(e, arg(0), 'Any?') : 'nil'})`;
170
+ }
171
+ if (name === 'isDevMode' && lib)
172
+ return 'false';
173
+ const shimmed = decl && ts.isFunctionDeclaration(decl) && decl.getSourceFile().fileName.startsWith('/__shims__/') ? decl.name?.text : undefined;
174
+ if (shimmed === 'enableProdMode')
175
+ return '()';
176
+ if (shimmed === 'isAngularHmrRestoringRoute')
177
+ return 'false';
178
+ if (name === 'output' && lib)
179
+ return `${t.typeOf(e)}()`;
180
+ if (name === 'inject' && lib)
181
+ return injection(t, e, arg(0), (token) => `Injector.inject(${token}${arg(1) ? `, ${t.restArgument(e, arg(1), 'Any?')}` : ''})`);
182
+ if (name === 'effect' && lib)
183
+ return `Effect.deferred(${t.callback(arg(0))})`;
184
+ if (name === 'toSignal' && lib) {
185
+ const options = arg(1) && ts.isObjectLiteralExpression(arg(1)) ? arg(1) : undefined;
186
+ const initial = options?.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'initialValue');
187
+ const inner = t.typeOf(e).replace(/^Signal<(.*)>$/, '$1');
188
+ return `toSignal(${t.expr(arg(0))}${initial ? `, initialValue: ${t.coerce(initial.initializer, inner)}` : ''})`;
189
+ }
190
+ if (name === 'firstValueFrom' && lib)
191
+ return `rxFirstValueFrom(${t.expr(arg(0))})`;
192
+ if (name === 'registerElement' && (lib || core.adapterRuntimeFile(decl?.getSourceFile().fileName) === 'runtime/angular-rx.ts'))
193
+ return '()';
194
+ return undefined;
195
+ }
196
+ function methodCall(t, owner, method, e) {
197
+ const target = e.expression.expression;
198
+ if ((owner === 'OutputEmitterRef' || owner === 'EventEmitter') && (method === 'emit' || method === 'next')) {
199
+ const value = /^(?:OutputEmitterRef|EventEmitter|Emitter)<(.*)>[?!]?$/.exec(t.typeOf(target))?.[1];
200
+ const a = e.arguments[0];
201
+ return `${t.expr(target)}.emit(${a ? (value && value !== 'Void' && value !== 'Unit' ? t.coerce(a, value) : t.expr(a)) : ''})`;
202
+ }
203
+ if (owner === 'Injector' && method === 'get' && e.arguments[0]) {
204
+ const rawArg0 = forwardRefTarget(e.arguments[0]);
205
+ const tokTarget = ts.isExpressionWithTypeArguments(rawArg0) ? rawArg0.expression : rawArg0;
206
+ const token = tokenName(t, tokTarget);
207
+ if (token === 'ViewContainerRef')
208
+ throw t.error(e, 'an injected ViewContainerRef', 'view-container-ref');
209
+ const tokenDecl = t.resolve(tokTarget)?.declarations?.[0];
210
+ if ((KIT_TOKENS.includes(token) || isInjectableClass(tokenDecl, t.pluginFiles)) && e.arguments.length === 1 && t.throwsInfo.expr(e))
211
+ return injectedToken(t, token, e, tokenDecl);
212
+ const raw = `${t.expr(target)}.get(${t.coerce(rawArg0, 'Any?')}${e.arguments[1] ? `, ${t.coerce(e.arguments[1], 'Any?')}` : ''}${e.arguments[2] ? `, ${t.coerce(e.arguments[2], 'Any?')}` : ''})`;
213
+ const type = t.typeOf(e);
214
+ return type === 'Any?' ? raw : t.fromAny(raw, type);
215
+ }
216
+ // `http.get<T>(url, options)` / `http.post<T>(url, body, options)`: the parsed body read as T.
217
+ if (owner === 'HttpClient' && ['get', 'delete', 'head', 'options', 'post', 'put', 'patch', 'request'].includes(method) && t.typeOf(e).startsWith('RxObservable<')) {
218
+ const value = /^RxObservable<(.*)>$/.exec(t.typeOf(e))?.[1] ?? 'Any?';
219
+ const call = method === 'request'
220
+ ? `${t.expr(target)}.request(${t.str(e.arguments[0])}, ${e.arguments[1] ? t.str(e.arguments[1]) : '""'}${e.arguments[2] ? `, ${t.coerce(e.arguments[2], 'Any?')}` : ''})`
221
+ : ['post', 'put', 'patch'].includes(method)
222
+ ? `${t.expr(target)}.${method}(${t.str(e.arguments[0])}${e.arguments[1] ? `, ${t.coerce(e.arguments[1], 'Any?')}` : ', nil'}${e.arguments[2] ? `, ${t.coerce(e.arguments[2], 'Any?')}` : ''})`
223
+ : `${t.expr(target)}.${method}(${t.str(e.arguments[0])}${e.arguments[1] ? `, ${t.coerce(e.arguments[1], 'Any?')}` : ''})`;
224
+ return value === 'Any?' ? call : `${call}.mapValues { (__v: Any?) -> ${value} in ${t.fromAny('__v', value)} }`;
225
+ }
226
+ return undefined;
227
+ }
228
+ /** A source base class the injector also makes, whose `shared` this class's overrides: each class has its own root instance. */
229
+ function injectableBase(t, cls) {
230
+ for (let b = t.sourceBase(cls); b; b = t.sourceBase(b))
231
+ if (ts.isClassDeclaration(b) && ['based', 'root'].includes(injectableRole(b, t.pluginFiles) ?? ''))
232
+ return true;
233
+ return false;
234
+ }
235
+ /**
236
+ * What makes a class the injector makes as a root service: an extension of it, or class members when a base class's
237
+ * are overridden (an extension cannot override) or when its subclasses may override them.
238
+ */
239
+ function injectableStatics(t, cls, code, form) {
240
+ const name = ts.isModuleBlock(cls.parent) ? cls.name.text : t.topName(cls, cls.name.text);
241
+ const ctor = cls.members.find((m) => ts.isConstructorDeclaration(m) && !!m.body);
242
+ const args = (ctor?.parameters ?? []).map((p) => t.constructorParameter(p));
243
+ const throwsInit = /^\s*(?:override )?(?:convenience )?init\(.*\) throws/m.test(code) || (ctor?.parameters ?? []).some((p) => t.throwsInfo.injects(p));
244
+ const make = core.swift.tryIf(throwsInit, `${name}(${args.join(', ')})`);
245
+ const mods = form === 'extension' ? 'static' : form === 'class' ? 'class' : 'override class';
246
+ const shared = injectableShared(cls, t.pluginFiles, t.checker);
247
+ const members = [
248
+ throwsInit ? ` ${mods} var ${shared}: ${name} { get throws { try Injector.root(${name}.self) { ${make} } } }` : ` ${mods} var ${shared}: ${name} { Injector.root(${name}.self, making: { ${make} }) }`,
249
+ ` ${mods} var jsSharedInstance: Any? { get throws { ${throwsInit ? 'try ' : ''}${shared} } }`,
250
+ ` ${mods} func jsConstruct() throws -> Any? { ${make} }`,
251
+ ];
252
+ return form === 'extension' ? [`extension ${name}: JSInjectableType {`, ...members, '}'] : members;
253
+ }
254
+ /**
255
+ * What the injector reads of an NgModule: its metadata, evaluated once as the decorator is, and how it is made, its
256
+ * constructor's parameters injected.
257
+ */
258
+ function ngModuleStatics(t, cls, name, def, code) {
259
+ const ctor = cls.members.find((m) => ts.isConstructorDeclaration(m) && !!m.body);
260
+ const args = (ctor?.parameters ?? []).map((p) => t.constructorParameter(p));
261
+ const throwsInit = /^\s*(?:override )?(?:convenience )?init\(.*\) throws/m.test(code) || (ctor?.parameters ?? []).some((p) => t.throwsInfo.injects(p));
262
+ return [
263
+ ` static let jsNgImports: Any? = JSArray<Any?>([${def.imports.map((e) => t.coerce(e, 'Any?')).join(', ')}])`,
264
+ ` static let jsNgProviders: Any? = ${def.providers ? t.coerce(def.providers, 'Any?') : 'nil'}`,
265
+ ` static func jsNgConstruct() throws -> Any? { ${core.swift.tryIf(throwsInit, `${name}(${args.join(', ')})`)} }`,
266
+ ];
267
+ }
268
+ export const swiftHooks = {
269
+ ...model,
270
+ typeMap: {
271
+ OutputEmitterRef: 'Emitter<$0>',
272
+ EventEmitter: 'Emitter<$0>',
273
+ RouterExtensions: { type: 'Router', shim: true },
274
+ EnvironmentInjector: { type: 'Injector', shim: true },
275
+ ...Object.fromEntries(['RxObservable', 'RxSubject', 'RxBehaviorSubject', 'RxReplaySubject'].map((n) => [n, { type: `${n}<$0>`, shim: true }])),
276
+ ...Object.fromEntries(['NativeDialogRef', 'NativeDialogService', 'DestroyRef', 'Injector', 'InjectionToken', 'ErrorHandler', 'NgZone', 'HttpClient', 'ChangeDetectorRef', 'PurePipeCache', 'NodeInjector', 'ElementRef', 'SimpleChange',
277
+ 'TeardownHandle', 'NavigationEnd', 'NavigationStart', 'NavigationCancel', 'NavigationError', 'RoutesRecognized', 'ResolveStart', 'ResolveEnd',
278
+ 'KitHttpClient', 'KitActivatedRoute', 'KitRouter', 'KitNativeDialogRef', 'KitNativeDialogService',
279
+ 'HttpParams', 'HttpHeaders', 'HttpResponse', 'HttpErrorResponse', 'HttpRequest', 'HttpContext', 'HttpContextToken',
280
+ 'ParamMap', 'UrlSegment', 'UrlTree', 'DefaultUrlSerializer', 'ActivatedRouteSnapshot',
281
+ 'ViewContainerRef', 'TemplateRef', 'ComponentRef', 'EmbeddedViewRef', 'ApplicationRef', 'Location'].map((n) => [n, { type: n, shim: true, metatype: true }])),
282
+ },
283
+ globalCall,
284
+ methodCall,
285
+ newCall: (t, name, e) => (name === 'Inject' && e.arguments?.[0] && t.resolve(e.expression)?.declarations?.[0]?.getSourceFile().fileName.startsWith('/__shims__/') ? `(${t.coerce(e.arguments[0], 'Any?')} as Any?)` : undefined),
286
+ constructorParameter: parameterInject,
287
+ componentField(t, m) {
288
+ const callee = m.initializer ? t.calleeName(m.initializer) : '';
289
+ if (callee !== 'input' && callee !== 'input.required' && callee !== 'model' && callee !== 'model.required')
290
+ return undefined;
291
+ // An Angular input is a prop: a signal the parent writes.
292
+ const type = t.typeOf(m.name).replace(/^Signal<(.*)>$/, '$1');
293
+ const given = m.initializer.arguments[0];
294
+ return { prop: { type, default: given ? (type.startsWith('JSNullish<') ? t.stored(given, given, type) : t.expr(given)) : callee === 'input' || callee === 'model' ? 'nil' : undefined } };
295
+ },
296
+ /** A standalone component's imports as its root-view injector reads them, evaluated once as the decorator is. */
297
+ componentStatics(t, cls) {
298
+ const ngImports = standaloneImports(cls, t.checker, t.compiles);
299
+ return ngImports ? [` static let jsNgImports: Any? = JSArray<Any?>([${ngImports.map((e) => t.coerce(e, 'Any?')).join(', ')}])`] : [];
300
+ },
301
+ componentAsValue: (t, cls, type) => `ComponentFactory { ${t.rootView(cls, type, `try ${type}().render()`)} }`,
302
+ /** A component created as a root view (bootstrap, route, dialog): made and rendered in its standalone injector. */
303
+ wrapRootView: (t, cls, type, make) => (standaloneImports(cls, t.checker, t.compiles) ? `try Injector.standalone(${type}.self, ${type}.jsNgImports) { ${make} }` : make),
304
+ serviceClass(t, cls, name) {
305
+ const members = t.componentMembers(cls, [], true);
306
+ // A constructor that throws throws from the inject() that made it, and the next inject() makes the service again.
307
+ const throwsInit = members.some((m) => /^\s*(?:convenience )?init\(.*\) throws/m.test(m));
308
+ const shared = throwsInit
309
+ ? [
310
+ ` static var shared: ${name} { get throws { try Injector.root(${name}.self) { try ${name}() } } }`,
311
+ ` static var jsSharedInstance: Any? { get throws { try shared } }`,
312
+ ` static func jsConstruct() throws -> Any? { try ${name}() }`,
313
+ ]
314
+ : [
315
+ ` static var shared: ${name} { Injector.root(${name}.self, making: { ${name}() }) }`,
316
+ ` static var jsSharedInstance: Any? { shared }`,
317
+ ` static func jsConstruct() throws -> Any? { ${name}() }`,
318
+ ];
319
+ return [`final class ${name}: JSInjectableType {`, core.swift.NONISOLATED_DEINIT, ...shared, '', ...members, '}'].join('\n');
320
+ },
321
+ // An app's @Injectable class extending another class: translated as any class is, and made by the injector as a service is.
322
+ afterClass: (t, cls, code) => (injectableRole(cls, t.pluginFiles) === 'based' && !injectableBase(t, cls) ? injectableStatics(t, cls, code, 'extension').join('\n') : undefined),
323
+ classExtras(t, cls, name, code) {
324
+ const supertypes = [];
325
+ const members = [];
326
+ const role = injectableRole(cls, t.pluginFiles);
327
+ if (role === 'root' || (role === 'based' && injectableBase(t, cls))) {
328
+ const overrides = injectableBase(t, cls);
329
+ if (!overrides)
330
+ supertypes.push('JSInjectableType');
331
+ members.push(...injectableStatics(t, cls, code, overrides ? 'override' : 'class'));
332
+ }
333
+ const ngModule = ngModuleDef(cls, t.checker, t.compiles);
334
+ if (ngModule) {
335
+ supertypes.push('JSNgModuleType');
336
+ members.push(...ngModuleStatics(t, cls, name, ngModule, [code, ...members].join('\n')));
337
+ }
338
+ return { supertypes, members };
339
+ },
340
+ };