1 |
|
2 | import {createRequire as __cjsCompatRequire} from 'module';
|
3 | const require = __cjsCompatRequire(import.meta.url);
|
4 | const __ESM_IMPORT_META_URL__ = import.meta.url;
|
5 |
|
6 | import {
|
7 | ClassMemberKind,
|
8 | Decorator,
|
9 | KnownDeclaration,
|
10 | filterToMembersWithDecorator,
|
11 | isConcreteDeclaration,
|
12 | isNamedClassDeclaration,
|
13 | reflectObjectLiteral,
|
14 | reflectTypeEntityToDeclaration,
|
15 | typeNodeToValueExpr
|
16 | } from "./chunk-Q5GIQ3RV.js";
|
17 | import {
|
18 | ErrorCode,
|
19 | FatalDiagnosticError,
|
20 | ImportFlags,
|
21 | ImportManager,
|
22 | Reference,
|
23 | assertSuccessfulReferenceEmit,
|
24 | attachDefaultImportDeclaration,
|
25 | createExportSpecifier,
|
26 | getDefaultImportDeclaration,
|
27 | getSourceFile,
|
28 | identifierOfNode,
|
29 | isDeclaration,
|
30 | makeDiagnostic,
|
31 | makeRelatedInformation,
|
32 | nodeDebugInfo,
|
33 | translateExpression,
|
34 | translateStatement,
|
35 | translateType
|
36 | } from "./chunk-WXB5AWIG.js";
|
37 | import {
|
38 | absoluteFrom,
|
39 | absoluteFromSourceFile,
|
40 | relative
|
41 | } from "./chunk-CLV7JFJQ.js";
|
42 | import {
|
43 | PerfEvent,
|
44 | PerfPhase
|
45 | } from "./chunk-R4NY3TJC.js";
|
46 | import {
|
47 | __spreadProps,
|
48 | __spreadValues
|
49 | } from "./chunk-GMSUYBZP.js";
|
50 |
|
51 |
|
52 | var DynamicValue = class {
|
53 | constructor(node, reason, code) {
|
54 | this.node = node;
|
55 | this.reason = reason;
|
56 | this.code = code;
|
57 | }
|
58 | static fromDynamicInput(node, input) {
|
59 | return new DynamicValue(node, input, 0);
|
60 | }
|
61 | static fromDynamicString(node) {
|
62 | return new DynamicValue(node, void 0, 1);
|
63 | }
|
64 | static fromExternalReference(node, ref) {
|
65 | return new DynamicValue(node, ref, 2);
|
66 | }
|
67 | static fromUnsupportedSyntax(node) {
|
68 | return new DynamicValue(node, void 0, 3);
|
69 | }
|
70 | static fromUnknownIdentifier(node) {
|
71 | return new DynamicValue(node, void 0, 4);
|
72 | }
|
73 | static fromInvalidExpressionType(node, value) {
|
74 | return new DynamicValue(node, value, 5);
|
75 | }
|
76 | static fromComplexFunctionCall(node, fn) {
|
77 | return new DynamicValue(node, fn, 6);
|
78 | }
|
79 | static fromDynamicType(node) {
|
80 | return new DynamicValue(node, void 0, 7);
|
81 | }
|
82 | static fromUnknown(node) {
|
83 | return new DynamicValue(node, void 0, 8);
|
84 | }
|
85 | isFromDynamicInput() {
|
86 | return this.code === 0;
|
87 | }
|
88 | isFromDynamicString() {
|
89 | return this.code === 1;
|
90 | }
|
91 | isFromExternalReference() {
|
92 | return this.code === 2;
|
93 | }
|
94 | isFromUnsupportedSyntax() {
|
95 | return this.code === 3;
|
96 | }
|
97 | isFromUnknownIdentifier() {
|
98 | return this.code === 4;
|
99 | }
|
100 | isFromInvalidExpressionType() {
|
101 | return this.code === 5;
|
102 | }
|
103 | isFromComplexFunctionCall() {
|
104 | return this.code === 6;
|
105 | }
|
106 | isFromDynamicType() {
|
107 | return this.code === 7;
|
108 | }
|
109 | isFromUnknown() {
|
110 | return this.code === 8;
|
111 | }
|
112 | accept(visitor) {
|
113 | switch (this.code) {
|
114 | case 0:
|
115 | return visitor.visitDynamicInput(this);
|
116 | case 1:
|
117 | return visitor.visitDynamicString(this);
|
118 | case 2:
|
119 | return visitor.visitExternalReference(this);
|
120 | case 3:
|
121 | return visitor.visitUnsupportedSyntax(this);
|
122 | case 4:
|
123 | return visitor.visitUnknownIdentifier(this);
|
124 | case 5:
|
125 | return visitor.visitInvalidExpressionType(this);
|
126 | case 6:
|
127 | return visitor.visitComplexFunctionCall(this);
|
128 | case 7:
|
129 | return visitor.visitDynamicType(this);
|
130 | case 8:
|
131 | return visitor.visitUnknown(this);
|
132 | }
|
133 | }
|
134 | };
|
135 |
|
136 |
|
137 | import ts from "typescript";
|
138 |
|
139 |
|
140 | var ResolvedModule = class {
|
141 | constructor(exports, evaluate) {
|
142 | this.exports = exports;
|
143 | this.evaluate = evaluate;
|
144 | }
|
145 | getExport(name) {
|
146 | if (!this.exports.has(name)) {
|
147 | return void 0;
|
148 | }
|
149 | return this.evaluate(this.exports.get(name));
|
150 | }
|
151 | getExports() {
|
152 | const map = new Map();
|
153 | this.exports.forEach((decl, name) => {
|
154 | map.set(name, this.evaluate(decl));
|
155 | });
|
156 | return map;
|
157 | }
|
158 | };
|
159 | var EnumValue = class {
|
160 | constructor(enumRef, name, resolved) {
|
161 | this.enumRef = enumRef;
|
162 | this.name = name;
|
163 | this.resolved = resolved;
|
164 | }
|
165 | };
|
166 | var KnownFn = class {
|
167 | };
|
168 |
|
169 |
|
170 | var ArraySliceBuiltinFn = class extends KnownFn {
|
171 | constructor(lhs) {
|
172 | super();
|
173 | this.lhs = lhs;
|
174 | }
|
175 | evaluate(node, args) {
|
176 | if (args.length === 0) {
|
177 | return this.lhs;
|
178 | } else {
|
179 | return DynamicValue.fromUnknown(node);
|
180 | }
|
181 | }
|
182 | };
|
183 | var ArrayConcatBuiltinFn = class extends KnownFn {
|
184 | constructor(lhs) {
|
185 | super();
|
186 | this.lhs = lhs;
|
187 | }
|
188 | evaluate(node, args) {
|
189 | const result = [...this.lhs];
|
190 | for (const arg of args) {
|
191 | if (arg instanceof DynamicValue) {
|
192 | result.push(DynamicValue.fromDynamicInput(node, arg));
|
193 | } else if (Array.isArray(arg)) {
|
194 | result.push(...arg);
|
195 | } else {
|
196 | result.push(arg);
|
197 | }
|
198 | }
|
199 | return result;
|
200 | }
|
201 | };
|
202 | var StringConcatBuiltinFn = class extends KnownFn {
|
203 | constructor(lhs) {
|
204 | super();
|
205 | this.lhs = lhs;
|
206 | }
|
207 | evaluate(node, args) {
|
208 | let result = this.lhs;
|
209 | for (const arg of args) {
|
210 | const resolved = arg instanceof EnumValue ? arg.resolved : arg;
|
211 | if (typeof resolved === "string" || typeof resolved === "number" || typeof resolved === "boolean" || resolved == null) {
|
212 | result = result.concat(resolved);
|
213 | } else {
|
214 | return DynamicValue.fromUnknown(node);
|
215 | }
|
216 | }
|
217 | return result;
|
218 | }
|
219 | };
|
220 | var ObjectAssignBuiltinFn = class extends KnownFn {
|
221 | evaluate(node, args) {
|
222 | if (args.length === 0) {
|
223 | return DynamicValue.fromUnsupportedSyntax(node);
|
224 | }
|
225 | for (const arg of args) {
|
226 | if (arg instanceof DynamicValue) {
|
227 | return DynamicValue.fromDynamicInput(node, arg);
|
228 | } else if (!(arg instanceof Map)) {
|
229 | return DynamicValue.fromUnsupportedSyntax(node);
|
230 | }
|
231 | }
|
232 | const [target, ...sources] = args;
|
233 | for (const source of sources) {
|
234 | source.forEach((value, key) => target.set(key, value));
|
235 | }
|
236 | return target;
|
237 | }
|
238 | };
|
239 |
|
240 |
|
241 | var AssignHelperFn = class extends ObjectAssignBuiltinFn {
|
242 | };
|
243 | var SpreadHelperFn = class extends KnownFn {
|
244 | evaluate(node, args) {
|
245 | const result = [];
|
246 | for (const arg of args) {
|
247 | if (arg instanceof DynamicValue) {
|
248 | result.push(DynamicValue.fromDynamicInput(node, arg));
|
249 | } else if (Array.isArray(arg)) {
|
250 | result.push(...arg);
|
251 | } else {
|
252 | result.push(arg);
|
253 | }
|
254 | }
|
255 | return result;
|
256 | }
|
257 | };
|
258 | var SpreadArrayHelperFn = class extends KnownFn {
|
259 | evaluate(node, args) {
|
260 | if (args.length !== 2 && args.length !== 3) {
|
261 | return DynamicValue.fromUnknown(node);
|
262 | }
|
263 | const [to, from] = args;
|
264 | if (to instanceof DynamicValue) {
|
265 | return DynamicValue.fromDynamicInput(node, to);
|
266 | } else if (from instanceof DynamicValue) {
|
267 | return DynamicValue.fromDynamicInput(node, from);
|
268 | }
|
269 | if (!Array.isArray(to)) {
|
270 | return DynamicValue.fromInvalidExpressionType(node, to);
|
271 | } else if (!Array.isArray(from)) {
|
272 | return DynamicValue.fromInvalidExpressionType(node, from);
|
273 | }
|
274 | return to.concat(from);
|
275 | }
|
276 | };
|
277 | var ReadHelperFn = class extends KnownFn {
|
278 | evaluate(node, args) {
|
279 | if (args.length !== 1) {
|
280 | return DynamicValue.fromUnknown(node);
|
281 | }
|
282 | const [value] = args;
|
283 | if (value instanceof DynamicValue) {
|
284 | return DynamicValue.fromDynamicInput(node, value);
|
285 | }
|
286 | if (!Array.isArray(value)) {
|
287 | return DynamicValue.fromInvalidExpressionType(node, value);
|
288 | }
|
289 | return value;
|
290 | }
|
291 | };
|
292 |
|
293 |
|
294 | var jsGlobalObjectValue = new Map([["assign", new ObjectAssignBuiltinFn()]]);
|
295 | var assignTsHelperFn = new AssignHelperFn();
|
296 | var spreadTsHelperFn = new SpreadHelperFn();
|
297 | var spreadArrayTsHelperFn = new SpreadArrayHelperFn();
|
298 | var readTsHelperFn = new ReadHelperFn();
|
299 | function resolveKnownDeclaration(decl) {
|
300 | switch (decl) {
|
301 | case KnownDeclaration.JsGlobalObject:
|
302 | return jsGlobalObjectValue;
|
303 | case KnownDeclaration.TsHelperAssign:
|
304 | return assignTsHelperFn;
|
305 | case KnownDeclaration.TsHelperSpread:
|
306 | case KnownDeclaration.TsHelperSpreadArrays:
|
307 | return spreadTsHelperFn;
|
308 | case KnownDeclaration.TsHelperSpreadArray:
|
309 | return spreadArrayTsHelperFn;
|
310 | case KnownDeclaration.TsHelperRead:
|
311 | return readTsHelperFn;
|
312 | default:
|
313 | throw new Error(`Cannot resolve known declaration. Received: ${KnownDeclaration[decl]}.`);
|
314 | }
|
315 | }
|
316 |
|
317 |
|
318 | function literalBinaryOp(op) {
|
319 | return { op, literal: true };
|
320 | }
|
321 | function referenceBinaryOp(op) {
|
322 | return { op, literal: false };
|
323 | }
|
324 | var BINARY_OPERATORS = new Map([
|
325 | [ts.SyntaxKind.PlusToken, literalBinaryOp((a, b) => a + b)],
|
326 | [ts.SyntaxKind.MinusToken, literalBinaryOp((a, b) => a - b)],
|
327 | [ts.SyntaxKind.AsteriskToken, literalBinaryOp((a, b) => a * b)],
|
328 | [ts.SyntaxKind.SlashToken, literalBinaryOp((a, b) => a / b)],
|
329 | [ts.SyntaxKind.PercentToken, literalBinaryOp((a, b) => a % b)],
|
330 | [ts.SyntaxKind.AmpersandToken, literalBinaryOp((a, b) => a & b)],
|
331 | [ts.SyntaxKind.BarToken, literalBinaryOp((a, b) => a | b)],
|
332 | [ts.SyntaxKind.CaretToken, literalBinaryOp((a, b) => a ^ b)],
|
333 | [ts.SyntaxKind.LessThanToken, literalBinaryOp((a, b) => a < b)],
|
334 | [ts.SyntaxKind.LessThanEqualsToken, literalBinaryOp((a, b) => a <= b)],
|
335 | [ts.SyntaxKind.GreaterThanToken, literalBinaryOp((a, b) => a > b)],
|
336 | [ts.SyntaxKind.GreaterThanEqualsToken, literalBinaryOp((a, b) => a >= b)],
|
337 | [ts.SyntaxKind.EqualsEqualsToken, literalBinaryOp((a, b) => a == b)],
|
338 | [ts.SyntaxKind.EqualsEqualsEqualsToken, literalBinaryOp((a, b) => a === b)],
|
339 | [ts.SyntaxKind.ExclamationEqualsToken, literalBinaryOp((a, b) => a != b)],
|
340 | [ts.SyntaxKind.ExclamationEqualsEqualsToken, literalBinaryOp((a, b) => a !== b)],
|
341 | [ts.SyntaxKind.LessThanLessThanToken, literalBinaryOp((a, b) => a << b)],
|
342 | [ts.SyntaxKind.GreaterThanGreaterThanToken, literalBinaryOp((a, b) => a >> b)],
|
343 | [ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken, literalBinaryOp((a, b) => a >>> b)],
|
344 | [ts.SyntaxKind.AsteriskAsteriskToken, literalBinaryOp((a, b) => Math.pow(a, b))],
|
345 | [ts.SyntaxKind.AmpersandAmpersandToken, referenceBinaryOp((a, b) => a && b)],
|
346 | [ts.SyntaxKind.BarBarToken, referenceBinaryOp((a, b) => a || b)]
|
347 | ]);
|
348 | var UNARY_OPERATORS = new Map([
|
349 | [ts.SyntaxKind.TildeToken, (a) => ~a],
|
350 | [ts.SyntaxKind.MinusToken, (a) => -a],
|
351 | [ts.SyntaxKind.PlusToken, (a) => +a],
|
352 | [ts.SyntaxKind.ExclamationToken, (a) => !a]
|
353 | ]);
|
354 | var StaticInterpreter = class {
|
355 | constructor(host, checker, dependencyTracker) {
|
356 | this.host = host;
|
357 | this.checker = checker;
|
358 | this.dependencyTracker = dependencyTracker;
|
359 | }
|
360 | visit(node, context) {
|
361 | return this.visitExpression(node, context);
|
362 | }
|
363 | visitExpression(node, context) {
|
364 | let result;
|
365 | if (node.kind === ts.SyntaxKind.TrueKeyword) {
|
366 | return true;
|
367 | } else if (node.kind === ts.SyntaxKind.FalseKeyword) {
|
368 | return false;
|
369 | } else if (node.kind === ts.SyntaxKind.NullKeyword) {
|
370 | return null;
|
371 | } else if (ts.isStringLiteral(node)) {
|
372 | return node.text;
|
373 | } else if (ts.isNoSubstitutionTemplateLiteral(node)) {
|
374 | return node.text;
|
375 | } else if (ts.isTemplateExpression(node)) {
|
376 | result = this.visitTemplateExpression(node, context);
|
377 | } else if (ts.isNumericLiteral(node)) {
|
378 | return parseFloat(node.text);
|
379 | } else if (ts.isObjectLiteralExpression(node)) {
|
380 | result = this.visitObjectLiteralExpression(node, context);
|
381 | } else if (ts.isIdentifier(node)) {
|
382 | result = this.visitIdentifier(node, context);
|
383 | } else if (ts.isPropertyAccessExpression(node)) {
|
384 | result = this.visitPropertyAccessExpression(node, context);
|
385 | } else if (ts.isCallExpression(node)) {
|
386 | result = this.visitCallExpression(node, context);
|
387 | } else if (ts.isConditionalExpression(node)) {
|
388 | result = this.visitConditionalExpression(node, context);
|
389 | } else if (ts.isPrefixUnaryExpression(node)) {
|
390 | result = this.visitPrefixUnaryExpression(node, context);
|
391 | } else if (ts.isBinaryExpression(node)) {
|
392 | result = this.visitBinaryExpression(node, context);
|
393 | } else if (ts.isArrayLiteralExpression(node)) {
|
394 | result = this.visitArrayLiteralExpression(node, context);
|
395 | } else if (ts.isParenthesizedExpression(node)) {
|
396 | result = this.visitParenthesizedExpression(node, context);
|
397 | } else if (ts.isElementAccessExpression(node)) {
|
398 | result = this.visitElementAccessExpression(node, context);
|
399 | } else if (ts.isAsExpression(node)) {
|
400 | result = this.visitExpression(node.expression, context);
|
401 | } else if (ts.isNonNullExpression(node)) {
|
402 | result = this.visitExpression(node.expression, context);
|
403 | } else if (this.host.isClass(node)) {
|
404 | result = this.visitDeclaration(node, context);
|
405 | } else {
|
406 | return DynamicValue.fromUnsupportedSyntax(node);
|
407 | }
|
408 | if (result instanceof DynamicValue && result.node !== node) {
|
409 | return DynamicValue.fromDynamicInput(node, result);
|
410 | }
|
411 | return result;
|
412 | }
|
413 | visitArrayLiteralExpression(node, context) {
|
414 | const array = [];
|
415 | for (let i = 0; i < node.elements.length; i++) {
|
416 | const element = node.elements[i];
|
417 | if (ts.isSpreadElement(element)) {
|
418 | array.push(...this.visitSpreadElement(element, context));
|
419 | } else {
|
420 | array.push(this.visitExpression(element, context));
|
421 | }
|
422 | }
|
423 | return array;
|
424 | }
|
425 | visitObjectLiteralExpression(node, context) {
|
426 | const map = new Map();
|
427 | for (let i = 0; i < node.properties.length; i++) {
|
428 | const property = node.properties[i];
|
429 | if (ts.isPropertyAssignment(property)) {
|
430 | const name = this.stringNameFromPropertyName(property.name, context);
|
431 | if (name === void 0) {
|
432 | return DynamicValue.fromDynamicInput(node, DynamicValue.fromDynamicString(property.name));
|
433 | }
|
434 | map.set(name, this.visitExpression(property.initializer, context));
|
435 | } else if (ts.isShorthandPropertyAssignment(property)) {
|
436 | const symbol = this.checker.getShorthandAssignmentValueSymbol(property);
|
437 | if (symbol === void 0 || symbol.valueDeclaration === void 0) {
|
438 | map.set(property.name.text, DynamicValue.fromUnknown(property));
|
439 | } else {
|
440 | map.set(property.name.text, this.visitDeclaration(symbol.valueDeclaration, context));
|
441 | }
|
442 | } else if (ts.isSpreadAssignment(property)) {
|
443 | const spread = this.visitExpression(property.expression, context);
|
444 | if (spread instanceof DynamicValue) {
|
445 | return DynamicValue.fromDynamicInput(node, spread);
|
446 | } else if (spread instanceof Map) {
|
447 | spread.forEach((value, key) => map.set(key, value));
|
448 | } else if (spread instanceof ResolvedModule) {
|
449 | spread.getExports().forEach((value, key) => map.set(key, value));
|
450 | } else {
|
451 | return DynamicValue.fromDynamicInput(node, DynamicValue.fromInvalidExpressionType(property, spread));
|
452 | }
|
453 | } else {
|
454 | return DynamicValue.fromUnknown(node);
|
455 | }
|
456 | }
|
457 | return map;
|
458 | }
|
459 | visitTemplateExpression(node, context) {
|
460 | const pieces = [node.head.text];
|
461 | for (let i = 0; i < node.templateSpans.length; i++) {
|
462 | const span = node.templateSpans[i];
|
463 | const value = literal(this.visit(span.expression, context), () => DynamicValue.fromDynamicString(span.expression));
|
464 | if (value instanceof DynamicValue) {
|
465 | return DynamicValue.fromDynamicInput(node, value);
|
466 | }
|
467 | pieces.push(`${value}`, span.literal.text);
|
468 | }
|
469 | return pieces.join("");
|
470 | }
|
471 | visitIdentifier(node, context) {
|
472 | const decl = this.host.getDeclarationOfIdentifier(node);
|
473 | if (decl === null) {
|
474 | if (node.originalKeywordKind === ts.SyntaxKind.UndefinedKeyword) {
|
475 | return void 0;
|
476 | } else {
|
477 | if (this.dependencyTracker !== null && this.host.getImportOfIdentifier(node) !== null) {
|
478 | this.dependencyTracker.recordDependencyAnalysisFailure(context.originatingFile);
|
479 | }
|
480 | return DynamicValue.fromUnknownIdentifier(node);
|
481 | }
|
482 | }
|
483 | if (decl.known !== null) {
|
484 | return resolveKnownDeclaration(decl.known);
|
485 | } else if (isConcreteDeclaration(decl) && decl.identity !== null && decl.identity.kind === 0) {
|
486 | return this.getResolvedEnum(decl.node, decl.identity.enumMembers, context);
|
487 | }
|
488 | const declContext = __spreadValues(__spreadValues({}, context), joinModuleContext(context, node, decl));
|
489 | const result = this.visitAmbiguousDeclaration(decl, declContext);
|
490 | if (result instanceof Reference) {
|
491 | if (!result.synthetic) {
|
492 | result.addIdentifier(node);
|
493 | }
|
494 | } else if (result instanceof DynamicValue) {
|
495 | return DynamicValue.fromDynamicInput(node, result);
|
496 | }
|
497 | return result;
|
498 | }
|
499 | visitDeclaration(node, context) {
|
500 | if (this.dependencyTracker !== null) {
|
501 | this.dependencyTracker.addDependency(context.originatingFile, node.getSourceFile());
|
502 | }
|
503 | if (this.host.isClass(node)) {
|
504 | return this.getReference(node, context);
|
505 | } else if (ts.isVariableDeclaration(node)) {
|
506 | return this.visitVariableDeclaration(node, context);
|
507 | } else if (ts.isParameter(node) && context.scope.has(node)) {
|
508 | return context.scope.get(node);
|
509 | } else if (ts.isExportAssignment(node)) {
|
510 | return this.visitExpression(node.expression, context);
|
511 | } else if (ts.isEnumDeclaration(node)) {
|
512 | return this.visitEnumDeclaration(node, context);
|
513 | } else if (ts.isSourceFile(node)) {
|
514 | return this.visitSourceFile(node, context);
|
515 | } else if (ts.isBindingElement(node)) {
|
516 | return this.visitBindingElement(node, context);
|
517 | } else {
|
518 | return this.getReference(node, context);
|
519 | }
|
520 | }
|
521 | visitVariableDeclaration(node, context) {
|
522 | const value = this.host.getVariableValue(node);
|
523 | if (value !== null) {
|
524 | return this.visitExpression(value, context);
|
525 | } else if (isVariableDeclarationDeclared(node)) {
|
526 | if (node.type !== void 0) {
|
527 | const evaluatedType = this.visitType(node.type, context);
|
528 | if (!(evaluatedType instanceof DynamicValue)) {
|
529 | return evaluatedType;
|
530 | }
|
531 | }
|
532 | return this.getReference(node, context);
|
533 | } else {
|
534 | return void 0;
|
535 | }
|
536 | }
|
537 | visitEnumDeclaration(node, context) {
|
538 | const enumRef = this.getReference(node, context);
|
539 | const map = new Map();
|
540 | node.members.forEach((member) => {
|
541 | const name = this.stringNameFromPropertyName(member.name, context);
|
542 | if (name !== void 0) {
|
543 | const resolved = member.initializer && this.visit(member.initializer, context);
|
544 | map.set(name, new EnumValue(enumRef, name, resolved));
|
545 | }
|
546 | });
|
547 | return map;
|
548 | }
|
549 | visitElementAccessExpression(node, context) {
|
550 | const lhs = this.visitExpression(node.expression, context);
|
551 | if (lhs instanceof DynamicValue) {
|
552 | return DynamicValue.fromDynamicInput(node, lhs);
|
553 | }
|
554 | const rhs = this.visitExpression(node.argumentExpression, context);
|
555 | if (rhs instanceof DynamicValue) {
|
556 | return DynamicValue.fromDynamicInput(node, rhs);
|
557 | }
|
558 | if (typeof rhs !== "string" && typeof rhs !== "number") {
|
559 | return DynamicValue.fromInvalidExpressionType(node, rhs);
|
560 | }
|
561 | return this.accessHelper(node, lhs, rhs, context);
|
562 | }
|
563 | visitPropertyAccessExpression(node, context) {
|
564 | const lhs = this.visitExpression(node.expression, context);
|
565 | const rhs = node.name.text;
|
566 | if (lhs instanceof DynamicValue) {
|
567 | return DynamicValue.fromDynamicInput(node, lhs);
|
568 | }
|
569 | return this.accessHelper(node, lhs, rhs, context);
|
570 | }
|
571 | visitSourceFile(node, context) {
|
572 | const declarations = this.host.getExportsOfModule(node);
|
573 | if (declarations === null) {
|
574 | return DynamicValue.fromUnknown(node);
|
575 | }
|
576 | return new ResolvedModule(declarations, (decl) => {
|
577 | if (decl.known !== null) {
|
578 | return resolveKnownDeclaration(decl.known);
|
579 | }
|
580 | const declContext = __spreadValues(__spreadValues({}, context), joinModuleContext(context, node, decl));
|
581 | return this.visitAmbiguousDeclaration(decl, declContext);
|
582 | });
|
583 | }
|
584 | visitAmbiguousDeclaration(decl, declContext) {
|
585 | return decl.kind === 1 && decl.implementation !== void 0 && !isDeclaration(decl.implementation) ? this.visitExpression(decl.implementation, declContext) : this.visitDeclaration(decl.node, declContext);
|
586 | }
|
587 | accessHelper(node, lhs, rhs, context) {
|
588 | const strIndex = `${rhs}`;
|
589 | if (lhs instanceof Map) {
|
590 | if (lhs.has(strIndex)) {
|
591 | return lhs.get(strIndex);
|
592 | } else {
|
593 | return void 0;
|
594 | }
|
595 | } else if (lhs instanceof ResolvedModule) {
|
596 | return lhs.getExport(strIndex);
|
597 | } else if (Array.isArray(lhs)) {
|
598 | if (rhs === "length") {
|
599 | return lhs.length;
|
600 | } else if (rhs === "slice") {
|
601 | return new ArraySliceBuiltinFn(lhs);
|
602 | } else if (rhs === "concat") {
|
603 | return new ArrayConcatBuiltinFn(lhs);
|
604 | }
|
605 | if (typeof rhs !== "number" || !Number.isInteger(rhs)) {
|
606 | return DynamicValue.fromInvalidExpressionType(node, rhs);
|
607 | }
|
608 | return lhs[rhs];
|
609 | } else if (typeof lhs === "string" && rhs === "concat") {
|
610 | return new StringConcatBuiltinFn(lhs);
|
611 | } else if (lhs instanceof Reference) {
|
612 | const ref = lhs.node;
|
613 | if (this.host.isClass(ref)) {
|
614 | const module = owningModule(context, lhs.bestGuessOwningModule);
|
615 | let value = void 0;
|
616 | const member = this.host.getMembersOfClass(ref).find((member2) => member2.isStatic && member2.name === strIndex);
|
617 | if (member !== void 0) {
|
618 | if (member.value !== null) {
|
619 | value = this.visitExpression(member.value, context);
|
620 | } else if (member.implementation !== null) {
|
621 | value = new Reference(member.implementation, module);
|
622 | } else if (member.node) {
|
623 | value = new Reference(member.node, module);
|
624 | }
|
625 | }
|
626 | return value;
|
627 | } else if (isDeclaration(ref)) {
|
628 | return DynamicValue.fromDynamicInput(node, DynamicValue.fromExternalReference(ref, lhs));
|
629 | }
|
630 | } else if (lhs instanceof DynamicValue) {
|
631 | return DynamicValue.fromDynamicInput(node, lhs);
|
632 | }
|
633 | return DynamicValue.fromUnknown(node);
|
634 | }
|
635 | visitCallExpression(node, context) {
|
636 | const lhs = this.visitExpression(node.expression, context);
|
637 | if (lhs instanceof DynamicValue) {
|
638 | return DynamicValue.fromDynamicInput(node, lhs);
|
639 | }
|
640 | if (lhs instanceof KnownFn) {
|
641 | return lhs.evaluate(node, this.evaluateFunctionArguments(node, context));
|
642 | }
|
643 | if (!(lhs instanceof Reference)) {
|
644 | return DynamicValue.fromInvalidExpressionType(node.expression, lhs);
|
645 | }
|
646 | const fn = this.host.getDefinitionOfFunction(lhs.node);
|
647 | if (fn === null) {
|
648 | return DynamicValue.fromInvalidExpressionType(node.expression, lhs);
|
649 | }
|
650 | if (!isFunctionOrMethodReference(lhs)) {
|
651 | return DynamicValue.fromInvalidExpressionType(node.expression, lhs);
|
652 | }
|
653 | if (fn.body === null) {
|
654 | let expr = null;
|
655 | if (context.foreignFunctionResolver) {
|
656 | expr = context.foreignFunctionResolver(lhs, node.arguments);
|
657 | }
|
658 | if (expr === null) {
|
659 | return DynamicValue.fromDynamicInput(node, DynamicValue.fromExternalReference(node.expression, lhs));
|
660 | }
|
661 | if (expr.getSourceFile() !== node.expression.getSourceFile() && lhs.bestGuessOwningModule !== null) {
|
662 | context = __spreadProps(__spreadValues({}, context), {
|
663 | absoluteModuleName: lhs.bestGuessOwningModule.specifier,
|
664 | resolutionContext: lhs.bestGuessOwningModule.resolutionContext
|
665 | });
|
666 | }
|
667 | return this.visitFfrExpression(expr, context);
|
668 | }
|
669 | let res = this.visitFunctionBody(node, fn, context);
|
670 | if (res instanceof DynamicValue && context.foreignFunctionResolver !== void 0) {
|
671 | const ffrExpr = context.foreignFunctionResolver(lhs, node.arguments);
|
672 | if (ffrExpr !== null) {
|
673 | const ffrRes = this.visitFfrExpression(ffrExpr, context);
|
674 | if (!(ffrRes instanceof DynamicValue)) {
|
675 | res = ffrRes;
|
676 | }
|
677 | }
|
678 | }
|
679 | return res;
|
680 | }
|
681 | visitFfrExpression(expr, context) {
|
682 | const res = this.visitExpression(expr, context);
|
683 | if (res instanceof Reference) {
|
684 | res.synthetic = true;
|
685 | }
|
686 | return res;
|
687 | }
|
688 | visitFunctionBody(node, fn, context) {
|
689 | if (fn.body === null) {
|
690 | return DynamicValue.fromUnknown(node);
|
691 | } else if (fn.body.length !== 1 || !ts.isReturnStatement(fn.body[0])) {
|
692 | return DynamicValue.fromComplexFunctionCall(node, fn);
|
693 | }
|
694 | const ret = fn.body[0];
|
695 | const args = this.evaluateFunctionArguments(node, context);
|
696 | const newScope = new Map();
|
697 | const calleeContext = __spreadProps(__spreadValues({}, context), { scope: newScope });
|
698 | fn.parameters.forEach((param, index) => {
|
699 | let arg = args[index];
|
700 | if (param.node.dotDotDotToken !== void 0) {
|
701 | arg = args.slice(index);
|
702 | }
|
703 | if (arg === void 0 && param.initializer !== null) {
|
704 | arg = this.visitExpression(param.initializer, calleeContext);
|
705 | }
|
706 | newScope.set(param.node, arg);
|
707 | });
|
708 | return ret.expression !== void 0 ? this.visitExpression(ret.expression, calleeContext) : void 0;
|
709 | }
|
710 | visitConditionalExpression(node, context) {
|
711 | const condition = this.visitExpression(node.condition, context);
|
712 | if (condition instanceof DynamicValue) {
|
713 | return DynamicValue.fromDynamicInput(node, condition);
|
714 | }
|
715 | if (condition) {
|
716 | return this.visitExpression(node.whenTrue, context);
|
717 | } else {
|
718 | return this.visitExpression(node.whenFalse, context);
|
719 | }
|
720 | }
|
721 | visitPrefixUnaryExpression(node, context) {
|
722 | const operatorKind = node.operator;
|
723 | if (!UNARY_OPERATORS.has(operatorKind)) {
|
724 | return DynamicValue.fromUnsupportedSyntax(node);
|
725 | }
|
726 | const op = UNARY_OPERATORS.get(operatorKind);
|
727 | const value = this.visitExpression(node.operand, context);
|
728 | if (value instanceof DynamicValue) {
|
729 | return DynamicValue.fromDynamicInput(node, value);
|
730 | } else {
|
731 | return op(value);
|
732 | }
|
733 | }
|
734 | visitBinaryExpression(node, context) {
|
735 | const tokenKind = node.operatorToken.kind;
|
736 | if (!BINARY_OPERATORS.has(tokenKind)) {
|
737 | return DynamicValue.fromUnsupportedSyntax(node);
|
738 | }
|
739 | const opRecord = BINARY_OPERATORS.get(tokenKind);
|
740 | let lhs, rhs;
|
741 | if (opRecord.literal) {
|
742 | lhs = literal(this.visitExpression(node.left, context), (value) => DynamicValue.fromInvalidExpressionType(node.left, value));
|
743 | rhs = literal(this.visitExpression(node.right, context), (value) => DynamicValue.fromInvalidExpressionType(node.right, value));
|
744 | } else {
|
745 | lhs = this.visitExpression(node.left, context);
|
746 | rhs = this.visitExpression(node.right, context);
|
747 | }
|
748 | if (lhs instanceof DynamicValue) {
|
749 | return DynamicValue.fromDynamicInput(node, lhs);
|
750 | } else if (rhs instanceof DynamicValue) {
|
751 | return DynamicValue.fromDynamicInput(node, rhs);
|
752 | } else {
|
753 | return opRecord.op(lhs, rhs);
|
754 | }
|
755 | }
|
756 | visitParenthesizedExpression(node, context) {
|
757 | return this.visitExpression(node.expression, context);
|
758 | }
|
759 | evaluateFunctionArguments(node, context) {
|
760 | const args = [];
|
761 | for (const arg of node.arguments) {
|
762 | if (ts.isSpreadElement(arg)) {
|
763 | args.push(...this.visitSpreadElement(arg, context));
|
764 | } else {
|
765 | args.push(this.visitExpression(arg, context));
|
766 | }
|
767 | }
|
768 | return args;
|
769 | }
|
770 | visitSpreadElement(node, context) {
|
771 | const spread = this.visitExpression(node.expression, context);
|
772 | if (spread instanceof DynamicValue) {
|
773 | return [DynamicValue.fromDynamicInput(node, spread)];
|
774 | } else if (!Array.isArray(spread)) {
|
775 | return [DynamicValue.fromInvalidExpressionType(node, spread)];
|
776 | } else {
|
777 | return spread;
|
778 | }
|
779 | }
|
780 | visitBindingElement(node, context) {
|
781 | const path = [];
|
782 | let closestDeclaration = node;
|
783 | while (ts.isBindingElement(closestDeclaration) || ts.isArrayBindingPattern(closestDeclaration) || ts.isObjectBindingPattern(closestDeclaration)) {
|
784 | if (ts.isBindingElement(closestDeclaration)) {
|
785 | path.unshift(closestDeclaration);
|
786 | }
|
787 | closestDeclaration = closestDeclaration.parent;
|
788 | }
|
789 | if (!ts.isVariableDeclaration(closestDeclaration) || closestDeclaration.initializer === void 0) {
|
790 | return DynamicValue.fromUnknown(node);
|
791 | }
|
792 | let value = this.visit(closestDeclaration.initializer, context);
|
793 | for (const element of path) {
|
794 | let key;
|
795 | if (ts.isArrayBindingPattern(element.parent)) {
|
796 | key = element.parent.elements.indexOf(element);
|
797 | } else {
|
798 | const name = element.propertyName || element.name;
|
799 | if (ts.isIdentifier(name)) {
|
800 | key = name.text;
|
801 | } else {
|
802 | return DynamicValue.fromUnknown(element);
|
803 | }
|
804 | }
|
805 | value = this.accessHelper(element, value, key, context);
|
806 | if (value instanceof DynamicValue) {
|
807 | return value;
|
808 | }
|
809 | }
|
810 | return value;
|
811 | }
|
812 | stringNameFromPropertyName(node, context) {
|
813 | if (ts.isIdentifier(node) || ts.isStringLiteral(node) || ts.isNumericLiteral(node)) {
|
814 | return node.text;
|
815 | } else if (ts.isComputedPropertyName(node)) {
|
816 | const literal2 = this.visitExpression(node.expression, context);
|
817 | return typeof literal2 === "string" ? literal2 : void 0;
|
818 | } else {
|
819 | return void 0;
|
820 | }
|
821 | }
|
822 | getResolvedEnum(node, enumMembers, context) {
|
823 | const enumRef = this.getReference(node, context);
|
824 | const map = new Map();
|
825 | enumMembers.forEach((member) => {
|
826 | const name = this.stringNameFromPropertyName(member.name, context);
|
827 | if (name !== void 0) {
|
828 | const resolved = this.visit(member.initializer, context);
|
829 | map.set(name, new EnumValue(enumRef, name, resolved));
|
830 | }
|
831 | });
|
832 | return map;
|
833 | }
|
834 | getReference(node, context) {
|
835 | return new Reference(node, owningModule(context));
|
836 | }
|
837 | visitType(node, context) {
|
838 | if (ts.isLiteralTypeNode(node)) {
|
839 | return this.visitExpression(node.literal, context);
|
840 | } else if (ts.isTupleTypeNode(node)) {
|
841 | return this.visitTupleType(node, context);
|
842 | } else if (ts.isNamedTupleMember(node)) {
|
843 | return this.visitType(node.type, context);
|
844 | }
|
845 | return DynamicValue.fromDynamicType(node);
|
846 | }
|
847 | visitTupleType(node, context) {
|
848 | const res = [];
|
849 | for (const elem of node.elements) {
|
850 | res.push(this.visitType(elem, context));
|
851 | }
|
852 | return res;
|
853 | }
|
854 | };
|
855 | function isFunctionOrMethodReference(ref) {
|
856 | return ts.isFunctionDeclaration(ref.node) || ts.isMethodDeclaration(ref.node) || ts.isFunctionExpression(ref.node);
|
857 | }
|
858 | function literal(value, reject) {
|
859 | if (value instanceof EnumValue) {
|
860 | value = value.resolved;
|
861 | }
|
862 | if (value instanceof DynamicValue || value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
863 | return value;
|
864 | }
|
865 | return reject(value);
|
866 | }
|
867 | function isVariableDeclarationDeclared(node) {
|
868 | if (node.parent === void 0 || !ts.isVariableDeclarationList(node.parent)) {
|
869 | return false;
|
870 | }
|
871 | const declList = node.parent;
|
872 | if (declList.parent === void 0 || !ts.isVariableStatement(declList.parent)) {
|
873 | return false;
|
874 | }
|
875 | const varStmt = declList.parent;
|
876 | return varStmt.modifiers !== void 0 && varStmt.modifiers.some((mod) => mod.kind === ts.SyntaxKind.DeclareKeyword);
|
877 | }
|
878 | var EMPTY = {};
|
879 | function joinModuleContext(existing, node, decl) {
|
880 | if (decl.viaModule !== null && decl.viaModule !== existing.absoluteModuleName) {
|
881 | return {
|
882 | absoluteModuleName: decl.viaModule,
|
883 | resolutionContext: node.getSourceFile().fileName
|
884 | };
|
885 | } else {
|
886 | return EMPTY;
|
887 | }
|
888 | }
|
889 | function owningModule(context, override = null) {
|
890 | let specifier = context.absoluteModuleName;
|
891 | if (override !== null) {
|
892 | specifier = override.specifier;
|
893 | }
|
894 | if (specifier !== null) {
|
895 | return {
|
896 | specifier,
|
897 | resolutionContext: context.resolutionContext
|
898 | };
|
899 | } else {
|
900 | return null;
|
901 | }
|
902 | }
|
903 |
|
904 |
|
905 | var PartialEvaluator = class {
|
906 | constructor(host, checker, dependencyTracker) {
|
907 | this.host = host;
|
908 | this.checker = checker;
|
909 | this.dependencyTracker = dependencyTracker;
|
910 | }
|
911 | evaluate(expr, foreignFunctionResolver) {
|
912 | const interpreter = new StaticInterpreter(this.host, this.checker, this.dependencyTracker);
|
913 | const sourceFile = expr.getSourceFile();
|
914 | return interpreter.visit(expr, {
|
915 | originatingFile: sourceFile,
|
916 | absoluteModuleName: null,
|
917 | resolutionContext: sourceFile.fileName,
|
918 | scope: new Map(),
|
919 | foreignFunctionResolver
|
920 | });
|
921 | }
|
922 | };
|
923 |
|
924 |
|
925 | import ts2 from "typescript";
|
926 | function describeResolvedType(value, maxDepth = 1) {
|
927 | var _a, _b;
|
928 | if (value === null) {
|
929 | return "null";
|
930 | } else if (value === void 0) {
|
931 | return "undefined";
|
932 | } else if (typeof value === "number" || typeof value === "boolean" || typeof value === "string") {
|
933 | return typeof value;
|
934 | } else if (value instanceof Map) {
|
935 | if (maxDepth === 0) {
|
936 | return "object";
|
937 | }
|
938 | const entries = Array.from(value.entries()).map(([key, v]) => {
|
939 | return `${quoteKey(key)}: ${describeResolvedType(v, maxDepth - 1)}`;
|
940 | });
|
941 | return entries.length > 0 ? `{ ${entries.join("; ")} }` : "{}";
|
942 | } else if (value instanceof ResolvedModule) {
|
943 | return "(module)";
|
944 | } else if (value instanceof EnumValue) {
|
945 | return (_a = value.enumRef.debugName) != null ? _a : "(anonymous)";
|
946 | } else if (value instanceof Reference) {
|
947 | return (_b = value.debugName) != null ? _b : "(anonymous)";
|
948 | } else if (Array.isArray(value)) {
|
949 | if (maxDepth === 0) {
|
950 | return "Array";
|
951 | }
|
952 | return `[${value.map((v) => describeResolvedType(v, maxDepth - 1)).join(", ")}]`;
|
953 | } else if (value instanceof DynamicValue) {
|
954 | return "(not statically analyzable)";
|
955 | } else if (value instanceof KnownFn) {
|
956 | return "Function";
|
957 | } else {
|
958 | return "unknown";
|
959 | }
|
960 | }
|
961 | function quoteKey(key) {
|
962 | if (/^[a-z0-9_]+$/i.test(key)) {
|
963 | return key;
|
964 | } else {
|
965 | return `'${key.replace(/'/g, "\\'")}'`;
|
966 | }
|
967 | }
|
968 | function traceDynamicValue(node, value) {
|
969 | return value.accept(new TraceDynamicValueVisitor(node));
|
970 | }
|
971 | var TraceDynamicValueVisitor = class {
|
972 | constructor(node) {
|
973 | this.node = node;
|
974 | this.currentContainerNode = null;
|
975 | }
|
976 | visitDynamicInput(value) {
|
977 | const trace = value.reason.accept(this);
|
978 | if (this.shouldTrace(value.node)) {
|
979 | const info = makeRelatedInformation(value.node, "Unable to evaluate this expression statically.");
|
980 | trace.unshift(info);
|
981 | }
|
982 | return trace;
|
983 | }
|
984 | visitDynamicString(value) {
|
985 | return [makeRelatedInformation(value.node, "A string value could not be determined statically.")];
|
986 | }
|
987 | visitExternalReference(value) {
|
988 | const name = value.reason.debugName;
|
989 | const description = name !== null ? `'${name}'` : "an anonymous declaration";
|
990 | return [makeRelatedInformation(value.node, `A value for ${description} cannot be determined statically, as it is an external declaration.`)];
|
991 | }
|
992 | visitComplexFunctionCall(value) {
|
993 | return [
|
994 | makeRelatedInformation(value.node, "Unable to evaluate function call of complex function. A function must have exactly one return statement."),
|
995 | makeRelatedInformation(value.reason.node, "Function is declared here.")
|
996 | ];
|
997 | }
|
998 | visitInvalidExpressionType(value) {
|
999 | return [makeRelatedInformation(value.node, "Unable to evaluate an invalid expression.")];
|
1000 | }
|
1001 | visitUnknown(value) {
|
1002 | return [makeRelatedInformation(value.node, "Unable to evaluate statically.")];
|
1003 | }
|
1004 | visitUnknownIdentifier(value) {
|
1005 | return [makeRelatedInformation(value.node, "Unknown reference.")];
|
1006 | }
|
1007 | visitDynamicType(value) {
|
1008 | return [makeRelatedInformation(value.node, "Dynamic type.")];
|
1009 | }
|
1010 | visitUnsupportedSyntax(value) {
|
1011 | return [makeRelatedInformation(value.node, "This syntax is not supported.")];
|
1012 | }
|
1013 | shouldTrace(node) {
|
1014 | if (node === this.node) {
|
1015 | return false;
|
1016 | }
|
1017 | const container = getContainerNode(node);
|
1018 | if (container === this.currentContainerNode) {
|
1019 | return false;
|
1020 | }
|
1021 | this.currentContainerNode = container;
|
1022 | return true;
|
1023 | }
|
1024 | };
|
1025 | function getContainerNode(node) {
|
1026 | let currentNode = node;
|
1027 | while (currentNode !== void 0) {
|
1028 | switch (currentNode.kind) {
|
1029 | case ts2.SyntaxKind.ExpressionStatement:
|
1030 | case ts2.SyntaxKind.VariableStatement:
|
1031 | case ts2.SyntaxKind.ReturnStatement:
|
1032 | case ts2.SyntaxKind.IfStatement:
|
1033 | case ts2.SyntaxKind.SwitchStatement:
|
1034 | case ts2.SyntaxKind.DoStatement:
|
1035 | case ts2.SyntaxKind.WhileStatement:
|
1036 | case ts2.SyntaxKind.ForStatement:
|
1037 | case ts2.SyntaxKind.ForInStatement:
|
1038 | case ts2.SyntaxKind.ForOfStatement:
|
1039 | case ts2.SyntaxKind.ContinueStatement:
|
1040 | case ts2.SyntaxKind.BreakStatement:
|
1041 | case ts2.SyntaxKind.ThrowStatement:
|
1042 | case ts2.SyntaxKind.ObjectBindingPattern:
|
1043 | case ts2.SyntaxKind.ArrayBindingPattern:
|
1044 | return currentNode;
|
1045 | }
|
1046 | currentNode = currentNode.parent;
|
1047 | }
|
1048 | return node.getSourceFile();
|
1049 | }
|
1050 |
|
1051 |
|
1052 | import { ExternalExpr, LiteralExpr, ParseLocation, ParseSourceFile, ParseSourceSpan, ReadPropExpr, WrappedNodeExpr } from "@angular/compiler";
|
1053 | import ts3 from "typescript";
|
1054 | function getConstructorDependencies(clazz, reflector, isCore) {
|
1055 | const deps = [];
|
1056 | const errors = [];
|
1057 | let ctorParams = reflector.getConstructorParameters(clazz);
|
1058 | if (ctorParams === null) {
|
1059 | if (reflector.hasBaseClass(clazz)) {
|
1060 | return null;
|
1061 | } else {
|
1062 | ctorParams = [];
|
1063 | }
|
1064 | }
|
1065 | ctorParams.forEach((param, idx) => {
|
1066 | let token = valueReferenceToExpression(param.typeValueReference);
|
1067 | let attributeNameType = null;
|
1068 | let optional = false, self = false, skipSelf = false, host = false;
|
1069 | (param.decorators || []).filter((dec) => isCore || isAngularCore(dec)).forEach((dec) => {
|
1070 | const name = isCore || dec.import === null ? dec.name : dec.import.name;
|
1071 | if (name === "Inject") {
|
1072 | if (dec.args === null || dec.args.length !== 1) {
|
1073 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(dec), `Unexpected number of arguments to @Inject().`);
|
1074 | }
|
1075 | token = new WrappedNodeExpr(dec.args[0]);
|
1076 | } else if (name === "Optional") {
|
1077 | optional = true;
|
1078 | } else if (name === "SkipSelf") {
|
1079 | skipSelf = true;
|
1080 | } else if (name === "Self") {
|
1081 | self = true;
|
1082 | } else if (name === "Host") {
|
1083 | host = true;
|
1084 | } else if (name === "Attribute") {
|
1085 | if (dec.args === null || dec.args.length !== 1) {
|
1086 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(dec), `Unexpected number of arguments to @Attribute().`);
|
1087 | }
|
1088 | const attributeName = dec.args[0];
|
1089 | token = new WrappedNodeExpr(attributeName);
|
1090 | if (ts3.isStringLiteralLike(attributeName)) {
|
1091 | attributeNameType = new LiteralExpr(attributeName.text);
|
1092 | } else {
|
1093 | attributeNameType = new WrappedNodeExpr(ts3.createKeywordTypeNode(ts3.SyntaxKind.UnknownKeyword));
|
1094 | }
|
1095 | } else {
|
1096 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_UNEXPECTED, Decorator.nodeForError(dec), `Unexpected decorator ${name} on parameter.`);
|
1097 | }
|
1098 | });
|
1099 | if (token === null) {
|
1100 | if (param.typeValueReference.kind !== 2) {
|
1101 | throw new Error("Illegal state: expected value reference to be unavailable if no token is present");
|
1102 | }
|
1103 | errors.push({
|
1104 | index: idx,
|
1105 | param,
|
1106 | reason: param.typeValueReference.reason
|
1107 | });
|
1108 | } else {
|
1109 | deps.push({ token, attributeNameType, optional, self, skipSelf, host });
|
1110 | }
|
1111 | });
|
1112 | if (errors.length === 0) {
|
1113 | return { deps };
|
1114 | } else {
|
1115 | return { deps: null, errors };
|
1116 | }
|
1117 | }
|
1118 | function valueReferenceToExpression(valueRef) {
|
1119 | if (valueRef.kind === 2) {
|
1120 | return null;
|
1121 | } else if (valueRef.kind === 0) {
|
1122 | const expr = new WrappedNodeExpr(valueRef.expression);
|
1123 | if (valueRef.defaultImportStatement !== null) {
|
1124 | attachDefaultImportDeclaration(expr, valueRef.defaultImportStatement);
|
1125 | }
|
1126 | return expr;
|
1127 | } else {
|
1128 | let importExpr = new ExternalExpr({ moduleName: valueRef.moduleName, name: valueRef.importedName });
|
1129 | if (valueRef.nestedPath !== null) {
|
1130 | for (const property of valueRef.nestedPath) {
|
1131 | importExpr = new ReadPropExpr(importExpr, property);
|
1132 | }
|
1133 | }
|
1134 | return importExpr;
|
1135 | }
|
1136 | }
|
1137 | function unwrapConstructorDependencies(deps) {
|
1138 | if (deps === null) {
|
1139 | return null;
|
1140 | } else if (deps.deps !== null) {
|
1141 | return deps.deps;
|
1142 | } else {
|
1143 | return "invalid";
|
1144 | }
|
1145 | }
|
1146 | function getValidConstructorDependencies(clazz, reflector, isCore) {
|
1147 | return validateConstructorDependencies(clazz, getConstructorDependencies(clazz, reflector, isCore));
|
1148 | }
|
1149 | function validateConstructorDependencies(clazz, deps) {
|
1150 | if (deps === null) {
|
1151 | return null;
|
1152 | } else if (deps.deps !== null) {
|
1153 | return deps.deps;
|
1154 | } else {
|
1155 | const error = deps.errors[0];
|
1156 | throw createUnsuitableInjectionTokenError(clazz, error);
|
1157 | }
|
1158 | }
|
1159 | function createUnsuitableInjectionTokenError(clazz, error) {
|
1160 | const { param, index, reason } = error;
|
1161 | let chainMessage = void 0;
|
1162 | let hints = void 0;
|
1163 | switch (reason.kind) {
|
1164 | case 5:
|
1165 | chainMessage = "Consider using the @Inject decorator to specify an injection token.";
|
1166 | hints = [
|
1167 | makeRelatedInformation(reason.typeNode, "This type is not supported as injection token.")
|
1168 | ];
|
1169 | break;
|
1170 | case 1:
|
1171 | chainMessage = "Consider using the @Inject decorator to specify an injection token.";
|
1172 | hints = [
|
1173 | makeRelatedInformation(reason.typeNode, "This type does not have a value, so it cannot be used as injection token.")
|
1174 | ];
|
1175 | if (reason.decl !== null) {
|
1176 | hints.push(makeRelatedInformation(reason.decl, "The type is declared here."));
|
1177 | }
|
1178 | break;
|
1179 | case 2:
|
1180 | chainMessage = "Consider changing the type-only import to a regular import, or use the @Inject decorator to specify an injection token.";
|
1181 | hints = [
|
1182 | makeRelatedInformation(reason.typeNode, "This type is imported using a type-only import, which prevents it from being usable as an injection token."),
|
1183 | makeRelatedInformation(reason.node, "The type-only import occurs here.")
|
1184 | ];
|
1185 | break;
|
1186 | case 4:
|
1187 | chainMessage = "Consider using the @Inject decorator to specify an injection token.";
|
1188 | hints = [
|
1189 | makeRelatedInformation(reason.typeNode, "This type corresponds with a namespace, which cannot be used as injection token."),
|
1190 | makeRelatedInformation(reason.importClause, "The namespace import occurs here.")
|
1191 | ];
|
1192 | break;
|
1193 | case 3:
|
1194 | chainMessage = "The type should reference a known declaration.";
|
1195 | hints = [makeRelatedInformation(reason.typeNode, "This type could not be resolved.")];
|
1196 | break;
|
1197 | case 0:
|
1198 | chainMessage = "Consider adding a type to the parameter or use the @Inject decorator to specify an injection token.";
|
1199 | break;
|
1200 | }
|
1201 | const chain = {
|
1202 | messageText: `No suitable injection token for parameter '${param.name || index}' of class '${clazz.name.text}'.`,
|
1203 | category: ts3.DiagnosticCategory.Error,
|
1204 | code: 0,
|
1205 | next: [{
|
1206 | messageText: chainMessage,
|
1207 | category: ts3.DiagnosticCategory.Message,
|
1208 | code: 0
|
1209 | }]
|
1210 | };
|
1211 | return new FatalDiagnosticError(ErrorCode.PARAM_MISSING_TOKEN, param.nameNode, chain, hints);
|
1212 | }
|
1213 | function toR3Reference(origin, valueRef, typeRef, valueContext, typeContext, refEmitter) {
|
1214 | const emittedValueRef = refEmitter.emit(valueRef, valueContext);
|
1215 | assertSuccessfulReferenceEmit(emittedValueRef, origin, "class");
|
1216 | const emittedTypeRef = refEmitter.emit(typeRef, typeContext, ImportFlags.ForceNewImport | ImportFlags.AllowTypeImports);
|
1217 | assertSuccessfulReferenceEmit(emittedTypeRef, origin, "class");
|
1218 | return {
|
1219 | value: emittedValueRef.expression,
|
1220 | type: emittedTypeRef.expression
|
1221 | };
|
1222 | }
|
1223 | function isAngularCore(decorator) {
|
1224 | return decorator.import !== null && decorator.import.from === "@angular/core";
|
1225 | }
|
1226 | function isAngularCoreReference(reference, symbolName) {
|
1227 | return reference.ownedByModuleGuess === "@angular/core" && reference.debugName === symbolName;
|
1228 | }
|
1229 | function findAngularDecorator(decorators, name, isCore) {
|
1230 | return decorators.find((decorator) => isAngularDecorator(decorator, name, isCore));
|
1231 | }
|
1232 | function isAngularDecorator(decorator, name, isCore) {
|
1233 | if (isCore) {
|
1234 | return decorator.name === name;
|
1235 | } else if (isAngularCore(decorator)) {
|
1236 | return decorator.import.name === name;
|
1237 | }
|
1238 | return false;
|
1239 | }
|
1240 | function unwrapExpression(node) {
|
1241 | while (ts3.isAsExpression(node) || ts3.isParenthesizedExpression(node)) {
|
1242 | node = node.expression;
|
1243 | }
|
1244 | return node;
|
1245 | }
|
1246 | function expandForwardRef(arg) {
|
1247 | arg = unwrapExpression(arg);
|
1248 | if (!ts3.isArrowFunction(arg) && !ts3.isFunctionExpression(arg)) {
|
1249 | return null;
|
1250 | }
|
1251 | const body = arg.body;
|
1252 | if (ts3.isBlock(body)) {
|
1253 | if (body.statements.length !== 1) {
|
1254 | return null;
|
1255 | }
|
1256 | const stmt = body.statements[0];
|
1257 | if (!ts3.isReturnStatement(stmt) || stmt.expression === void 0) {
|
1258 | return null;
|
1259 | }
|
1260 | return stmt.expression;
|
1261 | } else {
|
1262 | return body;
|
1263 | }
|
1264 | }
|
1265 | function tryUnwrapForwardRef(node, reflector) {
|
1266 | node = unwrapExpression(node);
|
1267 | if (!ts3.isCallExpression(node) || node.arguments.length !== 1) {
|
1268 | return null;
|
1269 | }
|
1270 | const fn = ts3.isPropertyAccessExpression(node.expression) ? node.expression.name : node.expression;
|
1271 | if (!ts3.isIdentifier(fn)) {
|
1272 | return null;
|
1273 | }
|
1274 | const expr = expandForwardRef(node.arguments[0]);
|
1275 | if (expr === null) {
|
1276 | return null;
|
1277 | }
|
1278 | const imp = reflector.getImportOfIdentifier(fn);
|
1279 | if (imp === null || imp.from !== "@angular/core" || imp.name !== "forwardRef") {
|
1280 | return null;
|
1281 | }
|
1282 | return expr;
|
1283 | }
|
1284 | function forwardRefResolver(ref, args) {
|
1285 | if (!isAngularCoreReference(ref, "forwardRef") || args.length !== 1) {
|
1286 | return null;
|
1287 | }
|
1288 | return expandForwardRef(args[0]);
|
1289 | }
|
1290 | function combineResolvers(resolvers) {
|
1291 | return (ref, args) => {
|
1292 | for (const resolver of resolvers) {
|
1293 | const resolved = resolver(ref, args);
|
1294 | if (resolved !== null) {
|
1295 | return resolved;
|
1296 | }
|
1297 | }
|
1298 | return null;
|
1299 | };
|
1300 | }
|
1301 | function isExpressionForwardReference(expr, context, contextSource) {
|
1302 | if (isWrappedTsNodeExpr(expr)) {
|
1303 | const node = ts3.getOriginalNode(expr.node);
|
1304 | return node.getSourceFile() === contextSource && context.pos < node.pos;
|
1305 | } else {
|
1306 | return false;
|
1307 | }
|
1308 | }
|
1309 | function isWrappedTsNodeExpr(expr) {
|
1310 | return expr instanceof WrappedNodeExpr;
|
1311 | }
|
1312 | function readBaseClass(node, reflector, evaluator) {
|
1313 | const baseExpression = reflector.getBaseClassExpression(node);
|
1314 | if (baseExpression !== null) {
|
1315 | const baseClass = evaluator.evaluate(baseExpression);
|
1316 | if (baseClass instanceof Reference && reflector.isClass(baseClass.node)) {
|
1317 | return baseClass;
|
1318 | } else {
|
1319 | return "dynamic";
|
1320 | }
|
1321 | }
|
1322 | return null;
|
1323 | }
|
1324 | var parensWrapperTransformerFactory = (context) => {
|
1325 | const visitor = (node) => {
|
1326 | const visited = ts3.visitEachChild(node, visitor, context);
|
1327 | if (ts3.isArrowFunction(visited) || ts3.isFunctionExpression(visited)) {
|
1328 | return ts3.createParen(visited);
|
1329 | }
|
1330 | return visited;
|
1331 | };
|
1332 | return (node) => ts3.visitEachChild(node, visitor, context);
|
1333 | };
|
1334 | function wrapFunctionExpressionsInParens(expression) {
|
1335 | return ts3.transform(expression, [parensWrapperTransformerFactory]).transformed[0];
|
1336 | }
|
1337 | function makeDuplicateDeclarationError(node, data, kind) {
|
1338 | const context = [];
|
1339 | for (const decl of data) {
|
1340 | if (decl.rawDeclarations === null) {
|
1341 | continue;
|
1342 | }
|
1343 | const contextNode = decl.ref.getOriginForDiagnostics(decl.rawDeclarations, decl.ngModule.name);
|
1344 | context.push(makeRelatedInformation(contextNode, `'${node.name.text}' is listed in the declarations of the NgModule '${decl.ngModule.name.text}'.`));
|
1345 | }
|
1346 | return makeDiagnostic(ErrorCode.NGMODULE_DECLARATION_NOT_UNIQUE, node.name, `The ${kind} '${node.name.text}' is declared by more than one NgModule.`, context);
|
1347 | }
|
1348 | function resolveProvidersRequiringFactory(rawProviders, reflector, evaluator) {
|
1349 | const providers = new Set();
|
1350 | const resolvedProviders = evaluator.evaluate(rawProviders);
|
1351 | if (!Array.isArray(resolvedProviders)) {
|
1352 | return providers;
|
1353 | }
|
1354 | resolvedProviders.forEach(function processProviders(provider) {
|
1355 | let tokenClass = null;
|
1356 | if (Array.isArray(provider)) {
|
1357 | provider.forEach(processProviders);
|
1358 | } else if (provider instanceof Reference) {
|
1359 | tokenClass = provider;
|
1360 | } else if (provider instanceof Map && provider.has("useClass") && !provider.has("deps")) {
|
1361 | const useExisting = provider.get("useClass");
|
1362 | if (useExisting instanceof Reference) {
|
1363 | tokenClass = useExisting;
|
1364 | }
|
1365 | }
|
1366 | if (tokenClass !== null && !tokenClass.node.getSourceFile().isDeclarationFile && reflector.isClass(tokenClass.node)) {
|
1367 | const constructorParameters = reflector.getConstructorParameters(tokenClass.node);
|
1368 | if (constructorParameters !== null && constructorParameters.length > 0) {
|
1369 | providers.add(tokenClass);
|
1370 | }
|
1371 | }
|
1372 | });
|
1373 | return providers;
|
1374 | }
|
1375 | function wrapTypeReference(reflector, clazz) {
|
1376 | const dtsClass = reflector.getDtsDeclaration(clazz);
|
1377 | const value = new WrappedNodeExpr(clazz.name);
|
1378 | const type = dtsClass !== null && isNamedClassDeclaration(dtsClass) ? new WrappedNodeExpr(dtsClass.name) : value;
|
1379 | return { value, type };
|
1380 | }
|
1381 | function createSourceSpan(node) {
|
1382 | const sf = node.getSourceFile();
|
1383 | const [startOffset, endOffset] = [node.getStart(), node.getEnd()];
|
1384 | const { line: startLine, character: startCol } = sf.getLineAndCharacterOfPosition(startOffset);
|
1385 | const { line: endLine, character: endCol } = sf.getLineAndCharacterOfPosition(endOffset);
|
1386 | const parseSf = new ParseSourceFile(sf.getFullText(), sf.fileName);
|
1387 | return new ParseSourceSpan(new ParseLocation(parseSf, startOffset, startLine + 1, startCol + 1), new ParseLocation(parseSf, endOffset, endLine + 1, endCol + 1));
|
1388 | }
|
1389 | function compileResults(fac, def, metadataStmt, propName) {
|
1390 | const statements = def.statements;
|
1391 | if (metadataStmt !== null) {
|
1392 | statements.push(metadataStmt);
|
1393 | }
|
1394 | return [
|
1395 | fac,
|
1396 | {
|
1397 | name: propName,
|
1398 | initializer: def.expression,
|
1399 | statements: def.statements,
|
1400 | type: def.type
|
1401 | }
|
1402 | ];
|
1403 | }
|
1404 | function toFactoryMetadata(meta, target) {
|
1405 | return {
|
1406 | name: meta.name,
|
1407 | type: meta.type,
|
1408 | internalType: meta.internalType,
|
1409 | typeArgumentCount: meta.typeArgumentCount,
|
1410 | deps: meta.deps,
|
1411 | target
|
1412 | };
|
1413 | }
|
1414 | function isAngularAnimationsReference(reference, symbolName) {
|
1415 | return reference.ownedByModuleGuess === "@angular/animations" && reference.debugName === symbolName;
|
1416 | }
|
1417 | var animationTriggerResolver = (ref, args) => {
|
1418 | const animationTriggerMethodName = "trigger";
|
1419 | if (!isAngularAnimationsReference(ref, animationTriggerMethodName)) {
|
1420 | return null;
|
1421 | }
|
1422 | const triggerNameExpression = args[0];
|
1423 | if (!triggerNameExpression) {
|
1424 | return null;
|
1425 | }
|
1426 | const factory = ts3.factory;
|
1427 | return factory.createObjectLiteralExpression([
|
1428 | factory.createPropertyAssignment(factory.createIdentifier("name"), triggerNameExpression)
|
1429 | ], true);
|
1430 | };
|
1431 |
|
1432 |
|
1433 | import { compileClassMetadata as compileClassMetadata3, compileComponentFromMetadata, compileDeclareClassMetadata as compileDeclareClassMetadata3, compileDeclareComponentFromMetadata, CssSelector, DEFAULT_INTERPOLATION_CONFIG, DomElementSchemaRegistry, ExternalExpr as ExternalExpr5, FactoryTarget as FactoryTarget3, InterpolationConfig, makeBindingParser as makeBindingParser2, ParseSourceFile as ParseSourceFile2, parseTemplate, R3TargetBinder, SelectorMatcher, ViewEncapsulation, WrappedNodeExpr as WrappedNodeExpr5 } from "@angular/compiler";
|
1434 | import ts18 from "typescript";
|
1435 |
|
1436 |
|
1437 | import ts4 from "typescript";
|
1438 | var SemanticSymbol = class {
|
1439 | constructor(decl) {
|
1440 | this.decl = decl;
|
1441 | this.path = absoluteFromSourceFile(decl.getSourceFile());
|
1442 | this.identifier = getSymbolIdentifier(decl);
|
1443 | }
|
1444 | };
|
1445 | function getSymbolIdentifier(decl) {
|
1446 | if (!ts4.isSourceFile(decl.parent)) {
|
1447 | return null;
|
1448 | }
|
1449 | return decl.name.text;
|
1450 | }
|
1451 |
|
1452 |
|
1453 | import { ExternalExpr as ExternalExpr2 } from "@angular/compiler";
|
1454 | var OpaqueSymbol = class extends SemanticSymbol {
|
1455 | isPublicApiAffected() {
|
1456 | return false;
|
1457 | }
|
1458 | isTypeCheckApiAffected() {
|
1459 | return false;
|
1460 | }
|
1461 | };
|
1462 | var SemanticDepGraph = class {
|
1463 | constructor() {
|
1464 | this.files = new Map();
|
1465 | this.symbolByDecl = new Map();
|
1466 | }
|
1467 | registerSymbol(symbol) {
|
1468 | this.symbolByDecl.set(symbol.decl, symbol);
|
1469 | if (symbol.identifier !== null) {
|
1470 | if (!this.files.has(symbol.path)) {
|
1471 | this.files.set(symbol.path, new Map());
|
1472 | }
|
1473 | this.files.get(symbol.path).set(symbol.identifier, symbol);
|
1474 | }
|
1475 | }
|
1476 | getEquivalentSymbol(symbol) {
|
1477 | let previousSymbol = this.getSymbolByDecl(symbol.decl);
|
1478 | if (previousSymbol === null && symbol.identifier !== null) {
|
1479 | previousSymbol = this.getSymbolByName(symbol.path, symbol.identifier);
|
1480 | }
|
1481 | return previousSymbol;
|
1482 | }
|
1483 | getSymbolByName(path, identifier) {
|
1484 | if (!this.files.has(path)) {
|
1485 | return null;
|
1486 | }
|
1487 | const file = this.files.get(path);
|
1488 | if (!file.has(identifier)) {
|
1489 | return null;
|
1490 | }
|
1491 | return file.get(identifier);
|
1492 | }
|
1493 | getSymbolByDecl(decl) {
|
1494 | if (!this.symbolByDecl.has(decl)) {
|
1495 | return null;
|
1496 | }
|
1497 | return this.symbolByDecl.get(decl);
|
1498 | }
|
1499 | };
|
1500 | var SemanticDepGraphUpdater = class {
|
1501 | constructor(priorGraph) {
|
1502 | this.priorGraph = priorGraph;
|
1503 | this.newGraph = new SemanticDepGraph();
|
1504 | this.opaqueSymbols = new Map();
|
1505 | }
|
1506 | registerSymbol(symbol) {
|
1507 | this.newGraph.registerSymbol(symbol);
|
1508 | }
|
1509 | finalize() {
|
1510 | if (this.priorGraph === null) {
|
1511 | return {
|
1512 | needsEmit: new Set(),
|
1513 | needsTypeCheckEmit: new Set(),
|
1514 | newGraph: this.newGraph
|
1515 | };
|
1516 | }
|
1517 | const needsEmit = this.determineInvalidatedFiles(this.priorGraph);
|
1518 | const needsTypeCheckEmit = this.determineInvalidatedTypeCheckFiles(this.priorGraph);
|
1519 | return {
|
1520 | needsEmit,
|
1521 | needsTypeCheckEmit,
|
1522 | newGraph: this.newGraph
|
1523 | };
|
1524 | }
|
1525 | determineInvalidatedFiles(priorGraph) {
|
1526 | const isPublicApiAffected = new Set();
|
1527 | for (const symbol of this.newGraph.symbolByDecl.values()) {
|
1528 | const previousSymbol = priorGraph.getEquivalentSymbol(symbol);
|
1529 | if (previousSymbol === null || symbol.isPublicApiAffected(previousSymbol)) {
|
1530 | isPublicApiAffected.add(symbol);
|
1531 | }
|
1532 | }
|
1533 | const needsEmit = new Set();
|
1534 | for (const symbol of this.newGraph.symbolByDecl.values()) {
|
1535 | if (symbol.isEmitAffected === void 0) {
|
1536 | continue;
|
1537 | }
|
1538 | const previousSymbol = priorGraph.getEquivalentSymbol(symbol);
|
1539 | if (previousSymbol === null || symbol.isEmitAffected(previousSymbol, isPublicApiAffected)) {
|
1540 | needsEmit.add(symbol.path);
|
1541 | }
|
1542 | }
|
1543 | return needsEmit;
|
1544 | }
|
1545 | determineInvalidatedTypeCheckFiles(priorGraph) {
|
1546 | const isTypeCheckApiAffected = new Set();
|
1547 | for (const symbol of this.newGraph.symbolByDecl.values()) {
|
1548 | const previousSymbol = priorGraph.getEquivalentSymbol(symbol);
|
1549 | if (previousSymbol === null || symbol.isTypeCheckApiAffected(previousSymbol)) {
|
1550 | isTypeCheckApiAffected.add(symbol);
|
1551 | }
|
1552 | }
|
1553 | const needsTypeCheckEmit = new Set();
|
1554 | for (const symbol of this.newGraph.symbolByDecl.values()) {
|
1555 | if (symbol.isTypeCheckBlockAffected === void 0) {
|
1556 | continue;
|
1557 | }
|
1558 | const previousSymbol = priorGraph.getEquivalentSymbol(symbol);
|
1559 | if (previousSymbol === null || symbol.isTypeCheckBlockAffected(previousSymbol, isTypeCheckApiAffected)) {
|
1560 | needsTypeCheckEmit.add(symbol.path);
|
1561 | }
|
1562 | }
|
1563 | return needsTypeCheckEmit;
|
1564 | }
|
1565 | getSemanticReference(decl, expr) {
|
1566 | return {
|
1567 | symbol: this.getSymbol(decl),
|
1568 | importPath: getImportPath(expr)
|
1569 | };
|
1570 | }
|
1571 | getSymbol(decl) {
|
1572 | const symbol = this.newGraph.getSymbolByDecl(decl);
|
1573 | if (symbol === null) {
|
1574 | return this.getOpaqueSymbol(decl);
|
1575 | }
|
1576 | return symbol;
|
1577 | }
|
1578 | getOpaqueSymbol(decl) {
|
1579 | if (this.opaqueSymbols.has(decl)) {
|
1580 | return this.opaqueSymbols.get(decl);
|
1581 | }
|
1582 | const symbol = new OpaqueSymbol(decl);
|
1583 | this.opaqueSymbols.set(decl, symbol);
|
1584 | return symbol;
|
1585 | }
|
1586 | };
|
1587 | function getImportPath(expr) {
|
1588 | if (expr instanceof ExternalExpr2) {
|
1589 | return `${expr.value.moduleName}$${expr.value.name}`;
|
1590 | } else {
|
1591 | return null;
|
1592 | }
|
1593 | }
|
1594 |
|
1595 |
|
1596 | import ts5 from "typescript";
|
1597 |
|
1598 |
|
1599 | function isSymbolEqual(a, b) {
|
1600 | if (a.decl === b.decl) {
|
1601 | return true;
|
1602 | }
|
1603 | if (a.identifier === null || b.identifier === null) {
|
1604 | return false;
|
1605 | }
|
1606 | return a.path === b.path && a.identifier === b.identifier;
|
1607 | }
|
1608 | function isReferenceEqual(a, b) {
|
1609 | if (!isSymbolEqual(a.symbol, b.symbol)) {
|
1610 | return false;
|
1611 | }
|
1612 | return a.importPath === b.importPath;
|
1613 | }
|
1614 | function referenceEquality(a, b) {
|
1615 | return a === b;
|
1616 | }
|
1617 | function isArrayEqual(a, b, equalityTester = referenceEquality) {
|
1618 | if (a === null || b === null) {
|
1619 | return a === b;
|
1620 | }
|
1621 | if (a.length !== b.length) {
|
1622 | return false;
|
1623 | }
|
1624 | return !a.some((item, index) => !equalityTester(item, b[index]));
|
1625 | }
|
1626 | function isSetEqual(a, b, equalityTester = referenceEquality) {
|
1627 | if (a === null || b === null) {
|
1628 | return a === b;
|
1629 | }
|
1630 | if (a.size !== b.size) {
|
1631 | return false;
|
1632 | }
|
1633 | for (const itemA of a) {
|
1634 | let found = false;
|
1635 | for (const itemB of b) {
|
1636 | if (equalityTester(itemA, itemB)) {
|
1637 | found = true;
|
1638 | break;
|
1639 | }
|
1640 | }
|
1641 | if (!found) {
|
1642 | return false;
|
1643 | }
|
1644 | }
|
1645 | return true;
|
1646 | }
|
1647 |
|
1648 |
|
1649 | function extractSemanticTypeParameters(node) {
|
1650 | if (!ts5.isClassDeclaration(node) || node.typeParameters === void 0) {
|
1651 | return null;
|
1652 | }
|
1653 | return node.typeParameters.map((typeParam) => ({ hasGenericTypeBound: typeParam.constraint !== void 0 }));
|
1654 | }
|
1655 | function areTypeParametersEqual(current, previous) {
|
1656 | if (!isArrayEqual(current, previous, isTypeParameterEqual)) {
|
1657 | return false;
|
1658 | }
|
1659 | if (current !== null && current.some((typeParam) => typeParam.hasGenericTypeBound)) {
|
1660 | return false;
|
1661 | }
|
1662 | return true;
|
1663 | }
|
1664 | function isTypeParameterEqual(a, b) {
|
1665 | return a.hasGenericTypeBound === b.hasGenericTypeBound;
|
1666 | }
|
1667 |
|
1668 |
|
1669 | var MetaType;
|
1670 | (function(MetaType2) {
|
1671 | MetaType2[MetaType2["Pipe"] = 0] = "Pipe";
|
1672 | MetaType2[MetaType2["Directive"] = 1] = "Directive";
|
1673 | })(MetaType || (MetaType = {}));
|
1674 |
|
1675 |
|
1676 | import ts7 from "typescript";
|
1677 |
|
1678 |
|
1679 | var ClassPropertyMapping = class {
|
1680 | constructor(forwardMap) {
|
1681 | this.forwardMap = forwardMap;
|
1682 | this.reverseMap = reverseMapFromForwardMap(forwardMap);
|
1683 | }
|
1684 | static empty() {
|
1685 | return new ClassPropertyMapping( new Map());
|
1686 | }
|
1687 | static fromMappedObject(obj) {
|
1688 | const forwardMap = new Map();
|
1689 | for (const classPropertyName of Object.keys(obj)) {
|
1690 | const value = obj[classPropertyName];
|
1691 | const bindingPropertyName = Array.isArray(value) ? value[0] : value;
|
1692 | const inputOrOutput = { classPropertyName, bindingPropertyName };
|
1693 | forwardMap.set(classPropertyName, inputOrOutput);
|
1694 | }
|
1695 | return new ClassPropertyMapping(forwardMap);
|
1696 | }
|
1697 | static merge(a, b) {
|
1698 | const forwardMap = new Map(a.forwardMap.entries());
|
1699 | for (const [classPropertyName, inputOrOutput] of b.forwardMap) {
|
1700 | forwardMap.set(classPropertyName, inputOrOutput);
|
1701 | }
|
1702 | return new ClassPropertyMapping(forwardMap);
|
1703 | }
|
1704 | get classPropertyNames() {
|
1705 | return Array.from(this.forwardMap.keys());
|
1706 | }
|
1707 | get propertyNames() {
|
1708 | return Array.from(this.reverseMap.keys());
|
1709 | }
|
1710 | hasBindingPropertyName(propertyName) {
|
1711 | return this.reverseMap.has(propertyName);
|
1712 | }
|
1713 | getByBindingPropertyName(propertyName) {
|
1714 | return this.reverseMap.has(propertyName) ? this.reverseMap.get(propertyName) : null;
|
1715 | }
|
1716 | getByClassPropertyName(classPropertyName) {
|
1717 | return this.forwardMap.has(classPropertyName) ? this.forwardMap.get(classPropertyName) : null;
|
1718 | }
|
1719 | toDirectMappedObject() {
|
1720 | const obj = {};
|
1721 | for (const [classPropertyName, inputOrOutput] of this.forwardMap) {
|
1722 | obj[classPropertyName] = inputOrOutput.bindingPropertyName;
|
1723 | }
|
1724 | return obj;
|
1725 | }
|
1726 | toJointMappedObject() {
|
1727 | const obj = {};
|
1728 | for (const [classPropertyName, inputOrOutput] of this.forwardMap) {
|
1729 | if (inputOrOutput.bindingPropertyName === classPropertyName) {
|
1730 | obj[classPropertyName] = inputOrOutput.bindingPropertyName;
|
1731 | } else {
|
1732 | obj[classPropertyName] = [inputOrOutput.bindingPropertyName, classPropertyName];
|
1733 | }
|
1734 | }
|
1735 | return obj;
|
1736 | }
|
1737 | *[Symbol.iterator]() {
|
1738 | for (const [classPropertyName, inputOrOutput] of this.forwardMap.entries()) {
|
1739 | yield [classPropertyName, inputOrOutput.bindingPropertyName];
|
1740 | }
|
1741 | }
|
1742 | };
|
1743 | function reverseMapFromForwardMap(forwardMap) {
|
1744 | const reverseMap = new Map();
|
1745 | for (const [_, inputOrOutput] of forwardMap) {
|
1746 | if (!reverseMap.has(inputOrOutput.bindingPropertyName)) {
|
1747 | reverseMap.set(inputOrOutput.bindingPropertyName, []);
|
1748 | }
|
1749 | reverseMap.get(inputOrOutput.bindingPropertyName).push(inputOrOutput);
|
1750 | }
|
1751 | return reverseMap;
|
1752 | }
|
1753 |
|
1754 |
|
1755 | import ts6 from "typescript";
|
1756 | function extractReferencesFromType(checker, def, bestGuessOwningModule) {
|
1757 | if (!ts6.isTupleTypeNode(def)) {
|
1758 | return [];
|
1759 | }
|
1760 | return def.elements.map((element) => {
|
1761 | if (!ts6.isTypeQueryNode(element)) {
|
1762 | throw new Error(`Expected TypeQueryNode: ${nodeDebugInfo(element)}`);
|
1763 | }
|
1764 | const type = element.exprName;
|
1765 | const { node, from } = reflectTypeEntityToDeclaration(type, checker);
|
1766 | if (!isNamedClassDeclaration(node)) {
|
1767 | throw new Error(`Expected named ClassDeclaration: ${nodeDebugInfo(node)}`);
|
1768 | }
|
1769 | if (from !== null && !from.startsWith(".")) {
|
1770 | return new Reference(node, { specifier: from, resolutionContext: def.getSourceFile().fileName });
|
1771 | } else {
|
1772 | return new Reference(node, bestGuessOwningModule);
|
1773 | }
|
1774 | });
|
1775 | }
|
1776 | function readStringType(type) {
|
1777 | if (!ts6.isLiteralTypeNode(type) || !ts6.isStringLiteral(type.literal)) {
|
1778 | return null;
|
1779 | }
|
1780 | return type.literal.text;
|
1781 | }
|
1782 | function readStringMapType(type) {
|
1783 | if (!ts6.isTypeLiteralNode(type)) {
|
1784 | return {};
|
1785 | }
|
1786 | const obj = {};
|
1787 | type.members.forEach((member) => {
|
1788 | if (!ts6.isPropertySignature(member) || member.type === void 0 || member.name === void 0 || !ts6.isStringLiteral(member.name)) {
|
1789 | return;
|
1790 | }
|
1791 | const value = readStringType(member.type);
|
1792 | if (value === null) {
|
1793 | return null;
|
1794 | }
|
1795 | obj[member.name.text] = value;
|
1796 | });
|
1797 | return obj;
|
1798 | }
|
1799 | function readStringArrayType(type) {
|
1800 | if (!ts6.isTupleTypeNode(type)) {
|
1801 | return [];
|
1802 | }
|
1803 | const res = [];
|
1804 | type.elements.forEach((el) => {
|
1805 | if (!ts6.isLiteralTypeNode(el) || !ts6.isStringLiteral(el.literal)) {
|
1806 | return;
|
1807 | }
|
1808 | res.push(el.literal.text);
|
1809 | });
|
1810 | return res;
|
1811 | }
|
1812 | function extractDirectiveTypeCheckMeta(node, inputs, reflector) {
|
1813 | const members = reflector.getMembersOfClass(node);
|
1814 | const staticMembers = members.filter((member) => member.isStatic);
|
1815 | const ngTemplateGuards = staticMembers.map(extractTemplateGuard).filter((guard) => guard !== null);
|
1816 | const hasNgTemplateContextGuard = staticMembers.some((member) => member.kind === ClassMemberKind.Method && member.name === "ngTemplateContextGuard");
|
1817 | const coercedInputFields = new Set(staticMembers.map(extractCoercedInput).filter((inputName) => inputName !== null));
|
1818 | const restrictedInputFields = new Set();
|
1819 | const stringLiteralInputFields = new Set();
|
1820 | const undeclaredInputFields = new Set();
|
1821 | for (const classPropertyName of inputs.classPropertyNames) {
|
1822 | const field = members.find((member) => member.name === classPropertyName);
|
1823 | if (field === void 0 || field.node === null) {
|
1824 | undeclaredInputFields.add(classPropertyName);
|
1825 | continue;
|
1826 | }
|
1827 | if (isRestricted(field.node)) {
|
1828 | restrictedInputFields.add(classPropertyName);
|
1829 | }
|
1830 | if (field.nameNode !== null && ts6.isStringLiteral(field.nameNode)) {
|
1831 | stringLiteralInputFields.add(classPropertyName);
|
1832 | }
|
1833 | }
|
1834 | const arity = reflector.getGenericArityOfClass(node);
|
1835 | return {
|
1836 | hasNgTemplateContextGuard,
|
1837 | ngTemplateGuards,
|
1838 | coercedInputFields,
|
1839 | restrictedInputFields,
|
1840 | stringLiteralInputFields,
|
1841 | undeclaredInputFields,
|
1842 | isGeneric: arity !== null && arity > 0
|
1843 | };
|
1844 | }
|
1845 | function isRestricted(node) {
|
1846 | if (node.modifiers === void 0) {
|
1847 | return false;
|
1848 | }
|
1849 | return node.modifiers.some((modifier) => modifier.kind === ts6.SyntaxKind.PrivateKeyword || modifier.kind === ts6.SyntaxKind.ProtectedKeyword || modifier.kind === ts6.SyntaxKind.ReadonlyKeyword);
|
1850 | }
|
1851 | function extractTemplateGuard(member) {
|
1852 | if (!member.name.startsWith("ngTemplateGuard_")) {
|
1853 | return null;
|
1854 | }
|
1855 | const inputName = afterUnderscore(member.name);
|
1856 | if (member.kind === ClassMemberKind.Property) {
|
1857 | let type = null;
|
1858 | if (member.type !== null && ts6.isLiteralTypeNode(member.type) && ts6.isStringLiteral(member.type.literal)) {
|
1859 | type = member.type.literal.text;
|
1860 | }
|
1861 | if (type !== "binding") {
|
1862 | return null;
|
1863 | }
|
1864 | return { inputName, type };
|
1865 | } else if (member.kind === ClassMemberKind.Method) {
|
1866 | return { inputName, type: "invocation" };
|
1867 | } else {
|
1868 | return null;
|
1869 | }
|
1870 | }
|
1871 | function extractCoercedInput(member) {
|
1872 | if (member.kind !== ClassMemberKind.Property || !member.name.startsWith("ngAcceptInputType_")) {
|
1873 | return null;
|
1874 | }
|
1875 | return afterUnderscore(member.name);
|
1876 | }
|
1877 | var CompoundMetadataReader = class {
|
1878 | constructor(readers) {
|
1879 | this.readers = readers;
|
1880 | }
|
1881 | getDirectiveMetadata(node) {
|
1882 | for (const reader of this.readers) {
|
1883 | const meta = reader.getDirectiveMetadata(node);
|
1884 | if (meta !== null) {
|
1885 | return meta;
|
1886 | }
|
1887 | }
|
1888 | return null;
|
1889 | }
|
1890 | getNgModuleMetadata(node) {
|
1891 | for (const reader of this.readers) {
|
1892 | const meta = reader.getNgModuleMetadata(node);
|
1893 | if (meta !== null) {
|
1894 | return meta;
|
1895 | }
|
1896 | }
|
1897 | return null;
|
1898 | }
|
1899 | getPipeMetadata(node) {
|
1900 | for (const reader of this.readers) {
|
1901 | const meta = reader.getPipeMetadata(node);
|
1902 | if (meta !== null) {
|
1903 | return meta;
|
1904 | }
|
1905 | }
|
1906 | return null;
|
1907 | }
|
1908 | };
|
1909 | function afterUnderscore(str) {
|
1910 | const pos = str.indexOf("_");
|
1911 | if (pos === -1) {
|
1912 | throw new Error(`Expected '${str}' to contain '_'`);
|
1913 | }
|
1914 | return str.substr(pos + 1);
|
1915 | }
|
1916 | function hasInjectableFields(clazz, host) {
|
1917 | const members = host.getMembersOfClass(clazz);
|
1918 | return members.some(({ isStatic, name }) => isStatic && (name === "\u0275prov" || name === "\u0275fac"));
|
1919 | }
|
1920 |
|
1921 |
|
1922 | var DtsMetadataReader = class {
|
1923 | constructor(checker, reflector) {
|
1924 | this.checker = checker;
|
1925 | this.reflector = reflector;
|
1926 | }
|
1927 | getNgModuleMetadata(ref) {
|
1928 | const clazz = ref.node;
|
1929 | const ngModuleDef = this.reflector.getMembersOfClass(clazz).find((member) => member.name === "\u0275mod" && member.isStatic);
|
1930 | if (ngModuleDef === void 0) {
|
1931 | return null;
|
1932 | } else if (ngModuleDef.type === null || !ts7.isTypeReferenceNode(ngModuleDef.type) || ngModuleDef.type.typeArguments === void 0 || ngModuleDef.type.typeArguments.length !== 4) {
|
1933 | return null;
|
1934 | }
|
1935 | const [_, declarationMetadata, importMetadata, exportMetadata] = ngModuleDef.type.typeArguments;
|
1936 | return {
|
1937 | ref,
|
1938 | declarations: extractReferencesFromType(this.checker, declarationMetadata, ref.bestGuessOwningModule),
|
1939 | exports: extractReferencesFromType(this.checker, exportMetadata, ref.bestGuessOwningModule),
|
1940 | imports: extractReferencesFromType(this.checker, importMetadata, ref.bestGuessOwningModule),
|
1941 | schemas: [],
|
1942 | rawDeclarations: null
|
1943 | };
|
1944 | }
|
1945 | getDirectiveMetadata(ref) {
|
1946 | const clazz = ref.node;
|
1947 | const def = this.reflector.getMembersOfClass(clazz).find((field) => field.isStatic && (field.name === "\u0275cmp" || field.name === "\u0275dir"));
|
1948 | if (def === void 0) {
|
1949 | return null;
|
1950 | } else if (def.type === null || !ts7.isTypeReferenceNode(def.type) || def.type.typeArguments === void 0 || def.type.typeArguments.length < 2) {
|
1951 | return null;
|
1952 | }
|
1953 | const isComponent = def.name === "\u0275cmp";
|
1954 | const ctorParams = this.reflector.getConstructorParameters(clazz);
|
1955 | const isStructural = !isComponent && ctorParams !== null && ctorParams.some((param) => {
|
1956 | return param.typeValueReference.kind === 1 && param.typeValueReference.moduleName === "@angular/core" && param.typeValueReference.importedName === "TemplateRef";
|
1957 | });
|
1958 | const inputs = ClassPropertyMapping.fromMappedObject(readStringMapType(def.type.typeArguments[3]));
|
1959 | const outputs = ClassPropertyMapping.fromMappedObject(readStringMapType(def.type.typeArguments[4]));
|
1960 | return __spreadProps(__spreadValues({
|
1961 | type: MetaType.Directive,
|
1962 | ref,
|
1963 | name: clazz.name.text,
|
1964 | isComponent,
|
1965 | selector: readStringType(def.type.typeArguments[1]),
|
1966 | exportAs: readStringArrayType(def.type.typeArguments[2]),
|
1967 | inputs,
|
1968 | outputs,
|
1969 | queries: readStringArrayType(def.type.typeArguments[5])
|
1970 | }, extractDirectiveTypeCheckMeta(clazz, inputs, this.reflector)), {
|
1971 | baseClass: readBaseClass2(clazz, this.checker, this.reflector),
|
1972 | isPoisoned: false,
|
1973 | isStructural,
|
1974 | animationTriggerNames: null
|
1975 | });
|
1976 | }
|
1977 | getPipeMetadata(ref) {
|
1978 | const def = this.reflector.getMembersOfClass(ref.node).find((field) => field.isStatic && field.name === "\u0275pipe");
|
1979 | if (def === void 0) {
|
1980 | return null;
|
1981 | } else if (def.type === null || !ts7.isTypeReferenceNode(def.type) || def.type.typeArguments === void 0 || def.type.typeArguments.length < 2) {
|
1982 | return null;
|
1983 | }
|
1984 | const type = def.type.typeArguments[1];
|
1985 | if (!ts7.isLiteralTypeNode(type) || !ts7.isStringLiteral(type.literal)) {
|
1986 | return null;
|
1987 | }
|
1988 | const name = type.literal.text;
|
1989 | return {
|
1990 | type: MetaType.Pipe,
|
1991 | ref,
|
1992 | name,
|
1993 | nameExpr: null
|
1994 | };
|
1995 | }
|
1996 | };
|
1997 | function readBaseClass2(clazz, checker, reflector) {
|
1998 | if (!isNamedClassDeclaration(clazz)) {
|
1999 | return reflector.hasBaseClass(clazz) ? "dynamic" : null;
|
2000 | }
|
2001 | if (clazz.heritageClauses !== void 0) {
|
2002 | for (const clause of clazz.heritageClauses) {
|
2003 | if (clause.token === ts7.SyntaxKind.ExtendsKeyword) {
|
2004 | const baseExpr = clause.types[0].expression;
|
2005 | let symbol = checker.getSymbolAtLocation(baseExpr);
|
2006 | if (symbol === void 0) {
|
2007 | return "dynamic";
|
2008 | } else if (symbol.flags & ts7.SymbolFlags.Alias) {
|
2009 | symbol = checker.getAliasedSymbol(symbol);
|
2010 | }
|
2011 | if (symbol.valueDeclaration !== void 0 && isNamedClassDeclaration(symbol.valueDeclaration)) {
|
2012 | return new Reference(symbol.valueDeclaration);
|
2013 | } else {
|
2014 | return "dynamic";
|
2015 | }
|
2016 | }
|
2017 | }
|
2018 | }
|
2019 | return null;
|
2020 | }
|
2021 |
|
2022 |
|
2023 | function flattenInheritedDirectiveMetadata(reader, dir) {
|
2024 | const topMeta = reader.getDirectiveMetadata(dir);
|
2025 | if (topMeta === null) {
|
2026 | throw new Error(`Metadata not found for directive: ${dir.debugName}`);
|
2027 | }
|
2028 | if (topMeta.baseClass === null) {
|
2029 | return topMeta;
|
2030 | }
|
2031 | const coercedInputFields = new Set();
|
2032 | const undeclaredInputFields = new Set();
|
2033 | const restrictedInputFields = new Set();
|
2034 | const stringLiteralInputFields = new Set();
|
2035 | let isDynamic = false;
|
2036 | let inputs = ClassPropertyMapping.empty();
|
2037 | let outputs = ClassPropertyMapping.empty();
|
2038 | let isStructural = false;
|
2039 | const addMetadata = (meta) => {
|
2040 | if (meta.baseClass === "dynamic") {
|
2041 | isDynamic = true;
|
2042 | } else if (meta.baseClass !== null) {
|
2043 | const baseMeta = reader.getDirectiveMetadata(meta.baseClass);
|
2044 | if (baseMeta !== null) {
|
2045 | addMetadata(baseMeta);
|
2046 | } else {
|
2047 | isDynamic = true;
|
2048 | }
|
2049 | }
|
2050 | isStructural = isStructural || meta.isStructural;
|
2051 | inputs = ClassPropertyMapping.merge(inputs, meta.inputs);
|
2052 | outputs = ClassPropertyMapping.merge(outputs, meta.outputs);
|
2053 | for (const coercedInputField of meta.coercedInputFields) {
|
2054 | coercedInputFields.add(coercedInputField);
|
2055 | }
|
2056 | for (const undeclaredInputField of meta.undeclaredInputFields) {
|
2057 | undeclaredInputFields.add(undeclaredInputField);
|
2058 | }
|
2059 | for (const restrictedInputField of meta.restrictedInputFields) {
|
2060 | restrictedInputFields.add(restrictedInputField);
|
2061 | }
|
2062 | for (const field of meta.stringLiteralInputFields) {
|
2063 | stringLiteralInputFields.add(field);
|
2064 | }
|
2065 | };
|
2066 | addMetadata(topMeta);
|
2067 | return __spreadProps(__spreadValues({}, topMeta), {
|
2068 | inputs,
|
2069 | outputs,
|
2070 | coercedInputFields,
|
2071 | undeclaredInputFields,
|
2072 | restrictedInputFields,
|
2073 | stringLiteralInputFields,
|
2074 | baseClass: isDynamic ? "dynamic" : null,
|
2075 | isStructural
|
2076 | });
|
2077 | }
|
2078 |
|
2079 |
|
2080 | var LocalMetadataRegistry = class {
|
2081 | constructor() {
|
2082 | this.directives = new Map();
|
2083 | this.ngModules = new Map();
|
2084 | this.pipes = new Map();
|
2085 | }
|
2086 | getDirectiveMetadata(ref) {
|
2087 | return this.directives.has(ref.node) ? this.directives.get(ref.node) : null;
|
2088 | }
|
2089 | getNgModuleMetadata(ref) {
|
2090 | return this.ngModules.has(ref.node) ? this.ngModules.get(ref.node) : null;
|
2091 | }
|
2092 | getPipeMetadata(ref) {
|
2093 | return this.pipes.has(ref.node) ? this.pipes.get(ref.node) : null;
|
2094 | }
|
2095 | registerDirectiveMetadata(meta) {
|
2096 | this.directives.set(meta.ref.node, meta);
|
2097 | }
|
2098 | registerNgModuleMetadata(meta) {
|
2099 | this.ngModules.set(meta.ref.node, meta);
|
2100 | }
|
2101 | registerPipeMetadata(meta) {
|
2102 | this.pipes.set(meta.ref.node, meta);
|
2103 | }
|
2104 | };
|
2105 | var CompoundMetadataRegistry = class {
|
2106 | constructor(registries) {
|
2107 | this.registries = registries;
|
2108 | }
|
2109 | registerDirectiveMetadata(meta) {
|
2110 | for (const registry of this.registries) {
|
2111 | registry.registerDirectiveMetadata(meta);
|
2112 | }
|
2113 | }
|
2114 | registerNgModuleMetadata(meta) {
|
2115 | for (const registry of this.registries) {
|
2116 | registry.registerNgModuleMetadata(meta);
|
2117 | }
|
2118 | }
|
2119 | registerPipeMetadata(meta) {
|
2120 | for (const registry of this.registries) {
|
2121 | registry.registerPipeMetadata(meta);
|
2122 | }
|
2123 | }
|
2124 | };
|
2125 | var InjectableClassRegistry = class {
|
2126 | constructor(host) {
|
2127 | this.host = host;
|
2128 | this.classes = new Set();
|
2129 | }
|
2130 | registerInjectable(declaration) {
|
2131 | this.classes.add(declaration);
|
2132 | }
|
2133 | isInjectable(declaration) {
|
2134 | return this.classes.has(declaration) || hasInjectableFields(declaration, this.host);
|
2135 | }
|
2136 | };
|
2137 |
|
2138 |
|
2139 | var ResourceRegistry = class {
|
2140 | constructor() {
|
2141 | this.externalTemplateToComponentsMap = new Map();
|
2142 | this.componentToTemplateMap = new Map();
|
2143 | this.componentToStylesMap = new Map();
|
2144 | this.externalStyleToComponentsMap = new Map();
|
2145 | }
|
2146 | getComponentsWithTemplate(template) {
|
2147 | if (!this.externalTemplateToComponentsMap.has(template)) {
|
2148 | return new Set();
|
2149 | }
|
2150 | return this.externalTemplateToComponentsMap.get(template);
|
2151 | }
|
2152 | registerResources(resources, component) {
|
2153 | if (resources.template !== null) {
|
2154 | this.registerTemplate(resources.template, component);
|
2155 | }
|
2156 | for (const style of resources.styles) {
|
2157 | this.registerStyle(style, component);
|
2158 | }
|
2159 | }
|
2160 | registerTemplate(templateResource, component) {
|
2161 | const { path } = templateResource;
|
2162 | if (path !== null) {
|
2163 | if (!this.externalTemplateToComponentsMap.has(path)) {
|
2164 | this.externalTemplateToComponentsMap.set(path, new Set());
|
2165 | }
|
2166 | this.externalTemplateToComponentsMap.get(path).add(component);
|
2167 | }
|
2168 | this.componentToTemplateMap.set(component, templateResource);
|
2169 | }
|
2170 | getTemplate(component) {
|
2171 | if (!this.componentToTemplateMap.has(component)) {
|
2172 | return null;
|
2173 | }
|
2174 | return this.componentToTemplateMap.get(component);
|
2175 | }
|
2176 | registerStyle(styleResource, component) {
|
2177 | const { path } = styleResource;
|
2178 | if (!this.componentToStylesMap.has(component)) {
|
2179 | this.componentToStylesMap.set(component, new Set());
|
2180 | }
|
2181 | if (path !== null) {
|
2182 | if (!this.externalStyleToComponentsMap.has(path)) {
|
2183 | this.externalStyleToComponentsMap.set(path, new Set());
|
2184 | }
|
2185 | this.externalStyleToComponentsMap.get(path).add(component);
|
2186 | }
|
2187 | this.componentToStylesMap.get(component).add(styleResource);
|
2188 | }
|
2189 | getStyles(component) {
|
2190 | if (!this.componentToStylesMap.has(component)) {
|
2191 | return new Set();
|
2192 | }
|
2193 | return this.componentToStylesMap.get(component);
|
2194 | }
|
2195 | getComponentsWithStyle(styleUrl) {
|
2196 | if (!this.externalStyleToComponentsMap.has(styleUrl)) {
|
2197 | return new Set();
|
2198 | }
|
2199 | return this.externalStyleToComponentsMap.get(styleUrl);
|
2200 | }
|
2201 | };
|
2202 |
|
2203 |
|
2204 | var CompilationMode;
|
2205 | (function(CompilationMode2) {
|
2206 | CompilationMode2[CompilationMode2["FULL"] = 0] = "FULL";
|
2207 | CompilationMode2[CompilationMode2["PARTIAL"] = 1] = "PARTIAL";
|
2208 | })(CompilationMode || (CompilationMode = {}));
|
2209 | var HandlerPrecedence;
|
2210 | (function(HandlerPrecedence2) {
|
2211 | HandlerPrecedence2[HandlerPrecedence2["PRIMARY"] = 0] = "PRIMARY";
|
2212 | HandlerPrecedence2[HandlerPrecedence2["SHARED"] = 1] = "SHARED";
|
2213 | HandlerPrecedence2[HandlerPrecedence2["WEAK"] = 2] = "WEAK";
|
2214 | })(HandlerPrecedence || (HandlerPrecedence = {}));
|
2215 | var HandlerFlags;
|
2216 | (function(HandlerFlags2) {
|
2217 | HandlerFlags2[HandlerFlags2["NONE"] = 0] = "NONE";
|
2218 | HandlerFlags2[HandlerFlags2["FULL_INHERITANCE"] = 1] = "FULL_INHERITANCE";
|
2219 | })(HandlerFlags || (HandlerFlags = {}));
|
2220 |
|
2221 |
|
2222 | import ts8 from "typescript";
|
2223 | function aliasTransformFactory(exportStatements) {
|
2224 | return (context) => {
|
2225 | return (file) => {
|
2226 | if (ts8.isBundle(file) || !exportStatements.has(file.fileName)) {
|
2227 | return file;
|
2228 | }
|
2229 | const statements = [...file.statements];
|
2230 | exportStatements.get(file.fileName).forEach(([moduleName, symbolName], aliasName) => {
|
2231 | const stmt = ts8.createExportDeclaration(void 0, void 0, ts8.createNamedExports([createExportSpecifier(symbolName, aliasName)]), ts8.createStringLiteral(moduleName));
|
2232 | statements.push(stmt);
|
2233 | });
|
2234 | return ts8.updateSourceFileNode(file, statements);
|
2235 | };
|
2236 | };
|
2237 | }
|
2238 |
|
2239 |
|
2240 | import ts9 from "typescript";
|
2241 |
|
2242 |
|
2243 | var TraitState;
|
2244 | (function(TraitState2) {
|
2245 | TraitState2[TraitState2["Pending"] = 0] = "Pending";
|
2246 | TraitState2[TraitState2["Analyzed"] = 1] = "Analyzed";
|
2247 | TraitState2[TraitState2["Resolved"] = 2] = "Resolved";
|
2248 | TraitState2[TraitState2["Skipped"] = 3] = "Skipped";
|
2249 | })(TraitState || (TraitState = {}));
|
2250 | var Trait = {
|
2251 | pending: (handler, detected) => TraitImpl.pending(handler, detected)
|
2252 | };
|
2253 | var TraitImpl = class {
|
2254 | constructor(handler, detected) {
|
2255 | this.state = TraitState.Pending;
|
2256 | this.analysis = null;
|
2257 | this.symbol = null;
|
2258 | this.resolution = null;
|
2259 | this.analysisDiagnostics = null;
|
2260 | this.resolveDiagnostics = null;
|
2261 | this.handler = handler;
|
2262 | this.detected = detected;
|
2263 | }
|
2264 | toAnalyzed(analysis, diagnostics, symbol) {
|
2265 | this.assertTransitionLegal(TraitState.Pending, TraitState.Analyzed);
|
2266 | this.analysis = analysis;
|
2267 | this.analysisDiagnostics = diagnostics;
|
2268 | this.symbol = symbol;
|
2269 | this.state = TraitState.Analyzed;
|
2270 | return this;
|
2271 | }
|
2272 | toResolved(resolution, diagnostics) {
|
2273 | this.assertTransitionLegal(TraitState.Analyzed, TraitState.Resolved);
|
2274 | if (this.analysis === null) {
|
2275 | throw new Error(`Cannot transition an Analyzed trait with a null analysis to Resolved`);
|
2276 | }
|
2277 | this.resolution = resolution;
|
2278 | this.state = TraitState.Resolved;
|
2279 | this.resolveDiagnostics = diagnostics;
|
2280 | return this;
|
2281 | }
|
2282 | toSkipped() {
|
2283 | this.assertTransitionLegal(TraitState.Pending, TraitState.Skipped);
|
2284 | this.state = TraitState.Skipped;
|
2285 | return this;
|
2286 | }
|
2287 | assertTransitionLegal(allowedState, transitionTo) {
|
2288 | if (!(this.state === allowedState)) {
|
2289 | throw new Error(`Assertion failure: cannot transition from ${TraitState[this.state]} to ${TraitState[transitionTo]}.`);
|
2290 | }
|
2291 | }
|
2292 | static pending(handler, detected) {
|
2293 | return new TraitImpl(handler, detected);
|
2294 | }
|
2295 | };
|
2296 |
|
2297 |
|
2298 | var TraitCompiler = class {
|
2299 | constructor(handlers, reflector, perf, incrementalBuild, compileNonExportedClasses, compilationMode, dtsTransforms, semanticDepGraphUpdater, sourceFileTypeIdentifier) {
|
2300 | this.handlers = handlers;
|
2301 | this.reflector = reflector;
|
2302 | this.perf = perf;
|
2303 | this.incrementalBuild = incrementalBuild;
|
2304 | this.compileNonExportedClasses = compileNonExportedClasses;
|
2305 | this.compilationMode = compilationMode;
|
2306 | this.dtsTransforms = dtsTransforms;
|
2307 | this.semanticDepGraphUpdater = semanticDepGraphUpdater;
|
2308 | this.sourceFileTypeIdentifier = sourceFileTypeIdentifier;
|
2309 | this.classes = new Map();
|
2310 | this.fileToClasses = new Map();
|
2311 | this.filesWithoutTraits = new Set();
|
2312 | this.reexportMap = new Map();
|
2313 | this.handlersByName = new Map();
|
2314 | for (const handler of handlers) {
|
2315 | this.handlersByName.set(handler.name, handler);
|
2316 | }
|
2317 | }
|
2318 | analyzeSync(sf) {
|
2319 | this.analyze(sf, false);
|
2320 | }
|
2321 | analyzeAsync(sf) {
|
2322 | return this.analyze(sf, true);
|
2323 | }
|
2324 | analyze(sf, preanalyze) {
|
2325 | if (sf.isDeclarationFile || this.sourceFileTypeIdentifier.isShim(sf) || this.sourceFileTypeIdentifier.isResource(sf)) {
|
2326 | return void 0;
|
2327 | }
|
2328 | const promises = [];
|
2329 | const priorWork = this.incrementalBuild.priorAnalysisFor(sf);
|
2330 | if (priorWork !== null) {
|
2331 | this.perf.eventCount(PerfEvent.SourceFileReuseAnalysis);
|
2332 | if (priorWork.length > 0) {
|
2333 | for (const priorRecord of priorWork) {
|
2334 | this.adopt(priorRecord);
|
2335 | }
|
2336 | this.perf.eventCount(PerfEvent.TraitReuseAnalysis, priorWork.length);
|
2337 | } else {
|
2338 | this.filesWithoutTraits.add(sf);
|
2339 | }
|
2340 | return;
|
2341 | }
|
2342 | const visit2 = (node) => {
|
2343 | if (this.reflector.isClass(node)) {
|
2344 | this.analyzeClass(node, preanalyze ? promises : null);
|
2345 | }
|
2346 | ts9.forEachChild(node, visit2);
|
2347 | };
|
2348 | visit2(sf);
|
2349 | if (!this.fileToClasses.has(sf)) {
|
2350 | this.filesWithoutTraits.add(sf);
|
2351 | }
|
2352 | if (preanalyze && promises.length > 0) {
|
2353 | return Promise.all(promises).then(() => void 0);
|
2354 | } else {
|
2355 | return void 0;
|
2356 | }
|
2357 | }
|
2358 | recordFor(clazz) {
|
2359 | if (this.classes.has(clazz)) {
|
2360 | return this.classes.get(clazz);
|
2361 | } else {
|
2362 | return null;
|
2363 | }
|
2364 | }
|
2365 | recordsFor(sf) {
|
2366 | if (!this.fileToClasses.has(sf)) {
|
2367 | return null;
|
2368 | }
|
2369 | const records = [];
|
2370 | for (const clazz of this.fileToClasses.get(sf)) {
|
2371 | records.push(this.classes.get(clazz));
|
2372 | }
|
2373 | return records;
|
2374 | }
|
2375 | getAnalyzedRecords() {
|
2376 | const result = new Map();
|
2377 | for (const [sf, classes] of this.fileToClasses) {
|
2378 | const records = [];
|
2379 | for (const clazz of classes) {
|
2380 | records.push(this.classes.get(clazz));
|
2381 | }
|
2382 | result.set(sf, records);
|
2383 | }
|
2384 | for (const sf of this.filesWithoutTraits) {
|
2385 | result.set(sf, []);
|
2386 | }
|
2387 | return result;
|
2388 | }
|
2389 | adopt(priorRecord) {
|
2390 | const record = {
|
2391 | hasPrimaryHandler: priorRecord.hasPrimaryHandler,
|
2392 | hasWeakHandlers: priorRecord.hasWeakHandlers,
|
2393 | metaDiagnostics: priorRecord.metaDiagnostics,
|
2394 | node: priorRecord.node,
|
2395 | traits: []
|
2396 | };
|
2397 | for (const priorTrait of priorRecord.traits) {
|
2398 | const handler = this.handlersByName.get(priorTrait.handler.name);
|
2399 | let trait = Trait.pending(handler, priorTrait.detected);
|
2400 | if (priorTrait.state === TraitState.Analyzed || priorTrait.state === TraitState.Resolved) {
|
2401 | const symbol = this.makeSymbolForTrait(handler, record.node, priorTrait.analysis);
|
2402 | trait = trait.toAnalyzed(priorTrait.analysis, priorTrait.analysisDiagnostics, symbol);
|
2403 | if (trait.analysis !== null && trait.handler.register !== void 0) {
|
2404 | trait.handler.register(record.node, trait.analysis);
|
2405 | }
|
2406 | } else if (priorTrait.state === TraitState.Skipped) {
|
2407 | trait = trait.toSkipped();
|
2408 | }
|
2409 | record.traits.push(trait);
|
2410 | }
|
2411 | this.classes.set(record.node, record);
|
2412 | const sf = record.node.getSourceFile();
|
2413 | if (!this.fileToClasses.has(sf)) {
|
2414 | this.fileToClasses.set(sf, new Set());
|
2415 | }
|
2416 | this.fileToClasses.get(sf).add(record.node);
|
2417 | }
|
2418 | scanClassForTraits(clazz) {
|
2419 | if (!this.compileNonExportedClasses && !this.reflector.isStaticallyExported(clazz)) {
|
2420 | return null;
|
2421 | }
|
2422 | const decorators = this.reflector.getDecoratorsOfDeclaration(clazz);
|
2423 | return this.detectTraits(clazz, decorators);
|
2424 | }
|
2425 | detectTraits(clazz, decorators) {
|
2426 | let record = this.recordFor(clazz);
|
2427 | let foundTraits = [];
|
2428 | for (const handler of this.handlers) {
|
2429 | const result = handler.detect(clazz, decorators);
|
2430 | if (result === void 0) {
|
2431 | continue;
|
2432 | }
|
2433 | const isPrimaryHandler = handler.precedence === HandlerPrecedence.PRIMARY;
|
2434 | const isWeakHandler = handler.precedence === HandlerPrecedence.WEAK;
|
2435 | const trait = Trait.pending(handler, result);
|
2436 | foundTraits.push(trait);
|
2437 | if (record === null) {
|
2438 | record = {
|
2439 | node: clazz,
|
2440 | traits: [trait],
|
2441 | metaDiagnostics: null,
|
2442 | hasPrimaryHandler: isPrimaryHandler,
|
2443 | hasWeakHandlers: isWeakHandler
|
2444 | };
|
2445 | this.classes.set(clazz, record);
|
2446 | const sf = clazz.getSourceFile();
|
2447 | if (!this.fileToClasses.has(sf)) {
|
2448 | this.fileToClasses.set(sf, new Set());
|
2449 | }
|
2450 | this.fileToClasses.get(sf).add(clazz);
|
2451 | } else {
|
2452 | if (!isWeakHandler && record.hasWeakHandlers) {
|
2453 | record.traits = record.traits.filter((field) => field.handler.precedence !== HandlerPrecedence.WEAK);
|
2454 | record.hasWeakHandlers = false;
|
2455 | } else if (isWeakHandler && !record.hasWeakHandlers) {
|
2456 | continue;
|
2457 | }
|
2458 | if (isPrimaryHandler && record.hasPrimaryHandler) {
|
2459 | record.metaDiagnostics = [{
|
2460 | category: ts9.DiagnosticCategory.Error,
|
2461 | code: Number("-99" + ErrorCode.DECORATOR_COLLISION),
|
2462 | file: getSourceFile(clazz),
|
2463 | start: clazz.getStart(void 0, false),
|
2464 | length: clazz.getWidth(),
|
2465 | messageText: "Two incompatible decorators on class"
|
2466 | }];
|
2467 | record.traits = foundTraits = [];
|
2468 | break;
|
2469 | }
|
2470 | record.traits.push(trait);
|
2471 | record.hasPrimaryHandler = record.hasPrimaryHandler || isPrimaryHandler;
|
2472 | }
|
2473 | }
|
2474 | return foundTraits.length > 0 ? foundTraits : null;
|
2475 | }
|
2476 | makeSymbolForTrait(handler, decl, analysis) {
|
2477 | if (analysis === null) {
|
2478 | return null;
|
2479 | }
|
2480 | const symbol = handler.symbol(decl, analysis);
|
2481 | if (symbol !== null && this.semanticDepGraphUpdater !== null) {
|
2482 | const isPrimary = handler.precedence === HandlerPrecedence.PRIMARY;
|
2483 | if (!isPrimary) {
|
2484 | throw new Error(`AssertionError: ${handler.name} returned a symbol but is not a primary handler.`);
|
2485 | }
|
2486 | this.semanticDepGraphUpdater.registerSymbol(symbol);
|
2487 | }
|
2488 | return symbol;
|
2489 | }
|
2490 | analyzeClass(clazz, preanalyzeQueue) {
|
2491 | const traits = this.scanClassForTraits(clazz);
|
2492 | if (traits === null) {
|
2493 | return;
|
2494 | }
|
2495 | for (const trait of traits) {
|
2496 | const analyze = () => this.analyzeTrait(clazz, trait);
|
2497 | let preanalysis = null;
|
2498 | if (preanalyzeQueue !== null && trait.handler.preanalyze !== void 0) {
|
2499 | try {
|
2500 | preanalysis = trait.handler.preanalyze(clazz, trait.detected.metadata) || null;
|
2501 | } catch (err) {
|
2502 | if (err instanceof FatalDiagnosticError) {
|
2503 | trait.toAnalyzed(null, [err.toDiagnostic()], null);
|
2504 | return;
|
2505 | } else {
|
2506 | throw err;
|
2507 | }
|
2508 | }
|
2509 | }
|
2510 | if (preanalysis !== null) {
|
2511 | preanalyzeQueue.push(preanalysis.then(analyze));
|
2512 | } else {
|
2513 | analyze();
|
2514 | }
|
2515 | }
|
2516 | }
|
2517 | analyzeTrait(clazz, trait, flags) {
|
2518 | var _a, _b, _c;
|
2519 | if (trait.state !== TraitState.Pending) {
|
2520 | throw new Error(`Attempt to analyze trait of ${clazz.name.text} in state ${TraitState[trait.state]} (expected DETECTED)`);
|
2521 | }
|
2522 | this.perf.eventCount(PerfEvent.TraitAnalyze);
|
2523 | let result;
|
2524 | try {
|
2525 | result = trait.handler.analyze(clazz, trait.detected.metadata, flags);
|
2526 | } catch (err) {
|
2527 | if (err instanceof FatalDiagnosticError) {
|
2528 | trait.toAnalyzed(null, [err.toDiagnostic()], null);
|
2529 | return;
|
2530 | } else {
|
2531 | throw err;
|
2532 | }
|
2533 | }
|
2534 | const symbol = this.makeSymbolForTrait(trait.handler, clazz, (_a = result.analysis) != null ? _a : null);
|
2535 | if (result.analysis !== void 0 && trait.handler.register !== void 0) {
|
2536 | trait.handler.register(clazz, result.analysis);
|
2537 | }
|
2538 | trait = trait.toAnalyzed((_b = result.analysis) != null ? _b : null, (_c = result.diagnostics) != null ? _c : null, symbol);
|
2539 | }
|
2540 | resolve() {
|
2541 | var _a, _b;
|
2542 | const classes = Array.from(this.classes.keys());
|
2543 | for (const clazz of classes) {
|
2544 | const record = this.classes.get(clazz);
|
2545 | for (let trait of record.traits) {
|
2546 | const handler = trait.handler;
|
2547 | switch (trait.state) {
|
2548 | case TraitState.Skipped:
|
2549 | continue;
|
2550 | case TraitState.Pending:
|
2551 | throw new Error(`Resolving a trait that hasn't been analyzed: ${clazz.name.text} / ${Object.getPrototypeOf(trait.handler).constructor.name}`);
|
2552 | case TraitState.Resolved:
|
2553 | throw new Error(`Resolving an already resolved trait`);
|
2554 | }
|
2555 | if (trait.analysis === null) {
|
2556 | continue;
|
2557 | }
|
2558 | if (handler.resolve === void 0) {
|
2559 | trait = trait.toResolved(null, null);
|
2560 | continue;
|
2561 | }
|
2562 | let result;
|
2563 | try {
|
2564 | result = handler.resolve(clazz, trait.analysis, trait.symbol);
|
2565 | } catch (err) {
|
2566 | if (err instanceof FatalDiagnosticError) {
|
2567 | trait = trait.toResolved(null, [err.toDiagnostic()]);
|
2568 | continue;
|
2569 | } else {
|
2570 | throw err;
|
2571 | }
|
2572 | }
|
2573 | trait = trait.toResolved((_a = result.data) != null ? _a : null, (_b = result.diagnostics) != null ? _b : null);
|
2574 | if (result.reexports !== void 0) {
|
2575 | const fileName = clazz.getSourceFile().fileName;
|
2576 | if (!this.reexportMap.has(fileName)) {
|
2577 | this.reexportMap.set(fileName, new Map());
|
2578 | }
|
2579 | const fileReexports = this.reexportMap.get(fileName);
|
2580 | for (const reexport of result.reexports) {
|
2581 | fileReexports.set(reexport.asAlias, [reexport.fromModule, reexport.symbolName]);
|
2582 | }
|
2583 | }
|
2584 | }
|
2585 | }
|
2586 | }
|
2587 | typeCheck(sf, ctx) {
|
2588 | if (!this.fileToClasses.has(sf)) {
|
2589 | return;
|
2590 | }
|
2591 | for (const clazz of this.fileToClasses.get(sf)) {
|
2592 | const record = this.classes.get(clazz);
|
2593 | for (const trait of record.traits) {
|
2594 | if (trait.state !== TraitState.Resolved) {
|
2595 | continue;
|
2596 | } else if (trait.handler.typeCheck === void 0) {
|
2597 | continue;
|
2598 | }
|
2599 | if (trait.resolution !== null) {
|
2600 | trait.handler.typeCheck(ctx, clazz, trait.analysis, trait.resolution);
|
2601 | }
|
2602 | }
|
2603 | }
|
2604 | }
|
2605 | extendedTemplateCheck(sf, extendedTemplateChecker) {
|
2606 | const classes = this.fileToClasses.get(sf);
|
2607 | if (classes === void 0) {
|
2608 | return [];
|
2609 | }
|
2610 | const diagnostics = [];
|
2611 | for (const clazz of classes) {
|
2612 | if (!isNamedClassDeclaration(clazz)) {
|
2613 | continue;
|
2614 | }
|
2615 | const record = this.classes.get(clazz);
|
2616 | for (const trait of record.traits) {
|
2617 | if (trait.handler.extendedTemplateCheck === void 0) {
|
2618 | continue;
|
2619 | }
|
2620 | diagnostics.push(...trait.handler.extendedTemplateCheck(clazz, extendedTemplateChecker));
|
2621 | }
|
2622 | }
|
2623 | return diagnostics;
|
2624 | }
|
2625 | index(ctx) {
|
2626 | for (const clazz of this.classes.keys()) {
|
2627 | const record = this.classes.get(clazz);
|
2628 | for (const trait of record.traits) {
|
2629 | if (trait.state !== TraitState.Resolved) {
|
2630 | continue;
|
2631 | } else if (trait.handler.index === void 0) {
|
2632 | continue;
|
2633 | }
|
2634 | if (trait.resolution !== null) {
|
2635 | trait.handler.index(ctx, clazz, trait.analysis, trait.resolution);
|
2636 | }
|
2637 | }
|
2638 | }
|
2639 | }
|
2640 | xi18n(bundle) {
|
2641 | for (const clazz of this.classes.keys()) {
|
2642 | const record = this.classes.get(clazz);
|
2643 | for (const trait of record.traits) {
|
2644 | if (trait.state !== TraitState.Analyzed && trait.state !== TraitState.Resolved) {
|
2645 | continue;
|
2646 | } else if (trait.handler.xi18n === void 0) {
|
2647 | continue;
|
2648 | }
|
2649 | if (trait.analysis !== null) {
|
2650 | trait.handler.xi18n(bundle, clazz, trait.analysis);
|
2651 | }
|
2652 | }
|
2653 | }
|
2654 | }
|
2655 | updateResources(clazz) {
|
2656 | if (!this.reflector.isClass(clazz) || !this.classes.has(clazz)) {
|
2657 | return;
|
2658 | }
|
2659 | const record = this.classes.get(clazz);
|
2660 | for (const trait of record.traits) {
|
2661 | if (trait.state !== TraitState.Resolved || trait.handler.updateResources === void 0) {
|
2662 | continue;
|
2663 | }
|
2664 | trait.handler.updateResources(clazz, trait.analysis, trait.resolution);
|
2665 | }
|
2666 | }
|
2667 | compile(clazz, constantPool) {
|
2668 | const original = ts9.getOriginalNode(clazz);
|
2669 | if (!this.reflector.isClass(clazz) || !this.reflector.isClass(original) || !this.classes.has(original)) {
|
2670 | return null;
|
2671 | }
|
2672 | const record = this.classes.get(original);
|
2673 | let res = [];
|
2674 | for (const trait of record.traits) {
|
2675 | if (trait.state !== TraitState.Resolved || trait.analysisDiagnostics !== null || trait.resolveDiagnostics !== null) {
|
2676 | continue;
|
2677 | }
|
2678 | let compileRes;
|
2679 | if (this.compilationMode === CompilationMode.PARTIAL && trait.handler.compilePartial !== void 0) {
|
2680 | compileRes = trait.handler.compilePartial(clazz, trait.analysis, trait.resolution);
|
2681 | } else {
|
2682 | compileRes = trait.handler.compileFull(clazz, trait.analysis, trait.resolution, constantPool);
|
2683 | }
|
2684 | const compileMatchRes = compileRes;
|
2685 | if (Array.isArray(compileMatchRes)) {
|
2686 | for (const result of compileMatchRes) {
|
2687 | if (!res.some((r) => r.name === result.name)) {
|
2688 | res.push(result);
|
2689 | }
|
2690 | }
|
2691 | } else if (!res.some((result) => result.name === compileMatchRes.name)) {
|
2692 | res.push(compileMatchRes);
|
2693 | }
|
2694 | }
|
2695 | this.dtsTransforms.getIvyDeclarationTransform(original.getSourceFile()).addFields(original, res);
|
2696 | return res.length > 0 ? res : null;
|
2697 | }
|
2698 | decoratorsFor(node) {
|
2699 | const original = ts9.getOriginalNode(node);
|
2700 | if (!this.reflector.isClass(original) || !this.classes.has(original)) {
|
2701 | return [];
|
2702 | }
|
2703 | const record = this.classes.get(original);
|
2704 | const decorators = [];
|
2705 | for (const trait of record.traits) {
|
2706 | if (trait.state !== TraitState.Resolved) {
|
2707 | continue;
|
2708 | }
|
2709 | if (trait.detected.trigger !== null && ts9.isDecorator(trait.detected.trigger)) {
|
2710 | decorators.push(trait.detected.trigger);
|
2711 | }
|
2712 | }
|
2713 | return decorators;
|
2714 | }
|
2715 | get diagnostics() {
|
2716 | const diagnostics = [];
|
2717 | for (const clazz of this.classes.keys()) {
|
2718 | const record = this.classes.get(clazz);
|
2719 | if (record.metaDiagnostics !== null) {
|
2720 | diagnostics.push(...record.metaDiagnostics);
|
2721 | }
|
2722 | for (const trait of record.traits) {
|
2723 | if ((trait.state === TraitState.Analyzed || trait.state === TraitState.Resolved) && trait.analysisDiagnostics !== null) {
|
2724 | diagnostics.push(...trait.analysisDiagnostics);
|
2725 | }
|
2726 | if (trait.state === TraitState.Resolved && trait.resolveDiagnostics !== null) {
|
2727 | diagnostics.push(...trait.resolveDiagnostics);
|
2728 | }
|
2729 | }
|
2730 | }
|
2731 | return diagnostics;
|
2732 | }
|
2733 | get exportStatements() {
|
2734 | return this.reexportMap;
|
2735 | }
|
2736 | };
|
2737 |
|
2738 |
|
2739 | import ts11 from "typescript";
|
2740 |
|
2741 |
|
2742 | import ts10 from "typescript";
|
2743 | function addImports(importManager, sf, extraStatements = []) {
|
2744 | const addedImports = importManager.getAllImports(sf.fileName).map((i) => {
|
2745 | const qualifier = ts10.createIdentifier(i.qualifier.text);
|
2746 | const importClause = ts10.createImportClause(void 0, ts10.createNamespaceImport(qualifier));
|
2747 | const decl = ts10.createImportDeclaration(void 0, void 0, importClause, ts10.createLiteral(i.specifier));
|
2748 | ts10.setOriginalNode(i.qualifier, decl);
|
2749 | return decl;
|
2750 | });
|
2751 | const existingImports = sf.statements.filter((stmt) => isImportStatement(stmt));
|
2752 | const body = sf.statements.filter((stmt) => !isImportStatement(stmt));
|
2753 | if (addedImports.length > 0) {
|
2754 | const fileoverviewAnchorStmt = ts10.createNotEmittedStatement(sf);
|
2755 | return ts10.updateSourceFileNode(sf, ts10.createNodeArray([
|
2756 | fileoverviewAnchorStmt,
|
2757 | ...existingImports,
|
2758 | ...addedImports,
|
2759 | ...extraStatements,
|
2760 | ...body
|
2761 | ]));
|
2762 | }
|
2763 | return sf;
|
2764 | }
|
2765 | function isImportStatement(stmt) {
|
2766 | return ts10.isImportDeclaration(stmt) || ts10.isImportEqualsDeclaration(stmt) || ts10.isNamespaceImport(stmt);
|
2767 | }
|
2768 |
|
2769 |
|
2770 | var DtsTransformRegistry = class {
|
2771 | constructor() {
|
2772 | this.ivyDeclarationTransforms = new Map();
|
2773 | }
|
2774 | getIvyDeclarationTransform(sf) {
|
2775 | if (!this.ivyDeclarationTransforms.has(sf)) {
|
2776 | this.ivyDeclarationTransforms.set(sf, new IvyDeclarationDtsTransform());
|
2777 | }
|
2778 | return this.ivyDeclarationTransforms.get(sf);
|
2779 | }
|
2780 | getAllTransforms(sf) {
|
2781 | if (!sf.isDeclarationFile) {
|
2782 | return null;
|
2783 | }
|
2784 | const originalSf = ts11.getOriginalNode(sf);
|
2785 | let transforms = null;
|
2786 | if (this.ivyDeclarationTransforms.has(originalSf)) {
|
2787 | transforms = [];
|
2788 | transforms.push(this.ivyDeclarationTransforms.get(originalSf));
|
2789 | }
|
2790 | return transforms;
|
2791 | }
|
2792 | };
|
2793 | function declarationTransformFactory(transformRegistry, importRewriter, importPrefix) {
|
2794 | return (context) => {
|
2795 | const transformer = new DtsTransformer(context, importRewriter, importPrefix);
|
2796 | return (fileOrBundle) => {
|
2797 | if (ts11.isBundle(fileOrBundle)) {
|
2798 | return fileOrBundle;
|
2799 | }
|
2800 | const transforms = transformRegistry.getAllTransforms(fileOrBundle);
|
2801 | if (transforms === null) {
|
2802 | return fileOrBundle;
|
2803 | }
|
2804 | return transformer.transform(fileOrBundle, transforms);
|
2805 | };
|
2806 | };
|
2807 | }
|
2808 | var DtsTransformer = class {
|
2809 | constructor(ctx, importRewriter, importPrefix) {
|
2810 | this.ctx = ctx;
|
2811 | this.importRewriter = importRewriter;
|
2812 | this.importPrefix = importPrefix;
|
2813 | }
|
2814 | transform(sf, transforms) {
|
2815 | const imports = new ImportManager(this.importRewriter, this.importPrefix);
|
2816 | const visitor = (node) => {
|
2817 | if (ts11.isClassDeclaration(node)) {
|
2818 | return this.transformClassDeclaration(node, transforms, imports);
|
2819 | } else if (ts11.isFunctionDeclaration(node)) {
|
2820 | return this.transformFunctionDeclaration(node, transforms, imports);
|
2821 | } else {
|
2822 | return ts11.visitEachChild(node, visitor, this.ctx);
|
2823 | }
|
2824 | };
|
2825 | sf = ts11.visitNode(sf, visitor);
|
2826 | return addImports(imports, sf);
|
2827 | }
|
2828 | transformClassDeclaration(clazz, transforms, imports) {
|
2829 | let elements = clazz.members;
|
2830 | let elementsChanged = false;
|
2831 | for (const transform of transforms) {
|
2832 | if (transform.transformClassElement !== void 0) {
|
2833 | for (let i = 0; i < elements.length; i++) {
|
2834 | const res = transform.transformClassElement(elements[i], imports);
|
2835 | if (res !== elements[i]) {
|
2836 | if (!elementsChanged) {
|
2837 | elements = [...elements];
|
2838 | elementsChanged = true;
|
2839 | }
|
2840 | elements[i] = res;
|
2841 | }
|
2842 | }
|
2843 | }
|
2844 | }
|
2845 | let newClazz = clazz;
|
2846 | for (const transform of transforms) {
|
2847 | if (transform.transformClass !== void 0) {
|
2848 | const inputMembers = clazz === newClazz ? elements : newClazz.members;
|
2849 | newClazz = transform.transformClass(newClazz, inputMembers, imports);
|
2850 | }
|
2851 | }
|
2852 | if (elementsChanged && clazz === newClazz) {
|
2853 | newClazz = ts11.updateClassDeclaration(clazz, clazz.decorators, clazz.modifiers, clazz.name, clazz.typeParameters, clazz.heritageClauses, elements);
|
2854 | }
|
2855 | return newClazz;
|
2856 | }
|
2857 | transformFunctionDeclaration(declaration, transforms, imports) {
|
2858 | let newDecl = declaration;
|
2859 | for (const transform of transforms) {
|
2860 | if (transform.transformFunctionDeclaration !== void 0) {
|
2861 | newDecl = transform.transformFunctionDeclaration(newDecl, imports);
|
2862 | }
|
2863 | }
|
2864 | return newDecl;
|
2865 | }
|
2866 | };
|
2867 | var IvyDeclarationDtsTransform = class {
|
2868 | constructor() {
|
2869 | this.declarationFields = new Map();
|
2870 | }
|
2871 | addFields(decl, fields) {
|
2872 | this.declarationFields.set(decl, fields);
|
2873 | }
|
2874 | transformClass(clazz, members, imports) {
|
2875 | const original = ts11.getOriginalNode(clazz);
|
2876 | if (!this.declarationFields.has(original)) {
|
2877 | return clazz;
|
2878 | }
|
2879 | const fields = this.declarationFields.get(original);
|
2880 | const newMembers = fields.map((decl) => {
|
2881 | const modifiers = [ts11.createModifier(ts11.SyntaxKind.StaticKeyword)];
|
2882 | const typeRef = translateType(decl.type, imports);
|
2883 | markForEmitAsSingleLine(typeRef);
|
2884 | return ts11.createProperty(void 0, modifiers, decl.name, void 0, typeRef, void 0);
|
2885 | });
|
2886 | return ts11.updateClassDeclaration(clazz, clazz.decorators, clazz.modifiers, clazz.name, clazz.typeParameters, clazz.heritageClauses, [...members, ...newMembers]);
|
2887 | }
|
2888 | };
|
2889 | function markForEmitAsSingleLine(node) {
|
2890 | ts11.setEmitFlags(node, ts11.EmitFlags.SingleLine);
|
2891 | ts11.forEachChild(node, markForEmitAsSingleLine);
|
2892 | }
|
2893 |
|
2894 |
|
2895 | import { ConstantPool } from "@angular/compiler";
|
2896 | import ts13 from "typescript";
|
2897 |
|
2898 |
|
2899 | import ts12 from "typescript";
|
2900 | function visit(node, visitor, context) {
|
2901 | return visitor._visit(node, context);
|
2902 | }
|
2903 | var Visitor = class {
|
2904 | constructor() {
|
2905 | this._before = new Map();
|
2906 | this._after = new Map();
|
2907 | }
|
2908 | _visitListEntryNode(node, visitor) {
|
2909 | const result = visitor(node);
|
2910 | if (result.before !== void 0) {
|
2911 | this._before.set(result.node, result.before);
|
2912 | }
|
2913 | if (result.after !== void 0) {
|
2914 | this._after.set(result.node, result.after);
|
2915 | }
|
2916 | return result.node;
|
2917 | }
|
2918 | visitOtherNode(node) {
|
2919 | return node;
|
2920 | }
|
2921 | _visit(node, context) {
|
2922 | let visitedNode = null;
|
2923 | node = ts12.visitEachChild(node, (child) => this._visit(child, context), context);
|
2924 | if (ts12.isClassDeclaration(node)) {
|
2925 | visitedNode = this._visitListEntryNode(node, (node2) => this.visitClassDeclaration(node2));
|
2926 | } else {
|
2927 | visitedNode = this.visitOtherNode(node);
|
2928 | }
|
2929 | if (hasStatements(visitedNode)) {
|
2930 | visitedNode = this._maybeProcessStatements(visitedNode);
|
2931 | }
|
2932 | return visitedNode;
|
2933 | }
|
2934 | _maybeProcessStatements(node) {
|
2935 | if (node.statements.every((stmt) => !this._before.has(stmt) && !this._after.has(stmt))) {
|
2936 | return node;
|
2937 | }
|
2938 | const clone = ts12.getMutableClone(node);
|
2939 | const newStatements = [];
|
2940 | clone.statements.forEach((stmt) => {
|
2941 | if (this._before.has(stmt)) {
|
2942 | newStatements.push(...this._before.get(stmt));
|
2943 | this._before.delete(stmt);
|
2944 | }
|
2945 | newStatements.push(stmt);
|
2946 | if (this._after.has(stmt)) {
|
2947 | newStatements.push(...this._after.get(stmt));
|
2948 | this._after.delete(stmt);
|
2949 | }
|
2950 | });
|
2951 | clone.statements = ts12.createNodeArray(newStatements, node.statements.hasTrailingComma);
|
2952 | return clone;
|
2953 | }
|
2954 | };
|
2955 | function hasStatements(node) {
|
2956 | const block = node;
|
2957 | return block.statements !== void 0 && Array.isArray(block.statements);
|
2958 | }
|
2959 |
|
2960 |
|
2961 | var NO_DECORATORS = new Set();
|
2962 | var CLOSURE_FILE_OVERVIEW_REGEXP = /\s+@fileoverview\s+/i;
|
2963 | function ivyTransformFactory(compilation, reflector, importRewriter, defaultImportTracker, perf, isCore, isClosureCompilerEnabled) {
|
2964 | const recordWrappedNode = createRecorderFn(defaultImportTracker);
|
2965 | return (context) => {
|
2966 | return (file) => {
|
2967 | return perf.inPhase(PerfPhase.Compile, () => transformIvySourceFile(compilation, context, reflector, importRewriter, file, isCore, isClosureCompilerEnabled, recordWrappedNode));
|
2968 | };
|
2969 | };
|
2970 | }
|
2971 | var IvyCompilationVisitor = class extends Visitor {
|
2972 | constructor(compilation, constantPool) {
|
2973 | super();
|
2974 | this.compilation = compilation;
|
2975 | this.constantPool = constantPool;
|
2976 | this.classCompilationMap = new Map();
|
2977 | }
|
2978 | visitClassDeclaration(node) {
|
2979 | const result = this.compilation.compile(node, this.constantPool);
|
2980 | if (result !== null) {
|
2981 | this.classCompilationMap.set(node, result);
|
2982 | }
|
2983 | return { node };
|
2984 | }
|
2985 | };
|
2986 | var IvyTransformationVisitor = class extends Visitor {
|
2987 | constructor(compilation, classCompilationMap, reflector, importManager, recordWrappedNodeExpr, isClosureCompilerEnabled, isCore) {
|
2988 | super();
|
2989 | this.compilation = compilation;
|
2990 | this.classCompilationMap = classCompilationMap;
|
2991 | this.reflector = reflector;
|
2992 | this.importManager = importManager;
|
2993 | this.recordWrappedNodeExpr = recordWrappedNodeExpr;
|
2994 | this.isClosureCompilerEnabled = isClosureCompilerEnabled;
|
2995 | this.isCore = isCore;
|
2996 | }
|
2997 | visitClassDeclaration(node) {
|
2998 | if (!this.classCompilationMap.has(node)) {
|
2999 | return { node };
|
3000 | }
|
3001 | const translateOptions = {
|
3002 | recordWrappedNode: this.recordWrappedNodeExpr,
|
3003 | annotateForClosureCompiler: this.isClosureCompilerEnabled
|
3004 | };
|
3005 | const statements = [];
|
3006 | const members = [...node.members];
|
3007 | for (const field of this.classCompilationMap.get(node)) {
|
3008 | const exprNode = translateExpression(field.initializer, this.importManager, translateOptions);
|
3009 | const property = ts13.createProperty(void 0, [ts13.createToken(ts13.SyntaxKind.StaticKeyword)], field.name, void 0, void 0, exprNode);
|
3010 | if (this.isClosureCompilerEnabled) {
|
3011 | ts13.addSyntheticLeadingComment(property, ts13.SyntaxKind.MultiLineCommentTrivia, "* @nocollapse ", false);
|
3012 | }
|
3013 | field.statements.map((stmt) => translateStatement(stmt, this.importManager, translateOptions)).forEach((stmt) => statements.push(stmt));
|
3014 | members.push(property);
|
3015 | }
|
3016 | node = ts13.updateClassDeclaration(node, maybeFilterDecorator(node.decorators, this.compilation.decoratorsFor(node)), node.modifiers, node.name, node.typeParameters, node.heritageClauses || [], members.map((member) => this._stripAngularDecorators(member)));
|
3017 | return { node, after: statements };
|
3018 | }
|
3019 | _angularCoreDecorators(decl) {
|
3020 | const decorators = this.reflector.getDecoratorsOfDeclaration(decl);
|
3021 | if (decorators === null) {
|
3022 | return NO_DECORATORS;
|
3023 | }
|
3024 | const coreDecorators = decorators.filter((dec) => this.isCore || isFromAngularCore(dec)).map((dec) => dec.node);
|
3025 | if (coreDecorators.length > 0) {
|
3026 | return new Set(coreDecorators);
|
3027 | } else {
|
3028 | return NO_DECORATORS;
|
3029 | }
|
3030 | }
|
3031 | _nonCoreDecoratorsOnly(node) {
|
3032 | if (node.decorators === void 0) {
|
3033 | return void 0;
|
3034 | }
|
3035 | const coreDecorators = this._angularCoreDecorators(node);
|
3036 | if (coreDecorators.size === node.decorators.length) {
|
3037 | return void 0;
|
3038 | } else if (coreDecorators.size === 0) {
|
3039 | return node.decorators;
|
3040 | }
|
3041 | const filtered = node.decorators.filter((dec) => !coreDecorators.has(dec));
|
3042 | if (filtered.length === 0) {
|
3043 | return void 0;
|
3044 | }
|
3045 | const array = ts13.createNodeArray(filtered);
|
3046 | array.pos = node.decorators.pos;
|
3047 | array.end = node.decorators.end;
|
3048 | return array;
|
3049 | }
|
3050 | _stripAngularDecorators(node) {
|
3051 | if (ts13.isParameter(node)) {
|
3052 | node = ts13.updateParameter(node, this._nonCoreDecoratorsOnly(node), node.modifiers, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer);
|
3053 | } else if (ts13.isMethodDeclaration(node) && node.decorators !== void 0) {
|
3054 | node = ts13.updateMethod(node, this._nonCoreDecoratorsOnly(node), node.modifiers, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body);
|
3055 | } else if (ts13.isPropertyDeclaration(node) && node.decorators !== void 0) {
|
3056 | node = ts13.updateProperty(node, this._nonCoreDecoratorsOnly(node), node.modifiers, node.name, node.questionToken, node.type, node.initializer);
|
3057 | } else if (ts13.isGetAccessor(node)) {
|
3058 | node = ts13.updateGetAccessor(node, this._nonCoreDecoratorsOnly(node), node.modifiers, node.name, node.parameters, node.type, node.body);
|
3059 | } else if (ts13.isSetAccessor(node)) {
|
3060 | node = ts13.updateSetAccessor(node, this._nonCoreDecoratorsOnly(node), node.modifiers, node.name, node.parameters, node.body);
|
3061 | } else if (ts13.isConstructorDeclaration(node)) {
|
3062 | const parameters = node.parameters.map((param) => this._stripAngularDecorators(param));
|
3063 | node = ts13.updateConstructor(node, node.decorators, node.modifiers, parameters, node.body);
|
3064 | }
|
3065 | return node;
|
3066 | }
|
3067 | };
|
3068 | function transformIvySourceFile(compilation, context, reflector, importRewriter, file, isCore, isClosureCompilerEnabled, recordWrappedNode) {
|
3069 | const constantPool = new ConstantPool(isClosureCompilerEnabled);
|
3070 | const importManager = new ImportManager(importRewriter);
|
3071 | const compilationVisitor = new IvyCompilationVisitor(compilation, constantPool);
|
3072 | visit(file, compilationVisitor, context);
|
3073 | const transformationVisitor = new IvyTransformationVisitor(compilation, compilationVisitor.classCompilationMap, reflector, importManager, recordWrappedNode, isClosureCompilerEnabled, isCore);
|
3074 | let sf = visit(file, transformationVisitor, context);
|
3075 | const downlevelTranslatedCode = getLocalizeCompileTarget(context) < ts13.ScriptTarget.ES2015;
|
3076 | const constants = constantPool.statements.map((stmt) => translateStatement(stmt, importManager, {
|
3077 | recordWrappedNode,
|
3078 | downlevelTaggedTemplates: downlevelTranslatedCode,
|
3079 | downlevelVariableDeclarations: downlevelTranslatedCode,
|
3080 | annotateForClosureCompiler: isClosureCompilerEnabled
|
3081 | }));
|
3082 | const fileOverviewMeta = isClosureCompilerEnabled ? getFileOverviewComment(sf.statements) : null;
|
3083 | sf = addImports(importManager, sf, constants);
|
3084 | if (fileOverviewMeta !== null) {
|
3085 | setFileOverviewComment(sf, fileOverviewMeta);
|
3086 | }
|
3087 | return sf;
|
3088 | }
|
3089 | function getLocalizeCompileTarget(context) {
|
3090 | const target = context.getCompilerOptions().target || ts13.ScriptTarget.ES2015;
|
3091 | return target !== ts13.ScriptTarget.JSON ? target : ts13.ScriptTarget.ES2015;
|
3092 | }
|
3093 | function getFileOverviewComment(statements) {
|
3094 | if (statements.length > 0) {
|
3095 | const host = statements[0];
|
3096 | let trailing = false;
|
3097 | let comments = ts13.getSyntheticLeadingComments(host);
|
3098 | if (!comments || comments.length === 0) {
|
3099 | trailing = true;
|
3100 | comments = ts13.getSyntheticTrailingComments(host);
|
3101 | }
|
3102 | if (comments && comments.length > 0 && CLOSURE_FILE_OVERVIEW_REGEXP.test(comments[0].text)) {
|
3103 | return { comments, host, trailing };
|
3104 | }
|
3105 | }
|
3106 | return null;
|
3107 | }
|
3108 | function setFileOverviewComment(sf, fileoverview) {
|
3109 | const { comments, host, trailing } = fileoverview;
|
3110 | if (sf.statements.length > 0 && host !== sf.statements[0]) {
|
3111 | if (trailing) {
|
3112 | ts13.setSyntheticTrailingComments(host, void 0);
|
3113 | } else {
|
3114 | ts13.setSyntheticLeadingComments(host, void 0);
|
3115 | }
|
3116 | ts13.setSyntheticLeadingComments(sf.statements[0], comments);
|
3117 | }
|
3118 | }
|
3119 | function maybeFilterDecorator(decorators, toRemove) {
|
3120 | if (decorators === void 0) {
|
3121 | return void 0;
|
3122 | }
|
3123 | const filtered = decorators.filter((dec) => toRemove.find((decToRemove) => ts13.getOriginalNode(dec) === decToRemove) === void 0);
|
3124 | if (filtered.length === 0) {
|
3125 | return void 0;
|
3126 | }
|
3127 | return ts13.createNodeArray(filtered);
|
3128 | }
|
3129 | function isFromAngularCore(decorator) {
|
3130 | return decorator.import !== null && decorator.import.from === "@angular/core";
|
3131 | }
|
3132 | function createRecorderFn(defaultImportTracker) {
|
3133 | return (node) => {
|
3134 | const importDecl = getDefaultImportDeclaration(node);
|
3135 | if (importDecl !== null) {
|
3136 | defaultImportTracker.recordUsedImport(importDecl);
|
3137 | }
|
3138 | };
|
3139 | }
|
3140 |
|
3141 |
|
3142 | import ts14 from "typescript";
|
3143 | function createValueHasWrongTypeError(node, value, messageText) {
|
3144 | var _a;
|
3145 | let chainedMessage;
|
3146 | let relatedInformation;
|
3147 | if (value instanceof DynamicValue) {
|
3148 | chainedMessage = "Value could not be determined statically.";
|
3149 | relatedInformation = traceDynamicValue(node, value);
|
3150 | } else if (value instanceof Reference) {
|
3151 | const target = value.debugName !== null ? `'${value.debugName}'` : "an anonymous declaration";
|
3152 | chainedMessage = `Value is a reference to ${target}.`;
|
3153 | const referenceNode = (_a = identifierOfNode(value.node)) != null ? _a : value.node;
|
3154 | relatedInformation = [makeRelatedInformation(referenceNode, "Reference is declared here.")];
|
3155 | } else {
|
3156 | chainedMessage = `Value is of type '${describeResolvedType(value)}'.`;
|
3157 | }
|
3158 | const chain = {
|
3159 | messageText,
|
3160 | category: ts14.DiagnosticCategory.Error,
|
3161 | code: 0,
|
3162 | next: [{
|
3163 | messageText: chainedMessage,
|
3164 | category: ts14.DiagnosticCategory.Message,
|
3165 | code: 0
|
3166 | }]
|
3167 | };
|
3168 | return new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, node, chain, relatedInformation);
|
3169 | }
|
3170 | function getProviderDiagnostics(providerClasses, providersDeclaration, registry) {
|
3171 | const diagnostics = [];
|
3172 | for (const provider of providerClasses) {
|
3173 | if (registry.isInjectable(provider.node)) {
|
3174 | continue;
|
3175 | }
|
3176 | const contextNode = provider.getOriginForDiagnostics(providersDeclaration);
|
3177 | diagnostics.push(makeDiagnostic(ErrorCode.UNDECORATED_PROVIDER, contextNode, `The class '${provider.node.name.text}' cannot be created via dependency injection, as it does not have an Angular decorator. This will result in an error at runtime.
|
3178 |
|
3179 | Either add the @Injectable() decorator to '${provider.node.name.text}', or configure a different provider (such as a provider with 'useFactory').
|
3180 | `, [makeRelatedInformation(provider.node, `'${provider.node.name.text}' is declared here.`)]));
|
3181 | }
|
3182 | return diagnostics;
|
3183 | }
|
3184 | function getDirectiveDiagnostics(node, reader, evaluator, reflector, scopeRegistry, kind) {
|
3185 | let diagnostics = [];
|
3186 | const addDiagnostics = (more) => {
|
3187 | if (more === null) {
|
3188 | return;
|
3189 | } else if (diagnostics === null) {
|
3190 | diagnostics = Array.isArray(more) ? more : [more];
|
3191 | } else if (Array.isArray(more)) {
|
3192 | diagnostics.push(...more);
|
3193 | } else {
|
3194 | diagnostics.push(more);
|
3195 | }
|
3196 | };
|
3197 | const duplicateDeclarations = scopeRegistry.getDuplicateDeclarations(node);
|
3198 | if (duplicateDeclarations !== null) {
|
3199 | addDiagnostics(makeDuplicateDeclarationError(node, duplicateDeclarations, kind));
|
3200 | }
|
3201 | addDiagnostics(checkInheritanceOfDirective(node, reader, reflector, evaluator));
|
3202 | return diagnostics;
|
3203 | }
|
3204 | function getUndecoratedClassWithAngularFeaturesDiagnostic(node) {
|
3205 | return makeDiagnostic(ErrorCode.UNDECORATED_CLASS_USING_ANGULAR_FEATURES, node.name, `Class is using Angular features but is not decorated. Please add an explicit Angular decorator.`);
|
3206 | }
|
3207 | function checkInheritanceOfDirective(node, reader, reflector, evaluator) {
|
3208 | if (!reflector.isClass(node) || reflector.getConstructorParameters(node) !== null) {
|
3209 | return null;
|
3210 | }
|
3211 | let baseClass = readBaseClass(node, reflector, evaluator);
|
3212 | while (baseClass !== null) {
|
3213 | if (baseClass === "dynamic") {
|
3214 | return null;
|
3215 | }
|
3216 | const baseClassMeta = reader.getDirectiveMetadata(baseClass);
|
3217 | if (baseClassMeta !== null) {
|
3218 | return null;
|
3219 | }
|
3220 | const baseClassConstructorParams = reflector.getConstructorParameters(baseClass.node);
|
3221 | const newParentClass = readBaseClass(baseClass.node, reflector, evaluator);
|
3222 | if (baseClassConstructorParams !== null && baseClassConstructorParams.length > 0) {
|
3223 | return getInheritedUndecoratedCtorDiagnostic(node, baseClass, reader);
|
3224 | } else if (baseClassConstructorParams !== null || newParentClass === null) {
|
3225 | return null;
|
3226 | }
|
3227 | baseClass = newParentClass;
|
3228 | }
|
3229 | return null;
|
3230 | }
|
3231 | function getInheritedUndecoratedCtorDiagnostic(node, baseClass, reader) {
|
3232 | const subclassMeta = reader.getDirectiveMetadata(new Reference(node));
|
3233 | const dirOrComp = subclassMeta.isComponent ? "Component" : "Directive";
|
3234 | const baseClassName = baseClass.debugName;
|
3235 | return makeDiagnostic(ErrorCode.DIRECTIVE_INHERITS_UNDECORATED_CTOR, node.name, `The ${dirOrComp.toLowerCase()} ${node.name.text} inherits its constructor from ${baseClassName}, but the latter does not have an Angular decorator of its own. Dependency injection will not be able to resolve the parameters of ${baseClassName}'s constructor. Either add a @Directive decorator to ${baseClassName}, or add an explicit constructor to ${node.name.text}.`);
|
3236 | }
|
3237 |
|
3238 |
|
3239 | import { compileClassMetadata, compileDeclareClassMetadata, compileDeclareDirectiveFromMetadata, compileDirectiveFromMetadata, createMayBeForwardRefExpression, emitDistinctChangesOnlyDefaultValue, ExternalExpr as ExternalExpr3, FactoryTarget, getSafePropertyAccessString, makeBindingParser, parseHostBindings, verifyHostBindings, WrappedNodeExpr as WrappedNodeExpr3 } from "@angular/compiler";
|
3240 | import ts16 from "typescript";
|
3241 |
|
3242 |
|
3243 | import { compileDeclareFactoryFunction, compileFactoryFunction } from "@angular/compiler";
|
3244 | function compileNgFactoryDefField(metadata) {
|
3245 | const res = compileFactoryFunction(metadata);
|
3246 | return { name: "\u0275fac", initializer: res.expression, statements: res.statements, type: res.type };
|
3247 | }
|
3248 | function compileDeclareFactory(metadata) {
|
3249 | const res = compileDeclareFactoryFunction(metadata);
|
3250 | return { name: "\u0275fac", initializer: res.expression, statements: res.statements, type: res.type };
|
3251 | }
|
3252 |
|
3253 |
|
3254 | import { FunctionExpr, LiteralArrayExpr, LiteralExpr as LiteralExpr2, literalMap, ReturnStatement, WrappedNodeExpr as WrappedNodeExpr2 } from "@angular/compiler";
|
3255 | import ts15 from "typescript";
|
3256 | function extractClassMetadata(clazz, reflection, isCore, annotateForClosureCompiler, angularDecoratorTransform = (dec) => dec) {
|
3257 | if (!reflection.isClass(clazz)) {
|
3258 | return null;
|
3259 | }
|
3260 | const id = reflection.getAdjacentNameOfClass(clazz);
|
3261 | const classDecorators = reflection.getDecoratorsOfDeclaration(clazz);
|
3262 | if (classDecorators === null) {
|
3263 | return null;
|
3264 | }
|
3265 | const ngClassDecorators = classDecorators.filter((dec) => isAngularDecorator2(dec, isCore)).map((decorator) => decoratorToMetadata(angularDecoratorTransform(decorator), annotateForClosureCompiler)).map((decorator) => removeIdentifierReferences(decorator, id.text));
|
3266 | if (ngClassDecorators.length === 0) {
|
3267 | return null;
|
3268 | }
|
3269 | const metaDecorators = new WrappedNodeExpr2(ts15.createArrayLiteral(ngClassDecorators));
|
3270 | let metaCtorParameters = null;
|
3271 | const classCtorParameters = reflection.getConstructorParameters(clazz);
|
3272 | if (classCtorParameters !== null) {
|
3273 | const ctorParameters = classCtorParameters.map((param) => ctorParameterToMetadata(param, isCore));
|
3274 | metaCtorParameters = new FunctionExpr([], [
|
3275 | new ReturnStatement(new LiteralArrayExpr(ctorParameters))
|
3276 | ]);
|
3277 | }
|
3278 | let metaPropDecorators = null;
|
3279 | const classMembers = reflection.getMembersOfClass(clazz).filter((member) => !member.isStatic && member.decorators !== null && member.decorators.length > 0);
|
3280 | const duplicateDecoratedMemberNames = classMembers.map((member) => member.name).filter((name, i, arr) => arr.indexOf(name) < i);
|
3281 | if (duplicateDecoratedMemberNames.length > 0) {
|
3282 | throw new Error(`Duplicate decorated properties found on class '${clazz.name.text}': ` + duplicateDecoratedMemberNames.join(", "));
|
3283 | }
|
3284 | const decoratedMembers = classMembers.map((member) => {
|
3285 | var _a;
|
3286 | return classMemberToMetadata((_a = member.nameNode) != null ? _a : member.name, member.decorators, isCore);
|
3287 | });
|
3288 | if (decoratedMembers.length > 0) {
|
3289 | metaPropDecorators = new WrappedNodeExpr2(ts15.createObjectLiteral(decoratedMembers));
|
3290 | }
|
3291 | return {
|
3292 | type: new WrappedNodeExpr2(id),
|
3293 | decorators: metaDecorators,
|
3294 | ctorParameters: metaCtorParameters,
|
3295 | propDecorators: metaPropDecorators
|
3296 | };
|
3297 | }
|
3298 | function ctorParameterToMetadata(param, isCore) {
|
3299 | const type = param.typeValueReference.kind !== 2 ? valueReferenceToExpression(param.typeValueReference) : new LiteralExpr2(void 0);
|
3300 | const mapEntries = [
|
3301 | { key: "type", value: type, quoted: false }
|
3302 | ];
|
3303 | if (param.decorators !== null) {
|
3304 | const ngDecorators = param.decorators.filter((dec) => isAngularDecorator2(dec, isCore)).map((decorator) => decoratorToMetadata(decorator));
|
3305 | const value = new WrappedNodeExpr2(ts15.createArrayLiteral(ngDecorators));
|
3306 | mapEntries.push({ key: "decorators", value, quoted: false });
|
3307 | }
|
3308 | return literalMap(mapEntries);
|
3309 | }
|
3310 | function classMemberToMetadata(name, decorators, isCore) {
|
3311 | const ngDecorators = decorators.filter((dec) => isAngularDecorator2(dec, isCore)).map((decorator) => decoratorToMetadata(decorator));
|
3312 | const decoratorMeta = ts15.createArrayLiteral(ngDecorators);
|
3313 | return ts15.createPropertyAssignment(name, decoratorMeta);
|
3314 | }
|
3315 | function decoratorToMetadata(decorator, wrapFunctionsInParens) {
|
3316 | if (decorator.identifier === null) {
|
3317 | throw new Error("Illegal state: synthesized decorator cannot be emitted in class metadata.");
|
3318 | }
|
3319 | const properties = [
|
3320 | ts15.createPropertyAssignment("type", ts15.getMutableClone(decorator.identifier))
|
3321 | ];
|
3322 | if (decorator.args !== null && decorator.args.length > 0) {
|
3323 | const args = decorator.args.map((arg) => {
|
3324 | const expr = ts15.getMutableClone(arg);
|
3325 | return wrapFunctionsInParens ? wrapFunctionExpressionsInParens(expr) : expr;
|
3326 | });
|
3327 | properties.push(ts15.createPropertyAssignment("args", ts15.createArrayLiteral(args)));
|
3328 | }
|
3329 | return ts15.createObjectLiteral(properties, true);
|
3330 | }
|
3331 | function isAngularDecorator2(decorator, isCore) {
|
3332 | return isCore || decorator.import !== null && decorator.import.from === "@angular/core";
|
3333 | }
|
3334 | function removeIdentifierReferences(node, name) {
|
3335 | const result = ts15.transform(node, [(context) => (root) => ts15.visitNode(root, function walk(current) {
|
3336 | return ts15.isIdentifier(current) && current.text === name ? ts15.createIdentifier(current.text) : ts15.visitEachChild(current, walk, context);
|
3337 | })]);
|
3338 | return result.transformed[0];
|
3339 | }
|
3340 |
|
3341 |
|
3342 | var EMPTY_OBJECT = {};
|
3343 | var FIELD_DECORATORS = [
|
3344 | "Input",
|
3345 | "Output",
|
3346 | "ViewChild",
|
3347 | "ViewChildren",
|
3348 | "ContentChild",
|
3349 | "ContentChildren",
|
3350 | "HostBinding",
|
3351 | "HostListener"
|
3352 | ];
|
3353 | var LIFECYCLE_HOOKS = new Set([
|
3354 | "ngOnChanges",
|
3355 | "ngOnInit",
|
3356 | "ngOnDestroy",
|
3357 | "ngDoCheck",
|
3358 | "ngAfterViewInit",
|
3359 | "ngAfterViewChecked",
|
3360 | "ngAfterContentInit",
|
3361 | "ngAfterContentChecked"
|
3362 | ]);
|
3363 | var DirectiveSymbol = class extends SemanticSymbol {
|
3364 | constructor(decl, selector, inputs, outputs, exportAs, typeCheckMeta, typeParameters) {
|
3365 | super(decl);
|
3366 | this.selector = selector;
|
3367 | this.inputs = inputs;
|
3368 | this.outputs = outputs;
|
3369 | this.exportAs = exportAs;
|
3370 | this.typeCheckMeta = typeCheckMeta;
|
3371 | this.typeParameters = typeParameters;
|
3372 | this.baseClass = null;
|
3373 | }
|
3374 | isPublicApiAffected(previousSymbol) {
|
3375 | if (!(previousSymbol instanceof DirectiveSymbol)) {
|
3376 | return true;
|
3377 | }
|
3378 | return this.selector !== previousSymbol.selector || !isArrayEqual(this.inputs.propertyNames, previousSymbol.inputs.propertyNames) || !isArrayEqual(this.outputs.propertyNames, previousSymbol.outputs.propertyNames) || !isArrayEqual(this.exportAs, previousSymbol.exportAs);
|
3379 | }
|
3380 | isTypeCheckApiAffected(previousSymbol) {
|
3381 | if (this.isPublicApiAffected(previousSymbol)) {
|
3382 | return true;
|
3383 | }
|
3384 | if (!(previousSymbol instanceof DirectiveSymbol)) {
|
3385 | return true;
|
3386 | }
|
3387 | if (!isArrayEqual(Array.from(this.inputs), Array.from(previousSymbol.inputs), isInputMappingEqual) || !isArrayEqual(Array.from(this.outputs), Array.from(previousSymbol.outputs), isInputMappingEqual)) {
|
3388 | return true;
|
3389 | }
|
3390 | if (!areTypeParametersEqual(this.typeParameters, previousSymbol.typeParameters)) {
|
3391 | return true;
|
3392 | }
|
3393 | if (!isTypeCheckMetaEqual(this.typeCheckMeta, previousSymbol.typeCheckMeta)) {
|
3394 | return true;
|
3395 | }
|
3396 | if (!isBaseClassEqual(this.baseClass, previousSymbol.baseClass)) {
|
3397 | return true;
|
3398 | }
|
3399 | return false;
|
3400 | }
|
3401 | };
|
3402 | function isInputMappingEqual(current, previous) {
|
3403 | return current[0] === previous[0] && current[1] === previous[1];
|
3404 | }
|
3405 | function isTypeCheckMetaEqual(current, previous) {
|
3406 | if (current.hasNgTemplateContextGuard !== previous.hasNgTemplateContextGuard) {
|
3407 | return false;
|
3408 | }
|
3409 | if (current.isGeneric !== previous.isGeneric) {
|
3410 | return false;
|
3411 | }
|
3412 | if (!isArrayEqual(current.ngTemplateGuards, previous.ngTemplateGuards, isTemplateGuardEqual)) {
|
3413 | return false;
|
3414 | }
|
3415 | if (!isSetEqual(current.coercedInputFields, previous.coercedInputFields)) {
|
3416 | return false;
|
3417 | }
|
3418 | if (!isSetEqual(current.restrictedInputFields, previous.restrictedInputFields)) {
|
3419 | return false;
|
3420 | }
|
3421 | if (!isSetEqual(current.stringLiteralInputFields, previous.stringLiteralInputFields)) {
|
3422 | return false;
|
3423 | }
|
3424 | if (!isSetEqual(current.undeclaredInputFields, previous.undeclaredInputFields)) {
|
3425 | return false;
|
3426 | }
|
3427 | return true;
|
3428 | }
|
3429 | function isTemplateGuardEqual(current, previous) {
|
3430 | return current.inputName === previous.inputName && current.type === previous.type;
|
3431 | }
|
3432 | function isBaseClassEqual(current, previous) {
|
3433 | if (current === null || previous === null) {
|
3434 | return current === previous;
|
3435 | }
|
3436 | return isSymbolEqual(current, previous);
|
3437 | }
|
3438 | var DirectiveDecoratorHandler = class {
|
3439 | constructor(reflector, evaluator, metaRegistry, scopeRegistry, metaReader, injectableRegistry, isCore, semanticDepGraphUpdater, annotateForClosureCompiler, compileUndecoratedClassesWithAngularFeatures, perf) {
|
3440 | this.reflector = reflector;
|
3441 | this.evaluator = evaluator;
|
3442 | this.metaRegistry = metaRegistry;
|
3443 | this.scopeRegistry = scopeRegistry;
|
3444 | this.metaReader = metaReader;
|
3445 | this.injectableRegistry = injectableRegistry;
|
3446 | this.isCore = isCore;
|
3447 | this.semanticDepGraphUpdater = semanticDepGraphUpdater;
|
3448 | this.annotateForClosureCompiler = annotateForClosureCompiler;
|
3449 | this.compileUndecoratedClassesWithAngularFeatures = compileUndecoratedClassesWithAngularFeatures;
|
3450 | this.perf = perf;
|
3451 | this.precedence = HandlerPrecedence.PRIMARY;
|
3452 | this.name = DirectiveDecoratorHandler.name;
|
3453 | }
|
3454 | detect(node, decorators) {
|
3455 | if (!decorators) {
|
3456 | const angularField = this.findClassFieldWithAngularFeatures(node);
|
3457 | return angularField ? { trigger: angularField.node, decorator: null, metadata: null } : void 0;
|
3458 | } else {
|
3459 | const decorator = findAngularDecorator(decorators, "Directive", this.isCore);
|
3460 | return decorator ? { trigger: decorator.node, decorator, metadata: decorator } : void 0;
|
3461 | }
|
3462 | }
|
3463 | analyze(node, decorator, flags = HandlerFlags.NONE) {
|
3464 | if (this.compileUndecoratedClassesWithAngularFeatures === false && decorator === null) {
|
3465 | return { diagnostics: [getUndecoratedClassWithAngularFeaturesDiagnostic(node)] };
|
3466 | }
|
3467 | this.perf.eventCount(PerfEvent.AnalyzeDirective);
|
3468 | const directiveResult = extractDirectiveMetadata(node, decorator, this.reflector, this.evaluator, this.isCore, flags, this.annotateForClosureCompiler);
|
3469 | if (directiveResult === void 0) {
|
3470 | return {};
|
3471 | }
|
3472 | const analysis = directiveResult.metadata;
|
3473 | let providersRequiringFactory = null;
|
3474 | if (directiveResult !== void 0 && directiveResult.decorator.has("providers")) {
|
3475 | providersRequiringFactory = resolveProvidersRequiringFactory(directiveResult.decorator.get("providers"), this.reflector, this.evaluator);
|
3476 | }
|
3477 | return {
|
3478 | analysis: {
|
3479 | inputs: directiveResult.inputs,
|
3480 | outputs: directiveResult.outputs,
|
3481 | meta: analysis,
|
3482 | classMetadata: extractClassMetadata(node, this.reflector, this.isCore, this.annotateForClosureCompiler),
|
3483 | baseClass: readBaseClass(node, this.reflector, this.evaluator),
|
3484 | typeCheckMeta: extractDirectiveTypeCheckMeta(node, directiveResult.inputs, this.reflector),
|
3485 | providersRequiringFactory,
|
3486 | isPoisoned: false,
|
3487 | isStructural: directiveResult.isStructural
|
3488 | }
|
3489 | };
|
3490 | }
|
3491 | symbol(node, analysis) {
|
3492 | const typeParameters = extractSemanticTypeParameters(node);
|
3493 | return new DirectiveSymbol(node, analysis.meta.selector, analysis.inputs, analysis.outputs, analysis.meta.exportAs, analysis.typeCheckMeta, typeParameters);
|
3494 | }
|
3495 | register(node, analysis) {
|
3496 | const ref = new Reference(node);
|
3497 | this.metaRegistry.registerDirectiveMetadata(__spreadProps(__spreadValues({
|
3498 | type: MetaType.Directive,
|
3499 | ref,
|
3500 | name: node.name.text,
|
3501 | selector: analysis.meta.selector,
|
3502 | exportAs: analysis.meta.exportAs,
|
3503 | inputs: analysis.inputs,
|
3504 | outputs: analysis.outputs,
|
3505 | queries: analysis.meta.queries.map((query) => query.propertyName),
|
3506 | isComponent: false,
|
3507 | baseClass: analysis.baseClass
|
3508 | }, analysis.typeCheckMeta), {
|
3509 | isPoisoned: analysis.isPoisoned,
|
3510 | isStructural: analysis.isStructural,
|
3511 | animationTriggerNames: null
|
3512 | }));
|
3513 | this.injectableRegistry.registerInjectable(node);
|
3514 | }
|
3515 | resolve(node, analysis, symbol) {
|
3516 | if (this.semanticDepGraphUpdater !== null && analysis.baseClass instanceof Reference) {
|
3517 | symbol.baseClass = this.semanticDepGraphUpdater.getSymbol(analysis.baseClass.node);
|
3518 | }
|
3519 | const diagnostics = [];
|
3520 | if (analysis.providersRequiringFactory !== null && analysis.meta.providers instanceof WrappedNodeExpr3) {
|
3521 | const providerDiagnostics = getProviderDiagnostics(analysis.providersRequiringFactory, analysis.meta.providers.node, this.injectableRegistry);
|
3522 | diagnostics.push(...providerDiagnostics);
|
3523 | }
|
3524 | const directiveDiagnostics = getDirectiveDiagnostics(node, this.metaReader, this.evaluator, this.reflector, this.scopeRegistry, "Directive");
|
3525 | if (directiveDiagnostics !== null) {
|
3526 | diagnostics.push(...directiveDiagnostics);
|
3527 | }
|
3528 | return { diagnostics: diagnostics.length > 0 ? diagnostics : void 0 };
|
3529 | }
|
3530 | compileFull(node, analysis, resolution, pool) {
|
3531 | const fac = compileNgFactoryDefField(toFactoryMetadata(analysis.meta, FactoryTarget.Directive));
|
3532 | const def = compileDirectiveFromMetadata(analysis.meta, pool, makeBindingParser());
|
3533 | const classMetadata = analysis.classMetadata !== null ? compileClassMetadata(analysis.classMetadata).toStmt() : null;
|
3534 | return compileResults(fac, def, classMetadata, "\u0275dir");
|
3535 | }
|
3536 | compilePartial(node, analysis, resolution) {
|
3537 | const fac = compileDeclareFactory(toFactoryMetadata(analysis.meta, FactoryTarget.Directive));
|
3538 | const def = compileDeclareDirectiveFromMetadata(analysis.meta);
|
3539 | const classMetadata = analysis.classMetadata !== null ? compileDeclareClassMetadata(analysis.classMetadata).toStmt() : null;
|
3540 | return compileResults(fac, def, classMetadata, "\u0275dir");
|
3541 | }
|
3542 | findClassFieldWithAngularFeatures(node) {
|
3543 | return this.reflector.getMembersOfClass(node).find((member) => {
|
3544 | if (!member.isStatic && member.kind === ClassMemberKind.Method && LIFECYCLE_HOOKS.has(member.name)) {
|
3545 | return true;
|
3546 | }
|
3547 | if (member.decorators) {
|
3548 | return member.decorators.some((decorator) => FIELD_DECORATORS.some((decoratorName) => isAngularDecorator(decorator, decoratorName, this.isCore)));
|
3549 | }
|
3550 | return false;
|
3551 | });
|
3552 | }
|
3553 | };
|
3554 | function extractDirectiveMetadata(clazz, decorator, reflector, evaluator, isCore, flags, annotateForClosureCompiler, defaultSelector = null) {
|
3555 | let directive;
|
3556 | if (decorator === null || decorator.args === null || decorator.args.length === 0) {
|
3557 | directive = new Map();
|
3558 | } else if (decorator.args.length !== 1) {
|
3559 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), `Incorrect number of arguments to @${decorator.name} decorator`);
|
3560 | } else {
|
3561 | const meta = unwrapExpression(decorator.args[0]);
|
3562 | if (!ts16.isObjectLiteralExpression(meta)) {
|
3563 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, meta, `@${decorator.name} argument must be an object literal`);
|
3564 | }
|
3565 | directive = reflectObjectLiteral(meta);
|
3566 | }
|
3567 | if (directive.has("jit")) {
|
3568 | return void 0;
|
3569 | }
|
3570 | const members = reflector.getMembersOfClass(clazz);
|
3571 | const decoratedElements = members.filter((member) => !member.isStatic && member.decorators !== null);
|
3572 | const coreModule = isCore ? void 0 : "@angular/core";
|
3573 | const inputsFromMeta = parseFieldToPropertyMapping(directive, "inputs", evaluator);
|
3574 | const inputsFromFields = parseDecoratedFields(filterToMembersWithDecorator(decoratedElements, "Input", coreModule), evaluator, resolveInput);
|
3575 | const outputsFromMeta = parseFieldToPropertyMapping(directive, "outputs", evaluator);
|
3576 | const outputsFromFields = parseDecoratedFields(filterToMembersWithDecorator(decoratedElements, "Output", coreModule), evaluator, resolveOutput);
|
3577 | const contentChildFromFields = queriesFromFields(filterToMembersWithDecorator(decoratedElements, "ContentChild", coreModule), reflector, evaluator);
|
3578 | const contentChildrenFromFields = queriesFromFields(filterToMembersWithDecorator(decoratedElements, "ContentChildren", coreModule), reflector, evaluator);
|
3579 | const queries = [...contentChildFromFields, ...contentChildrenFromFields];
|
3580 | const viewChildFromFields = queriesFromFields(filterToMembersWithDecorator(decoratedElements, "ViewChild", coreModule), reflector, evaluator);
|
3581 | const viewChildrenFromFields = queriesFromFields(filterToMembersWithDecorator(decoratedElements, "ViewChildren", coreModule), reflector, evaluator);
|
3582 | const viewQueries = [...viewChildFromFields, ...viewChildrenFromFields];
|
3583 | if (directive.has("queries")) {
|
3584 | const queriesFromDecorator = extractQueriesFromDecorator(directive.get("queries"), reflector, evaluator, isCore);
|
3585 | queries.push(...queriesFromDecorator.content);
|
3586 | viewQueries.push(...queriesFromDecorator.view);
|
3587 | }
|
3588 | let selector = defaultSelector;
|
3589 | if (directive.has("selector")) {
|
3590 | const expr = directive.get("selector");
|
3591 | const resolved = evaluator.evaluate(expr);
|
3592 | if (typeof resolved !== "string") {
|
3593 | throw createValueHasWrongTypeError(expr, resolved, `selector must be a string`);
|
3594 | }
|
3595 | selector = resolved === "" ? defaultSelector : resolved;
|
3596 | if (!selector) {
|
3597 | throw new FatalDiagnosticError(ErrorCode.DIRECTIVE_MISSING_SELECTOR, expr, `Directive ${clazz.name.text} has no selector, please add it!`);
|
3598 | }
|
3599 | }
|
3600 | const host = extractHostBindings(decoratedElements, evaluator, coreModule, directive);
|
3601 | const providers = directive.has("providers") ? new WrappedNodeExpr3(annotateForClosureCompiler ? wrapFunctionExpressionsInParens(directive.get("providers")) : directive.get("providers")) : null;
|
3602 | const usesOnChanges = members.some((member) => !member.isStatic && member.kind === ClassMemberKind.Method && member.name === "ngOnChanges");
|
3603 | let exportAs = null;
|
3604 | if (directive.has("exportAs")) {
|
3605 | const expr = directive.get("exportAs");
|
3606 | const resolved = evaluator.evaluate(expr);
|
3607 | if (typeof resolved !== "string") {
|
3608 | throw createValueHasWrongTypeError(expr, resolved, `exportAs must be a string`);
|
3609 | }
|
3610 | exportAs = resolved.split(",").map((part) => part.trim());
|
3611 | }
|
3612 | const rawCtorDeps = getConstructorDependencies(clazz, reflector, isCore);
|
3613 | const ctorDeps = selector !== null ? validateConstructorDependencies(clazz, rawCtorDeps) : unwrapConstructorDependencies(rawCtorDeps);
|
3614 | const isStructural = ctorDeps !== null && ctorDeps !== "invalid" && ctorDeps.some((dep) => dep.token instanceof ExternalExpr3 && dep.token.value.moduleName === "@angular/core" && dep.token.value.name === "TemplateRef");
|
3615 | const usesInheritance = reflector.hasBaseClass(clazz);
|
3616 | const type = wrapTypeReference(reflector, clazz);
|
3617 | const internalType = new WrappedNodeExpr3(reflector.getInternalNameOfClass(clazz));
|
3618 | const inputs = ClassPropertyMapping.fromMappedObject(__spreadValues(__spreadValues({}, inputsFromMeta), inputsFromFields));
|
3619 | const outputs = ClassPropertyMapping.fromMappedObject(__spreadValues(__spreadValues({}, outputsFromMeta), outputsFromFields));
|
3620 | const metadata = {
|
3621 | name: clazz.name.text,
|
3622 | deps: ctorDeps,
|
3623 | host,
|
3624 | lifecycle: {
|
3625 | usesOnChanges
|
3626 | },
|
3627 | inputs: inputs.toJointMappedObject(),
|
3628 | outputs: outputs.toDirectMappedObject(),
|
3629 | queries,
|
3630 | viewQueries,
|
3631 | selector,
|
3632 | fullInheritance: !!(flags & HandlerFlags.FULL_INHERITANCE),
|
3633 | type,
|
3634 | internalType,
|
3635 | typeArgumentCount: reflector.getGenericArityOfClass(clazz) || 0,
|
3636 | typeSourceSpan: createSourceSpan(clazz.name),
|
3637 | usesInheritance,
|
3638 | exportAs,
|
3639 | providers
|
3640 | };
|
3641 | return {
|
3642 | decorator: directive,
|
3643 | metadata,
|
3644 | inputs,
|
3645 | outputs,
|
3646 | isStructural
|
3647 | };
|
3648 | }
|
3649 | function extractQueryMetadata(exprNode, name, args, propertyName, reflector, evaluator) {
|
3650 | if (args.length === 0) {
|
3651 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, exprNode, `@${name} must have arguments`);
|
3652 | }
|
3653 | const first = name === "ViewChild" || name === "ContentChild";
|
3654 | const forwardReferenceTarget = tryUnwrapForwardRef(args[0], reflector);
|
3655 | const node = forwardReferenceTarget != null ? forwardReferenceTarget : args[0];
|
3656 | const arg = evaluator.evaluate(node);
|
3657 | let isStatic = false;
|
3658 | let predicate = null;
|
3659 | if (arg instanceof Reference || arg instanceof DynamicValue) {
|
3660 | predicate = createMayBeForwardRefExpression(new WrappedNodeExpr3(node), forwardReferenceTarget !== null ? 2 : 0);
|
3661 | } else if (typeof arg === "string") {
|
3662 | predicate = [arg];
|
3663 | } else if (isStringArrayOrDie(arg, `@${name} predicate`, node)) {
|
3664 | predicate = arg;
|
3665 | } else {
|
3666 | throw createValueHasWrongTypeError(node, arg, `@${name} predicate cannot be interpreted`);
|
3667 | }
|
3668 | let read = null;
|
3669 | let descendants = name !== "ContentChildren";
|
3670 | let emitDistinctChangesOnly = emitDistinctChangesOnlyDefaultValue;
|
3671 | if (args.length === 2) {
|
3672 | const optionsExpr = unwrapExpression(args[1]);
|
3673 | if (!ts16.isObjectLiteralExpression(optionsExpr)) {
|
3674 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, optionsExpr, `@${name} options must be an object literal`);
|
3675 | }
|
3676 | const options = reflectObjectLiteral(optionsExpr);
|
3677 | if (options.has("read")) {
|
3678 | read = new WrappedNodeExpr3(options.get("read"));
|
3679 | }
|
3680 | if (options.has("descendants")) {
|
3681 | const descendantsExpr = options.get("descendants");
|
3682 | const descendantsValue = evaluator.evaluate(descendantsExpr);
|
3683 | if (typeof descendantsValue !== "boolean") {
|
3684 | throw createValueHasWrongTypeError(descendantsExpr, descendantsValue, `@${name} options.descendants must be a boolean`);
|
3685 | }
|
3686 | descendants = descendantsValue;
|
3687 | }
|
3688 | if (options.has("emitDistinctChangesOnly")) {
|
3689 | const emitDistinctChangesOnlyExpr = options.get("emitDistinctChangesOnly");
|
3690 | const emitDistinctChangesOnlyValue = evaluator.evaluate(emitDistinctChangesOnlyExpr);
|
3691 | if (typeof emitDistinctChangesOnlyValue !== "boolean") {
|
3692 | throw createValueHasWrongTypeError(emitDistinctChangesOnlyExpr, emitDistinctChangesOnlyValue, `@${name} options.emitDistinctChangesOnly must be a boolean`);
|
3693 | }
|
3694 | emitDistinctChangesOnly = emitDistinctChangesOnlyValue;
|
3695 | }
|
3696 | if (options.has("static")) {
|
3697 | const staticValue = evaluator.evaluate(options.get("static"));
|
3698 | if (typeof staticValue !== "boolean") {
|
3699 | throw createValueHasWrongTypeError(node, staticValue, `@${name} options.static must be a boolean`);
|
3700 | }
|
3701 | isStatic = staticValue;
|
3702 | }
|
3703 | } else if (args.length > 2) {
|
3704 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, node, `@${name} has too many arguments`);
|
3705 | }
|
3706 | return {
|
3707 | propertyName,
|
3708 | predicate,
|
3709 | first,
|
3710 | descendants,
|
3711 | read,
|
3712 | static: isStatic,
|
3713 | emitDistinctChangesOnly
|
3714 | };
|
3715 | }
|
3716 | function extractQueriesFromDecorator(queryData, reflector, evaluator, isCore) {
|
3717 | const content = [], view = [];
|
3718 | if (!ts16.isObjectLiteralExpression(queryData)) {
|
3719 | throw new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, queryData, "Decorator queries metadata must be an object literal");
|
3720 | }
|
3721 | reflectObjectLiteral(queryData).forEach((queryExpr, propertyName) => {
|
3722 | queryExpr = unwrapExpression(queryExpr);
|
3723 | if (!ts16.isNewExpression(queryExpr)) {
|
3724 | throw new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, queryData, "Decorator query metadata must be an instance of a query type");
|
3725 | }
|
3726 | const queryType = ts16.isPropertyAccessExpression(queryExpr.expression) ? queryExpr.expression.name : queryExpr.expression;
|
3727 | if (!ts16.isIdentifier(queryType)) {
|
3728 | throw new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, queryData, "Decorator query metadata must be an instance of a query type");
|
3729 | }
|
3730 | const type = reflector.getImportOfIdentifier(queryType);
|
3731 | if (type === null || !isCore && type.from !== "@angular/core" || !QUERY_TYPES.has(type.name)) {
|
3732 | throw new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, queryData, "Decorator query metadata must be an instance of a query type");
|
3733 | }
|
3734 | const query = extractQueryMetadata(queryExpr, type.name, queryExpr.arguments || [], propertyName, reflector, evaluator);
|
3735 | if (type.name.startsWith("Content")) {
|
3736 | content.push(query);
|
3737 | } else {
|
3738 | view.push(query);
|
3739 | }
|
3740 | });
|
3741 | return { content, view };
|
3742 | }
|
3743 | function isStringArrayOrDie(value, name, node) {
|
3744 | if (!Array.isArray(value)) {
|
3745 | return false;
|
3746 | }
|
3747 | for (let i = 0; i < value.length; i++) {
|
3748 | if (typeof value[i] !== "string") {
|
3749 | throw createValueHasWrongTypeError(node, value[i], `Failed to resolve ${name} at position ${i} to a string`);
|
3750 | }
|
3751 | }
|
3752 | return true;
|
3753 | }
|
3754 | function parseFieldArrayValue(directive, field, evaluator) {
|
3755 | if (!directive.has(field)) {
|
3756 | return null;
|
3757 | }
|
3758 | const expression = directive.get(field);
|
3759 | const value = evaluator.evaluate(expression);
|
3760 | if (!isStringArrayOrDie(value, field, expression)) {
|
3761 | throw createValueHasWrongTypeError(expression, value, `Failed to resolve @Directive.${field} to a string array`);
|
3762 | }
|
3763 | return value;
|
3764 | }
|
3765 | function parseFieldToPropertyMapping(directive, field, evaluator) {
|
3766 | const metaValues = parseFieldArrayValue(directive, field, evaluator);
|
3767 | if (!metaValues) {
|
3768 | return EMPTY_OBJECT;
|
3769 | }
|
3770 | return metaValues.reduce((results, value) => {
|
3771 | const [field2, property] = value.split(":", 2).map((str) => str.trim());
|
3772 | results[field2] = property || field2;
|
3773 | return results;
|
3774 | }, {});
|
3775 | }
|
3776 | function parseDecoratedFields(fields, evaluator, mapValueResolver) {
|
3777 | return fields.reduce((results, field) => {
|
3778 | const fieldName = field.member.name;
|
3779 | field.decorators.forEach((decorator) => {
|
3780 | if (decorator.args == null || decorator.args.length === 0) {
|
3781 | results[fieldName] = fieldName;
|
3782 | } else if (decorator.args.length === 1) {
|
3783 | const property = evaluator.evaluate(decorator.args[0]);
|
3784 | if (typeof property !== "string") {
|
3785 | throw createValueHasWrongTypeError(Decorator.nodeForError(decorator), property, `@${decorator.name} decorator argument must resolve to a string`);
|
3786 | }
|
3787 | results[fieldName] = mapValueResolver(property, fieldName);
|
3788 | } else {
|
3789 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), `@${decorator.name} can have at most one argument, got ${decorator.args.length} argument(s)`);
|
3790 | }
|
3791 | });
|
3792 | return results;
|
3793 | }, {});
|
3794 | }
|
3795 | function resolveInput(publicName, internalName) {
|
3796 | return [publicName, internalName];
|
3797 | }
|
3798 | function resolveOutput(publicName, internalName) {
|
3799 | return publicName;
|
3800 | }
|
3801 | function queriesFromFields(fields, reflector, evaluator) {
|
3802 | return fields.map(({ member, decorators }) => {
|
3803 | const decorator = decorators[0];
|
3804 | const node = member.node || Decorator.nodeForError(decorator);
|
3805 | if (member.decorators.some((v) => v.name === "Input")) {
|
3806 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_COLLISION, node, "Cannot combine @Input decorators with query decorators");
|
3807 | }
|
3808 | if (decorators.length !== 1) {
|
3809 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_COLLISION, node, "Cannot have multiple query decorators on the same class member");
|
3810 | } else if (!isPropertyTypeMember(member)) {
|
3811 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_UNEXPECTED, node, "Query decorator must go on a property-type member");
|
3812 | }
|
3813 | return extractQueryMetadata(node, decorator.name, decorator.args || [], member.name, reflector, evaluator);
|
3814 | });
|
3815 | }
|
3816 | function isPropertyTypeMember(member) {
|
3817 | return member.kind === ClassMemberKind.Getter || member.kind === ClassMemberKind.Setter || member.kind === ClassMemberKind.Property;
|
3818 | }
|
3819 | function evaluateHostExpressionBindings(hostExpr, evaluator) {
|
3820 | const hostMetaMap = evaluator.evaluate(hostExpr);
|
3821 | if (!(hostMetaMap instanceof Map)) {
|
3822 | throw createValueHasWrongTypeError(hostExpr, hostMetaMap, `Decorator host metadata must be an object`);
|
3823 | }
|
3824 | const hostMetadata = {};
|
3825 | hostMetaMap.forEach((value, key) => {
|
3826 | if (value instanceof EnumValue) {
|
3827 | value = value.resolved;
|
3828 | }
|
3829 | if (typeof key !== "string") {
|
3830 | throw createValueHasWrongTypeError(hostExpr, key, `Decorator host metadata must be a string -> string object, but found unparseable key`);
|
3831 | }
|
3832 | if (typeof value == "string") {
|
3833 | hostMetadata[key] = value;
|
3834 | } else if (value instanceof DynamicValue) {
|
3835 | hostMetadata[key] = new WrappedNodeExpr3(value.node);
|
3836 | } else {
|
3837 | throw createValueHasWrongTypeError(hostExpr, value, `Decorator host metadata must be a string -> string object, but found unparseable value`);
|
3838 | }
|
3839 | });
|
3840 | const bindings = parseHostBindings(hostMetadata);
|
3841 | const errors = verifyHostBindings(bindings, createSourceSpan(hostExpr));
|
3842 | if (errors.length > 0) {
|
3843 | throw new FatalDiagnosticError(ErrorCode.HOST_BINDING_PARSE_ERROR, hostExpr, errors.map((error) => error.msg).join("\n"));
|
3844 | }
|
3845 | return bindings;
|
3846 | }
|
3847 | function extractHostBindings(members, evaluator, coreModule, metadata) {
|
3848 | let bindings;
|
3849 | if (metadata && metadata.has("host")) {
|
3850 | bindings = evaluateHostExpressionBindings(metadata.get("host"), evaluator);
|
3851 | } else {
|
3852 | bindings = parseHostBindings({});
|
3853 | }
|
3854 | filterToMembersWithDecorator(members, "HostBinding", coreModule).forEach(({ member, decorators }) => {
|
3855 | decorators.forEach((decorator) => {
|
3856 | let hostPropertyName = member.name;
|
3857 | if (decorator.args !== null && decorator.args.length > 0) {
|
3858 | if (decorator.args.length !== 1) {
|
3859 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), `@HostBinding can have at most one argument, got ${decorator.args.length} argument(s)`);
|
3860 | }
|
3861 | const resolved = evaluator.evaluate(decorator.args[0]);
|
3862 | if (typeof resolved !== "string") {
|
3863 | throw createValueHasWrongTypeError(Decorator.nodeForError(decorator), resolved, `@HostBinding's argument must be a string`);
|
3864 | }
|
3865 | hostPropertyName = resolved;
|
3866 | }
|
3867 | bindings.properties[hostPropertyName] = getSafePropertyAccessString("this", member.name);
|
3868 | });
|
3869 | });
|
3870 | filterToMembersWithDecorator(members, "HostListener", coreModule).forEach(({ member, decorators }) => {
|
3871 | decorators.forEach((decorator) => {
|
3872 | let eventName = member.name;
|
3873 | let args = [];
|
3874 | if (decorator.args !== null && decorator.args.length > 0) {
|
3875 | if (decorator.args.length > 2) {
|
3876 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, decorator.args[2], `@HostListener can have at most two arguments`);
|
3877 | }
|
3878 | const resolved = evaluator.evaluate(decorator.args[0]);
|
3879 | if (typeof resolved !== "string") {
|
3880 | throw createValueHasWrongTypeError(decorator.args[0], resolved, `@HostListener's event name argument must be a string`);
|
3881 | }
|
3882 | eventName = resolved;
|
3883 | if (decorator.args.length === 2) {
|
3884 | const expression = decorator.args[1];
|
3885 | const resolvedArgs = evaluator.evaluate(decorator.args[1]);
|
3886 | if (!isStringArrayOrDie(resolvedArgs, "@HostListener.args", expression)) {
|
3887 | throw createValueHasWrongTypeError(decorator.args[1], resolvedArgs, `@HostListener's second argument must be a string array`);
|
3888 | }
|
3889 | args = resolvedArgs;
|
3890 | }
|
3891 | }
|
3892 | bindings.listeners[eventName] = `${member.name}(${args.join(",")})`;
|
3893 | });
|
3894 | });
|
3895 | return bindings;
|
3896 | }
|
3897 | var QUERY_TYPES = new Set([
|
3898 | "ContentChild",
|
3899 | "ContentChildren",
|
3900 | "ViewChild",
|
3901 | "ViewChildren"
|
3902 | ]);
|
3903 |
|
3904 |
|
3905 | import { compileClassMetadata as compileClassMetadata2, compileDeclareClassMetadata as compileDeclareClassMetadata2, compileDeclareInjectorFromMetadata, compileDeclareNgModuleFromMetadata, compileInjector, compileNgModule, CUSTOM_ELEMENTS_SCHEMA, ExternalExpr as ExternalExpr4, FactoryTarget as FactoryTarget2, InvokeFunctionExpr, LiteralArrayExpr as LiteralArrayExpr2, NO_ERRORS_SCHEMA, R3Identifiers, WrappedNodeExpr as WrappedNodeExpr4 } from "@angular/compiler";
|
3906 | import ts17 from "typescript";
|
3907 | var NgModuleSymbol = class extends SemanticSymbol {
|
3908 | constructor() {
|
3909 | super(...arguments);
|
3910 | this.remotelyScopedComponents = [];
|
3911 | }
|
3912 | isPublicApiAffected(previousSymbol) {
|
3913 | if (!(previousSymbol instanceof NgModuleSymbol)) {
|
3914 | return true;
|
3915 | }
|
3916 | return false;
|
3917 | }
|
3918 | isEmitAffected(previousSymbol) {
|
3919 | if (!(previousSymbol instanceof NgModuleSymbol)) {
|
3920 | return true;
|
3921 | }
|
3922 | if (previousSymbol.remotelyScopedComponents.length !== this.remotelyScopedComponents.length) {
|
3923 | return true;
|
3924 | }
|
3925 | for (const currEntry of this.remotelyScopedComponents) {
|
3926 | const prevEntry = previousSymbol.remotelyScopedComponents.find((prevEntry2) => {
|
3927 | return isSymbolEqual(prevEntry2.component, currEntry.component);
|
3928 | });
|
3929 | if (prevEntry === void 0) {
|
3930 | return true;
|
3931 | }
|
3932 | if (!isArrayEqual(currEntry.usedDirectives, prevEntry.usedDirectives, isReferenceEqual)) {
|
3933 | return true;
|
3934 | }
|
3935 | if (!isArrayEqual(currEntry.usedPipes, prevEntry.usedPipes, isReferenceEqual)) {
|
3936 | return true;
|
3937 | }
|
3938 | }
|
3939 | return false;
|
3940 | }
|
3941 | isTypeCheckApiAffected(previousSymbol) {
|
3942 | if (!(previousSymbol instanceof NgModuleSymbol)) {
|
3943 | return true;
|
3944 | }
|
3945 | return false;
|
3946 | }
|
3947 | addRemotelyScopedComponent(component, usedDirectives, usedPipes) {
|
3948 | this.remotelyScopedComponents.push({ component, usedDirectives, usedPipes });
|
3949 | }
|
3950 | };
|
3951 | var NgModuleDecoratorHandler = class {
|
3952 | constructor(reflector, evaluator, metaReader, metaRegistry, scopeRegistry, referencesRegistry, isCore, refEmitter, factoryTracker, annotateForClosureCompiler, injectableRegistry, perf) {
|
3953 | this.reflector = reflector;
|
3954 | this.evaluator = evaluator;
|
3955 | this.metaReader = metaReader;
|
3956 | this.metaRegistry = metaRegistry;
|
3957 | this.scopeRegistry = scopeRegistry;
|
3958 | this.referencesRegistry = referencesRegistry;
|
3959 | this.isCore = isCore;
|
3960 | this.refEmitter = refEmitter;
|
3961 | this.factoryTracker = factoryTracker;
|
3962 | this.annotateForClosureCompiler = annotateForClosureCompiler;
|
3963 | this.injectableRegistry = injectableRegistry;
|
3964 | this.perf = perf;
|
3965 | this.precedence = HandlerPrecedence.PRIMARY;
|
3966 | this.name = NgModuleDecoratorHandler.name;
|
3967 | }
|
3968 | detect(node, decorators) {
|
3969 | if (!decorators) {
|
3970 | return void 0;
|
3971 | }
|
3972 | const decorator = findAngularDecorator(decorators, "NgModule", this.isCore);
|
3973 | if (decorator !== void 0) {
|
3974 | return {
|
3975 | trigger: decorator.node,
|
3976 | decorator,
|
3977 | metadata: decorator
|
3978 | };
|
3979 | } else {
|
3980 | return void 0;
|
3981 | }
|
3982 | }
|
3983 | analyze(node, decorator) {
|
3984 | this.perf.eventCount(PerfEvent.AnalyzeNgModule);
|
3985 | const name = node.name.text;
|
3986 | if (decorator.args === null || decorator.args.length > 1) {
|
3987 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), `Incorrect number of arguments to @NgModule decorator`);
|
3988 | }
|
3989 | const meta = decorator.args.length === 1 ? unwrapExpression(decorator.args[0]) : ts17.createObjectLiteral([]);
|
3990 | if (!ts17.isObjectLiteralExpression(meta)) {
|
3991 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, meta, "@NgModule argument must be an object literal");
|
3992 | }
|
3993 | const ngModule = reflectObjectLiteral(meta);
|
3994 | if (ngModule.has("jit")) {
|
3995 | return {};
|
3996 | }
|
3997 | const moduleResolvers = combineResolvers([
|
3998 | (ref) => this._extractModuleFromModuleWithProvidersFn(ref.node),
|
3999 | forwardRefResolver
|
4000 | ]);
|
4001 | const diagnostics = [];
|
4002 | let declarationRefs = [];
|
4003 | let rawDeclarations = null;
|
4004 | if (ngModule.has("declarations")) {
|
4005 | rawDeclarations = ngModule.get("declarations");
|
4006 | const declarationMeta = this.evaluator.evaluate(rawDeclarations, forwardRefResolver);
|
4007 | declarationRefs = this.resolveTypeList(rawDeclarations, declarationMeta, name, "declarations");
|
4008 | for (const ref of declarationRefs) {
|
4009 | if (ref.node.getSourceFile().isDeclarationFile) {
|
4010 | const errorNode = ref.getOriginForDiagnostics(rawDeclarations);
|
4011 | diagnostics.push(makeDiagnostic(ErrorCode.NGMODULE_INVALID_DECLARATION, errorNode, `Cannot declare '${ref.node.name.text}' in an NgModule as it's not a part of the current compilation.`, [makeRelatedInformation(ref.node.name, `'${ref.node.name.text}' is declared here.`)]));
|
4012 | }
|
4013 | }
|
4014 | }
|
4015 | if (diagnostics.length > 0) {
|
4016 | return { diagnostics };
|
4017 | }
|
4018 | let importRefs = [];
|
4019 | if (ngModule.has("imports")) {
|
4020 | const rawImports = ngModule.get("imports");
|
4021 | const importsMeta = this.evaluator.evaluate(rawImports, moduleResolvers);
|
4022 | importRefs = this.resolveTypeList(rawImports, importsMeta, name, "imports");
|
4023 | }
|
4024 | let exportRefs = [];
|
4025 | if (ngModule.has("exports")) {
|
4026 | const rawExports = ngModule.get("exports");
|
4027 | const exportsMeta = this.evaluator.evaluate(rawExports, moduleResolvers);
|
4028 | exportRefs = this.resolveTypeList(rawExports, exportsMeta, name, "exports");
|
4029 | this.referencesRegistry.add(node, ...exportRefs);
|
4030 | }
|
4031 | let bootstrapRefs = [];
|
4032 | if (ngModule.has("bootstrap")) {
|
4033 | const expr = ngModule.get("bootstrap");
|
4034 | const bootstrapMeta = this.evaluator.evaluate(expr, forwardRefResolver);
|
4035 | bootstrapRefs = this.resolveTypeList(expr, bootstrapMeta, name, "bootstrap");
|
4036 | }
|
4037 | const schemas = [];
|
4038 | if (ngModule.has("schemas")) {
|
4039 | const rawExpr = ngModule.get("schemas");
|
4040 | const result = this.evaluator.evaluate(rawExpr);
|
4041 | if (!Array.isArray(result)) {
|
4042 | throw createValueHasWrongTypeError(rawExpr, result, `NgModule.schemas must be an array`);
|
4043 | }
|
4044 | for (const schemaRef of result) {
|
4045 | if (!(schemaRef instanceof Reference)) {
|
4046 | throw createValueHasWrongTypeError(rawExpr, result, "NgModule.schemas must be an array of schemas");
|
4047 | }
|
4048 | const id2 = schemaRef.getIdentityIn(schemaRef.node.getSourceFile());
|
4049 | if (id2 === null || schemaRef.ownedByModuleGuess !== "@angular/core") {
|
4050 | throw createValueHasWrongTypeError(rawExpr, result, "NgModule.schemas must be an array of schemas");
|
4051 | }
|
4052 | switch (id2.text) {
|
4053 | case "CUSTOM_ELEMENTS_SCHEMA":
|
4054 | schemas.push(CUSTOM_ELEMENTS_SCHEMA);
|
4055 | break;
|
4056 | case "NO_ERRORS_SCHEMA":
|
4057 | schemas.push(NO_ERRORS_SCHEMA);
|
4058 | break;
|
4059 | default:
|
4060 | throw createValueHasWrongTypeError(rawExpr, schemaRef, `'${schemaRef.debugName}' is not a valid NgModule schema`);
|
4061 | }
|
4062 | }
|
4063 | }
|
4064 | const id = ngModule.has("id") ? new WrappedNodeExpr4(ngModule.get("id")) : null;
|
4065 | const valueContext = node.getSourceFile();
|
4066 | let typeContext = valueContext;
|
4067 | const typeNode = this.reflector.getDtsDeclaration(node);
|
4068 | if (typeNode !== null) {
|
4069 | typeContext = typeNode.getSourceFile();
|
4070 | }
|
4071 | const bootstrap = bootstrapRefs.map((bootstrap2) => this._toR3Reference(bootstrap2.getOriginForDiagnostics(meta, node.name), bootstrap2, valueContext, typeContext));
|
4072 | const declarations = declarationRefs.map((decl) => this._toR3Reference(decl.getOriginForDiagnostics(meta, node.name), decl, valueContext, typeContext));
|
4073 | const imports = importRefs.map((imp) => this._toR3Reference(imp.getOriginForDiagnostics(meta, node.name), imp, valueContext, typeContext));
|
4074 | const exports = exportRefs.map((exp) => this._toR3Reference(exp.getOriginForDiagnostics(meta, node.name), exp, valueContext, typeContext));
|
4075 | const isForwardReference = (ref) => isExpressionForwardReference(ref.value, node.name, valueContext);
|
4076 | const containsForwardDecls = bootstrap.some(isForwardReference) || declarations.some(isForwardReference) || imports.some(isForwardReference) || exports.some(isForwardReference);
|
4077 | const type = wrapTypeReference(this.reflector, node);
|
4078 | const internalType = new WrappedNodeExpr4(this.reflector.getInternalNameOfClass(node));
|
4079 | const adjacentType = new WrappedNodeExpr4(this.reflector.getAdjacentNameOfClass(node));
|
4080 | const ngModuleMetadata = {
|
4081 | type,
|
4082 | internalType,
|
4083 | adjacentType,
|
4084 | bootstrap,
|
4085 | declarations,
|
4086 | exports,
|
4087 | imports,
|
4088 | containsForwardDecls,
|
4089 | id,
|
4090 | emitInline: false,
|
4091 | schemas: []
|
4092 | };
|
4093 | const rawProviders = ngModule.has("providers") ? ngModule.get("providers") : null;
|
4094 | const wrapperProviders = rawProviders !== null ? new WrappedNodeExpr4(this.annotateForClosureCompiler ? wrapFunctionExpressionsInParens(rawProviders) : rawProviders) : null;
|
4095 | const injectorImports = [];
|
4096 | if (ngModule.has("imports")) {
|
4097 | injectorImports.push(new WrappedNodeExpr4(ngModule.get("imports")));
|
4098 | }
|
4099 | const injectorMetadata = {
|
4100 | name,
|
4101 | type,
|
4102 | internalType,
|
4103 | providers: wrapperProviders,
|
4104 | imports: injectorImports
|
4105 | };
|
4106 | const factoryMetadata = {
|
4107 | name,
|
4108 | type,
|
4109 | internalType,
|
4110 | typeArgumentCount: 0,
|
4111 | deps: getValidConstructorDependencies(node, this.reflector, this.isCore),
|
4112 | target: FactoryTarget2.NgModule
|
4113 | };
|
4114 | return {
|
4115 | analysis: {
|
4116 | id,
|
4117 | schemas,
|
4118 | mod: ngModuleMetadata,
|
4119 | inj: injectorMetadata,
|
4120 | fac: factoryMetadata,
|
4121 | declarations: declarationRefs,
|
4122 | rawDeclarations,
|
4123 | imports: importRefs,
|
4124 | exports: exportRefs,
|
4125 | providers: rawProviders,
|
4126 | providersRequiringFactory: rawProviders ? resolveProvidersRequiringFactory(rawProviders, this.reflector, this.evaluator) : null,
|
4127 | classMetadata: extractClassMetadata(node, this.reflector, this.isCore, this.annotateForClosureCompiler),
|
4128 | factorySymbolName: node.name.text
|
4129 | }
|
4130 | };
|
4131 | }
|
4132 | symbol(node) {
|
4133 | return new NgModuleSymbol(node);
|
4134 | }
|
4135 | register(node, analysis) {
|
4136 | this.metaRegistry.registerNgModuleMetadata({
|
4137 | ref: new Reference(node),
|
4138 | schemas: analysis.schemas,
|
4139 | declarations: analysis.declarations,
|
4140 | imports: analysis.imports,
|
4141 | exports: analysis.exports,
|
4142 | rawDeclarations: analysis.rawDeclarations
|
4143 | });
|
4144 | if (this.factoryTracker !== null) {
|
4145 | this.factoryTracker.track(node.getSourceFile(), {
|
4146 | name: analysis.factorySymbolName,
|
4147 | hasId: analysis.id !== null
|
4148 | });
|
4149 | }
|
4150 | this.injectableRegistry.registerInjectable(node);
|
4151 | }
|
4152 | resolve(node, analysis) {
|
4153 | const scope = this.scopeRegistry.getScopeOfModule(node);
|
4154 | const diagnostics = [];
|
4155 | const scopeDiagnostics = this.scopeRegistry.getDiagnosticsOfModule(node);
|
4156 | if (scopeDiagnostics !== null) {
|
4157 | diagnostics.push(...scopeDiagnostics);
|
4158 | }
|
4159 | if (analysis.providersRequiringFactory !== null) {
|
4160 | const providerDiagnostics = getProviderDiagnostics(analysis.providersRequiringFactory, analysis.providers, this.injectableRegistry);
|
4161 | diagnostics.push(...providerDiagnostics);
|
4162 | }
|
4163 | const data = {
|
4164 | injectorImports: []
|
4165 | };
|
4166 | if (scope !== null && !scope.compilation.isPoisoned) {
|
4167 | const context = getSourceFile(node);
|
4168 | for (const exportRef of analysis.exports) {
|
4169 | if (isNgModule(exportRef.node, scope.compilation)) {
|
4170 | const type = this.refEmitter.emit(exportRef, context);
|
4171 | assertSuccessfulReferenceEmit(type, node, "NgModule");
|
4172 | data.injectorImports.push(type.expression);
|
4173 | }
|
4174 | }
|
4175 | for (const decl of analysis.declarations) {
|
4176 | const metadata = this.metaReader.getDirectiveMetadata(decl);
|
4177 | if (metadata !== null && metadata.selector === null) {
|
4178 | throw new FatalDiagnosticError(ErrorCode.DIRECTIVE_MISSING_SELECTOR, decl.node, `Directive ${decl.node.name.text} has no selector, please add it!`);
|
4179 | }
|
4180 | }
|
4181 | }
|
4182 | if (diagnostics.length > 0) {
|
4183 | return { diagnostics };
|
4184 | }
|
4185 | if (scope === null || scope.compilation.isPoisoned || scope.exported.isPoisoned || scope.reexports === null) {
|
4186 | return { data };
|
4187 | } else {
|
4188 | return {
|
4189 | data,
|
4190 | reexports: scope.reexports
|
4191 | };
|
4192 | }
|
4193 | }
|
4194 | compileFull(node, { inj, mod, fac, classMetadata, declarations }, { injectorImports }) {
|
4195 | const factoryFn = compileNgFactoryDefField(fac);
|
4196 | const ngInjectorDef = compileInjector(this.mergeInjectorImports(inj, injectorImports));
|
4197 | const ngModuleDef = compileNgModule(mod);
|
4198 | const statements = ngModuleDef.statements;
|
4199 | const metadata = classMetadata !== null ? compileClassMetadata2(classMetadata) : null;
|
4200 | this.insertMetadataStatement(statements, metadata);
|
4201 | this.appendRemoteScopingStatements(statements, node, declarations);
|
4202 | return this.compileNgModule(factoryFn, ngInjectorDef, ngModuleDef);
|
4203 | }
|
4204 | compilePartial(node, { inj, fac, mod, classMetadata }, { injectorImports }) {
|
4205 | const factoryFn = compileDeclareFactory(fac);
|
4206 | const injectorDef = compileDeclareInjectorFromMetadata(this.mergeInjectorImports(inj, injectorImports));
|
4207 | const ngModuleDef = compileDeclareNgModuleFromMetadata(mod);
|
4208 | const metadata = classMetadata !== null ? compileDeclareClassMetadata2(classMetadata) : null;
|
4209 | this.insertMetadataStatement(ngModuleDef.statements, metadata);
|
4210 | return this.compileNgModule(factoryFn, injectorDef, ngModuleDef);
|
4211 | }
|
4212 | mergeInjectorImports(inj, injectorImports) {
|
4213 | return __spreadProps(__spreadValues({}, inj), { imports: [...inj.imports, ...injectorImports] });
|
4214 | }
|
4215 | insertMetadataStatement(ngModuleStatements, metadata) {
|
4216 | if (metadata !== null) {
|
4217 | ngModuleStatements.unshift(metadata.toStmt());
|
4218 | }
|
4219 | }
|
4220 | appendRemoteScopingStatements(ngModuleStatements, node, declarations) {
|
4221 | const context = getSourceFile(node);
|
4222 | for (const decl of declarations) {
|
4223 | const remoteScope = this.scopeRegistry.getRemoteScope(decl.node);
|
4224 | if (remoteScope !== null) {
|
4225 | const directives = remoteScope.directives.map((directive) => {
|
4226 | const type = this.refEmitter.emit(directive, context);
|
4227 | assertSuccessfulReferenceEmit(type, node, "directive");
|
4228 | return type.expression;
|
4229 | });
|
4230 | const pipes = remoteScope.pipes.map((pipe) => {
|
4231 | const type = this.refEmitter.emit(pipe, context);
|
4232 | assertSuccessfulReferenceEmit(type, node, "pipe");
|
4233 | return type.expression;
|
4234 | });
|
4235 | const directiveArray = new LiteralArrayExpr2(directives);
|
4236 | const pipesArray = new LiteralArrayExpr2(pipes);
|
4237 | const componentType = this.refEmitter.emit(decl, context);
|
4238 | assertSuccessfulReferenceEmit(componentType, node, "component");
|
4239 | const declExpr = componentType.expression;
|
4240 | const setComponentScope = new ExternalExpr4(R3Identifiers.setComponentScope);
|
4241 | const callExpr = new InvokeFunctionExpr(setComponentScope, [declExpr, directiveArray, pipesArray]);
|
4242 | ngModuleStatements.push(callExpr.toStmt());
|
4243 | }
|
4244 | }
|
4245 | }
|
4246 | compileNgModule(factoryFn, injectorDef, ngModuleDef) {
|
4247 | const res = [
|
4248 | factoryFn,
|
4249 | {
|
4250 | name: "\u0275mod",
|
4251 | initializer: ngModuleDef.expression,
|
4252 | statements: ngModuleDef.statements,
|
4253 | type: ngModuleDef.type
|
4254 | },
|
4255 | {
|
4256 | name: "\u0275inj",
|
4257 | initializer: injectorDef.expression,
|
4258 | statements: injectorDef.statements,
|
4259 | type: injectorDef.type
|
4260 | }
|
4261 | ];
|
4262 | return res;
|
4263 | }
|
4264 | _toR3Reference(origin, valueRef, valueContext, typeContext) {
|
4265 | if (valueRef.hasOwningModuleGuess) {
|
4266 | return toR3Reference(origin, valueRef, valueRef, valueContext, valueContext, this.refEmitter);
|
4267 | } else {
|
4268 | let typeRef = valueRef;
|
4269 | let typeNode = this.reflector.getDtsDeclaration(typeRef.node);
|
4270 | if (typeNode !== null && isNamedClassDeclaration(typeNode)) {
|
4271 | typeRef = new Reference(typeNode);
|
4272 | }
|
4273 | return toR3Reference(origin, valueRef, typeRef, valueContext, typeContext, this.refEmitter);
|
4274 | }
|
4275 | }
|
4276 | _extractModuleFromModuleWithProvidersFn(node) {
|
4277 | const type = node.type || null;
|
4278 | return type && (this._reflectModuleFromTypeParam(type, node) || this._reflectModuleFromLiteralType(type));
|
4279 | }
|
4280 | _reflectModuleFromTypeParam(type, node) {
|
4281 | if (!ts17.isTypeReferenceNode(type)) {
|
4282 | return null;
|
4283 | }
|
4284 | const typeName = type && (ts17.isIdentifier(type.typeName) && type.typeName || ts17.isQualifiedName(type.typeName) && type.typeName.right) || null;
|
4285 | if (typeName === null) {
|
4286 | return null;
|
4287 | }
|
4288 | const id = this.reflector.getImportOfIdentifier(typeName);
|
4289 | if (id === null || id.name !== "ModuleWithProviders") {
|
4290 | return null;
|
4291 | }
|
4292 | if (!this.isCore && id.from !== "@angular/core") {
|
4293 | return null;
|
4294 | }
|
4295 | if (type.typeArguments === void 0 || type.typeArguments.length !== 1) {
|
4296 | const parent = ts17.isMethodDeclaration(node) && ts17.isClassDeclaration(node.parent) ? node.parent : null;
|
4297 | const symbolName = (parent && parent.name ? parent.name.getText() + "." : "") + (node.name ? node.name.getText() : "anonymous");
|
4298 | throw new FatalDiagnosticError(ErrorCode.NGMODULE_MODULE_WITH_PROVIDERS_MISSING_GENERIC, type, `${symbolName} returns a ModuleWithProviders type without a generic type argument. Please add a generic type argument to the ModuleWithProviders type. If this occurrence is in library code you don't control, please contact the library authors.`);
|
4299 | }
|
4300 | const arg = type.typeArguments[0];
|
4301 | return typeNodeToValueExpr(arg);
|
4302 | }
|
4303 | _reflectModuleFromLiteralType(type) {
|
4304 | if (!ts17.isIntersectionTypeNode(type)) {
|
4305 | return null;
|
4306 | }
|
4307 | for (const t of type.types) {
|
4308 | if (ts17.isTypeLiteralNode(t)) {
|
4309 | for (const m of t.members) {
|
4310 | const ngModuleType = ts17.isPropertySignature(m) && ts17.isIdentifier(m.name) && m.name.text === "ngModule" && m.type || null;
|
4311 | const ngModuleExpression = ngModuleType && typeNodeToValueExpr(ngModuleType);
|
4312 | if (ngModuleExpression) {
|
4313 | return ngModuleExpression;
|
4314 | }
|
4315 | }
|
4316 | }
|
4317 | }
|
4318 | return null;
|
4319 | }
|
4320 | isClassDeclarationReference(ref) {
|
4321 | return this.reflector.isClass(ref.node);
|
4322 | }
|
4323 | resolveTypeList(expr, resolvedList, className, arrayName) {
|
4324 | const refList = [];
|
4325 | if (!Array.isArray(resolvedList)) {
|
4326 | throw createValueHasWrongTypeError(expr, resolvedList, `Expected array when reading the NgModule.${arrayName} of ${className}`);
|
4327 | }
|
4328 | resolvedList.forEach((entry, idx) => {
|
4329 | if (entry instanceof Map && entry.has("ngModule")) {
|
4330 | entry = entry.get("ngModule");
|
4331 | }
|
4332 | if (Array.isArray(entry)) {
|
4333 | refList.push(...this.resolveTypeList(expr, entry, className, arrayName));
|
4334 | } else if (entry instanceof Reference) {
|
4335 | if (!this.isClassDeclarationReference(entry)) {
|
4336 | throw createValueHasWrongTypeError(entry.node, entry, `Value at position ${idx} in the NgModule.${arrayName} of ${className} is not a class`);
|
4337 | }
|
4338 | refList.push(entry);
|
4339 | } else {
|
4340 | throw createValueHasWrongTypeError(expr, entry, `Value at position ${idx} in the NgModule.${arrayName} of ${className} is not a reference`);
|
4341 | }
|
4342 | });
|
4343 | return refList;
|
4344 | }
|
4345 | };
|
4346 | function isNgModule(node, compilation) {
|
4347 | return !compilation.directives.some((directive) => directive.ref.node === node) && !compilation.pipes.some((pipe) => pipe.ref.node === node);
|
4348 | }
|
4349 |
|
4350 |
|
4351 | var EMPTY_MAP = new Map();
|
4352 | var EMPTY_ARRAY = [];
|
4353 | var ComponentSymbol = class extends DirectiveSymbol {
|
4354 | constructor() {
|
4355 | super(...arguments);
|
4356 | this.usedDirectives = [];
|
4357 | this.usedPipes = [];
|
4358 | this.isRemotelyScoped = false;
|
4359 | }
|
4360 | isEmitAffected(previousSymbol, publicApiAffected) {
|
4361 | if (!(previousSymbol instanceof ComponentSymbol)) {
|
4362 | return true;
|
4363 | }
|
4364 | const isSymbolUnaffected = (current, previous) => isReferenceEqual(current, previous) && !publicApiAffected.has(current.symbol);
|
4365 | return this.isRemotelyScoped !== previousSymbol.isRemotelyScoped || !isArrayEqual(this.usedDirectives, previousSymbol.usedDirectives, isSymbolUnaffected) || !isArrayEqual(this.usedPipes, previousSymbol.usedPipes, isSymbolUnaffected);
|
4366 | }
|
4367 | isTypeCheckBlockAffected(previousSymbol, typeCheckApiAffected) {
|
4368 | if (!(previousSymbol instanceof ComponentSymbol)) {
|
4369 | return true;
|
4370 | }
|
4371 | const isInheritanceChainAffected = (symbol) => {
|
4372 | let currentSymbol = symbol;
|
4373 | while (currentSymbol instanceof DirectiveSymbol) {
|
4374 | if (typeCheckApiAffected.has(currentSymbol)) {
|
4375 | return true;
|
4376 | }
|
4377 | currentSymbol = currentSymbol.baseClass;
|
4378 | }
|
4379 | return false;
|
4380 | };
|
4381 | const isDirectiveUnaffected = (current, previous) => isReferenceEqual(current, previous) && !isInheritanceChainAffected(current.symbol);
|
4382 | const isPipeUnaffected = (current, previous) => isReferenceEqual(current, previous) && !typeCheckApiAffected.has(current.symbol);
|
4383 | return !isArrayEqual(this.usedDirectives, previousSymbol.usedDirectives, isDirectiveUnaffected) || !isArrayEqual(this.usedPipes, previousSymbol.usedPipes, isPipeUnaffected);
|
4384 | }
|
4385 | };
|
4386 | var ComponentDecoratorHandler = class {
|
4387 | constructor(reflector, evaluator, metaRegistry, metaReader, scopeReader, scopeRegistry, typeCheckScopeRegistry, resourceRegistry, isCore, resourceLoader, rootDirs, defaultPreserveWhitespaces, i18nUseExternalIds, enableI18nLegacyMessageIdFormat, usePoisonedData, i18nNormalizeLineEndingsInICUs, moduleResolver, cycleAnalyzer, cycleHandlingStrategy, refEmitter, depTracker, injectableRegistry, semanticDepGraphUpdater, annotateForClosureCompiler, perf) {
|
4388 | this.reflector = reflector;
|
4389 | this.evaluator = evaluator;
|
4390 | this.metaRegistry = metaRegistry;
|
4391 | this.metaReader = metaReader;
|
4392 | this.scopeReader = scopeReader;
|
4393 | this.scopeRegistry = scopeRegistry;
|
4394 | this.typeCheckScopeRegistry = typeCheckScopeRegistry;
|
4395 | this.resourceRegistry = resourceRegistry;
|
4396 | this.isCore = isCore;
|
4397 | this.resourceLoader = resourceLoader;
|
4398 | this.rootDirs = rootDirs;
|
4399 | this.defaultPreserveWhitespaces = defaultPreserveWhitespaces;
|
4400 | this.i18nUseExternalIds = i18nUseExternalIds;
|
4401 | this.enableI18nLegacyMessageIdFormat = enableI18nLegacyMessageIdFormat;
|
4402 | this.usePoisonedData = usePoisonedData;
|
4403 | this.i18nNormalizeLineEndingsInICUs = i18nNormalizeLineEndingsInICUs;
|
4404 | this.moduleResolver = moduleResolver;
|
4405 | this.cycleAnalyzer = cycleAnalyzer;
|
4406 | this.cycleHandlingStrategy = cycleHandlingStrategy;
|
4407 | this.refEmitter = refEmitter;
|
4408 | this.depTracker = depTracker;
|
4409 | this.injectableRegistry = injectableRegistry;
|
4410 | this.semanticDepGraphUpdater = semanticDepGraphUpdater;
|
4411 | this.annotateForClosureCompiler = annotateForClosureCompiler;
|
4412 | this.perf = perf;
|
4413 | this.literalCache = new Map();
|
4414 | this.elementSchemaRegistry = new DomElementSchemaRegistry();
|
4415 | this.preanalyzeTemplateCache = new Map();
|
4416 | this.preanalyzeStylesCache = new Map();
|
4417 | this.precedence = HandlerPrecedence.PRIMARY;
|
4418 | this.name = ComponentDecoratorHandler.name;
|
4419 | }
|
4420 | detect(node, decorators) {
|
4421 | if (!decorators) {
|
4422 | return void 0;
|
4423 | }
|
4424 | const decorator = findAngularDecorator(decorators, "Component", this.isCore);
|
4425 | if (decorator !== void 0) {
|
4426 | return {
|
4427 | trigger: decorator.node,
|
4428 | decorator,
|
4429 | metadata: decorator
|
4430 | };
|
4431 | } else {
|
4432 | return void 0;
|
4433 | }
|
4434 | }
|
4435 | preanalyze(node, decorator) {
|
4436 | if (!this.resourceLoader.canPreload) {
|
4437 | return void 0;
|
4438 | }
|
4439 | const meta = this._resolveLiteral(decorator);
|
4440 | const component = reflectObjectLiteral(meta);
|
4441 | const containingFile = node.getSourceFile().fileName;
|
4442 | const resolveStyleUrl = (styleUrl) => {
|
4443 | try {
|
4444 | const resourceUrl = this.resourceLoader.resolve(styleUrl, containingFile);
|
4445 | return this.resourceLoader.preload(resourceUrl, { type: "style", containingFile });
|
4446 | } catch {
|
4447 | return void 0;
|
4448 | }
|
4449 | };
|
4450 | const templateAndTemplateStyleResources = this._preloadAndParseTemplate(node, decorator, component, containingFile).then((template) => {
|
4451 | if (template === null) {
|
4452 | return void 0;
|
4453 | }
|
4454 | return Promise.all(template.styleUrls.map((styleUrl) => resolveStyleUrl(styleUrl))).then(() => void 0);
|
4455 | });
|
4456 | const componentStyleUrls = this._extractComponentStyleUrls(component);
|
4457 | let inlineStyles;
|
4458 | if (component.has("styles")) {
|
4459 | const litStyles = parseFieldArrayValue(component, "styles", this.evaluator);
|
4460 | if (litStyles === null) {
|
4461 | this.preanalyzeStylesCache.set(node, null);
|
4462 | } else {
|
4463 | inlineStyles = Promise.all(litStyles.map((style) => this.resourceLoader.preprocessInline(style, { type: "style", containingFile }))).then((styles) => {
|
4464 | this.preanalyzeStylesCache.set(node, styles);
|
4465 | });
|
4466 | }
|
4467 | } else {
|
4468 | this.preanalyzeStylesCache.set(node, null);
|
4469 | }
|
4470 | return Promise.all([
|
4471 | templateAndTemplateStyleResources,
|
4472 | inlineStyles,
|
4473 | ...componentStyleUrls.map((styleUrl) => resolveStyleUrl(styleUrl.url))
|
4474 | ]).then(() => void 0);
|
4475 | }
|
4476 | analyze(node, decorator, flags = HandlerFlags.NONE) {
|
4477 | var _a, _b;
|
4478 | this.perf.eventCount(PerfEvent.AnalyzeComponent);
|
4479 | const containingFile = node.getSourceFile().fileName;
|
4480 | this.literalCache.delete(decorator);
|
4481 | let diagnostics;
|
4482 | let isPoisoned = false;
|
4483 | const directiveResult = extractDirectiveMetadata(node, decorator, this.reflector, this.evaluator, this.isCore, flags, this.annotateForClosureCompiler, this.elementSchemaRegistry.getDefaultComponentElementName());
|
4484 | if (directiveResult === void 0) {
|
4485 | return {};
|
4486 | }
|
4487 | const { decorator: component, metadata, inputs, outputs } = directiveResult;
|
4488 | const encapsulation = (_a = this._resolveEnumValue(component, "encapsulation", "ViewEncapsulation")) != null ? _a : ViewEncapsulation.Emulated;
|
4489 | const changeDetection = this._resolveEnumValue(component, "changeDetection", "ChangeDetectionStrategy");
|
4490 | let animations = null;
|
4491 | let animationTriggerNames = null;
|
4492 | if (component.has("animations")) {
|
4493 | animations = new WrappedNodeExpr5(component.get("animations"));
|
4494 | const animationsValue = this.evaluator.evaluate(component.get("animations"), animationTriggerResolver);
|
4495 | animationTriggerNames = { includesDynamicAnimations: false, staticTriggerNames: [] };
|
4496 | collectAnimationNames(animationsValue, animationTriggerNames);
|
4497 | }
|
4498 | const relativeContextFilePath = this.rootDirs.reduce((previous, rootDir) => {
|
4499 | const candidate = relative(absoluteFrom(rootDir), absoluteFrom(containingFile));
|
4500 | if (previous === void 0 || candidate.length < previous.length) {
|
4501 | return candidate;
|
4502 | } else {
|
4503 | return previous;
|
4504 | }
|
4505 | }, void 0);
|
4506 | let viewProvidersRequiringFactory = null;
|
4507 | let providersRequiringFactory = null;
|
4508 | let wrappedViewProviders = null;
|
4509 | if (component.has("viewProviders")) {
|
4510 | const viewProviders = component.get("viewProviders");
|
4511 | viewProvidersRequiringFactory = resolveProvidersRequiringFactory(viewProviders, this.reflector, this.evaluator);
|
4512 | wrappedViewProviders = new WrappedNodeExpr5(this.annotateForClosureCompiler ? wrapFunctionExpressionsInParens(viewProviders) : viewProviders);
|
4513 | }
|
4514 | if (component.has("providers")) {
|
4515 | providersRequiringFactory = resolveProvidersRequiringFactory(component.get("providers"), this.reflector, this.evaluator);
|
4516 | }
|
4517 | let template;
|
4518 | if (this.preanalyzeTemplateCache.has(node)) {
|
4519 | const preanalyzed = this.preanalyzeTemplateCache.get(node);
|
4520 | this.preanalyzeTemplateCache.delete(node);
|
4521 | template = preanalyzed;
|
4522 | } else {
|
4523 | const templateDecl = this.parseTemplateDeclaration(decorator, component, containingFile);
|
4524 | template = this.extractTemplate(node, templateDecl);
|
4525 | }
|
4526 | const templateResource = template.declaration.isInline ? { path: null, expression: component.get("template") } : {
|
4527 | path: absoluteFrom(template.declaration.resolvedTemplateUrl),
|
4528 | expression: template.sourceMapping.node
|
4529 | };
|
4530 | let styles = [];
|
4531 | const styleResources = this._extractStyleResources(component, containingFile);
|
4532 | const styleUrls = [
|
4533 | ...this._extractComponentStyleUrls(component),
|
4534 | ...this._extractTemplateStyleUrls(template)
|
4535 | ];
|
4536 | for (const styleUrl of styleUrls) {
|
4537 | try {
|
4538 | const resourceUrl = this.resourceLoader.resolve(styleUrl.url, containingFile);
|
4539 | const resourceStr = this.resourceLoader.load(resourceUrl);
|
4540 | styles.push(resourceStr);
|
4541 | if (this.depTracker !== null) {
|
4542 | this.depTracker.addResourceDependency(node.getSourceFile(), absoluteFrom(resourceUrl));
|
4543 | }
|
4544 | } catch {
|
4545 | if (diagnostics === void 0) {
|
4546 | diagnostics = [];
|
4547 | }
|
4548 | const resourceType = styleUrl.source === 2 ? 2 : 1;
|
4549 | diagnostics.push(this.makeResourceNotFoundError(styleUrl.url, styleUrl.nodeForError, resourceType).toDiagnostic());
|
4550 | }
|
4551 | }
|
4552 | if (encapsulation === ViewEncapsulation.ShadowDom && metadata.selector !== null) {
|
4553 | const selectorError = checkCustomElementSelectorForErrors(metadata.selector);
|
4554 | if (selectorError !== null) {
|
4555 | if (diagnostics === void 0) {
|
4556 | diagnostics = [];
|
4557 | }
|
4558 | diagnostics.push(makeDiagnostic(ErrorCode.COMPONENT_INVALID_SHADOW_DOM_SELECTOR, component.get("selector"), selectorError));
|
4559 | }
|
4560 | }
|
4561 | let inlineStyles = null;
|
4562 | if (this.preanalyzeStylesCache.has(node)) {
|
4563 | inlineStyles = this.preanalyzeStylesCache.get(node);
|
4564 | this.preanalyzeStylesCache.delete(node);
|
4565 | if (inlineStyles !== null) {
|
4566 | styles.push(...inlineStyles);
|
4567 | }
|
4568 | } else {
|
4569 | if (this.resourceLoader.canPreprocess) {
|
4570 | throw new Error("Inline resource processing requires asynchronous preanalyze.");
|
4571 | }
|
4572 | if (component.has("styles")) {
|
4573 | const litStyles = parseFieldArrayValue(component, "styles", this.evaluator);
|
4574 | if (litStyles !== null) {
|
4575 | inlineStyles = [...litStyles];
|
4576 | styles.push(...litStyles);
|
4577 | }
|
4578 | }
|
4579 | }
|
4580 | if (template.styles.length > 0) {
|
4581 | styles.push(...template.styles);
|
4582 | }
|
4583 | const output = {
|
4584 | analysis: {
|
4585 | baseClass: readBaseClass(node, this.reflector, this.evaluator),
|
4586 | inputs,
|
4587 | outputs,
|
4588 | meta: __spreadProps(__spreadValues({}, metadata), {
|
4589 | template: {
|
4590 | nodes: template.nodes,
|
4591 | ngContentSelectors: template.ngContentSelectors
|
4592 | },
|
4593 | encapsulation,
|
4594 | interpolation: (_b = template.interpolationConfig) != null ? _b : DEFAULT_INTERPOLATION_CONFIG,
|
4595 | styles,
|
4596 | animations,
|
4597 | viewProviders: wrappedViewProviders,
|
4598 | i18nUseExternalIds: this.i18nUseExternalIds,
|
4599 | relativeContextFilePath
|
4600 | }),
|
4601 | typeCheckMeta: extractDirectiveTypeCheckMeta(node, inputs, this.reflector),
|
4602 | classMetadata: extractClassMetadata(node, this.reflector, this.isCore, this.annotateForClosureCompiler, (dec) => this._transformDecoratorToInlineResources(dec, component, styles, template)),
|
4603 | template,
|
4604 | providersRequiringFactory,
|
4605 | viewProvidersRequiringFactory,
|
4606 | inlineStyles,
|
4607 | styleUrls,
|
4608 | resources: {
|
4609 | styles: styleResources,
|
4610 | template: templateResource
|
4611 | },
|
4612 | isPoisoned,
|
4613 | animationTriggerNames
|
4614 | },
|
4615 | diagnostics
|
4616 | };
|
4617 | if (changeDetection !== null) {
|
4618 | output.analysis.meta.changeDetection = changeDetection;
|
4619 | }
|
4620 | return output;
|
4621 | }
|
4622 | symbol(node, analysis) {
|
4623 | const typeParameters = extractSemanticTypeParameters(node);
|
4624 | return new ComponentSymbol(node, analysis.meta.selector, analysis.inputs, analysis.outputs, analysis.meta.exportAs, analysis.typeCheckMeta, typeParameters);
|
4625 | }
|
4626 | register(node, analysis) {
|
4627 | const ref = new Reference(node);
|
4628 | this.metaRegistry.registerDirectiveMetadata(__spreadProps(__spreadValues({
|
4629 | type: MetaType.Directive,
|
4630 | ref,
|
4631 | name: node.name.text,
|
4632 | selector: analysis.meta.selector,
|
4633 | exportAs: analysis.meta.exportAs,
|
4634 | inputs: analysis.inputs,
|
4635 | outputs: analysis.outputs,
|
4636 | queries: analysis.meta.queries.map((query) => query.propertyName),
|
4637 | isComponent: true,
|
4638 | baseClass: analysis.baseClass
|
4639 | }, analysis.typeCheckMeta), {
|
4640 | isPoisoned: analysis.isPoisoned,
|
4641 | isStructural: false,
|
4642 | animationTriggerNames: analysis.animationTriggerNames
|
4643 | }));
|
4644 | this.resourceRegistry.registerResources(analysis.resources, node);
|
4645 | this.injectableRegistry.registerInjectable(node);
|
4646 | }
|
4647 | index(context, node, analysis) {
|
4648 | if (analysis.isPoisoned && !this.usePoisonedData) {
|
4649 | return null;
|
4650 | }
|
4651 | const scope = this.scopeReader.getScopeForComponent(node);
|
4652 | const selector = analysis.meta.selector;
|
4653 | const matcher = new SelectorMatcher();
|
4654 | if (scope !== null) {
|
4655 | if ((scope.compilation.isPoisoned || scope.exported.isPoisoned) && !this.usePoisonedData) {
|
4656 | return null;
|
4657 | }
|
4658 | for (const directive of scope.compilation.directives) {
|
4659 | if (directive.selector !== null) {
|
4660 | matcher.addSelectables(CssSelector.parse(directive.selector), directive);
|
4661 | }
|
4662 | }
|
4663 | }
|
4664 | const binder = new R3TargetBinder(matcher);
|
4665 | const boundTemplate = binder.bind({ template: analysis.template.diagNodes });
|
4666 | context.addComponent({
|
4667 | declaration: node,
|
4668 | selector,
|
4669 | boundTemplate,
|
4670 | templateMeta: {
|
4671 | isInline: analysis.template.declaration.isInline,
|
4672 | file: analysis.template.file
|
4673 | }
|
4674 | });
|
4675 | }
|
4676 | typeCheck(ctx, node, meta) {
|
4677 | if (this.typeCheckScopeRegistry === null || !ts18.isClassDeclaration(node)) {
|
4678 | return;
|
4679 | }
|
4680 | if (meta.isPoisoned && !this.usePoisonedData) {
|
4681 | return;
|
4682 | }
|
4683 | const scope = this.typeCheckScopeRegistry.getTypeCheckScope(node);
|
4684 | if (scope.isPoisoned && !this.usePoisonedData) {
|
4685 | return;
|
4686 | }
|
4687 | const binder = new R3TargetBinder(scope.matcher);
|
4688 | ctx.addTemplate(new Reference(node), binder, meta.template.diagNodes, scope.pipes, scope.schemas, meta.template.sourceMapping, meta.template.file, meta.template.errors);
|
4689 | }
|
4690 | extendedTemplateCheck(component, extendedTemplateChecker) {
|
4691 | return extendedTemplateChecker.getDiagnosticsForComponent(component);
|
4692 | }
|
4693 | resolve(node, analysis, symbol) {
|
4694 | if (this.semanticDepGraphUpdater !== null && analysis.baseClass instanceof Reference) {
|
4695 | symbol.baseClass = this.semanticDepGraphUpdater.getSymbol(analysis.baseClass.node);
|
4696 | }
|
4697 | if (analysis.isPoisoned && !this.usePoisonedData) {
|
4698 | return {};
|
4699 | }
|
4700 | const context = node.getSourceFile();
|
4701 | const scope = this.scopeReader.getScopeForComponent(node);
|
4702 | let metadata = analysis.meta;
|
4703 | const data = {
|
4704 | directives: EMPTY_ARRAY,
|
4705 | pipes: EMPTY_MAP,
|
4706 | declarationListEmitMode: 0
|
4707 | };
|
4708 | if (scope !== null && (!scope.compilation.isPoisoned || this.usePoisonedData)) {
|
4709 | const matcher = new SelectorMatcher();
|
4710 | for (const dir of scope.compilation.directives) {
|
4711 | if (dir.selector !== null) {
|
4712 | matcher.addSelectables(CssSelector.parse(dir.selector), dir);
|
4713 | }
|
4714 | }
|
4715 | const pipes = new Map();
|
4716 | for (const pipe of scope.compilation.pipes) {
|
4717 | pipes.set(pipe.name, pipe.ref);
|
4718 | }
|
4719 | const binder = new R3TargetBinder(matcher);
|
4720 | const bound = binder.bind({ template: metadata.template.nodes });
|
4721 | const usedDirectives = bound.getUsedDirectives().map((directive) => {
|
4722 | const type = this.refEmitter.emit(directive.ref, context);
|
4723 | assertSuccessfulReferenceEmit(type, node.name, directive.isComponent ? "component" : "directive");
|
4724 | return {
|
4725 | ref: directive.ref,
|
4726 | type: type.expression,
|
4727 | importedFile: type.importedFile,
|
4728 | selector: directive.selector,
|
4729 | inputs: directive.inputs.propertyNames,
|
4730 | outputs: directive.outputs.propertyNames,
|
4731 | exportAs: directive.exportAs,
|
4732 | isComponent: directive.isComponent
|
4733 | };
|
4734 | });
|
4735 | const usedPipes = [];
|
4736 | for (const pipeName of bound.getUsedPipes()) {
|
4737 | if (!pipes.has(pipeName)) {
|
4738 | continue;
|
4739 | }
|
4740 | const pipe = pipes.get(pipeName);
|
4741 | const type = this.refEmitter.emit(pipe, context);
|
4742 | assertSuccessfulReferenceEmit(type, node.name, "pipe");
|
4743 | usedPipes.push({
|
4744 | ref: pipe,
|
4745 | pipeName,
|
4746 | expression: type.expression,
|
4747 | importedFile: type.importedFile
|
4748 | });
|
4749 | }
|
4750 | if (this.semanticDepGraphUpdater !== null) {
|
4751 | symbol.usedDirectives = usedDirectives.map((dir) => this.semanticDepGraphUpdater.getSemanticReference(dir.ref.node, dir.type));
|
4752 | symbol.usedPipes = usedPipes.map((pipe) => this.semanticDepGraphUpdater.getSemanticReference(pipe.ref.node, pipe.expression));
|
4753 | }
|
4754 | const cyclesFromDirectives = new Map();
|
4755 | for (const usedDirective of usedDirectives) {
|
4756 | const cycle = this._checkForCyclicImport(usedDirective.importedFile, usedDirective.type, context);
|
4757 | if (cycle !== null) {
|
4758 | cyclesFromDirectives.set(usedDirective, cycle);
|
4759 | }
|
4760 | }
|
4761 | const cyclesFromPipes = new Map();
|
4762 | for (const usedPipe of usedPipes) {
|
4763 | const cycle = this._checkForCyclicImport(usedPipe.importedFile, usedPipe.expression, context);
|
4764 | if (cycle !== null) {
|
4765 | cyclesFromPipes.set(usedPipe, cycle);
|
4766 | }
|
4767 | }
|
4768 | const cycleDetected = cyclesFromDirectives.size !== 0 || cyclesFromPipes.size !== 0;
|
4769 | if (!cycleDetected) {
|
4770 | for (const { type, importedFile } of usedDirectives) {
|
4771 | this._recordSyntheticImport(importedFile, type, context);
|
4772 | }
|
4773 | for (const { expression, importedFile } of usedPipes) {
|
4774 | this._recordSyntheticImport(importedFile, expression, context);
|
4775 | }
|
4776 | const wrapDirectivesAndPipesInClosure = usedDirectives.some((dir) => isExpressionForwardReference(dir.type, node.name, context)) || usedPipes.some((pipe) => isExpressionForwardReference(pipe.expression, node.name, context));
|
4777 | data.directives = usedDirectives;
|
4778 | data.pipes = new Map(usedPipes.map((pipe) => [pipe.pipeName, pipe.expression]));
|
4779 | data.declarationListEmitMode = wrapDirectivesAndPipesInClosure ? 1 : 0;
|
4780 | } else {
|
4781 | if (this.cycleHandlingStrategy === 0) {
|
4782 | this.scopeRegistry.setComponentRemoteScope(node, usedDirectives.map((dir) => dir.ref), usedPipes.map((pipe) => pipe.ref));
|
4783 | symbol.isRemotelyScoped = true;
|
4784 | if (this.semanticDepGraphUpdater !== null) {
|
4785 | const moduleSymbol = this.semanticDepGraphUpdater.getSymbol(scope.ngModule);
|
4786 | if (!(moduleSymbol instanceof NgModuleSymbol)) {
|
4787 | throw new Error(`AssertionError: Expected ${scope.ngModule.name} to be an NgModuleSymbol.`);
|
4788 | }
|
4789 | moduleSymbol.addRemotelyScopedComponent(symbol, symbol.usedDirectives, symbol.usedPipes);
|
4790 | }
|
4791 | } else {
|
4792 | const relatedMessages = [];
|
4793 | for (const [dir, cycle] of cyclesFromDirectives) {
|
4794 | relatedMessages.push(makeCyclicImportInfo(dir.ref, dir.isComponent ? "component" : "directive", cycle));
|
4795 | }
|
4796 | for (const [pipe, cycle] of cyclesFromPipes) {
|
4797 | relatedMessages.push(makeCyclicImportInfo(pipe.ref, "pipe", cycle));
|
4798 | }
|
4799 | throw new FatalDiagnosticError(ErrorCode.IMPORT_CYCLE_DETECTED, node, "One or more import cycles would need to be created to compile this component, which is not supported by the current compiler configuration.", relatedMessages);
|
4800 | }
|
4801 | }
|
4802 | }
|
4803 | const diagnostics = [];
|
4804 | if (analysis.providersRequiringFactory !== null && analysis.meta.providers instanceof WrappedNodeExpr5) {
|
4805 | const providerDiagnostics = getProviderDiagnostics(analysis.providersRequiringFactory, analysis.meta.providers.node, this.injectableRegistry);
|
4806 | diagnostics.push(...providerDiagnostics);
|
4807 | }
|
4808 | if (analysis.viewProvidersRequiringFactory !== null && analysis.meta.viewProviders instanceof WrappedNodeExpr5) {
|
4809 | const viewProviderDiagnostics = getProviderDiagnostics(analysis.viewProvidersRequiringFactory, analysis.meta.viewProviders.node, this.injectableRegistry);
|
4810 | diagnostics.push(...viewProviderDiagnostics);
|
4811 | }
|
4812 | const directiveDiagnostics = getDirectiveDiagnostics(node, this.metaReader, this.evaluator, this.reflector, this.scopeRegistry, "Component");
|
4813 | if (directiveDiagnostics !== null) {
|
4814 | diagnostics.push(...directiveDiagnostics);
|
4815 | }
|
4816 | if (diagnostics.length > 0) {
|
4817 | return { diagnostics };
|
4818 | }
|
4819 | return { data };
|
4820 | }
|
4821 | xi18n(ctx, node, analysis) {
|
4822 | var _a;
|
4823 | ctx.updateFromTemplate(analysis.template.content, analysis.template.declaration.resolvedTemplateUrl, (_a = analysis.template.interpolationConfig) != null ? _a : DEFAULT_INTERPOLATION_CONFIG);
|
4824 | }
|
4825 | updateResources(node, analysis) {
|
4826 | const containingFile = node.getSourceFile().fileName;
|
4827 | const templateDecl = analysis.template.declaration;
|
4828 | if (!templateDecl.isInline) {
|
4829 | analysis.template = this.extractTemplate(node, templateDecl);
|
4830 | }
|
4831 | let styles = [];
|
4832 | if (analysis.styleUrls !== null) {
|
4833 | for (const styleUrl of analysis.styleUrls) {
|
4834 | try {
|
4835 | const resolvedStyleUrl = this.resourceLoader.resolve(styleUrl.url, containingFile);
|
4836 | const styleText = this.resourceLoader.load(resolvedStyleUrl);
|
4837 | styles.push(styleText);
|
4838 | } catch (e) {
|
4839 | }
|
4840 | }
|
4841 | }
|
4842 | if (analysis.inlineStyles !== null) {
|
4843 | for (const styleText of analysis.inlineStyles) {
|
4844 | styles.push(styleText);
|
4845 | }
|
4846 | }
|
4847 | for (const styleText of analysis.template.styles) {
|
4848 | styles.push(styleText);
|
4849 | }
|
4850 | analysis.meta.styles = styles;
|
4851 | }
|
4852 | compileFull(node, analysis, resolution, pool) {
|
4853 | if (analysis.template.errors !== null && analysis.template.errors.length > 0) {
|
4854 | return [];
|
4855 | }
|
4856 | const meta = __spreadValues(__spreadValues({}, analysis.meta), resolution);
|
4857 | const fac = compileNgFactoryDefField(toFactoryMetadata(meta, FactoryTarget3.Component));
|
4858 | const def = compileComponentFromMetadata(meta, pool, makeBindingParser2());
|
4859 | const classMetadata = analysis.classMetadata !== null ? compileClassMetadata3(analysis.classMetadata).toStmt() : null;
|
4860 | return compileResults(fac, def, classMetadata, "\u0275cmp");
|
4861 | }
|
4862 | compilePartial(node, analysis, resolution) {
|
4863 | if (analysis.template.errors !== null && analysis.template.errors.length > 0) {
|
4864 | return [];
|
4865 | }
|
4866 | const templateInfo = {
|
4867 | content: analysis.template.content,
|
4868 | sourceUrl: analysis.template.declaration.resolvedTemplateUrl,
|
4869 | isInline: analysis.template.declaration.isInline,
|
4870 | inlineTemplateLiteralExpression: analysis.template.sourceMapping.type === "direct" ? new WrappedNodeExpr5(analysis.template.sourceMapping.node) : null
|
4871 | };
|
4872 | const meta = __spreadValues(__spreadValues({}, analysis.meta), resolution);
|
4873 | const fac = compileDeclareFactory(toFactoryMetadata(meta, FactoryTarget3.Component));
|
4874 | const def = compileDeclareComponentFromMetadata(meta, analysis.template, templateInfo);
|
4875 | const classMetadata = analysis.classMetadata !== null ? compileDeclareClassMetadata3(analysis.classMetadata).toStmt() : null;
|
4876 | return compileResults(fac, def, classMetadata, "\u0275cmp");
|
4877 | }
|
4878 | _transformDecoratorToInlineResources(dec, component, styles, template) {
|
4879 | if (dec.name !== "Component") {
|
4880 | return dec;
|
4881 | }
|
4882 | if (!component.has("templateUrl") && !component.has("styleUrls")) {
|
4883 | return dec;
|
4884 | }
|
4885 | const metadata = new Map(component);
|
4886 | if (metadata.has("templateUrl")) {
|
4887 | metadata.delete("templateUrl");
|
4888 | metadata.set("template", ts18.createStringLiteral(template.content));
|
4889 | }
|
4890 | if (metadata.has("styleUrls")) {
|
4891 | metadata.delete("styleUrls");
|
4892 | metadata.set("styles", ts18.createArrayLiteral(styles.map((s) => ts18.createStringLiteral(s))));
|
4893 | }
|
4894 | const newMetadataFields = [];
|
4895 | for (const [name, value] of metadata.entries()) {
|
4896 | newMetadataFields.push(ts18.createPropertyAssignment(name, value));
|
4897 | }
|
4898 | return __spreadProps(__spreadValues({}, dec), { args: [ts18.createObjectLiteral(newMetadataFields)] });
|
4899 | }
|
4900 | _resolveLiteral(decorator) {
|
4901 | if (this.literalCache.has(decorator)) {
|
4902 | return this.literalCache.get(decorator);
|
4903 | }
|
4904 | if (decorator.args === null || decorator.args.length !== 1) {
|
4905 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), `Incorrect number of arguments to @Component decorator`);
|
4906 | }
|
4907 | const meta = unwrapExpression(decorator.args[0]);
|
4908 | if (!ts18.isObjectLiteralExpression(meta)) {
|
4909 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, meta, `Decorator argument must be literal.`);
|
4910 | }
|
4911 | this.literalCache.set(decorator, meta);
|
4912 | return meta;
|
4913 | }
|
4914 | _resolveEnumValue(component, field, enumSymbolName) {
|
4915 | let resolved = null;
|
4916 | if (component.has(field)) {
|
4917 | const expr = component.get(field);
|
4918 | const value = this.evaluator.evaluate(expr);
|
4919 | if (value instanceof EnumValue && isAngularCoreReference(value.enumRef, enumSymbolName)) {
|
4920 | resolved = value.resolved;
|
4921 | } else {
|
4922 | throw createValueHasWrongTypeError(expr, value, `${field} must be a member of ${enumSymbolName} enum from @angular/core`);
|
4923 | }
|
4924 | }
|
4925 | return resolved;
|
4926 | }
|
4927 | _extractComponentStyleUrls(component) {
|
4928 | if (!component.has("styleUrls")) {
|
4929 | return [];
|
4930 | }
|
4931 | return this._extractStyleUrlsFromExpression(component.get("styleUrls"));
|
4932 | }
|
4933 | _extractStyleUrlsFromExpression(styleUrlsExpr) {
|
4934 | const styleUrls = [];
|
4935 | if (ts18.isArrayLiteralExpression(styleUrlsExpr)) {
|
4936 | for (const styleUrlExpr of styleUrlsExpr.elements) {
|
4937 | if (ts18.isSpreadElement(styleUrlExpr)) {
|
4938 | styleUrls.push(...this._extractStyleUrlsFromExpression(styleUrlExpr.expression));
|
4939 | } else {
|
4940 | const styleUrl = this.evaluator.evaluate(styleUrlExpr);
|
4941 | if (typeof styleUrl !== "string") {
|
4942 | throw createValueHasWrongTypeError(styleUrlExpr, styleUrl, "styleUrl must be a string");
|
4943 | }
|
4944 | styleUrls.push({
|
4945 | url: styleUrl,
|
4946 | source: 2,
|
4947 | nodeForError: styleUrlExpr
|
4948 | });
|
4949 | }
|
4950 | }
|
4951 | } else {
|
4952 | const evaluatedStyleUrls = this.evaluator.evaluate(styleUrlsExpr);
|
4953 | if (!isStringArray(evaluatedStyleUrls)) {
|
4954 | throw createValueHasWrongTypeError(styleUrlsExpr, evaluatedStyleUrls, "styleUrls must be an array of strings");
|
4955 | }
|
4956 | for (const styleUrl of evaluatedStyleUrls) {
|
4957 | styleUrls.push({
|
4958 | url: styleUrl,
|
4959 | source: 2,
|
4960 | nodeForError: styleUrlsExpr
|
4961 | });
|
4962 | }
|
4963 | }
|
4964 | return styleUrls;
|
4965 | }
|
4966 | _extractStyleResources(component, containingFile) {
|
4967 | const styles = new Set();
|
4968 | function stringLiteralElements(array) {
|
4969 | return array.elements.filter((e) => ts18.isStringLiteralLike(e));
|
4970 | }
|
4971 | const styleUrlsExpr = component.get("styleUrls");
|
4972 | if (styleUrlsExpr !== void 0 && ts18.isArrayLiteralExpression(styleUrlsExpr)) {
|
4973 | for (const expression of stringLiteralElements(styleUrlsExpr)) {
|
4974 | try {
|
4975 | const resourceUrl = this.resourceLoader.resolve(expression.text, containingFile);
|
4976 | styles.add({ path: absoluteFrom(resourceUrl), expression });
|
4977 | } catch {
|
4978 | }
|
4979 | }
|
4980 | }
|
4981 | const stylesExpr = component.get("styles");
|
4982 | if (stylesExpr !== void 0 && ts18.isArrayLiteralExpression(stylesExpr)) {
|
4983 | for (const expression of stringLiteralElements(stylesExpr)) {
|
4984 | styles.add({ path: null, expression });
|
4985 | }
|
4986 | }
|
4987 | return styles;
|
4988 | }
|
4989 | _preloadAndParseTemplate(node, decorator, component, containingFile) {
|
4990 | if (component.has("templateUrl")) {
|
4991 | const templateUrlExpr = component.get("templateUrl");
|
4992 | const templateUrl = this.evaluator.evaluate(templateUrlExpr);
|
4993 | if (typeof templateUrl !== "string") {
|
4994 | throw createValueHasWrongTypeError(templateUrlExpr, templateUrl, "templateUrl must be a string");
|
4995 | }
|
4996 | try {
|
4997 | const resourceUrl = this.resourceLoader.resolve(templateUrl, containingFile);
|
4998 | const templatePromise = this.resourceLoader.preload(resourceUrl, { type: "template", containingFile });
|
4999 | if (templatePromise !== void 0) {
|
5000 | return templatePromise.then(() => {
|
5001 | const templateDecl = this.parseTemplateDeclaration(decorator, component, containingFile);
|
5002 | const template = this.extractTemplate(node, templateDecl);
|
5003 | this.preanalyzeTemplateCache.set(node, template);
|
5004 | return template;
|
5005 | });
|
5006 | } else {
|
5007 | return Promise.resolve(null);
|
5008 | }
|
5009 | } catch (e) {
|
5010 | throw this.makeResourceNotFoundError(templateUrl, templateUrlExpr, 0);
|
5011 | }
|
5012 | } else {
|
5013 | const templateDecl = this.parseTemplateDeclaration(decorator, component, containingFile);
|
5014 | const template = this.extractTemplate(node, templateDecl);
|
5015 | this.preanalyzeTemplateCache.set(node, template);
|
5016 | return Promise.resolve(template);
|
5017 | }
|
5018 | }
|
5019 | extractTemplate(node, template) {
|
5020 | if (template.isInline) {
|
5021 | let sourceStr;
|
5022 | let sourceParseRange = null;
|
5023 | let templateContent;
|
5024 | let sourceMapping;
|
5025 | let escapedString = false;
|
5026 | let sourceMapUrl;
|
5027 | if (ts18.isStringLiteral(template.expression) || ts18.isNoSubstitutionTemplateLiteral(template.expression)) {
|
5028 | sourceParseRange = getTemplateRange(template.expression);
|
5029 | sourceStr = template.expression.getSourceFile().text;
|
5030 | templateContent = template.expression.text;
|
5031 | escapedString = true;
|
5032 | sourceMapping = {
|
5033 | type: "direct",
|
5034 | node: template.expression
|
5035 | };
|
5036 | sourceMapUrl = template.resolvedTemplateUrl;
|
5037 | } else {
|
5038 | const resolvedTemplate = this.evaluator.evaluate(template.expression);
|
5039 | if (typeof resolvedTemplate !== "string") {
|
5040 | throw createValueHasWrongTypeError(template.expression, resolvedTemplate, "template must be a string");
|
5041 | }
|
5042 | sourceStr = resolvedTemplate;
|
5043 | templateContent = resolvedTemplate;
|
5044 | sourceMapping = {
|
5045 | type: "indirect",
|
5046 | node: template.expression,
|
5047 | componentClass: node,
|
5048 | template: templateContent
|
5049 | };
|
5050 | sourceMapUrl = null;
|
5051 | }
|
5052 | return __spreadProps(__spreadValues({}, this._parseTemplate(template, sourceStr, sourceParseRange, escapedString, sourceMapUrl)), {
|
5053 | content: templateContent,
|
5054 | sourceMapping,
|
5055 | declaration: template
|
5056 | });
|
5057 | } else {
|
5058 | const templateContent = this.resourceLoader.load(template.resolvedTemplateUrl);
|
5059 | if (this.depTracker !== null) {
|
5060 | this.depTracker.addResourceDependency(node.getSourceFile(), absoluteFrom(template.resolvedTemplateUrl));
|
5061 | }
|
5062 | return __spreadProps(__spreadValues({}, this._parseTemplate(template, templateContent, null, false, template.resolvedTemplateUrl)), {
|
5063 | content: templateContent,
|
5064 | sourceMapping: {
|
5065 | type: "external",
|
5066 | componentClass: node,
|
5067 | node: template.templateUrlExpression,
|
5068 | template: templateContent,
|
5069 | templateUrl: template.resolvedTemplateUrl
|
5070 | },
|
5071 | declaration: template
|
5072 | });
|
5073 | }
|
5074 | }
|
5075 | _parseTemplate(template, sourceStr, sourceParseRange, escapedString, sourceMapUrl) {
|
5076 | const i18nNormalizeLineEndingsInICUs = escapedString || this.i18nNormalizeLineEndingsInICUs;
|
5077 | const parsedTemplate = parseTemplate(sourceStr, sourceMapUrl != null ? sourceMapUrl : "", {
|
5078 | preserveWhitespaces: template.preserveWhitespaces,
|
5079 | interpolationConfig: template.interpolationConfig,
|
5080 | range: sourceParseRange != null ? sourceParseRange : void 0,
|
5081 | escapedString,
|
5082 | enableI18nLegacyMessageIdFormat: this.enableI18nLegacyMessageIdFormat,
|
5083 | i18nNormalizeLineEndingsInICUs,
|
5084 | alwaysAttemptHtmlToR3AstConversion: this.usePoisonedData
|
5085 | });
|
5086 | const { nodes: diagNodes } = parseTemplate(sourceStr, sourceMapUrl != null ? sourceMapUrl : "", {
|
5087 | preserveWhitespaces: true,
|
5088 | preserveLineEndings: true,
|
5089 | interpolationConfig: template.interpolationConfig,
|
5090 | range: sourceParseRange != null ? sourceParseRange : void 0,
|
5091 | escapedString,
|
5092 | enableI18nLegacyMessageIdFormat: this.enableI18nLegacyMessageIdFormat,
|
5093 | i18nNormalizeLineEndingsInICUs,
|
5094 | leadingTriviaChars: [],
|
5095 | alwaysAttemptHtmlToR3AstConversion: this.usePoisonedData
|
5096 | });
|
5097 | return __spreadProps(__spreadValues({}, parsedTemplate), {
|
5098 | diagNodes,
|
5099 | file: new ParseSourceFile2(sourceStr, sourceMapUrl != null ? sourceMapUrl : "")
|
5100 | });
|
5101 | }
|
5102 | parseTemplateDeclaration(decorator, component, containingFile) {
|
5103 | let preserveWhitespaces = this.defaultPreserveWhitespaces;
|
5104 | if (component.has("preserveWhitespaces")) {
|
5105 | const expr = component.get("preserveWhitespaces");
|
5106 | const value = this.evaluator.evaluate(expr);
|
5107 | if (typeof value !== "boolean") {
|
5108 | throw createValueHasWrongTypeError(expr, value, "preserveWhitespaces must be a boolean");
|
5109 | }
|
5110 | preserveWhitespaces = value;
|
5111 | }
|
5112 | let interpolationConfig = DEFAULT_INTERPOLATION_CONFIG;
|
5113 | if (component.has("interpolation")) {
|
5114 | const expr = component.get("interpolation");
|
5115 | const value = this.evaluator.evaluate(expr);
|
5116 | if (!Array.isArray(value) || value.length !== 2 || !value.every((element) => typeof element === "string")) {
|
5117 | throw createValueHasWrongTypeError(expr, value, "interpolation must be an array with 2 elements of string type");
|
5118 | }
|
5119 | interpolationConfig = InterpolationConfig.fromArray(value);
|
5120 | }
|
5121 | if (component.has("templateUrl")) {
|
5122 | const templateUrlExpr = component.get("templateUrl");
|
5123 | const templateUrl = this.evaluator.evaluate(templateUrlExpr);
|
5124 | if (typeof templateUrl !== "string") {
|
5125 | throw createValueHasWrongTypeError(templateUrlExpr, templateUrl, "templateUrl must be a string");
|
5126 | }
|
5127 | try {
|
5128 | const resourceUrl = this.resourceLoader.resolve(templateUrl, containingFile);
|
5129 | return {
|
5130 | isInline: false,
|
5131 | interpolationConfig,
|
5132 | preserveWhitespaces,
|
5133 | templateUrl,
|
5134 | templateUrlExpression: templateUrlExpr,
|
5135 | resolvedTemplateUrl: resourceUrl
|
5136 | };
|
5137 | } catch (e) {
|
5138 | throw this.makeResourceNotFoundError(templateUrl, templateUrlExpr, 0);
|
5139 | }
|
5140 | } else if (component.has("template")) {
|
5141 | return {
|
5142 | isInline: true,
|
5143 | interpolationConfig,
|
5144 | preserveWhitespaces,
|
5145 | expression: component.get("template"),
|
5146 | templateUrl: containingFile,
|
5147 | resolvedTemplateUrl: containingFile
|
5148 | };
|
5149 | } else {
|
5150 | throw new FatalDiagnosticError(ErrorCode.COMPONENT_MISSING_TEMPLATE, Decorator.nodeForError(decorator), "component is missing a template");
|
5151 | }
|
5152 | }
|
5153 | _resolveImportedFile(importedFile, expr, origin) {
|
5154 | if (importedFile !== "unknown") {
|
5155 | return importedFile;
|
5156 | }
|
5157 | if (!(expr instanceof ExternalExpr5)) {
|
5158 | return null;
|
5159 | }
|
5160 | return this.moduleResolver.resolveModule(expr.value.moduleName, origin.fileName);
|
5161 | }
|
5162 | _checkForCyclicImport(importedFile, expr, origin) {
|
5163 | const imported = this._resolveImportedFile(importedFile, expr, origin);
|
5164 | if (imported === null) {
|
5165 | return null;
|
5166 | }
|
5167 | return this.cycleAnalyzer.wouldCreateCycle(origin, imported);
|
5168 | }
|
5169 | _recordSyntheticImport(importedFile, expr, origin) {
|
5170 | const imported = this._resolveImportedFile(importedFile, expr, origin);
|
5171 | if (imported === null) {
|
5172 | return;
|
5173 | }
|
5174 | this.cycleAnalyzer.recordSyntheticImport(origin, imported);
|
5175 | }
|
5176 | makeResourceNotFoundError(file, nodeForError, resourceType) {
|
5177 | let errorText;
|
5178 | switch (resourceType) {
|
5179 | case 0:
|
5180 | errorText = `Could not find template file '${file}'.`;
|
5181 | break;
|
5182 | case 1:
|
5183 | errorText = `Could not find stylesheet file '${file}' linked from the template.`;
|
5184 | break;
|
5185 | case 2:
|
5186 | errorText = `Could not find stylesheet file '${file}'.`;
|
5187 | break;
|
5188 | }
|
5189 | return new FatalDiagnosticError(ErrorCode.COMPONENT_RESOURCE_NOT_FOUND, nodeForError, errorText);
|
5190 | }
|
5191 | _extractTemplateStyleUrls(template) {
|
5192 | if (template.styleUrls === null) {
|
5193 | return [];
|
5194 | }
|
5195 | const nodeForError = getTemplateDeclarationNodeForError(template.declaration);
|
5196 | return template.styleUrls.map((url) => ({ url, source: 1, nodeForError }));
|
5197 | }
|
5198 | };
|
5199 | function getTemplateRange(templateExpr) {
|
5200 | const startPos = templateExpr.getStart() + 1;
|
5201 | const { line, character } = ts18.getLineAndCharacterOfPosition(templateExpr.getSourceFile(), startPos);
|
5202 | return {
|
5203 | startPos,
|
5204 | startLine: line,
|
5205 | startCol: character,
|
5206 | endPos: templateExpr.getEnd() - 1
|
5207 | };
|
5208 | }
|
5209 | function isStringArray(resolvedValue) {
|
5210 | return Array.isArray(resolvedValue) && resolvedValue.every((elem) => typeof elem === "string");
|
5211 | }
|
5212 | function getTemplateDeclarationNodeForError(declaration) {
|
5213 | switch (declaration.isInline) {
|
5214 | case true:
|
5215 | return declaration.expression;
|
5216 | case false:
|
5217 | return declaration.templateUrlExpression;
|
5218 | }
|
5219 | }
|
5220 | function makeCyclicImportInfo(ref, type, cycle) {
|
5221 | const name = ref.debugName || "(unknown)";
|
5222 | const path = cycle.getPath().map((sf) => sf.fileName).join(" -> ");
|
5223 | const message = `The ${type} '${name}' is used in the template but importing it would create a cycle: `;
|
5224 | return makeRelatedInformation(ref.node, message + path);
|
5225 | }
|
5226 | function checkCustomElementSelectorForErrors(selector) {
|
5227 | if (selector.includes(".") || selector.includes("[") && selector.includes("]")) {
|
5228 | return null;
|
5229 | }
|
5230 | if (!/^[a-z]/.test(selector)) {
|
5231 | return "Selector of a ShadowDom-encapsulated component must start with a lower case letter.";
|
5232 | }
|
5233 | if (/[A-Z]/.test(selector)) {
|
5234 | return "Selector of a ShadowDom-encapsulated component must all be in lower case.";
|
5235 | }
|
5236 | if (!selector.includes("-")) {
|
5237 | return "Selector of a component that uses ViewEncapsulation.ShadowDom must contain a hyphen.";
|
5238 | }
|
5239 | return null;
|
5240 | }
|
5241 | function collectAnimationNames(value, animationTriggerNames) {
|
5242 | if (value instanceof Map) {
|
5243 | const name = value.get("name");
|
5244 | if (typeof name === "string") {
|
5245 | animationTriggerNames.staticTriggerNames.push(name);
|
5246 | } else {
|
5247 | animationTriggerNames.includesDynamicAnimations = true;
|
5248 | }
|
5249 | } else if (Array.isArray(value)) {
|
5250 | for (const resolvedValue of value) {
|
5251 | collectAnimationNames(resolvedValue, animationTriggerNames);
|
5252 | }
|
5253 | } else {
|
5254 | animationTriggerNames.includesDynamicAnimations = true;
|
5255 | }
|
5256 | }
|
5257 |
|
5258 |
|
5259 | import { compileClassMetadata as compileClassMetadata4, compileDeclareClassMetadata as compileDeclareClassMetadata4, compileDeclareInjectableFromMetadata, compileInjectable, createMayBeForwardRefExpression as createMayBeForwardRefExpression2, FactoryTarget as FactoryTarget4, LiteralExpr as LiteralExpr3, WrappedNodeExpr as WrappedNodeExpr6 } from "@angular/compiler";
|
5260 | import ts19 from "typescript";
|
5261 | var InjectableDecoratorHandler = class {
|
5262 | constructor(reflector, isCore, strictCtorDeps, injectableRegistry, perf, errorOnDuplicateProv = true) {
|
5263 | this.reflector = reflector;
|
5264 | this.isCore = isCore;
|
5265 | this.strictCtorDeps = strictCtorDeps;
|
5266 | this.injectableRegistry = injectableRegistry;
|
5267 | this.perf = perf;
|
5268 | this.errorOnDuplicateProv = errorOnDuplicateProv;
|
5269 | this.precedence = HandlerPrecedence.SHARED;
|
5270 | this.name = InjectableDecoratorHandler.name;
|
5271 | }
|
5272 | detect(node, decorators) {
|
5273 | if (!decorators) {
|
5274 | return void 0;
|
5275 | }
|
5276 | const decorator = findAngularDecorator(decorators, "Injectable", this.isCore);
|
5277 | if (decorator !== void 0) {
|
5278 | return {
|
5279 | trigger: decorator.node,
|
5280 | decorator,
|
5281 | metadata: decorator
|
5282 | };
|
5283 | } else {
|
5284 | return void 0;
|
5285 | }
|
5286 | }
|
5287 | analyze(node, decorator) {
|
5288 | this.perf.eventCount(PerfEvent.AnalyzeInjectable);
|
5289 | const meta = extractInjectableMetadata(node, decorator, this.reflector);
|
5290 | const decorators = this.reflector.getDecoratorsOfDeclaration(node);
|
5291 | return {
|
5292 | analysis: {
|
5293 | meta,
|
5294 | ctorDeps: extractInjectableCtorDeps(node, meta, decorator, this.reflector, this.isCore, this.strictCtorDeps),
|
5295 | classMetadata: extractClassMetadata(node, this.reflector, this.isCore),
|
5296 | needsFactory: !decorators || decorators.every((current) => !isAngularCore(current) || current.name === "Injectable")
|
5297 | }
|
5298 | };
|
5299 | }
|
5300 | symbol() {
|
5301 | return null;
|
5302 | }
|
5303 | register(node) {
|
5304 | this.injectableRegistry.registerInjectable(node);
|
5305 | }
|
5306 | compileFull(node, analysis) {
|
5307 | return this.compile(compileNgFactoryDefField, (meta) => compileInjectable(meta, false), compileClassMetadata4, node, analysis);
|
5308 | }
|
5309 | compilePartial(node, analysis) {
|
5310 | return this.compile(compileDeclareFactory, compileDeclareInjectableFromMetadata, compileDeclareClassMetadata4, node, analysis);
|
5311 | }
|
5312 | compile(compileFactoryFn, compileInjectableFn, compileClassMetadataFn, node, analysis) {
|
5313 | const results = [];
|
5314 | if (analysis.needsFactory) {
|
5315 | const meta = analysis.meta;
|
5316 | const factoryRes = compileFactoryFn(toFactoryMetadata(__spreadProps(__spreadValues({}, meta), { deps: analysis.ctorDeps }), FactoryTarget4.Injectable));
|
5317 | if (analysis.classMetadata !== null) {
|
5318 | factoryRes.statements.push(compileClassMetadataFn(analysis.classMetadata).toStmt());
|
5319 | }
|
5320 | results.push(factoryRes);
|
5321 | }
|
5322 | const \u0275prov = this.reflector.getMembersOfClass(node).find((member) => member.name === "\u0275prov");
|
5323 | if (\u0275prov !== void 0 && this.errorOnDuplicateProv) {
|
5324 | throw new FatalDiagnosticError(ErrorCode.INJECTABLE_DUPLICATE_PROV, \u0275prov.nameNode || \u0275prov.node || node, "Injectables cannot contain a static \u0275prov property, because the compiler is going to generate one.");
|
5325 | }
|
5326 | if (\u0275prov === void 0) {
|
5327 | const res = compileInjectableFn(analysis.meta);
|
5328 | results.push({ name: "\u0275prov", initializer: res.expression, statements: res.statements, type: res.type });
|
5329 | }
|
5330 | return results;
|
5331 | }
|
5332 | };
|
5333 | function extractInjectableMetadata(clazz, decorator, reflector) {
|
5334 | const name = clazz.name.text;
|
5335 | const type = wrapTypeReference(reflector, clazz);
|
5336 | const internalType = new WrappedNodeExpr6(reflector.getInternalNameOfClass(clazz));
|
5337 | const typeArgumentCount = reflector.getGenericArityOfClass(clazz) || 0;
|
5338 | if (decorator.args === null) {
|
5339 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_NOT_CALLED, Decorator.nodeForError(decorator), "@Injectable must be called");
|
5340 | }
|
5341 | if (decorator.args.length === 0) {
|
5342 | return {
|
5343 | name,
|
5344 | type,
|
5345 | typeArgumentCount,
|
5346 | internalType,
|
5347 | providedIn: createMayBeForwardRefExpression2(new LiteralExpr3(null), 0)
|
5348 | };
|
5349 | } else if (decorator.args.length === 1) {
|
5350 | const metaNode = decorator.args[0];
|
5351 | if (!ts19.isObjectLiteralExpression(metaNode)) {
|
5352 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, metaNode, `@Injectable argument must be an object literal`);
|
5353 | }
|
5354 | const meta = reflectObjectLiteral(metaNode);
|
5355 | const providedIn = meta.has("providedIn") ? getProviderExpression(meta.get("providedIn"), reflector) : createMayBeForwardRefExpression2(new LiteralExpr3(null), 0);
|
5356 | let deps = void 0;
|
5357 | if ((meta.has("useClass") || meta.has("useFactory")) && meta.has("deps")) {
|
5358 | const depsExpr = meta.get("deps");
|
5359 | if (!ts19.isArrayLiteralExpression(depsExpr)) {
|
5360 | throw new FatalDiagnosticError(ErrorCode.VALUE_NOT_LITERAL, depsExpr, `@Injectable deps metadata must be an inline array`);
|
5361 | }
|
5362 | deps = depsExpr.elements.map((dep) => getDep(dep, reflector));
|
5363 | }
|
5364 | const result = { name, type, typeArgumentCount, internalType, providedIn };
|
5365 | if (meta.has("useValue")) {
|
5366 | result.useValue = getProviderExpression(meta.get("useValue"), reflector);
|
5367 | } else if (meta.has("useExisting")) {
|
5368 | result.useExisting = getProviderExpression(meta.get("useExisting"), reflector);
|
5369 | } else if (meta.has("useClass")) {
|
5370 | result.useClass = getProviderExpression(meta.get("useClass"), reflector);
|
5371 | result.deps = deps;
|
5372 | } else if (meta.has("useFactory")) {
|
5373 | result.useFactory = new WrappedNodeExpr6(meta.get("useFactory"));
|
5374 | result.deps = deps;
|
5375 | }
|
5376 | return result;
|
5377 | } else {
|
5378 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, decorator.args[2], "Too many arguments to @Injectable");
|
5379 | }
|
5380 | }
|
5381 | function getProviderExpression(expression, reflector) {
|
5382 | const forwardRefValue = tryUnwrapForwardRef(expression, reflector);
|
5383 | return createMayBeForwardRefExpression2(new WrappedNodeExpr6(forwardRefValue != null ? forwardRefValue : expression), forwardRefValue !== null ? 2 : 0);
|
5384 | }
|
5385 | function extractInjectableCtorDeps(clazz, meta, decorator, reflector, isCore, strictCtorDeps) {
|
5386 | if (decorator.args === null) {
|
5387 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_NOT_CALLED, Decorator.nodeForError(decorator), "@Injectable must be called");
|
5388 | }
|
5389 | let ctorDeps = null;
|
5390 | if (decorator.args.length === 0) {
|
5391 | if (strictCtorDeps) {
|
5392 | ctorDeps = getValidConstructorDependencies(clazz, reflector, isCore);
|
5393 | } else {
|
5394 | ctorDeps = unwrapConstructorDependencies(getConstructorDependencies(clazz, reflector, isCore));
|
5395 | }
|
5396 | return ctorDeps;
|
5397 | } else if (decorator.args.length === 1) {
|
5398 | const rawCtorDeps = getConstructorDependencies(clazz, reflector, isCore);
|
5399 | if (strictCtorDeps && meta.useValue === void 0 && meta.useExisting === void 0 && meta.useClass === void 0 && meta.useFactory === void 0) {
|
5400 | ctorDeps = validateConstructorDependencies(clazz, rawCtorDeps);
|
5401 | } else {
|
5402 | ctorDeps = unwrapConstructorDependencies(rawCtorDeps);
|
5403 | }
|
5404 | }
|
5405 | return ctorDeps;
|
5406 | }
|
5407 | function getDep(dep, reflector) {
|
5408 | const meta = {
|
5409 | token: new WrappedNodeExpr6(dep),
|
5410 | attributeNameType: null,
|
5411 | host: false,
|
5412 | optional: false,
|
5413 | self: false,
|
5414 | skipSelf: false
|
5415 | };
|
5416 | function maybeUpdateDecorator(dec, reflector2, token) {
|
5417 | const source = reflector2.getImportOfIdentifier(dec);
|
5418 | if (source === null || source.from !== "@angular/core") {
|
5419 | return false;
|
5420 | }
|
5421 | switch (source.name) {
|
5422 | case "Inject":
|
5423 | if (token !== void 0) {
|
5424 | meta.token = new WrappedNodeExpr6(token);
|
5425 | }
|
5426 | break;
|
5427 | case "Optional":
|
5428 | meta.optional = true;
|
5429 | break;
|
5430 | case "SkipSelf":
|
5431 | meta.skipSelf = true;
|
5432 | break;
|
5433 | case "Self":
|
5434 | meta.self = true;
|
5435 | break;
|
5436 | default:
|
5437 | return false;
|
5438 | }
|
5439 | return true;
|
5440 | }
|
5441 | if (ts19.isArrayLiteralExpression(dep)) {
|
5442 | dep.elements.forEach((el) => {
|
5443 | let isDecorator = false;
|
5444 | if (ts19.isIdentifier(el)) {
|
5445 | isDecorator = maybeUpdateDecorator(el, reflector);
|
5446 | } else if (ts19.isNewExpression(el) && ts19.isIdentifier(el.expression)) {
|
5447 | const token = el.arguments && el.arguments.length > 0 && el.arguments[0] || void 0;
|
5448 | isDecorator = maybeUpdateDecorator(el.expression, reflector, token);
|
5449 | }
|
5450 | if (!isDecorator) {
|
5451 | meta.token = new WrappedNodeExpr6(el);
|
5452 | }
|
5453 | });
|
5454 | }
|
5455 | return meta;
|
5456 | }
|
5457 |
|
5458 |
|
5459 | import { compileClassMetadata as compileClassMetadata5, compileDeclareClassMetadata as compileDeclareClassMetadata5, compileDeclarePipeFromMetadata, compilePipeFromMetadata, FactoryTarget as FactoryTarget5, WrappedNodeExpr as WrappedNodeExpr7 } from "@angular/compiler";
|
5460 | import ts20 from "typescript";
|
5461 | var PipeSymbol = class extends SemanticSymbol {
|
5462 | constructor(decl, name) {
|
5463 | super(decl);
|
5464 | this.name = name;
|
5465 | }
|
5466 | isPublicApiAffected(previousSymbol) {
|
5467 | if (!(previousSymbol instanceof PipeSymbol)) {
|
5468 | return true;
|
5469 | }
|
5470 | return this.name !== previousSymbol.name;
|
5471 | }
|
5472 | isTypeCheckApiAffected(previousSymbol) {
|
5473 | return this.isPublicApiAffected(previousSymbol);
|
5474 | }
|
5475 | };
|
5476 | var PipeDecoratorHandler = class {
|
5477 | constructor(reflector, evaluator, metaRegistry, scopeRegistry, injectableRegistry, isCore, perf) {
|
5478 | this.reflector = reflector;
|
5479 | this.evaluator = evaluator;
|
5480 | this.metaRegistry = metaRegistry;
|
5481 | this.scopeRegistry = scopeRegistry;
|
5482 | this.injectableRegistry = injectableRegistry;
|
5483 | this.isCore = isCore;
|
5484 | this.perf = perf;
|
5485 | this.precedence = HandlerPrecedence.PRIMARY;
|
5486 | this.name = PipeDecoratorHandler.name;
|
5487 | }
|
5488 | detect(node, decorators) {
|
5489 | if (!decorators) {
|
5490 | return void 0;
|
5491 | }
|
5492 | const decorator = findAngularDecorator(decorators, "Pipe", this.isCore);
|
5493 | if (decorator !== void 0) {
|
5494 | return {
|
5495 | trigger: decorator.node,
|
5496 | decorator,
|
5497 | metadata: decorator
|
5498 | };
|
5499 | } else {
|
5500 | return void 0;
|
5501 | }
|
5502 | }
|
5503 | analyze(clazz, decorator) {
|
5504 | this.perf.eventCount(PerfEvent.AnalyzePipe);
|
5505 | const name = clazz.name.text;
|
5506 | const type = wrapTypeReference(this.reflector, clazz);
|
5507 | const internalType = new WrappedNodeExpr7(this.reflector.getInternalNameOfClass(clazz));
|
5508 | if (decorator.args === null) {
|
5509 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_NOT_CALLED, Decorator.nodeForError(decorator), `@Pipe must be called`);
|
5510 | }
|
5511 | if (decorator.args.length !== 1) {
|
5512 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), "@Pipe must have exactly one argument");
|
5513 | }
|
5514 | const meta = unwrapExpression(decorator.args[0]);
|
5515 | if (!ts20.isObjectLiteralExpression(meta)) {
|
5516 | throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, meta, "@Pipe must have a literal argument");
|
5517 | }
|
5518 | const pipe = reflectObjectLiteral(meta);
|
5519 | if (!pipe.has("name")) {
|
5520 | throw new FatalDiagnosticError(ErrorCode.PIPE_MISSING_NAME, meta, `@Pipe decorator is missing name field`);
|
5521 | }
|
5522 | const pipeNameExpr = pipe.get("name");
|
5523 | const pipeName = this.evaluator.evaluate(pipeNameExpr);
|
5524 | if (typeof pipeName !== "string") {
|
5525 | throw createValueHasWrongTypeError(pipeNameExpr, pipeName, `@Pipe.name must be a string`);
|
5526 | }
|
5527 | let pure = true;
|
5528 | if (pipe.has("pure")) {
|
5529 | const expr = pipe.get("pure");
|
5530 | const pureValue = this.evaluator.evaluate(expr);
|
5531 | if (typeof pureValue !== "boolean") {
|
5532 | throw createValueHasWrongTypeError(expr, pureValue, `@Pipe.pure must be a boolean`);
|
5533 | }
|
5534 | pure = pureValue;
|
5535 | }
|
5536 | return {
|
5537 | analysis: {
|
5538 | meta: {
|
5539 | name,
|
5540 | type,
|
5541 | internalType,
|
5542 | typeArgumentCount: this.reflector.getGenericArityOfClass(clazz) || 0,
|
5543 | pipeName,
|
5544 | deps: getValidConstructorDependencies(clazz, this.reflector, this.isCore),
|
5545 | pure
|
5546 | },
|
5547 | classMetadata: extractClassMetadata(clazz, this.reflector, this.isCore),
|
5548 | pipeNameExpr
|
5549 | }
|
5550 | };
|
5551 | }
|
5552 | symbol(node, analysis) {
|
5553 | return new PipeSymbol(node, analysis.meta.name);
|
5554 | }
|
5555 | register(node, analysis) {
|
5556 | const ref = new Reference(node);
|
5557 | this.metaRegistry.registerPipeMetadata({ type: MetaType.Pipe, ref, name: analysis.meta.pipeName, nameExpr: analysis.pipeNameExpr });
|
5558 | this.injectableRegistry.registerInjectable(node);
|
5559 | }
|
5560 | resolve(node) {
|
5561 | const duplicateDeclData = this.scopeRegistry.getDuplicateDeclarations(node);
|
5562 | if (duplicateDeclData !== null) {
|
5563 | return {
|
5564 | diagnostics: [makeDuplicateDeclarationError(node, duplicateDeclData, "Pipe")]
|
5565 | };
|
5566 | }
|
5567 | return {};
|
5568 | }
|
5569 | compileFull(node, analysis) {
|
5570 | const fac = compileNgFactoryDefField(toFactoryMetadata(analysis.meta, FactoryTarget5.Pipe));
|
5571 | const def = compilePipeFromMetadata(analysis.meta);
|
5572 | const classMetadata = analysis.classMetadata !== null ? compileClassMetadata5(analysis.classMetadata).toStmt() : null;
|
5573 | return compileResults(fac, def, classMetadata, "\u0275pipe");
|
5574 | }
|
5575 | compilePartial(node, analysis) {
|
5576 | const fac = compileDeclareFactory(toFactoryMetadata(analysis.meta, FactoryTarget5.Pipe));
|
5577 | const def = compileDeclarePipeFromMetadata(analysis.meta);
|
5578 | const classMetadata = analysis.classMetadata !== null ? compileDeclareClassMetadata5(analysis.classMetadata).toStmt() : null;
|
5579 | return compileResults(fac, def, classMetadata, "\u0275pipe");
|
5580 | }
|
5581 | };
|
5582 |
|
5583 |
|
5584 | var NoopReferencesRegistry = class {
|
5585 | add(source, ...references) {
|
5586 | }
|
5587 | };
|
5588 |
|
5589 | export {
|
5590 | SemanticDepGraphUpdater,
|
5591 | CompoundMetadataReader,
|
5592 | DtsMetadataReader,
|
5593 | flattenInheritedDirectiveMetadata,
|
5594 | LocalMetadataRegistry,
|
5595 | CompoundMetadataRegistry,
|
5596 | InjectableClassRegistry,
|
5597 | ResourceRegistry,
|
5598 | DynamicValue,
|
5599 | StaticInterpreter,
|
5600 | PartialEvaluator,
|
5601 | CompilationMode,
|
5602 | HandlerFlags,
|
5603 | aliasTransformFactory,
|
5604 | TraitState,
|
5605 | TraitCompiler,
|
5606 | DtsTransformRegistry,
|
5607 | declarationTransformFactory,
|
5608 | ivyTransformFactory,
|
5609 | forwardRefResolver,
|
5610 | readBaseClass,
|
5611 | DirectiveDecoratorHandler,
|
5612 | NgModuleDecoratorHandler,
|
5613 | ComponentDecoratorHandler,
|
5614 | InjectableDecoratorHandler,
|
5615 | PipeDecoratorHandler,
|
5616 | NoopReferencesRegistry
|
5617 | };
|
5618 |
|
5619 |
|
5620 |
|
5621 |
|
5622 |
|
5623 |
|
5624 |
|
5625 |
|