@unframework.dev/target-angular 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,57 @@
1
+ /** A rolldown plugin for `optimizeDeps.rolldownOptions.plugins` that AOT-links dependencies. */
2
+ function angularLinker(tools) {
3
+ let transformer;
4
+ return {
5
+ name: "unframework:angular-linker",
6
+ load: {
7
+ filter: { id: {
8
+ include: /\.[cm]?js$/,
9
+ exclude: /^\0/
10
+ } },
11
+ async handler(id) {
12
+ transformer ??= tools.createTransformer();
13
+ const contents = await transformer.transformFile(id);
14
+ return {
15
+ code: new TextDecoder().decode(contents),
16
+ moduleType: "js"
17
+ };
18
+ }
19
+ },
20
+ async buildEnd() {
21
+ const finished = transformer;
22
+ transformer = void 0;
23
+ await finished?.close();
24
+ }
25
+ };
26
+ }
27
+ /** Angular's published packages, wherever a package manager puts them. */
28
+ const ANGULAR_PACKAGE = /[\\/]node_modules[\\/]@angular[\\/][^?]+\.[cm]?js(?:\?|$)/;
29
+ /**
30
+ * A Vite plugin that AOT-links Angular's packages in the SSR module graph, as a production
31
+ * server build does, so a server render never needs the JIT compiler, whatever the order in
32
+ * which the component and the renderer load. The SSR configuration inlines the packages
33
+ * (`ssr.noExternal`) so that they reach it.
34
+ */
35
+ function angularSsrLinker(tools) {
36
+ let transformer;
37
+ return {
38
+ name: "unframework:angular-ssr-linker",
39
+ transform: {
40
+ filter: { id: ANGULAR_PACKAGE },
41
+ async handler(code, id) {
42
+ transformer ??= tools.createTransformer();
43
+ const linked = await transformer.transformData(id.split("?")[0], code);
44
+ return {
45
+ code: new TextDecoder().decode(linked),
46
+ map: { mappings: "" }
47
+ };
48
+ }
49
+ },
50
+ async buildEnd() {
51
+ const finished = transformer;
52
+ transformer = void 0;
53
+ await finished?.close();
54
+ }
55
+ };
56
+ }
57
+ export { angularLinker, angularSsrLinker };
@@ -0,0 +1,238 @@
1
+ import { dirname, extname, resolve } from "node:path";
2
+ import { availableParallelism } from "node:os";
3
+ import { Worker } from "node:worker_threads";
4
+ /**
5
+ * The Angular id scheme of the unframework plugin, not on disk: `<abs>/X.uf.tsx.ts` for a file's
6
+ * main component, `<abs>/X.uf.tsx.<output file>` for any other (`Card.uf.tsx.card-icon.ts`,
7
+ * ADR-0053), and `<abs>/X.uf.ts.ts` for a module of composables, which a component's program
8
+ * reads to check its template against the composable's types (ADR-0069).
9
+ */
10
+ const VIRTUAL_ID = /\.uf\.tsx?(?:\.[^/?]+)?\.ts$/;
11
+ /**
12
+ * A relative import or re-export in generated code, of a child's output (`./field`, ADR-0053)
13
+ * or of a file on disk: `import … from "./x"`, `export … from "./x"` or `import "./x"`. Its
14
+ * specifier is the first group.
15
+ */
16
+ const RELATIVE_IMPORT = /^\s*(?:(?:import|export)\b[^"';]*?\bfrom\s*|import\s*)["'](\.\.?\/[^"']+)["']/gm;
17
+ /**
18
+ * A component's scoped sheet in generated code, `styleUrl: "./Card.uf.tsx.css"` (ADR-0063): its
19
+ * specifier is the first group.
20
+ */
21
+ const STYLE_URL = /\bstyleUrl:\s*["'](\.\/[^"']+\.uf\.tsx\.css)["']/g;
22
+ /** An import of another component in generated code: `./Child.uf.tsx`. */
23
+ const COMPONENT_IMPORT = /^\.\.?\/.*\.uf\.tsx$/;
24
+ /**
25
+ * Compiles `<abs>/X.uf.tsx.ts` and `<abs>/X.uf.ts.ts` ids with Angular's AOT compiler under the
26
+ * strict options L3 checks with, failing the module on any error (template type errors included)
27
+ * and passing warnings to Vite. Compiles run in a pool of workers (`compilePool`), as many at once
28
+ * as it has workers, and each worker's compiles for a plugin reuse its previous program, so each
29
+ * worker analyses the libraries once. `declarations` are the ambient declarations each program
30
+ * reads beside the module (`ToolchainContext.declarations`).
31
+ */
32
+ function ngtscVirtual(compiler, declarations = []) {
33
+ const pluginId = nextPlugin++;
34
+ let api;
35
+ /** The virtual module each relative import of a virtual module resolved to, by importer. */
36
+ const children = /* @__PURE__ */ new Map();
37
+ function compile(id, code) {
38
+ const sources = /* @__PURE__ */ new Map([[id, code]]);
39
+ const sheets = /* @__PURE__ */ new Map();
40
+ const resolved = /* @__PURE__ */ new Map();
41
+ for (const [file, text] of sources) {
42
+ for (const [, specifier = ""] of text.matchAll(STYLE_URL)) {
43
+ const path = resolve(dirname(file), specifier);
44
+ const sheet = api.getSheet(path.slice(0, -4));
45
+ if (sheet !== void 0) sheets.set(path, sheet);
46
+ }
47
+ for (const [, specifier = ""] of text.matchAll(RELATIVE_IMPORT)) {
48
+ const key = childKey(file, specifier);
49
+ const child = COMPONENT_IMPORT.test(specifier) ? `${resolve(dirname(file), specifier)}.ts` : children.get(key);
50
+ if (!child) continue;
51
+ if (!COMPONENT_IMPORT.test(specifier)) resolved.set(key, child);
52
+ const source = sources.has(child) ? void 0 : api.getCompiled(child);
53
+ if (source !== void 0) sources.set(child, source);
54
+ }
55
+ }
56
+ return compilePoolOf(compiler).compile({
57
+ plugin: pluginId,
58
+ id,
59
+ sources: [...sources, ...sheets],
60
+ children: [...resolved],
61
+ declarations: [...declarations]
62
+ });
63
+ }
64
+ const result = {
65
+ name: "unframework:angular-ngtsc",
66
+ enforce: "pre",
67
+ configResolved(config) {
68
+ const candidate = config.plugins.find((candidate) => candidate.name === "unframework")?.api;
69
+ if (typeof candidate?.getCompiled !== "function" || typeof candidate.getSheet !== "function") throw new Error("The Angular toolchain compiles the unframework plugin's output, but this Vite config has no plugin named \"unframework\" exposing api.getCompiled(id) and api.getSheet(file). Add @unframework.dev/unplugin/vite before the Angular toolchain's plugins.");
70
+ api = candidate;
71
+ },
72
+ transform: {
73
+ filter: { id: /\.uf\.tsx?(?:\.[^/?]+)?\.ts(?:\?|$)/ },
74
+ async handler(code, rawId) {
75
+ const id = rawId.split("?")[0];
76
+ const client = this.environment.mode === "dev" && this.environment.config.consumer === "client";
77
+ for (const [, fileName = ""] of code.matchAll(RELATIVE_IMPORT)) {
78
+ if (COMPONENT_IMPORT.test(fileName)) continue;
79
+ const resolved = await this.resolve(fileName, id);
80
+ const child = resolved?.id.split("?")[0];
81
+ if (!resolved || !child || !VIRTUAL_ID.test(child)) continue;
82
+ children.set(childKey(id, fileName), child);
83
+ if (api.getCompiled(child) !== void 0) continue;
84
+ try {
85
+ await this.load({ id: resolved.id });
86
+ } catch (error) {
87
+ const message = `${id} imports ${fileName}, which failed to load:\n${error instanceof Error ? error.message : String(error)}`;
88
+ if (!client) this.error(message);
89
+ this.environment.logger.error(message);
90
+ return {
91
+ code: failingModule(message, exportedNames(code)),
92
+ map: null
93
+ };
94
+ }
95
+ }
96
+ const compiled = await compile(id, code);
97
+ if (compiled.warnings) this.warn(compiled.warnings);
98
+ if (compiled.codes.length) {
99
+ const message = `ngtsc rejected ${id} (${compiled.codes.join(", ")}):\n${compiled.errors}`;
100
+ if (client) {
101
+ this.environment.logger.error(message);
102
+ return {
103
+ code: failingModule(message, compiled.exports),
104
+ map: null
105
+ };
106
+ }
107
+ this.error(message);
108
+ }
109
+ if (compiled.code === void 0) this.error(`ngtsc emitted no JavaScript for ${id}`);
110
+ return {
111
+ code: compiled.code,
112
+ map: compiled.map ?? null
113
+ };
114
+ }
115
+ }
116
+ };
117
+ released.register(result, () => pools.get(compiler)?.release(pluginId));
118
+ return result;
119
+ }
120
+ /**
121
+ * The URL of the compile worker beside the module at `moduleUrl`, with the module's own
122
+ * extension: the source worker from `src`, and the built one from `dist`.
123
+ */
124
+ function workerUrl(moduleUrl) {
125
+ return new URL(`./ngtsc-worker${extname(new URL(moduleUrl).pathname)}`, moduleUrl);
126
+ }
127
+ /**
128
+ * How many workers a pool may start: one, or two on a machine with four cores or more. Vitest's
129
+ * own workers render and test while ngtsc compiles, and each compile worker holds about 400 MB,
130
+ * a TypeScript program with Angular's declarations for each plugin. On the ssr run, three or
131
+ * four workers took the peak memory past 1.5 times that of a single worker, and saved no time
132
+ * that a loaded machine's measurements could tell apart from two's (ADR-0093).
133
+ */
134
+ function poolSize(parallelism = availableParallelism()) {
135
+ return Math.min(2, Math.max(1, Math.floor(parallelism / 2)));
136
+ }
137
+ /**
138
+ * A pool of at most `size` threads, each started by `start` only when every thread alive is
139
+ * busy. A compile goes to an idle thread, the one started first, so a light load keeps reusing
140
+ * one program, or else to a new thread, or else to the thread with the fewest compiles waiting.
141
+ * Each thread compiles one request at a time, in the order it gets them. A thread holds the
142
+ * process open only while a compile waits on it. A thread that dies fails only the compiles it
143
+ * holds, or exits, and the next compile starts another in its place.
144
+ */
145
+ function compilePool(start, size) {
146
+ if (!Number.isInteger(size) || size < 1) throw new Error(`A compile pool needs at least one thread, not ${size}.`);
147
+ const slots = [];
148
+ let nextRequest = 0;
149
+ function open() {
150
+ const thread = start();
151
+ thread.unref();
152
+ const slot = {
153
+ thread,
154
+ pending: /* @__PURE__ */ new Map()
155
+ };
156
+ thread.on("message", (reply) => {
157
+ const waiting = slot.pending.get(reply.request);
158
+ if (!waiting) return;
159
+ slot.pending.delete(reply.request);
160
+ if (!slot.pending.size) thread.unref();
161
+ if ("failure" in reply) waiting.reject(reply.failure);
162
+ else waiting.resolve(reply.compiled);
163
+ });
164
+ const end = (error) => {
165
+ const index = slots.indexOf(slot);
166
+ if (index !== -1) slots.splice(index, 1);
167
+ for (const waiting of slot.pending.values()) waiting.reject(error);
168
+ slot.pending.clear();
169
+ };
170
+ thread.on("error", end);
171
+ thread.on("exit", (code) => end(/* @__PURE__ */ new Error(`An ngtsc worker exited with code ${code}.`)));
172
+ slots.push(slot);
173
+ return slot;
174
+ }
175
+ function pick() {
176
+ const idle = slots.find((slot) => !slot.pending.size);
177
+ if (idle) return idle;
178
+ if (slots.length < size) return open();
179
+ return slots.reduce((least, slot) => slot.pending.size < least.pending.size ? slot : least);
180
+ }
181
+ return {
182
+ compile(request) {
183
+ const slot = pick();
184
+ const number = nextRequest++;
185
+ if (!slot.pending.size) slot.thread.ref();
186
+ return new Promise((fulfil, reject) => {
187
+ slot.pending.set(number, {
188
+ resolve: fulfil,
189
+ reject
190
+ });
191
+ slot.thread.postMessage({
192
+ ...request,
193
+ request: number
194
+ });
195
+ });
196
+ },
197
+ release(plugin) {
198
+ for (const { thread } of slots) thread.postMessage({ release: plugin });
199
+ },
200
+ get threads() {
201
+ return slots.length;
202
+ }
203
+ };
204
+ }
205
+ let nextPlugin = 0;
206
+ const pools = /* @__PURE__ */ new WeakMap();
207
+ const released = new FinalizationRegistry((release) => release());
208
+ /**
209
+ * The pool of `compiler`, made on its first compile. One per compiler and so per process: each
210
+ * of its workers loads the compiler and parses the library declarations once, for every plugin.
211
+ */
212
+ function compilePoolOf(compiler) {
213
+ const existing = pools.get(compiler);
214
+ if (existing) return existing;
215
+ const toolchainDir = dirname(dirname(compiler.angularScope));
216
+ const pool = compilePool(() => new Worker(workerUrl(import.meta.url), { workerData: { toolchainDir } }), poolSize());
217
+ pools.set(compiler, pool);
218
+ return pool;
219
+ }
220
+ /** The values a module's code exports by name, for a module that stands in for it. */
221
+ function exportedNames(code) {
222
+ return [...code.matchAll(/^export\s+(?:default\s+)?(?:class|const|function)\s+(\w+)/gm)].filter(([whole]) => !/^export\s+default\b/.test(whole)).map(([, name]) => name);
223
+ }
224
+ /** The key of an import in `children`: the importing file and the specifier. */
225
+ function childKey(importer, specifier) {
226
+ return `${importer}\0${specifier}`;
227
+ }
228
+ /**
229
+ * A module that throws `message` when it runs and still provides every export of the module it
230
+ * stands in for, so its importers link and the message is what they see.
231
+ */
232
+ function failingModule(message, exports) {
233
+ const lines = [`throw new Error(${JSON.stringify(message)});`, "export default undefined;"];
234
+ const named = exports.filter((name) => name !== "default");
235
+ if (named.length) lines.push("const failed = undefined;", `export { ${named.map((name) => `failed as ${JSON.stringify(name)}`).join(", ")} };`);
236
+ return `${lines.join("\n")}\n`;
237
+ }
238
+ export { COMPONENT_IMPORT, childKey, compilePool, ngtscVirtual, poolSize, workerUrl };
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,104 @@
1
+ import { createHost, diagnosticCode, formatDiagnostics, strictOptions } from "./ngtsc.js";
2
+ import { loadCompiler } from "./tools.js";
3
+ import { COMPONENT_IMPORT, childKey } from "./ngtsc-virtual.js";
4
+ import { dirname, resolve } from "node:path";
5
+ import { parentPort, workerData } from "node:worker_threads";
6
+ const { toolchainDir } = workerData;
7
+ /** The compiler, and the strict options L3 checks with, set to emit. */
8
+ const loaded = loadCompiler(toolchainDir).then((compiler) => {
9
+ return {
10
+ compiler,
11
+ options: {
12
+ ...strictOptions(compiler),
13
+ noEmit: false,
14
+ declaration: false,
15
+ sourceMap: true,
16
+ inlineSources: true,
17
+ supportTestBed: false,
18
+ supportJitMode: false
19
+ }
20
+ };
21
+ });
22
+ /** Each plugin's previous program in this worker, which its next compile here reuses. */
23
+ const previous = /* @__PURE__ */ new Map();
24
+ let queue = Promise.resolve();
25
+ parentPort.on("message", (message) => {
26
+ queue = queue.then(async () => {
27
+ if ("release" in message) {
28
+ previous.delete(message.release);
29
+ return;
30
+ }
31
+ let reply;
32
+ try {
33
+ const { compiler, options } = await loaded;
34
+ reply = {
35
+ request: message.request,
36
+ compiled: await compile(compiler, options, message)
37
+ };
38
+ } catch (failure) {
39
+ reply = {
40
+ request: message.request,
41
+ failure
42
+ };
43
+ }
44
+ parentPort.postMessage(reply);
45
+ });
46
+ });
47
+ async function compile(compiler, options, { plugin, id, sources, children, declarations }) {
48
+ const { ts } = compiler;
49
+ const inMemory = new Map(sources);
50
+ const resolved = new Map(children);
51
+ const host = createHost(compiler, options, (fileName) => inMemory.get(fileName));
52
+ const resolveOne = (name, containingFile, settings, redirect) => {
53
+ const child = COMPONENT_IMPORT.test(name) ? `${resolve(dirname(containingFile), name)}.ts` : resolved.get(childKey(containingFile, name));
54
+ return child ? { resolvedModule: {
55
+ resolvedFileName: child,
56
+ extension: ts.Extension.Ts,
57
+ isExternalLibraryImport: false
58
+ } } : ts.resolveModuleName(name, containingFile, settings, host, void 0, redirect);
59
+ };
60
+ host.resolveModuleNameLiterals = (literals, containingFile, redirect, settings) => literals.map(({ text }) => resolveOne(text, containingFile, settings, redirect));
61
+ host.resolveModuleNames = (names, containingFile, _reused, redirect, settings) => names.map((name) => resolveOne(name, containingFile, settings, redirect).resolvedModule);
62
+ const program = new compiler.cli.NgtscProgram([id, ...declarations], options, host, previous.get(plugin));
63
+ previous.set(plugin, program);
64
+ const tsProgram = program.getTsProgram();
65
+ const sourceFile = tsProgram.getSourceFile(id);
66
+ const isError = (diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error;
67
+ const diagnostics = [
68
+ ...program.getTsOptionDiagnostics(),
69
+ ...program.getNgOptionDiagnostics(),
70
+ ...program.getTsSyntacticDiagnostics()
71
+ ];
72
+ let code;
73
+ let map;
74
+ if (!diagnostics.some(isError)) {
75
+ await program.compiler.analyzeAsync();
76
+ diagnostics.push(...program.getTsSemanticDiagnostics(sourceFile), ...program.getNgStructuralDiagnostics(), ...program.getNgSemanticDiagnostics(id));
77
+ }
78
+ if (!diagnostics.some(isError)) {
79
+ const { transformers } = program.compiler.prepareEmit();
80
+ const emitted = tsProgram.emit(sourceFile, (fileName, text) => {
81
+ if (fileName.endsWith(".map")) map = text;
82
+ else if (/\.[cm]?js$/.test(fileName)) code = text;
83
+ }, void 0, false, transformers);
84
+ diagnostics.push(...emitted.diagnostics);
85
+ code = code?.replace(/\n\/\/# sourceMappingURL=\S+\s*$/, "\n");
86
+ }
87
+ const errors = diagnostics.filter(isError);
88
+ const warnings = diagnostics.filter((diagnostic) => !isError(diagnostic));
89
+ let exports = [];
90
+ if (errors.length && sourceFile) {
91
+ const checker = tsProgram.getTypeChecker();
92
+ const symbol = checker.getSymbolAtLocation(sourceFile);
93
+ exports = symbol ? checker.getExportsOfModule(symbol).map(({ name }) => name) : [];
94
+ }
95
+ return {
96
+ ...code === void 0 ? {} : { code },
97
+ ...map === void 0 ? {} : { map },
98
+ errors: formatDiagnostics(compiler, errors),
99
+ codes: [...new Set(errors.map(diagnosticCode))],
100
+ warnings: formatDiagnostics(compiler, warnings),
101
+ exports
102
+ };
103
+ }
104
+ export {};
@@ -0,0 +1,187 @@
1
+ import { dirname, join, relative, resolve } from "node:path";
2
+ /**
3
+ * The options `ng new` generates (strict TypeScript, strict templates, host binding checks),
4
+ * plus the type-checking flags it leaves out that the other targets' checkers set
5
+ * (`noUncheckedIndexedAccess`, `verbatimModuleSyntax`: tests/toolchains/angular/tsconfig.json),
6
+ * with `@angular/*` resolved from the toolchain so output anywhere on disk, or only in memory,
7
+ * compiles without an Angular dependency of its own. Extended template diagnostics stay
8
+ * warnings, so L3 can hold output to zero of each.
9
+ */
10
+ function strictOptions(compiler) {
11
+ const { ts } = compiler;
12
+ return {
13
+ target: ts.ScriptTarget.ES2022,
14
+ module: ts.ModuleKind.Preserve,
15
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
16
+ lib: [
17
+ "lib.es2024.d.ts",
18
+ "lib.dom.d.ts",
19
+ "lib.dom.iterable.d.ts"
20
+ ],
21
+ strict: true,
22
+ noUncheckedIndexedAccess: true,
23
+ noImplicitOverride: true,
24
+ noPropertyAccessFromIndexSignature: true,
25
+ noImplicitReturns: true,
26
+ noFallthroughCasesInSwitch: true,
27
+ isolatedModules: true,
28
+ verbatimModuleSyntax: true,
29
+ skipLibCheck: true,
30
+ noEmit: true,
31
+ types: [],
32
+ paths: { "@angular/*": [join(compiler.angularScope, "*")] },
33
+ strictTemplates: true,
34
+ strictInjectionParameters: true,
35
+ strictInputAccessModifiers: true,
36
+ strictStandalone: true,
37
+ typeCheckHostBindings: true,
38
+ extendedDiagnostics: { defaultCategory: "warning" }
39
+ };
40
+ }
41
+ const DECLARATION = /\.d\.[cm]?ts$/;
42
+ /**
43
+ * A compiler host that serves `contents(fileName)` from memory and everything else from disk.
44
+ * The directories of in-memory files exist for it: TypeScript resolves the template type-check
45
+ * shims next to their component, and in a directory it believes missing, ngtsc silently skips
46
+ * template type-checking. Declaration files under node_modules (TypeScript's libs, Angular's
47
+ * typings) are parsed once per process and shared by every program: parsing them is most of a
48
+ * cold compile.
49
+ */
50
+ function createHost(compiler, options, contents) {
51
+ const { ts, declarations } = compiler;
52
+ const host = ts.createCompilerHost(options, true);
53
+ const fileExists = host.fileExists.bind(host);
54
+ const readFile = host.readFile.bind(host);
55
+ const directoryExists = host.directoryExists.bind(host);
56
+ const getSourceFile = host.getSourceFile.bind(host);
57
+ const directories = /* @__PURE__ */ new Set();
58
+ const inMemory = (fileName) => {
59
+ const text = contents(fileName);
60
+ let directory = dirname(resolve(fileName));
61
+ while (text !== void 0 && !directories.has(directory)) {
62
+ directories.add(directory);
63
+ if (dirname(directory) === directory) break;
64
+ directory = dirname(directory);
65
+ }
66
+ return text;
67
+ };
68
+ host.fileExists = (fileName) => inMemory(fileName) !== void 0 || fileExists(fileName);
69
+ host.readFile = (fileName) => inMemory(fileName) ?? readFile(fileName);
70
+ host.directoryExists = (directory) => directories.has(resolve(directory)) || directoryExists(directory);
71
+ host.getSourceFile = (fileName, languageVersion, onError, shouldCreateNewSourceFile) => {
72
+ const text = inMemory(fileName);
73
+ if (text !== void 0) return ts.createSourceFile(fileName, text, languageVersion, true);
74
+ if (!fileName.includes("/node_modules/") || !DECLARATION.test(fileName)) return getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
75
+ const key = `${fileName}|${JSON.stringify(languageVersion)}`;
76
+ const cached = shouldCreateNewSourceFile ? void 0 : declarations.get(key);
77
+ if (cached) return cached;
78
+ const parsed = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
79
+ if (parsed) declarations.set(key, parsed);
80
+ return parsed;
81
+ };
82
+ return host;
83
+ }
84
+ /**
85
+ * Every diagnostic of a check over `rootNames`, collected as ngc does: options and syntax
86
+ * first, then (only for a program that parses) TypeScript semantics, Angular structure
87
+ * (decorators, metadata) and Angular semantics (template parsing and type-checking, extended
88
+ * template diagnostics). ngc skips the later phases for the whole program when any file fails
89
+ * to parse, which would make every other file look clean, so the parsable files are checked
90
+ * again on their own.
91
+ */
92
+ function collectDiagnostics(compiler, rootNames, createProgram) {
93
+ const program = createProgram(rootNames);
94
+ const isError = (diagnostic) => diagnostic.category === compiler.ts.DiagnosticCategory.Error;
95
+ const early = [
96
+ ...program.getTsOptionDiagnostics(),
97
+ ...program.getNgOptionDiagnostics(),
98
+ ...program.getTsSyntacticDiagnostics()
99
+ ];
100
+ if (!early.some(isError)) return [
101
+ ...early,
102
+ ...program.getTsSemanticDiagnostics(),
103
+ ...program.getNgStructuralDiagnostics(),
104
+ ...program.getNgSemanticDiagnostics()
105
+ ];
106
+ const unparsable = new Set(early.flatMap((diagnostic) => isError(diagnostic) && diagnostic.file ? [resolve(diagnostic.file.fileName)] : []));
107
+ const parsable = rootNames.filter((fileName) => !unparsable.has(resolve(fileName)));
108
+ if (early.some((diagnostic) => isError(diagnostic) && !diagnostic.file) || parsable.length === 0 || parsable.length === rootNames.length) return early;
109
+ return [...early.filter((diagnostic) => diagnostic.file && unparsable.has(resolve(diagnostic.file.fileName))), ...collectDiagnostics(compiler, parsable, createProgram)];
110
+ }
111
+ /**
112
+ * Groups diagnostics by input file, errors apart from warnings. A diagnostic outside
113
+ * the inputs (options, a library, an imported file) is reported on every file, with its own
114
+ * location in the message: nothing is dropped.
115
+ */
116
+ function groupByFile(compiler, fileNames, diagnostics) {
117
+ const byPath = new Map(fileNames.map((fileName) => [resolve(fileName), fileName]));
118
+ const results = new Map(fileNames.map((fileName) => [fileName, {
119
+ errors: [],
120
+ warnings: []
121
+ }]));
122
+ const global = {
123
+ errors: [],
124
+ warnings: []
125
+ };
126
+ for (const diagnostic of diagnostics) {
127
+ const input = diagnostic.file && byPath.get(resolve(diagnostic.file.fileName));
128
+ const result = input ? results.get(input) : global;
129
+ const message = toMessage(compiler, diagnostic, input === void 0);
130
+ if (diagnostic.category === compiler.ts.DiagnosticCategory.Error) result.errors.push(message);
131
+ else result.warnings.push(message);
132
+ }
133
+ for (const result of results.values()) {
134
+ result.errors.unshift(...global.errors);
135
+ result.warnings.unshift(...global.warnings);
136
+ }
137
+ return results;
138
+ }
139
+ /** The code ngc prints: Angular's diagnostics are `-99xxxx` internally and `NGxxxx` outside. */
140
+ function diagnosticCode(diagnostic) {
141
+ const code = String(diagnostic.code);
142
+ return code.startsWith("-99") ? `NG${code.slice(3)}` : `TS${code}`;
143
+ }
144
+ /**
145
+ * A diagnostic as a toolchain message, with a 1-based line and column. `located` puts the
146
+ * file and position in the message instead, for a diagnostic reported on another file.
147
+ */
148
+ function toMessage(compiler, diagnostic, located = false) {
149
+ const text = compiler.ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
150
+ const code = diagnosticCode(diagnostic);
151
+ const position = positionOf(diagnostic);
152
+ if (located && diagnostic.file) return {
153
+ message: `${locationOf(diagnostic)}: ${text}`,
154
+ code
155
+ };
156
+ return position ? {
157
+ message: text,
158
+ ...position,
159
+ code
160
+ } : {
161
+ message: text,
162
+ code
163
+ };
164
+ }
165
+ /** Diagnostics as ngc prints them, one per line: `file(line,column): error NG8002: …`. */
166
+ function formatDiagnostics(compiler, diagnostics) {
167
+ return diagnostics.map((diagnostic) => {
168
+ const text = compiler.ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
169
+ const severity = diagnostic.category === compiler.ts.DiagnosticCategory.Error ? "error" : "warning";
170
+ return `${diagnostic.file ? `${locationOf(diagnostic)}: ` : ""}${severity} ${diagnosticCode(diagnostic)}: ${text}`;
171
+ }).join("\n");
172
+ }
173
+ function positionOf(diagnostic) {
174
+ if (!diagnostic.file || diagnostic.start === void 0) return void 0;
175
+ const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
176
+ return {
177
+ line: line + 1,
178
+ column: character + 1
179
+ };
180
+ }
181
+ /** `path(line,column)`, relative to the working directory, as ngc prints it. */
182
+ function locationOf(diagnostic) {
183
+ const path = relative(process.cwd(), diagnostic.file.fileName);
184
+ const position = positionOf(diagnostic);
185
+ return position ? `${path}(${position.line},${position.column})` : path;
186
+ }
187
+ export { collectDiagnostics, createHost, diagnosticCode, formatDiagnostics, groupByFile, strictOptions, toMessage };
@@ -0,0 +1,8 @@
1
+ import { SsrRenderer } from "@unframework.dev/codegen";
2
+ /**
3
+ * Renders a component on Angular's server platform and returns the content of `<body>`: the
4
+ * component's host element (`<uf-x style="display: contents;">`) and its content. Inputs are
5
+ * set before the first change detection; `createComponent` adds neither `ng-version` nor
6
+ * `ng-server-context`, which `bootstrapApplication` would.
7
+ */
8
+ export declare const renderToString: SsrRenderer;
@@ -0,0 +1,31 @@
1
+ import { angularComponent } from "./component.js";
2
+ import { DOCUMENT, createComponent, provideZonelessChangeDetection } from "@angular/core";
3
+ import { createApplication } from "@angular/platform-browser";
4
+ import { renderApplication } from "@angular/platform-server";
5
+ /** The document the component renders into; only its body is returned. */
6
+ const DOCUMENT_HTML = "<html><head></head><body></body></html>";
7
+ /**
8
+ * Renders a component on Angular's server platform and returns the content of `<body>`: the
9
+ * component's host element (`<uf-x style="display: contents;">`) and its content. Inputs are
10
+ * set before the first change detection; `createComponent` adds neither `ng-version` nor
11
+ * `ng-server-context`, which `bootstrapApplication` would.
12
+ */
13
+ const renderToString = async (component, options) => {
14
+ const type = angularComponent(component);
15
+ const html = await renderApplication(async (context) => {
16
+ const app = await createApplication({ providers: [provideZonelessChangeDetection()] }, context);
17
+ const ref = createComponent(type, { environmentInjector: app.injector });
18
+ for (const [name, value] of Object.entries(options.props ?? {})) ref.setInput(name, value);
19
+ app.attachView(ref.hostView);
20
+ app.injector.get(DOCUMENT).body.appendChild(ref.location.nativeElement);
21
+ return app;
22
+ }, {
23
+ document: DOCUMENT_HTML,
24
+ url: "http://localhost/",
25
+ allowedHosts: ["localhost"]
26
+ });
27
+ const body = /<body[^>]*>([\s\S]*)<\/body>/.exec(html);
28
+ if (!body) throw new Error(`Angular rendered a document without a <body>: ${html}`);
29
+ return body[1];
30
+ };
31
+ export { renderToString };