@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/core-api.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** The compiler's own functions and state, from the compiler that loaded the adapter: set by its entry before any front end runs. */
|
|
2
|
+
export let core;
|
|
3
|
+
/** The compiler's TypeScript (`core.ts`), set with `core`: the adapter reads and makes the compiler's syntax trees with it, never with a TypeScript of its own. */
|
|
4
|
+
export let ts;
|
|
5
|
+
export function useCore(api) {
|
|
6
|
+
core = api;
|
|
7
|
+
ts = api.ts;
|
|
8
|
+
}
|
package/dist/entry.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { dirname, join, resolve } from 'node:path';
|
|
2
|
+
import { ts } from "./core-api.js";
|
|
3
|
+
/** A route tree as the Swift kit's `RouteConfig`s. */
|
|
4
|
+
export function swiftRouteConfig(routes, indent, ctx) {
|
|
5
|
+
const one = (r) => {
|
|
6
|
+
const named = [
|
|
7
|
+
r.outlet ? `outlet: ${JSON.stringify(r.outlet)}` : '',
|
|
8
|
+
r.redirectTo !== undefined ? `redirectTo: ${JSON.stringify(r.redirectTo)}` : '',
|
|
9
|
+
r.full ? 'full: true' : '',
|
|
10
|
+
r.emptyOutlet ? 'emptyOutlet: true' : '',
|
|
11
|
+
r.guards !== undefined ? `guards: ${r.guards}` : '',
|
|
12
|
+
r.data ? `data: [${r.data.map(([k, v]) => `(${ctx.string(k)}, ${v === null ? 'jsNull' : typeof v === 'string' ? ctx.string(v) : typeof v === 'number' ? `Double(${Object.is(v, -0) ? '-0.0' : v})` : v})`).join(', ')}]` : '',
|
|
13
|
+
r.children?.length ? `children: ${swiftRouteConfig(r.children, indent + ' ', ctx)}` : '',
|
|
14
|
+
].filter(Boolean);
|
|
15
|
+
// canDeactivate guards take the component: the router keeps the instance it renders.
|
|
16
|
+
const make = r.deactivate ? `Router.shared.activating(${ctx.className(r.component)}())` : `${ctx.className(r.component)}()`;
|
|
17
|
+
return `RouteConfig(${[JSON.stringify(r.path), ...named].join(', ')})${r.component ? ` { ${ctx.rootView(r.component, `try ${make}.render()`)} }` : ''}`;
|
|
18
|
+
};
|
|
19
|
+
return `[\n${routes.map((r) => `${indent} ${one(r)}`).join(',\n')}\n${indent}]`;
|
|
20
|
+
}
|
|
21
|
+
const kotlinDouble = (n) => (Object.is(n, -0) ? '-0.0' : /[.e]/.test(String(n)) ? String(n) : `${n}.0`);
|
|
22
|
+
/** A route tree as the generated Android kit's `RouteConfig`s. */
|
|
23
|
+
export function kotlinRouteConfig(routes, indent, ctx) {
|
|
24
|
+
const one = (r) => {
|
|
25
|
+
const named = [
|
|
26
|
+
r.outlet ? `outlet = ${ctx.string(r.outlet)}` : '',
|
|
27
|
+
r.redirectTo !== undefined ? `redirectTo = ${ctx.string(r.redirectTo)}` : '',
|
|
28
|
+
r.full ? 'full = true' : '',
|
|
29
|
+
r.guards !== undefined ? `guards = ${r.guards}` : '',
|
|
30
|
+
r.data ? `data = listOf(${r.data.map(([k, v]) => `${ctx.string(k)} to ${v === null ? 'jsNull' : typeof v === 'string' ? ctx.string(v) : typeof v === 'number' ? kotlinDouble(v) : v}`).join(', ')})` : '',
|
|
31
|
+
r.children?.length ? `children = ${kotlinRouteConfig(r.children, indent + ' ', ctx)}` : '',
|
|
32
|
+
].filter(Boolean);
|
|
33
|
+
// canDeactivate guards take the component: the router keeps the instance it renders.
|
|
34
|
+
const make = r.deactivate ? `Router.shared.activating(${r.component}())` : `${r.component}()`;
|
|
35
|
+
return `RouteConfig(${[ctx.string(r.path), ...named].join(', ')})${r.component ? ` { ${ctx.rootView(r.component, `${make}.render()`)} }` : ''}`;
|
|
36
|
+
};
|
|
37
|
+
return `listOf(\n${routes.map((r) => `${indent} ${one(r)}`).join(',\n')}\n${indent})`;
|
|
38
|
+
}
|
|
39
|
+
/** The Angular entry without the call that bootstraps the app, or null when that is all it does. */
|
|
40
|
+
export function angularEntryModule(file, text, routeFiles, components, aliased) {
|
|
41
|
+
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
|
|
42
|
+
const isBootstrap = (st) => ts.isExpressionStatement(st) && ts.isCallExpression(st.expression)
|
|
43
|
+
&& /^(runNativeScriptAngularApp|platformNativeScript|platformNativeScriptDynamic|bootstrapApplication)\b/.test(st.expression.expression.getText());
|
|
44
|
+
const isBuiltinProviderCall = (e) => {
|
|
45
|
+
if (!ts.isCallExpression(e))
|
|
46
|
+
return false;
|
|
47
|
+
const fn = e.expression.getText();
|
|
48
|
+
if (/^(provideNativeScriptRouter|provideRouter|provideZoneChangeDetection|provideZonelessChangeDetection|provideExperimentalZonelessChangeDetection|provideNativeScriptNgZone)$/.test(fn))
|
|
49
|
+
return true;
|
|
50
|
+
if (/^(provideNativeScriptHttpClient|provideHttpClient)$/.test(fn) && e.arguments.every((a) => ts.isCallExpression(a) && /^(withInterceptorsFromDi|withFetch|withJsonpSupport|withNoXsrfProtection)$/.test(a.expression.getText())))
|
|
51
|
+
return true;
|
|
52
|
+
return false;
|
|
53
|
+
};
|
|
54
|
+
let hasCustomProviders = false;
|
|
55
|
+
const blankRanges = [];
|
|
56
|
+
const nullFirstArgRanges = [];
|
|
57
|
+
const visit = (n) => {
|
|
58
|
+
if (ts.isCallExpression(n)) {
|
|
59
|
+
const fn = n.expression.getText();
|
|
60
|
+
if (fn === 'bootstrapApplication') {
|
|
61
|
+
if (n.arguments[0]) {
|
|
62
|
+
nullFirstArgRanges.push([n.arguments[0].getStart(), n.arguments[0].getEnd()]);
|
|
63
|
+
}
|
|
64
|
+
const cfg = n.arguments[1];
|
|
65
|
+
if (cfg) {
|
|
66
|
+
if (ts.isObjectLiteralExpression(cfg)) {
|
|
67
|
+
for (const prop of cfg.properties) {
|
|
68
|
+
if (ts.isPropertyAssignment(prop) && prop.name.getText() === 'providers' && ts.isArrayLiteralExpression(prop.initializer)) {
|
|
69
|
+
if (prop.initializer.elements.some((el) => !isBuiltinProviderCall(el))) {
|
|
70
|
+
hasCustomProviders = true;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
hasCustomProviders = true;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
else if (fn === 'provideNativeScriptRouter' || fn === 'provideRouter') {
|
|
81
|
+
if (n.arguments.length) {
|
|
82
|
+
blankRanges.push([n.arguments[0].getStart(), n.arguments[n.arguments.length - 1].getEnd()]);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
ts.forEachChild(n, visit);
|
|
87
|
+
};
|
|
88
|
+
visit(sf);
|
|
89
|
+
const rest = sf.statements.filter((st) => !ts.isImportDeclaration(st) && !isBootstrap(st));
|
|
90
|
+
if (!rest.length && !hasCustomProviders)
|
|
91
|
+
return null;
|
|
92
|
+
const componentFiles = new Set(components.map((c) => c.file.replace(/\.release\.ts$/, '.ts')));
|
|
93
|
+
for (const st of sf.statements) {
|
|
94
|
+
if (ts.isImportDeclaration(st) && ts.isStringLiteral(st.moduleSpecifier)) {
|
|
95
|
+
const spec = st.moduleSpecifier.text;
|
|
96
|
+
const base = aliased(spec) ?? (spec.startsWith('.') ? resolve(dirname(file), spec) : undefined);
|
|
97
|
+
if (base) {
|
|
98
|
+
const candidates = [base, base + '.ts', join(base, 'index.ts')];
|
|
99
|
+
if (candidates.some((c) => routeFiles.has(c) || componentFiles.has(c))) {
|
|
100
|
+
blankRanges.push([st.getStart(), st.getEnd()]);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
else if (isBootstrap(st) && !hasCustomProviders) {
|
|
105
|
+
blankRanges.push([st.getStart(), st.getEnd()]);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
let out = text;
|
|
109
|
+
for (const [s, e] of nullFirstArgRanges) {
|
|
110
|
+
const len = e - s;
|
|
111
|
+
const rep = (len >= 4 ? 'null' : '0').padEnd(len, ' ');
|
|
112
|
+
out = out.slice(0, s) + rep + out.slice(e);
|
|
113
|
+
}
|
|
114
|
+
for (const [s, e] of blankRanges) {
|
|
115
|
+
out = out.slice(0, s) + out.slice(s, e).replace(/[^\n]/g, ' ') + out.slice(e);
|
|
116
|
+
}
|
|
117
|
+
return out;
|
|
118
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { angularComponent, angularDirectives, angularPipes, angularRoutes, angularRouteTree, componentOf, declarableSource, declarablesIn, hostedComponent, routedComponents, selectorElements } from "./angular.js";
|
|
4
|
+
import { angularLibraries, registeredElements } from "./angular-libraries.js";
|
|
5
|
+
import { refuseBaseUses } from "./component-bases.js";
|
|
6
|
+
import { useCore } from "./core-api.js";
|
|
7
|
+
import { angularEntryModule, kotlinRouteConfig, swiftRouteConfig } from "./entry.js";
|
|
8
|
+
import { modules } from "./modules.js";
|
|
9
|
+
import { PACKAGE, RUNTIME } from "./package.js";
|
|
10
|
+
import { refusals } from "./refusals.js";
|
|
11
|
+
import { kotlinHooks } from "./kotlin.js";
|
|
12
|
+
import { swiftHooks } from "./swift.js";
|
|
13
|
+
/** @angular/common's pipes, NgClass, NgStyle and QueryList as TypeScript the app's components compile with. */
|
|
14
|
+
const COMMON = join(RUNTIME, 'angular.ts');
|
|
15
|
+
/** The build's own module of `COMMON`, in the app's folder: the components import it by a relative path. */
|
|
16
|
+
const COMMON_MODULE = '__angular.release.ts';
|
|
17
|
+
/**
|
|
18
|
+
* Angular appends each view as it is created, runs a template's bindings once its views are built, and re-reads every
|
|
19
|
+
* binding when change detection checks its view (`Check`); under zone.js an OnPush component is checked only once
|
|
20
|
+
* marked dirty (`check+onPush`). A listener marks its view and the views above it dirty (`markViewDirty`). Views and
|
|
21
|
+
* embedded views order effects; `@for` rows read their item and index as signals.
|
|
22
|
+
*/
|
|
23
|
+
const behaviour = {
|
|
24
|
+
schedule: 'task', eventScope: 'event+dirtyView', propsOrder: 'pre', deferBindings: true, insertion: 'created', listenersAfterBindings: false,
|
|
25
|
+
effectScope: 'view', checkEveryBinding: 'check', slots: false, rowSignals: 'array', fragments: true,
|
|
26
|
+
kit: {
|
|
27
|
+
scope: { template: 'EffectOrder.view', region: 'EffectOrder.embedded' },
|
|
28
|
+
currentView: 'EffectOrder.current.view',
|
|
29
|
+
check: 'Check',
|
|
30
|
+
inputChanged: 'Zone.inputChanged',
|
|
31
|
+
directiveHost: 'ElementRef.hosting',
|
|
32
|
+
routerOutlet: { call: 'Router.shared.outlet', primary: 'primary' },
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
export default function adapter(core) {
|
|
36
|
+
useCore(core);
|
|
37
|
+
return {
|
|
38
|
+
apiVersion: 1,
|
|
39
|
+
name: 'angular',
|
|
40
|
+
packages: ['@nativescript/angular', '@angular/*'],
|
|
41
|
+
behaviour,
|
|
42
|
+
reach: 'entry',
|
|
43
|
+
swift: swiftHooks,
|
|
44
|
+
kotlin: kotlinHooks,
|
|
45
|
+
modules,
|
|
46
|
+
runtimeRoots: [RUNTIME],
|
|
47
|
+
runtimeModules: [COMMON_MODULE],
|
|
48
|
+
package: PACKAGE,
|
|
49
|
+
kit: { apple: 'kit-apple', android: 'kit-android/main', androidGenerated: 'kit-android/fromcore', androidHandPort: 'kit-android/handport' },
|
|
50
|
+
refusals,
|
|
51
|
+
frontEnd(app) {
|
|
52
|
+
const read = (f) => readFileSync(f, 'utf8');
|
|
53
|
+
const { sources, entry, entryText, appDir, platform } = app;
|
|
54
|
+
// The Angular components of plugins the app imports (`<package>/angular`), compiled from their source with the app's.
|
|
55
|
+
const libraries = angularLibraries(sources, app.nodeModules, app.plugins, app.replacedPackages);
|
|
56
|
+
sources.push(...libraries);
|
|
57
|
+
const selectors = new Map();
|
|
58
|
+
const hosts = [];
|
|
59
|
+
for (const f of sources) {
|
|
60
|
+
const text = read(f);
|
|
61
|
+
const c = componentOf(f, text);
|
|
62
|
+
for (const tag of c?.selector ? selectorElements(c.selector) : [])
|
|
63
|
+
selectors.set(tag, c.name);
|
|
64
|
+
const hosted = c ? hostedComponent(f, text) : null;
|
|
65
|
+
if (hosted)
|
|
66
|
+
hosts.push(hosted);
|
|
67
|
+
}
|
|
68
|
+
// The configuration the entry provides, lazy routes followed into their files; else one routes file read flat.
|
|
69
|
+
const tree = angularRouteTree(entry, read, app.aliased);
|
|
70
|
+
const routesFile = tree ? undefined : sources.find((f) => /Routes\b/.test(read(f)) && /component:/.test(read(f)));
|
|
71
|
+
const { routes, initial } = routesFile ? angularRoutes(read(routesFile), routesFile) : { routes: [], initial: '/' };
|
|
72
|
+
const routeFiles = new Set([...(tree?.files ?? []), ...(routesFile ? [routesFile] : [])]);
|
|
73
|
+
// Tags the entry registers too (`registerElement('Glass', …)` in main.ts, before the app bootstraps).
|
|
74
|
+
const elements = registeredElements([...(entry && !sources.includes(entry) ? [entry] : []), ...sources], app.nodeModules);
|
|
75
|
+
// Angular 22 checks with zone.js only when the app provides it (`provideZoneChangeDetection`, or @nativescript/angular's
|
|
76
|
+
// `provideNativeScriptNgZone`, which is `_internalProvideZoneChangeDetection` with its own NgZone) and not `provideZonelessChangeDetection`.
|
|
77
|
+
const texts = [entryText, ...sources.map(read)];
|
|
78
|
+
const zone = texts.some((t) => /\bprovide(ZoneChangeDetection|NativeScriptNgZone)\(/.test(t)) && !texts.some((t) => /\bprovideZonelessChangeDetection\(/.test(t));
|
|
79
|
+
// The pipes templates name: the app's and its libraries' `@Pipe` classes, and @angular/common's, in the build's Angular runtime module.
|
|
80
|
+
const pipes = angularPipes(sources, read);
|
|
81
|
+
// The app's own directives: a library's are written against the view internals a compiled template replaces.
|
|
82
|
+
const directives = angularDirectives(sources.filter((f) => !libraries.includes(f)), read);
|
|
83
|
+
// What each NgModule declares, imports and exports: a component's directives are those in its scope.
|
|
84
|
+
const ngModuleNames = new Map(sources.flatMap((f) => [...declarablesIn(f, read(f), !libraries.includes(f)).modules]));
|
|
85
|
+
const runtimeModule = join(appDir, COMMON_MODULE);
|
|
86
|
+
refuseBaseUses(sources);
|
|
87
|
+
const components = sources.map((f) => angularComponent(f, read(f), selectors, { zone, platform, pipes, runtimeModule, directives, ngModules: ngModuleNames, hosts, elements: new Map([...elements].map(([tag, e]) => [tag, e.name])), elementMeta: new Map([...elements].flatMap(([tag, e]) => (e.meta === undefined ? [] : [[tag, e.meta]]))) })).filter((c) => !!c);
|
|
88
|
+
const routed = new Set(tree ? routedComponents(tree.routes) : routes.map((r) => r.component));
|
|
89
|
+
for (const c of components)
|
|
90
|
+
c.page = routed.has(c.name);
|
|
91
|
+
const overrides = new Map();
|
|
92
|
+
// The classes of registered tags, imported where the build can reach them: route files, which only configure, are not compiled.
|
|
93
|
+
if (elements.size) {
|
|
94
|
+
const file = join(appDir, '__elements.release.ts');
|
|
95
|
+
const specs = [...elements.values()];
|
|
96
|
+
overrides.set(file, specs.map((e) => `import { ${e.name} } from '${e.from}';`).join('\n') + `\nexport function $elements(): any[] { return [${specs.map((e) => `new ${e.name}()`).join(', ')}]; }\n`);
|
|
97
|
+
}
|
|
98
|
+
const modules = [...sources.filter((f) => !routeFiles.has(f) && !components.some((c) => c.file === f.replace(/\.ts$/, '.release.ts'))), ...(elements.size ? [join(appDir, '__elements.release.ts')] : [])];
|
|
99
|
+
// Route files only configure and are not compiled; their guards are, each file's in a module of its own.
|
|
100
|
+
(tree?.guards ?? []).forEach((g, i) => {
|
|
101
|
+
const file = join(appDir, `__routes${i}.release.ts`);
|
|
102
|
+
overrides.set(file, g.source(appDir, platform));
|
|
103
|
+
modules.push(file);
|
|
104
|
+
});
|
|
105
|
+
if (components.some((c) => 'usesRuntime' in c && c.usesRuntime)) {
|
|
106
|
+
overrides.set(runtimeModule, read(COMMON));
|
|
107
|
+
modules.push(runtimeModule);
|
|
108
|
+
}
|
|
109
|
+
// `@Pipe` and `@Directive` classes without their decorators, made through the `$create` that injects their constructor's parameters.
|
|
110
|
+
for (const f of modules) {
|
|
111
|
+
if (overrides.has(f))
|
|
112
|
+
continue;
|
|
113
|
+
const declarable = declarableSource(f, read(f));
|
|
114
|
+
if (declarable)
|
|
115
|
+
overrides.set(f, declarable);
|
|
116
|
+
}
|
|
117
|
+
// The entry's own statements (an app delegate, a keyboard setup) run after the modules it imports, the bootstrap call aside.
|
|
118
|
+
const entryModule = angularEntryModule(entry, entryText, routeFiles, components, app.aliased);
|
|
119
|
+
if (entryModule) {
|
|
120
|
+
overrides.set(entry, entryModule);
|
|
121
|
+
modules.push(entry);
|
|
122
|
+
}
|
|
123
|
+
let root = /bootstrapApplication\(\s*(\w+)/.exec(entryText)?.[1] ?? '';
|
|
124
|
+
const appModule = /bootstrapModule\(\s*(\w+)/.exec(entryText)?.[1];
|
|
125
|
+
if (!root && appModule) {
|
|
126
|
+
const declaring = sources.map(read).find((t) => new RegExp(`class\\s+${appModule}\\b`).test(t));
|
|
127
|
+
root = (declaring && /bootstrap:\s*\[\s*(\w+)/.exec(declaring)?.[1]) ?? '';
|
|
128
|
+
}
|
|
129
|
+
if (!root)
|
|
130
|
+
throw new Error(`${entry}: no bootstrapApplication(Component) or bootstrapModule(AppModule) with a bootstrap component`);
|
|
131
|
+
const zoneEnabled = zone ? ' Zone.enabled = true\n' : '';
|
|
132
|
+
return {
|
|
133
|
+
components,
|
|
134
|
+
modules,
|
|
135
|
+
overrides,
|
|
136
|
+
root,
|
|
137
|
+
behaviour: zone ? { ...behaviour, checkEveryBinding: 'check+onPush' } : behaviour,
|
|
138
|
+
elementClasses: new Set([...elements.values()].map((e) => e.name)),
|
|
139
|
+
entry: {
|
|
140
|
+
swift: (ctx) => ({
|
|
141
|
+
setup: zoneEnabled,
|
|
142
|
+
beforeRoot: tree
|
|
143
|
+
? ` Router.shared.config = ${swiftRouteConfig(tree.routes, ' ', ctx)}\n`
|
|
144
|
+
: ` Router.shared.routes = [${routes.map((r) => `Route(${JSON.stringify(r.path)}) { ${ctx.rootView(r.component, `try ${ctx.className(r.component)}().render()`)} }`).join(', ')}]\n Router.shared.initial = ${JSON.stringify(initial)}\n`,
|
|
145
|
+
}),
|
|
146
|
+
// Only the generated Android kit has `RouteConfig`: the hand-ported one takes the flat routes.
|
|
147
|
+
kotlin: (ctx) => ({
|
|
148
|
+
setup: zoneEnabled,
|
|
149
|
+
beforeRoot: tree && ctx.generatedKit
|
|
150
|
+
? ` Router.shared.config = ${kotlinRouteConfig(tree.routes, ' ', ctx)}\n`
|
|
151
|
+
: ` Router.shared.routes = listOf(${routes.map((r) => `Route(${ctx.string(r.path)}) { ${ctx.rootView(r.component, `${r.component}().render()`)} }`).join(', ')})\n Router.shared.initial = ${ctx.string(initial)}\n`,
|
|
152
|
+
}),
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|
package/dist/kotlin.js
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
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, isStatic, model, parameterDecorators } from "./semantics.js";
|
|
4
|
+
/** An injection token's name: a framework class by the name it is declared with (`NativeDialog` is `NativeDialogService`). */
|
|
5
|
+
function tokenName(t, e) {
|
|
6
|
+
const decl = t.resolve(e)?.declarations?.[0];
|
|
7
|
+
if (!decl || !ts.isClassDeclaration(decl) || !decl.name)
|
|
8
|
+
return e.getText();
|
|
9
|
+
const file = decl.getSourceFile();
|
|
10
|
+
if (file.fileName.startsWith('/__shims__/'))
|
|
11
|
+
return decl.name.text;
|
|
12
|
+
// A program's class by its Kotlin name, whatever the import calls it (`RouterExtensions as $RouterExtensions`).
|
|
13
|
+
return file.isDeclarationFile ? e.getText() : t.topName(decl, decl.name.text);
|
|
14
|
+
}
|
|
15
|
+
/** What `inject(token)` gives at `at`; a ViewContainerRef has no instance whose views would attach to the component's. */
|
|
16
|
+
function injectedToken(t, token, at, decl) {
|
|
17
|
+
if (token === 'ViewContainerRef')
|
|
18
|
+
throw t.error(at, 'an injected ViewContainerRef', 'view-container-ref');
|
|
19
|
+
const code = injected('kotlin', token, decl && ts.isClassDeclaration(decl) ? injectableShared(decl, t.pluginFiles, t.checker) : undefined);
|
|
20
|
+
// A `shared` the module's statements initialize is held nullable until they run, which they have by injection.
|
|
21
|
+
const shared = decl && ts.isClassDeclaration(decl) ? decl.members.find((m) => ts.isPropertyDeclaration(m) && isStatic(m) && m.name.getText() === 'shared') : undefined;
|
|
22
|
+
return shared && t.heldUntilModuleRuns(shared) && code === `${token}.shared` ? `${code}!!` : code;
|
|
23
|
+
}
|
|
24
|
+
/** A class only a library's typings declare has no instance in a release build: the library's JavaScript provides it. */
|
|
25
|
+
function refuseTypingsOnlyToken(t, tokenDecl, token, at) {
|
|
26
|
+
if (tokenDecl && ts.isClassDeclaration(tokenDecl) && tokenDecl.getSourceFile().isDeclarationFile && !core.isCoreDeclaration(tokenDecl))
|
|
27
|
+
throw t.error(at, `an injected class only a library's typings declare (${token})`, 'library-injectable');
|
|
28
|
+
}
|
|
29
|
+
function parameterInject(t, p) {
|
|
30
|
+
const pt = t.typeOf(p.name);
|
|
31
|
+
const { token: given, optional, skipSelf } = parameterDecorators(p);
|
|
32
|
+
if (optional && skipSelf)
|
|
33
|
+
return core.kotlin.isNullable(pt) || pt === 'Any?' ? 'null' : t.fromAny('null', pt);
|
|
34
|
+
const injectArg = given && forwardRefTarget(given);
|
|
35
|
+
if (injectArg) {
|
|
36
|
+
const target = ts.isExpressionWithTypeArguments(injectArg) ? injectArg.expression : injectArg;
|
|
37
|
+
const token = tokenName(t, target);
|
|
38
|
+
if (token === 'NATIVE_DIALOG_DATA')
|
|
39
|
+
return t.fromAny('NativeDialogRef.current.data', pt);
|
|
40
|
+
const tokenDecl = t.resolve(target)?.declarations?.[0];
|
|
41
|
+
if (KIT_TOKENS.includes(token) || isInjectableClass(tokenDecl, t.pluginFiles))
|
|
42
|
+
return injectedToken(t, token, p, tokenDecl);
|
|
43
|
+
refuseTypingsOnlyToken(t, tokenDecl, token, p);
|
|
44
|
+
const raw = `Injector.inject(${t.coerce(injectArg, 'Any?')}${optional ? ', JSObject("optional" to true)' : ''})`;
|
|
45
|
+
return pt === 'Any?' ? raw : t.fromAny(raw, pt);
|
|
46
|
+
}
|
|
47
|
+
const ref = p.type && ts.isTypeReferenceNode(p.type)
|
|
48
|
+
? p.type
|
|
49
|
+
: p.type && ts.isUnionTypeNode(p.type)
|
|
50
|
+
? p.type.types.find(ts.isTypeReferenceNode)
|
|
51
|
+
: undefined;
|
|
52
|
+
if (ref) {
|
|
53
|
+
const token = tokenName(t, ref.typeName);
|
|
54
|
+
const tokenDecl = t.resolve(ref.typeName)?.declarations?.[0];
|
|
55
|
+
if (KIT_TOKENS.includes(token) || isInjectableClass(tokenDecl, t.pluginFiles))
|
|
56
|
+
return injectedToken(t, token, p, tokenDecl);
|
|
57
|
+
if (tokenDecl && ts.isClassDeclaration(tokenDecl)) {
|
|
58
|
+
refuseTypingsOnlyToken(t, tokenDecl, token, p);
|
|
59
|
+
const raw = `Injector.inject(${token}::class.java${optional ? ', JSObject("optional" to true)' : ''})`;
|
|
60
|
+
return pt === 'Any?' ? raw : t.fromAny(raw, pt);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
/** `linkedSignal({ source, computation })`: `computation`'s `previous` is the runtime's pair made the parameter's object. */
|
|
66
|
+
function linkedSignal(t, options, type, equals) {
|
|
67
|
+
const prop = (n) => {
|
|
68
|
+
const p = options.properties.find((q) => q.name && ts.isIdentifier(q.name) && q.name.text === n);
|
|
69
|
+
if (!p)
|
|
70
|
+
return undefined;
|
|
71
|
+
if (ts.isPropertyAssignment(p))
|
|
72
|
+
return p.initializer;
|
|
73
|
+
if (ts.isShorthandPropertyAssignment(p))
|
|
74
|
+
return p.name;
|
|
75
|
+
throw t.error(p, `a \`${n}\` of linkedSignal's options other than a property`);
|
|
76
|
+
};
|
|
77
|
+
const source = prop('source'), computation = prop('computation');
|
|
78
|
+
if (!source || !computation)
|
|
79
|
+
throw t.error(options, 'linkedSignal options without both `source` and `computation`');
|
|
80
|
+
const c = t.checker;
|
|
81
|
+
const sig = c.getResolvedSignature(options.parent);
|
|
82
|
+
const opts = c.getTypeOfSymbol(sig.parameters[0]);
|
|
83
|
+
const s = t.type(c.getTypeOfSymbol(c.getPropertyOfType(opts, 'source')).getCallSignatures()[0].getReturnType(), options);
|
|
84
|
+
const compSig = c.getTypeOfSymbol(c.getPropertyOfType(opts, 'computation')).getCallSignatures()[0];
|
|
85
|
+
const takesPrevious = (c.getTypeAtLocation(computation).getCallSignatures()[0]?.parameters.length ?? 2) > 1;
|
|
86
|
+
const prevType = takesPrevious ? t.type(c.getNonNullableType(c.getTypeOfSymbol(compSig.parameters[1])), options) : undefined;
|
|
87
|
+
const read = t.typeOf(source).startsWith('Signal<') ? `{ ${t.expr(source)}.value }` : t.symbolName(source) === 'Signal' ? `{ ${t.expr(source)} }` : t.expr(source);
|
|
88
|
+
const made = prevType && /^Object_\w+$/.test(prevType) ? `${prevType}(source = it.first, value = it.second)` : 'JSObject("source" to it.first, "value" to it.second)';
|
|
89
|
+
return `Signal.linked<${s}, ${type}>(${read}, { s: ${s}, p: Pair<${s}, ${type}>? -> (${t.expr(computation)})(s${prevType ? `, p?.let { ${made} }` : ''}) }${equals})`;
|
|
90
|
+
}
|
|
91
|
+
/** Whether a `linkedSignal(…)` call resolves to the overload taking `{ source, computation }` rather than a function. */
|
|
92
|
+
function linkedOptionsOverload(t, e) {
|
|
93
|
+
const first = t.checker.getResolvedSignature(e)?.parameters[0];
|
|
94
|
+
return !!first && t.checker.getTypeOfSymbol(first).getCallSignatures().length === 0;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* `linkedSignal(options)` with options other than a literal: `source`, `computation` and `equal` read by name once, as
|
|
98
|
+
* the signal is made, as Angular reads them. `previous` is made the type the options' own `computation` declares, which
|
|
99
|
+
* is what the function held there takes.
|
|
100
|
+
*/
|
|
101
|
+
function linkedSignalOptions(t, options, type, reference) {
|
|
102
|
+
const c = t.checker;
|
|
103
|
+
const sig = c.getResolvedSignature(options.parent);
|
|
104
|
+
const opts = c.getTypeOfSymbol(sig.parameters[0]);
|
|
105
|
+
const s = t.type(c.getTypeOfSymbol(c.getPropertyOfType(opts, 'source')).getCallSignatures()[0].getReturnType(), options);
|
|
106
|
+
const held = c.getPropertyOfType(c.getNonNullableType(c.getTypeAtLocation(options)), 'computation');
|
|
107
|
+
const prevParam = held && c.getNonNullableType(c.getTypeOfSymbol(held)).getCallSignatures()[0]?.parameters[1];
|
|
108
|
+
const prevType = prevParam ? t.type(c.getNonNullableType(c.getTypeOfSymbol(prevParam)), options) : 'Any?';
|
|
109
|
+
const previous = t.fromAny('JSObject("source" to it.first, "value" to it.second)', prevType);
|
|
110
|
+
const fallback = reference ? '::jsSame' : `{ a: ${type}, b: ${type} -> a == b }`;
|
|
111
|
+
return `run { val __o: Any? = ${t.coerce(options, 'Any?')}; val __source = jsGetOptional(__o, "source"); val __computation = jsGetOptional(__o, "computation"); `
|
|
112
|
+
+ `Signal.linked<${s}, ${type}>({ ${t.fromAny('jsCall(__source)', s)} }, { s: ${s}, p: Pair<${s}, ${type}>? -> ${t.fromAny(`jsCall(__computation, s, p?.let { ${previous} })`, type)} }, jsEqualOption<${type}>(__o, ${fallback})) }`;
|
|
113
|
+
}
|
|
114
|
+
function globalCall(t, name, e, decl, lib) {
|
|
115
|
+
const arg = (k) => e.arguments[k];
|
|
116
|
+
if (name === 'linkedSignal' && lib) {
|
|
117
|
+
const type = t.typeOf(e).replace(/^Signal<(.*)>$/, '$1');
|
|
118
|
+
const reference = !['Double', 'String', 'Boolean'].includes(type.replace(/\?$/, '')) && !core.kotlin.isFunctionType(type);
|
|
119
|
+
const fallback = reference ? ', ::jsSame' : '';
|
|
120
|
+
const options = arg(0) && ts.isObjectLiteralExpression(ts.skipOuterExpressions(arg(0))) ? ts.skipOuterExpressions(arg(0)) : undefined;
|
|
121
|
+
if (!options && linkedOptionsOverload(t, e))
|
|
122
|
+
return linkedSignalOptions(t, arg(0), type, reference);
|
|
123
|
+
if (!options)
|
|
124
|
+
return `Signal.linked<${type}>(${t.expr(arg(0))}${t.equalsArg(arg(1), type) ?? fallback})`;
|
|
125
|
+
return linkedSignal(t, options, type, t.equalsArg(options, type) ?? fallback);
|
|
126
|
+
}
|
|
127
|
+
if (name === 'computed' && angularCall(e, 'computed', t.checker) && t.typeOf(e).startsWith('Signal<')) {
|
|
128
|
+
const fn = arg(0), rt = t.typeOf(e).replace(/^Signal<(.*)>$/, '$1');
|
|
129
|
+
if (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn))
|
|
130
|
+
return `Signal.computed(${t.memo(fn, rt, t.indent)})`;
|
|
131
|
+
return `Signal.computed(Memo<${rt}>(${t.coerce(fn, `() -> ${rt}`)}${t.equalsArg(arg(1), rt) ?? ''}))`;
|
|
132
|
+
}
|
|
133
|
+
if (name === 'untracked' && lib)
|
|
134
|
+
return `untrack(${t.expr(arg(0))})`;
|
|
135
|
+
if (name === 'runInInjectionContext' && lib) {
|
|
136
|
+
const fn = arg(1);
|
|
137
|
+
if (fn && (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn))) {
|
|
138
|
+
const type = t.typeOf(e);
|
|
139
|
+
return `Injector.runInContext(${t.restArgument(e, arg(0), 'Any?')}, ${t.closure(fn, `() -> ${type}`)})`;
|
|
140
|
+
}
|
|
141
|
+
const raw = `Injector.runInContext(${t.restArgument(e, arg(0), 'Any?')}) { jsCall(${t.restArgument(e, arg(1), 'Any?')}) }`;
|
|
142
|
+
const type = t.typeOf(e);
|
|
143
|
+
return type === 'Any?' || type === 'Unit' ? raw : t.fromAny(raw, type);
|
|
144
|
+
}
|
|
145
|
+
if ((name === 'forwardRef' || name === 'resolveForwardRef') && lib) {
|
|
146
|
+
const fn = arg(0);
|
|
147
|
+
if (fn && (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) && !ts.isBlock(fn.body))
|
|
148
|
+
return t.expr(fn.body);
|
|
149
|
+
return `resolveForwardRef(${arg(0) ? t.restArgument(e, arg(0), 'Any?') : 'null'})`;
|
|
150
|
+
}
|
|
151
|
+
if (name === 'isDevMode' && lib)
|
|
152
|
+
return 'false';
|
|
153
|
+
const shimmed = decl && ts.isFunctionDeclaration(decl) && decl.getSourceFile().fileName.startsWith('/__shims__/') ? decl.name?.text : undefined;
|
|
154
|
+
if (shimmed === 'enableProdMode')
|
|
155
|
+
return 'Unit';
|
|
156
|
+
if (shimmed === 'isAngularHmrRestoringRoute')
|
|
157
|
+
return 'false';
|
|
158
|
+
if (name === 'effect' && lib && arg(0))
|
|
159
|
+
return `Effect.deferred(${t.callback(arg(0))})`;
|
|
160
|
+
if (name === 'output' && lib)
|
|
161
|
+
return `${t.typeOf(e)}()`;
|
|
162
|
+
if (name === 'inject' && lib) {
|
|
163
|
+
const rawArg0 = forwardRefTarget(arg(0));
|
|
164
|
+
const target = ts.isExpressionWithTypeArguments(rawArg0) ? rawArg0.expression : rawArg0;
|
|
165
|
+
const token = tokenName(t, target);
|
|
166
|
+
if (token === 'NATIVE_DIALOG_DATA')
|
|
167
|
+
return t.fromAny('NativeDialogRef.current.data', t.typeOf(e));
|
|
168
|
+
const tokenDecl = t.resolve(target)?.declarations?.[0];
|
|
169
|
+
if (KIT_TOKENS.includes(token) || isInjectableClass(tokenDecl, t.pluginFiles))
|
|
170
|
+
return injectedToken(t, token, e, tokenDecl);
|
|
171
|
+
refuseTypingsOnlyToken(t, tokenDecl, token, e);
|
|
172
|
+
const raw = `Injector.inject(${t.coerce(rawArg0, 'Any?')}${arg(1) ? `, ${t.restArgument(e, arg(1), 'Any?')}` : ''})`;
|
|
173
|
+
const type = t.typeOf(e);
|
|
174
|
+
return type === 'Any?' ? raw : t.fromAny(raw, type);
|
|
175
|
+
}
|
|
176
|
+
if (name === 'firstValueFrom' && lib)
|
|
177
|
+
return `rxFirstValueFrom(${t.expr(arg(0))})`;
|
|
178
|
+
return undefined;
|
|
179
|
+
}
|
|
180
|
+
function methodCall(t, owner, method, e) {
|
|
181
|
+
const target = e.expression.expression;
|
|
182
|
+
if ((owner === 'OutputEmitterRef' || owner === 'EventEmitter') && (method === 'emit' || method === 'next')) {
|
|
183
|
+
const value = /^(?:OutputEmitterRef|EventEmitter|Emitter)<(.*)>[?!]?$/.exec(t.typeOf(target))?.[1];
|
|
184
|
+
const a = e.arguments[0];
|
|
185
|
+
return `${t.expr(target)}.emit(${a ? (value && value !== 'Void' && value !== 'Unit' ? t.coerce(a, value) : t.expr(a)) : ''})`;
|
|
186
|
+
}
|
|
187
|
+
if (owner === 'Injector' && method === 'get' && e.arguments[0]) {
|
|
188
|
+
const rawArg0 = forwardRefTarget(e.arguments[0]);
|
|
189
|
+
if (tokenName(t, ts.isExpressionWithTypeArguments(rawArg0) ? rawArg0.expression : rawArg0) === 'ViewContainerRef')
|
|
190
|
+
throw t.error(e, 'an injected ViewContainerRef', 'view-container-ref');
|
|
191
|
+
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?')}` : ''})`;
|
|
192
|
+
const type = t.typeOf(e);
|
|
193
|
+
return type === 'Any?' ? raw : t.fromAny(raw, type);
|
|
194
|
+
}
|
|
195
|
+
// `http.get<T>(url, options)` / `http.post<T>(url, body, options)`: the parsed body read as T.
|
|
196
|
+
if (owner === 'HttpClient' && ['get', 'delete', 'head', 'options', 'post', 'put', 'patch', 'request'].includes(method) && t.typeOf(e).startsWith('RxObservable<')) {
|
|
197
|
+
const value = /^RxObservable<(.*)>$/.exec(t.typeOf(e))?.[1] ?? 'Any?';
|
|
198
|
+
const call = method === 'request'
|
|
199
|
+
? `${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?')}` : ''})`
|
|
200
|
+
: ['post', 'put', 'patch'].includes(method)
|
|
201
|
+
? `${t.expr(target)}.${method}(${t.str(e.arguments[0])}${e.arguments[1] ? `, ${t.coerce(e.arguments[1], 'Any?')}` : ', null'}${e.arguments[2] ? `, ${t.coerce(e.arguments[2], 'Any?')}` : ''})`
|
|
202
|
+
: `${t.expr(target)}.${method}(${t.str(e.arguments[0])}${e.arguments[1] ? `, ${t.coerce(e.arguments[1], 'Any?')}` : ''})`;
|
|
203
|
+
return value === 'Any?' ? call : `${call}.mapValues { __v: Any? -> ${t.fromAny('__v', value)} }`;
|
|
204
|
+
}
|
|
205
|
+
return undefined;
|
|
206
|
+
}
|
|
207
|
+
export const kotlinHooks = {
|
|
208
|
+
...model,
|
|
209
|
+
typeMap: {
|
|
210
|
+
OutputEmitterRef: 'Emitter<$0>',
|
|
211
|
+
EventEmitter: 'Emitter<$0>',
|
|
212
|
+
RouterExtensions: 'Router',
|
|
213
|
+
EnvironmentInjector: { type: 'Injector', shim: true },
|
|
214
|
+
// kit-android's NativeDialogService takes its config as script gives it.
|
|
215
|
+
NativeDialogConfig: { type: 'Any?', shim: true },
|
|
216
|
+
...Object.fromEntries(['NativeDialogRef', 'NativeDialogService', 'DestroyRef', 'Injector', 'InjectionToken', 'ErrorHandler', 'NgZone', 'HttpClient', 'ChangeDetectorRef', 'PurePipeCache', 'NodeInjector', 'ElementRef', 'SimpleChange',
|
|
217
|
+
'TeardownHandle', 'NavigationEnd', 'NavigationStart', 'NavigationCancel', 'NavigationError', 'RoutesRecognized', 'ResolveStart', 'ResolveEnd',
|
|
218
|
+
'HttpParams', 'HttpHeaders', 'HttpResponse', 'HttpErrorResponse', 'HttpRequest', 'HttpContext', 'HttpContextToken',
|
|
219
|
+
'ParamMap', 'UrlSegment', 'UrlTree', 'DefaultUrlSerializer', 'ActivatedRouteSnapshot',
|
|
220
|
+
'ViewContainerRef', 'TemplateRef', 'ComponentRef', 'EmbeddedViewRef', 'ApplicationRef', 'Location'].map((n) => [n, { type: n, shim: true }])),
|
|
221
|
+
},
|
|
222
|
+
globalCall,
|
|
223
|
+
methodCall,
|
|
224
|
+
// `deps: [new Inject(TOKEN)]` names the token itself.
|
|
225
|
+
newCall: (t, name, e) => (name === 'Inject' && e.arguments?.[0] && t.resolve(ts.skipParentheses(e.expression))?.declarations?.[0]?.getSourceFile().fileName.startsWith('/__shims__/') ? t.coerce(e.arguments[0], 'Any?') : undefined),
|
|
226
|
+
constructorParameter: parameterInject,
|
|
227
|
+
componentField(t, m, name) {
|
|
228
|
+
const callee = m.initializer ? t.calleeName(m.initializer) : '';
|
|
229
|
+
if (callee === 'input' || callee === 'input.required' || callee === 'model' || callee === 'model.required') {
|
|
230
|
+
const type = t.typeOf(m.name).replace(/^Signal<(.*)>$/, '$1');
|
|
231
|
+
const given = m.initializer.arguments[0];
|
|
232
|
+
return { prop: { type, default: given ? (type.startsWith('JSNullish<') ? t.stored(given, given, type) : t.coerce(given, type)) : callee === 'input' || callee === 'model' ? (type.startsWith('JSNullish<') ? 'JSNullish.Undefined' : 'null') : undefined } };
|
|
233
|
+
}
|
|
234
|
+
if (callee !== 'toSignal')
|
|
235
|
+
return undefined;
|
|
236
|
+
// A signal of the source's latest value, read as a computed is: by its name.
|
|
237
|
+
const ident = core.kotlin.ident;
|
|
238
|
+
const [source, options] = m.initializer.arguments;
|
|
239
|
+
const type = t.typeOf(m.name);
|
|
240
|
+
const initial = options && ts.isObjectLiteralExpression(options) ? options.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'initialValue') : undefined;
|
|
241
|
+
// rxjs compiled from source: the program's `toSignal`, a signal of any value, its value read as the field types it.
|
|
242
|
+
const program = t.resolve(m.initializer.expression)?.declarations?.some((d) => !d.getSourceFile().isDeclarationFile);
|
|
243
|
+
if (program)
|
|
244
|
+
return { lines: [` private val __${name}: Signal<Any?> = ${t.fromAny(t.expr(m.initializer), 'Signal<Any?>')}`, ` val ${ident(name)}: ${type}`, ` get() = ${t.fromAny(`__${name}.value`, type)}`] };
|
|
245
|
+
if (!initial)
|
|
246
|
+
throw t.error(m, 'toSignal without an initialValue');
|
|
247
|
+
return { lines: [` private val __${name}: Signal<${type}> = toSignal(${t.expr(source)}, ${t.coerce(initial.initializer, type)})`, ` val ${ident(name)}: ${type}`, ` get() = __${name}.value`] };
|
|
248
|
+
},
|
|
249
|
+
componentStatics(t, cls) {
|
|
250
|
+
const ngImports = standaloneImports(cls, t.checker, t.compiles);
|
|
251
|
+
return ngImports ? [` val jsNgImports: Any? by lazy { jsArrayOf<Any?>(${ngImports.map((e) => t.coerce(e, 'Any?')).join(', ')}) }`] : [];
|
|
252
|
+
},
|
|
253
|
+
componentAsValue: (t, cls, type) => `ComponentFactory { ${t.rootView(cls, type, `${type}().render()`)} }`,
|
|
254
|
+
/** A component created as a root view (bootstrap, route, dialog): made and rendered in its standalone injector. */
|
|
255
|
+
wrapRootView: (t, cls, type, make) => (standaloneImports(cls, t.checker, t.compiles) ? `Injector.standalone(${type}::class.java, ${type}.jsNgImports) { ${make} }` : make),
|
|
256
|
+
serviceClass(t, cls, name) {
|
|
257
|
+
const { params, lines, statics } = t.componentMembers(cls, [], true);
|
|
258
|
+
return [`class ${name}(${params.join(', ')}) {`, ...lines, '', ' companion object {', ` val shared: ${name} get() = AppInjector.service(${name}::class.java) { ${name}() }`, ...statics, ' }', '}'].join('\n');
|
|
259
|
+
},
|
|
260
|
+
classExtras(t, cls, name) {
|
|
261
|
+
const ident = core.kotlin.ident;
|
|
262
|
+
const members = [];
|
|
263
|
+
const role = injectableRole(cls, t.pluginFiles);
|
|
264
|
+
if (role === 'based' || role === 'root') {
|
|
265
|
+
const ctor = cls.members.find((m) => ts.isConstructorDeclaration(m) && !!m.body);
|
|
266
|
+
const made = `${ident(name)}(${(ctor?.parameters ?? []).map((p) => t.constructorParameter(p)).join(', ')})`;
|
|
267
|
+
members.push(` val ${injectableShared(cls, t.pluginFiles, t.checker)}: ${ident(name)} get() = AppInjector.service(${ident(name)}::class.java) { ${made} }`);
|
|
268
|
+
// The kit makes a class of a no-argument constructor itself; one whose constructor injects needs this.
|
|
269
|
+
if (ctor?.parameters.length)
|
|
270
|
+
members.push(` fun jsConstruct(): Any? = ${made}`);
|
|
271
|
+
}
|
|
272
|
+
// What the injector reads of an NgModule: its metadata, evaluated once as the decorator is, and how it is made.
|
|
273
|
+
const ngModule = ngModuleDef(cls, t.checker, t.compiles);
|
|
274
|
+
if (ngModule) {
|
|
275
|
+
const ctor = cls.members.find((m) => ts.isConstructorDeclaration(m) && !!m.body);
|
|
276
|
+
members.push(` override val jsNgImports: Any? by lazy { jsArrayOf<Any?>(${ngModule.imports.map((e) => t.coerce(e, 'Any?')).join(', ')}) }`, ` override val jsNgProviders: Any? by lazy { ${ngModule.providers ? t.coerce(ngModule.providers, 'Any?') : 'null'} }`, ` override fun jsNgConstruct(): Any? = ${ident(name)}(${(ctor?.parameters ?? []).map((p) => t.constructorParameter(p)).join(', ')})`);
|
|
277
|
+
}
|
|
278
|
+
return { members, companionSupertype: ngModule ? 'JSNgModuleDef' : undefined };
|
|
279
|
+
},
|
|
280
|
+
};
|