_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/compiler-cli/src/ngtsc/annotations/ng_module/src/module_with_providers.ts_0_5515 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {ErrorCode, FatalDiagnosticError} from '../../../diagnostics';
import {Reference} from '../../../imports';
import {ForeignFunctionResolver, SyntheticValue} from '../../../partial_evaluator';
import {
ClassDeclaration,
entityNameToValue,
isNamedClassDeclaration,
ReflectionHost,
typeNodeToValueExpr,
} from '../../../reflection';
/**
* Creates a foreign function resolver to detect a `ModuleWithProviders<T>` type in a return type
* position of a function or method declaration. A `SyntheticValue` is produced if such a return
* type is recognized.
*
* @param reflector The reflection host to use for analyzing the syntax.
* @param isCore Whether the @angular/core package is being compiled.
*/
export function createModuleWithProvidersResolver(
reflector: ReflectionHost,
isCore: boolean,
): ForeignFunctionResolver {
/**
* Retrieve an `NgModule` identifier (T) from the specified `type`, if it is of the form:
* `ModuleWithProviders<T>`
* @param type The type to reflect on.
* @returns the identifier of the NgModule type if found, or null otherwise.
*/
function _reflectModuleFromTypeParam(
type: ts.TypeNode,
node: ts.FunctionDeclaration | ts.MethodDeclaration | ts.FunctionExpression,
): ts.Expression | null {
// Examine the type of the function to see if it's a ModuleWithProviders reference.
if (!ts.isTypeReferenceNode(type)) {
return null;
}
const typeName =
(type &&
((ts.isIdentifier(type.typeName) && type.typeName) ||
(ts.isQualifiedName(type.typeName) && type.typeName.right))) ||
null;
if (typeName === null) {
return null;
}
// Look at the type itself to see where it comes from.
const id = reflector.getImportOfIdentifier(typeName);
// If it's not named ModuleWithProviders, bail.
if (id === null || id.name !== 'ModuleWithProviders') {
return null;
}
// If it's not from @angular/core, bail.
if (!isCore && id.from !== '@angular/core') {
return null;
}
// If there's no type parameter specified, bail.
if (type.typeArguments === undefined || type.typeArguments.length !== 1) {
const parent =
ts.isMethodDeclaration(node) && ts.isClassDeclaration(node.parent) ? node.parent : null;
const symbolName =
(parent && parent.name ? parent.name.getText() + '.' : '') +
(node.name ? node.name.getText() : 'anonymous');
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.`,
);
}
const arg = type.typeArguments[0];
return typeNodeToValueExpr(arg);
}
/**
* Retrieve an `NgModule` identifier (T) from the specified `type`, if it is of the form:
* `A|B|{ngModule: T}|C`.
* @param type The type to reflect on.
* @returns the identifier of the NgModule type if found, or null otherwise.
*/
function _reflectModuleFromLiteralType(type: ts.TypeNode): ts.Expression | null {
if (!ts.isIntersectionTypeNode(type)) {
return null;
}
for (const t of type.types) {
if (ts.isTypeLiteralNode(t)) {
for (const m of t.members) {
const ngModuleType =
(ts.isPropertySignature(m) &&
ts.isIdentifier(m.name) &&
m.name.text === 'ngModule' &&
m.type) ||
null;
let ngModuleExpression: ts.Expression | null = null;
// Handle `: typeof X` or `: X` cases.
if (ngModuleType !== null && ts.isTypeQueryNode(ngModuleType)) {
ngModuleExpression = entityNameToValue(ngModuleType.exprName);
} else if (ngModuleType !== null) {
ngModuleExpression = typeNodeToValueExpr(ngModuleType);
}
if (ngModuleExpression) {
return ngModuleExpression;
}
}
}
}
return null;
}
return (fn, callExpr, resolve, unresolvable) => {
const rawType = fn.node.type;
if (rawType === undefined) {
return unresolvable;
}
const type =
_reflectModuleFromTypeParam(rawType, fn.node) ?? _reflectModuleFromLiteralType(rawType);
if (type === null) {
return unresolvable;
}
const ngModule = resolve(type);
if (!(ngModule instanceof Reference) || !isNamedClassDeclaration(ngModule.node)) {
return unresolvable;
}
return new SyntheticValue({
ngModule: ngModule as Reference<ClassDeclaration>,
mwpCall: callExpr,
});
};
}
export interface ResolvedModuleWithProviders {
ngModule: Reference<ClassDeclaration>;
mwpCall: ts.CallExpression;
}
export function isResolvedModuleWithProviders(
sv: SyntheticValue<unknown>,
): sv is SyntheticValue<ResolvedModuleWithProviders> {
return (
typeof sv.value === 'object' &&
sv.value != null &&
sv.value.hasOwnProperty('ngModule' as keyof ResolvedModuleWithProviders) &&
sv.value.hasOwnProperty('mwpCall' as keyof ResolvedModuleWithProviders)
);
}
| {
"end_byte": 5515,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/ng_module/src/module_with_providers.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/ng_module/src/handler.ts_0_7559 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
compileClassMetadata,
compileDeclareClassMetadata,
compileDeclareInjectorFromMetadata,
compileDeclareNgModuleFromMetadata,
compileInjector,
compileNgModule,
Expression,
ExternalExpr,
FactoryTarget,
FunctionExpr,
InvokeFunctionExpr,
LiteralArrayExpr,
R3ClassMetadata,
R3CompiledExpression,
R3FactoryMetadata,
R3Identifiers,
R3InjectorMetadata,
R3NgModuleMetadata,
R3NgModuleMetadataKind,
R3Reference,
R3SelectorScopeMode,
ReturnStatement,
SchemaMetadata,
Statement,
WrappedNodeExpr,
} from '@angular/compiler';
import ts from 'typescript';
import {
ErrorCode,
FatalDiagnosticError,
makeDiagnostic,
makeRelatedInformation,
} from '../../../diagnostics';
import {
assertSuccessfulReferenceEmit,
LocalCompilationExtraImportsTracker,
Reference,
ReferenceEmitter,
} from '../../../imports';
import {
isArrayEqual,
isReferenceEqual,
isSymbolEqual,
SemanticDepGraphUpdater,
SemanticReference,
SemanticSymbol,
} from '../../../incremental/semantic_graph';
import {
ExportedProviderStatusResolver,
MetadataReader,
MetadataRegistry,
MetaKind,
} from '../../../metadata';
import {
DynamicValue,
PartialEvaluator,
ResolvedValue,
SyntheticValue,
} from '../../../partial_evaluator';
import {PerfEvent, PerfRecorder} from '../../../perf';
import {
ClassDeclaration,
DeclarationNode,
Decorator,
ReflectionHost,
reflectObjectLiteral,
} from '../../../reflection';
import {LocalModuleScopeRegistry, ScopeData} from '../../../scope';
import {getDiagnosticNode} from '../../../scope/src/util';
import {
AnalysisOutput,
CompilationMode,
CompileResult,
DecoratorHandler,
DetectResult,
HandlerPrecedence,
ResolveResult,
} from '../../../transform';
import {getSourceFile} from '../../../util/src/typescript';
import {
combineResolvers,
compileDeclareFactory,
compileNgFactoryDefField,
createValueHasWrongTypeError,
extractClassMetadata,
extractSchemas,
findAngularDecorator,
forwardRefResolver,
getProviderDiagnostics,
getValidConstructorDependencies,
InjectableClassRegistry,
isExpressionForwardReference,
JitDeclarationRegistry,
ReferencesRegistry,
resolveProvidersRequiringFactory,
toR3Reference,
unwrapExpression,
wrapFunctionExpressionsInParens,
wrapTypeReference,
} from '../../common';
import {
createModuleWithProvidersResolver,
isResolvedModuleWithProviders,
} from './module_with_providers';
export interface NgModuleAnalysis {
mod: R3NgModuleMetadata;
inj: R3InjectorMetadata;
fac: R3FactoryMetadata;
classMetadata: R3ClassMetadata | null;
declarations: Reference<ClassDeclaration>[];
rawDeclarations: ts.Expression | null;
schemas: SchemaMetadata[];
imports: TopLevelImportedExpression[];
importRefs: Reference<ClassDeclaration>[];
rawImports: ts.Expression | null;
exports: Reference<ClassDeclaration>[];
rawExports: ts.Expression | null;
id: Expression | null;
factorySymbolName: string;
providersRequiringFactory: Set<Reference<ClassDeclaration>> | null;
providers: ts.Expression | null;
remoteScopesMayRequireCycleProtection: boolean;
decorator: ts.Decorator | null;
}
export interface NgModuleResolution {
injectorImports: Expression[];
}
/**
* Represents an Angular NgModule.
*/
export class NgModuleSymbol extends SemanticSymbol {
private remotelyScopedComponents: {
component: SemanticSymbol;
usedDirectives: SemanticReference[];
usedPipes: SemanticReference[];
}[] = [];
/**
* `SemanticSymbol`s of the transitive imports of this NgModule which came from imported
* standalone components.
*
* Standalone components are excluded/included in the `InjectorDef` emit output of the NgModule
* based on whether the compiler can prove that their transitive imports may contain exported
* providers, so a change in this set of symbols may affect the compilation output of this
* NgModule.
*/
private transitiveImportsFromStandaloneComponents = new Set<SemanticSymbol>();
constructor(
decl: ClassDeclaration,
public readonly hasProviders: boolean,
) {
super(decl);
}
override isPublicApiAffected(previousSymbol: SemanticSymbol): boolean {
if (!(previousSymbol instanceof NgModuleSymbol)) {
return true;
}
// Changes in the provider status of this NgModule affect downstream dependencies, which may
// consider provider status in their own emits.
if (previousSymbol.hasProviders !== this.hasProviders) {
return true;
}
return false;
}
override isEmitAffected(previousSymbol: SemanticSymbol): boolean {
if (!(previousSymbol instanceof NgModuleSymbol)) {
return true;
}
// compare our remotelyScopedComponents to the previous symbol
if (previousSymbol.remotelyScopedComponents.length !== this.remotelyScopedComponents.length) {
return true;
}
for (const currEntry of this.remotelyScopedComponents) {
const prevEntry = previousSymbol.remotelyScopedComponents.find((prevEntry) => {
return isSymbolEqual(prevEntry.component, currEntry.component);
});
if (prevEntry === undefined) {
// No previous entry was found, which means that this component became remotely scoped and
// hence this NgModule needs to be re-emitted.
return true;
}
if (!isArrayEqual(currEntry.usedDirectives, prevEntry.usedDirectives, isReferenceEqual)) {
// The list of used directives or their order has changed. Since this NgModule emits
// references to the list of used directives, it should be re-emitted to update this list.
// Note: the NgModule does not have to be re-emitted when any of the directives has had
// their public API changed, as the NgModule only emits a reference to the symbol by its
// name. Therefore, testing for symbol equality is sufficient.
return true;
}
if (!isArrayEqual(currEntry.usedPipes, prevEntry.usedPipes, isReferenceEqual)) {
return true;
}
}
if (
previousSymbol.transitiveImportsFromStandaloneComponents.size !==
this.transitiveImportsFromStandaloneComponents.size
) {
return true;
}
const previousImports = Array.from(previousSymbol.transitiveImportsFromStandaloneComponents);
for (const transitiveImport of this.transitiveImportsFromStandaloneComponents) {
const prevEntry = previousImports.find((prevEntry) =>
isSymbolEqual(prevEntry, transitiveImport),
);
if (prevEntry === undefined) {
return true;
}
if (transitiveImport.isPublicApiAffected(prevEntry)) {
return true;
}
}
return false;
}
override isTypeCheckApiAffected(previousSymbol: SemanticSymbol): boolean {
if (!(previousSymbol instanceof NgModuleSymbol)) {
return true;
}
return false;
}
addRemotelyScopedComponent(
component: SemanticSymbol,
usedDirectives: SemanticReference[],
usedPipes: SemanticReference[],
): void {
this.remotelyScopedComponents.push({component, usedDirectives, usedPipes});
}
addTransitiveImportFromStandaloneComponent(importedSymbol: SemanticSymbol): void {
this.transitiveImportsFromStandaloneComponents.add(importedSymbol);
}
}
/**
* Compiles @NgModule annotations to ngModuleDef fields.
*/ | {
"end_byte": 7559,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/ng_module/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/ng_module/src/handler.ts_7560_9246 | export class NgModuleDecoratorHandler
implements DecoratorHandler<Decorator, NgModuleAnalysis, NgModuleSymbol, NgModuleResolution>
{
constructor(
private reflector: ReflectionHost,
private evaluator: PartialEvaluator,
private metaReader: MetadataReader,
private metaRegistry: MetadataRegistry,
private scopeRegistry: LocalModuleScopeRegistry,
private referencesRegistry: ReferencesRegistry,
private exportedProviderStatusResolver: ExportedProviderStatusResolver,
private semanticDepGraphUpdater: SemanticDepGraphUpdater | null,
private isCore: boolean,
private refEmitter: ReferenceEmitter,
private annotateForClosureCompiler: boolean,
private onlyPublishPublicTypings: boolean,
private injectableRegistry: InjectableClassRegistry,
private perf: PerfRecorder,
private includeClassMetadata: boolean,
private includeSelectorScope: boolean,
private readonly compilationMode: CompilationMode,
private readonly localCompilationExtraImportsTracker: LocalCompilationExtraImportsTracker | null,
private readonly jitDeclarationRegistry: JitDeclarationRegistry,
) {}
readonly precedence = HandlerPrecedence.PRIMARY;
readonly name = 'NgModuleDecoratorHandler';
detect(
node: ClassDeclaration,
decorators: Decorator[] | null,
): DetectResult<Decorator> | undefined {
if (!decorators) {
return undefined;
}
const decorator = findAngularDecorator(decorators, 'NgModule', this.isCore);
if (decorator !== undefined) {
return {
trigger: decorator.node,
decorator: decorator,
metadata: decorator,
};
} else {
return undefined;
}
} | {
"end_byte": 9246,
"start_byte": 7560,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/ng_module/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/ng_module/src/handler.ts_9250_17181 | analyze(
node: ClassDeclaration,
decorator: Readonly<Decorator>,
): AnalysisOutput<NgModuleAnalysis> {
this.perf.eventCount(PerfEvent.AnalyzeNgModule);
const name = node.name.text;
if (decorator.args === null || decorator.args.length > 1) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG,
decorator.node,
`Incorrect number of arguments to @NgModule decorator`,
);
}
// @NgModule can be invoked without arguments. In case it is, pretend as if a blank object
// literal was specified. This simplifies the code below.
const meta =
decorator.args.length === 1
? unwrapExpression(decorator.args[0])
: ts.factory.createObjectLiteralExpression([]);
if (!ts.isObjectLiteralExpression(meta)) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARG_NOT_LITERAL,
meta,
'@NgModule argument must be an object literal',
);
}
const ngModule = reflectObjectLiteral(meta);
if (ngModule.has('jit')) {
this.jitDeclarationRegistry.jitDeclarations.add(node);
// The only allowed value is true, so there's no need to expand further.
return {};
}
const moduleResolvers = combineResolvers([
createModuleWithProvidersResolver(this.reflector, this.isCore),
forwardRefResolver,
]);
const diagnostics: ts.Diagnostic[] = [];
// Resolving declarations
let declarationRefs: Reference<ClassDeclaration>[] = [];
const rawDeclarations: ts.Expression | null = ngModule.get('declarations') ?? null;
if (rawDeclarations !== null) {
const declarationMeta = this.evaluator.evaluate(rawDeclarations, forwardRefResolver);
declarationRefs = this.resolveTypeList(
rawDeclarations,
declarationMeta,
name,
'declarations',
0,
this.compilationMode === CompilationMode.LOCAL,
).references;
// Look through the declarations to make sure they're all a part of the current compilation.
for (const ref of declarationRefs) {
if (ref.node.getSourceFile().isDeclarationFile) {
const errorNode = ref.getOriginForDiagnostics(rawDeclarations);
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.`)],
),
);
}
}
}
if (diagnostics.length > 0) {
return {diagnostics};
}
// Resolving imports
let importRefs: Reference<ClassDeclaration>[] = [];
let rawImports: ts.Expression | null = ngModule.get('imports') ?? null;
if (rawImports !== null) {
const importsMeta = this.evaluator.evaluate(rawImports, moduleResolvers);
const result = this.resolveTypeList(
rawImports,
importsMeta,
name,
'imports',
0,
this.compilationMode === CompilationMode.LOCAL,
);
if (
this.compilationMode === CompilationMode.LOCAL &&
this.localCompilationExtraImportsTracker !== null
) {
// For generating extra imports in local mode, the NgModule imports that are from external
// files (i.e., outside of the compilation unit) are to be added to all the files in the
// compilation unit. This is because any external component that is a dependency of some
// component in the compilation unit must be imported by one of these NgModule's external
// imports (or the external component cannot be a dependency of that internal component).
// This approach can be further optimized by adding these NgModule external imports to a
// subset of files in the compilation unit and not all. See comments in {@link
// LocalCompilationExtraImportsTracker} and {@link
// LocalCompilationExtraImportsTracker#addGlobalImportFromIdentifier} for more details.
for (const d of result.dynamicValues) {
this.localCompilationExtraImportsTracker.addGlobalImportFromIdentifier(d.node);
}
}
importRefs = result.references;
}
// Resolving exports
let exportRefs: Reference<ClassDeclaration>[] = [];
const rawExports: ts.Expression | null = ngModule.get('exports') ?? null;
if (rawExports !== null) {
const exportsMeta = this.evaluator.evaluate(rawExports, moduleResolvers);
exportRefs = this.resolveTypeList(
rawExports,
exportsMeta,
name,
'exports',
0,
this.compilationMode === CompilationMode.LOCAL,
).references;
this.referencesRegistry.add(node, ...exportRefs);
}
// Resolving bootstrap
let bootstrapRefs: Reference<ClassDeclaration>[] = [];
const rawBootstrap: ts.Expression | null = ngModule.get('bootstrap') ?? null;
if (this.compilationMode !== CompilationMode.LOCAL && rawBootstrap !== null) {
const bootstrapMeta = this.evaluator.evaluate(rawBootstrap, forwardRefResolver);
bootstrapRefs = this.resolveTypeList(
rawBootstrap,
bootstrapMeta,
name,
'bootstrap',
0,
/* allowUnresolvedReferences */ false,
).references;
// Verify that the `@NgModule.bootstrap` list doesn't have Standalone Components.
for (const ref of bootstrapRefs) {
const dirMeta = this.metaReader.getDirectiveMetadata(ref);
if (dirMeta?.isStandalone) {
diagnostics.push(makeStandaloneBootstrapDiagnostic(node, ref, rawBootstrap));
}
}
}
const schemas =
this.compilationMode !== CompilationMode.LOCAL && ngModule.has('schemas')
? extractSchemas(ngModule.get('schemas')!, this.evaluator, 'NgModule')
: [];
let id: Expression | null = null;
if (ngModule.has('id')) {
const idExpr = ngModule.get('id')!;
if (!isModuleIdExpression(idExpr)) {
id = new WrappedNodeExpr(idExpr);
} else {
const diag = makeDiagnostic(
ErrorCode.WARN_NGMODULE_ID_UNNECESSARY,
idExpr,
`Using 'module.id' for NgModule.id is a common anti-pattern that is ignored by the Angular compiler.`,
);
diag.category = ts.DiagnosticCategory.Warning;
diagnostics.push(diag);
}
}
const valueContext = node.getSourceFile();
const exportedNodes = new Set(exportRefs.map((ref) => ref.node));
const declarations: R3Reference[] = [];
const exportedDeclarations: Expression[] = [];
const bootstrap = bootstrapRefs.map((bootstrap) =>
this._toR3Reference(
bootstrap.getOriginForDiagnostics(meta, node.name),
bootstrap,
valueContext,
),
);
for (const ref of declarationRefs) {
const decl = this._toR3Reference(
ref.getOriginForDiagnostics(meta, node.name),
ref,
valueContext,
);
declarations.push(decl);
if (exportedNodes.has(ref.node)) {
exportedDeclarations.push(decl.type);
}
}
const imports = importRefs.map((imp) =>
this._toR3Reference(imp.getOriginForDiagnostics(meta, node.name), imp, valueContext),
);
const exports = exportRefs.map((exp) =>
this._toR3Reference(exp.getOriginForDiagnostics(meta, node.name), exp, valueContext),
);
const isForwardReference = (ref: R3Reference) =>
isExpressionForwardReference(ref.value, node.name!, valueContext);
const containsForwardDecls =
bootstrap.some(isForwardReference) ||
declarations.some(isForwardReference) ||
imports.some(isForwardReference) ||
exports.some(isForwardReference);
const type = wrapTypeReference(this.reflector, node);
let ngModuleMetadata: R3NgModuleMetadata; | {
"end_byte": 17181,
"start_byte": 9250,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/ng_module/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/ng_module/src/handler.ts_17186_25710 | if (this.compilationMode === CompilationMode.LOCAL) {
ngModuleMetadata = {
kind: R3NgModuleMetadataKind.Local,
type,
bootstrapExpression: rawBootstrap ? new WrappedNodeExpr(rawBootstrap) : null,
declarationsExpression: rawDeclarations ? new WrappedNodeExpr(rawDeclarations) : null,
exportsExpression: rawExports ? new WrappedNodeExpr(rawExports) : null,
importsExpression: rawImports ? new WrappedNodeExpr(rawImports) : null,
id,
// Use `ɵɵsetNgModuleScope` to patch selector scopes onto the generated definition in a
// tree-shakeable way.
selectorScopeMode: R3SelectorScopeMode.SideEffect,
// TODO: to be implemented as a part of FW-1004.
schemas: [],
};
} else {
ngModuleMetadata = {
kind: R3NgModuleMetadataKind.Global,
type,
bootstrap,
declarations,
publicDeclarationTypes: this.onlyPublishPublicTypings ? exportedDeclarations : null,
exports,
imports,
// Imported types are generally private, so include them unless restricting the .d.ts emit
// to only public types.
includeImportTypes: !this.onlyPublishPublicTypings,
containsForwardDecls,
id,
// Use `ɵɵsetNgModuleScope` to patch selector scopes onto the generated definition in a
// tree-shakeable way.
selectorScopeMode: this.includeSelectorScope
? R3SelectorScopeMode.SideEffect
: R3SelectorScopeMode.Omit,
// TODO: to be implemented as a part of FW-1004.
schemas: [],
};
}
const rawProviders = ngModule.has('providers') ? ngModule.get('providers')! : null;
let wrappedProviders: WrappedNodeExpr<ts.Expression> | null = null;
// In most cases the providers will be an array literal. Check if it has any elements
// and don't include the providers if it doesn't which saves us a few bytes.
if (
rawProviders !== null &&
(!ts.isArrayLiteralExpression(rawProviders) || rawProviders.elements.length > 0)
) {
wrappedProviders = new WrappedNodeExpr(
this.annotateForClosureCompiler
? wrapFunctionExpressionsInParens(rawProviders)
: rawProviders,
);
}
const topLevelImports: TopLevelImportedExpression[] = [];
if (this.compilationMode !== CompilationMode.LOCAL && ngModule.has('imports')) {
const rawImports = unwrapExpression(ngModule.get('imports')!);
let topLevelExpressions: ts.Expression[] = [];
if (ts.isArrayLiteralExpression(rawImports)) {
for (const element of rawImports.elements) {
if (ts.isSpreadElement(element)) {
// Because `imports` allows nested arrays anyway, a spread expression (`...foo`) can be
// treated the same as a direct reference to `foo`.
topLevelExpressions.push(element.expression);
continue;
}
topLevelExpressions.push(element);
}
} else {
// Treat the whole `imports` expression as top-level.
topLevelExpressions.push(rawImports);
}
let absoluteIndex = 0;
for (const importExpr of topLevelExpressions) {
const resolved = this.evaluator.evaluate(importExpr, moduleResolvers);
const {references, hasModuleWithProviders} = this.resolveTypeList(
importExpr,
[resolved],
node.name.text,
'imports',
absoluteIndex,
/* allowUnresolvedReferences */ false,
);
absoluteIndex += references.length;
topLevelImports.push({
expression: importExpr,
resolvedReferences: references,
hasModuleWithProviders,
});
}
}
const injectorMetadata: R3InjectorMetadata = {
name,
type,
providers: wrappedProviders,
imports: [],
};
if (this.compilationMode === CompilationMode.LOCAL) {
// Adding NgModule's raw imports/exports to the injector's imports field in local compilation
// mode.
for (const exp of [rawImports, rawExports]) {
if (exp === null) {
continue;
}
if (ts.isArrayLiteralExpression(exp)) {
// If array expression then add it entry-by-entry to the injector imports
if (exp.elements) {
injectorMetadata.imports.push(...exp.elements.map((n) => new WrappedNodeExpr(n)));
}
} else {
// if not array expression then add it as is to the injector's imports field.
injectorMetadata.imports.push(new WrappedNodeExpr(exp));
}
}
}
const factoryMetadata: R3FactoryMetadata = {
name,
type,
typeArgumentCount: 0,
deps: getValidConstructorDependencies(node, this.reflector, this.isCore),
target: FactoryTarget.NgModule,
};
// Remote scoping is used when adding imports to a component file would create a cycle. In such
// circumstances the component scope is monkey-patched from the NgModule file instead.
//
// However, if the NgModule itself has a cycle with the desired component/directive
// reference(s), then we need to be careful. This can happen for example if an NgModule imports
// a standalone component and the component also imports the NgModule.
//
// In this case, it'd be tempting to rely on the compiler's cycle detector to automatically put
// such circular references behind a function/closure. This requires global knowledge of the
// import graph though, and we don't want to depend on such techniques for new APIs like
// standalone components.
//
// Instead, we look for `forwardRef`s in the NgModule dependencies - an explicit signal from the
// user that a reference may not be defined until a circular import is resolved. If an NgModule
// contains forward-referenced declarations or imports, we assume that remotely scoped
// components should also guard against cycles using a closure-wrapped scope.
//
// The actual detection here is done heuristically. The compiler doesn't actually know whether
// any given `Reference` came from a `forwardRef`, but it does know when a `Reference` came from
// a `ForeignFunctionResolver` _like_ the `forwardRef` resolver. So we know when it's safe to
// not use a closure, and will use one just in case otherwise.
const remoteScopesMayRequireCycleProtection =
declarationRefs.some(isSyntheticReference) || importRefs.some(isSyntheticReference);
return {
diagnostics: diagnostics.length > 0 ? diagnostics : undefined,
analysis: {
id,
schemas,
mod: ngModuleMetadata,
inj: injectorMetadata,
fac: factoryMetadata,
declarations: declarationRefs,
rawDeclarations,
imports: topLevelImports,
rawImports,
importRefs,
exports: exportRefs,
rawExports,
providers: rawProviders,
providersRequiringFactory: rawProviders
? resolveProvidersRequiringFactory(rawProviders, this.reflector, this.evaluator)
: null,
classMetadata: this.includeClassMetadata
? extractClassMetadata(node, this.reflector, this.isCore, this.annotateForClosureCompiler)
: null,
factorySymbolName: node.name.text,
remoteScopesMayRequireCycleProtection,
decorator: (decorator?.node as ts.Decorator | null) ?? null,
},
};
}
symbol(node: ClassDeclaration, analysis: NgModuleAnalysis): NgModuleSymbol {
return new NgModuleSymbol(node, analysis.providers !== null);
}
register(node: ClassDeclaration, analysis: NgModuleAnalysis): void {
// Register this module's information with the LocalModuleScopeRegistry. This ensures that
// during the compile() phase, the module's metadata is available for selector scope
// computation.
this.metaRegistry.registerNgModuleMetadata({
kind: MetaKind.NgModule,
ref: new Reference(node),
schemas: analysis.schemas,
declarations: analysis.declarations,
imports: analysis.importRefs,
exports: analysis.exports,
rawDeclarations: analysis.rawDeclarations,
rawImports: analysis.rawImports,
rawExports: analysis.rawExports,
decorator: analysis.decorator,
mayDeclareProviders: analysis.providers !== null,
});
this.injectableRegistry.registerInjectable(node, {
ctorDeps: analysis.fac.deps,
});
}
| {
"end_byte": 25710,
"start_byte": 17186,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/ng_module/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/ng_module/src/handler.ts_25714_33727 | lve(
node: ClassDeclaration,
analysis: Readonly<NgModuleAnalysis>,
): ResolveResult<NgModuleResolution> {
if (this.compilationMode === CompilationMode.LOCAL) {
return {};
}
const scope = this.scopeRegistry.getScopeOfModule(node);
const diagnostics: ts.Diagnostic[] = [];
const scopeDiagnostics = this.scopeRegistry.getDiagnosticsOfModule(node);
if (scopeDiagnostics !== null) {
diagnostics.push(...scopeDiagnostics);
}
if (analysis.providersRequiringFactory !== null) {
const providerDiagnostics = getProviderDiagnostics(
analysis.providersRequiringFactory,
analysis.providers!,
this.injectableRegistry,
);
diagnostics.push(...providerDiagnostics);
}
const data: NgModuleResolution = {
injectorImports: [],
};
// Add all top-level imports from the `imports` field to the injector imports.
for (const topLevelImport of analysis.imports) {
if (topLevelImport.hasModuleWithProviders) {
// We have no choice but to emit expressions which contain MWPs, as we cannot filter on
// individual references.
data.injectorImports.push(new WrappedNodeExpr(topLevelImport.expression));
continue;
}
const refsToEmit: Reference<ClassDeclaration>[] = [];
let symbol: NgModuleSymbol | null = null;
if (this.semanticDepGraphUpdater !== null) {
const sym = this.semanticDepGraphUpdater.getSymbol(node) as NgModuleSymbol;
if (sym instanceof NgModuleSymbol) {
symbol = sym;
}
}
for (const ref of topLevelImport.resolvedReferences) {
const dirMeta = this.metaReader.getDirectiveMetadata(ref);
if (dirMeta !== null) {
if (!dirMeta.isComponent) {
// Skip emit of directives in imports - directives can't carry providers.
continue;
}
// Check whether this component has providers.
const mayExportProviders = this.exportedProviderStatusResolver.mayExportProviders(
dirMeta.ref,
(importRef) => {
// We need to keep track of which transitive imports were used to decide
// `mayExportProviders`, since if those change in a future compilation this
// NgModule will need to be re-emitted.
if (symbol !== null && this.semanticDepGraphUpdater !== null) {
const importSymbol = this.semanticDepGraphUpdater.getSymbol(importRef.node);
symbol.addTransitiveImportFromStandaloneComponent(importSymbol);
}
},
);
if (!mayExportProviders) {
// Skip emit of components that don't carry providers.
continue;
}
}
const pipeMeta = dirMeta === null ? this.metaReader.getPipeMetadata(ref) : null;
if (pipeMeta !== null) {
// Skip emit of pipes in imports - pipes can't carry providers.
continue;
}
refsToEmit.push(ref);
}
if (refsToEmit.length === topLevelImport.resolvedReferences.length) {
// All references within this top-level import should be emitted, so just use the user's
// expression.
data.injectorImports.push(new WrappedNodeExpr(topLevelImport.expression));
} else {
// Some references have been filtered out. Emit references to individual classes.
const context = node.getSourceFile();
for (const ref of refsToEmit) {
const emittedRef = this.refEmitter.emit(ref, context);
assertSuccessfulReferenceEmit(emittedRef, topLevelImport.expression, 'class');
data.injectorImports.push(emittedRef.expression);
}
}
}
if (scope !== null && !scope.compilation.isPoisoned) {
// Using the scope information, extend the injector's imports using the modules that are
// specified as module exports.
const context = getSourceFile(node);
for (const exportRef of analysis.exports) {
if (isNgModule(exportRef.node, scope.compilation)) {
const type = this.refEmitter.emit(exportRef, context);
assertSuccessfulReferenceEmit(type, node, 'NgModule');
data.injectorImports.push(type.expression);
}
}
for (const decl of analysis.declarations) {
const dirMeta = this.metaReader.getDirectiveMetadata(decl);
if (dirMeta !== null) {
const refType = dirMeta.isComponent ? 'Component' : 'Directive';
if (dirMeta.selector === null) {
throw new FatalDiagnosticError(
ErrorCode.DIRECTIVE_MISSING_SELECTOR,
decl.node,
`${refType} ${decl.node.name.text} has no selector, please add it!`,
);
}
continue;
}
}
}
if (diagnostics.length > 0) {
return {diagnostics};
}
if (
scope === null ||
scope.compilation.isPoisoned ||
scope.exported.isPoisoned ||
scope.reexports === null
) {
return {data};
} else {
return {
data,
reexports: scope.reexports,
};
}
}
compileFull(
node: ClassDeclaration,
{
inj,
mod,
fac,
classMetadata,
declarations,
remoteScopesMayRequireCycleProtection,
}: Readonly<NgModuleAnalysis>,
{injectorImports}: Readonly<NgModuleResolution>,
): CompileResult[] {
const factoryFn = compileNgFactoryDefField(fac);
const ngInjectorDef = compileInjector({
...inj,
imports: injectorImports,
});
const ngModuleDef = compileNgModule(mod);
const statements = ngModuleDef.statements;
const metadata = classMetadata !== null ? compileClassMetadata(classMetadata) : null;
this.insertMetadataStatement(statements, metadata);
this.appendRemoteScopingStatements(
statements,
node,
declarations,
remoteScopesMayRequireCycleProtection,
);
return this.compileNgModule(factoryFn, ngInjectorDef, ngModuleDef);
}
compilePartial(
node: ClassDeclaration,
{inj, fac, mod, classMetadata}: Readonly<NgModuleAnalysis>,
{injectorImports}: Readonly<NgModuleResolution>,
): CompileResult[] {
const factoryFn = compileDeclareFactory(fac);
const injectorDef = compileDeclareInjectorFromMetadata({
...inj,
imports: injectorImports,
});
const ngModuleDef = compileDeclareNgModuleFromMetadata(mod);
const metadata = classMetadata !== null ? compileDeclareClassMetadata(classMetadata) : null;
this.insertMetadataStatement(ngModuleDef.statements, metadata);
// NOTE: no remote scoping required as this is banned in partial compilation.
return this.compileNgModule(factoryFn, injectorDef, ngModuleDef);
}
compileLocal(
node: ClassDeclaration,
{
inj,
mod,
fac,
classMetadata,
declarations,
remoteScopesMayRequireCycleProtection,
}: Readonly<NgModuleAnalysis>,
): CompileResult[] {
const factoryFn = compileNgFactoryDefField(fac);
const ngInjectorDef = compileInjector({
...inj,
});
const ngModuleDef = compileNgModule(mod);
const statements = ngModuleDef.statements;
const metadata = classMetadata !== null ? compileClassMetadata(classMetadata) : null;
this.insertMetadataStatement(statements, metadata);
this.appendRemoteScopingStatements(
statements,
node,
declarations,
remoteScopesMayRequireCycleProtection,
);
return this.compileNgModule(factoryFn, ngInjectorDef, ngModuleDef);
}
/**
* Add class metadata statements, if provided, to the `ngModuleStatements`.
*/
private insertMetadataStatement(
ngModuleStatements: Statement[],
metadata: Expression | null,
): void {
if (metadata !== null) {
ngModuleStatements.unshift(metadata.toStmt());
}
}
/**
* Add remote scoping statements, as needed, to the `ngModuleStatements`.
*/
p | {
"end_byte": 33727,
"start_byte": 25714,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/ng_module/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/ng_module/src/handler.ts_33730_42019 | ate appendRemoteScopingStatements(
ngModuleStatements: Statement[],
node: ClassDeclaration,
declarations: Reference<ClassDeclaration>[],
remoteScopesMayRequireCycleProtection: boolean,
): void {
// Local compilation mode generates its own runtimes to compute the dependencies. So there no
// need to add remote scope statements (which also conflicts with local compilation runtimes)
if (this.compilationMode === CompilationMode.LOCAL) {
return;
}
const context = getSourceFile(node);
for (const decl of declarations) {
const remoteScope = this.scopeRegistry.getRemoteScope(decl.node);
if (remoteScope !== null) {
const directives = remoteScope.directives.map((directive) => {
const type = this.refEmitter.emit(directive, context);
assertSuccessfulReferenceEmit(type, node, 'directive');
return type.expression;
});
const pipes = remoteScope.pipes.map((pipe) => {
const type = this.refEmitter.emit(pipe, context);
assertSuccessfulReferenceEmit(type, node, 'pipe');
return type.expression;
});
const directiveArray = new LiteralArrayExpr(directives);
const pipesArray = new LiteralArrayExpr(pipes);
const directiveExpr =
remoteScopesMayRequireCycleProtection && directives.length > 0
? new FunctionExpr([], [new ReturnStatement(directiveArray)])
: directiveArray;
const pipesExpr =
remoteScopesMayRequireCycleProtection && pipes.length > 0
? new FunctionExpr([], [new ReturnStatement(pipesArray)])
: pipesArray;
const componentType = this.refEmitter.emit(decl, context);
assertSuccessfulReferenceEmit(componentType, node, 'component');
const declExpr = componentType.expression;
const setComponentScope = new ExternalExpr(R3Identifiers.setComponentScope);
const callExpr = new InvokeFunctionExpr(setComponentScope, [
declExpr,
directiveExpr,
pipesExpr,
]);
ngModuleStatements.push(callExpr.toStmt());
}
}
}
private compileNgModule(
factoryFn: CompileResult,
injectorDef: R3CompiledExpression,
ngModuleDef: R3CompiledExpression,
): CompileResult[] {
const res: CompileResult[] = [
factoryFn,
{
name: 'ɵmod',
initializer: ngModuleDef.expression,
statements: ngModuleDef.statements,
type: ngModuleDef.type,
deferrableImports: null,
},
{
name: 'ɵinj',
initializer: injectorDef.expression,
statements: injectorDef.statements,
type: injectorDef.type,
deferrableImports: null,
},
];
return res;
}
private _toR3Reference(
origin: ts.Node,
valueRef: Reference<ClassDeclaration>,
valueContext: ts.SourceFile,
): R3Reference {
if (valueRef.hasOwningModuleGuess) {
return toR3Reference(origin, valueRef, valueContext, this.refEmitter);
} else {
return toR3Reference(origin, valueRef, valueContext, this.refEmitter);
}
}
// Verify that a "Declaration" reference is a `ClassDeclaration` reference.
private isClassDeclarationReference(ref: Reference): ref is Reference<ClassDeclaration> {
return this.reflector.isClass(ref.node);
}
/**
* Compute a list of `Reference`s from a resolved metadata value.
*/
private resolveTypeList(
expr: ts.Node,
resolvedList: ResolvedValue,
className: string,
arrayName: string,
absoluteIndex: number,
allowUnresolvedReferences: boolean,
): {
references: Reference<ClassDeclaration>[];
hasModuleWithProviders: boolean;
dynamicValues: DynamicValue[];
} {
let hasModuleWithProviders = false;
const refList: Reference<ClassDeclaration>[] = [];
const dynamicValueSet = new Set<DynamicValue>();
if (!Array.isArray(resolvedList)) {
if (allowUnresolvedReferences) {
return {
references: [],
hasModuleWithProviders: false,
dynamicValues: [],
};
}
throw createValueHasWrongTypeError(
expr,
resolvedList,
`Expected array when reading the NgModule.${arrayName} of ${className}`,
);
}
for (let idx = 0; idx < resolvedList.length; idx++) {
let entry = resolvedList[idx];
// Unwrap ModuleWithProviders for modules that are locally declared (and thus static
// resolution was able to descend into the function and return an object literal, a Map).
if (entry instanceof SyntheticValue && isResolvedModuleWithProviders(entry)) {
entry = entry.value.ngModule;
hasModuleWithProviders = true;
} else if (entry instanceof Map && entry.has('ngModule')) {
entry = entry.get('ngModule')!;
hasModuleWithProviders = true;
}
if (Array.isArray(entry)) {
// Recurse into nested arrays.
const recursiveResult = this.resolveTypeList(
expr,
entry,
className,
arrayName,
absoluteIndex,
allowUnresolvedReferences,
);
refList.push(...recursiveResult.references);
for (const d of recursiveResult.dynamicValues) {
dynamicValueSet.add(d);
}
absoluteIndex += recursiveResult.references.length;
hasModuleWithProviders = hasModuleWithProviders || recursiveResult.hasModuleWithProviders;
} else if (entry instanceof Reference) {
if (!this.isClassDeclarationReference(entry)) {
throw createValueHasWrongTypeError(
entry.node,
entry,
`Value at position ${absoluteIndex} in the NgModule.${arrayName} of ${className} is not a class`,
);
}
refList.push(entry);
absoluteIndex += 1;
} else if (entry instanceof DynamicValue && allowUnresolvedReferences) {
dynamicValueSet.add(entry);
continue;
} else {
// TODO(alxhub): Produce a better diagnostic here - the array index may be an inner array.
throw createValueHasWrongTypeError(
expr,
entry,
`Value at position ${absoluteIndex} in the NgModule.${arrayName} of ${className} is not a reference`,
);
}
}
return {
references: refList,
hasModuleWithProviders,
dynamicValues: [...dynamicValueSet],
};
}
}
function isNgModule(node: ClassDeclaration, compilation: ScopeData): boolean {
return !compilation.dependencies.some((dep) => dep.ref.node === node);
}
/**
* Checks whether the given `ts.Expression` is the expression `module.id`.
*/
function isModuleIdExpression(expr: ts.Expression): boolean {
return (
ts.isPropertyAccessExpression(expr) &&
ts.isIdentifier(expr.expression) &&
expr.expression.text === 'module' &&
expr.name.text === 'id'
);
}
export interface TopLevelImportedExpression {
expression: ts.Expression;
resolvedReferences: Array<Reference<ClassDeclaration>>;
hasModuleWithProviders: boolean;
}
/**
* Helper method to produce a diagnostics for a situation when a standalone component
* is referenced in the `@NgModule.bootstrap` array.
*/
function makeStandaloneBootstrapDiagnostic(
ngModuleClass: ClassDeclaration,
bootstrappedClassRef: Reference<ClassDeclaration>,
rawBootstrapExpr: ts.Expression | null,
): ts.Diagnostic {
const componentClassName = bootstrappedClassRef.node.name.text;
// Note: this error message should be aligned with the one produced by JIT.
const message = //
`The \`${componentClassName}\` class is a standalone component, which can ` +
`not be used in the \`@NgModule.bootstrap\` array. Use the \`bootstrapApplication\` ` +
`function for bootstrap instead.`;
const relatedInformation: ts.DiagnosticRelatedInformation[] | undefined = [
makeRelatedInformation(ngModuleClass, `The 'bootstrap' array is present on this NgModule.`),
];
return makeDiagnostic(
ErrorCode.NGMODULE_BOOTSTRAP_IS_STANDALONE,
getDiagnosticNode(bootstrappedClassRef, rawBootstrapExpr),
message,
relatedInformation,
);
}
function isSyntheticReference(ref: Reference<DeclarationNode>): boolean {
return ref.synthetic;
}
| {
"end_byte": 42019,
"start_byte": 33730,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/ng_module/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/README.md_0_553 | # What is the 'annotations/component' package?
This package implements the `ComponentDecoratorHandler`, which processes and compiles `@Component`-decorated classes.
Component compilation is complex, and so not only is this package split out from the parent 'annotations' package, but its functionality is divided into separate files. In Angular, the concept of a component is an extension of a directive, so much of the component compilation functionality is shared with directive compilation, and is imported from the 'annotations/directive' package. | {
"end_byte": 553,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/README.md"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/BUILD.bazel_0_1651 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "component",
srcs = ["index.ts"] + glob([
"src/**/*.ts",
]),
deps = [
"//packages/compiler",
"//packages/compiler-cli/src/ngtsc/annotations/common",
"//packages/compiler-cli/src/ngtsc/annotations/directive",
"//packages/compiler-cli/src/ngtsc/annotations/ng_module",
"//packages/compiler-cli/src/ngtsc/cycles",
"//packages/compiler-cli/src/ngtsc/diagnostics",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/hmr",
"//packages/compiler-cli/src/ngtsc/imports",
"//packages/compiler-cli/src/ngtsc/incremental:api",
"//packages/compiler-cli/src/ngtsc/incremental/semantic_graph",
"//packages/compiler-cli/src/ngtsc/indexer",
"//packages/compiler-cli/src/ngtsc/metadata",
"//packages/compiler-cli/src/ngtsc/partial_evaluator",
"//packages/compiler-cli/src/ngtsc/perf",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/scope",
"//packages/compiler-cli/src/ngtsc/transform",
"//packages/compiler-cli/src/ngtsc/typecheck",
"//packages/compiler-cli/src/ngtsc/typecheck/api",
"//packages/compiler-cli/src/ngtsc/typecheck/extended/api",
"//packages/compiler-cli/src/ngtsc/typecheck/template_semantics/api",
"//packages/compiler-cli/src/ngtsc/util",
"//packages/compiler-cli/src/ngtsc/xi18n",
"@npm//@types/node",
"@npm//typescript",
],
)
| {
"end_byte": 1651,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/index.ts_0_261 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {ComponentDecoratorHandler} from './src/handler';
| {
"end_byte": 261,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/index.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/test/component_spec.ts_0_5275 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ConstantPool, ViewEncapsulation} from '@angular/compiler';
import ts from 'typescript';
import {CycleAnalyzer, CycleHandlingStrategy, ImportGraph} from '../../../cycles';
import {ErrorCode, FatalDiagnosticError, ngErrorCode} from '../../../diagnostics';
import {absoluteFrom} from '../../../file_system';
import {runInEachFileSystem} from '../../../file_system/testing';
import {
DeferredSymbolTracker,
ImportedSymbolsTracker,
ModuleResolver,
Reference,
ReferenceEmitter,
} from '../../../imports';
import {
CompoundMetadataReader,
DtsMetadataReader,
HostDirectivesResolver,
LocalMetadataRegistry,
ResourceRegistry,
} from '../../../metadata';
import {PartialEvaluator} from '../../../partial_evaluator';
import {NOOP_PERF_RECORDER} from '../../../perf';
import {isNamedClassDeclaration, TypeScriptReflectionHost} from '../../../reflection';
import {
LocalModuleScopeRegistry,
MetadataDtsModuleScopeResolver,
TypeCheckScopeRegistry,
} from '../../../scope';
import {getDeclaration, makeProgram} from '../../../testing';
import {CompilationMode} from '../../../transform';
import {
InjectableClassRegistry,
JitDeclarationRegistry,
NoopReferencesRegistry,
ResourceLoader,
ResourceLoaderContext,
} from '../../common';
import {ComponentDecoratorHandler} from '../src/handler';
export class StubResourceLoader implements ResourceLoader {
resolve(v: string): string {
return v;
}
canPreload = false;
canPreprocess = false;
load(v: string): string {
return '';
}
preload(): Promise<void> | undefined {
throw new Error('Not implemented');
}
preprocessInline(_data: string, _context: ResourceLoaderContext): Promise<string> {
throw new Error('Not implemented');
}
}
function setup(
program: ts.Program,
options: ts.CompilerOptions,
host: ts.CompilerHost,
opts: {
compilationMode?: CompilationMode;
usePoisonedData?: boolean;
externalRuntimeStyles?: boolean;
} = {},
) {
const {
compilationMode = CompilationMode.FULL,
usePoisonedData,
externalRuntimeStyles = false,
} = opts;
const checker = program.getTypeChecker();
const reflectionHost = new TypeScriptReflectionHost(checker);
const evaluator = new PartialEvaluator(reflectionHost, checker, /* dependencyTracker */ null);
const moduleResolver = new ModuleResolver(
program,
options,
host,
/* moduleResolutionCache */ null,
);
const importGraph = new ImportGraph(checker, NOOP_PERF_RECORDER);
const cycleAnalyzer = new CycleAnalyzer(importGraph);
const metaRegistry = new LocalMetadataRegistry();
const dtsReader = new DtsMetadataReader(checker, reflectionHost);
const dtsResolver = new MetadataDtsModuleScopeResolver(dtsReader, null);
const metaReader = new CompoundMetadataReader([metaRegistry, dtsReader]);
const scopeRegistry = new LocalModuleScopeRegistry(
metaRegistry,
metaReader,
dtsResolver,
new ReferenceEmitter([]),
null,
);
const refEmitter = new ReferenceEmitter([]);
const referencesRegistry = new NoopReferencesRegistry();
const injectableRegistry = new InjectableClassRegistry(reflectionHost, /* isCore */ false);
const resourceRegistry = new ResourceRegistry();
const hostDirectivesResolver = new HostDirectivesResolver(metaReader);
const typeCheckScopeRegistry = new TypeCheckScopeRegistry(
scopeRegistry,
metaReader,
hostDirectivesResolver,
);
const resourceLoader = new StubResourceLoader();
const importTracker = new ImportedSymbolsTracker();
const jitDeclarationRegistry = new JitDeclarationRegistry();
const handler = new ComponentDecoratorHandler(
reflectionHost,
evaluator,
metaRegistry,
metaReader,
scopeRegistry,
{
getCanonicalFileName: (fileName) => fileName,
},
scopeRegistry,
typeCheckScopeRegistry,
resourceRegistry,
/* isCore */ false,
/* strictCtorDeps */ false,
resourceLoader,
/* rootDirs */ ['/'],
/* defaultPreserveWhitespaces */ false,
/* i18nUseExternalIds */ true,
/* enableI18nLegacyMessageIdFormat */ false,
!!usePoisonedData,
/* i18nNormalizeLineEndingsInICUs */ false,
moduleResolver,
cycleAnalyzer,
CycleHandlingStrategy.UseRemoteScoping,
refEmitter,
referencesRegistry,
/* depTracker */ null,
injectableRegistry,
/* semanticDepGraphUpdater */ null,
/* annotateForClosureCompiler */ false,
NOOP_PERF_RECORDER,
hostDirectivesResolver,
importTracker,
true,
compilationMode,
new DeferredSymbolTracker(checker, /* onlyExplicitDeferDependencyImports */ false),
/* forbidOrphanRenderering */ false,
/* enableBlockSyntax */ true,
/* enableLetSyntax */ true,
externalRuntimeStyles,
/* localCompilationExtraImportsTracker */ null,
jitDeclarationRegistry,
/* i18nPreserveSignificantWhitespace */ true,
/* strictStandalone */ false,
/* enableHmr */ false,
);
return {reflectionHost, handler, resourceLoader, metaRegistry};
}
runInEachFileSystem(() => {
describe('ComponentDecoratorHandler', | {
"end_byte": 5275,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/test/component_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/test/component_spec.ts_5276_14261 | () => {
let _: typeof absoluteFrom;
beforeEach(() => (_ = absoluteFrom));
it('should produce a diagnostic when @Component has non-literal argument', () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
const TEST = '';
@Component(TEST) class TestCmp {}
`,
},
]);
const {reflectionHost, handler} = setup(program, options, host);
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
try {
handler.analyze(TestCmp, detected.metadata);
return fail('Analysis should have failed');
} catch (err) {
if (!(err instanceof FatalDiagnosticError)) {
return fail('Error should be a FatalDiagnosticError');
}
const diag = err.toDiagnostic();
expect(diag.code).toEqual(ivyCode(ErrorCode.DECORATOR_ARG_NOT_LITERAL));
expect(diag.file.fileName.endsWith('entry.ts')).toBe(true);
expect(diag.start).toBe(detected.metadata.args![0].getStart());
}
});
it('should keep track of inline template', () => {
const template = '<span>inline</span>';
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
@Component({
template: '${template}',
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler} = setup(program, options, host);
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {analysis} = handler.analyze(TestCmp, detected.metadata);
expect(analysis?.resources.template.path).toBeNull();
expect(analysis?.resources.template.expression.getText()).toEqual(`'${template}'`);
});
it('should keep track of external template', () => {
const templateUrl = '/myTemplate.ng.html';
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _(templateUrl),
contents: '<div>hello world</div>',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
@Component({
templateUrl: '${templateUrl}',
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler} = setup(program, options, host);
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {analysis} = handler.analyze(TestCmp, detected.metadata);
expect(analysis?.resources.template.path).toContain(templateUrl);
expect(analysis?.resources.template.expression.getText()).toContain(`'${templateUrl}'`);
});
it('should keep track of internal and external styles', () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/myStyle.css'),
contents: '<div>hello world</div>',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
// These are ignored because we only attempt to store string literals
const ignoredStyleUrl = 'asdlfkj';
const ignoredStyle = '';
@Component({
template: '',
styleUrls: ['/myStyle.css', ignoredStyleUrl],
styles: ['a { color: red; }', 'b { color: blue; }', ignoredStyle, ...[ignoredStyle]],
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler} = setup(program, options, host);
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {analysis} = handler.analyze(TestCmp, detected.metadata);
expect(analysis?.resources.styles.size).toBe(3);
});
it('should use an empty source map URL for an indirect template', () => {
const template = '<span>indirect</span>';
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
const TEMPLATE = '${template}';
@Component({
template: TEMPLATE,
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler} = setup(program, options, host);
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {analysis} = handler.analyze(TestCmp, detected.metadata);
expect(analysis?.template.file?.url).toEqual('');
});
it('does not emit a program with template parse errors', () => {
const template = '{{x ? y }}';
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
@Component({
template: '${template}',
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler} = setup(program, options, host);
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {analysis} = handler.analyze(TestCmp, detected.metadata);
const symbol = handler.symbol(TestCmp, analysis!);
const resolution = handler.resolve(TestCmp, analysis!, symbol);
const compileResult = handler.compileFull(
TestCmp,
analysis!,
resolution.data!,
new ConstantPool(),
);
expect(compileResult).toEqual([]);
});
it('should populate externalStyles from styleUrl when externalRuntimeStyles is enabled', () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/myStyle.css'),
contents: '<div>hello world</div>',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
@Component({
template: '',
styleUrl: '/myStyle.css',
styles: ['a { color: red; }', 'b { color: blue; }'],
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler} = setup(program, options, host, {
externalRuntimeStyles: true,
});
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {analysis} = handler.analyze(TestCmp, detected.metadata);
expect(analysis?.resources.styles.size).toBe(2);
expect(analysis?.meta.externalStyles).toEqual(['/myStyle.css']);
}); | {
"end_byte": 14261,
"start_byte": 5276,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/test/component_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/test/component_spec.ts_14267_22847 | it('should populate externalStyles from styleUrls when externalRuntimeStyles is enabled', () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/myStyle.css'),
contents: '<div>hello world</div>',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
@Component({
template: '',
styleUrls: ['/myStyle.css', '/myOtherStyle.css'],
styles: ['a { color: red; }', 'b { color: blue; }'],
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler} = setup(program, options, host, {
externalRuntimeStyles: true,
});
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {analysis} = handler.analyze(TestCmp, detected.metadata);
expect(analysis?.resources.styles.size).toBe(2);
expect(analysis?.meta.externalStyles).toEqual(['/myStyle.css', '/myOtherStyle.css']);
});
it('should keep default emulated view encapsulation with styleUrls when externalRuntimeStyles is enabled', () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/myStyle.css'),
contents: '<div>hello world</div>',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
@Component({
template: '',
styleUrls: ['/myStyle.css', '/myOtherStyle.css'],
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler} = setup(program, options, host, {
externalRuntimeStyles: true,
});
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {analysis} = handler.analyze(TestCmp, detected.metadata);
expect(analysis?.meta.encapsulation).toBe(ViewEncapsulation.Emulated);
});
it('should populate externalStyles from template link element when externalRuntimeStyles is enabled', () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/myStyle.css'),
contents: '<div>hello world</div>',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
@Component({
template: '<link rel="stylesheet" href="myTemplateStyle.css" />',
styles: ['a { color: red; }', 'b { color: blue; }'],
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler} = setup(program, options, host, {
externalRuntimeStyles: true,
});
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {analysis} = handler.analyze(TestCmp, detected.metadata);
expect(analysis?.resources.styles.size).toBe(2);
expect(analysis?.meta.externalStyles).toEqual(['myTemplateStyle.css']);
});
it('should populate externalStyles with resolve return values when externalRuntimeStyles is enabled', () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/myStyle.css'),
contents: '<div>hello world</div>',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
@Component({
template: '<link rel="stylesheet" href="myTemplateStyle.css" />',
styleUrl: '/myStyle.css',
styles: ['a { color: red; }', 'b { color: blue; }'],
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler, resourceLoader} = setup(program, options, host, {
externalRuntimeStyles: true,
});
resourceLoader.resolve = (v) => 'abc/' + v;
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {analysis} = handler.analyze(TestCmp, detected.metadata);
expect(analysis?.resources.styles.size).toBe(2);
expect(analysis?.meta.externalStyles).toEqual([
'abc//myStyle.css',
'abc/myTemplateStyle.css',
]);
});
it('should populate externalStyles from inline style transform when externalRuntimeStyles is enabled', async () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
@Component({
template: '',
styles: ['.abc {}']
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler, resourceLoader} = setup(program, options, host, {
externalRuntimeStyles: true,
});
resourceLoader.canPreload = true;
resourceLoader.canPreprocess = true;
resourceLoader.preprocessInline = async function (data, context) {
expect(data).toBe('.abc {}');
expect(context.containingFile).toBe(_('/entry.ts').toLowerCase());
expect(context.type).toBe('style');
expect(context.order).toBe(0);
return 'abc/myInlineStyle.css';
};
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
await handler.preanalyze(TestCmp, detected.metadata);
const {analysis} = handler.analyze(TestCmp, detected.metadata);
expect(analysis?.resources.styles.size).toBe(1);
expect(analysis?.meta.externalStyles).toEqual(['abc/myInlineStyle.css']);
expect(analysis?.meta.styles).toEqual([]);
});
it('should not populate externalStyles from inline style when externalRuntimeStyles is enabled and no transform', async () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
@Component({
template: '',
styles: ['.abc {}']
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler} = setup(program, options, host, {
externalRuntimeStyles: true,
});
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
await handler.preanalyze(TestCmp, detected.metadata);
const {analysis} = handler.analyze(TestCmp, detected.metadata);
expect(analysis?.resources.styles.size).toBe(1);
expect(analysis?.meta.externalStyles).toEqual([]);
expect(analysis?.meta.styles).toEqual(['.abc {}']);
}); | {
"end_byte": 22847,
"start_byte": 14267,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/test/component_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/test/component_spec.ts_22853_31447 | it('should not populate externalStyles from inline style when externalRuntimeStyles is enabled and no preanalyze', async () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
@Component({
template: '',
styles: ['.abc {}']
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler} = setup(program, options, host, {
externalRuntimeStyles: true,
});
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {analysis} = handler.analyze(TestCmp, detected.metadata);
expect(analysis?.resources.styles.size).toBe(1);
expect(analysis?.meta.externalStyles).toEqual([]);
expect(analysis?.meta.styles).toEqual(['.abc {}']);
});
it('should replace inline style content with transformed content', async () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
@Component({
template: '',
styles: ['.abc {}']
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler, resourceLoader} = setup(program, options, host);
resourceLoader.canPreload = true;
resourceLoader.canPreprocess = true;
resourceLoader.preprocessInline = async function (data, context) {
expect(data).toBe('.abc {}');
expect(context.containingFile).toBe(_('/entry.ts').toLowerCase());
expect(context.type).toBe('style');
return '.xyz {}';
};
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
await handler.preanalyze(TestCmp, detected.metadata);
const {analysis} = handler.analyze(TestCmp, detected.metadata);
expect(analysis?.inlineStyles).toEqual(jasmine.arrayWithExactContents(['.xyz {}']));
});
it('should replace template style element content for inline template with transformed content', async () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
@Component({
template: '<style>.abc {}</style>',
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler, resourceLoader} = setup(program, options, host);
resourceLoader.canPreload = true;
resourceLoader.canPreprocess = true;
resourceLoader.preprocessInline = async function (data, context) {
expect(data).toBe('.abc {}');
expect(context.containingFile).toBe(_('/entry.ts').toLowerCase());
expect(context.type).toBe('style');
return '.xyz {}';
};
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
await handler.preanalyze(TestCmp, detected.metadata);
const {analysis} = handler.analyze(TestCmp, detected.metadata);
expect(analysis?.inlineStyles).toEqual(jasmine.arrayWithExactContents(['.xyz {}']));
});
it('should replace template style element content for external template with transformed content', async () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/component.ng.html'),
contents: '<style>.abc {}</style>',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
@Component({
templateUrl: '/component.ng.html',
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler, resourceLoader} = setup(program, options, host);
resourceLoader.canPreload = true;
resourceLoader.canPreprocess = true;
resourceLoader.resolve = function (v) {
return _(v).toLowerCase();
};
resourceLoader.load = function (v) {
return host.readFile(v) ?? '';
};
resourceLoader.preload = () => Promise.resolve();
resourceLoader.preprocessInline = async function (data, context) {
expect(data).toBe('.abc {}');
expect(context.containingFile).toBe(_('/component.ng.html').toLowerCase());
expect(context.type).toBe('style');
return '.xyz {}';
};
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
await handler.preanalyze(TestCmp, detected.metadata);
const {analysis} = handler.analyze(TestCmp, detected.metadata);
expect(analysis?.inlineStyles).toEqual(jasmine.arrayWithExactContents(['.xyz {}']));
});
it('should error if canPreprocess is true and async analyze is not used', async () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
@Component({
template: '',
styles: ['.abc {}']
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler, resourceLoader} = setup(program, options, host);
resourceLoader.canPreload = true;
resourceLoader.canPreprocess = true;
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
expect(() => handler.analyze(TestCmp, detected.metadata)).toThrowError(
'Inline resource processing requires asynchronous preanalyze.',
);
});
it('should not error if component has no inline styles and canPreprocess is true', async () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
@Component({
template: '',
}) class TestCmp {}
`,
},
]);
const {reflectionHost, handler, resourceLoader} = setup(program, options, host);
resourceLoader.canPreload = true;
resourceLoader.canPreprocess = true;
resourceLoader.preprocessInline = async function (data, context) {
fail('preprocessInline should not have been called.');
return data;
};
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
await handler.preanalyze(TestCmp, detected.metadata);
expect(() => handler.analyze(TestCmp, detected.metadata)).not.toThrow();
}); | {
"end_byte": 31447,
"start_byte": 22853,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/test/component_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/test/component_spec.ts_31453_36419 | it('should evaluate the name of animations', () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/node_modules/@angular/animations/index.d.ts'),
contents: 'export declare function trigger(name: any): any',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
import {trigger} from '@angular/animations';
@Component({
template: '',
animations: [
trigger('animationName'),
[trigger('nestedAnimationName')],
],
})
class TestCmp {}
`,
},
]);
const {reflectionHost, handler, metaRegistry} = setup(program, options, host);
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {analysis} = handler.analyze(TestCmp, detected.metadata);
handler.register(TestCmp, analysis!);
const meta = metaRegistry.getDirectiveMetadata(new Reference(TestCmp));
expect(meta?.animationTriggerNames?.staticTriggerNames).toEqual([
'animationName',
'nestedAnimationName',
]);
expect(meta?.animationTriggerNames?.includesDynamicAnimations).toBeFalse();
});
it('should tell if the animations include a dynamic value', () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/node_modules/@angular/animations/index.d.ts'),
contents: 'export declare function trigger(name: any): any',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
import {trigger} from '@angular/animations';
function buildComplexAnimations() {
const name = 'complex';
return [trigger(name)];
}
@Component({
template: '',
animations: [
trigger('animationName'),
buildComplexAnimations(),
],
})
class TestCmp {}
`,
},
]);
const {reflectionHost, handler, metaRegistry} = setup(program, options, host);
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {analysis} = handler.analyze(TestCmp, detected.metadata);
handler.register(TestCmp, analysis!);
const meta = metaRegistry.getDirectiveMetadata(new Reference(TestCmp));
expect(meta?.animationTriggerNames?.staticTriggerNames).toEqual(['animationName']);
expect(meta?.animationTriggerNames?.includesDynamicAnimations).toBeTrue();
});
it('should treat complex animations expressions as dynamic', () => {
const {program, options, host} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/node_modules/@angular/animations/index.d.ts'),
contents: 'export declare function trigger(name: any): any',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
import {trigger} from '@angular/animations';
function buildComplexAnimations() {
const name = 'complex';
return [trigger(name)];
}
@Component({
template: '',
animations: buildComplexAnimations(),
})
class TestCmp {}
`,
},
]);
const {reflectionHost, handler, metaRegistry} = setup(program, options, host);
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(TestCmp, reflectionHost.getDecoratorsOfDeclaration(TestCmp));
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {analysis} = handler.analyze(TestCmp, detected.metadata);
handler.register(TestCmp, analysis!);
const meta = metaRegistry.getDirectiveMetadata(new Reference(TestCmp));
expect(meta?.animationTriggerNames?.includesDynamicAnimations).toBeTrue();
expect(meta?.animationTriggerNames?.staticTriggerNames.length).toBe(0);
}); | {
"end_byte": 36419,
"start_byte": 31453,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/test/component_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/test/component_spec.ts_36425_42772 | describe('localCompilation', () => {
it('should not produce diagnostic for cross-file imports in standalone component', () => {
const {program, options, host} = makeProgram(
[
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
import {SomeModule} from './some_where';
@Component({
standalone: true,
selector: 'main',
template: '<span>Hi!</span>',
imports: [SomeModule],
}) class TestCmp {}
`,
},
],
undefined,
undefined,
false,
);
const {reflectionHost, handler} = setup(program, options, host, {
compilationMode: CompilationMode.LOCAL,
});
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(
TestCmp,
reflectionHost.getDecoratorsOfDeclaration(TestCmp),
);
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {diagnostics} = handler.analyze(TestCmp, detected.metadata);
expect(diagnostics).toBeUndefined();
});
it('should produce diagnostic for imports in non-standalone component', () => {
const {program, options, host} = makeProgram(
[
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any;',
},
{
name: _('/entry.ts'),
contents: `
import {Component} from '@angular/core';
import {SomeModule} from './some_where';
@Component({
selector: 'main',
template: '<span>Hi!</span>',
imports: [SomeModule],
standalone: false,
}) class TestCmp {}
`,
},
],
undefined,
undefined,
false,
);
const {reflectionHost, handler} = setup(program, options, host, {
compilationMode: CompilationMode.LOCAL,
});
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(
TestCmp,
reflectionHost.getDecoratorsOfDeclaration(TestCmp),
);
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {diagnostics} = handler.analyze(TestCmp, detected.metadata);
expect(diagnostics).toContain(
jasmine.objectContaining({
code: ngErrorCode(ErrorCode.COMPONENT_NOT_STANDALONE),
messageText: jasmine.stringContaining(`'imports' is only valid`),
}),
);
});
it('should not produce diagnostic for cross-file schemas in standalone component', () => {
const {program, options, host} = makeProgram(
[
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any; export const CUSTOM_ELEMENTS_SCHEMA: any;',
},
{
name: _('/entry.ts'),
contents: `
import {Component, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
import {SomeModule} from './some_where';
@Component({
standalone: true,
selector: 'main',
template: '<span>Hi!</span>',
schemas: [CUSTOM_ELEMENTS_SCHEMA],
}) class TestCmp {}
`,
},
],
undefined,
undefined,
false,
);
const {reflectionHost, handler} = setup(program, options, host, {
compilationMode: CompilationMode.LOCAL,
});
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(
TestCmp,
reflectionHost.getDecoratorsOfDeclaration(TestCmp),
);
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {diagnostics} = handler.analyze(TestCmp, detected.metadata);
expect(diagnostics).toBeUndefined();
});
it('should produce diagnostic for schemas in non-standalone component', () => {
const {program, options, host} = makeProgram(
[
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Component: any; export const CUSTOM_ELEMENTS_SCHEMA: any;',
},
{
name: _('/entry.ts'),
contents: `
import {Component, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
import {SomeModule} from './some_where';
@Component({
selector: 'main',
standalone: false,
template: '<span>Hi!</span>',
schemas: [CUSTOM_ELEMENTS_SCHEMA],
}) class TestCmp {}
`,
},
],
undefined,
undefined,
false,
);
const {reflectionHost, handler} = setup(program, options, host, {
compilationMode: CompilationMode.LOCAL,
});
const TestCmp = getDeclaration(program, _('/entry.ts'), 'TestCmp', isNamedClassDeclaration);
const detected = handler.detect(
TestCmp,
reflectionHost.getDecoratorsOfDeclaration(TestCmp),
);
if (detected === undefined) {
return fail('Failed to recognize @Component');
}
const {diagnostics} = handler.analyze(TestCmp, detected.metadata);
expect(diagnostics).toContain(
jasmine.objectContaining({
code: ngErrorCode(ErrorCode.COMPONENT_NOT_STANDALONE),
messageText: jasmine.stringContaining(`'schemas' is only valid`),
}),
);
});
});
});
function ivyCode(code: ErrorCode): number {
return Number('-99' + code.valueOf());
}
}); | {
"end_byte": 42772,
"start_byte": 36425,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/test/component_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/test/BUILD.bazel_0_1262 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "test_lib",
testonly = True,
srcs = glob([
"**/*.ts",
]),
deps = [
"//packages:types",
"//packages/compiler",
"//packages/compiler-cli/src/ngtsc/annotations/common",
"//packages/compiler-cli/src/ngtsc/annotations/component",
"//packages/compiler-cli/src/ngtsc/cycles",
"//packages/compiler-cli/src/ngtsc/diagnostics",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/file_system/testing",
"//packages/compiler-cli/src/ngtsc/imports",
"//packages/compiler-cli/src/ngtsc/metadata",
"//packages/compiler-cli/src/ngtsc/partial_evaluator",
"//packages/compiler-cli/src/ngtsc/perf",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/scope",
"//packages/compiler-cli/src/ngtsc/testing",
"//packages/compiler-cli/src/ngtsc/transform",
"@npm//typescript",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node_no_angular"],
deps = [
":test_lib",
],
)
| {
"end_byte": 1262,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/test/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/src/resources.ts_0_8560 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
DEFAULT_INTERPOLATION_CONFIG,
InterpolationConfig,
LexerRange,
ParsedTemplate,
ParseSourceFile,
parseTemplate,
ParseTemplateOptions,
TmplAstNode,
} from '@angular/compiler';
import ts from 'typescript';
import {ErrorCode, FatalDiagnosticError} from '../../../diagnostics';
import {absoluteFrom} from '../../../file_system';
import {DependencyTracker} from '../../../incremental/api';
import {Resource} from '../../../metadata';
import {DynamicValue, PartialEvaluator, traceDynamicValue} from '../../../partial_evaluator';
import {ClassDeclaration, DeclarationNode, Decorator} from '../../../reflection';
import {CompilationMode} from '../../../transform';
import {TemplateSourceMapping} from '../../../typecheck/api';
import {
createValueHasWrongTypeError,
isStringArray,
ResourceLoader,
assertLocalCompilationUnresolvedConst,
} from '../../common';
/**
* The literal style url extracted from the decorator, along with metadata for diagnostics.
*/
export interface StyleUrlMeta {
url: string;
expression: ts.Expression;
source:
| ResourceTypeForDiagnostics.StylesheetFromTemplate
| ResourceTypeForDiagnostics.StylesheetFromDecorator;
}
/**
* Information about the origin of a resource in the application code. This is used for creating
* diagnostics, so we can point to the root cause of an error in the application code.
*
* A template resource comes from the `templateUrl` property on the component decorator.
*
* Stylesheets resources can come from either the `styleUrls` property on the component decorator,
* or from inline `style` tags and style links on the external template.
*/
export const enum ResourceTypeForDiagnostics {
Template,
StylesheetFromTemplate,
StylesheetFromDecorator,
}
/**
* Information about the template which was extracted during parsing.
*
* This contains the actual parsed template as well as any metadata collected during its parsing,
* some of which might be useful for re-parsing the template with different options.
*/
export interface ParsedComponentTemplate extends ParsedTemplate {
/**
* The template AST, parsed in a manner which preserves source map information for diagnostics.
*
* Not useful for emit.
*/
diagNodes: TmplAstNode[];
/**
* The `ParseSourceFile` for the template.
*/
file: ParseSourceFile;
}
export interface ParsedTemplateWithSource extends ParsedComponentTemplate {
/** The string contents of the template. */
content: string;
sourceMapping: TemplateSourceMapping;
declaration: TemplateDeclaration;
}
/**
* Common fields extracted from the declaration of a template.
*/
interface CommonTemplateDeclaration {
preserveWhitespaces: boolean;
interpolationConfig: InterpolationConfig;
templateUrl: string;
resolvedTemplateUrl: string;
}
/**
* Information extracted from the declaration of an inline template.
*/
export interface InlineTemplateDeclaration extends CommonTemplateDeclaration {
isInline: true;
expression: ts.Expression;
}
/**
* Information extracted from the declaration of an external template.
*/
export interface ExternalTemplateDeclaration extends CommonTemplateDeclaration {
isInline: false;
templateUrlExpression: ts.Expression;
}
/**
* The declaration of a template extracted from a component decorator.
*
* This data is extracted and stored separately to facilitate re-interpreting the template
* declaration whenever the compiler is notified of a change to a template file. With this
* information, `ComponentDecoratorHandler` is able to re-read the template and update the component
* record without needing to parse the original decorator again.
*/
export type TemplateDeclaration = InlineTemplateDeclaration | ExternalTemplateDeclaration;
/** Determines the node to use for debugging purposes for the given TemplateDeclaration. */
export function getTemplateDeclarationNodeForError(
declaration: TemplateDeclaration,
): ts.Expression {
return declaration.isInline ? declaration.expression : declaration.templateUrlExpression;
}
export interface ExtractTemplateOptions {
usePoisonedData: boolean;
enableI18nLegacyMessageIdFormat: boolean;
i18nNormalizeLineEndingsInICUs: boolean;
enableBlockSyntax: boolean;
enableLetSyntax: boolean;
preserveSignificantWhitespace?: boolean;
}
export function extractTemplate(
node: ClassDeclaration,
template: TemplateDeclaration,
evaluator: PartialEvaluator,
depTracker: DependencyTracker | null,
resourceLoader: ResourceLoader,
options: ExtractTemplateOptions,
compilationMode: CompilationMode,
): ParsedTemplateWithSource {
if (template.isInline) {
let sourceStr: string;
let sourceParseRange: LexerRange | null = null;
let templateContent: string;
let sourceMapping: TemplateSourceMapping;
let escapedString = false;
let sourceMapUrl: string | null;
// We only support SourceMaps for inline templates that are simple string literals.
if (
ts.isStringLiteral(template.expression) ||
ts.isNoSubstitutionTemplateLiteral(template.expression)
) {
// the start and end of the `templateExpr` node includes the quotation marks, which we must
// strip
sourceParseRange = getTemplateRange(template.expression);
sourceStr = template.expression.getSourceFile().text;
templateContent = template.expression.text;
escapedString = true;
sourceMapping = {
type: 'direct',
node: template.expression,
};
sourceMapUrl = template.resolvedTemplateUrl;
} else {
const resolvedTemplate = evaluator.evaluate(template.expression);
// The identifier used for @Component.template cannot be resolved in local compilation mode. An error specific to this situation is generated.
assertLocalCompilationUnresolvedConst(
compilationMode,
resolvedTemplate,
template.expression,
'Unresolved identifier found for @Component.template field! ' +
'Did you import this identifier from a file outside of the compilation unit? ' +
'This is not allowed when Angular compiler runs in local mode. ' +
'Possible solutions: 1) Move the declaration into a file within the ' +
'compilation unit, 2) Inline the template, 3) Move the template into ' +
'a separate .html file and include it using @Component.templateUrl',
);
if (typeof resolvedTemplate !== 'string') {
throw createValueHasWrongTypeError(
template.expression,
resolvedTemplate,
'template must be a string',
);
}
// We do not parse the template directly from the source file using a lexer range, so
// the template source and content are set to the statically resolved template.
sourceStr = resolvedTemplate;
templateContent = resolvedTemplate;
sourceMapping = {
type: 'indirect',
node: template.expression,
componentClass: node,
template: templateContent,
};
// Indirect templates cannot be mapped to a particular byte range of any input file, since
// they're computed by expressions that may span many files. Don't attempt to map them back
// to a given file.
sourceMapUrl = null;
}
return {
...parseExtractedTemplate(
template,
sourceStr,
sourceParseRange,
escapedString,
sourceMapUrl,
options,
),
content: templateContent,
sourceMapping,
declaration: template,
};
} else {
const templateContent = resourceLoader.load(template.resolvedTemplateUrl);
if (depTracker !== null) {
depTracker.addResourceDependency(
node.getSourceFile(),
absoluteFrom(template.resolvedTemplateUrl),
);
}
return {
...parseExtractedTemplate(
template,
/* sourceStr */ templateContent,
/* sourceParseRange */ null,
/* escapedString */ false,
/* sourceMapUrl */ template.resolvedTemplateUrl,
options,
),
content: templateContent,
sourceMapping: {
type: 'external',
componentClass: node,
node: template.templateUrlExpression,
template: templateContent,
templateUrl: template.resolvedTemplateUrl,
},
declaration: template,
};
}
} | {
"end_byte": 8560,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/src/resources.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/src/resources.ts_8562_17131 | function parseExtractedTemplate(
template: TemplateDeclaration,
sourceStr: string,
sourceParseRange: LexerRange | null,
escapedString: boolean,
sourceMapUrl: string | null,
options: ExtractTemplateOptions,
): ParsedComponentTemplate {
// We always normalize line endings if the template has been escaped (i.e. is inline).
const i18nNormalizeLineEndingsInICUs = escapedString || options.i18nNormalizeLineEndingsInICUs;
const commonParseOptions: ParseTemplateOptions = {
interpolationConfig: template.interpolationConfig,
range: sourceParseRange ?? undefined,
enableI18nLegacyMessageIdFormat: options.enableI18nLegacyMessageIdFormat,
i18nNormalizeLineEndingsInICUs,
alwaysAttemptHtmlToR3AstConversion: options.usePoisonedData,
escapedString,
enableBlockSyntax: options.enableBlockSyntax,
enableLetSyntax: options.enableLetSyntax,
};
const parsedTemplate = parseTemplate(sourceStr, sourceMapUrl ?? '', {
...commonParseOptions,
preserveWhitespaces: template.preserveWhitespaces,
preserveSignificantWhitespace: options.preserveSignificantWhitespace,
});
// Unfortunately, the primary parse of the template above may not contain accurate source map
// information. If used directly, it would result in incorrect code locations in template
// errors, etc. There are three main problems:
//
// 1. `preserveWhitespaces: false` or `preserveSignificantWhitespace: false` annihilates the
// correctness of template source mapping, as the whitespace transformation changes the
// contents of HTML text nodes before they're parsed into Angular expressions.
// 2. `preserveLineEndings: false` causes growing misalignments in templates that use '\r\n'
// line endings, by normalizing them to '\n'.
// 3. By default, the template parser strips leading trivia characters (like spaces, tabs, and
// newlines). This also destroys source mapping information.
//
// In order to guarantee the correctness of diagnostics, templates are parsed a second time
// with the above options set to preserve source mappings.
const {nodes: diagNodes} = parseTemplate(sourceStr, sourceMapUrl ?? '', {
...commonParseOptions,
preserveWhitespaces: true,
preserveLineEndings: true,
preserveSignificantWhitespace: true,
leadingTriviaChars: [],
});
return {
...parsedTemplate,
diagNodes,
file: new ParseSourceFile(sourceStr, sourceMapUrl ?? ''),
};
}
export function parseTemplateDeclaration(
node: ClassDeclaration,
decorator: Decorator,
component: Map<string, ts.Expression>,
containingFile: string,
evaluator: PartialEvaluator,
depTracker: DependencyTracker | null,
resourceLoader: ResourceLoader,
defaultPreserveWhitespaces: boolean,
): TemplateDeclaration {
let preserveWhitespaces: boolean = defaultPreserveWhitespaces;
if (component.has('preserveWhitespaces')) {
const expr = component.get('preserveWhitespaces')!;
const value = evaluator.evaluate(expr);
if (typeof value !== 'boolean') {
throw createValueHasWrongTypeError(expr, value, 'preserveWhitespaces must be a boolean');
}
preserveWhitespaces = value;
}
let interpolationConfig = DEFAULT_INTERPOLATION_CONFIG;
if (component.has('interpolation')) {
const expr = component.get('interpolation')!;
const value = evaluator.evaluate(expr);
if (
!Array.isArray(value) ||
value.length !== 2 ||
!value.every((element) => typeof element === 'string')
) {
throw createValueHasWrongTypeError(
expr,
value,
'interpolation must be an array with 2 elements of string type',
);
}
interpolationConfig = InterpolationConfig.fromArray(value as [string, string]);
}
if (component.has('templateUrl')) {
const templateUrlExpr = component.get('templateUrl')!;
const templateUrl = evaluator.evaluate(templateUrlExpr);
if (typeof templateUrl !== 'string') {
throw createValueHasWrongTypeError(
templateUrlExpr,
templateUrl,
'templateUrl must be a string',
);
}
try {
const resourceUrl = resourceLoader.resolve(templateUrl, containingFile);
return {
isInline: false,
interpolationConfig,
preserveWhitespaces,
templateUrl,
templateUrlExpression: templateUrlExpr,
resolvedTemplateUrl: resourceUrl,
};
} catch (e) {
if (depTracker !== null) {
// The analysis of this file cannot be re-used if the template URL could
// not be resolved. Future builds should re-analyze and re-attempt resolution.
depTracker.recordDependencyAnalysisFailure(node.getSourceFile());
}
throw makeResourceNotFoundError(
templateUrl,
templateUrlExpr,
ResourceTypeForDiagnostics.Template,
);
}
} else if (component.has('template')) {
return {
isInline: true,
interpolationConfig,
preserveWhitespaces,
expression: component.get('template')!,
templateUrl: containingFile,
resolvedTemplateUrl: containingFile,
};
} else {
throw new FatalDiagnosticError(
ErrorCode.COMPONENT_MISSING_TEMPLATE,
decorator.node,
'component is missing a template',
);
}
}
export function preloadAndParseTemplate(
evaluator: PartialEvaluator,
resourceLoader: ResourceLoader,
depTracker: DependencyTracker | null,
preanalyzeTemplateCache: Map<DeclarationNode, ParsedTemplateWithSource>,
node: ClassDeclaration,
decorator: Decorator,
component: Map<string, ts.Expression>,
containingFile: string,
defaultPreserveWhitespaces: boolean,
options: ExtractTemplateOptions,
compilationMode: CompilationMode,
): Promise<ParsedTemplateWithSource | null> {
if (component.has('templateUrl')) {
// Extract the templateUrl and preload it.
const templateUrlExpr = component.get('templateUrl')!;
const templateUrl = evaluator.evaluate(templateUrlExpr);
if (typeof templateUrl !== 'string') {
throw createValueHasWrongTypeError(
templateUrlExpr,
templateUrl,
'templateUrl must be a string',
);
}
try {
const resourceUrl = resourceLoader.resolve(templateUrl, containingFile);
const templatePromise = resourceLoader.preload(resourceUrl, {
type: 'template',
containingFile,
className: node.name.text,
});
// If the preload worked, then actually load and parse the template, and wait for any
// style URLs to resolve.
if (templatePromise !== undefined) {
return templatePromise.then(() => {
const templateDecl = parseTemplateDeclaration(
node,
decorator,
component,
containingFile,
evaluator,
depTracker,
resourceLoader,
defaultPreserveWhitespaces,
);
const template = extractTemplate(
node,
templateDecl,
evaluator,
depTracker,
resourceLoader,
options,
compilationMode,
);
preanalyzeTemplateCache.set(node, template);
return template;
});
} else {
return Promise.resolve(null);
}
} catch (e) {
if (depTracker !== null) {
// The analysis of this file cannot be re-used if the template URL could
// not be resolved. Future builds should re-analyze and re-attempt resolution.
depTracker.recordDependencyAnalysisFailure(node.getSourceFile());
}
throw makeResourceNotFoundError(
templateUrl,
templateUrlExpr,
ResourceTypeForDiagnostics.Template,
);
}
} else {
const templateDecl = parseTemplateDeclaration(
node,
decorator,
component,
containingFile,
evaluator,
depTracker,
resourceLoader,
defaultPreserveWhitespaces,
);
const template = extractTemplate(
node,
templateDecl,
evaluator,
depTracker,
resourceLoader,
options,
compilationMode,
);
preanalyzeTemplateCache.set(node, template);
return Promise.resolve(template);
}
}
function getTemplateRange(templateExpr: ts.Expression) {
const startPos = templateExpr.getStart() + 1;
const {line, character} = ts.getLineAndCharacterOfPosition(
templateExpr.getSourceFile(),
startPos,
);
return {
startPos,
startLine: line,
startCol: character,
endPos: templateExpr.getEnd() - 1,
};
} | {
"end_byte": 17131,
"start_byte": 8562,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/src/resources.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/src/resources.ts_17133_23943 | export function makeResourceNotFoundError(
file: string,
nodeForError: ts.Node,
resourceType: ResourceTypeForDiagnostics,
): FatalDiagnosticError {
let errorText: string;
switch (resourceType) {
case ResourceTypeForDiagnostics.Template:
errorText = `Could not find template file '${file}'.`;
break;
case ResourceTypeForDiagnostics.StylesheetFromTemplate:
errorText = `Could not find stylesheet file '${file}' linked from the template.`;
break;
case ResourceTypeForDiagnostics.StylesheetFromDecorator:
errorText = `Could not find stylesheet file '${file}'.`;
break;
}
return new FatalDiagnosticError(ErrorCode.COMPONENT_RESOURCE_NOT_FOUND, nodeForError, errorText);
}
/**
* Transforms the given decorator to inline external resources. i.e. if the decorator
* resolves to `@Component`, the `templateUrl` and `styleUrls` metadata fields will be
* transformed to their semantically-equivalent inline variants.
*
* This method is used for serializing decorators into the class metadata. The emitted
* class metadata should not refer to external resources as this would be inconsistent
* with the component definitions/declarations which already inline external resources.
*
* Additionally, the references to external resources would require libraries to ship
* external resources exclusively for the class metadata.
*/
export function transformDecoratorResources(
dec: Decorator,
component: Map<string, ts.Expression>,
styles: string[],
template: ParsedTemplateWithSource,
): Decorator {
if (dec.name !== 'Component') {
return dec;
}
// If no external resources are referenced, preserve the original decorator
// for the best source map experience when the decorator is emitted in TS.
if (
!component.has('templateUrl') &&
!component.has('styleUrls') &&
!component.has('styleUrl') &&
!component.has('styles')
) {
return dec;
}
const metadata = new Map(component);
// Set the `template` property if the `templateUrl` property is set.
if (metadata.has('templateUrl')) {
metadata.delete('templateUrl');
metadata.set('template', ts.factory.createStringLiteral(template.content));
}
if (metadata.has('styleUrls') || metadata.has('styleUrl') || metadata.has('styles')) {
metadata.delete('styles');
metadata.delete('styleUrls');
metadata.delete('styleUrl');
if (styles.length > 0) {
const styleNodes = styles.reduce((result, style) => {
if (style.trim().length > 0) {
result.push(ts.factory.createStringLiteral(style));
}
return result;
}, [] as ts.StringLiteral[]);
if (styleNodes.length > 0) {
metadata.set('styles', ts.factory.createArrayLiteralExpression(styleNodes));
}
}
}
// Convert the metadata to TypeScript AST object literal element nodes.
const newMetadataFields: ts.ObjectLiteralElementLike[] = [];
for (const [name, value] of metadata.entries()) {
newMetadataFields.push(ts.factory.createPropertyAssignment(name, value));
}
// Return the original decorator with the overridden metadata argument.
return {...dec, args: [ts.factory.createObjectLiteralExpression(newMetadataFields)]};
}
export function extractComponentStyleUrls(
evaluator: PartialEvaluator,
component: Map<string, ts.Expression>,
): StyleUrlMeta[] {
const styleUrlsExpr = component.get('styleUrls');
const styleUrlExpr = component.get('styleUrl');
if (styleUrlsExpr !== undefined && styleUrlExpr !== undefined) {
throw new FatalDiagnosticError(
ErrorCode.COMPONENT_INVALID_STYLE_URLS,
styleUrlExpr,
'@Component cannot define both `styleUrl` and `styleUrls`. ' +
'Use `styleUrl` if the component has one stylesheet, or `styleUrls` if it has multiple',
);
}
if (styleUrlsExpr !== undefined) {
return extractStyleUrlsFromExpression(evaluator, component.get('styleUrls')!);
}
if (styleUrlExpr !== undefined) {
const styleUrl = evaluator.evaluate(styleUrlExpr);
if (typeof styleUrl !== 'string') {
throw createValueHasWrongTypeError(styleUrlExpr, styleUrl, 'styleUrl must be a string');
}
return [
{
url: styleUrl,
source: ResourceTypeForDiagnostics.StylesheetFromDecorator,
expression: styleUrlExpr,
},
];
}
return [];
}
function extractStyleUrlsFromExpression(
evaluator: PartialEvaluator,
styleUrlsExpr: ts.Expression,
): StyleUrlMeta[] {
const styleUrls: StyleUrlMeta[] = [];
if (ts.isArrayLiteralExpression(styleUrlsExpr)) {
for (const styleUrlExpr of styleUrlsExpr.elements) {
if (ts.isSpreadElement(styleUrlExpr)) {
styleUrls.push(...extractStyleUrlsFromExpression(evaluator, styleUrlExpr.expression));
} else {
const styleUrl = evaluator.evaluate(styleUrlExpr);
if (typeof styleUrl !== 'string') {
throw createValueHasWrongTypeError(styleUrlExpr, styleUrl, 'styleUrl must be a string');
}
styleUrls.push({
url: styleUrl,
source: ResourceTypeForDiagnostics.StylesheetFromDecorator,
expression: styleUrlExpr,
});
}
}
} else {
const evaluatedStyleUrls = evaluator.evaluate(styleUrlsExpr);
if (!isStringArray(evaluatedStyleUrls)) {
throw createValueHasWrongTypeError(
styleUrlsExpr,
evaluatedStyleUrls,
'styleUrls must be an array of strings',
);
}
for (const styleUrl of evaluatedStyleUrls) {
styleUrls.push({
url: styleUrl,
source: ResourceTypeForDiagnostics.StylesheetFromDecorator,
expression: styleUrlsExpr,
});
}
}
return styleUrls;
}
export function extractInlineStyleResources(component: Map<string, ts.Expression>): Set<Resource> {
const styles = new Set<Resource>();
function stringLiteralElements(array: ts.ArrayLiteralExpression): ts.StringLiteralLike[] {
return array.elements.filter((e): e is ts.StringLiteralLike => ts.isStringLiteralLike(e));
}
const stylesExpr = component.get('styles');
if (stylesExpr !== undefined) {
if (ts.isArrayLiteralExpression(stylesExpr)) {
for (const expression of stringLiteralElements(stylesExpr)) {
styles.add({path: null, expression});
}
} else if (ts.isStringLiteralLike(stylesExpr)) {
styles.add({path: null, expression: stylesExpr});
}
}
return styles;
}
export function _extractTemplateStyleUrls(template: ParsedTemplateWithSource): StyleUrlMeta[] {
if (template.styleUrls === null) {
return [];
}
const expression = getTemplateDeclarationNodeForError(template.declaration);
return template.styleUrls.map((url) => ({
url,
source: ResourceTypeForDiagnostics.StylesheetFromTemplate,
expression,
}));
} | {
"end_byte": 23943,
"start_byte": 17133,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/src/resources.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/src/symbol.ts_0_4130 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
isArrayEqual,
isReferenceEqual,
SemanticReference,
SemanticSymbol,
} from '../../../incremental/semantic_graph';
import {DirectiveSymbol} from '../../directive';
/**
* Represents an Angular component.
*/
export class ComponentSymbol extends DirectiveSymbol {
usedDirectives: SemanticReference[] = [];
usedPipes: SemanticReference[] = [];
isRemotelyScoped = false;
override isEmitAffected(
previousSymbol: SemanticSymbol,
publicApiAffected: Set<SemanticSymbol>,
): boolean {
if (!(previousSymbol instanceof ComponentSymbol)) {
return true;
}
// Create an equality function that considers symbols equal if they represent the same
// declaration, but only if the symbol in the current compilation does not have its public API
// affected.
const isSymbolUnaffected = (current: SemanticReference, previous: SemanticReference) =>
isReferenceEqual(current, previous) && !publicApiAffected.has(current.symbol);
// The emit of a component is affected if either of the following is true:
// 1. The component used to be remotely scoped but no longer is, or vice versa.
// 2. The list of used directives has changed or any of those directives have had their public
// API changed. If the used directives have been reordered but not otherwise affected then
// the component must still be re-emitted, as this may affect directive instantiation order.
// 3. The list of used pipes has changed, or any of those pipes have had their public API
// changed.
return (
this.isRemotelyScoped !== previousSymbol.isRemotelyScoped ||
!isArrayEqual(this.usedDirectives, previousSymbol.usedDirectives, isSymbolUnaffected) ||
!isArrayEqual(this.usedPipes, previousSymbol.usedPipes, isSymbolUnaffected)
);
}
override isTypeCheckBlockAffected(
previousSymbol: SemanticSymbol,
typeCheckApiAffected: Set<SemanticSymbol>,
): boolean {
if (!(previousSymbol instanceof ComponentSymbol)) {
return true;
}
// To verify that a used directive is not affected we need to verify that its full inheritance
// chain is not present in `typeCheckApiAffected`.
const isInheritanceChainAffected = (symbol: SemanticSymbol): boolean => {
let currentSymbol: SemanticSymbol | null = symbol;
while (currentSymbol instanceof DirectiveSymbol) {
if (typeCheckApiAffected.has(currentSymbol)) {
return true;
}
currentSymbol = currentSymbol.baseClass;
}
return false;
};
// Create an equality function that considers directives equal if they represent the same
// declaration and if the symbol and all symbols it inherits from in the current compilation
// do not have their type-check API affected.
const isDirectiveUnaffected = (current: SemanticReference, previous: SemanticReference) =>
isReferenceEqual(current, previous) && !isInheritanceChainAffected(current.symbol);
// Create an equality function that considers pipes equal if they represent the same
// declaration and if the symbol in the current compilation does not have its type-check
// API affected.
const isPipeUnaffected = (current: SemanticReference, previous: SemanticReference) =>
isReferenceEqual(current, previous) && !typeCheckApiAffected.has(current.symbol);
// The emit of a type-check block of a component is affected if either of the following is true:
// 1. The list of used directives has changed or any of those directives have had their
// type-check API changed.
// 2. The list of used pipes has changed, or any of those pipes have had their type-check API
// changed.
return (
!isArrayEqual(this.usedDirectives, previousSymbol.usedDirectives, isDirectiveUnaffected) ||
!isArrayEqual(this.usedPipes, previousSymbol.usedPipes, isPipeUnaffected)
);
}
}
| {
"end_byte": 4130,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/src/symbol.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/src/diagnostics.ts_0_1918 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {Cycle} from '../../../cycles';
import {makeRelatedInformation} from '../../../diagnostics';
import {Reference} from '../../../imports';
/**
* Generate a diagnostic related information object that describes a potential cyclic import path.
*/
export function makeCyclicImportInfo(
ref: Reference,
type: string,
cycle: Cycle,
): ts.DiagnosticRelatedInformation {
const name = ref.debugName || '(unknown)';
const path = cycle
.getPath()
.map((sf) => sf.fileName)
.join(' -> ');
const message = `The ${type} '${name}' is used in the template but importing it would create a cycle: `;
return makeRelatedInformation(ref.node, message + path);
}
/**
* Checks whether a selector is a valid custom element tag name.
* Based loosely on https://github.com/sindresorhus/validate-element-name.
*/
export function checkCustomElementSelectorForErrors(selector: string): string | null {
// Avoid flagging components with an attribute or class selector. This isn't bulletproof since it
// won't catch cases like `foo[]bar`, but we don't need it to be. This is mainly to avoid flagging
// something like `foo-bar[baz]` incorrectly.
if (selector.includes('.') || (selector.includes('[') && selector.includes(']'))) {
return null;
}
if (!/^[a-z]/.test(selector)) {
return 'Selector of a ShadowDom-encapsulated component must start with a lower case letter.';
}
if (/[A-Z]/.test(selector)) {
return 'Selector of a ShadowDom-encapsulated component must all be in lower case.';
}
if (!selector.includes('-')) {
return 'Selector of a component that uses ViewEncapsulation.ShadowDom must contain a hyphen.';
}
return null;
}
| {
"end_byte": 1918,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/src/diagnostics.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/src/util.ts_0_5653 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {AnimationTriggerNames} from '@angular/compiler';
import {
isResolvedModuleWithProviders,
ResolvedModuleWithProviders,
} from '@angular/compiler-cli/src/ngtsc/annotations/ng_module';
import {ErrorCode, makeDiagnostic} from '@angular/compiler-cli/src/ngtsc/diagnostics';
import ts from 'typescript';
import {Reference} from '../../../imports';
import {
ForeignFunctionResolver,
ResolvedValue,
ResolvedValueMap,
SyntheticValue,
} from '../../../partial_evaluator';
import {ClassDeclaration, isNamedClassDeclaration} from '../../../reflection';
import {createValueHasWrongTypeError, getOriginNodeForDiagnostics} from '../../common';
/**
* Collect the animation names from the static evaluation result.
* @param value the static evaluation result of the animations
* @param animationTriggerNames the animation names collected and whether some names could not be
* statically evaluated.
*/
export function collectAnimationNames(
value: ResolvedValue,
animationTriggerNames: AnimationTriggerNames,
) {
if (value instanceof Map) {
const name = value.get('name');
if (typeof name === 'string') {
animationTriggerNames.staticTriggerNames.push(name);
} else {
animationTriggerNames.includesDynamicAnimations = true;
}
} else if (Array.isArray(value)) {
for (const resolvedValue of value) {
collectAnimationNames(resolvedValue, animationTriggerNames);
}
} else {
animationTriggerNames.includesDynamicAnimations = true;
}
}
export function isAngularAnimationsReference(reference: Reference, symbolName: string): boolean {
return (
reference.ownedByModuleGuess === '@angular/animations' && reference.debugName === symbolName
);
}
export const animationTriggerResolver: ForeignFunctionResolver = (
fn,
node,
resolve,
unresolvable,
) => {
const animationTriggerMethodName = 'trigger';
if (!isAngularAnimationsReference(fn, animationTriggerMethodName)) {
return unresolvable;
}
const triggerNameExpression = node.arguments[0];
if (!triggerNameExpression) {
return unresolvable;
}
const res = new Map<string, ResolvedValue>();
res.set('name', resolve(triggerNameExpression));
return res;
};
export function validateAndFlattenComponentImports(
imports: ResolvedValue,
expr: ts.Expression,
isDeferred: boolean,
): {
imports: Reference<ClassDeclaration>[];
diagnostics: ts.Diagnostic[];
} {
const flattened: Reference<ClassDeclaration>[] = [];
const errorMessage = isDeferred
? `'deferredImports' must be an array of components, directives, or pipes.`
: `'imports' must be an array of components, directives, pipes, or NgModules.`;
if (!Array.isArray(imports)) {
const error = createValueHasWrongTypeError(expr, imports, errorMessage).toDiagnostic();
return {
imports: [],
diagnostics: [error],
};
}
const diagnostics: ts.Diagnostic[] = [];
for (const ref of imports) {
if (Array.isArray(ref)) {
const {imports: childImports, diagnostics: childDiagnostics} =
validateAndFlattenComponentImports(ref, expr, isDeferred);
flattened.push(...childImports);
diagnostics.push(...childDiagnostics);
} else if (ref instanceof Reference) {
if (isNamedClassDeclaration(ref.node)) {
flattened.push(ref as Reference<ClassDeclaration>);
} else {
diagnostics.push(
createValueHasWrongTypeError(
ref.getOriginForDiagnostics(expr),
ref,
errorMessage,
).toDiagnostic(),
);
}
} else if (isLikelyModuleWithProviders(ref)) {
let origin = expr;
if (ref instanceof SyntheticValue) {
// The `ModuleWithProviders` type originated from a foreign function declaration, in which
// case the original foreign call is available which is used to get a more accurate origin
// node that points at the specific call expression.
origin = getOriginNodeForDiagnostics(ref.value.mwpCall, expr);
}
diagnostics.push(
makeDiagnostic(
ErrorCode.COMPONENT_UNKNOWN_IMPORT,
origin,
`Component imports contains a ModuleWithProviders value, likely the result of a 'Module.forRoot()'-style call. ` +
`These calls are not used to configure components and are not valid in standalone component imports - ` +
`consider importing them in the application bootstrap instead.`,
),
);
} else {
diagnostics.push(createValueHasWrongTypeError(expr, imports, errorMessage).toDiagnostic());
}
}
return {imports: flattened, diagnostics};
}
/**
* Inspects `value` to determine if it resembles a `ModuleWithProviders` value. This is an
* approximation only suitable for error reporting as any resolved object with an `ngModule`
* key is considered a `ModuleWithProviders`.
*/
function isLikelyModuleWithProviders(
value: ResolvedValue,
): value is SyntheticValue<ResolvedModuleWithProviders> | ResolvedValueMap {
if (value instanceof SyntheticValue && isResolvedModuleWithProviders(value)) {
// This is a `ModuleWithProviders` as extracted from a foreign function call.
return true;
}
if (value instanceof Map && value.has('ngModule')) {
// A resolved `Map` with `ngModule` property would have been extracted from locally declared
// functions that return a `ModuleWithProviders` object.
return true;
}
return false;
}
| {
"end_byte": 5653,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/src/util.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts_0_5874 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
AnimationTriggerNames,
BoundTarget,
compileClassDebugInfo,
compileHmrInitializer,
compileComponentClassMetadata,
compileComponentDeclareClassMetadata,
compileComponentFromMetadata,
compileDeclareComponentFromMetadata,
compileDeferResolverFunction,
ConstantPool,
CssSelector,
DeclarationListEmitMode,
DeclareComponentTemplateInfo,
DEFAULT_INTERPOLATION_CONFIG,
DeferBlockDepsEmitMode,
DomElementSchemaRegistry,
ExternalExpr,
FactoryTarget,
makeBindingParser,
outputAst as o,
R3ComponentDeferMetadata,
R3ComponentMetadata,
R3DeferPerComponentDependency,
R3DirectiveDependencyMetadata,
R3NgModuleDependencyMetadata,
R3PipeDependencyMetadata,
R3TargetBinder,
R3TemplateDependency,
R3TemplateDependencyKind,
R3TemplateDependencyMetadata,
SchemaMetadata,
SelectorMatcher,
TmplAstDeferredBlock,
ViewEncapsulation,
} from '@angular/compiler';
import ts from 'typescript';
import {Cycle, CycleAnalyzer, CycleHandlingStrategy} from '../../../cycles';
import {
ErrorCode,
FatalDiagnosticError,
makeDiagnostic,
makeRelatedInformation,
} from '../../../diagnostics';
import {absoluteFrom, relative} from '../../../file_system';
import {
assertSuccessfulReferenceEmit,
DeferredSymbolTracker,
ImportedFile,
ImportedSymbolsTracker,
LocalCompilationExtraImportsTracker,
ModuleResolver,
Reference,
ReferenceEmitter,
} from '../../../imports';
import {DependencyTracker} from '../../../incremental/api';
import {
extractSemanticTypeParameters,
SemanticDepGraphUpdater,
} from '../../../incremental/semantic_graph';
import {IndexingContext} from '../../../indexer';
import {
DirectiveMeta,
extractDirectiveTypeCheckMeta,
HostDirectivesResolver,
MatchSource,
MetadataReader,
MetadataRegistry,
MetaKind,
NgModuleMeta,
PipeMeta,
Resource,
ResourceRegistry,
} from '../../../metadata';
import {PartialEvaluator} from '../../../partial_evaluator';
import {PerfEvent, PerfRecorder} from '../../../perf';
import {
ClassDeclaration,
DeclarationNode,
Decorator,
Import,
isNamedClassDeclaration,
ReflectionHost,
reflectObjectLiteral,
} from '../../../reflection';
import {
ComponentScopeKind,
ComponentScopeReader,
DtsModuleScopeResolver,
LocalModuleScope,
LocalModuleScopeRegistry,
makeNotStandaloneDiagnostic,
makeUnknownComponentImportDiagnostic,
StandaloneScope,
TypeCheckScopeRegistry,
} from '../../../scope';
import {
getDiagnosticNode,
makeUnknownComponentDeferredImportDiagnostic,
} from '../../../scope/src/util';
import {
AnalysisOutput,
CompilationMode,
CompileResult,
DecoratorHandler,
DetectResult,
HandlerPrecedence,
ResolveResult,
} from '../../../transform';
import {TemplateId, TypeCheckableDirectiveMeta, TypeCheckContext} from '../../../typecheck/api';
import {ExtendedTemplateChecker} from '../../../typecheck/extended/api';
import {TemplateSemanticsChecker} from '../../../typecheck/template_semantics/api/api';
import {getSourceFile} from '../../../util/src/typescript';
import {Xi18nContext} from '../../../xi18n';
import {
combineResolvers,
compileDeclareFactory,
compileInputTransformFields,
compileNgFactoryDefField,
compileResults,
extractClassDebugInfo,
extractClassMetadata,
extractSchemas,
findAngularDecorator,
forwardRefResolver,
getDirectiveDiagnostics,
getProviderDiagnostics,
InjectableClassRegistry,
isExpressionForwardReference,
readBaseClass,
ReferencesRegistry,
removeIdentifierReferences,
resolveEncapsulationEnumValueLocally,
resolveEnumValue,
resolveImportedFile,
resolveLiteral,
resolveProvidersRequiringFactory,
ResourceLoader,
toFactoryMetadata,
tryUnwrapForwardRef,
validateHostDirectives,
wrapFunctionExpressionsInParens,
} from '../../common';
import {extractDirectiveMetadata, parseDirectiveStyles} from '../../directive';
import {createModuleWithProvidersResolver, NgModuleSymbol} from '../../ng_module';
import {checkCustomElementSelectorForErrors, makeCyclicImportInfo} from './diagnostics';
import {
ComponentAnalysisData,
ComponentResolutionData,
DeferredComponentDependency,
} from './metadata';
import {
_extractTemplateStyleUrls,
extractComponentStyleUrls,
extractInlineStyleResources,
extractTemplate,
makeResourceNotFoundError,
ParsedTemplateWithSource,
parseTemplateDeclaration,
preloadAndParseTemplate,
ResourceTypeForDiagnostics,
StyleUrlMeta,
transformDecoratorResources,
} from './resources';
import {ComponentSymbol} from './symbol';
import {
animationTriggerResolver,
collectAnimationNames,
validateAndFlattenComponentImports,
} from './util';
import {getTemplateDiagnostics} from '../../../typecheck';
import {JitDeclarationRegistry} from '../../common/src/jit_declaration_registry';
import {extractHmrMetatadata, getHmrUpdateDeclaration} from '../../../hmr';
const EMPTY_ARRAY: any[] = [];
type UsedDirective = R3DirectiveDependencyMetadata & {
ref: Reference<ClassDeclaration>;
importedFile: ImportedFile;
};
type UsedPipe = R3PipeDependencyMetadata & {
ref: Reference<ClassDeclaration>;
importedFile: ImportedFile;
};
type UsedNgModule = R3NgModuleDependencyMetadata & {
importedFile: ImportedFile;
};
type AnyUsedType = UsedPipe | UsedDirective | UsedNgModule;
type ComponentTemplate = R3ComponentMetadata<R3TemplateDependency>['template'];
const isUsedDirective = (decl: AnyUsedType): decl is UsedDirective =>
decl.kind === R3TemplateDependencyKind.Directive;
const isUsedPipe = (decl: AnyUsedType): decl is UsedPipe =>
decl.kind === R3TemplateDependencyKind.Pipe;
/**
* `DecoratorHandler` which handles the `@Component` annotation.
*/ | {
"end_byte": 5874,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts_5875_14783 | export class ComponentDecoratorHandler
implements
DecoratorHandler<Decorator, ComponentAnalysisData, ComponentSymbol, ComponentResolutionData>
{
constructor(
private reflector: ReflectionHost,
private evaluator: PartialEvaluator,
private metaRegistry: MetadataRegistry,
private metaReader: MetadataReader,
private scopeReader: ComponentScopeReader,
private compilerHost: Pick<ts.CompilerHost, 'getCanonicalFileName'>,
private scopeRegistry: LocalModuleScopeRegistry,
private typeCheckScopeRegistry: TypeCheckScopeRegistry,
private resourceRegistry: ResourceRegistry,
private isCore: boolean,
private strictCtorDeps: boolean,
private resourceLoader: ResourceLoader,
private rootDirs: ReadonlyArray<string>,
private defaultPreserveWhitespaces: boolean,
private i18nUseExternalIds: boolean,
private enableI18nLegacyMessageIdFormat: boolean,
private usePoisonedData: boolean,
private i18nNormalizeLineEndingsInICUs: boolean,
private moduleResolver: ModuleResolver,
private cycleAnalyzer: CycleAnalyzer,
private cycleHandlingStrategy: CycleHandlingStrategy,
private refEmitter: ReferenceEmitter,
private referencesRegistry: ReferencesRegistry,
private depTracker: DependencyTracker | null,
private injectableRegistry: InjectableClassRegistry,
private semanticDepGraphUpdater: SemanticDepGraphUpdater | null,
private annotateForClosureCompiler: boolean,
private perf: PerfRecorder,
private hostDirectivesResolver: HostDirectivesResolver,
private importTracker: ImportedSymbolsTracker,
private includeClassMetadata: boolean,
private readonly compilationMode: CompilationMode,
private readonly deferredSymbolTracker: DeferredSymbolTracker,
private readonly forbidOrphanRendering: boolean,
private readonly enableBlockSyntax: boolean,
private readonly enableLetSyntax: boolean,
private readonly externalRuntimeStyles: boolean,
private readonly localCompilationExtraImportsTracker: LocalCompilationExtraImportsTracker | null,
private readonly jitDeclarationRegistry: JitDeclarationRegistry,
private readonly i18nPreserveSignificantWhitespace: boolean,
private readonly strictStandalone: boolean,
private readonly enableHmr: boolean,
) {
this.extractTemplateOptions = {
enableI18nLegacyMessageIdFormat: this.enableI18nLegacyMessageIdFormat,
i18nNormalizeLineEndingsInICUs: this.i18nNormalizeLineEndingsInICUs,
usePoisonedData: this.usePoisonedData,
enableBlockSyntax: this.enableBlockSyntax,
enableLetSyntax: this.enableLetSyntax,
preserveSignificantWhitespace: this.i18nPreserveSignificantWhitespace,
};
// Dependencies can't be deferred during HMR, because the HMR update module can't have
// dynamic imports and its dependencies need to be passed in directly. If dependencies
// are deferred, their imports will be deleted so we won't may lose the reference to them.
this.canDeferDeps = !enableHmr;
}
private literalCache = new Map<Decorator, ts.ObjectLiteralExpression>();
private elementSchemaRegistry = new DomElementSchemaRegistry();
/**
* During the asynchronous preanalyze phase, it's necessary to parse the template to extract
* any potential <link> tags which might need to be loaded. This cache ensures that work is not
* thrown away, and the parsed template is reused during the analyze phase.
*/
private preanalyzeTemplateCache = new Map<DeclarationNode, ParsedTemplateWithSource>();
private preanalyzeStylesCache = new Map<DeclarationNode, string[] | null>();
/** Whether generated code for a component can defer its dependencies. */
private readonly canDeferDeps: boolean;
private extractTemplateOptions: {
enableI18nLegacyMessageIdFormat: boolean;
i18nNormalizeLineEndingsInICUs: boolean;
usePoisonedData: boolean;
enableBlockSyntax: boolean;
enableLetSyntax: boolean;
preserveSignificantWhitespace?: boolean;
};
readonly precedence = HandlerPrecedence.PRIMARY;
readonly name = 'ComponentDecoratorHandler';
detect(
node: ClassDeclaration,
decorators: Decorator[] | null,
): DetectResult<Decorator> | undefined {
if (!decorators) {
return undefined;
}
const decorator = findAngularDecorator(decorators, 'Component', this.isCore);
if (decorator !== undefined) {
return {
trigger: decorator.node,
decorator,
metadata: decorator,
};
} else {
return undefined;
}
}
preanalyze(node: ClassDeclaration, decorator: Readonly<Decorator>): Promise<void> | undefined {
// In preanalyze, resource URLs associated with the component are asynchronously preloaded via
// the resourceLoader. This is the only time async operations are allowed for a component.
// These resources are:
//
// - the templateUrl, if there is one
// - any styleUrls if present
// - any stylesheets referenced from <link> tags in the template itself
//
// As a result of the last one, the template must be parsed as part of preanalysis to extract
// <link> tags, which may involve waiting for the templateUrl to be resolved first.
// If preloading isn't possible, then skip this step.
if (!this.resourceLoader.canPreload) {
return undefined;
}
const meta = resolveLiteral(decorator, this.literalCache);
const component = reflectObjectLiteral(meta);
const containingFile = node.getSourceFile().fileName;
const resolveStyleUrl = (styleUrl: string): Promise<void> | undefined => {
try {
const resourceUrl = this.resourceLoader.resolve(styleUrl, containingFile);
return this.resourceLoader.preload(resourceUrl, {
type: 'style',
containingFile,
className: node.name.text,
});
} catch {
// Don't worry about failures to preload. We can handle this problem during analysis by
// producing a diagnostic.
return undefined;
}
};
// A Promise that waits for the template and all <link>ed styles within it to be preloaded.
const templateAndTemplateStyleResources = preloadAndParseTemplate(
this.evaluator,
this.resourceLoader,
this.depTracker,
this.preanalyzeTemplateCache,
node,
decorator,
component,
containingFile,
this.defaultPreserveWhitespaces,
this.extractTemplateOptions,
this.compilationMode,
).then(
(template): {templateUrl?: string; templateStyles: string[]; templateStyleUrls: string[]} => {
if (template === null) {
return {templateStyles: [], templateStyleUrls: []};
}
let templateUrl;
if (template.sourceMapping.type === 'external') {
templateUrl = template.sourceMapping.templateUrl;
}
return {
templateUrl,
templateStyles: template.styles,
templateStyleUrls: template.styleUrls,
};
},
);
// Extract all the styleUrls in the decorator.
const componentStyleUrls = extractComponentStyleUrls(this.evaluator, component);
return templateAndTemplateStyleResources.then(async (templateInfo) => {
// Extract inline styles, process, and cache for use in synchronous analyze phase
let styles: string[] | null = null;
// Order plus className allows inline styles to be identified per component by a preprocessor
let orderOffset = 0;
const rawStyles = parseDirectiveStyles(component, this.evaluator, this.compilationMode);
if (rawStyles?.length) {
styles = await Promise.all(
rawStyles.map((style) =>
this.resourceLoader.preprocessInline(style, {
type: 'style',
containingFile,
order: orderOffset++,
className: node.name.text,
}),
),
);
}
if (templateInfo.templateStyles) {
styles ??= [];
styles.push(
...(await Promise.all(
templateInfo.templateStyles.map((style) =>
this.resourceLoader.preprocessInline(style, {
type: 'style',
containingFile: templateInfo.templateUrl ?? containingFile,
order: orderOffset++,
className: node.name.text,
}),
),
)),
);
}
this.preanalyzeStylesCache.set(node, styles);
if (this.externalRuntimeStyles) {
// No preanalysis required for style URLs with external runtime styles
return;
}
// Wait for both the template and all styleUrl resources to resolve.
await Promise.all([
...componentStyleUrls.map((styleUrl) => resolveStyleUrl(styleUrl.url)),
...templateInfo.templateStyleUrls.map((url) => resolveStyleUrl(url)),
]);
});
} | {
"end_byte": 14783,
"start_byte": 5875,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts_14787_22724 | analyze(
node: ClassDeclaration,
decorator: Readonly<Decorator>,
): AnalysisOutput<ComponentAnalysisData> {
this.perf.eventCount(PerfEvent.AnalyzeComponent);
const containingFile = node.getSourceFile().fileName;
this.literalCache.delete(decorator);
let diagnostics: ts.Diagnostic[] | undefined;
let isPoisoned = false;
// @Component inherits @Directive, so begin by extracting the @Directive metadata and building
// on it.
const directiveResult = extractDirectiveMetadata(
node,
decorator,
this.reflector,
this.importTracker,
this.evaluator,
this.refEmitter,
this.referencesRegistry,
this.isCore,
this.annotateForClosureCompiler,
this.compilationMode,
this.elementSchemaRegistry.getDefaultComponentElementName(),
this.strictStandalone,
);
// `extractDirectiveMetadata` returns `jitForced = true` when the `@Component` has
// set `jit: true`. In this case, compilation of the decorator is skipped. Returning
// an empty object signifies that no analysis was produced.
if (directiveResult.jitForced) {
this.jitDeclarationRegistry.jitDeclarations.add(node);
return {};
}
// Next, read the `@Component`-specific fields.
const {
decorator: component,
metadata,
inputs,
outputs,
hostDirectives,
rawHostDirectives,
} = directiveResult;
const encapsulation: number =
(this.compilationMode !== CompilationMode.LOCAL
? resolveEnumValue(this.evaluator, component, 'encapsulation', 'ViewEncapsulation')
: resolveEncapsulationEnumValueLocally(component.get('encapsulation'))) ??
ViewEncapsulation.Emulated;
let changeDetection: number | o.Expression | null = null;
if (this.compilationMode !== CompilationMode.LOCAL) {
changeDetection = resolveEnumValue(
this.evaluator,
component,
'changeDetection',
'ChangeDetectionStrategy',
);
} else if (component.has('changeDetection')) {
changeDetection = new o.WrappedNodeExpr(component.get('changeDetection')!);
}
let animations: o.Expression | null = null;
let animationTriggerNames: AnimationTriggerNames | null = null;
if (component.has('animations')) {
const animationExpression = component.get('animations')!;
animations = new o.WrappedNodeExpr(animationExpression);
const animationsValue = this.evaluator.evaluate(
animationExpression,
animationTriggerResolver,
);
animationTriggerNames = {includesDynamicAnimations: false, staticTriggerNames: []};
collectAnimationNames(animationsValue, animationTriggerNames);
}
// Go through the root directories for this project, and select the one with the smallest
// relative path representation.
const relativeContextFilePath = this.rootDirs.reduce<string | undefined>(
(previous, rootDir) => {
const candidate = relative(absoluteFrom(rootDir), absoluteFrom(containingFile));
if (previous === undefined || candidate.length < previous.length) {
return candidate;
} else {
return previous;
}
},
undefined,
)!;
// Note that we could technically combine the `viewProvidersRequiringFactory` and
// `providersRequiringFactory` into a single set, but we keep the separate so that
// we can distinguish where an error is coming from when logging the diagnostics in `resolve`.
let viewProvidersRequiringFactory: Set<Reference<ClassDeclaration>> | null = null;
let providersRequiringFactory: Set<Reference<ClassDeclaration>> | null = null;
let wrappedViewProviders: o.Expression | null = null;
if (component.has('viewProviders')) {
const viewProviders = component.get('viewProviders')!;
viewProvidersRequiringFactory = resolveProvidersRequiringFactory(
viewProviders,
this.reflector,
this.evaluator,
);
wrappedViewProviders = new o.WrappedNodeExpr(
this.annotateForClosureCompiler
? wrapFunctionExpressionsInParens(viewProviders)
: viewProviders,
);
}
if (component.has('providers')) {
providersRequiringFactory = resolveProvidersRequiringFactory(
component.get('providers')!,
this.reflector,
this.evaluator,
);
}
let resolvedImports: Reference<ClassDeclaration>[] | null = null;
let resolvedDeferredImports: Reference<ClassDeclaration>[] | null = null;
let rawImports: ts.Expression | null = component.get('imports') ?? null;
let rawDeferredImports: ts.Expression | null = component.get('deferredImports') ?? null;
if ((rawImports || rawDeferredImports) && !metadata.isStandalone) {
if (diagnostics === undefined) {
diagnostics = [];
}
const importsField = rawImports ? 'imports' : 'deferredImports';
diagnostics.push(
makeDiagnostic(
ErrorCode.COMPONENT_NOT_STANDALONE,
component.get(importsField)!,
`'${importsField}' is only valid on a component that is standalone.`,
[
makeRelatedInformation(
node.name,
`Did you forget to add 'standalone: true' to this @Component?`,
),
],
),
);
// Poison the component so that we don't spam further template type-checking errors that
// result from misconfigured imports.
isPoisoned = true;
} else if (
this.compilationMode !== CompilationMode.LOCAL &&
(rawImports || rawDeferredImports)
) {
const importResolvers = combineResolvers([
createModuleWithProvidersResolver(this.reflector, this.isCore),
forwardRefResolver,
]);
const importDiagnostics: ts.Diagnostic[] = [];
if (rawImports) {
const expr = rawImports;
const imported = this.evaluator.evaluate(expr, importResolvers);
const {imports: flattened, diagnostics} = validateAndFlattenComponentImports(
imported,
expr,
false /* isDeferred */,
);
importDiagnostics.push(...diagnostics);
resolvedImports = flattened;
rawImports = expr;
}
if (rawDeferredImports) {
const expr = rawDeferredImports;
const imported = this.evaluator.evaluate(expr, importResolvers);
const {imports: flattened, diagnostics} = validateAndFlattenComponentImports(
imported,
expr,
true /* isDeferred */,
);
importDiagnostics.push(...diagnostics);
resolvedDeferredImports = flattened;
rawDeferredImports = expr;
}
if (importDiagnostics.length > 0) {
isPoisoned = true;
if (diagnostics === undefined) {
diagnostics = [];
}
diagnostics.push(...importDiagnostics);
}
}
let schemas: SchemaMetadata[] | null = null;
if (component.has('schemas') && !metadata.isStandalone) {
if (diagnostics === undefined) {
diagnostics = [];
}
diagnostics.push(
makeDiagnostic(
ErrorCode.COMPONENT_NOT_STANDALONE,
component.get('schemas')!,
`'schemas' is only valid on a component that is standalone.`,
),
);
} else if (this.compilationMode !== CompilationMode.LOCAL && component.has('schemas')) {
schemas = extractSchemas(component.get('schemas')!, this.evaluator, 'Component');
} else if (metadata.isStandalone) {
schemas = [];
}
// Parse the template.
// If a preanalyze phase was executed, the template may already exist in parsed form, so check
// the preanalyzeTemplateCache.
// Extract a closure of the template parsing code so that it can be reparsed with different
// options if needed, like in the indexing pipeline.
let template: ParsedTemplateWithSource; | {
"end_byte": 22724,
"start_byte": 14787,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts_22729_32471 | if (this.preanalyzeTemplateCache.has(node)) {
// The template was parsed in preanalyze. Use it and delete it to save memory.
const preanalyzed = this.preanalyzeTemplateCache.get(node)!;
this.preanalyzeTemplateCache.delete(node);
template = preanalyzed;
} else {
const templateDecl = parseTemplateDeclaration(
node,
decorator,
component,
containingFile,
this.evaluator,
this.depTracker,
this.resourceLoader,
this.defaultPreserveWhitespaces,
);
template = extractTemplate(
node,
templateDecl,
this.evaluator,
this.depTracker,
this.resourceLoader,
{
enableI18nLegacyMessageIdFormat: this.enableI18nLegacyMessageIdFormat,
i18nNormalizeLineEndingsInICUs: this.i18nNormalizeLineEndingsInICUs,
usePoisonedData: this.usePoisonedData,
enableBlockSyntax: this.enableBlockSyntax,
enableLetSyntax: this.enableLetSyntax,
preserveSignificantWhitespace: this.i18nPreserveSignificantWhitespace,
},
this.compilationMode,
);
if (
this.compilationMode === CompilationMode.LOCAL &&
template.errors &&
template.errors.length > 0
) {
// Template errors are handled at the type check phase. But we skip this phase in local compilation mode. As a result we need to handle the errors now and add them to the diagnostics.
if (diagnostics === undefined) {
diagnostics = [];
}
diagnostics.push(
...getTemplateDiagnostics(
template.errors,
'' as TemplateId, // Template ID is required as part of the template type check, mainly for mapping the template to its component class. But here we are generating the diagnostic outside of the type check context, and so we skip the template ID.
template.sourceMapping,
),
);
}
}
const templateResource = template.declaration.isInline
? {path: null, expression: component.get('template')!}
: {
path: absoluteFrom(template.declaration.resolvedTemplateUrl),
expression: template.sourceMapping.node,
};
// Figure out the set of styles. The ordering here is important: external resources (styleUrls)
// precede inline styles, and styles defined in the template override styles defined in the
// component.
let styles: string[] = [];
const externalStyles: string[] = [];
const styleResources = extractInlineStyleResources(component);
const styleUrls: StyleUrlMeta[] = [
...extractComponentStyleUrls(this.evaluator, component),
..._extractTemplateStyleUrls(template),
];
for (const styleUrl of styleUrls) {
try {
const resourceUrl = this.resourceLoader.resolve(styleUrl.url, containingFile);
if (this.externalRuntimeStyles) {
// External runtime styles are not considered disk-based and may not actually exist on disk
externalStyles.push(resourceUrl);
continue;
}
if (
styleUrl.source === ResourceTypeForDiagnostics.StylesheetFromDecorator &&
ts.isStringLiteralLike(styleUrl.expression)
) {
// Only string literal values from the decorator are considered style resources
styleResources.add({
path: absoluteFrom(resourceUrl),
expression: styleUrl.expression,
});
}
const resourceStr = this.resourceLoader.load(resourceUrl);
styles.push(resourceStr);
if (this.depTracker !== null) {
this.depTracker.addResourceDependency(node.getSourceFile(), absoluteFrom(resourceUrl));
}
} catch {
if (this.depTracker !== null) {
// The analysis of this file cannot be re-used if one of the style URLs could
// not be resolved or loaded. Future builds should re-analyze and re-attempt
// resolution/loading.
this.depTracker.recordDependencyAnalysisFailure(node.getSourceFile());
}
if (diagnostics === undefined) {
diagnostics = [];
}
const resourceType =
styleUrl.source === ResourceTypeForDiagnostics.StylesheetFromDecorator
? ResourceTypeForDiagnostics.StylesheetFromDecorator
: ResourceTypeForDiagnostics.StylesheetFromTemplate;
diagnostics.push(
makeResourceNotFoundError(styleUrl.url, styleUrl.expression, resourceType).toDiagnostic(),
);
}
}
if (encapsulation === ViewEncapsulation.ShadowDom && metadata.selector !== null) {
const selectorError = checkCustomElementSelectorForErrors(metadata.selector);
if (selectorError !== null) {
if (diagnostics === undefined) {
diagnostics = [];
}
diagnostics.push(
makeDiagnostic(
ErrorCode.COMPONENT_INVALID_SHADOW_DOM_SELECTOR,
component.get('selector')!,
selectorError,
),
);
}
}
// If inline styles were preprocessed use those
let inlineStyles: string[] | null = null;
if (this.preanalyzeStylesCache.has(node)) {
inlineStyles = this.preanalyzeStylesCache.get(node)!;
this.preanalyzeStylesCache.delete(node);
if (inlineStyles?.length) {
if (this.externalRuntimeStyles) {
// When external runtime styles is enabled, a list of URLs is provided
externalStyles.push(...inlineStyles);
} else {
styles.push(...inlineStyles);
}
}
} else {
// Preprocessing is only supported asynchronously
// If no style cache entry is present asynchronous preanalyze was not executed.
// This protects against accidental differences in resource contents when preanalysis
// is not used with a provided transformResource hook on the ResourceHost.
if (this.resourceLoader.canPreprocess) {
throw new Error('Inline resource processing requires asynchronous preanalyze.');
}
if (component.has('styles')) {
const litStyles = parseDirectiveStyles(component, this.evaluator, this.compilationMode);
if (litStyles !== null) {
inlineStyles = [...litStyles];
styles.push(...litStyles);
}
}
if (template.styles.length > 0) {
styles.push(...template.styles);
}
}
// Collect all explicitly deferred symbols from the `@Component.deferredImports` field
// (if it exists) and populate the `DeferredSymbolTracker` state. These operations are safe
// for the local compilation mode, since they don't require accessing/resolving symbols
// outside of the current source file.
let explicitlyDeferredTypes: R3DeferPerComponentDependency[] | null = null;
if (metadata.isStandalone && rawDeferredImports !== null) {
const deferredTypes = this.collectExplicitlyDeferredSymbols(rawDeferredImports);
for (const [deferredType, importDetails] of deferredTypes) {
explicitlyDeferredTypes ??= [];
explicitlyDeferredTypes.push({
symbolName: importDetails.name,
importPath: importDetails.from,
isDefaultImport: isDefaultImport(importDetails.node),
});
this.deferredSymbolTracker.markAsDeferrableCandidate(
deferredType,
importDetails.node,
node,
true /* isExplicitlyDeferred */,
);
}
}
const output: AnalysisOutput<ComponentAnalysisData> = {
analysis: {
baseClass: readBaseClass(node, this.reflector, this.evaluator),
inputs,
inputFieldNamesFromMetadataArray: directiveResult.inputFieldNamesFromMetadataArray,
outputs,
hostDirectives,
rawHostDirectives,
meta: {
...metadata,
template,
encapsulation,
changeDetection,
interpolation: template.interpolationConfig ?? DEFAULT_INTERPOLATION_CONFIG,
styles,
externalStyles,
// These will be replaced during the compilation step, after all `NgModule`s have been
// analyzed and the full compilation scope for the component can be realized.
animations,
viewProviders: wrappedViewProviders,
i18nUseExternalIds: this.i18nUseExternalIds,
relativeContextFilePath,
rawImports: rawImports !== null ? new o.WrappedNodeExpr(rawImports) : undefined,
},
typeCheckMeta: extractDirectiveTypeCheckMeta(node, inputs, this.reflector),
classMetadata: this.includeClassMetadata
? extractClassMetadata(
node,
this.reflector,
this.isCore,
this.annotateForClosureCompiler,
(dec) => transformDecoratorResources(dec, component, styles, template),
)
: null,
classDebugInfo: extractClassDebugInfo(
node,
this.reflector,
this.compilerHost,
this.rootDirs,
/* forbidOrphanRenderering */ this.forbidOrphanRendering,
),
template,
providersRequiringFactory,
viewProvidersRequiringFactory,
inlineStyles,
styleUrls,
resources: {
styles: styleResources,
template: templateResource,
},
isPoisoned,
animationTriggerNames,
rawImports,
resolvedImports,
rawDeferredImports,
resolvedDeferredImports,
explicitlyDeferredTypes,
schemas,
decorator: (decorator?.node as ts.Decorator | null) ?? null,
},
diagnostics,
};
return output;
} | {
"end_byte": 32471,
"start_byte": 22729,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts_32475_40682 | symbol(node: ClassDeclaration, analysis: Readonly<ComponentAnalysisData>): ComponentSymbol {
const typeParameters = extractSemanticTypeParameters(node);
return new ComponentSymbol(
node,
analysis.meta.selector,
analysis.inputs,
analysis.outputs,
analysis.meta.exportAs,
analysis.typeCheckMeta,
typeParameters,
);
}
register(node: ClassDeclaration, analysis: ComponentAnalysisData): void {
// Register this component's information with the `MetadataRegistry`. This ensures that
// the information about the component is available during the compile() phase.
const ref = new Reference(node);
this.metaRegistry.registerDirectiveMetadata({
kind: MetaKind.Directive,
matchSource: MatchSource.Selector,
ref,
name: node.name.text,
selector: analysis.meta.selector,
exportAs: analysis.meta.exportAs,
inputs: analysis.inputs,
inputFieldNamesFromMetadataArray: analysis.inputFieldNamesFromMetadataArray,
outputs: analysis.outputs,
queries: analysis.meta.queries.map((query) => query.propertyName),
isComponent: true,
baseClass: analysis.baseClass,
hostDirectives: analysis.hostDirectives,
...analysis.typeCheckMeta,
isPoisoned: analysis.isPoisoned,
isStructural: false,
isStandalone: analysis.meta.isStandalone,
isSignal: analysis.meta.isSignal,
imports: analysis.resolvedImports,
rawImports: analysis.rawImports,
deferredImports: analysis.resolvedDeferredImports,
animationTriggerNames: analysis.animationTriggerNames,
schemas: analysis.schemas,
decorator: analysis.decorator,
assumedToExportProviders: false,
ngContentSelectors: analysis.template.ngContentSelectors,
preserveWhitespaces: analysis.template.preserveWhitespaces ?? false,
isExplicitlyDeferred: false,
});
this.resourceRegistry.registerResources(analysis.resources, node);
this.injectableRegistry.registerInjectable(node, {
ctorDeps: analysis.meta.deps,
});
}
index(
context: IndexingContext,
node: ClassDeclaration,
analysis: Readonly<ComponentAnalysisData>,
) {
if (analysis.isPoisoned && !this.usePoisonedData) {
return null;
}
const scope = this.scopeReader.getScopeForComponent(node);
const selector = analysis.meta.selector;
const matcher = new SelectorMatcher<DirectiveMeta[]>();
if (scope !== null) {
let {dependencies, isPoisoned} =
scope.kind === ComponentScopeKind.NgModule ? scope.compilation : scope;
if (
(isPoisoned || (scope.kind === ComponentScopeKind.NgModule && scope.exported.isPoisoned)) &&
!this.usePoisonedData
) {
// Don't bother indexing components which had erroneous scopes, unless specifically
// requested.
return null;
}
for (const dep of dependencies) {
if (dep.kind === MetaKind.Directive && dep.selector !== null) {
matcher.addSelectables(CssSelector.parse(dep.selector), [
...this.hostDirectivesResolver.resolve(dep),
dep,
]);
}
}
}
const binder = new R3TargetBinder(matcher);
const boundTemplate = binder.bind({template: analysis.template.diagNodes});
context.addComponent({
declaration: node,
selector,
boundTemplate,
templateMeta: {
isInline: analysis.template.declaration.isInline,
file: analysis.template.file,
},
});
return null;
}
typeCheck(
ctx: TypeCheckContext,
node: ClassDeclaration,
meta: Readonly<ComponentAnalysisData>,
): void {
if (this.typeCheckScopeRegistry === null || !ts.isClassDeclaration(node)) {
return;
}
if (meta.isPoisoned && !this.usePoisonedData) {
return;
}
const scope = this.typeCheckScopeRegistry.getTypeCheckScope(node);
if (scope.isPoisoned && !this.usePoisonedData) {
// Don't type-check components that had errors in their scopes, unless requested.
return;
}
const binder = new R3TargetBinder<TypeCheckableDirectiveMeta>(scope.matcher);
ctx.addTemplate(
new Reference(node),
binder,
meta.template.diagNodes,
scope.pipes,
scope.schemas,
meta.template.sourceMapping,
meta.template.file,
meta.template.errors,
meta.meta.isStandalone,
meta.meta.template.preserveWhitespaces ?? false,
);
}
extendedTemplateCheck(
component: ts.ClassDeclaration,
extendedTemplateChecker: ExtendedTemplateChecker,
): ts.Diagnostic[] {
return extendedTemplateChecker.getDiagnosticsForComponent(component);
}
templateSemanticsCheck(
component: ts.ClassDeclaration,
templateSemanticsChecker: TemplateSemanticsChecker,
): ts.Diagnostic[] {
return templateSemanticsChecker.getDiagnosticsForComponent(component);
}
resolve(
node: ClassDeclaration,
analysis: Readonly<ComponentAnalysisData>,
symbol: ComponentSymbol,
): ResolveResult<ComponentResolutionData> {
const metadata = analysis.meta as Readonly<R3ComponentMetadata<R3TemplateDependencyMetadata>>;
const diagnostics: ts.Diagnostic[] = [];
const context = getSourceFile(node);
// Check if there are some import declarations that contain symbols used within
// the `@Component.deferredImports` field, but those imports contain other symbols
// and thus the declaration can not be removed. This diagnostics is shared between local and
// global compilation modes.
const nonRemovableImports = this.deferredSymbolTracker.getNonRemovableDeferredImports(
context,
node,
);
if (nonRemovableImports.length > 0) {
for (const importDecl of nonRemovableImports) {
const diagnostic = makeDiagnostic(
ErrorCode.DEFERRED_DEPENDENCY_IMPORTED_EAGERLY,
importDecl,
`This import contains symbols that are used both inside and outside of the ` +
`\`@Component.deferredImports\` fields in the file. This renders all these ` +
`defer imports useless as this import remains and its module is eagerly loaded. ` +
`To fix this, make sure that all symbols from the import are *only* used within ` +
`\`@Component.deferredImports\` arrays and there are no other references to those ` +
`symbols present in this file.`,
);
diagnostics.push(diagnostic);
}
return {diagnostics};
}
let data: ComponentResolutionData;
if (this.compilationMode === CompilationMode.LOCAL) {
// Initial value in local compilation mode.
data = {
declarations: EMPTY_ARRAY,
declarationListEmitMode:
!analysis.meta.isStandalone || analysis.rawImports !== null
? DeclarationListEmitMode.RuntimeResolved
: DeclarationListEmitMode.Direct,
deferPerBlockDependencies: this.locateDeferBlocksWithoutScope(analysis.template),
deferBlockDepsEmitMode: DeferBlockDepsEmitMode.PerComponent,
deferrableDeclToImportDecl: new Map(),
deferPerComponentDependencies: analysis.explicitlyDeferredTypes ?? [],
};
if (this.localCompilationExtraImportsTracker === null) {
// In local compilation mode the resolve phase is only needed for generating extra imports.
// Otherwise we can skip it.
return {data};
}
} else {
// Initial value in global compilation mode.
data = {
declarations: EMPTY_ARRAY,
declarationListEmitMode: DeclarationListEmitMode.Direct,
deferPerBlockDependencies: new Map(),
deferBlockDepsEmitMode: DeferBlockDepsEmitMode.PerBlock,
deferrableDeclToImportDecl: new Map(),
deferPerComponentDependencies: [],
};
}
if (this.semanticDepGraphUpdater !== null && analysis.baseClass instanceof Reference) {
symbol.baseClass = this.semanticDepGraphUpdater.getSymbol(analysis.baseClass.node);
}
if (analysis.isPoisoned && !this.usePoisonedData) {
return {};
}
const scope = this.scopeReader.getScopeForComponent(node);
if (scope !== null) | {
"end_byte": 40682,
"start_byte": 32475,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts_40683_50330 | {
// Replace the empty components and directives from the analyze() step with a fully expanded
// scope. This is possible now because during resolve() the whole compilation unit has been
// fully analyzed.
//
// First it needs to be determined if actually importing the directives/pipes used in the
// template would create a cycle. Currently ngtsc refuses to generate cycles, so an option
// known as "remote scoping" is used if a cycle would be created. In remote scoping, the
// module file sets the directives/pipes on the ɵcmp of the component, without
// requiring new imports (but also in a way that breaks tree shaking).
//
// Determining this is challenging, because the TemplateDefinitionBuilder is responsible for
// matching directives and pipes in the template; however, that doesn't run until the actual
// compile() step. It's not possible to run template compilation sooner as it requires the
// ConstantPool for the overall file being compiled (which isn't available until the
// transform step).
//
// Instead, directives/pipes are matched independently here, using the R3TargetBinder. This
// is an alternative implementation of template matching which is used for template
// type-checking and will eventually replace matching in the TemplateDefinitionBuilder.
const isModuleScope = scope.kind === ComponentScopeKind.NgModule;
// Dependencies coming from the regular `imports` field.
const dependencies = isModuleScope ? scope.compilation.dependencies : scope.dependencies;
// Dependencies from the `@Component.deferredImports` field.
const explicitlyDeferredDependencies = getExplicitlyDeferredDeps(scope);
// Mark the component is an NgModule-based component with its NgModule in a different file
// then mark this file for extra import generation
if (isModuleScope && context.fileName !== getSourceFile(scope.ngModule).fileName) {
this.localCompilationExtraImportsTracker?.markFileForExtraImportGeneration(context);
}
// Make sure that `@Component.imports` and `@Component.deferredImports` do not have
// the same dependencies.
if (
metadata.isStandalone &&
analysis.rawDeferredImports !== null &&
explicitlyDeferredDependencies.length > 0
) {
const diagnostic = validateNoImportOverlap(
dependencies,
explicitlyDeferredDependencies,
analysis.rawDeferredImports,
);
if (diagnostic !== null) {
diagnostics.push(diagnostic);
}
}
// Set up the R3TargetBinder, as well as a 'directives' array and a 'pipes' map that are
// later fed to the TemplateDefinitionBuilder.
const binder = createTargetBinder(dependencies);
const pipes = extractPipes(dependencies);
let allDependencies = dependencies;
let deferBlockBinder = binder;
// If there are any explicitly deferred dependencies (via `@Component.deferredImports`),
// re-compute the list of dependencies and create a new binder for defer blocks.
if (explicitlyDeferredDependencies.length > 0) {
allDependencies = [...explicitlyDeferredDependencies, ...dependencies];
deferBlockBinder = createTargetBinder(allDependencies);
}
// Next, the component template AST is bound using the R3TargetBinder. This produces a
// BoundTarget, which is similar to a ts.TypeChecker.
const bound = binder.bind({template: metadata.template.nodes});
// Find all defer blocks used in the template and for each block
// bind its own scope.
const deferBlocks = new Map<TmplAstDeferredBlock, BoundTarget<DirectiveMeta>>();
for (const deferBlock of bound.getDeferBlocks()) {
deferBlocks.set(deferBlock, deferBlockBinder.bind({template: deferBlock.children}));
}
// Register all Directives and Pipes used at the top level (outside
// of any defer blocks), which would be eagerly referenced.
const eagerlyUsed = new Set<ClassDeclaration>();
for (const dir of bound.getEagerlyUsedDirectives()) {
eagerlyUsed.add(dir.ref.node);
}
for (const name of bound.getEagerlyUsedPipes()) {
if (!pipes.has(name)) {
continue;
}
eagerlyUsed.add(pipes.get(name)!.ref.node);
}
// Set of Directives and Pipes used across the entire template,
// including all defer blocks.
const wholeTemplateUsed = new Set<ClassDeclaration>(eagerlyUsed);
for (const bound of deferBlocks.values()) {
for (const dir of bound.getEagerlyUsedDirectives()) {
wholeTemplateUsed.add(dir.ref.node);
}
for (const name of bound.getEagerlyUsedPipes()) {
if (!pipes.has(name)) {
continue;
}
wholeTemplateUsed.add(pipes.get(name)!.ref.node);
}
}
const declarations = new Map<ClassDeclaration, UsedPipe | UsedDirective | UsedNgModule>();
// Transform the dependencies list, filtering out unused dependencies.
for (const dep of allDependencies) {
// Only emit references to each dependency once.
if (declarations.has(dep.ref.node)) {
continue;
}
switch (dep.kind) {
case MetaKind.Directive:
if (!wholeTemplateUsed.has(dep.ref.node) || dep.matchSource !== MatchSource.Selector) {
continue;
}
const dirType = this.refEmitter.emit(dep.ref, context);
assertSuccessfulReferenceEmit(
dirType,
node.name,
dep.isComponent ? 'component' : 'directive',
);
declarations.set(dep.ref.node, {
kind: R3TemplateDependencyKind.Directive,
ref: dep.ref,
type: dirType.expression,
importedFile: dirType.importedFile,
selector: dep.selector!,
inputs: dep.inputs.propertyNames,
outputs: dep.outputs.propertyNames,
exportAs: dep.exportAs,
isComponent: dep.isComponent,
});
break;
case MetaKind.Pipe:
if (!wholeTemplateUsed.has(dep.ref.node)) {
continue;
}
const pipeType = this.refEmitter.emit(dep.ref, context);
assertSuccessfulReferenceEmit(pipeType, node.name, 'pipe');
declarations.set(dep.ref.node, {
kind: R3TemplateDependencyKind.Pipe,
type: pipeType.expression,
name: dep.name,
ref: dep.ref,
importedFile: pipeType.importedFile,
});
break;
case MetaKind.NgModule:
const ngModuleType = this.refEmitter.emit(dep.ref, context);
assertSuccessfulReferenceEmit(ngModuleType, node.name, 'NgModule');
declarations.set(dep.ref.node, {
kind: R3TemplateDependencyKind.NgModule,
type: ngModuleType.expression,
importedFile: ngModuleType.importedFile,
});
break;
}
}
const getSemanticReference = (decl: UsedDirective | UsedPipe) =>
this.semanticDepGraphUpdater!.getSemanticReference(decl.ref.node, decl.type);
if (this.semanticDepGraphUpdater !== null) {
symbol.usedDirectives = Array.from(declarations.values())
.filter(isUsedDirective)
.map(getSemanticReference);
symbol.usedPipes = Array.from(declarations.values())
.filter(isUsedPipe)
.map(getSemanticReference);
}
const eagerDeclarations = Array.from(declarations.values()).filter(
(decl) => decl.kind === R3TemplateDependencyKind.NgModule || eagerlyUsed.has(decl.ref.node),
);
// Process information related to defer blocks
if (this.compilationMode !== CompilationMode.LOCAL) {
this.resolveDeferBlocks(node, deferBlocks, declarations, data, analysis, eagerlyUsed);
}
const cyclesFromDirectives = new Map<UsedDirective, Cycle>();
const cyclesFromPipes = new Map<UsedPipe, Cycle>();
// Scan through the directives/pipes actually used in the template and check whether any
// import which needs to be generated would create a cycle. This check is skipped for
// standalone components as the dependencies of a standalone component have already been
// imported directly by the user, so Angular won't introduce any imports that aren't already
// in the user's program.
if (!metadata.isStandalone) {
for (const usedDep of eagerDeclarations) {
const cycle = this._checkForCyclicImport(usedDep.importedFile, usedDep.type, context);
if (cycle !== null) {
switch (usedDep.kind) {
case R3TemplateDependencyKind.Directive:
cyclesFromDirectives.set(usedDep, cycle);
break;
case R3TemplateDependencyKind.Pipe:
cyclesFromPipes.set(usedDep, cycle);
break;
}
}
}
}
// Check whether any usages of standalone components in imports requires the dependencies
// array to be wrapped in a closure. This check is technically a heuristic as there's no
// direct way to check whether a `Reference` came from a `forwardRef`. Instead, we check if
// the reference is `synthetic`, implying it came from _any_ foreign function resolver,
// including the `forwardRef` resolver.
| {
"end_byte": 50330,
"start_byte": 40683,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts_50337_60023 | onst standaloneImportMayBeForwardDeclared =
analysis.resolvedImports !== null && analysis.resolvedImports.some((ref) => ref.synthetic);
const cycleDetected = cyclesFromDirectives.size !== 0 || cyclesFromPipes.size !== 0;
if (!cycleDetected) {
// No cycle was detected. Record the imports that need to be created in the cycle detector
// so that future cyclic import checks consider their production.
for (const {type, importedFile} of eagerDeclarations) {
this.maybeRecordSyntheticImport(importedFile, type, context);
}
// Check whether the dependencies arrays in ɵcmp need to be wrapped in a closure.
// This is required if any dependency reference is to a declaration in the same file
// but declared after this component.
const declarationIsForwardDeclared = eagerDeclarations.some((decl) =>
isExpressionForwardReference(decl.type, node.name, context),
);
if (
this.compilationMode !== CompilationMode.LOCAL &&
(declarationIsForwardDeclared || standaloneImportMayBeForwardDeclared)
) {
data.declarationListEmitMode = DeclarationListEmitMode.Closure;
}
data.declarations = eagerDeclarations;
// Register extra local imports.
if (
this.compilationMode === CompilationMode.LOCAL &&
this.localCompilationExtraImportsTracker !== null
) {
// In global compilation mode `eagerDeclarations` contains "all" the component
// dependencies, whose import statements will be added to the file. In local compilation
// mode `eagerDeclarations` only includes the "local" dependencies, meaning those that are
// declared inside this compilation unit.Here the import info of these local dependencies
// are added to the tracker so that we can generate extra imports representing these local
// dependencies. For non-local dependencies we use another technique of adding some
// best-guess extra imports globally to all files using
// `localCompilationExtraImportsTracker.addGlobalImportFromIdentifier`.
for (const {type} of eagerDeclarations) {
if (type instanceof ExternalExpr && type.value.moduleName) {
this.localCompilationExtraImportsTracker.addImportForFile(
context,
type.value.moduleName,
);
}
}
}
} else {
if (this.cycleHandlingStrategy === CycleHandlingStrategy.UseRemoteScoping) {
// Declaring the directiveDefs/pipeDefs arrays directly would require imports that would
// create a cycle. Instead, mark this component as requiring remote scoping, so that the
// NgModule file will take care of setting the directives for the component.
this.scopeRegistry.setComponentRemoteScope(
node,
eagerDeclarations.filter(isUsedDirective).map((dir) => dir.ref),
eagerDeclarations.filter(isUsedPipe).map((pipe) => pipe.ref),
);
symbol.isRemotelyScoped = true;
// If a semantic graph is being tracked, record the fact that this component is remotely
// scoped with the declaring NgModule symbol as the NgModule's emit becomes dependent on
// the directive/pipe usages of this component.
if (
this.semanticDepGraphUpdater !== null &&
scope.kind === ComponentScopeKind.NgModule &&
scope.ngModule !== null
) {
const moduleSymbol = this.semanticDepGraphUpdater.getSymbol(scope.ngModule);
if (!(moduleSymbol instanceof NgModuleSymbol)) {
throw new Error(
`AssertionError: Expected ${scope.ngModule.name} to be an NgModuleSymbol.`,
);
}
moduleSymbol.addRemotelyScopedComponent(
symbol,
symbol.usedDirectives,
symbol.usedPipes,
);
}
} else {
// We are not able to handle this cycle so throw an error.
const relatedMessages: ts.DiagnosticRelatedInformation[] = [];
for (const [dir, cycle] of cyclesFromDirectives) {
relatedMessages.push(
makeCyclicImportInfo(dir.ref, dir.isComponent ? 'component' : 'directive', cycle),
);
}
for (const [pipe, cycle] of cyclesFromPipes) {
relatedMessages.push(makeCyclicImportInfo(pipe.ref, 'pipe', cycle));
}
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,
);
}
}
} else {
// If there is no scope, we can still use the binder to retrieve *some* information about the
// deferred blocks.
data.deferPerBlockDependencies = this.locateDeferBlocksWithoutScope(metadata.template);
}
// Run diagnostics only in global mode.
if (this.compilationMode !== CompilationMode.LOCAL) {
// Validate `@Component.imports` and `@Component.deferredImports` fields.
if (analysis.resolvedImports !== null && analysis.rawImports !== null) {
const importDiagnostics = validateStandaloneImports(
analysis.resolvedImports,
analysis.rawImports,
this.metaReader,
this.scopeReader,
false /* isDeferredImport */,
);
diagnostics.push(...importDiagnostics);
}
if (analysis.resolvedDeferredImports !== null && analysis.rawDeferredImports !== null) {
const importDiagnostics = validateStandaloneImports(
analysis.resolvedDeferredImports,
analysis.rawDeferredImports,
this.metaReader,
this.scopeReader,
true /* isDeferredImport */,
);
diagnostics.push(...importDiagnostics);
}
if (
analysis.providersRequiringFactory !== null &&
analysis.meta.providers instanceof o.WrappedNodeExpr
) {
const providerDiagnostics = getProviderDiagnostics(
analysis.providersRequiringFactory,
analysis.meta.providers!.node,
this.injectableRegistry,
);
diagnostics.push(...providerDiagnostics);
}
if (
analysis.viewProvidersRequiringFactory !== null &&
analysis.meta.viewProviders instanceof o.WrappedNodeExpr
) {
const viewProviderDiagnostics = getProviderDiagnostics(
analysis.viewProvidersRequiringFactory,
analysis.meta.viewProviders!.node,
this.injectableRegistry,
);
diagnostics.push(...viewProviderDiagnostics);
}
const directiveDiagnostics = getDirectiveDiagnostics(
node,
this.injectableRegistry,
this.evaluator,
this.reflector,
this.scopeRegistry,
this.strictCtorDeps,
'Component',
);
if (directiveDiagnostics !== null) {
diagnostics.push(...directiveDiagnostics);
}
const hostDirectivesDiagnostics =
analysis.hostDirectives && analysis.rawHostDirectives
? validateHostDirectives(
analysis.rawHostDirectives,
analysis.hostDirectives,
this.metaReader,
)
: null;
if (hostDirectivesDiagnostics !== null) {
diagnostics.push(...hostDirectivesDiagnostics);
}
}
if (diagnostics.length > 0) {
return {diagnostics};
}
return {data};
}
xi18n(
ctx: Xi18nContext,
node: ClassDeclaration,
analysis: Readonly<ComponentAnalysisData>,
): void {
ctx.updateFromTemplate(
analysis.template.content,
analysis.template.declaration.resolvedTemplateUrl,
analysis.template.interpolationConfig ?? DEFAULT_INTERPOLATION_CONFIG,
);
}
updateResources(node: ClassDeclaration, analysis: ComponentAnalysisData): void {
const containingFile = node.getSourceFile().fileName;
// If the template is external, re-parse it.
const templateDecl = analysis.template.declaration;
if (!templateDecl.isInline) {
analysis.template = extractTemplate(
node,
templateDecl,
this.evaluator,
this.depTracker,
this.resourceLoader,
this.extractTemplateOptions,
this.compilationMode,
);
}
// Update any external stylesheets and rebuild the combined 'styles' list.
// TODO(alxhub): write tests for styles when the primary compiler uses the updateResources
// path
let styles: string[] = [];
if (analysis.styleUrls !== null) {
for (const styleUrl of analysis.styleUrls) {
try {
const resolvedStyleUrl = this.resourceLoader.resolve(styleUrl.url, containingFile);
const styleText = this.resourceLoader.load(resolvedStyleUrl);
styles.push(styleText);
} catch (e) {
// Resource resolve failures should already be in the diagnostics list from the analyze
// stage. We do not need to do anything with them when updating resources.
}
}
}
if (analysis.inlineStyles !== null) {
for (const styleText of analysis.inlineStyles) {
styles.push(styleText);
}
}
for (const styleText of analysis.template.styles) {
styles.push(styleText);
}
analysis.meta.styles = styles.filter((s) => s.trim().length > 0);
}
| {
"end_byte": 60023,
"start_byte": 50337,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts_60027_68657 | mpileFull(
node: ClassDeclaration,
analysis: Readonly<ComponentAnalysisData>,
resolution: Readonly<ComponentResolutionData>,
pool: ConstantPool,
): CompileResult[] {
if (analysis.template.errors !== null && analysis.template.errors.length > 0) {
return [];
}
const perComponentDeferredDeps = this.canDeferDeps
? this.resolveAllDeferredDependencies(resolution)
: null;
const meta: R3ComponentMetadata<R3TemplateDependency> = {
...analysis.meta,
...resolution,
defer: this.compileDeferBlocks(resolution),
};
const fac = compileNgFactoryDefField(toFactoryMetadata(meta, FactoryTarget.Component));
if (perComponentDeferredDeps !== null) {
removeDeferrableTypesFromComponentDecorator(analysis, perComponentDeferredDeps);
}
const def = compileComponentFromMetadata(meta, pool, makeBindingParser());
const inputTransformFields = compileInputTransformFields(analysis.inputs);
const classMetadata =
analysis.classMetadata !== null
? compileComponentClassMetadata(analysis.classMetadata, perComponentDeferredDeps).toStmt()
: null;
const debugInfo =
analysis.classDebugInfo !== null
? compileClassDebugInfo(analysis.classDebugInfo).toStmt()
: null;
const hmrMeta = this.enableHmr
? extractHmrMetatadata(
node,
this.reflector,
this.compilerHost,
this.rootDirs,
def,
fac,
classMetadata,
debugInfo,
)
: null;
const hmrInitializer = hmrMeta ? compileHmrInitializer(hmrMeta).toStmt() : null;
const deferrableImports = this.canDeferDeps
? this.deferredSymbolTracker.getDeferrableImportDecls()
: null;
return compileResults(
fac,
def,
classMetadata,
'ɵcmp',
inputTransformFields,
deferrableImports,
debugInfo,
hmrInitializer,
);
}
compilePartial(
node: ClassDeclaration,
analysis: Readonly<ComponentAnalysisData>,
resolution: Readonly<ComponentResolutionData>,
): CompileResult[] {
if (analysis.template.errors !== null && analysis.template.errors.length > 0) {
return [];
}
const templateInfo: DeclareComponentTemplateInfo = {
content: analysis.template.content,
sourceUrl: analysis.template.declaration.resolvedTemplateUrl,
isInline: analysis.template.declaration.isInline,
inlineTemplateLiteralExpression:
analysis.template.sourceMapping.type === 'direct'
? new o.WrappedNodeExpr(analysis.template.sourceMapping.node)
: null,
};
const perComponentDeferredDeps = this.canDeferDeps
? this.resolveAllDeferredDependencies(resolution)
: null;
const meta: R3ComponentMetadata<R3TemplateDependencyMetadata> = {
...analysis.meta,
...resolution,
defer: this.compileDeferBlocks(resolution),
};
const fac = compileDeclareFactory(toFactoryMetadata(meta, FactoryTarget.Component));
const inputTransformFields = compileInputTransformFields(analysis.inputs);
const def = compileDeclareComponentFromMetadata(meta, analysis.template, templateInfo);
const classMetadata =
analysis.classMetadata !== null
? compileComponentDeclareClassMetadata(
analysis.classMetadata,
perComponentDeferredDeps,
).toStmt()
: null;
const hmrMeta = this.enableHmr
? extractHmrMetatadata(
node,
this.reflector,
this.compilerHost,
this.rootDirs,
def,
fac,
classMetadata,
null,
)
: null;
const hmrInitializer = hmrMeta ? compileHmrInitializer(hmrMeta).toStmt() : null;
const deferrableImports = this.canDeferDeps
? this.deferredSymbolTracker.getDeferrableImportDecls()
: null;
return compileResults(
fac,
def,
classMetadata,
'ɵcmp',
inputTransformFields,
deferrableImports,
null,
hmrInitializer,
);
}
compileLocal(
node: ClassDeclaration,
analysis: Readonly<ComponentAnalysisData>,
resolution: Readonly<Partial<ComponentResolutionData>>,
pool: ConstantPool,
): CompileResult[] {
// In the local compilation mode we can only rely on the information available
// within the `@Component.deferredImports` array, because in this mode compiler
// doesn't have information on which dependencies belong to which defer blocks.
const deferrableTypes = this.canDeferDeps ? analysis.explicitlyDeferredTypes : null;
const meta = {
...analysis.meta,
...resolution,
defer: this.compileDeferBlocks(resolution),
} as R3ComponentMetadata<R3TemplateDependency>;
if (deferrableTypes !== null) {
removeDeferrableTypesFromComponentDecorator(analysis, deferrableTypes);
}
const fac = compileNgFactoryDefField(toFactoryMetadata(meta, FactoryTarget.Component));
const def = compileComponentFromMetadata(meta, pool, makeBindingParser());
const inputTransformFields = compileInputTransformFields(analysis.inputs);
const classMetadata =
analysis.classMetadata !== null
? compileComponentClassMetadata(analysis.classMetadata, deferrableTypes).toStmt()
: null;
const debugInfo =
analysis.classDebugInfo !== null
? compileClassDebugInfo(analysis.classDebugInfo).toStmt()
: null;
const hmrMeta = this.enableHmr
? extractHmrMetatadata(
node,
this.reflector,
this.compilerHost,
this.rootDirs,
def,
fac,
classMetadata,
debugInfo,
)
: null;
const hmrInitializer = hmrMeta ? compileHmrInitializer(hmrMeta).toStmt() : null;
const deferrableImports = this.canDeferDeps
? this.deferredSymbolTracker.getDeferrableImportDecls()
: null;
return compileResults(
fac,
def,
classMetadata,
'ɵcmp',
inputTransformFields,
deferrableImports,
debugInfo,
hmrInitializer,
);
}
compileHmrUpdateDeclaration(
node: ClassDeclaration,
analysis: Readonly<ComponentAnalysisData>,
resolution: Readonly<ComponentResolutionData>,
): ts.FunctionDeclaration | null {
if (analysis.template.errors !== null && analysis.template.errors.length > 0) {
return null;
}
// Create a brand-new constant pool since there shouldn't be any constant sharing.
const pool = new ConstantPool();
const meta: R3ComponentMetadata<R3TemplateDependency> = {
...analysis.meta,
...resolution,
defer: this.compileDeferBlocks(resolution),
};
const fac = compileNgFactoryDefField(toFactoryMetadata(meta, FactoryTarget.Component));
const def = compileComponentFromMetadata(meta, pool, makeBindingParser());
const classMetadata =
analysis.classMetadata !== null
? compileComponentClassMetadata(analysis.classMetadata, null).toStmt()
: null;
const debugInfo =
analysis.classDebugInfo !== null
? compileClassDebugInfo(analysis.classDebugInfo).toStmt()
: null;
const hmrMeta = this.enableHmr
? extractHmrMetatadata(
node,
this.reflector,
this.compilerHost,
this.rootDirs,
def,
fac,
classMetadata,
debugInfo,
)
: null;
const res = compileResults(fac, def, classMetadata, 'ɵcmp', null, null, debugInfo, null);
return hmrMeta === null || res.length === 0
? null
: getHmrUpdateDeclaration(res, pool.statements, hmrMeta, node.getSourceFile());
}
/**
* Locates defer blocks in case scope information is not available.
* For example, this happens in the local compilation mode.
*/
private locateDeferBlocksWithoutScope(
template: ComponentTemplate,
): Map<TmplAstDeferredBlock, DeferredComponentDependency[]> {
const deferBlocks = new Map<TmplAstDeferredBlock, DeferredComponentDependency[]>();
const directivelessBinder = new R3TargetBinder<DirectiveMeta>(new SelectorMatcher());
const bound = directivelessBinder.bind({template: template.nodes});
const deferredBlocks = bound.getDeferBlocks();
for (const block of deferredBlocks) {
// We can't determine the dependencies without a scope so we leave them empty.
deferBlocks.set(block, []);
}
return deferBlocks;
}
/**
* Computes a list of deferrable symbols based on dependencies from
* the `@Component.imports` field and their usage in `@defer` blocks.
*/
pri | {
"end_byte": 68657,
"start_byte": 60027,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts_68660_77026 | e resolveAllDeferredDependencies(
resolution: Readonly<ComponentResolutionData>,
): R3DeferPerComponentDependency[] {
const deferrableTypes: R3DeferPerComponentDependency[] = [];
// Go over all dependencies of all defer blocks and update the value of
// the `isDeferrable` flag and the `importPath` to reflect the current
// state after visiting all components during the `resolve` phase.
for (const [_, deps] of resolution.deferPerBlockDependencies) {
for (const deferBlockDep of deps) {
const importDecl =
resolution.deferrableDeclToImportDecl.get(deferBlockDep.declaration.node) ?? null;
if (importDecl !== null && this.deferredSymbolTracker.canDefer(importDecl)) {
deferBlockDep.isDeferrable = true;
deferBlockDep.importPath = (importDecl.moduleSpecifier as ts.StringLiteral).text;
deferBlockDep.isDefaultImport = isDefaultImport(importDecl);
deferrableTypes.push(deferBlockDep as R3DeferPerComponentDependency);
}
}
}
return deferrableTypes;
}
/**
* Collects deferrable symbols from the `@Component.deferredImports` field.
*/
private collectExplicitlyDeferredSymbols(
rawDeferredImports: ts.Expression,
): Map<ts.Identifier, Import> {
const deferredTypes = new Map<ts.Identifier, Import>();
if (!ts.isArrayLiteralExpression(rawDeferredImports)) {
return deferredTypes;
}
for (const element of rawDeferredImports.elements) {
const node = tryUnwrapForwardRef(element, this.reflector) || element;
if (!ts.isIdentifier(node)) {
// Can't defer-load non-literal references.
continue;
}
const imp = this.reflector.getImportOfIdentifier(node);
if (imp !== null) {
deferredTypes.set(node, imp);
}
}
return deferredTypes;
}
/**
* Check whether adding an import from `origin` to the source-file corresponding to `expr` would
* create a cyclic import.
*
* @returns a `Cycle` object if a cycle would be created, otherwise `null`.
*/
private _checkForCyclicImport(
importedFile: ImportedFile,
expr: o.Expression,
origin: ts.SourceFile,
): Cycle | null {
const imported = resolveImportedFile(this.moduleResolver, importedFile, expr, origin);
if (imported === null) {
return null;
}
// Check whether the import is legal.
return this.cycleAnalyzer.wouldCreateCycle(origin, imported);
}
private maybeRecordSyntheticImport(
importedFile: ImportedFile,
expr: o.Expression,
origin: ts.SourceFile,
): void {
const imported = resolveImportedFile(this.moduleResolver, importedFile, expr, origin);
if (imported === null) {
return;
}
this.cycleAnalyzer.recordSyntheticImport(origin, imported);
}
/**
* Resolves information about defer blocks dependencies to make it
* available for the final `compile` step.
*/
private resolveDeferBlocks(
componentClassDecl: ClassDeclaration,
deferBlocks: Map<TmplAstDeferredBlock, BoundTarget<DirectiveMeta>>,
deferrableDecls: Map<ClassDeclaration, AnyUsedType>,
resolutionData: ComponentResolutionData,
analysisData: Readonly<ComponentAnalysisData>,
eagerlyUsedDecls: Set<ClassDeclaration>,
) {
// Collect all deferred decls from all defer blocks from the entire template
// to intersect with the information from the `imports` field of a particular
// Component.
const allDeferredDecls = new Set<ClassDeclaration>();
for (const [deferBlock, bound] of deferBlocks) {
const usedDirectives = new Set(bound.getEagerlyUsedDirectives().map((d) => d.ref.node));
const usedPipes = new Set(bound.getEagerlyUsedPipes());
let deps: DeferredComponentDependency[];
if (resolutionData.deferPerBlockDependencies.has(deferBlock)) {
deps = resolutionData.deferPerBlockDependencies.get(deferBlock)!;
} else {
deps = [];
resolutionData.deferPerBlockDependencies.set(deferBlock, deps);
}
for (const decl of Array.from(deferrableDecls.values())) {
if (decl.kind === R3TemplateDependencyKind.NgModule) {
continue;
}
if (
decl.kind === R3TemplateDependencyKind.Directive &&
!usedDirectives.has(decl.ref.node)
) {
continue;
}
if (decl.kind === R3TemplateDependencyKind.Pipe && !usedPipes.has(decl.name)) {
continue;
}
// Collect initial information about this dependency.
// `isDeferrable`, `importPath` and `isDefaultImport` will be
// added later during the `compile` step.
deps.push({
typeReference: decl.type,
symbolName: decl.ref.node.name.text,
isDeferrable: false,
importPath: null,
isDefaultImport: false,
declaration: decl.ref,
});
allDeferredDecls.add(decl.ref.node);
}
}
// For standalone components with the `imports` and `deferredImports` fields -
// inspect the list of referenced symbols and mark the ones used in defer blocks
// as potential candidates for defer loading.
if (analysisData.meta.isStandalone) {
if (analysisData.rawImports !== null) {
this.registerDeferrableCandidates(
componentClassDecl,
analysisData.rawImports,
false /* isDeferredImport */,
allDeferredDecls,
eagerlyUsedDecls,
resolutionData,
);
}
if (analysisData.rawDeferredImports !== null) {
this.registerDeferrableCandidates(
componentClassDecl,
analysisData.rawDeferredImports,
true /* isDeferredImport */,
allDeferredDecls,
eagerlyUsedDecls,
resolutionData,
);
}
}
}
/**
* Inspects provided imports expression (either `@Component.imports` or
* `@Component.deferredImports`) and registers imported types as deferrable
* candidates.
*/
private registerDeferrableCandidates(
componentClassDecl: ClassDeclaration,
importsExpr: ts.Expression,
isDeferredImport: boolean,
allDeferredDecls: Set<ClassDeclaration>,
eagerlyUsedDecls: Set<ClassDeclaration>,
resolutionData: ComponentResolutionData,
) {
if (!ts.isArrayLiteralExpression(importsExpr)) {
return;
}
for (const element of importsExpr.elements) {
const node = tryUnwrapForwardRef(element, this.reflector) || element;
if (!ts.isIdentifier(node)) {
// Can't defer-load non-literal references.
continue;
}
const imp = this.reflector.getImportOfIdentifier(node);
if (imp === null) {
// Can't defer-load symbols which aren't imported.
continue;
}
const decl = this.reflector.getDeclarationOfIdentifier(node);
if (decl === null) {
// Can't defer-load symbols which don't exist.
continue;
}
if (!isNamedClassDeclaration(decl.node)) {
// Can't defer-load symbols which aren't classes.
continue;
}
// Are we even trying to defer-load this symbol?
if (!allDeferredDecls.has(decl.node)) {
continue;
}
if (eagerlyUsedDecls.has(decl.node)) {
// Can't defer-load symbols that are eagerly referenced as a dependency
// in a template outside of a defer block.
continue;
}
// Is it a standalone directive/component?
const dirMeta = this.metaReader.getDirectiveMetadata(new Reference(decl.node));
if (dirMeta !== null && !dirMeta.isStandalone) {
continue;
}
// Is it a standalone pipe?
const pipeMeta = this.metaReader.getPipeMetadata(new Reference(decl.node));
if (pipeMeta !== null && !pipeMeta.isStandalone) {
continue;
}
if (dirMeta === null && pipeMeta === null) {
// This is not a directive or a pipe.
continue;
}
// Keep track of how this class made it into the current source file
// (which ts.ImportDeclaration was used for this symbol).
resolutionData.deferrableDeclToImportDecl.set(decl.node, imp.node);
this.deferredSymbolTracker.markAsDeferrableCandidate(
node,
imp.node,
componentClassDecl,
isDeferredImport,
);
}
}
pr | {
"end_byte": 77026,
"start_byte": 68660,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts_77030_83032 | e compileDeferBlocks(
resolution: Readonly<Partial<ComponentResolutionData>>,
): R3ComponentDeferMetadata {
const {
deferBlockDepsEmitMode: mode,
deferPerBlockDependencies: perBlockDeps,
deferPerComponentDependencies: perComponentDeps,
} = resolution;
if (mode === DeferBlockDepsEmitMode.PerBlock) {
if (!perBlockDeps) {
throw new Error(
'Internal error: deferPerBlockDependencies must be present when compiling in PerBlock mode',
);
}
const blocks = new Map<TmplAstDeferredBlock, o.Expression | null>();
for (const [block, dependencies] of perBlockDeps) {
blocks.set(
block,
dependencies.length === 0 ? null : compileDeferResolverFunction({mode, dependencies}),
);
}
return {mode, blocks};
}
if (mode === DeferBlockDepsEmitMode.PerComponent) {
if (!perComponentDeps) {
throw new Error(
'Internal error: deferPerComponentDependencies must be present in PerComponent mode',
);
}
return {
mode,
dependenciesFn:
perComponentDeps.length === 0
? null
: compileDeferResolverFunction({mode, dependencies: perComponentDeps}),
};
}
throw new Error(`Invalid deferBlockDepsEmitMode. Cannot compile deferred block metadata.`);
}
}
/**
* Creates an instance of a target binder based on provided dependencies.
*/
function createTargetBinder(dependencies: Array<PipeMeta | DirectiveMeta | NgModuleMeta>) {
const matcher = new SelectorMatcher<DirectiveMeta[]>();
for (const dep of dependencies) {
if (dep.kind === MetaKind.Directive && dep.selector !== null) {
matcher.addSelectables(CssSelector.parse(dep.selector), [dep]);
}
}
return new R3TargetBinder(matcher);
}
/**
* Returns the list of dependencies from `@Component.deferredImports` if provided.
*/
function getExplicitlyDeferredDeps(scope: LocalModuleScope | StandaloneScope) {
return scope.kind === ComponentScopeKind.NgModule
? []
: (scope as StandaloneScope).deferredDependencies;
}
function extractPipes(
dependencies: Array<PipeMeta | DirectiveMeta | NgModuleMeta>,
): Map<string, PipeMeta> {
const pipes = new Map<string, PipeMeta>();
for (const dep of dependencies) {
if (dep.kind === MetaKind.Pipe) {
pipes.set(dep.name, dep);
}
}
return pipes;
}
/**
* Drop references to existing imports for deferrable symbols that should be present
* in the `setClassMetadataAsync` call. Otherwise, an import declaration gets retained.
*/
function removeDeferrableTypesFromComponentDecorator(
analysis: Readonly<ComponentAnalysisData>,
deferrableTypes: R3DeferPerComponentDependency[],
) {
if (analysis.classMetadata) {
const deferrableSymbols = new Set(deferrableTypes.map((t) => t.symbolName));
const rewrittenDecoratorsNode = removeIdentifierReferences(
(analysis.classMetadata.decorators as o.WrappedNodeExpr<ts.Node>).node,
deferrableSymbols,
);
analysis.classMetadata.decorators = new o.WrappedNodeExpr(rewrittenDecoratorsNode);
}
}
/**
* Validates that `@Component.imports` and `@Component.deferredImports` do not have
* overlapping dependencies.
*/
function validateNoImportOverlap(
eagerDeps: Array<PipeMeta | DirectiveMeta | NgModuleMeta>,
deferredDeps: Array<PipeMeta | DirectiveMeta | NgModuleMeta>,
rawDeferredImports: ts.Expression,
) {
let diagnostic: ts.Diagnostic | null = null;
const eagerDepsSet = new Set();
for (const eagerDep of eagerDeps) {
eagerDepsSet.add(eagerDep.ref.node);
}
for (const deferredDep of deferredDeps) {
if (eagerDepsSet.has(deferredDep.ref.node)) {
const classInfo = deferredDep.ref.debugName
? `The \`${deferredDep.ref.debugName}\``
: 'One of the dependencies';
diagnostic = makeDiagnostic(
ErrorCode.DEFERRED_DEPENDENCY_IMPORTED_EAGERLY,
getDiagnosticNode(deferredDep.ref, rawDeferredImports),
`\`${classInfo}\` is imported via both \`@Component.imports\` and ` +
`\`@Component.deferredImports\`. To fix this, make sure that ` +
`dependencies are imported only once.`,
);
break;
}
}
return diagnostic;
}
function validateStandaloneImports(
importRefs: Reference<ClassDeclaration>[],
importExpr: ts.Expression,
metaReader: MetadataReader,
scopeReader: ComponentScopeReader,
isDeferredImport: boolean,
): ts.Diagnostic[] {
const diagnostics: ts.Diagnostic[] = [];
for (const ref of importRefs) {
const dirMeta = metaReader.getDirectiveMetadata(ref);
if (dirMeta !== null) {
if (!dirMeta.isStandalone) {
// Directly importing a directive that's not standalone is an error.
diagnostics.push(
makeNotStandaloneDiagnostic(
scopeReader,
ref,
importExpr,
dirMeta.isComponent ? 'component' : 'directive',
),
);
}
continue;
}
const pipeMeta = metaReader.getPipeMetadata(ref);
if (pipeMeta !== null) {
if (!pipeMeta.isStandalone) {
diagnostics.push(makeNotStandaloneDiagnostic(scopeReader, ref, importExpr, 'pipe'));
}
continue;
}
const ngModuleMeta = metaReader.getNgModuleMetadata(ref);
if (!isDeferredImport && ngModuleMeta !== null) {
// Importing NgModules is always legal in `@Component.imports`,
// but not supported in `@Component.deferredImports`.
continue;
}
// Make an error?
const error = isDeferredImport
? makeUnknownComponentDeferredImportDiagnostic(ref, importExpr)
: makeUnknownComponentImportDiagnostic(ref, importExpr);
diagnostics.push(error);
}
return diagnostics;
}
/** Returns whether an ImportDeclaration is a default import. */
function isDefaultImport(node: ts.ImportDeclaration): boolean {
return node.importClause !== undefined && node.importClause.namedBindings === undefined;
}
| {
"end_byte": 83032,
"start_byte": 77030,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/component/src/metadata.ts_0_4819 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
AnimationTriggerNames,
DeclarationListEmitMode,
DeferBlockDepsEmitMode,
R3ClassDebugInfo,
R3ClassMetadata,
R3ComponentMetadata,
R3DeferPerBlockDependency,
R3DeferPerComponentDependency,
R3TemplateDependencyMetadata,
SchemaMetadata,
TmplAstDeferredBlock,
} from '@angular/compiler';
import ts from 'typescript';
import {Reference} from '../../../imports';
import {
ClassPropertyMapping,
ComponentResources,
DirectiveTypeCheckMeta,
HostDirectiveMeta,
InputMapping,
} from '../../../metadata';
import {ClassDeclaration} from '../../../reflection';
import {SubsetOfKeys} from '../../../util/src/typescript';
import {ParsedTemplateWithSource, StyleUrlMeta} from './resources';
/**
* These fields of `R3ComponentMetadata` are updated in the `resolve` phase.
*
* The `keyof R3ComponentMetadata &` condition ensures that only fields of `R3ComponentMetadata` can
* be included here.
*/
export type ComponentMetadataResolvedFields = SubsetOfKeys<
R3ComponentMetadata<R3TemplateDependencyMetadata>,
'declarations' | 'declarationListEmitMode' | 'defer'
>;
export interface ComponentAnalysisData {
/**
* `meta` includes those fields of `R3ComponentMetadata` which are calculated at `analyze` time
* (not during resolve).
*/
meta: Omit<R3ComponentMetadata<R3TemplateDependencyMetadata>, ComponentMetadataResolvedFields>;
baseClass: Reference<ClassDeclaration> | 'dynamic' | null;
typeCheckMeta: DirectiveTypeCheckMeta;
template: ParsedTemplateWithSource;
classMetadata: R3ClassMetadata | null;
classDebugInfo: R3ClassDebugInfo | null;
inputs: ClassPropertyMapping<InputMapping>;
inputFieldNamesFromMetadataArray: Set<string>;
outputs: ClassPropertyMapping;
/**
* Providers extracted from the `providers` field of the component annotation which will require
* an Angular factory definition at runtime.
*/
providersRequiringFactory: Set<Reference<ClassDeclaration>> | null;
/**
* Providers extracted from the `viewProviders` field of the component annotation which will
* require an Angular factory definition at runtime.
*/
viewProvidersRequiringFactory: Set<Reference<ClassDeclaration>> | null;
resources: ComponentResources;
/**
* `styleUrls` extracted from the decorator, if present.
*/
styleUrls: StyleUrlMeta[] | null;
/**
* Inline stylesheets extracted from the decorator, if present.
*/
inlineStyles: string[] | null;
isPoisoned: boolean;
animationTriggerNames: AnimationTriggerNames | null;
rawImports: ts.Expression | null;
resolvedImports: Reference<ClassDeclaration>[] | null;
rawDeferredImports: ts.Expression | null;
resolvedDeferredImports: Reference<ClassDeclaration>[] | null;
/**
* Map of symbol name -> import path for types from `@Component.deferredImports` field.
*/
explicitlyDeferredTypes: R3DeferPerComponentDependency[] | null;
schemas: SchemaMetadata[] | null;
decorator: ts.Decorator | null;
/** Additional directives applied to the component host. */
hostDirectives: HostDirectiveMeta[] | null;
/** Raw expression that defined the host directives array. Used for diagnostics. */
rawHostDirectives: ts.Expression | null;
}
export interface ComponentResolutionData {
declarations: R3TemplateDependencyMetadata[];
declarationListEmitMode: DeclarationListEmitMode;
/**
* Map of all types that can be defer loaded (ts.ClassDeclaration) ->
* corresponding import declaration (ts.ImportDeclaration) within
* the current source file.
*/
deferrableDeclToImportDecl: Map<ClassDeclaration, ts.ImportDeclaration>;
/**
* Map of `@defer` blocks -> their corresponding dependencies.
* Required to compile the defer resolver function in `PerBlock` mode.
*/
deferPerBlockDependencies: Map<TmplAstDeferredBlock, DeferredComponentDependency[]>;
/**
* Defines how dynamic imports for deferred dependencies should be grouped:
* - either in a function on per-component basis (in case of local compilation)
* - or in a function on per-block basis (in full compilation mode)
*/
deferBlockDepsEmitMode: DeferBlockDepsEmitMode;
/**
* List of deferrable dependencies in the entire component. Used to compile the
* defer resolver function in `PerComponent` mode.
*/
deferPerComponentDependencies: R3DeferPerComponentDependency[];
}
/**
* Describes a dependency used within a `@defer` block.
*/
export type DeferredComponentDependency = R3DeferPerBlockDependency & {
/** Reference to the declaration that defines the dependency. */
declaration: Reference<ClassDeclaration>;
};
| {
"end_byte": 4819,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/component/src/metadata.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/README.md_0_500 | # What is the 'annotations/common' package?
This package contains common code related to the processing of Angular-decorated classes by `DecoratorHandler` implementations. Some common utilities provided by this package help with:
* Static evaluation of different kinds of expressions
* Construction of various diagnostics
* Extraction of dependency injection information
* Compilation of dependency injection factories
* Extraction of raw metadata suitable for generating `setClassMetadata` calls | {
"end_byte": 500,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/README.md"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/BUILD.bazel_0_745 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "common",
srcs = ["index.ts"] + glob([
"src/**/*.ts",
]),
deps = [
"//packages/compiler",
"//packages/compiler-cli/src/ngtsc/diagnostics",
"//packages/compiler-cli/src/ngtsc/imports",
"//packages/compiler-cli/src/ngtsc/metadata",
"//packages/compiler-cli/src/ngtsc/partial_evaluator",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/scope",
"//packages/compiler-cli/src/ngtsc/transform",
"//packages/compiler-cli/src/ngtsc/util",
"@npm//@types/node",
"@npm//typescript",
],
)
| {
"end_byte": 745,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/index.ts_0_655 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './src/api';
export * from './src/di';
export * from './src/diagnostics';
export * from './src/evaluation';
export * from './src/factory';
export * from './src/injectable_registry';
export * from './src/metadata';
export * from './src/debug_info';
export * from './src/references_registry';
export * from './src/schema';
export * from './src/util';
export * from './src/input_transforms';
export * from './src/jit_declaration_registry';
| {
"end_byte": 655,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/index.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/test/metadata_spec.ts_0_5093 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {compileClassMetadata} from '@angular/compiler';
import ts from 'typescript';
import {absoluteFrom, getSourceFileOrError} from '../../../file_system';
import {runInEachFileSystem, TestFile} from '../../../file_system/testing';
import {TypeScriptReflectionHost} from '../../../reflection';
import {getDeclaration, makeProgram} from '../../../testing';
import {
ImportManager,
presetImportManagerForceNamespaceImports,
translateStatement,
} from '../../../translator';
import {extractClassMetadata} from '../src/metadata';
runInEachFileSystem(() => {
describe('ngtsc setClassMetadata converter', () => {
it('should convert decorated class metadata', () => {
const res = compileAndPrint(`
import {Component} from '@angular/core';
@Component('metadata') class Target {}
`);
expect(res).toEqual(
`(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(Target, [{ type: Component, args: ['metadata'] }], null, null); })();`,
);
});
it('should convert namespaced decorated class metadata', () => {
const res = compileAndPrint(`
import * as core from '@angular/core';
@core.Component('metadata') class Target {}
`);
expect(res).toEqual(
`(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(Target, [{ type: core.Component, args: ['metadata'] }], null, null); })();`,
);
});
it('should convert decorated class constructor parameter metadata', () => {
const res = compileAndPrint(`
import {Component, Inject, Injector} from '@angular/core';
const FOO = 'foo';
@Component('metadata') class Target {
constructor(@Inject(FOO) foo: any, bar: Injector) {}
}
`);
expect(res).toContain(
`() => [{ type: undefined, decorators: [{ type: Inject, args: [FOO] }] }, { type: i0.Injector }], null);`,
);
});
it('should convert decorated field metadata', () => {
const res = compileAndPrint(`
import {Component, Input} from '@angular/core';
@Component('metadata') class Target {
@Input() foo: string;
@Input('value') bar: string;
notDecorated: string;
}
`);
expect(res).toContain(`{ foo: [{ type: Input }], bar: [{ type: Input, args: ['value'] }] })`);
});
it('should convert decorated field getter/setter metadata', () => {
const res = compileAndPrint(`
import {Component, Input} from '@angular/core';
@Component('metadata') class Target {
@Input() get foo() { return this._foo; }
set foo(value: string) { this._foo = value; }
private _foo: string;
get bar() { return this._bar; }
@Input('value') set bar(value: string) { this._bar = value; }
private _bar: string;
}
`);
expect(res).toContain(`{ foo: [{ type: Input }], bar: [{ type: Input, args: ['value'] }] })`);
});
it('should not convert non-angular decorators to metadata', () => {
const res = compileAndPrint(`
declare function NotAComponent(...args: any[]): any;
@NotAComponent('metadata') class Target {}
`);
expect(res).toBe('');
});
it('should preserve quotes around class member names', () => {
const res = compileAndPrint(`
import {Component, Input} from '@angular/core';
@Component('metadata') class Target {
@Input() 'has-dashes-in-name' = 123;
@Input() noDashesInName = 456;
}
`);
expect(res).toContain(
`{ 'has-dashes-in-name': [{ type: Input }], noDashesInName: [{ type: Input }] })`,
);
});
});
function compileAndPrint(contents: string): string {
const _ = absoluteFrom;
const CORE: TestFile = {
name: _('/node_modules/@angular/core/index.d.ts'),
contents: `
export declare function Input(...args: any[]): any;
export declare function Inject(...args: any[]): any;
export declare function Component(...args: any[]): any;
export declare class Injector {}
`,
};
const {program} = makeProgram(
[
CORE,
{
name: _('/index.ts'),
contents,
},
],
{target: ts.ScriptTarget.ES2015},
);
const host = new TypeScriptReflectionHost(program.getTypeChecker());
const target = getDeclaration(program, _('/index.ts'), 'Target', ts.isClassDeclaration);
const call = extractClassMetadata(target, host, false);
if (call === null) {
return '';
}
const sf = getSourceFileOrError(program, _('/index.ts'));
const im = new ImportManager(presetImportManagerForceNamespaceImports);
const stmt = compileClassMetadata(call).toStmt();
const tsStatement = translateStatement(sf, stmt, im);
const res = ts.createPrinter().printNode(ts.EmitHint.Unspecified, tsStatement, sf);
return res.replace(/\s+/g, ' ');
}
});
| {
"end_byte": 5093,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/test/metadata_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/test/diagnostics_spec.ts_0_5609 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {absoluteFrom as _, getSourceFileOrError} from '../../../file_system';
import {runInEachFileSystem, TestFile} from '../../../file_system/testing';
import {PartialEvaluator} from '../../../partial_evaluator';
import {TypeScriptReflectionHost} from '../../../reflection';
import {getDeclaration, makeProgram} from '../../../testing';
import {createValueHasWrongTypeError} from '../src/diagnostics';
runInEachFileSystem(() => {
describe('ngtsc annotation diagnostics', () => {
describe('createValueError()', () => {
it('should include a trace for dynamic values', () => {
const {error, program} = createError('', 'nonexistent', 'Error message');
const entrySf = getSourceFileOrError(program, _('/entry.ts'));
if (typeof error.diagnosticMessage === 'string') {
return fail('Created error must have a message chain');
}
expect(error.diagnosticMessage.messageText).toBe('Error message');
expect(error.diagnosticMessage.next!.length).toBe(1);
expect(error.diagnosticMessage.next![0].messageText).toBe(
`Value could not be determined statically.`,
);
expect(error.relatedInformation).toBeDefined();
expect(error.relatedInformation!.length).toBe(1);
expect(error.relatedInformation![0].messageText).toBe('Unknown reference.');
expect(error.relatedInformation![0].file!.fileName).toBe(entrySf.fileName);
expect(getSourceCode(error.relatedInformation![0])).toBe('nonexistent');
});
it('should include a pointer for a reference to a named declaration', () => {
const {error, program} = createError(`import {Foo} from './foo';`, 'Foo', 'Error message', [
{name: _('/foo.ts'), contents: 'export class Foo {}'},
]);
const fooSf = getSourceFileOrError(program, _('/foo.ts'));
if (typeof error.diagnosticMessage === 'string') {
return fail('Created error must have a message chain');
}
expect(error.diagnosticMessage.messageText).toBe('Error message');
expect(error.diagnosticMessage.next!.length).toBe(1);
expect(error.diagnosticMessage.next![0].messageText).toBe(`Value is a reference to 'Foo'.`);
expect(error.relatedInformation).toBeDefined();
expect(error.relatedInformation!.length).toBe(1);
expect(error.relatedInformation![0].messageText).toBe('Reference is declared here.');
expect(error.relatedInformation![0].file!.fileName).toBe(fooSf.fileName);
expect(getSourceCode(error.relatedInformation![0])).toBe('Foo');
});
it('should include a pointer for a reference to an anonymous declaration', () => {
const {error, program} = createError(`import Foo from './foo';`, 'Foo', 'Error message', [
{name: _('/foo.ts'), contents: 'export default class {}'},
]);
const fooSf = getSourceFileOrError(program, _('/foo.ts'));
if (typeof error.diagnosticMessage === 'string') {
return fail('Created error must have a message chain');
}
expect(error.diagnosticMessage.messageText).toBe('Error message');
expect(error.diagnosticMessage.next!.length).toBe(1);
expect(error.diagnosticMessage.next![0].messageText).toBe(
`Value is a reference to an anonymous declaration.`,
);
expect(error.relatedInformation).toBeDefined();
expect(error.relatedInformation!.length).toBe(1);
expect(error.relatedInformation![0].messageText).toBe('Reference is declared here.');
expect(error.relatedInformation![0].file!.fileName).toBe(fooSf.fileName);
expect(getSourceCode(error.relatedInformation![0])).toBe('export default class {}');
});
it("should include a representation of the value's type", () => {
const {error} = createError('', '{a: 2}', 'Error message');
if (typeof error.diagnosticMessage === 'string') {
return fail('Created error must have a message chain');
}
expect(error.diagnosticMessage.messageText).toBe('Error message');
expect(error.diagnosticMessage.next!.length).toBe(1);
expect(error.diagnosticMessage.next![0].messageText).toBe(
`Value is of type '{ a: number }'.`,
);
expect(error.relatedInformation).not.toBeDefined();
});
});
});
});
function getSourceCode(diag: ts.DiagnosticRelatedInformation): string {
const text = diag.file!.text;
return text.slice(diag.start!, diag.start! + diag.length!);
}
function createError(
code: string,
expr: string,
messageText: string,
supportingFiles: TestFile[] = [],
) {
const {program} = makeProgram(
[{name: _('/entry.ts'), contents: `${code}; const target$ = ${expr}`}, ...supportingFiles],
/* options */ undefined,
/* host */ undefined,
/* checkForErrors */ false,
);
const checker = program.getTypeChecker();
const decl = getDeclaration(program, _('/entry.ts'), 'target$', ts.isVariableDeclaration);
const valueExpr = decl.initializer!;
const reflectionHost = new TypeScriptReflectionHost(checker);
const evaluator = new PartialEvaluator(reflectionHost, checker, /* dependencyTracker */ null);
const value = evaluator.evaluate(valueExpr);
const error = createValueHasWrongTypeError(valueExpr, value, messageText);
return {error, program};
}
| {
"end_byte": 5609,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/test/diagnostics_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/test/util_spec.ts_0_1394 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {unwrapExpression} from '../src/util';
describe('ngtsc annotation utilities', () => {
describe('unwrapExpression', () => {
const obj = ts.factory.createObjectLiteralExpression();
it('should pass through an ObjectLiteralExpression', () => {
expect(unwrapExpression(obj)).toBe(obj);
});
it('should unwrap an ObjectLiteralExpression in parentheses', () => {
const wrapped = ts.factory.createParenthesizedExpression(obj);
expect(unwrapExpression(wrapped)).toBe(obj);
});
it('should unwrap an ObjectLiteralExpression with a type cast', () => {
const cast = ts.factory.createAsExpression(
obj,
ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword),
);
expect(unwrapExpression(cast)).toBe(obj);
});
it('should unwrap an ObjectLiteralExpression with a type cast in parentheses', () => {
const cast = ts.factory.createAsExpression(
obj,
ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword),
);
const wrapped = ts.factory.createParenthesizedExpression(cast);
expect(unwrapExpression(wrapped)).toBe(obj);
});
});
});
| {
"end_byte": 1394,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/test/util_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/test/BUILD.bazel_0_932 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "test_lib",
testonly = True,
srcs = glob([
"**/*.ts",
]),
deps = [
"//packages:types",
"//packages/compiler",
"//packages/compiler-cli/src/ngtsc/annotations/common",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/file_system/testing",
"//packages/compiler-cli/src/ngtsc/imports",
"//packages/compiler-cli/src/ngtsc/partial_evaluator",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/testing",
"//packages/compiler-cli/src/ngtsc/translator",
"@npm//typescript",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node_no_angular"],
deps = [
":test_lib",
],
)
| {
"end_byte": 932,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/test/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/src/schema.ts_0_2043 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA, SchemaMetadata} from '@angular/compiler';
import ts from 'typescript';
import {Reference} from '../../../imports';
import {PartialEvaluator} from '../../../partial_evaluator';
import {createValueHasWrongTypeError} from './diagnostics';
export function extractSchemas(
rawExpr: ts.Expression,
evaluator: PartialEvaluator,
context: string,
): SchemaMetadata[] {
const schemas: SchemaMetadata[] = [];
const result = evaluator.evaluate(rawExpr);
if (!Array.isArray(result)) {
throw createValueHasWrongTypeError(rawExpr, result, `${context}.schemas must be an array`);
}
for (const schemaRef of result) {
if (!(schemaRef instanceof Reference)) {
throw createValueHasWrongTypeError(
rawExpr,
result,
`${context}.schemas must be an array of schemas`,
);
}
const id = schemaRef.getIdentityIn(schemaRef.node.getSourceFile());
if (id === null || schemaRef.ownedByModuleGuess !== '@angular/core') {
throw createValueHasWrongTypeError(
rawExpr,
result,
`${context}.schemas must be an array of schemas`,
);
}
// Since `id` is the `ts.Identifier` within the schema ref's declaration file, it's safe to
// use `id.text` here to figure out which schema is in use. Even if the actual reference was
// renamed when the user imported it, these names will match.
switch (id.text) {
case 'CUSTOM_ELEMENTS_SCHEMA':
schemas.push(CUSTOM_ELEMENTS_SCHEMA);
break;
case 'NO_ERRORS_SCHEMA':
schemas.push(NO_ERRORS_SCHEMA);
break;
default:
throw createValueHasWrongTypeError(
rawExpr,
schemaRef,
`'${schemaRef.debugName}' is not a valid ${context} schema`,
);
}
}
return schemas;
}
| {
"end_byte": 2043,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/src/schema.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/src/standalone-default-value.ts_0_423 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A constant defining the default value for the standalone attribute in Directive and Pipes decorators.
* Extracted to a separate file to facilitate G3 patches.
*/
export const NG_STANDALONE_DEFAULT_VALUE = true;
| {
"end_byte": 423,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/src/standalone-default-value.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/src/injectable_registry.ts_0_1764 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {R3DependencyMetadata} from '@angular/compiler';
import {hasInjectableFields} from '../../../metadata';
import {ClassDeclaration, ReflectionHost} from '../../../reflection';
import {getConstructorDependencies, unwrapConstructorDependencies} from './di';
export interface InjectableMeta {
ctorDeps: R3DependencyMetadata[] | 'invalid' | null;
}
/**
* Registry that keeps track of classes that can be constructed via dependency injection (e.g.
* injectables, directives, pipes).
*/
export class InjectableClassRegistry {
private classes = new Map<ClassDeclaration, InjectableMeta>();
constructor(
private host: ReflectionHost,
private isCore: boolean,
) {}
registerInjectable(declaration: ClassDeclaration, meta: InjectableMeta): void {
this.classes.set(declaration, meta);
}
getInjectableMeta(declaration: ClassDeclaration): InjectableMeta | null {
// Figure out whether the class is injectable based on the registered classes, otherwise
// fall back to looking at its members since we might not have been able to register the class
// if it was compiled in another compilation unit.
if (this.classes.has(declaration)) {
return this.classes.get(declaration)!;
}
if (!hasInjectableFields(declaration, this.host)) {
return null;
}
const ctorDeps = getConstructorDependencies(declaration, this.host, this.isCore);
const meta: InjectableMeta = {
ctorDeps: unwrapConstructorDependencies(ctorDeps),
};
this.classes.set(declaration, meta);
return meta;
}
}
| {
"end_byte": 1764,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/src/injectable_registry.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/src/references_registry.ts_0_887 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Reference} from '../../../imports';
import {DeclarationNode} from '../../../reflection';
/**
* Implement this interface if you want DecoratorHandlers to register
* references that they find in their analysis of the code.
*/
export interface ReferencesRegistry {
/**
* Register one or more references in the registry.
* @param references A collection of references to register.
*/
add(source: DeclarationNode, ...references: Reference<DeclarationNode>[]): void;
}
/**
* This registry does nothing.
*/
export class NoopReferencesRegistry implements ReferencesRegistry {
add(source: DeclarationNode, ...references: Reference<DeclarationNode>[]): void {}
}
| {
"end_byte": 887,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/src/references_registry.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/src/input_transforms.ts_0_1148 | /*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {outputAst} from '@angular/compiler';
import {ClassPropertyMapping, InputMapping} from '../../../metadata';
import {CompileResult} from '../../../transform';
/** Generates additional fields to be added to a class that has inputs with transform functions. */
export function compileInputTransformFields(
inputs: ClassPropertyMapping<InputMapping>,
): CompileResult[] {
const extraFields: CompileResult[] = [];
for (const input of inputs) {
// Note: Signal inputs capture their transform `WriteT` as part of the `InputSignal`.
// Such inputs will not have a `transform` captured and not generate coercion members.
if (input.transform) {
extraFields.push({
name: `ngAcceptInputType_${input.classPropertyName}`,
type: outputAst.transplantedType(input.transform.type),
statements: [],
initializer: null,
deferrableImports: null,
});
}
}
return extraFields;
}
| {
"end_byte": 1148,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/src/input_transforms.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/src/api.ts_0_3985 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* Resolves and loads resource files that are referenced in Angular metadata.
*
* Note that `preload()` and `load()` take a `resolvedUrl`, which can be found
* by calling `resolve()`. These two steps are separated because sometimes the
* resolved URL to the resource is needed as well as its contents.
*/
export interface ResourceLoader {
/**
* True if this resource loader can preload resources.
*
* Sometimes a `ResourceLoader` is not able to do asynchronous pre-loading of resources.
*/
canPreload: boolean;
/**
* If true, the resource loader is able to preprocess inline resources.
*/
canPreprocess: boolean;
/**
* Resolve the url of a resource relative to the file that contains the reference to it.
* The return value of this method can be used in the `load()` and `preload()` methods.
*
* @param url The, possibly relative, url of the resource.
* @param fromFile The path to the file that contains the URL of the resource.
* @returns A resolved url of resource.
* @throws An error if the resource cannot be resolved.
*/
resolve(file: string, basePath: string): string;
/**
* Preload the specified resource, asynchronously. Once the resource is loaded, its value
* should be cached so it can be accessed synchronously via the `load()` method.
*
* @param resolvedUrl The url (resolved by a call to `resolve()`) of the resource to preload.
* @param context Information regarding the resource such as the type and containing file.
* @returns A Promise that is resolved once the resource has been loaded or `undefined`
* if the file has already been loaded.
* @throws An Error if pre-loading is not available.
*/
preload(resolvedUrl: string, context: ResourceLoaderContext): Promise<void> | undefined;
/**
* Preprocess the content data of an inline resource, asynchronously.
*
* @param data The existing content data from the inline resource.
* @param context Information regarding the resource such as the type and containing file.
* @returns A Promise that resolves to the processed data. If no processing occurs, the
* same data string that was passed to the function will be resolved.
*/
preprocessInline(data: string, context: ResourceLoaderContext): Promise<string>;
/**
* Load the resource at the given url, synchronously.
*
* The contents of the resource may have been cached by a previous call to `preload()`.
*
* @param resolvedUrl The url (resolved by a call to `resolve()`) of the resource to load.
* @returns The contents of the resource.
*/
load(resolvedUrl: string): string;
}
/**
* Contextual information used by members of the ResourceLoader interface.
*/
export interface ResourceLoaderContext {
/**
* The type of the component resource.
* * Resources referenced via a component's `styles` or `styleUrls` properties are of
* type `style`.
* * Resources referenced via a component's `template` or `templateUrl` properties are of type
* `template`.
*/
type: 'style' | 'template';
/**
* The absolute path to the file that contains the resource or reference to the resource.
*/
containingFile: string;
/**
* For style resources, the placement of the style within the containing file with lower numbers
* being before higher numbers.
* The value is primarily used by the Angular CLI to create a deterministic identifier for each
* style in HMR scenarios.
* This is undefined for templates.
*/
order?: number;
/**
* The name of the class that defines the component using the resource.
* This allows identifying the source usage of a resource in cases where multiple components are
* contained in a single source file.
*/
className: string;
}
| {
"end_byte": 3985,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/src/api.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/src/factory.ts_0_1030 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
compileDeclareFactoryFunction,
compileFactoryFunction,
R3FactoryMetadata,
} from '@angular/compiler';
import {CompileResult} from '../../../transform';
export type CompileFactoryFn = (metadata: R3FactoryMetadata) => CompileResult;
export function compileNgFactoryDefField(metadata: R3FactoryMetadata): CompileResult {
const res = compileFactoryFunction(metadata);
return {
name: 'ɵfac',
initializer: res.expression,
statements: res.statements,
type: res.type,
deferrableImports: null,
};
}
export function compileDeclareFactory(metadata: R3FactoryMetadata): CompileResult {
const res = compileDeclareFactoryFunction(metadata);
return {
name: 'ɵfac',
initializer: res.expression,
statements: res.statements,
type: res.type,
deferrableImports: null,
};
}
| {
"end_byte": 1030,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/src/factory.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/src/debug_info.ts_0_1199 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {literal, R3ClassDebugInfo, WrappedNodeExpr} from '@angular/compiler';
import ts from 'typescript';
import {DeclarationNode, ReflectionHost} from '../../../reflection';
import {getProjectRelativePath} from '../../../util/src/path';
export function extractClassDebugInfo(
clazz: DeclarationNode,
reflection: ReflectionHost,
compilerHost: Pick<ts.CompilerHost, 'getCanonicalFileName'>,
rootDirs: ReadonlyArray<string>,
forbidOrphanRendering: boolean,
): R3ClassDebugInfo | null {
if (!reflection.isClass(clazz)) {
return null;
}
const srcFile = clazz.getSourceFile();
const srcFileMaybeRelativePath = getProjectRelativePath(srcFile, rootDirs, compilerHost);
return {
type: new WrappedNodeExpr(clazz.name),
className: literal(clazz.name.getText()),
filePath: srcFileMaybeRelativePath ? literal(srcFileMaybeRelativePath) : null,
lineNumber: literal(srcFile.getLineAndCharacterOfPosition(clazz.name.pos).line + 1),
forbidOrphanRendering,
};
}
| {
"end_byte": 1199,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/src/debug_info.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/src/di.ts_0_8569 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Expression, LiteralExpr, R3DependencyMetadata, WrappedNodeExpr} from '@angular/compiler';
import ts from 'typescript';
import {ErrorCode, FatalDiagnosticError, makeRelatedInformation} from '../../../diagnostics';
import {
ClassDeclaration,
CtorParameter,
ReflectionHost,
TypeValueReferenceKind,
UnavailableValue,
ValueUnavailableKind,
} from '../../../reflection';
import {isAngularCore, valueReferenceToExpression} from './util';
export type ConstructorDeps =
| {
deps: R3DependencyMetadata[];
}
| {
deps: null;
errors: ConstructorDepError[];
};
export interface ConstructorDepError {
index: number;
param: CtorParameter;
reason: UnavailableValue;
}
export function getConstructorDependencies(
clazz: ClassDeclaration,
reflector: ReflectionHost,
isCore: boolean,
): ConstructorDeps | null {
const deps: R3DependencyMetadata[] = [];
const errors: ConstructorDepError[] = [];
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: Expression | null = 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 WrappedNodeExpr(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 WrappedNodeExpr(attributeName);
if (ts.isStringLiteralLike(attributeName)) {
attributeNameType = new LiteralExpr(attributeName.text);
} else {
attributeNameType = new WrappedNodeExpr(
ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword),
);
}
} else {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_UNEXPECTED,
dec.node,
`Unexpected decorator ${name} on parameter.`,
);
}
});
if (token === null) {
if (param.typeValueReference.kind !== TypeValueReferenceKind.UNAVAILABLE) {
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};
}
}
/**
* Convert `ConstructorDeps` into the `R3DependencyMetadata` array for those deps if they're valid,
* or into an `'invalid'` signal if they're not.
*
* This is a companion function to `validateConstructorDependencies` which accepts invalid deps.
*/
export function unwrapConstructorDependencies(
deps: ConstructorDeps | null,
): R3DependencyMetadata[] | 'invalid' | null {
if (deps === null) {
return null;
} else if (deps.deps !== null) {
// These constructor dependencies are valid.
return deps.deps;
} else {
// These deps are invalid.
return 'invalid';
}
}
export function getValidConstructorDependencies(
clazz: ClassDeclaration,
reflector: ReflectionHost,
isCore: boolean,
): R3DependencyMetadata[] | null {
return validateConstructorDependencies(
clazz,
getConstructorDependencies(clazz, reflector, isCore),
);
}
/**
* Validate that `ConstructorDeps` does not have any invalid dependencies and convert them into the
* `R3DependencyMetadata` array if so, or raise a diagnostic if some deps are invalid.
*
* This is a companion function to `unwrapConstructorDependencies` which does not accept invalid
* deps.
*/
export function validateConstructorDependencies(
clazz: ClassDeclaration,
deps: ConstructorDeps | null,
): R3DependencyMetadata[] | null {
if (deps === null) {
return null;
} else if (deps.deps !== null) {
return deps.deps;
} else {
// There is at least one error.
const error = deps.errors[0];
throw createUnsuitableInjectionTokenError(clazz, error);
}
}
/**
* Creates a fatal error with diagnostic for an invalid injection token.
* @param clazz The class for which the injection token was unavailable.
* @param error The reason why no valid injection token is available.
*/
function createUnsuitableInjectionTokenError(
clazz: ClassDeclaration,
error: ConstructorDepError,
): FatalDiagnosticError {
const {param, index, reason} = error;
let chainMessage: string | undefined = undefined;
let hints: ts.DiagnosticRelatedInformation[] | undefined = undefined;
switch (reason.kind) {
case ValueUnavailableKind.UNSUPPORTED:
chainMessage = 'Consider using the @Inject decorator to specify an injection token.';
hints = [
makeRelatedInformation(reason.typeNode, 'This type is not supported as injection token.'),
];
break;
case ValueUnavailableKind.NO_VALUE_DECLARATION:
chainMessage = 'Consider using the @Inject decorator to specify an injection token.';
hints = [
makeRelatedInformation(
reason.typeNode,
'This type does not have a value, so it cannot be used as injection token.',
),
];
if (reason.decl !== null) {
hints.push(makeRelatedInformation(reason.decl, 'The type is declared here.'));
}
break;
case ValueUnavailableKind.TYPE_ONLY_IMPORT:
chainMessage =
'Consider changing the type-only import to a regular import, or use the @Inject decorator to specify an injection token.';
hints = [
makeRelatedInformation(
reason.typeNode,
'This type is imported using a type-only import, which prevents it from being usable as an injection token.',
),
makeRelatedInformation(reason.node, 'The type-only import occurs here.'),
];
break;
case ValueUnavailableKind.NAMESPACE:
chainMessage = 'Consider using the @Inject decorator to specify an injection token.';
hints = [
makeRelatedInformation(
reason.typeNode,
'This type corresponds with a namespace, which cannot be used as injection token.',
),
makeRelatedInformation(reason.importClause, 'The namespace import occurs here.'),
];
break;
case ValueUnavailableKind.UNKNOWN_REFERENCE:
chainMessage = 'The type should reference a known declaration.';
hints = [makeRelatedInformation(reason.typeNode, 'This type could not be resolved.')];
break;
case ValueUnavailableKind.MISSING_TYPE:
chainMessage =
'Consider adding a type to the parameter or use the @Inject decorator to specify an injection token.';
break;
}
const chain: ts.DiagnosticMessageChain = {
messageText: `No suitable injection token for parameter '${param.name || index}' of class '${
clazz.name.text
}'.`,
category: ts.DiagnosticCategory.Error,
code: 0,
next: [
{
messageText: chainMessage,
category: ts.DiagnosticCategory.Message,
code: 0,
},
],
};
return new FatalDiagnosticError(ErrorCode.PARAM_MISSING_TOKEN, param.nameNode, chain, hints);
}
| {
"end_byte": 8569,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/src/di.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/src/evaluation.ts_0_3731 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ViewEncapsulation} from '@angular/compiler';
import ts from 'typescript';
import {ErrorCode, FatalDiagnosticError} from '../../../diagnostics';
import {Reference} from '../../../imports';
import {EnumValue, PartialEvaluator, ResolvedValue} from '../../../partial_evaluator';
import {ClassDeclaration, Decorator} from '../../../reflection';
import {createValueHasWrongTypeError} from './diagnostics';
import {isAngularCoreReference, unwrapExpression} from './util';
export function resolveEnumValue(
evaluator: PartialEvaluator,
metadata: Map<string, ts.Expression>,
field: string,
enumSymbolName: string,
): number | null {
let resolved: number | null = null;
if (metadata.has(field)) {
const expr = metadata.get(field)!;
const value = evaluator.evaluate(expr) as any;
if (value instanceof EnumValue && isAngularCoreReference(value.enumRef, enumSymbolName)) {
resolved = value.resolved as number;
} else {
throw createValueHasWrongTypeError(
expr,
value,
`${field} must be a member of ${enumSymbolName} enum from @angular/core`,
);
}
}
return resolved;
}
/**
* Resolves a EncapsulationEnum expression locally on best effort without having to calculate the
* reference. This suites local compilation mode where each file is compiled individually.
*
* The static analysis is still needed in local compilation mode since the value of this enum will
* be used later to decide the generated code for styles.
*/
export function resolveEncapsulationEnumValueLocally(expr?: ts.Expression): number | null {
if (!expr) {
return null;
}
const exprText = expr.getText().trim();
for (const key in ViewEncapsulation) {
if (!Number.isNaN(Number(key))) {
continue;
}
const suffix = `ViewEncapsulation.${key}`;
// Check whether the enum is imported by name or used by import namespace (e.g.,
// core.ViewEncapsulation.None)
if (exprText === suffix || exprText.endsWith(`.${suffix}`)) {
const ans = Number(ViewEncapsulation[key]);
return ans;
}
}
return null;
}
/** Determines if the result of an evaluation is a string array. */
export function isStringArray(resolvedValue: ResolvedValue): resolvedValue is string[] {
return Array.isArray(resolvedValue) && resolvedValue.every((elem) => typeof elem === 'string');
}
export function isClassReferenceArray(
resolvedValue: ResolvedValue,
): resolvedValue is Reference<ClassDeclaration>[] {
return (
Array.isArray(resolvedValue) &&
resolvedValue.every((elem) => elem instanceof Reference && ts.isClassDeclaration(elem.node))
);
}
export function isArray(value: ResolvedValue): value is Array<ResolvedValue> {
return Array.isArray(value);
}
export function resolveLiteral(
decorator: Decorator,
literalCache: Map<Decorator, ts.ObjectLiteralExpression>,
): ts.ObjectLiteralExpression {
if (literalCache.has(decorator)) {
return literalCache.get(decorator)!;
}
if (decorator.args === null || decorator.args.length !== 1) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG,
decorator.node,
`Incorrect number of arguments to @${decorator.name} decorator`,
);
}
const meta = unwrapExpression(decorator.args[0]);
if (!ts.isObjectLiteralExpression(meta)) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARG_NOT_LITERAL,
meta,
`Decorator argument must be literal.`,
);
}
literalCache.set(decorator, meta);
return meta;
}
| {
"end_byte": 3731,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/src/evaluation.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/src/diagnostics.ts_0_8589 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {
ErrorCode,
FatalDiagnosticError,
makeDiagnostic,
makeRelatedInformation,
} from '../../../diagnostics';
import {Reference} from '../../../imports';
import {
ClassPropertyName,
DirectiveMeta,
flattenInheritedDirectiveMetadata,
HostDirectiveMeta,
isHostDirectiveMetaForGlobalMode,
MetadataReader,
} from '../../../metadata';
import {
describeResolvedType,
DynamicValue,
PartialEvaluator,
ResolvedValue,
traceDynamicValue,
} from '../../../partial_evaluator';
import {ClassDeclaration, ReflectionHost} from '../../../reflection';
import {DeclarationData, LocalModuleScopeRegistry} from '../../../scope';
import {identifierOfNode, isFromDtsFile} from '../../../util/src/typescript';
import {InjectableClassRegistry} from './injectable_registry';
import {isAbstractClassDeclaration, readBaseClass} from './util';
import {CompilationMode} from '../../../transform';
/**
* Create a `ts.Diagnostic` which indicates the given class is part of the declarations of two or
* more NgModules.
*
* The resulting `ts.Diagnostic` will have a context entry for each NgModule showing the point where
* the directive/pipe exists in its `declarations` (if possible).
*/
export function makeDuplicateDeclarationError(
node: ClassDeclaration,
data: DeclarationData[],
kind: string,
): ts.Diagnostic {
const context: ts.DiagnosticRelatedInformation[] = [];
for (const decl of data) {
if (decl.rawDeclarations === null) {
continue;
}
// Try to find the reference to the declaration within the declarations array, to hang the
// error there. If it can't be found, fall back on using the NgModule's name.
const contextNode = decl.ref.getOriginForDiagnostics(decl.rawDeclarations, decl.ngModule.name);
context.push(
makeRelatedInformation(
contextNode,
`'${node.name.text}' is listed in the declarations of the NgModule '${decl.ngModule.name.text}'.`,
),
);
}
// Finally, produce the diagnostic.
return makeDiagnostic(
ErrorCode.NGMODULE_DECLARATION_NOT_UNIQUE,
node.name,
`The ${kind} '${node.name.text}' is declared by more than one NgModule.`,
context,
);
}
/**
* Creates a `FatalDiagnosticError` for a node that did not evaluate to the expected type. The
* diagnostic that is created will include details on why the value is incorrect, i.e. it includes
* a representation of the actual type that was unsupported, or in the case of a dynamic value the
* trace to the node where the dynamic value originated.
*
* @param node The node for which the diagnostic should be produced.
* @param value The evaluated value that has the wrong type.
* @param messageText The message text of the error.
*/
export function createValueHasWrongTypeError(
node: ts.Node,
value: ResolvedValue,
messageText: string,
): FatalDiagnosticError {
let chainedMessage: string;
let relatedInformation: ts.DiagnosticRelatedInformation[] | undefined;
if (value instanceof DynamicValue) {
chainedMessage = 'Value could not be determined statically.';
relatedInformation = traceDynamicValue(node, value);
} else if (value instanceof Reference) {
const target = value.debugName !== null ? `'${value.debugName}'` : 'an anonymous declaration';
chainedMessage = `Value is a reference to ${target}.`;
const referenceNode = identifierOfNode(value.node) ?? value.node;
relatedInformation = [makeRelatedInformation(referenceNode, 'Reference is declared here.')];
} else {
chainedMessage = `Value is of type '${describeResolvedType(value)}'.`;
}
const chain: ts.DiagnosticMessageChain = {
messageText,
category: ts.DiagnosticCategory.Error,
code: 0,
next: [
{
messageText: chainedMessage,
category: ts.DiagnosticCategory.Message,
code: 0,
},
],
};
return new FatalDiagnosticError(ErrorCode.VALUE_HAS_WRONG_TYPE, node, chain, relatedInformation);
}
/**
* Gets the diagnostics for a set of provider classes.
* @param providerClasses Classes that should be checked.
* @param providersDeclaration Node that declares the providers array.
* @param registry Registry that keeps track of the registered injectable classes.
*/
export function getProviderDiagnostics(
providerClasses: Set<Reference<ClassDeclaration>>,
providersDeclaration: ts.Expression,
registry: InjectableClassRegistry,
): ts.Diagnostic[] {
const diagnostics: ts.Diagnostic[] = [];
for (const provider of providerClasses) {
const injectableMeta = registry.getInjectableMeta(provider.node);
if (injectableMeta !== null) {
// The provided type is recognized as injectable, so we don't report a diagnostic for this
// provider.
continue;
}
const contextNode = provider.getOriginForDiagnostics(providersDeclaration);
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.
Either add the @Injectable() decorator to '${provider.node.name.text}', or configure a different provider (such as a provider with 'useFactory').
`,
[makeRelatedInformation(provider.node, `'${provider.node.name.text}' is declared here.`)],
),
);
}
return diagnostics;
}
export function getDirectiveDiagnostics(
node: ClassDeclaration,
injectableRegistry: InjectableClassRegistry,
evaluator: PartialEvaluator,
reflector: ReflectionHost,
scopeRegistry: LocalModuleScopeRegistry,
strictInjectionParameters: boolean,
kind: 'Directive' | 'Component',
): ts.Diagnostic[] | null {
let diagnostics: ts.Diagnostic[] | null = [];
const addDiagnostics = (more: ts.Diagnostic | ts.Diagnostic[] | null) => {
if (more === null) {
return;
} else if (diagnostics === null) {
diagnostics = Array.isArray(more) ? more : [more];
} else if (Array.isArray(more)) {
diagnostics.push(...more);
} else {
diagnostics.push(more);
}
};
const duplicateDeclarations = scopeRegistry.getDuplicateDeclarations(node);
if (duplicateDeclarations !== null) {
addDiagnostics(makeDuplicateDeclarationError(node, duplicateDeclarations, kind));
}
addDiagnostics(
checkInheritanceOfInjectable(
node,
injectableRegistry,
reflector,
evaluator,
strictInjectionParameters,
kind,
),
);
return diagnostics;
}
export function validateHostDirectives(
origin: ts.Expression,
hostDirectives: HostDirectiveMeta[],
metaReader: MetadataReader,
) {
const diagnostics: ts.DiagnosticWithLocation[] = [];
for (const current of hostDirectives) {
if (!isHostDirectiveMetaForGlobalMode(current)) {
throw new Error('Impossible state: diagnostics code path for local compilation');
}
const hostMeta = flattenInheritedDirectiveMetadata(metaReader, current.directive);
if (hostMeta === null) {
diagnostics.push(
makeDiagnostic(
ErrorCode.HOST_DIRECTIVE_INVALID,
current.directive.getOriginForDiagnostics(origin),
`${current.directive.debugName} must be a standalone directive to be used as a host directive`,
),
);
continue;
}
if (!hostMeta.isStandalone) {
diagnostics.push(
makeDiagnostic(
ErrorCode.HOST_DIRECTIVE_NOT_STANDALONE,
current.directive.getOriginForDiagnostics(origin),
`Host directive ${hostMeta.name} must be standalone`,
),
);
}
if (hostMeta.isComponent) {
diagnostics.push(
makeDiagnostic(
ErrorCode.HOST_DIRECTIVE_COMPONENT,
current.directive.getOriginForDiagnostics(origin),
`Host directive ${hostMeta.name} cannot be a component`,
),
);
}
const requiredInputNames = Array.from(hostMeta.inputs)
.filter((input) => input.required)
.map((input) => input.classPropertyName);
validateHostDirectiveMappings(
'input',
current,
hostMeta,
origin,
diagnostics,
requiredInputNames.length > 0 ? new Set(requiredInputNames) : null,
);
validateHostDirectiveMappings('output', current, hostMeta, origin, diagnostics, null);
}
return diagnostics;
} | {
"end_byte": 8589,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/src/diagnostics.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/src/diagnostics.ts_8591_17210 | function validateHostDirectiveMappings(
bindingType: 'input' | 'output',
hostDirectiveMeta: HostDirectiveMeta,
meta: DirectiveMeta,
origin: ts.Expression,
diagnostics: ts.DiagnosticWithLocation[],
requiredBindings: Set<ClassPropertyName> | null,
) {
if (!isHostDirectiveMetaForGlobalMode(hostDirectiveMeta)) {
throw new Error('Impossible state: diagnostics code path for local compilation');
}
const className = meta.name;
const hostDirectiveMappings =
bindingType === 'input' ? hostDirectiveMeta.inputs : hostDirectiveMeta.outputs;
const existingBindings = bindingType === 'input' ? meta.inputs : meta.outputs;
const exposedRequiredBindings = new Set<string>();
for (const publicName in hostDirectiveMappings) {
if (hostDirectiveMappings.hasOwnProperty(publicName)) {
const bindings = existingBindings.getByBindingPropertyName(publicName);
if (bindings === null) {
diagnostics.push(
makeDiagnostic(
ErrorCode.HOST_DIRECTIVE_UNDEFINED_BINDING,
hostDirectiveMeta.directive.getOriginForDiagnostics(origin),
`Directive ${className} does not have an ${bindingType} with a public name of ${publicName}.`,
),
);
} else if (requiredBindings !== null) {
for (const field of bindings) {
if (requiredBindings.has(field.classPropertyName)) {
exposedRequiredBindings.add(field.classPropertyName);
}
}
}
const remappedPublicName = hostDirectiveMappings[publicName];
const bindingsForPublicName = existingBindings.getByBindingPropertyName(remappedPublicName);
if (bindingsForPublicName !== null) {
for (const binding of bindingsForPublicName) {
if (binding.bindingPropertyName !== publicName) {
diagnostics.push(
makeDiagnostic(
ErrorCode.HOST_DIRECTIVE_CONFLICTING_ALIAS,
hostDirectiveMeta.directive.getOriginForDiagnostics(origin),
`Cannot alias ${bindingType} ${publicName} of host directive ${className} to ${remappedPublicName}, because it already has a different ${bindingType} with the same public name.`,
),
);
}
}
}
}
}
if (requiredBindings !== null && requiredBindings.size !== exposedRequiredBindings.size) {
const missingBindings: string[] = [];
for (const publicName of requiredBindings) {
if (!exposedRequiredBindings.has(publicName)) {
const name = existingBindings.getByClassPropertyName(publicName);
if (name) {
missingBindings.push(`'${name.bindingPropertyName}'`);
}
}
}
diagnostics.push(
makeDiagnostic(
ErrorCode.HOST_DIRECTIVE_MISSING_REQUIRED_BINDING,
hostDirectiveMeta.directive.getOriginForDiagnostics(origin),
`Required ${bindingType}${missingBindings.length === 1 ? '' : 's'} ${missingBindings.join(
', ',
)} from host directive ${className} must be exposed.`,
),
);
}
}
export function getUndecoratedClassWithAngularFeaturesDiagnostic(
node: ClassDeclaration,
): ts.Diagnostic {
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.`,
);
}
export function checkInheritanceOfInjectable(
node: ClassDeclaration,
injectableRegistry: InjectableClassRegistry,
reflector: ReflectionHost,
evaluator: PartialEvaluator,
strictInjectionParameters: boolean,
kind: 'Directive' | 'Component' | 'Pipe' | 'Injectable',
): ts.Diagnostic | null {
const classWithCtor = findInheritedCtor(node, injectableRegistry, reflector, evaluator);
if (classWithCtor === null || classWithCtor.isCtorValid) {
// The class does not inherit a constructor, or the inherited constructor is compatible
// with DI; no need to report a diagnostic.
return null;
}
if (!classWithCtor.isDecorated) {
// The inherited constructor exists in a class that does not have an Angular decorator.
// This is an error, as there won't be a factory definition available for DI to invoke
// the constructor.
return getInheritedUndecoratedCtorDiagnostic(node, classWithCtor.ref, kind);
}
if (isFromDtsFile(classWithCtor.ref.node)) {
// The inherited class is declared in a declaration file, in which case there is not enough
// information to detect invalid constructors as `@Inject()` metadata is not present in the
// declaration file. Consequently, we have to accept such occurrences, although they might
// still fail at runtime.
return null;
}
if (!strictInjectionParameters || isAbstractClassDeclaration(node)) {
// An invalid constructor is only reported as error under `strictInjectionParameters` and
// only for concrete classes; follow the same exclusions for derived types.
return null;
}
return getInheritedInvalidCtorDiagnostic(node, classWithCtor.ref, kind);
}
interface ClassWithCtor {
ref: Reference<ClassDeclaration>;
isCtorValid: boolean;
isDecorated: boolean;
}
export function findInheritedCtor(
node: ClassDeclaration,
injectableRegistry: InjectableClassRegistry,
reflector: ReflectionHost,
evaluator: PartialEvaluator,
): ClassWithCtor | null {
if (!reflector.isClass(node) || reflector.getConstructorParameters(node) !== null) {
// We should skip nodes that aren't classes. If a constructor exists, then no base class
// definition is required on the runtime side - it's legal to inherit from any class.
return null;
}
// The extends clause is an expression which can be as dynamic as the user wants. Try to
// evaluate it, but fall back on ignoring the clause if it can't be understood. This is a View
// Engine compatibility hack: View Engine ignores 'extends' expressions that it cannot understand.
let baseClass = readBaseClass(node, reflector, evaluator);
while (baseClass !== null) {
if (baseClass === 'dynamic') {
return null;
}
const injectableMeta = injectableRegistry.getInjectableMeta(baseClass.node);
if (injectableMeta !== null) {
if (injectableMeta.ctorDeps !== null) {
// The class has an Angular decorator with a constructor.
return {
ref: baseClass,
isCtorValid: injectableMeta.ctorDeps !== 'invalid',
isDecorated: true,
};
}
} else {
const baseClassConstructorParams = reflector.getConstructorParameters(baseClass.node);
if (baseClassConstructorParams !== null) {
// The class is not decorated, but it does have constructor. An undecorated class is only
// allowed to have a constructor without parameters, otherwise it is invalid.
return {
ref: baseClass,
isCtorValid: baseClassConstructorParams.length === 0,
isDecorated: false,
};
}
}
// Go up the chain and continue
baseClass = readBaseClass(baseClass.node, reflector, evaluator);
}
return null;
}
function getInheritedInvalidCtorDiagnostic(
node: ClassDeclaration,
baseClass: Reference,
kind: 'Directive' | 'Component' | 'Pipe' | 'Injectable',
) {
const baseClassName = baseClass.debugName;
return makeDiagnostic(
ErrorCode.INJECTABLE_INHERITS_INVALID_CONSTRUCTOR,
node.name,
`The ${kind.toLowerCase()} ${node.name.text} inherits its constructor from ${baseClassName}, ` +
`but the latter has a constructor parameter that is not compatible with dependency injection. ` +
`Either add an explicit constructor to ${node.name.text} or change ${baseClassName}'s constructor to ` +
`use parameters that are valid for DI.`,
);
}
function getInheritedUndecoratedCtorDiagnostic(
node: ClassDeclaration,
baseClass: Reference,
kind: 'Directive' | 'Component' | 'Pipe' | 'Injectable',
) {
const baseClassName = baseClass.debugName;
const baseNeedsDecorator =
kind === 'Component' || kind === 'Directive' ? 'Directive' : 'Injectable';
return makeDiagnostic(
ErrorCode.DIRECTIVE_INHERITS_UNDECORATED_CTOR,
node.name,
`The ${kind.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 @${baseNeedsDecorator} decorator ` +
`to ${baseClassName}, or add an explicit constructor to ${node.name.text}.`,
);
} | {
"end_byte": 17210,
"start_byte": 8591,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/src/diagnostics.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/src/diagnostics.ts_17212_18154 | /**
* Throws `FatalDiagnosticError` with error code `LOCAL_COMPILATION_UNRESOLVED_CONST`
* if the compilation mode is local and the value is not resolved due to being imported
* from external files. This is a common scenario for errors in local compilation mode,
* and so this helper can be used to quickly generate the relevant errors.
*
* @param nodeToHighlight Node to be highlighted in teh error message.
* Will default to value.node if not provided.
*/
export function assertLocalCompilationUnresolvedConst(
compilationMode: CompilationMode,
value: ResolvedValue,
nodeToHighlight: ts.Node | null,
errorMessage: string,
): void {
if (
compilationMode === CompilationMode.LOCAL &&
value instanceof DynamicValue &&
value.isFromUnknownIdentifier()
) {
throw new FatalDiagnosticError(
ErrorCode.LOCAL_COMPILATION_UNRESOLVED_CONST,
nodeToHighlight ?? value.node,
errorMessage,
);
}
} | {
"end_byte": 18154,
"start_byte": 17212,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/src/diagnostics.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/src/util.ts_0_8056 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Expression,
ExternalExpr,
FactoryTarget,
ParseLocation,
ParseSourceFile,
ParseSourceSpan,
R3CompiledExpression,
R3FactoryMetadata,
R3Reference,
ReadPropExpr,
Statement,
WrappedNodeExpr,
} from '@angular/compiler';
import ts from 'typescript';
import {
assertSuccessfulReferenceEmit,
ImportedFile,
ImportFlags,
ModuleResolver,
Reference,
ReferenceEmitter,
} from '../../../imports';
import {attachDefaultImportDeclaration} from '../../../imports/src/default';
import {ForeignFunctionResolver, PartialEvaluator} from '../../../partial_evaluator';
import {
ClassDeclaration,
Decorator,
Import,
ImportedTypeValueReference,
LocalTypeValueReference,
ReflectionHost,
TypeValueReference,
TypeValueReferenceKind,
} from '../../../reflection';
import {CompileResult} from '../../../transform';
/** Module name of the framework core. */
export const CORE_MODULE = '@angular/core';
/**
* Convert a `TypeValueReference` to an `Expression` which refers to the type as a value.
*
* Local references are converted to a `WrappedNodeExpr` of the TypeScript expression, and non-local
* references are converted to an `ExternalExpr`. Note that this is only valid in the context of the
* file in which the `TypeValueReference` originated.
*/
export function valueReferenceToExpression(
valueRef: LocalTypeValueReference | ImportedTypeValueReference,
): Expression;
export function valueReferenceToExpression(valueRef: TypeValueReference): Expression | null;
export function valueReferenceToExpression(valueRef: TypeValueReference): Expression | null {
if (valueRef.kind === TypeValueReferenceKind.UNAVAILABLE) {
return null;
} else if (valueRef.kind === TypeValueReferenceKind.LOCAL) {
const expr = new WrappedNodeExpr(valueRef.expression);
if (valueRef.defaultImportStatement !== null) {
attachDefaultImportDeclaration(expr, valueRef.defaultImportStatement);
}
return expr;
} else {
let importExpr: Expression = 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;
}
}
export function toR3Reference(
origin: ts.Node,
ref: Reference,
context: ts.SourceFile,
refEmitter: ReferenceEmitter,
): R3Reference {
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,
};
}
export function isAngularCore(decorator: Decorator): decorator is Decorator & {import: Import} {
return decorator.import !== null && decorator.import.from === CORE_MODULE;
}
export function isAngularCoreReference(reference: Reference, symbolName: string): boolean {
return reference.ownedByModuleGuess === CORE_MODULE && reference.debugName === symbolName;
}
export function findAngularDecorator(
decorators: Decorator[],
name: string,
isCore: boolean,
): Decorator | undefined {
return decorators.find((decorator) => isAngularDecorator(decorator, name, isCore));
}
export function isAngularDecorator(decorator: Decorator, name: string, isCore: boolean): boolean {
if (isCore) {
return decorator.name === name;
} else if (isAngularCore(decorator)) {
return decorator.import.name === name;
}
return false;
}
export function getAngularDecorators(
decorators: Decorator[],
names: readonly string[],
isCore: boolean,
) {
return decorators.filter((decorator) => {
const name = isCore ? decorator.name : decorator.import?.name;
if (name === undefined || !names.includes(name)) {
return false;
}
return isCore || isAngularCore(decorator);
});
}
/**
* Unwrap a `ts.Expression`, removing outer type-casts or parentheses until the expression is in its
* lowest level form.
*
* For example, the expression "(foo as Type)" unwraps to "foo".
*/
export function unwrapExpression(node: ts.Expression): ts.Expression {
while (ts.isAsExpression(node) || ts.isParenthesizedExpression(node)) {
node = node.expression;
}
return node;
}
function expandForwardRef(arg: ts.Expression): ts.Expression | null {
arg = unwrapExpression(arg);
if (!ts.isArrowFunction(arg) && !ts.isFunctionExpression(arg)) {
return null;
}
const body = arg.body;
// Either the body is a ts.Expression directly, or a block with a single return statement.
if (ts.isBlock(body)) {
// Block body - look for a single return statement.
if (body.statements.length !== 1) {
return null;
}
const stmt = body.statements[0];
if (!ts.isReturnStatement(stmt) || stmt.expression === undefined) {
return null;
}
return stmt.expression;
} else {
// Shorthand body - return as an expression.
return body;
}
}
/**
* If the given `node` is a forwardRef() expression then resolve its inner value, otherwise return
* `null`.
*
* @param node the forwardRef() expression to resolve
* @param reflector a ReflectionHost
* @returns the resolved expression, if the original expression was a forwardRef(), or `null`
* otherwise.
*/
export function tryUnwrapForwardRef(
node: ts.Expression,
reflector: ReflectionHost,
): ts.Expression | null {
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;
}
/**
* A foreign function resolver for `staticallyResolve` which unwraps forwardRef() expressions.
*
* @param ref a Reference to the declaration of the function being called (which might be
* forwardRef)
* @param args the arguments to the invocation of the forwardRef expression
* @returns an unwrapped argument if `ref` pointed to forwardRef, or null otherwise
*/
export const forwardRefResolver: ForeignFunctionResolver = (
fn,
callExpr,
resolve,
unresolvable,
) => {
if (!isAngularCoreReference(fn, 'forwardRef') || callExpr.arguments.length !== 1) {
return unresolvable;
}
const expanded = expandForwardRef(callExpr.arguments[0]);
if (expanded !== null) {
return resolve(expanded);
} else {
return unresolvable;
}
};
/**
* Combines an array of resolver functions into a one.
* @param resolvers Resolvers to be combined.
*/
export function combineResolvers(resolvers: ForeignFunctionResolver[]): ForeignFunctionResolver {
return (fn, callExpr, resolve, unresolvable) => {
for (const resolver of resolvers) {
const resolved = resolver(fn, callExpr, resolve, unresolvable);
if (resolved !== unresolvable) {
return resolved;
}
}
return unresolvable;
};
}
export function isExpressionForwardReference(
expr: Expression,
context: ts.Node,
contextSource: ts.SourceFile,
): boolean {
if (isWrappedTsNodeExpr(expr)) {
const node = ts.getOriginalNode(expr.node);
return node.getSourceFile() === contextSource && context.pos < node.pos;
} else {
return false;
}
}
export function isWrappedTsNodeExpr(expr: Expression): expr is WrappedNodeExpr<ts.Node> {
return expr instanceof WrappedNodeExpr;
} | {
"end_byte": 8056,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/src/util.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/src/util.ts_8058_16136 | export function readBaseClass(
node: ClassDeclaration,
reflector: ReflectionHost,
evaluator: PartialEvaluator,
): Reference<ClassDeclaration> | 'dynamic' | null {
const baseExpression = reflector.getBaseClassExpression(node);
if (baseExpression !== null) {
const baseClass = evaluator.evaluate(baseExpression);
if (baseClass instanceof Reference && reflector.isClass(baseClass.node)) {
return baseClass as Reference<ClassDeclaration>;
} else {
return 'dynamic';
}
}
return null;
}
const parensWrapperTransformerFactory: ts.TransformerFactory<ts.Expression> = (
context: ts.TransformationContext,
) => {
const visitor: ts.Visitor = (node: ts.Node): ts.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.Expression) => ts.visitEachChild(node, visitor, context);
};
/**
* Wraps all functions in a given expression in parentheses. This is needed to avoid problems
* where Tsickle annotations added between analyse and transform phases in Angular may trigger
* automatic semicolon insertion, e.g. if a function is the expression in a `return` statement.
* More
* info can be found in Tsickle source code here:
* https://github.com/angular/tsickle/blob/d7974262571c8a17d684e5ba07680e1b1993afdd/src/jsdoc_transformer.ts#L1021
*
* @param expression Expression where functions should be wrapped in parentheses
*/
export function wrapFunctionExpressionsInParens(expression: ts.Expression): ts.Expression {
return ts.transform(expression, [parensWrapperTransformerFactory]).transformed[0];
}
/**
* Resolves the given `rawProviders` into `ClassDeclarations` and returns
* a set containing those that are known to require a factory definition.
* @param rawProviders Expression that declared the providers array in the source.
*/
export function resolveProvidersRequiringFactory(
rawProviders: ts.Expression,
reflector: ReflectionHost,
evaluator: PartialEvaluator,
): Set<Reference<ClassDeclaration>> {
const providers = new Set<Reference<ClassDeclaration>>();
const resolvedProviders = evaluator.evaluate(rawProviders);
if (!Array.isArray(resolvedProviders)) {
return providers;
}
resolvedProviders.forEach(function processProviders(provider) {
let tokenClass: Reference | null = null;
if (Array.isArray(provider)) {
// If we ran into an array, recurse into it until we've resolve all the classes.
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;
}
}
// TODO(alxhub): there was a bug where `getConstructorParameters` would return `null` for a
// class in a .d.ts file, always, even if the class had a constructor. This was fixed for
// `getConstructorParameters`, but that fix causes more classes to be recognized here as needing
// provider checks, which is a breaking change in g3. Avoid this breakage for now by skipping
// classes from .d.ts files here directly, until g3 can be cleaned up.
if (
tokenClass !== null &&
!tokenClass.node.getSourceFile().isDeclarationFile &&
reflector.isClass(tokenClass.node)
) {
const constructorParameters = reflector.getConstructorParameters(tokenClass.node);
// Note that we only want to capture providers with a non-trivial constructor,
// because they're the ones that might be using DI and need to be decorated.
if (constructorParameters !== null && constructorParameters.length > 0) {
providers.add(tokenClass as Reference<ClassDeclaration>);
}
}
});
return providers;
}
/**
* Create an R3Reference for a class.
*
* The `value` is the exported declaration of the class from its source file.
* The `type` is an expression that would be used in the typings (.d.ts) files.
*/
export function wrapTypeReference(reflector: ReflectionHost, clazz: ClassDeclaration): R3Reference {
const value = new WrappedNodeExpr(clazz.name);
const type = value;
return {value, type};
}
/** Creates a ParseSourceSpan for a TypeScript node. */
export function createSourceSpan(node: ts.Node): ParseSourceSpan {
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);
// +1 because values are zero-indexed.
return new ParseSourceSpan(
new ParseLocation(parseSf, startOffset, startLine + 1, startCol + 1),
new ParseLocation(parseSf, endOffset, endLine + 1, endCol + 1),
);
}
/**
* Collate the factory and definition compiled results into an array of CompileResult objects.
*/
export function compileResults(
fac: CompileResult,
def: R3CompiledExpression,
metadataStmt: Statement | null,
propName: string,
additionalFields: CompileResult[] | null,
deferrableImports: Set<ts.ImportDeclaration> | null,
debugInfo: Statement | null = null,
hmrInitializer: Statement | null = null,
): CompileResult[] {
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;
}
export function toFactoryMetadata(
meta: Omit<R3FactoryMetadata, 'target'>,
target: FactoryTarget,
): R3FactoryMetadata {
return {
name: meta.name,
type: meta.type,
typeArgumentCount: meta.typeArgumentCount,
deps: meta.deps,
target,
};
}
export function resolveImportedFile(
moduleResolver: ModuleResolver,
importedFile: ImportedFile,
expr: Expression,
origin: ts.SourceFile,
): ts.SourceFile | null {
// If `importedFile` is not 'unknown' then it accurately reflects the source file that is
// being imported.
if (importedFile !== 'unknown') {
return importedFile;
}
// Otherwise `expr` has to be inspected to determine the file that is being imported. If `expr`
// is not an `ExternalExpr` then it does not correspond with an import, so return null in that
// case.
if (!(expr instanceof ExternalExpr)) {
return null;
}
// Figure out what file is being imported.
return moduleResolver.resolveModule(expr.value.moduleName!, origin.fileName);
}
/**
* Determines the most appropriate expression for diagnostic reporting purposes. If `expr` is
* contained within `container` then `expr` is used as origin node, otherwise `container` itself is
* used.
*/
export function getOriginNodeForDiagnostics(
expr: ts.Expression,
container: ts.Expression,
): ts.Expression {
const nodeSf = expr.getSourceFile();
const exprSf = container.getSourceFile();
if (nodeSf === exprSf && expr.pos >= container.pos && expr.end <= container.end) {
// `expr` occurs within the same source file as `container` and is contained within it, so
// `expr` is appropriate to use as origin node for diagnostics.
return expr;
} else {
return container;
}
}
export function isAbstractClassDeclaration(clazz: ClassDeclaration): boolean {
return ts.canHaveModifiers(clazz) && clazz.modifiers !== undefined
? clazz.modifiers.some((mod) => mod.kind === ts.SyntaxKind.AbstractKeyword)
: false;
} | {
"end_byte": 16136,
"start_byte": 8058,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/src/util.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/src/jit_declaration_registry.ts_0_507 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ClassDeclaration} from '../../../reflection';
/**
* Registry that keeps track of Angular declarations that are explicitly
* marked for JIT compilation and are skipping compilation by trait handlers.
*/
export class JitDeclarationRegistry {
jitDeclarations = new Set<ClassDeclaration>();
}
| {
"end_byte": 507,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/src/jit_declaration_registry.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/common/src/metadata.ts_0_7992 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ArrowFunctionExpr,
Expression,
LiteralArrayExpr,
LiteralExpr,
literalMap,
R3ClassMetadata,
WrappedNodeExpr,
} from '@angular/compiler';
import ts from 'typescript';
import {
CtorParameter,
DeclarationNode,
Decorator,
ReflectionHost,
TypeValueReferenceKind,
} from '../../../reflection';
import {valueReferenceToExpression, wrapFunctionExpressionsInParens} from './util';
/**
* Given a class declaration, generate a call to `setClassMetadata` with the Angular metadata
* present on the class or its member fields. An ngDevMode guard is used to allow the call to be
* tree-shaken away, as the `setClassMetadata` invocation is only needed for testing purposes.
*
* If no such metadata is present, this function returns `null`. Otherwise, the call is returned
* as a `Statement` for inclusion along with the class.
*/
export function extractClassMetadata(
clazz: DeclarationNode,
reflection: ReflectionHost,
isCore: boolean,
annotateForClosureCompiler?: boolean,
angularDecoratorTransform: (dec: Decorator) => Decorator = (dec) => dec,
): R3ClassMetadata | null {
if (!reflection.isClass(clazz)) {
return null;
}
const id = clazz.name;
// Reflect over the class decorators. If none are present, or those that are aren't from
// Angular, then return null. Otherwise, turn them into metadata.
const classDecorators = reflection.getDecoratorsOfDeclaration(clazz);
if (classDecorators === null) {
return null;
}
const ngClassDecorators = classDecorators
.filter((dec) => isAngularDecorator(dec, isCore))
.map((decorator) =>
decoratorToMetadata(angularDecoratorTransform(decorator), annotateForClosureCompiler),
)
// Since the `setClassMetadata` call is intended to be emitted after the class
// declaration, we have to strip references to the existing identifiers or
// TypeScript might generate invalid code when it emits to JS. In particular
// this can break when emitting a class to ES5 which has a custom decorator
// and is referenced inside of its own metadata (see #39509 for more information).
.map((decorator) => removeIdentifierReferences(decorator, id.text));
if (ngClassDecorators.length === 0) {
return null;
}
const metaDecorators = new WrappedNodeExpr(
ts.factory.createArrayLiteralExpression(ngClassDecorators),
);
// Convert the constructor parameters to metadata, passing null if none are present.
let metaCtorParameters: Expression | null = null;
const classCtorParameters = reflection.getConstructorParameters(clazz);
if (classCtorParameters !== null) {
const ctorParameters = classCtorParameters.map((param) =>
ctorParameterToMetadata(param, isCore),
);
metaCtorParameters = new ArrowFunctionExpr([], new LiteralArrayExpr(ctorParameters));
}
// Do the same for property decorators.
let metaPropDecorators: Expression | null = null;
const classMembers = reflection
.getMembersOfClass(clazz)
.filter(
(member) => !member.isStatic && member.decorators !== null && member.decorators.length > 0,
);
const duplicateDecoratedMemberNames = classMembers
.map((member) => member.name)
.filter((name, i, arr) => arr.indexOf(name) < i);
if (duplicateDecoratedMemberNames.length > 0) {
// This should theoretically never happen, because the only way to have duplicate instance
// member names is getter/setter pairs and decorators cannot appear in both a getter and the
// corresponding setter.
throw new Error(
`Duplicate decorated properties found on class '${clazz.name.text}': ` +
duplicateDecoratedMemberNames.join(', '),
);
}
const decoratedMembers = classMembers.map((member) =>
classMemberToMetadata(member.nameNode ?? member.name, member.decorators!, isCore),
);
if (decoratedMembers.length > 0) {
metaPropDecorators = new WrappedNodeExpr(
ts.factory.createObjectLiteralExpression(decoratedMembers),
);
}
return {
type: new WrappedNodeExpr(id),
decorators: metaDecorators,
ctorParameters: metaCtorParameters,
propDecorators: metaPropDecorators,
};
}
/**
* Convert a reflected constructor parameter to metadata.
*/
function ctorParameterToMetadata(param: CtorParameter, isCore: boolean): Expression {
// Parameters sometimes have a type that can be referenced. If so, then use it, otherwise
// its type is undefined.
const type =
param.typeValueReference.kind !== TypeValueReferenceKind.UNAVAILABLE
? valueReferenceToExpression(param.typeValueReference)
: new LiteralExpr(undefined);
const mapEntries: {key: string; value: Expression; quoted: false}[] = [
{key: 'type', value: type, quoted: false},
];
// If the parameter has decorators, include the ones from Angular.
if (param.decorators !== null) {
const ngDecorators = param.decorators
.filter((dec) => isAngularDecorator(dec, isCore))
.map((decorator: Decorator) => decoratorToMetadata(decorator));
const value = new WrappedNodeExpr(ts.factory.createArrayLiteralExpression(ngDecorators));
mapEntries.push({key: 'decorators', value, quoted: false});
}
return literalMap(mapEntries);
}
/**
* Convert a reflected class member to metadata.
*/
function classMemberToMetadata(
name: ts.PropertyName | string,
decorators: Decorator[],
isCore: boolean,
): ts.PropertyAssignment {
const ngDecorators = decorators
.filter((dec) => isAngularDecorator(dec, isCore))
.map((decorator: Decorator) => decoratorToMetadata(decorator));
const decoratorMeta = ts.factory.createArrayLiteralExpression(ngDecorators);
return ts.factory.createPropertyAssignment(name, decoratorMeta);
}
/**
* Convert a reflected decorator to metadata.
*/
function decoratorToMetadata(
decorator: Decorator,
wrapFunctionsInParens?: boolean,
): ts.ObjectLiteralExpression {
if (decorator.identifier === null) {
throw new Error('Illegal state: synthesized decorator cannot be emitted in class metadata.');
}
// Decorators have a type.
const properties: ts.ObjectLiteralElementLike[] = [
ts.factory.createPropertyAssignment('type', decorator.identifier),
];
// Sometimes they have arguments.
if (decorator.args !== null && decorator.args.length > 0) {
const args = decorator.args.map((arg) => {
return wrapFunctionsInParens ? wrapFunctionExpressionsInParens(arg) : arg;
});
properties.push(
ts.factory.createPropertyAssignment('args', ts.factory.createArrayLiteralExpression(args)),
);
}
return ts.factory.createObjectLiteralExpression(properties, true);
}
/**
* Whether a given decorator should be treated as an Angular decorator.
*
* Either it's used in @angular/core, or it's imported from there.
*/
function isAngularDecorator(decorator: Decorator, isCore: boolean): boolean {
return isCore || (decorator.import !== null && decorator.import.from === '@angular/core');
}
/**
* Recursively recreates all of the `Identifier` descendant nodes with a particular name inside
* of an AST node, thus removing any references to them. Useful if a particular node has to be
* taken from one place any emitted to another one exactly as it has been written.
*/
export function removeIdentifierReferences<T extends ts.Node>(
node: T,
names: string | Set<string>,
): T {
const result = ts.transform(node, [
(context) => (root) =>
ts.visitNode(root, function walk(current: ts.Node): T {
return (
ts.isIdentifier(current) &&
(typeof names === 'string' ? current.text === names : names.has(current.text))
? ts.factory.createIdentifier(current.text)
: ts.visitEachChild(current, walk, context)
) as T;
}) as T,
]);
return result.transformed[0];
}
| {
"end_byte": 7992,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/common/src/metadata.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/README.md_0_362 | # What is the 'annotations/directive' package?
This package implements the `DirectiveDecoratorHandler`, which processes and compiles `@Directive`-decorated classes.
Directive compilation is also the base of component compilation, and so this package exports a number of utilities related to directive compilation for the 'annotations/component' package to use. | {
"end_byte": 362,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/README.md"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/BUILD.bazel_0_940 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "directive",
srcs = ["index.ts"] + glob([
"src/**/*.ts",
]),
deps = [
"//packages/compiler",
"//packages/compiler-cli/src/ngtsc/annotations/common",
"//packages/compiler-cli/src/ngtsc/diagnostics",
"//packages/compiler-cli/src/ngtsc/imports",
"//packages/compiler-cli/src/ngtsc/incremental/semantic_graph",
"//packages/compiler-cli/src/ngtsc/metadata",
"//packages/compiler-cli/src/ngtsc/partial_evaluator",
"//packages/compiler-cli/src/ngtsc/perf",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/scope",
"//packages/compiler-cli/src/ngtsc/transform",
"//packages/compiler-cli/src/ngtsc/translator",
"@npm//@types/node",
"@npm//typescript",
],
)
| {
"end_byte": 940,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/index.ts_0_536 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {DirectiveDecoratorHandler} from './src/handler';
export {DirectiveSymbol} from './src/symbol';
export * from './src/shared';
export * from './src/input_function';
export * from './src/output_function';
export * from './src/query_functions';
export * from './src/model_function';
export * from './src/initializer_functions';
| {
"end_byte": 536,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/index.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/test/directive_spec.ts_0_7823 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
CssSelector,
DirectiveMeta as T2DirectiveMeta,
parseTemplate,
R3TargetBinder,
SelectorMatcher,
TmplAstElement,
} from '@angular/compiler';
import ts from 'typescript';
import {absoluteFrom} from '../../../file_system';
import {runInEachFileSystem} from '../../../file_system/testing';
import {ImportedSymbolsTracker, ReferenceEmitter} from '../../../imports';
import {CompoundMetadataReader, DtsMetadataReader, LocalMetadataRegistry} from '../../../metadata';
import {PartialEvaluator} from '../../../partial_evaluator';
import {NOOP_PERF_RECORDER} from '../../../perf';
import {
ClassDeclaration,
isNamedClassDeclaration,
TypeScriptReflectionHost,
} from '../../../reflection';
import {LocalModuleScopeRegistry, MetadataDtsModuleScopeResolver} from '../../../scope';
import {getDeclaration, makeProgram} from '../../../testing';
import {CompilationMode} from '../../../transform';
import {
InjectableClassRegistry,
JitDeclarationRegistry,
NoopReferencesRegistry,
} from '../../common';
import {DirectiveDecoratorHandler} from '../index';
runInEachFileSystem(() => {
let _: typeof absoluteFrom;
beforeEach(() => (_ = absoluteFrom));
describe('DirectiveDecoratorHandler', () => {
it('should use the `ReflectionHost` to detect class inheritance', () => {
const {program} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Directive: any;',
},
{
name: _('/entry.ts'),
contents: `
import {Directive} from '@angular/core';
@Directive({selector: 'test-dir-1'})
export class TestDir1 {}
@Directive({selector: 'test-dir-2'})
export class TestDir2 {}
`,
},
]);
const analysis1 = analyzeDirective(program, 'TestDir1', /*hasBaseClass*/ false);
expect(analysis1.meta.usesInheritance).toBe(false);
const analysis2 = analyzeDirective(program, 'TestDir2', /*hasBaseClass*/ true);
expect(analysis2.meta.usesInheritance).toBe(true);
});
it('should record the source span of a Directive class type', () => {
const src = `
import {Directive} from '@angular/core';
@Directive({selector: 'test-dir'})
export class TestDir {}
`;
const {program} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Directive: any;',
},
{
name: _('/entry.ts'),
contents: src,
},
]);
const analysis = analyzeDirective(program, 'TestDir');
const span = analysis.meta.typeSourceSpan;
expect(span.toString()).toBe('TestDir');
expect(span.start.toString()).toContain('/entry.ts@5:22');
expect(span.end.toString()).toContain('/entry.ts@5:29');
});
it('should produce metadata compatible with template binding', () => {
const src = `
import {Directive, Input} from '@angular/core';
@Directive({selector: '[dir]'})
export class TestDir {
@Input('propName')
fieldName: string;
}
`;
const {program} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Directive: any; export const Input: any;',
},
{
name: _('/entry.ts'),
contents: src,
},
]);
const analysis = analyzeDirective(program, 'TestDir');
const matcher = new SelectorMatcher<T2DirectiveMeta[]>();
const dirMeta: T2DirectiveMeta = {
exportAs: null,
inputs: analysis.inputs,
outputs: analysis.outputs,
isComponent: false,
name: 'Dir',
selector: '[dir]',
isStructural: false,
animationTriggerNames: null,
ngContentSelectors: null,
preserveWhitespaces: false,
};
matcher.addSelectables(CssSelector.parse('[dir]'), [dirMeta]);
const {nodes} = parseTemplate('<div dir [propName]="expr"></div>', 'unimportant.html');
const binder = new R3TargetBinder(matcher).bind({template: nodes});
const propBinding = (nodes[0] as TmplAstElement).inputs[0];
const propBindingConsumer = binder.getConsumerOfBinding(propBinding);
// Assert that the consumer of the binding is the directive, which means that the metadata
// fed into the SelectorMatcher was compatible with the binder, and did not confuse property
// and field names.
expect(propBindingConsumer).toBe(dirMeta);
});
it('should identify a structural directive', () => {
const src = `
import {Directive, TemplateRef} from '@angular/core';
@Directive({selector: 'test-dir'})
export class TestDir {
constructor(private ref: TemplateRef) {}
}
`;
const {program} = makeProgram([
{
name: _('/node_modules/@angular/core/index.d.ts'),
contents: 'export const Directive: any; export declare class TemplateRef {}',
},
{
name: _('/entry.ts'),
contents: src,
},
]);
const analysis = analyzeDirective(program, 'TestDir');
expect(analysis.isStructural).toBeTrue();
});
});
// Helpers
function analyzeDirective(program: ts.Program, dirName: string, hasBaseClass: boolean = false) {
class TestReflectionHost extends TypeScriptReflectionHost {
constructor(checker: ts.TypeChecker) {
super(checker);
}
override hasBaseClass(_class: ClassDeclaration): boolean {
return hasBaseClass;
}
}
const checker = program.getTypeChecker();
const reflectionHost = new TestReflectionHost(checker);
const evaluator = new PartialEvaluator(reflectionHost, checker, /*dependencyTracker*/ null);
const metaReader = new LocalMetadataRegistry();
const dtsReader = new DtsMetadataReader(checker, reflectionHost);
const refEmitter = new ReferenceEmitter([]);
const referenceRegistry = new NoopReferencesRegistry();
const scopeRegistry = new LocalModuleScopeRegistry(
metaReader,
new CompoundMetadataReader([metaReader, dtsReader]),
new MetadataDtsModuleScopeResolver(dtsReader, null),
refEmitter,
null,
);
const injectableRegistry = new InjectableClassRegistry(reflectionHost, /* isCore */ false);
const importTracker = new ImportedSymbolsTracker();
const jitDeclarationRegistry = new JitDeclarationRegistry();
const handler = new DirectiveDecoratorHandler(
reflectionHost,
evaluator,
scopeRegistry,
scopeRegistry,
metaReader,
injectableRegistry,
refEmitter,
referenceRegistry,
/*isCore*/ false,
/*strictCtorDeps*/ false,
/*semanticDepGraphUpdater*/ null,
/*annotateForClosureCompiler*/ false,
NOOP_PERF_RECORDER,
importTracker,
/*includeClassMetadata*/ true,
/*compilationMode */ CompilationMode.FULL,
jitDeclarationRegistry,
/* strictStandalone */ false,
);
const DirNode = getDeclaration(program, _('/entry.ts'), dirName, isNamedClassDeclaration);
const detected = handler.detect(DirNode, reflectionHost.getDecoratorsOfDeclaration(DirNode));
if (detected === undefined) {
throw new Error(`Failed to recognize @Directive (${dirName}).`);
}
const {analysis} = handler.analyze(DirNode, detected.metadata);
if (analysis === undefined) {
throw new Error(`Failed to analyze @Directive (${dirName}).`);
}
return analysis;
}
});
| {
"end_byte": 7823,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/test/directive_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/test/BUILD.bazel_0_1210 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "test_lib",
testonly = True,
srcs = glob([
"**/*.ts",
]),
deps = [
"//packages:types",
"//packages/compiler",
"//packages/compiler-cli/src/ngtsc/annotations/common",
"//packages/compiler-cli/src/ngtsc/annotations/directive",
"//packages/compiler-cli/src/ngtsc/diagnostics",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/file_system/testing",
"//packages/compiler-cli/src/ngtsc/imports",
"//packages/compiler-cli/src/ngtsc/metadata",
"//packages/compiler-cli/src/ngtsc/partial_evaluator",
"//packages/compiler-cli/src/ngtsc/perf",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/scope",
"//packages/compiler-cli/src/ngtsc/testing",
"//packages/compiler-cli/src/ngtsc/transform",
"@npm//typescript",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node_no_angular"],
deps = [
":test_lib",
],
)
| {
"end_byte": 1210,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/test/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/test/initializer_functions_spec.ts_0_875 | /*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {ErrorCode, FatalDiagnosticError} from '../../../diagnostics';
import {absoluteFrom} from '../../../file_system';
import {runInEachFileSystem} from '../../../file_system/testing';
import {ImportedSymbolsTracker} from '../../../imports';
import {ClassMember, ClassMemberAccessLevel, TypeScriptReflectionHost} from '../../../reflection';
import {reflectClassMember} from '../../../reflection/src/typescript';
import {makeProgram} from '../../../testing';
import {validateAccessOfInitializerApiMember} from '../src/initializer_function_access';
import {InitializerApiFunction, tryParseInitializerApi} from '../src/initializer_functions'; | {
"end_byte": 875,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/test/initializer_functions_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/test/initializer_functions_spec.ts_877_9484 | runInEachFileSystem(() => {
const modelApi: InitializerApiFunction = {
functionName: 'model',
owningModule: '@angular/core',
allowedAccessLevels: [ClassMemberAccessLevel.PublicWritable],
};
describe('initializer function detection', () => {
it('should identify a non-required function that is imported directly', () => {
const {member, reflector, importTracker} = setup(`
import {Directive, model} from '@angular/core';
@Directive()
export class Dir {
test = model(1);
}
`);
const result = tryParseInitializerApi([modelApi], member.value!, reflector, importTracker);
expect(result).toEqual({
api: modelApi,
isRequired: false,
call: jasmine.objectContaining({kind: ts.SyntaxKind.CallExpression}),
});
});
it('should check for multiple initializer APIs', () => {
const {member, reflector, importTracker} = setup(`
import {Directive, model} from '@angular/core';
@Directive()
export class Dir {
test = model(1);
}
`);
const result = tryParseInitializerApi(
[
{
functionName: 'input',
owningModule: '@angular/core',
allowedAccessLevels: [ClassMemberAccessLevel.PublicWritable],
},
modelApi,
],
member.value!,
reflector,
importTracker,
);
expect(result).toEqual({
api: modelApi,
isRequired: false,
call: jasmine.objectContaining({kind: ts.SyntaxKind.CallExpression}),
});
});
it('should support initializer APIs from different modules', () => {
const {member, reflector, importTracker} = setup(`
import {Directive} from '@angular/core';
import {outputFromObservable} from '@angular/core/rxjs-interop';
@Directive()
export class Dir {
test = outputFromObservable(1);
}
`);
const result = tryParseInitializerApi(
[
modelApi,
{
functionName: 'outputFromObservable',
owningModule: '@angular/core/rxjs-interop',
allowedAccessLevels: [ClassMemberAccessLevel.PublicWritable],
},
],
member.value!,
reflector,
importTracker,
);
expect(result).toEqual({
api: {
functionName: 'outputFromObservable',
owningModule: '@angular/core/rxjs-interop',
allowedAccessLevels: [ClassMemberAccessLevel.PublicWritable],
},
isRequired: false,
call: jasmine.objectContaining({kind: ts.SyntaxKind.CallExpression}),
});
});
it('should identify a required function that is imported directly', () => {
const {member, reflector, importTracker} = setup(`
import {Directive, model} from '@angular/core';
@Directive()
export class Dir {
test = model.required();
}
`);
const result = tryParseInitializerApi([modelApi], member.value!, reflector, importTracker);
expect(result).toEqual({
api: modelApi,
isRequired: true,
call: jasmine.objectContaining({kind: ts.SyntaxKind.CallExpression}),
});
});
it('should identify a non-required function that is aliased', () => {
const {member, reflector, importTracker} = setup(`
import {Directive, model as alias} from '@angular/core';
@Directive()
export class Dir {
test = alias(1);
}
`);
const result = tryParseInitializerApi([modelApi], member.value!, reflector, importTracker);
expect(result).toEqual({
api: modelApi,
isRequired: false,
call: jasmine.objectContaining({kind: ts.SyntaxKind.CallExpression}),
});
});
it('should identify a required function that is aliased', () => {
const {member, reflector, importTracker} = setup(`
import {Directive, model as alias} from '@angular/core';
@Directive()
export class Dir {
test = alias.required();
}
`);
const result = tryParseInitializerApi([modelApi], member.value!, reflector, importTracker);
expect(result).toEqual({
api: modelApi,
isRequired: true,
call: jasmine.objectContaining({kind: ts.SyntaxKind.CallExpression}),
});
});
it('should identify a non-required function that is imported via namespace import', () => {
const {member, reflector, importTracker} = setup(`
import * as core from '@angular/core';
@core.Directive()
export class Dir {
test = core.model(1);
}
`);
const result = tryParseInitializerApi([modelApi], member.value!, reflector, importTracker);
expect(result).toEqual({
api: modelApi,
isRequired: false,
call: jasmine.objectContaining({kind: ts.SyntaxKind.CallExpression}),
});
});
it('should identify a required function that is imported via namespace import', () => {
const {member, reflector, importTracker} = setup(`
import * as core from '@angular/core';
@core.Directive()
export class Dir {
test = core.model.required();
}
`);
const result = tryParseInitializerApi([modelApi], member.value!, reflector, importTracker);
expect(result).toEqual({
api: modelApi,
isRequired: true,
call: jasmine.objectContaining({kind: ts.SyntaxKind.CallExpression}),
});
});
it('should not identify a valid core function that is not being checked for', () => {
const {member, reflector, importTracker} = setup(`
import {Directive, input} from '@angular/core';
@Directive()
export class Dir {
test = input(1);
}
`);
const result = tryParseInitializerApi([modelApi], member.value!, reflector, importTracker);
expect(result).toBe(null);
});
it('should not identify a function coming from a different module', () => {
const {member, reflector, importTracker} = setup(`
import {Directive} from '@angular/core';
import {model} from '@not-angular/core';
@Directive()
export class Dir {
test = model(1);
}
`);
const result = tryParseInitializerApi([modelApi], member.value!, reflector, importTracker);
expect(result).toBe(null);
});
it('should not identify an invalid call on a core function', () => {
const {member, reflector, importTracker} = setup(`
import {Directive, model} from '@angular/core';
@Directive()
export class Dir {
test = model.unknown();
}
`);
const result = tryParseInitializerApi([modelApi], member.value!, reflector, importTracker);
expect(result).toBe(null);
});
it('should not identify an invalid call on a core function through a namespace import', () => {
const {member, reflector, importTracker} = setup(`
import {Directive} from '@angular/core';
import * as core from '@angular/core';
@Directive()
export class Dir {
test = core.model.unknown();
}
`);
const result = tryParseInitializerApi([modelApi], member.value!, reflector, importTracker);
expect(result).toBe(null);
});
it('should identify shadowed declarations', () => {
const {member, reflector, importTracker} = setup(`
import {Directive, model} from '@angular/core';
function wrapper() {
function model(value: number): any {}
@Directive()
class Dir {
test = model(1);
}
}
`);
const result = tryParseInitializerApi([modelApi], member.value!, reflector, importTracker);
expect(result).toBe(null);
});
});
it('should identify an initializer function in a file containing an import whose name overlaps with an object prototype member', () => {
const {member, reflector, importTracker} = setup(`
import {Directive, model} from '@angular/core';
import {toString} from '@unknown/utils';
@Directive()
export class Dir {
test = model(1);
}
`);
const result = tryParseInitializerApi([modelApi], member.value!, reflector, importTracker);
expect(result).toEqual({
api: modelApi,
isRequired: false,
call: jasmine.objectContaining({kind: ts.SyntaxKind.CallExpression}),
});
}); | {
"end_byte": 9484,
"start_byte": 877,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/test/initializer_functions_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/test/initializer_functions_spec.ts_9488_15012 | describe('`validateAccessOfInitializerApiMember`', () => {
it('should report errors if a private field is used, but not allowed', () => {
const {member, reflector, importTracker} = setup(`
import {Directive, model} from '@angular/core';
@Directive()
class Dir {
private test = model(1);
}
`);
const result = tryParseInitializerApi([modelApi], member.value!, reflector, importTracker);
expect(result).not.toBeNull();
expect(() => validateAccessOfInitializerApiMember(result!, member)).toThrowMatching(
(err) =>
err instanceof FatalDiagnosticError &&
err.code === ErrorCode.INITIALIZER_API_DISALLOWED_MEMBER_VISIBILITY,
);
});
it('should report errors if a protected field is used, but not allowed', () => {
const {member, reflector, importTracker} = setup(`
import {Directive, model} from '@angular/core';
@Directive()
class Dir {
protected test = model(1);
}
`);
const result = tryParseInitializerApi([modelApi], member.value!, reflector, importTracker);
expect(result).not.toBeNull();
expect(() => validateAccessOfInitializerApiMember(result!, member)).toThrowMatching(
(err) =>
err instanceof FatalDiagnosticError &&
err.code === ErrorCode.INITIALIZER_API_DISALLOWED_MEMBER_VISIBILITY,
);
});
it('should report errors if an ECMAScript private field is used, but not allowed', () => {
const {member, reflector, importTracker} = setup(`
import {Directive, model} from '@angular/core';
@Directive()
class Dir {
#test = model(1);
}
`);
const result = tryParseInitializerApi([modelApi], member.value!, reflector, importTracker);
expect(result).not.toBeNull();
expect(() => validateAccessOfInitializerApiMember(result!, member)).toThrowMatching(
(err) =>
err instanceof FatalDiagnosticError &&
err.code === ErrorCode.INITIALIZER_API_DISALLOWED_MEMBER_VISIBILITY,
);
});
it('should report errors if a readonly public field is used, but not allowed', () => {
const {member, reflector, importTracker} = setup(`
import {Directive, model} from '@angular/core';
@Directive()
class Dir {
// test model initializer API definition doesn't even allow readonly!
readonly test = model(1);
}
`);
const result = tryParseInitializerApi([modelApi], member.value!, reflector, importTracker);
expect(result).not.toBeNull();
expect(() => validateAccessOfInitializerApiMember(result!, member)).toThrowMatching(
(err) =>
err instanceof FatalDiagnosticError &&
err.code === ErrorCode.INITIALIZER_API_DISALLOWED_MEMBER_VISIBILITY,
);
});
it('should allow private field if API explicitly allows it', () => {
const {member, reflector, importTracker} = setup(`
import {Directive, model} from '@angular/core';
@Directive()
class Dir {
// test model initializer API definition doesn't even allow readonly!
private test = model(1);
}
`);
const result = tryParseInitializerApi(
[{...modelApi, allowedAccessLevels: [ClassMemberAccessLevel.Private]}],
member.value!,
reflector,
importTracker,
);
expect(result?.api).toEqual(
jasmine.objectContaining<InitializerApiFunction>({
functionName: 'model',
}),
);
expect(() => validateAccessOfInitializerApiMember(result!, member)).not.toThrow();
});
});
});
function setup(contents: string) {
const fileName = absoluteFrom('/test.ts');
const {program} = makeProgram(
[
{
name: absoluteFrom('/node_modules/@angular/core/index.d.ts'),
contents: `
export const Directive: any;
export const input: any;
export const model: any;
`,
},
{
name: absoluteFrom('/node_modules/@angular/core/rxjs-interop/index.d.ts'),
contents: `
export const outputFromObservable: any;
`,
},
{
name: absoluteFrom('/node_modules/@unknown/utils/index.d.ts'),
contents: `
export declare function toString(value: any): string;
`,
},
{
name: absoluteFrom('/node_modules/@not-angular/core/index.d.ts'),
contents: `
export const model: any;
`,
},
{name: fileName, contents},
],
{target: ts.ScriptTarget.ESNext},
);
const sourceFile = program.getSourceFile(fileName);
const importTracker = new ImportedSymbolsTracker();
const reflector = new TypeScriptReflectionHost(program.getTypeChecker());
if (sourceFile === undefined) {
throw new Error(`Cannot resolve test file ${fileName}`);
}
let member: Pick<ClassMember, 'value' | 'accessLevel'> | null = null;
(function walk(node: ts.Node) {
if (
ts.isPropertyDeclaration(node) &&
((ts.isIdentifier(node.name) && node.name.text === 'test') ||
(ts.isPrivateIdentifier(node.name) && node.name.text === '#test'))
) {
member = reflectClassMember(node);
} else {
ts.forEachChild(node, walk);
}
})(sourceFile);
if (member === null) {
throw new Error(`Could not resolve a class property with a name of "test" in the test file`);
}
return {member, reflector, importTracker};
} | {
"end_byte": 15012,
"start_byte": 9488,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/test/initializer_functions_spec.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/query_functions.ts_0_6254 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
createMayBeForwardRefExpression,
ForwardRefHandling,
MaybeForwardRefExpression,
outputAst as o,
R3QueryMetadata,
} from '@angular/compiler';
import ts from 'typescript';
import {ErrorCode, FatalDiagnosticError} from '../../../diagnostics';
import {ImportedSymbolsTracker} from '../../../imports';
import {
ClassMember,
ClassMemberAccessLevel,
ReflectionHost,
reflectObjectLiteral,
} from '../../../reflection';
import {tryUnwrapForwardRef} from '../../common';
import {validateAccessOfInitializerApiMember} from './initializer_function_access';
import {tryParseInitializerApi} from './initializer_functions';
/** Possible query initializer API functions. */
export type QueryFunctionName = 'viewChild' | 'contentChild' | 'viewChildren' | 'contentChildren';
/** Possible names of query initializer APIs. */
const queryFunctionNames: QueryFunctionName[] = [
'viewChild',
'viewChildren',
'contentChild',
'contentChildren',
];
/** Possible query initializer API functions. */
export const QUERY_INITIALIZER_FNS = queryFunctionNames.map((fnName) => ({
functionName: fnName,
owningModule: '@angular/core' as const,
// Queries are accessed from within static blocks, via the query definition functions.
// Conceptually, the fields could access private members— even ES private fields.
// Support for ES private fields requires special caution and complexity when partial
// output is linked— hence not supported. TS private members are allowed in static blocks.
allowedAccessLevels: [
ClassMemberAccessLevel.PublicWritable,
ClassMemberAccessLevel.PublicReadonly,
ClassMemberAccessLevel.Protected,
ClassMemberAccessLevel.Private,
],
}));
// The `descendants` option is enabled by default, except for content children.
const defaultDescendantsValue = (type: QueryFunctionName) => type !== 'contentChildren';
/**
* Attempts to detect a possible query definition for the given class member.
*
* This function checks for all possible variants of queries and matches the
* first one. The query is then analyzed and its resolved metadata is returned.
*
* @returns Resolved query metadata, or null if no query is declared.
*/
export function tryParseSignalQueryFromInitializer(
member: Pick<ClassMember, 'name' | 'value' | 'accessLevel'>,
reflector: ReflectionHost,
importTracker: ImportedSymbolsTracker,
): {name: QueryFunctionName; metadata: R3QueryMetadata; call: ts.CallExpression} | null {
if (member.value === null) {
return null;
}
const query = tryParseInitializerApi(
QUERY_INITIALIZER_FNS,
member.value,
reflector,
importTracker,
);
if (query === null) {
return null;
}
validateAccessOfInitializerApiMember(query, member);
const {functionName} = query.api;
const isSingleQuery = functionName === 'viewChild' || functionName === 'contentChild';
const predicateNode = query.call.arguments[0] as ts.Expression | undefined;
if (predicateNode === undefined) {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE,
query.call,
'No locator specified.',
);
}
const optionsNode = query.call.arguments[1] as ts.Expression | undefined;
if (optionsNode !== undefined && !ts.isObjectLiteralExpression(optionsNode)) {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE,
optionsNode,
'Argument needs to be an object literal.',
);
}
const options = optionsNode && reflectObjectLiteral(optionsNode);
const read = options?.has('read') ? parseReadOption(options.get('read')!) : null;
const descendants = options?.has('descendants')
? parseDescendantsOption(options.get('descendants')!)
: defaultDescendantsValue(functionName);
return {
name: functionName,
call: query.call,
metadata: {
isSignal: true,
propertyName: member.name,
static: false,
emitDistinctChangesOnly: true,
predicate: parseLocator(predicateNode, reflector),
first: isSingleQuery,
read,
descendants,
},
};
}
/** Parses the locator/predicate of the query. */
function parseLocator(
expression: ts.Expression,
reflector: ReflectionHost,
): string[] | MaybeForwardRefExpression<o.Expression> {
// Attempt to unwrap `forwardRef` calls.
const unwrappedExpression = tryUnwrapForwardRef(expression, reflector);
if (unwrappedExpression !== null) {
expression = unwrappedExpression;
}
if (ts.isStringLiteralLike(expression)) {
return [expression.text];
}
return createMayBeForwardRefExpression(
new o.WrappedNodeExpr(expression),
unwrappedExpression !== null ? ForwardRefHandling.Unwrapped : ForwardRefHandling.None,
);
}
/**
* Parses the `read` option of a query.
*
* We only support the following patterns for the `read` option:
* - `read: someImport.BLA`,
* - `read: BLA`
*
* That is because we cannot trivially support complex expressions,
* especially those referencing `this`. The read provider token will
* live outside of the class in the static class definition.
*/
function parseReadOption(value: ts.Expression): o.Expression {
if (
ts.isExpressionWithTypeArguments(value) ||
ts.isParenthesizedExpression(value) ||
ts.isAsExpression(value)
) {
return parseReadOption(value.expression);
}
if (
(ts.isPropertyAccessExpression(value) && ts.isIdentifier(value.expression)) ||
ts.isIdentifier(value)
) {
return new o.WrappedNodeExpr(value);
}
throw new FatalDiagnosticError(
ErrorCode.VALUE_NOT_LITERAL,
value,
`Query "read" option expected a literal class reference.`,
);
}
/** Parses the `descendants` option of a query. */
function parseDescendantsOption(value: ts.Expression): boolean {
if (value.kind === ts.SyntaxKind.TrueKeyword) {
return true;
} else if (value.kind === ts.SyntaxKind.FalseKeyword) {
return false;
}
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE,
value,
`Expected "descendants" option to be a boolean literal.`,
);
}
| {
"end_byte": 6254,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/query_functions.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/input_output_parse_options.ts_0_1422 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {ErrorCode, FatalDiagnosticError} from '../../../diagnostics';
import {reflectObjectLiteral} from '../../../reflection';
/**
* Parses and validates input and output initializer function options.
*
* This currently only parses the `alias` option and returns it. The other
* options for signal inputs are runtime constructs that aren't relevant at
* compile time.
*/
export function parseAndValidateInputAndOutputOptions(optionsNode: ts.Expression): {
alias: string | undefined;
} {
if (!ts.isObjectLiteralExpression(optionsNode)) {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE,
optionsNode,
'Argument needs to be an object literal that is statically analyzable.',
);
}
const options = reflectObjectLiteral(optionsNode);
let alias: string | undefined = undefined;
if (options.has('alias')) {
const aliasExpr = options.get('alias')!;
if (!ts.isStringLiteralLike(aliasExpr)) {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE,
aliasExpr,
'Alias needs to be a string that is statically analyzable.',
);
}
alias = aliasExpr.text;
}
return {alias};
}
| {
"end_byte": 1422,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/input_output_parse_options.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts_0_3757 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
createMayBeForwardRefExpression,
emitDistinctChangesOnlyDefaultValue,
Expression,
ExternalExpr,
ForwardRefHandling,
getSafePropertyAccessString,
MaybeForwardRefExpression,
ParsedHostBindings,
ParseError,
parseHostBindings,
R3DirectiveMetadata,
R3HostDirectiveMetadata,
R3InputMetadata,
R3QueryMetadata,
R3Reference,
verifyHostBindings,
WrappedNodeExpr,
} from '@angular/compiler';
import ts from 'typescript';
import {ErrorCode, FatalDiagnosticError, makeRelatedInformation} from '../../../diagnostics';
import {
assertSuccessfulReferenceEmit,
ImportedSymbolsTracker,
ImportFlags,
Reference,
ReferenceEmitter,
} from '../../../imports';
import {
ClassPropertyMapping,
DecoratorInputTransform,
HostDirectiveMeta,
InputMapping,
InputOrOutput,
isHostDirectiveMetaForGlobalMode,
} from '../../../metadata';
import {
DynamicValue,
EnumValue,
PartialEvaluator,
ResolvedValue,
traceDynamicValue,
} from '../../../partial_evaluator';
import {
AmbientImport,
ClassDeclaration,
ClassMember,
ClassMemberKind,
Decorator,
filterToMembersWithDecorator,
isNamedClassDeclaration,
ReflectionHost,
reflectObjectLiteral,
} from '../../../reflection';
import {CompilationMode} from '../../../transform';
import {
assertLocalCompilationUnresolvedConst,
createSourceSpan,
createValueHasWrongTypeError,
forwardRefResolver,
getAngularDecorators,
getConstructorDependencies,
isAngularDecorator,
ReferencesRegistry,
toR3Reference,
tryUnwrapForwardRef,
unwrapConstructorDependencies,
unwrapExpression,
validateConstructorDependencies,
wrapFunctionExpressionsInParens,
wrapTypeReference,
} from '../../common';
import {tryParseSignalInputMapping} from './input_function';
import {tryParseSignalModelMapping} from './model_function';
import {tryParseInitializerBasedOutput} from './output_function';
import {tryParseSignalQueryFromInitializer} from './query_functions';
import {NG_STANDALONE_DEFAULT_VALUE} from '../../common/src/standalone-default-value';
const EMPTY_OBJECT: {[key: string]: string} = {};
type QueryDecoratorName = 'ViewChild' | 'ViewChildren' | 'ContentChild' | 'ContentChildren';
export const queryDecoratorNames: QueryDecoratorName[] = [
'ViewChild',
'ViewChildren',
'ContentChild',
'ContentChildren',
];
const QUERY_TYPES = new Set<string>(queryDecoratorNames);
/**
* Helper function to extract metadata from a `Directive` or `Component`. `Directive`s without a
* selector are allowed to be used for abstract base classes. These abstract directives should not
* appear in the declarations of an `NgModule` and additional verification is done when processing
* the module.
*/
export function extractDirectiveMetadata(
clazz: ClassDeclaration,
decorator: Readonly<Decorator>,
reflector: ReflectionHost,
importTracker: ImportedSymbolsTracker,
evaluator: PartialEvaluator,
refEmitter: ReferenceEmitter,
referencesRegistry: ReferencesRegistry,
isCore: boolean,
annotateForClosureCompiler: boolean,
compilationMode: CompilationMode,
defaultSelector: string | null,
strictStandalone: boolean,
):
| {
jitForced: false;
decorator: Map<string, ts.Expression>;
metadata: R3DirectiveMetadata;
inputs: ClassPropertyMapping<InputMapping>;
outputs: ClassPropertyMapping;
isStructural: boolean;
hostDirectives: HostDirectiveMeta[] | null;
rawHostDirectives: ts.Expression | null;
inputFieldNamesFromMetadataArray: Set<string>;
}
| {jitForced: true} | {
"end_byte": 3757,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts_3758_11953 | {
let directive: Map<string, ts.Expression>;
if (decorator.args === null || decorator.args.length === 0) {
directive = new Map<string, ts.Expression>();
} else if (decorator.args.length !== 1) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG,
decorator.node,
`Incorrect number of arguments to @${decorator.name} decorator`,
);
} else {
const meta = unwrapExpression(decorator.args[0]);
if (!ts.isObjectLiteralExpression(meta)) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARG_NOT_LITERAL,
meta,
`@${decorator.name} argument must be an object literal`,
);
}
directive = reflectObjectLiteral(meta);
}
if (directive.has('jit')) {
// The only allowed value is true, so there's no need to expand further.
return {jitForced: true};
}
const members = reflector.getMembersOfClass(clazz);
// Precompute a list of ts.ClassElements that have decorators. This includes things like @Input,
// @Output, @HostBinding, etc.
const decoratedElements = members.filter(
(member) => !member.isStatic && member.decorators !== null,
);
const coreModule = isCore ? undefined : '@angular/core';
// Construct the map of inputs both from the @Directive/@Component
// decorator, and the decorated fields.
const inputsFromMeta = parseInputsArray(
clazz,
directive,
evaluator,
reflector,
refEmitter,
compilationMode,
);
const inputsFromFields = parseInputFields(
clazz,
members,
evaluator,
reflector,
importTracker,
refEmitter,
isCore,
compilationMode,
inputsFromMeta,
decorator,
);
const inputs = ClassPropertyMapping.fromMappedObject({...inputsFromMeta, ...inputsFromFields});
// And outputs.
const outputsFromMeta = parseOutputsArray(directive, evaluator);
const outputsFromFields = parseOutputFields(
clazz,
decorator,
members,
isCore,
reflector,
importTracker,
evaluator,
outputsFromMeta,
);
const outputs = ClassPropertyMapping.fromMappedObject({...outputsFromMeta, ...outputsFromFields});
// Parse queries of fields.
const {viewQueries, contentQueries} = parseQueriesOfClassFields(
members,
reflector,
importTracker,
evaluator,
isCore,
);
if (directive.has('queries')) {
const signalQueryFields = new Set(
[...viewQueries, ...contentQueries].filter((q) => q.isSignal).map((q) => q.propertyName),
);
const queriesFromDecorator = extractQueriesFromDecorator(
directive.get('queries')!,
reflector,
evaluator,
isCore,
);
// Checks if the query is already declared/reserved via class members declaration.
// If so, we throw a fatal diagnostic error to prevent this unintentional pattern.
const checkAndUnwrapQuery = (q: {expr: ts.Expression; metadata: R3QueryMetadata}) => {
if (signalQueryFields.has(q.metadata.propertyName)) {
throw new FatalDiagnosticError(
ErrorCode.INITIALIZER_API_DECORATOR_METADATA_COLLISION,
q.expr,
`Query is declared multiple times. "@${decorator.name}" declares a query for the same property.`,
);
}
return q.metadata;
};
contentQueries.push(...queriesFromDecorator.content.map((q) => checkAndUnwrapQuery(q)));
viewQueries.push(...queriesFromDecorator.view.map((q) => checkAndUnwrapQuery(q)));
}
// Parse the selector.
let selector = defaultSelector;
if (directive.has('selector')) {
const expr = directive.get('selector')!;
const resolved = evaluator.evaluate(expr);
assertLocalCompilationUnresolvedConst(
compilationMode,
resolved,
null,
'Unresolved identifier found for @Component.selector field! Did you ' +
'import this identifier from a file outside of the compilation unit? ' +
'This is not allowed when Angular compiler runs in local mode. Possible ' +
'solutions: 1) Move the declarations into a file within the compilation ' +
'unit, 2) Inline the selector',
);
if (typeof resolved !== 'string') {
throw createValueHasWrongTypeError(expr, resolved, `selector must be a string`);
}
// use default selector in case selector is an empty string
selector = resolved === '' ? defaultSelector : resolved;
if (!selector) {
throw new FatalDiagnosticError(
ErrorCode.DIRECTIVE_MISSING_SELECTOR,
expr,
`Directive ${clazz.name.text} has no selector, please add it!`,
);
}
}
const host = extractHostBindings(
decoratedElements,
evaluator,
coreModule,
compilationMode,
directive,
);
const providers: Expression | null = directive.has('providers')
? new WrappedNodeExpr(
annotateForClosureCompiler
? wrapFunctionExpressionsInParens(directive.get('providers')!)
: directive.get('providers')!,
)
: null;
// Determine if `ngOnChanges` is a lifecycle hook defined on the component.
const usesOnChanges = members.some(
(member) =>
!member.isStatic && member.kind === ClassMemberKind.Method && member.name === 'ngOnChanges',
);
// Parse exportAs.
let exportAs: string[] | null = null;
if (directive.has('exportAs')) {
const expr = directive.get('exportAs')!;
const resolved = evaluator.evaluate(expr);
assertLocalCompilationUnresolvedConst(
compilationMode,
resolved,
null,
'Unresolved identifier found for exportAs field! Did you import this ' +
'identifier from a file outside of the compilation unit? This is not ' +
'allowed when Angular compiler runs in local mode. Possible solutions: ' +
'1) Move the declarations into a file within the compilation unit, ' +
'2) Inline the selector',
);
if (typeof resolved !== 'string') {
throw createValueHasWrongTypeError(expr, resolved, `exportAs must be a string`);
}
exportAs = resolved.split(',').map((part) => part.trim());
}
const rawCtorDeps = getConstructorDependencies(clazz, reflector, isCore);
// Non-abstract directives (those with a selector) require valid constructor dependencies, whereas
// abstract directives are allowed to have invalid dependencies, given that a subclass may call
// the constructor explicitly.
const ctorDeps =
selector !== null
? validateConstructorDependencies(clazz, rawCtorDeps)
: unwrapConstructorDependencies(rawCtorDeps);
// Structural directives must have a `TemplateRef` dependency.
const isStructural =
ctorDeps !== null &&
ctorDeps !== 'invalid' &&
ctorDeps.some(
(dep) =>
dep.token instanceof ExternalExpr &&
dep.token.value.moduleName === '@angular/core' &&
dep.token.value.name === 'TemplateRef',
);
let isStandalone = NG_STANDALONE_DEFAULT_VALUE;
if (directive.has('standalone')) {
const expr = directive.get('standalone')!;
const resolved = evaluator.evaluate(expr);
if (typeof resolved !== 'boolean') {
throw createValueHasWrongTypeError(expr, resolved, `standalone flag must be a boolean`);
}
isStandalone = resolved;
if (!isStandalone && strictStandalone) {
throw new FatalDiagnosticError(
ErrorCode.NON_STANDALONE_NOT_ALLOWED,
expr,
`Only standalone components/directives are allowed when 'strictStandalone' is enabled.`,
);
}
}
let isSignal = false;
if (directive.has('signals')) {
const expr = directive.get('signals')!;
const resolved = evaluator.evaluate(expr);
if (typeof resolved !== 'boolean') {
throw createValueHasWrongTypeError(expr, resolved, `signals flag must be a boolean`);
}
isSignal = resolved;
}
// Detect if the component inherits from another class
const usesInheritance = reflector.hasBaseClass(clazz);
const sourceFile = clazz.getSourceFile();
const type = wrapTypeReference(reflector, clazz);
const rawHostDirectives = directive.get('hostDirectives') || null;
const hostDirectives =
rawHostDirectives === null
? null
: extractHostDirectives(rawHostDirectives, evaluator, compilationMode); | {
"end_byte": 11953,
"start_byte": 3758,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts_11957_17603 | if (compilationMode !== CompilationMode.LOCAL && hostDirectives !== null) {
// In global compilation mode where we do type checking, the template type-checker will need to
// import host directive types, so add them as referenced by `clazz`. This will ensure that
// libraries are required to export host directives which are visible from publicly exported
// components.
referencesRegistry.add(
clazz,
...hostDirectives.map((hostDir) => {
if (!isHostDirectiveMetaForGlobalMode(hostDir)) {
throw new Error('Impossible state');
}
return hostDir.directive;
}),
);
}
const metadata: R3DirectiveMetadata = {
name: clazz.name.text,
deps: ctorDeps,
host: {
...host,
},
lifecycle: {
usesOnChanges,
},
inputs: inputs.toJointMappedObject(toR3InputMetadata),
outputs: outputs.toDirectMappedObject(),
queries: contentQueries,
viewQueries,
selector,
fullInheritance: false,
type,
typeArgumentCount: reflector.getGenericArityOfClass(clazz) || 0,
typeSourceSpan: createSourceSpan(clazz.name),
usesInheritance,
exportAs,
providers,
isStandalone,
isSignal,
hostDirectives:
hostDirectives?.map((hostDir) => toHostDirectiveMetadata(hostDir, sourceFile, refEmitter)) ||
null,
};
return {
jitForced: false,
decorator: directive,
metadata,
inputs,
outputs,
isStructural,
hostDirectives,
rawHostDirectives,
// Track inputs from class metadata. This is useful for migration efforts.
inputFieldNamesFromMetadataArray: new Set(
Object.values(inputsFromMeta).map((i) => i.classPropertyName),
),
};
}
export function extractDecoratorQueryMetadata(
exprNode: ts.Node,
name: string,
args: ReadonlyArray<ts.Expression>,
propertyName: string,
reflector: ReflectionHost,
evaluator: PartialEvaluator,
): R3QueryMetadata {
if (args.length === 0) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG,
exprNode,
`@${name} must have arguments`,
);
}
const first = name === 'ViewChild' || name === 'ContentChild';
const forwardReferenceTarget = tryUnwrapForwardRef(args[0], reflector);
const node = forwardReferenceTarget ?? args[0];
const arg = evaluator.evaluate(node);
/** Whether or not this query should collect only static results (see view/api.ts) */
let isStatic: boolean = false;
// Extract the predicate
let predicate: MaybeForwardRefExpression | string[] | null = null;
if (arg instanceof Reference || arg instanceof DynamicValue) {
// References and predicates that could not be evaluated statically are emitted as is.
predicate = createMayBeForwardRefExpression(
new WrappedNodeExpr(node),
forwardReferenceTarget !== null ? ForwardRefHandling.Unwrapped : ForwardRefHandling.None,
);
} else if (typeof arg === 'string') {
predicate = [arg];
} else if (isStringArrayOrDie(arg, `@${name} predicate`, node)) {
predicate = arg;
} else {
throw createValueHasWrongTypeError(node, arg, `@${name} predicate cannot be interpreted`);
}
// Extract the read and descendants options.
let read: Expression | null = null;
// The default value for descendants is true for every decorator except @ContentChildren.
let descendants: boolean = name !== 'ContentChildren';
let emitDistinctChangesOnly: boolean = emitDistinctChangesOnlyDefaultValue;
if (args.length === 2) {
const optionsExpr = unwrapExpression(args[1]);
if (!ts.isObjectLiteralExpression(optionsExpr)) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARG_NOT_LITERAL,
optionsExpr,
`@${name} options must be an object literal`,
);
}
const options = reflectObjectLiteral(optionsExpr);
if (options.has('read')) {
read = new WrappedNodeExpr(options.get('read')!);
}
if (options.has('descendants')) {
const descendantsExpr = options.get('descendants')!;
const descendantsValue = evaluator.evaluate(descendantsExpr);
if (typeof descendantsValue !== 'boolean') {
throw createValueHasWrongTypeError(
descendantsExpr,
descendantsValue,
`@${name} options.descendants must be a boolean`,
);
}
descendants = descendantsValue;
}
if (options.has('emitDistinctChangesOnly')) {
const emitDistinctChangesOnlyExpr = options.get('emitDistinctChangesOnly')!;
const emitDistinctChangesOnlyValue = evaluator.evaluate(emitDistinctChangesOnlyExpr);
if (typeof emitDistinctChangesOnlyValue !== 'boolean') {
throw createValueHasWrongTypeError(
emitDistinctChangesOnlyExpr,
emitDistinctChangesOnlyValue,
`@${name} options.emitDistinctChangesOnly must be a boolean`,
);
}
emitDistinctChangesOnly = emitDistinctChangesOnlyValue;
}
if (options.has('static')) {
const staticValue = evaluator.evaluate(options.get('static')!);
if (typeof staticValue !== 'boolean') {
throw createValueHasWrongTypeError(
node,
staticValue,
`@${name} options.static must be a boolean`,
);
}
isStatic = staticValue;
}
} else if (args.length > 2) {
// Too many arguments.
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG,
node,
`@${name} has too many arguments`,
);
}
return {
isSignal: false,
propertyName,
predicate,
first,
descendants,
read,
static: isStatic,
emitDistinctChangesOnly,
};
} | {
"end_byte": 17603,
"start_byte": 11957,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts_17605_26822 | export function extractHostBindings(
members: ClassMember[],
evaluator: PartialEvaluator,
coreModule: string | undefined,
compilationMode: CompilationMode,
metadata?: Map<string, ts.Expression>,
): ParsedHostBindings {
let bindings: ParsedHostBindings;
if (metadata && metadata.has('host')) {
bindings = evaluateHostExpressionBindings(metadata.get('host')!, evaluator);
} else {
bindings = parseHostBindings({});
}
filterToMembersWithDecorator(members, 'HostBinding', coreModule).forEach(
({member, decorators}) => {
decorators.forEach((decorator) => {
let hostPropertyName: string = member.name;
if (decorator.args !== null && decorator.args.length > 0) {
if (decorator.args.length !== 1) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG,
decorator.node,
`@HostBinding can have at most one argument, got ${decorator.args.length} argument(s)`,
);
}
const resolved = evaluator.evaluate(decorator.args[0]);
// Specific error for local compilation mode if the argument cannot be resolved
assertLocalCompilationUnresolvedConst(
compilationMode,
resolved,
null,
"Unresolved identifier found for @HostBinding's argument! Did " +
'you import this identifier from a file outside of the compilation ' +
'unit? This is not allowed when Angular compiler runs in local mode. ' +
'Possible solutions: 1) Move the declaration into a file within ' +
'the compilation unit, 2) Inline the argument',
);
if (typeof resolved !== 'string') {
throw createValueHasWrongTypeError(
decorator.node,
resolved,
`@HostBinding's argument must be a string`,
);
}
hostPropertyName = resolved;
}
// Since this is a decorator, we know that the value is a class member. Always access it
// through `this` so that further down the line it can't be confused for a literal value
// (e.g. if there's a property called `true`). There is no size penalty, because all
// values (except literals) are converted to `ctx.propName` eventually.
bindings.properties[hostPropertyName] = getSafePropertyAccessString('this', member.name);
});
},
);
filterToMembersWithDecorator(members, 'HostListener', coreModule).forEach(
({member, decorators}) => {
decorators.forEach((decorator) => {
let eventName: string = member.name;
let args: string[] = [];
if (decorator.args !== null && decorator.args.length > 0) {
if (decorator.args.length > 2) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG,
decorator.args[2],
`@HostListener can have at most two arguments`,
);
}
const resolved = evaluator.evaluate(decorator.args[0]);
// Specific error for local compilation mode if the event name cannot be resolved
assertLocalCompilationUnresolvedConst(
compilationMode,
resolved,
null,
"Unresolved identifier found for @HostListener's event name " +
'argument! Did you import this identifier from a file outside of ' +
'the compilation unit? This is not allowed when Angular compiler ' +
'runs in local mode. Possible solutions: 1) Move the declaration ' +
'into a file within the compilation unit, 2) Inline the argument',
);
if (typeof resolved !== 'string') {
throw createValueHasWrongTypeError(
decorator.args[0],
resolved,
`@HostListener's event name argument must be a string`,
);
}
eventName = resolved;
if (decorator.args.length === 2) {
const expression = decorator.args[1];
const resolvedArgs = evaluator.evaluate(decorator.args[1]);
if (!isStringArrayOrDie(resolvedArgs, '@HostListener.args', expression)) {
throw createValueHasWrongTypeError(
decorator.args[1],
resolvedArgs,
`@HostListener's second argument must be a string array`,
);
}
args = resolvedArgs;
}
}
bindings.listeners[eventName] = `${member.name}(${args.join(',')})`;
});
},
);
return bindings;
}
function extractQueriesFromDecorator(
queryData: ts.Expression,
reflector: ReflectionHost,
evaluator: PartialEvaluator,
isCore: boolean,
): {
content: {expr: ts.Expression; metadata: R3QueryMetadata}[];
view: {expr: ts.Expression; metadata: R3QueryMetadata}[];
} {
const content: {expr: ts.Expression; metadata: R3QueryMetadata}[] = [];
const view: {expr: ts.Expression; metadata: R3QueryMetadata}[] = [];
if (!ts.isObjectLiteralExpression(queryData)) {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE,
queryData,
'Decorator queries metadata must be an object literal',
);
}
reflectObjectLiteral(queryData).forEach((queryExpr, propertyName) => {
queryExpr = unwrapExpression(queryExpr);
if (!ts.isNewExpression(queryExpr)) {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE,
queryData,
'Decorator query metadata must be an instance of a query type',
);
}
const queryType = ts.isPropertyAccessExpression(queryExpr.expression)
? queryExpr.expression.name
: queryExpr.expression;
if (!ts.isIdentifier(queryType)) {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE,
queryData,
'Decorator query metadata must be an instance of a query type',
);
}
const type = reflector.getImportOfIdentifier(queryType);
if (
type === null ||
(!isCore && type.from !== '@angular/core') ||
!QUERY_TYPES.has(type.name)
) {
throw new FatalDiagnosticError(
ErrorCode.VALUE_HAS_WRONG_TYPE,
queryData,
'Decorator query metadata must be an instance of a query type',
);
}
const query = extractDecoratorQueryMetadata(
queryExpr,
type.name,
queryExpr.arguments || [],
propertyName,
reflector,
evaluator,
);
if (type.name.startsWith('Content')) {
content.push({expr: queryExpr, metadata: query});
} else {
view.push({expr: queryExpr, metadata: query});
}
});
return {content, view};
}
export function parseDirectiveStyles(
directive: Map<string, ts.Expression>,
evaluator: PartialEvaluator,
compilationMode: CompilationMode,
): null | string[] {
const expression = directive.get('styles');
if (!expression) {
return null;
}
const evaluated = evaluator.evaluate(expression);
const value = typeof evaluated === 'string' ? [evaluated] : evaluated;
// Check if the identifier used for @Component.styles cannot be resolved in local compilation
// mode. if the case, an error specific to this situation is generated.
if (compilationMode === CompilationMode.LOCAL) {
let unresolvedNode: ts.Node | null = null;
if (Array.isArray(value)) {
const entry = value.find((e) => e instanceof DynamicValue && e.isFromUnknownIdentifier()) as
| DynamicValue
| undefined;
unresolvedNode = entry?.node ?? null;
} else if (value instanceof DynamicValue && value.isFromUnknownIdentifier()) {
unresolvedNode = value.node;
}
if (unresolvedNode !== null) {
throw new FatalDiagnosticError(
ErrorCode.LOCAL_COMPILATION_UNRESOLVED_CONST,
unresolvedNode,
'Unresolved identifier found for @Component.styles field! Did you import ' +
'this identifier from a file outside of the compilation unit? This is ' +
'not allowed when Angular compiler runs in local mode. Possible ' +
'solutions: 1) Move the declarations into a file within the compilation ' +
'unit, 2) Inline the styles, 3) Move the styles into separate files and ' +
'include it using @Component.styleUrls',
);
}
}
if (!isStringArrayOrDie(value, 'styles', expression)) {
throw createValueHasWrongTypeError(
expression,
value,
`Failed to resolve @Component.styles to a string or an array of strings`,
);
}
return value;
}
export function parseFieldStringArrayValue(
directive: Map<string, ts.Expression>,
field: string,
evaluator: PartialEvaluator,
): null | string[] {
if (!directive.has(field)) {
return null;
}
// Resolve the field of interest from the directive metadata to a string[].
const expression = directive.get(field)!;
const value = evaluator.evaluate(expression);
if (!isStringArrayOrDie(value, field, expression)) {
throw createValueHasWrongTypeError(
expression,
value,
`Failed to resolve @Directive.${field} to a string array`,
);
}
return value;
} | {
"end_byte": 26822,
"start_byte": 17605,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts_26824_33231 | function isStringArrayOrDie(value: any, name: string, node: ts.Expression): value is string[] {
if (!Array.isArray(value)) {
return false;
}
for (let i = 0; i < value.length; i++) {
if (typeof value[i] !== 'string') {
throw createValueHasWrongTypeError(
node,
value[i],
`Failed to resolve ${name} at position ${i} to a string`,
);
}
}
return true;
}
function tryGetQueryFromFieldDecorator(
member: ClassMember,
reflector: ReflectionHost,
evaluator: PartialEvaluator,
isCore: boolean,
): {name: QueryDecoratorName; decorator: Decorator; metadata: R3QueryMetadata} | null {
const decorators = member.decorators;
if (decorators === null) {
return null;
}
const queryDecorators = getAngularDecorators(decorators, queryDecoratorNames, isCore);
if (queryDecorators.length === 0) {
return null;
}
if (queryDecorators.length !== 1) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_COLLISION,
member.node ?? queryDecorators[0].node,
'Cannot combine multiple query decorators.',
);
}
const decorator = queryDecorators[0];
const node = member.node || decorator.node;
// Throw in case of `@Input() @ContentChild('foo') foo: any`, which is not supported in Ivy
if (decorators.some((v) => v.name === 'Input')) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_COLLISION,
node,
'Cannot combine @Input decorators with query decorators',
);
}
if (!isPropertyTypeMember(member)) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_UNEXPECTED,
node,
'Query decorator must go on a property-type member',
);
}
// Either the decorator was aliased, or is referenced directly with
// the proper query name.
const name = (decorator.import?.name ?? decorator.name) as QueryDecoratorName;
return {
name,
decorator,
metadata: extractDecoratorQueryMetadata(
node,
name,
decorator.args || [],
member.name,
reflector,
evaluator,
),
};
}
function isPropertyTypeMember(member: ClassMember): boolean {
return (
member.kind === ClassMemberKind.Getter ||
member.kind === ClassMemberKind.Setter ||
member.kind === ClassMemberKind.Property
);
}
function parseMappingStringArray(values: string[]) {
return values.reduce(
(results, value) => {
if (typeof value !== 'string') {
throw new Error('Mapping value must be a string');
}
const [bindingPropertyName, fieldName] = parseMappingString(value);
results[fieldName] = bindingPropertyName;
return results;
},
{} as {[field: string]: string},
);
}
function parseMappingString(value: string): [bindingPropertyName: string, fieldName: string] {
// Either the value is 'field' or 'field: property'. In the first case, `property` will
// be undefined, in which case the field name should also be used as the property name.
const [fieldName, bindingPropertyName] = value.split(':', 2).map((str) => str.trim());
return [bindingPropertyName ?? fieldName, fieldName];
}
/** Parses the `inputs` array of a directive/component decorator. */
function parseInputsArray(
clazz: ClassDeclaration,
decoratorMetadata: Map<string, ts.Expression>,
evaluator: PartialEvaluator,
reflector: ReflectionHost,
refEmitter: ReferenceEmitter,
compilationMode: CompilationMode,
): Record<string, InputMapping> {
const inputsField = decoratorMetadata.get('inputs');
if (inputsField === undefined) {
return {};
}
const inputs = {} as Record<string, InputMapping>;
const inputsArray = evaluator.evaluate(inputsField);
if (!Array.isArray(inputsArray)) {
throw createValueHasWrongTypeError(
inputsField,
inputsArray,
`Failed to resolve @Directive.inputs to an array`,
);
}
for (let i = 0; i < inputsArray.length; i++) {
const value = inputsArray[i];
if (typeof value === 'string') {
// If the value is a string, we treat it as a mapping string.
const [bindingPropertyName, classPropertyName] = parseMappingString(value);
inputs[classPropertyName] = {
bindingPropertyName,
classPropertyName,
required: false,
transform: null,
// Note: Signal inputs are not allowed with the array form.
isSignal: false,
};
} else if (value instanceof Map) {
// If it's a map, we treat it as a config object.
const name = value.get('name');
const alias = value.get('alias');
const required = value.get('required');
let transform: DecoratorInputTransform | null = null;
if (typeof name !== 'string') {
throw createValueHasWrongTypeError(
inputsField,
name,
`Value at position ${i} of @Directive.inputs array must have a "name" property`,
);
}
if (value.has('transform')) {
const transformValue = value.get('transform');
if (!(transformValue instanceof DynamicValue) && !(transformValue instanceof Reference)) {
throw createValueHasWrongTypeError(
inputsField,
transformValue,
`Transform of value at position ${i} of @Directive.inputs array must be a function`,
);
}
transform = parseDecoratorInputTransformFunction(
clazz,
name,
transformValue,
reflector,
refEmitter,
compilationMode,
);
}
inputs[name] = {
classPropertyName: name,
bindingPropertyName: typeof alias === 'string' ? alias : name,
required: required === true,
// Note: Signal inputs are not allowed with the array form.
isSignal: false,
transform,
};
} else {
throw createValueHasWrongTypeError(
inputsField,
value,
`@Directive.inputs array can only contain strings or object literals`,
);
}
}
return inputs;
}
/** Attempts to find a given Angular decorator on the class member. */
function tryGetDecoratorOnMember(
member: ClassMember,
decoratorName: string,
isCore: boolean,
): Decorator | null {
if (member.decorators === null) {
return null;
}
for (const decorator of member.decorators) {
if (isAngularDecorator(decorator, decoratorName, isCore)) {
return decorator;
}
}
return null;
} | {
"end_byte": 33231,
"start_byte": 26824,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts_33233_38735 | function tryParseInputFieldMapping(
clazz: ClassDeclaration,
member: ClassMember,
evaluator: PartialEvaluator,
reflector: ReflectionHost,
importTracker: ImportedSymbolsTracker,
isCore: boolean,
refEmitter: ReferenceEmitter,
compilationMode: CompilationMode,
): InputMapping | null {
const classPropertyName = member.name;
const decorator = tryGetDecoratorOnMember(member, 'Input', isCore);
const signalInputMapping = tryParseSignalInputMapping(member, reflector, importTracker);
const modelInputMapping = tryParseSignalModelMapping(member, reflector, importTracker);
if (decorator !== null && signalInputMapping !== null) {
throw new FatalDiagnosticError(
ErrorCode.INITIALIZER_API_WITH_DISALLOWED_DECORATOR,
decorator.node,
`Using @Input with a signal input is not allowed.`,
);
}
if (decorator !== null && modelInputMapping !== null) {
throw new FatalDiagnosticError(
ErrorCode.INITIALIZER_API_WITH_DISALLOWED_DECORATOR,
decorator.node,
`Using @Input with a model input is not allowed.`,
);
}
// Check `@Input` case.
if (decorator !== null) {
if (decorator.args !== null && decorator.args.length > 1) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG,
decorator.node,
`@${decorator.name} can have at most one argument, got ${decorator.args.length} argument(s)`,
);
}
const optionsNode =
decorator.args !== null && decorator.args.length === 1 ? decorator.args[0] : undefined;
const options = optionsNode !== undefined ? evaluator.evaluate(optionsNode) : null;
const required = options instanceof Map ? options.get('required') === true : false;
// To preserve old behavior: Even though TypeScript types ensure proper options are
// passed, we sanity check for unsupported values here again.
if (options !== null && typeof options !== 'string' && !(options instanceof Map)) {
throw createValueHasWrongTypeError(
decorator.node,
options,
`@${decorator.name} decorator argument must resolve to a string or an object literal`,
);
}
let alias: string | null = null;
if (typeof options === 'string') {
alias = options;
} else if (options instanceof Map && typeof options.get('alias') === 'string') {
alias = options.get('alias') as string;
}
const publicInputName = alias ?? classPropertyName;
let transform: DecoratorInputTransform | null = null;
if (options instanceof Map && options.has('transform')) {
const transformValue = options.get('transform');
if (!(transformValue instanceof DynamicValue) && !(transformValue instanceof Reference)) {
throw createValueHasWrongTypeError(
optionsNode!,
transformValue,
`Input transform must be a function`,
);
}
transform = parseDecoratorInputTransformFunction(
clazz,
classPropertyName,
transformValue,
reflector,
refEmitter,
compilationMode,
);
}
return {
isSignal: false,
classPropertyName,
bindingPropertyName: publicInputName,
transform,
required,
};
}
// Look for signal inputs. e.g. `memberName = input()`
if (signalInputMapping !== null) {
return signalInputMapping;
}
if (modelInputMapping !== null) {
return modelInputMapping.input;
}
return null;
}
/** Parses the class members that declare inputs (via decorator or initializer). */
function parseInputFields(
clazz: ClassDeclaration,
members: ClassMember[],
evaluator: PartialEvaluator,
reflector: ReflectionHost,
importTracker: ImportedSymbolsTracker,
refEmitter: ReferenceEmitter,
isCore: boolean,
compilationMode: CompilationMode,
inputsFromClassDecorator: Record<string, InputMapping>,
classDecorator: Decorator,
): Record<string, InputMapping> {
const inputs = {} as Record<string, InputMapping>;
for (const member of members) {
const classPropertyName = member.name;
const inputMapping = tryParseInputFieldMapping(
clazz,
member,
evaluator,
reflector,
importTracker,
isCore,
refEmitter,
compilationMode,
);
if (inputMapping === null) {
continue;
}
if (member.isStatic) {
throw new FatalDiagnosticError(
ErrorCode.INCORRECTLY_DECLARED_ON_STATIC_MEMBER,
member.node ?? clazz,
`Input "${member.name}" is incorrectly declared as static member of "${clazz.name.text}".`,
);
}
// Validate that signal inputs are not accidentally declared in the `inputs` metadata.
if (inputMapping.isSignal && inputsFromClassDecorator.hasOwnProperty(classPropertyName)) {
throw new FatalDiagnosticError(
ErrorCode.INITIALIZER_API_DECORATOR_METADATA_COLLISION,
member.node ?? clazz,
`Input "${member.name}" is also declared as non-signal in @${classDecorator.name}.`,
);
}
inputs[classPropertyName] = inputMapping;
}
return inputs;
}
/**
* Parses the `transform` function and its type for a decorator `@Input`.
*
* This logic verifies feasibility of extracting the transform write type
* into a different place, so that the input write type can be captured at
* a later point in a static acceptance member.
*
* Note: This is not needed for signal inputs where the transform type is
* automatically captured in the type of the `InputSignal`.
*
*/ | {
"end_byte": 38735,
"start_byte": 33233,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts_38736_47807 | export function parseDecoratorInputTransformFunction(
clazz: ClassDeclaration,
classPropertyName: string,
value: DynamicValue | Reference,
reflector: ReflectionHost,
refEmitter: ReferenceEmitter,
compilationMode: CompilationMode,
): DecoratorInputTransform {
// In local compilation mode we can skip type checking the function args. This is because usually
// the type check is done in a separate build which runs in full compilation mode. So here we skip
// all the diagnostics.
if (compilationMode === CompilationMode.LOCAL) {
const node =
value instanceof Reference ? value.getIdentityIn(clazz.getSourceFile()) : value.node;
// This should never be null since we know the reference originates
// from the same file, but we null check it just in case.
if (node === null) {
throw createValueHasWrongTypeError(
value.node,
value,
'Input transform function could not be referenced',
);
}
return {
node,
type: new Reference(ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword)),
};
}
const definition = reflector.getDefinitionOfFunction(value.node);
if (definition === null) {
throw createValueHasWrongTypeError(value.node, value, 'Input transform must be a function');
}
if (definition.typeParameters !== null && definition.typeParameters.length > 0) {
throw createValueHasWrongTypeError(
value.node,
value,
'Input transform function cannot be generic',
);
}
if (definition.signatureCount > 1) {
throw createValueHasWrongTypeError(
value.node,
value,
'Input transform function cannot have multiple signatures',
);
}
const members = reflector.getMembersOfClass(clazz);
for (const member of members) {
const conflictingName = `ngAcceptInputType_${classPropertyName}`;
if (member.name === conflictingName && member.isStatic) {
throw new FatalDiagnosticError(
ErrorCode.CONFLICTING_INPUT_TRANSFORM,
value.node,
`Class cannot have both a transform function on Input ${classPropertyName} and a static member called ${conflictingName}`,
);
}
}
const node = value instanceof Reference ? value.getIdentityIn(clazz.getSourceFile()) : value.node;
// This should never be null since we know the reference originates
// from the same file, but we null check it just in case.
if (node === null) {
throw createValueHasWrongTypeError(
value.node,
value,
'Input transform function could not be referenced',
);
}
// Skip over `this` parameters since they're typing the context, not the actual parameter.
// `this` parameters are guaranteed to be first if they exist, and the only to distinguish them
// is using the name, TS doesn't have a special AST for them.
const firstParam =
definition.parameters[0]?.name === 'this' ? definition.parameters[1] : definition.parameters[0];
// Treat functions with no arguments as `unknown` since returning
// the same value from the transform function is valid.
if (!firstParam) {
return {
node,
type: new Reference(ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword)),
};
}
// This should be caught by `noImplicitAny` already, but null check it just in case.
if (!firstParam.type) {
throw createValueHasWrongTypeError(
value.node,
value,
'Input transform function first parameter must have a type',
);
}
if (firstParam.node.dotDotDotToken) {
throw createValueHasWrongTypeError(
value.node,
value,
'Input transform function first parameter cannot be a spread parameter',
);
}
assertEmittableInputType(firstParam.type, clazz.getSourceFile(), reflector, refEmitter);
const viaModule = value instanceof Reference ? value.bestGuessOwningModule : null;
return {node, type: new Reference(firstParam.type, viaModule)};
}
/**
* Verifies that a type and all types contained within
* it can be referenced in a specific context file.
*/
function assertEmittableInputType(
type: ts.TypeNode,
contextFile: ts.SourceFile,
reflector: ReflectionHost,
refEmitter: ReferenceEmitter,
): void {
(function walk(node: ts.Node) {
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) {
const declaration = reflector.getDeclarationOfIdentifier(node.typeName);
if (declaration !== null) {
// If the type is declared in a different file, we have to check that it can be imported
// into the context file. If they're in the same file, we need to verify that they're
// exported, otherwise TS won't emit it to the .d.ts.
if (declaration.node.getSourceFile() !== contextFile) {
const emittedType = refEmitter.emit(
new Reference(
declaration.node,
declaration.viaModule === AmbientImport ? AmbientImport : null,
),
contextFile,
ImportFlags.NoAliasing |
ImportFlags.AllowTypeImports |
ImportFlags.AllowRelativeDtsImports |
ImportFlags.AllowAmbientReferences,
);
assertSuccessfulReferenceEmit(emittedType, node, 'type');
} else if (!reflector.isStaticallyExported(declaration.node)) {
throw new FatalDiagnosticError(
ErrorCode.SYMBOL_NOT_EXPORTED,
type,
`Symbol must be exported in order to be used as the type of an Input transform function`,
[makeRelatedInformation(declaration.node, `The symbol is declared here.`)],
);
}
}
}
node.forEachChild(walk);
})(type);
}
/**
* Iterates through all specified class members and attempts to detect
* view and content queries defined.
*
* Queries may be either defined via decorators, or through class member
* initializers for signal-based queries.
*/
function parseQueriesOfClassFields(
members: ClassMember[],
reflector: ReflectionHost,
importTracker: ImportedSymbolsTracker,
evaluator: PartialEvaluator,
isCore: boolean,
): {
viewQueries: R3QueryMetadata[];
contentQueries: R3QueryMetadata[];
} {
const viewQueries: R3QueryMetadata[] = [];
const contentQueries: R3QueryMetadata[] = [];
// For backwards compatibility, decorator-based queries are grouped and
// ordered in a specific way. The order needs to match with what we had in:
// https://github.com/angular/angular/blob/8737544d6963bf664f752de273e919575cca08ac/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts#L94-L111.
const decoratorViewChild: R3QueryMetadata[] = [];
const decoratorViewChildren: R3QueryMetadata[] = [];
const decoratorContentChild: R3QueryMetadata[] = [];
const decoratorContentChildren: R3QueryMetadata[] = [];
for (const member of members) {
const decoratorQuery = tryGetQueryFromFieldDecorator(member, reflector, evaluator, isCore);
const signalQuery = tryParseSignalQueryFromInitializer(member, reflector, importTracker);
if (decoratorQuery !== null && signalQuery !== null) {
throw new FatalDiagnosticError(
ErrorCode.INITIALIZER_API_WITH_DISALLOWED_DECORATOR,
decoratorQuery.decorator.node,
`Using @${decoratorQuery.name} with a signal-based query is not allowed.`,
);
}
const queryNode = decoratorQuery?.decorator.node ?? signalQuery?.call;
if (queryNode !== undefined && member.isStatic) {
throw new FatalDiagnosticError(
ErrorCode.INCORRECTLY_DECLARED_ON_STATIC_MEMBER,
queryNode,
`Query is incorrectly declared on a static class member.`,
);
}
if (decoratorQuery !== null) {
switch (decoratorQuery.name) {
case 'ViewChild':
decoratorViewChild.push(decoratorQuery.metadata);
break;
case 'ViewChildren':
decoratorViewChildren.push(decoratorQuery.metadata);
break;
case 'ContentChild':
decoratorContentChild.push(decoratorQuery.metadata);
break;
case 'ContentChildren':
decoratorContentChildren.push(decoratorQuery.metadata);
break;
}
} else if (signalQuery !== null) {
switch (signalQuery.name) {
case 'viewChild':
case 'viewChildren':
viewQueries.push(signalQuery.metadata);
break;
case 'contentChild':
case 'contentChildren':
contentQueries.push(signalQuery.metadata);
break;
}
}
}
return {
viewQueries: [...viewQueries, ...decoratorViewChild, ...decoratorViewChildren],
contentQueries: [...contentQueries, ...decoratorContentChild, ...decoratorContentChildren],
};
}
/** Parses the `outputs` array of a directive/component. */
function parseOutputsArray(
directive: Map<string, ts.Expression>,
evaluator: PartialEvaluator,
): Record<string, string> {
const metaValues = parseFieldStringArrayValue(directive, 'outputs', evaluator);
return metaValues ? parseMappingStringArray(metaValues) : EMPTY_OBJECT;
} | {
"end_byte": 47807,
"start_byte": 38736,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts_47809_56824 | /** Parses the class members that are outputs. */
function parseOutputFields(
clazz: ClassDeclaration,
classDecorator: Decorator,
members: ClassMember[],
isCore: boolean,
reflector: ReflectionHost,
importTracker: ImportedSymbolsTracker,
evaluator: PartialEvaluator,
outputsFromMeta: Record<string, string>,
): Record<string, string> {
const outputs = {} as Record<string, string>;
for (const member of members) {
const decoratorOutput = tryParseDecoratorOutput(member, evaluator, isCore);
const initializerOutput = tryParseInitializerBasedOutput(member, reflector, importTracker);
const modelMapping = tryParseSignalModelMapping(member, reflector, importTracker);
if (decoratorOutput !== null && initializerOutput !== null) {
throw new FatalDiagnosticError(
ErrorCode.INITIALIZER_API_WITH_DISALLOWED_DECORATOR,
decoratorOutput.decorator.node,
`Using "@Output" with "output()" is not allowed.`,
);
}
if (decoratorOutput !== null && modelMapping !== null) {
throw new FatalDiagnosticError(
ErrorCode.INITIALIZER_API_WITH_DISALLOWED_DECORATOR,
decoratorOutput.decorator.node,
`Using @Output with a model input is not allowed.`,
);
}
const queryNode =
decoratorOutput?.decorator.node ?? initializerOutput?.call ?? modelMapping?.call;
if (queryNode !== undefined && member.isStatic) {
throw new FatalDiagnosticError(
ErrorCode.INCORRECTLY_DECLARED_ON_STATIC_MEMBER,
queryNode,
`Output is incorrectly declared on a static class member.`,
);
}
let bindingPropertyName: string;
if (decoratorOutput !== null) {
bindingPropertyName = decoratorOutput.metadata.bindingPropertyName;
} else if (initializerOutput !== null) {
bindingPropertyName = initializerOutput.metadata.bindingPropertyName;
} else if (modelMapping !== null) {
bindingPropertyName = modelMapping.output.bindingPropertyName;
} else {
continue;
}
// Validate that initializer-based outputs are not accidentally declared
// in the `outputs` class metadata.
if (
(initializerOutput !== null || modelMapping !== null) &&
outputsFromMeta.hasOwnProperty(member.name)
) {
throw new FatalDiagnosticError(
ErrorCode.INITIALIZER_API_DECORATOR_METADATA_COLLISION,
member.node ?? clazz,
`Output "${member.name}" is unexpectedly declared in @${classDecorator.name} as well.`,
);
}
outputs[member.name] = bindingPropertyName;
}
return outputs;
}
/** Attempts to parse a decorator-based @Output. */
function tryParseDecoratorOutput(
member: ClassMember,
evaluator: PartialEvaluator,
isCore: boolean,
): {decorator: Decorator; metadata: InputOrOutput} | null {
const decorator = tryGetDecoratorOnMember(member, 'Output', isCore);
if (decorator === null) {
return null;
}
if (decorator.args !== null && decorator.args.length > 1) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG,
decorator.node,
`@Output can have at most one argument, got ${decorator.args.length} argument(s)`,
);
}
const classPropertyName = member.name;
let alias: string | null = null;
if (decorator.args?.length === 1) {
const resolvedAlias = evaluator.evaluate(decorator.args[0]);
if (typeof resolvedAlias !== 'string') {
throw createValueHasWrongTypeError(
decorator.node,
resolvedAlias,
`@Output decorator argument must resolve to a string`,
);
}
alias = resolvedAlias;
}
return {
decorator,
metadata: {
isSignal: false,
classPropertyName,
bindingPropertyName: alias ?? classPropertyName,
},
};
}
function evaluateHostExpressionBindings(
hostExpr: ts.Expression,
evaluator: PartialEvaluator,
): ParsedHostBindings {
const hostMetaMap = evaluator.evaluate(hostExpr);
if (!(hostMetaMap instanceof Map)) {
throw createValueHasWrongTypeError(
hostExpr,
hostMetaMap,
`Decorator host metadata must be an object`,
);
}
const hostMetadata: Record<string, string | Expression> = {};
hostMetaMap.forEach((value, key) => {
// Resolve Enum references to their declared value.
if (value instanceof EnumValue) {
value = value.resolved;
}
if (typeof key !== 'string') {
throw createValueHasWrongTypeError(
hostExpr,
key,
`Decorator host metadata must be a string -> string object, but found unparseable key`,
);
}
if (typeof value == 'string') {
hostMetadata[key] = value;
} else if (value instanceof DynamicValue) {
hostMetadata[key] = new WrappedNodeExpr(value.node as ts.Expression);
} else {
throw createValueHasWrongTypeError(
hostExpr,
value,
`Decorator host metadata must be a string -> string object, but found unparseable value`,
);
}
});
const bindings = parseHostBindings(hostMetadata);
const errors = verifyHostBindings(bindings, createSourceSpan(hostExpr));
if (errors.length > 0) {
throw new FatalDiagnosticError(
// TODO: provide more granular diagnostic and output specific host expression that
// triggered an error instead of the whole host object.
ErrorCode.HOST_BINDING_PARSE_ERROR,
hostExpr,
errors.map((error: ParseError) => error.msg).join('\n'),
);
}
return bindings;
}
/**
* Extracts and prepares the host directives metadata from an array literal expression.
* @param rawHostDirectives Expression that defined the `hostDirectives`.
*/
function extractHostDirectives(
rawHostDirectives: ts.Expression,
evaluator: PartialEvaluator,
compilationMode: CompilationMode,
): HostDirectiveMeta[] {
const resolved = evaluator.evaluate(rawHostDirectives, forwardRefResolver);
if (!Array.isArray(resolved)) {
throw createValueHasWrongTypeError(
rawHostDirectives,
resolved,
'hostDirectives must be an array',
);
}
return resolved.map((value) => {
const hostReference = value instanceof Map ? value.get('directive') : value;
// Diagnostics
if (compilationMode !== CompilationMode.LOCAL) {
if (!(hostReference instanceof Reference)) {
throw createValueHasWrongTypeError(
rawHostDirectives,
hostReference,
'Host directive must be a reference',
);
}
if (!isNamedClassDeclaration(hostReference.node)) {
throw createValueHasWrongTypeError(
rawHostDirectives,
hostReference,
'Host directive reference must be a class',
);
}
}
let directive: Reference<ClassDeclaration> | Expression;
let nameForErrors = (fieldName: string) => '@Directive.hostDirectives';
if (compilationMode === CompilationMode.LOCAL && hostReference instanceof DynamicValue) {
// At the moment in local compilation we only support simple array for host directives, i.e.,
// an array consisting of the directive identifiers. We don't support forward refs or other
// expressions applied on externally imported directives. The main reason is simplicity, and
// that almost nobody wants to use host directives this way (e.g., what would be the point of
// forward ref for imported symbols?!)
if (
!ts.isIdentifier(hostReference.node) &&
!ts.isPropertyAccessExpression(hostReference.node)
) {
throw new FatalDiagnosticError(
ErrorCode.LOCAL_COMPILATION_UNSUPPORTED_EXPRESSION,
hostReference.node,
`In local compilation mode, host directive cannot be an expression. Use an identifier instead`,
);
}
directive = new WrappedNodeExpr(hostReference.node);
} else if (hostReference instanceof Reference) {
directive = hostReference as Reference<ClassDeclaration>;
nameForErrors = (fieldName: string) =>
`@Directive.hostDirectives.${
(directive as Reference<ClassDeclaration>).node.name.text
}.${fieldName}`;
} else {
throw new Error('Impossible state');
}
const meta: HostDirectiveMeta = {
directive,
isForwardReference: hostReference instanceof Reference && hostReference.synthetic,
inputs: parseHostDirectivesMapping(
'inputs',
value,
nameForErrors('input'),
rawHostDirectives,
),
outputs: parseHostDirectivesMapping(
'outputs',
value,
nameForErrors('output'),
rawHostDirectives,
),
};
return meta;
});
}
/**
* Parses the expression that defines the `inputs` or `outputs` of a host directive.
* @param field Name of the field that is being parsed.
* @param resolvedValue Evaluated value of the expression that defined the field.
* @param classReference Reference to the host directive class.
* @param sourceExpression Expression that the host directive is referenced in.
*/ | {
"end_byte": 56824,
"start_byte": 47809,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts_56825_58470 | function parseHostDirectivesMapping(
field: 'inputs' | 'outputs',
resolvedValue: ResolvedValue,
nameForErrors: string,
sourceExpression: ts.Expression,
): {[bindingPropertyName: string]: string} | null {
if (resolvedValue instanceof Map && resolvedValue.has(field)) {
const rawInputs = resolvedValue.get(field);
if (isStringArrayOrDie(rawInputs, nameForErrors, sourceExpression)) {
return parseMappingStringArray(rawInputs);
}
}
return null;
}
/** Converts the parsed host directive information into metadata. */
function toHostDirectiveMetadata(
hostDirective: HostDirectiveMeta,
context: ts.SourceFile,
refEmitter: ReferenceEmitter,
): R3HostDirectiveMetadata {
let directive: R3Reference;
if (hostDirective.directive instanceof Reference) {
directive = toR3Reference(
hostDirective.directive.node,
hostDirective.directive,
context,
refEmitter,
);
} else {
directive = {
value: hostDirective.directive,
type: hostDirective.directive,
};
}
return {
directive,
isForwardReference: hostDirective.isForwardReference,
inputs: hostDirective.inputs || null,
outputs: hostDirective.outputs || null,
};
}
/** Converts the parsed input information into metadata. */
function toR3InputMetadata(mapping: InputMapping): R3InputMetadata {
return {
classPropertyName: mapping.classPropertyName,
bindingPropertyName: mapping.bindingPropertyName,
required: mapping.required,
transformFunction:
mapping.transform !== null ? new WrappedNodeExpr(mapping.transform.node) : null,
isSignal: mapping.isSignal,
};
} | {
"end_byte": 58470,
"start_byte": 56825,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/shared.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/input_function.ts_0_2653 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {ImportedSymbolsTracker} from '../../../imports';
import {InputMapping} from '../../../metadata';
import {ClassMember, ClassMemberAccessLevel, ReflectionHost} from '../../../reflection';
import {validateAccessOfInitializerApiMember} from './initializer_function_access';
import {InitializerApiFunction, tryParseInitializerApi} from './initializer_functions';
import {parseAndValidateInputAndOutputOptions} from './input_output_parse_options';
/** Represents a function that can declare an input. */
export const INPUT_INITIALIZER_FN: InitializerApiFunction = {
functionName: 'input',
owningModule: '@angular/core',
// Inputs are accessed from parents, via the `property` instruction.
// Conceptually, the fields need to be publicly readable, but in practice,
// accessing `protected` or `private` members works at runtime, so we can allow
// cases where the input is intentionally not part of the public API, programmatically.
// Note: `private` is omitted intentionally as this would be a conceptual confusion point.
allowedAccessLevels: [
ClassMemberAccessLevel.PublicWritable,
ClassMemberAccessLevel.PublicReadonly,
ClassMemberAccessLevel.Protected,
],
};
/**
* Attempts to parse a signal input class member. Returns the parsed
* input mapping if possible.
*/
export function tryParseSignalInputMapping(
member: Pick<ClassMember, 'name' | 'value' | 'accessLevel'>,
reflector: ReflectionHost,
importTracker: ImportedSymbolsTracker,
): InputMapping | null {
if (member.value === null) {
return null;
}
const signalInput = tryParseInitializerApi(
[INPUT_INITIALIZER_FN],
member.value,
reflector,
importTracker,
);
if (signalInput === null) {
return null;
}
validateAccessOfInitializerApiMember(signalInput, member);
const optionsNode = (
signalInput.isRequired ? signalInput.call.arguments[0] : signalInput.call.arguments[1]
) as ts.Expression | undefined;
const options =
optionsNode !== undefined ? parseAndValidateInputAndOutputOptions(optionsNode) : null;
const classPropertyName = member.name;
return {
isSignal: true,
classPropertyName,
bindingPropertyName: options?.alias ?? classPropertyName,
required: signalInput.isRequired,
// Signal inputs do not capture complex transform metadata.
// See more details in the `transform` type of `InputMapping`.
transform: null,
};
}
| {
"end_byte": 2653,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/input_function.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/symbol.ts_0_5898 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
areTypeParametersEqual,
isArrayEqual,
isSetEqual,
isSymbolEqual,
SemanticSymbol,
SemanticTypeParameter,
} from '../../../incremental/semantic_graph';
import {
ClassPropertyMapping,
DirectiveTypeCheckMeta,
InputMapping,
InputOrOutput,
TemplateGuardMeta,
} from '../../../metadata';
import {ClassDeclaration} from '../../../reflection';
/**
* Represents an Angular directive. Components are represented by `ComponentSymbol`, which inherits
* from this symbol.
*/
export class DirectiveSymbol extends SemanticSymbol {
baseClass: SemanticSymbol | null = null;
constructor(
decl: ClassDeclaration,
public readonly selector: string | null,
public readonly inputs: ClassPropertyMapping<InputMapping>,
public readonly outputs: ClassPropertyMapping,
public readonly exportAs: string[] | null,
public readonly typeCheckMeta: DirectiveTypeCheckMeta,
public readonly typeParameters: SemanticTypeParameter[] | null,
) {
super(decl);
}
override isPublicApiAffected(previousSymbol: SemanticSymbol): boolean {
// Note: since components and directives have exactly the same items contributing to their
// public API, it is okay for a directive to change into a component and vice versa without
// the API being affected.
if (!(previousSymbol instanceof DirectiveSymbol)) {
return true;
}
// Directives and components have a public API of:
// 1. Their selector.
// 2. The binding names of their inputs and outputs; a change in ordering is also considered
// to be a change in public API.
// 3. The list of exportAs names and its ordering.
return (
this.selector !== previousSymbol.selector ||
!isArrayEqual(this.inputs.propertyNames, previousSymbol.inputs.propertyNames) ||
!isArrayEqual(this.outputs.propertyNames, previousSymbol.outputs.propertyNames) ||
!isArrayEqual(this.exportAs, previousSymbol.exportAs)
);
}
override isTypeCheckApiAffected(previousSymbol: SemanticSymbol): boolean {
// If the public API of the directive has changed, then so has its type-check API.
if (this.isPublicApiAffected(previousSymbol)) {
return true;
}
if (!(previousSymbol instanceof DirectiveSymbol)) {
return true;
}
// The type-check block also depends on the class property names, as writes property bindings
// directly into the backing fields.
if (
!isArrayEqual(
Array.from(this.inputs),
Array.from(previousSymbol.inputs),
isInputMappingEqual,
) ||
!isArrayEqual(
Array.from(this.outputs),
Array.from(previousSymbol.outputs),
isInputOrOutputEqual,
)
) {
return true;
}
// The type parameters of a directive are emitted into the type constructors in the type-check
// block of a component, so if the type parameters are not considered equal then consider the
// type-check API of this directive to be affected.
if (!areTypeParametersEqual(this.typeParameters, previousSymbol.typeParameters)) {
return true;
}
// The type-check metadata is used during TCB code generation, so any changes should invalidate
// prior type-check files.
if (!isTypeCheckMetaEqual(this.typeCheckMeta, previousSymbol.typeCheckMeta)) {
return true;
}
// Changing the base class of a directive means that its inputs/outputs etc may have changed,
// so the type-check block of components that use this directive needs to be regenerated.
if (!isBaseClassEqual(this.baseClass, previousSymbol.baseClass)) {
return true;
}
return false;
}
}
function isInputMappingEqual(current: InputMapping, previous: InputMapping): boolean {
return isInputOrOutputEqual(current, previous) && current.required === previous.required;
}
function isInputOrOutputEqual(current: InputOrOutput, previous: InputOrOutput): boolean {
return (
current.classPropertyName === previous.classPropertyName &&
current.bindingPropertyName === previous.bindingPropertyName &&
current.isSignal === previous.isSignal
);
}
function isTypeCheckMetaEqual(
current: DirectiveTypeCheckMeta,
previous: DirectiveTypeCheckMeta,
): boolean {
if (current.hasNgTemplateContextGuard !== previous.hasNgTemplateContextGuard) {
return false;
}
if (current.isGeneric !== previous.isGeneric) {
// Note: changes in the number of type parameters is also considered in
// `areTypeParametersEqual` so this check is technically not needed; it is done anyway for
// completeness in terms of whether the `DirectiveTypeCheckMeta` struct itself compares
// equal or not.
return false;
}
if (!isArrayEqual(current.ngTemplateGuards, previous.ngTemplateGuards, isTemplateGuardEqual)) {
return false;
}
if (!isSetEqual(current.coercedInputFields, previous.coercedInputFields)) {
return false;
}
if (!isSetEqual(current.restrictedInputFields, previous.restrictedInputFields)) {
return false;
}
if (!isSetEqual(current.stringLiteralInputFields, previous.stringLiteralInputFields)) {
return false;
}
if (!isSetEqual(current.undeclaredInputFields, previous.undeclaredInputFields)) {
return false;
}
return true;
}
function isTemplateGuardEqual(current: TemplateGuardMeta, previous: TemplateGuardMeta): boolean {
return current.inputName === previous.inputName && current.type === previous.type;
}
function isBaseClassEqual(
current: SemanticSymbol | null,
previous: SemanticSymbol | null,
): boolean {
if (current === null || previous === null) {
return current === previous;
}
return isSymbolEqual(current, previous);
}
| {
"end_byte": 5898,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/symbol.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/model_function.ts_0_2588 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {ImportedSymbolsTracker} from '../../../imports';
import {ModelMapping} from '../../../metadata';
import {ClassMember, ClassMemberAccessLevel, ReflectionHost} from '../../../reflection';
import {validateAccessOfInitializerApiMember} from './initializer_function_access';
import {InitializerApiFunction, tryParseInitializerApi} from './initializer_functions';
import {parseAndValidateInputAndOutputOptions} from './input_output_parse_options';
/** Represents a function that can declare a model. */
export const MODEL_INITIALIZER_FN: InitializerApiFunction = {
functionName: 'model',
owningModule: '@angular/core',
// Inputs are accessed from parents, via the `property` instruction.
// Conceptually, the fields need to be publicly readable, but in practice,
// accessing `protected` or `private` members works at runtime, so we can allow
// cases where the input is intentionally not part of the public API, programmatically.
allowedAccessLevels: [
ClassMemberAccessLevel.PublicWritable,
ClassMemberAccessLevel.PublicReadonly,
ClassMemberAccessLevel.Protected,
],
};
/**
* Attempts to parse a model class member. Returns the parsed model mapping if possible.
*/
export function tryParseSignalModelMapping(
member: Pick<ClassMember, 'name' | 'value' | 'accessLevel'>,
reflector: ReflectionHost,
importTracker: ImportedSymbolsTracker,
): ModelMapping | null {
if (member.value === null) {
return null;
}
const model = tryParseInitializerApi(
[MODEL_INITIALIZER_FN],
member.value,
reflector,
importTracker,
);
if (model === null) {
return null;
}
validateAccessOfInitializerApiMember(model, member);
const optionsNode = (model.isRequired ? model.call.arguments[0] : model.call.arguments[1]) as
| ts.Expression
| undefined;
const options =
optionsNode !== undefined ? parseAndValidateInputAndOutputOptions(optionsNode) : null;
const classPropertyName = member.name;
const bindingPropertyName = options?.alias ?? classPropertyName;
return {
call: model.call,
input: {
isSignal: true,
transform: null,
classPropertyName,
bindingPropertyName,
required: model.isRequired,
},
output: {
isSignal: false,
classPropertyName,
bindingPropertyName: bindingPropertyName + 'Change',
},
};
}
| {
"end_byte": 2588,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/model_function.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/initializer_function_access.ts_0_1487 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ErrorCode, FatalDiagnosticError, makeDiagnosticChain} from '../../../diagnostics';
import {ClassMember} from '../../../reflection';
import {classMemberAccessLevelToString} from '../../../reflection/src/util';
import {InitializerFunctionMetadata} from './initializer_functions';
/**
* Validates that the initializer member is compatible with the given class
* member in terms of field access and visibility.
*
* @throws {FatalDiagnosticError} If the recognized initializer API is
* incompatible.
*/
export function validateAccessOfInitializerApiMember(
{api, call}: InitializerFunctionMetadata,
member: Pick<ClassMember, 'accessLevel'>,
): void {
if (!api.allowedAccessLevels.includes(member.accessLevel)) {
throw new FatalDiagnosticError(
ErrorCode.INITIALIZER_API_DISALLOWED_MEMBER_VISIBILITY,
call,
makeDiagnosticChain(
`Cannot use "${
api.functionName
}" on a class member that is declared as ${classMemberAccessLevelToString(
member.accessLevel,
)}.`,
[
makeDiagnosticChain(
`Update the class field to be either: ` +
api.allowedAccessLevels.map((l) => classMemberAccessLevelToString(l)).join(', '),
),
],
),
);
}
}
| {
"end_byte": 1487,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/initializer_function_access.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/initializer_functions.ts_0_6942 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {ImportedSymbolsTracker} from '../../../imports';
import {ClassMemberAccessLevel, ReflectionHost} from '../../../reflection';
/**
* @fileoverview
*
* Angular exposes functions that can be used as class member initializers
* to make use of various APIs. Those are called initializer APIs.
*
* Signal-based inputs are relying on initializer APIs because such inputs
* are declared using `input` and `input.required` intersection functions.
* Similarly, signal-based queries follow the same pattern and are also
* declared through initializer APIs.
*/
export interface InitializerApiFunction {
/** Module name where the initializer function is imported from. */
owningModule: '@angular/core' | '@angular/core/rxjs-interop';
/** Export name of the initializer function. */
functionName:
| 'input'
| 'model'
| 'output'
| 'outputFromObservable'
| 'viewChild'
| 'viewChildren'
| 'contentChild'
| 'contentChildren';
/** Class member access levels compatible with the API. */
allowedAccessLevels: ClassMemberAccessLevel[];
}
/**
* Metadata describing an Angular class member that was recognized through
* a function initializer. Like `input`, `input.required` or `viewChild`.
*/
export interface InitializerFunctionMetadata {
/** Initializer API function that was recognized. */
api: InitializerApiFunction;
/** Node referring to the call expression. */
call: ts.CallExpression;
/** Whether the initializer is required or not. E.g. `input.required` was used. */
isRequired: boolean;
}
/**
* Metadata that can be inferred from an initializer
* statically without going through the type checker.
*/
interface StaticInitializerData {
/** Initializer-function API that was matched. */
api: InitializerApiFunction;
/** Identifier in the initializer that refers to the Angular API. */
apiReference: ts.Identifier;
/** Whether the call is required. */
isRequired: boolean;
}
/**
* Attempts to identify an Angular initializer function call.
*
* Note that multiple possible initializer API function names can be specified,
* allowing for checking multiple types in one pass.
*
* @returns The parsed initializer API, or null if none was found.
*/
export function tryParseInitializerApi<Functions extends InitializerApiFunction[]>(
functions: Functions,
expression: ts.Expression,
reflector: ReflectionHost,
importTracker: ImportedSymbolsTracker,
): (InitializerFunctionMetadata & {api: Functions[number]}) | null {
if (!ts.isCallExpression(expression)) {
return null;
}
const staticResult =
parseTopLevelCall(expression, functions, importTracker) ||
parseTopLevelRequiredCall(expression, functions, importTracker) ||
parseTopLevelCallFromNamespace(expression, functions, importTracker);
if (staticResult === null) {
return null;
}
const {api, apiReference, isRequired} = staticResult;
// Once we've statically determined that the initializer is one of the APIs we're looking for, we
// need to verify it using the type checker which accounts for things like shadowed variables.
// This should be done as the absolute last step since using the type check can be expensive.
const resolvedImport = reflector.getImportOfIdentifier(apiReference);
if (
resolvedImport === null ||
api.functionName !== resolvedImport.name ||
api.owningModule !== resolvedImport.from
) {
return null;
}
return {
api,
call: expression,
isRequired,
};
}
/**
* Attempts to parse a top-level call to an initializer function,
* e.g. `prop = input()`. Returns null if it can't be parsed.
*/
function parseTopLevelCall(
call: ts.CallExpression,
functions: InitializerApiFunction[],
importTracker: ImportedSymbolsTracker,
): StaticInitializerData | null {
const node = call.expression;
if (!ts.isIdentifier(node)) {
return null;
}
const matchingApi = functions.find((fn) =>
importTracker.isPotentialReferenceToNamedImport(node, fn.functionName, fn.owningModule),
);
if (matchingApi === undefined) {
return null;
}
return {api: matchingApi, apiReference: node, isRequired: false};
}
/**
* Attempts to parse a top-level call to a required initializer,
* e.g. `prop = input.required()`. Returns null if it can't be parsed.
*/
function parseTopLevelRequiredCall(
call: ts.CallExpression,
functions: InitializerApiFunction[],
importTracker: ImportedSymbolsTracker,
): StaticInitializerData | null {
const node = call.expression;
if (
!ts.isPropertyAccessExpression(node) ||
!ts.isIdentifier(node.expression) ||
node.name.text !== 'required'
) {
return null;
}
const expression = node.expression;
const matchingApi = functions.find((fn) =>
importTracker.isPotentialReferenceToNamedImport(expression, fn.functionName, fn.owningModule),
);
if (matchingApi === undefined) {
return null;
}
return {api: matchingApi, apiReference: expression, isRequired: true};
}
/**
* Attempts to parse a top-level call to a function referenced via a namespace import,
* e.g. `prop = core.input.required()`. Returns null if it can't be parsed.
*/
function parseTopLevelCallFromNamespace(
call: ts.CallExpression,
functions: InitializerApiFunction[],
importTracker: ImportedSymbolsTracker,
): StaticInitializerData | null {
const node = call.expression;
if (!ts.isPropertyAccessExpression(node)) {
return null;
}
let apiReference: ts.Identifier | null = null;
let matchingApi: InitializerApiFunction | undefined = undefined;
let isRequired = false;
// `prop = core.input()`
if (ts.isIdentifier(node.expression) && ts.isIdentifier(node.name)) {
const namespaceRef = node.expression;
apiReference = node.name;
matchingApi = functions.find(
(fn) =>
node.name.text === fn.functionName &&
importTracker.isPotentialReferenceToNamespaceImport(namespaceRef, fn.owningModule),
);
} else if (
// `prop = core.input.required()`
ts.isPropertyAccessExpression(node.expression) &&
ts.isIdentifier(node.expression.expression) &&
ts.isIdentifier(node.expression.name) &&
node.name.text === 'required'
) {
const potentialName = node.expression.name.text;
const namespaceRef = node.expression.expression;
apiReference = node.expression.name;
matchingApi = functions.find(
(fn) =>
fn.functionName === potentialName &&
importTracker.isPotentialReferenceToNamespaceImport(namespaceRef!, fn.owningModule),
);
isRequired = true;
}
if (matchingApi === undefined || apiReference === null) {
return null;
}
return {api: matchingApi, apiReference, isRequired};
}
| {
"end_byte": 6942,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/initializer_functions.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/handler.ts_0_2973 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
compileClassMetadata,
compileDeclareClassMetadata,
compileDeclareDirectiveFromMetadata,
compileDirectiveFromMetadata,
ConstantPool,
FactoryTarget,
makeBindingParser,
R3ClassMetadata,
R3DirectiveMetadata,
WrappedNodeExpr,
} from '@angular/compiler';
import ts from 'typescript';
import {ImportedSymbolsTracker, Reference, ReferenceEmitter} from '../../../imports';
import {
extractSemanticTypeParameters,
SemanticDepGraphUpdater,
} from '../../../incremental/semantic_graph';
import {
ClassPropertyMapping,
DirectiveTypeCheckMeta,
extractDirectiveTypeCheckMeta,
HostDirectiveMeta,
InputMapping,
MatchSource,
MetadataReader,
MetadataRegistry,
MetaKind,
} from '../../../metadata';
import {PartialEvaluator} from '../../../partial_evaluator';
import {PerfEvent, PerfRecorder} from '../../../perf';
import {
ClassDeclaration,
ClassMember,
ClassMemberKind,
Decorator,
ReflectionHost,
} from '../../../reflection';
import {LocalModuleScopeRegistry} from '../../../scope';
import {
AnalysisOutput,
CompilationMode,
CompileResult,
DecoratorHandler,
DetectResult,
HandlerPrecedence,
ResolveResult,
} from '../../../transform';
import {
compileDeclareFactory,
compileInputTransformFields,
compileNgFactoryDefField,
compileResults,
extractClassMetadata,
findAngularDecorator,
getDirectiveDiagnostics,
getProviderDiagnostics,
getUndecoratedClassWithAngularFeaturesDiagnostic,
InjectableClassRegistry,
isAngularDecorator,
readBaseClass,
ReferencesRegistry,
resolveProvidersRequiringFactory,
toFactoryMetadata,
validateHostDirectives,
} from '../../common';
import {extractDirectiveMetadata} from './shared';
import {DirectiveSymbol} from './symbol';
import {JitDeclarationRegistry} from '../../common/src/jit_declaration_registry';
const FIELD_DECORATORS = [
'Input',
'Output',
'ViewChild',
'ViewChildren',
'ContentChild',
'ContentChildren',
'HostBinding',
'HostListener',
];
const LIFECYCLE_HOOKS = new Set([
'ngOnChanges',
'ngOnInit',
'ngOnDestroy',
'ngDoCheck',
'ngAfterViewInit',
'ngAfterViewChecked',
'ngAfterContentInit',
'ngAfterContentChecked',
]);
export interface DirectiveHandlerData {
baseClass: Reference<ClassDeclaration> | 'dynamic' | null;
typeCheckMeta: DirectiveTypeCheckMeta;
meta: R3DirectiveMetadata;
classMetadata: R3ClassMetadata | null;
providersRequiringFactory: Set<Reference<ClassDeclaration>> | null;
inputs: ClassPropertyMapping<InputMapping>;
inputFieldNamesFromMetadataArray: Set<string>;
outputs: ClassPropertyMapping;
isPoisoned: boolean;
isStructural: boolean;
decorator: ts.Decorator | null;
hostDirectives: HostDirectiveMeta[] | null;
rawHostDirectives: ts.Expression | null;
} | {
"end_byte": 2973,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/handler.ts_2975_12052 | export class DirectiveDecoratorHandler
implements DecoratorHandler<Decorator | null, DirectiveHandlerData, DirectiveSymbol, unknown>
{
constructor(
private reflector: ReflectionHost,
private evaluator: PartialEvaluator,
private metaRegistry: MetadataRegistry,
private scopeRegistry: LocalModuleScopeRegistry,
private metaReader: MetadataReader,
private injectableRegistry: InjectableClassRegistry,
private refEmitter: ReferenceEmitter,
private referencesRegistry: ReferencesRegistry,
private isCore: boolean,
private strictCtorDeps: boolean,
private semanticDepGraphUpdater: SemanticDepGraphUpdater | null,
private annotateForClosureCompiler: boolean,
private perf: PerfRecorder,
private importTracker: ImportedSymbolsTracker,
private includeClassMetadata: boolean,
private readonly compilationMode: CompilationMode,
private readonly jitDeclarationRegistry: JitDeclarationRegistry,
private readonly strictStandalone: boolean,
) {}
readonly precedence = HandlerPrecedence.PRIMARY;
readonly name = 'DirectiveDecoratorHandler';
detect(
node: ClassDeclaration,
decorators: Decorator[] | null,
): DetectResult<Decorator | null> | undefined {
// If a class is undecorated but uses Angular features, we detect it as an
// abstract directive. This is an unsupported pattern as of v10, but we want
// to still detect these patterns so that we can report diagnostics.
if (!decorators) {
const angularField = this.findClassFieldWithAngularFeatures(node);
return angularField
? {trigger: angularField.node, decorator: null, metadata: null}
: undefined;
} else {
const decorator = findAngularDecorator(decorators, 'Directive', this.isCore);
return decorator ? {trigger: decorator.node, decorator, metadata: decorator} : undefined;
}
}
analyze(
node: ClassDeclaration,
decorator: Readonly<Decorator | null>,
): AnalysisOutput<DirectiveHandlerData> {
// Skip processing of the class declaration if compilation of undecorated classes
// with Angular features is disabled. Previously in ngtsc, such classes have always
// been processed, but we want to enforce a consistent decorator mental model.
// See: https://v9.angular.io/guide/migration-undecorated-classes.
if (decorator === null) {
// If compiling @angular/core, skip the diagnostic as core occasionally hand-writes
// definitions.
if (this.isCore) {
return {};
}
return {diagnostics: [getUndecoratedClassWithAngularFeaturesDiagnostic(node)]};
}
this.perf.eventCount(PerfEvent.AnalyzeDirective);
const directiveResult = extractDirectiveMetadata(
node,
decorator,
this.reflector,
this.importTracker,
this.evaluator,
this.refEmitter,
this.referencesRegistry,
this.isCore,
this.annotateForClosureCompiler,
this.compilationMode,
/* defaultSelector */ null,
this.strictStandalone,
);
// `extractDirectiveMetadata` returns `jitForced = true` when the `@Directive` has
// set `jit: true`. In this case, compilation of the decorator is skipped. Returning
// an empty object signifies that no analysis was produced.
if (directiveResult.jitForced) {
this.jitDeclarationRegistry.jitDeclarations.add(node);
return {};
}
const analysis = directiveResult.metadata;
let providersRequiringFactory: Set<Reference<ClassDeclaration>> | null = null;
if (directiveResult !== undefined && directiveResult.decorator.has('providers')) {
providersRequiringFactory = resolveProvidersRequiringFactory(
directiveResult.decorator.get('providers')!,
this.reflector,
this.evaluator,
);
}
return {
analysis: {
inputs: directiveResult.inputs,
inputFieldNamesFromMetadataArray: directiveResult.inputFieldNamesFromMetadataArray,
outputs: directiveResult.outputs,
meta: analysis,
hostDirectives: directiveResult.hostDirectives,
rawHostDirectives: directiveResult.rawHostDirectives,
classMetadata: this.includeClassMetadata
? extractClassMetadata(node, this.reflector, this.isCore, this.annotateForClosureCompiler)
: null,
baseClass: readBaseClass(node, this.reflector, this.evaluator),
typeCheckMeta: extractDirectiveTypeCheckMeta(node, directiveResult.inputs, this.reflector),
providersRequiringFactory,
isPoisoned: false,
isStructural: directiveResult.isStructural,
decorator: (decorator?.node as ts.Decorator | null) ?? null,
},
};
}
symbol(node: ClassDeclaration, analysis: Readonly<DirectiveHandlerData>): DirectiveSymbol {
const typeParameters = extractSemanticTypeParameters(node);
return new DirectiveSymbol(
node,
analysis.meta.selector,
analysis.inputs,
analysis.outputs,
analysis.meta.exportAs,
analysis.typeCheckMeta,
typeParameters,
);
}
register(node: ClassDeclaration, analysis: Readonly<DirectiveHandlerData>): void {
// Register this directive's information with the `MetadataRegistry`. This ensures that
// the information about the directive is available during the compile() phase.
const ref = new Reference(node);
this.metaRegistry.registerDirectiveMetadata({
kind: MetaKind.Directive,
matchSource: MatchSource.Selector,
ref,
name: node.name.text,
selector: analysis.meta.selector,
exportAs: analysis.meta.exportAs,
inputs: analysis.inputs,
inputFieldNamesFromMetadataArray: analysis.inputFieldNamesFromMetadataArray,
outputs: analysis.outputs,
queries: analysis.meta.queries.map((query) => query.propertyName),
isComponent: false,
baseClass: analysis.baseClass,
hostDirectives: analysis.hostDirectives,
...analysis.typeCheckMeta,
isPoisoned: analysis.isPoisoned,
isStructural: analysis.isStructural,
animationTriggerNames: null,
isStandalone: analysis.meta.isStandalone,
isSignal: analysis.meta.isSignal,
imports: null,
rawImports: null,
deferredImports: null,
schemas: null,
ngContentSelectors: null,
decorator: analysis.decorator,
preserveWhitespaces: false,
// Directives analyzed within our own compilation are not _assumed_ to export providers.
// Instead, we statically analyze their imports to make a direct determination.
assumedToExportProviders: false,
isExplicitlyDeferred: false,
});
this.injectableRegistry.registerInjectable(node, {
ctorDeps: analysis.meta.deps,
});
}
resolve(
node: ClassDeclaration,
analysis: DirectiveHandlerData,
symbol: DirectiveSymbol,
): ResolveResult<unknown> {
if (this.compilationMode === CompilationMode.LOCAL) {
return {};
}
if (this.semanticDepGraphUpdater !== null && analysis.baseClass instanceof Reference) {
symbol.baseClass = this.semanticDepGraphUpdater.getSymbol(analysis.baseClass.node);
}
const diagnostics: ts.Diagnostic[] = [];
if (
analysis.providersRequiringFactory !== null &&
analysis.meta.providers instanceof WrappedNodeExpr
) {
const providerDiagnostics = getProviderDiagnostics(
analysis.providersRequiringFactory,
analysis.meta.providers!.node,
this.injectableRegistry,
);
diagnostics.push(...providerDiagnostics);
}
const directiveDiagnostics = getDirectiveDiagnostics(
node,
this.injectableRegistry,
this.evaluator,
this.reflector,
this.scopeRegistry,
this.strictCtorDeps,
'Directive',
);
if (directiveDiagnostics !== null) {
diagnostics.push(...directiveDiagnostics);
}
const hostDirectivesDiagnotics =
analysis.hostDirectives && analysis.rawHostDirectives
? validateHostDirectives(
analysis.rawHostDirectives,
analysis.hostDirectives,
this.metaReader,
)
: null;
if (hostDirectivesDiagnotics !== null) {
diagnostics.push(...hostDirectivesDiagnotics);
}
return {diagnostics: diagnostics.length > 0 ? diagnostics : undefined};
}
compileFull(
node: ClassDeclaration,
analysis: Readonly<DirectiveHandlerData>,
resolution: Readonly<unknown>,
pool: ConstantPool,
): CompileResult[] {
const fac = compileNgFactoryDefField(toFactoryMetadata(analysis.meta, FactoryTarget.Directive));
const def = compileDirectiveFromMetadata(analysis.meta, pool, makeBindingParser());
const inputTransformFields = compileInputTransformFields(analysis.inputs);
const classMetadata =
analysis.classMetadata !== null
? compileClassMetadata(analysis.classMetadata).toStmt()
: null;
return compileResults(
fac,
def,
classMetadata,
'ɵdir',
inputTransformFields,
null /* deferrableImports */,
);
}
| {
"end_byte": 12052,
"start_byte": 2975,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/handler.ts_12056_14438 | ompilePartial(
node: ClassDeclaration,
analysis: Readonly<DirectiveHandlerData>,
resolution: Readonly<unknown>,
): CompileResult[] {
const fac = compileDeclareFactory(toFactoryMetadata(analysis.meta, FactoryTarget.Directive));
const def = compileDeclareDirectiveFromMetadata(analysis.meta);
const inputTransformFields = compileInputTransformFields(analysis.inputs);
const classMetadata =
analysis.classMetadata !== null
? compileDeclareClassMetadata(analysis.classMetadata).toStmt()
: null;
return compileResults(
fac,
def,
classMetadata,
'ɵdir',
inputTransformFields,
null /* deferrableImports */,
);
}
compileLocal(
node: ClassDeclaration,
analysis: Readonly<DirectiveHandlerData>,
resolution: Readonly<unknown>,
pool: ConstantPool,
): CompileResult[] {
const fac = compileNgFactoryDefField(toFactoryMetadata(analysis.meta, FactoryTarget.Directive));
const def = compileDirectiveFromMetadata(analysis.meta, pool, makeBindingParser());
const inputTransformFields = compileInputTransformFields(analysis.inputs);
const classMetadata =
analysis.classMetadata !== null
? compileClassMetadata(analysis.classMetadata).toStmt()
: null;
return compileResults(
fac,
def,
classMetadata,
'ɵdir',
inputTransformFields,
null /* deferrableImports */,
);
}
/**
* Checks if a given class uses Angular features and returns the TypeScript node
* that indicated the usage. Classes are considered using Angular features if they
* contain class members that are either decorated with a known Angular decorator,
* or if they correspond to a known Angular lifecycle hook.
*/
private findClassFieldWithAngularFeatures(node: ClassDeclaration): ClassMember | undefined {
return this.reflector.getMembersOfClass(node).find((member) => {
if (
!member.isStatic &&
member.kind === ClassMemberKind.Method &&
LIFECYCLE_HOOKS.has(member.name)
) {
return true;
}
if (member.decorators) {
return member.decorators.some((decorator) =>
FIELD_DECORATORS.some((decoratorName) =>
isAngularDecorator(decorator, decoratorName, this.isCore),
),
);
}
return false;
});
}
}
| {
"end_byte": 14438,
"start_byte": 12056,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/handler.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/directive/src/output_function.ts_0_3165 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {ErrorCode, FatalDiagnosticError} from '../../../diagnostics';
import {ImportedSymbolsTracker} from '../../../imports';
import {InputOrOutput} from '../../../metadata';
import {ClassMember, ClassMemberAccessLevel, ReflectionHost} from '../../../reflection';
import {validateAccessOfInitializerApiMember} from './initializer_function_access';
import {InitializerApiFunction, tryParseInitializerApi} from './initializer_functions';
import {parseAndValidateInputAndOutputOptions} from './input_output_parse_options';
// Outputs are accessed from parents, via the `listener` instruction.
// Conceptually, the fields need to be publicly readable, but in practice,
// accessing `protected` or `private` members works at runtime, so we can allow
// such outputs that may not want to expose the `OutputRef` as part of the
// component API, programmatically.
// Note: `private` is omitted intentionally as this would be a conceptual confusion point.
const allowedAccessLevels = [
ClassMemberAccessLevel.PublicWritable,
ClassMemberAccessLevel.PublicReadonly,
ClassMemberAccessLevel.Protected,
];
/** Possible functions that can declare an output. */
export const OUTPUT_INITIALIZER_FNS: InitializerApiFunction[] = [
{
functionName: 'output',
owningModule: '@angular/core',
allowedAccessLevels,
},
{
functionName: 'outputFromObservable',
owningModule: '@angular/core/rxjs-interop',
allowedAccessLevels,
},
];
/**
* Attempts to parse a signal output class member. Returns the parsed
* input mapping if possible.
*/
export function tryParseInitializerBasedOutput(
member: Pick<ClassMember, 'name' | 'value' | 'accessLevel'>,
reflector: ReflectionHost,
importTracker: ImportedSymbolsTracker,
): {call: ts.CallExpression; metadata: InputOrOutput} | null {
if (member.value === null) {
return null;
}
const output = tryParseInitializerApi(
OUTPUT_INITIALIZER_FNS,
member.value,
reflector,
importTracker,
);
if (output === null) {
return null;
}
if (output.isRequired) {
throw new FatalDiagnosticError(
ErrorCode.INITIALIZER_API_NO_REQUIRED_FUNCTION,
output.call,
`Output does not support ".required()".`,
);
}
validateAccessOfInitializerApiMember(output, member);
// Options are the first parameter for `output()`, while for
// the interop `outputFromObservable()` they are the second argument.
const optionsNode = (
output.api.functionName === 'output' ? output.call.arguments[0] : output.call.arguments[1]
) as ts.Expression | undefined;
const options =
optionsNode !== undefined ? parseAndValidateInputAndOutputOptions(optionsNode) : null;
const classPropertyName = member.name;
return {
call: output.call,
metadata: {
// Outputs are not signal-based.
isSignal: false,
classPropertyName,
bindingPropertyName: options?.alias ?? classPropertyName,
},
};
}
| {
"end_byte": 3165,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/directive/src/output_function.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/src/pipe.ts_0_8913 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
compileClassMetadata,
compileDeclareClassMetadata,
compileDeclarePipeFromMetadata,
compilePipeFromMetadata,
FactoryTarget,
R3ClassMetadata,
R3PipeMetadata,
WrappedNodeExpr,
} from '@angular/compiler';
import ts from 'typescript';
import {ErrorCode, FatalDiagnosticError} from '../../diagnostics';
import {Reference} from '../../imports';
import {SemanticSymbol} from '../../incremental/semantic_graph';
import {MetadataRegistry, MetaKind} from '../../metadata';
import {PartialEvaluator} from '../../partial_evaluator';
import {PerfEvent, PerfRecorder} from '../../perf';
import {ClassDeclaration, Decorator, ReflectionHost, reflectObjectLiteral} from '../../reflection';
import {LocalModuleScopeRegistry} from '../../scope';
import {
AnalysisOutput,
CompilationMode,
CompileResult,
DecoratorHandler,
DetectResult,
HandlerPrecedence,
ResolveResult,
} from '../../transform';
import {
compileDeclareFactory,
compileNgFactoryDefField,
compileResults,
createValueHasWrongTypeError,
extractClassMetadata,
findAngularDecorator,
getValidConstructorDependencies,
InjectableClassRegistry,
makeDuplicateDeclarationError,
toFactoryMetadata,
unwrapExpression,
wrapTypeReference,
} from '../common';
import {NG_STANDALONE_DEFAULT_VALUE} from '../common/src/standalone-default-value';
export interface PipeHandlerData {
meta: R3PipeMetadata;
classMetadata: R3ClassMetadata | null;
pipeNameExpr: ts.Expression;
decorator: ts.Decorator | null;
}
/**
* Represents an Angular pipe.
*/
export class PipeSymbol extends SemanticSymbol {
constructor(
decl: ClassDeclaration,
public readonly name: string,
) {
super(decl);
}
override isPublicApiAffected(previousSymbol: SemanticSymbol): boolean {
if (!(previousSymbol instanceof PipeSymbol)) {
return true;
}
return this.name !== previousSymbol.name;
}
override isTypeCheckApiAffected(previousSymbol: SemanticSymbol): boolean {
return this.isPublicApiAffected(previousSymbol);
}
}
export class PipeDecoratorHandler
implements DecoratorHandler<Decorator, PipeHandlerData, PipeSymbol, unknown>
{
constructor(
private reflector: ReflectionHost,
private evaluator: PartialEvaluator,
private metaRegistry: MetadataRegistry,
private scopeRegistry: LocalModuleScopeRegistry,
private injectableRegistry: InjectableClassRegistry,
private isCore: boolean,
private perf: PerfRecorder,
private includeClassMetadata: boolean,
private readonly compilationMode: CompilationMode,
private readonly generateExtraImportsInLocalMode: boolean,
private readonly strictStandalone: boolean,
) {}
readonly precedence = HandlerPrecedence.PRIMARY;
readonly name = 'PipeDecoratorHandler';
detect(
node: ClassDeclaration,
decorators: Decorator[] | null,
): DetectResult<Decorator> | undefined {
if (!decorators) {
return undefined;
}
const decorator = findAngularDecorator(decorators, 'Pipe', this.isCore);
if (decorator !== undefined) {
return {
trigger: decorator.node,
decorator: decorator,
metadata: decorator,
};
} else {
return undefined;
}
}
analyze(
clazz: ClassDeclaration,
decorator: Readonly<Decorator>,
): AnalysisOutput<PipeHandlerData> {
this.perf.eventCount(PerfEvent.AnalyzePipe);
const name = clazz.name.text;
const type = wrapTypeReference(this.reflector, clazz);
if (decorator.args === null) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_NOT_CALLED,
decorator.node,
`@Pipe must be called`,
);
}
if (decorator.args.length !== 1) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG,
decorator.node,
'@Pipe must have exactly one argument',
);
}
const meta = unwrapExpression(decorator.args[0]);
if (!ts.isObjectLiteralExpression(meta)) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARG_NOT_LITERAL,
meta,
'@Pipe must have a literal argument',
);
}
const pipe = reflectObjectLiteral(meta);
if (!pipe.has('name')) {
throw new FatalDiagnosticError(
ErrorCode.PIPE_MISSING_NAME,
meta,
`@Pipe decorator is missing name field`,
);
}
const pipeNameExpr = pipe.get('name')!;
const pipeName = this.evaluator.evaluate(pipeNameExpr);
if (typeof pipeName !== 'string') {
throw createValueHasWrongTypeError(pipeNameExpr, pipeName, `@Pipe.name must be a string`);
}
let pure = true;
if (pipe.has('pure')) {
const expr = pipe.get('pure')!;
const pureValue = this.evaluator.evaluate(expr);
if (typeof pureValue !== 'boolean') {
throw createValueHasWrongTypeError(expr, pureValue, `@Pipe.pure must be a boolean`);
}
pure = pureValue;
}
let isStandalone = NG_STANDALONE_DEFAULT_VALUE;
if (pipe.has('standalone')) {
const expr = pipe.get('standalone')!;
const resolved = this.evaluator.evaluate(expr);
if (typeof resolved !== 'boolean') {
throw createValueHasWrongTypeError(expr, resolved, `standalone flag must be a boolean`);
}
isStandalone = resolved;
if (!isStandalone && this.strictStandalone) {
throw new FatalDiagnosticError(
ErrorCode.NON_STANDALONE_NOT_ALLOWED,
expr,
`Only standalone pipes are allowed when 'strictStandalone' is enabled.`,
);
}
}
return {
analysis: {
meta: {
name,
type,
typeArgumentCount: this.reflector.getGenericArityOfClass(clazz) || 0,
pipeName,
deps: getValidConstructorDependencies(clazz, this.reflector, this.isCore),
pure,
isStandalone,
},
classMetadata: this.includeClassMetadata
? extractClassMetadata(clazz, this.reflector, this.isCore)
: null,
pipeNameExpr,
decorator: (decorator?.node as ts.Decorator | null) ?? null,
},
};
}
symbol(node: ClassDeclaration, analysis: Readonly<PipeHandlerData>): PipeSymbol {
return new PipeSymbol(node, analysis.meta.pipeName);
}
register(node: ClassDeclaration, analysis: Readonly<PipeHandlerData>): void {
const ref = new Reference(node);
this.metaRegistry.registerPipeMetadata({
kind: MetaKind.Pipe,
ref,
name: analysis.meta.pipeName,
nameExpr: analysis.pipeNameExpr,
isStandalone: analysis.meta.isStandalone,
decorator: analysis.decorator,
isExplicitlyDeferred: false,
});
this.injectableRegistry.registerInjectable(node, {
ctorDeps: analysis.meta.deps,
});
}
resolve(node: ClassDeclaration): ResolveResult<unknown> {
if (this.compilationMode === CompilationMode.LOCAL) {
return {};
}
const duplicateDeclData = this.scopeRegistry.getDuplicateDeclarations(node);
if (duplicateDeclData !== null) {
// This pipe was declared twice (or more).
return {
diagnostics: [makeDuplicateDeclarationError(node, duplicateDeclData, 'Pipe')],
};
}
return {};
}
compileFull(node: ClassDeclaration, analysis: Readonly<PipeHandlerData>): CompileResult[] {
const fac = compileNgFactoryDefField(toFactoryMetadata(analysis.meta, FactoryTarget.Pipe));
const def = compilePipeFromMetadata(analysis.meta);
const classMetadata =
analysis.classMetadata !== null
? compileClassMetadata(analysis.classMetadata).toStmt()
: null;
return compileResults(fac, def, classMetadata, 'ɵpipe', null, null /* deferrableImports */);
}
compilePartial(node: ClassDeclaration, analysis: Readonly<PipeHandlerData>): CompileResult[] {
const fac = compileDeclareFactory(toFactoryMetadata(analysis.meta, FactoryTarget.Pipe));
const def = compileDeclarePipeFromMetadata(analysis.meta);
const classMetadata =
analysis.classMetadata !== null
? compileDeclareClassMetadata(analysis.classMetadata).toStmt()
: null;
return compileResults(fac, def, classMetadata, 'ɵpipe', null, null /* deferrableImports */);
}
compileLocal(node: ClassDeclaration, analysis: Readonly<PipeHandlerData>): CompileResult[] {
const fac = compileNgFactoryDefField(toFactoryMetadata(analysis.meta, FactoryTarget.Pipe));
const def = compilePipeFromMetadata(analysis.meta);
const classMetadata =
analysis.classMetadata !== null
? compileClassMetadata(analysis.classMetadata).toStmt()
: null;
return compileResults(fac, def, classMetadata, 'ɵpipe', null, null /* deferrableImports */);
}
}
| {
"end_byte": 8913,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/src/pipe.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/src/injectable.ts_0_7607 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
compileClassMetadata,
CompileClassMetadataFn,
compileDeclareClassMetadata,
compileDeclareInjectableFromMetadata,
compileInjectable,
createMayBeForwardRefExpression,
FactoryTarget,
ForwardRefHandling,
LiteralExpr,
MaybeForwardRefExpression,
R3ClassMetadata,
R3CompiledExpression,
R3DependencyMetadata,
R3InjectableMetadata,
WrappedNodeExpr,
} from '@angular/compiler';
import ts from 'typescript';
import {InjectableClassRegistry, isAbstractClassDeclaration} from '../../annotations/common';
import {ErrorCode, FatalDiagnosticError} from '../../diagnostics';
import {PartialEvaluator} from '../../partial_evaluator';
import {PerfEvent, PerfRecorder} from '../../perf';
import {ClassDeclaration, Decorator, ReflectionHost, reflectObjectLiteral} from '../../reflection';
import {
AnalysisOutput,
CompilationMode,
CompileResult,
DecoratorHandler,
DetectResult,
HandlerPrecedence,
ResolveResult,
} from '../../transform';
import {
checkInheritanceOfInjectable,
compileDeclareFactory,
CompileFactoryFn,
compileNgFactoryDefField,
extractClassMetadata,
findAngularDecorator,
getConstructorDependencies,
getValidConstructorDependencies,
isAngularCore,
toFactoryMetadata,
tryUnwrapForwardRef,
unwrapConstructorDependencies,
validateConstructorDependencies,
wrapTypeReference,
} from '../common';
export interface InjectableHandlerData {
meta: R3InjectableMetadata;
classMetadata: R3ClassMetadata | null;
ctorDeps: R3DependencyMetadata[] | 'invalid' | null;
needsFactory: boolean;
}
/**
* Adapts the `compileInjectable` compiler for `@Injectable` decorators to the Ivy compiler.
*/
export class InjectableDecoratorHandler
implements DecoratorHandler<Decorator, InjectableHandlerData, null, unknown>
{
constructor(
private reflector: ReflectionHost,
private evaluator: PartialEvaluator,
private isCore: boolean,
private strictCtorDeps: boolean,
private injectableRegistry: InjectableClassRegistry,
private perf: PerfRecorder,
private includeClassMetadata: boolean,
private readonly compilationMode: CompilationMode,
/**
* What to do if the injectable already contains a ɵprov property.
*
* If true then an error diagnostic is reported.
* If false then there is no error and a new ɵprov property is not added.
*/
private errorOnDuplicateProv = true,
) {}
readonly precedence = HandlerPrecedence.SHARED;
readonly name = 'InjectableDecoratorHandler';
detect(
node: ClassDeclaration,
decorators: Decorator[] | null,
): DetectResult<Decorator> | undefined {
if (!decorators) {
return undefined;
}
const decorator = findAngularDecorator(decorators, 'Injectable', this.isCore);
if (decorator !== undefined) {
return {
trigger: decorator.node,
decorator: decorator,
metadata: decorator,
};
} else {
return undefined;
}
}
analyze(
node: ClassDeclaration,
decorator: Readonly<Decorator>,
): AnalysisOutput<InjectableHandlerData> {
this.perf.eventCount(PerfEvent.AnalyzeInjectable);
const meta = extractInjectableMetadata(node, decorator, this.reflector);
const decorators = this.reflector.getDecoratorsOfDeclaration(node);
return {
analysis: {
meta,
ctorDeps: extractInjectableCtorDeps(
node,
meta,
decorator,
this.reflector,
this.isCore,
this.strictCtorDeps,
),
classMetadata: this.includeClassMetadata
? extractClassMetadata(node, this.reflector, this.isCore)
: null,
// Avoid generating multiple factories if a class has
// more Angular decorators, apart from Injectable.
needsFactory:
!decorators ||
decorators.every((current) => !isAngularCore(current) || current.name === 'Injectable'),
},
};
}
symbol(): null {
return null;
}
register(node: ClassDeclaration, analysis: InjectableHandlerData): void {
if (this.compilationMode === CompilationMode.LOCAL) {
return;
}
this.injectableRegistry.registerInjectable(node, {
ctorDeps: analysis.ctorDeps,
});
}
resolve(
node: ClassDeclaration,
analysis: Readonly<InjectableHandlerData>,
): ResolveResult<unknown> {
if (this.compilationMode === CompilationMode.LOCAL) {
return {};
}
if (requiresValidCtor(analysis.meta)) {
const diagnostic = checkInheritanceOfInjectable(
node,
this.injectableRegistry,
this.reflector,
this.evaluator,
this.strictCtorDeps,
'Injectable',
);
if (diagnostic !== null) {
return {
diagnostics: [diagnostic],
};
}
}
return {};
}
compileFull(node: ClassDeclaration, analysis: Readonly<InjectableHandlerData>): CompileResult[] {
return this.compile(
compileNgFactoryDefField,
(meta) => compileInjectable(meta, false),
compileClassMetadata,
node,
analysis,
);
}
compilePartial(
node: ClassDeclaration,
analysis: Readonly<InjectableHandlerData>,
): CompileResult[] {
return this.compile(
compileDeclareFactory,
compileDeclareInjectableFromMetadata,
compileDeclareClassMetadata,
node,
analysis,
);
}
compileLocal(node: ClassDeclaration, analysis: Readonly<InjectableHandlerData>): CompileResult[] {
return this.compile(
compileNgFactoryDefField,
(meta) => compileInjectable(meta, false),
compileClassMetadata,
node,
analysis,
);
}
private compile(
compileFactoryFn: CompileFactoryFn,
compileInjectableFn: (meta: R3InjectableMetadata) => R3CompiledExpression,
compileClassMetadataFn: CompileClassMetadataFn,
node: ClassDeclaration,
analysis: Readonly<InjectableHandlerData>,
): CompileResult[] {
const results: CompileResult[] = [];
if (analysis.needsFactory) {
const meta = analysis.meta;
const factoryRes = compileFactoryFn(
toFactoryMetadata({...meta, deps: analysis.ctorDeps}, FactoryTarget.Injectable),
);
if (analysis.classMetadata !== null) {
factoryRes.statements.push(compileClassMetadataFn(analysis.classMetadata).toStmt());
}
results.push(factoryRes);
}
const ɵprov = this.reflector.getMembersOfClass(node).find((member) => member.name === 'ɵprov');
if (ɵprov !== undefined && this.errorOnDuplicateProv) {
throw new FatalDiagnosticError(
ErrorCode.INJECTABLE_DUPLICATE_PROV,
ɵprov.nameNode || ɵprov.node || node,
'Injectables cannot contain a static ɵprov property, because the compiler is going to generate one.',
);
}
if (ɵprov === undefined) {
// Only add a new ɵprov if there is not one already
const res = compileInjectableFn(analysis.meta);
results.push({
name: 'ɵprov',
initializer: res.expression,
statements: res.statements,
type: res.type,
deferrableImports: null,
});
}
return results;
}
}
/**
* Read metadata from the `@Injectable` decorator and produce the `IvyInjectableMetadata`, the
* input metadata needed to run `compileInjectable`.
*
* A `null` return value indicates this is @Injectable has invalid data.
*/
function e | {
"end_byte": 7607,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/src/injectable.ts"
} |
angular/packages/compiler-cli/src/ngtsc/annotations/src/injectable.ts_7608_14793 | tractInjectableMetadata(
clazz: ClassDeclaration,
decorator: Decorator,
reflector: ReflectionHost,
): R3InjectableMetadata {
const name = clazz.name.text;
const type = wrapTypeReference(reflector, clazz);
const typeArgumentCount = reflector.getGenericArityOfClass(clazz) || 0;
if (decorator.args === null) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_NOT_CALLED,
decorator.node,
'@Injectable must be called',
);
}
if (decorator.args.length === 0) {
return {
name,
type,
typeArgumentCount,
providedIn: createMayBeForwardRefExpression(new LiteralExpr(null), ForwardRefHandling.None),
};
} else if (decorator.args.length === 1) {
const metaNode = decorator.args[0];
// Firstly make sure the decorator argument is an inline literal - if not, it's illegal to
// transport references from one location to another. This is the problem that lowering
// used to solve - if this restriction proves too undesirable we can re-implement lowering.
if (!ts.isObjectLiteralExpression(metaNode)) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARG_NOT_LITERAL,
metaNode,
`@Injectable argument must be an object literal`,
);
}
// Resolve the fields of the literal into a map of field name to expression.
const meta = reflectObjectLiteral(metaNode);
const providedIn = meta.has('providedIn')
? getProviderExpression(meta.get('providedIn')!, reflector)
: createMayBeForwardRefExpression(new LiteralExpr(null), ForwardRefHandling.None);
let deps: R3DependencyMetadata[] | undefined = undefined;
if ((meta.has('useClass') || meta.has('useFactory')) && meta.has('deps')) {
const depsExpr = meta.get('deps')!;
if (!ts.isArrayLiteralExpression(depsExpr)) {
throw new FatalDiagnosticError(
ErrorCode.VALUE_NOT_LITERAL,
depsExpr,
`@Injectable deps metadata must be an inline array`,
);
}
deps = depsExpr.elements.map((dep) => getDep(dep, reflector));
}
const result: R3InjectableMetadata = {name, type, typeArgumentCount, providedIn};
if (meta.has('useValue')) {
result.useValue = getProviderExpression(meta.get('useValue')!, reflector);
} else if (meta.has('useExisting')) {
result.useExisting = getProviderExpression(meta.get('useExisting')!, reflector);
} else if (meta.has('useClass')) {
result.useClass = getProviderExpression(meta.get('useClass')!, reflector);
result.deps = deps;
} else if (meta.has('useFactory')) {
result.useFactory = new WrappedNodeExpr(meta.get('useFactory')!);
result.deps = deps;
}
return result;
} else {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_ARITY_WRONG,
decorator.args[2],
'Too many arguments to @Injectable',
);
}
}
/**
* Get the `R3ProviderExpression` for this `expression`.
*
* The `useValue`, `useExisting` and `useClass` properties might be wrapped in a `ForwardRef`, which
* needs to be unwrapped. This function will do that unwrapping and set a flag on the returned
* object to indicate whether the value needed unwrapping.
*/
function getProviderExpression(
expression: ts.Expression,
reflector: ReflectionHost,
): MaybeForwardRefExpression {
const forwardRefValue = tryUnwrapForwardRef(expression, reflector);
return createMayBeForwardRefExpression(
new WrappedNodeExpr(forwardRefValue ?? expression),
forwardRefValue !== null ? ForwardRefHandling.Unwrapped : ForwardRefHandling.None,
);
}
function extractInjectableCtorDeps(
clazz: ClassDeclaration,
meta: R3InjectableMetadata,
decorator: Decorator,
reflector: ReflectionHost,
isCore: boolean,
strictCtorDeps: boolean,
) {
if (decorator.args === null) {
throw new FatalDiagnosticError(
ErrorCode.DECORATOR_NOT_CALLED,
decorator.node,
'@Injectable must be called',
);
}
let ctorDeps: R3DependencyMetadata[] | 'invalid' | null = null;
if (decorator.args.length === 0) {
// Ideally, using @Injectable() would have the same effect as using @Injectable({...}), and be
// subject to the same validation. However, existing Angular code abuses @Injectable, applying
// it to things like abstract classes with constructors that were never meant for use with
// Angular's DI.
//
// To deal with this, @Injectable() without an argument is more lenient, and if the
// constructor signature does not work for DI then a factory definition (ɵfac) that throws is
// generated.
if (strictCtorDeps && !isAbstractClassDeclaration(clazz)) {
ctorDeps = getValidConstructorDependencies(clazz, reflector, isCore);
} else {
ctorDeps = unwrapConstructorDependencies(
getConstructorDependencies(clazz, reflector, isCore),
);
}
return ctorDeps;
} else if (decorator.args.length === 1) {
const rawCtorDeps = getConstructorDependencies(clazz, reflector, isCore);
if (strictCtorDeps && !isAbstractClassDeclaration(clazz) && requiresValidCtor(meta)) {
// Since use* was not provided for a concrete class, validate the deps according to
// strictCtorDeps.
ctorDeps = validateConstructorDependencies(clazz, rawCtorDeps);
} else {
ctorDeps = unwrapConstructorDependencies(rawCtorDeps);
}
}
return ctorDeps;
}
function requiresValidCtor(meta: R3InjectableMetadata): boolean {
return (
meta.useValue === undefined &&
meta.useExisting === undefined &&
meta.useClass === undefined &&
meta.useFactory === undefined
);
}
function getDep(dep: ts.Expression, reflector: ReflectionHost): R3DependencyMetadata {
const meta: R3DependencyMetadata = {
token: new WrappedNodeExpr(dep),
attributeNameType: null,
host: false,
optional: false,
self: false,
skipSelf: false,
};
function maybeUpdateDecorator(
dec: ts.Identifier,
reflector: ReflectionHost,
token?: ts.Expression,
): boolean {
const source = reflector.getImportOfIdentifier(dec);
if (source === null || source.from !== '@angular/core') {
return false;
}
switch (source.name) {
case 'Inject':
if (token !== undefined) {
meta.token = new WrappedNodeExpr(token);
}
break;
case 'Optional':
meta.optional = true;
break;
case 'SkipSelf':
meta.skipSelf = true;
break;
case 'Self':
meta.self = true;
break;
default:
return false;
}
return true;
}
if (ts.isArrayLiteralExpression(dep)) {
dep.elements.forEach((el) => {
let isDecorator = false;
if (ts.isIdentifier(el)) {
isDecorator = maybeUpdateDecorator(el, reflector);
} else if (ts.isNewExpression(el) && ts.isIdentifier(el.expression)) {
const token = (el.arguments && el.arguments.length > 0 && el.arguments[0]) || undefined;
isDecorator = maybeUpdateDecorator(el.expression, reflector, token);
}
if (!isDecorator) {
meta.token = new WrappedNodeExpr(el);
}
});
}
return meta;
}
| {
"end_byte": 14793,
"start_byte": 7608,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/annotations/src/injectable.ts"
} |
angular/packages/compiler-cli/src/ngtsc/testing/BUILD.bazel_0_599 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "testing",
testonly = True,
srcs = glob([
"**/*.ts",
]),
module_name = "@angular/compiler-cli/src/ngtsc/testing",
deps = [
"//packages:types",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/file_system/testing",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/util",
"@npm//@bazel/runfiles",
"@npm//typescript",
],
)
| {
"end_byte": 599,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/testing/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/testing/index.ts_0_392 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './src/utils';
export * from './src/cached_source_files';
export * from './src/compiler_host';
export * from './src/mock_file_loading';
export * from './src/runfile_helpers';
| {
"end_byte": 392,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/testing/index.ts"
} |
angular/packages/compiler-cli/src/ngtsc/testing/fake_common/BUILD.bazel_0_406 | load("//tools:defaults.bzl", "ng_package", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "fake_common",
srcs = [
"index.ts",
],
module_name = "@angular/common",
deps = [
"//packages/core",
],
)
ng_package(
name = "npm_package",
srcs = [
"package.json",
],
deps = [
":fake_common",
],
)
| {
"end_byte": 406,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/testing/fake_common/BUILD.bazel"
} |
angular/packages/compiler-cli/src/ngtsc/testing/fake_common/index.ts_0_3179 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
NgIterable,
TemplateRef,
TrackByFunction,
ɵɵDirectiveDeclaration,
ɵɵNgModuleDeclaration,
ɵɵPipeDeclaration,
} from '@angular/core';
export interface NgForOfContext<T, U extends NgIterable<T>> {
$implicit: T;
ngForOf: U;
odd: boolean;
event: boolean;
first: boolean;
last: boolean;
count: number;
index: number;
}
export interface NgIfContext<T = unknown> {
$implicit: T;
ngIf: T;
}
/**
* A fake version of the NgFor directive.
*/
export declare class NgForOf<T, U extends NgIterable<T>> {
ngForOf: (U & NgIterable<T>) | null | undefined;
ngForTrackBy: TrackByFunction<T>;
ngForTemplate: TemplateRef<NgForOfContext<T, U>>;
static ɵdir: ɵɵDirectiveDeclaration<
NgForOf<any, any>,
'[ngFor][ngForOf]',
never,
{
'ngForOf': 'ngForOf';
'ngForTrackBy': 'ngForTrackBy';
'ngForTemplate': 'ngForTemplate';
},
{},
never
>;
static ngTemplateContextGuard<T, U extends NgIterable<T>>(
dir: NgForOf<T, U>,
ctx: any,
): ctx is NgForOfContext<T, U>;
}
export declare class NgIf<T = unknown> {
ngIf: T;
ngIfThen: TemplateRef<NgIfContext<T>> | null;
ngIfElse: TemplateRef<NgIfContext<T>> | null;
static ɵdir: ɵɵDirectiveDeclaration<
NgIf<any>,
'[ngIf]',
never,
{
'ngIf': 'ngIf';
'ngIfThen': 'ngIfThen';
'ngIfElse': 'ngIfElse';
},
{},
never
>;
static ngTemplateGuard_ngIf: 'binding';
static ngTemplateContextGuard<T>(
dir: NgIf<T>,
ctx: any,
): ctx is NgIfContext<Exclude<T, false | 0 | '' | null | undefined>>;
}
export declare class NgTemplateOutlet<C = unknown> {
ngTemplateOutlet: TemplateRef<C> | null;
ngTemplateOutletContext: C | null;
static ɵdir: ɵɵDirectiveDeclaration<
NgTemplateOutlet<any>,
'[ngTemplateOutlet]',
never,
{
'ngTemplateOutlet': 'ngTemplateOutlet';
'ngTemplateOutletContext': 'ngTemplateOutletContext';
},
{},
never
>;
static ngTemplateContextGuard<T>(dir: NgTemplateOutlet<T>, ctx: any): ctx is T;
}
export declare class DatePipe {
transform(
value: Date | string | number,
format?: string,
timezone?: string,
locale?: string,
): string | null;
transform(value: null | undefined, format?: string, timezone?: string, locale?: string): null;
transform(
value: Date | string | number | null | undefined,
format?: string,
timezone?: string,
locale?: string,
): string | null;
static ɵpipe: ɵɵPipeDeclaration<DatePipe, 'date'>;
}
export declare class IndexPipe {
transform<T>(value: T[], index: number): T;
static ɵpipe: ɵɵPipeDeclaration<IndexPipe, 'index'>;
}
export declare class CommonModule {
static ɵmod: ɵɵNgModuleDeclaration<
CommonModule,
[typeof NgForOf, typeof NgIf, typeof DatePipe, typeof IndexPipe, typeof NgTemplateOutlet],
never,
[typeof NgForOf, typeof NgIf, typeof DatePipe, typeof IndexPipe, typeof NgTemplateOutlet]
>;
}
| {
"end_byte": 3179,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/testing/fake_common/index.ts"
} |
angular/packages/compiler-cli/src/ngtsc/testing/src/mock_file_loading.ts_0_4495 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/// <reference types="node" />
import {readdirSync, readFileSync, statSync} from 'fs';
import {resolve} from 'path';
import {AbsoluteFsPath, FileSystem, getFileSystem} from '../../file_system';
import {Folder, MockFileSystemPosix, TestFile} from '../../file_system/testing';
import {getAngularPackagesFromRunfiles, resolveFromRunfiles} from './runfile_helpers';
export function loadTestFiles(files: TestFile[]) {
const fs = getFileSystem();
files.forEach((file) => {
fs.ensureDir(fs.dirname(file.name));
fs.writeFile(file.name, file.contents);
});
}
/**
* A folder that is lazily loaded upon first access and then cached.
*/
class CachedFolder {
private folder: Folder | null = null;
constructor(private loader: () => Folder) {}
get(): Folder {
if (this.folder === null) {
this.folder = this.loader();
}
return this.folder;
}
}
const typescriptFolder = new CachedFolder(() =>
loadFolder(resolveFromRunfiles('npm/node_modules/typescript')),
);
const angularFolder = new CachedFolder(loadAngularFolder);
const rxjsFolder = new CachedFolder(() => loadFolder(resolveFromRunfiles('npm/node_modules/rxjs')));
export function loadStandardTestFiles({
fakeCommon = false,
rxjs = false,
}: {fakeCommon?: boolean; rxjs?: boolean} = {}): Folder {
const tmpFs = new MockFileSystemPosix(true);
const basePath = '/' as AbsoluteFsPath;
tmpFs.mount(tmpFs.resolve('/node_modules/typescript'), typescriptFolder.get());
tmpFs.mount(tmpFs.resolve('/node_modules/@angular'), angularFolder.get());
loadTsLib(tmpFs, basePath);
// TODO: Consider removing.
if (fakeCommon) {
loadFakeCommon(tmpFs, basePath);
}
if (rxjs) {
tmpFs.mount(tmpFs.resolve('/node_modules/rxjs'), rxjsFolder.get());
}
return tmpFs.dump();
}
export function loadTsLib(fs: FileSystem, basePath: string = '/') {
loadTestDirectory(
fs,
resolveFromRunfiles('npm/node_modules/tslib'),
fs.resolve(basePath, 'node_modules/tslib'),
);
}
export function loadFakeCommon(fs: FileSystem, basePath: string = '/') {
loadTestDirectory(
fs,
resolveFromRunfiles('angular/packages/compiler-cli/src/ngtsc/testing/fake_common/npm_package'),
fs.resolve(basePath, 'node_modules/@angular/common'),
);
}
export function loadAngularCore(fs: FileSystem, basePath: string = '/') {
loadTestDirectory(
fs,
resolveFromRunfiles('angular/packages/core/npm_package'),
fs.resolve(basePath, 'node_modules/@angular/core'),
);
}
function loadFolder(path: string): Folder {
const tmpFs = new MockFileSystemPosix(true);
// Note that we intentionally pass the native `path`, without resolving it through the file
// system, because the mock posix file system may break paths coming from a non-posix system.
loadTestDirectory(tmpFs, path, tmpFs.resolve('/'));
return tmpFs.dump();
}
function loadAngularFolder(): Folder {
const tmpFs = new MockFileSystemPosix(true);
getAngularPackagesFromRunfiles().forEach(({name, pkgPath}) => {
loadTestDirectory(tmpFs, pkgPath, tmpFs.resolve(name));
});
return tmpFs.dump();
}
/**
* Load real files from the real file-system into a mock file-system.
*
* Note that this function contains a mix of `FileSystem` calls and NodeJS `fs` calls.
* This is because the function is a bridge between the "real" file-system (via `fs`) and the "mock"
* file-system (via `FileSystem`).
*
* @param fs the file-system where the directory is to be loaded.
* @param directoryPath the path to the directory we want to load.
* @param mockPath the path within the mock file-system where the directory is to be loaded.
*/
export function loadTestDirectory(
fs: FileSystem,
directoryPath: string,
mockPath: AbsoluteFsPath,
): void {
readdirSync(directoryPath).forEach((item) => {
const srcPath = resolve(directoryPath, item);
const targetPath = fs.resolve(mockPath, item);
try {
if (statSync(srcPath).isDirectory()) {
fs.ensureDir(targetPath);
loadTestDirectory(fs, srcPath, targetPath);
} else {
fs.ensureDir(fs.dirname(targetPath));
fs.writeFile(targetPath, readFileSync(srcPath, 'utf-8'));
}
} catch (e) {
console.warn(`Failed to add ${srcPath} to the mock file-system: ${(e as Error).message}`);
}
});
}
| {
"end_byte": 4495,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/testing/src/mock_file_loading.ts"
} |
angular/packages/compiler-cli/src/ngtsc/testing/src/runfile_helpers.ts_0_1743 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/// <reference types="node" />
import {runfiles} from '@bazel/runfiles';
import * as fs from 'fs';
import * as path from 'path';
/**
* Gets all built Angular NPM package artifacts by querying the Bazel runfiles.
* In case there is a runfiles manifest (e.g. on Windows), the packages are resolved
* through the manifest because the runfiles are not symlinked and cannot be searched
* within the real filesystem.
*/
export function getAngularPackagesFromRunfiles() {
// Path to the Bazel runfiles manifest if present. This file is present if runfiles are
// not symlinked into the runfiles directory.
const runfilesManifestPath = process.env['RUNFILES_MANIFEST_FILE'];
if (!runfilesManifestPath) {
const packageRunfilesDir = path.join(process.env['RUNFILES']!, 'angular/packages');
return fs
.readdirSync(packageRunfilesDir)
.map((name) => ({name, pkgPath: path.join(packageRunfilesDir, name, 'npm_package/')}))
.filter(({pkgPath}) => fs.existsSync(pkgPath));
}
return fs
.readFileSync(runfilesManifestPath, 'utf8')
.split('\n')
.map((mapping) => mapping.split(' '))
.filter(([runfilePath]) => runfilePath.match(/^angular\/packages\/[\w-]+\/npm_package$/))
.map(([runfilePath, realPath]) => ({
name: path.relative('angular/packages', runfilePath).split(path.sep)[0],
pkgPath: realPath,
}));
}
/** Resolves a file or directory from the Bazel runfiles. */
export function resolveFromRunfiles(manifestPath: string) {
return runfiles.resolve(manifestPath);
}
| {
"end_byte": 1743,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/testing/src/runfile_helpers.ts"
} |
angular/packages/compiler-cli/src/ngtsc/testing/src/cached_source_files.ts_0_1860 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {basename} from '../../file_system';
// A cache of source files that are typically used across tests and are expensive to parse.
let sourceFileCache = new Map<string, ts.SourceFile>();
/**
* If the `fileName` is determined to benefit from caching across tests, a parsed `ts.SourceFile`
* is returned from a shared cache. If caching is not applicable for the requested `fileName`, then
* `null` is returned.
*
* Even if a `ts.SourceFile` already exists for the given `fileName` will the contents be loaded
* from disk, such that it can be verified whether the cached `ts.SourceFile` is identical to the
* disk contents. If there is a difference, a new `ts.SourceFile` is parsed from the loaded contents
* which replaces the prior cache entry.
*
* @param fileName the path of the file to request a source file for.
* @param load a callback to load the contents of the file; this is even called when a cache entry
* is available to verify that the cached `ts.SourceFile` corresponds with the contents on disk.
*/
export function getCachedSourceFile(
fileName: string,
load: () => string | undefined,
): ts.SourceFile | null {
if (
!/^lib\..+\.d\.ts$/.test(basename(fileName)) &&
!/\/node_modules\/(@angular|rxjs)\//.test(fileName)
) {
return null;
}
const content = load();
if (content === undefined) {
return null;
}
if (!sourceFileCache.has(fileName) || sourceFileCache.get(fileName)!.text !== content) {
const sf = ts.createSourceFile(fileName, content, ts.ScriptTarget.ES2015);
sourceFileCache.set(fileName, sf);
}
return sourceFileCache.get(fileName)!;
}
| {
"end_byte": 1860,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/testing/src/cached_source_files.ts"
} |
angular/packages/compiler-cli/src/ngtsc/testing/src/utils.ts_0_6237 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
///<reference types="jasmine"/>
import ts from 'typescript';
import {
AbsoluteFsPath,
dirname,
getFileSystem,
getSourceFileOrError,
NgtscCompilerHost,
} from '../../file_system';
import {DeclarationNode} from '../../reflection';
import {getTokenAtPosition} from '../../util/src/typescript';
import {NgtscTestCompilerHost} from './compiler_host';
export function makeProgram(
files: {name: AbsoluteFsPath; contents: string; isRoot?: boolean}[],
options?: ts.CompilerOptions,
host?: ts.CompilerHost,
checkForErrors: boolean = true,
): {program: ts.Program; host: ts.CompilerHost; options: ts.CompilerOptions} {
const fs = getFileSystem();
files.forEach((file) => {
fs.ensureDir(dirname(file.name));
fs.writeFile(file.name, file.contents);
});
const compilerOptions = {
noLib: true,
experimentalDecorators: true,
moduleResolution: ts.ModuleResolutionKind.Node10,
...options,
};
const compilerHost = new NgtscTestCompilerHost(fs, compilerOptions);
const rootNames = files
.filter((file) => file.isRoot !== false)
.map((file) => compilerHost.getCanonicalFileName(file.name));
const program = ts.createProgram(rootNames, compilerOptions, compilerHost);
if (checkForErrors) {
const diags = [...program.getSyntacticDiagnostics(), ...program.getSemanticDiagnostics()];
if (diags.length > 0) {
const errors = diags.map((diagnostic) => {
let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
if (diagnostic.file) {
const {line, character} = diagnostic.file.getLineAndCharacterOfPosition(
diagnostic.start!,
);
message = `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`;
}
return `Error: ${message}`;
});
throw new Error(`Typescript diagnostics failed! ${errors.join(', ')}`);
}
}
return {program, host: compilerHost, options: compilerOptions};
}
/**
* Search the file specified by `fileName` in the given `program` for a declaration that has the
* name `name` and passes the `predicate` function.
*
* An error will be thrown if there is not at least one AST node with the given `name` and passes
* the `predicate` test.
*/
export function getDeclaration<T extends DeclarationNode>(
program: ts.Program,
fileName: AbsoluteFsPath,
name: string,
assert: (value: any) => value is T,
): T {
const sf = getSourceFileOrError(program, fileName);
const chosenDecls = walkForDeclarations(name, sf);
if (chosenDecls.length === 0) {
throw new Error(`No such symbol: ${name} in ${fileName}`);
}
const chosenDecl = chosenDecls.find(assert);
if (chosenDecl === undefined) {
throw new Error(
`Symbols with name ${name} in ${fileName} have types: ${chosenDecls.map(
(decl) => ts.SyntaxKind[decl.kind],
)}. Expected one to pass predicate "${assert.name}()".`,
);
}
return chosenDecl;
}
/**
* Walk the AST tree from the `rootNode` looking for a declaration that has the given `name`.
*/
export function walkForDeclarations(name: string, rootNode: ts.Node): DeclarationNode[] {
const chosenDecls: DeclarationNode[] = [];
rootNode.forEachChild((node) => {
if (ts.isVariableStatement(node)) {
node.declarationList.declarations.forEach((decl) => {
if (bindingNameEquals(decl.name, name)) {
chosenDecls.push(decl);
if (decl.initializer) {
chosenDecls.push(...walkForDeclarations(name, decl.initializer));
}
} else {
chosenDecls.push(...walkForDeclarations(name, node));
}
});
} else if (isNamedDeclaration(node)) {
if (node.name !== undefined && node.name.text === name) {
chosenDecls.push(node);
}
chosenDecls.push(...walkForDeclarations(name, node));
} else if (
ts.isImportDeclaration(node) &&
node.importClause !== undefined &&
node.importClause.name !== undefined &&
node.importClause.name.text === name
) {
chosenDecls.push(node.importClause);
} else {
chosenDecls.push(...walkForDeclarations(name, node));
}
});
return chosenDecls;
}
export function isNamedDeclaration(node: ts.Node): node is ts.Declaration & {name: ts.Identifier} {
const namedNode = node as {name?: ts.Identifier};
return namedNode.name !== undefined && ts.isIdentifier(namedNode.name);
}
const COMPLETE_REUSE_FAILURE_MESSAGE =
'The original program was not reused completely, even though no changes should have been made to its structure';
/**
* Extracted from TypeScript's internal enum `StructureIsReused`.
*/
enum TsStructureIsReused {
Not = 0,
SafeModules = 1,
Completely = 2,
}
export function expectCompleteReuse(program: ts.Program): void {
// Assert complete reuse using TypeScript's private API.
expect((program as any).structureIsReused)
.withContext(COMPLETE_REUSE_FAILURE_MESSAGE)
.toBe(TsStructureIsReused.Completely);
}
function bindingNameEquals(node: ts.BindingName, name: string): boolean {
if (ts.isIdentifier(node)) {
return node.text === name;
}
return false;
}
export function getSourceCodeForDiagnostic(diag: ts.Diagnostic): string {
if (diag.file === undefined || diag.start === undefined || diag.length === undefined) {
throw new Error(
`Unable to get source code for diagnostic. Provided diagnostic instance doesn't contain "file", "start" and/or "length" properties.`,
);
}
const text = diag.file.text;
return text.slice(diag.start, diag.start + diag.length);
}
export function diagnosticToNode<T extends ts.Node>(
diagnostic: ts.Diagnostic | ts.DiagnosticRelatedInformation,
guard: (node: ts.Node) => node is T,
): T {
const diag = diagnostic as ts.Diagnostic | ts.DiagnosticRelatedInformation;
if (diag.file === undefined) {
throw new Error(`Expected ts.Diagnostic to have a file source`);
}
const node = getTokenAtPosition(diag.file, diag.start!);
expect(guard(node)).toBe(true);
return node as T;
}
| {
"end_byte": 6237,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/testing/src/utils.ts"
} |
angular/packages/compiler-cli/src/ngtsc/testing/src/compiler_host.ts_0_865 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {NgtscCompilerHost} from '../../file_system';
import {getCachedSourceFile} from './cached_source_files';
/**
* A compiler host intended to improve test performance by caching default library source files for
* reuse across tests.
*/
export class NgtscTestCompilerHost extends NgtscCompilerHost {
override getSourceFile(
fileName: string,
languageVersion: ts.ScriptTarget,
): ts.SourceFile | undefined {
const cachedSf = getCachedSourceFile(fileName, () => this.readFile(fileName));
if (cachedSf !== null) {
return cachedSf;
}
return super.getSourceFile(fileName, languageVersion);
}
}
| {
"end_byte": 865,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/testing/src/compiler_host.ts"
} |
angular/packages/compiler-cli/src/ngtsc/sourcemaps/README.md_0_82 | # Source-map handling
Here there are classes for loading and merging source-maps. | {
"end_byte": 82,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/README.md"
} |
angular/packages/compiler-cli/src/ngtsc/sourcemaps/BUILD.bazel_0_485 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "sourcemaps",
srcs = ["index.ts"] + glob([
"src/**/*.ts",
]),
deps = [
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/logging",
"@npm//@jridgewell/sourcemap-codec",
"@npm//@types/convert-source-map",
"@npm//@types/node",
"@npm//convert-source-map",
],
)
| {
"end_byte": 485,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/BUILD.bazel"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.