@angular/compiler-cli
Version:
Angular - the compiler CLI for Node.js
1,408 lines (1,391 loc) • 617 kB
JavaScript
import {createRequire as __cjsCompatRequire} from 'module';
const require = __cjsCompatRequire(import.meta.url);
import {
AmbientImport,
ClassMemberAccessLevel,
ClassMemberKind,
ErrorCode,
FatalDiagnosticError,
ImportFlags,
ImportManager,
Reference,
ReferenceEmitKind,
TypeEmitter,
TypeEntityToDeclarationError,
addDiagnosticChain,
assertSuccessfulReferenceEmit,
attachDefaultImportDeclaration,
canEmitType,
classMemberAccessLevelToString,
entityNameToValue,
filterToMembersWithDecorator,
getDefaultImportDeclaration,
getProjectRelativePath,
getSourceFile,
getSourceFileOrNull,
getTokenAtPosition,
identifierOfNode,
isAssignment,
isDeclaration,
isDtsPath,
isFromDtsFile,
isNamedClassDeclaration,
isNonDeclarationTsPath,
isSymbolWithValueDeclaration,
makeDiagnostic,
makeDiagnosticChain,
makeRelatedInformation,
ngErrorCode,
nodeDebugInfo,
nodeNameForError,
presetImportManagerForceNamespaceImports,
reflectObjectLiteral,
reflectTypeEntityToDeclaration,
toUnredirectedSourceFile,
translateExpression,
translateStatement,
translateType,
typeNodeToValueExpr
} from "./chunk-XRSJELB6.js";
import {
PerfCheckpoint,
PerfEvent,
PerfPhase
} from "./chunk-Q2WE7ECN.js";
import {
absoluteFrom,
absoluteFromSourceFile,
getSourceFileOrError,
relative
} from "./chunk-37JMVF7H.js";
import {
__publicField
} from "./chunk-KPQ72R34.js";
// bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/common/src/util.mjs
import { ExternalExpr, ParseLocation, ParseSourceFile, ParseSourceSpan, ReadPropExpr, WrappedNodeExpr } from "@angular/compiler";
import ts from "typescript";
var CORE_MODULE = "@angular/core";
function valueReferenceToExpression(valueRef) {
if (valueRef.kind === 2) {
return null;
} else if (valueRef.kind === 0) {
const expr = new WrappedNodeExpr(valueRef.expression);
if (valueRef.defaultImportStatement !== null) {
attachDefaultImportDeclaration(expr, valueRef.defaultImportStatement);
}
return expr;
} else {
let importExpr = new ExternalExpr({
moduleName: valueRef.moduleName,
name: valueRef.importedName
});
if (valueRef.nestedPath !== null) {
for (const property of valueRef.nestedPath) {
importExpr = new ReadPropExpr(importExpr, property);
}
}
return importExpr;
}
}
function toR3Reference(origin, ref, context, refEmitter) {
const emittedValueRef = refEmitter.emit(ref, context);
assertSuccessfulReferenceEmit(emittedValueRef, origin, "class");
const emittedTypeRef = refEmitter.emit(ref, context, ImportFlags.ForceNewImport | ImportFlags.AllowTypeImports);
assertSuccessfulReferenceEmit(emittedTypeRef, origin, "class");
return {
value: emittedValueRef.expression,
type: emittedTypeRef.expression
};
}
function isAngularCore(decorator) {
return decorator.import !== null && decorator.import.from === CORE_MODULE;
}
function isAngularCoreReferenceWithPotentialAliasing(reference, symbolName, isCore) {
var _a;
return (reference.ownedByModuleGuess === CORE_MODULE || isCore) && ((_a = reference.debugName) == null ? void 0 : _a.replace(/\$\d+$/, "")) === symbolName;
}
function findAngularDecorator(decorators, name, isCore) {
return decorators.find((decorator) => isAngularDecorator(decorator, name, isCore));
}
function isAngularDecorator(decorator, name, isCore) {
if (isCore) {
return decorator.name === name;
} else if (isAngularCore(decorator)) {
return decorator.import.name === name;
}
return false;
}
function getAngularDecorators(decorators, names, isCore) {
return decorators.filter((decorator) => {
var _a;
const name = isCore ? decorator.name : (_a = decorator.import) == null ? void 0 : _a.name;
if (name === void 0 || !names.includes(name)) {
return false;
}
return isCore || isAngularCore(decorator);
});
}
function unwrapExpression(node) {
while (ts.isAsExpression(node) || ts.isParenthesizedExpression(node)) {
node = node.expression;
}
return node;
}
function expandForwardRef(arg) {
arg = unwrapExpression(arg);
if (!ts.isArrowFunction(arg) && !ts.isFunctionExpression(arg)) {
return null;
}
const body = arg.body;
if (ts.isBlock(body)) {
if (body.statements.length !== 1) {
return null;
}
const stmt = body.statements[0];
if (!ts.isReturnStatement(stmt) || stmt.expression === void 0) {
return null;
}
return stmt.expression;
} else {
return body;
}
}
function tryUnwrapForwardRef(node, reflector) {
node = unwrapExpression(node);
if (!ts.isCallExpression(node) || node.arguments.length !== 1) {
return null;
}
const fn = ts.isPropertyAccessExpression(node.expression) ? node.expression.name : node.expression;
if (!ts.isIdentifier(fn)) {
return null;
}
const expr = expandForwardRef(node.arguments[0]);
if (expr === null) {
return null;
}
const imp = reflector.getImportOfIdentifier(fn);
if (imp === null || imp.from !== "@angular/core" || imp.name !== "forwardRef") {
return null;
}
return expr;
}
function createForwardRefResolver(isCore) {
return (fn, callExpr, resolve, unresolvable) => {
if (!isAngularCoreReferenceWithPotentialAliasing(fn, "forwardRef", isCore) || callExpr.arguments.length !== 1) {
return unresolvable;
}
const expanded = expandForwardRef(callExpr.arguments[0]);
if (expanded !== null) {
return resolve(expanded);
} else {
return unresolvable;
}
};
}
function combineResolvers(resolvers) {
return (fn, callExpr, resolve, unresolvable) => {
for (const resolver of resolvers) {
const resolved = resolver(fn, callExpr, resolve, unresolvable);
if (resolved !== unresolvable) {
return resolved;
}
}
return unresolvable;
};
}
function isExpressionForwardReference(expr, context, contextSource) {
if (isWrappedTsNodeExpr(expr)) {
const node = ts.getOriginalNode(expr.node);
return node.getSourceFile() === contextSource && context.pos < node.pos;
} else {
return false;
}
}
function isWrappedTsNodeExpr(expr) {
return expr instanceof WrappedNodeExpr;
}
function readBaseClass(node, reflector, evaluator) {
const baseExpression = reflector.getBaseClassExpression(node);
if (baseExpression !== null) {
const baseClass = evaluator.evaluate(baseExpression);
if (baseClass instanceof Reference && reflector.isClass(baseClass.node)) {
return baseClass;
} else {
return "dynamic";
}
}
return null;
}
var parensWrapperTransformerFactory = (context) => {
const visitor = (node) => {
const visited = ts.visitEachChild(node, visitor, context);
if (ts.isArrowFunction(visited) || ts.isFunctionExpression(visited)) {
return ts.factory.createParenthesizedExpression(visited);
}
return visited;
};
return (node) => ts.visitEachChild(node, visitor, context);
};
function wrapFunctionExpressionsInParens(expression) {
return ts.transform(expression, [parensWrapperTransformerFactory]).transformed[0];
}
function resolveProvidersRequiringFactory(rawProviders, reflector, evaluator) {
const providers = /* @__PURE__ */ new Set();
const resolvedProviders = evaluator.evaluate(rawProviders);
if (!Array.isArray(resolvedProviders)) {
return providers;
}
resolvedProviders.forEach(function processProviders(provider) {
let tokenClass = null;
if (Array.isArray(provider)) {
provider.forEach(processProviders);
} else if (provider instanceof Reference) {
tokenClass = provider;
} else if (provider instanceof Map && provider.has("useClass") && !provider.has("deps")) {
const useExisting = provider.get("useClass");
if (useExisting instanceof Reference) {
tokenClass = useExisting;
}
}
if (tokenClass !== null && !tokenClass.node.getSourceFile().isDeclarationFile && reflector.isClass(tokenClass.node)) {
const constructorParameters = reflector.getConstructorParameters(tokenClass.node);
if (constructorParameters !== null && constructorParameters.length > 0) {
providers.add(tokenClass);
}
}
});
return providers;
}
function wrapTypeReference(reflector, clazz) {
const value = new WrappedNodeExpr(clazz.name);
const type = value;
return { value, type };
}
function createSourceSpan(node) {
const sf = node.getSourceFile();
const [startOffset, endOffset] = [node.getStart(), node.getEnd()];
const { line: startLine, character: startCol } = sf.getLineAndCharacterOfPosition(startOffset);
const { line: endLine, character: endCol } = sf.getLineAndCharacterOfPosition(endOffset);
const parseSf = new ParseSourceFile(sf.getFullText(), sf.fileName);
return new ParseSourceSpan(new ParseLocation(parseSf, startOffset, startLine + 1, startCol + 1), new ParseLocation(parseSf, endOffset, endLine + 1, endCol + 1));
}
function compileResults(fac, def, metadataStmt, propName, additionalFields, deferrableImports, debugInfo = null, hmrInitializer = null) {
const statements = def.statements;
if (metadataStmt !== null) {
statements.push(metadataStmt);
}
if (debugInfo !== null) {
statements.push(debugInfo);
}
if (hmrInitializer !== null) {
statements.push(hmrInitializer);
}
const results = [
fac,
{
name: propName,
initializer: def.expression,
statements: def.statements,
type: def.type,
deferrableImports
}
];
if (additionalFields !== null) {
results.push(...additionalFields);
}
return results;
}
function toFactoryMetadata(meta, target) {
return {
name: meta.name,
type: meta.type,
typeArgumentCount: meta.typeArgumentCount,
deps: meta.deps,
target
};
}
function resolveImportedFile(moduleResolver, importedFile, expr, origin) {
if (importedFile !== "unknown") {
return importedFile;
}
if (!(expr instanceof ExternalExpr)) {
return null;
}
return moduleResolver.resolveModule(expr.value.moduleName, origin.fileName);
}
function getOriginNodeForDiagnostics(expr, container) {
const nodeSf = expr.getSourceFile();
const exprSf = container.getSourceFile();
if (nodeSf === exprSf && expr.pos >= container.pos && expr.end <= container.end) {
return expr;
} else {
return container;
}
}
function isAbstractClassDeclaration(clazz) {
return ts.canHaveModifiers(clazz) && clazz.modifiers !== void 0 ? clazz.modifiers.some((mod) => mod.kind === ts.SyntaxKind.AbstractKeyword) : false;
}
// bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/partial_evaluator/src/dynamic.mjs
var DynamicValue = class {
node;
reason;
code;
constructor(node, reason, code) {
this.node = node;
this.reason = reason;
this.code = code;
}
static fromDynamicInput(node, input) {
return new DynamicValue(node, input, 0);
}
static fromDynamicString(node) {
return new DynamicValue(node, void 0, 1);
}
static fromExternalReference(node, ref) {
return new DynamicValue(node, ref, 2);
}
static fromUnsupportedSyntax(node) {
return new DynamicValue(node, void 0, 3);
}
static fromUnknownIdentifier(node) {
return new DynamicValue(node, void 0, 4);
}
static fromInvalidExpressionType(node, value) {
return new DynamicValue(node, value, 5);
}
static fromComplexFunctionCall(node, fn) {
return new DynamicValue(node, fn, 6);
}
static fromDynamicType(node) {
return new DynamicValue(node, void 0, 7);
}
static fromSyntheticInput(node, value) {
return new DynamicValue(node, value, 8);
}
static fromUnknown(node) {
return new DynamicValue(node, void 0, 9);
}
isFromDynamicInput() {
return this.code === 0;
}
isFromDynamicString() {
return this.code === 1;
}
isFromExternalReference() {
return this.code === 2;
}
isFromUnsupportedSyntax() {
return this.code === 3;
}
isFromUnknownIdentifier() {
return this.code === 4;
}
isFromInvalidExpressionType() {
return this.code === 5;
}
isFromComplexFunctionCall() {
return this.code === 6;
}
isFromDynamicType() {
return this.code === 7;
}
isFromUnknown() {
return this.code === 9;
}
accept(visitor) {
switch (this.code) {
case 0:
return visitor.visitDynamicInput(this);
case 1:
return visitor.visitDynamicString(this);
case 2:
return visitor.visitExternalReference(this);
case 3:
return visitor.visitUnsupportedSyntax(this);
case 4:
return visitor.visitUnknownIdentifier(this);
case 5:
return visitor.visitInvalidExpressionType(this);
case 6:
return visitor.visitComplexFunctionCall(this);
case 7:
return visitor.visitDynamicType(this);
case 8:
return visitor.visitSyntheticInput(this);
case 9:
return visitor.visitUnknown(this);
}
}
};
// bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.mjs
import ts2 from "typescript";
// bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/partial_evaluator/src/result.mjs
var ResolvedModule = class {
exports;
evaluate;
constructor(exports, evaluate) {
this.exports = exports;
this.evaluate = evaluate;
}
getExport(name) {
if (!this.exports.has(name)) {
return void 0;
}
return this.evaluate(this.exports.get(name));
}
getExports() {
const map = /* @__PURE__ */ new Map();
this.exports.forEach((decl, name) => {
map.set(name, this.evaluate(decl));
});
return map;
}
};
var EnumValue = class {
enumRef;
name;
resolved;
constructor(enumRef, name, resolved) {
this.enumRef = enumRef;
this.name = name;
this.resolved = resolved;
}
};
var KnownFn = class {
};
// bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/partial_evaluator/src/builtin.mjs
var ArraySliceBuiltinFn = class extends KnownFn {
lhs;
constructor(lhs) {
super();
this.lhs = lhs;
}
evaluate(node, args) {
if (args.length === 0) {
return this.lhs;
} else {
return DynamicValue.fromUnknown(node);
}
}
};
var ArrayConcatBuiltinFn = class extends KnownFn {
lhs;
constructor(lhs) {
super();
this.lhs = lhs;
}
evaluate(node, args) {
const result = [...this.lhs];
for (const arg of args) {
if (arg instanceof DynamicValue) {
result.push(DynamicValue.fromDynamicInput(node, arg));
} else if (Array.isArray(arg)) {
result.push(...arg);
} else {
result.push(arg);
}
}
return result;
}
};
var StringConcatBuiltinFn = class extends KnownFn {
lhs;
constructor(lhs) {
super();
this.lhs = lhs;
}
evaluate(node, args) {
let result = this.lhs;
for (const arg of args) {
const resolved = arg instanceof EnumValue ? arg.resolved : arg;
if (typeof resolved === "string" || typeof resolved === "number" || typeof resolved === "boolean" || resolved == null) {
result = result.concat(resolved);
} else {
return DynamicValue.fromUnknown(node);
}
}
return result;
}
};
// bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/partial_evaluator/src/synthetic.mjs
var SyntheticValue = class {
value;
constructor(value) {
this.value = value;
}
};
// bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interpreter.mjs
function literalBinaryOp(op) {
return { op, literal: true };
}
function referenceBinaryOp(op) {
return { op, literal: false };
}
var BINARY_OPERATORS = /* @__PURE__ */ new Map([
[ts2.SyntaxKind.PlusToken, literalBinaryOp((a, b) => a + b)],
[ts2.SyntaxKind.MinusToken, literalBinaryOp((a, b) => a - b)],
[ts2.SyntaxKind.AsteriskToken, literalBinaryOp((a, b) => a * b)],
[ts2.SyntaxKind.SlashToken, literalBinaryOp((a, b) => a / b)],
[ts2.SyntaxKind.PercentToken, literalBinaryOp((a, b) => a % b)],
[ts2.SyntaxKind.AmpersandToken, literalBinaryOp((a, b) => a & b)],
[ts2.SyntaxKind.BarToken, literalBinaryOp((a, b) => a | b)],
[ts2.SyntaxKind.CaretToken, literalBinaryOp((a, b) => a ^ b)],
[ts2.SyntaxKind.LessThanToken, literalBinaryOp((a, b) => a < b)],
[ts2.SyntaxKind.LessThanEqualsToken, literalBinaryOp((a, b) => a <= b)],
[ts2.SyntaxKind.GreaterThanToken, literalBinaryOp((a, b) => a > b)],
[ts2.SyntaxKind.GreaterThanEqualsToken, literalBinaryOp((a, b) => a >= b)],
[ts2.SyntaxKind.EqualsEqualsToken, literalBinaryOp((a, b) => a == b)],
[ts2.SyntaxKind.EqualsEqualsEqualsToken, literalBinaryOp((a, b) => a === b)],
[ts2.SyntaxKind.ExclamationEqualsToken, literalBinaryOp((a, b) => a != b)],
[ts2.SyntaxKind.ExclamationEqualsEqualsToken, literalBinaryOp((a, b) => a !== b)],
[ts2.SyntaxKind.LessThanLessThanToken, literalBinaryOp((a, b) => a << b)],
[ts2.SyntaxKind.GreaterThanGreaterThanToken, literalBinaryOp((a, b) => a >> b)],
[ts2.SyntaxKind.GreaterThanGreaterThanGreaterThanToken, literalBinaryOp((a, b) => a >>> b)],
[ts2.SyntaxKind.AsteriskAsteriskToken, literalBinaryOp((a, b) => Math.pow(a, b))],
[ts2.SyntaxKind.AmpersandAmpersandToken, referenceBinaryOp((a, b) => a && b)],
[ts2.SyntaxKind.BarBarToken, referenceBinaryOp((a, b) => a || b)]
]);
var UNARY_OPERATORS = /* @__PURE__ */ new Map([
[ts2.SyntaxKind.TildeToken, (a) => ~a],
[ts2.SyntaxKind.MinusToken, (a) => -a],
[ts2.SyntaxKind.PlusToken, (a) => +a],
[ts2.SyntaxKind.ExclamationToken, (a) => !a]
]);
var StaticInterpreter = class {
host;
checker;
dependencyTracker;
constructor(host, checker, dependencyTracker) {
this.host = host;
this.checker = checker;
this.dependencyTracker = dependencyTracker;
}
visit(node, context) {
return this.visitExpression(node, context);
}
visitExpression(node, context) {
let result;
if (node.kind === ts2.SyntaxKind.TrueKeyword) {
return true;
} else if (node.kind === ts2.SyntaxKind.FalseKeyword) {
return false;
} else if (node.kind === ts2.SyntaxKind.NullKeyword) {
return null;
} else if (ts2.isStringLiteral(node)) {
return node.text;
} else if (ts2.isNoSubstitutionTemplateLiteral(node)) {
return node.text;
} else if (ts2.isTemplateExpression(node)) {
result = this.visitTemplateExpression(node, context);
} else if (ts2.isNumericLiteral(node)) {
return parseFloat(node.text);
} else if (ts2.isObjectLiteralExpression(node)) {
result = this.visitObjectLiteralExpression(node, context);
} else if (ts2.isIdentifier(node)) {
result = this.visitIdentifier(node, context);
} else if (ts2.isPropertyAccessExpression(node)) {
result = this.visitPropertyAccessExpression(node, context);
} else if (ts2.isCallExpression(node)) {
result = this.visitCallExpression(node, context);
} else if (ts2.isConditionalExpression(node)) {
result = this.visitConditionalExpression(node, context);
} else if (ts2.isPrefixUnaryExpression(node)) {
result = this.visitPrefixUnaryExpression(node, context);
} else if (ts2.isBinaryExpression(node)) {
result = this.visitBinaryExpression(node, context);
} else if (ts2.isArrayLiteralExpression(node)) {
result = this.visitArrayLiteralExpression(node, context);
} else if (ts2.isParenthesizedExpression(node)) {
result = this.visitParenthesizedExpression(node, context);
} else if (ts2.isElementAccessExpression(node)) {
result = this.visitElementAccessExpression(node, context);
} else if (ts2.isAsExpression(node)) {
result = this.visitExpression(node.expression, context);
} else if (ts2.isNonNullExpression(node)) {
result = this.visitExpression(node.expression, context);
} else if (this.host.isClass(node)) {
result = this.visitDeclaration(node, context);
} else {
return DynamicValue.fromUnsupportedSyntax(node);
}
if (result instanceof DynamicValue && result.node !== node) {
return DynamicValue.fromDynamicInput(node, result);
}
return result;
}
visitArrayLiteralExpression(node, context) {
const array = [];
for (let i = 0; i < node.elements.length; i++) {
const element = node.elements[i];
if (ts2.isSpreadElement(element)) {
array.push(...this.visitSpreadElement(element, context));
} else {
array.push(this.visitExpression(element, context));
}
}
return array;
}
visitObjectLiteralExpression(node, context) {
const map = /* @__PURE__ */ new Map();
for (let i = 0; i < node.properties.length; i++) {
const property = node.properties[i];
if (ts2.isPropertyAssignment(property)) {
const name = this.stringNameFromPropertyName(property.name, context);
if (name === void 0) {
return DynamicValue.fromDynamicInput(node, DynamicValue.fromDynamicString(property.name));
}
map.set(name, this.visitExpression(property.initializer, context));
} else if (ts2.isShorthandPropertyAssignment(property)) {
const symbol = this.checker.getShorthandAssignmentValueSymbol(property);
if (symbol === void 0 || symbol.valueDeclaration === void 0) {
map.set(property.name.text, DynamicValue.fromUnknown(property));
} else {
map.set(property.name.text, this.visitDeclaration(symbol.valueDeclaration, context));
}
} else if (ts2.isSpreadAssignment(property)) {
const spread = this.visitExpression(property.expression, context);
if (spread instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, spread);
} else if (spread instanceof Map) {
spread.forEach((value, key) => map.set(key, value));
} else if (spread instanceof ResolvedModule) {
spread.getExports().forEach((value, key) => map.set(key, value));
} else {
return DynamicValue.fromDynamicInput(node, DynamicValue.fromInvalidExpressionType(property, spread));
}
} else {
return DynamicValue.fromUnknown(node);
}
}
return map;
}
visitTemplateExpression(node, context) {
const pieces = [node.head.text];
for (let i = 0; i < node.templateSpans.length; i++) {
const span = node.templateSpans[i];
const value = literal(this.visit(span.expression, context), () => DynamicValue.fromDynamicString(span.expression));
if (value instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, value);
}
pieces.push(`${value}`, span.literal.text);
}
return pieces.join("");
}
visitIdentifier(node, context) {
const decl = this.host.getDeclarationOfIdentifier(node);
if (decl === null) {
if (ts2.identifierToKeywordKind(node) === ts2.SyntaxKind.UndefinedKeyword) {
return void 0;
} else {
if (this.dependencyTracker !== null && this.host.getImportOfIdentifier(node) !== null) {
this.dependencyTracker.recordDependencyAnalysisFailure(context.originatingFile);
}
return DynamicValue.fromUnknownIdentifier(node);
}
}
const declContext = { ...context, ...joinModuleContext(context, node, decl) };
const result = this.visitDeclaration(decl.node, declContext);
if (result instanceof Reference) {
if (!result.synthetic) {
result.addIdentifier(node);
}
} else if (result instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, result);
}
return result;
}
visitDeclaration(node, context) {
if (this.dependencyTracker !== null) {
this.dependencyTracker.addDependency(context.originatingFile, node.getSourceFile());
}
if (this.host.isClass(node)) {
return this.getReference(node, context);
} else if (ts2.isVariableDeclaration(node)) {
return this.visitVariableDeclaration(node, context);
} else if (ts2.isParameter(node) && context.scope.has(node)) {
return context.scope.get(node);
} else if (ts2.isExportAssignment(node)) {
return this.visitExpression(node.expression, context);
} else if (ts2.isEnumDeclaration(node)) {
return this.visitEnumDeclaration(node, context);
} else if (ts2.isSourceFile(node)) {
return this.visitSourceFile(node, context);
} else if (ts2.isBindingElement(node)) {
return this.visitBindingElement(node, context);
} else {
return this.getReference(node, context);
}
}
visitVariableDeclaration(node, context) {
const value = this.host.getVariableValue(node);
if (value !== null) {
return this.visitExpression(value, context);
} else if (isVariableDeclarationDeclared(node)) {
if (node.type !== void 0) {
const evaluatedType = this.visitType(node.type, context);
if (!(evaluatedType instanceof DynamicValue)) {
return evaluatedType;
}
}
return this.getReference(node, context);
} else {
return void 0;
}
}
visitEnumDeclaration(node, context) {
const enumRef = this.getReference(node, context);
const map = /* @__PURE__ */ new Map();
node.members.forEach((member, index) => {
const name = this.stringNameFromPropertyName(member.name, context);
if (name !== void 0) {
const resolved = member.initializer ? this.visit(member.initializer, context) : index;
map.set(name, new EnumValue(enumRef, name, resolved));
}
});
return map;
}
visitElementAccessExpression(node, context) {
const lhs = this.visitExpression(node.expression, context);
if (lhs instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, lhs);
}
const rhs = this.visitExpression(node.argumentExpression, context);
if (rhs instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, rhs);
}
if (typeof rhs !== "string" && typeof rhs !== "number") {
return DynamicValue.fromInvalidExpressionType(node, rhs);
}
return this.accessHelper(node, lhs, rhs, context);
}
visitPropertyAccessExpression(node, context) {
const lhs = this.visitExpression(node.expression, context);
const rhs = node.name.text;
if (lhs instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, lhs);
}
return this.accessHelper(node, lhs, rhs, context);
}
visitSourceFile(node, context) {
const declarations = this.host.getExportsOfModule(node);
if (declarations === null) {
return DynamicValue.fromUnknown(node);
}
return new ResolvedModule(declarations, (decl) => {
const declContext = {
...context,
...joinModuleContext(context, node, decl)
};
return this.visitDeclaration(decl.node, declContext);
});
}
accessHelper(node, lhs, rhs, context) {
const strIndex = `${rhs}`;
if (lhs instanceof Map) {
if (lhs.has(strIndex)) {
return lhs.get(strIndex);
} else {
return void 0;
}
} else if (lhs instanceof ResolvedModule) {
return lhs.getExport(strIndex);
} else if (Array.isArray(lhs)) {
if (rhs === "length") {
return lhs.length;
} else if (rhs === "slice") {
return new ArraySliceBuiltinFn(lhs);
} else if (rhs === "concat") {
return new ArrayConcatBuiltinFn(lhs);
}
if (typeof rhs !== "number" || !Number.isInteger(rhs)) {
return DynamicValue.fromInvalidExpressionType(node, rhs);
}
return lhs[rhs];
} else if (typeof lhs === "string" && rhs === "concat") {
return new StringConcatBuiltinFn(lhs);
} else if (lhs instanceof Reference) {
const ref = lhs.node;
if (this.host.isClass(ref)) {
const module = owningModule(context, lhs.bestGuessOwningModule);
let value = void 0;
const member = this.host.getMembersOfClass(ref).find((member2) => member2.isStatic && member2.name === strIndex);
if (member !== void 0) {
if (member.value !== null) {
value = this.visitExpression(member.value, context);
} else if (member.implementation !== null) {
value = new Reference(member.implementation, module);
} else if (member.node) {
value = new Reference(member.node, module);
}
}
return value;
} else if (isDeclaration(ref)) {
return DynamicValue.fromDynamicInput(node, DynamicValue.fromExternalReference(ref, lhs));
}
} else if (lhs instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, lhs);
} else if (lhs instanceof SyntheticValue) {
return DynamicValue.fromSyntheticInput(node, lhs);
}
return DynamicValue.fromUnknown(node);
}
visitCallExpression(node, context) {
const lhs = this.visitExpression(node.expression, context);
if (lhs instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, lhs);
}
if (lhs instanceof KnownFn) {
return lhs.evaluate(node, this.evaluateFunctionArguments(node, context));
}
if (!(lhs instanceof Reference)) {
return DynamicValue.fromInvalidExpressionType(node.expression, lhs);
}
const fn = this.host.getDefinitionOfFunction(lhs.node);
if (fn === null) {
return DynamicValue.fromInvalidExpressionType(node.expression, lhs);
}
if (!isFunctionOrMethodReference(lhs)) {
return DynamicValue.fromInvalidExpressionType(node.expression, lhs);
}
const resolveFfrExpr = (expr) => {
let contextExtension = {};
if (fn.body === null && expr.getSourceFile() !== node.expression.getSourceFile() && lhs.bestGuessOwningModule !== null) {
contextExtension = {
absoluteModuleName: lhs.bestGuessOwningModule.specifier,
resolutionContext: lhs.bestGuessOwningModule.resolutionContext
};
}
return this.visitFfrExpression(expr, { ...context, ...contextExtension });
};
if (fn.body === null && context.foreignFunctionResolver !== void 0) {
const unresolvable = DynamicValue.fromDynamicInput(node, DynamicValue.fromExternalReference(node.expression, lhs));
return context.foreignFunctionResolver(lhs, node, resolveFfrExpr, unresolvable);
}
const res = this.visitFunctionBody(node, fn, context);
if (res instanceof DynamicValue && context.foreignFunctionResolver !== void 0) {
const unresolvable = DynamicValue.fromComplexFunctionCall(node, fn);
return context.foreignFunctionResolver(lhs, node, resolveFfrExpr, unresolvable);
}
return res;
}
visitFfrExpression(expr, context) {
const res = this.visitExpression(expr, context);
if (res instanceof Reference) {
res.synthetic = true;
}
return res;
}
visitFunctionBody(node, fn, context) {
if (fn.body === null) {
return DynamicValue.fromUnknown(node);
} else if (fn.body.length !== 1 || !ts2.isReturnStatement(fn.body[0])) {
return DynamicValue.fromComplexFunctionCall(node, fn);
}
const ret = fn.body[0];
const args = this.evaluateFunctionArguments(node, context);
const newScope = /* @__PURE__ */ new Map();
const calleeContext = { ...context, scope: newScope };
fn.parameters.forEach((param, index) => {
let arg = args[index];
if (param.node.dotDotDotToken !== void 0) {
arg = args.slice(index);
}
if (arg === void 0 && param.initializer !== null) {
arg = this.visitExpression(param.initializer, calleeContext);
}
newScope.set(param.node, arg);
});
return ret.expression !== void 0 ? this.visitExpression(ret.expression, calleeContext) : void 0;
}
visitConditionalExpression(node, context) {
const condition = this.visitExpression(node.condition, context);
if (condition instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, condition);
}
if (condition) {
return this.visitExpression(node.whenTrue, context);
} else {
return this.visitExpression(node.whenFalse, context);
}
}
visitPrefixUnaryExpression(node, context) {
const operatorKind = node.operator;
if (!UNARY_OPERATORS.has(operatorKind)) {
return DynamicValue.fromUnsupportedSyntax(node);
}
const op = UNARY_OPERATORS.get(operatorKind);
const value = this.visitExpression(node.operand, context);
if (value instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, value);
} else {
return op(value);
}
}
visitBinaryExpression(node, context) {
const tokenKind = node.operatorToken.kind;
if (!BINARY_OPERATORS.has(tokenKind)) {
return DynamicValue.fromUnsupportedSyntax(node);
}
const opRecord = BINARY_OPERATORS.get(tokenKind);
let lhs, rhs;
if (opRecord.literal) {
lhs = literal(this.visitExpression(node.left, context), (value) => DynamicValue.fromInvalidExpressionType(node.left, value));
rhs = literal(this.visitExpression(node.right, context), (value) => DynamicValue.fromInvalidExpressionType(node.right, value));
} else {
lhs = this.visitExpression(node.left, context);
rhs = this.visitExpression(node.right, context);
}
if (lhs instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, lhs);
} else if (rhs instanceof DynamicValue) {
return DynamicValue.fromDynamicInput(node, rhs);
} else {
return opRecord.op(lhs, rhs);
}
}
visitParenthesizedExpression(node, context) {
return this.visitExpression(node.expression, context);
}
evaluateFunctionArguments(node, context) {
const args = [];
for (const arg of node.arguments) {
if (ts2.isSpreadElement(arg)) {
args.push(...this.visitSpreadElement(arg, context));
} else {
args.push(this.visitExpression(arg, context));
}
}
return args;
}
visitSpreadElement(node, context) {
const spread = this.visitExpression(node.expression, context);
if (spread instanceof DynamicValue) {
return [DynamicValue.fromDynamicInput(node, spread)];
} else if (!Array.isArray(spread)) {
return [DynamicValue.fromInvalidExpressionType(node, spread)];
} else {
return spread;
}
}
visitBindingElement(node, context) {
const path = [];
let closestDeclaration = node;
while (ts2.isBindingElement(closestDeclaration) || ts2.isArrayBindingPattern(closestDeclaration) || ts2.isObjectBindingPattern(closestDeclaration)) {
if (ts2.isBindingElement(closestDeclaration)) {
path.unshift(closestDeclaration);
}
closestDeclaration = closestDeclaration.parent;
}
if (!ts2.isVariableDeclaration(closestDeclaration) || closestDeclaration.initializer === void 0) {
return DynamicValue.fromUnknown(node);
}
let value = this.visit(closestDeclaration.initializer, context);
for (const element of path) {
let key;
if (ts2.isArrayBindingPattern(element.parent)) {
key = element.parent.elements.indexOf(element);
} else {
const name = element.propertyName || element.name;
if (ts2.isIdentifier(name)) {
key = name.text;
} else {
return DynamicValue.fromUnknown(element);
}
}
value = this.accessHelper(element, value, key, context);
if (value instanceof DynamicValue) {
return value;
}
}
return value;
}
stringNameFromPropertyName(node, context) {
if (ts2.isIdentifier(node) || ts2.isStringLiteral(node) || ts2.isNumericLiteral(node)) {
return node.text;
} else if (ts2.isComputedPropertyName(node)) {
const literal3 = this.visitExpression(node.expression, context);
return typeof literal3 === "string" ? literal3 : void 0;
} else {
return void 0;
}
}
getReference(node, context) {
return new Reference(node, owningModule(context));
}
visitType(node, context) {
if (ts2.isLiteralTypeNode(node)) {
return this.visitExpression(node.literal, context);
} else if (ts2.isTupleTypeNode(node)) {
return this.visitTupleType(node, context);
} else if (ts2.isNamedTupleMember(node)) {
return this.visitType(node.type, context);
} else if (ts2.isTypeOperatorNode(node) && node.operator === ts2.SyntaxKind.ReadonlyKeyword) {
return this.visitType(node.type, context);
} else if (ts2.isTypeQueryNode(node)) {
return this.visitTypeQuery(node, context);
}
return DynamicValue.fromDynamicType(node);
}
visitTupleType(node, context) {
const res = [];
for (const elem of node.elements) {
res.push(this.visitType(elem, context));
}
return res;
}
visitTypeQuery(node, context) {
if (!ts2.isIdentifier(node.exprName)) {
return DynamicValue.fromUnknown(node);
}
const decl = this.host.getDeclarationOfIdentifier(node.exprName);
if (decl === null) {
return DynamicValue.fromUnknownIdentifier(node.exprName);
}
const declContext = { ...context, ...joinModuleContext(context, node, decl) };
return this.visitDeclaration(decl.node, declContext);
}
};
function isFunctionOrMethodReference(ref) {
return ts2.isFunctionDeclaration(ref.node) || ts2.isMethodDeclaration(ref.node) || ts2.isFunctionExpression(ref.node);
}
function literal(value, reject) {
if (value instanceof EnumValue) {
value = value.resolved;
}
if (value instanceof DynamicValue || value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
return value;
}
return reject(value);
}
function isVariableDeclarationDeclared(node) {
if (node.parent === void 0 || !ts2.isVariableDeclarationList(node.parent)) {
return false;
}
const declList = node.parent;
if (declList.parent === void 0 || !ts2.isVariableStatement(declList.parent)) {
return false;
}
const varStmt = declList.parent;
const modifiers = ts2.getModifiers(varStmt);
return modifiers !== void 0 && modifiers.some((mod) => mod.kind === ts2.SyntaxKind.DeclareKeyword);
}
var EMPTY = {};
function joinModuleContext(existing, node, decl) {
if (typeof decl.viaModule === "string" && decl.viaModule !== existing.absoluteModuleName) {
return {
absoluteModuleName: decl.viaModule,
resolutionContext: node.getSourceFile().fileName
};
} else {
return EMPTY;
}
}
function owningModule(context, override = null) {
let specifier = context.absoluteModuleName;
if (override !== null) {
specifier = override.specifier;
}
if (specifier !== null) {
return {
specifier,
resolutionContext: context.resolutionContext
};
} else {
return null;
}
}
// bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/partial_evaluator/src/interface.mjs
var PartialEvaluator = class {
host;
checker;
dependencyTracker;
constructor(host, checker, dependencyTracker) {
this.host = host;
this.checker = checker;
this.dependencyTracker = dependencyTracker;
}
evaluate(expr, foreignFunctionResolver) {
const interpreter = new StaticInterpreter(this.host, this.checker, this.dependencyTracker);
const sourceFile = expr.getSourceFile();
return interpreter.visit(expr, {
originatingFile: sourceFile,
absoluteModuleName: null,
resolutionContext: sourceFile.fileName,
scope: /* @__PURE__ */ new Map(),
foreignFunctionResolver
});
}
};
// bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/partial_evaluator/src/diagnostics.mjs
import ts3 from "typescript";
function describeResolvedType(value, maxDepth = 1) {
var _a, _b;
if (value === null) {
return "null";
} else if (value === void 0) {
return "undefined";
} else if (typeof value === "number" || typeof value === "boolean" || typeof value === "string") {
return typeof value;
} else if (value instanceof Map) {
if (maxDepth === 0) {
return "object";
}
const entries = Array.from(value.entries()).map(([key, v]) => {
return `${quoteKey(key)}: ${describeResolvedType(v, maxDepth - 1)}`;
});
return entries.length > 0 ? `{ ${entries.join("; ")} }` : "{}";
} else if (value instanceof ResolvedModule) {
return "(module)";
} else if (value instanceof EnumValue) {
return (_a = value.enumRef.debugName) != null ? _a : "(anonymous)";
} else if (value instanceof Reference) {
return (_b = value.debugName) != null ? _b : "(anonymous)";
} else if (Array.isArray(value)) {
if (maxDepth === 0) {
return "Array";
}
return `[${value.map((v) => describeResolvedType(v, maxDepth - 1)).join(", ")}]`;
} else if (value instanceof DynamicValue) {
return "(not statically analyzable)";
} else if (value instanceof KnownFn) {
return "Function";
} else {
return "unknown";
}
}
function quoteKey(key) {
if (/^[a-z0-9_]+$/i.test(key)) {
return key;
} else {
return `'${key.replace(/'/g, "\\'")}'`;
}
}
function traceDynamicValue(node, value) {
return value.accept(new TraceDynamicValueVisitor(node));
}
var TraceDynamicValueVisitor = class {
node;
currentContainerNode = null;
constructor(node) {
this.node = node;
}
visitDynamicInput(value) {
const trace = value.reason.accept(this);
if (this.shouldTrace(value.node)) {
const info = makeRelatedInformation(value.node, "Unable to evaluate this expression statically.");
trace.unshift(info);
}
return trace;
}
visitSyntheticInput(value) {
return [makeRelatedInformation(value.node, "Unable to evaluate this expression further.")];
}
visitDynamicString(value) {
return [
makeRelatedInformation(value.node, "A string value could not be determined statically.")
];
}
visitExternalReference(value) {
const name = value.reason.debugName;
const description = name !== null ? `'${name}'` : "an anonymous declaration";
return [
makeRelatedInformation(value.node, `A value for ${description} cannot be determined statically, as it is an external declaration.`)
];
}
visitComplexFunctionCall(value) {
return [
makeRelatedInformation(value.node, "Unable to evaluate function call of complex function. A function must have exactly one return statement."),
makeRelatedInformation(value.reason.node, "Function is declared here.")
];
}
visitInvalidExpressionType(value) {
return [makeRelatedInformation(value.node, "Unable to evaluate an invalid expression.")];
}
visitUnknown(value) {
return [makeRelatedInformation(value.node, "Unable to evaluate statically.")];
}
visitUnknownIdentifier(value) {
return [makeRelatedInformation(value.node, "Unknown reference.")];
}
visitDynamicType(value) {
return [makeRelatedInformation(value.node, "Dynamic type.")];
}
visitUnsupportedSyntax(value) {
return [makeRelatedInformation(value.node, "This syntax is not supported.")];
}
shouldTrace(node) {
if (node === this.node) {
return false;
}
const container = getContainerNode(node);
if (container === this.currentContainerNode) {
return false;
}
this.currentContainerNode = container;
return true;
}
};
function getContainerNode(node) {
let currentNode = node;
while (currentNode !== void 0) {
switch (currentNode.kind) {
case ts3.SyntaxKind.ExpressionStatement:
case ts3.SyntaxKind.VariableStatement:
case ts3.SyntaxKind.ReturnStatement:
case ts3.SyntaxKind.IfStatement:
case ts3.SyntaxKind.SwitchStatement:
case ts3.SyntaxKind.DoStatement:
case ts3.SyntaxKind.WhileStatement:
case ts3.SyntaxKind.ForStatement:
case ts3.SyntaxKind.ForInStatement:
case ts3.SyntaxKind.ForOfStatement:
case ts3.SyntaxKind.ContinueStatement:
case ts3.SyntaxKind.BreakStatement:
case ts3.SyntaxKind.ThrowStatement:
case ts3.SyntaxKind.ObjectBindingPattern:
case ts3.SyntaxKind.ArrayBindingPattern:
return currentNode;
}
currentNode = currentNode.parent;
}
return node.getSourceFile();
}
// bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/api/checker.mjs
var OptimizeFor;
(function(OptimizeFor2) {
OptimizeFor2[OptimizeFor2["SingleFile"] = 0] = "SingleFile";
OptimizeFor2[OptimizeFor2["WholeProgram"] = 1] = "WholeProgram";
})(OptimizeFor || (OptimizeFor = {}));
// bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/api/scope.mjs
var PotentialImportKind;
(function(PotentialImportKind2) {
PotentialImportKind2[PotentialImportKind2["NgModule"] = 0] = "NgModule";
PotentialImportKind2[PotentialImportKind2["Standalone"] = 1] = "Standalone";
})(PotentialImportKind || (PotentialImportKind = {}));
var PotentialImportMode;
(function(PotentialImportMode2) {
PotentialImportMode2[PotentialImportMode2["Normal"] = 0] = "Normal";
PotentialImportMode2[PotentialImportMode2["ForceDirect"] = 1] = "ForceDirect";
})(PotentialImportMode || (PotentialImportMode = {}));
// bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/api/completion.mjs
var CompletionKind;
(function(CompletionKind2) {
CompletionKind2[CompletionKind2["Reference"] = 0] = "Reference";
CompletionKind2[CompletionKind2["Variable"] = 1] = "Variable";
CompletionKind2[CompletionKind2["LetDeclaration"] = 2] = "LetDeclaration";
})(CompletionKind || (CompletionKind = {}));
// bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/typecheck/api/symbols.mjs
var SymbolKind;
(function(SymbolKind2) {
SymbolKind2[SymbolKind2["Input"] = 0] = "Input";
SymbolKind2[SymbolKind2["Output"] = 1] = "Output";
SymbolKind2[SymbolKind2["Binding"] = 2] = "Binding";
SymbolKind2[SymbolKind2["Reference"] = 3] = "Reference";
SymbolKind2[SymbolKind2["Variable"] = 4] = "Variable";
SymbolKind2[SymbolKind2["Directive"] = 5] = "Directive";
SymbolKind2[SymbolKind2["Element"] = 6] = "Element";
SymbolKind2[SymbolKind2["Template"] = 7] = "Template";
SymbolKind2[SymbolKind2["Expression"] = 8] = "Expression";
SymbolKind2[SymbolKind2["DomBinding"] = 9] = "DomBinding";
SymbolKind2[SymbolKind2["Pipe"] = 10] = "Pipe";
SymbolKind2[SymbolKind2["LetDeclaration"] = 11] = "LetDeclaration";
})(SymbolKind || (SymbolKind = {}));
// bazel-out/k8-fastbuild/bin/packages/compiler-cli/src/ngtsc/annotations/common/src/di.mjs
import { LiteralExpr, WrappedNodeExpr as WrappedNodeExpr2 } from "@angular/compiler";
import ts4 from "typescript";
function getConstructorDependencies(clazz, reflector, isCore) {
const deps = [];
const errors = [];
let ctorParams = reflector.getConstructorParameters(clazz);
if (ctorParams === null) {
if (reflector.hasBaseClass(clazz)) {
return null;
} else {
ctorParams = [];
}
}
ctorParams.forEach((param, idx) => {
let token = valueReferenceToExpression(param.typeValueReference);
let attributeNameType = null;
let optional = false, self = false, skipSelf = false, host = false;
(param.decorators || []).filter((dec) => isCore || isAngularCore(dec)).forEach((dec) => {
const name = isCore || dec.import === null ? dec.name : dec.import.name;
if (name === "Inject") {
if (dec.args === null || dec.args.length !== 1) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, dec.node, `Unexpected number of arguments to @Inject().`);
}
token = new WrappedNodeExpr2(dec.args[0]);
} else if (name === "Optional") {
optional = true;
} else if (name === "SkipSelf") {
skipSelf = true;
} else if (name === "Self") {
self = true;
} else if (name === "Host") {
host = true;
} else if (name === "Attribute") {
if (dec.args === null || dec.args.length !== 1) {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, dec.node, `Unexpected number of arguments to @Attribute().`);
}
const attributeName = dec.args[0];
token = new WrappedNodeExpr2(attributeName);
if (ts4.isStringLiteralLike(attributeName)) {
attributeNameType = new LiteralExpr(attributeName.text);
} else {
attributeNameType = new WrappedNodeExpr2(ts4.factory.createKeywordTypeNode(ts4.SyntaxKind.UnknownKeyword));
}
} else {
throw new FatalDiagnosticError(ErrorCode.DECORATOR_UNEXPECTED, dec.node, `Unexpected decorator ${name} on parameter.`);
}
});
if (token === null) {
if (param.typeValueReference.kind !== 2) {
throw new Error("Illegal state: expected value reference to be unavailable if no token is present");
}
errors.push({
index: idx,
param,
reason: param.typeValueReference.reason
});
} else {
deps.push({ token, attributeNameType, optional, self, skipSelf, host });
}
});
if (errors.length === 0) {
return { deps };
} else {
return { deps: null, errors };
}
}
function unwrapConstructorDependencies(deps) {
if (deps === null) {
return null;
} else if (deps.deps !== null) {
return deps.deps;
} else {
return "invalid";
}
}
function getValidConstructorDependencies(clazz, reflector, isCore) {
return validateConstructorDependencies(clazz, getConstructorDependencies(clazz, reflector, isCore));
}
function validateConstructorDependencies(clazz, deps) {
if (deps === null) {
return null;
} else if (deps.deps !== null) {
return deps.deps;
} else {
const error = deps.errors[0];
throw createUnsuitableInjectionTokenError(clazz, error);
}
}
function createUnsuitableInjectionTokenError(clazz, error) {
const { param, index, reason } = error;
let chainMessage = void 0;
let hints = void 0;
switch (reason.kind) {
case 5:
chainMessage = "Consider using the @Inject decorator to specify an injection token.";
hints = [
makeRelatedInformation(reason.typeNode, "This type is not supported as injection token.")
];