_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/compiler-cli/src/ngtsc/typecheck/test/output_function_diagnostics.spec.ts_0_3194
/** * @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 {runInEachFileSystem} from '../../file_system/testing'; import {generateDiagnoseJasmineSpecs, TestCase} from './test_case_helper'; runInEachFileSystem(() => { describe('output() function type-check diagnostics', () => { const testCases: TestCase[] = [ { id: 'basic output', outputs: {'evt': {type: 'OutputEmitterRef<string>'}}, template: `<div dir (evt)="$event.bla">`, expected: [`TestComponent.html(1, 24): Property 'bla' does not exist on type 'string'.`], }, { id: 'output with void type', outputs: {'evt': {type: 'OutputEmitterRef<void>'}}, template: `<div dir (evt)="$event.x">`, expected: [`TestComponent.html(1, 24): Property 'x' does not exist on type 'void'.`], }, { id: 'two way data binding, invalid', inputs: {'value': {type: 'InputSignal<string>', isSignal: true}}, outputs: {'valueChange': {type: 'OutputEmitterRef<string>'}}, template: `<div dir [(value)]="bla">`, component: `bla = true;`, expected: [`TestComponent.html(1, 12): Type 'boolean' is not assignable to type 'string'.`], }, { id: 'two way data binding, valid', inputs: {'value': {type: 'InputSignal<string>', isSignal: true}}, outputs: {'valueChange': {type: 'OutputEmitterRef<string>'}}, template: `<div dir [(value)]="bla">`, component: `bla: string = ''`, expected: [], }, { id: 'complex output object', outputs: {'evt': {type: 'OutputEmitterRef<{works: boolean}>'}}, template: `<div dir (evt)="x = $event.works">`, component: `x: never = null!`, // to raise a diagnostic to check the type. expected: [`TestComponent.html(1, 17): Type 'boolean' is not assignable to type 'never'.`], }, // mixing cases { id: 'mixing decorator-based and initializer-based outputs', outputs: { evt1: {type: 'EventEmitter<string>'}, evt2: {type: 'OutputEmitterRef<string>'}, }, template: `<div dir (evt1)="x1 = $event" (evt2)="x2 = $event">`, component: ` x1: never = null!; x2: never = null!; `, expected: [ `TestComponent.html(1, 18): Type 'string' is not assignable to type 'never'.`, `TestComponent.html(1, 39): Type 'string' is not assignable to type 'never'.`, ], }, // restricted fields { id: 'allows access to private output', outputs: {evt: {type: 'OutputEmitterRef<string>', restrictionModifier: 'private'}}, template: `<div dir (evt)="true">`, expected: [], }, { id: 'allows access to protected output', outputs: {evt: {type: 'OutputEmitterRef<string>', restrictionModifier: 'protected'}}, template: `<div dir (evt)="true">`, expected: [], }, ]; generateDiagnoseJasmineSpecs(testCases); }); });
{ "end_byte": 3194, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/output_function_diagnostics.spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/BUILD.bazel_0_1482
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/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/incremental", "//packages/compiler-cli/src/ngtsc/metadata", "//packages/compiler-cli/src/ngtsc/perf", "//packages/compiler-cli/src/ngtsc/program_driver", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/scope", "//packages/compiler-cli/src/ngtsc/shims", "//packages/compiler-cli/src/ngtsc/testing", "//packages/compiler-cli/src/ngtsc/typecheck", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck/testing", "//packages/compiler-cli/src/ngtsc/util", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/core:npm_package", ], deps = [ ":test_lib", ], )
{ "end_byte": 1482, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_constructor_spec.ts_0_1267
/** * @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, getFileSystem, getSourceFileOrError, LogicalFileSystem, NgtscCompilerHost, } from '../../file_system'; import {runInEachFileSystem, TestFile} from '../../file_system/testing'; import { AbsoluteModuleStrategy, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, Reference, ReferenceEmitter, } from '../../imports'; import {ClassPropertyMapping, InputMapping} from '../../metadata'; import {NOOP_PERF_RECORDER} from '../../perf'; import {TsCreateProgramDriver, UpdateMode} from '../../program_driver'; import {isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection'; import {getDeclaration, makeProgram} from '../../testing'; import {getRootDirs} from '../../util/src/typescript'; import { InliningMode, PendingFileTypeCheckingData, TypeCheckContextImpl, TypeCheckingHost, } from '../src/context'; import {TemplateSourceManager} from '../src/source'; import {TypeCheckFile} from '../src/type_check_file'; import {ALL_ENABLED_CONFIG} from '../testing';
{ "end_byte": 1267, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_constructor_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_constructor_spec.ts_1269_10705
runInEachFileSystem(() => { describe('ngtsc typechecking', () => { let _: typeof absoluteFrom; let LIB_D_TS: TestFile; beforeEach(() => { _ = absoluteFrom; LIB_D_TS = { name: _('/lib.d.ts'), contents: ` type Partial<T> = { [P in keyof T]?: T[P]; }; type Pick<T, K extends keyof T> = { [P in K]: T[P]; }; type NonNullable<T> = T extends null | undefined ? never : T;`, }; }); it('should not produce an empty SourceFile when there is nothing to typecheck', () => { const host = new NgtscCompilerHost(getFileSystem()); const file = new TypeCheckFile( _('/_typecheck_.ts'), ALL_ENABLED_CONFIG, new ReferenceEmitter([]), /* reflector */ null!, host, ); const sf = file.render(false /* removeComments */); expect(sf).toContain('export const IS_A_MODULE = true;'); }); describe('ctors', () => { it('compiles a basic type constructor', () => { const files: TestFile[] = [ LIB_D_TS, { name: _('/main.ts'), contents: ` class TestClass<T extends string> { value: T; } TestClass.ngTypeCtor({value: 'test'}); `, }, ]; const {program, host, options} = makeProgram(files, undefined, undefined, false); const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(checker); const logicalFs = new LogicalFileSystem(getRootDirs(host, options), host); const moduleResolver = new ModuleResolver( program, options, host, /* moduleResolutionCache */ null, ); const emitter = new ReferenceEmitter([ new LocalIdentifierStrategy(), new AbsoluteModuleStrategy(program, checker, moduleResolver, reflectionHost), new LogicalProjectStrategy(reflectionHost, logicalFs), ]); const ctx = new TypeCheckContextImpl( ALL_ENABLED_CONFIG, host, emitter, reflectionHost, new TestTypeCheckingHost(), InliningMode.InlineOps, NOOP_PERF_RECORDER, ); const TestClass = getDeclaration( program, _('/main.ts'), 'TestClass', isNamedClassDeclaration, ); const pendingFile = makePendingFile(); ctx.addInlineTypeCtor( pendingFile, getSourceFileOrError(program, _('/main.ts')), new Reference(TestClass), { fnName: 'ngTypeCtor', body: true, fields: { inputs: ClassPropertyMapping.fromMappedObject<InputMapping>({value: 'value'}), queries: [], }, coercedInputFields: new Set(), }, ); ctx.finalize(); }); it('should not consider query fields', () => { const files: TestFile[] = [ LIB_D_TS, { name: _('/main.ts'), contents: `class TestClass { value: any; }`, }, ]; const {program, host, options} = makeProgram(files, undefined, undefined, false); const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(checker); const logicalFs = new LogicalFileSystem(getRootDirs(host, options), host); const moduleResolver = new ModuleResolver( program, options, host, /* moduleResolutionCache */ null, ); const emitter = new ReferenceEmitter([ new LocalIdentifierStrategy(), new AbsoluteModuleStrategy(program, checker, moduleResolver, reflectionHost), new LogicalProjectStrategy(reflectionHost, logicalFs), ]); const pendingFile = makePendingFile(); const ctx = new TypeCheckContextImpl( ALL_ENABLED_CONFIG, host, emitter, reflectionHost, new TestTypeCheckingHost(), InliningMode.InlineOps, NOOP_PERF_RECORDER, ); const TestClass = getDeclaration( program, _('/main.ts'), 'TestClass', isNamedClassDeclaration, ); ctx.addInlineTypeCtor( pendingFile, getSourceFileOrError(program, _('/main.ts')), new Reference(TestClass), { fnName: 'ngTypeCtor', body: true, fields: { inputs: ClassPropertyMapping.fromMappedObject<InputMapping>({value: 'value'}), queries: ['queryField'], }, coercedInputFields: new Set(), }, ); const programStrategy = new TsCreateProgramDriver(program, host, options, []); programStrategy.updateFiles(ctx.finalize(), UpdateMode.Complete); const TestClassWithCtor = getDeclaration( programStrategy.getProgram(), _('/main.ts'), 'TestClass', isNamedClassDeclaration, ); const typeCtor = TestClassWithCtor.members.find(isTypeCtor)!; expect(typeCtor.getText()).not.toContain('queryField'); }); }); describe('input type coercion', () => { it('should coerce input types', () => { const files: TestFile[] = [ LIB_D_TS, { name: _('/main.ts'), contents: `class TestClass { value: any; }`, }, ]; const {program, host, options} = makeProgram(files, undefined, undefined, false); const checker = program.getTypeChecker(); const reflectionHost = new TypeScriptReflectionHost(checker); const logicalFs = new LogicalFileSystem(getRootDirs(host, options), host); const moduleResolver = new ModuleResolver( program, options, host, /* moduleResolutionCache */ null, ); const emitter = new ReferenceEmitter([ new LocalIdentifierStrategy(), new AbsoluteModuleStrategy(program, checker, moduleResolver, reflectionHost), new LogicalProjectStrategy(reflectionHost, logicalFs), ]); const pendingFile = makePendingFile(); const ctx = new TypeCheckContextImpl( ALL_ENABLED_CONFIG, host, emitter, reflectionHost, new TestTypeCheckingHost(), InliningMode.InlineOps, NOOP_PERF_RECORDER, ); const TestClass = getDeclaration( program, _('/main.ts'), 'TestClass', isNamedClassDeclaration, ); ctx.addInlineTypeCtor( pendingFile, getSourceFileOrError(program, _('/main.ts')), new Reference(TestClass), { fnName: 'ngTypeCtor', body: true, fields: { inputs: ClassPropertyMapping.fromMappedObject<InputMapping>({ foo: 'foo', bar: 'bar', baz: { classPropertyName: 'baz', bindingPropertyName: 'baz', required: false, isSignal: false, transform: { type: new Reference( ts.factory.createUnionTypeNode([ ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword), ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), ]), ), node: ts.factory.createFunctionDeclaration( undefined, undefined, undefined, undefined, [], undefined, undefined, ), }, }, }), queries: [], }, coercedInputFields: new Set(['bar', 'baz']), }, ); const programStrategy = new TsCreateProgramDriver(program, host, options, []); programStrategy.updateFiles(ctx.finalize(), UpdateMode.Complete); const TestClassWithCtor = getDeclaration( programStrategy.getProgram(), _('/main.ts'), 'TestClass', isNamedClassDeclaration, ); const typeCtor = TestClassWithCtor.members.find(isTypeCtor)!; const ctorText = typeCtor.getText().replace(/[ \r\n]+/g, ' '); expect(ctorText).toContain( 'init: Pick<TestClass, "foo"> & { bar: typeof TestClass.ngAcceptInputType_bar; baz: boolean | string; }', ); }); }); }); function isTypeCtor(el: ts.ClassElement): el is ts.MethodDeclaration { return ts.isMethodDeclaration(el) && ts.isIdentifier(el.name) && el.name.text === 'ngTypeCtor'; } }); function makePendingFile(): PendingFileTypeCheckingData { return { hasInlines: false, sourceManager: new TemplateSourceManager(), shimData: new Map(), }; } class TestTypeCheckingHost implements TypeCheckingHost { private sourceManager = new TemplateSourceManager(); getSourceManager(): TemplateSourceManager { return this.sourceManager; } shouldCheckComponent(): boolean { return true; } getTemplateOverride(): null { return null; } recordShimData(): void {} recordComplete(): void {} }
{ "end_byte": 10705, "start_byte": 1269, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_constructor_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__completion_spec.ts_0_6973
/** * @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 {ParseTemplateOptions, TmplAstTemplate} from '@angular/compiler'; import ts from 'typescript'; import {absoluteFrom, getSourceFileOrError} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {getTokenAtPosition} from '../../util/src/typescript'; import {CompletionKind, GlobalCompletion, TemplateTypeChecker} from '../api'; import {getClass, setup} from '../testing'; runInEachFileSystem(() => { describe('TemplateTypeChecker.getGlobalCompletions()', () => { it('should return a completion point in the TCB for the component context', () => { const {completions, program} = setupCompletions(`No special template needed`); expect(completions.templateContext.size).toBe(0); const {tcbPath, positionInFile} = completions.componentContext; const tcbSf = getSourceFileOrError(program, tcbPath); const node = getTokenAtPosition(tcbSf, positionInFile).parent; if (!ts.isExpressionStatement(node)) { return fail(`Expected a ts.ExpressionStatement`); } expect(node.expression.getText()).toEqual('this.'); // The position should be between the '.' and a following space. expect(tcbSf.text.slice(positionInFile - 1, positionInFile + 1)).toEqual('. '); }); it('should return additional completions for references and variables when available', () => { const template = ` <div *ngFor="let user of users"> <div #innerRef></div> <div *ngIf="user"> <div #notInScope></div> </div> </div> <div #topLevelRef></div> `; const members = `users: string[];`; // Embedded view in question is the first node in the template (index 0). const {completions} = setupCompletions(template, members, 0); expect(new Set(completions.templateContext.keys())).toEqual( new Set(['innerRef', 'user', 'topLevelRef']), ); }); it('should support shadowing between outer and inner templates', () => { const template = ` <div *ngFor="let user of users"> Within this template, 'user' should be a variable, not a reference. </div> <div #user>Out here, 'user' is the reference.</div> `; const members = `users: string[];`; // Completions for the top level. const {completions: topLevel} = setupCompletions(template, members); // Completions within the embedded view at index 0. const {completions: inNgFor} = setupCompletions(template, members, 0); expect(topLevel.templateContext.has('user')).toBeTrue(); const userAtTopLevel = topLevel.templateContext.get('user')!; expect(inNgFor.templateContext.has('user')).toBeTrue(); const userInNgFor = inNgFor.templateContext.get('user')!; expect(userAtTopLevel.kind).toBe(CompletionKind.Reference); expect(userInNgFor.kind).toBe(CompletionKind.Variable); }); it('should return completions for let declarations', () => { const template = ` @let one = 1; <ng-template> @let two = 1 + one; {{two}} </ng-template> @let three = one + 2; `; const { completions: {templateContext: outerContext}, } = setupCompletions(template); expect(Array.from(outerContext.keys())).toEqual(['one', 'three']); expect(outerContext.get('one')?.kind).toBe(CompletionKind.LetDeclaration); expect(outerContext.get('three')?.kind).toBe(CompletionKind.LetDeclaration); const { completions: {templateContext: innerContext}, } = setupCompletions(template, '', 1); expect(Array.from(innerContext.keys())).toEqual(['one', 'three', 'two']); expect(innerContext.get('one')?.kind).toBe(CompletionKind.LetDeclaration); expect(innerContext.get('three')?.kind).toBe(CompletionKind.LetDeclaration); expect(innerContext.get('two')?.kind).toBe(CompletionKind.LetDeclaration); }); }); describe('TemplateTypeChecker scopes', () => { it('should get directives and pipes in scope for a component', () => { const MAIN_TS = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName: MAIN_TS, templates: { 'SomeCmp': 'Not important', }, declarations: [ { type: 'directive', file: MAIN_TS, name: 'OtherDir', selector: 'other-dir', }, { type: 'pipe', file: MAIN_TS, name: 'OtherPipe', pipeName: 'otherPipe', }, ], source: ` export class SomeCmp {} export class OtherDir {} export class OtherPipe {} export class SomeCmpModule {} `, }, ]); const sf = getSourceFileOrError(program, MAIN_TS); const SomeCmp = getClass(sf, 'SomeCmp'); let directives = templateTypeChecker.getPotentialTemplateDirectives(SomeCmp) ?? []; directives = directives.filter((d) => d.isInScope); const pipes = templateTypeChecker.getPotentialPipes(SomeCmp) ?? []; expect(directives.map((dir) => dir.selector)).toEqual(['other-dir']); expect(pipes.map((pipe) => pipe.name)).toEqual(['otherPipe']); }); }); }); function setupCompletions( template: string, componentMembers: string = '', inChildTemplateAtIndex: number | null = null, parseOptions?: ParseTemplateOptions, ): { completions: GlobalCompletion; program: ts.Program; templateTypeChecker: TemplateTypeChecker; component: ts.ClassDeclaration; } { const MAIN_TS = absoluteFrom('/main.ts'); const {templateTypeChecker, programStrategy} = setup( [ { fileName: MAIN_TS, templates: {'SomeCmp': template}, source: `export class SomeCmp { ${componentMembers} }`, }, ], {inlining: false, config: {enableTemplateTypeChecker: true}, parseOptions}, ); const sf = getSourceFileOrError(programStrategy.getProgram(), MAIN_TS); const SomeCmp = getClass(sf, 'SomeCmp'); let context: TmplAstTemplate | null = null; if (inChildTemplateAtIndex !== null) { const tmpl = templateTypeChecker.getTemplate(SomeCmp)![inChildTemplateAtIndex]; if (!(tmpl instanceof TmplAstTemplate)) { throw new Error( `AssertionError: expected TmplAstTemplate at index ${inChildTemplateAtIndex}`, ); } context = tmpl; } const completions = templateTypeChecker.getGlobalCompletions(context, SomeCmp, null!)!; expect(completions).toBeDefined(); return { completions, program: programStrategy.getProgram(), templateTypeChecker, component: SomeCmp, }; }
{ "end_byte": 6973, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__completion_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/input_signal_diagnostics_spec.ts_0_8481
/** * @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 {runInEachFileSystem} from '../../file_system/testing'; import {generateDiagnoseJasmineSpecs, TestCase} from './test_case_helper'; runInEachFileSystem(() => { describe('input signal type-check diagnostics', () => { const bindingCases: TestCase[] = [ { id: 'binding via attribute', inputs: {'show': {type: 'InputSignal<boolean>', isSignal: true}}, template: `<div dir show="works">`, expected: [`TestComponent.html(1, 10): Type 'string' is not assignable to type 'boolean'.`], }, { id: 'explicit inline true binding', inputs: {'show': {type: 'InputSignal<boolean>', isSignal: true}}, template: `<div dir [show]="true">`, expected: [], }, { id: 'explicit inline false binding', inputs: {'show': {type: 'InputSignal<boolean>', isSignal: true}}, template: `<div dir [show]="false">`, expected: [], }, { id: 'explicit binding using component field', inputs: {'show': {type: 'InputSignal<boolean>', isSignal: true}}, template: `<div dir [show]="prop">`, component: 'prop = true;', expected: [], }, { id: 'complex object input', inputs: {'show': {type: 'InputSignal<{works: boolean}>', isSignal: true}}, template: `<div dir [show]="{works: true}">`, expected: [], }, { id: 'complex object input, unexpected extra fields', inputs: {'show': {type: 'InputSignal<{works: boolean}>', isSignal: true}}, template: `<div dir [show]="{works: true, extraField: true}">`, expected: [ jasmine.stringContaining( `Object literal may only specify known properties, and '"extraField"' does not exist in type '{ works: boolean; }'.`, ), ], }, { id: 'complex object input, missing fields', inputs: {'show': {type: 'InputSignal<{works: boolean}>', isSignal: true}}, template: `<div dir [show]="{}">`, expected: [ `TestComponent.html(1, 11): Property 'works' is missing in type '{}' but required in type '{ works: boolean; }'.`, ], }, // mixing cases { id: 'mixing zone and signal inputs, valid', inputs: { zoneProp: {type: 'string', isSignal: false}, signalProp: {type: 'InputSignal<string>', isSignal: true}, }, template: `<div dir [zoneProp]="'works'" [signalProp]="'stringVal'">`, expected: [], }, { id: 'mixing zone and signal inputs, invalid zone binding', inputs: { zoneProp: {type: 'string', isSignal: false}, signalProp: {type: 'InputSignal<string>', isSignal: true}, }, template: `<div dir [zoneProp]="false" [signalProp]="'stringVal'">`, expected: [`TestComponent.html(1, 11): Type 'boolean' is not assignable to type 'string'.`], }, { id: 'mixing zone and signal inputs, invalid signal binding', inputs: { zoneProp: {type: 'string', isSignal: false}, signalProp: {type: 'InputSignal<string>', isSignal: true}, }, template: `<div dir [zoneProp]="'works'" [signalProp]="{}">`, expected: [`TestComponent.html(1, 32): Type '{}' is not assignable to type 'string'.`], }, { id: 'mixing zone and signal inputs, both invalid', inputs: { zoneProp: {type: 'string', isSignal: false}, signalProp: {type: 'InputSignal<string>', isSignal: true}, }, template: `<div dir [zoneProp]="false" [signalProp]="{}">`, expected: [ `TestComponent.html(1, 11): Type 'boolean' is not assignable to type 'string'.`, `TestComponent.html(1, 30): Type '{}' is not assignable to type 'string'.`, ], }, // restricted fields { id: 'disallows access to private input', inputs: { pattern: {type: 'InputSignal<string>', isSignal: true, restrictionModifier: 'private'}, }, template: `<div dir [pattern]="'works'">`, expected: [ `TestComponent.html(1, 11): Property 'pattern' is private and only accessible within class 'Dir'.`, ], }, { id: 'disallows access to protected input', inputs: { pattern: {type: 'InputSignal<string>', isSignal: true, restrictionModifier: 'protected'}, }, template: `<div dir [pattern]="'works'">`, expected: [ `TestComponent.html(1, 11): Property 'pattern' is protected and only accessible within class 'Dir' and its subclasses.`, ], }, { // NOTE FOR REVIEWER: This is something different with input signals. The framework // runtime, and the input public API are already read-only, but under the hood it would // be perfectly fine to keep the `input()` member as readonly. id: 'allows access to readonly input', inputs: { pattern: {type: 'InputSignal<string>', isSignal: true, restrictionModifier: 'readonly'}, }, template: `<div dir [pattern]="'works'">`, expected: [], }, // restricted fields (but opt-out of check) { id: 'allow access to private input if modifiers are explicitly ignored', inputs: { pattern: {type: 'InputSignal<string>', isSignal: true, restrictionModifier: 'private'}, }, template: `<div dir [pattern]="'works'">`, expected: [], options: { honorAccessModifiersForInputBindings: false, }, }, { id: 'allow access to protected input if modifiers are explicitly ignored', inputs: { pattern: {type: 'InputSignal<string>', isSignal: true, restrictionModifier: 'protected'}, }, template: `<div dir [pattern]="'works'">`, expected: [], options: { honorAccessModifiersForInputBindings: false, }, }, { id: 'allow access to readonly input if modifiers are explicitly ignored', inputs: { pattern: {type: 'InputSignal<string>', isSignal: true, restrictionModifier: 'readonly'}, }, template: `<div dir [pattern]="'works'">`, expected: [], options: { honorAccessModifiersForInputBindings: false, }, }, { id: 'allow access to private input if modifiers are explicitly ignored, but error if not assignable', inputs: { pattern: {type: 'InputSignal<string>', isSignal: true, restrictionModifier: 'private'}, }, template: `<div dir [pattern]="false">`, expected: [`TestComponent.html(1, 11): Type 'boolean' is not assignable to type 'string'.`], options: { honorAccessModifiersForInputBindings: false, }, }, // coercion is not supported / respected { id: 'coercion members are not respected', inputs: { pattern: { type: 'InputSignal<string>', isSignal: true, }, }, extraDirectiveMembers: ['static ngAcceptInputType_pattern: string|boolean'], template: `<div dir [pattern]="false">`, expected: [`TestComponent.html(1, 11): Type 'boolean' is not assignable to type 'string'.`], }, // transforms { id: 'signal inputs write transform type respected', inputs: { pattern: { type: 'InputSignalWithTransform<string, string|boolean>', isSignal: true, }, }, template: `<div dir [pattern]="false">`, expected: [], }, // with generics (type constructor tests) { id: 'generic inference and binding to directive, all signal inputs', inputs: { gen: { type: 'InputSignal<T>', isSignal: true, }, other: { type: 'InputSignal<T>', isSignal: true, }, }, directiveGenerics: '<T>', template: `<div dir [gen]="false" [other]="'invalid'">`, expected: [`TestComponent.html(1, 25): Type 'string' is not assignable to type 'boolean'.`], },
{ "end_byte": 8481, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/input_signal_diagnostics_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/input_signal_diagnostics_spec.ts_8488_15676
{ id: 'generic inference and binding to directive, mix of zone and signal', inputs: { gen: { type: 'InputSignal<T>', isSignal: true, }, other: { type: 'T', isSignal: false, }, }, directiveGenerics: '<T>', template: `<div dir [gen]="false" [other]="'invalid'">`, expected: [`TestComponent.html(1, 11): Type 'boolean' is not assignable to type 'string'.`], }, { id: 'generic inference and binding to directive (with `extends boolean`), all signal inputs', inputs: { gen: { type: 'InputSignal<T>', isSignal: true, }, other: { type: 'InputSignal<T>', isSignal: true, }, }, directiveGenerics: '<T extends boolean>', template: `<div dir [gen]="false" [other]="'invalid'">`, expected: [ `TestComponent.html(1, 25): Type '"invalid"' is not assignable to type 'false'.`, ], }, { id: 'generic inference and binding to directive (with `extends boolean`), mix of zone and signal inputs', inputs: { gen: { type: 'InputSignal<T>', isSignal: true, }, other: { type: 'T', isSignal: false, }, }, directiveGenerics: '<T extends boolean>', template: `<div dir [gen]="false" [other]="'invalid'">`, expected: [`TestComponent.html(1, 25): Type 'string' is not assignable to type 'boolean'.`], }, { id: 'generic multi-inference and bindings to directive, all signal inputs', inputs: { gen: { type: 'InputSignal<T>', isSignal: true, }, other: { type: 'InputSignal<U>', isSignal: true, }, }, extraDirectiveMembers: ['tester: {t: T, u: U} = null!'], directiveGenerics: '<T, U>', template: ` <div dir [gen]="false" [other]="'text'" #ref="dir" (click)="ref.tester = {t: 1, u: 0}">`, expected: [ `TestComponent.html(3, 61): Type 'number' is not assignable to type 'boolean'.`, `TestComponent.html(3, 67): Type 'number' is not assignable to type 'string'.`, ], }, { id: 'generic multi-inference and bindings to directive, mix of zone and signal inputs', inputs: { gen: { type: 'InputSignal<T>', isSignal: true, }, other: { type: 'U', isSignal: false, }, }, extraDirectiveMembers: ['tester: {t: T, u: U} = null!'], directiveGenerics: '<T, U>', template: ` <div dir [gen]="false" [other]="'text'" #ref="dir" (click)="ref.tester = {t: 1, u: 0}">`, expected: [ `TestComponent.html(3, 61): Type 'number' is not assignable to type 'boolean'.`, `TestComponent.html(3, 67): Type 'number' is not assignable to type 'string'.`, ], }, { id: 'generic multi-inference and bindings to directive, more complicated generic inference', inputs: { gen: { type: 'InputSignal<T>', isSignal: true, }, other: { type: 'InputSignal<{u: U}>', isSignal: true, }, }, extraDirectiveMembers: ['tester: {t: T, u: U} = null!'], directiveGenerics: '<T, U>', template: ` <div dir [gen]="false" [other]="{u: null}" #ref="dir" (click)="ref.tester = {t: 1, u: 0}">`, expected: [ `TestComponent.html(3, 57): Type 'number' is not assignable to type 'boolean'.`, `TestComponent.html(3, 63): Type 'number' is not assignable to type 'null'.`, ], }, // differing Write and ReadT { id: 'differing WriteT and ReadT, superset union, valid binding', inputs: { bla: { type: 'InputSignalWithTransform<boolean, boolean|string>', isSignal: true, }, }, template: `<div dir bla="string value">`, expected: [], }, { id: 'differing WriteT and ReadT, superset union, invalid binding', inputs: { bla: { type: 'InputSignalWithTransform<boolean, boolean|string>', isSignal: true, }, }, template: `<div dir [bla]="2">`, expected: [ `TestComponent.html(1, 11): Type '2' is not assignable to type 'string | boolean'.`, ], }, { id: 'differing WriteT and ReadT, divergent, valid binding', inputs: { bla: { type: 'InputSignalWithTransform<boolean, string>', isSignal: true, }, }, template: `<div dir bla="works">`, expected: [], }, { id: 'differing WriteT and ReadT, divergent, invalid binding', inputs: { bla: { type: 'InputSignalWithTransform<boolean, string>', isSignal: true, }, }, template: `<div dir [bla]="true">`, expected: [`TestComponent.html(1, 11): Type 'boolean' is not assignable to type 'string'.`], }, { id: 'differing WriteT and ReadT, generic ctor inference', inputs: { bla: { type: 'InputSignalWithTransform<string, T>', isSignal: true, }, }, extraDirectiveMembers: [`tester: {t: T, blaValue: never} = null!`], directiveGenerics: '<T>', template: ` <div dir [bla]="prop" #ref="dir" (click)="ref.tester = {t: 0, blaValue: ref.bla()}">`, component: `prop: HTMLElement = null!`, expected: [ // This verifies that the `ref.tester.t` is correctly inferred to be `HTMLElement`. `TestComponent.html(3, 46): Type 'number' is not assignable to type 'HTMLElement'.`, // This verifies that the `bla` input value is still a `string` when accessed. `TestComponent.html(3, 59): Type 'string' is not assignable to type 'never'.`, ], }, { id: 'inline constructor generic inference', inputs: { bla: { type: 'InputSignal<T>', isSignal: true, }, }, extraFileContent: ` class SomeNonExportedClass {} `, extraDirectiveMembers: [`tester: {t: T} = null!`], directiveGenerics: '<T extends SomeNonExportedClass>', template: `<div dir [bla]="prop" #ref="dir" (click)="ref.tester = {t: 0}">`, component: `prop: HTMLElement = null!`, expected: [ // This verifies that the `ref.tester.t` is correctly inferred to be `HTMLElement`. `TestComponent.html(1, 60): Type 'number' is not assignable to type 'HTMLElement'.`, ], }, ]; generateDiagnoseJasmineSpecs(bindingCases); }); });
{ "end_byte": 15676, "start_byte": 8488, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/input_signal_diagnostics_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/program_spec.ts_0_4080
/** * @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, AbsoluteFsPath, getSourceFileOrError} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {FileUpdate, TsCreateProgramDriver, UpdateMode} from '../../program_driver'; import {sfExtensionData, ShimReferenceTagger} from '../../shims'; import {expectCompleteReuse, makeProgram} from '../../testing'; import {OptimizeFor} from '../api'; import {setup} from '../testing'; runInEachFileSystem(() => { describe('template type-checking program', () => { it('should not be created if no components need to be checked', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker, programStrategy} = setup([ { fileName, templates: {}, source: `export class NotACmp {}`, }, ]); const sf = getSourceFileOrError(program, fileName); templateTypeChecker.getDiagnosticsForFile(sf, OptimizeFor.WholeProgram); // expect() here would create a really long error message, so this is checked manually. if (programStrategy.getProgram() !== program) { fail('Template type-checking created a new ts.Program even though it had no changes.'); } }); it('should have complete reuse if no structural changes are made to shims', () => { const {program, host, options, typecheckPath} = makeSingleFileProgramWithTypecheckShim(); const programStrategy = new TsCreateProgramDriver(program, host, options, ['ngtypecheck']); // Update /main.ngtypecheck.ts without changing its shape. Verify that the old program was // reused completely. programStrategy.updateFiles( new Map([[typecheckPath, createUpdate('export const VERSION = 2;')]]), UpdateMode.Complete, ); expectCompleteReuse(programStrategy.getProgram()); }); it('should have complete reuse if no structural changes are made to input files', () => { const {program, host, options, mainPath} = makeSingleFileProgramWithTypecheckShim(); const programStrategy = new TsCreateProgramDriver(program, host, options, ['ngtypecheck']); // Update /main.ts without changing its shape. Verify that the old program was reused // completely. programStrategy.updateFiles( new Map([[mainPath, createUpdate('export const STILL_NOT_A_COMPONENT = true;')]]), UpdateMode.Complete, ); expectCompleteReuse(programStrategy.getProgram()); }); }); }); function createUpdate(text: string): FileUpdate { return { newText: text, originalFile: null, }; } function makeSingleFileProgramWithTypecheckShim(): { program: ts.Program; host: ts.CompilerHost; options: ts.CompilerOptions; mainPath: AbsoluteFsPath; typecheckPath: AbsoluteFsPath; } { const mainPath = absoluteFrom('/main.ts'); const typecheckPath = absoluteFrom('/main.ngtypecheck.ts'); const {program, host, options} = makeProgram([ { name: mainPath, contents: 'export const NOT_A_COMPONENT = true;', }, { name: typecheckPath, contents: 'export const VERSION = 1;', }, ]); const sf = getSourceFileOrError(program, mainPath); const typecheckSf = getSourceFileOrError(program, typecheckPath); // To ensure this test is validating the correct behavior, the initial conditions of the // input program must be such that: // // 1) /main.ts was previously tagged with a reference to its ngtypecheck shim. // 2) /main.ngtypecheck.ts is marked as a shim itself. // Condition 1: const tagger = new ShimReferenceTagger(['ngtypecheck']); tagger.tag(sf); tagger.finalize(); // Condition 2: sfExtensionData(typecheckSf).fileShim = { extension: 'ngtypecheck', generatedFrom: mainPath, }; return {program, host, options, mainPath, typecheckPath}; }
{ "end_byte": 4080, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/program_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/template_semantics/BUILD.bazel_0_590
load("//tools:defaults.bzl", "ts_library") ts_library( name = "template_semantics", srcs = glob( ["**/*.ts"], ), visibility = ["//packages/compiler-cli/src/ngtsc:__subpackages__"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/template_semantics/api", "@npm//typescript", ], )
{ "end_byte": 590, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/template_semantics/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/template_semantics/api/api.ts_0_616
/** * @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 {TemplateDiagnostic} from '../../api'; /** * Interface to generate diagnostics related to the semantics of a component's template. */ export interface TemplateSemanticsChecker { /** * Run `TemplateSemanticsChecker`s for a component and return the generated `ts.Diagnostic`s. */ getDiagnosticsForComponent(component: ts.ClassDeclaration): TemplateDiagnostic[]; }
{ "end_byte": 616, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/template_semantics/api/api.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/template_semantics/api/BUILD.bazel_0_442
load("//tools:defaults.bzl", "ts_library") ts_library( name = "api", srcs = glob( ["**/*.ts"], ), visibility = ["//packages/compiler-cli/src/ngtsc:__subpackages__"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck/api", "@npm//typescript", ], )
{ "end_byte": 442, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/template_semantics/api/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/template_semantics/src/template_semantics_checker.ts_0_5589
/** * @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 { AST, ASTWithSource, ImplicitReceiver, ParsedEventType, PropertyRead, PropertyWrite, RecursiveAstVisitor, TmplAstBoundEvent, TmplAstLetDeclaration, TmplAstNode, TmplAstRecursiveVisitor, TmplAstVariable, } from '@angular/compiler'; import ts from 'typescript'; import {ErrorCode, ngErrorCode} from '../../../diagnostics'; import {TemplateDiagnostic, TemplateTypeChecker} from '../../api'; import {isSignalReference} from '../../src/symbol_util'; import {TemplateSemanticsChecker} from '../api/api'; export class TemplateSemanticsCheckerImpl implements TemplateSemanticsChecker { constructor(private templateTypeChecker: TemplateTypeChecker) {} getDiagnosticsForComponent(component: ts.ClassDeclaration): TemplateDiagnostic[] { const template = this.templateTypeChecker.getTemplate(component); return template !== null ? TemplateSemanticsVisitor.visit(template, component, this.templateTypeChecker) : []; } } /** Visitor that verifies the semantics of a template. */ class TemplateSemanticsVisitor extends TmplAstRecursiveVisitor { private constructor(private expressionVisitor: ExpressionsSemanticsVisitor) { super(); } static visit( nodes: TmplAstNode[], component: ts.ClassDeclaration, templateTypeChecker: TemplateTypeChecker, ) { const diagnostics: TemplateDiagnostic[] = []; const expressionVisitor = new ExpressionsSemanticsVisitor( templateTypeChecker, component, diagnostics, ); const templateVisitor = new TemplateSemanticsVisitor(expressionVisitor); nodes.forEach((node) => node.visit(templateVisitor)); return diagnostics; } override visitBoundEvent(event: TmplAstBoundEvent): void { super.visitBoundEvent(event); event.handler.visit(this.expressionVisitor, event); } } /** Visitor that verifies the semantics of the expressions within a template. */ class ExpressionsSemanticsVisitor extends RecursiveAstVisitor { constructor( private templateTypeChecker: TemplateTypeChecker, private component: ts.ClassDeclaration, private diagnostics: TemplateDiagnostic[], ) { super(); } override visitPropertyWrite(ast: PropertyWrite, context: TmplAstNode): void { super.visitPropertyWrite(ast, context); this.checkForIllegalWriteInEventBinding(ast, context); } override visitPropertyRead(ast: PropertyRead, context: TmplAstNode) { super.visitPropertyRead(ast, context); this.checkForIllegalWriteInTwoWayBinding(ast, context); } private checkForIllegalWriteInEventBinding(ast: PropertyWrite, context: TmplAstNode) { if (!(context instanceof TmplAstBoundEvent) || !(ast.receiver instanceof ImplicitReceiver)) { return; } const target = this.templateTypeChecker.getExpressionTarget(ast, this.component); if (target instanceof TmplAstVariable) { const errorMessage = `Cannot use variable '${target.name}' as the left-hand side of an assignment expression. Template variables are read-only.`; this.diagnostics.push(this.makeIllegalTemplateVarDiagnostic(target, context, errorMessage)); } } private checkForIllegalWriteInTwoWayBinding(ast: PropertyRead, context: TmplAstNode) { // Only check top-level property reads inside two-way bindings for illegal assignments. if ( !(context instanceof TmplAstBoundEvent) || context.type !== ParsedEventType.TwoWay || !(ast.receiver instanceof ImplicitReceiver) || ast !== unwrapAstWithSource(context.handler) ) { return; } const target = this.templateTypeChecker.getExpressionTarget(ast, this.component); const isVariable = target instanceof TmplAstVariable; const isLet = target instanceof TmplAstLetDeclaration; if (!isVariable && !isLet) { return; } // Two-way bindings to template variables are only allowed if the variables are signals. const symbol = this.templateTypeChecker.getSymbolOfNode(target, this.component); if (symbol !== null && !isSignalReference(symbol)) { let errorMessage: string; if (isVariable) { errorMessage = `Cannot use a non-signal variable '${target.name}' in a two-way binding expression. Template variables are read-only.`; } else { errorMessage = `Cannot use non-signal @let declaration '${target.name}' in a two-way binding expression. @let declarations are read-only.`; } this.diagnostics.push(this.makeIllegalTemplateVarDiagnostic(target, context, errorMessage)); } } private makeIllegalTemplateVarDiagnostic( target: TmplAstVariable | TmplAstLetDeclaration, expressionNode: TmplAstBoundEvent, errorMessage: string, ): TemplateDiagnostic { const span = target instanceof TmplAstVariable ? target.valueSpan || target.sourceSpan : target.sourceSpan; return this.templateTypeChecker.makeTemplateDiagnostic( this.component, expressionNode.handlerSpan, ts.DiagnosticCategory.Error, ngErrorCode(ErrorCode.WRITE_TO_READ_ONLY_VARIABLE), errorMessage, [ { text: `'${target.name}' is declared here.`, start: span.start.offset, end: span.end.offset, sourceFile: this.component.getSourceFile(), }, ], ); } } function unwrapAstWithSource(ast: AST): AST { return ast instanceof ASTWithSource ? ast.ast : ast; }
{ "end_byte": 5589, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/template_semantics/src/template_semantics_checker.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/testing/BUILD.bazel_0_1068
load("//tools:defaults.bzl", "ts_library") ts_library( name = "testing", testonly = True, srcs = glob([ "**/*.ts", ]), visibility = ["//packages/compiler-cli/src/ngtsc:__subpackages__"], deps = [ "//packages/compiler", "//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/incremental", "//packages/compiler-cli/src/ngtsc/metadata", "//packages/compiler-cli/src/ngtsc/perf", "//packages/compiler-cli/src/ngtsc/program_driver", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/scope", "//packages/compiler-cli/src/ngtsc/shims", "//packages/compiler-cli/src/ngtsc/testing", "//packages/compiler-cli/src/ngtsc/typecheck", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/util", "@npm//typescript", ], )
{ "end_byte": 1068, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/testing/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/testing/index.ts_0_8012
/** * @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 { BindingPipe, CssSelector, ParseSourceFile, ParseSourceSpan, parseTemplate, ParseTemplateOptions, PropertyRead, PropertyWrite, R3TargetBinder, SchemaMetadata, SelectorMatcher, TmplAstElement, TmplAstLetDeclaration, } from '@angular/compiler'; import {readFileSync} from 'fs'; import path from 'path'; import ts from 'typescript'; import { absoluteFrom, AbsoluteFsPath, getSourceFileOrError, LogicalFileSystem, } from '../../file_system'; import {TestFile} from '../../file_system/testing'; import { AbsoluteModuleStrategy, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, Reference, ReferenceEmitter, RelativePathStrategy, } from '../../imports'; import {NOOP_INCREMENTAL_BUILD} from '../../incremental'; import { ClassPropertyMapping, CompoundMetadataReader, DecoratorInputTransform, DirectiveMeta, HostDirectivesResolver, InputMapping, MatchSource, MetadataReaderWithIndex, MetaKind, NgModuleIndex, PipeMeta, } from '../../metadata'; import {NOOP_PERF_RECORDER} from '../../perf'; import {TsCreateProgramDriver} from '../../program_driver'; import { ClassDeclaration, isNamedClassDeclaration, TypeScriptReflectionHost, } from '../../reflection'; import { ComponentScopeKind, ComponentScopeReader, LocalModuleScope, ScopeData, TypeCheckScopeRegistry, } from '../../scope'; import {makeProgram, resolveFromRunfiles} from '../../testing'; import {getRootDirs} from '../../util/src/typescript'; import { OptimizeFor, ProgramTypeCheckAdapter, TemplateDiagnostic, TemplateTypeChecker, TypeCheckContext, } from '../api'; import { TemplateId, TemplateSourceMapping, TypeCheckableDirectiveMeta, TypeCheckBlockMetadata, TypeCheckingConfig, } from '../api/api'; import {TemplateTypeCheckerImpl} from '../src/checker'; import {DomSchemaChecker} from '../src/dom'; import {OutOfBandDiagnosticRecorder} from '../src/oob'; import {TypeCheckShimGenerator} from '../src/shim'; import {TcbGenericContextBehavior} from '../src/type_check_block'; import {TypeCheckFile} from '../src/type_check_file'; import {sfExtensionData} from '../../shims'; export function typescriptLibDts(): TestFile { return { name: absoluteFrom('/lib.d.ts'), contents: ` type Partial<T> = { [P in keyof T]?: T[P]; }; type Pick<T, K extends keyof T> = { [P in K]: T[P]; }; type NonNullable<T> = T extends null | undefined ? never : T; // The following native type declarations are required for proper type inference declare interface Function { call(...args: any[]): any; } declare interface Array<T> { [index: number]: T; length: number; } declare interface Iterable<T> {} declare interface String { length: number; } declare interface Event { preventDefault(): void; } declare interface MouseEvent extends Event { readonly x: number; readonly y: number; } declare interface HTMLElementEventMap { "click": MouseEvent; } declare interface HTMLElement { addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any): void; addEventListener(type: string, listener: (evt: Event) => void): void; } declare interface HTMLDivElement extends HTMLElement {} declare interface HTMLImageElement extends HTMLElement { src: string; alt: string; width: number; height: number; } declare interface HTMLQuoteElement extends HTMLElement { cite: string; } declare interface HTMLElementTagNameMap { "blockquote": HTMLQuoteElement; "div": HTMLDivElement; "img": HTMLImageElement; } declare interface Document { createElement<K extends keyof HTMLElementTagNameMap>(tagName: K): HTMLElementTagNameMap[K]; createElement(tagName: string): HTMLElement; } declare const document: Document; `, }; } export function angularCoreDtsFiles(): TestFile[] { const directory = resolveFromRunfiles('angular/packages/core/npm_package'); return [ { name: absoluteFrom('/node_modules/@angular/core/index.d.ts'), contents: readFileSync(path.join(directory, 'index.d.ts'), 'utf8'), }, { name: absoluteFrom('/node_modules/@angular/core/primitives/signals/index.d.ts'), contents: readFileSync(path.join(directory, 'primitives/signals/index.d.ts'), 'utf8'), }, ]; } export function angularAnimationsDts(): TestFile { return { name: absoluteFrom('/node_modules/@angular/animations/index.d.ts'), contents: ` export declare class AnimationEvent { element: any; } `, }; } export function ngIfDeclaration(): TestDeclaration { return { type: 'directive', file: absoluteFrom('/ngif.d.ts'), selector: '[ngIf]', name: 'NgIf', inputs: {ngIf: 'ngIf'}, ngTemplateGuards: [{type: 'binding', inputName: 'ngIf'}], hasNgTemplateContextGuard: true, isGeneric: true, }; } export function ngIfDts(): TestFile { return { name: absoluteFrom('/ngif.d.ts'), contents: ` export declare class NgIf<T> { ngIf: T; static ngTemplateContextGuard<T>(dir: NgIf<T>, ctx: any): ctx is NgIfContext<Exclude<T, false|0|''|null|undefined>> } export declare class NgIfContext<T> { $implicit: T; ngIf: T; }`, }; } export function ngForDeclaration(): TestDeclaration { return { type: 'directive', file: absoluteFrom('/ngfor.d.ts'), selector: '[ngForOf]', name: 'NgForOf', inputs: {ngForOf: 'ngForOf', ngForTrackBy: 'ngForTrackBy', ngForTemplate: 'ngForTemplate'}, hasNgTemplateContextGuard: true, isGeneric: true, }; } export function ngForDts(): TestFile { return { name: absoluteFrom('/ngfor.d.ts'), contents: ` export declare class NgForOf<T> { ngForOf: T[]; ngForTrackBy: TrackByFunction<T>; static ngTemplateContextGuard<T>(dir: NgForOf<T>, ctx: any): ctx is NgForOfContext<T>; } export interface TrackByFunction<T> { (index: number, item: T): any; } export declare class NgForOfContext<T> { $implicit: T; index: number; count: number; readonly odd: boolean; readonly even: boolean; readonly first: boolean; readonly last: boolean; }`, }; } export function ngForTypeCheckTarget(): TypeCheckingTarget { const dts = ngForDts(); return { ...dts, fileName: dts.name, source: dts.contents, templates: {}, }; } export const ALL_ENABLED_CONFIG: Readonly<TypeCheckingConfig> = { applyTemplateContextGuards: true, checkQueries: false, checkTemplateBodies: true, checkControlFlowBodies: true, alwaysCheckSchemaInTemplateBodies: true, checkTypeOfInputBindings: true, honorAccessModifiersForInputBindings: true, strictNullInputBindings: true, checkTypeOfAttributes: true, // Feature is still in development. // TODO(alxhub): enable when DOM checking via lib.dom.d.ts is further along. checkTypeOfDomBindings: false, checkTypeOfOutputEvents: true, checkTypeOfAnimationEvents: true, checkTypeOfDomEvents: true, checkTypeOfDomReferences: true, checkTypeOfNonDomReferences: true, checkTypeOfPipes: true, strictSafeNavigationTypes: true, useContextGenericType: true, strictLiteralTypes: true, enableTemplateTypeChecker: false, useInlineTypeConstructors: true, suggestionsForSuboptimalTypeInference: false, controlFlowPreventingContentProjection: 'warning', unusedStandaloneImports: 'warning', allowSignalsInTwoWayBindings: true, }; // Remove 'ref' from TypeCheckableDirectiveMeta and add a 'selector' instead.
{ "end_byte": 8012, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/testing/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/testing/index.ts_8013_13871
export interface TestDirective extends Partial< Pick< TypeCheckableDirectiveMeta, Exclude< keyof TypeCheckableDirectiveMeta, | 'ref' | 'coercedInputFields' | 'restrictedInputFields' | 'stringLiteralInputFields' | 'undeclaredInputFields' | 'inputs' | 'outputs' | 'hostDirectives' > > > { selector: string; name: string; file?: AbsoluteFsPath; type: 'directive'; inputs?: { [fieldName: string]: | string | { classPropertyName: string; bindingPropertyName: string; required: boolean; isSignal: boolean; transform: DecoratorInputTransform | null; }; }; outputs?: {[fieldName: string]: string}; coercedInputFields?: string[]; restrictedInputFields?: string[]; stringLiteralInputFields?: string[]; undeclaredInputFields?: string[]; isGeneric?: boolean; code?: string; ngContentSelectors?: string[] | null; preserveWhitespaces?: boolean; hostDirectives?: { directive: TestDirective & {isStandalone: true}; inputs?: string[]; outputs?: string[]; }[]; } export interface TestPipe { name: string; file?: AbsoluteFsPath; isStandalone?: boolean; pipeName: string; type: 'pipe'; code?: string; } export type TestDeclaration = TestDirective | TestPipe; export function tcb( template: string, declarations: TestDeclaration[] = [], config?: Partial<TypeCheckingConfig>, options?: {emitSpans?: boolean}, templateParserOptions?: ParseTemplateOptions, ): string { const codeLines = [`export class Test<T extends string> {}`]; (function addCodeLines(currentDeclarations) { for (const decl of currentDeclarations) { if (decl.type === 'directive' && decl.hostDirectives) { addCodeLines(decl.hostDirectives.map((hostDir) => hostDir.directive)); } codeLines.push(decl.code ?? `export class ${decl.name}<T extends string> {}`); } })(declarations); const rootFilePath = absoluteFrom('/synthetic.ts'); const {program, host} = makeProgram([ {name: rootFilePath, contents: codeLines.join('\n'), isRoot: true}, ]); const sf = getSourceFileOrError(program, rootFilePath); const clazz = getClass(sf, 'Test'); const templateUrl = 'synthetic.html'; const {nodes, errors} = parseTemplate(template, templateUrl, templateParserOptions); if (errors !== null) { throw new Error('Template parse errors: \n' + errors.join('\n')); } const {matcher, pipes} = prepareDeclarations( declarations, (decl) => getClass(sf, decl.name), new Map(), ); const binder = new R3TargetBinder<DirectiveMeta>(matcher); const boundTarget = binder.bind({template: nodes}); const id = 'tcb' as TemplateId; const meta: TypeCheckBlockMetadata = { id, boundTarget, pipes, schemas: [], isStandalone: false, preserveWhitespaces: false, }; const fullConfig: TypeCheckingConfig = { applyTemplateContextGuards: true, checkQueries: false, checkTypeOfInputBindings: true, honorAccessModifiersForInputBindings: false, strictNullInputBindings: true, checkTypeOfAttributes: true, checkTypeOfDomBindings: false, checkTypeOfOutputEvents: true, checkTypeOfAnimationEvents: true, checkTypeOfDomEvents: true, checkTypeOfDomReferences: true, checkTypeOfNonDomReferences: true, checkTypeOfPipes: true, checkTemplateBodies: true, checkControlFlowBodies: true, alwaysCheckSchemaInTemplateBodies: true, controlFlowPreventingContentProjection: 'warning', unusedStandaloneImports: 'warning', strictSafeNavigationTypes: true, useContextGenericType: true, strictLiteralTypes: true, enableTemplateTypeChecker: false, useInlineTypeConstructors: true, suggestionsForSuboptimalTypeInference: false, allowSignalsInTwoWayBindings: true, ...config, }; options = options || { emitSpans: false, }; const fileName = absoluteFrom('/type-check-file.ts'); const reflectionHost = new TypeScriptReflectionHost(program.getTypeChecker()); const refEmmiter: ReferenceEmitter = new ReferenceEmitter([ new LocalIdentifierStrategy(), new RelativePathStrategy(reflectionHost), ]); const env = new TypeCheckFile(fileName, fullConfig, refEmmiter, reflectionHost, host); env.addTypeCheckBlock( new Reference(clazz), meta, new NoopSchemaChecker(), new NoopOobRecorder(), TcbGenericContextBehavior.UseEmitter, ); const rendered = env.render(!options.emitSpans /* removeComments */); return rendered.replace(/\s+/g, ' '); } /** * A file in the test program, along with any template information for components within the file. */ export interface TypeCheckingTarget { /** * Path to the file in the virtual test filesystem. */ fileName: AbsoluteFsPath; /** * Raw source code for the file. * * If this is omitted, source code for the file will be generated based on any expected component * classes. */ source?: string; /** * A map of component class names to string templates for that component. */ templates: {[className: string]: string}; /** * Any declarations (e.g. directives) which should be considered as part of the scope for the * components in this file. */ declarations?: TestDeclaration[]; } /** * Create a testing environment for template type-checking which contains a number of given test * targets. * * A full Angular environment is not necessary to exercise the template type-checking system. * Components only need to be classes which exist, with templates specified in the target * configuration. In many cases, it's not even necessary to include source code for test files, as * that can be auto-generated based on the provided target configuration. */
{ "end_byte": 13871, "start_byte": 8013, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/testing/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/testing/index.ts_13872_22623
export function setup( targets: TypeCheckingTarget[], overrides: { config?: Partial<TypeCheckingConfig>; options?: ts.CompilerOptions; inlining?: boolean; parseOptions?: ParseTemplateOptions; } = {}, ): { templateTypeChecker: TemplateTypeChecker; program: ts.Program; programStrategy: TsCreateProgramDriver; } { const files = [typescriptLibDts(), ...angularCoreDtsFiles(), angularAnimationsDts()]; const fakeMetadataRegistry = new Map(); const shims = new Map<AbsoluteFsPath, AbsoluteFsPath>(); for (const target of targets) { let contents: string; if (target.source !== undefined) { contents = target.source; } else { contents = `// generated from templates\n\nexport const MODULE = true;\n\n`; for (const className of Object.keys(target.templates)) { contents += `export class ${className} {}\n`; } } files.push({ name: target.fileName, contents, }); if (!target.fileName.endsWith('.d.ts')) { const shimName = TypeCheckShimGenerator.shimFor(target.fileName); shims.set(target.fileName, shimName); files.push({ name: shimName, contents: 'export const MODULE = true;', }); } } const opts = overrides.options ?? {}; const config = overrides.config ?? {}; const {program, host, options} = makeProgram( files, { strictNullChecks: true, skipLibCheck: true, noImplicitAny: true, ...opts, }, /* host */ undefined, /* checkForErrors */ false, ); const checker = program.getTypeChecker(); const logicalFs = new LogicalFileSystem(getRootDirs(host, options), host); const reflectionHost = new TypeScriptReflectionHost(checker); const moduleResolver = new ModuleResolver( program, options, host, /* moduleResolutionCache */ null, ); const emitter = new ReferenceEmitter([ new LocalIdentifierStrategy(), new AbsoluteModuleStrategy( program, checker, moduleResolver, new TypeScriptReflectionHost(checker), ), new LogicalProjectStrategy(reflectionHost, logicalFs), ]); const fullConfig = { ...ALL_ENABLED_CONFIG, useInlineTypeConstructors: overrides.inlining !== undefined ? overrides.inlining : ALL_ENABLED_CONFIG.useInlineTypeConstructors, ...config, }; // Map out the scope of each target component, which is needed for the ComponentScopeReader. const scopeMap = new Map<ClassDeclaration, ScopeData>(); for (const target of targets) { const sf = getSourceFileOrError(program, target.fileName); const scope = makeScope(program, sf, target.declarations ?? []); if (shims.has(target.fileName)) { const shimFileName = shims.get(target.fileName)!; const shimSf = getSourceFileOrError(program, shimFileName); sfExtensionData(shimSf).fileShim = { extension: 'ngtypecheck', generatedFrom: target.fileName, }; } for (const className of Object.keys(target.templates)) { const classDecl = getClass(sf, className); scopeMap.set(classDecl, scope); } } const checkAdapter = createTypeCheckAdapter((sf, ctx) => { for (const target of targets) { if (getSourceFileOrError(program, target.fileName) !== sf) { continue; } const declarations = target.declarations ?? []; for (const className of Object.keys(target.templates)) { const classDecl = getClass(sf, className); const template = target.templates[className]; const templateUrl = `${className}.html`; const templateFile = new ParseSourceFile(template, templateUrl); const {nodes, errors} = parseTemplate(template, templateUrl, overrides.parseOptions); if (errors !== null) { throw new Error('Template parse errors: \n' + errors.join('\n')); } const {matcher, pipes} = prepareDeclarations( declarations, (decl) => { let declFile = sf; if (decl.file !== undefined) { declFile = program.getSourceFile(decl.file)!; if (declFile === undefined) { throw new Error(`Unable to locate ${decl.file} for ${decl.type} ${decl.name}`); } } return getClass(declFile, decl.name); }, fakeMetadataRegistry, ); const binder = new R3TargetBinder<DirectiveMeta>(matcher); const classRef = new Reference(classDecl); const sourceMapping: TemplateSourceMapping = { type: 'external', template, templateUrl, componentClass: classRef.node, // Use the class's name for error mappings. node: classRef.node.name, }; ctx.addTemplate( classRef, binder, nodes, pipes, [], sourceMapping, templateFile, errors, false, false, ); } } }); const programStrategy = new TsCreateProgramDriver(program, host, options, ['ngtypecheck']); if (overrides.inlining !== undefined) { (programStrategy as any).supportsInlineOperations = overrides.inlining; } const fakeScopeReader: ComponentScopeReader = { getRemoteScope(): null { return null; }, // If there is a module with [className] + 'Module' in the same source file, that will be // returned as the NgModule for the class. getScopeForComponent(clazz: ClassDeclaration): LocalModuleScope | null { try { const ngModule = getClass(clazz.getSourceFile(), `${clazz.name.getText()}Module`); if (!scopeMap.has(clazz)) { // This class wasn't part of the target set of components with templates, but is // probably a declaration used in one of them. Return an empty scope. const emptyScope: ScopeData = { dependencies: [], isPoisoned: false, }; return { kind: ComponentScopeKind.NgModule, ngModule, compilation: emptyScope, reexports: [], schemas: [], exported: emptyScope, }; } const scope = scopeMap.get(clazz)!; return { kind: ComponentScopeKind.NgModule, ngModule, compilation: scope, reexports: [], schemas: [], exported: scope, }; } catch (e) { // No NgModule was found for this class, so it has no scope. return null; } }, }; const fakeMetadataReader = getFakeMetadataReader(fakeMetadataRegistry); const fakeNgModuleIndex = getFakeNgModuleIndex(fakeMetadataRegistry); const typeCheckScopeRegistry = new TypeCheckScopeRegistry( fakeScopeReader, new CompoundMetadataReader([fakeMetadataReader]), new HostDirectivesResolver(fakeMetadataReader), ); const templateTypeChecker = new TemplateTypeCheckerImpl( program, programStrategy, checkAdapter, fullConfig, emitter, reflectionHost, host, NOOP_INCREMENTAL_BUILD, fakeMetadataReader, fakeMetadataReader, fakeNgModuleIndex, fakeScopeReader, typeCheckScopeRegistry, NOOP_PERF_RECORDER, ); return { templateTypeChecker, program, programStrategy, }; } /** * Diagnoses the given template with the specified declarations. * * @returns a list of error diagnostics. */ export function diagnose( template: string, source: string, declarations?: TestDeclaration[], additionalSources: TestFile[] = [], config?: Partial<TypeCheckingConfig>, options?: ts.CompilerOptions, ): string[] { const sfPath = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup( [ { fileName: sfPath, templates: { 'TestComponent': template, }, source, declarations, }, ...additionalSources.map((testFile) => ({ fileName: testFile.name, source: testFile.contents, templates: {}, })), ], {config, options}, ); const sf = getSourceFileOrError(program, sfPath); const diagnostics = templateTypeChecker.getDiagnosticsForFile(sf, OptimizeFor.WholeProgram); return diagnostics.map((diag) => { const text = ts.flattenDiagnosticMessageText(diag.messageText, '\n'); const fileName = diag.file!.fileName; const {line, character} = ts.getLineAndCharacterOfPosition(diag.file!, diag.start!); return `${fileName}(${line + 1}, ${character + 1}): ${text}`; }); } function createTypeCheckAdapter( fn: (sf: ts.SourceFile, ctx: TypeCheckContext) => void, ): ProgramTypeCheckAdapter { return {typeCheck: fn}; }
{ "end_byte": 22623, "start_byte": 13872, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/testing/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/testing/index.ts_22625_31234
function getFakeMetadataReader( fakeMetadataRegistry: Map<any, DirectiveMeta | null>, ): MetadataReaderWithIndex { return { getDirectiveMetadata(node: Reference<ClassDeclaration>): DirectiveMeta | null { return fakeMetadataRegistry.get(node.debugName) ?? null; }, getKnown(kind: MetaKind): Array<ClassDeclaration> { switch (kind) { // TODO: This is not needed for these ngtsc tests, but may be wanted in the future. default: return []; } }, } as MetadataReaderWithIndex; } function getFakeNgModuleIndex(fakeMetadataRegistry: Map<any, DirectiveMeta | null>): NgModuleIndex { return { getNgModulesExporting(trait: ClassDeclaration): Array<Reference<ClassDeclaration>> { return []; }, } as NgModuleIndex; } type DeclarationResolver = (decl: TestDeclaration) => ClassDeclaration<ts.ClassDeclaration>; function prepareDeclarations( declarations: TestDeclaration[], resolveDeclaration: DeclarationResolver, metadataRegistry: Map<string, TypeCheckableDirectiveMeta>, ) { const matcher = new SelectorMatcher<DirectiveMeta[]>(); const pipes = new Map<string, PipeMeta>(); const hostDirectiveResolder = new HostDirectivesResolver( getFakeMetadataReader(metadataRegistry as Map<string, DirectiveMeta>), ); const directives: DirectiveMeta[] = []; const registerDirective = (decl: TestDirective) => { const meta = getDirectiveMetaFromDeclaration(decl, resolveDeclaration); directives.push(meta as DirectiveMeta); metadataRegistry.set(decl.name, meta); decl.hostDirectives?.forEach((hostDecl) => registerDirective(hostDecl.directive)); }; for (const decl of declarations) { if (decl.type === 'directive') { registerDirective(decl); } else if (decl.type === 'pipe') { pipes.set(decl.pipeName, { kind: MetaKind.Pipe, ref: new Reference(resolveDeclaration(decl)), name: decl.pipeName, nameExpr: null, isStandalone: false, decorator: null, isExplicitlyDeferred: false, }); } } // We need to make two passes over the directives so that all declarations // have been registered by the time we resolve the host directives. for (const meta of directives) { const selector = CssSelector.parse(meta.selector || ''); const matches = [...hostDirectiveResolder.resolve(meta), meta] as DirectiveMeta[]; matcher.addSelectables(selector, matches); } return {matcher, pipes}; } export function getClass(sf: ts.SourceFile, name: string): ClassDeclaration<ts.ClassDeclaration> { for (const stmt of sf.statements) { if (isNamedClassDeclaration(stmt) && stmt.name.text === name) { return stmt; } } throw new Error(`Class ${name} not found in file: ${sf.fileName}: ${sf.text}`); } function getDirectiveMetaFromDeclaration( decl: TestDirective, resolveDeclaration: DeclarationResolver, ) { return { name: decl.name, ref: new Reference(resolveDeclaration(decl)), exportAs: decl.exportAs || null, selector: decl.selector || null, hasNgTemplateContextGuard: decl.hasNgTemplateContextGuard || false, inputs: ClassPropertyMapping.fromMappedObject<InputMapping>(decl.inputs || {}), isComponent: decl.isComponent || false, ngTemplateGuards: decl.ngTemplateGuards || [], coercedInputFields: new Set<string>(decl.coercedInputFields || []), restrictedInputFields: new Set<string>(decl.restrictedInputFields || []), stringLiteralInputFields: new Set<string>(decl.stringLiteralInputFields || []), undeclaredInputFields: new Set<string>(decl.undeclaredInputFields || []), isGeneric: decl.isGeneric ?? false, outputs: ClassPropertyMapping.fromMappedObject(decl.outputs || {}), queries: decl.queries || [], isStructural: false, isStandalone: !!decl.isStandalone, isSignal: !!decl.isSignal, baseClass: null, animationTriggerNames: null, decorator: null, ngContentSelectors: decl.ngContentSelectors || null, preserveWhitespaces: decl.preserveWhitespaces ?? false, isExplicitlyDeferred: false, imports: decl.imports, rawImports: null, hostDirectives: decl.hostDirectives === undefined ? null : decl.hostDirectives.map((hostDecl) => { return { directive: new Reference(resolveDeclaration(hostDecl.directive)), inputs: parseInputOutputMappingArray(hostDecl.inputs || []), outputs: parseInputOutputMappingArray(hostDecl.outputs || []), }; }), } as TypeCheckableDirectiveMeta; } /** * Synthesize `ScopeData` metadata from an array of `TestDeclaration`s. */ function makeScope(program: ts.Program, sf: ts.SourceFile, decls: TestDeclaration[]): ScopeData { const scope: ScopeData = { dependencies: [], isPoisoned: false, }; for (const decl of decls) { let declSf = sf; if (decl.file !== undefined) { declSf = getSourceFileOrError(program, decl.file); } const declClass = getClass(declSf, decl.name); if (decl.type === 'directive') { scope.dependencies.push({ kind: MetaKind.Directive, matchSource: MatchSource.Selector, ref: new Reference(declClass), baseClass: null, name: decl.name, selector: decl.selector, queries: [], inputs: ClassPropertyMapping.fromMappedObject<InputMapping>(decl.inputs || {}), outputs: ClassPropertyMapping.fromMappedObject(decl.outputs || {}), isComponent: decl.isComponent ?? false, exportAs: decl.exportAs ?? null, ngTemplateGuards: decl.ngTemplateGuards ?? [], hasNgTemplateContextGuard: decl.hasNgTemplateContextGuard ?? false, coercedInputFields: new Set<string>(decl.coercedInputFields ?? []), restrictedInputFields: new Set<string>(decl.restrictedInputFields ?? []), stringLiteralInputFields: new Set<string>(decl.stringLiteralInputFields ?? []), undeclaredInputFields: new Set<string>(decl.undeclaredInputFields ?? []), isGeneric: decl.isGeneric ?? false, isPoisoned: false, isStructural: false, animationTriggerNames: null, isStandalone: false, isSignal: false, imports: null, rawImports: null, deferredImports: null, schemas: null, decorator: null, assumedToExportProviders: false, ngContentSelectors: decl.ngContentSelectors || null, preserveWhitespaces: decl.preserveWhitespaces ?? false, isExplicitlyDeferred: false, inputFieldNamesFromMetadataArray: null, hostDirectives: decl.hostDirectives === undefined ? null : decl.hostDirectives.map((hostDecl) => { return { directive: new Reference( getClass( hostDecl.directive.file ? getSourceFileOrError(program, hostDecl.directive.file) : sf, hostDecl.directive.name, ), ), origin: sf, isForwardReference: false, inputs: hostDecl.inputs || {}, outputs: hostDecl.outputs || {}, }; }), }); } else if (decl.type === 'pipe') { scope.dependencies.push({ kind: MetaKind.Pipe, ref: new Reference(declClass), name: decl.pipeName, nameExpr: null, isStandalone: false, decorator: null, isExplicitlyDeferred: false, }); } } return scope; } function parseInputOutputMappingArray(values: string[]) { return values.reduce( (results, value) => { // 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 [field, property] = value.split(':', 2).map((str) => str.trim()); results[field] = property || field; return results; }, {} as {[field: string]: string}, ); } export class NoopSchemaChecker implements DomSchemaChecker { get diagnostics(): ReadonlyArray<TemplateDiagnostic> { return []; } checkElement( id: string, element: TmplAstElement, schemas: SchemaMetadata[], hostIsStandalone: boolean, ): void {} checkProperty( id: string, element: TmplAstElement, name: string, span: ParseSourceSpan, schemas: SchemaMetadata[], hostIsStandalone: boolean, ): void {} }
{ "end_byte": 31234, "start_byte": 22625, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/testing/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/testing/index.ts_31236_32312
export class NoopOobRecorder implements OutOfBandDiagnosticRecorder { get diagnostics(): ReadonlyArray<TemplateDiagnostic> { return []; } missingReferenceTarget(): void {} missingPipe(): void {} deferredPipeUsedEagerly(templateId: TemplateId, ast: BindingPipe): void {} deferredComponentUsedEagerly(templateId: TemplateId, element: TmplAstElement): void {} duplicateTemplateVar(): void {} requiresInlineTcb(): void {} requiresInlineTypeConstructors(): void {} suboptimalTypeInference(): void {} splitTwoWayBinding(): void {} missingRequiredInputs(): void {} illegalForLoopTrackAccess(): void {} inaccessibleDeferredTriggerElement(): void {} controlFlowPreventingContentProjection(): void {} illegalWriteToLetDeclaration( templateId: TemplateId, node: PropertyWrite, target: TmplAstLetDeclaration, ): void {} letUsedBeforeDefinition( templateId: TemplateId, node: PropertyRead, target: TmplAstLetDeclaration, ): void {} conflictingDeclaration(templateId: TemplateId, current: TmplAstLetDeclaration): void {} }
{ "end_byte": 32312, "start_byte": 31236, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/testing/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/diagnostics/BUILD.bazel_0_523
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "diagnostics", srcs = glob(["**/*.ts"]), module_name = "@angular/compiler-cli/src/ngtsc/typecheck/diagnostics", deps = [ "//packages:types", "//packages/compiler", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/typecheck/api", "@npm//typescript", ], )
{ "end_byte": 523, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/diagnostics/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/diagnostics/index.ts_0_264
/** * @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/diagnostic'; export * from './src/id';
{ "end_byte": 264, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/diagnostics/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/diagnostics/src/diagnostic.ts_0_6752
/** * @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 {ParseSourceSpan} from '@angular/compiler'; import ts from 'typescript'; import {addDiagnosticChain, makeDiagnosticChain} from '../../../diagnostics'; import { ExternalTemplateSourceMapping, IndirectTemplateSourceMapping, TemplateDiagnostic, TemplateId, TemplateSourceMapping, } from '../../api'; /** * Constructs a `ts.Diagnostic` for a given `ParseSourceSpan` within a template. */ export function makeTemplateDiagnostic( templateId: TemplateId, mapping: TemplateSourceMapping, span: ParseSourceSpan, category: ts.DiagnosticCategory, code: number, messageText: string | ts.DiagnosticMessageChain, relatedMessages?: { text: string; start: number; end: number; sourceFile: ts.SourceFile; }[], ): TemplateDiagnostic { if (mapping.type === 'direct') { let relatedInformation: ts.DiagnosticRelatedInformation[] | undefined = undefined; if (relatedMessages !== undefined) { relatedInformation = []; for (const relatedMessage of relatedMessages) { relatedInformation.push({ category: ts.DiagnosticCategory.Message, code: 0, file: relatedMessage.sourceFile, start: relatedMessage.start, length: relatedMessage.end - relatedMessage.start, messageText: relatedMessage.text, }); } } // For direct mappings, the error is shown inline as ngtsc was able to pinpoint a string // constant within the `@Component` decorator for the template. This allows us to map the error // directly into the bytes of the source file. return { source: 'ngtsc', code, category, messageText, file: mapping.node.getSourceFile(), componentFile: mapping.node.getSourceFile(), templateId, start: span.start.offset, length: span.end.offset - span.start.offset, relatedInformation, }; } else if (mapping.type === 'indirect' || mapping.type === 'external') { // For indirect mappings (template was declared inline, but ngtsc couldn't map it directly // to a string constant in the decorator), the component's file name is given with a suffix // indicating it's not the TS file being displayed, but a template. // For external temoplates, the HTML filename is used. const componentSf = mapping.componentClass.getSourceFile(); const componentName = mapping.componentClass.name.text; const fileName = mapping.type === 'indirect' ? `${componentSf.fileName} (${componentName} template)` : mapping.templateUrl; let relatedInformation: ts.DiagnosticRelatedInformation[] = []; if (relatedMessages !== undefined) { for (const relatedMessage of relatedMessages) { relatedInformation.push({ category: ts.DiagnosticCategory.Message, code: 0, file: relatedMessage.sourceFile, start: relatedMessage.start, length: relatedMessage.end - relatedMessage.start, messageText: relatedMessage.text, }); } } let sf: ts.SourceFile; try { sf = getParsedTemplateSourceFile(fileName, mapping); } catch (e) { const failureChain = makeDiagnosticChain( `Failed to report an error in '${fileName}' at ${span.start.line + 1}:${ span.start.col + 1 }`, [makeDiagnosticChain((e as Error)?.stack ?? `${e}`)], ); return { source: 'ngtsc', category, code, messageText: addDiagnosticChain(messageText, [failureChain]), file: componentSf, componentFile: componentSf, templateId, // mapping.node represents either the 'template' or 'templateUrl' expression. getStart() // and getEnd() are used because they don't include surrounding whitespace. start: mapping.node.getStart(), length: mapping.node.getEnd() - mapping.node.getStart(), relatedInformation, }; } relatedInformation.push({ category: ts.DiagnosticCategory.Message, code: 0, file: componentSf, // mapping.node represents either the 'template' or 'templateUrl' expression. getStart() // and getEnd() are used because they don't include surrounding whitespace. start: mapping.node.getStart(), length: mapping.node.getEnd() - mapping.node.getStart(), messageText: `Error occurs in the template of component ${componentName}.`, }); return { source: 'ngtsc', category, code, messageText, file: sf, componentFile: componentSf, templateId, start: span.start.offset, length: span.end.offset - span.start.offset, // Show a secondary message indicating the component whose template contains the error. relatedInformation, }; } else { throw new Error(`Unexpected source mapping type: ${(mapping as {type: string}).type}`); } } const TemplateSourceFile = Symbol('TemplateSourceFile'); type TemplateSourceMappingWithSourceFile = ( | ExternalTemplateSourceMapping | IndirectTemplateSourceMapping ) & { [TemplateSourceFile]?: ts.SourceFile; }; function getParsedTemplateSourceFile( fileName: string, mapping: TemplateSourceMappingWithSourceFile, ): ts.SourceFile { if (mapping[TemplateSourceFile] === undefined) { mapping[TemplateSourceFile] = parseTemplateAsSourceFile(fileName, mapping.template); } return mapping[TemplateSourceFile]; } let parseTemplateAsSourceFileForTest: typeof parseTemplateAsSourceFile | null = null; export function setParseTemplateAsSourceFileForTest(fn: typeof parseTemplateAsSourceFile): void { parseTemplateAsSourceFileForTest = fn; } export function resetParseTemplateAsSourceFileForTest(): void { parseTemplateAsSourceFileForTest = null; } function parseTemplateAsSourceFile(fileName: string, template: string): ts.SourceFile { if (parseTemplateAsSourceFileForTest !== null) { return parseTemplateAsSourceFileForTest(fileName, template); } // TODO(alxhub): investigate creating a fake `ts.SourceFile` here instead of invoking the TS // parser against the template (HTML is just really syntactically invalid TypeScript code ;). return ts.createSourceFile( fileName, template, ts.ScriptTarget.Latest, /* setParentNodes */ false, ts.ScriptKind.JSX, ); } export function isTemplateDiagnostic(diagnostic: ts.Diagnostic): diagnostic is TemplateDiagnostic { return ( diagnostic.hasOwnProperty('componentFile') && ts.isSourceFile((diagnostic as any).componentFile) ); }
{ "end_byte": 6752, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/diagnostics/src/diagnostic.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/diagnostics/src/id.ts_0_1047
/** * @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 {DeclarationNode} from '../../../reflection'; import {TemplateId} from '../../api'; const TEMPLATE_ID = Symbol('ngTemplateId'); const NEXT_TEMPLATE_ID = Symbol('ngNextTemplateId'); interface HasTemplateId { [TEMPLATE_ID]: TemplateId; } interface HasNextTemplateId { [NEXT_TEMPLATE_ID]: number; } export function getTemplateId(clazz: DeclarationNode): TemplateId { const node = clazz as ts.Declaration & Partial<HasTemplateId>; if (node[TEMPLATE_ID] === undefined) { node[TEMPLATE_ID] = allocateTemplateId(node.getSourceFile()); } return node[TEMPLATE_ID]!; } function allocateTemplateId(sf: ts.SourceFile & Partial<HasNextTemplateId>): TemplateId { if (sf[NEXT_TEMPLATE_ID] === undefined) { sf[NEXT_TEMPLATE_ID] = 1; } return `tcb${sf[NEXT_TEMPLATE_ID]!++}` as TemplateId; }
{ "end_byte": 1047, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/diagnostics/src/id.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/BUILD.bazel_0_1594
load("//tools:defaults.bzl", "ts_library") ts_library( name = "extended", srcs = glob( ["**/*.ts"], ), visibility = ["//packages/compiler-cli/src/ngtsc:__subpackages__"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/extended/api", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/interpolated_signal_not_invoked", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/invalid_banana_in_box", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/missing_control_flow_directive", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/missing_ngforof_let", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/nullish_coalescing_not_nullable", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/optional_chain_not_nullable", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/skip_hydration_not_static", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/suffix_not_supported", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/text_attribute_not_binding", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/uninvoked_function_in_event_binding", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/unused_let_declaration", "@npm//typescript", ], )
{ "end_byte": 1594, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/index.ts_0_2082
/** * @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, ExtendedTemplateDiagnosticName} from '../../diagnostics'; import {TemplateCheckFactory} from './api'; import {factory as interpolatedSignalNotInvoked} from './checks/interpolated_signal_not_invoked'; import {factory as invalidBananaInBoxFactory} from './checks/invalid_banana_in_box'; import {factory as missingControlFlowDirectiveFactory} from './checks/missing_control_flow_directive'; import {factory as missingNgForOfLetFactory} from './checks/missing_ngforof_let'; import {factory as nullishCoalescingNotNullableFactory} from './checks/nullish_coalescing_not_nullable'; import {factory as optionalChainNotNullableFactory} from './checks/optional_chain_not_nullable'; import {factory as suffixNotSupportedFactory} from './checks/suffix_not_supported'; import {factory as textAttributeNotBindingFactory} from './checks/text_attribute_not_binding'; import {factory as uninvokedFunctionInEventBindingFactory} from './checks/uninvoked_function_in_event_binding'; import {factory as unusedLetDeclarationFactory} from './checks/unused_let_declaration'; export {ExtendedTemplateCheckerImpl} from './src/extended_template_checker'; export const ALL_DIAGNOSTIC_FACTORIES: readonly TemplateCheckFactory< ErrorCode, ExtendedTemplateDiagnosticName >[] = [ invalidBananaInBoxFactory, nullishCoalescingNotNullableFactory, optionalChainNotNullableFactory, missingControlFlowDirectiveFactory, textAttributeNotBindingFactory, missingNgForOfLetFactory, suffixNotSupportedFactory, interpolatedSignalNotInvoked, uninvokedFunctionInEventBindingFactory, unusedLetDeclarationFactory, ]; export const SUPPORTED_DIAGNOSTIC_NAMES = new Set<string>([ ExtendedTemplateDiagnosticName.CONTROL_FLOW_PREVENTING_CONTENT_PROJECTION, ExtendedTemplateDiagnosticName.UNUSED_STANDALONE_IMPORTS, ...ALL_DIAGNOSTIC_FACTORIES.map((factory) => factory.name), ]);
{ "end_byte": 2082, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/skip_hydration_not_static/skip_hydration_not_static_spec.ts_0_5941
/** * @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, ExtendedTemplateDiagnosticName, ngErrorCode} from '../../../../../diagnostics'; import {absoluteFrom, getSourceFileOrError} from '../../../../../file_system'; import {runInEachFileSystem} from '../../../../../file_system/testing'; import {getSourceCodeForDiagnostic} from '../../../../../testing'; import {getClass, setup} from '../../../../testing'; import {factory as skipHydrationNotStaticFactory} from '../../../checks/skip_hydration_not_static'; import {ExtendedTemplateCheckerImpl} from '../../../src/extended_template_checker'; runInEachFileSystem(() => { describe('SkipHydrationNotStatic', () => { it('binds the error code to its extended template diagnostic name', () => { expect(skipHydrationNotStaticFactory.code).toBe(ErrorCode.SKIP_HYDRATION_NOT_STATIC); expect(skipHydrationNotStaticFactory.name).toBe( ExtendedTemplateDiagnosticName.SKIP_HYDRATION_NOT_STATIC, ); }); it('should produce class binding warning', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div [ngSkipHydration]="true"></div>`, }, source: 'export class TestCmp { }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [skipHydrationNotStaticFactory], {}, /* options */ ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.SKIP_HYDRATION_NOT_STATIC)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`[ngSkipHydration]="true"`); }); it('should produce an attribute binding warning', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div [ngSkipHydration]="''"></div>`, }, source: 'export class TestCmp { }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [skipHydrationNotStaticFactory], {}, /* options */ ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.SKIP_HYDRATION_NOT_STATIC)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`[ngSkipHydration]="''"`); }); it('should produce a wrong value warning', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div ngSkipHydration="XXX"></div>`, }, source: 'export class TestCmp { }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [skipHydrationNotStaticFactory], {}, /* options */ ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.SKIP_HYDRATION_NOT_STATIC)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`ngSkipHydration="XXX"`); }); it('should not produce a warning when there is no value', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div ngSkipHydration></div>`, }, source: 'export class TestCmp { }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [skipHydrationNotStaticFactory], {}, /* options */ ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should not produce a warning with a correct value ', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div ngSkipHydration="true"></div>`, }, source: 'export class TestCmp { }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [skipHydrationNotStaticFactory], {}, /* options */ ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); }); });
{ "end_byte": 5941, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/skip_hydration_not_static/skip_hydration_not_static_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/skip_hydration_not_static/BUILD.bazel_0_956
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = ["skip_hydration_not_static_spec.ts"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//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/testing", "//packages/compiler-cli/src/ngtsc/typecheck/extended", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/skip_hydration_not_static", "//packages/compiler-cli/src/ngtsc/typecheck/testing", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/core:npm_package", ], deps = [ ":test_lib", ], )
{ "end_byte": 956, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/skip_hydration_not_static/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/optional_chain_not_nullable/optional_chain_not_nullable_spec.ts_0_873
/** * @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 {DiagnosticCategoryLabel} from '@angular/compiler-cli/src/ngtsc/core/api'; import ts from 'typescript'; import {ErrorCode, ExtendedTemplateDiagnosticName, ngErrorCode} from '../../../../../diagnostics'; import {absoluteFrom, getSourceFileOrError} from '../../../../../file_system'; import {runInEachFileSystem} from '../../../../../file_system/testing'; import {getSourceCodeForDiagnostic} from '../../../../../testing'; import {getClass, setup} from '../../../../testing'; import {factory as optionalChainNotNullableFactory} from '../../../checks/optional_chain_not_nullable'; import {ExtendedTemplateCheckerImpl} from '../../../src/extended_template_checker';
{ "end_byte": 873, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/optional_chain_not_nullable/optional_chain_not_nullable_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/optional_chain_not_nullable/optional_chain_not_nullable_spec.ts_875_9355
runInEachFileSystem(() => { describe('OptionalChainNotNullableCheck', () => { it('binds the error code to its extended template diagnostic name', () => { expect(optionalChainNotNullableFactory.code).toBe(ErrorCode.OPTIONAL_CHAIN_NOT_NULLABLE); expect(optionalChainNotNullableFactory.name).toBe( ExtendedTemplateDiagnosticName.OPTIONAL_CHAIN_NOT_NULLABLE, ); }); it('should return a check if `strictNullChecks` is enabled', () => { expect(optionalChainNotNullableFactory.create({strictNullChecks: true})).toBeDefined(); }); it('should return a check if `strictNullChecks` is not configured but `strict` is enabled', () => { expect(optionalChainNotNullableFactory.create({strict: true})).toBeDefined(); }); it('should not return a check if `strictNullChecks` is disabled', () => { expect(optionalChainNotNullableFactory.create({strictNullChecks: false})).toBeNull(); expect(optionalChainNotNullableFactory.create({})).toBeNull(); // Defaults disabled. }); it('should not return a check if `strict` is enabled but `strictNullChecks` is disabled', () => { expect( optionalChainNotNullableFactory.create({strict: true, strictNullChecks: false}), ).toBeNull(); }); it('should produce optional chain warning for property access', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ var1?.bar }}`, }, source: 'export class TestCmp { var1: { foo: string } = { foo: "bar" }; }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [optionalChainNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.OPTIONAL_CHAIN_NOT_NULLABLE)); expect(diags[0].messageText).toContain( `the '?.' operator can be replaced with the '.' operator`, ); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`bar`); }); it('should produce optional chain warning for indexed access', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ var1?.['bar'] }}`, }, source: 'export class TestCmp { var1: { foo: string } = { foo: "bar" }; }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [optionalChainNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.OPTIONAL_CHAIN_NOT_NULLABLE)); expect(diags[0].messageText).toContain(`the '?.' operator can be safely removed`); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`var1?.['bar']`); }); it('should produce optional chain warning for method call', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ foo?.() }}`, }, source: 'export class TestCmp { foo: () => string }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [optionalChainNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.OPTIONAL_CHAIN_NOT_NULLABLE)); expect(diags[0].messageText).toContain(`the '?.' operator can be safely removed`); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`foo?.()`); }); it('should produce optional chain warning for classes with inline TCBs', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup( [ { fileName, templates: { 'TestCmp': `{{ var1?.bar }}`, }, source: 'class TestCmp { var1: { foo: string } = { foo: "bar" }; }', }, ], {inlining: true}, ); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [optionalChainNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.OPTIONAL_CHAIN_NOT_NULLABLE)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`bar`); }); it('should not produce optional chain warning for a nullable type', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ var1?.bar }}`, }, source: 'export class TestCmp { var1: string | null = "text"; }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [optionalChainNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should not produce optional chain warning for the any type', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ var1?.bar }}`, }, source: 'export class TestCmp { var1: any; }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [optionalChainNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should not produce optional chain warning for the unknown type', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ var1?.bar }}`, }, source: 'export class TestCmp { var1: unknown; }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [optionalChainNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); });
{ "end_byte": 9355, "start_byte": 875, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/optional_chain_not_nullable/optional_chain_not_nullable_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/optional_chain_not_nullable/optional_chain_not_nullable_spec.ts_9361_12364
it('should not produce optional chain warning for a type that includes undefined', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ var1?.bar }}`, }, source: 'export class TestCmp { var1: string | undefined = "text"; }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [optionalChainNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should not produce optional chain warning when the left side is a nullable expression', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ func()?.foo }}`, }, source: ` export class TestCmp { func = (): { foo: string } | null => null; } `, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [optionalChainNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should respect configured diagnostic category', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ var1?.bar }}`, }, source: 'export class TestCmp { var1: { foo: string } = { foo: "bar" }; }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [optionalChainNotNullableFactory], { strictNullChecks: true, extendedDiagnostics: { checks: { optionalChainNotNullable: DiagnosticCategoryLabel.Error, }, }, }, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Error); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.OPTIONAL_CHAIN_NOT_NULLABLE)); }); }); });
{ "end_byte": 12364, "start_byte": 9361, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/optional_chain_not_nullable/optional_chain_not_nullable_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/optional_chain_not_nullable/BUILD.bazel_0_960
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = ["optional_chain_not_nullable_spec.ts"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//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/testing", "//packages/compiler-cli/src/ngtsc/typecheck/extended", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/optional_chain_not_nullable", "//packages/compiler-cli/src/ngtsc/typecheck/testing", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/core:npm_package", ], deps = [ ":test_lib", ], )
{ "end_byte": 960, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/optional_chain_not_nullable/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/interpolated_signal_not_invoked/interpolated_signal_not_invoked_spec.ts_0_789
/** * @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, ExtendedTemplateDiagnosticName, ngErrorCode} from '../../../../../diagnostics'; import {absoluteFrom, getSourceFileOrError} from '../../../../../file_system'; import {runInEachFileSystem} from '../../../../../file_system/testing'; import {getSourceCodeForDiagnostic} from '../../../../../testing'; import {getClass, setup} from '../../../../testing'; import {factory as interpolatedSignalFactory} from '../../../checks/interpolated_signal_not_invoked'; import {ExtendedTemplateCheckerImpl} from '../../../src/extended_template_checker';
{ "end_byte": 789, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/interpolated_signal_not_invoked/interpolated_signal_not_invoked_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/interpolated_signal_not_invoked/interpolated_signal_not_invoked_spec.ts_791_8880
runInEachFileSystem(() => { describe('Interpolated Signal', () => { it('binds the error code to its extended template diagnostic name', () => { expect(interpolatedSignalFactory.code).toBe(ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED); expect(interpolatedSignalFactory.name).toBe( ExtendedTemplateDiagnosticName.INTERPOLATED_SIGNAL_NOT_INVOKED, ); }); it('should not produce a warning when a signal getter is invoked', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div>{{ mySignal() }}</div>`, }, source: ` import {signal} from '@angular/core'; export class TestCmp { mySignal = signal(0); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {}, /* options */ ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); }); it('should produce a warning when a signal is not invoked', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div>{{ mySignal1 }} {{ mySignal2 }}</div>`, }, source: ` import {signal, Signal} from '@angular/core'; export class TestCmp { mySignal1 = signal<number>(0); mySignal2: Signal<number>; }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(2); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`mySignal1`); expect(getSourceCodeForDiagnostic(diags[1])).toBe(`mySignal2`); }); it('should produce a warning when a readonly signal is not invoked', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div>{{ count }}</div>`, }, source: ` import {signal} from '@angular/core'; export class TestCmp { count = signal(0).asReadonly(); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED)); expect(getSourceCodeForDiagnostic(diags[0])).toBe('count'); }); it('should produce a warning when a computed signal is not invoked', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div>{{ mySignal2 }}</div>`, }, source: ` import {signal, computed} from '@angular/core'; export class TestCmp { mySignal1 = signal<number>(0); mySignal2 = computed(() => mySignal() * 2); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`mySignal2`); }); it('should produce a warning when an input signal is not invoked', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div>{{ myInput }}</div>`, }, source: ` import {input} from '@angular/core'; export class TestCmp { myInput = input(0); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`myInput`); }); it('should produce a warning when a required input signal is not invoked', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div>{{ myRequiredInput }}</div>`, }, source: ` import {input} from '@angular/core'; export class TestCmp { myRequiredInput = input.required(0); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`myRequiredInput`); }); it('should produce a warning when a model signal is not invoked', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div>{{ myModel }}</div>`, }, source: ` import {model} from '@angular/core'; export class TestCmp { myModel = model(0); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`myModel`); });
{ "end_byte": 8880, "start_byte": 791, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/interpolated_signal_not_invoked/interpolated_signal_not_invoked_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/interpolated_signal_not_invoked/interpolated_signal_not_invoked_spec.ts_8884_17543
it('should produce a warning when a required model signal is not invoked', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div>{{ myRequiredModel }}</div>`, }, source: ` import {model} from '@angular/core'; export class TestCmp { myRequiredModel = model.required(0); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`myRequiredModel`); }); it('should not produce a warning when a signal is not invoked in a banana in box binding', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div [(value)]="signal">{{ myRequiredModel }}</div>`, }, source: ` import {signal} from '@angular/core'; export class TestCmp { mySignal = signal(0); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should not produce a warning when a signal is not invoked in an input binding as they are skipped', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div dir [myInput]="mySignal"></div>`, }, source: ` import {signal, input} from '@angular/core'; export class TestDir { myInput = input.required(); } export class TestCmp { mySignal = signal(0); }`, declarations: [ { type: 'directive', name: 'TestDir', selector: '[dir]', inputs: { myInput: { isSignal: true, bindingPropertyName: 'myInput', classPropertyName: 'myInput', required: true, transform: null, }, }, }, ], }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {}, /* options */ ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should produce a warning when a signal in a nested property read is not invoked', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div>{{ obj.nested.prop.signal }}</div>`, }, source: ` import {signal} from '@angular/core'; export class TestCmp { obj = { nested: { prop: { signal: signal<number>(0) } } } }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`signal`); }); it('should not produce a warning when model signals are invoked', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div>{{ myModel() }} - {{ myRequiredModel() }}</div>`, }, source: ` import {model} from '@angular/core'; export class TestCmp { myModel = model(0); myRequiredModel = model.required(0); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should not produce a warning when a computed signal is invoked', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div>{{ mySignal2() }}</div>`, }, source: ` import {signal, computed} from '@angular/core'; export class TestCmp { mySignal1 = signal<number>(0); mySignal2 = computed(() => mySignal() * 2); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should not produce a warning when input signals are invoked', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div>{{ myInput() }} - {{ myRequiredInput() }}</div>`, }, source: ` import {input} from '@angular/core'; export class TestCmp { myInput = input(0); myRequiredInput = input.required(0); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should produce a warning when signal is not invoked on interpolated binding', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div id="{{mySignal}}"></div>`, }, source: ` import {signal} from '@angular/core'; export class TestCmp { mySignal = signal<number>(0); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`mySignal`); });
{ "end_byte": 17543, "start_byte": 8884, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/interpolated_signal_not_invoked/interpolated_signal_not_invoked_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/interpolated_signal_not_invoked/interpolated_signal_not_invoked_spec.ts_17547_25859
it('should not produce a warning when signal is invoked on interpolated binding', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div id="{{mySignal()}}"></div>`, }, source: ` import {signal} from '@angular/core'; export class TestCmp { mySignal = signal<number>(0); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should produce a warning when signal is invoked in attribute binding interpolation ', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div attr.id="my-{{mySignal}}-item"></div>`, }, source: ` import {signal} from '@angular/core'; export class TestCmp { mySignal = signal<number>(0); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`mySignal`); }); it('should not produce a warning when signal is invoked in attribute binding interpolation ', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div attr.id="my-{{mySignal()}}-item"></div>`, }, source: ` import {signal} from '@angular/core'; export class TestCmp { mySignal = signal<number>(0); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {}, /* options */ ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should produce a warning when nested signal is not invoked on interpolated binding', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div id="{{myObject.myObject2.myNestedSignal}}"></div>`, }, source: ` import {signal} from '@angular/core'; export class TestCmp { myObject = {myObject2: {myNestedSignal: signal<number>(0)}}; }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`myNestedSignal`); }); [ ['dom property', 'id'], ['class', 'class.green'], ['style', 'style.width'], ['attribute', 'attr.role'], ['animation', '@triggerName'], ].forEach(([name, binding]) => { it(`should produce a warning when signal isn't invoked on ${name} binding`, () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div [${binding}]="mySignal"></div>`, }, source: ` import {signal} from '@angular/core'; export class TestCmp { mySignal = signal<number>(0); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`mySignal`); }); it(`should not produce a warning when signal is invoked on ${name} binding`, () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div [${binding}]="mySignal()"></div>`, }, source: ` import {signal} from '@angular/core'; export class TestCmp { mySignal = signal<number>(0); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); }); it('should not produce a warning with other Signal type', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div>{{ mySignal }} {{ mySignal2 }}</div>`, }, source: ` import {signal} from '@not-angular/core'; export class TestCmp { mySignal = signal(0); mySignal2 = signal(2); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should not produce a warning with other Signal type', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div>{{ foo(mySignal) }} </div>`, }, source: ` import {signal} from '@angular/core'; export class TestCmp { mySignal = signal(0); foo(signal: Signal) { return 'foo' } } `, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); });
{ "end_byte": 25859, "start_byte": 17547, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/interpolated_signal_not_invoked/interpolated_signal_not_invoked_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/interpolated_signal_not_invoked/interpolated_signal_not_invoked_spec.ts_25863_29603
['name', 'length', 'prototype', 'set', 'update', 'asReadonly'].forEach( (functionInstanceProperty) => { it(`should produce a warning when a property named '${functionInstanceProperty}' of a not invoked signal is used in interpolation`, () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div>{{myObject.mySignal.${functionInstanceProperty}}}</div>`, }, source: ` import {signal} from '@angular/core'; export class TestCmp { myObject = { mySignal: signal<{ ${functionInstanceProperty}: string }>({ ${functionInstanceProperty}: 'foo' }) }; }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {}, /* options */ ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`mySignal`); }); it(`should not produce a warning when a property named ${functionInstanceProperty} of an invoked signal is used in interpolation`, () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div>{{mySignal().${functionInstanceProperty}}}</div>`, }, source: ` import {signal} from '@angular/core'; export class TestCmp { mySignal = signal<{ ${functionInstanceProperty}: string }>({ ${functionInstanceProperty}: 'foo' }); }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {}, /* options */ ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it(`should not produce a warning when a property named ${functionInstanceProperty} of an object is used in interpolation`, () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div>{{myObject.${functionInstanceProperty}}}</div>`, }, source: ` import {signal} from '@angular/core'; export class TestCmp { myObject = { ${functionInstanceProperty}: 'foo' }; }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [interpolatedSignalFactory], {}, /* options */ ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); }, ); });
{ "end_byte": 29603, "start_byte": 25863, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/interpolated_signal_not_invoked/interpolated_signal_not_invoked_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/interpolated_signal_not_invoked/BUILD.bazel_0_968
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = ["interpolated_signal_not_invoked_spec.ts"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//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/testing", "//packages/compiler-cli/src/ngtsc/typecheck/extended", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/interpolated_signal_not_invoked", "//packages/compiler-cli/src/ngtsc/typecheck/testing", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/core:npm_package", ], deps = [ ":test_lib", ], )
{ "end_byte": 968, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/interpolated_signal_not_invoked/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/uninvoked_function_in_event_binding/uninvoked_function_in_event_binding_spec.ts_0_806
/** * @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, ExtendedTemplateDiagnosticName, ngErrorCode} from '../../../../../diagnostics'; import {absoluteFrom, getSourceFileOrError} from '../../../../../file_system'; import {runInEachFileSystem} from '../../../../../file_system/testing'; import {getSourceCodeForDiagnostic} from '../../../../../testing'; import {getClass, setup} from '../../../../testing'; import {factory as uninvokedFunctionInEventBindingFactory} from '../../../checks/uninvoked_function_in_event_binding'; import {ExtendedTemplateCheckerImpl} from '../../../src/extended_template_checker';
{ "end_byte": 806, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/uninvoked_function_in_event_binding/uninvoked_function_in_event_binding_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/uninvoked_function_in_event_binding/uninvoked_function_in_event_binding_spec.ts_808_8460
runInEachFileSystem(() => { describe('UninvokedFunctionInEventBindingFactoryCheck', () => { it('binds the error code to its extended template diagnostic name', () => { expect(uninvokedFunctionInEventBindingFactory.code).toBe( ErrorCode.UNINVOKED_FUNCTION_IN_EVENT_BINDING, ); expect(uninvokedFunctionInEventBindingFactory.name).toBe( ExtendedTemplateDiagnosticName.UNINVOKED_FUNCTION_IN_EVENT_BINDING, ); }); it('should produce a diagnostic when a function in an event binding is not invoked', () => { const diags = setupTestComponent(`<button (click)="increment"></button>`, `increment() { }`); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.UNINVOKED_FUNCTION_IN_EVENT_BINDING)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`(click)="increment"`); expect(diags[0].messageText).toBe(generateDiagnosticText('increment()')); }); it('should produce a diagnostic when a nested function in an event binding is not invoked', () => { const diags = setupTestComponent( `<button (click)="nested.nested1.nested2.increment"></button>`, `nested = { nested1: { nested2: { increment() { } } } }`, ); expect(diags.length).toBe(1); expect(getSourceCodeForDiagnostic(diags[0])).toBe( `(click)="nested.nested1.nested2.increment"`, ); expect(diags[0].messageText).toBe( generateDiagnosticText('nested.nested1.nested2.increment()'), ); }); it('should produce a diagnostic when a nested function that uses key read in an event binding is not invoked', () => { const diags = setupTestComponent( `<button (click)="nested.nested1['nested2'].increment"></button>`, `nested = { nested1: { nested2: { increment() { } } } }`, ); expect(diags.length).toBe(1); expect(getSourceCodeForDiagnostic(diags[0])).toBe( `(click)="nested.nested1['nested2'].increment"`, ); expect(diags[0].messageText).toBe( generateDiagnosticText(`nested.nested1['nested2'].increment()`), ); }); it('should produce a diagnostic when a function in a chain is not invoked', () => { const diags = setupTestComponent( ` <button (click)="increment; decrement"></button> <button (click)="increment; decrement()"></button> <button (click)="increment(); decrement"></button> `, `increment() { } decrement() { }`, ); expect(diags.length).toBe(4); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`(click)="increment; decrement"`); expect(diags[0].messageText).toBe(generateDiagnosticText('increment()')); expect(getSourceCodeForDiagnostic(diags[1])).toBe(`(click)="increment; decrement"`); expect(diags[1].messageText).toBe(generateDiagnosticText('decrement()')); expect(getSourceCodeForDiagnostic(diags[2])).toBe(`(click)="increment; decrement()"`); expect(diags[2].messageText).toBe(generateDiagnosticText('increment()')); expect(getSourceCodeForDiagnostic(diags[3])).toBe(`(click)="increment(); decrement"`); expect(diags[3].messageText).toBe(generateDiagnosticText('decrement()')); }); it('should produce a diagnostic when a function in a conditional is not invoked', () => { const diags = setupTestComponent( `<button (click)="true ? increment : decrement"></button>`, `increment() { } decrement() { }`, ); expect(diags.length).toBe(2); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`(click)="true ? increment : decrement"`); expect(diags[0].messageText).toBe(generateDiagnosticText('increment()')); expect(getSourceCodeForDiagnostic(diags[1])).toBe(`(click)="true ? increment : decrement"`); expect(diags[1].messageText).toBe(generateDiagnosticText('decrement()')); }); it('should produce a diagnostic when a function in a conditional is not invoked', () => { const diags = setupTestComponent( `<button (click)="true ? increment() : decrement"></button>`, `increment() { } decrement() { }`, ); expect(diags.length).toBe(1); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`(click)="true ? increment() : decrement"`); expect(diags[0].messageText).toBe(generateDiagnosticText('decrement()')); }); it('should produce a diagnostic when a nested function in a conditional is not invoked', () => { const diags = setupTestComponent( `<button (click)="true ? counter.increment : nested['nested1'].nested2?.source().decrement"></button>`, ` counter = { increment() { } } nested = { nested1: { nested2?: { source() { return { decrement() } { } } } } } `, ); expect(diags.length).toBe(2); expect(getSourceCodeForDiagnostic(diags[0])).toBe( `(click)="true ? counter.increment : nested['nested1'].nested2?.source().decrement"`, ); expect(diags[0].messageText).toBe(generateDiagnosticText('counter.increment()')); expect(getSourceCodeForDiagnostic(diags[1])).toBe( `(click)="true ? counter.increment : nested['nested1'].nested2?.source().decrement"`, ); expect(diags[1].messageText).toBe( generateDiagnosticText(`nested['nested1'].nested2?.source().decrement()`), ); }); it('should produce a diagnostic when a function in a function is not invoked', () => { const diags = setupTestComponent( `<button (click)="nested.nested1.nested2.source().decrement"></button>`, `nested = { nested1: { nested2: { source() { return { decrement() { } } } } } }`, ); expect(diags.length).toBe(1); expect(getSourceCodeForDiagnostic(diags[0])).toBe( `(click)="nested.nested1.nested2.source().decrement"`, ); expect(diags[0].messageText).toBe( generateDiagnosticText('nested.nested1.nested2.source().decrement()'), ); }); it('should produce a diagnostic when a function that returns a function is not invoked', () => { const diags = setupTestComponent( `<button (click)="incrementAndLaterDecrement"></button>`, `incrementAndLaterDecrement(): () => void { return () => {} }`, ); expect(diags.length).toBe(1); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`(click)="incrementAndLaterDecrement"`); expect(diags[0].messageText).toBe(generateDiagnosticText('incrementAndLaterDecrement()')); }); it('should not produce a diagnostic when an invoked function returns a function', () => { const diags = setupTestComponent( `<button (click)="incrementAndLaterDecrement()"></button>`, `incrementAndLaterDecrement(): () => void { return () => {} }`, ); expect(diags.length).toBe(0); }); it('should not produce a warning when the function is not invoked in two-way-binding', () => { const diags = setupTestComponent( `<button [(event)]="increment"></button>`, `increment() { }`, ); expect(diags.length).toBe(0); }); it('should not produce a warning when the function is invoked', () => { const diags = setupTestComponent( ` <button (click)="increment()"></button> <button (click)="counter.increment()"></button> <button (click)="increment?.()"></button> `, ` counter = { increment() { } } increment() { } `, ); expect(diags.length).toBe(0); }); }); });
{ "end_byte": 8460, "start_byte": 808, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/uninvoked_function_in_event_binding/uninvoked_function_in_event_binding_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/uninvoked_function_in_event_binding/uninvoked_function_in_event_binding_spec.ts_8462_9247
function setupTestComponent(template: string, classField: string) { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: {'TestCmp': template}, source: `export class TestCmp { ${classField} }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [uninvokedFunctionInEventBindingFactory], {} /* options */, ); return extendedTemplateChecker.getDiagnosticsForComponent(component); } function generateDiagnosticText(text: string): string { return `Function in event binding should be invoked: ${text}`; }
{ "end_byte": 9247, "start_byte": 8462, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/uninvoked_function_in_event_binding/uninvoked_function_in_event_binding_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/uninvoked_function_in_event_binding/BUILD.bazel_0_976
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = ["uninvoked_function_in_event_binding_spec.ts"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//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/testing", "//packages/compiler-cli/src/ngtsc/typecheck/extended", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/uninvoked_function_in_event_binding", "//packages/compiler-cli/src/ngtsc/typecheck/testing", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/core:npm_package", ], deps = [ ":test_lib", ], )
{ "end_byte": 976, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/uninvoked_function_in_event_binding/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/text_attribute_not_binding/BUILD.bazel_0_958
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = ["text_attribute_not_binding_spec.ts"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//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/testing", "//packages/compiler-cli/src/ngtsc/typecheck/extended", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/text_attribute_not_binding", "//packages/compiler-cli/src/ngtsc/typecheck/testing", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/core:npm_package", ], deps = [ ":test_lib", ], )
{ "end_byte": 958, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/text_attribute_not_binding/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/text_attribute_not_binding/text_attribute_not_binding_spec.ts_0_5327
/** * @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 {DiagnosticCategoryLabel} from '@angular/compiler-cli/src/ngtsc/core/api'; import ts from 'typescript'; import {ErrorCode, ExtendedTemplateDiagnosticName, ngErrorCode} from '../../../../../diagnostics'; import {absoluteFrom, getSourceFileOrError} from '../../../../../file_system'; import {runInEachFileSystem} from '../../../../../file_system/testing'; import {getSourceCodeForDiagnostic} from '../../../../../testing'; import {getClass, setup} from '../../../../testing'; import {factory as textAttributeNotBindingFactory} from '../../../checks/text_attribute_not_binding'; import {ExtendedTemplateCheckerImpl} from '../../../src/extended_template_checker'; runInEachFileSystem(() => { describe('TextAttributeNotBindingCheck', () => { it('binds the error code to its extended template diagnostic name', () => { expect(textAttributeNotBindingFactory.code).toBe(ErrorCode.TEXT_ATTRIBUTE_NOT_BINDING); expect(textAttributeNotBindingFactory.name).toBe( ExtendedTemplateDiagnosticName.TEXT_ATTRIBUTE_NOT_BINDING, ); }); it('should produce class binding warning', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div class.blue="true"></div>`, }, source: 'export class TestCmp { }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [textAttributeNotBindingFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.TEXT_ATTRIBUTE_NOT_BINDING)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`class.blue="true"`); }); it('should produce an attribute binding warning', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div attr.id="bar"></div>`, }, source: 'export class TestCmp { }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [textAttributeNotBindingFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.TEXT_ATTRIBUTE_NOT_BINDING)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`attr.id="bar"`); }); it('should produce a style binding warning', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div style.margin-right.px="5"></div>`, }, source: 'export class TestCmp { }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [textAttributeNotBindingFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.TEXT_ATTRIBUTE_NOT_BINDING)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`style.margin-right.px="5"`); }); it('should not produce a warning when there is no value', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div attr.readonly></div>`, }, source: 'export class TestCmp { }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [textAttributeNotBindingFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.TEXT_ATTRIBUTE_NOT_BINDING)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`attr.readonly`); }); }); });
{ "end_byte": 5327, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/text_attribute_not_binding/text_attribute_not_binding_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/nullish_coalescing_not_nullable/BUILD.bazel_0_968
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = ["nullish_coalescing_not_nullable_spec.ts"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//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/testing", "//packages/compiler-cli/src/ngtsc/typecheck/extended", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/nullish_coalescing_not_nullable", "//packages/compiler-cli/src/ngtsc/typecheck/testing", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/core:npm_package", ], deps = [ ":test_lib", ], )
{ "end_byte": 968, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/nullish_coalescing_not_nullable/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/nullish_coalescing_not_nullable/nullish_coalescing_not_nullable_spec.ts_0_881
/** * @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 {DiagnosticCategoryLabel} from '@angular/compiler-cli/src/ngtsc/core/api'; import ts from 'typescript'; import {ErrorCode, ExtendedTemplateDiagnosticName, ngErrorCode} from '../../../../../diagnostics'; import {absoluteFrom, getSourceFileOrError} from '../../../../../file_system'; import {runInEachFileSystem} from '../../../../../file_system/testing'; import {getSourceCodeForDiagnostic} from '../../../../../testing'; import {getClass, setup} from '../../../../testing'; import {factory as nullishCoalescingNotNullableFactory} from '../../../checks/nullish_coalescing_not_nullable'; import {ExtendedTemplateCheckerImpl} from '../../../src/extended_template_checker';
{ "end_byte": 881, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/nullish_coalescing_not_nullable/nullish_coalescing_not_nullable_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/nullish_coalescing_not_nullable/nullish_coalescing_not_nullable_spec.ts_883_8802
runInEachFileSystem(() => { describe('NullishCoalescingNotNullableCheck', () => { it('binds the error code to its extended template diagnostic name', () => { expect(nullishCoalescingNotNullableFactory.code).toBe( ErrorCode.NULLISH_COALESCING_NOT_NULLABLE, ); expect(nullishCoalescingNotNullableFactory.name).toBe( ExtendedTemplateDiagnosticName.NULLISH_COALESCING_NOT_NULLABLE, ); }); it('should return a check if `strictNullChecks` is enabled', () => { expect(nullishCoalescingNotNullableFactory.create({strictNullChecks: true})).toBeDefined(); }); it('should return a check if `strictNullChecks` is not configured but `strict` is enabled', () => { expect(nullishCoalescingNotNullableFactory.create({strict: true})).toBeDefined(); }); it('should not return a check if `strictNullChecks` is disabled', () => { expect(nullishCoalescingNotNullableFactory.create({strictNullChecks: false})).toBeNull(); expect(nullishCoalescingNotNullableFactory.create({})).toBeNull(); // Defaults disabled. }); it('should not return a check if `strict` is enabled but `strictNullChecks` is disabled', () => { expect( nullishCoalescingNotNullableFactory.create({strict: true, strictNullChecks: false}), ).toBeNull(); }); it('should produce nullish coalescing warning', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ var1 ?? 'foo' }}`, }, source: 'export class TestCmp { var1: string = "text"; }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [nullishCoalescingNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.NULLISH_COALESCING_NOT_NULLABLE)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`var1 ?? 'foo'`); }); it('should produce nullish coalescing warning for classes with inline TCBs', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup( [ { fileName, templates: { 'TestCmp': `{{ var1 ?? 'foo' }}`, }, source: 'class TestCmp { var1: string = "text"; }', }, ], {inlining: true}, ); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [nullishCoalescingNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.NULLISH_COALESCING_NOT_NULLABLE)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`var1 ?? 'foo'`); }); it('should not produce nullish coalescing warning for a nullable type', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ var1 ?? 'foo' }}`, }, source: 'export class TestCmp { var1: string | null = "text"; }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [nullishCoalescingNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should not produce diagnostics for nullish coalescing in a chain', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ var1 !== '' && (items?.length ?? 0) > 0 }}`, }, source: 'export class TestCmp { var1 = "text"; items: string[] | undefined = [] }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [nullishCoalescingNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should not produce nullish coalescing warning for the any type', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ var1 ?? 'foo' }}`, }, source: 'export class TestCmp { var1: any; }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [nullishCoalescingNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should not produce nullish coalescing warning for the unknown type', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ var1 ?? 'foo' }}`, }, source: 'export class TestCmp { var1: unknown; }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [nullishCoalescingNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should not produce nullish coalescing warning for a type that includes undefined', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ var1 ?? 'foo' }}`, }, source: 'export class TestCmp { var1: string | undefined = "text"; }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [nullishCoalescingNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); });
{ "end_byte": 8802, "start_byte": 883, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/nullish_coalescing_not_nullable/nullish_coalescing_not_nullable_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/nullish_coalescing_not_nullable/nullish_coalescing_not_nullable_spec.ts_8808_13607
it('warns for pipe arguments which are likely configured incorrectly (?? operates on "format" here)', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ 123 | date: 'format' ?? 'invalid date' }}`, }, source: ` export class TestCmp { var1: string | undefined = "text"; } export class DatePipe { transform(value: string, format: string): string[] { } `, declarations: [ { type: 'pipe', name: 'DatePipe', pipeName: 'date', }, ], }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [nullishCoalescingNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.NULLISH_COALESCING_NOT_NULLABLE)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`'format' ?? 'invalid date'`); }); it('does not warn for pipe arguments when parens are used', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ (123 | date: 'format') ?? 'invalid date' }}`, }, source: ` export class TestCmp { var1: string | undefined = "text"; } export class DatePipe { transform(value: string, format: string): string[] { } `, declarations: [ { type: 'pipe', name: 'DatePipe', pipeName: 'date', }, ], }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [nullishCoalescingNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should not produce nullish coalescing warning when the left side is a nullable expression', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ func() ?? 'foo' }}`, }, source: ` export class TestCmp { func = (): string | null => null; } `, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [nullishCoalescingNotNullableFactory], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should respect configured diagnostic category', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `{{ var1 ?? 'foo' }}`, }, source: 'export class TestCmp { var1: string = "text"; }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [nullishCoalescingNotNullableFactory], { strictNullChecks: true, extendedDiagnostics: { checks: { nullishCoalescingNotNullable: DiagnosticCategoryLabel.Error, }, }, }, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Error); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.NULLISH_COALESCING_NOT_NULLABLE)); }); }); });
{ "end_byte": 13607, "start_byte": 8808, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/nullish_coalescing_not_nullable/nullish_coalescing_not_nullable_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/missing_control_flow_directive/BUILD.bazel_0_966
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = ["missing_control_flow_directive_spec.ts"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//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/testing", "//packages/compiler-cli/src/ngtsc/typecheck/extended", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/missing_control_flow_directive", "//packages/compiler-cli/src/ngtsc/typecheck/testing", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/core:npm_package", ], deps = [ ":test_lib", ], )
{ "end_byte": 966, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/missing_control_flow_directive/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/missing_control_flow_directive/missing_control_flow_directive_spec.ts_0_7148
/** * @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, ngErrorCode} from '../../../../../diagnostics'; import {absoluteFrom, getSourceFileOrError} from '../../../../../file_system'; import {runInEachFileSystem} from '../../../../../file_system/testing'; import {getSourceCodeForDiagnostic} from '../../../../../testing'; import {getClass, setup} from '../../../../testing'; import { factory as missingControlFlowDirectiveCheck, KNOWN_CONTROL_FLOW_DIRECTIVES, } from '../../../checks/missing_control_flow_directive'; import {ExtendedTemplateCheckerImpl} from '../../../src/extended_template_checker'; runInEachFileSystem(() => { describe('MissingControlFlowDirectiveCheck', () => { KNOWN_CONTROL_FLOW_DIRECTIVES.forEach((correspondingImport, directive) => { ['div', 'ng-template', 'ng-container', 'ng-content'].forEach((element) => { it( `should produce a warning when the '${directive}' directive is not imported ` + `(when used on the '${element}' element)`, () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<${element} *${directive}="exp"></${element}>`, }, declarations: [ { name: 'TestCmp', type: 'directive', selector: `[test-cmp]`, isStandalone: true, }, ], }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [missingControlFlowDirectiveCheck], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.MISSING_CONTROL_FLOW_DIRECTIVE)); expect(diags[0].messageText).toContain(`The \`*${directive}\` directive was used`); expect(diags[0].messageText).toContain( `neither the \`${correspondingImport.directive}\` directive nor the \`CommonModule\` was imported. `, ); expect(diags[0].messageText).toContain( `Use Angular's built-in control flow ${correspondingImport?.builtIn}`, ); expect(getSourceCodeForDiagnostic(diags[0])).toBe(directive); }, ); it( `should *not* produce a warning when the '${directive}' directive is not imported ` + `into a non-standalone component scope (when used on the '${element}' element)`, () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<${element} *${directive}="exp"></${element}>`, }, declarations: [ { name: 'TestCmp', type: 'directive', selector: `[test-cmp]`, isStandalone: false, }, ], }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [missingControlFlowDirectiveCheck], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); // No diagnostic messages are expected. expect(diags.length).toBe(0); }, ); it( `should *not* produce a warning when the '${directive}' directive is imported ` + `(when used on the '${element}' element)`, () => { const className = directive.charAt(0).toUpperCase() + directive.substr(1); const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<${element} *${directive}="exp"></${element}>`, }, source: ` export class TestCmp {} export class ${className} {} `, declarations: [ { type: 'directive', name: className, selector: `[${directive}]`, }, { name: 'TestCmp', type: 'directive', selector: `[test-cmp]`, isStandalone: true, }, ], }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [missingControlFlowDirectiveCheck], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); // No diagnostic messages are expected. expect(diags.length).toBe(0); }, ); }); }); it(`should *not* produce a warning for other missing structural directives`, () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div *foo="exp"></div>`, }, declarations: [ { name: 'TestCmp', type: 'directive', selector: `[test-cmp]`, isStandalone: true, }, ], }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [missingControlFlowDirectiveCheck], {strictNullChecks: true} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); // No diagnostic messages are expected. expect(diags.length).toBe(0); }); }); });
{ "end_byte": 7148, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/missing_control_flow_directive/missing_control_flow_directive_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/suffix_not_supported/BUILD.bazel_0_946
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = ["suffix_not_supported_spec.ts"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//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/testing", "//packages/compiler-cli/src/ngtsc/typecheck/extended", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/suffix_not_supported", "//packages/compiler-cli/src/ngtsc/typecheck/testing", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/core:npm_package", ], deps = [ ":test_lib", ], )
{ "end_byte": 946, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/suffix_not_supported/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/suffix_not_supported/suffix_not_supported_spec.ts_0_3840
/** * @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 {DiagnosticCategoryLabel} from '@angular/compiler-cli/src/ngtsc/core/api'; import ts from 'typescript'; import {ErrorCode, ExtendedTemplateDiagnosticName, ngErrorCode} from '../../../../../diagnostics'; import {absoluteFrom, getSourceFileOrError} from '../../../../../file_system'; import {runInEachFileSystem} from '../../../../../file_system/testing'; import {getSourceCodeForDiagnostic} from '../../../../../testing'; import {getClass, setup} from '../../../../testing'; import {factory as suffixNotSupportedFactory} from '../../../checks/suffix_not_supported'; import {ExtendedTemplateCheckerImpl} from '../../../src/extended_template_checker'; runInEachFileSystem(() => { describe('SuffixNotSupportedCheck', () => { it('binds the error code to its extended template diagnostic name', () => { expect(suffixNotSupportedFactory.code).toBe(ErrorCode.SUFFIX_NOT_SUPPORTED); expect(suffixNotSupportedFactory.name).toBe( ExtendedTemplateDiagnosticName.SUFFIX_NOT_SUPPORTED, ); }); it('should produce suffix not supported warning', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div [attr.width.px]="1"></div>`, }, source: 'export class TestCmp {}', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [suffixNotSupportedFactory], {}, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.SUFFIX_NOT_SUPPORTED)); expect(getSourceCodeForDiagnostic(diags[0])).toBe(`attr.width.px`); }); it('should not produce suffix not supported warning on a style binding', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div [style.width.px]="1"></div>`, }, source: 'export class TestCmp {}', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [suffixNotSupportedFactory], {}, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should not produce suffix not supported warning on an input', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div [myInput.px]="1"></div>`, }, source: 'export class TestCmp {}', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [suffixNotSupportedFactory], {}, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); }); });
{ "end_byte": 3840, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/suffix_not_supported/suffix_not_supported_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/missing_ngforof_let/missing_ngforof_let_spec.ts_0_4027
/** * @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, ExtendedTemplateDiagnosticName, ngErrorCode} from '../../../../../diagnostics'; import {absoluteFrom, getSourceFileOrError} from '../../../../../file_system'; import {runInEachFileSystem} from '../../../../../file_system/testing'; import {getSourceCodeForDiagnostic} from '../../../../../testing'; import {getClass, setup} from '../../../../testing'; import {factory as missingNgForOfLet} from '../../../checks/missing_ngforof_let/index'; import {ExtendedTemplateCheckerImpl} from '../../../src/extended_template_checker'; runInEachFileSystem(() => { describe('TemplateChecks', () => { it('binds the error code to its extended template diagnostic name', () => { expect(missingNgForOfLet.code).toBe(ErrorCode.MISSING_NGFOROF_LET); expect(missingNgForOfLet.name).toBe(ExtendedTemplateDiagnosticName.MISSING_NGFOROF_LET); }); it('should produce missing ngforof let warning', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': '<ul><li *ngFor="thing of items">{{thing["name"]}}</li></ul>', }, source: "export class TestCmp { items: [] = [{'name': 'diana'}, {'name': 'prince'}] }", }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [missingNgForOfLet], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.MISSING_NGFOROF_LET)); expect(getSourceCodeForDiagnostic(diags[0])).toBe('ngFor="thing '); }); it('should not produce missing ngforof let warning if written correctly', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': '<ul><li *ngFor="let item of items">{{item["name"]}};</li></ul>', }, source: "export class TestCmp { items: [] = [{'name': 'diana'}, {'name': 'prince'}] }", }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [missingNgForOfLet], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should not produce missing ngforof let warning if written correctly in longhand', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': '<ng-template ngFor let-item [ngForOf]="items">{{item["name"]}}</ng-template>', }, source: "export class TestCmp { items: [] = [{'name': 'diana'}, {'name': 'prince'}] }", }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [missingNgForOfLet], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); }); });
{ "end_byte": 4027, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/missing_ngforof_let/missing_ngforof_let_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/missing_ngforof_let/BUILD.bazel_0_944
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = ["missing_ngforof_let_spec.ts"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//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/testing", "//packages/compiler-cli/src/ngtsc/typecheck/extended", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/missing_ngforof_let", "//packages/compiler-cli/src/ngtsc/typecheck/testing", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/core:npm_package", ], deps = [ ":test_lib", ], )
{ "end_byte": 944, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/missing_ngforof_let/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/invalid_banana_in_box/BUILD.bazel_0_948
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = ["invalid_banana_in_box_spec.ts"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//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/testing", "//packages/compiler-cli/src/ngtsc/typecheck/extended", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/invalid_banana_in_box", "//packages/compiler-cli/src/ngtsc/typecheck/testing", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/core:npm_package", ], deps = [ ":test_lib", ], )
{ "end_byte": 948, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/invalid_banana_in_box/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/invalid_banana_in_box/invalid_banana_in_box_spec.ts_0_6555
/** * @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 {DiagnosticCategoryLabel} from '../../../../../core/api'; import {ErrorCode, ExtendedTemplateDiagnosticName, ngErrorCode} from '../../../../../diagnostics'; import {absoluteFrom, getSourceFileOrError} from '../../../../../file_system'; import {runInEachFileSystem} from '../../../../../file_system/testing'; import {getSourceCodeForDiagnostic} from '../../../../../testing'; import {getClass, setup} from '../../../../testing'; import {factory as invalidBananaInBoxFactory} from '../../../checks/invalid_banana_in_box/index'; import {ExtendedTemplateCheckerImpl} from '../../../src/extended_template_checker'; runInEachFileSystem(() => { describe('TemplateChecks', () => { it('binds the error code to its extended template diagnostic name', () => { expect(invalidBananaInBoxFactory.code).toBe(ErrorCode.INVALID_BANANA_IN_BOX); expect(invalidBananaInBoxFactory.name).toBe( ExtendedTemplateDiagnosticName.INVALID_BANANA_IN_BOX, ); }); it('should produce invalid banana in a box warning', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': '<div ([notARealThing])="var1"> </div>', }, source: 'export class TestCmp { var1: string = "text"; }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [invalidBananaInBoxFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INVALID_BANANA_IN_BOX)); expect(getSourceCodeForDiagnostic(diags[0])).toBe('([notARealThing])="var1"'); }); it('should not produce invalid banana in a box warning if written correctly', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': '<div [(notARealThing)]="var1"> </div>', }, source: 'export class TestCmp { var1: string = "text"; }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [invalidBananaInBoxFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should not produce invalid banana in a box warning with bracket in the middle of the name', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': '<div (not[AReal]Thing)="var1"> </div>', }, source: 'export class TestCmp { var1: string = "text"; }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [invalidBananaInBoxFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(0); }); it('should produce invalid banana in a box warnings for *ngIf and ng-template', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': `<div> <div *ngIf="false" ([notARealThing])="var1"> </div> <ng-template #elseBlock ([notARealThing2])="var1">Content to render when condition is false.</ng-template> </div>`, }, source: `export class TestCmp { var1: string = "text"; }`, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [invalidBananaInBoxFactory], {} /* options */, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(2); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INVALID_BANANA_IN_BOX)); expect(getSourceCodeForDiagnostic(diags[0])).toBe('([notARealThing])="var1"'); expect(diags[1].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[1].code).toBe(ngErrorCode(ErrorCode.INVALID_BANANA_IN_BOX)); expect(getSourceCodeForDiagnostic(diags[1])).toBe('([notARealThing2])="var1"'); }); it('should respect configured category', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': '<div ([notARealThing])="var1"> </div>', }, source: 'export class TestCmp { var1: string = "text"; }', }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [invalidBananaInBoxFactory], {extendedDiagnostics: {checks: {invalidBananaInBox: DiagnosticCategoryLabel.Error}}}, ); const diags = extendedTemplateChecker.getDiagnosticsForComponent(component); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Error); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INVALID_BANANA_IN_BOX)); }); }); });
{ "end_byte": 6555, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/invalid_banana_in_box/invalid_banana_in_box_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/unused_let_declaration/unused_let_declaration_spec.ts_0_3926
/** * @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, ExtendedTemplateDiagnosticName, ngErrorCode} from '../../../../../diagnostics'; import {absoluteFrom, getSourceFileOrError} from '../../../../../file_system'; import {runInEachFileSystem} from '../../../../../file_system/testing'; import {getSourceCodeForDiagnostic} from '../../../../../testing'; import {getClass, setup} from '../../../../testing'; import {factory as unusedLetDeclarationFactory} from '../../../checks/unused_let_declaration/index'; import {ExtendedTemplateCheckerImpl} from '../../../src/extended_template_checker'; runInEachFileSystem(() => { describe('UnusedLetDeclarationCheck', () => { function diagnose(template: string) { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'TestCmp': template, }, source: ` export class TestCmp { eventCallback(value: any) {} } `, }, ]); const sf = getSourceFileOrError(program, fileName); const component = getClass(sf, 'TestCmp'); const extendedTemplateChecker = new ExtendedTemplateCheckerImpl( templateTypeChecker, program.getTypeChecker(), [unusedLetDeclarationFactory], {}, ); return extendedTemplateChecker.getDiagnosticsForComponent(component); } it('binds the error code to its extended template diagnostic name', () => { expect(unusedLetDeclarationFactory.code).toBe(ErrorCode.UNUSED_LET_DECLARATION); expect(unusedLetDeclarationFactory.name).toBe( ExtendedTemplateDiagnosticName.UNUSED_LET_DECLARATION, ); }); it('should report a @let declaration that is not used', () => { const diags = diagnose(` @let used = 1; @let unused = 2; {{used}} `); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.UNUSED_LET_DECLARATION)); expect(getSourceCodeForDiagnostic(diags[0])).toBe('@let unused = 2'); }); it('should report a @let declaration that is not used', () => { const diags = diagnose(` @let foo = 1; @if (true) { @let foo = 2; {{foo}} } `); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.UNUSED_LET_DECLARATION)); expect(getSourceCodeForDiagnostic(diags[0])).toBe('@let foo = 1'); }); it('should not report a @let declaration that is only used in other @let declarations', () => { const diags = diagnose(` @let one = 1; @let two = 2; @let three = one + two; {{three}} `); expect(diags.length).toBe(0); }); it('should not report a @let declaration that is only used in an event listener', () => { const diags = diagnose(` @let foo = 1; <button (click)="eventCallback(foo + 1)">Click me</button> `); expect(diags.length).toBe(0); }); it('should not report a @let declaration that is only used in a structural directive', () => { const diags = diagnose(` @let foo = null; <div *ngIf="foo"></div> `); expect(diags.length).toBe(0); }); it('should not report a @let declaration that is only used in an ICU', () => { const diags = diagnose(` @let value = 1; <h1 i18n>{value, select, 1 {one} 2 {two} other {other}}</h1> `); expect(diags.length).toBe(0); }); }); });
{ "end_byte": 3926, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/unused_let_declaration/unused_let_declaration_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/unused_let_declaration/BUILD.bazel_0_950
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = ["unused_let_declaration_spec.ts"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//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/testing", "//packages/compiler-cli/src/ngtsc/typecheck/extended", "//packages/compiler-cli/src/ngtsc/typecheck/extended/checks/unused_let_declaration", "//packages/compiler-cli/src/ngtsc/typecheck/testing", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/core:npm_package", ], deps = [ ":test_lib", ], )
{ "end_byte": 950, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/test/checks/unused_let_declaration/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/skip_hydration_not_static/BUILD.bazel_0_527
load("//tools:defaults.bzl", "ts_library") ts_library( name = "skip_hydration_not_static", srcs = ["index.ts"], visibility = [ "//packages/compiler-cli/src/ngtsc:__subpackages__", "//packages/compiler-cli/test/ngtsc:__pkg__", ], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/extended/api", "@npm//typescript", ], )
{ "end_byte": 527, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/skip_hydration_not_static/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/skip_hydration_not_static/index.ts_0_2386
/** * @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 {AST, TmplAstBoundAttribute, TmplAstNode, TmplAstTextAttribute} from '@angular/compiler'; import ts from 'typescript'; import {ErrorCode, ExtendedTemplateDiagnosticName} from '../../../../diagnostics'; import {NgTemplateDiagnostic} from '../../../api'; import {TemplateCheckFactory, TemplateCheckWithVisitor, TemplateContext} from '../../api'; const NG_SKIP_HYDRATION_ATTR_NAME = 'ngSkipHydration'; /** * Ensures that the special attribute `ngSkipHydration` is not a binding and has no other * value than `"true"` or an empty value. */ class NgSkipHydrationSpec extends TemplateCheckWithVisitor<ErrorCode.SKIP_HYDRATION_NOT_STATIC> { override code = ErrorCode.SKIP_HYDRATION_NOT_STATIC as const; override visitNode( ctx: TemplateContext<ErrorCode.SKIP_HYDRATION_NOT_STATIC>, component: ts.ClassDeclaration, node: TmplAstNode | AST, ): NgTemplateDiagnostic<ErrorCode.SKIP_HYDRATION_NOT_STATIC>[] { /** Binding should always error */ if (node instanceof TmplAstBoundAttribute && node.name === NG_SKIP_HYDRATION_ATTR_NAME) { const errorString = `ngSkipHydration should not be used as a binding.`; const diagnostic = ctx.makeTemplateDiagnostic(node.sourceSpan, errorString); return [diagnostic]; } /** No value, empty string or `"true"` are the only valid values */ const acceptedValues = ['true', '' /* empty string */]; if ( node instanceof TmplAstTextAttribute && node.name === NG_SKIP_HYDRATION_ATTR_NAME && !acceptedValues.includes(node.value) && node.value !== undefined ) { const errorString = `ngSkipHydration only accepts "true" or "" as value or no value at all. For example 'ngSkipHydration="true"' or 'ngSkipHydration'`; const diagnostic = ctx.makeTemplateDiagnostic(node.sourceSpan, errorString); return [diagnostic]; } return []; } } export const factory: TemplateCheckFactory< ErrorCode.SKIP_HYDRATION_NOT_STATIC, ExtendedTemplateDiagnosticName.SKIP_HYDRATION_NOT_STATIC > = { code: ErrorCode.SKIP_HYDRATION_NOT_STATIC, name: ExtendedTemplateDiagnosticName.SKIP_HYDRATION_NOT_STATIC, create: () => new NgSkipHydrationSpec(), };
{ "end_byte": 2386, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/skip_hydration_not_static/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/optional_chain_not_nullable/BUILD.bazel_0_514
load("//tools:defaults.bzl", "ts_library") ts_library( name = "optional_chain_not_nullable", srcs = ["index.ts"], visibility = ["//packages/compiler-cli/src/ngtsc:__subpackages__"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/extended/api", "@npm//typescript", ], )
{ "end_byte": 514, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/optional_chain_not_nullable/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/optional_chain_not_nullable/index.ts_0_3574
/** * @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 {AST, SafeCall, SafeKeyedRead, SafePropertyRead, TmplAstNode} from '@angular/compiler'; import ts from 'typescript'; import {NgCompilerOptions} from '../../../../core/api'; import {ErrorCode, ExtendedTemplateDiagnosticName} from '../../../../diagnostics'; import {NgTemplateDiagnostic, SymbolKind} from '../../../api'; import {TemplateCheckFactory, TemplateCheckWithVisitor, TemplateContext} from '../../api'; /** * Ensures the left side of an optional chain operation is nullable. * Returns diagnostics for the cases where the operator is useless. * This check should only be use if `strictNullChecks` is enabled, * otherwise it would produce inaccurate results. */ class OptionalChainNotNullableCheck extends TemplateCheckWithVisitor<ErrorCode.OPTIONAL_CHAIN_NOT_NULLABLE> { override readonly canVisitStructuralAttributes = false; override code = ErrorCode.OPTIONAL_CHAIN_NOT_NULLABLE as const; override visitNode( ctx: TemplateContext<ErrorCode.OPTIONAL_CHAIN_NOT_NULLABLE>, component: ts.ClassDeclaration, node: TmplAstNode | AST, ): NgTemplateDiagnostic<ErrorCode.OPTIONAL_CHAIN_NOT_NULLABLE>[] { if ( !(node instanceof SafeCall) && !(node instanceof SafePropertyRead) && !(node instanceof SafeKeyedRead) ) return []; const symbolLeft = ctx.templateTypeChecker.getSymbolOfNode(node.receiver, component); if (symbolLeft === null || symbolLeft.kind !== SymbolKind.Expression) { return []; } const typeLeft = symbolLeft.tsType; if (typeLeft.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) { // We should not make assumptions about the any and unknown types; using a nullish coalescing // operator is acceptable for those. return []; } // If the left operand's type is different from its non-nullable self, then it must // contain a null or undefined so this nullish coalescing operator is useful. No diagnostic to // report. if (typeLeft.getNonNullableType() !== typeLeft) return []; const symbol = ctx.templateTypeChecker.getSymbolOfNode(node, component)!; if (symbol.kind !== SymbolKind.Expression) { return []; } const templateMapping = ctx.templateTypeChecker.getTemplateMappingAtTcbLocation( symbol.tcbLocation, ); if (templateMapping === null) { return []; } const advice = node instanceof SafePropertyRead ? `the '?.' operator can be replaced with the '.' operator` : `the '?.' operator can be safely removed`; const diagnostic = ctx.makeTemplateDiagnostic( templateMapping.span, `The left side of this optional chain operation does not include 'null' or 'undefined' in its type, therefore ${advice}.`, ); return [diagnostic]; } } export const factory: TemplateCheckFactory< ErrorCode.OPTIONAL_CHAIN_NOT_NULLABLE, ExtendedTemplateDiagnosticName.OPTIONAL_CHAIN_NOT_NULLABLE > = { code: ErrorCode.OPTIONAL_CHAIN_NOT_NULLABLE, name: ExtendedTemplateDiagnosticName.OPTIONAL_CHAIN_NOT_NULLABLE, create: (options: NgCompilerOptions) => { // Require `strictNullChecks` to be enabled. const strictNullChecks = options.strictNullChecks === undefined ? !!options.strict : !!options.strictNullChecks; if (!strictNullChecks) { return null; } return new OptionalChainNotNullableCheck(); }, };
{ "end_byte": 3574, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/optional_chain_not_nullable/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/interpolated_signal_not_invoked/BUILD.bazel_0_588
load("//tools:defaults.bzl", "ts_library") ts_library( name = "interpolated_signal_not_invoked", srcs = ["index.ts"], visibility = [ "//packages/compiler-cli/src/ngtsc:__subpackages__", "//packages/compiler-cli/test/ngtsc:__pkg__", ], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/extended/api", "@npm//typescript", ], )
{ "end_byte": 588, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/interpolated_signal_not_invoked/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/interpolated_signal_not_invoked/index.ts_0_5489
/** * @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 { AST, ASTWithSource, BindingType, Interpolation, PropertyRead, TmplAstBoundAttribute, TmplAstNode, } from '@angular/compiler'; import ts from 'typescript'; import {ErrorCode, ExtendedTemplateDiagnosticName} from '../../../../diagnostics'; import {NgTemplateDiagnostic, SymbolKind} from '../../../api'; import {isSignalReference} from '../../../src/symbol_util'; import {TemplateCheckFactory, TemplateCheckWithVisitor, TemplateContext} from '../../api'; /** Names of known signal instance properties. */ const SIGNAL_INSTANCE_PROPERTIES = new Set(['set', 'update', 'asReadonly']); /** * Names of known function instance properties. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function#instance_properties */ const FUNCTION_INSTANCE_PROPERTIES = new Set(['name', 'length', 'prototype']); /** * Ensures Signals are invoked when used in template interpolations. */ class InterpolatedSignalCheck extends TemplateCheckWithVisitor<ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED> { override code = ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED as const; override visitNode( ctx: TemplateContext<ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED>, component: ts.ClassDeclaration, node: TmplAstNode | AST, ): NgTemplateDiagnostic<ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED>[] { // interpolations like `{{ mySignal }}` if (node instanceof Interpolation) { return node.expressions .filter((item): item is PropertyRead => item instanceof PropertyRead) .flatMap((item) => buildDiagnosticForSignal(ctx, item, component)); } // bound properties like `[prop]="mySignal"` else if (node instanceof TmplAstBoundAttribute) { // we skip the check if the node is an input binding const usedDirectives = ctx.templateTypeChecker.getUsedDirectives(component); if ( usedDirectives !== null && usedDirectives.some((dir) => dir.inputs.getByBindingPropertyName(node.name) !== null) ) { return []; } // otherwise, we check if the node is if ( // a bound property like `[prop]="mySignal"` (node.type === BindingType.Property || // or a class binding like `[class.myClass]="mySignal"` node.type === BindingType.Class || // or a style binding like `[style.width]="mySignal"` node.type === BindingType.Style || // or an attribute binding like `[attr.role]="mySignal"` node.type === BindingType.Attribute || // or an animation binding like `[@myAnimation]="mySignal"` node.type === BindingType.Animation) && node.value instanceof ASTWithSource && node.value.ast instanceof PropertyRead ) { return buildDiagnosticForSignal(ctx, node.value.ast, component); } } return []; } } function isFunctionInstanceProperty(name: string): boolean { return FUNCTION_INSTANCE_PROPERTIES.has(name); } function isSignalInstanceProperty(name: string): boolean { return SIGNAL_INSTANCE_PROPERTIES.has(name); } function buildDiagnosticForSignal( ctx: TemplateContext<ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED>, node: PropertyRead, component: ts.ClassDeclaration, ): Array<NgTemplateDiagnostic<ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED>> { // check for `{{ mySignal }}` const symbol = ctx.templateTypeChecker.getSymbolOfNode(node, component); if (symbol !== null && symbol.kind === SymbolKind.Expression && isSignalReference(symbol)) { const templateMapping = ctx.templateTypeChecker.getTemplateMappingAtTcbLocation( symbol.tcbLocation, )!; const errorString = `${node.name} is a function and should be invoked: ${node.name}()`; const diagnostic = ctx.makeTemplateDiagnostic(templateMapping.span, errorString); return [diagnostic]; } // check for `{{ mySignal.name }}` or `{{ mySignal.length }}` or `{{ mySignal.prototype }}` // as these are the names of instance properties of Function, the compiler does _not_ throw an // error. // We also check for `{{ mySignal.set }}` or `{{ mySignal.update }}` or // `{{ mySignal.asReadonly }}` as these are the names of instance properties of Signal const symbolOfReceiver = ctx.templateTypeChecker.getSymbolOfNode(node.receiver, component); if ( (isFunctionInstanceProperty(node.name) || isSignalInstanceProperty(node.name)) && symbolOfReceiver !== null && symbolOfReceiver.kind === SymbolKind.Expression && isSignalReference(symbolOfReceiver) ) { const templateMapping = ctx.templateTypeChecker.getTemplateMappingAtTcbLocation( symbolOfReceiver.tcbLocation, )!; const errorString = `${ (node.receiver as PropertyRead).name } is a function and should be invoked: ${(node.receiver as PropertyRead).name}()`; const diagnostic = ctx.makeTemplateDiagnostic(templateMapping.span, errorString); return [diagnostic]; } return []; } export const factory: TemplateCheckFactory< ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED, ExtendedTemplateDiagnosticName.INTERPOLATED_SIGNAL_NOT_INVOKED > = { code: ErrorCode.INTERPOLATED_SIGNAL_NOT_INVOKED, name: ExtendedTemplateDiagnosticName.INTERPOLATED_SIGNAL_NOT_INVOKED, create: () => new InterpolatedSignalCheck(), };
{ "end_byte": 5489, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/interpolated_signal_not_invoked/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/uninvoked_function_in_event_binding/BUILD.bazel_0_537
load("//tools:defaults.bzl", "ts_library") ts_library( name = "uninvoked_function_in_event_binding", srcs = ["index.ts"], visibility = [ "//packages/compiler-cli/src/ngtsc:__subpackages__", "//packages/compiler-cli/test/ngtsc:__pkg__", ], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/extended/api", "@npm//typescript", ], )
{ "end_byte": 537, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/uninvoked_function_in_event_binding/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/uninvoked_function_in_event_binding/index.ts_0_4268
/** * @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 { AST, ASTWithSource, Call, Chain, Conditional, ParsedEventType, PropertyRead, SafeCall, SafePropertyRead, TmplAstBoundEvent, TmplAstNode, } from '@angular/compiler'; import ts from 'typescript'; import {ErrorCode, ExtendedTemplateDiagnosticName} from '../../../../diagnostics'; import {NgTemplateDiagnostic, SymbolKind} from '../../../api'; import {TemplateCheckFactory, TemplateCheckWithVisitor, TemplateContext} from '../../api'; /** * Ensures that function in event bindings are called. For example, `<button (click)="myFunc"></button>` * will not call `myFunc` when the button is clicked. Instead, it should be `<button (click)="myFunc()"></button>`. * This is likely not the intent of the developer. Instead, the intent is likely to call `myFunc`. */ class UninvokedFunctionInEventBindingSpec extends TemplateCheckWithVisitor<ErrorCode.UNINVOKED_FUNCTION_IN_EVENT_BINDING> { override code = ErrorCode.UNINVOKED_FUNCTION_IN_EVENT_BINDING as const; override visitNode( ctx: TemplateContext<ErrorCode.UNINVOKED_FUNCTION_IN_EVENT_BINDING>, component: ts.ClassDeclaration, node: TmplAstNode | AST, ): NgTemplateDiagnostic<ErrorCode.UNINVOKED_FUNCTION_IN_EVENT_BINDING>[] { // If the node is not a bound event, skip it. if (!(node instanceof TmplAstBoundEvent)) return []; // If the node is not a regular or animation event, skip it. if (node.type !== ParsedEventType.Regular && node.type !== ParsedEventType.Animation) return []; if (!(node.handler instanceof ASTWithSource)) return []; const sourceExpressionText = node.handler.source || ''; if (node.handler.ast instanceof Chain) { // (click)="increment; decrement" return node.handler.ast.expressions.flatMap((expression) => assertExpressionInvoked(expression, component, node, sourceExpressionText, ctx), ); } if (node.handler.ast instanceof Conditional) { // (click)="true ? increment : decrement" const {trueExp, falseExp} = node.handler.ast; return [trueExp, falseExp].flatMap((expression) => assertExpressionInvoked(expression, component, node, sourceExpressionText, ctx), ); } // (click)="increment" return assertExpressionInvoked(node.handler.ast, component, node, sourceExpressionText, ctx); } } /** * Asserts that the expression is invoked. * If the expression is a property read, and it has a call signature, a diagnostic is generated. */ function assertExpressionInvoked( expression: AST, component: ts.ClassDeclaration, node: TmplAstBoundEvent, expressionText: string, ctx: TemplateContext<ErrorCode.UNINVOKED_FUNCTION_IN_EVENT_BINDING>, ): NgTemplateDiagnostic<ErrorCode.UNINVOKED_FUNCTION_IN_EVENT_BINDING>[] { if (expression instanceof Call || expression instanceof SafeCall) { return []; // If the method is called, skip it. } if (!(expression instanceof PropertyRead) && !(expression instanceof SafePropertyRead)) { return []; // If the expression is not a property read, skip it. } const symbol = ctx.templateTypeChecker.getSymbolOfNode(expression, component); if (symbol !== null && symbol.kind === SymbolKind.Expression) { if (symbol.tsType.getCallSignatures()?.length > 0) { const fullExpressionText = generateStringFromExpression(expression, expressionText); const errorString = `Function in event binding should be invoked: ${fullExpressionText}()`; return [ctx.makeTemplateDiagnostic(node.sourceSpan, errorString)]; } } return []; } function generateStringFromExpression(expression: AST, source: string): string { return source.substring(expression.span.start, expression.span.end); } export const factory: TemplateCheckFactory< ErrorCode.UNINVOKED_FUNCTION_IN_EVENT_BINDING, ExtendedTemplateDiagnosticName.UNINVOKED_FUNCTION_IN_EVENT_BINDING > = { code: ErrorCode.UNINVOKED_FUNCTION_IN_EVENT_BINDING, name: ExtendedTemplateDiagnosticName.UNINVOKED_FUNCTION_IN_EVENT_BINDING, create: () => new UninvokedFunctionInEventBindingSpec(), };
{ "end_byte": 4268, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/uninvoked_function_in_event_binding/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/text_attribute_not_binding/BUILD.bazel_0_528
load("//tools:defaults.bzl", "ts_library") ts_library( name = "text_attribute_not_binding", srcs = ["index.ts"], visibility = [ "//packages/compiler-cli/src/ngtsc:__subpackages__", "//packages/compiler-cli/test/ngtsc:__pkg__", ], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/extended/api", "@npm//typescript", ], )
{ "end_byte": 528, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/text_attribute_not_binding/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/text_attribute_not_binding/index.ts_0_2819
/** * @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 {AST, TmplAstNode, TmplAstTextAttribute} from '@angular/compiler'; import ts from 'typescript'; import {ErrorCode, ExtendedTemplateDiagnosticName} from '../../../../diagnostics'; import {NgTemplateDiagnostic} from '../../../api'; import {TemplateCheckFactory, TemplateCheckWithVisitor, TemplateContext} from '../../api'; /** * Ensures that attributes that have the "special" angular binding prefix (attr., style., and * class.) are interpreted as bindings. For example, `<div attr.id="my-id"></div>` will not * interpret this as an `AttributeBinding` to `id` but rather just a `TmplAstTextAttribute`. This * is likely not the intent of the developer. Instead, the intent is likely to have the `id` be set * to 'my-id'. */ class TextAttributeNotBindingSpec extends TemplateCheckWithVisitor<ErrorCode.TEXT_ATTRIBUTE_NOT_BINDING> { override code = ErrorCode.TEXT_ATTRIBUTE_NOT_BINDING as const; override visitNode( ctx: TemplateContext<ErrorCode.TEXT_ATTRIBUTE_NOT_BINDING>, component: ts.ClassDeclaration, node: TmplAstNode | AST, ): NgTemplateDiagnostic<ErrorCode.TEXT_ATTRIBUTE_NOT_BINDING>[] { if (!(node instanceof TmplAstTextAttribute)) return []; const name = node.name; if (!name.startsWith('attr.') && !name.startsWith('style.') && !name.startsWith('class.')) { return []; } let errorString: string; if (name.startsWith('attr.')) { const staticAttr = name.replace('attr.', ''); errorString = `Static attributes should be written without the 'attr.' prefix.`; if (node.value) { errorString += ` For example, ${staticAttr}="${node.value}".`; } } else { const expectedKey = `[${name}]`; const expectedValue = // true/false are special cases because we don't want to convert them to strings but // rather maintain the logical true/false when bound. node.value === 'true' || node.value === 'false' ? node.value : `'${node.value}'`; errorString = 'Attribute, style, and class bindings should be enclosed with square braces.'; if (node.value) { errorString += ` For example, '${expectedKey}="${expectedValue}"'.`; } } const diagnostic = ctx.makeTemplateDiagnostic(node.sourceSpan, errorString); return [diagnostic]; } } export const factory: TemplateCheckFactory< ErrorCode.TEXT_ATTRIBUTE_NOT_BINDING, ExtendedTemplateDiagnosticName.TEXT_ATTRIBUTE_NOT_BINDING > = { code: ErrorCode.TEXT_ATTRIBUTE_NOT_BINDING, name: ExtendedTemplateDiagnosticName.TEXT_ATTRIBUTE_NOT_BINDING, create: () => new TextAttributeNotBindingSpec(), };
{ "end_byte": 2819, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/text_attribute_not_binding/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/nullish_coalescing_not_nullable/BUILD.bazel_0_518
load("//tools:defaults.bzl", "ts_library") ts_library( name = "nullish_coalescing_not_nullable", srcs = ["index.ts"], visibility = ["//packages/compiler-cli/src/ngtsc:__subpackages__"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/extended/api", "@npm//typescript", ], )
{ "end_byte": 518, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/nullish_coalescing_not_nullable/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/nullish_coalescing_not_nullable/index.ts_0_3353
/** * @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 {AST, Binary, TmplAstNode} from '@angular/compiler'; import ts from 'typescript'; import {NgCompilerOptions} from '../../../../core/api'; import {ErrorCode, ExtendedTemplateDiagnosticName} from '../../../../diagnostics'; import {NgTemplateDiagnostic, SymbolKind} from '../../../api'; import {TemplateCheckFactory, TemplateCheckWithVisitor, TemplateContext} from '../../api'; /** * Ensures the left side of a nullish coalescing operation is nullable. * Returns diagnostics for the cases where the operator is useless. * This check should only be use if `strictNullChecks` is enabled, * otherwise it would produce inaccurate results. */ class NullishCoalescingNotNullableCheck extends TemplateCheckWithVisitor<ErrorCode.NULLISH_COALESCING_NOT_NULLABLE> { override readonly canVisitStructuralAttributes = false; override code = ErrorCode.NULLISH_COALESCING_NOT_NULLABLE as const; override visitNode( ctx: TemplateContext<ErrorCode.NULLISH_COALESCING_NOT_NULLABLE>, component: ts.ClassDeclaration, node: TmplAstNode | AST, ): NgTemplateDiagnostic<ErrorCode.NULLISH_COALESCING_NOT_NULLABLE>[] { if (!(node instanceof Binary) || node.operation !== '??') return []; const symbolLeft = ctx.templateTypeChecker.getSymbolOfNode(node.left, component); if (symbolLeft === null || symbolLeft.kind !== SymbolKind.Expression) { return []; } const typeLeft = symbolLeft.tsType; if (typeLeft.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) { // We should not make assumptions about the any and unknown types; using a nullish coalescing // operator is acceptable for those. return []; } // If the left operand's type is different from its non-nullable self, then it must // contain a null or undefined so this nullish coalescing operator is useful. No diagnostic to // report. if (typeLeft.getNonNullableType() !== typeLeft) return []; const symbol = ctx.templateTypeChecker.getSymbolOfNode(node, component)!; if (symbol.kind !== SymbolKind.Expression) { return []; } const templateMapping = ctx.templateTypeChecker.getTemplateMappingAtTcbLocation( symbol.tcbLocation, ); if (templateMapping === null) { return []; } const diagnostic = ctx.makeTemplateDiagnostic( templateMapping.span, `The left side of this nullish coalescing operation does not include 'null' or 'undefined' in its type, therefore the '??' operator can be safely removed.`, ); return [diagnostic]; } } export const factory: TemplateCheckFactory< ErrorCode.NULLISH_COALESCING_NOT_NULLABLE, ExtendedTemplateDiagnosticName.NULLISH_COALESCING_NOT_NULLABLE > = { code: ErrorCode.NULLISH_COALESCING_NOT_NULLABLE, name: ExtendedTemplateDiagnosticName.NULLISH_COALESCING_NOT_NULLABLE, create: (options: NgCompilerOptions) => { // Require `strictNullChecks` to be enabled. const strictNullChecks = options.strictNullChecks === undefined ? !!options.strict : !!options.strictNullChecks; if (!strictNullChecks) { return null; } return new NullishCoalescingNotNullableCheck(); }, };
{ "end_byte": 3353, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/nullish_coalescing_not_nullable/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/missing_control_flow_directive/BUILD.bazel_0_517
load("//tools:defaults.bzl", "ts_library") ts_library( name = "missing_control_flow_directive", srcs = ["index.ts"], visibility = ["//packages/compiler-cli/src/ngtsc:__subpackages__"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/extended/api", "@npm//typescript", ], )
{ "end_byte": 517, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/missing_control_flow_directive/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/missing_control_flow_directive/index.ts_0_4199
/** * @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 {AST, TmplAstNode, TmplAstTemplate} from '@angular/compiler'; import ts from 'typescript'; import {NgCompilerOptions} from '../../../../core/api'; import {ErrorCode, ExtendedTemplateDiagnosticName} from '../../../../diagnostics'; import {NgTemplateDiagnostic} from '../../../api'; import {TemplateCheckFactory, TemplateCheckWithVisitor, TemplateContext} from '../../api'; /** * The list of known control flow directives present in the `CommonModule`, * and their corresponding imports. * * Note: there is no `ngSwitch` here since it's typically used as a regular * binding (e.g. `[ngSwitch]`), however the `ngSwitchCase` and `ngSwitchDefault` * are used as structural directives and a warning would be generated. Once the * `CommonModule` is included, the `ngSwitch` would also be covered. */ export const KNOWN_CONTROL_FLOW_DIRECTIVES = new Map([ ['ngIf', {directive: 'NgIf', builtIn: '@if'}], ['ngFor', {directive: 'NgFor', builtIn: '@for'}], ['ngSwitchCase', {directive: 'NgSwitchCase', builtIn: '@switch with @case'}], ['ngSwitchDefault', {directive: 'NgSwitchDefault', builtIn: '@switch with @default'}], ]); /** * Ensures that there are no known control flow directives (such as *ngIf and *ngFor) * used in a template of a *standalone* component without importing a `CommonModule`. Returns * diagnostics in case such a directive is detected. * * Note: this check only handles the cases when structural directive syntax is used (e.g. `*ngIf`). * Regular binding syntax (e.g. `[ngIf]`) is handled separately in type checker and treated as a * hard error instead of a warning. */ class MissingControlFlowDirectiveCheck extends TemplateCheckWithVisitor<ErrorCode.MISSING_CONTROL_FLOW_DIRECTIVE> { override code = ErrorCode.MISSING_CONTROL_FLOW_DIRECTIVE as const; override run( ctx: TemplateContext<ErrorCode.MISSING_CONTROL_FLOW_DIRECTIVE>, component: ts.ClassDeclaration, template: TmplAstNode[], ) { const componentMetadata = ctx.templateTypeChecker.getDirectiveMetadata(component); // Avoid running this check for non-standalone components. if (!componentMetadata || !componentMetadata.isStandalone) { return []; } return super.run(ctx, component, template); } override visitNode( ctx: TemplateContext<ErrorCode.MISSING_CONTROL_FLOW_DIRECTIVE>, component: ts.ClassDeclaration, node: TmplAstNode | AST, ): NgTemplateDiagnostic<ErrorCode.MISSING_CONTROL_FLOW_DIRECTIVE>[] { if (!(node instanceof TmplAstTemplate)) return []; const controlFlowAttr = node.templateAttrs.find((attr) => KNOWN_CONTROL_FLOW_DIRECTIVES.has(attr.name), ); if (!controlFlowAttr) return []; const symbol = ctx.templateTypeChecker.getSymbolOfNode(node, component); if (symbol === null || symbol.directives.length > 0) { return []; } const sourceSpan = controlFlowAttr.keySpan || controlFlowAttr.sourceSpan; const directiveAndBuiltIn = KNOWN_CONTROL_FLOW_DIRECTIVES.get(controlFlowAttr.name); const errorMessage = `The \`*${controlFlowAttr.name}\` directive was used in the template, ` + `but neither the \`${directiveAndBuiltIn?.directive}\` directive nor the \`CommonModule\` was imported. ` + `Use Angular's built-in control flow ${directiveAndBuiltIn?.builtIn} or ` + `make sure that either the \`${directiveAndBuiltIn?.directive}\` directive or the \`CommonModule\` ` + `is included in the \`@Component.imports\` array of this component.`; const diagnostic = ctx.makeTemplateDiagnostic(sourceSpan, errorMessage); return [diagnostic]; } } export const factory: TemplateCheckFactory< ErrorCode.MISSING_CONTROL_FLOW_DIRECTIVE, ExtendedTemplateDiagnosticName.MISSING_CONTROL_FLOW_DIRECTIVE > = { code: ErrorCode.MISSING_CONTROL_FLOW_DIRECTIVE, name: ExtendedTemplateDiagnosticName.MISSING_CONTROL_FLOW_DIRECTIVE, create: (options: NgCompilerOptions) => { return new MissingControlFlowDirectiveCheck(); }, };
{ "end_byte": 4199, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/missing_control_flow_directive/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/suffix_not_supported/BUILD.bazel_0_507
load("//tools:defaults.bzl", "ts_library") ts_library( name = "suffix_not_supported", srcs = ["index.ts"], visibility = ["//packages/compiler-cli/src/ngtsc:__subpackages__"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/extended/api", "@npm//typescript", ], )
{ "end_byte": 507, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/suffix_not_supported/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/suffix_not_supported/index.ts_0_1876
/** * @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 {AST, TmplAstBoundAttribute, TmplAstNode} from '@angular/compiler'; import ts from 'typescript'; import {ErrorCode, ExtendedTemplateDiagnosticName} from '../../../../diagnostics'; import {NgTemplateDiagnostic} from '../../../api'; import {TemplateCheckFactory, TemplateCheckWithVisitor, TemplateContext} from '../../api'; const STYLE_SUFFIXES = ['px', '%', 'em']; /** * A check which detects when the `.px`, `.%`, and `.em` suffixes are used with an attribute * binding. These suffixes are only available for style bindings. */ class SuffixNotSupportedCheck extends TemplateCheckWithVisitor<ErrorCode.SUFFIX_NOT_SUPPORTED> { override code = ErrorCode.SUFFIX_NOT_SUPPORTED as const; override visitNode( ctx: TemplateContext<ErrorCode.SUFFIX_NOT_SUPPORTED>, component: ts.ClassDeclaration, node: TmplAstNode | AST, ): NgTemplateDiagnostic<ErrorCode.SUFFIX_NOT_SUPPORTED>[] { if (!(node instanceof TmplAstBoundAttribute)) return []; if ( !node.keySpan.toString().startsWith('attr.') || !STYLE_SUFFIXES.some((suffix) => node.name.endsWith(`.${suffix}`)) ) { return []; } const diagnostic = ctx.makeTemplateDiagnostic( node.keySpan, `The ${STYLE_SUFFIXES.map((suffix) => `'.${suffix}'`).join( ', ', )} suffixes are only supported on style bindings.`, ); return [diagnostic]; } } export const factory: TemplateCheckFactory< ErrorCode.SUFFIX_NOT_SUPPORTED, ExtendedTemplateDiagnosticName.SUFFIX_NOT_SUPPORTED > = { code: ErrorCode.SUFFIX_NOT_SUPPORTED, name: ExtendedTemplateDiagnosticName.SUFFIX_NOT_SUPPORTED, create: () => new SuffixNotSupportedCheck(), };
{ "end_byte": 1876, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/suffix_not_supported/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/missing_ngforof_let/BUILD.bazel_0_521
load("//tools:defaults.bzl", "ts_library") ts_library( name = "missing_ngforof_let", srcs = ["index.ts"], visibility = [ "//packages/compiler-cli/src/ngtsc:__subpackages__", "//packages/compiler-cli/test/ngtsc:__pkg__", ], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/extended/api", "@npm//typescript", ], )
{ "end_byte": 521, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/missing_ngforof_let/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/missing_ngforof_let/index.ts_0_1893
/** * @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 {AST, TmplAstNode, TmplAstTemplate} from '@angular/compiler'; import ts from 'typescript'; import {ErrorCode, ExtendedTemplateDiagnosticName} from '../../../../diagnostics'; import {NgTemplateDiagnostic} from '../../../api'; import {TemplateCheckFactory, TemplateCheckWithVisitor, TemplateContext} from '../../api'; /** * Ensures a user doesn't forget to omit `let` when using ngfor. * Will return diagnostic information when `let` is missing. */ class MissingNgForOfLetCheck extends TemplateCheckWithVisitor<ErrorCode.MISSING_NGFOROF_LET> { override code = ErrorCode.MISSING_NGFOROF_LET as const; override visitNode( ctx: TemplateContext<ErrorCode.MISSING_NGFOROF_LET>, component: ts.ClassDeclaration, node: TmplAstNode | AST, ): NgTemplateDiagnostic<ErrorCode.MISSING_NGFOROF_LET>[] { const isTemplate = node instanceof TmplAstTemplate; if (!(node instanceof TmplAstTemplate)) { return []; } if (node.templateAttrs.length === 0) { return []; } const attr = node.templateAttrs.find((x) => x.name === 'ngFor'); if (attr === undefined) { return []; } if (node.variables.length > 0) { return []; } const errorString = 'Your ngFor is missing a value. Did you forget to add the `let` keyword?'; const diagnostic = ctx.makeTemplateDiagnostic(attr.sourceSpan, errorString); return [diagnostic]; } } export const factory: TemplateCheckFactory< ErrorCode.MISSING_NGFOROF_LET, ExtendedTemplateDiagnosticName.MISSING_NGFOROF_LET > = { code: ErrorCode.MISSING_NGFOROF_LET, name: ExtendedTemplateDiagnosticName.MISSING_NGFOROF_LET, create: () => new MissingNgForOfLetCheck(), };
{ "end_byte": 1893, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/missing_ngforof_let/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/invalid_banana_in_box/BUILD.bazel_0_523
load("//tools:defaults.bzl", "ts_library") ts_library( name = "invalid_banana_in_box", srcs = ["index.ts"], visibility = [ "//packages/compiler-cli/src/ngtsc:__subpackages__", "//packages/compiler-cli/test/ngtsc:__pkg__", ], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/extended/api", "@npm//typescript", ], )
{ "end_byte": 523, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/invalid_banana_in_box/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/invalid_banana_in_box/index.ts_0_1963
/** * @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 {AST, TmplAstBoundEvent, TmplAstNode} from '@angular/compiler'; import ts from 'typescript'; import {ErrorCode, ExtendedTemplateDiagnosticName} from '../../../../diagnostics'; import {NgTemplateDiagnostic} from '../../../api'; import {TemplateCheckFactory, TemplateCheckWithVisitor, TemplateContext} from '../../api'; /** * Ensures the two-way binding syntax is correct. * Parentheses should be inside the brackets "[()]". * Will return diagnostic information when "([])" is found. */ class InvalidBananaInBoxCheck extends TemplateCheckWithVisitor<ErrorCode.INVALID_BANANA_IN_BOX> { override code = ErrorCode.INVALID_BANANA_IN_BOX as const; override visitNode( ctx: TemplateContext<ErrorCode.INVALID_BANANA_IN_BOX>, component: ts.ClassDeclaration, node: TmplAstNode | AST, ): NgTemplateDiagnostic<ErrorCode.INVALID_BANANA_IN_BOX>[] { if (!(node instanceof TmplAstBoundEvent)) return []; const name = node.name; if (!name.startsWith('[') || !name.endsWith(']')) return []; const boundSyntax = node.sourceSpan.toString(); const expectedBoundSyntax = boundSyntax.replace(`(${name})`, `[(${name.slice(1, -1)})]`); const diagnostic = ctx.makeTemplateDiagnostic( node.sourceSpan, `In the two-way binding syntax the parentheses should be inside the brackets, ex. '${expectedBoundSyntax}'. Find more at https://angular.dev/guide/templates/two-way-binding`, ); return [diagnostic]; } } export const factory: TemplateCheckFactory< ErrorCode.INVALID_BANANA_IN_BOX, ExtendedTemplateDiagnosticName.INVALID_BANANA_IN_BOX > = { code: ErrorCode.INVALID_BANANA_IN_BOX, name: ExtendedTemplateDiagnosticName.INVALID_BANANA_IN_BOX, create: () => new InvalidBananaInBoxCheck(), };
{ "end_byte": 1963, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/invalid_banana_in_box/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/unused_let_declaration/BUILD.bazel_0_524
load("//tools:defaults.bzl", "ts_library") ts_library( name = "unused_let_declaration", srcs = ["index.ts"], visibility = [ "//packages/compiler-cli/src/ngtsc:__subpackages__", "//packages/compiler-cli/test/ngtsc:__pkg__", ], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/extended/api", "@npm//typescript", ], )
{ "end_byte": 524, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/unused_let_declaration/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/unused_let_declaration/index.ts_0_3006
/** * @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 {AST, ASTWithSource, TmplAstLetDeclaration, TmplAstNode} from '@angular/compiler'; import ts from 'typescript'; import {ErrorCode, ExtendedTemplateDiagnosticName} from '../../../../diagnostics'; import {NgTemplateDiagnostic} from '../../../api'; import {TemplateCheckFactory, TemplateCheckWithVisitor, TemplateContext} from '../../api'; interface ClassAnalysis { allLetDeclarations: Set<TmplAstLetDeclaration>; usedLetDeclarations: Set<TmplAstLetDeclaration>; } /** * Ensures that all `@let` declarations in a template are used. */ class UnusedLetDeclarationCheck extends TemplateCheckWithVisitor<ErrorCode.UNUSED_LET_DECLARATION> { override code = ErrorCode.UNUSED_LET_DECLARATION as const; private analysis = new Map<ts.ClassDeclaration, ClassAnalysis>(); override run( ctx: TemplateContext<ErrorCode.UNUSED_LET_DECLARATION>, component: ts.ClassDeclaration, template: TmplAstNode[], ): NgTemplateDiagnostic<ErrorCode.UNUSED_LET_DECLARATION>[] { super.run(ctx, component, template); const diagnostics: NgTemplateDiagnostic<ErrorCode.UNUSED_LET_DECLARATION>[] = []; const {allLetDeclarations, usedLetDeclarations} = this.getAnalysis(component); for (const decl of allLetDeclarations) { if (!usedLetDeclarations.has(decl)) { diagnostics.push( ctx.makeTemplateDiagnostic( decl.sourceSpan, `@let ${decl.name} is declared but its value is never read.`, ), ); } } this.analysis.clear(); return diagnostics; } override visitNode( ctx: TemplateContext<ErrorCode.UNUSED_LET_DECLARATION>, component: ts.ClassDeclaration, node: TmplAstNode | AST, ): NgTemplateDiagnostic<ErrorCode.UNUSED_LET_DECLARATION>[] { if (node instanceof TmplAstLetDeclaration) { this.getAnalysis(component).allLetDeclarations.add(node); } else if (node instanceof AST) { const unwrappedNode = node instanceof ASTWithSource ? node.ast : node; const target = ctx.templateTypeChecker.getExpressionTarget(unwrappedNode, component); if (target !== null && target instanceof TmplAstLetDeclaration) { this.getAnalysis(component).usedLetDeclarations.add(target); } } return []; } private getAnalysis(node: ts.ClassDeclaration): ClassAnalysis { if (!this.analysis.has(node)) { this.analysis.set(node, {allLetDeclarations: new Set(), usedLetDeclarations: new Set()}); } return this.analysis.get(node)!; } } export const factory: TemplateCheckFactory< ErrorCode.UNUSED_LET_DECLARATION, ExtendedTemplateDiagnosticName.UNUSED_LET_DECLARATION > = { code: ErrorCode.UNUSED_LET_DECLARATION, name: ExtendedTemplateDiagnosticName.UNUSED_LET_DECLARATION, create: () => new UnusedLetDeclarationCheck(), };
{ "end_byte": 3006, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/checks/unused_let_declaration/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/api/extended_template_checker.ts_0_600
/** * @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 {TemplateDiagnostic} from '../../api'; /** * Interface to generate extended template diagnostics from the component templates. */ export interface ExtendedTemplateChecker { /** * Run `TemplateCheck`s for a component and return the generated `ts.Diagnostic`s. */ getDiagnosticsForComponent(component: ts.ClassDeclaration): TemplateDiagnostic[]; }
{ "end_byte": 600, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/api/extended_template_checker.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/api/api.ts_0_4687
/** * @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 { AST, ASTWithSource, ParseSourceSpan, RecursiveAstVisitor, TmplAstBoundAttribute, TmplAstBoundDeferredTrigger, TmplAstBoundEvent, TmplAstBoundText, TmplAstContent, TmplAstDeferredBlock, TmplAstDeferredBlockError, TmplAstDeferredBlockLoading, TmplAstDeferredBlockPlaceholder, TmplAstDeferredTrigger, TmplAstElement, TmplAstForLoopBlock, TmplAstForLoopBlockEmpty, TmplAstIcu, TmplAstIfBlock, TmplAstIfBlockBranch, TmplAstLetDeclaration, TmplAstNode, TmplAstRecursiveVisitor, TmplAstReference, TmplAstSwitchBlock, TmplAstSwitchBlockCase, TmplAstTemplate, TmplAstText, TmplAstTextAttribute, TmplAstUnknownBlock, TmplAstVariable, } from '@angular/compiler'; import ts from 'typescript'; import {NgCompilerOptions} from '../../../core/api'; import {ErrorCode, ExtendedTemplateDiagnosticName} from '../../../diagnostics'; import {NgTemplateDiagnostic, TemplateTypeChecker} from '../../api'; /** * A Template Check receives information about the template it's checking and returns * information about the diagnostics to be generated. */ export interface TemplateCheck<Code extends ErrorCode> { /** Unique template check code, used for configuration and searching the error. */ code: Code; /** Runs check and returns information about the diagnostics to be generated. */ run( ctx: TemplateContext<Code>, component: ts.ClassDeclaration, template: TmplAstNode[], ): NgTemplateDiagnostic<Code>[]; } /** * The TemplateContext provided to a Template Check to get diagnostic information. */ export interface TemplateContext<Code extends ErrorCode> { /** Interface that provides information about template nodes. */ templateTypeChecker: TemplateTypeChecker; /** * TypeScript interface that provides type information about symbols that appear * in the template (it is not to query types outside the Angular component). */ typeChecker: ts.TypeChecker; /** * Creates a template diagnostic with the given information for the template being processed and * using the diagnostic category configured for the extended template diagnostic. */ makeTemplateDiagnostic( sourceSpan: ParseSourceSpan, message: string, relatedInformation?: { text: string; start: number; end: number; sourceFile: ts.SourceFile; }[], ): NgTemplateDiagnostic<Code>; } /** * A factory which creates a template check for a particular code and name. This binds the two * together and associates them with a specific `TemplateCheck`. */ export interface TemplateCheckFactory< Code extends ErrorCode, Name extends ExtendedTemplateDiagnosticName, > { code: Code; name: Name; create(options: NgCompilerOptions): TemplateCheck<Code> | null; } /** * This abstract class provides a base implementation for the run method. */ export abstract class TemplateCheckWithVisitor<Code extends ErrorCode> implements TemplateCheck<Code> { /** * When extended diagnostics were first introduced, the visitor wasn't implemented correctly * which meant that it wasn't visiting the `templateAttrs` of structural directives (e.g. * the expression of `*ngIf`). Fixing the issue causes a lot of internal breakages and will likely * need to be done in a major version to avoid external breakages. This flag is used to opt out * pre-existing diagnostics from the correct behavior until the breakages have been fixed while * ensuring that newly-written diagnostics are correct from the beginning. * TODO(crisbeto): remove this flag and fix the internal brekages. */ readonly canVisitStructuralAttributes: boolean = true; abstract code: Code; /** * Base implementation for run function, visits all nodes in template and calls * `visitNode()` for each one. */ run( ctx: TemplateContext<Code>, component: ts.ClassDeclaration, template: TmplAstNode[], ): NgTemplateDiagnostic<Code>[] { const visitor = new TemplateVisitor<Code>(ctx, component, this); return visitor.getDiagnostics(template); } /** * Visit a TmplAstNode or AST node of the template. Authors should override this * method to implement the check and return diagnostics. */ abstract visitNode( ctx: TemplateContext<Code>, component: ts.ClassDeclaration, node: TmplAstNode | AST, ): NgTemplateDiagnostic<Code>[]; } /** * Visits all nodes in a template (TmplAstNode and AST) and calls `visitNode` for each one. */
{ "end_byte": 4687, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/api/api.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/api/api.ts_4688_9367
class TemplateVisitor<Code extends ErrorCode> extends RecursiveAstVisitor implements TmplAstRecursiveVisitor { diagnostics: NgTemplateDiagnostic<Code>[] = []; constructor( private readonly ctx: TemplateContext<Code>, private readonly component: ts.ClassDeclaration, private readonly check: TemplateCheckWithVisitor<Code>, ) { super(); } override visit(node: AST | TmplAstNode, context?: any) { this.diagnostics.push(...this.check.visitNode(this.ctx, this.component, node)); node.visit(this); } visitAllNodes(nodes: TmplAstNode[]) { for (const node of nodes) { this.visit(node); } } visitAst(ast: AST) { if (ast instanceof ASTWithSource) { ast = ast.ast; } this.visit(ast); } visitElement(element: TmplAstElement) { this.visitAllNodes(element.attributes); this.visitAllNodes(element.inputs); this.visitAllNodes(element.outputs); this.visitAllNodes(element.references); this.visitAllNodes(element.children); } visitTemplate(template: TmplAstTemplate) { const isInlineTemplate = template.tagName === 'ng-template'; this.visitAllNodes(template.attributes); if (isInlineTemplate) { // Only visit input/outputs if this isn't an inline template node generated for a structural // directive (like `<div *ngIf></div>`). These nodes would be visited when the underlying // element of an inline template node is processed. this.visitAllNodes(template.inputs); this.visitAllNodes(template.outputs); } // TODO(crisbeto): remove this condition when deleting `canVisitStructuralAttributes`. if (this.check.canVisitStructuralAttributes || isInlineTemplate) { // `templateAttrs` aren't transferred over to the inner element so we always have to visit them. this.visitAllNodes(template.templateAttrs); } this.visitAllNodes(template.variables); this.visitAllNodes(template.references); this.visitAllNodes(template.children); } visitContent(content: TmplAstContent): void { this.visitAllNodes(content.children); } visitVariable(variable: TmplAstVariable): void {} visitReference(reference: TmplAstReference): void {} visitTextAttribute(attribute: TmplAstTextAttribute): void {} visitUnknownBlock(block: TmplAstUnknownBlock): void {} visitBoundAttribute(attribute: TmplAstBoundAttribute): void { this.visitAst(attribute.value); } visitBoundEvent(attribute: TmplAstBoundEvent): void { this.visitAst(attribute.handler); } visitText(text: TmplAstText): void {} visitBoundText(text: TmplAstBoundText): void { this.visitAst(text.value); } visitIcu(icu: TmplAstIcu): void { Object.keys(icu.vars).forEach((key) => this.visit(icu.vars[key])); Object.keys(icu.placeholders).forEach((key) => this.visit(icu.placeholders[key])); } visitDeferredBlock(deferred: TmplAstDeferredBlock): void { deferred.visitAll(this); } visitDeferredTrigger(trigger: TmplAstDeferredTrigger): void { if (trigger instanceof TmplAstBoundDeferredTrigger) { this.visitAst(trigger.value); } } visitDeferredBlockPlaceholder(block: TmplAstDeferredBlockPlaceholder): void { this.visitAllNodes(block.children); } visitDeferredBlockError(block: TmplAstDeferredBlockError): void { this.visitAllNodes(block.children); } visitDeferredBlockLoading(block: TmplAstDeferredBlockLoading): void { this.visitAllNodes(block.children); } visitSwitchBlock(block: TmplAstSwitchBlock): void { this.visitAst(block.expression); this.visitAllNodes(block.cases); } visitSwitchBlockCase(block: TmplAstSwitchBlockCase): void { block.expression && this.visitAst(block.expression); this.visitAllNodes(block.children); } visitForLoopBlock(block: TmplAstForLoopBlock): void { block.item.visit(this); this.visitAllNodes(block.contextVariables); this.visitAst(block.expression); this.visitAllNodes(block.children); block.empty?.visit(this); } visitForLoopBlockEmpty(block: TmplAstForLoopBlockEmpty): void { this.visitAllNodes(block.children); } visitIfBlock(block: TmplAstIfBlock): void { this.visitAllNodes(block.branches); } visitIfBlockBranch(block: TmplAstIfBlockBranch): void { block.expression && this.visitAst(block.expression); block.expressionAlias?.visit(this); this.visitAllNodes(block.children); } visitLetDeclaration(decl: TmplAstLetDeclaration): void { this.visitAst(decl.value); } getDiagnostics(template: TmplAstNode[]): NgTemplateDiagnostic<Code>[] { this.diagnostics = []; this.visitAllNodes(template); return this.diagnostics; } }
{ "end_byte": 9367, "start_byte": 4688, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/api/api.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/api/BUILD.bazel_0_442
load("//tools:defaults.bzl", "ts_library") ts_library( name = "api", srcs = glob( ["**/*.ts"], ), visibility = ["//packages/compiler-cli/src/ngtsc:__subpackages__"], deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/typecheck/api", "@npm//typescript", ], )
{ "end_byte": 442, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/api/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/api/index.ts_0_272
/** * @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 './api'; export * from './extended_template_checker';
{ "end_byte": 272, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/api/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/extended/src/extended_template_checker.ts_0_4302
/** * @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 {ParseSourceSpan} from '@angular/compiler'; import ts from 'typescript'; import {DiagnosticCategoryLabel, NgCompilerOptions} from '../../../core/api'; import {ErrorCode, ExtendedTemplateDiagnosticName} from '../../../diagnostics'; import {NgTemplateDiagnostic, TemplateDiagnostic, TemplateTypeChecker} from '../../api'; import { ExtendedTemplateChecker, TemplateCheck, TemplateCheckFactory, TemplateContext, } from '../api'; export class ExtendedTemplateCheckerImpl implements ExtendedTemplateChecker { private readonly partialCtx: Omit<TemplateContext<ErrorCode>, 'makeTemplateDiagnostic'>; private readonly templateChecks: Map<TemplateCheck<ErrorCode>, ts.DiagnosticCategory>; constructor( templateTypeChecker: TemplateTypeChecker, typeChecker: ts.TypeChecker, templateCheckFactories: readonly TemplateCheckFactory< ErrorCode, ExtendedTemplateDiagnosticName >[], options: NgCompilerOptions, ) { this.partialCtx = {templateTypeChecker, typeChecker}; this.templateChecks = new Map<TemplateCheck<ErrorCode>, ts.DiagnosticCategory>(); for (const factory of templateCheckFactories) { // Read the diagnostic category from compiler options. const category = diagnosticLabelToCategory( options?.extendedDiagnostics?.checks?.[factory.name] ?? options?.extendedDiagnostics?.defaultCategory ?? DiagnosticCategoryLabel.Warning, ); // Skip the diagnostic if suppressed via compiler options. if (category === null) { continue; } // Try to create the check. const check = factory.create(options); // Skip the diagnostic if it was disabled due to unsupported options. For example, this can // happen if the check requires `strictNullChecks: true` but that flag is disabled in compiler // options. if (check === null) { continue; } // Use the check. this.templateChecks.set(check, category); } } getDiagnosticsForComponent(component: ts.ClassDeclaration): TemplateDiagnostic[] { const template = this.partialCtx.templateTypeChecker.getTemplate(component); // Skip checks if component has no template. This can happen if the user writes a // `@Component()` but doesn't add the template, could happen in the language service // when users are in the middle of typing code. if (template === null) { return []; } const diagnostics: TemplateDiagnostic[] = []; for (const [check, category] of this.templateChecks.entries()) { const ctx: TemplateContext<ErrorCode> = { ...this.partialCtx, // Wrap `templateTypeChecker.makeTemplateDiagnostic()` to implicitly provide all the known // options. makeTemplateDiagnostic: ( span: ParseSourceSpan, message: string, relatedInformation?: { text: string; start: number; end: number; sourceFile: ts.SourceFile; }[], ): NgTemplateDiagnostic<ErrorCode> => { return this.partialCtx.templateTypeChecker.makeTemplateDiagnostic( component, span, category, check.code, message, relatedInformation, ); }, }; diagnostics.push(...check.run(ctx, component, template)); } return diagnostics; } } /** * Converts a `DiagnosticCategoryLabel` to its equivalent `ts.DiagnosticCategory` or `null` if * the label is `DiagnosticCategoryLabel.Suppress`. */ function diagnosticLabelToCategory(label: DiagnosticCategoryLabel): ts.DiagnosticCategory | null { switch (label) { case DiagnosticCategoryLabel.Warning: return ts.DiagnosticCategory.Warning; case DiagnosticCategoryLabel.Error: return ts.DiagnosticCategory.Error; case DiagnosticCategoryLabel.Suppress: return null; default: return assertNever(label); } } function assertNever(value: never): never { throw new Error(`Unexpected call to 'assertNever()' with value:\n${value}`); }
{ "end_byte": 4302, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/extended/src/extended_template_checker.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/api/checker.ts_0_1687
/** * @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 { AST, LiteralPrimitive, ParseSourceSpan, PropertyRead, SafePropertyRead, TemplateEntity, TmplAstElement, TmplAstNode, TmplAstTemplate, TmplAstTextAttribute, } from '@angular/compiler'; import ts from 'typescript'; import {AbsoluteFsPath} from '../../../../src/ngtsc/file_system'; import {ErrorCode} from '../../diagnostics'; import {Reference} from '../../imports'; import {NgModuleMeta, PipeMeta} from '../../metadata'; import {ClassDeclaration} from '../../reflection'; import {FullTemplateMapping, NgTemplateDiagnostic, TypeCheckableDirectiveMeta} from './api'; import {GlobalCompletion} from './completion'; import {PotentialDirective, PotentialImport, PotentialImportMode, PotentialPipe} from './scope'; import {ElementSymbol, Symbol, TcbLocation, TemplateSymbol} from './symbols'; /** * Interface to the Angular Template Type Checker to extract diagnostics and intelligence from the * compiler's understanding of component templates. * * This interface is analogous to TypeScript's own `ts.TypeChecker` API. * * In general, this interface supports two kinds of operations: * - updating Type Check Blocks (TCB)s that capture the template in the form of TypeScript code * - querying information about available TCBs, including diagnostics * * Once a TCB is available, information about it can be queried. If no TCB is available to answer a * query, depending on the method either `null` will be returned or an error will be thrown. */
{ "end_byte": 1687, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/api/checker.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/api/checker.ts_1688_9914
export interface TemplateTypeChecker { /** * Retrieve the template in use for the given component. */ getTemplate(component: ts.ClassDeclaration, optimizeFor?: OptimizeFor): TmplAstNode[] | null; /** * Get all `ts.Diagnostic`s currently available for the given `ts.SourceFile`. * * This method will fail (throw) if there are components within the `ts.SourceFile` that do not * have TCBs available. * * Generating a template type-checking program is expensive, and in some workflows (e.g. checking * an entire program before emit), it should ideally only be done once. The `optimizeFor` flag * allows the caller to hint to `getDiagnosticsForFile` (which internally will create a template * type-checking program if needed) whether the caller is interested in just the results of the * single file, or whether they plan to query about other files in the program. Based on this * flag, `getDiagnosticsForFile` will determine how much of the user's program to prepare for * checking as part of the template type-checking program it creates. */ getDiagnosticsForFile(sf: ts.SourceFile, optimizeFor: OptimizeFor): ts.Diagnostic[]; /** * Given a `shim` and position within the file, returns information for mapping back to a template * location. */ getTemplateMappingAtTcbLocation(tcbLocation: TcbLocation): FullTemplateMapping | null; /** * Get all `ts.Diagnostic`s currently available that pertain to the given component. * * This method always runs in `OptimizeFor.SingleFile` mode. */ getDiagnosticsForComponent(component: ts.ClassDeclaration): ts.Diagnostic[]; /** * Ensures shims for the whole program are generated. This type of operation would be required by * operations like "find references" and "refactor/rename" because references may appear in type * check blocks generated from templates anywhere in the program. */ generateAllTypeCheckBlocks(): void; /** * Returns `true` if the given file is in the record of known shims generated by the compiler, * `false` if we cannot find the file in the shim records. */ isTrackedTypeCheckFile(filePath: AbsoluteFsPath): boolean; /** * Retrieve the top-level node representing the TCB for the given component. * * This can return `null` if there is no TCB available for the component. * * This method always runs in `OptimizeFor.SingleFile` mode. */ getTypeCheckBlock(component: ts.ClassDeclaration): ts.Node | null; /** * Retrieves a `Symbol` for the node in a component's template. * * This method can return `null` if a valid `Symbol` cannot be determined for the node. * * @see Symbol */ getSymbolOfNode(node: TmplAstElement, component: ts.ClassDeclaration): ElementSymbol | null; getSymbolOfNode(node: TmplAstTemplate, component: ts.ClassDeclaration): TemplateSymbol | null; getSymbolOfNode(node: AST | TmplAstNode, component: ts.ClassDeclaration): Symbol | null; /** * Get "global" `Completion`s in the given context. * * Global completions are completions in the global context, as opposed to completions within an * existing expression. For example, completing inside a new interpolation expression (`{{|}}`) or * inside a new property binding `[input]="|" should retrieve global completions, which will * include completions from the template's context component, as well as any local references or * template variables which are in scope for that expression. */ getGlobalCompletions( context: TmplAstTemplate | null, component: ts.ClassDeclaration, node: AST | TmplAstNode, ): GlobalCompletion | null; /** * For the given expression node, retrieve a `TcbLocation` that can be used to perform * autocompletion at that point in the expression, if such a location exists. */ getExpressionCompletionLocation( expr: PropertyRead | SafePropertyRead, component: ts.ClassDeclaration, ): TcbLocation | null; /** * For the given node represents a `LiteralPrimitive`(the `TextAttribute` represents a string * literal), retrieve a `TcbLocation` that can be used to perform autocompletion at that point in * the node, if such a location exists. */ getLiteralCompletionLocation( strNode: LiteralPrimitive | TmplAstTextAttribute, component: ts.ClassDeclaration, ): TcbLocation | null; /** * Get basic metadata on the directives which are in scope or can be imported for the given * component. */ getPotentialTemplateDirectives(component: ts.ClassDeclaration): PotentialDirective[]; /** * Get basic metadata on the pipes which are in scope or can be imported for the given component. */ getPotentialPipes(component: ts.ClassDeclaration): PotentialPipe[]; /** * Retrieve a `Map` of potential template element tags, to either the `PotentialDirective` that * declares them (if the tag is from a directive/component), or `null` if the tag originates from * the DOM schema. */ getPotentialElementTags(component: ts.ClassDeclaration): Map<string, PotentialDirective | null>; /** * In the context of an Angular trait, generate potential imports for a directive. */ getPotentialImportsFor( toImport: Reference<ClassDeclaration>, inComponent: ts.ClassDeclaration, importMode: PotentialImportMode, ): ReadonlyArray<PotentialImport>; /** * Get the primary decorator for an Angular class (such as @Component). This does not work for * `@Injectable`. */ getPrimaryAngularDecorator(target: ts.ClassDeclaration): ts.Decorator | null; /** * Get the class of the NgModule that owns this Angular trait. If the result is `null`, that * probably means the provided component is standalone. */ getOwningNgModule(component: ts.ClassDeclaration): ts.ClassDeclaration | null; /** * Retrieve any potential DOM bindings for the given element. * * This returns an array of objects which list both the attribute and property names of each * binding, which are usually identical but can vary if the HTML attribute name is for example a * reserved keyword in JS, like the `for` attribute which corresponds to the `htmlFor` property. */ getPotentialDomBindings(tagName: string): {attribute: string; property: string}[]; /** * Retrieve any potential DOM events. */ getPotentialDomEvents(tagName: string): string[]; /** * Retrieve the type checking engine's metadata for the given directive class, if available. */ getDirectiveMetadata(dir: ts.ClassDeclaration): TypeCheckableDirectiveMeta | null; /** * Retrieve the type checking engine's metadata for the given NgModule class, if available. */ getNgModuleMetadata(module: ts.ClassDeclaration): NgModuleMeta | null; /** * Retrieve the type checking engine's metadata for the given pipe class, if available. */ getPipeMetadata(pipe: ts.ClassDeclaration): PipeMeta | null; /** * Gets the directives that have been used in a component's template. */ getUsedDirectives(component: ts.ClassDeclaration): TypeCheckableDirectiveMeta[] | null; /** * Gets the pipes that have been used in a component's template. */ getUsedPipes(component: ts.ClassDeclaration): string[] | null; /** * Reset the `TemplateTypeChecker`'s state for the given class, so that it will be recomputed on * the next request. */ invalidateClass(clazz: ts.ClassDeclaration): void; /** * Gets the target of a template expression, if possible. * See `BoundTarget.getExpressionTarget` for more information. */ getExpressionTarget(expression: AST, clazz: ts.ClassDeclaration): TemplateEntity | null; /** * Constructs a `ts.Diagnostic` for a given `ParseSourceSpan` within a template. */ makeTemplateDiagnostic<T extends ErrorCode>( clazz: ts.ClassDeclaration, sourceSpan: ParseSourceSpan, category: ts.DiagnosticCategory, errorCode: T, message: string, relatedInformation?: { text: string; start: number; end: number; sourceFile: ts.SourceFile; }[], ): NgTemplateDiagnostic<T>; } /** * Describes the scope of the caller's interest in template type-checking results. */
{ "end_byte": 9914, "start_byte": 1688, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/api/checker.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/api/checker.ts_9915_10742
export enum OptimizeFor { /** * Indicates that a consumer of a `TemplateTypeChecker` is only interested in results for a * given file, and wants them as fast as possible. * * Calling `TemplateTypeChecker` methods successively for multiple files while specifying * `OptimizeFor.SingleFile` can result in significant unnecessary overhead overall. */ SingleFile, /** * Indicates that a consumer of a `TemplateTypeChecker` intends to query for results pertaining * to the entire user program, and so the type-checker should internally optimize for this case. * * Initial calls to retrieve type-checking information may take longer, but repeated calls to * gather information for the whole user program will be significantly faster with this mode of * optimization. */ WholeProgram, }
{ "end_byte": 10742, "start_byte": 9915, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/api/checker.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/api/scope.ts_0_2395
/** * @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 {EmittedReference, Reference} from '../../imports'; import {ClassDeclaration} from '../../reflection'; import {SymbolWithValueDeclaration} from '../../util/src/typescript'; /** * A PotentialImport for some Angular trait has a TypeScript module specifier, which can be * relative, as well as an identifier name. */ export interface PotentialImport { kind: PotentialImportKind; // If no moduleSpecifier is present, the given symbol name is already in scope. moduleSpecifier?: string; symbolName: string; isForwardReference: boolean; } /** * Which kind of Angular Trait the import targets. */ export enum PotentialImportKind { NgModule, Standalone, } /** * Metadata on a directive which is available in a template. */ export interface PotentialDirective { ref: Reference<ClassDeclaration>; /** * The `ts.Symbol` for the directive class. */ tsSymbol: SymbolWithValueDeclaration; /** * The module which declares the directive. */ ngModule: ClassDeclaration | null; /** * The selector for the directive or component. */ selector: string | null; /** * `true` if this directive is a component. */ isComponent: boolean; /** * `true` if this directive is a structural directive. */ isStructural: boolean; /** * Whether or not this directive is in scope. */ isInScope: boolean; } /** * Metadata for a pipe which is available in a template. */ export interface PotentialPipe { ref: Reference<ClassDeclaration>; /** * The `ts.Symbol` for the pipe class. */ tsSymbol: ts.Symbol; /** * Name of the pipe. */ name: string; /** * Whether or not this pipe is in scope. */ isInScope: boolean; } /** * Possible modes in which to look up a potential import. */ export enum PotentialImportMode { /** Whether an import is standalone is inferred based on its metadata. */ Normal, /** * An import is assumed to be standalone and is imported directly. This is useful for migrations * where a declaration wasn't standalone when the program was created, but will become standalone * as a part of the migration. */ ForceDirect, }
{ "end_byte": 2395, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/api/scope.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/api/context.ts_0_2587
/** * @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 { ParseError, ParseSourceFile, R3TargetBinder, SchemaMetadata, TmplAstNode, } from '@angular/compiler'; import ts from 'typescript'; import {Reference} from '../../imports'; import {PipeMeta} from '../../metadata'; import {ClassDeclaration} from '../../reflection'; import {TemplateSourceMapping, TypeCheckableDirectiveMeta} from './api'; /** * A currently pending type checking operation, into which templates for type-checking can be * registered. */ export interface TypeCheckContext { /** * Register a template to potentially be type-checked. * * Templates registered via `addTemplate` are available for checking, but might be skipped if * checking of that component is not required. This can happen for a few reasons, including if * the component was previously checked and the prior results are still valid. * * @param ref a `Reference` to the component class which yielded this template. * @param binder an `R3TargetBinder` which encapsulates the scope of this template, including all * available directives. * @param template the original template AST of this component. * @param pipes a `Map` of pipes available within the scope of this template. * @param schemas any schemas which apply to this template. * @param sourceMapping a `TemplateSourceMapping` instance which describes the origin of the * template text described by the AST. * @param file the `ParseSourceFile` associated with the template. * @param parseErrors the `ParseError`'s associated with the template. * @param isStandalone a boolean indicating whether the component is standalone. * @param preserveWhitespaces a boolean indicating whether the component's template preserves * whitespaces. */ addTemplate( ref: Reference<ClassDeclaration<ts.ClassDeclaration>>, binder: R3TargetBinder<TypeCheckableDirectiveMeta>, template: TmplAstNode[], pipes: Map<string, PipeMeta>, schemas: SchemaMetadata[], sourceMapping: TemplateSourceMapping, file: ParseSourceFile, parseErrors: ParseError[] | null, isStandalone: boolean, preserveWhitespaces: boolean, ): void; } /** * Interface to trigger generation of type-checking code for a program given a new * `TypeCheckContext`. */ export interface ProgramTypeCheckAdapter { typeCheck(sf: ts.SourceFile, ctx: TypeCheckContext): void; }
{ "end_byte": 2587, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/api/context.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/api/symbols.ts_0_7991
/** * @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 { TmplAstElement, TmplAstLetDeclaration, TmplAstReference, TmplAstTemplate, TmplAstVariable, } from '@angular/compiler'; import ts from 'typescript'; import {AbsoluteFsPath} from '../../file_system'; import {SymbolWithValueDeclaration} from '../../util/src/typescript'; import {PotentialDirective} from './scope'; export enum SymbolKind { Input, Output, Binding, Reference, Variable, Directive, Element, Template, Expression, DomBinding, Pipe, LetDeclaration, } /** * A representation of an entity in the `TemplateAst`. */ export type Symbol = | InputBindingSymbol | OutputBindingSymbol | ElementSymbol | ReferenceSymbol | VariableSymbol | ExpressionSymbol | DirectiveSymbol | TemplateSymbol | DomBindingSymbol | PipeSymbol | LetDeclarationSymbol; /** * A `Symbol` which declares a new named entity in the template scope. */ export type TemplateDeclarationSymbol = ReferenceSymbol | VariableSymbol; /** * Information about where a `ts.Node` can be found in the type check file. This can either be * a type-checking shim file, or an original source file for inline type check blocks. */ export interface TcbLocation { /** * The fully qualified path of the file which contains the generated TypeScript type check * code for the component's template. */ tcbPath: AbsoluteFsPath; /** * Whether the type check block exists in a type-checking shim file or is inline. */ isShimFile: boolean; /** The location in the file where node appears. */ positionInFile: number; } /** * A generic representation of some node in a template. */ export interface TsNodeSymbolInfo { /** The `ts.Type` of the template node. */ tsType: ts.Type; /** The `ts.Symbol` for the template node */ tsSymbol: ts.Symbol | null; /** The position of the most relevant part of the template node. */ tcbLocation: TcbLocation; } /** * A representation of an expression in a component template. */ export interface ExpressionSymbol { kind: SymbolKind.Expression; /** The `ts.Type` of the expression AST. */ tsType: ts.Type; /** * The `ts.Symbol` of the entity. This could be `null`, for example `AST` expression * `{{foo.bar + foo.baz}}` does not have a `ts.Symbol` but `foo.bar` and `foo.baz` both do. */ tsSymbol: ts.Symbol | null; /** The position of the most relevant part of the expression. */ tcbLocation: TcbLocation; } /** Represents either an input or output binding in a template. */ export interface BindingSymbol { kind: SymbolKind.Binding; /** The `ts.Type` of the class member on the directive that is the target of the binding. */ tsType: ts.Type; /** The `ts.Symbol` of the class member on the directive that is the target of the binding. */ tsSymbol: ts.Symbol; /** * The `DirectiveSymbol` or `ElementSymbol` for the Directive, Component, or `HTMLElement` with * the binding. */ target: DirectiveSymbol | ElementSymbol | TemplateSymbol; /** The location in the shim file where the field access for the binding appears. */ tcbLocation: TcbLocation; } /** * A representation of an input binding in a component template. */ export interface InputBindingSymbol { kind: SymbolKind.Input; /** A single input may be bound to multiple components or directives. */ bindings: BindingSymbol[]; } /** * A representation of an output binding in a component template. */ export interface OutputBindingSymbol { kind: SymbolKind.Output; /** A single output may be bound to multiple components or directives. */ bindings: BindingSymbol[]; } /** * A representation of a local reference in a component template. */ export interface ReferenceSymbol { kind: SymbolKind.Reference; /** * The `ts.Type` of the Reference value. * * `TmplAstTemplate` - The type of the `TemplateRef` * `TmplAstElement` - The `ts.Type` for the `HTMLElement`. * Directive - The `ts.Type` for the class declaration. */ tsType: ts.Type; /** * The `ts.Symbol` for the Reference value. * * `TmplAstTemplate` - A `TemplateRef` symbol. * `TmplAstElement` - The symbol for the `HTMLElement`. * Directive - The symbol for the class declaration of the directive. */ tsSymbol: ts.Symbol; /** * Depending on the type of the reference, this is one of the following: * - `TmplAstElement` when the local ref refers to the HTML element * - `TmplAstTemplate` when the ref refers to an `ng-template` * - `ts.ClassDeclaration` when the local ref refers to a Directive instance (#ref="myExportAs") */ target: TmplAstElement | TmplAstTemplate | ts.ClassDeclaration; /** * The node in the `TemplateAst` where the symbol is declared. That is, node for the `#ref` or * `#ref="exportAs"`. */ declaration: TmplAstReference; /** * The location in the shim file of a variable that holds the type of the local ref. * For example, a reference declaration like the following: * ``` * var _t1 = document.createElement('div'); * var _t2 = _t1; // This is the reference declaration * ``` * This `targetLocation` is `[_t1 variable declaration].getStart()`. */ targetLocation: TcbLocation; /** * The location in the TCB for the identifier node in the reference variable declaration. * For example, given a variable declaration statement for a template reference: * `var _t2 = _t1`, this location is `[_t2 node].getStart()`. This location can * be used to find references to the variable within the template. */ referenceVarLocation: TcbLocation; } /** * A representation of a context variable in a component template. */ export interface VariableSymbol { kind: SymbolKind.Variable; /** * The `ts.Type` of the entity. * * This will be `any` if there is no `ngTemplateContextGuard`. */ tsType: ts.Type; /** * The `ts.Symbol` for the context variable. * * This will be `null` if there is no `ngTemplateContextGuard`. */ tsSymbol: ts.Symbol | null; /** * The node in the `TemplateAst` where the variable is declared. That is, the node for the `let-` * node in the template. */ declaration: TmplAstVariable; /** * The location in the shim file for the identifier that was declared for the template variable. */ localVarLocation: TcbLocation; /** * The location in the shim file for the initializer node of the variable that represents the * template variable. */ initializerLocation: TcbLocation; } /** * A representation of an `@let` declaration in a component template. */ export interface LetDeclarationSymbol { kind: SymbolKind.LetDeclaration; /** The `ts.Type` of the entity. */ tsType: ts.Type; /** * The `ts.Symbol` for the declaration. * * This will be `null` if the symbol could not be resolved using the type checker. */ tsSymbol: ts.Symbol | null; /** The node in the `TemplateAst` where the `@let` is declared. */ declaration: TmplAstLetDeclaration; /** * The location in the shim file for the identifier of the `@let` declaration. */ localVarLocation: TcbLocation; /** * The location in the shim file of the `@let` declaration's initializer expression. */ initializerLocation: TcbLocation; } /** * A representation of an element in a component template. */ export interface ElementSymbol { kind: SymbolKind.Element; /** The `ts.Type` for the `HTMLElement`. */ tsType: ts.Type; /** The `ts.Symbol` for the `HTMLElement`. */ tsSymbol: ts.Symbol | null; /** A list of directives applied to the element. */ directives: DirectiveSymbol[]; /** The location in the shim file for the variable that holds the type of the element. */ tcbLocation: TcbLocation; templateNode: TmplAstElement; }
{ "end_byte": 7991, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/api/symbols.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/api/symbols.ts_7993_10286
export interface TemplateSymbol { kind: SymbolKind.Template; /** A list of directives applied to the element. */ directives: DirectiveSymbol[]; templateNode: TmplAstTemplate; } /** Interface shared between host and non-host directives. */ interface DirectiveSymbolBase extends PotentialDirective { kind: SymbolKind.Directive; /** The `ts.Type` for the class declaration. */ tsType: ts.Type; /** The location in the shim file for the variable that holds the type of the directive. */ tcbLocation: TcbLocation; } /** * A representation of a directive/component whose selector matches a node in a component * template. */ export type DirectiveSymbol = | (DirectiveSymbolBase & {isHostDirective: false}) | (DirectiveSymbolBase & { isHostDirective: true; exposedInputs: Record<string, string> | null; exposedOutputs: Record<string, string> | null; }); /** * A representation of an attribute on an element or template. These bindings aren't currently * type-checked (see `checkTypeOfDomBindings`) so they won't have a `ts.Type`, `ts.Symbol`, or shim * location. */ export interface DomBindingSymbol { kind: SymbolKind.DomBinding; /** The symbol for the element or template of the text attribute. */ host: ElementSymbol | TemplateSymbol; } /** * A representation for a call to a pipe's transform method in the TCB. */ export interface PipeSymbol { kind: SymbolKind.Pipe; /** The `ts.Type` of the transform node. */ tsType: ts.Type; /** * The `ts.Symbol` for the transform call. This could be `null` when `checkTypeOfPipes` is set to * `false` because the transform call would be of the form `(_pipe1 as any).transform()` */ tsSymbol: ts.Symbol | null; /** The position of the transform call in the template. */ tcbLocation: TcbLocation; /** The symbol for the pipe class as an instance that appears in the TCB. */ classSymbol: ClassSymbol; } /** Represents an instance of a class found in the TCB, i.e. `var _pipe1: MyPipe = null!; */ export interface ClassSymbol { /** The `ts.Type` of class. */ tsType: ts.Type; /** The `ts.Symbol` for class. */ tsSymbol: SymbolWithValueDeclaration; /** The position for the variable declaration for the class instance. */ tcbLocation: TcbLocation; }
{ "end_byte": 10286, "start_byte": 7993, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/api/symbols.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/api/api.ts_0_3287
/** * @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 { AbsoluteSourceSpan, BoundTarget, DirectiveMeta, ParseSourceSpan, SchemaMetadata, } from '@angular/compiler'; import ts from 'typescript'; import {ErrorCode} from '../../diagnostics'; import {Reference} from '../../imports'; import { ClassPropertyMapping, DirectiveTypeCheckMeta, HostDirectiveMeta, InputMapping, PipeMeta, } from '../../metadata'; import {ClassDeclaration} from '../../reflection'; /** * Extension of `DirectiveMeta` that includes additional information required to type-check the * usage of a particular directive. */ export interface TypeCheckableDirectiveMeta extends DirectiveMeta, DirectiveTypeCheckMeta { ref: Reference<ClassDeclaration>; queries: string[]; inputs: ClassPropertyMapping<InputMapping>; outputs: ClassPropertyMapping; isStandalone: boolean; isSignal: boolean; hostDirectives: HostDirectiveMeta[] | null; decorator: ts.Decorator | null; isExplicitlyDeferred: boolean; imports: Reference<ClassDeclaration>[] | null; rawImports: ts.Expression | null; } export type TemplateId = string & {__brand: 'TemplateId'}; /** * A `ts.Diagnostic` with additional information about the diagnostic related to template * type-checking. */ export interface TemplateDiagnostic extends ts.Diagnostic { /** * The component with the template that resulted in this diagnostic. */ componentFile: ts.SourceFile; /** * The template id of the component that resulted in this diagnostic. */ templateId: TemplateId; } /** * A `TemplateDiagnostic` with a specific error code. */ export type NgTemplateDiagnostic<T extends ErrorCode> = TemplateDiagnostic & {__ngCode: T}; /** * Metadata required in addition to a component class in order to generate a type check block (TCB) * for that component. */ export interface TypeCheckBlockMetadata { /** * A unique identifier for the class which gave rise to this TCB. * * This can be used to map errors back to the `ts.ClassDeclaration` for the component. */ id: TemplateId; /** * Semantic information about the template of the component. */ boundTarget: BoundTarget<TypeCheckableDirectiveMeta>; /* * Pipes used in the template of the component. */ pipes: Map<string, PipeMeta>; /** * Schemas that apply to this template. */ schemas: SchemaMetadata[]; /* * A boolean indicating whether the component is standalone. */ isStandalone: boolean; /** * A boolean indicating whether the component preserves whitespaces in its template. */ preserveWhitespaces: boolean; } export interface TypeCtorMetadata { /** * The name of the requested type constructor function. */ fnName: string; /** * Whether to generate a body for the function or not. */ body: boolean; /** * Input, output, and query field names in the type which should be included as constructor input. */ fields: {inputs: ClassPropertyMapping<InputMapping>; queries: string[]}; /** * `Set` of field names which have type coercion enabled. */ coercedInputFields: Set<string>; }
{ "end_byte": 3287, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/api/api.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/api/api.ts_3289_11351
export interface TypeCheckingConfig { /** * Whether to check the left-hand side type of binding operations. * * For example, if this is `false` then the expression `[input]="expr"` will have `expr` type- * checked, but not the assignment of the resulting type to the `input` property of whichever * directive or component is receiving the binding. If set to `true`, both sides of the assignment * are checked. * * This flag only affects bindings to components/directives. Bindings to the DOM are checked if * `checkTypeOfDomBindings` is set. */ checkTypeOfInputBindings: boolean; /** * Whether to honor the access modifiers on input bindings for the component/directive. * * If a template binding attempts to assign to an input that is private/protected/readonly, * this will produce errors when enabled but will not when disabled. */ honorAccessModifiersForInputBindings: boolean; /** * Whether to use strict null types for input bindings for directives. * * If this is `true`, applications that are compiled with TypeScript's `strictNullChecks` enabled * will produce type errors for bindings which can evaluate to `undefined` or `null` where the * inputs's type does not include `undefined` or `null` in its type. If set to `false`, all * binding expressions are wrapped in a non-null assertion operator to effectively disable strict * null checks. This may be particularly useful when the directive is from a library that is not * compiled with `strictNullChecks` enabled. * * If `checkTypeOfInputBindings` is set to `false`, this flag has no effect. */ strictNullInputBindings: boolean; /** * Whether to check text attributes that happen to be consumed by a directive or component. * * For example, in a template containing `<input matInput disabled>` the `disabled` attribute ends * up being consumed as an input with type `boolean` by the `matInput` directive. At runtime, the * input will be set to the attribute's string value, which is an empty string for attributes * without a value, so with this flag set to `true`, an error would be reported. If set to * `false`, text attributes will never report an error. * * Note that if `checkTypeOfInputBindings` is set to `false`, this flag has no effect. */ checkTypeOfAttributes: boolean; /** * Whether to check the left-hand side type of binding operations to DOM properties. * * As `checkTypeOfBindings`, but only applies to bindings to DOM properties. * * This does not affect the use of the `DomSchemaChecker` to validate the template against the DOM * schema. Rather, this flag is an experimental, not yet complete feature which uses the * lib.dom.d.ts DOM typings in TypeScript to validate that DOM bindings are of the correct type * for assignability to the underlying DOM element properties. */ checkTypeOfDomBindings: boolean; /** * Whether to infer the type of the `$event` variable in event bindings for directive outputs or * animation events. * * If this is `true`, the type of `$event` will be inferred based on the generic type of * `EventEmitter`/`Subject` of the output. If set to `false`, the `$event` variable will be of * type `any`. */ checkTypeOfOutputEvents: boolean; /** * Whether to infer the type of the `$event` variable in event bindings for animations. * * If this is `true`, the type of `$event` will be `AnimationEvent` from `@angular/animations`. * If set to `false`, the `$event` variable will be of type `any`. */ checkTypeOfAnimationEvents: boolean; /** * Whether to infer the type of the `$event` variable in event bindings to DOM events. * * If this is `true`, the type of `$event` will be inferred based on TypeScript's * `HTMLElementEventMap`, with a fallback to the native `Event` type. If set to `false`, the * `$event` variable will be of type `any`. */ checkTypeOfDomEvents: boolean; /** * Whether to infer the type of local references to DOM elements. * * If this is `true`, the type of a `#ref` variable on a DOM node in the template will be * determined by the type of `document.createElement` for the given DOM node type. If set to * `false`, the type of `ref` for DOM nodes will be `any`. */ checkTypeOfDomReferences: boolean; /** * Whether to infer the type of local references. * * If this is `true`, the type of a `#ref` variable that points to a directive or `TemplateRef` in * the template will be inferred correctly. If set to `false`, the type of `ref` for will be * `any`. */ checkTypeOfNonDomReferences: boolean; /** * Whether to adjust the output of the TCB to ensure compatibility with the `TemplateTypeChecker`. * * The statements generated in the TCB are optimized for performance and producing diagnostics. * These optimizations can result in generating a TCB that does not have all the information * needed by the `TemplateTypeChecker` for retrieving `Symbol`s. For example, as an optimization, * the TCB will not generate variable declaration statements for directives that have no * references, inputs, or outputs. However, the `TemplateTypeChecker` always needs these * statements to be present in order to provide `ts.Symbol`s and `ts.Type`s for the directives. * * When set to `false`, enables TCB optimizations for template diagnostics. * When set to `true`, ensures all information required by `TemplateTypeChecker` to * retrieve symbols for template nodes is available in the TCB. */ enableTemplateTypeChecker: boolean; /** * Whether to include type information from pipes in the type-checking operation. * * If this is `true`, then the pipe's type signature for `transform()` will be used to check the * usage of the pipe. If this is `false`, then the result of applying a pipe will be `any`, and * the types of the pipe's value and arguments will not be matched against the `transform()` * method. */ checkTypeOfPipes: boolean; /** * Whether to narrow the types of template contexts. */ applyTemplateContextGuards: boolean; /** * Whether to use a strict type for null-safe navigation operations. * * If this is `false`, then the return type of `a?.b` or `a?()` will be `any`. If set to `true`, * then the return type of `a?.b` for example will be the same as the type of the ternary * expression `a != null ? a.b : a`. */ strictSafeNavigationTypes: boolean; /** * Whether to descend into template bodies and check any bindings there. */ checkTemplateBodies: boolean; /** * Whether to always apply DOM schema checks in template bodies, independently of the * `checkTemplateBodies` setting. */ alwaysCheckSchemaInTemplateBodies: boolean; /** * Whether to check resolvable queries. * * This is currently an unsupported feature. */ checkQueries: false; /** * Whether to check if control flow syntax will prevent a node from being projected. */ controlFlowPreventingContentProjection: 'error' | 'warning' | 'suppress'; /** * Whether to check if `@Component.imports` contains unused symbols. */ unusedStandaloneImports: 'error' | 'warning' | 'suppress'; /** * Whether to use any generic types of the context component. * * If this is `true`, then if the context component has generic types, those will be mirrored in * the template type-checking context. If `false`, any generic type parameters of the context * component will be set to `any` during type-checking. */ useContextGenericType: boolean; /** * Whether or not to infer types for object and array literals in the template. * * If this is `true`, then the type of an object or an array literal in the template will be the * same type that TypeScript would infer if the literal appeared in code. If `false`, then such * literals are cast to `any` when declared. */ strictLiteralTypes: boolean;
{ "end_byte": 11351, "start_byte": 3289, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/api/api.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/api/api.ts_11355_14869
/** * Whether to use inline type constructors. * * If this is `true`, create inline type constructors when required. For example, if a type * constructor's parameters has private types, it cannot be created normally, so we inline it in * the directives definition file. * * If false, do not create inline type constructors. Fall back to using `any` type for * constructors that normally require inlining. * * This option requires the environment to support inlining. If the environment does not support * inlining, this must be set to `false`. */ useInlineTypeConstructors: boolean; /** * Whether or not to produce diagnostic suggestions in cases where the compiler could have * inferred a better type for a construct, but was prevented from doing so by the current type * checking configuration. * * For example, if the compiler could have used a template context guard to infer a better type * for a structural directive's context and `let-` variables, but the user is in * `fullTemplateTypeCheck` mode and such guards are therefore disabled. * * This mode is useful for clients like the Language Service which want to inform users of * opportunities to improve their own developer experience. */ suggestionsForSuboptimalTypeInference: boolean; /** * Whether the type of two-way bindings should be widened to allow `WritableSignal`. */ allowSignalsInTwoWayBindings: boolean; /** * Whether to descend into the bodies of control flow blocks (`@if`, `@switch` and `@for`). */ checkControlFlowBodies: boolean; } export type TemplateSourceMapping = | DirectTemplateSourceMapping | IndirectTemplateSourceMapping | ExternalTemplateSourceMapping; /** * A mapping to an inline template in a TS file. * * `ParseSourceSpan`s for this template should be accurate for direct reporting in a TS error * message. */ export interface DirectTemplateSourceMapping { type: 'direct'; node: ts.StringLiteral | ts.NoSubstitutionTemplateLiteral; } /** * A mapping to a template which is still in a TS file, but where the node positions in any * `ParseSourceSpan`s are not accurate for one reason or another. * * This can occur if the template expression was interpolated in a way where the compiler could not * construct a contiguous mapping for the template string. The `node` refers to the `template` * expression. */ export interface IndirectTemplateSourceMapping { type: 'indirect'; componentClass: ClassDeclaration; node: ts.Expression; template: string; } /** * A mapping to a template declared in an external HTML file, where node positions in * `ParseSourceSpan`s represent accurate offsets into the external file. * * In this case, the given `node` refers to the `templateUrl` expression. */ export interface ExternalTemplateSourceMapping { type: 'external'; componentClass: ClassDeclaration; node: ts.Expression; template: string; templateUrl: string; } /** * A mapping of a TCB template id to a span in the corresponding template source. */ export interface SourceLocation { id: TemplateId; span: AbsoluteSourceSpan; } /** * A representation of all a node's template mapping information we know. Useful for producing * diagnostics based on a TCB node or generally mapping from a TCB node back to a template location. */ export interface FullTemplateMapping { sourceLocation: SourceLocation; templateSourceMapping: TemplateSourceMapping; span: ParseSourceSpan; }
{ "end_byte": 14869, "start_byte": 11355, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/api/api.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/api/BUILD.bazel_0_662
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "api", srcs = glob(["**/*.ts"]), module_name = "@angular/compiler-cli/src/ngtsc/typecheck/api", deps = [ "//packages:types", "//packages/compiler", "//packages/compiler-cli/src/ngtsc/diagnostics", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/metadata", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/util", "@npm//typescript", ], )
{ "end_byte": 662, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/api/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/api/index.ts_0_363
/** * @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 './api'; export * from './checker'; export * from './completion'; export * from './context'; export * from './scope'; export * from './symbols';
{ "end_byte": 363, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/api/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/api/completion.ts_0_2790
/** * @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 {TmplAstLetDeclaration, TmplAstReference, TmplAstVariable} from '@angular/compiler'; import {TcbLocation} from './symbols'; /** * An autocompletion source of any kind. */ export type Completion = ReferenceCompletion | VariableCompletion | LetDeclarationCompletion; /** * Discriminant of an autocompletion source (a `Completion`). */ export enum CompletionKind { Reference, Variable, LetDeclaration, } /** * An autocompletion result representing a local reference declared in the template. */ export interface ReferenceCompletion { kind: CompletionKind.Reference; /** * The `TmplAstReference` from the template which should be available as a completion. */ node: TmplAstReference; } /** * An autocompletion result representing a variable declared in the template. */ export interface VariableCompletion { kind: CompletionKind.Variable; /** * The `TmplAstVariable` from the template which should be available as a completion. */ node: TmplAstVariable; } /** * An autocompletion result representing an `@let` declaration in the template. */ export interface LetDeclarationCompletion { kind: CompletionKind.LetDeclaration; /** * The `TmplAstLetDeclaration` from the template which should be available as a completion. */ node: TmplAstLetDeclaration; } /** * Autocompletion data for an expression in the global scope. * * Global completion is accomplished by merging data from two sources: * * TypeScript completion of the component's class members. * * Local references and variables that are in scope at a given template level. */ export interface GlobalCompletion { /** * A location within the type-checking shim where TypeScript's completion APIs can be used to * access completions for the template's component context (component class members). */ componentContext: TcbLocation; /** * `Map` of local references and variables that are visible at the requested level of the * template. * * Shadowing of references/variables from multiple levels of the template has already been * accounted for in the preparation of `templateContext`. Entries here shadow component members of * the same name (from the `componentContext` completions). */ templateContext: Map<string, ReferenceCompletion | VariableCompletion | LetDeclarationCompletion>; /** * A location within the type-checking shim where TypeScript's completion APIs can be used to * access completions for the AST node of the cursor position (primitive constants). */ nodeContext: TcbLocation | null; }
{ "end_byte": 2790, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/api/completion.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/comments.ts_0_6612
/** * @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 {AbsoluteSourceSpan, ParseSourceSpan} from '@angular/compiler'; import ts from 'typescript'; const parseSpanComment = /^(\d+),(\d+)$/; /** * Reads the trailing comments and finds the first match which is a span comment (i.e. 4,10) on a * node and returns it as an `AbsoluteSourceSpan`. * * Will return `null` if no trailing comments on the node match the expected form of a source span. */ export function readSpanComment( node: ts.Node, sourceFile: ts.SourceFile = node.getSourceFile(), ): AbsoluteSourceSpan | null { return ( ts.forEachTrailingCommentRange(sourceFile.text, node.getEnd(), (pos, end, kind) => { if (kind !== ts.SyntaxKind.MultiLineCommentTrivia) { return null; } const commentText = sourceFile.text.substring(pos + 2, end - 2); const match = commentText.match(parseSpanComment); if (match === null) { return null; } return new AbsoluteSourceSpan(+match[1], +match[2]); }) || null ); } /** Used to identify what type the comment is. */ export enum CommentTriviaType { DIAGNOSTIC = 'D', EXPRESSION_TYPE_IDENTIFIER = 'T', } /** Identifies what the TCB expression is for (for example, a directive declaration). */ export enum ExpressionIdentifier { DIRECTIVE = 'DIR', COMPONENT_COMPLETION = 'COMPCOMP', EVENT_PARAMETER = 'EP', VARIABLE_AS_EXPRESSION = 'VAE', } /** Tags the node with the given expression identifier. */ export function addExpressionIdentifier(node: ts.Node, identifier: ExpressionIdentifier) { ts.addSyntheticTrailingComment( node, ts.SyntaxKind.MultiLineCommentTrivia, `${CommentTriviaType.EXPRESSION_TYPE_IDENTIFIER}:${identifier}`, /* hasTrailingNewLine */ false, ); } const IGNORE_FOR_DIAGNOSTICS_MARKER = `${CommentTriviaType.DIAGNOSTIC}:ignore`; /** * Tag the `ts.Node` with an indication that any errors arising from the evaluation of the node * should be ignored. */ export function markIgnoreDiagnostics(node: ts.Node): void { ts.addSyntheticTrailingComment( node, ts.SyntaxKind.MultiLineCommentTrivia, IGNORE_FOR_DIAGNOSTICS_MARKER, /* hasTrailingNewLine */ false, ); } /** Returns true if the node has a marker that indicates diagnostics errors should be ignored. */ export function hasIgnoreForDiagnosticsMarker(node: ts.Node, sourceFile: ts.SourceFile): boolean { return ( ts.forEachTrailingCommentRange(sourceFile.text, node.getEnd(), (pos, end, kind) => { if (kind !== ts.SyntaxKind.MultiLineCommentTrivia) { return null; } const commentText = sourceFile.text.substring(pos + 2, end - 2); return commentText === IGNORE_FOR_DIAGNOSTICS_MARKER; }) === true ); } function makeRecursiveVisitor<T extends ts.Node>( visitor: (node: ts.Node) => T | null, ): (node: ts.Node) => T | undefined { function recursiveVisitor(node: ts.Node): T | undefined { const res = visitor(node); return res !== null ? res : node.forEachChild(recursiveVisitor); } return recursiveVisitor; } export interface FindOptions<T extends ts.Node> { filter: (node: ts.Node) => node is T; withExpressionIdentifier?: ExpressionIdentifier; withSpan?: AbsoluteSourceSpan | ParseSourceSpan; } function getSpanFromOptions(opts: FindOptions<ts.Node>) { let withSpan: {start: number; end: number} | null = null; if (opts.withSpan !== undefined) { if (opts.withSpan instanceof AbsoluteSourceSpan) { withSpan = opts.withSpan; } else { withSpan = {start: opts.withSpan.start.offset, end: opts.withSpan.end.offset}; } } return withSpan; } /** * Given a `ts.Node` with finds the first node whose matching the criteria specified * by the `FindOptions`. * * Returns `null` when no `ts.Node` matches the given conditions. */ export function findFirstMatchingNode<T extends ts.Node>( tcb: ts.Node, opts: FindOptions<T>, ): T | null { const withSpan = getSpanFromOptions(opts); const withExpressionIdentifier = opts.withExpressionIdentifier; const sf = tcb.getSourceFile(); const visitor = makeRecursiveVisitor<T>((node) => { if (!opts.filter(node)) { return null; } if (withSpan !== null) { const comment = readSpanComment(node, sf); if (comment === null || withSpan.start !== comment.start || withSpan.end !== comment.end) { return null; } } if ( withExpressionIdentifier !== undefined && !hasExpressionIdentifier(sf, node, withExpressionIdentifier) ) { return null; } return node; }); return tcb.forEachChild(visitor) ?? null; } /** * Given a `ts.Node` with source span comments, finds the first node whose source span comment * matches the given `sourceSpan`. Additionally, the `filter` function allows matching only * `ts.Nodes` of a given type, which provides the ability to select only matches of a given type * when there may be more than one. * * Returns `null` when no `ts.Node` matches the given conditions. */ export function findAllMatchingNodes<T extends ts.Node>(tcb: ts.Node, opts: FindOptions<T>): T[] { const withSpan = getSpanFromOptions(opts); const withExpressionIdentifier = opts.withExpressionIdentifier; const results: T[] = []; const stack: ts.Node[] = [tcb]; const sf = tcb.getSourceFile(); while (stack.length > 0) { const node = stack.pop()!; if (!opts.filter(node)) { stack.push(...node.getChildren()); continue; } if (withSpan !== null) { const comment = readSpanComment(node, sf); if (comment === null || withSpan.start !== comment.start || withSpan.end !== comment.end) { stack.push(...node.getChildren()); continue; } } if ( withExpressionIdentifier !== undefined && !hasExpressionIdentifier(sf, node, withExpressionIdentifier) ) { continue; } results.push(node); } return results; } export function hasExpressionIdentifier( sourceFile: ts.SourceFile, node: ts.Node, identifier: ExpressionIdentifier, ): boolean { return ( ts.forEachTrailingCommentRange(sourceFile.text, node.getEnd(), (pos, end, kind) => { if (kind !== ts.SyntaxKind.MultiLineCommentTrivia) { return false; } const commentText = sourceFile.text.substring(pos + 2, end - 2); return commentText === `${CommentTriviaType.EXPRESSION_TYPE_IDENTIFIER}:${identifier}`; }) || false ); }
{ "end_byte": 6612, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/comments.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/checker.ts_0_2704
/** * @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 { AST, CssSelector, DomElementSchemaRegistry, ExternalExpr, LiteralPrimitive, ParseSourceSpan, PropertyRead, SafePropertyRead, TemplateEntity, TmplAstElement, TmplAstNode, TmplAstTemplate, TmplAstTextAttribute, WrappedNodeExpr, } from '@angular/compiler'; import ts from 'typescript'; import {ErrorCode, ngErrorCode} from '../../diagnostics'; import {absoluteFromSourceFile, AbsoluteFsPath, getSourceFileOrError} from '../../file_system'; import {Reference, ReferenceEmitKind, ReferenceEmitter} from '../../imports'; import {IncrementalBuild} from '../../incremental/api'; import { DirectiveMeta, MetadataReader, MetadataReaderWithIndex, MetaKind, NgModuleIndex, NgModuleMeta, PipeMeta, } from '../../metadata'; import {PerfCheckpoint, PerfEvent, PerfPhase, PerfRecorder} from '../../perf'; import {ProgramDriver, UpdateMode} from '../../program_driver'; import { ClassDeclaration, DeclarationNode, isNamedClassDeclaration, ReflectionHost, } from '../../reflection'; import {ComponentScopeKind, ComponentScopeReader, TypeCheckScopeRegistry} from '../../scope'; import {isShim} from '../../shims'; import {getSourceFileOrNull, isSymbolWithValueDeclaration} from '../../util/src/typescript'; import { ElementSymbol, FullTemplateMapping, GlobalCompletion, NgTemplateDiagnostic, OptimizeFor, PotentialDirective, PotentialImport, PotentialImportKind, PotentialImportMode, PotentialPipe, ProgramTypeCheckAdapter, Symbol, TcbLocation, TemplateDiagnostic, TemplateId, TemplateSymbol, TemplateTypeChecker, TypeCheckableDirectiveMeta, TypeCheckingConfig, } from '../api'; import {makeTemplateDiagnostic} from '../diagnostics'; import {CompletionEngine} from './completion'; import { InliningMode, ShimTypeCheckingData, TemplateData, TypeCheckContextImpl, TypeCheckingHost, } from './context'; import {shouldReportDiagnostic, translateDiagnostic} from './diagnostics'; import {TypeCheckShimGenerator} from './shim'; import {TemplateSourceManager} from './source'; import {findTypeCheckBlock, getTemplateMapping, TemplateSourceResolver} from './tcb_util'; import {SymbolBuilder} from './template_symbol_builder'; const REGISTRY = new DomElementSchemaRegistry(); /** * Primary template type-checking engine, which performs type-checking using a * `TypeCheckingProgramStrategy` for type-checking program maintenance, and the * `ProgramTypeCheckAdapter` for generation of template type-checking code. */
{ "end_byte": 2704, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/checker.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/src/checker.ts_2705_9829
export class TemplateTypeCheckerImpl implements TemplateTypeChecker { private state = new Map<AbsoluteFsPath, FileTypeCheckingData>(); /** * Stores the `CompletionEngine` which powers autocompletion for each component class. * * Must be invalidated whenever the component's template or the `ts.Program` changes. Invalidation * on template changes is performed within this `TemplateTypeCheckerImpl` instance. When the * `ts.Program` changes, the `TemplateTypeCheckerImpl` as a whole is destroyed and replaced. */ private completionCache = new Map<ts.ClassDeclaration, CompletionEngine>(); /** * Stores the `SymbolBuilder` which creates symbols for each component class. * * Must be invalidated whenever the component's template or the `ts.Program` changes. Invalidation * on template changes is performed within this `TemplateTypeCheckerImpl` instance. When the * `ts.Program` changes, the `TemplateTypeCheckerImpl` as a whole is destroyed and replaced. */ private symbolBuilderCache = new Map<ts.ClassDeclaration, SymbolBuilder>(); /** * Stores directives and pipes that are in scope for each component. * * Unlike other caches, the scope of a component is not affected by its template. It will be * destroyed when the `ts.Program` changes and the `TemplateTypeCheckerImpl` as a whole is * destroyed and replaced. */ private scopeCache = new Map<ts.ClassDeclaration, ScopeData>(); /** * Stores potential element tags for each component (a union of DOM tags as well as directive * tags). * * Unlike other caches, the scope of a component is not affected by its template. It will be * destroyed when the `ts.Program` changes and the `TemplateTypeCheckerImpl` as a whole is * destroyed and replaced. */ private elementTagCache = new Map<ts.ClassDeclaration, Map<string, PotentialDirective | null>>(); private isComplete = false; constructor( private originalProgram: ts.Program, readonly programDriver: ProgramDriver, private typeCheckAdapter: ProgramTypeCheckAdapter, private config: TypeCheckingConfig, private refEmitter: ReferenceEmitter, private reflector: ReflectionHost, private compilerHost: Pick<ts.CompilerHost, 'getCanonicalFileName'>, private priorBuild: IncrementalBuild<unknown, FileTypeCheckingData>, private readonly metaReader: MetadataReader, private readonly localMetaReader: MetadataReaderWithIndex, private readonly ngModuleIndex: NgModuleIndex, private readonly componentScopeReader: ComponentScopeReader, private readonly typeCheckScopeRegistry: TypeCheckScopeRegistry, private readonly perf: PerfRecorder, ) {} getTemplate(component: ts.ClassDeclaration, optimizeFor?: OptimizeFor): TmplAstNode[] | null { const {data} = this.getLatestComponentState(component); if (data === null) { return null; } return data.template; } getUsedDirectives(component: ts.ClassDeclaration): TypeCheckableDirectiveMeta[] | null { return this.getLatestComponentState(component).data?.boundTarget.getUsedDirectives() || null; } getUsedPipes(component: ts.ClassDeclaration): string[] | null { return this.getLatestComponentState(component).data?.boundTarget.getUsedPipes() || null; } private getLatestComponentState( component: ts.ClassDeclaration, optimizeFor: OptimizeFor = OptimizeFor.SingleFile, ): { data: TemplateData | null; tcb: ts.Node | null; tcbPath: AbsoluteFsPath; tcbIsShim: boolean; } { switch (optimizeFor) { case OptimizeFor.WholeProgram: this.ensureAllShimsForAllFiles(); break; case OptimizeFor.SingleFile: this.ensureShimForComponent(component); break; } const sf = component.getSourceFile(); const sfPath = absoluteFromSourceFile(sf); const shimPath = TypeCheckShimGenerator.shimFor(sfPath); const fileRecord = this.getFileData(sfPath); if (!fileRecord.shimData.has(shimPath)) { return {data: null, tcb: null, tcbPath: shimPath, tcbIsShim: true}; } const templateId = fileRecord.sourceManager.getTemplateId(component); const shimRecord = fileRecord.shimData.get(shimPath)!; const id = fileRecord.sourceManager.getTemplateId(component); const program = this.programDriver.getProgram(); const shimSf = getSourceFileOrNull(program, shimPath); if (shimSf === null || !fileRecord.shimData.has(shimPath)) { throw new Error(`Error: no shim file in program: ${shimPath}`); } let tcb: ts.Node | null = findTypeCheckBlock(shimSf, id, /*isDiagnosticsRequest*/ false); let tcbPath = shimPath; if (tcb === null) { // Try for an inline block. const inlineSf = getSourceFileOrError(program, sfPath); tcb = findTypeCheckBlock(inlineSf, id, /*isDiagnosticsRequest*/ false); if (tcb !== null) { tcbPath = sfPath; } } let data: TemplateData | null = null; if (shimRecord.templates.has(templateId)) { data = shimRecord.templates.get(templateId)!; } return {data, tcb, tcbPath, tcbIsShim: tcbPath === shimPath}; } isTrackedTypeCheckFile(filePath: AbsoluteFsPath): boolean { return this.getFileAndShimRecordsForPath(filePath) !== null; } private getFileRecordForTcbLocation({ tcbPath, isShimFile, }: TcbLocation): FileTypeCheckingData | null { if (!isShimFile) { // The location is not within a shim file but corresponds with an inline TCB in an original // source file; we can obtain the record directly by its path. if (this.state.has(tcbPath)) { return this.state.get(tcbPath)!; } else { return null; } } // The location is within a type-checking shim file; find the type-checking data that owns this // shim path. const records = this.getFileAndShimRecordsForPath(tcbPath); if (records !== null) { return records.fileRecord; } else { return null; } } private getFileAndShimRecordsForPath( shimPath: AbsoluteFsPath, ): {fileRecord: FileTypeCheckingData; shimRecord: ShimTypeCheckingData} | null { for (const fileRecord of this.state.values()) { if (fileRecord.shimData.has(shimPath)) { return {fileRecord, shimRecord: fileRecord.shimData.get(shimPath)!}; } } return null; } getTemplateMappingAtTcbLocation(tcbLocation: TcbLocation): FullTemplateMapping | null { const fileRecord = this.getFileRecordForTcbLocation(tcbLocation); if (fileRecord === null) { return null; } const shimSf = this.programDriver.getProgram().getSourceFile(tcbLocation.tcbPath); if (shimSf === undefined) { return null; } return getTemplateMapping( shimSf, tcbLocation.positionInFile, fileRecord.sourceManager, /*isDiagnosticsRequest*/ false, ); } generateAllTypeCheckBlocks() { this.ensureAllShimsForAllFiles(); } /** * Retrieve type-checking and template parse diagnostics from the given `ts.SourceFile` using the * most recent type-checking program. */
{ "end_byte": 9829, "start_byte": 2705, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/src/checker.ts" }