@unframework.dev/target-angular 0.0.0-stage → 0.0.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,213 @@
1
+ import { isSignal, memberOf } from "./plan.js";
2
+ import { tidied } from "./rules.js";
3
+ import { functionBodyText, parseExpression, parseStatementsSource } from "@unframework.dev/codegen";
4
+ /**
5
+ * A function's body as statements, its value dropped (see the module's comment): a block body's
6
+ * own `return`s give none (`withoutValues`), since Angular calls what the output moves it to (a
7
+ * method, a hook, an effect) for no value, and a value on some paths only fails
8
+ * `noImplicitReturns`.
9
+ */
10
+ function bodyStatements(fn, plan, rules) {
11
+ const body = functionBodyText(fn, plan.component, rules, "client", { discard: true });
12
+ if (!fn.expression) return tidied(returnsValue(fn) ? withoutValues(body, plan) : body, "statements");
13
+ const code = body.replace(/;$/, "");
14
+ return tidied(effectsOf(parseExpression(code), code, reads(plan)), "statements");
15
+ }
16
+ /**
17
+ * The members whose call reads a value and changes nothing: the signals (inputs, states,
18
+ * derived values, setup-once constants, a composable's returned refs, `toggle_1.on`) and the
19
+ * template refs' queries.
20
+ */
21
+ function reads(plan) {
22
+ const names = /* @__PURE__ */ new Set();
23
+ for (const binding of plan.component.bindings) {
24
+ const form = plan.forms.get(binding.id);
25
+ if (form !== void 0 && (isSignal(form) || form === "query")) names.add(memberOf(plan, binding));
26
+ }
27
+ return names;
28
+ }
29
+ /**
30
+ * The statements that run what an expression in `code` changes, its value dropped, or `""` when
31
+ * it changes nothing. A side of `&&`, `||` or `??` that changes something runs under the test its
32
+ * operator makes; a branch of `?:` that does, under the condition. An operand, an element or a
33
+ * member read that changes nothing goes, and the parts that do run in their order.
34
+ */
35
+ function effectsOf(node, code, members) {
36
+ if (!hasEffects(node, members)) return "";
37
+ const text = (part) => code.slice(part.start, part.end);
38
+ const of = (part) => effectsOf(part, code, members);
39
+ const all = (parts) => parts.map(of).filter(Boolean).join("\n");
40
+ switch (node.type) {
41
+ case "LogicalExpression": {
42
+ const right = of(node.right);
43
+ if (right === "") return of(node.left);
44
+ const left = text(node.left);
45
+ return `if (${node.operator === "&&" ? left : node.operator === "||" ? `!(${left})` : `(${left}) == null`}) ${branch(right)}`;
46
+ }
47
+ case "ConditionalExpression": {
48
+ const consequent = of(node.consequent);
49
+ const alternate = of(node.alternate);
50
+ const test = text(node.test);
51
+ if (consequent === "" && alternate === "") return of(node.test);
52
+ if (alternate === "") return `if (${test}) ${branch(consequent)}`;
53
+ if (consequent === "") return `if (!(${test})) ${branch(alternate)}`;
54
+ return `if (${test}) ${branch(consequent, true)} else ${branch(alternate)}`;
55
+ }
56
+ case "SequenceExpression": return all(node.expressions);
57
+ case "BinaryExpression": return all([node.left, node.right]);
58
+ case "UnaryExpression": return node.operator === "delete" ? `${text(node)};` : of(node.argument);
59
+ case "MemberExpression": return all(node.computed ? [node.object, node.property] : [node.object]);
60
+ case "TemplateLiteral": return all(node.expressions);
61
+ case "ArrayExpression": return all(node.elements.filter((element) => element !== null));
62
+ case "SpreadElement": return of(node.argument);
63
+ case "ObjectExpression": return all(node.properties.flatMap((property) => property.type === "SpreadElement" ? [property] : property.computed ? [property.key, property.value] : [property.value]));
64
+ case "TSAsExpression":
65
+ case "TSSatisfiesExpression":
66
+ case "TSNonNullExpression":
67
+ case "TSTypeAssertion":
68
+ case "TSInstantiationExpression": return of(node.expression);
69
+ case "ChainExpression": return node.expression.type === "CallExpression" ? `${text(node)};` : `void ${text(node)};`;
70
+ default: {
71
+ const statement = text(node);
72
+ return `${/^(?:\{|function\b|class\b|let\s*\[)/.test(statement) ? `(${statement})` : statement};`;
73
+ }
74
+ }
75
+ }
76
+ /** Statements as an `if`'s branch: braced when there are several, or when an `else` follows an `if`. */
77
+ function branch(statements, beforeElse = false) {
78
+ return statements.includes("\n") || beforeElse && statements.startsWith("if ") ? `{\n${statements}\n}` : statements;
79
+ }
80
+ /** The nodes that start a function: code inside one is not the handler's own. */
81
+ const FUNCTIONS = /* @__PURE__ */ new Set([
82
+ "ArrowFunctionExpression",
83
+ "FunctionExpression",
84
+ "FunctionDeclaration",
85
+ "ClassDeclaration",
86
+ "ClassExpression"
87
+ ]);
88
+ /** The expressions that may change something when they run. */
89
+ const EFFECTS = /* @__PURE__ */ new Set([
90
+ "CallExpression",
91
+ "NewExpression",
92
+ "AssignmentExpression",
93
+ "UpdateExpression",
94
+ "AwaitExpression",
95
+ "YieldExpression",
96
+ "TaggedTemplateExpression",
97
+ "ImportExpression"
98
+ ]);
99
+ /**
100
+ * Whether a function may return a value: an expression body, or a `return` with an argument in
101
+ * its own body (not in a function inside it).
102
+ */
103
+ function returnsValue(fn) {
104
+ return fn.expression === true || ownReturns(fn.body.code, true);
105
+ }
106
+ /** Whether a function's block body has a `return` of its own (not in a function inside it). */
107
+ function hasReturn(fn) {
108
+ return fn.expression !== true && ownReturns(fn.body.code, false);
109
+ }
110
+ /** Whether a body has a `return` of its own, with an argument when `valued`. */
111
+ function ownReturns(code, valued) {
112
+ let found = false;
113
+ const visit = (value) => {
114
+ if (found) return;
115
+ if (Array.isArray(value)) {
116
+ for (const item of value) visit(item);
117
+ return;
118
+ }
119
+ if (!isNode(value) || FUNCTIONS.has(value.type)) return;
120
+ if (value.type === "ReturnStatement" && (!valued || value.argument !== null)) {
121
+ found = true;
122
+ return;
123
+ }
124
+ for (const [key, child] of Object.entries(value)) if (key !== "type" && typeof child === "object") visit(child);
125
+ };
126
+ visit(parseStatementsSource(code).statements);
127
+ return found;
128
+ }
129
+ /**
130
+ * A moved body's statements, its own `return`s giving no value: Angular prevents the event when
131
+ * a listener's value is `false`, and a method that returns a value on some paths only fails
132
+ * `noImplicitReturns`. `return false;` becomes `return;`, `return save();` becomes `save();
133
+ * return;` (in a block where it stood alone), and the body's last `return x;` keeps only what
134
+ * runs (`save();`, or nothing for `return count.value > 0;`).
135
+ */
136
+ function withoutValues(code, plan) {
137
+ const members = reads(plan);
138
+ const { statements } = parseStatementsSource(code);
139
+ const last = statements.at(-1);
140
+ const edits = [];
141
+ /** Visits a statement; `listed` when it stands in a list of statements, not alone. */
142
+ const visit = (value, listed) => {
143
+ if (Array.isArray(value)) {
144
+ for (const item of value) visit(item, listed);
145
+ return;
146
+ }
147
+ if (!isNode(value) || FUNCTIONS.has(value.type)) return;
148
+ if (value.type === "ReturnStatement") {
149
+ const argument = value.argument;
150
+ if (argument === null) return;
151
+ const runs = effectsOf(argument, code, members);
152
+ const replaced = value === last ? runs : runs === "" ? "return;" : `${runs}\nreturn;`;
153
+ edits.push({
154
+ start: value.start,
155
+ end: value.end,
156
+ text: listed || runs === "" ? replaced : `{\n${replaced}\n}`
157
+ });
158
+ return;
159
+ }
160
+ for (const [key, child] of Object.entries(value)) {
161
+ if (key === "type" || typeof child !== "object") continue;
162
+ visit(child, Array.isArray(child));
163
+ }
164
+ };
165
+ visit(statements, true);
166
+ let result = code;
167
+ for (const { start, end, text: replacement } of edits.toSorted((a, b) => b.start - a.start)) result = `${result.slice(0, start)}${replacement}${result.slice(end)}`;
168
+ return result.trim();
169
+ }
170
+ /**
171
+ * Whether an expression may change something when it runs (code inside a function aside): a
172
+ * call of a member `members` names, with no arguments, only reads.
173
+ */
174
+ function hasEffects(node, members) {
175
+ let found = false;
176
+ const visit = (value) => {
177
+ if (found) return;
178
+ if (Array.isArray(value)) {
179
+ for (const item of value) visit(item);
180
+ return;
181
+ }
182
+ if (!isNode(value) || FUNCTIONS.has(value.type)) return;
183
+ if (EFFECTS.has(value.type) && !isRead(value, members) || value.type === "UnaryExpression" && value.operator === "delete") {
184
+ found = true;
185
+ return;
186
+ }
187
+ for (const [key, child] of Object.entries(value)) if (key !== "type" && typeof child === "object") visit(child);
188
+ };
189
+ visit(node);
190
+ return found;
191
+ }
192
+ /**
193
+ * Whether a node is the class code's read of a signal or a query: `this.count()`, or a
194
+ * composable's returned ref through its holder, `this.toggle_1.on()`.
195
+ */
196
+ function isRead(node, members) {
197
+ if (node.type !== "CallExpression" || node.arguments.length > 0) return false;
198
+ const path = memberPath(node.callee);
199
+ return path !== void 0 && members.has(path);
200
+ }
201
+ /** `this.count` as `count`, `this.toggle_1.on` as `toggle_1.on`, or `undefined`. */
202
+ function memberPath(node) {
203
+ if (node.type !== "MemberExpression" || node.computed) return void 0;
204
+ const object = node.object;
205
+ const name = node.property.name;
206
+ if (object.type === "ThisExpression") return name;
207
+ const holder = memberPath(object);
208
+ return holder === void 0 || holder.includes(".") ? void 0 : `${holder}.${name}`;
209
+ }
210
+ function isNode(value) {
211
+ return typeof value === "object" && value !== null && typeof value.type === "string" && typeof value.start === "number";
212
+ }
213
+ export { bodyStatements, hasReturn, returnsValue };
@@ -0,0 +1,243 @@
1
+ import { outputName } from "./outputs.js";
2
+ import { bindingById, memberOf, unreachable } from "./plan.js";
3
+ import { readThroughLet, templateRules } from "./rules.js";
4
+ import { selectorOf } from "./composition.js";
5
+ import { angularCode, angularDialect, printMarkup, spreadStyleExpression, staticClassValue, vueClassValue } from "@unframework.dev/codegen";
6
+ import { expressionsOf, walk } from "@unframework.dev/ir";
7
+ /** The consumer's `style`, which the root merges over its own (ADR-0056). */
8
+ const CONSUMER_STYLE = "this.style()";
9
+ /** The template's indentation: two levels, inside the decorator's object. */
10
+ const INDENT = " ";
11
+ const LEVEL = 2;
12
+ /**
13
+ * The component's template: the `@let` declarations that read the signals it uses, each once,
14
+ * then its markup. Angular drops whitespace at the template's edges and between a `@let` and
15
+ * what follows it, so each can sit on a line of its own.
16
+ *
17
+ * Why `@let`: Angular's type checker narrows a template variable as TypeScript narrows a local
18
+ * (`@if (phone) { {{ phone.length }} }`, `item && item.name`, `items[0] && items[0].id`), but
19
+ * never a signal call, which it reads again each time (TS2532 on `phone() && phone().length`).
20
+ * Through a variable, every expression the source wrote type-checks in the template as it does
21
+ * in the source (L4). `this.label()` reads the input: the variable takes the binding's name, and
22
+ * a name in a template means a template variable before a member. The props come first, in
23
+ * member order, then the setup's signals in source order.
24
+ *
25
+ * A `track` expression may read only its own item, `$index` and the component's members
26
+ * (NG8009), so a signal a list's key reads is read there from the class, `this.label()`, and
27
+ * counts as no use of its variable (an unread `@let` is NG8112).
28
+ */
29
+ function template(plan, listeners, reads, composition, models, fallthrough, scope) {
30
+ const { component } = plan;
31
+ const pad = INDENT.repeat(LEVEL);
32
+ const lets = [];
33
+ const declare = (id) => {
34
+ if (id === void 0 || !reads.read.has(id)) return;
35
+ const binding = bindingById(plan, id);
36
+ if (readThroughLet(plan, binding)) lets.push(`${pad}@let ${binding.name} = this.${memberOf(plan, binding)}();`);
37
+ };
38
+ for (const prop of component.props) declare(prop.binding);
39
+ for (const item of component.setup) {
40
+ if ("binding" in item) declare(item.binding);
41
+ if (item.kind === "Use") for (const member of item.members) declare(member.binding);
42
+ }
43
+ const dialect = {
44
+ ...angularDialect,
45
+ componentTag: (name) => composition.tags.get(name) ?? selectorOf(name),
46
+ componentEvent: ({ attribute }) => {
47
+ const name = `(${outputName(attribute.event)})`;
48
+ const statement = listeners.outputs.get(attribute);
49
+ return [{
50
+ name,
51
+ text: `${name}="${angularCode(statement, "event")}"`
52
+ }];
53
+ },
54
+ modelAttribute: ({ attribute }) => models.attributes.get(attribute),
55
+ classAttribute: (written, context) => {
56
+ const { classNames } = models;
57
+ if (!classNames || !written.some((part) => part.kind === "Dynamic" && part.collection)) return angularDialect.classAttribute(written, context);
58
+ const whole = context.element.tag.startsWith("uf-") || written.some((part) => part.kind === "Static" && part.value.includes("{{"));
59
+ const value = whole ? "" : staticClassValue(written);
60
+ const parts = whole ? written.map((part) => part.kind === "Static" ? {
61
+ kind: "Dynamic",
62
+ value: JSON.stringify(part.value)
63
+ } : part) : written;
64
+ const call = `${classNames}(${vueClassValue(parts)})`;
65
+ return [...value ? [{
66
+ name: "class",
67
+ text: angularDialect.attribute("class", value, "")
68
+ }] : [], {
69
+ name: "class",
70
+ text: `[class]="${angularCode(call, "attribute")}"`
71
+ }];
72
+ },
73
+ styleAttribute: (written, context) => {
74
+ const { styleObject } = models;
75
+ const merged = context.element.tag.startsWith("uf-") || written.length > 1;
76
+ const parts = written.map((part) => styleObject && merged && part.property === "" && part.value !== CONSUMER_STYLE ? {
77
+ ...part,
78
+ value: `${styleObject}(${part.value})`
79
+ } : part);
80
+ return angularDialect.styleAttribute(parts, context);
81
+ }
82
+ };
83
+ const render = fallthrough ? withFallthrough(models.render) : models.render;
84
+ const markup = printMarkup(render, dialect, {
85
+ indent: INDENT,
86
+ level: LEVEL,
87
+ component,
88
+ module: plan.module,
89
+ rewrite: templateRules(plan, reads.signals),
90
+ handler: (attribute) => listeners.statements.get(attribute),
91
+ attribute: (attribute) => attribute.kind === "Event" ? listeners.attributes.get(attribute) : models.options.get(attribute),
92
+ scopeRootAttributes: ({ span }) => scope?.roots.has(`${span.start}:${span.end}`) ? [`[ufScope]="this.${scope.host}"`] : []
93
+ });
94
+ const selects = composition.slots.map(({ attribute }) => `${pad}<ng-content select="[${attribute}]" />`);
95
+ return [
96
+ ...lets,
97
+ markup,
98
+ ...selects
99
+ ].join("\n");
100
+ }
101
+ /**
102
+ * The component's root (an element, or a fragment of one element or component), which a
103
+ * consumer's `class` and `style` fall through to (ADR-0054), or none.
104
+ */
105
+ function fallthroughRoot(render) {
106
+ if (render.kind === "Element") return render;
107
+ const [only] = render.children;
108
+ return render.children.length === 1 && (only?.kind === "Element" || only?.kind === "Component") ? only : void 0;
109
+ }
110
+ /**
111
+ * The render tree with the consumer's `class` and `style` inputs merged into the root
112
+ * (ADR-0056): `this.class()` among its class's parts, and `this.style()` as its whole style,
113
+ * whose own declarations it overrides as Vue's merge does.
114
+ */
115
+ function withFallthrough(render) {
116
+ const root = fallthroughRoot(render);
117
+ const span = root.span;
118
+ const expression = (code) => ({
119
+ code,
120
+ span,
121
+ refs: []
122
+ });
123
+ const attributes = [...root.attributes];
124
+ const item = {
125
+ kind: "Dynamic",
126
+ value: expression("this.class()"),
127
+ span
128
+ };
129
+ const classAt = attributes.findIndex((attribute) => attribute.kind === "Class");
130
+ const found = attributes[classAt];
131
+ if (found?.kind === "Class") attributes[classAt] = {
132
+ ...found,
133
+ items: [...found.items, item]
134
+ };
135
+ else attributes.push({
136
+ kind: "Class",
137
+ items: [item],
138
+ span
139
+ });
140
+ const declaration = {
141
+ kind: "Bound",
142
+ property: "",
143
+ value: expression(CONSUMER_STYLE),
144
+ span
145
+ };
146
+ const styleAt = attributes.findIndex((attribute) => attribute.kind === "Style");
147
+ const style = attributes[styleAt];
148
+ const spreadAt = attributes.findIndex((attribute) => attribute.kind === "Spread" && attribute.keys.some((key) => key.name === "style"));
149
+ const spread = attributes[spreadAt];
150
+ if (spread?.kind === "Spread") {
151
+ const own = {
152
+ kind: "Bound",
153
+ property: "",
154
+ value: spreadStyleExpression(spread),
155
+ span: spread.span
156
+ };
157
+ attributes[spreadAt] = {
158
+ ...spread,
159
+ keys: spread.keys.filter((key) => key.name !== "style")
160
+ };
161
+ attributes.push({
162
+ kind: "Style",
163
+ declarations: [own, declaration],
164
+ span
165
+ });
166
+ } else if (style?.kind === "Style" && style.value) attributes[styleAt] = {
167
+ kind: "Style",
168
+ declarations: [{
169
+ kind: "Bound",
170
+ property: "",
171
+ value: style.value,
172
+ span
173
+ }, declaration],
174
+ span: style.span
175
+ };
176
+ else if (style?.kind === "Style") attributes[styleAt] = {
177
+ ...style,
178
+ declarations: [...style.declarations, declaration]
179
+ };
180
+ else attributes.push({
181
+ kind: "Style",
182
+ declarations: [declaration],
183
+ span
184
+ });
185
+ const merged = {
186
+ ...root,
187
+ attributes
188
+ };
189
+ if (render.kind === "Element") return merged;
190
+ return {
191
+ ...render,
192
+ children: [merged]
193
+ };
194
+ }
195
+ /**
196
+ * The bindings the template reads through a variable or as members, and those lists' keys read
197
+ * from the class. A spread whose type declares no key prints nothing, so its object is no read
198
+ * either. The listeners' template statements count too.
199
+ */
200
+ function templateReads(plan, listeners) {
201
+ const signals = /* @__PURE__ */ new Set();
202
+ const slots = /* @__PURE__ */ new Set();
203
+ const { component } = plan;
204
+ const unprinted = /* @__PURE__ */ new Set();
205
+ walk(component.render, { enter(node) {
206
+ if (node.kind === "SlotOutlet" && (node.slot !== "default" || node.props)) slots.add(node.slot);
207
+ if (node.kind !== "Element" && node.kind !== "Component" && node.kind !== "Dynamic") return;
208
+ for (const fill of node.kind === "Element" ? [] : node.fills ?? []) if (fill.forward !== void 0 && fill.forward !== "default") slots.add(fill.forward);
209
+ for (const attribute of node.attributes) {
210
+ if (attribute.kind === "Spread" && attribute.keys.length === 0) unprinted.add(attribute.value);
211
+ if (attribute.kind === "Model" || attribute.kind === "ModelBinding") signals.add(attribute.value);
212
+ }
213
+ } });
214
+ const read = new Set(listeners.reads);
215
+ const keyed = /* @__PURE__ */ new Set();
216
+ const globals = new Set(listeners.globals);
217
+ for (const { expression, path } of expressionsOf(component)) {
218
+ if (unprinted.has(expression) || path.startsWith("/setup/")) continue;
219
+ const key = path.endsWith("/key") || signals.has(expression);
220
+ for (const reference of expression.refs) switch (reference.kind) {
221
+ case "Binding":
222
+ if (bindingById(plan, reference.binding).kind === "component") break;
223
+ (key ? keyed : read).add(reference.binding);
224
+ break;
225
+ case "Global":
226
+ if (reference.name !== "undefined") globals.add(reference.name);
227
+ break;
228
+ case "Import": break;
229
+ case "Slot":
230
+ slots.add(reference.slot);
231
+ break;
232
+ default: unreachable(reference);
233
+ }
234
+ }
235
+ return {
236
+ read,
237
+ keyed,
238
+ globals: [...globals].toSorted(),
239
+ slots,
240
+ signals
241
+ };
242
+ }
243
+ export { fallthroughRoot, template, templateReads };
@@ -0,0 +1,91 @@
1
+ import { collectDiagnostics, createHost, groupByFile, strictOptions, toMessage } from "./ngtsc.js";
2
+ import { loadCompiler } from "./tools.js";
3
+ import { assertFilesToCheck, assertFilesToCompile, diagnosticsByFile } from "@unframework.dev/codegen/toolchain-node";
4
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
5
+ import { join, resolve } from "node:path";
6
+ /**
7
+ * L3: compiles the files, in memory, as one ngtsc program under the strict options, and
8
+ * reports every file's errors and warnings (extended template diagnostics are the warnings).
9
+ */
10
+ async function frameworkCompile(files, context) {
11
+ assertFilesToCompile(files);
12
+ const compiler = await loadCompiler(context.toolchainDir);
13
+ const options = strictOptions(compiler);
14
+ const contents = new Map(files.map((file) => [resolve(file.path), file.contents]));
15
+ const host = createHost(compiler, options, (fileName) => contents.get(resolve(fileName)));
16
+ const declarations = (context.declarations ?? []).map((file) => resolve(file));
17
+ const diagnostics = collectDiagnostics(compiler, [...contents.keys()], (rootNames) => {
18
+ return new compiler.cli.NgtscProgram([...rootNames, ...declarations], options, host);
19
+ });
20
+ return groupByFile(compiler, files.map((file) => file.path), diagnostics);
21
+ }
22
+ /**
23
+ * L15: each file's JavaScript from one ngtsc program, AOT only, as the Vite plugin emits it
24
+ * (`ngtsc-worker.ts`), since no TestBed or JIT metadata reaches a production build.
25
+ */
26
+ async function frameworkEmit(files, context) {
27
+ assertFilesToCompile(files);
28
+ const compiler = await loadCompiler(context.toolchainDir);
29
+ const options = {
30
+ ...strictOptions(compiler),
31
+ noEmit: false,
32
+ declaration: false,
33
+ supportTestBed: false,
34
+ supportJitMode: false
35
+ };
36
+ const contents = new Map(files.map((file) => [resolve(file.path), file.contents]));
37
+ const host = createHost(compiler, options, (fileName) => contents.get(resolve(fileName)));
38
+ const declarations = (context.declarations ?? []).map((file) => resolve(file));
39
+ const program = new compiler.cli.NgtscProgram([...contents.keys(), ...declarations], options, host);
40
+ await program.compiler.analyzeAsync();
41
+ const { transformers } = program.compiler.prepareEmit();
42
+ const tsProgram = program.getTsProgram();
43
+ const emitted = /* @__PURE__ */ new Map();
44
+ for (const file of files) {
45
+ let code;
46
+ tsProgram.emit(tsProgram.getSourceFile(resolve(file.path)), (fileName, text) => {
47
+ if (/\.[cm]?js$/.test(fileName)) code = text;
48
+ }, void 0, false, transformers);
49
+ if (code === void 0) throw new Error(`ngtsc emitted nothing for ${file.path}.`);
50
+ emitted.set(file.path, [{
51
+ path: file.path,
52
+ contents: code
53
+ }]);
54
+ }
55
+ return emitted;
56
+ }
57
+ let configs = 0;
58
+ /**
59
+ * L4: type-checks the files on disk as ngc would, with the toolchain directory's
60
+ * `tsconfig.json`, through a temporary tsconfig in its `.uf-tmp/` that extends it and lists
61
+ * exactly these files, and the context's declarations. Returns every diagnostic ngtsc reported,
62
+ * by file: a requested file's own, an imported file's, the toolchain tsconfig's, and, under the
63
+ * temporary tsconfig, the ones that belong to no file (options, globals). Rejects when the
64
+ * toolchain has no tsconfig.
65
+ */
66
+ async function typecheck(files, context) {
67
+ assertFilesToCheck(files);
68
+ const compiler = await loadCompiler(context.toolchainDir);
69
+ const base = join(context.toolchainDir, "tsconfig.json");
70
+ if (!existsSync(base)) throw new Error(`Cannot start the Angular type check: ${base} does not exist, and it is what the check extends.`);
71
+ const directory = join(context.toolchainDir, ".uf-tmp");
72
+ const project = join(directory, `tsconfig.typecheck.${process.pid}.${++configs}.json`);
73
+ mkdirSync(directory, { recursive: true });
74
+ writeFileSync(project, `${JSON.stringify({
75
+ extends: "../tsconfig.json",
76
+ files: [...files, ...context.declarations ?? []].map((file) => resolve(file)),
77
+ include: []
78
+ }, null, 2)}\n`);
79
+ let config;
80
+ try {
81
+ config = compiler.cli.readConfiguration(project);
82
+ } finally {
83
+ rmSync(project, { force: true });
84
+ }
85
+ const { options, rootNames, errors } = config;
86
+ const host = createHost(compiler, options, () => void 0);
87
+ const diagnostics = diagnosticsByFile(files, project);
88
+ for (const diagnostic of [...errors, ...collectDiagnostics(compiler, rootNames, (roots) => new compiler.cli.NgtscProgram(roots, options, host))]) diagnostics.add(diagnostic.file?.fileName, toMessage(compiler, diagnostic));
89
+ return diagnostics.results;
90
+ }
91
+ export { frameworkCompile, frameworkEmit, typecheck };
@@ -0,0 +1,10 @@
1
+ import { MountAdapter } from "@unframework.dev/codegen";
2
+ /**
3
+ * Mounts a component as its own zoneless application. `createComponent` rather than
4
+ * `bootstrapApplication`: it sets inputs before the first change detection, and adds neither
5
+ * `ng-version` nor the development-mode console message. The host element is created from the
6
+ * component's selector (`<uf-x>`, `display: contents`). The test's listeners are bound to the
7
+ * component's outputs, each named as its event (ADR-0012), when it is created, as a parent's
8
+ * `(change)` would be: they outlive every rerender, which sets inputs only.
9
+ */
10
+ export declare const mount: MountAdapter;
@@ -0,0 +1,79 @@
1
+ import { outputName } from "../outputs.js";
2
+ import { angularComponent } from "./component.js";
3
+ import { createComponent, outputBinding, provideZonelessChangeDetection } from "@angular/core";
4
+ import { createApplication } from "@angular/platform-browser";
5
+ /**
6
+ * Mounts a component as its own zoneless application. `createComponent` rather than
7
+ * `bootstrapApplication`: it sets inputs before the first change detection, and adds neither
8
+ * `ng-version` nor the development-mode console message. The host element is created from the
9
+ * component's selector (`<uf-x>`, `display: contents`). The test's listeners are bound to the
10
+ * component's outputs, each named as its event (ADR-0012), when it is created, as a parent's
11
+ * `(change)` would be: they outlive every rerender, which sets inputs only.
12
+ */
13
+ const mount = async (component, container, options) => {
14
+ const type = angularComponent(component);
15
+ const app = await createApplication({ providers: [provideZonelessChangeDetection()] });
16
+ const inputs = /* @__PURE__ */ new Set();
17
+ let ref;
18
+ let host;
19
+ try {
20
+ ref = createComponent(type, {
21
+ environmentInjector: app.injector,
22
+ bindings: outputBindings(options.on, options.events)
23
+ });
24
+ setInputs(ref, inputs, options.props ?? {});
25
+ host = ref.location.nativeElement;
26
+ container.appendChild(host);
27
+ app.attachView(ref.hostView);
28
+ } catch (error) {
29
+ app.destroy();
30
+ throw error;
31
+ }
32
+ const settle = () => app.whenStable();
33
+ await settle();
34
+ return {
35
+ settle,
36
+ async rerender(props) {
37
+ setInputs(ref, inputs, props);
38
+ await settle();
39
+ },
40
+ async unmount() {
41
+ app.destroy();
42
+ host.remove();
43
+ }
44
+ };
45
+ };
46
+ /**
47
+ * Sets every input `props` has, and each input set before that `props` lacks to `undefined`:
48
+ * an input cannot be unset, and the emitted input's transform turns `undefined` into its
49
+ * default (ADR-0043). For a name that is not an input, Angular logs NG0303, which fails L13.
50
+ */
51
+ function setInputs(ref, set, props) {
52
+ for (const name of set) {
53
+ if (Object.hasOwn(props, name)) continue;
54
+ ref.setInput(name, void 0);
55
+ set.delete(name);
56
+ }
57
+ for (const [name, value] of Object.entries(props)) {
58
+ ref.setInput(name, value);
59
+ set.add(name);
60
+ }
61
+ }
62
+ /**
63
+ * A binding of each listener to the output of its event's name. An `output()` emits one value,
64
+ * so the target emits a payload by its shape (ADR-0047): nothing for an event without members,
65
+ * the value for one required member, and the tuple of the arguments otherwise; the listener gets
66
+ * the arguments back, exactly as many as the component passed.
67
+ */
68
+ function outputBindings(on = {}, events = []) {
69
+ return Object.entries(on).map(([name, listener]) => {
70
+ const optional = events.find((event) => event.name === name)?.optional;
71
+ if (!optional) throw new Error(`Angular mount: the test listens to "${name}", which the component declares no payload for: an output's value is read by the event's shape.`);
72
+ return outputBinding(outputName(name), (value) => {
73
+ if (!optional.length) listener();
74
+ else if (optional.length === 1 && !optional[0]) listener(value);
75
+ else listener(...value);
76
+ });
77
+ });
78
+ }
79
+ export { mount };
@@ -0,0 +1,20 @@
1
+ import { reflectComponentType } from "@angular/core";
2
+ /**
3
+ * The component a test mounts or renders, checked to be an AOT-compiled Angular component, so a
4
+ * module that skipped ngtsc fails here with its cause instead of deep inside Angular, or, where
5
+ * the JIT compiler is loaded, instead of rendering code no user ships.
6
+ */
7
+ function angularComponent(component) {
8
+ if (typeof component === "function" && isAotCompiled(component) && reflectComponentType(component)) return component;
9
+ const actual = typeof component !== "function" ? component === null ? "null" : typeof component : Object.getOwnPropertyDescriptor(component, "ɵcmp")?.get ? `${component.name || "an anonymous component"}, which the JIT compiler would compile at runtime` : `the function ${component.name || "(anonymous)"}`;
10
+ throw new TypeError(`Expected an AOT-compiled Angular component, got ${actual}. Was the module compiled by the Angular toolchain's ngtsc plugin?`);
11
+ }
12
+ /**
13
+ * Whether ngtsc defined the component: AOT output declares `static ɵcmp = ɵɵdefineComponent(…)`,
14
+ * an own data property, where a JIT-decorated class gets a getter that compiles on first read.
15
+ */
16
+ function isAotCompiled(type) {
17
+ const definition = Object.getOwnPropertyDescriptor(type, "ɵcmp");
18
+ return definition !== void 0 && "value" in definition;
19
+ }
20
+ export { angularComponent };
@@ -0,0 +1,4 @@
1
+ import { Toolchain } from "@unframework.dev/codegen";
2
+ /** The Angular 22 toolchain: ngtsc AOT with strict templates for L3, L4 and every project. */
3
+ export declare const toolchain: Toolchain;
4
+ export { toolchain as default };
@@ -0,0 +1,15 @@
1
+ import { frameworkCompile, frameworkEmit, typecheck } from "./check.js";
2
+ import { viteConfig } from "./vite.js";
3
+ import { lintWithEslint, lintWithOxlint, mergeLintResults } from "@unframework.dev/codegen/toolchain-node";
4
+ /** The Angular 22 toolchain: ngtsc AOT with strict templates for L3, L4 and every project. */
5
+ const toolchain = {
6
+ name: "angular",
7
+ vite: viteConfig,
8
+ client: "@unframework.dev/target-angular/toolchain/client",
9
+ server: "@unframework.dev/target-angular/toolchain/server",
10
+ frameworkCompile,
11
+ frameworkEmit,
12
+ typecheck,
13
+ lint: async (files, context) => mergeLintResults(await Promise.all([lintWithOxlint(files, context), lintWithEslint(files, context)]))
14
+ };
15
+ export { toolchain as default, toolchain };