_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/compiler-cli/src/ngtsc/sourcemaps/index.ts_0_432
/** * @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 {ContentOrigin} from './src/content_origin'; export {MapAndPath, RawSourceMap} from './src/raw_source_map'; export {Mapping, SourceFile} from './src/source_file'; export {SourceFileLoader} from './src/source_file_loader';
{ "end_byte": 432, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/index.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_loader_spec.ts_0_925
/** * @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 mapHelpers from 'convert-source-map'; import {absoluteFrom, FileSystem, getFileSystem} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {MockLogger} from '../../logging/testing'; import {RawSourceMap} from '../src/raw_source_map'; import {SourceFileLoader} from '../src/source_file_loader'; runInEachFileSystem(() => { describe('SourceFileLoader', () => { let fs: FileSystem; let logger: MockLogger; let _: typeof absoluteFrom; let registry: SourceFileLoader; beforeEach(() => { fs = getFileSystem(); logger = new MockLogger(); _ = absoluteFrom; registry = new SourceFileLoader(fs, logger, {webpack: _('/foo')}); });
{ "end_byte": 925, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_loader_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_loader_spec.ts_931_9632
describe('loadSourceFile', () => { it('should load a file with no source map and inline contents', () => { const sourceFile = registry.loadSourceFile(_('/foo/src/index.js'), 'some inline content'); if (sourceFile === null) { return fail('Expected source file to be defined'); } expect(sourceFile.contents).toEqual('some inline content'); expect(sourceFile.sourcePath).toEqual(_('/foo/src/index.js')); expect(sourceFile.rawMap).toBe(null); expect(sourceFile.sources).toEqual([]); }); it('should load a file with no source map and read its contents from disk', () => { fs.ensureDir(_('/foo/src')); fs.writeFile(_('/foo/src/index.js'), 'some external content'); const sourceFile = registry.loadSourceFile(_('/foo/src/index.js')); if (sourceFile === null) { return fail('Expected source file to be defined'); } expect(sourceFile.contents).toEqual('some external content'); expect(sourceFile.sourcePath).toEqual(_('/foo/src/index.js')); expect(sourceFile.rawMap).toBe(null); expect(sourceFile.sources).toEqual([]); }); it('should load a file with an external source map', () => { fs.ensureDir(_('/foo/src')); const sourceMap = createRawSourceMap({file: 'index.js'}); fs.writeFile(_('/foo/src/external.js.map'), JSON.stringify(sourceMap)); const sourceFile = registry.loadSourceFile( _('/foo/src/index.js'), 'some inline content\n//# sourceMappingURL=external.js.map', ); if (sourceFile === null) { return fail('Expected source file to be defined'); } if (sourceFile.rawMap === null) { return fail('Expected source map to be defined'); } expect(sourceFile.rawMap.map).toEqual(sourceMap); }); it('should only read source-map comments from the last line of a file', () => { fs.ensureDir(_('/foo/src')); const sourceMap = createRawSourceMap({file: 'index.js'}); fs.writeFile(_('/foo/src/external.js.map'), JSON.stringify(sourceMap)); const sourceFile = registry.loadSourceFile( _('/foo/src/index.js'), [ 'some content', '//# sourceMappingURL=bad.js.map', 'some more content', '//# sourceMappingURL=external.js.map', ].join('\n'), ); if (sourceFile === null) { return fail('Expected source file to be defined'); } if (sourceFile.rawMap === null) { return fail('Expected source map to be defined'); } expect(sourceFile.rawMap.map).toEqual(sourceMap); }); for (const eolMarker of ['\n', '\r\n']) { it(`should only read source-map comments from the last non-blank line of a file [EOL marker: ${ eolMarker === '\n' ? '\\n' : '\\r\\n' }]`, () => { fs.ensureDir(_('/foo/src')); const sourceMap = createRawSourceMap({file: 'index.js'}); fs.writeFile(_('/foo/src/external.js.map'), JSON.stringify(sourceMap)); const sourceFile = registry.loadSourceFile( _('/foo/src/index.js'), [ 'some content', '//# sourceMappingURL=bad.js.map', 'some more content', '//# sourceMappingURL=external.js.map', '', '', ].join(eolMarker), ); if (sourceFile === null) { return fail('Expected source file to be defined'); } if (sourceFile.rawMap === null) { return fail('Expected source map to be defined'); } expect(sourceFile.rawMap.map).toEqual(sourceMap); }); } it('should handle a missing external source map', () => { fs.ensureDir(_('/foo/src')); const sourceFile = registry.loadSourceFile( _('/foo/src/index.js'), 'some inline content\n//# sourceMappingURL=external.js.map', ); if (sourceFile === null) { return fail('Expected source file to be defined'); } expect(sourceFile.rawMap).toBe(null); }); it('should load a file with an inline encoded source map', () => { const sourceMap = createRawSourceMap({file: 'index.js'}); const encodedSourceMap = Buffer.from(JSON.stringify(sourceMap)).toString('base64'); const sourceFile = registry.loadSourceFile( _('/foo/src/index.js'), `some inline content\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${encodedSourceMap}`, ); if (sourceFile === null) { return fail('Expected source file to be defined'); } if (sourceFile.rawMap === null) { return fail('Expected source map to be defined'); } expect(sourceFile.rawMap.map).toEqual(sourceMap); }); it('should load a file with an implied source map', () => { const sourceMap = createRawSourceMap({file: 'index.js'}); fs.ensureDir(_('/foo/src')); fs.writeFile(_('/foo/src/index.js.map'), JSON.stringify(sourceMap)); const sourceFile = registry.loadSourceFile(_('/foo/src/index.js'), 'some inline content'); if (sourceFile === null) { return fail('Expected source file to be defined'); } if (sourceFile.rawMap === null) { return fail('Expected source map to be defined'); } expect(sourceFile.rawMap.map).toEqual(sourceMap); }); it('should handle missing implied source-map file', () => { fs.ensureDir(_('/foo/src')); const sourceFile = registry.loadSourceFile(_('/foo/src/index.js'), 'some inline content'); if (sourceFile === null) { return fail('Expected source file to be defined'); } expect(sourceFile.rawMap).toBe(null); }); it('should recurse into external original source files that are referenced from source maps', () => { // Setup a scenario where the generated files reference previous files: // // index.js // -> x.js // -> y.js // -> a.js // -> z.js (inline content) fs.ensureDir(_('/foo/src')); const indexSourceMap = createRawSourceMap({ file: 'index.js', sources: ['x.js', 'y.js', 'z.js'], 'sourcesContent': [null, null, 'z content'], }); fs.writeFile(_('/foo/src/index.js.map'), JSON.stringify(indexSourceMap)); fs.writeFile(_('/foo/src/x.js'), 'x content'); const ySourceMap = createRawSourceMap({file: 'y.js', sources: ['a.js']}); fs.writeFile(_('/foo/src/y.js'), 'y content'); fs.writeFile(_('/foo/src/y.js.map'), JSON.stringify(ySourceMap)); fs.writeFile(_('/foo/src/z.js'), 'z content'); fs.writeFile(_('/foo/src/a.js'), 'a content'); const sourceFile = registry.loadSourceFile(_('/foo/src/index.js'), 'index content'); if (sourceFile === null) { return fail('Expected source file to be defined'); } expect(sourceFile.contents).toEqual('index content'); expect(sourceFile.sourcePath).toEqual(_('/foo/src/index.js')); if (sourceFile.rawMap === null) { return fail('Expected source map to be defined'); } expect(sourceFile.rawMap.map).toEqual(indexSourceMap); expect(sourceFile.sources.length).toEqual(3); expect(sourceFile.sources[0]!.contents).toEqual('x content'); expect(sourceFile.sources[0]!.sourcePath).toEqual(_('/foo/src/x.js')); expect(sourceFile.sources[0]!.rawMap).toBe(null); expect(sourceFile.sources[0]!.sources).toEqual([]); expect(sourceFile.sources[1]!.contents).toEqual('y content'); expect(sourceFile.sources[1]!.sourcePath).toEqual(_('/foo/src/y.js')); expect(sourceFile.sources[1]!.rawMap!.map).toEqual(ySourceMap); expect(sourceFile.sources[1]!.sources.length).toEqual(1); expect(sourceFile.sources[1]!.sources[0]!.contents).toEqual('a content'); expect(sourceFile.sources[1]!.sources[0]!.sourcePath).toEqual(_('/foo/src/a.js')); expect(sourceFile.sources[1]!.sources[0]!.rawMap).toBe(null); expect(sourceFile.sources[1]!.sources[0]!.sources).toEqual([]); expect(sourceFile.sources[2]!.contents).toEqual('z content'); expect(sourceFile.sources[2]!.sourcePath).toEqual(_('/foo/src/z.js')); expect(sourceFile.sources[2]!.rawMap).toBe(null); expect(sourceFile.sources[2]!.sources).toEqual([]); });
{ "end_byte": 9632, "start_byte": 931, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_loader_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_loader_spec.ts_9640_17114
it('should handle a missing source file referenced from a source-map', () => { fs.ensureDir(_('/foo/src')); const indexSourceMap = createRawSourceMap({ file: 'index.js', sources: ['x.js'], 'sourcesContent': [null], }); fs.writeFile(_('/foo/src/index.js.map'), JSON.stringify(indexSourceMap)); const sourceFile = registry.loadSourceFile(_('/foo/src/index.js'), 'index content'); if (sourceFile === null) { return fail('Expected source file to be defined'); } expect(sourceFile.contents).toEqual('index content'); expect(sourceFile.sourcePath).toEqual(_('/foo/src/index.js')); if (sourceFile.rawMap === null) { return fail('Expected source map to be defined'); } expect(sourceFile.rawMap.map).toEqual(indexSourceMap); expect(sourceFile.sources.length).toEqual(1); expect(sourceFile.sources[0]).toBe(null); }); }); it('should log a warning if there is a cyclic dependency in source files loaded from disk', () => { // a.js -> a.js.map -> b.js -> b.js.map -> c.js -> c.js.map -> (external) a.js // ^^^^^^^^^^^^^^^ // c.js.map incorrectly links to a.js, creating a cycle fs.ensureDir(_('/foo/src')); const aMap = createRawSourceMap({file: 'a.js', sources: ['b.js']}); const aPath = _('/foo/src/a.js'); fs.writeFile(aPath, 'a content\n' + mapHelpers.fromObject(aMap).toComment()); const bPath = _('/foo/src/b.js'); fs.writeFile( bPath, 'b content\n' + mapHelpers.fromObject(createRawSourceMap({file: 'b.js', sources: ['c.js']})).toComment(), ); const cPath = _('/foo/src/c.js'); fs.writeFile( cPath, 'c content\n' + mapHelpers.fromObject(createRawSourceMap({file: 'c.js', sources: ['a.js']})).toComment(), ); const sourceFile = registry.loadSourceFile(aPath)!; expect(sourceFile).not.toBe(null!); expect(sourceFile.contents).toEqual('a content\n'); expect(sourceFile.sourcePath).toEqual(_('/foo/src/a.js')); if (sourceFile.rawMap === null) { return fail('Expected source map to be defined'); } expect(sourceFile.rawMap.map).toEqual(aMap); expect(sourceFile.sources.length).toEqual(1); expect(logger.logs.warn[0][0]).toContain( `Circular source file mapping dependency: ` + `${aPath} -> ${bPath} -> ${cPath} -> ${aPath}`, ); }); it('should log a warning if there is a cyclic dependency in source maps loaded from disk', () => { // a.js -> a.js.map -> b.js -> a.js.map -> c.js // ^^^^^^^^ // b.js incorrectly links to a.js.map, creating a cycle fs.ensureDir(_('/foo/src')); const aPath = _('/foo/src/a.js'); fs.writeFile(aPath, 'a.js content\n//# sourceMappingURL=a.js.map'); const aMap = createRawSourceMap({file: 'a.js', sources: ['b.js']}); const aMapPath = _('/foo/src/a.js.map'); fs.writeFile(aMapPath, JSON.stringify(aMap)); const bPath = _('/foo/src/b.js'); fs.writeFile(bPath, 'b.js content\n//# sourceMappingURL=a.js.map'); const sourceFile = registry.loadSourceFile(aPath); if (sourceFile === null) { return fail('Expected source file to be defined'); } expect(sourceFile.contents).toEqual('a.js content\n'); expect(sourceFile.sourcePath).toEqual(_('/foo/src/a.js')); if (sourceFile.rawMap === null) { return fail('Expected source map to be defined'); } expect(sourceFile.rawMap.map).toEqual(aMap); expect(sourceFile.sources.length).toEqual(1); expect(logger.logs.warn[0][0]).toContain( `Circular source file mapping dependency: ` + `${aPath} -> ${aMapPath} -> ${bPath} -> ${aMapPath}`, ); const innerSourceFile = sourceFile.sources[0]; if (innerSourceFile === null) { return fail('Expected source file to be defined'); } expect(innerSourceFile.contents).toEqual('b.js content\n'); expect(innerSourceFile.sourcePath).toEqual(_('/foo/src/b.js')); // The source-map from b.js was not loaded as it would have caused a cycle expect(innerSourceFile.rawMap).toBe(null); expect(innerSourceFile.sources.length).toEqual(0); }); it('should not fail if the filename of an inline source looks like a cyclic dependency', () => { // a.js -> (inline) a.js.map -> (inline) a.js // ^^^^^^^^^^^^^ // a.js loads despite same name as previous file because it is inline fs.ensureDir(_('/foo/src')); const aPath = _('/foo/src/a.js'); const aMap = createRawSourceMap({ file: 'a.js', sources: ['a.js'], sourcesContent: ['inline original a.js content'], }); fs.writeFile(aPath, 'a content\n' + mapHelpers.fromObject(aMap).toComment()); const sourceFile = registry.loadSourceFile(aPath); if (sourceFile === null) { return fail('Expected source file to be defined'); } expect(sourceFile.sources.length).toEqual(1); expect(sourceFile.sources[0]!.contents).toEqual('inline original a.js content'); expect(sourceFile.sources[0]!.sourcePath).toEqual(aPath); expect(sourceFile.sources[0]!.rawMap).toBe(null); expect(sourceFile.sources[0]!.sources).toEqual([]); expect(logger.logs.warn.length).toEqual(0); }); it('should not load source-maps (after the initial map) from disk if the source file was inline', () => { // a.js -> (initial) a.js.map -> b.js -> b.js.map -> (inline) c.js -> c.js.map // ^^^^^^^^ // c.js.map is not loaded because the referencing source file (c.js) was inline fs.ensureDir(_('/foo/src')); const aPath = _('/foo/src/a.js'); fs.writeFile(aPath, 'a.js content\n//# sourceMappingURL=a.js.map'); const aMapPath = _('/foo/src/a.js.map'); const aMap = createRawSourceMap({file: 'a.js', sources: ['b.js']}); fs.writeFile(aMapPath, JSON.stringify(aMap)); const bPath = _('/foo/src/b.js'); fs.writeFile(bPath, 'b.js content\n//# sourceMappingURL=b.js.map'); const bMapPath = _('/foo/src/b.js.map'); const bMap = createRawSourceMap({ file: 'b.js', sources: ['c.js'], sourcesContent: ['c content\n//# sourceMappingURL=c.js.map'], }); fs.writeFile(bMapPath, JSON.stringify(bMap)); const cMapPath = _('/foo/src/c.js.map'); const cMap = createRawSourceMap({file: 'c.js', sources: ['d.js']}); fs.writeFile(cMapPath, JSON.stringify(cMap)); const sourceFile = registry.loadSourceFile(aPath); if (sourceFile === null) { return fail('Expected source file to be defined'); } const bSource = sourceFile.sources[0]; if (!bSource) { return fail('Expected source file to be defined'); } const cSource = bSource.sources[0]; if (!cSource) { return fail('Expected source file to be defined'); } // External c.js.map never gets loaded because c.js was inline source expect(cSource.rawMap).toBe(null); expect(cSource.sources).toEqual([]); expect(logger.logs.warn.length).toEqual(0); });
{ "end_byte": 17114, "start_byte": 9640, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_loader_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_loader_spec.ts_17120_19655
for (const {scheme, mappedPath} of [ {scheme: 'WEBPACK://', mappedPath: '/foo/src/index.ts'}, {scheme: 'webpack://', mappedPath: '/foo/src/index.ts'}, {scheme: 'missing://', mappedPath: '/src/index.ts'}, ]) { it(`should handle source paths that are protocol mapped [scheme:"${scheme}"]`, () => { fs.ensureDir(_('/foo/src')); const indexSourceMap = createRawSourceMap({ file: 'index.js', sources: [`${scheme}/src/index.ts`], 'sourcesContent': ['original content'], }); fs.writeFile(_('/foo/src/index.js.map'), JSON.stringify(indexSourceMap)); const sourceFile = registry.loadSourceFile(_('/foo/src/index.js'), 'generated content'); if (sourceFile === null) { return fail('Expected source file to be defined'); } const originalSource = sourceFile.sources[0]; if (originalSource === null) { return fail('Expected source file to be defined'); } expect(originalSource.contents).toEqual('original content'); expect(originalSource.sourcePath).toEqual(_(mappedPath)); expect(originalSource.rawMap).toBe(null); expect(originalSource.sources).toEqual([]); }); it(`should handle source roots that are protocol mapped [scheme:"${scheme}"]`, () => { fs.ensureDir(_('/foo/src')); const indexSourceMap = createRawSourceMap({ file: 'index.js', sources: ['index.ts'], 'sourcesContent': ['original content'], sourceRoot: `${scheme}/src`, }); fs.writeFile(_('/foo/src/index.js.map'), JSON.stringify(indexSourceMap)); const sourceFile = registry.loadSourceFile(_('/foo/src/index.js'), 'generated content'); if (sourceFile === null) { return fail('Expected source file to be defined'); } const originalSource = sourceFile.sources[0]; if (originalSource === null) { return fail('Expected source file to be defined'); } expect(originalSource.contents).toEqual('original content'); expect(originalSource.sourcePath).toEqual(_(mappedPath)); expect(originalSource.rawMap).toBe(null); expect(originalSource.sources).toEqual([]); }); } }); }); function createRawSourceMap(custom: Partial<RawSourceMap>): RawSourceMap { return { 'version': 3, 'sourceRoot': '', 'sources': [], 'sourcesContent': [], 'names': [], 'mappings': '', ...custom, }; }
{ "end_byte": 19655, "start_byte": 17120, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_loader_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_spec.ts_0_5175
/** * @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 {encode} from '@jridgewell/sourcemap-codec'; import {absoluteFrom, getFileSystem, PathManipulation} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {ContentOrigin} from '../src/content_origin'; import {RawSourceMap, SourceMapInfo} from '../src/raw_source_map'; import {SegmentMarker} from '../src/segment_marker'; import { computeStartOfLinePositions, ensureOriginalSegmentLinks, extractOriginalSegments, findLastMappingIndexBefore, Mapping, parseMappings, SourceFile, } from '../src/source_file'; runInEachFileSystem(() => { describe('SourceFile and utilities', () => { let fs: PathManipulation; let _: typeof absoluteFrom; beforeEach(() => { fs = getFileSystem(); _ = absoluteFrom; }); describe('parseMappings()', () => { it('should be an empty array for source files with no source map', () => { const mappings = parseMappings(null, [], []); expect(mappings).toEqual([]); }); it('should be empty array for source files with no source map mappings', () => { const rawSourceMap: RawSourceMap = {mappings: '', names: [], sources: [], version: 3}; const mappings = parseMappings(rawSourceMap, [], []); expect(mappings).toEqual([]); }); it('should parse the mappings from the raw source map', () => { const rawSourceMap: RawSourceMap = { mappings: encode([ [ [0, 0, 0, 0], [6, 0, 0, 3], ], ]), names: [], sources: ['a.js'], version: 3, }; const originalSource = new SourceFile(_('/foo/src/a.js'), 'abcdefg', null, [], fs); const mappings = parseMappings(rawSourceMap, [originalSource], [0, 8]); expect(mappings).toEqual([ { generatedSegment: {line: 0, column: 0, position: 0, next: undefined}, originalSource, originalSegment: {line: 0, column: 0, position: 0, next: undefined}, name: undefined, }, { generatedSegment: {line: 0, column: 6, position: 6, next: undefined}, originalSource, originalSegment: {line: 0, column: 3, position: 3, next: undefined}, name: undefined, }, ]); }); }); describe('extractOriginalSegments()', () => { it('should return an empty Map for source files with no source map', () => { expect(extractOriginalSegments(parseMappings(null, [], []))).toEqual(new Map()); }); it('should be empty Map for source files with no source map mappings', () => { const rawSourceMap: RawSourceMap = {mappings: '', names: [], sources: [], version: 3}; expect(extractOriginalSegments(parseMappings(rawSourceMap, [], []))).toEqual(new Map()); }); it('should parse the segments in ascending order of original position from the raw source map', () => { const originalSource = new SourceFile(_('/foo/src/a.js'), 'abcdefg', null, [], fs); const rawSourceMap: RawSourceMap = { mappings: encode([ [ [0, 0, 0, 0], [2, 0, 0, 3], [4, 0, 0, 2], ], ]), names: [], sources: ['a.js'], version: 3, }; const originalSegments = extractOriginalSegments( parseMappings(rawSourceMap, [originalSource], [0, 8]), ); expect(originalSegments.get(originalSource)).toEqual([ {line: 0, column: 0, position: 0, next: undefined}, {line: 0, column: 2, position: 2, next: undefined}, {line: 0, column: 3, position: 3, next: undefined}, ]); }); it('should create separate arrays for each original source file', () => { const sourceA = new SourceFile(_('/foo/src/a.js'), 'abcdefg', null, [], fs); const sourceB = new SourceFile(_('/foo/src/b.js'), '1234567', null, [], fs); const rawSourceMap: RawSourceMap = { mappings: encode([ [ [0, 0, 0, 0], [2, 1, 0, 3], [4, 0, 0, 2], [5, 1, 0, 5], [6, 1, 0, 2], ], ]), names: [], sources: ['a.js', 'b.js'], version: 3, }; const originalSegments = extractOriginalSegments( parseMappings(rawSourceMap, [sourceA, sourceB], [0, 8]), ); expect(originalSegments.get(sourceA)).toEqual([ {line: 0, column: 0, position: 0, next: undefined}, {line: 0, column: 2, position: 2, next: undefined}, ]); expect(originalSegments.get(sourceB)).toEqual([ {line: 0, column: 2, position: 2, next: undefined}, {line: 0, column: 3, position: 3, next: undefined}, {line: 0, column: 5, position: 5, next: undefined}, ]); }); });
{ "end_byte": 5175, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_spec.ts_5181_10953
describe('findLastMappingIndexBefore', () => { it('should find the highest mapping index that has a segment marker below the given one if there is not an exact match', () => { const marker5: SegmentMarker = {line: 0, column: 50, position: 50, next: undefined}; const marker4: SegmentMarker = {line: 0, column: 40, position: 40, next: marker5}; const marker3: SegmentMarker = {line: 0, column: 30, position: 30, next: marker4}; const marker2: SegmentMarker = {line: 0, column: 20, position: 20, next: marker3}; const marker1: SegmentMarker = {line: 0, column: 10, position: 10, next: marker2}; const mappings: Mapping[] = [marker1, marker2, marker3, marker4, marker5].map( (marker) => ({generatedSegment: marker}) as Mapping, ); const marker: SegmentMarker = {line: 0, column: 35, position: 35, next: undefined}; const index = findLastMappingIndexBefore(mappings, marker, /* exclusive */ false, 0); expect(index).toEqual(2); }); it('should find the highest mapping index that has a segment marker (when there are duplicates) below the given one if there is not an exact match', () => { const marker5: SegmentMarker = {line: 0, column: 50, position: 50, next: undefined}; const marker4: SegmentMarker = {line: 0, column: 30, position: 30, next: marker5}; const marker3: SegmentMarker = {line: 0, column: 30, position: 30, next: marker4}; const marker2: SegmentMarker = {line: 0, column: 20, position: 20, next: marker3}; const marker1: SegmentMarker = {line: 0, column: 10, position: 10, next: marker2}; const mappings: Mapping[] = [marker1, marker2, marker3, marker4, marker5].map( (marker) => ({generatedSegment: marker}) as Mapping, ); const marker: SegmentMarker = {line: 0, column: 35, position: 35, next: undefined}; const index = findLastMappingIndexBefore(mappings, marker, /* exclusive */ false, 0); expect(index).toEqual(3); }); it('should find the last mapping if the segment marker is higher than all of them', () => { const marker5: SegmentMarker = {line: 0, column: 50, position: 50, next: undefined}; const marker4: SegmentMarker = {line: 0, column: 40, position: 40, next: marker5}; const marker3: SegmentMarker = {line: 0, column: 30, position: 30, next: marker4}; const marker2: SegmentMarker = {line: 0, column: 20, position: 20, next: marker3}; const marker1: SegmentMarker = {line: 0, column: 10, position: 10, next: marker2}; const mappings: Mapping[] = [marker1, marker2, marker3, marker4, marker5].map( (marker) => ({generatedSegment: marker}) as Mapping, ); const marker: SegmentMarker = {line: 0, column: 60, position: 60, next: undefined}; const index = findLastMappingIndexBefore(mappings, marker, /* exclusive */ false, 0); expect(index).toEqual(4); }); it('should return -1 if the segment marker is lower than all of them', () => { const marker5: SegmentMarker = {line: 0, column: 50, position: 50, next: undefined}; const marker4: SegmentMarker = {line: 0, column: 40, position: 40, next: marker5}; const marker3: SegmentMarker = {line: 0, column: 30, position: 30, next: marker4}; const marker2: SegmentMarker = {line: 0, column: 20, position: 20, next: marker3}; const marker1: SegmentMarker = {line: 0, column: 10, position: 10, next: marker2}; const mappings: Mapping[] = [marker1, marker2, marker3, marker4, marker5].map( (marker) => ({generatedSegment: marker}) as Mapping, ); const marker: SegmentMarker = {line: 0, column: 5, position: 5, next: undefined}; const index = findLastMappingIndexBefore(mappings, marker, /* exclusive */ false, 0); expect(index).toEqual(-1); }); describe('[exact match inclusive]', () => { it('should find the matching segment marker mapping index if there is only one of them', () => { const marker5: SegmentMarker = {line: 0, column: 50, position: 50, next: undefined}; const marker4: SegmentMarker = {line: 0, column: 40, position: 40, next: marker5}; const marker3: SegmentMarker = {line: 0, column: 30, position: 30, next: marker4}; const marker2: SegmentMarker = {line: 0, column: 20, position: 20, next: marker3}; const marker1: SegmentMarker = {line: 0, column: 10, position: 10, next: marker2}; const mappings: Mapping[] = [marker1, marker2, marker3, marker4, marker5].map( (marker) => ({generatedSegment: marker}) as Mapping, ); const index = findLastMappingIndexBefore(mappings, marker3, /* exclusive */ false, 0); expect(index).toEqual(2); }); it('should find the highest matching segment marker mapping index if there is more than one of them', () => { const marker5: SegmentMarker = {line: 0, column: 50, position: 50, next: undefined}; const marker4: SegmentMarker = {line: 0, column: 30, position: 30, next: marker5}; const marker3: SegmentMarker = {line: 0, column: 30, position: 30, next: marker4}; const marker2: SegmentMarker = {line: 0, column: 20, position: 20, next: marker3}; const marker1: SegmentMarker = {line: 0, column: 10, position: 10, next: marker2}; const mappings: Mapping[] = [marker1, marker2, marker3, marker4, marker5].map( (marker) => ({generatedSegment: marker}) as Mapping, ); const index = findLastMappingIndexBefore(mappings, marker3, /* exclusive */ false, 0); expect(index).toEqual(3); }); });
{ "end_byte": 10953, "start_byte": 5181, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_spec.ts_10961_17854
describe('[exact match exclusive]', () => { it('should find the preceding mapping index if there is a matching segment marker', () => { const marker5: SegmentMarker = {line: 0, column: 50, position: 50, next: undefined}; const marker4: SegmentMarker = {line: 0, column: 40, position: 40, next: marker5}; const marker3: SegmentMarker = {line: 0, column: 30, position: 30, next: marker4}; const marker2: SegmentMarker = {line: 0, column: 20, position: 20, next: marker3}; const marker1: SegmentMarker = {line: 0, column: 10, position: 10, next: marker2}; const mappings: Mapping[] = [marker1, marker2, marker3, marker4, marker5].map( (marker) => ({generatedSegment: marker}) as Mapping, ); const index = findLastMappingIndexBefore(mappings, marker3, /* exclusive */ true, 0); expect(index).toEqual(1); }); it('should find the highest preceding mapping index if there is more than one matching segment marker', () => { const marker5: SegmentMarker = {line: 0, column: 50, position: 50, next: undefined}; const marker4: SegmentMarker = {line: 0, column: 30, position: 30, next: marker5}; const marker3: SegmentMarker = {line: 0, column: 30, position: 30, next: marker4}; const marker2: SegmentMarker = {line: 0, column: 20, position: 20, next: marker3}; const marker1: SegmentMarker = {line: 0, column: 10, position: 10, next: marker2}; const mappings: Mapping[] = [marker1, marker2, marker3, marker4, marker5].map( (marker) => ({generatedSegment: marker}) as Mapping, ); const index = findLastMappingIndexBefore(mappings, marker3, /* exclusive */ false, 0); expect(index).toEqual(3); }); }); describe('[with lowerIndex hint', () => { it('should find the highest mapping index above the lowerIndex hint that has a segment marker below the given one if there is not an exact match', () => { const marker5: SegmentMarker = {line: 0, column: 50, position: 50, next: undefined}; const marker4: SegmentMarker = {line: 0, column: 40, position: 40, next: marker5}; const marker3: SegmentMarker = {line: 0, column: 30, position: 30, next: marker4}; const marker2: SegmentMarker = {line: 0, column: 20, position: 20, next: marker3}; const marker1: SegmentMarker = {line: 0, column: 10, position: 10, next: marker2}; const mappings: Mapping[] = [marker1, marker2, marker3, marker4, marker5].map( (marker) => ({generatedSegment: marker}) as Mapping, ); const marker: SegmentMarker = {line: 0, column: 35, position: 35, next: undefined}; const index = findLastMappingIndexBefore(mappings, marker, /* exclusive */ false, 1); expect(index).toEqual(2); }); it('should return the lowerIndex mapping index if there is a single exact match and we are not exclusive', () => { const marker5: SegmentMarker = {line: 0, column: 50, position: 50, next: undefined}; const marker4: SegmentMarker = {line: 0, column: 40, position: 40, next: marker5}; const marker3: SegmentMarker = {line: 0, column: 30, position: 30, next: marker4}; const marker2: SegmentMarker = {line: 0, column: 20, position: 20, next: marker3}; const marker1: SegmentMarker = {line: 0, column: 10, position: 10, next: marker2}; const mappings: Mapping[] = [marker1, marker2, marker3, marker4, marker5].map( (marker) => ({generatedSegment: marker}) as Mapping, ); const marker: SegmentMarker = {line: 0, column: 30, position: 30, next: undefined}; const index = findLastMappingIndexBefore(mappings, marker, /* exclusive */ false, 2); expect(index).toEqual(2); }); it('should return the lowerIndex mapping index if there are multiple exact matches and we are not exclusive', () => { const marker5: SegmentMarker = {line: 0, column: 50, position: 50, next: undefined}; const marker4: SegmentMarker = {line: 0, column: 30, position: 30, next: marker5}; const marker3: SegmentMarker = {line: 0, column: 30, position: 30, next: marker4}; const marker2: SegmentMarker = {line: 0, column: 20, position: 20, next: marker3}; const marker1: SegmentMarker = {line: 0, column: 10, position: 10, next: marker2}; const mappings: Mapping[] = [marker1, marker2, marker3, marker4, marker5].map( (marker) => ({generatedSegment: marker}) as Mapping, ); const marker: SegmentMarker = {line: 0, column: 30, position: 30, next: undefined}; const index = findLastMappingIndexBefore(mappings, marker, /* exclusive */ false, 3); expect(index).toEqual(3); }); it('should return -1 if the segment marker is lower than the lowerIndex hint', () => { const marker5: SegmentMarker = {line: 0, column: 50, position: 50, next: undefined}; const marker4: SegmentMarker = {line: 0, column: 40, position: 40, next: marker5}; const marker3: SegmentMarker = {line: 0, column: 30, position: 30, next: marker4}; const marker2: SegmentMarker = {line: 0, column: 20, position: 20, next: marker3}; const marker1: SegmentMarker = {line: 0, column: 10, position: 10, next: marker2}; const mappings: Mapping[] = [marker1, marker2, marker3, marker4, marker5].map( (marker) => ({generatedSegment: marker}) as Mapping, ); const marker: SegmentMarker = {line: 0, column: 25, position: 25, next: undefined}; const index = findLastMappingIndexBefore(mappings, marker, /* exclusive */ false, 2); expect(index).toEqual(-1); }); it('should return -1 if the segment marker is equal to the lowerIndex hint and we are exclusive', () => { const marker5: SegmentMarker = {line: 0, column: 50, position: 50, next: undefined}; const marker4: SegmentMarker = {line: 0, column: 40, position: 40, next: marker5}; const marker3: SegmentMarker = {line: 0, column: 30, position: 30, next: marker4}; const marker2: SegmentMarker = {line: 0, column: 20, position: 20, next: marker3}; const marker1: SegmentMarker = {line: 0, column: 10, position: 10, next: marker2}; const mappings: Mapping[] = [marker1, marker2, marker3, marker4, marker5].map( (marker) => ({generatedSegment: marker}) as Mapping, ); const marker: SegmentMarker = {line: 0, column: 30, position: 30, next: undefined}; const index = findLastMappingIndexBefore(mappings, marker, /* exclusive */ true, 2); expect(index).toEqual(-1); }); }); });
{ "end_byte": 17854, "start_byte": 10961, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_spec.ts_17860_26028
describe('ensureOriginalSegmentLinks', () => { it('should add `next` properties to each segment that point to the next segment in the same source file', () => { const sourceA = new SourceFile(_('/foo/src/a.js'), 'abcdefg', null, [], fs); const sourceB = new SourceFile(_('/foo/src/b.js'), '1234567', null, [], fs); const rawSourceMap: RawSourceMap = { mappings: encode([ [ [0, 0, 0, 0], [2, 1, 0, 3], [4, 0, 0, 2], [5, 1, 0, 5], [6, 1, 0, 2], ], ]), names: [], sources: ['a.js', 'b.js'], version: 3, }; const mappings = parseMappings(rawSourceMap, [sourceA, sourceB], [0, 8]); ensureOriginalSegmentLinks(mappings); expect(mappings[0].originalSegment.next).toBe(mappings[2].originalSegment); expect(mappings[1].originalSegment.next).toBe(mappings[3].originalSegment); expect(mappings[2].originalSegment.next).toBeUndefined(); expect(mappings[3].originalSegment.next).toBeUndefined(); expect(mappings[4].originalSegment.next).toBe(mappings[1].originalSegment); }); }); describe('SourceFile', () => { describe('flattenedMappings', () => { it('should be an empty array for source files with no source map', () => { const sourceFile = new SourceFile(_('/foo/src/index.js'), 'index contents', null, [], fs); expect(sourceFile.flattenedMappings).toEqual([]); }); it('should be empty array for source files with no source map mappings', () => { const rawSourceMap: SourceMapInfo = { map: {mappings: '', names: [], sources: [], version: 3}, mapPath: null, origin: ContentOrigin.Provided, }; const sourceFile = new SourceFile( _('/foo/src/index.js'), 'index contents', rawSourceMap, [], fs, ); expect(sourceFile.flattenedMappings).toEqual([]); }); it('should be the same as non-flat mappings if there is only one level of source map', () => { const rawSourceMap: SourceMapInfo = { mapPath: null, map: { mappings: encode([ [ [0, 0, 0, 0], [6, 0, 0, 3], ], ]), names: [], sources: ['a.js'], version: 3, }, origin: ContentOrigin.Provided, }; const originalSource = new SourceFile(_('/foo/src/a.js'), 'abcdefg', null, [], fs); const sourceFile = new SourceFile( _('/foo/src/index.js'), 'abc123defg', rawSourceMap, [originalSource], fs, ); expect(removeOriginalSegmentLinks(sourceFile.flattenedMappings)).toEqual( parseMappings(rawSourceMap.map, [originalSource], [0, 11]), ); }); it('should merge mappings from flattened original source files', () => { const cSource = new SourceFile(_('/foo/src/c.js'), 'bcd123', null, [], fs); const dSource = new SourceFile(_('/foo/src/d.js'), 'aef', null, [], fs); const bSourceMap: SourceMapInfo = { mapPath: null, map: { mappings: encode([ [ [0, 1, 0, 0], [1, 0, 0, 0], [4, 1, 0, 1], ], ]), names: [], sources: ['c.js', 'd.js'], version: 3, }, origin: ContentOrigin.Provided, }; const bSource = new SourceFile( _('/foo/src/b.js'), 'abcdef', bSourceMap, [cSource, dSource], fs, ); const aSourceMap: SourceMapInfo = { mapPath: null, map: { mappings: encode([ [ [0, 0, 0, 0], [2, 0, 0, 3], [4, 0, 0, 2], [5, 0, 0, 5], ], ]), names: [], sources: ['b.js'], version: 3, }, origin: ContentOrigin.Provided, }; const aSource = new SourceFile(_('/foo/src/a.js'), 'abdecf', aSourceMap, [bSource], fs); expect(removeOriginalSegmentLinks(aSource.flattenedMappings)).toEqual([ { generatedSegment: {line: 0, column: 0, position: 0, next: undefined}, originalSource: dSource, originalSegment: {line: 0, column: 0, position: 0, next: undefined}, name: undefined, }, { generatedSegment: {line: 0, column: 1, position: 1, next: undefined}, originalSource: cSource, originalSegment: {line: 0, column: 0, position: 0, next: undefined}, name: undefined, }, { generatedSegment: {line: 0, column: 2, position: 2, next: undefined}, originalSource: cSource, originalSegment: {line: 0, column: 2, position: 2, next: undefined}, name: undefined, }, { generatedSegment: {line: 0, column: 3, position: 3, next: undefined}, originalSource: dSource, originalSegment: {line: 0, column: 1, position: 1, next: undefined}, name: undefined, }, { generatedSegment: {line: 0, column: 4, position: 4, next: undefined}, originalSource: cSource, originalSegment: {line: 0, column: 1, position: 1, next: undefined}, name: undefined, }, { generatedSegment: {line: 0, column: 5, position: 5, next: undefined}, originalSource: dSource, originalSegment: {line: 0, column: 2, position: 2, next: undefined}, name: undefined, }, ]); }); it('should ignore mappings to missing source files', () => { const bSourceMap: SourceMapInfo = { mapPath: null, map: { mappings: encode([ [ [1, 0, 0, 0], [4, 0, 0, 3], [4, 0, 0, 6], [5, 0, 0, 7], ], ]), names: [], sources: ['c.js'], version: 3, }, origin: ContentOrigin.Provided, }; const bSource = new SourceFile(_('/foo/src/b.js'), 'abcdef', bSourceMap, [null], fs); const aSourceMap: SourceMapInfo = { mapPath: null, map: { mappings: encode([ [ [0, 0, 0, 0], [2, 0, 0, 3], [4, 0, 0, 2], [5, 0, 0, 5], ], ]), names: [], sources: ['b.js'], version: 3, }, origin: ContentOrigin.Provided, }; const aSource = new SourceFile(_('/foo/src/a.js'), 'abdecf', aSourceMap, [bSource], fs); // These flattened mappings are just the mappings from a to b. // (The mappings to c are dropped since there is no source file to map // to.) expect(removeOriginalSegmentLinks(aSource.flattenedMappings)).toEqual( parseMappings(aSourceMap.map, [bSource], [0, 7]), ); }); /** * Clean out the links between original segments of each of the given `mappings`. * * @param mappings the mappings whose segments are to be cleaned. */ function removeOriginalSegmentLinks(mappings: Mapping[]) { for (const mapping of mappings) { mapping.originalSegment.next = undefined; } return mappings; } });
{ "end_byte": 26028, "start_byte": 17860, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_spec.ts_26036_32128
describe('renderFlattenedSourceMap()', () => { it('should convert the flattenedMappings into a raw source-map object', () => { const cSource = new SourceFile(_('/foo/src/c.js'), 'bcd123e', null, [], fs); const bToCSourceMap: SourceMapInfo = { mapPath: null, map: { mappings: encode([ [ [1, 0, 0, 0], [4, 0, 0, 3], [4, 0, 0, 6], [5, 0, 0, 7], ], ]), names: [], sources: ['c.js'], version: 3, }, origin: ContentOrigin.Provided, }; const bSource = new SourceFile( _('/foo/src/b.js'), 'abcdef', bToCSourceMap, [cSource], fs, ); const aToBSourceMap: SourceMapInfo = { mapPath: null, map: { mappings: encode([ [ [0, 0, 0, 0], [2, 0, 0, 3], [4, 0, 0, 2], [5, 0, 0, 5], ], ]), names: [], sources: ['b.js'], version: 3, }, origin: ContentOrigin.Provided, }; const aSource = new SourceFile( _('/foo/src/a.js'), 'abdecf', aToBSourceMap, [bSource], fs, ); const aTocSourceMap = aSource.renderFlattenedSourceMap(); expect(aTocSourceMap.version).toEqual(3); expect(aTocSourceMap.file).toEqual('a.js'); expect(aTocSourceMap.names).toEqual([]); expect(aTocSourceMap.sourceRoot).toBeUndefined(); expect(aTocSourceMap.sources).toEqual(['c.js']); expect(aTocSourceMap.sourcesContent).toEqual(['bcd123e']); expect(aTocSourceMap.mappings).toEqual( encode([ [ [1, 0, 0, 0], [2, 0, 0, 2], [3, 0, 0, 3], [3, 0, 0, 6], [4, 0, 0, 1], [5, 0, 0, 7], ], ]), ); }); it('should handle mappings that map from lines outside of the actual content lines', () => { const bSource = new SourceFile(_('/foo/src/b.js'), 'abcdef', null, [], fs); const aToBSourceMap: SourceMapInfo = { mapPath: null, map: { mappings: encode([ [ [0, 0, 0, 0], [2, 0, 0, 3], [4, 0, 0, 2], [5, 0, 0, 5], ], [ [0, 0, 0, 0], // Extra mapping from a non-existent line ], ]), names: [], sources: ['b.js'], version: 3, }, origin: ContentOrigin.Provided, }; const aSource = new SourceFile( _('/foo/src/a.js'), 'abdecf', aToBSourceMap, [bSource], fs, ); const aTocSourceMap = aSource.renderFlattenedSourceMap(); expect(aTocSourceMap.version).toEqual(3); expect(aTocSourceMap.file).toEqual('a.js'); expect(aTocSourceMap.names).toEqual([]); expect(aTocSourceMap.sourceRoot).toBeUndefined(); expect(aTocSourceMap.sources).toEqual(['b.js']); expect(aTocSourceMap.sourcesContent).toEqual(['abcdef']); expect(aTocSourceMap.mappings).toEqual(aToBSourceMap.map.mappings); }); it('should consolidate source-files with the same relative path', () => { const cSource1 = new SourceFile(_('/foo/src/lib/c.js'), 'bcd123e', null, [], fs); const cSource2 = new SourceFile(_('/foo/src/lib/c.js'), 'bcd123e', null, [], fs); const bToCSourceMap: SourceMapInfo = { mapPath: null, map: { mappings: encode([ [ [1, 0, 0, 0], [4, 0, 0, 3], [4, 0, 0, 6], [5, 0, 0, 7], ], ]), names: [], sources: ['c.js'], version: 3, }, origin: ContentOrigin.Provided, }; const bSource = new SourceFile( _('/foo/src/lib/b.js'), 'abcdef', bToCSourceMap, [cSource1], fs, ); const aToBCSourceMap: SourceMapInfo = { mapPath: null, map: { mappings: encode([ [ [0, 0, 0, 0], [2, 0, 0, 3], [4, 0, 0, 2], [5, 0, 0, 5], [6, 1, 0, 3], ], ]), names: [], sources: ['lib/b.js', 'lib/c.js'], version: 3, }, origin: ContentOrigin.Provided, }; const aSource = new SourceFile( _('/foo/src/a.js'), 'abdecf123', aToBCSourceMap, [bSource, cSource2], fs, ); const aTocSourceMap = aSource.renderFlattenedSourceMap(); expect(aTocSourceMap.version).toEqual(3); expect(aTocSourceMap.file).toEqual('a.js'); expect(aTocSourceMap.names).toEqual([]); expect(aTocSourceMap.sourceRoot).toBeUndefined(); expect(aTocSourceMap.sources).toEqual(['lib/c.js']); expect(aTocSourceMap.sourcesContent).toEqual(['bcd123e']); expect(aTocSourceMap.mappings).toEqual( encode([ [ [1, 0, 0, 0], [2, 0, 0, 2], [3, 0, 0, 3], [3, 0, 0, 6], [4, 0, 0, 1], [5, 0, 0, 7], [6, 0, 0, 3], ], ]), ); }); });
{ "end_byte": 32128, "start_byte": 26036, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_spec.ts_32136_35874
describe('getOriginalLocation()', () => { it('should return null for source files with no flattened mappings', () => { const sourceFile = new SourceFile(_('/foo/src/index.js'), 'index contents', null, [], fs); expect(sourceFile.getOriginalLocation(1, 1)).toEqual(null); }); it('should return offset locations in multiple flattened original source files', () => { const cSource = new SourceFile(_('/foo/src/c.js'), 'bcd123', null, [], fs); const dSource = new SourceFile(_('/foo/src/d.js'), 'aef', null, [], fs); const bSourceMap: SourceMapInfo = { mapPath: null, map: { mappings: encode([ [ [0, 1, 0, 0], // "a" is in d.js [source 1] [1, 0, 0, 0], // "bcd" are in c.js [source 0] [4, 1, 0, 1], // "ef" are in d.js [source 1] ], ]), names: [], sources: ['c.js', 'd.js'], version: 3, }, origin: ContentOrigin.Provided, }; const bSource = new SourceFile( _('/foo/src/b.js'), 'abcdef', bSourceMap, [cSource, dSource], fs, ); const aSourceMap: SourceMapInfo = { mapPath: null, map: { mappings: encode([ [ [0, 0, 0, 0], [2, 0, 0, 3], // "c" is missing from first line ], [ [4, 0, 0, 2], // second line has new indentation, and starts // with "c" [5, 0, 0, 5], // "f" is here ], ]), names: [], sources: ['b.js'], version: 3, }, origin: ContentOrigin.Provided, }; const aSource = new SourceFile( _('/foo/src/a.js'), 'abde\n cf', aSourceMap, [bSource], fs, ); // Line 0 expect(aSource.getOriginalLocation(0, 0)) // a .toEqual({file: dSource.sourcePath, line: 0, column: 0}); expect(aSource.getOriginalLocation(0, 1)) // b .toEqual({file: cSource.sourcePath, line: 0, column: 0}); expect(aSource.getOriginalLocation(0, 2)) // d .toEqual({file: cSource.sourcePath, line: 0, column: 2}); expect(aSource.getOriginalLocation(0, 3)) // e .toEqual({file: dSource.sourcePath, line: 0, column: 1}); expect(aSource.getOriginalLocation(0, 4)) // off the end of the line .toEqual({file: dSource.sourcePath, line: 0, column: 2}); // Line 1 expect(aSource.getOriginalLocation(1, 0)) // indent .toEqual({file: dSource.sourcePath, line: 0, column: 3}); expect(aSource.getOriginalLocation(1, 1)) // indent .toEqual({file: dSource.sourcePath, line: 0, column: 4}); expect(aSource.getOriginalLocation(1, 2)) // indent .toEqual({file: dSource.sourcePath, line: 0, column: 5}); expect(aSource.getOriginalLocation(1, 3)) // indent .toEqual({file: dSource.sourcePath, line: 0, column: 6}); expect(aSource.getOriginalLocation(1, 4)) // c .toEqual({file: cSource.sourcePath, line: 0, column: 1}); expect(aSource.getOriginalLocation(1, 5)) // f .toEqual({file: dSource.sourcePath, line: 0, column: 2}); expect(aSource.getOriginalLocation(1, 6)) // off the end of the line .toEqual({file: dSource.sourcePath, line: 0, column: 3}); });
{ "end_byte": 35874, "start_byte": 32136, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_spec.ts_35884_40812
it('should return offset locations across multiple lines', () => { const originalSource = new SourceFile( _('/foo/src/original.js'), 'abcdef\nghijk\nlmnop', null, [], fs, ); const generatedSourceMap: SourceMapInfo = { mapPath: null, map: { mappings: encode([ [ [0, 0, 0, 0], // "ABC" [0,0] => [0,0] ], [ [0, 0, 1, 0], // "GHIJ" [1, 0] => [1,0] [4, 0, 0, 3], // "DEF" [1, 4] => [0,3] [7, 0, 1, 4], // "K" [1, 7] => [1,4] ], [ [0, 0, 2, 0], // "LMNOP" [2,0] => [2,0] ], ]), names: [], sources: ['original.js'], version: 3, }, origin: ContentOrigin.Provided, }; const generatedSource = new SourceFile( _('/foo/src/generated.js'), 'ABC\nGHIJDEFK\nLMNOP', generatedSourceMap, [originalSource], fs, ); // Line 0 expect(generatedSource.getOriginalLocation(0, 0)) // A .toEqual({file: originalSource.sourcePath, line: 0, column: 0}); expect(generatedSource.getOriginalLocation(0, 1)) // B .toEqual({file: originalSource.sourcePath, line: 0, column: 1}); expect(generatedSource.getOriginalLocation(0, 2)) // C .toEqual({file: originalSource.sourcePath, line: 0, column: 2}); expect(generatedSource.getOriginalLocation(0, 3)) // off the end of line 0 .toEqual({file: originalSource.sourcePath, line: 0, column: 3}); // Line 1 expect(generatedSource.getOriginalLocation(1, 0)) // G .toEqual({file: originalSource.sourcePath, line: 1, column: 0}); expect(generatedSource.getOriginalLocation(1, 1)) // H .toEqual({file: originalSource.sourcePath, line: 1, column: 1}); expect(generatedSource.getOriginalLocation(1, 2)) // I .toEqual({file: originalSource.sourcePath, line: 1, column: 2}); expect(generatedSource.getOriginalLocation(1, 3)) // J .toEqual({file: originalSource.sourcePath, line: 1, column: 3}); expect(generatedSource.getOriginalLocation(1, 4)) // D .toEqual({file: originalSource.sourcePath, line: 0, column: 3}); expect(generatedSource.getOriginalLocation(1, 5)) // E .toEqual({file: originalSource.sourcePath, line: 0, column: 4}); expect(generatedSource.getOriginalLocation(1, 6)) // F .toEqual({file: originalSource.sourcePath, line: 0, column: 5}); expect(generatedSource.getOriginalLocation(1, 7)) // K .toEqual({file: originalSource.sourcePath, line: 1, column: 4}); expect(generatedSource.getOriginalLocation(1, 8)) // off the end of line 1 .toEqual({file: originalSource.sourcePath, line: 1, column: 5}); // Line 2 expect(generatedSource.getOriginalLocation(2, 0)) // L .toEqual({file: originalSource.sourcePath, line: 2, column: 0}); expect(generatedSource.getOriginalLocation(2, 1)) // M .toEqual({file: originalSource.sourcePath, line: 2, column: 1}); expect(generatedSource.getOriginalLocation(2, 2)) // N .toEqual({file: originalSource.sourcePath, line: 2, column: 2}); expect(generatedSource.getOriginalLocation(2, 3)) // O .toEqual({file: originalSource.sourcePath, line: 2, column: 3}); expect(generatedSource.getOriginalLocation(2, 4)) // P .toEqual({file: originalSource.sourcePath, line: 2, column: 4}); expect(generatedSource.getOriginalLocation(2, 5)) // off the end of line 2 .toEqual({file: originalSource.sourcePath, line: 2, column: 5}); }); }); }); describe('computeStartOfLinePositions()', () => { it('should compute the cumulative length of each line in the given string', () => { expect(computeStartOfLinePositions('')).toEqual([0]); expect(computeStartOfLinePositions('abc')).toEqual([0]); expect(computeStartOfLinePositions('\n')).toEqual([0, 1]); expect(computeStartOfLinePositions('\n\n')).toEqual([0, 1, 2]); expect(computeStartOfLinePositions('abc\n')).toEqual([0, 4]); expect(computeStartOfLinePositions('\nabc')).toEqual([0, 1]); expect(computeStartOfLinePositions('abc\ndefg')).toEqual([0, 4]); expect(computeStartOfLinePositions('abc\r\n')).toEqual([0, 5]); expect(computeStartOfLinePositions('abc\r\ndefg')).toEqual([0, 5]); expect(computeStartOfLinePositions('abc\uD83D\uDE80\ndef🚀\r\n')).toEqual([0, 6, 13]); }); }); }); });
{ "end_byte": 40812, "start_byte": 35884, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/test/source_file_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/test/segment_marker_spec.ts_0_5819
/** * @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 {compareSegments, offsetSegment} from '../src/segment_marker'; import {computeStartOfLinePositions} from '../src/source_file'; describe('SegmentMarker utils', () => { describe('compareSegments()', () => { it('should return 0 if the segments are the same', () => { expect( compareSegments( {line: 0, column: 0, position: 0, next: undefined}, {line: 0, column: 0, position: 0, next: undefined}, ), ).toEqual(0); expect( compareSegments( {line: 123, column: 0, position: 200, next: undefined}, {line: 123, column: 0, position: 200, next: undefined}, ), ).toEqual(0); expect( compareSegments( {line: 0, column: 45, position: 45, next: undefined}, {line: 0, column: 45, position: 45, next: undefined}, ), ).toEqual(0); expect( compareSegments( {line: 123, column: 45, position: 245, next: undefined}, {line: 123, column: 45, position: 245, next: undefined}, ), ).toEqual(0); }); it('should return a negative number if the first segment is before the second segment', () => { expect( compareSegments( {line: 0, column: 0, position: 0, next: undefined}, {line: 0, column: 45, position: 45, next: undefined}, ), ).toBeLessThan(0); expect( compareSegments( {line: 123, column: 0, position: 200, next: undefined}, {line: 123, column: 45, position: 245, next: undefined}, ), ).toBeLessThan(0); expect( compareSegments( {line: 13, column: 45, position: 75, next: undefined}, {line: 123, column: 45, position: 245, next: undefined}, ), ).toBeLessThan(0); expect( compareSegments( {line: 13, column: 45, position: 75, next: undefined}, {line: 123, column: 9, position: 209, next: undefined}, ), ).toBeLessThan(0); }); it('should return a positive number if the first segment is after the second segment', () => { expect( compareSegments( {line: 0, column: 45, position: 45, next: undefined}, {line: 0, column: 0, position: 0, next: undefined}, ), ).toBeGreaterThan(0); expect( compareSegments( {line: 123, column: 45, position: 245, next: undefined}, {line: 123, column: 0, position: 200, next: undefined}, ), ).toBeGreaterThan(0); expect( compareSegments( {line: 123, column: 45, position: 245, next: undefined}, {line: 13, column: 45, position: 75, next: undefined}, ), ).toBeGreaterThan(0); expect( compareSegments( {line: 123, column: 9, position: 209, next: undefined}, {line: 13, column: 45, position: 75, next: undefined}, ), ).toBeGreaterThan(0); }); }); describe('offsetSegment()', () => { it('should return an identical marker if offset is 0', () => { const startOfLinePositions = computeStartOfLinePositions( '012345\n0123456789\r\n012*4567\n0123456', ); const marker = {line: 2, column: 3, position: 20, next: undefined}; expect(offsetSegment(startOfLinePositions, marker, 0)).toBe(marker); }); it('should return a new marker offset by the given chars', () => { const startOfLinePositions = computeStartOfLinePositions( '012345\n0123456789\r\n012*4567\n0123456', ); const marker = {line: 2, column: 3, position: 22, next: undefined}; expect(offsetSegment(startOfLinePositions, marker, 1)).toEqual({ line: 2, column: 4, position: 23, next: undefined, }); expect(offsetSegment(startOfLinePositions, marker, 2)).toEqual({ line: 2, column: 5, position: 24, next: undefined, }); expect(offsetSegment(startOfLinePositions, marker, 4)).toEqual({ line: 2, column: 7, position: 26, next: undefined, }); expect(offsetSegment(startOfLinePositions, marker, 6)).toEqual({ line: 3, column: 0, position: 28, next: undefined, }); expect(offsetSegment(startOfLinePositions, marker, 8)).toEqual({ line: 3, column: 2, position: 30, next: undefined, }); expect(offsetSegment(startOfLinePositions, marker, 20)).toEqual({ line: 3, column: 14, position: 42, next: undefined, }); expect(offsetSegment(startOfLinePositions, marker, -1)).toEqual({ line: 2, column: 2, position: 21, next: undefined, }); expect(offsetSegment(startOfLinePositions, marker, -2)).toEqual({ line: 2, column: 1, position: 20, next: undefined, }); expect(offsetSegment(startOfLinePositions, marker, -3)).toEqual({ line: 2, column: 0, position: 19, next: undefined, }); expect(offsetSegment(startOfLinePositions, marker, -4)).toEqual({ line: 1, column: 11, position: 18, next: undefined, }); expect(offsetSegment(startOfLinePositions, marker, -6)).toEqual({ line: 1, column: 9, position: 16, next: undefined, }); expect(offsetSegment(startOfLinePositions, marker, -16)).toEqual({ line: 0, column: 6, position: 6, next: undefined, }); }); }); });
{ "end_byte": 5819, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/test/segment_marker_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/test/BUILD.bazel_0_741
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/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/logging/testing", "//packages/compiler-cli/src/ngtsc/sourcemaps", "@npm//@jridgewell/sourcemap-codec", "@npm//@types/convert-source-map", "@npm//convert-source-map", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], deps = [ ":test_lib", ], )
{ "end_byte": 741, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/test/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/src/content_origin.ts_0_1104
/** * @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 */ /** * From where the content for a source file or source-map came. * * - Source files can be linked to source-maps by: * - providing the content inline via a base64 encoded data comment, * - providing a URL to the file path in a comment, * - the loader inferring the source-map path from the source file path. * - Source-maps can link to source files by: * - providing the content inline in the `sourcesContent` property * - providing the path to the file in the `sources` property */ export enum ContentOrigin { /** * The contents were provided programmatically when calling `loadSourceFile()`. */ Provided, /** * The contents were extracted directly form the contents of the referring file. */ Inline, /** * The contents were loaded from the file-system, after being explicitly referenced or inferred * from the referring file. */ FileSystem, }
{ "end_byte": 1104, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/src/content_origin.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file.ts_0_740
/** * @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 {decode, encode, SourceMapMappings, SourceMapSegment} from '@jridgewell/sourcemap-codec'; import mapHelpers from 'convert-source-map'; import {AbsoluteFsPath, PathManipulation} from '../../file_system'; import {RawSourceMap, SourceMapInfo} from './raw_source_map'; import {compareSegments, offsetSegment, SegmentMarker} from './segment_marker'; export function removeSourceMapComments(contents: string): string { return mapHelpers .removeMapFileComments(mapHelpers.removeComments(contents)) .replace(/\n\n$/, '\n'); }
{ "end_byte": 740, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file.ts_742_8605
export class SourceFile { /** * The parsed mappings that have been flattened so that any intermediate source mappings have been * flattened. * * The result is that any source file mentioned in the flattened mappings have no source map (are * pure original source files). */ readonly flattenedMappings: Mapping[]; readonly startOfLinePositions: number[]; constructor( /** The path to this source file. */ readonly sourcePath: AbsoluteFsPath, /** The contents of this source file. */ readonly contents: string, /** The raw source map (if any) referenced by this source file. */ readonly rawMap: SourceMapInfo | null, /** Any source files referenced by the raw source map associated with this source file. */ readonly sources: (SourceFile | null)[], private fs: PathManipulation, ) { this.contents = removeSourceMapComments(contents); this.startOfLinePositions = computeStartOfLinePositions(this.contents); this.flattenedMappings = this.flattenMappings(); } /** * Render the raw source map generated from the flattened mappings. */ renderFlattenedSourceMap(): RawSourceMap { const sources = new IndexedMap<string, string>(); const names = new IndexedSet<string>(); const mappings: SourceMapMappings = []; const sourcePathDir = this.fs.dirname(this.sourcePath); // Computing the relative path can be expensive, and we are likely to have the same path for // many (if not all!) mappings. const relativeSourcePathCache = new Cache<string, string>((input) => this.fs.relative(sourcePathDir, input), ); for (const mapping of this.flattenedMappings) { const sourceIndex = sources.set( relativeSourcePathCache.get(mapping.originalSource.sourcePath), mapping.originalSource.contents, ); const mappingArray: SourceMapSegment = [ mapping.generatedSegment.column, sourceIndex, mapping.originalSegment.line, mapping.originalSegment.column, ]; if (mapping.name !== undefined) { const nameIndex = names.add(mapping.name); mappingArray.push(nameIndex); } // Ensure a mapping line array for this mapping. const line = mapping.generatedSegment.line; while (line >= mappings.length) { mappings.push([]); } // Add this mapping to the line mappings[line].push(mappingArray); } const sourceMap: RawSourceMap = { version: 3, file: this.fs.relative(sourcePathDir, this.sourcePath), sources: sources.keys, names: names.values, mappings: encode(mappings), sourcesContent: sources.values, }; return sourceMap; } /** * Find the original mapped location for the given `line` and `column` in the generated file. * * First we search for a mapping whose generated segment is at or directly before the given * location. Then we compute the offset between the given location and the matching generated * segment. Finally we apply this offset to the original source segment to get the desired * original location. */ getOriginalLocation( line: number, column: number, ): {file: AbsoluteFsPath; line: number; column: number} | null { if (this.flattenedMappings.length === 0) { return null; } let position: number; if (line < this.startOfLinePositions.length) { position = this.startOfLinePositions[line] + column; } else { // The line is off the end of the file, so just assume we are at the end of the file. position = this.contents.length; } const locationSegment: SegmentMarker = {line, column, position, next: undefined}; let mappingIndex = findLastMappingIndexBefore( this.flattenedMappings, locationSegment, false, 0, ); if (mappingIndex < 0) { mappingIndex = 0; } const {originalSegment, originalSource, generatedSegment} = this.flattenedMappings[mappingIndex]; const offset = locationSegment.position - generatedSegment.position; const offsetOriginalSegment = offsetSegment( originalSource.startOfLinePositions, originalSegment, offset, ); return { file: originalSource.sourcePath, line: offsetOriginalSegment.line, column: offsetOriginalSegment.column, }; } /** * Flatten the parsed mappings for this source file, so that all the mappings are to pure original * source files with no transitive source maps. */ private flattenMappings(): Mapping[] { const mappings = parseMappings( this.rawMap && this.rawMap.map, this.sources, this.startOfLinePositions, ); ensureOriginalSegmentLinks(mappings); const flattenedMappings: Mapping[] = []; for (let mappingIndex = 0; mappingIndex < mappings.length; mappingIndex++) { const aToBmapping = mappings[mappingIndex]; const bSource = aToBmapping.originalSource; if (bSource.flattenedMappings.length === 0) { // The b source file has no mappings of its own (i.e. it is a pure original file) // so just use the mapping as-is. flattenedMappings.push(aToBmapping); continue; } // The `incomingStart` and `incomingEnd` are the `SegmentMarker`s in `B` that represent the // section of `B` source file that is being mapped to by the current `aToBmapping`. // // For example, consider the mappings from A to B: // // src A src B mapping // // a ----- a [0, 0] // b b // f - /- c [4, 2] // g \ / d // c -/\ e // d \- f [2, 5] // e // // For mapping [0,0] the incoming start and end are 0 and 2 (i.e. the range a, b, c) // For mapping [4,2] the incoming start and end are 2 and 5 (i.e. the range c, d, e, f) // const incomingStart = aToBmapping.originalSegment; const incomingEnd = incomingStart.next; // The `outgoingStartIndex` and `outgoingEndIndex` are the indices of the range of mappings // that leave `b` that we are interested in merging with the aToBmapping. // We actually care about all the markers from the last bToCmapping directly before the // `incomingStart` to the last bToCmaping directly before the `incomingEnd`, inclusive. // // For example, if we consider the range 2 to 5 from above (i.e. c, d, e, f) with the // following mappings from B to C: // // src B src C mapping // a // b ----- b [1, 0] // - c c // | d d // | e ----- 1 [4, 3] // - f \ 2 // \ 3 // \- e [4, 6] // // The range with `incomingStart` at 2 and `incomingEnd` at 5 has outgoing start mapping of // [1,0] and outgoing end mapping of [4, 6], which also includes [4, 3]. // let outgoingStartIndex = findLastMappingIndexBefore( bSource.flattenedMappings, incomingStart, false, 0, ); if (outgoingStartIndex < 0) { outgoingStartIndex = 0; } const outgoingEndIndex = incomingEnd !== undefined ? findLastMappingIndexBefore( bSource.flattenedMappings, incomingEnd, true, outgoingStartIndex, ) : bSource.flattenedMappings.length - 1; for ( let bToCmappingIndex = outgoingStartIndex; bToCmappingIndex <= outgoingEndIndex; bToCmappingIndex++ ) { const bToCmapping: Mapping = bSource.flattenedMappings[bToCmappingIndex]; flattenedMappings.push(mergeMappings(this, aToBmapping, bToCmapping)); } } return flattenedMappings; } }
{ "end_byte": 8605, "start_byte": 742, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file.ts_8607_16567
/** * * @param mappings The collection of mappings whose segment-markers we are searching. * @param marker The segment-marker to match against those of the given `mappings`. * @param exclusive If exclusive then we must find a mapping with a segment-marker that is * exclusively earlier than the given `marker`. * If not exclusive then we can return the highest mappings with an equivalent segment-marker to the * given `marker`. * @param lowerIndex If provided, this is used as a hint that the marker we are searching for has an * index that is no lower than this. */ export function findLastMappingIndexBefore( mappings: Mapping[], marker: SegmentMarker, exclusive: boolean, lowerIndex: number, ): number { let upperIndex = mappings.length - 1; const test = exclusive ? -1 : 0; if (compareSegments(mappings[lowerIndex].generatedSegment, marker) > test) { // Exit early since the marker is outside the allowed range of mappings. return -1; } let matchingIndex = -1; while (lowerIndex <= upperIndex) { const index = (upperIndex + lowerIndex) >> 1; if (compareSegments(mappings[index].generatedSegment, marker) <= test) { matchingIndex = index; lowerIndex = index + 1; } else { upperIndex = index - 1; } } return matchingIndex; } /** * A Mapping consists of two segment markers: one in the generated source and one in the original * source, which indicate the start of each segment. The end of a segment is indicated by the first * segment marker of another mapping whose start is greater or equal to this one. * * It may also include a name associated with the segment being mapped. */ export interface Mapping { readonly generatedSegment: SegmentMarker; readonly originalSource: SourceFile; readonly originalSegment: SegmentMarker; readonly name?: string; } /** * Merge two mappings that go from A to B and B to C, to result in a mapping that goes from A to C. */ export function mergeMappings(generatedSource: SourceFile, ab: Mapping, bc: Mapping): Mapping { const name = bc.name || ab.name; // We need to modify the segment-markers of the new mapping to take into account the shifts that // occur due to the combination of the two mappings. // For example: // * Simple map where the B->C starts at the same place the A->B ends: // // ``` // A: 1 2 b c d // | A->B [2,0] // | | // B: b c d A->C [2,1] // | | // | B->C [0,1] // C: a b c d e // ``` // * More complicated case where diffs of segment-markers is needed: // // ``` // A: b 1 2 c d // \ // | A->B [0,1*] [0,1*] // | | |+3 // B: a b 1 2 c d A->C [0,1] [3,2] // | / |+1 | // | / B->C [0*,0] [4*,2] // | / // C: a b c d e // ``` // // `[0,1]` mapping from A->C: // The difference between the "original segment-marker" of A->B (1*) and the "generated // segment-marker of B->C (0*): `1 - 0 = +1`. // Since it is positive we must increment the "original segment-marker" with `1` to give [0,1]. // // `[3,2]` mapping from A->C: // The difference between the "original segment-marker" of A->B (1*) and the "generated // segment-marker" of B->C (4*): `1 - 4 = -3`. // Since it is negative we must increment the "generated segment-marker" with `3` to give [3,2]. const diff = compareSegments(bc.generatedSegment, ab.originalSegment); if (diff > 0) { return { name, generatedSegment: offsetSegment( generatedSource.startOfLinePositions, ab.generatedSegment, diff, ), originalSource: bc.originalSource, originalSegment: bc.originalSegment, }; } else { return { name, generatedSegment: ab.generatedSegment, originalSource: bc.originalSource, originalSegment: offsetSegment( bc.originalSource.startOfLinePositions, bc.originalSegment, -diff, ), }; } } /** * Parse the `rawMappings` into an array of parsed mappings, which reference source-files provided * in the `sources` parameter. */ export function parseMappings( rawMap: RawSourceMap | null, sources: (SourceFile | null)[], generatedSourceStartOfLinePositions: number[], ): Mapping[] { if (rawMap === null) { return []; } const rawMappings = decode(rawMap.mappings); if (rawMappings === null) { return []; } const mappings: Mapping[] = []; for (let generatedLine = 0; generatedLine < rawMappings.length; generatedLine++) { const generatedLineMappings = rawMappings[generatedLine]; for (const rawMapping of generatedLineMappings) { if (rawMapping.length >= 4) { const originalSource = sources[rawMapping[1]!]; if (originalSource === null || originalSource === undefined) { // the original source is missing so ignore this mapping continue; } const generatedColumn = rawMapping[0]; const name = rawMapping.length === 5 ? rawMap.names[rawMapping[4]] : undefined; const line = rawMapping[2]!; const column = rawMapping[3]!; const generatedSegment: SegmentMarker = { line: generatedLine, column: generatedColumn, position: generatedSourceStartOfLinePositions[generatedLine] + generatedColumn, next: undefined, }; const originalSegment: SegmentMarker = { line, column, position: originalSource.startOfLinePositions[line] + column, next: undefined, }; mappings.push({name, generatedSegment, originalSegment, originalSource}); } } } return mappings; } /** * Extract the segment markers from the original source files in each mapping of an array of * `mappings`. * * @param mappings The mappings whose original segments we want to extract * @returns Return a map from original source-files (referenced in the `mappings`) to arrays of * segment-markers sorted by their order in their source file. */ export function extractOriginalSegments(mappings: Mapping[]): Map<SourceFile, SegmentMarker[]> { const originalSegments = new Map<SourceFile, SegmentMarker[]>(); for (const mapping of mappings) { const originalSource = mapping.originalSource; if (!originalSegments.has(originalSource)) { originalSegments.set(originalSource, []); } const segments = originalSegments.get(originalSource)!; segments.push(mapping.originalSegment); } originalSegments.forEach((segmentMarkers) => segmentMarkers.sort(compareSegments)); return originalSegments; } /** * Update the original segments of each of the given `mappings` to include a link to the next * segment in the source file. * * @param mappings the mappings whose segments should be updated */ export function ensureOriginalSegmentLinks(mappings: Mapping[]): void { const segmentsBySource = extractOriginalSegments(mappings); segmentsBySource.forEach((markers) => { for (let i = 0; i < markers.length - 1; i++) { markers[i].next = markers[i + 1]; } }); } export function computeStartOfLinePositions(str: string) { // The `1` is to indicate a newline character between the lines. // Note that in the actual contents there could be more than one character that indicates a // newline // - e.g. \r\n - but that is not important here since segment-markers are in line/column pairs and // so differences in length due to extra `\r` characters do not affect the algorithms. const NEWLINE_MARKER_OFFSET = 1; const lineLengths = computeLineLengths(str); const startPositions = [0]; // First line starts at position 0 for (let i = 0; i < lineLengths.length - 1; i++) { startPositions.push(startPositions[i] + lineLengths[i] + NEWLINE_MARKER_OFFSET); } return startPositions; }
{ "end_byte": 16567, "start_byte": 8607, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file.ts_16569_19446
function computeLineLengths(str: string): number[] { return str.split(/\n/).map((s) => s.length); } /** * A collection of mappings between `keys` and `values` stored in the order in which the keys are * first seen. * * The difference between this and a standard `Map` is that when you add a key-value pair the index * of the `key` is returned. */ class IndexedMap<K, V> { private map = new Map<K, number>(); /** * An array of keys added to this map. * * This array is guaranteed to be in the order of the first time the key was added to the map. */ readonly keys: K[] = []; /** * An array of values added to this map. * * This array is guaranteed to be in the order of the first time the associated key was added to * the map. */ readonly values: V[] = []; /** * Associate the `value` with the `key` and return the index of the key in the collection. * * If the `key` already exists then the `value` is not set and the index of that `key` is * returned; otherwise the `key` and `value` are stored and the index of the new `key` is * returned. * * @param key the key to associated with the `value`. * @param value the value to associated with the `key`. * @returns the index of the `key` in the `keys` array. */ set(key: K, value: V): number { if (this.map.has(key)) { return this.map.get(key)!; } const index = this.values.push(value) - 1; this.keys.push(key); this.map.set(key, index); return index; } } /** * A collection of `values` stored in the order in which they were added. * * The difference between this and a standard `Set` is that when you add a value the index of that * item is returned. */ class IndexedSet<V> { private map = new Map<V, number>(); /** * An array of values added to this set. * This array is guaranteed to be in the order of the first time the value was added to the set. */ readonly values: V[] = []; /** * Add the `value` to the `values` array, if it doesn't already exist; returning the index of the * `value` in the `values` array. * * If the `value` already exists then the index of that `value` is returned, otherwise the new * `value` is stored and the new index returned. * * @param value the value to add to the set. * @returns the index of the `value` in the `values` array. */ add(value: V): number { if (this.map.has(value)) { return this.map.get(value)!; } const index = this.values.push(value) - 1; this.map.set(value, index); return index; } } class Cache<Input, Cached> { private map = new Map<Input, Cached>(); constructor(private computeFn: (input: Input) => Cached) {} get(input: Input): Cached { if (!this.map.has(input)) { this.map.set(input, this.computeFn(input)); } return this.map.get(input)!; } }
{ "end_byte": 19446, "start_byte": 16569, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/src/segment_marker.ts_0_1773
/** * @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 */ /** * A marker that indicates the start of a segment in a mapping. * * The end of a segment is indicated by the first segment-marker of another mapping whose start * is greater or equal to this one. */ export interface SegmentMarker { readonly line: number; readonly column: number; readonly position: number; next: SegmentMarker | undefined; } /** * Compare two segment-markers, for use in a search or sorting algorithm. * * @returns a positive number if `a` is after `b`, a negative number if `b` is after `a` * and zero if they are at the same position. */ export function compareSegments(a: SegmentMarker, b: SegmentMarker): number { return a.position - b.position; } /** * Return a new segment-marker that is offset by the given number of characters. * * @param startOfLinePositions the position of the start of each line of content of the source file * whose segment-marker we are offsetting. * @param marker the segment to offset. * @param offset the number of character to offset by. */ export function offsetSegment( startOfLinePositions: number[], marker: SegmentMarker, offset: number, ): SegmentMarker { if (offset === 0) { return marker; } let line = marker.line; const position = marker.position + offset; while (line < startOfLinePositions.length - 1 && startOfLinePositions[line + 1] <= position) { line++; } while (line > 0 && startOfLinePositions[line] > position) { line--; } const column = position - startOfLinePositions[line]; return {line, column, position, next: undefined}; }
{ "end_byte": 1773, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/src/segment_marker.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/src/raw_source_map.ts_0_1061
/** * @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 {AbsoluteFsPath} from '../../file_system'; import {ContentOrigin} from './content_origin'; /** * This interface is the basic structure of the JSON in a raw source map that one might load from * disk. */ export interface RawSourceMap { version: number | string; file?: string; sourceRoot?: string; sources: string[]; names: string[]; sourcesContent?: (string | null)[]; mappings: string; } /** * The path and content of a source-map. */ export interface MapAndPath { /** The path to the source map if it was external or `null` if it was inline. */ mapPath: AbsoluteFsPath | null; /** The raw source map itself. */ map: RawSourceMap; } /** * Information about a loaded source-map. */ export interface SourceMapInfo extends MapAndPath { /** From where the content for this source-map came. */ origin: ContentOrigin; }
{ "end_byte": 1061, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/src/raw_source_map.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file_loader.ts_0_1027
/** * @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 mapHelpers from 'convert-source-map'; import {AbsoluteFsPath, ReadonlyFileSystem} from '../../file_system'; import {Logger} from '../../logging'; import {ContentOrigin} from './content_origin'; import {MapAndPath, RawSourceMap, SourceMapInfo} from './raw_source_map'; import {SourceFile} from './source_file'; const SCHEME_MATCHER = /^([a-z][a-z0-9.-]*):\/\//i; /** * This class can be used to load a source file, its associated source map and any upstream sources. * * Since a source file might reference (or include) a source map, this class can load those too. * Since a source map might reference other source files, these are also loaded as needed. * * This is done recursively. The result is a "tree" of `SourceFile` objects, each containing * mappings to other `SourceFile` objects as necessary. */
{ "end_byte": 1027, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file_loader.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file_loader.ts_1028_9444
export class SourceFileLoader { private currentPaths: AbsoluteFsPath[] = []; constructor( private fs: ReadonlyFileSystem, private logger: Logger, /** A map of URL schemes to base paths. The scheme name should be lowercase. */ private schemeMap: Record<string, AbsoluteFsPath>, ) {} /** * Load a source file from the provided content and source map, and recursively load any * referenced source files. * * @param sourcePath The path to the source file to load. * @param contents The contents of the source file to load. * @param mapAndPath The raw source-map and the path to the source-map file. * @returns a SourceFile object created from the `contents` and provided source-map info. */ loadSourceFile(sourcePath: AbsoluteFsPath, contents: string, mapAndPath: MapAndPath): SourceFile; /** * Load a source file from the provided content, compute its source map, and recursively load any * referenced source files. * * @param sourcePath The path to the source file to load. * @param contents The contents of the source file to load. * @returns a SourceFile object created from the `contents` and computed source-map info. */ loadSourceFile(sourcePath: AbsoluteFsPath, contents: string): SourceFile; /** * Load a source file from the file-system, compute its source map, and recursively load any * referenced source files. * * @param sourcePath The path to the source file to load. * @returns a SourceFile object if its contents could be loaded from disk, or null otherwise. */ loadSourceFile(sourcePath: AbsoluteFsPath): SourceFile | null; loadSourceFile( sourcePath: AbsoluteFsPath, contents: string | null = null, mapAndPath: MapAndPath | null = null, ): SourceFile | null { const contentsOrigin = contents !== null ? ContentOrigin.Provided : ContentOrigin.FileSystem; const sourceMapInfo: SourceMapInfo | null = mapAndPath && { origin: ContentOrigin.Provided, ...mapAndPath, }; return this.loadSourceFileInternal(sourcePath, contents, contentsOrigin, sourceMapInfo); } /** * The overload used internally to load source files referenced in a source-map. * * In this case there is no guarantee that it will return a non-null SourceMap. * * @param sourcePath The path to the source file to load. * @param contents The contents of the source file to load, if provided inline. If `null`, * the contents will be read from the file at the `sourcePath`. * @param sourceOrigin Describes where the source content came from. * @param sourceMapInfo The raw contents and path of the source-map file. If `null` the * source-map will be computed from the contents of the source file, either inline or loaded * from the file-system. * * @returns a SourceFile if the content for one was provided or was able to be loaded from disk, * `null` otherwise. */ private loadSourceFileInternal( sourcePath: AbsoluteFsPath, contents: string | null, sourceOrigin: ContentOrigin, sourceMapInfo: SourceMapInfo | null, ): SourceFile | null { const previousPaths = this.currentPaths.slice(); try { if (contents === null) { if (!this.fs.exists(sourcePath)) { return null; } contents = this.readSourceFile(sourcePath); } // If not provided try to load the source map based on the source itself if (sourceMapInfo === null) { sourceMapInfo = this.loadSourceMap(sourcePath, contents, sourceOrigin); } let sources: (SourceFile | null)[] = []; if (sourceMapInfo !== null) { const basePath = sourceMapInfo.mapPath || sourcePath; sources = this.processSources(basePath, sourceMapInfo); } return new SourceFile(sourcePath, contents, sourceMapInfo, sources, this.fs); } catch (e) { this.logger.warn( `Unable to fully load ${sourcePath} for source-map flattening: ${(e as Error).message}`, ); return null; } finally { // We are finished with this recursion so revert the paths being tracked this.currentPaths = previousPaths; } } /** * Find the source map associated with the source file whose `sourcePath` and `contents` are * provided. * * Source maps can be inline, as part of a base64 encoded comment, or external as a separate file * whose path is indicated in a comment or implied from the name of the source file itself. * * @param sourcePath the path to the source file. * @param sourceContents the contents of the source file. * @param sourceOrigin where the content of the source file came from. * @returns the parsed contents and path of the source-map, if loading was successful, null * otherwise. */ private loadSourceMap( sourcePath: AbsoluteFsPath, sourceContents: string, sourceOrigin: ContentOrigin, ): SourceMapInfo | null { // Only consider a source-map comment from the last non-empty line of the file, in case there // are embedded source-map comments elsewhere in the file (as can be the case with bundlers like // webpack). const lastLine = this.getLastNonEmptyLine(sourceContents); const inline = mapHelpers.commentRegex.exec(lastLine); if (inline !== null) { return { map: mapHelpers.fromComment(inline.pop()!).sourcemap, mapPath: null, origin: ContentOrigin.Inline, }; } if (sourceOrigin === ContentOrigin.Inline) { // The source file was provided inline and its contents did not include an inline source-map. // So we don't try to load an external source-map from the file-system, since this can lead to // invalid circular dependencies. return null; } const external = mapHelpers.mapFileCommentRegex.exec(lastLine); if (external) { try { const fileName = external[1] || external[2]; const externalMapPath = this.fs.resolve(this.fs.dirname(sourcePath), fileName); return { map: this.readRawSourceMap(externalMapPath), mapPath: externalMapPath, origin: ContentOrigin.FileSystem, }; } catch (e) { this.logger.warn( `Unable to fully load ${sourcePath} for source-map flattening: ${(e as Error).message}`, ); return null; } } const impliedMapPath = this.fs.resolve(sourcePath + '.map'); if (this.fs.exists(impliedMapPath)) { return { map: this.readRawSourceMap(impliedMapPath), mapPath: impliedMapPath, origin: ContentOrigin.FileSystem, }; } return null; } /** * Iterate over each of the "sources" for this source file's source map, recursively loading each * source file and its associated source map. */ private processSources( basePath: AbsoluteFsPath, {map, origin: sourceMapOrigin}: SourceMapInfo, ): (SourceFile | null)[] { const sourceRoot = this.fs.resolve( this.fs.dirname(basePath), this.replaceSchemeWithPath(map.sourceRoot || ''), ); return map.sources.map((source, index) => { const path = this.fs.resolve(sourceRoot, this.replaceSchemeWithPath(source)); const content = (map.sourcesContent && map.sourcesContent[index]) || null; // The origin of this source file is "inline" if we extracted it from the source-map's // `sourcesContent`, except when the source-map itself was "provided" in-memory. // An inline source file is treated as if it were from the file-system if the source-map that // contains it was provided in-memory. The first call to `loadSourceFile()` is special in that // if you "provide" the contents of the source-map in-memory then we don't want to block // loading sources from the file-system just because this source-map had an inline source. const sourceOrigin = content !== null && sourceMapOrigin !== ContentOrigin.Provided ? ContentOrigin.Inline : ContentOrigin.FileSystem; return this.loadSourceFileInternal(path, content, sourceOrigin, null); }); } /** * Load the contents of the source file from disk. * * @param sourcePath The path to the source file. */ private readSourceFile(sourcePath: AbsoluteFsPath): string { this.trackPath(sourcePath); return this.fs.readFile(sourcePath); }
{ "end_byte": 9444, "start_byte": 1028, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file_loader.ts" }
angular/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file_loader.ts_9448_11390
/** * Load the source map from the file at `mapPath`, parsing its JSON contents into a `RawSourceMap` * object. * * @param mapPath The path to the source-map file. */ private readRawSourceMap(mapPath: AbsoluteFsPath): RawSourceMap { this.trackPath(mapPath); return JSON.parse(this.fs.readFile(mapPath)) as RawSourceMap; } /** * Track source file paths if we have loaded them from disk so that we don't get into an infinite * recursion. */ private trackPath(path: AbsoluteFsPath): void { if (this.currentPaths.includes(path)) { throw new Error( `Circular source file mapping dependency: ${this.currentPaths.join(' -> ')} -> ${path}`, ); } this.currentPaths.push(path); } private getLastNonEmptyLine(contents: string): string { let trailingWhitespaceIndex = contents.length - 1; while ( trailingWhitespaceIndex > 0 && (contents[trailingWhitespaceIndex] === '\n' || contents[trailingWhitespaceIndex] === '\r') ) { trailingWhitespaceIndex--; } let lastRealLineIndex = contents.lastIndexOf('\n', trailingWhitespaceIndex - 1); if (lastRealLineIndex === -1) { lastRealLineIndex = 0; } return contents.slice(lastRealLineIndex + 1); } /** * Replace any matched URL schemes with their corresponding path held in the schemeMap. * * Some build tools replace real file paths with scheme prefixed paths - e.g. `webpack://`. * We use the `schemeMap` passed to this class to convert such paths to "real" file paths. * In some cases, this is not possible, since the file was actually synthesized by the build tool. * But the end result is better than prefixing the sourceRoot in front of the scheme. */ private replaceSchemeWithPath(path: string): string { return path.replace( SCHEME_MATCHER, (_: string, scheme: string) => this.schemeMap[scheme.toLowerCase()] || '', ); } }
{ "end_byte": 11390, "start_byte": 9448, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/sourcemaps/src/source_file_loader.ts" }
angular/packages/compiler-cli/src/ngtsc/shims/api.ts_0_1511
/** * @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 {AbsoluteFsPath} from '../file_system'; /** * Generates a single shim file for the entire program. */ export interface TopLevelShimGenerator { /** * Whether this shim should be emitted during TypeScript emit. */ readonly shouldEmit: boolean; /** * Create a `ts.SourceFile` representing the shim, with the correct filename. */ makeTopLevelShim(): ts.SourceFile; } /** * Generates a shim file for each original `ts.SourceFile` in the user's program, with a file * extension prefix. */ export interface PerFileShimGenerator { /** * The extension prefix which will be used for the shim. * * Knowing this allows the `ts.CompilerHost` implementation which is consuming this shim generator * to predict the shim filename, which is useful when a previous `ts.Program` already includes a * generated version of the shim. */ readonly extensionPrefix: string; /** * Whether shims produced by this generator should be emitted during TypeScript emit. */ readonly shouldEmit: boolean; /** * Generate the shim for a given original `ts.SourceFile`, with the given filename. */ generateShimForFile( sf: ts.SourceFile, genFilePath: AbsoluteFsPath, priorShimSf: ts.SourceFile | null, ): ts.SourceFile; }
{ "end_byte": 1511, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/shims/api.ts" }
angular/packages/compiler-cli/src/ngtsc/shims/README.md_0_6199
# Shims The shims package deals with the specification and generation of "shim files". These are files which are not part of the user's original program, but are added by the compiler by user request or in support of certain features. For example, users can request that the compiler produce `.ngfactory` files alongside user files to support migration from View Engine (which used `.ngfactory` files) to Ivy which does not. ## API Shim generation is exposed through two interfaces: `TopLevelShimGenerator` and `PerFileShimGenerator`. Each implementation of one of these interfaces produces one or more shims of a particular type. A top-level shim is a shim which is a "singleton" with respect to the program - it's one file that's generated and added in addition to all the user files. A per-file shim is a shim generated from the contents of a particular file (like how `.ngfactory` shims are generated for each user input file, if requested). Shims from either kind of generator can be emittable, in which case their `ts.SourceFile`s will be transpiled to JS and emitted alongside the user's code, or non-emittable, which means the user is unlikely to be aware of their existence. This API is used both by the shim generators in this package as well as for other types of shims generated by other compiler subsystems. ## Implementation The shim package exposes two specific pieces of functionality related to the integration of shims into the creation of a `ts.Program`: * A `ShimReferenceTagger` which "tags" `ts.SourceFile`s prior to program creation, and creates links from each original file to all of the per-file shims which need to be created for those file. * A `ShimAdapter` which is used by an implementation of `ts.CompilerHost` to include shims in any program created via the host. ### `ShimAdapter` The shim adapter is responsible for recognizing when a path being loaded corresponds to a shim, and producing a `ts.SourceFile` for the shim if so. Recognizing a shim filename involves two steps. First, the path itself must match a pattern for a particular `PerFileShimGenerator`'s shims (for example, NgFactory shims end in `.ngfactory.ts`). From this filename, the "source" filename can be inferred (actually several source filenames, since the source file might be `.ts` or `.tsx`). Even if a path matches the pattern, it's only a valid shim if the source file actually exists. Once a filename has been recognized, the `ShimAdapter` caches the generated shim source file and can quickly produce it on request. #### Shim loading in practice As TS starts from the root files and walks imports and references, it discovers new files which are part of the program. It will discover shim files in two different ways: * As references on their source files (those added by `ShimReferenceTagger`). * As imports written by users. This means that it's not guaranteed for a source file to be loaded before its shim. ### `ShimReferenceTagger` During program creation, TypeScript enumerates the `.ts` files on disk (the original files) and includes them into the program. However, each original file may have many associated shim files, which are not referenced and do not exist on disk, but still need to be included as well. The mechanism used to do this is "reference tagging", which is performed by the `ShimReferenceTagger`. `ts.SourceFile`s have a `referencedFiles` property, which contains paths extracted from any `/// <reference>` comments within the file. If a `ts.SourceFile` with references is included in a program, so are its referenced files. This mechanism is (ab)used by the `ShimReferenceTagger` to create references from each original file to its shims, causing them to be loaded as well. Once the program has been created, the `referencedFiles` properties can be restored to their original values via the `cleanup()` operation. This is necessary as `ts.SourceFile`s may live on in various caches for much longer than the duration of a single compilation. ### Expando The shim system needs to keep track of various pieces of metadata for `ts.SourceFile`s: * Whether or not they're shims, and if so which generator created them. * If the file is not a shim, then the original `referenceFiles` for that file (so it can be restored later). Instead of `Map`s keyed with `ts.SourceFile`s which could lead to memory leaks, this information is instead patched directly onto the `ts.SourceFile` instances using an expando symbol property `NgExtension`. ## Usage ### Factory shim generation Generated factory files create a catch-22 in ngtsc. Their contents depends on static analysis of the current program, yet they're also importable from the current program. This importability gives rise to the requirement that the contents of the generated file must be known before program creation, so that imports of it are valid. However, until the program is created, the analysis to determine the contents of the generated file cannot take place. ngc used to get away with this because the analysis phase did not depend on program creation but on the metadata collection / global analysis process. ngtsc is forced to take a different approach. A lightweight analysis pipeline which does not rely on the `ts.TypeChecker` (and thus can run before the program is created) is used to estimate the contents of a generated file, in a way that allows the program to be created. A transformer then operates on this estimated file during emit and replaces the estimated contents with accurate information. It is important that this estimate be an overestimate, as type-checking will always be run against the estimated file, and must succeed in every case where it would have succeeded with accurate info. ### Summary shim generation Summary shim generation is simpler than factory generation, and can be generated from a `ts.SourceFile` without needing to be cleaned up later. ### Other uses of shims A few other systems in the compiler make use of shim generation as well. * `entry_point` generates a flat module index (in the way View Engine used to) using a shim. * `typecheck` includes template type-checking code in the program using a shim generator.
{ "end_byte": 6199, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/shims/README.md" }
angular/packages/compiler-cli/src/ngtsc/shims/BUILD.bazel_0_642
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "api", srcs = ["api.ts"], deps = [ "//packages/compiler-cli/src/ngtsc/file_system", "@npm//typescript", ], ) ts_library( name = "shims", srcs = ["index.ts"] + glob([ "src/**/*.ts", ]), deps = [ ":api", "//packages/compiler", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/util", "@npm//@types/node", "@npm//typescript", ], )
{ "end_byte": 642, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/shims/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/shims/index.ts_0_489
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /// <reference types="node" /> export {ShimAdapter} from './src/adapter'; export { copyFileShimData, isShim, retagAllTsFiles, retagTsFile, sfExtensionData, untagAllTsFiles, untagTsFile, } from './src/expando'; export {ShimReferenceTagger} from './src/reference_tagger';
{ "end_byte": 489, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/shims/index.ts" }
angular/packages/compiler-cli/src/ngtsc/shims/test/reference_tagger_spec.ts_0_4762
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import ts from 'typescript'; import {absoluteFrom as _, AbsoluteFsPath, getSourceFileOrError} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {makeProgram} from '../../testing'; import {ShimAdapter} from '../src/adapter'; import {retagTsFile, untagTsFile} from '../src/expando'; import {ShimReferenceTagger} from '../src/reference_tagger'; import {TestShimGenerator} from './util'; runInEachFileSystem(() => { describe('ShimReferenceTagger', () => { it('should tag a source file with its appropriate shims', () => { const tagger = new ShimReferenceTagger(['test1', 'test2']); const fileName = _('/file.ts'); const sf = makeArbitrarySf(fileName); expect(sf.referencedFiles).toEqual([]); tagger.tag(sf); expectReferencedFiles(sf, ['/file.test1.ts', '/file.test2.ts']); }); it('should not tag .d.ts files', () => { const tagger = new ShimReferenceTagger(['test1', 'test2']); const fileName = _('/file.d.ts'); const sf = makeArbitrarySf(fileName); expectReferencedFiles(sf, []); tagger.tag(sf); expectReferencedFiles(sf, []); }); it('should not tag .js files', () => { const tagger = new ShimReferenceTagger(['test1', 'test2']); const fileName = _('/file.js'); const sf = makeArbitrarySf(fileName); expectReferencedFiles(sf, []); tagger.tag(sf); expectReferencedFiles(sf, []); }); it('should not tag shim files', () => { const tagger = new ShimReferenceTagger(['test1', 'test2']); const fileName = _('/file.ts'); const {host} = makeProgram([ {name: fileName, contents: 'export declare const UNIMPORTANT = true;'}, ]); const shimAdapter = new ShimAdapter( host, [], [], [new TestShimGenerator()], /* oldProgram */ null, ); const shimSf = shimAdapter.maybeGenerate(_('/file.testshim.ts'))!; expect(shimSf.referencedFiles).toEqual([]); tagger.tag(shimSf); expect(shimSf.referencedFiles).toEqual([]); }); it('should not tag shims after finalization', () => { const tagger = new ShimReferenceTagger(['test1', 'test2']); tagger.finalize(); const fileName = _('/file.ts'); const sf = makeArbitrarySf(fileName); tagger.tag(sf); expectReferencedFiles(sf, []); }); it('should not overwrite original referencedFiles', () => { const tagger = new ShimReferenceTagger(['test']); const fileName = _('/file.ts'); const sf = makeArbitrarySf(fileName); sf.referencedFiles = [ { fileName: _('/other.ts'), pos: 0, end: 0, }, ]; tagger.tag(sf); expectReferencedFiles(sf, ['/other.ts', '/file.test.ts']); }); it('should always tag against the original referencedFiles', () => { const tagger1 = new ShimReferenceTagger(['test1']); const tagger2 = new ShimReferenceTagger(['test2']); const fileName = _('/file.ts'); const sf = makeArbitrarySf(fileName); tagger1.tag(sf); tagger2.tag(sf); expectReferencedFiles(sf, ['/file.test2.ts']); }); describe('tagging and untagging', () => { it('should be able to untag references and retag them later', () => { const tagger = new ShimReferenceTagger(['test']); const fileName = _('/file.ts'); const sf = makeArbitrarySf(fileName); sf.referencedFiles = [ { fileName: _('/other.ts'), pos: 0, end: 0, }, ]; tagger.tag(sf); expectReferencedFiles(sf, ['/other.ts', '/file.test.ts']); untagTsFile(sf); expectReferencedFiles(sf, ['/other.ts']); retagTsFile(sf); expectReferencedFiles(sf, ['/other.ts', '/file.test.ts']); }); }); }); }); function makeSf(fileName: AbsoluteFsPath, contents: string): ts.SourceFile { return ts.createSourceFile(fileName, contents, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS); } function makeArbitrarySf(fileName: AbsoluteFsPath): ts.SourceFile { const declare = fileName.endsWith('.d.ts') ? 'declare ' : ''; return makeSf(fileName, `export ${declare}const UNIMPORTANT = true;`); } function expectReferencedFiles(sf: ts.SourceFile, files: string[]): void { const actual = sf.referencedFiles.map((f) => _(f.fileName)).sort(); const expected = files.map((fileName) => _(fileName)).sort(); expect(actual).toEqual(expected); }
{ "end_byte": 4762, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/shims/test/reference_tagger_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/shims/test/adapter_spec.ts_0_3294
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import ts from 'typescript'; import {absoluteFrom as _} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {makeProgram} from '../../testing'; import {ShimAdapter} from '../src/adapter'; import {TestShimGenerator} from './util'; runInEachFileSystem(() => { describe('ShimAdapter', () => { it('should recognize a basic shim name', () => { const {host} = makeProgram([ { name: _('/test.ts'), contents: `export class A {}`, }, ]); const adapter = new ShimAdapter( host, [], [], [new TestShimGenerator()], /* oldProgram */ null, ); const shimSf = adapter.maybeGenerate(_('/test.testshim.ts')); expect(shimSf).not.toBeNull(); expect(shimSf!.fileName).toBe(_('/test.testshim.ts')); expect(shimSf!.text).toContain('SHIM_FOR_FILE'); }); it('should not recognize a normal file in the program', () => { const {host} = makeProgram([ { name: _('/test.ts'), contents: `export class A {}`, }, ]); const adapter = new ShimAdapter( host, [], [], [new TestShimGenerator()], /* oldProgram */ null, ); const shimSf = adapter.maybeGenerate(_('/test.ts')); expect(shimSf).toBeNull(); }); it('should not recognize a shim-named file without a source file', () => { const {host} = makeProgram([ { name: _('/test.ts'), contents: `export class A {}`, }, ]); const adapter = new ShimAdapter( host, [], [], [new TestShimGenerator()], /* oldProgram */ null, ); const shimSf = adapter.maybeGenerate(_('/other.testshim.ts')); // Expect undefined, not null, since that indicates a valid shim path but an invalid source // file. expect(shimSf).toBeUndefined(); }); it('should detect a prior shim if one is available', () => { // Create a shim via the ShimAdapter, then create a second ShimAdapter simulating an // incremental compilation, with a stub passed for the oldProgram that includes the original // shim file. Verify that the new ShimAdapter incorporates the original shim in generation of // the new one. const {host, program} = makeProgram([ { name: _('/test.ts'), contents: `export class A {}`, }, ]); const adapter = new ShimAdapter( host, [], [], [new TestShimGenerator()], /* oldProgram */ null, ); const originalShim = adapter.maybeGenerate(_('/test.testshim.ts'))!; const oldProgramStub = { getSourceFiles: () => [...program.getSourceFiles(), originalShim], } as unknown as ts.Program; const adapter2 = new ShimAdapter(host, [], [], [new TestShimGenerator()], oldProgramStub); const newShim = adapter.maybeGenerate(_('/test.testshim.ts')); expect(newShim).toBe(originalShim); }); }); });
{ "end_byte": 3294, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/shims/test/adapter_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/shims/test/util.ts_0_885
/** * @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 {absoluteFromSourceFile, AbsoluteFsPath} from '../../file_system'; import {PerFileShimGenerator} from '../api'; export class TestShimGenerator implements PerFileShimGenerator { readonly shouldEmit = false; readonly extensionPrefix = 'testshim'; generateShimForFile( sf: ts.SourceFile, genFilePath: AbsoluteFsPath, priorSf: ts.SourceFile | null, ): ts.SourceFile { if (priorSf !== null) { return priorSf; } const path = absoluteFromSourceFile(sf); return ts.createSourceFile( genFilePath, `export const SHIM_FOR_FILE = '${path}';\n`, ts.ScriptTarget.Latest, true, ); } }
{ "end_byte": 885, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/shims/test/util.ts" }
angular/packages/compiler-cli/src/ngtsc/shims/test/BUILD.bazel_0_715
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-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/shims", "//packages/compiler-cli/src/ngtsc/shims:api", "//packages/compiler-cli/src/ngtsc/testing", "@npm//typescript", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_no_angular"], deps = [ ":test_lib", ], )
{ "end_byte": 715, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/shims/test/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/shims/src/expando.ts_0_4870
/** * @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 {AbsoluteFsPath} from '../../file_system'; /** * A `Symbol` which is used to patch extension data onto `ts.SourceFile`s. */ export const NgExtension = Symbol('NgExtension'); /** * Contents of the `NgExtension` property of a `ts.SourceFile`. */ export interface NgExtensionData { isTopLevelShim: boolean; fileShim: NgFileShimData | null; /** * The contents of the `referencedFiles` array, before modification by a `ShimReferenceTagger`. */ originalReferencedFiles: ReadonlyArray<ts.FileReference> | null; /** * The contents of the `referencedFiles` array, after modification by a `ShimReferenceTagger`. */ taggedReferenceFiles: ReadonlyArray<ts.FileReference> | null; } /** * A `ts.SourceFile` which may or may not have `NgExtension` data. */ interface MaybeNgExtendedSourceFile extends ts.SourceFile { [NgExtension]?: NgExtensionData; } /** * A `ts.SourceFile` which has `NgExtension` data. */ export interface NgExtendedSourceFile extends ts.SourceFile { /** * Overrides the type of `referencedFiles` to be writeable. */ referencedFiles: ts.FileReference[]; [NgExtension]: NgExtensionData; } /** * Narrows a `ts.SourceFile` if it has an `NgExtension` property. */ export function isExtended(sf: ts.SourceFile): sf is NgExtendedSourceFile { return (sf as MaybeNgExtendedSourceFile)[NgExtension] !== undefined; } /** * Returns the `NgExtensionData` for a given `ts.SourceFile`, adding it if none exists. */ export function sfExtensionData(sf: ts.SourceFile): NgExtensionData { const extSf = sf as MaybeNgExtendedSourceFile; if (extSf[NgExtension] !== undefined) { // The file already has extension data, so return it directly. return extSf[NgExtension]!; } // The file has no existing extension data, so add it and return it. const extension: NgExtensionData = { isTopLevelShim: false, fileShim: null, originalReferencedFiles: null, taggedReferenceFiles: null, }; extSf[NgExtension] = extension; return extension; } /** * Data associated with a per-shim instance `ts.SourceFile`. */ export interface NgFileShimData { generatedFrom: AbsoluteFsPath; extension: string; } /** * An `NgExtendedSourceFile` that is a per-file shim and has `NgFileShimData`. */ export interface NgFileShimSourceFile extends NgExtendedSourceFile { [NgExtension]: NgExtensionData & { fileShim: NgFileShimData; }; } /** * Check whether `sf` is a per-file shim `ts.SourceFile`. */ export function isFileShimSourceFile(sf: ts.SourceFile): sf is NgFileShimSourceFile { return isExtended(sf) && sf[NgExtension].fileShim !== null; } /** * Check whether `sf` is a shim `ts.SourceFile` (either a per-file shim or a top-level shim). */ export function isShim(sf: ts.SourceFile): boolean { return isExtended(sf) && (sf[NgExtension].fileShim !== null || sf[NgExtension].isTopLevelShim); } /** * Copy any shim data from one `ts.SourceFile` to another. */ export function copyFileShimData(from: ts.SourceFile, to: ts.SourceFile): void { if (!isFileShimSourceFile(from)) { return; } sfExtensionData(to).fileShim = sfExtensionData(from).fileShim; } /** * For those `ts.SourceFile`s in the `program` which have previously been tagged by a * `ShimReferenceTagger`, restore the original `referencedFiles` array that does not have shim tags. */ export function untagAllTsFiles(program: ts.Program): void { for (const sf of program.getSourceFiles()) { untagTsFile(sf); } } /** * For those `ts.SourceFile`s in the `program` which have previously been tagged by a * `ShimReferenceTagger`, re-apply the effects of tagging by updating the `referencedFiles` array to * the tagged version produced previously. */ export function retagAllTsFiles(program: ts.Program): void { for (const sf of program.getSourceFiles()) { retagTsFile(sf); } } /** * Restore the original `referencedFiles` for the given `ts.SourceFile`. */ export function untagTsFile(sf: ts.SourceFile): void { if (sf.isDeclarationFile || !isExtended(sf)) { return; } const ext = sfExtensionData(sf); if (ext.originalReferencedFiles !== null) { sf.referencedFiles = ext.originalReferencedFiles as Array<ts.FileReference>; } } /** * Apply the previously tagged `referencedFiles` to the given `ts.SourceFile`, if it was previously * tagged. */ export function retagTsFile(sf: ts.SourceFile): void { if (sf.isDeclarationFile || !isExtended(sf)) { return; } const ext = sfExtensionData(sf); if (ext.taggedReferenceFiles !== null) { sf.referencedFiles = ext.taggedReferenceFiles as Array<ts.FileReference>; } }
{ "end_byte": 4870, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/shims/src/expando.ts" }
angular/packages/compiler-cli/src/ngtsc/shims/src/adapter.ts_0_1102
/** * @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, absoluteFromSourceFile, AbsoluteFsPath} from '../../file_system'; import {isDtsPath} from '../../util/src/typescript'; import {PerFileShimGenerator, TopLevelShimGenerator} from '../api'; import {isFileShimSourceFile, isShim, sfExtensionData} from './expando'; import {makeShimFileName} from './util'; interface ShimGeneratorData { generator: PerFileShimGenerator; test: RegExp; suffix: string; } /** * Generates and tracks shim files for each original `ts.SourceFile`. * * The `ShimAdapter` provides an API that's designed to be used by a `ts.CompilerHost` * implementation and allows it to include synthetic "shim" files in the program that's being * created. It works for both freshly created programs as well as with reuse of an older program * (which already may contain shim files and thus have a different creation flow). */
{ "end_byte": 1102, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/shims/src/adapter.ts" }
angular/packages/compiler-cli/src/ngtsc/shims/src/adapter.ts_1103_8685
export class ShimAdapter { /** * A map of shim file names to the `ts.SourceFile` generated for those shims. */ private shims = new Map<AbsoluteFsPath, ts.SourceFile>(); /** * A map of shim file names to existing shims which were part of a previous iteration of this * program. * * Not all of these shims will be inherited into this program. */ private priorShims = new Map<AbsoluteFsPath, ts.SourceFile>(); /** * File names which are already known to not be shims. * * This allows for short-circuit returns without the expense of running regular expressions * against the filename repeatedly. */ private notShims = new Set<AbsoluteFsPath>(); /** * The shim generators supported by this adapter as well as extra precalculated data facilitating * their use. */ private generators: ShimGeneratorData[] = []; /** * A `Set` of shim `ts.SourceFile`s which should not be emitted. */ readonly ignoreForEmit = new Set<ts.SourceFile>(); /** * A list of extra filenames which should be considered inputs to program creation. * * This includes any top-level shims generated for the program, as well as per-file shim names for * those files which are included in the root files of the program. */ readonly extraInputFiles: ReadonlyArray<AbsoluteFsPath>; /** * Extension prefixes of all installed per-file shims. */ readonly extensionPrefixes: string[] = []; constructor( private delegate: Pick<ts.CompilerHost, 'getSourceFile' | 'fileExists'>, tsRootFiles: AbsoluteFsPath[], topLevelGenerators: TopLevelShimGenerator[], perFileGenerators: PerFileShimGenerator[], oldProgram: ts.Program | null, ) { // Initialize `this.generators` with a regex that matches each generator's paths. for (const gen of perFileGenerators) { // This regex matches paths for shims from this generator. The first (and only) capture group // extracts the filename prefix, which can be used to find the original file that was used to // generate this shim. const pattern = `^(.*)\\.${gen.extensionPrefix}\\.ts$`; const regexp = new RegExp(pattern, 'i'); this.generators.push({ generator: gen, test: regexp, suffix: `.${gen.extensionPrefix}.ts`, }); this.extensionPrefixes.push(gen.extensionPrefix); } // Process top-level generators and pre-generate their shims. Accumulate the list of filenames // as extra input files. const extraInputFiles: AbsoluteFsPath[] = []; for (const gen of topLevelGenerators) { const sf = gen.makeTopLevelShim(); sfExtensionData(sf).isTopLevelShim = true; if (!gen.shouldEmit) { this.ignoreForEmit.add(sf); } const fileName = absoluteFromSourceFile(sf); this.shims.set(fileName, sf); extraInputFiles.push(fileName); } // Add to that list the per-file shims associated with each root file. This is needed because // reference tagging alone may not work in TS compilations that have `noResolve` set. Such // compilations rely on the list of input files completely describing the program. for (const rootFile of tsRootFiles) { for (const gen of this.generators) { extraInputFiles.push(makeShimFileName(rootFile, gen.suffix)); } } this.extraInputFiles = extraInputFiles; // If an old program is present, extract all per-file shims into a map, which will be used to // generate new versions of those shims. if (oldProgram !== null) { for (const oldSf of oldProgram.getSourceFiles()) { if (oldSf.isDeclarationFile || !isFileShimSourceFile(oldSf)) { continue; } this.priorShims.set(absoluteFromSourceFile(oldSf), oldSf); } } } /** * Produce a shim `ts.SourceFile` if `fileName` refers to a shim file which should exist in the * program. * * If `fileName` does not refer to a potential shim file, `null` is returned. If a corresponding * base file could not be determined, `undefined` is returned instead. */ maybeGenerate(fileName: AbsoluteFsPath): ts.SourceFile | null | undefined { // Fast path: either this filename has been proven not to be a shim before, or it is a known // shim and no generation is required. if (this.notShims.has(fileName)) { return null; } else if (this.shims.has(fileName)) { return this.shims.get(fileName)!; } // .d.ts files can't be shims. if (isDtsPath(fileName)) { this.notShims.add(fileName); return null; } // This is the first time seeing this path. Try to match it against a shim generator. for (const record of this.generators) { const match = record.test.exec(fileName); if (match === null) { continue; } // The path matched. Extract the filename prefix without the extension. const prefix = match[1]; // This _might_ be a shim, if an underlying base file exists. The base file might be .ts or // .tsx. let baseFileName = absoluteFrom(prefix + '.ts'); // Retrieve the original file for which the shim will be generated. let inputFile = this.delegate.getSourceFile(baseFileName, ts.ScriptTarget.Latest); if (inputFile === undefined) { // No .ts file by that name - try .tsx. baseFileName = absoluteFrom(prefix + '.tsx'); inputFile = this.delegate.getSourceFile(baseFileName, ts.ScriptTarget.Latest); } if (inputFile === undefined || isShim(inputFile)) { // This isn't a shim after all since there is no original file which would have triggered // its generation, even though the path is right. There are a few reasons why this could // occur: // // * when resolving an import to an .ngfactory.d.ts file, the module resolution algorithm // will first look for an .ngfactory.ts file in its place, which will be requested here. // * when the user writes a bad import. // * when a file is present in one compilation and removed in the next incremental step. // // Note that this does not add the filename to `notShims`, so this path is not cached. // That's okay as these cases above are edge cases and do not occur regularly in normal // operations. return undefined; } // Actually generate and cache the shim. return this.generateSpecific(fileName, record.generator, inputFile); } // No generator matched. this.notShims.add(fileName); return null; } private generateSpecific( fileName: AbsoluteFsPath, generator: PerFileShimGenerator, inputFile: ts.SourceFile, ): ts.SourceFile { let priorShimSf: ts.SourceFile | null = null; if (this.priorShims.has(fileName)) { // In the previous program a shim with this name already existed. It's passed to the shim // generator which may reuse it instead of generating a fresh shim. priorShimSf = this.priorShims.get(fileName)!; this.priorShims.delete(fileName); } const shimSf = generator.generateShimForFile(inputFile, fileName, priorShimSf); // Mark the new generated source file as a shim that originated from this generator. sfExtensionData(shimSf).fileShim = { extension: generator.extensionPrefix, generatedFrom: absoluteFromSourceFile(inputFile), }; if (!generator.shouldEmit) { this.ignoreForEmit.add(shimSf); } this.shims.set(fileName, shimSf); return shimSf; } }
{ "end_byte": 8685, "start_byte": 1103, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/shims/src/adapter.ts" }
angular/packages/compiler-cli/src/ngtsc/shims/src/util.ts_0_900
/** * @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 {absoluteFrom, AbsoluteFsPath} from '../../file_system'; const TS_EXTENSIONS = /\.tsx?$/i; /** * Replace the .ts or .tsx extension of a file with the shim filename suffix. */ export function makeShimFileName(fileName: AbsoluteFsPath, suffix: string): AbsoluteFsPath { return absoluteFrom(fileName.replace(TS_EXTENSIONS, suffix)); } export function generatedModuleName( originalModuleName: string, originalFileName: string, genSuffix: string, ): string { let moduleName: string; if (originalFileName.endsWith('/index.ts')) { moduleName = originalModuleName + '/index' + genSuffix; } else { moduleName = originalModuleName + genSuffix; } return moduleName; }
{ "end_byte": 900, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/shims/src/util.ts" }
angular/packages/compiler-cli/src/ngtsc/shims/src/reference_tagger.ts_0_2388
/** * @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 {absoluteFromSourceFile} from '../../file_system'; import {isNonDeclarationTsPath} from '../../util/src/typescript'; import {isShim, sfExtensionData} from './expando'; import {makeShimFileName} from './util'; /** * Manipulates the `referencedFiles` property of `ts.SourceFile`s to add references to shim files * for each original source file, causing the shims to be loaded into the program as well. * * `ShimReferenceTagger`s are intended to operate during program creation only. */ export class ShimReferenceTagger { private suffixes: string[]; /** * Tracks which original files have been processed and had shims generated if necessary. * * This is used to avoid generating shims twice for the same file. */ private tagged = new Set<ts.SourceFile>(); /** * Whether shim tagging is currently being performed. */ private enabled: boolean = true; constructor(shimExtensions: string[]) { this.suffixes = shimExtensions.map((extension) => `.${extension}.ts`); } /** * Tag `sf` with any needed references if it's not a shim itself. */ tag(sf: ts.SourceFile): void { if ( !this.enabled || sf.isDeclarationFile || isShim(sf) || this.tagged.has(sf) || !isNonDeclarationTsPath(sf.fileName) ) { return; } const ext = sfExtensionData(sf); // If this file has never been tagged before, capture its `referencedFiles` in the extension // data. if (ext.originalReferencedFiles === null) { ext.originalReferencedFiles = sf.referencedFiles; } const referencedFiles = [...ext.originalReferencedFiles]; const sfPath = absoluteFromSourceFile(sf); for (const suffix of this.suffixes) { referencedFiles.push({ fileName: makeShimFileName(sfPath, suffix), pos: 0, end: 0, }); } ext.taggedReferenceFiles = referencedFiles; sf.referencedFiles = referencedFiles; this.tagged.add(sf); } /** * Disable the `ShimReferenceTagger` and free memory associated with tracking tagged files. */ finalize(): void { this.enabled = false; this.tagged.clear(); } }
{ "end_byte": 2388, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/shims/src/reference_tagger.ts" }
angular/packages/compiler-cli/src/ngtsc/diagnostics/BUILD.bazel_0_282
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "diagnostics", srcs = ["index.ts"] + glob([ "src/**/*.ts", ]), deps = [ "//packages/compiler", "@npm//typescript", ], )
{ "end_byte": 282, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/diagnostics/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/diagnostics/index.ts_0_734
/** * @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 {COMPILER_ERRORS_WITH_GUIDES} from './src/docs'; export { addDiagnosticChain, FatalDiagnosticError, isFatalDiagnosticError, isLocalCompilationDiagnostics, makeDiagnostic, makeDiagnosticChain, makeRelatedInformation, } from './src/error'; export {ErrorCode} from './src/error_code'; export {ERROR_DETAILS_PAGE_BASE_URL} from './src/error_details_base_url'; export {ExtendedTemplateDiagnosticName} from './src/extended_template_diagnostic_name'; export {ngErrorCode, replaceTsWithNgInErrors} from './src/util';
{ "end_byte": 734, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/diagnostics/index.ts" }
angular/packages/compiler-cli/src/ngtsc/diagnostics/src/error_code.ts_0_7815
/** * @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 */ /** * @publicApi */ export enum ErrorCode { DECORATOR_ARG_NOT_LITERAL = 1001, DECORATOR_ARITY_WRONG = 1002, DECORATOR_NOT_CALLED = 1003, DECORATOR_UNEXPECTED = 1005, /** * This error code indicates that there are incompatible decorators on a type or a class field. */ DECORATOR_COLLISION = 1006, VALUE_HAS_WRONG_TYPE = 1010, VALUE_NOT_LITERAL = 1011, /** * Raised when an initializer API is annotated with an unexpected decorator. * * e.g. `@Input` is also applied on the class member using `input`. */ INITIALIZER_API_WITH_DISALLOWED_DECORATOR = 1050, /** * Raised when an initializer API feature (like signal inputs) are also * declared in the class decorator metadata. * * e.g. a signal input is also declared in the `@Directive` `inputs` array. */ INITIALIZER_API_DECORATOR_METADATA_COLLISION = 1051, /** * Raised whenever an initializer API does not support the `.required` * function, but is still detected unexpectedly. */ INITIALIZER_API_NO_REQUIRED_FUNCTION = 1052, /** * Raised whenever an initializer API is used on a class member * and the given access modifiers (e.g. `private`) are not allowed. */ INITIALIZER_API_DISALLOWED_MEMBER_VISIBILITY = 1053, /** * An Angular feature, like inputs, outputs or queries is incorrectly * declared on a static member. */ INCORRECTLY_DECLARED_ON_STATIC_MEMBER = 1100, COMPONENT_MISSING_TEMPLATE = 2001, PIPE_MISSING_NAME = 2002, PARAM_MISSING_TOKEN = 2003, DIRECTIVE_MISSING_SELECTOR = 2004, /** Raised when an undecorated class is passed in as a provider to a module or a directive. */ UNDECORATED_PROVIDER = 2005, /** * Raised when a Directive inherits its constructor from a base class without an Angular * decorator. */ DIRECTIVE_INHERITS_UNDECORATED_CTOR = 2006, /** * Raised when an undecorated class that is using Angular features * has been discovered. */ UNDECORATED_CLASS_USING_ANGULAR_FEATURES = 2007, /** * Raised when an component cannot resolve an external resource, such as a template or a style * sheet. */ COMPONENT_RESOURCE_NOT_FOUND = 2008, /** * Raised when a component uses `ShadowDom` view encapsulation, but its selector * does not match the shadow DOM tag name requirements. */ COMPONENT_INVALID_SHADOW_DOM_SELECTOR = 2009, /** * Raised when a component has `imports` but is not marked as `standalone: true`. */ COMPONENT_NOT_STANDALONE = 2010, /** * Raised when a type in the `imports` of a component is a directive or pipe, but is not * standalone. */ COMPONENT_IMPORT_NOT_STANDALONE = 2011, /** * Raised when a type in the `imports` of a component is not a directive, pipe, or NgModule. */ COMPONENT_UNKNOWN_IMPORT = 2012, /** * Raised when the compiler wasn't able to resolve the metadata of a host directive. */ HOST_DIRECTIVE_INVALID = 2013, /** * Raised when a host directive isn't standalone. */ HOST_DIRECTIVE_NOT_STANDALONE = 2014, /** * Raised when a host directive is a component. */ HOST_DIRECTIVE_COMPONENT = 2015, /** * Raised when a type with Angular decorator inherits its constructor from a base class * which has a constructor that is incompatible with Angular DI. */ INJECTABLE_INHERITS_INVALID_CONSTRUCTOR = 2016, /** Raised when a host tries to alias a host directive binding that does not exist. */ HOST_DIRECTIVE_UNDEFINED_BINDING = 2017, /** * Raised when a host tries to alias a host directive * binding to a pre-existing binding's public name. */ HOST_DIRECTIVE_CONFLICTING_ALIAS = 2018, /** * Raised when a host directive definition doesn't expose a * required binding from the host directive. */ HOST_DIRECTIVE_MISSING_REQUIRED_BINDING = 2019, /** * Raised when a component specifies both a `transform` function on an input * and has a corresponding `ngAcceptInputType_` member for the same input. */ CONFLICTING_INPUT_TRANSFORM = 2020, /** Raised when a component has both `styleUrls` and `styleUrl`. */ COMPONENT_INVALID_STYLE_URLS = 2021, /** * Raised when a type in the `deferredImports` of a component is not a component, directive or * pipe. */ COMPONENT_UNKNOWN_DEFERRED_IMPORT = 2022, /** * Raised when a `standalone: false` component is declared but `strictStandalone` is set. */ NON_STANDALONE_NOT_ALLOWED = 2023, SYMBOL_NOT_EXPORTED = 3001, /** * Raised when a relationship between directives and/or pipes would cause a cyclic import to be * created that cannot be handled, such as in partial compilation mode. */ IMPORT_CYCLE_DETECTED = 3003, /** * Raised when the compiler is unable to generate an import statement for a reference. */ IMPORT_GENERATION_FAILURE = 3004, CONFIG_FLAT_MODULE_NO_INDEX = 4001, CONFIG_STRICT_TEMPLATES_IMPLIES_FULL_TEMPLATE_TYPECHECK = 4002, CONFIG_EXTENDED_DIAGNOSTICS_IMPLIES_STRICT_TEMPLATES = 4003, CONFIG_EXTENDED_DIAGNOSTICS_UNKNOWN_CATEGORY_LABEL = 4004, CONFIG_EXTENDED_DIAGNOSTICS_UNKNOWN_CHECK = 4005, /** * Raised when a host expression has a parse error, such as a host listener or host binding * expression containing a pipe. */ HOST_BINDING_PARSE_ERROR = 5001, /** * Raised when the compiler cannot parse a component's template. */ TEMPLATE_PARSE_ERROR = 5002, /** * Raised when an NgModule contains an invalid reference in `declarations`. */ NGMODULE_INVALID_DECLARATION = 6001, /** * Raised when an NgModule contains an invalid type in `imports`. */ NGMODULE_INVALID_IMPORT = 6002, /** * Raised when an NgModule contains an invalid type in `exports`. */ NGMODULE_INVALID_EXPORT = 6003, /** * Raised when an NgModule contains a type in `exports` which is neither in `declarations` nor * otherwise imported. */ NGMODULE_INVALID_REEXPORT = 6004, /** * Raised when a `ModuleWithProviders` with a missing * generic type argument is passed into an `NgModule`. */ NGMODULE_MODULE_WITH_PROVIDERS_MISSING_GENERIC = 6005, /** * Raised when an NgModule exports multiple directives/pipes of the same name and the compiler * attempts to generate private re-exports within the NgModule file. */ NGMODULE_REEXPORT_NAME_COLLISION = 6006, /** * Raised when a directive/pipe is part of the declarations of two or more NgModules. */ NGMODULE_DECLARATION_NOT_UNIQUE = 6007, /** * Raised when a standalone directive/pipe is part of the declarations of an NgModule. */ NGMODULE_DECLARATION_IS_STANDALONE = 6008, /** * Raised when a standalone component is part of the bootstrap list of an NgModule. */ NGMODULE_BOOTSTRAP_IS_STANDALONE = 6009, /** * Indicates that an NgModule is declared with `id: module.id`. This is an anti-pattern that is * disabled explicitly in the compiler, that was originally based on a misunderstanding of * `NgModule.id`. */ WARN_NGMODULE_ID_UNNECESSARY = 6100, /** * 6999 was previously assigned to NGMODULE_VE_DEPENDENCY_ON_IVY_LIB * To prevent any confusion, let's not reassign it. */ /** * An element name failed validation against the DOM schema. */ SCHEMA_INVALID_ELEMENT = 8001, /** * An element's attribute name failed validation against the DOM schema. */ SCHEMA_INVALID_ATTRIBUTE = 8002, /** * No matching directive was found for a `#ref="target"` expression. */ MISSING_REFERENCE_TARGET = 8003, /** * No matching pipe was found for a */ MISSING_PIPE = 8004,
{ "end_byte": 7815, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/diagnostics/src/error_code.ts" }
angular/packages/compiler-cli/src/ngtsc/diagnostics/src/error_code.ts_7819_15044
/** * The left-hand side of an assignment expression was a template variable. Effectively, the * template looked like: * * ``` * <ng-template let-something> * <button (click)="something = ...">...</button> * </ng-template> * ``` * * Template variables are read-only. */ WRITE_TO_READ_ONLY_VARIABLE = 8005, /** * A template variable was declared twice. For example: * * ```html * <div *ngFor="let i of items; let i = index"> * </div> * ``` */ DUPLICATE_VARIABLE_DECLARATION = 8006, /** * A template has a two way binding (two bindings created by a single syntactical element) * in which the input and output are going to different places. */ SPLIT_TWO_WAY_BINDING = 8007, /** * A directive usage isn't binding to one or more required inputs. */ MISSING_REQUIRED_INPUTS = 8008, /** * The tracking expression of a `for` loop block is accessing a variable that is unavailable, * for example: * * ``` * <ng-template let-ref> * @for (item of items; track ref) {} * </ng-template> * ``` */ ILLEGAL_FOR_LOOP_TRACK_ACCESS = 8009, /** * The trigger of a `defer` block cannot access its trigger element, * either because it doesn't exist or it's in a different view. * * ``` * @defer (on interaction(trigger)) {...} * * <ng-template> * <button #trigger></button> * </ng-template> * ``` */ INACCESSIBLE_DEFERRED_TRIGGER_ELEMENT = 8010, /** * A control flow node is projected at the root of a component and is preventing its direct * descendants from being projected, because it has more than one root node. * * ``` * <comp> * @if (expr) { * <div projectsIntoSlot></div> * Text preventing the div from being projected * } * </comp> * ``` */ CONTROL_FLOW_PREVENTING_CONTENT_PROJECTION = 8011, /** * A pipe imported via `@Component.deferredImports` is * used outside of a `@defer` block in a template. */ DEFERRED_PIPE_USED_EAGERLY = 8012, /** * A directive/component imported via `@Component.deferredImports` is * used outside of a `@defer` block in a template. */ DEFERRED_DIRECTIVE_USED_EAGERLY = 8013, /** * A directive/component/pipe imported via `@Component.deferredImports` is * also included into the `@Component.imports` list. */ DEFERRED_DEPENDENCY_IMPORTED_EAGERLY = 8014, /** An expression is trying to write to an `@let` declaration. */ ILLEGAL_LET_WRITE = 8015, /** An expression is trying to read an `@let` before it has been defined. */ LET_USED_BEFORE_DEFINITION = 8016, /** A `@let` declaration conflicts with another symbol in the same scope. */ CONFLICTING_LET_DECLARATION = 8017, /** * A two way binding in a template has an incorrect syntax, * parentheses outside brackets. For example: * * ``` * <div ([foo])="bar" /> * ``` */ INVALID_BANANA_IN_BOX = 8101, /** * The left side of a nullish coalescing operation is not nullable. * * ``` * {{ foo ?? bar }} * ``` * When the type of foo doesn't include `null` or `undefined`. */ NULLISH_COALESCING_NOT_NULLABLE = 8102, /** * A known control flow directive (e.g. `*ngIf`) is used in a template, * but the `CommonModule` is not imported. */ MISSING_CONTROL_FLOW_DIRECTIVE = 8103, /** * A text attribute is not interpreted as a binding but likely intended to be. * * For example: * ``` * <div * attr.x="value" * class.blue="true" * style.margin-right.px="5"> * </div> * ``` * * All of the above attributes will just be static text attributes and will not be interpreted as * bindings by the compiler. */ TEXT_ATTRIBUTE_NOT_BINDING = 8104, /** * NgForOf is used in a template, but the user forgot to include let * in their statement. * * For example: * ``` * <ul><li *ngFor="item of items">{{item["name"]}};</li></ul> * ``` */ MISSING_NGFOROF_LET = 8105, /** * Indicates that the binding suffix is not supported * * Style bindings support suffixes like `style.width.px`, `.em`, and `.%`. * These suffixes are _not_ supported for attribute bindings. * * For example `[attr.width.px]="5"` becomes `width.px="5"` when bound. * This is almost certainly unintentional and this error is meant to * surface this mistake to the developer. */ SUFFIX_NOT_SUPPORTED = 8106, /** * The left side of an optional chain operation is not nullable. * * ``` * {{ foo?.bar }} * {{ foo?.['bar'] }} * {{ foo?.() }} * ``` * When the type of foo doesn't include `null` or `undefined`. */ OPTIONAL_CHAIN_NOT_NULLABLE = 8107, /** * `ngSkipHydration` should not be a binding (it should be a static attribute). * * For example: * ``` * <my-cmp [ngSkipHydration]="someTruthyVar" /> * ``` * * `ngSkipHydration` cannot be a binding and can not have values other than "true" or an empty * value */ SKIP_HYDRATION_NOT_STATIC = 8108, /** * Signal functions should be invoked when interpolated in templates. * * For example: * ``` * {{ mySignal() }} * ``` */ INTERPOLATED_SIGNAL_NOT_INVOKED = 8109, /** * Initializer-based APIs can only be invoked from inside of an initializer. * * ``` * // Allowed * myInput = input(); * * // Not allowed * function myInput() { * return input(); * } * ``` */ UNSUPPORTED_INITIALIZER_API_USAGE = 8110, /** * A function in an event binding is not called. * * For example: * ``` * <button (click)="myFunc"></button> * ``` * * This will not call `myFunc` when the button is clicked. Instead, it should be * `<button (click)="myFunc()"></button>`. */ UNINVOKED_FUNCTION_IN_EVENT_BINDING = 8111, /** * A `@let` declaration in a template isn't used. * * For example: * ``` * @let used = 1; <!-- Not an error --> * @let notUsed = 2; <!-- Error --> * * {{used}} * ``` */ UNUSED_LET_DECLARATION = 8112, /** * A symbol referenced in `@Component.imports` isn't being used within the template. */ UNUSED_STANDALONE_IMPORTS = 8113, /** * The template type-checking engine would need to generate an inline type check block for a * component, but the current type-checking environment doesn't support it. */ INLINE_TCB_REQUIRED = 8900, /** * The template type-checking engine would need to generate an inline type constructor for a * directive or component, but the current type-checking environment doesn't support it. */ INLINE_TYPE_CTOR_REQUIRED = 8901, /** * An injectable already has a `ɵprov` property. */ INJECTABLE_DUPLICATE_PROV = 9001, // 10XXX error codes are reserved for diagnostics with categories other than // `ts.DiagnosticCategory.Error`. These diagnostics are generated by the compiler when configured // to do so by a tool such as the Language Service, or by the Language Service itself. /** * Suggest users to enable `strictTemplates` to make use of full capabilities * provided by Angular language service. */ SUGGEST_STRICT_TEMPLATES = 10001,
{ "end_byte": 15044, "start_byte": 7819, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/diagnostics/src/error_code.ts" }
angular/packages/compiler-cli/src/ngtsc/diagnostics/src/error_code.ts_15048_16117
** * Indicates that a particular structural directive provides advanced type narrowing * functionality, but the current template type-checking configuration does not allow its usage in * type inference. */ SUGGEST_SUBOPTIMAL_TYPE_INFERENCE = 10002, /** * In local compilation mode a const is required to be resolved statically but cannot be so since * it is imported from a file outside of the compilation unit. This usually happens with const * being used as Angular decorators parameters such as `@Component.template`, * `@HostListener.eventName`, etc. */ LOCAL_COMPILATION_UNRESOLVED_CONST = 11001, /** * In local compilation mode a certain expression or syntax is not supported. This is usually * because the expression/syntax is not very common and so we did not add support for it yet. This * can be changed in the future and support for more expressions could be added if need be. * Meanwhile, this error is thrown to indicate a current unavailability. */ LOCAL_COMPILATION_UNSUPPORTED_EXPRESSION = 11003, }
{ "end_byte": 16117, "start_byte": 15048, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/diagnostics/src/error_code.ts" }
angular/packages/compiler-cli/src/ngtsc/diagnostics/src/extended_template_diagnostic_name.ts_0_1381
/** * @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 */ /** * Enum holding the name of each extended template diagnostic. The name is used as a user-meaningful * value for configuring the diagnostic in the project's options. * * See the corresponding `ErrorCode` for documentation about each specific error. * packages/compiler-cli/src/ngtsc/diagnostics/src/error_code.ts * * @publicApi */ export enum ExtendedTemplateDiagnosticName { INVALID_BANANA_IN_BOX = 'invalidBananaInBox', NULLISH_COALESCING_NOT_NULLABLE = 'nullishCoalescingNotNullable', OPTIONAL_CHAIN_NOT_NULLABLE = 'optionalChainNotNullable', MISSING_CONTROL_FLOW_DIRECTIVE = 'missingControlFlowDirective', TEXT_ATTRIBUTE_NOT_BINDING = 'textAttributeNotBinding', UNINVOKED_FUNCTION_IN_EVENT_BINDING = 'uninvokedFunctionInEventBinding', MISSING_NGFOROF_LET = 'missingNgForOfLet', SUFFIX_NOT_SUPPORTED = 'suffixNotSupported', SKIP_HYDRATION_NOT_STATIC = 'skipHydrationNotStatic', INTERPOLATED_SIGNAL_NOT_INVOKED = 'interpolatedSignalNotInvoked', CONTROL_FLOW_PREVENTING_CONTENT_PROJECTION = 'controlFlowPreventingContentProjection', UNUSED_LET_DECLARATION = 'unusedLetDeclaration', UNUSED_STANDALONE_IMPORTS = 'unusedStandaloneImports', }
{ "end_byte": 1381, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/diagnostics/src/extended_template_diagnostic_name.ts" }
angular/packages/compiler-cli/src/ngtsc/diagnostics/src/error_details_base_url.ts_0_496
/** * @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 */ /** * Base URL for the error details page. * * Keep the files below in full sync: * - packages/compiler-cli/src/ngtsc/diagnostics/src/error_details_base_url.ts * - packages/core/src/error_details_base_url.ts */ export const ERROR_DETAILS_PAGE_BASE_URL = 'https://angular.dev/errors';
{ "end_byte": 496, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/diagnostics/src/error_details_base_url.ts" }
angular/packages/compiler-cli/src/ngtsc/diagnostics/src/docs.ts_0_781
/** * @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} from './error_code'; /** * Contains a set of error messages that have detailed guides at angular.io. * Full list of available error guides can be found at https://angular.dev/errors */ export const COMPILER_ERRORS_WITH_GUIDES = new Set([ ErrorCode.DECORATOR_ARG_NOT_LITERAL, ErrorCode.IMPORT_CYCLE_DETECTED, ErrorCode.PARAM_MISSING_TOKEN, ErrorCode.SCHEMA_INVALID_ELEMENT, ErrorCode.SCHEMA_INVALID_ATTRIBUTE, ErrorCode.MISSING_REFERENCE_TARGET, ErrorCode.COMPONENT_INVALID_SHADOW_DOM_SELECTOR, ErrorCode.WARN_NGMODULE_ID_UNNECESSARY, ]);
{ "end_byte": 781, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/diagnostics/src/docs.ts" }
angular/packages/compiler-cli/src/ngtsc/diagnostics/src/util.ts_0_994
/** * @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} from './error_code'; const ERROR_CODE_MATCHER = /(\u001b\[\d+m ?)TS-99(\d+: ?\u001b\[\d+m)/g; /** * During formatting of `ts.Diagnostic`s, the numeric code of each diagnostic is prefixed with the * hard-coded "TS" prefix. For Angular's own error codes, a prefix of "NG" is desirable. To achieve * this, all Angular error codes start with "-99" so that the sequence "TS-99" can be assumed to * correspond with an Angular specific error code. This function replaces those occurrences with * just "NG". * * @param errors The formatted diagnostics */ export function replaceTsWithNgInErrors(errors: string): string { return errors.replace(ERROR_CODE_MATCHER, '$1NG$2'); } export function ngErrorCode(code: ErrorCode): number { return parseInt('-99' + code); }
{ "end_byte": 994, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/diagnostics/src/util.ts" }
angular/packages/compiler-cli/src/ngtsc/diagnostics/src/error.ts_0_3573
/** * @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} from './error_code'; import {ngErrorCode} from './util'; export class FatalDiagnosticError extends Error { constructor( readonly code: ErrorCode, readonly node: ts.Node, readonly diagnosticMessage: string | ts.DiagnosticMessageChain, readonly relatedInformation?: ts.DiagnosticRelatedInformation[], ) { super( `FatalDiagnosticError: Code: ${code}, Message: ${ts.flattenDiagnosticMessageText( diagnosticMessage, '\n', )}`, ); // Extending `Error` ends up breaking some internal tests. This appears to be a known issue // when extending errors in TS and the workaround is to explicitly set the prototype. // https://stackoverflow.com/questions/41102060/typescript-extending-error-class Object.setPrototypeOf(this, new.target.prototype); } // Trying to hide `.message` from `Error` to encourage users to look // at `diagnosticMessage` instead. declare message: never; /** * @internal */ _isFatalDiagnosticError = true; toDiagnostic(): ts.DiagnosticWithLocation { return makeDiagnostic(this.code, this.node, this.diagnosticMessage, this.relatedInformation); } } export function makeDiagnostic( code: ErrorCode, node: ts.Node, messageText: string | ts.DiagnosticMessageChain, relatedInformation?: ts.DiagnosticRelatedInformation[], category: ts.DiagnosticCategory = ts.DiagnosticCategory.Error, ): ts.DiagnosticWithLocation { node = ts.getOriginalNode(node); return { category, code: ngErrorCode(code), file: ts.getOriginalNode(node).getSourceFile(), start: node.getStart(undefined, false), length: node.getWidth(), messageText, relatedInformation, }; } export function makeDiagnosticChain( messageText: string, next?: ts.DiagnosticMessageChain[], ): ts.DiagnosticMessageChain { return { category: ts.DiagnosticCategory.Message, code: 0, messageText, next, }; } export function makeRelatedInformation( node: ts.Node, messageText: string, ): ts.DiagnosticRelatedInformation { node = ts.getOriginalNode(node); return { category: ts.DiagnosticCategory.Message, code: 0, file: node.getSourceFile(), start: node.getStart(), length: node.getWidth(), messageText, }; } export function addDiagnosticChain( messageText: string | ts.DiagnosticMessageChain, add: ts.DiagnosticMessageChain[], ): ts.DiagnosticMessageChain { if (typeof messageText === 'string') { return makeDiagnosticChain(messageText, add); } if (messageText.next === undefined) { messageText.next = add; } else { messageText.next.push(...add); } return messageText; } export function isFatalDiagnosticError(err: any): err is FatalDiagnosticError { return err._isFatalDiagnosticError === true; } /** * Whether the compiler diagnostics represents an error related to local compilation mode. * * This helper has application in 1P where we check whether a diagnostic is related to local * compilation in order to add some g3 specific info to it. */ export function isLocalCompilationDiagnostics(diagnostic: ts.Diagnostic): boolean { return ( diagnostic.code === ngErrorCode(ErrorCode.LOCAL_COMPILATION_UNRESOLVED_CONST) || diagnostic.code === ngErrorCode(ErrorCode.LOCAL_COMPILATION_UNSUPPORTED_EXPRESSION) ); }
{ "end_byte": 3573, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/diagnostics/src/error.ts" }
angular/packages/compiler-cli/src/ngtsc/xi18n/BUILD.bazel_0_277
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "xi18n", srcs = glob([ "*.ts", "src/**/*.ts", ]), deps = [ "//packages/compiler", "@npm//typescript", ], )
{ "end_byte": 277, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/xi18n/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/xi18n/index.ts_0_235
/** * @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/context';
{ "end_byte": 235, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/xi18n/index.ts" }
angular/packages/compiler-cli/src/ngtsc/xi18n/src/context.ts_0_1028
/** * @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 {InterpolationConfig} from '@angular/compiler'; /** * Captures template information intended for extraction of i18n messages from a template. * * This interface is compatible with the View Engine compiler's `MessageBundle` class, which is used * to implement xi18n for VE. Due to the dependency graph of ngtsc, an interface is needed as it * can't depend directly on `MessageBundle`. */ export interface Xi18nContext { /** * Capture i18n messages from the template. * * In `MessageBundle` itself, this returns any `ParseError`s from the template. In this interface, * the return type is declared as `void` for simplicity, since any parse errors would be reported * as diagnostics anyway. */ updateFromTemplate(html: string, url: string, interpolationConfig: InterpolationConfig): void; }
{ "end_byte": 1028, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/xi18n/src/context.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/README.md_0_8768
# The Template Type Checking Engine The `typecheck` package is concerned with template type-checking, the process by which the compiler determines and understands the TypeScript types of constructs within component templates. It's used to perform actual type checking of templates (similarly to how TypeScript checks code for type errors). It also provides the `TemplateTypeChecker` API which is a conceptual analogue to TypeScript's own `ts.TypeChecker`, exposing various semantic details about template types to consumers such as the Angular Language Service. The template type-checking engine is complex, as TypeScript itself is not very pluggable when it comes to the type system. The main algorithm for template type-checking is as follows: 1. The input `ts.Program` is analyzed, and information about directives/pipes as well as candidate templates is collected. 2. Each candidate template is converted into a "type-check block", or TCB, a TypeScript function that semantically describes the operations in the template as well as their types. 3. A derivative `ts.Program` is created from the user's input program from step 1, plus the newly generated TCBs. 4. TypeScript is asked to produce diagnostics for the TCBs, which arise from type errors within the template. 5. TCB diagnostics are converted to template diagnostics and reported to the user. This algorithm relies extensively on TypeScript's ability to rapidly type check incremental changes in a `ts.Program` for its performance characteristics. Much of its design is optimized to ensure TypeScript has to do the minimum incremental work to check the new `ts.Program`. ## Type Check Blocks To understand and check the types of various operations and structures within templates, the `typecheck` system maps them to TypeScript code, encoding them in such a way as to express the intent of the operation within the type system. TCBs are not ever emitted, nor are they referenced from any other code (they're unused code as far as TypeScript is concerned). Their _runtime_ effect is therefore unimportant. What matters is that they express to TypeScript the type relationships of directives, bindings, and other entities in the template. Type errors within TCBs translate directly to type errors in the original template. ### Theory Given a component `SomeCmp`, its TCB takes the form of a function: ```typescript function tcb(this: SomeCmp): void { // TCB code } ``` Encoding the TCB as a function serves two purposes: 1. It provides a lexical scope in which to declare variables without fear of collisions. 2. It provides a convenient location (the parameter list) to declare the component context. The component context is the theoretical component instance associated with the template. Expressions within the template often refer to properties of this component. For example, if `SomeCmp`'s template has an interpolation expression `{{foo.bar}}`, this suggests that `SomeCmp` has a property `foo`, and that `foo` itself is an object with a property `bar` (or in a type sense, that the type of `SomeCmp.foo` has a property `bar`). Such a binding is expressed in the TCB function, using the `this` parameter as the component instance: ```typescript function tcb(this: SomeCmp): void { '' + this.foo.bar; } ``` If `SomeCmp` does not have a `foo` property, then TypeScript will produce a type error/diagnostic for the expression `this.foo`. If `this.foo` does exist, but is not of a type that has a `bar` property, then TypeScript will catch that too. By mapping the template expression `{{foo.bar}}` to TypeScript code, the compiler has captured its _intent_ in the TCB in a way that TypeScript can validate. #### Types of template declarations Not only can a template consume properties declared from its component, but various structures within a template can also be considered "declarations" which have types of their own. For example, the template: ```html <input #name> {{name.value}} ``` declares a single `<input>` element with a local ref `#name`, meaning that within this template `name` refers to the `<input>` element. The `{{name.value}}` interpolation is reading the `value` property of this element. Within the TCB, the `<input>` element is treated as a declaration, and the compiler leverages the powerful type inference of `document.createElement`: ```typescript function tcb(this: SomeCmp): void { var _t1 = document.createElement('input'); '' + _t1.value; } ``` The `_t1` variable represents the instance of the `<input>` element within the template. This statement will never be executed, but its initialization expression is used to infer a correct type of `_t1` (`HTMLInputElement`), using the `document.createElement` typings that TypeScript provides. By knowing the type of this element, the expression involving the `name` local ref can be translated into the TCB as `_t1.value`. TypeScript will then validate that `_t1` has a `value` property (really, that the `HTMLInputElement` type has a `value` property). #### Directive types Just like with HTML elements, directives present on elements within the template (including those directives which are components) are treated as declarations as well. Consider the template: ```html <other-cmp [foo]="bar"></other-cmp> ``` The TCB for this template looks like: ```typescript function tcb(this: SomeCmp): void { var _t1: OtherCmp = null!; _t1.foo = this.bar; } ``` Since `<other-cmp>` is a component, the TCB declares `_t1` to be of that component's type. This allows for the binding `[foo]="bar"` to be expressed in TypeScript as `_t1.foo = this.bar` - an assignment to `OtherCmp`'s `@Input` for `foo` of the `bar` property from the template's context. TypeScript can then type check this operation and produce diagnostics if the type of `this.bar` is not assignable to the `_t1.foo` property which backs the `@Input`. #### Generic directives & type constructors The above declaration of `_t1` using the component's type only works when the directive/component class is not generic. If `OtherCmp` were declared as: ```typescript export class OtherCmp<T> { ... } ``` then the compiler could not write ```typescript var _t1: OtherCmp<?> = ...; ``` without picking a value for the generic type parameter `T` of `OtherCmp`. How should the compiler know what type the user intended for this component instance? Ordinarily, for a plain TypeScript class such as `Set<T>`, the generic type parameters of an instance are determined in one of two ways: 1. Directly, via construction: `new Set<string>()` 2. Indirectly, via inference from constructor parameters: `new Set(['foo', 'bar']); // Set<string>` For directives, neither of these options makes sense. Users do not write direct constructor calls to directives in a template, so there is no mechanism by which they can specify generic types directly. Directive constructors are also dependency-injected, and generic types cannot be used as DI tokens and so they cannot be inferred from DI. Instead, conceptually, the generic type of a directive depends on the types bound to its _inputs_. This is immediately evident for a directive such as `NgFor`: ```typescript @Directive({selector: '[ngFor]'}) export class NgFor<T> { @Input() ngForOf!: Iterable<T>; } ``` (Note: the real `NgFor` directive is more complex than the simplistic version examined here, but the same principles still apply) In this case, the `T` type parameter of `NgFor` represents the value type of the `Iterable` over which we're iterating. This depends entirely on the `Iterable` passed to `NgFor` - if the user passes a `User[]` array, then this should conceptually create an `NgFor<User>` instance. If they pass a `string[]` array, it should be an `NgFor<string>` instead. To infer a correct type for a generic directive, the TCB system generates a **type constructor** for the directive. The type constructor is a "fake" constructor which can be used to infer the directive type based on any provided input bindings. A type constructor for the simplistic `NgFor` directive above would look like: ```typescript declare function ctor1<T>(inputs: {ngForOf?: Iterable<T>}): NgFor<T>; ``` This type constructor can then be used to infer the instance type of a usage of `NgFor` based on provided bindings. For example, the template: ```html= <div *ngFor="let user of users">...</div> ``` Would use the above type constructor in its TCB: ```typescript function tcb(this: SomeCmp): void { var _t1 = ctor1({ngForOf: this.users}); // Assuming this.users is User[], then _t1 is inferred as NgFor<User>. } ``` A single type constructor for a directive can be used in multiple places, whenever an instance of the directive is present in the template.
{ "end_byte": 8768, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/README.md" }
angular/packages/compiler-cli/src/ngtsc/typecheck/README.md_8768_14916
#### Nested templates & structural directives `NgFor` is a structural directive, meaning that it applies to a nested `<ng-template>`. That is, the template: ```html <div *ngFor="let user of users"> {{user.name}} </div> ``` is syntactic sugar for: ```html <ng-template ngFor let-user="$implicit" [ngForOf]="users"> <div>{{user.name}}</div> </ng-template> ``` The `NgFor` directive injects a `TemplateRef` for this _embedded view_, as well as a `ViewContainerRef`, and at runtime creates dynamic instances of this nested template (one per row). Each instance of the embedded view has its own "template context" object, from which any `let` bindings are read. In the TCB, the template context of this nested template is itself a declaration with its own type. Since a structural directive can in theory create embedded views with any context object it wants, the template context type always starts as `any`: ```typescript declare function ctor1(inputs: {ngForOf?: Iterable<T>}): NgFor<T>; function tcb(this: SomeCmp): void { // _t1 is the NgFor directive instance, inferred as NgFor<User>. var _t1 = ctor1({ngForOf: this.users}); // _t2 is the context type for the embedded views created by the NgFor structural directive. var _t2: any; // _t3 is the let-user variable within the embedded view. var _t3 = _t2.$implicit; // Represents the `{{user.name}}` interpolation within the embedded view. '' + _t3.name; } ``` Note that the `any` type of the embedded view context `_t2` effectively disables type-checking of the `{{user.name}}` expression, because the compiler has no idea what type `user` will be when `NgFor` instantiates this embedded view. Since this instantiation is imperative code, the compiler cannot know what `NgFor` will do. ##### Template context hints To solve this problem, the template type-checking engine allows structural directives to _declaratively_ narrow the context type of any embedded views they create. The example `NgFor` directive would do this by declaring a static `ngTemplateContextGuard` function: ```typescript @Directive({selector: '[ngFor]'}) export class NgFor<T> { @Input() ngForOf!: Iterable<T>; static ngTemplateContextGuard<T>(dir: NgFor<T>, ctx: any): ctx is NgForContext<T> { return true; // implementation is not important } } export interface NgForContext<T> { $implicit: T; } ``` The `typecheck` system is aware of the presence of this method on any structural directives used in templates, and uses it to narrow the type of its context declarations. So with this method on `NgFor`, the template from before would now generate a TCB of: ```typescript declare function ctor1(inputs: {ngForOf?: Iterable<T>}): NgFor<T>; function tcb(this: SomeCmp): void { // _t1 is the NgFor directive instance, inferred as NgFor<User>. var _t1 = ctor1({ngForOf: this.users}); // _t2 is the context type for the embedded views created by the NgFor structural directive. var _t2: any; if (NgFor.ngTemplateContextGuard(_t1, _t2)) { // NgFor's ngTemplateContextGuard has narrowed the type of _t2 // based on the type of _t1 (the NgFor directive itself). // Within this `if` block, _t2 is now of type NgForContext<User>. // _t3 is the let-user variable within the embedded view. // Because _t2 is narrowed, _t3 is now of type User. var _t3 = _t2.$implicit; // Represents the `{{user.name}}` interpolation within the embedded view. '' + _t3.name; } } ``` Because the `NgFor` directive _declared_ to the template type checking engine what type it intends to use for embedded views it creates, the TCB has full type information for expressions within the nested template for the `*ngFor` invocation, and the compiler is able to correctly type check the `{{user.name}}` expression. ##### 'binding' guard hints `NgIf` requires a similar, albeit not identical, operation to perform type narrowing with its nested template. Instead of narrowing the template context, `NgIf` wants to narrow the actual type of the expression within its binding. Consider the template: ```html <div *ngIf="user !== null"> {{user.name}} </div> ``` Obviously, if `user` is potentially `null`, then this `NgIf` is intended to only show the `<div>` when `user` actually has a value. However, from a type-checking perspective, the expression `user.name` is not legal if `user` is potentially `null`. So if this template was rendered into a TCB as: ```typescript function tcb(this: SomeCmp): void { // Type of the NgIf directive instance. var _t1: NgIf; // Binding *ngIf="user != null". _t1.ngIf = this.user !== null; // Nested template interpolation `{{user.name}}` '' + this.user.name; } ``` Then the `'' + user.name` line would produce a type error that `user` might be `null`. At runtime, though, the `NgIf` prevents this condition by only instantiating its embedded view if its bound `ngIf` expression is truthy. Similarly to `ngTemplateContextGuard`, the template type checking engine allows `NgIf` to express this behavior by adding a static field: ```typescript @Directive({selector: '[ngIf]'}) export class NgIf { @Input() ngIf!: boolean; static ngTemplateGuard_ngIf: 'binding'; } ``` The presence and type of this static property tells the template type-checking engine to reflect the bound expression for its `ngIf` input as a guard for any embedded views created by the structural directive. This produces a TCB: ```typescript function tcb(this: SomeCmp): void { // Type of the NgIf directive instance. var _t1: NgIf; // Binding *ngIf="user != null". _t1.ngIf = this.user !== null; // Guard generated due to the `ngTemplateGuard_ngIf` declaration by the NgIf directive. if (user !== null) { // Nested template interpolation `{{user.name}}`. // `this.user` here is appropriately narrowed to be non-nullable. '' + this.user.name; } } ``` The guard expression causes TypeScript to narrow the type of `this.user` within the `if` block and identify that `this.user` cannot be `null` within the embedded view context, just as `NgIf` itself does during rendering.
{ "end_byte": 14916, "start_byte": 8768, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/README.md" }
angular/packages/compiler-cli/src/ngtsc/typecheck/README.md_14916_21910
### Generation process Angular templates allow forward references. For example, the template: ```html The value is: {{in.value}} <input #in> ``` contains an expression which makes use of the `#in` local reference before the targeted `<input #in>` element is declared. Since such forward references are not legal in TypeScript code, the TCB may need to declare and check template structures in a different order than the template itself. #### Two phase generation To support this out-of-order generation, the template type checking engine processes templates using an abstraction of known as a `TcbOp`, or TCB operation. `TcbOp`s have two main behaviors: 1. Executing a `TcbOp` appends code to the TCB being generated. 2. Executing a `TcbOp` optionally returns an identifier or expression, which can be used by other operations to refer to some aspect of the generated structure. The main algorithm for TCB generation then makes use of this abstraction: 1. The template is processed in a depth-first manner, and `TcbOp`s representing the code to be generated for the structures and expressions within are enqueued into a `TcbOp` queue. 2. Execution of operations begins from the start of the queue. 3. As each `TcbOp` is executed, its result is recorded. 4. An executing `TcbOp` may request the results of other `TcbOp`s for any dependencies, even `TcbOp`s which appear later in the queue and have not yet executed. 5. Such dependency `TcbOp`s are executed "on demand", when requested. This potential out-of-order execution of `TcbOp`s allows for the TCB ordering to support forward references within templates. The above forward reference example thus results in a `TcbOp` queue of two operations: ```typescript [ TcbTextInterpolationOp(`in.value`), TcbElementOp('<input #in>'), ] ``` Execution of the first `TcbTextInterpolationOp` will attempt to generate code representing the expression. Doing this requires knowing the type of the `in` reference, which maps to the element node for the `<input>`. Therefore, as part of executing the `TcbTextInterpolationOp`, the execution of the `TcbElementOp` will be requested. This operation produces TCB code for the element: ```typescript var t1 = document.createElement('input'); ``` and returns the expression `t1` which represents the element type. The `TcbTextInterpolationOp` can then finish executing and produce its code: ```typescript '' + t1.value; ``` resulting in a final TCB: ```typescript var t1 = document.createElement('input'); '' + t1.value; ``` This ordering resolves the forward reference from the original template. ##### Tracking of `TcbOp`s In practice, a `TcbOp` queue is maintained as an array, where each element begins as a `TcbOp` and is later replaced with the resulting `ts.Expression` once the operation is executed. As `TcbOp`s are generated for various template structures, the index of these operations is recorded. Future dependencies on those operations can then be satisfied by looking in the queue at the appropriate index. The contents will either be a `TcbOp` which has yet to be executed, or the result of the required operation. #### `Scope` Angular templates are nested structures, as the main template can contain embedded views, which can contain their own views. Much like in other programming languages, this leads to a scoped hierarchy of symbol visibility and name resolution. This is reflected in the TCB generation system via the `Scope` class, which actually performs the TCB generation itself. Each embedded view is its own `Scope`, with its own `TcbOp` queue. When a parent `Scope` processing a template encounters an `<ng-template>` node: 1. a new child `Scope` is created from the nodes of the embedded view. 2. a `TcbTemplateBodyOp` is added to the parent scope's queue, which upon execution triggers generation of the child `Scope`'s TCB code and inserts it into the parent's code at the right position. Resolution of names (such as local refs) within the template is also driven by the `Scope` hierarchy. Resolution of a name within a particular embedded view begins in that view's `Scope`. If the name is not defined there, resolution proceeds upwards to the parent `Scope`, all the way up to the root template `Scope`. If the name resolves in any given `Scope`, the associated `TcbOp` can be executed and returned. If the name does not resolve even at the root scope, then it's treated as a reference to the component context for the template. #### Breaking cycles It's possible for a template to contain a referential cycle. As a contrived example, if a component is generic over one of its inputs: ```html <generic-cmp #ref [in]="ref.value"></generic-cmp> ``` Here, type-checking the `[in]` binding requires knowing the type of `ref`, which is the `<generic-cmp>`. But the `<generic-cmp>` type is inferred using a type constructor for the component which requires the `[in]` binding expression: ```typescript declare function ctor1<T>(inputs: {in?: T}): GenericCmp<T>; function tcb(this: SomeCmp): void { // Not legal: cannot refer to t1 (ref) before its declaration. var t1 = ctor1({in: t1.value}); t1.in = t1.value; } ``` This is only a cycle in the _type_ sense. At runtime, the component is created before its inputs are set, so no cycle exists. To get around this, `TcbOp`s may optionally provide a fallback value via a `circularFallback()` method, which will be used in the event that evaluation of a `TcbOp` attempts to re-enter its own evaluation. In the above example, the `TcbOp` for the directive type declares a fallback which infers a type for the directive _without_ using its bound inputs: ```typescript declare function ctor1<T>(inputs: {in?: T}): GenericCmp<T>; function tcb(this: SomeCmp): void { // Generated to break the cycle for `ref` - infers a placeholder // type for the component without using any of its input bindings. var t1 = ctor1(null!); // Infer the real type of the component using the `t1` placeholder // type for `ref`. var t2 = ctor1({in: t1.value}); // Check the binding to [in] using the real type of `ref`. t2.in = t2.value; } ``` #### Optional operations Some `TcbOp`s are marked as optional. Optional operations are never executed as part of processing the op queue, and are skipped when encountered directly. However, other ops may depend on the results of optional operations, and the optional ops are then executed when requested in this manner. The TCB node generated to represent a DOM element type (`TcbElementOp`) is an example of such an optional operation. Such nodes are only useful if the type of the element is referenced in some other context (such as via a `#ref` local reference). If not, then including it in the TCB only serves to bloat the TCB and increase the time it takes TypeScript to process it. Therefore, the `TcbElementOp` is optional. If nothing requires the element type, it won't be executed and no code will be generated for the element node.
{ "end_byte": 21910, "start_byte": 14916, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/README.md" }
angular/packages/compiler-cli/src/ngtsc/typecheck/README.md_21910_29888
### Source mapping and diagnostic translation Once TCB code is generated, TypeScript is able to process it. One use case is to have TypeScript produce diagnostics related to type issues within the TCB code, which indicate type issues within the template itself. These diagnostics are of course expressed in terms of the TCB itself, but the compiler wants to report diagnostics to the user in terms of the original template text. To do this, the template type checking system is capable of mapping from the TCB back to the original template. The algorithm to perform this mapping relies on the emission of source mapping information into the TCB itself, in the form of comments. Consider a template expression of the form: ```html {{foo.bar}} ``` The generated TCB code for this expression would look like: ```typescript '' + this.foo.bar; ``` What actually gets generated for this expression looks more like: ```typescript '' + (this.foo /* 3,5 */).bar /* 3,9 */; ``` The trailing comment for each node in the TCB indicates the template offsets for the corresponding template nodes. If for example TypeScript returns a diagnostic for the `this.foo` part of the expression (such as if `foo` is not a valid property on the component context), the attached comment can be used to map this diagnostic back to the original template's `foo` node. #### `TemplateId` As multiple TCBs can be present in a single typecheck file, an additional layer of mapping is necessary to determine the component and template for a given TCB diagnostic. During TCB generation, a numeric `TemplateId` is assigned to each template declared within a given input file. These `TemplateId` are attached in a comment to the TCBs for each template within the corresponding typecheck files. So the full algorithm for mapping a diagnostic back to the original template involves two steps: 1. Locate the top level TCB function declaration that contains the TCB node in error, extract its `TemplateId`, and use that to locate the component and template in question. 2. Locate the closest source map comment to the TCB node in error, and combine that with knowledge of the template to locate the template node in error to produce the template diagnostic. #### Ignore markers Occasionally, code needs to be generated in the TCB that should not produce diagnostics. For example, a safe property navigation operation `a?.b` is mapped to a TypeScript ternary operation `a ? a.b : undefined` (the actual code here may be more complex). If the original `a` expression is in error, then redundant diagnostics would be produced from both instances of `a` in the generated TCB code. To avoid this, generated code can be marked with a special comment indicating that any diagnostics produced within should be ignored and not converted into template diagnostics. #### Why not real sourcemaps? TypeScript unfortunately cannot consume sourcemaps, only produce them. Therefore, it's impossible to generate a source map to go along with the TCB code and feed it to TypeScript. ### Generation diagnostics Not all template errors will be caught by TypeScript from generated TCB code. The template type checking engine may also detect errors during the creation of the TCB itself. Several classes of errors are caught this way: * DOM schema errors, like elements that don't exist or attributes that aren't correct. * Missing pipes. * Missing `#ref` targets. * Duplicate `let-variable`s. * Attempts to write to a `let-variable`. These errors manifest as "generation diagnostics", diagnostics which are produced during TCB generation, before TCB code is fed to TypeScript. They're ultimately reported together with any converted TCB diagnostics, but are tracked separately by the type checking system. ### Inline operations In certain cases, generation of TCBs as separate, independent structures may not be possible. #### Inline type constructors The mechanics of generic directive type constructors were described above. However, the example given was for a directive with an unbounded generic type. If the directive has a _bounded_ generic type, then the type bounds must be repeated as part of the type constructor. For example, consider the directive: ```typescript @Directive({selector: '[dir]'}) export class MyDir<T extends string> { @Input() value: T; } ``` In order to properly infer and check the type of this directive, the type constructor must include the generic bounds: ```typescript declare function ctor1<T extends string>(inputs: {value?: T}): MyDir<T>; ``` A generic bound for a type parameter is an arbitrary type, which may contain references to other types. These other types may be imported, or declared locally in the same file as a directive. This means that copying the generic bounds into the type constructor for the directive is not always straightforward, as the TCB which requires this type constructor is usually not emitted into the same file as the directive itself. For example, copying the generic bounds is not possible for the directive: ```typescript interface PrivateInterface { field: string; } @Directive({selector: '[dir]'}) export class MyDir<T extends PrivateInterface> { @Input() value: T; } ``` In such cases, the type checking system falls back to an alternative mechanism for declaring type constructors: adding them as static methods on the directive class itself. As part of the type checking phase, the above directive would be transformed to: ```typescript interface PrivateInterface { field: string; } @Directive({selector: '[dir]'}) export class MyDir<T extends PrivateInterface> { @Input() value: T; static ngTypeCtor<T extends PrivateInterface>(inputs: {value?: T}): MyDir<T> { return null!; } } ``` Putting the type constructor declaration within the directive class itself allows the generic signature to be copied without issue, as any references to other types in the same file will still be valid. The type constructor can then be consumed from a TCB as `MyDir.ngTypeCtor`. This is known as an "inline" type constructor. Additions of such inline type checking code have significant ramifications on the performance of template type checking, as discussed below. #### Inline Type Check Blocks A similar problem exists for generic components and the declaration of TCBs. A TCB function must also copy the generic bounds of its context component: ```typescript function tcb<T extends string>(this: SomeCmp<T>): void { /* tcb code */ } ``` If `SomeCmp`'s generic bounds are more complex and reference types that cannot be safely reproduced in the separate context of the TCB, then a similar workaround is employed: the compiler generates the TCB as an "inline" static method on the component. This can also happen for components which aren't themselves importable: ```typescript it('should type-check components declared within functions', () => { @Component({ selector: 'some-cmp', template: '{{foo.bar}}'}) class SomeCmp { foo: Foo = {...}; } }); ``` Such component declarations are still processed by the compiler and can still be type checked using inline TCBs. ### `Environment` TCBs are not standalone, and require supporting code such as imports to be properly checked. Additionally, multiple TCBs can share declarations regarding common dependencies, such as type constructors for directives as well as pipe instances. Each TCB is therefore generated in the context of an `Environment`, which loosely represents the file which will ultimately contain the TCB code. During TCB generation, the `Environment` is used to obtain references to imported types, type constructors, and other shared structures. #### `TypeCheckingConfig` `Environment` also carries the `TypeCheckingConfig`, an options interface which controls the specifics of TCB generation. Through the `TypeCheckingConfig`, a consumer can enable or disable various kinds of strictness checks and other TCB operations.
{ "end_byte": 29888, "start_byte": 21910, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/README.md" }
angular/packages/compiler-cli/src/ngtsc/typecheck/README.md_29888_35457
## The `TemplateTypeChecker` The main interface used by consumers to interact with the template type checking system is the `TemplateTypeChecker`. Methods on this interface allow for various operations related to TCBs, such as: * Generation of diagnostics. * Retrieving `Symbol`s (the template equivalent to TypeScript's `ts.Symbol`) for template nodes. * Retrieving TCB locations suitable for autocompletion operations. ### Symbols The TCB structures representing specific template nodes and operations are highly useful for "code intelligence" purposes, not just for type checking. For example, consider the "Go to Definition" function within an IDE. Within TypeScript code, TypeScript's language service can access semantic information about an identifier under the user's cursor, and locate the referenced declaration for that identifier. Because TCBs are TypeScript code, the TypeScript language service can be used within TCB code to locate definitions in a similar manner. Such a "template language service" works in the following manner: 1. Find the template node under the user's cursor. 2. Locate its equivalent structure in the TCB. 3. Ask TypeScript's language service to perform the requested operation on the TCB node. Step 2 in this algorithm is made possible by the `TemplateTypeChecker`'s APIs for retrieving `Symbol`s for template nodes. A `Symbol` is a structure describing the TCB information associated with a given template node, including positions within the TCB where type information about the node in question can be found. For example, an `ElementSymbol` contains a TCB location for the element type, as well as any directives which may be present on the element. Such information can be used by a consumer to query TypeScript for further information about the types present in the template for that element. This is used in the Angular Language Service to implement many of its features. ## The type checking workflow Like TypeScript's `ts.TypeChecker`, the `TemplateTypeChecker`'s operations are lazy. TCB code for a given template is only generated on demand, to satisfy a query for information about that specific template. Once generated, future queries regarding that template can be answered using the existing TCB structure. The lazy algorithm used by the `TemplateTypeChecker` is as follows. 1. Given a query, determine which (if any) components need TCBs generated. 2. Request sufficient information about those components and any used directives/pipes from the main compiler. 3. Generate TCB source text. 4. Obtain a `ts.Program` containing the new, generated TCBs. 5. Use TypeScript APIs against this program and the TCBs to answer the query. To enable the most flexibility for integrating the template type checking engine into various compilation workflows, steps 2 and 4 are abstracted behind interfaces. ### Step 2: template information To answer most queries, the `TemplateTypeChecker` will require the TCB for a specific component. If not already generated, this involves generating a TCB for that component, and incorporating that TCB somehow into a new `ts.Program`. Each source file in the user's program has a corresponding synthetic "typecheck" file which holds the TCBs for any components it contains. Updating this typecheck file with new contents (a new TCB) has a large fixed cost, regardless of the scope of the textual change to the file. Thus, the `TemplateTypeChecker` will always generate _all_ TCBs for a given input file, instead of just the one it needs. The marginal cost of generating the extra TCBs is extremely low. To perform this generation, the type checking system first constructs a "context" into which template information can be recorded. It then requests (via an interface, the `ProgramTypeCheckAdapter`) that this context be populated with information about any templates present in the input file(s) it needs to process. Once populated, the information in the context can be used to drive TCB generation. This process is somewhat complicated by the bookkeeping required to track which TCBs have been generated as well as the source mapping information for components within those TCBs. On the compiler side, this interface drives the `TraitCompiler` to call the `typeCheck()` method of the `ComponentDecoratorHandler` for each decorated component class. ### Step 4: `ts.Program`s The main output of the TCB generation mechanism is a list of new text contents for various source files. Typically this contains new TCB text for "typecheck" source files, but inline operations may require changes to actual user input files. Before diagnostics can be produced or the `ts.TypeChecker` API can be used to interrogate types within the TCBs, these changes need to be parsed and incorporated into a `ts.Program`. Creating such a `ts.Program` is not the responsibility of the `TemplateTypeChecker`. Instead, this creation is abstracted behind the `TypeCheckingProgramStrategy` interface. A strategy which implements this interface allows the type checking system to request textual changes be applied to the current `ts.Program`, resulting in an updated `ts.Program`. As a convenience, the type-checking system provides an implementation of this abstraction, the `ReusedProgramStrategy`, which can be used by consumers that manage `ts.Program`s via TypeScript's `ts.createProgram` API. The main compiler uses this strategy to support template type checking. `ts.Program`s can also be created via Language Service APIs, which would require a different strategy implementation.
{ "end_byte": 35457, "start_byte": 29888, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/README.md" }
angular/packages/compiler-cli/src/ngtsc/typecheck/BUILD.bazel_0_1185
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "typecheck", 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/imports", "//packages/compiler-cli/src/ngtsc/incremental:api", "//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/shims:api", "//packages/compiler-cli/src/ngtsc/translator", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/compiler-cli/src/ngtsc/typecheck/diagnostics", "//packages/compiler-cli/src/ngtsc/util", "@npm//@types/node", "@npm//magic-string", "@npm//typescript", ], )
{ "end_byte": 1185, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/BUILD.bazel" }
angular/packages/compiler-cli/src/ngtsc/typecheck/index.ts_0_465
/** * @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 {FileTypeCheckingData, TemplateTypeCheckerImpl} from './src/checker'; export {TypeCheckContextImpl, getTemplateDiagnostics} from './src/context'; export {TypeCheckShimGenerator} from './src/shim'; export {typeCheckFilePath} from './src/type_check_file';
{ "end_byte": 465, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/index.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_parameter_emitter_spec.ts_0_936
/** * @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, LogicalFileSystem} from '../../file_system'; import {runInEachFileSystem, TestFile} from '../../file_system/testing'; import { AbsoluteModuleStrategy, ImportFlags, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, ReferenceEmitter, } from '../../imports'; import {isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection'; import {getDeclaration, makeProgram} from '../../testing'; import {Environment} from '../src/environment'; import {TypeCheckFile} from '../src/type_check_file'; import {TypeParameterEmitter} from '../src/type_parameter_emitter'; import {ALL_ENABLED_CONFIG, angularCoreDtsFiles, typescriptLibDts} from '../testing';
{ "end_byte": 936, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_parameter_emitter_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_parameter_emitter_spec.ts_938_9761
runInEachFileSystem(() => { describe('type parameter emitter', () => { function createEmitter(source: string, additionalFiles: TestFile[] = []) { const files: TestFile[] = [ ...angularCoreDtsFiles(), {name: absoluteFrom('/app/main.ts'), contents: source}, ...additionalFiles, ]; const {program, host} = makeProgram(files, undefined, undefined, false); const checker = program.getTypeChecker(); const reflector = new TypeScriptReflectionHost(checker); const TestClass = getDeclaration( program, absoluteFrom('/app/main.ts'), 'TestClass', isNamedClassDeclaration, ); const moduleResolver = new ModuleResolver( program, program.getCompilerOptions(), host, /* moduleResolutionCache */ null, ); const refEmitter = new ReferenceEmitter([ new LocalIdentifierStrategy(), new AbsoluteModuleStrategy(program, checker, moduleResolver, reflector), new LogicalProjectStrategy(reflector, new LogicalFileSystem([absoluteFrom('/app')], host)), ]); const env = new TypeCheckFile( absoluteFrom('/app/main.ngtypecheck.ts'), ALL_ENABLED_CONFIG, refEmitter, reflector, host, ); const emitter = new TypeParameterEmitter(TestClass.typeParameters, reflector); return {emitter, env}; } function emit( {emitter, env}: {emitter: TypeParameterEmitter; env: Environment}, flags?: ImportFlags, ) { const canEmit = emitter.canEmit((ref) => env.canReferenceType(ref, flags)); let emitted: ts.TypeParameterDeclaration[] | undefined; try { emitted = emitter.emit((ref) => env.referenceType(ref, flags)); expect(canEmit).toBe(true); } catch (e) { expect(canEmit).toBe(false); throw e; } if (emitted === undefined) { return ''; } const printer = ts.createPrinter({newLine: ts.NewLineKind.LineFeed}); const sf = ts.createSourceFile('test.ts', '', ts.ScriptTarget.Latest); const generics = emitted .map((param) => printer.printNode(ts.EmitHint.Unspecified, param, sf)) .join(', '); return `<${generics}>`; } it('can emit for simple generic types', () => { expect(emit(createEmitter(`export class TestClass {}`))).toEqual(''); expect(emit(createEmitter(`export class TestClass<T> {}`))).toEqual('<T>'); expect(emit(createEmitter(`export class TestClass<T extends any> {}`))).toEqual( '<T extends any>', ); expect(emit(createEmitter(`export class TestClass<T extends unknown> {}`))).toEqual( '<T extends unknown>', ); expect(emit(createEmitter(`export class TestClass<T extends string> {}`))).toEqual( '<T extends string>', ); expect(emit(createEmitter(`export class TestClass<T extends number> {}`))).toEqual( '<T extends number>', ); expect(emit(createEmitter(`export class TestClass<T extends boolean> {}`))).toEqual( '<T extends boolean>', ); expect(emit(createEmitter(`export class TestClass<T extends object> {}`))).toEqual( '<T extends object>', ); expect(emit(createEmitter(`export class TestClass<T extends null> {}`))).toEqual( '<T extends null>', ); expect(emit(createEmitter(`export class TestClass<T extends undefined> {}`))).toEqual( '<T extends undefined>', ); expect(emit(createEmitter(`export class TestClass<T extends string[]> {}`))).toEqual( '<T extends string[]>', ); expect(emit(createEmitter(`export class TestClass<T extends [string, boolean]> {}`))).toEqual( '<T extends [\n string,\n boolean\n]>', ); expect(emit(createEmitter(`export class TestClass<T extends string | boolean> {}`))).toEqual( '<T extends string | boolean>', ); expect(emit(createEmitter(`export class TestClass<T extends string & boolean> {}`))).toEqual( '<T extends string & boolean>', ); expect( emit(createEmitter(`export class TestClass<T extends { [key: string]: boolean }> {}`)), ).toEqual('<T extends {\n [key: string]: boolean;\n}>'); }); it('can emit literal types', () => { expect(emit(createEmitter(`export class TestClass<T extends 'a"a'> {}`))).toEqual( `<T extends "a\\"a">`, ); expect(emit(createEmitter(`export class TestClass<T extends "b\\\"b"> {}`))).toEqual( `<T extends "b\\"b">`, ); expect(emit(createEmitter(`export class TestClass<T extends \`c\\\`c\`> {}`))).toEqual( `<T extends \`c\\\`c\`>`, ); expect(emit(createEmitter(`export class TestClass<T extends -1> {}`))).toEqual( `<T extends -1>`, ); expect(emit(createEmitter(`export class TestClass<T extends 1> {}`))).toEqual( `<T extends 1>`, ); expect(emit(createEmitter(`export class TestClass<T extends 1n> {}`))).toEqual( `<T extends 1n>`, ); }); it('cannot emit import types', () => { const emitter = createEmitter(`export class TestClass<T extends import('module')> {}`); expect(() => emit(emitter)).toThrowError('Unable to emit import type'); }); it('can emit references into external modules', () => { const emitter = createEmitter(` import {NgIterable} from '@angular/core'; export class TestClass<T extends NgIterable<any>> {}`); expect(emit(emitter)).toEqual('<T extends i0.NgIterable<any>>'); }); it('can emit references into external modules using qualified name', () => { const emitter = createEmitter(` import * as ng from '@angular/core'; export class TestClass<T extends ng.NgIterable<any>> {}`); expect(emit(emitter)).toEqual('<T extends i0.NgIterable<any>>'); }); it('can emit references to other type parameters', () => { const emitter = createEmitter(` import {NgIterable} from '@angular/core'; export class TestClass<T, U extends NgIterable<T>> {}`); expect(emit(emitter)).toEqual('<T, U extends i0.NgIterable<T>>'); }); it('can emit references to local, exported declarations', () => { const emitter = createEmitter(` class Local {}; export {Local}; export class TestClass<T extends Local> {}`); expect(emit(emitter)).toEqual('<T extends i0.Local>'); }); it('cannot emit references to non-exported local declarations', () => { const emitter = createEmitter(` class Local {}; export class TestClass<T extends Local> {}`); expect(() => emit(emitter)).toThrow(); }); it('cannot emit references to local declarations as nested type arguments', () => { const emitter = createEmitter(` import {NgIterable} from '@angular/core'; class Local {}; export class TestClass<T extends NgIterable<Local>> {}`); expect(() => emit(emitter)).toThrow(); }); it('can emit references into external modules within array types', () => { const emitter = createEmitter(` import {NgIterable} from '@angular/core'; export class TestClass<T extends NgIterable[]> {}`); expect(emit(emitter)).toEqual('<T extends i0.NgIterable[]>'); }); it('cannot emit references to local declarations within array types', () => { const emitter = createEmitter(` class Local {}; export class TestClass<T extends Local[]> {}`); expect(() => emit(emitter)).toThrow(); }); it('can emit references into relative files', () => { const additionalFiles: TestFile[] = [ { name: absoluteFrom('/app/internal.ts'), contents: `export class Internal {}`, }, ]; const emitter = createEmitter( ` import {Internal} from './internal'; export class TestClass<T extends Internal> {}`, additionalFiles, ); expect(emit(emitter)).toEqual('<T extends i0.Internal>'); }); it('cannot emit references into relative source files that are outside of rootDirs', () => { const additionalFiles: TestFile[] = [ { name: absoluteFrom('/internal.ts'), contents: `export class Internal {}`, }, ]; const emitter = createEmitter( ` import {Internal} from '../internal'; export class TestClass<T extends Internal> {}`, additionalFiles, ); // The `internal.ts` source file is outside `rootDir` and importing from it would trigger // TS6059, so this emit should fail. expect(() => emit(emitter)).toThrow(); });
{ "end_byte": 9761, "start_byte": 938, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_parameter_emitter_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_parameter_emitter_spec.ts_9767_14948
it('can emit references into relative declaration files that are outside of rootDirs', () => { const additionalFiles: TestFile[] = [ { name: absoluteFrom('/internal.d.ts'), contents: `export class Internal {}`, }, ]; const emitter = createEmitter( ` import {Internal} from '../internal'; export class TestClass<T extends Internal> {}`, additionalFiles, ); // The `internal.d.ts` is outside `rootDir` but declaration files do not trigger TS6059, so we // allow such an import to be created. expect(emit(emitter)).toEqual('<T extends i0.Internal>'); }); it('cannot emit unresolved references', () => { const emitter = createEmitter(` import {Internal} from 'unresolved'; export class TestClass<T extends Internal> {}`); expect(() => emit(emitter)).toThrow(); }); it('can emit references to exported classes imported using a namespace import', () => { const additionalFiles: TestFile[] = [ { name: absoluteFrom('/app/internal.ts'), contents: `export class Internal {}`, }, ]; const emitter = createEmitter( ` import * as ns from './internal'; export class TestClass<T extends ns.Internal> {}`, additionalFiles, ); expect(emit(emitter)).toEqual('<T extends i0.Internal>'); }); it('cannot emit references to local classes exported within a namespace', () => { const additionalFiles: TestFile[] = [ { name: absoluteFrom('/app/ns.ts'), contents: ` export namespace ns { export class Nested {} } `, }, ]; const emitter = createEmitter( ` import {ns} from './ns'; export class TestClass<T extends ns.Nested> {}`, additionalFiles, ); expect(() => emit(emitter)).toThrow(); }); it('cannot emit references to external classes exported within a namespace', () => { const additionalFiles: TestFile[] = [ { name: absoluteFrom('/node_modules/ns/index.d.ts'), contents: ` export namespace ns { export declare class Nested {} } `, }, ]; const emitter = createEmitter( ` import {ns} from 'ns'; export class TestClass<T extends ns.Nested> {}`, additionalFiles, ); expect(() => emit(emitter)).toThrow(); }); it('can emit references to interfaces', () => { const additionalFiles: TestFile[] = [ { name: absoluteFrom('/node_modules/types/index.d.ts'), contents: `export declare interface MyInterface {}`, }, ]; const emitter = createEmitter( ` import {MyInterface} from 'types'; export class TestClass<T extends MyInterface> {}`, additionalFiles, ); expect(emit(emitter)).toEqual('<T extends i0.MyInterface>'); }); it('can emit references to enums', () => { const additionalFiles: TestFile[] = [ { name: absoluteFrom('/node_modules/types/index.d.ts'), contents: `export declare enum MyEnum {}`, }, ]; const emitter = createEmitter( ` import {MyEnum} from 'types'; export class TestClass<T extends MyEnum> {}`, additionalFiles, ); expect(emit(emitter)).toEqual('<T extends i0.MyEnum>'); }); it('can emit references to type aliases', () => { const additionalFiles: TestFile[] = [ { name: absoluteFrom('/node_modules/types/index.d.ts'), contents: `export declare type MyType = string;`, }, ]; const emitter = createEmitter( ` import {MyType} from 'types'; export class TestClass<T extends MyType> {}`, additionalFiles, ); expect(emit(emitter)).toEqual('<T extends i0.MyType>'); }); it('transforms generic type parameter defaults', () => { const additionalFiles: TestFile[] = [ { name: absoluteFrom('/node_modules/types/index.d.ts'), contents: `export declare type MyType = string;`, }, ]; const emitter = createEmitter( ` import {MyType} from 'types'; export class TestClass<T extends MyType = MyType> {}`, additionalFiles, ); expect(emit(emitter)).toEqual('<T extends i0.MyType = i0.MyType>'); }); it('cannot emit when a type parameter default cannot be emitted', () => { const emitter = createEmitter(` interface Local {} export class TestClass<T extends object = Local> {}`); expect(() => emit(emitter)).toThrow(); }); it('can opt into emitting references to ambient types', () => { const emitter = createEmitter(`export class TestClass<T extends HTMLElement> {}`, [ typescriptLibDts(), ]); expect(emit(emitter, ImportFlags.AllowAmbientReferences)).toBe('<T extends HTMLElement>'); }); }); });
{ "end_byte": 14948, "start_byte": 9767, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_parameter_emitter_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts_0_5086
/** * @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, getSourceFileOrError} from '../../file_system'; import {initMockFileSystem} from '../../file_system/testing'; import {Reference} from '../../imports'; import {OptimizeFor, TypeCheckingConfig} from '../api'; import {ALL_ENABLED_CONFIG, setup, tcb, TestDeclaration, TestDirective} from '../testing'; describe('type check blocks', () => { beforeEach(() => initMockFileSystem('Native')); it('should generate a basic block for a binding', () => { expect(tcb('{{hello}} {{world}}')).toContain('"" + (((this).hello)) + (((this).world));'); }); it('should generate literal map expressions', () => { const TEMPLATE = '{{ method({foo: a, bar: b}) }}'; expect(tcb(TEMPLATE)).toContain('(this).method({ "foo": ((this).a), "bar": ((this).b) })'); }); it('should generate literal array expressions', () => { const TEMPLATE = '{{ method([a, b]) }}'; expect(tcb(TEMPLATE)).toContain('(this).method([((this).a), ((this).b)])'); }); it('should handle non-null assertions', () => { const TEMPLATE = `{{a!}}`; expect(tcb(TEMPLATE)).toContain('((((this).a))!)'); }); it('should handle unary - operator', () => { const TEMPLATE = `{{-1}}`; expect(tcb(TEMPLATE)).toContain('(-1)'); }); it('should handle keyed property access', () => { const TEMPLATE = `{{a[b]}}`; expect(tcb(TEMPLATE)).toContain('(((this).a))[((this).b)]'); }); it('should handle nested ternary expressions', () => { const TEMPLATE = `{{a ? b : c ? d : e}}`; expect(tcb(TEMPLATE)).toContain( '(((this).a) ? ((this).b) : ((((this).c) ? ((this).d) : (((this).e)))))', ); }); it('should handle nullish coalescing operator', () => { expect(tcb('{{ a ?? b }}')).toContain('((((this).a)) ?? (((this).b)))'); expect(tcb('{{ a ?? b ?? c }}')).toContain('(((((this).a)) ?? (((this).b))) ?? (((this).c)))'); expect(tcb('{{ (a ?? b) + (c ?? e) }}')).toContain( '(((((this).a)) ?? (((this).b))) + ((((this).c)) ?? (((this).e))))', ); }); it('should handle typeof expressions', () => { expect(tcb('{{typeof a}}')).toContain('typeof (((this).a))'); expect(tcb('{{!(typeof a)}}')).toContain('!(typeof (((this).a)))'); expect(tcb('{{!(typeof a === "object")}}')).toContain( '!((typeof (((this).a))) === ("object"))', ); }); it('should handle attribute values for directive inputs', () => { const TEMPLATE = `<div dir inputA="value"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'DirA', selector: '[dir]', inputs: {inputA: 'inputA'}, }, ]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain('_t1 = null! as i0.DirA; _t1.inputA = ("value");'); }); it('should handle multiple bindings to the same property', () => { const TEMPLATE = `<div dir-a [inputA]="1" [inputA]="2"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'DirA', selector: '[dir-a]', inputs: {inputA: 'inputA'}, }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('_t1.inputA = (1);'); expect(block).toContain('_t1.inputA = (2);'); }); it('should handle empty bindings', () => { const TEMPLATE = `<div dir-a [inputA]=""></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'DirA', selector: '[dir-a]', inputs: {inputA: 'inputA'}, }, ]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain('_t1.inputA = (undefined);'); }); it('should handle bindings without value', () => { const TEMPLATE = `<div dir-a [inputA]></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'DirA', selector: '[dir-a]', inputs: {inputA: 'inputA'}, }, ]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain('_t1.inputA = (undefined);'); }); it('should handle implicit vars on ng-template', () => { const TEMPLATE = `<ng-template let-a></ng-template>`; expect(tcb(TEMPLATE)).toContain('var _t2 = _t1.$implicit;'); }); it('should handle method calls of template variables', () => { const TEMPLATE = `<ng-template let-a>{{a(1)}}</ng-template>`; expect(tcb(TEMPLATE)).toContain('var _t2 = _t1.$implicit;'); expect(tcb(TEMPLATE)).toContain('_t2(1)'); }); it('should handle implicit vars when using microsyntax', () => { const TEMPLATE = `<div *ngFor="let user of users"></div>`; expect(tcb(TEMPLATE)).toContain('var _t2 = _t1.$implicit;'); }); it('should handle direct calls of an implicit template variable', () => { const TEMPLATE = `<div *ngFor="let a of letters">{{a(1)}}</div>`; expect(tcb(TEMPLATE)).toContain('var _t2 = _t1.$implicit;'); expect(tcb(TEMPLATE)).toContain('_t2(1)'); });
{ "end_byte": 5086, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts_5090_12645
describe('type constructors', () => { it('should handle missing property bindings', () => { const TEMPLATE = `<div dir [inputA]="foo"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { fieldA: 'inputA', fieldB: 'inputB', }, isGeneric: true, }, ]; const actual = tcb(TEMPLATE, DIRECTIVES); expect(actual).toContain( 'const _ctor1: <T extends string = any>(init: Pick<i0.Dir<T>, "fieldA" | "fieldB">) => i0.Dir<T> = null!;', ); expect(actual).toContain( 'var _t1 = _ctor1({ "fieldA": (((this).foo)), "fieldB": 0 as any });', ); }); it('should handle multiple bindings to the same property', () => { const TEMPLATE = `<div dir [inputA]="1" [inputA]="2"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { fieldA: 'inputA', }, isGeneric: true, }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('"fieldA": (1)'); expect(block).not.toContain('"fieldA": (2)'); }); it('should only apply property bindings to directives', () => { const TEMPLATE = ` <div dir [style.color]="'blue'" [class.strong]="false" [attr.enabled]="true"></div> `; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: {'color': 'color', 'strong': 'strong', 'enabled': 'enabled'}, isGeneric: true, }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).not.toContain('Dir.ngTypeCtor'); expect(block).toContain('"blue"; false; true;'); }); it('should generate a circular directive reference correctly', () => { const TEMPLATE = ` <div dir #d="dir" [input]="d"></div> `; const DIRECTIVES: TestDirective[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', exportAs: ['dir'], inputs: {input: 'input'}, isGeneric: true, }, ]; const actual = tcb(TEMPLATE, DIRECTIVES); expect(actual).toContain( 'const _ctor1: <T extends string = any>(init: Pick<i0.Dir<T>, "input">) => i0.Dir<T> = null!;', ); expect(actual).toContain( 'var _t2 = _ctor1({ "input": (null!) }); ' + 'var _t1 = _t2; ' + '_t2.input = (_t1);', ); }); it('should generate circular references between two directives correctly', () => { const TEMPLATE = ` <div #a="dirA" dir-a [inputA]="b">A</div> <div #b="dirB" dir-b [inputB]="a">B</div> `; const DIRECTIVES: TestDirective[] = [ { type: 'directive', name: 'DirA', selector: '[dir-a]', exportAs: ['dirA'], inputs: {inputA: 'inputA'}, isGeneric: true, }, { type: 'directive', name: 'DirB', selector: '[dir-b]', exportAs: ['dirB'], inputs: {inputB: 'inputB'}, isGeneric: true, }, ]; const actual = tcb(TEMPLATE, DIRECTIVES); expect(actual).toContain( 'const _ctor1: <T extends string = any>(init: Pick<i0.DirA<T>, "inputA">) => i0.DirA<T> = null!; const _ctor2: <T extends string = any>(init: Pick<i0.DirB<T>, "inputB">) => i0.DirB<T> = null!;', ); expect(actual).toContain( 'var _t4 = _ctor1({ "inputA": (null!) }); ' + 'var _t3 = _t4; ' + 'var _t2 = _ctor2({ "inputB": (_t3) }); ' + 'var _t1 = _t2; ' + '_t4.inputA = (_t1); ' + '_t2.inputB = (_t3);', ); }); it('should handle empty bindings', () => { const TEMPLATE = `<div dir-a [inputA]=""></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'DirA', selector: '[dir-a]', inputs: {inputA: 'inputA'}, isGeneric: true, }, ]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain('"inputA": (undefined)'); }); it('should handle bindings without value', () => { const TEMPLATE = `<div dir-a [inputA]></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'DirA', selector: '[dir-a]', inputs: {inputA: 'inputA'}, isGeneric: true, }, ]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain('"inputA": (undefined)'); }); it('should use coercion types if declared', () => { const TEMPLATE = `<div dir [inputA]="foo"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { fieldA: 'inputA', }, isGeneric: true, coercedInputFields: ['fieldA'], }, ]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain( 'var _t1 = null! as typeof i0.Dir.ngAcceptInputType_fieldA; ' + '_t1 = (((this).foo));', ); }); }); it('should only generate code for DOM elements that are actually referenced', () => { const TEMPLATE = ` <div></div> <button #me (click)="handle(me)"></button> `; const block = tcb(TEMPLATE); expect(block).not.toContain('"div"'); expect(block).toContain( 'var _t2 = document.createElement("button"); ' + 'var _t1 = _t2; ' + '_t2.addEventListener', ); }); it('should only generate directive declarations that have bindings or are referenced', () => { const TEMPLATE = ` <div hasInput [input]="value" hasOutput (output)="handle()" hasReference #ref="ref" noReference noBindings>{{ref.a}}</div> `; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'HasInput', selector: '[hasInput]', inputs: {input: 'input'}, }, { type: 'directive', name: 'HasOutput', selector: '[hasOutput]', outputs: {output: 'output'}, }, { type: 'directive', name: 'HasReference', selector: '[hasReference]', exportAs: ['ref'], }, { type: 'directive', name: 'NoReference', selector: '[noReference]', exportAs: ['no-ref'], }, { type: 'directive', name: 'NoBindings', selector: '[noBindings]', inputs: {unset: 'unset'}, }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('var _t1 = null! as i0.HasInput'); expect(block).toContain('_t1.input = (((this).value));'); expect(block).toContain('var _t2 = null! as i0.HasOutput'); expect(block).toContain('_t2["output"]'); expect(block).toContain('var _t4 = null! as i0.HasReference'); expect(block).toContain('var _t3 = _t4;'); expect(block).toContain('(_t3).a'); expect(block).not.toContain('NoBindings'); expect(block).not.toContain('NoReference'); }); it('should generate a forward element reference correctly', () => { const TEMPLATE = ` {{ i.value }} <input #i> `; expect(tcb(TEMPLATE)).toContain( 'var _t2 = document.createElement("input"); var _t1 = _t2; "" + (((_t1).value));', ); });
{ "end_byte": 12645, "start_byte": 5090, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts_12649_19516
it('should generate a forward directive reference correctly', () => { const TEMPLATE = ` {{d.value}} <div dir #d="dir"></div> `; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', exportAs: ['dir'], }, ]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain( 'var _t2 = null! as i0.Dir; ' + 'var _t1 = _t2; ' + '"" + (((_t1).value));', ); }); it('should handle style and class bindings specially', () => { const TEMPLATE = ` <div [style]="a" [class]="b"></div> `; const block = tcb(TEMPLATE); expect(block).toContain('((this).a); ((this).b);'); // There should be no assignments to the class or style properties. expect(block).not.toContain('.class = '); expect(block).not.toContain('.style = '); }); it('should only apply property bindings to directives', () => { const TEMPLATE = ` <div dir [style.color]="'blue'" [class.strong]="false" [attr.enabled]="true"></div> `; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: {'color': 'color', 'strong': 'strong', 'enabled': 'enabled'}, }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).not.toContain('var _t1 = null! as Dir;'); expect(block).not.toContain('"color"'); expect(block).not.toContain('"strong"'); expect(block).not.toContain('"enabled"'); expect(block).toContain('"blue"; false; true;'); }); it('should generate a circular directive reference correctly', () => { const TEMPLATE = ` <div dir #d="dir" [input]="d"></div> `; const DIRECTIVES: TestDirective[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', exportAs: ['dir'], inputs: {input: 'input'}, }, ]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain( 'var _t2 = null! as i0.Dir; ' + 'var _t1 = _t2; ' + '_t2.input = (_t1);', ); }); it('should generate circular references between two directives correctly', () => { const TEMPLATE = ` <div #a="dirA" dir-a [inputA]="b">A</div> <div #b="dirB" dir-b [inputB]="a">B</div> `; const DIRECTIVES: TestDirective[] = [ { type: 'directive', name: 'DirA', selector: '[dir-a]', exportAs: ['dirA'], inputs: {inputA: 'inputA'}, }, { type: 'directive', name: 'DirB', selector: '[dir-b]', exportAs: ['dirB'], inputs: {inputA: 'inputB'}, }, ]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain( 'var _t2 = null! as i0.DirB; ' + 'var _t1 = _t2; ' + 'var _t3 = null! as i0.DirA; ' + '_t3.inputA = (_t1); ' + 'var _t4 = _t3; ' + '_t2.inputA = (_t4);', ); }); it('should handle undeclared properties', () => { const TEMPLATE = `<div dir [inputA]="foo"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { fieldA: 'inputA', }, undeclaredInputFields: ['fieldA'], }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).not.toContain('var _t1 = null! as Dir;'); expect(block).toContain('(((this).foo)); '); }); it('should assign restricted properties to temp variables by default', () => { const TEMPLATE = `<div dir [inputA]="foo"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { fieldA: 'inputA', }, restrictedInputFields: ['fieldA'], }, ]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain( 'var _t1 = null! as i0.Dir; ' + 'var _t2 = null! as (typeof _t1)["fieldA"]; ' + '_t2 = (((this).foo)); ', ); }); it('should assign properties via element access for field names that are not JS identifiers', () => { const TEMPLATE = `<div dir [inputA]="foo"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { 'some-input.xs': 'inputA', }, stringLiteralInputFields: ['some-input.xs'], }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain( 'var _t1 = null! as i0.Dir; ' + '_t1["some-input.xs"] = (((this).foo)); ', ); }); it('should handle a single property bound to multiple fields', () => { const TEMPLATE = `<div dir [inputA]="foo"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { field1: 'inputA', field2: 'inputA', }, }, ]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain( 'var _t1 = null! as i0.Dir; ' + '_t1.field2 = _t1.field1 = (((this).foo));', ); }); it('should handle a single property bound to multiple fields, where one of them is coerced', () => { const TEMPLATE = `<div dir [inputA]="foo"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { field1: 'inputA', field2: 'inputA', }, coercedInputFields: ['field1'], }, ]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain( 'var _t1 = null! as typeof i0.Dir.ngAcceptInputType_field1; ' + 'var _t2 = null! as i0.Dir; ' + '_t2.field2 = _t1 = (((this).foo));', ); }); it('should handle a single property bound to multiple fields, where one of them is undeclared', () => { const TEMPLATE = `<div dir [inputA]="foo"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { field1: 'inputA', field2: 'inputA', }, undeclaredInputFields: ['field1'], }, ]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain( 'var _t1 = null! as i0.Dir; ' + '_t1.field2 = (((this).foo));', ); }); it('should use coercion types if declared', () => { const TEMPLATE = `<div dir [inputA]="foo"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { fieldA: 'inputA', }, coercedInputFields: ['fieldA'], }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).not.toContain('var _t1 = null! as Dir;'); expect(block).toContain( 'var _t1 = null! as typeof i0.Dir.ngAcceptInputType_fieldA; ' + '_t1 = (((this).foo));', ); });
{ "end_byte": 19516, "start_byte": 12649, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts_19520_27771
it('should use coercion types if declared, even when backing field is not declared', () => { const TEMPLATE = `<div dir [inputA]="foo"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { fieldA: 'inputA', }, coercedInputFields: ['fieldA'], undeclaredInputFields: ['fieldA'], }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).not.toContain('var _t1 = null! as Dir;'); expect(block).toContain( 'var _t1 = null! as typeof i0.Dir.ngAcceptInputType_fieldA; ' + '_t1 = (((this).foo));', ); }); it('should use transform type if an input has one', () => { const TEMPLATE = `<div dir [fieldA]="expr"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { fieldA: { bindingPropertyName: 'fieldA', classPropertyName: 'fieldA', required: false, isSignal: false, transform: { node: ts.factory.createFunctionDeclaration( undefined, undefined, undefined, undefined, [], undefined, undefined, ), type: new Reference( ts.factory.createUnionTypeNode([ ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword), ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), ]), ), }, }, }, coercedInputFields: ['fieldA'], }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('var _t1 = null! as boolean | string; ' + '_t1 = (((this).expr));'); }); it('should handle $any casts', () => { const TEMPLATE = `{{$any(a)}}`; const block = tcb(TEMPLATE); expect(block).toContain('(((this).a) as any)'); }); it('should handle $any accessed through `this`', () => { const TEMPLATE = `{{this.$any(a)}}`; const block = tcb(TEMPLATE); expect(block).toContain('((this).$any(((this).a)))'); }); it('should handle $any accessed through a property read', () => { const TEMPLATE = `{{foo.$any(a)}}`; const block = tcb(TEMPLATE); expect(block).toContain('((((this).foo)).$any(((this).a)))'); }); it('should handle a two-way binding to an input/output pair', () => { const TEMPLATE = `<div twoWay [(input)]="value"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'TwoWay', selector: '[twoWay]', inputs: {input: 'input'}, outputs: {inputChange: 'inputChange'}, }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('var _t1 = null! as i0.TwoWay;'); expect(block).toContain('_t1.input = i1.ɵunwrapWritableSignal((((this).value)));'); }); it('should handle a two-way binding to an input/output pair of a generic directive', () => { const TEMPLATE = `<div twoWay [(input)]="value"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'TwoWay', selector: '[twoWay]', inputs: {input: 'input'}, outputs: {inputChange: 'inputChange'}, isGeneric: true, }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain( 'const _ctor1: <T extends string = any>(init: Pick<i0.TwoWay<T>, "input">) => i0.TwoWay<T> = null!', ); expect(block).toContain( 'var _t1 = _ctor1({ "input": (i1.ɵunwrapWritableSignal(((this).value))) });', ); expect(block).toContain('_t1.input = i1.ɵunwrapWritableSignal((((this).value)));'); }); it('should handle a two-way binding to a model()', () => { const TEMPLATE = `<div twoWay [(input)]="value"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'TwoWay', selector: '[twoWay]', inputs: { input: { classPropertyName: 'input', bindingPropertyName: 'input', required: false, isSignal: true, transform: null, }, }, outputs: {inputChange: 'inputChange'}, }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('var _t1 = null! as i0.TwoWay;'); expect(block).toContain( '_t1.input[i1.ɵINPUT_SIGNAL_BRAND_WRITE_TYPE] = i1.ɵunwrapWritableSignal((((this).value)));', ); }); it('should handle a two-way binding to an input with a transform', () => { const TEMPLATE = `<div twoWay [(input)]="value"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'TwoWay', selector: '[twoWay]', inputs: { input: { classPropertyName: 'input', bindingPropertyName: 'input', required: false, isSignal: false, transform: { node: ts.factory.createFunctionDeclaration( undefined, undefined, undefined, undefined, [], undefined, undefined, ), type: new Reference( ts.factory.createUnionTypeNode([ ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword), ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), ]), ), }, }, }, outputs: {inputChange: 'inputChange'}, coercedInputFields: ['input'], }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('var _t1 = null! as boolean | string;'); expect(block).toContain('_t1 = i1.ɵunwrapWritableSignal((((this).value)));'); }); describe('experimental DOM checking via lib.dom.d.ts', () => { it('should translate unclaimed bindings to their property equivalent', () => { const TEMPLATE = `<label [for]="'test'"></label>`; const CONFIG = {...ALL_ENABLED_CONFIG, checkTypeOfDomBindings: true}; expect(tcb(TEMPLATE, /* declarations */ undefined, CONFIG)).toContain( '_t1["htmlFor"] = ("test");', ); }); }); describe('template guards', () => { it('should emit invocation guards', () => { const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'NgIf', selector: '[ngIf]', inputs: {'ngIf': 'ngIf'}, ngTemplateGuards: [ { inputName: 'ngIf', type: 'invocation', }, ], }, ]; const TEMPLATE = `<div *ngIf="person">{{person.name}}</div>`; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('if (i0.NgIf.ngTemplateGuard_ngIf(_t1, ((this).person)))'); }); it('should emit binding guards', () => { const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'NgIf', selector: '[ngIf]', inputs: {'ngIf': 'ngIf'}, ngTemplateGuards: [ { inputName: 'ngIf', type: 'binding', }, ], }, ]; const TEMPLATE = `<div *ngIf="person !== null">{{person.name}}</div>`; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('if ((((this).person)) !== (null))'); }); it('should not emit guards when the child scope is empty', () => { const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'NgIf', selector: '[ngIf]', inputs: {'ngIf': 'ngIf'}, ngTemplateGuards: [ { inputName: 'ngIf', type: 'invocation', }, ], }, ]; const TEMPLATE = `<div *ngIf="person">static</div>`; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).not.toContain('NgIf.ngTemplateGuard_ngIf'); }); }); de
{ "end_byte": 27771, "start_byte": 19520, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts_27775_29829
be('outputs', () => { it('should emit subscribe calls for directive outputs', () => { const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', outputs: {'outputField': 'dirOutput'}, }, ]; const TEMPLATE = `<div dir (dirOutput)="foo($event)"></div>`; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain( '_t1["outputField"].subscribe(($event): any => { (this).foo($event); });', ); }); it('should emit a listener function with AnimationEvent for animation events', () => { const TEMPLATE = `<div (@animation.done)="foo($event)"></div>`; const block = tcb(TEMPLATE); expect(block).toContain('($event: i1.AnimationEvent): any => { (this).foo($event); }'); }); it('should emit addEventListener calls for unclaimed outputs', () => { const TEMPLATE = `<div (event)="foo($event)"></div>`; const block = tcb(TEMPLATE); expect(block).toContain( '_t1.addEventListener("event", ($event): any => { (this).foo($event); });', ); }); it('should allow to cast $event using $any', () => { const TEMPLATE = `<div (event)="foo($any($event))"></div>`; const block = tcb(TEMPLATE); expect(block).toContain( '_t1.addEventListener("event", ($event): any => { (this).foo(($event as any)); });', ); }); it('should detect writes to template variables', () => { const TEMPLATE = `<ng-template let-v><div (event)="v = 3"></div></ng-template>`; const block = tcb(TEMPLATE); expect(block).toContain('_t3.addEventListener("event", ($event): any => { (_t2 = 3); });'); }); it('should ignore accesses to $event through `this`', () => { const TEMPLATE = `<div (event)="foo(this.$event)"></div>`; const block = tcb(TEMPLATE); expect(block).toContain( '_t1.addEventListener("event", ($event): any => { (this).foo(((this).$event)); });', ); }); }); de
{ "end_byte": 29829, "start_byte": 27775, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts_29833_38129
be('config', () => { const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', exportAs: ['dir'], inputs: {'dirInput': 'dirInput'}, outputs: {'outputField': 'dirOutput'}, hasNgTemplateContextGuard: true, }, ]; const BASE_CONFIG: TypeCheckingConfig = { applyTemplateContextGuards: true, checkQueries: false, checkTemplateBodies: true, checkControlFlowBodies: true, alwaysCheckSchemaInTemplateBodies: true, checkTypeOfInputBindings: true, honorAccessModifiersForInputBindings: false, strictNullInputBindings: true, checkTypeOfAttributes: true, 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, }; describe('config.applyTemplateContextGuards', () => { const TEMPLATE = `<div *dir>{{ value }}</div>`; const GUARD_APPLIED = 'if (i0.Dir.ngTemplateContextGuard('; it('should apply template context guards when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain(GUARD_APPLIED); }); it('should not apply template context guards when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = { ...BASE_CONFIG, applyTemplateContextGuards: false, }; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).not.toContain(GUARD_APPLIED); }); }); describe('config.checkTemplateBodies', () => { const TEMPLATE = `<ng-template #ref>{{a}}</ng-template>{{ref}}`; it('should descend into template bodies when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('((this).a)'); }); it('should not descend into template bodies when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTemplateBodies: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).not.toContain('((this).a)'); }); it('generates a references var when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('var _t1 = (_t2 as any as i1.TemplateRef<any>);'); }); it('generates a reference var when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTemplateBodies: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('var _t1 = (_t2 as any as i1.TemplateRef<any>);'); }); }); describe('config.strictNullInputBindings', () => { const TEMPLATE = `<div dir [dirInput]="a" [nonDirInput]="b"></div>`; it('should include null and undefined when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('_t1.dirInput = (((this).a));'); expect(block).toContain('((this).b);'); }); it('should use the non-null assertion operator when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = { ...BASE_CONFIG, strictNullInputBindings: false, }; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('_t1.dirInput = (((this).a)!);'); expect(block).toContain('((this).b)!;'); }); }); describe('config.checkTypeOfBindings', () => { it('should check types of bindings when enabled', () => { const TEMPLATE = `<div dir [dirInput]="a" [nonDirInput]="b"></div>`; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('_t1.dirInput = (((this).a));'); expect(block).toContain('((this).b);'); }); it('should not check types of bindings when disabled', () => { const TEMPLATE = `<div dir [dirInput]="a" [nonDirInput]="b"></div>`; const DISABLED_CONFIG: TypeCheckingConfig = { ...BASE_CONFIG, checkTypeOfInputBindings: false, }; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('_t1.dirInput = ((((this).a) as any));'); expect(block).toContain('(((this).b) as any);'); }); it('should wrap the cast to any in parentheses when required', () => { const TEMPLATE = `<div dir [dirInput]="a === b"></div>`; const DISABLED_CONFIG: TypeCheckingConfig = { ...BASE_CONFIG, checkTypeOfInputBindings: false, }; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('_t1.dirInput = ((((((this).a)) === (((this).b))) as any));'); }); }); describe('config.checkTypeOfOutputEvents', () => { const TEMPLATE = `<div dir (dirOutput)="foo($event)" (nonDirOutput)="foo($event)"></div>`; it('should check types of directive outputs when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain( '_t1["outputField"].subscribe(($event): any => { (this).foo($event); });', ); expect(block).toContain( '_t2.addEventListener("nonDirOutput", ($event): any => { (this).foo($event); });', ); }); it('should not check types of directive outputs when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = { ...BASE_CONFIG, checkTypeOfOutputEvents: false, }; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('($event: any): any => { (this).foo($event); }'); // Note that DOM events are still checked, that is controlled by `checkTypeOfDomEvents` expect(block).toContain( 'addEventListener("nonDirOutput", ($event): any => { (this).foo($event); });', ); }); }); describe('config.checkTypeOfAnimationEvents', () => { const TEMPLATE = `<div (@animation.done)="foo($event)"></div>`; it('should check types of animation events when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('($event: i1.AnimationEvent): any => { (this).foo($event); }'); }); it('should not check types of animation events when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = { ...BASE_CONFIG, checkTypeOfAnimationEvents: false, }; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('($event: any): any => { (this).foo($event); }'); }); }); describe('config.checkTypeOfDomEvents', () => { const TEMPLATE = `<div dir (dirOutput)="foo($event)" (nonDirOutput)="foo($event)"></div>`; it('should check types of DOM events when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain( '_t1["outputField"].subscribe(($event): any => { (this).foo($event); });', ); expect(block).toContain( '_t2.addEventListener("nonDirOutput", ($event): any => { (this).foo($event); });', ); }); it('should not check types of DOM events when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfDomEvents: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); // Note that directive outputs are still checked, that is controlled by // `checkTypeOfOutputEvents` expect(block).toContain( '_t1["outputField"].subscribe(($event): any => { (this).foo($event); });', ); expect(block).toContain('($event: any): any => { (this).foo($event); }'); }); });
{ "end_byte": 38129, "start_byte": 29833, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts_38135_45459
be('config.checkTypeOfDomReferences', () => { const TEMPLATE = `<input #ref>{{ref.value}}`; it('should trace references when enabled', () => { const block = tcb(TEMPLATE); expect(block).toContain('(_t1).value'); }); it('should use any for reference types when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = { ...BASE_CONFIG, checkTypeOfDomReferences: false, }; const block = tcb(TEMPLATE, [], DISABLED_CONFIG); expect(block).toContain('var _t1 = _t2 as any; ' + '"" + (((_t1).value));'); }); }); describe('config.checkTypeOfNonDomReferences', () => { const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', exportAs: ['dir'], inputs: {'dirInput': 'dirInput'}, outputs: {'outputField': 'dirOutput'}, hasNgTemplateContextGuard: true, }, ]; const TEMPLATE = `<div dir #ref="dir">{{ref.value}}</div><ng-template #ref2></ng-template>{{ref2.value2}}`; it('should trace references to a directive when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('(_t1).value'); }); it('should trace references to an <ng-template> when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain( 'var _t3 = (_t4 as any as i1.TemplateRef<any>); ' + '"" + (((_t3).value2));', ); }); it('should use any for reference types when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = { ...BASE_CONFIG, checkTypeOfNonDomReferences: false, }; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('var _t1 = _t2 as any; ' + '"" + (((_t1).value));'); }); }); describe('config.checkTypeOfAttributes', () => { const TEMPLATE = `<textarea dir disabled cols="3" [rows]="2">{{ref.value}}</textarea>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: {'disabled': 'disabled', 'cols': 'cols', 'rows': 'rows'}, }, ]; it('should assign string value to the input when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('_t1.disabled = ("");'); expect(block).toContain('_t1.cols = ("3");'); expect(block).toContain('_t1.rows = (2);'); }); it('should use any for attributes but still check bound attributes when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfAttributes: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).not.toContain('"disabled"'); expect(block).not.toContain('"cols"'); expect(block).toContain('_t1.rows = (2);'); }); }); describe('config.checkTypeOfPipes', () => { const TEMPLATE = `{{a | test:b:c}}`; const PIPES: TestDeclaration[] = [ { type: 'pipe', name: 'TestPipe', pipeName: 'test', }, ]; it('should check types of pipes when enabled', () => { const block = tcb(TEMPLATE, PIPES); expect(block).toContain('var _pipe1 = null! as i0.TestPipe;'); expect(block).toContain('(_pipe1.transform(((this).a), ((this).b), ((this).c)));'); }); it('should not check types of pipes when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfPipes: false}; const block = tcb(TEMPLATE, PIPES, DISABLED_CONFIG); expect(block).toContain('var _pipe1 = null! as i0.TestPipe;'); expect(block).toContain('((_pipe1.transform as any)(((this).a), ((this).b), ((this).c))'); }); }); describe('config.strictSafeNavigationTypes', () => { const TEMPLATE = `{{a?.b}} {{a?.method()}} {{a?.[0]}} {{a.optionalMethod?.()}}`; it('should use undefined for safe navigation operations when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain( '(0 as any ? (0 as any ? (((this).a))!.method : undefined)!() : undefined)', ); expect(block).toContain('(0 as any ? (((this).a))!.b : undefined)'); expect(block).toContain('(0 as any ? (((this).a))![0] : undefined)'); expect(block).toContain('(0 as any ? (((((this).a)).optionalMethod))!() : undefined)'); }); it("should use an 'any' type for safe navigation operations when disabled", () => { const DISABLED_CONFIG: TypeCheckingConfig = { ...BASE_CONFIG, strictSafeNavigationTypes: false, }; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('((((((this).a))!.method as any) as any)())'); expect(block).toContain('((((this).a))!.b as any)'); expect(block).toContain('(((((this).a))![0] as any)'); expect(block).toContain('((((((this).a)).optionalMethod))!() as any)'); }); }); describe('config.strictSafeNavigationTypes (View Engine bug emulation)', () => { const TEMPLATE = `{{a.method()?.b}} {{a()?.method()}} {{a.method()?.[0]}} {{a.method()?.otherMethod?.()}}`; it('should check the presence of a property/method on the receiver when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('(0 as any ? ((((this).a)).method())!.b : undefined)'); expect(block).toContain( '(0 as any ? (0 as any ? ((this).a())!.method : undefined)!() : undefined)', ); expect(block).toContain('(0 as any ? ((((this).a)).method())![0] : undefined)'); expect(block).toContain( '(0 as any ? ((0 as any ? ((((this).a)).method())!.otherMethod : undefined))!() : undefined)', ); }); it('should not check the presence of a property/method on the receiver when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = { ...BASE_CONFIG, strictSafeNavigationTypes: false, }; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('(((((this).a)).method()) as any).b'); expect(block).toContain('(((((this).a()) as any).method as any)())'); expect(block).toContain('(((((this).a)).method()) as any)[0]'); expect(block).toContain('(((((((this).a)).method()) as any).otherMethod)!() as any)'); }); }); describe('config.strictContextGenerics', () => { const TEMPLATE = `Test`; it('should use the generic type of the context when enabled', () => { const block = tcb(TEMPLATE); expect(block).toContain('function _tcb1<T extends string>(this: i0.Test<T>)'); }); it('should use any for the context generic type when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, useContextGenericType: false}; const block = tcb(TEMPLATE, undefined, DISABLED_CONFIG); expect(block).toContain('function _tcb1(this: i0.Test<any>)'); }); });
{ "end_byte": 45459, "start_byte": 38135, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts_45465_49441
be('config.checkAccessModifiersForInputBindings', () => { const TEMPLATE = `<div dir [inputA]="foo"></div>`; it('should assign restricted properties via element access for field names that are not JS identifiers', () => { const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { 'some-input.xs': 'inputA', }, restrictedInputFields: ['some-input.xs'], stringLiteralInputFields: ['some-input.xs'], }, ]; const enableChecks: TypeCheckingConfig = { ...BASE_CONFIG, honorAccessModifiersForInputBindings: true, }; const block = tcb(TEMPLATE, DIRECTIVES, enableChecks); expect(block).toContain( 'var _t1 = null! as i0.Dir; ' + '_t1["some-input.xs"] = (((this).foo)); ', ); }); it('should assign restricted properties via property access', () => { const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { fieldA: 'inputA', }, restrictedInputFields: ['fieldA'], }, ]; const enableChecks: TypeCheckingConfig = { ...BASE_CONFIG, honorAccessModifiersForInputBindings: true, }; const block = tcb(TEMPLATE, DIRECTIVES, enableChecks); expect(block).toContain('var _t1 = null! as i0.Dir; ' + '_t1.fieldA = (((this).foo)); '); }); }); describe('config.allowSignalsInTwoWayBindings', () => { it('should not unwrap signals in two-way binding expressions', () => { const TEMPLATE = `<div twoWay [(input)]="value"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'TwoWay', selector: '[twoWay]', inputs: {input: 'input'}, outputs: {inputChange: 'inputChange'}, }, ]; const block = tcb(TEMPLATE, DIRECTIVES, { ...BASE_CONFIG, allowSignalsInTwoWayBindings: false, }); expect(block).not.toContain('ɵunwrapWritableSignal'); }); it('should not unwrap signals in two-way bindings to generic directives', () => { const TEMPLATE = `<div twoWay [(input)]="value"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'TwoWay', selector: '[twoWay]', inputs: {input: 'input'}, outputs: {inputChange: 'inputChange'}, isGeneric: true, }, ]; const block = tcb(TEMPLATE, DIRECTIVES, { ...BASE_CONFIG, allowSignalsInTwoWayBindings: false, }); expect(block).not.toContain('ɵunwrapWritableSignal'); }); }); }); it( 'should use `any` type for type constructors with bound generic params ' + 'when `useInlineTypeConstructors` is `false`', () => { const template = ` <div dir [inputA]='foo' [inputB]='bar' ></div> `; const declarations: TestDeclaration[] = [ { code: ` interface PrivateInterface{}; export class Dir<T extends PrivateInterface, U extends string> {}; `, type: 'directive', name: 'Dir', selector: '[dir]', inputs: { inputA: 'inputA', inputB: 'inputB', }, isGeneric: true, }, ]; const renderedTcb = tcb(template, declarations, {useInlineTypeConstructors: false}); expect(renderedTcb).toContain(`var _t1 = null! as i0.Dir<any, any>;`); expect(renderedTcb).toContain(`_t1.inputA = (((this).foo));`); expect(renderedTcb).toContain(`_t1.inputB = (((this).bar));`); }, ); desc
{ "end_byte": 49441, "start_byte": 45465, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts_49445_58263
('host directives', () => { it('should generate bindings to host directive inputs/outputs', () => { const TEMPLATE = `<div dir-a [hostInput]="1" (hostOutput)="handle($event)"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'DirA', selector: '[dir-a]', hostDirectives: [ { directive: { type: 'directive', name: 'HostDir', selector: '', inputs: {hostInput: 'hostInput'}, outputs: {hostOutput: 'hostOutput'}, isStandalone: true, }, inputs: ['hostInput'], outputs: ['hostOutput'], }, ], }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('var _t1 = null! as i0.HostDir'); expect(block).toContain('_t1.hostInput = (1)'); expect(block).toContain('_t1["hostOutput"].subscribe'); }); it('should generate bindings to aliased host directive inputs/outputs', () => { const TEMPLATE = `<div dir-a [inputAlias]="1" (outputAlias)="handle($event)"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'DirA', selector: '[dir-a]', hostDirectives: [ { directive: { type: 'directive', name: 'HostDir', selector: '', inputs: {hostInput: 'hostInput'}, outputs: {hostOutput: 'hostOutput'}, isStandalone: true, }, inputs: ['hostInput: inputAlias'], outputs: ['hostOutput: outputAlias'], }, ], }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('var _t1 = null! as i0.HostDir'); expect(block).toContain('_t1.hostInput = (1)'); expect(block).toContain('_t1["hostOutput"].subscribe'); }); it('should generate bindings to an input from a multi-level host directive', () => { const TEMPLATE = `<div dir-a [multiLevelHostInput]="1"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'DirA', selector: '[dir-a]', hostDirectives: [ { directive: { type: 'directive', name: 'HostDir', selector: '', isStandalone: true, hostDirectives: [ { directive: { type: 'directive', name: 'MultiLevelHostDir', selector: '', isStandalone: true, inputs: {'multiLevelHostInput': 'multiLevelHostInput'}, }, inputs: ['multiLevelHostInput'], }, ], }, }, ], }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('var _t1 = null! as i0.MultiLevelHostDir;'); expect(block).toContain('_t1.multiLevelHostInput = (1)'); }); it('should generate references to host directives', () => { const TEMPLATE = `<div dir-a #a="hostA" #b="hostB">{{a.propA}} {{b.propB}}</div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'DirA', selector: '[dir-a]', hostDirectives: [ { directive: { type: 'directive', name: 'HostA', selector: '', isStandalone: true, exportAs: ['hostA'], }, }, { directive: { type: 'directive', name: 'HostB', selector: '', isStandalone: true, exportAs: ['hostB'], }, }, ], }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('var _t2 = null! as i0.HostA;'); expect(block).toContain('var _t4 = null! as i0.HostB;'); expect(block).toContain('(((_t1).propA)) + (((_t3).propB))'); }); it('should generate bindings to the same input both from the host and host input', () => { const TEMPLATE = `<div dir-a [input]="1"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'DirA', selector: '[dir-a]', inputs: {input: 'input'}, hostDirectives: [ { directive: { type: 'directive', name: 'HostDir', selector: '', inputs: {input: 'input'}, isStandalone: true, }, inputs: ['input'], }, ], }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('var _t1 = null! as i0.HostDir'); expect(block).toContain('var _t2 = null! as i0.DirA;'); expect(block).toContain('_t1.input = (1)'); expect(block).toContain('_t2.input = (1)'); }); it('should not generate bindings to host directive inputs/outputs that have not been exposed', () => { const TEMPLATE = `<div dir-a [hostInput]="1" (hostOutput)="handle($event)"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'DirA', selector: '[dir-a]', hostDirectives: [ { directive: { type: 'directive', name: 'HostDir', selector: '', inputs: {hostInput: 'hostInput'}, outputs: {hostOutput: 'hostOutput'}, isStandalone: true, }, // Intentionally left blank. inputs: [], outputs: [], }, ], }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).not.toContain('var _t1 = null! i0.HostDir'); expect(block).not.toContain('_t1.hostInput = (1)'); expect(block).not.toContain('_t1["hostOutput"].subscribe'); expect(block).toContain('_t1.addEventListener("hostOutput"'); }); it('should generate bindings to aliased host directive inputs/outputs on a host with its own aliases', () => { const TEMPLATE = `<div dir-a [inputAlias]="1" (outputAlias)="handle($event)"></div>`; const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'DirA', selector: '[dir-a]', hostDirectives: [ { directive: { type: 'directive', name: 'HostDir', selector: '', inputs: {hostInput: 'hostInputAlias'}, outputs: {hostOutput: 'hostOutputAlias'}, isStandalone: true, }, inputs: ['hostInputAlias: inputAlias'], outputs: ['hostOutputAlias: outputAlias'], }, ], }, ]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('var _t1 = null! as i0.HostDir'); expect(block).toContain('_t1.hostInput = (1)'); expect(block).toContain('_t1["hostOutput"].subscribe'); }); }); describe('deferred blocks', () => { it('should generate bindings inside deferred blocks', () => { const TEMPLATE = ` @defer { {{main()}} } @placeholder { {{placeholder()}} } @loading { {{loading()}} } @error { {{error()}} } `; expect(tcb(TEMPLATE)).toContain( '"" + ((this).main()); "" + ((this).placeholder()); "" + ((this).loading()); "" + ((this).error());', ); }); it('should generate `when` trigger', () => { const TEMPLATE = ` @defer (when shouldShow() && isVisible) { {{main()}} } `; expect(tcb(TEMPLATE)).toContain('((this).shouldShow()) && (((this).isVisible));'); }); it('should generate `prefetch when` trigger', () => { const TEMPLATE = ` @defer (prefetch when shouldShow() && isVisible) { {{main()}} } `; expect(tcb(TEMPLATE)).toContain('((this).shouldShow()) && (((this).isVisible));'); }); it('should generate `hydrate when` trigger', () => { const TEMPLATE = ` @defer (hydrate when shouldShow() && isVisible) { {{main()}} } `; expect(tcb(TEMPLATE)).toContain('((this).shouldShow()) && (((this).isVisible));'); }); }); desc
{ "end_byte": 58263, "start_byte": 49445, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts_58267_63881
('conditional blocks', () => { it('should generate an if block', () => { const TEMPLATE = ` @if (expr === 0) { {{main()}} } @else if (expr1 === 1) { {{one()}} } @else if (expr2 === 2) { {{two()}} } @else { {{other()}} } `; expect(tcb(TEMPLATE)).toContain( 'if ((((this).expr)) === (0)) { "" + ((this).main()); } ' + 'else if ((((this).expr1)) === (1)) { "" + ((this).one()); } ' + 'else if ((((this).expr2)) === (2)) { "" + ((this).two()); } ' + 'else { "" + ((this).other()); }', ); }); it('should generate a guard expression for listener inside conditional', () => { const TEMPLATE = ` @if (expr === 0) { <button (click)="zero()"></button> } @else if (expr === 1) { <button (click)="one()"></button> } @else if (expr === 2) { <button (click)="two()"></button> } @else { <button (click)="otherwise()"></button> } `; const result = tcb(TEMPLATE); expect(result).toContain(`if ((((this).expr)) === (0)) (this).zero();`); expect(result).toContain( `if (!((((this).expr)) === (0)) && (((this).expr)) === (1)) (this).one();`, ); expect(result).toContain( `if (!((((this).expr)) === (0)) && !((((this).expr)) === (1)) && (((this).expr)) === (2)) (this).two();`, ); expect(result).toContain( `if (!((((this).expr)) === (0)) && !((((this).expr)) === (1)) && !((((this).expr)) === (2))) (this).otherwise();`, ); }); it('should generate an if block with an `as` expression', () => { const TEMPLATE = `@if (expr === 1; as alias) { {{alias}} }`; expect(tcb(TEMPLATE)).toContain( 'var _t1 = ((((this).expr)) === (1)); if (((((this).expr)) === (1)) && _t1) { "" + (_t1); } } }', ); }); it('should not generate the body of if blocks when `checkControlFlowBodies` is disabled', () => { const TEMPLATE = ` @if (expr === 0) { {{main()}} } @else if (expr1 === 1) { {{one()}} } @else if (expr2 === 2) { {{two()}} } @else { {{other()}} } `; expect(tcb(TEMPLATE, undefined, {checkControlFlowBodies: false})).toContain( 'if ((((this).expr)) === (0)) { } ' + 'else if ((((this).expr1)) === (1)) { } ' + 'else if ((((this).expr2)) === (2)) { } ' + 'else { }', ); }); it('should generate a switch block', () => { const TEMPLATE = ` @switch (expr) { @case (1) { {{one()}} } @case (2) { {{two()}} } @default { {{default()}} } } `; expect(tcb(TEMPLATE)).toContain( 'switch (((this).expr)) { ' + 'case 1: "" + ((this).one()); break; ' + 'case 2: "" + ((this).two()); break; ' + 'default: "" + ((this).default()); break; }', ); }); it('should generate a switch block that only has a default case', () => { const TEMPLATE = ` @switch (expr) { @default { {{default()}} } } `; expect(tcb(TEMPLATE)).toContain( 'switch (((this).expr)) { default: "" + ((this).default()); break; }', ); }); it('should generate a guard expression for a listener inside a switch case', () => { const TEMPLATE = ` @switch (expr) { @case (1) { <button (click)="one()"></button> } @case (2) { <button (click)="two()"></button> } @default { <button (click)="default()"></button> } } `; const result = tcb(TEMPLATE); expect(result).toContain(`if (((this).expr) === 1) (this).one();`); expect(result).toContain(`if (((this).expr) === 2) (this).two();`); expect(result).toContain(`if (((this).expr) !== 1 && ((this).expr) !== 2) (this).default();`); }); it('should generate a switch block inside a template', () => { const TEMPLATE = ` <ng-template let-expr="exp"> @switch (expr()) { @case ('one') { {{one()}} } @case ('two') { {{two()}} } @default { {{default()}} } } </ng-template> `; expect(tcb(TEMPLATE)).toContain( 'var _t1 = null! as any; { var _t2 = (_t1.exp); switch (_t2()) { ' + 'case "one": "" + ((this).one()); break; ' + 'case "two": "" + ((this).two()); break; ' + 'default: "" + ((this).default()); break; } }', ); }); it('should handle an empty switch block', () => { expect(tcb('@switch (expr) {}')).toContain('if (true) { switch (((this).expr)) { } }'); }); it('should not generate the body of a switch block if checkControlFlowBodies is disabled', () => { const TEMPLATE = ` @switch (expr) { @case (1) { {{one()}} } @case (2) { {{two()}} } @default { {{default()}} } } `; expect(tcb(TEMPLATE, undefined, {checkControlFlowBodies: false})).toContain( 'switch (((this).expr)) { ' + 'case 1: break; ' + 'case 2: break; ' + 'default: break; }', ); }); }); desc
{ "end_byte": 63881, "start_byte": 58267, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts_63885_70912
('for loop blocks', () => { it('should generate a for block', () => { const TEMPLATE = ` @for (item of items; track item) { {{main(item)}} } @empty { {{empty()}} } `; const result = tcb(TEMPLATE); expect(result).toContain('for (const _t1 of ((this).items)!) {'); expect(result).toContain('"" + ((this).main(_t1))'); expect(result).toContain('"" + ((this).empty())'); }); it('should generate a for block with implicit variables', () => { const TEMPLATE = ` @for (item of items; track item) { {{$index}} {{$first}} {{$last}} {{$even}} {{$odd}} {{$count}} } `; const result = tcb(TEMPLATE); expect(result).toContain('for (const _t1 of ((this).items)!) {'); expect(result).toContain('var _t2 = null! as number;'); expect(result).toContain('var _t3 = null! as boolean;'); expect(result).toContain('var _t4 = null! as boolean;'); expect(result).toContain('var _t5 = null! as boolean;'); expect(result).toContain('var _t6 = null! as boolean;'); expect(result).toContain('var _t7 = null! as number;'); expect(result).toContain('"" + (_t2) + (_t3) + (_t4) + (_t5) + (_t6) + (_t7)'); }); it('should generate a for block with aliased variables', () => { const TEMPLATE = ` @for (item of items; track item; let i = $index, f = $first, l = $last, e = $even, o = $odd, c = $count) { {{i}} {{f}} {{l}} {{e}} {{o}} {{c}} } `; const result = tcb(TEMPLATE); expect(result).toContain('for (const _t1 of ((this).items)!) {'); expect(result).toContain('var _t2 = null! as number;'); expect(result).toContain('var _t3 = null! as boolean;'); expect(result).toContain('var _t4 = null! as boolean;'); expect(result).toContain('var _t5 = null! as boolean;'); expect(result).toContain('var _t6 = null! as boolean;'); expect(result).toContain('var _t7 = null! as number;'); expect(result).toContain('"" + (_t2) + (_t3) + (_t4) + (_t5) + (_t6) + (_t7)'); }); it('should read both implicit variables and their alias at the same time', () => { const TEMPLATE = ` @for (item of items; track item; let i = $index) { {{$index}} {{i}} } `; const result = tcb(TEMPLATE); expect(result).toContain('for (const _t1 of ((this).items)!) {'); expect(result).toContain('var _t2 = null! as number;'); expect(result).toContain('var _t3 = null! as number;'); expect(result).toContain('"" + (_t2) + (_t3)'); }); it('should read variable from a parent for loop', () => { const TEMPLATE = ` @for (item of items; track item; let indexAlias = $index) { {{item}} {{indexAlias}} @for (inner of item.items; track inner) { {{item}} {{indexAlias}} {{inner}} {{$index}} } } `; const result = tcb(TEMPLATE); expect(result).toContain('for (const _t1 of ((this).items)!) { var _t2 = null! as number;'); expect(result).toContain('"" + (_t1) + (_t2)'); expect(result).toContain('for (const _t3 of ((_t1).items)!) { var _t4 = null! as number;'); expect(result).toContain('"" + (_t1) + (_t2) + (_t3) + (_t4)'); }); it('should generate the tracking expression of a for loop', () => { const result = tcb(`@for (item of items; track trackingFn($index, item, prop)) {}`); expect(result).toContain('for (const _t1 of ((this).items)!) { var _t2 = null! as number;'); expect(result).toContain('(this).trackingFn(_t2, _t1, ((this).prop));'); }); it('should not generate the body of a for block when checkControlFlowBodies is disabled', () => { const TEMPLATE = ` @for (item of items; track item) { {{main(item)}} } @empty { {{empty()}} } `; const result = tcb(TEMPLATE, undefined, {checkControlFlowBodies: false}); expect(result).toContain('for (const _t1 of ((this).items)!) {'); expect(result).not.toContain('.main'); expect(result).not.toContain('.empty'); }); }); describe('let declarations', () => { it('should generate let declarations as constants', () => { const result = tcb(` @let one = 1; @let two = 2; @let sum = one + two; {{sum}} `); expect(result).toContain('const _t1 = (1);'); expect(result).toContain('const _t2 = (2);'); expect(result).toContain('const _t3 = ((_t1) + (_t2));'); expect(result).toContain('"" + (_t3);'); }); it('should rewrite references to let declarations inside event listeners', () => { const result = tcb(` @let value = 1; <button (click)="doStuff(value)"></button> `); expect(result).toContain('const _t1 = (1);'); expect(result).toContain('var _t2 = document.createElement("button");'); expect(result).toContain( '_t2.addEventListener("click", ($event): any => { (this).doStuff(_t1); });', ); }); }); describe('import generation', () => { const TEMPLATE = `<div dir [test]="null"></div>`; const DIRECTIVE: TestDeclaration = { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { test: { isSignal: true, bindingPropertyName: 'test', classPropertyName: 'test', required: true, transform: null, }, }, }; it('should prefer namespace imports in type check files for new imports', () => { const result = tcb(TEMPLATE, [DIRECTIVE]); expect(result).toContain(`import * as i1 from '@angular/core';`); expect(result).toContain(`[i1.ɵINPUT_SIGNAL_BRAND_WRITE_TYPE]`); }); it('should re-use existing imports from original source files', () => { // This is especially important for inline type check blocks. // See: https://github.com/angular/angular/pull/53521#pullrequestreview-1778130879. const {templateTypeChecker, program, programStrategy} = setup([ { fileName: absoluteFrom('/test.ts'), templates: {'AppComponent': TEMPLATE}, declarations: [DIRECTIVE], source: ` import {Component} from '@angular/core'; // should be re-used class AppComponent {} export class Dir {} `, }, ]); // Trigger type check block generation. templateTypeChecker.getDiagnosticsForFile( getSourceFileOrError(program, absoluteFrom('/test.ts')), OptimizeFor.SingleFile, ); const testSf = getSourceFileOrError(programStrategy.getProgram(), absoluteFrom('/test.ts')); expect(testSf.text).toContain( `import { Component, ɵINPUT_SIGNAL_BRAND_WRITE_TYPE } from '@angular/core'; // should be re-used`, ); expect(testSf.text).toContain(`[ɵINPUT_SIGNAL_BRAND_WRITE_TYPE]`); }); }); });
{ "end_byte": 70912, "start_byte": 63885, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts_0_471
/** * @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 { resetParseTemplateAsSourceFileForTest, setParseTemplateAsSourceFileForTest, } from '../diagnostics'; import {diagnose, ngForDeclaration, ngForDts, ngIfDeclaration, ngIfDts} from '../testing';
{ "end_byte": 471, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts_473_8873
runInEachFileSystem(() => { describe('template diagnostics', () => { it('works for directive bindings', () => { const messages = diagnose( `<div dir [input]="person.name"></div>`, ` class Dir { input: number; } class TestComponent { person: { name: string; }; }`, [ { type: 'directive', name: 'Dir', selector: '[dir]', exportAs: ['dir'], inputs: {input: 'input'}, }, ], ); expect(messages).toEqual([ `TestComponent.html(1, 11): Type 'string' is not assignable to type 'number'.`, ]); }); it('infers type of template variables', () => { const messages = diagnose( `<div *ngFor="let person of persons; let idx=index">{{ render(idx) }}</div>`, ` class TestComponent { persons: {}[]; render(input: string): string { return input; } }`, [ngForDeclaration()], [ngForDts()], ); expect(messages).toEqual([ `TestComponent.html(1, 62): Argument of type 'number' is not assignable to parameter of type 'string'.`, ]); }); it('infers any type when generic type inference fails', () => { const messages = diagnose( `<div *ngFor="let person of persons;">{{ render(person.namme) }}</div>`, ` class TestComponent { persons: any; render(input: string): string { return input; } }`, [ngForDeclaration()], [ngForDts()], ); expect(messages).toEqual([]); }); it('infers type of element references', () => { const messages = diagnose( `<div dir #el>{{ render(el) }}</div>`, ` class Dir { value: number; } class TestComponent { render(input: string): string { return input; } }`, [ { type: 'directive', name: 'Dir', selector: '[dir]', exportAs: ['dir'], }, ], ); expect(messages).toEqual([ `TestComponent.html(1, 24): Argument of type 'HTMLDivElement' is not assignable to parameter of type 'string'.`, ]); }); it('infers type of directive references', () => { const messages = diagnose( `<div dir #dir="dir">{{ render(dir) }}</div>`, ` class Dir { value: number; } class TestComponent { render(input: string): string { return input; } }`, [ { type: 'directive', name: 'Dir', selector: '[dir]', exportAs: ['dir'], }, ], ); expect(messages).toEqual([ `TestComponent.html(1, 31): Argument of type 'Dir' is not assignable to parameter of type 'string'.`, ]); }); it('infers TemplateRef<any> for ng-template references', () => { const messages = diagnose( `<ng-template #tmpl>{{ render(tmpl) }}</ng-template>`, ` class TestComponent { render(input: string): string { return input; } }`, ); expect(messages).toEqual([ `TestComponent.html(1, 30): Argument of type 'TemplateRef<any>' is not assignable to parameter of type 'string'.`, ]); }); it('infers type of template context', () => { const messages = diagnose( `<div *ngFor="let person of persons">{{ person.namme }}</div>`, ` class TestComponent { persons: { name: string; }[]; }`, [ngForDeclaration()], [ngForDts()], ); expect(messages).toEqual([ `TestComponent.html(1, 47): Property 'namme' does not exist on type '{ name: string; }'. Did you mean 'name'?`, ]); }); it('interprets interpolation as strings', () => { const messages = diagnose( `<blockquote title="{{ person }}"></blockquote>`, ` class TestComponent { person: {}; }`, ); expect(messages).toEqual([]); }); it('checks bindings to regular element', () => { const messages = diagnose( `<img [srcc]="src" [height]="heihgt">`, ` class TestComponent { src: string; height: number; }`, ); expect(messages).toEqual([ `TestComponent.html(1, 29): Property 'heihgt' does not exist on type 'TestComponent'. Did you mean 'height'?`, `TestComponent.html(1, 6): Can't bind to 'srcc' since it isn't a known property of 'img'.`, ]); }); it('checks text attributes that are consumed by bindings with literal string types', () => { const messages = diagnose( `<div dir mode="drak"></div><div dir mode="light"></div>`, ` class Dir { mode: 'dark'|'light'; } class TestComponent {}`, [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: {'mode': 'mode'}, }, ], ); expect(messages).toEqual([ `TestComponent.html(1, 10): Type '"drak"' is not assignable to type '"dark" | "light"'.`, ]); }); it('checks expressions in ICUs', () => { const messages = diagnose( `<span i18n>{switch, plural, other { {{interpolation}} {nestedSwitch, plural, other { {{nestedInterpolation}} }} }}</span>`, `class TestComponent {}`, ); expect(messages.sort()).toEqual([ `TestComponent.html(1, 13): Property 'switch' does not exist on type 'TestComponent'.`, `TestComponent.html(1, 39): Property 'interpolation' does not exist on type 'TestComponent'.`, `TestComponent.html(2, 14): Property 'nestedSwitch' does not exist on type 'TestComponent'.`, `TestComponent.html(2, 46): Property 'nestedInterpolation' does not exist on type 'TestComponent'.`, ]); }); it('produces diagnostics for pipes', () => { const messages = diagnose( `<div>{{ person.name | pipe:person.age:1 }}</div>`, ` class Pipe { transform(value: string, a: string, b: string): string { return a + b; } } class TestComponent { person: { name: string; age: number; }; }`, [{type: 'pipe', name: 'Pipe', pipeName: 'pipe'}], ); expect(messages).toEqual([ `TestComponent.html(1, 35): Argument of type 'number' is not assignable to parameter of type 'string'.`, ]); }); it('does not repeat diagnostics for missing pipes in directive inputs', () => { // The directive here is structured so that a type constructor is used, which results in each // input binding being processed twice. This results in the 'uppercase' pipe being resolved // twice, and since it doesn't exist this operation will fail. The test is here to verify that // failing to resolve the pipe twice only produces a single diagnostic (no duplicates). const messages = diagnose( '<div *dir="let x of name | uppercase"></div>', ` class Dir<T> { dirOf: T; } class TestComponent { name: string; }`, [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: {'dirOf': 'dirOf'}, isGeneric: true, }, ], ); expect(messages.length).toBe(1); expect(messages[0]).toContain(`No pipe found with name 'uppercase'.`); }); it('does not repeat diagnostics for errors within LHS of safe-navigation operator', () => { const messages = diagnose( `{{ personn?.name }} {{ personn?.getName() }}`, ` class TestComponent { person: { name: string; getName: () => string; } | null; }`, ); expect(messages).toEqual([ `TestComponent.html(1, 4): Property 'personn' does not exist on type 'TestComponent'. Did you mean 'person'?`, `TestComponent.html(1, 24): Property 'personn' does not exist on type 'TestComponent'. Did you mean 'person'?`, ]); });
{ "end_byte": 8873, "start_byte": 473, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts_8879_15096
it('does not repeat diagnostics for errors used in template guard expressions', () => { const messages = diagnose( `<div *guard="personn.name"></div>`, ` class GuardDir { static ngTemplateGuard_guard: 'binding'; } class TestComponent { person: { name: string; }; }`, [ { type: 'directive', name: 'GuardDir', selector: '[guard]', inputs: {'guard': 'guard'}, ngTemplateGuards: [{inputName: 'guard', type: 'binding'}], undeclaredInputFields: ['guard'], }, ], ); expect(messages).toEqual([ `TestComponent.html(1, 14): Property 'personn' does not exist on type 'TestComponent'. Did you mean 'person'?`, ]); }); it('should retain literal types in object literals together if strictNullInputBindings is disabled', () => { const messages = diagnose( `<div dir [ngModelOptions]="{updateOn: 'change'}"></div>`, ` class Dir { ngModelOptions: { updateOn: 'change'|'blur' }; } class TestComponent {}`, [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: {'ngModelOptions': 'ngModelOptions'}, }, ], [], {strictNullInputBindings: false}, ); expect(messages).toEqual([]); }); it('should retain literal types in array literals together if strictNullInputBindings is disabled', () => { const messages = diagnose( `<div dir [options]="['literal']"></div>`, ` class Dir { options!: Array<'literal'>; } class TestComponent {}`, [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: {'options': 'options'}, }, ], [], {strictNullInputBindings: false}, ); expect(messages).toEqual([]); }); it('does not produce diagnostics for user code', () => { const messages = diagnose( `{{ person.name }}`, ` class TestComponent { person: { name: string; }; render(input: string): number { return input; } // <-- type error here should not be reported }`, ); expect(messages).toEqual([]); }); it('should treat unary operators as literal types', () => { const messages = diagnose( `{{ test(-1) + test(+1) + test(-2) }}`, ` class TestComponent { test(value: -1 | 1): number { return value; } }`, ); expect(messages).toEqual([ `TestComponent.html(1, 32): Argument of type '-2' is not assignable to parameter of type '1 | -1'.`, ]); }); it('should support type-narrowing for methods with type guards', () => { const messages = diagnose( `<div *ngIf="hasSuccess()">{{ success }}</div>`, ` class TestComponent { hasSuccess(): this is { success: boolean }; }`, [ngIfDeclaration()], [ngIfDts()], ); expect(messages).toEqual([]); }); describe('outputs', () => { it('should produce a diagnostic for directive outputs', () => { const messages = diagnose( `<div dir (event)="handleEvent($event)"></div>`, ` import {EventEmitter} from '@angular/core'; class Dir { out = new EventEmitter<number>(); } class TestComponent { handleEvent(event: string): void {} }`, [{type: 'directive', name: 'Dir', selector: '[dir]', outputs: {'out': 'event'}}], ); expect(messages).toEqual([ `TestComponent.html(1, 31): Argument of type 'number' is not assignable to parameter of type 'string'.`, ]); }); it('should produce a diagnostic for animation events', () => { const messages = diagnose( `<div dir (@animation.done)="handleEvent($event)"></div>`, ` class TestComponent { handleEvent(event: string): void {} }`, ); expect(messages).toEqual([ `TestComponent.html(1, 41): Argument of type 'AnimationEvent' is not assignable to parameter of type 'string'.`, ]); }); it('should produce a diagnostic for element outputs', () => { const messages = diagnose( `<div (click)="handleEvent($event)"></div>`, ` import {EventEmitter} from '@angular/core'; class TestComponent { handleEvent(event: string): void {} }`, ); expect(messages).toEqual([ `TestComponent.html(1, 27): Argument of type 'MouseEvent' is not assignable to parameter of type 'string'.`, ]); }); it('should not produce a diagnostic when $event implicitly has an any type', () => { const messages = diagnose( `<div dir (event)="handleEvent($event)"></div>`, ` class Dir { out: any; } class TestComponent { handleEvent(event: string): void {} }`, [{type: 'directive', name: 'Dir', selector: '[dir]', outputs: {'out': 'event'}}], ); expect(messages).toEqual([]); }); // https://github.com/angular/angular/issues/33528 it('should not produce a diagnostic for implicit any return types', () => { const messages = diagnose( `<div (click)="state = null"></div>`, ` class TestComponent { state: any; }`, // Disable strict DOM event checking and strict null checks, to infer an any return type // that would be implicit if the handler function would not have an explicit return // type. [], [], {checkTypeOfDomEvents: false}, {strictNullChecks: false}, ); expect(messages).toEqual([]); }); });
{ "end_byte": 15096, "start_byte": 8879, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts_15102_24082
describe('strict null checks', () => { it('produces diagnostic for unchecked property access', () => { const messages = diagnose( `<div [class.has-street]="person.address.street.length > 0"></div>`, ` export class TestComponent { person: { address?: { street: string; }; }; }`, ); expect(messages).toEqual([`TestComponent.html(1, 41): Object is possibly 'undefined'.`]); }); it('does not produce diagnostic for checked property access', () => { const messages = diagnose( `<div [class.has-street]="person.address && person.address.street.length > 0"></div>`, ` export class TestComponent { person: { address?: { street: string; }; }; }`, ); expect(messages).toEqual([]); }); it('does not produce diagnostic for fallback value using nullish coalescing', () => { const messages = diagnose( `<div>{{ greet(name ?? 'Frodo') }}</div>`, ` export class TestComponent { name: string | null; greet(name: string) { return 'hello ' + name; } }`, ); expect(messages).toEqual([]); }); it('does not produce diagnostic for safe keyed access', () => { const messages = diagnose( `<div [class.red-text]="person.favoriteColors?.[0] === 'red'"></div>`, ` export class TestComponent { person: { favoriteColors?: string[]; }; }`, ); expect(messages).toEqual([]); }); it('infers a safe keyed read as undefined', () => { const messages = diagnose( `<div (click)="log(person.favoriteColors?.[0])"></div>`, ` export class TestComponent { person: { favoriteColors?: string[]; }; log(color: string) { console.log(color); } }`, ); expect(messages).toEqual([ `TestComponent.html(1, 19): Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.`, ]); }); it('does not produce diagnostic for safe calls', () => { const messages = diagnose( `<div [class.is-hobbit]="person.getName?.() === 'Bilbo'"></div>`, ` export class TestComponent { person: { getName?: () => string; }; }`, ); expect(messages).toEqual([]); }); it('infers a safe call return value as undefined', () => { const messages = diagnose( `<div (click)="log(person.getName?.())"></div>`, ` export class TestComponent { person: { getName?: () => string; }; log(name: string) { console.log(name); } }`, ); expect(messages).toEqual([ `TestComponent.html(1, 19): Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.`, ]); }); }); it('computes line and column offsets', () => { const messages = diagnose( ` <div> <img [src]="srcc" [height]="heihgt"> </div> `, ` class TestComponent { src: string; height: number; }`, ); expect(messages).toEqual([ `TestComponent.html(3, 15): Property 'srcc' does not exist on type 'TestComponent'. Did you mean 'src'?`, `TestComponent.html(4, 18): Property 'heihgt' does not exist on type 'TestComponent'. Did you mean 'height'?`, ]); }); it('works for shorthand property declarations', () => { const messages = diagnose( `<div dir [input]="{a, b: 2}"></div>`, ` class Dir { input: {a: string, b: number}; } class TestComponent { a: number; }`, [ { type: 'directive', name: 'Dir', selector: '[dir]', exportAs: ['dir'], inputs: {input: 'input'}, }, ], ); expect(messages).toEqual([ `TestComponent.html(1, 20): Type 'number' is not assignable to type 'string'.`, ]); }); it('works for shorthand property declarations referring to template variables', () => { const messages = diagnose( ` <span #span></span> <div dir [input]="{span, b: 2}"></div> `, ` class Dir { input: {span: string, b: number}; } class TestComponent {}`, [ { type: 'directive', name: 'Dir', selector: '[dir]', exportAs: ['dir'], inputs: {input: 'input'}, }, ], ); expect(messages).toEqual([ `TestComponent.html(3, 30): Type 'HTMLElement' is not assignable to type 'string'.`, ]); }); it('allows access to protected members', () => { const messages = diagnose( `<button (click)="doFoo()">{{ message }}</button>`, ` class TestComponent { protected message = 'Hello world'; protected doFoo(): void {} }`, ); expect(messages).toEqual([]); }); it('disallows access to private members', () => { const messages = diagnose( `<button (click)="doFoo()">{{ message }}</button>`, ` class TestComponent { private message = 'Hello world'; private doFoo(): void {} }`, ); expect(messages).toEqual([ `TestComponent.html(1, 18): Property 'doFoo' is private and only accessible within class 'TestComponent'.`, `TestComponent.html(1, 30): Property 'message' is private and only accessible within class 'TestComponent'.`, ]); }); }); describe('method call spans', () => { it('reports invalid method name on method name span', () => { const messages = diagnose( `{{ person.getNName() }}`, ` export class TestComponent { person: { getName(): string; }; }`, ); expect(messages).toEqual([ `TestComponent.html(1, 11): Property 'getNName' does not exist on type '{ getName(): string; }'. Did you mean 'getName'?`, ]); }); it('reports invalid method call signature on parameter span', () => { const messages = diagnose( `{{ person.getName('abcd') }}`, ` export class TestComponent { person: { getName(): string; }; }`, ); expect(messages).toEqual([`TestComponent.html(1, 19): Expected 0 arguments, but got 1.`]); }); }); describe('safe method call spans', () => { it('reports invalid method name on method name span', () => { const messages = diagnose( `{{ person?.getNName() }}`, ` export class TestComponent { person?: { getName(): string; }; }`, ); expect(messages).toEqual([ `TestComponent.html(1, 12): Property 'getNName' does not exist on type '{ getName(): string; }'. Did you mean 'getName'?`, ]); }); it('reports invalid method call signature on parameter span', () => { const messages = diagnose( `{{ person?.getName('abcd') }}`, ` export class TestComponent { person?: { getName(): string; }; }`, ); expect(messages).toEqual([`TestComponent.html(1, 20): Expected 0 arguments, but got 1.`]); }); }); describe('property write spans', () => { it('reports invalid receiver property access on property access name span', () => { const messages = diagnose( `<div (click)="person.nname = 'jacky'"></div>`, ` export class TestComponent { person: { name: string; }; }`, ); expect(messages).toEqual([ `TestComponent.html(1, 22): Property 'nname' does not exist on type '{ name: string; }'. Did you mean 'name'?`, ]); }); it('reports unassignable value on property write span', () => { const messages = diagnose( `<div (click)="person.name = 2"></div>`, ` export class TestComponent { person: { name: string; }; }`, ); expect(messages).toEqual([ `TestComponent.html(1, 15): Type 'number' is not assignable to type 'string'.`, ]); }); }); // https://github.com/angular/angular/issues/44999
{ "end_byte": 24082, "start_byte": 15102, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts_24085_30079
it('should not fail for components outside of rootDir', () => { // This test configures a component that is located outside the configured `rootDir`. Such // configuration requires that an inline type-check block is used as the reference emitter does // not allow generating imports outside `rootDir`. const messages = diagnose( `{{invalid}}`, `export class TestComponent {}`, [], [], {}, {rootDir: '/root'}, ); expect(messages).toEqual([ `TestComponent.html(1, 3): Property 'invalid' does not exist on type 'TestComponent'.`, ]); }); describe('host directives', () => { it('should produce a diagnostic for host directive input bindings', () => { const messages = diagnose( `<div dir [input]="person.name" [alias]="person.age"></div>`, ` class Dir { } class HostDir { input: number; otherInput: string; } class TestComponent { person: { name: string; age: number; }; }`, [ { type: 'directive', name: 'Dir', selector: '[dir]', hostDirectives: [ { directive: { type: 'directive', name: 'HostDir', selector: '', inputs: {input: 'input', otherInput: 'otherInput'}, isStandalone: true, }, inputs: ['input', 'otherInput: alias'], }, ], }, ], ); expect(messages).toEqual([ `TestComponent.html(1, 11): Type 'string' is not assignable to type 'number'.`, `TestComponent.html(1, 33): Type 'number' is not assignable to type 'string'.`, ]); }); it('should produce a diagnostic for directive outputs', () => { const messages = diagnose( `<div dir (numberAlias)="handleStringEvent($event)" (stringEvent)="handleNumberEvent($event)"></div>`, ` import {EventEmitter} from '@angular/core'; class HostDir { stringEvent = new EventEmitter<string>(); numberEvent = new EventEmitter<number>(); } class Dir { } class TestComponent { handleStringEvent(event: string): void {} handleNumberEvent(event: number): void {} }`, [ { type: 'directive', name: 'Dir', selector: '[dir]', hostDirectives: [ { directive: { type: 'directive', name: 'HostDir', selector: '', isStandalone: true, outputs: {stringEvent: 'stringEvent', numberEvent: 'numberEvent'}, }, outputs: ['stringEvent', 'numberEvent: numberAlias'], }, ], }, ], ); expect(messages).toEqual([ `TestComponent.html(3, 46): Argument of type 'number' is not assignable to parameter of type 'string'.`, `TestComponent.html(4, 46): Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); it('should produce a diagnostic for host directive inputs and outputs that have not been exposed', () => { const messages = diagnose( `<div dir [input]="person.name" (output)="handleStringEvent($event)"></div>`, ` class Dir { } class HostDir { input: number; output = new EventEmitter<number>(); } class TestComponent { person: { name: string; }; handleStringEvent(event: string): void {} }`, [ { type: 'directive', name: 'Dir', selector: '[dir]', hostDirectives: [ { directive: { type: 'directive', name: 'HostDir', selector: '', inputs: {input: 'input'}, outputs: {output: 'output'}, isStandalone: true, }, // Intentionally left blank. inputs: [], outputs: [], }, ], }, ], ); expect(messages).toEqual([ // These messages are expected to refer to the native // typings since the inputs/outputs haven't been exposed. `TestComponent.html(1, 60): Argument of type 'Event' is not assignable to parameter of type 'string'.`, `TestComponent.html(1, 10): Can't bind to 'input' since it isn't a known property of 'div'.`, ]); }); it('should infer the type of host directive references', () => { const messages = diagnose( `<div dir #hostDir="hostDir">{{ render(hostDir) }}</div>`, ` class Dir {} class HostDir { value: number; } class TestComponent { render(input: string): string { return input; } }`, [ { type: 'directive', name: 'Dir', selector: '[dir]', hostDirectives: [ { directive: { type: 'directive', selector: '', isStandalone: true, name: 'HostDir', exportAs: ['hostDir'], }, }, ], }, ], ); expect(messages).toEqual([ `TestComponent.html(1, 39): Argument of type 'HostDir' is not assignable to parameter of type 'string'.`, ]); }); });
{ "end_byte": 30079, "start_byte": 24085, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts_30083_39640
describe('required inputs', () => { it('should produce a diagnostic when a single required input is missing', () => { const messages = diagnose( `<div dir></div>`, ` class Dir { input: any; } class TestComponent {} `, [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { input: { classPropertyName: 'input', bindingPropertyName: 'input', required: true, transform: null, isSignal: false, }, }, }, ], ); expect(messages).toEqual([ `TestComponent.html(1, 1): Required input 'input' from directive Dir must be specified.`, ]); }); it('should produce a diagnostic when a multiple required inputs are missing', () => { const messages = diagnose( `<div dir otherDir></div>`, ` class Dir { input: any; otherInput: any; } class OtherDir { otherDirInput: any; } class TestComponent {} `, [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { input: { classPropertyName: 'input', bindingPropertyName: 'input', required: true, transform: null, isSignal: false, }, otherInput: { classPropertyName: 'otherInput', bindingPropertyName: 'otherInput', required: true, transform: null, isSignal: false, }, }, }, { type: 'directive', name: 'OtherDir', selector: '[otherDir]', inputs: { otherDirInput: { classPropertyName: 'otherDirInput', bindingPropertyName: 'otherDirInput', required: true, transform: null, isSignal: false, }, }, }, ], ); expect(messages).toEqual([ `TestComponent.html(1, 1): Required inputs 'input', 'otherInput' from directive Dir must be specified.`, `TestComponent.html(1, 1): Required input 'otherDirInput' from directive OtherDir must be specified.`, ]); }); it('should report the public name of a missing required input', () => { const messages = diagnose( `<div dir></div>`, ` class Dir { input: any; } class TestComponent {} `, [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { input: { classPropertyName: 'input', bindingPropertyName: 'inputAlias', required: true, transform: null, isSignal: false, }, }, }, ], ); expect(messages).toEqual([ `TestComponent.html(1, 1): Required input 'inputAlias' from directive Dir must be specified.`, ]); }); it('should not produce a diagnostic if a required input is used in a binding', () => { const messages = diagnose( `<div dir [input]="foo"></div>`, ` class Dir { input: any; } class TestComponent { foo: any; } `, [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { input: { classPropertyName: 'input', bindingPropertyName: 'input', required: true, transform: null, isSignal: false, }, }, }, ], ); expect(messages).toEqual([]); }); it('should not produce a diagnostic if a required input is used in a binding through an alias', () => { const messages = diagnose( `<div dir [inputAlias]="foo"></div>`, ` class Dir { input: any; } class TestComponent { foo: any; } `, [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { input: { classPropertyName: 'input', bindingPropertyName: 'inputAlias', required: true, transform: null, isSignal: false, }, }, }, ], ); expect(messages).toEqual([]); }); it('should not produce a diagnostic if a required input is used in a static binding', () => { const messages = diagnose( `<div dir input="hello"></div>`, ` class Dir { input: any; } class TestComponent {} `, [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { input: { classPropertyName: 'input', bindingPropertyName: 'input', required: true, transform: null, isSignal: false, }, }, }, ], ); expect(messages).toEqual([]); }); it('should not produce a diagnostic if a required input is used in a two-way binding', () => { const messages = diagnose( `<div dir [(input)]="foo"></div>`, ` class Dir { input: any; inputChange: any; } class TestComponent { foo: any; } `, [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { input: { classPropertyName: 'input', bindingPropertyName: 'input', required: true, transform: null, isSignal: false, }, }, outputs: {inputChange: 'inputChange'}, }, ], ); expect(messages).toEqual([]); }); it('should not produce a diagnostic for a required input that is the same the directive selector', () => { const messages = diagnose( `<div dir></div>`, ` class Dir { dir: any; } class TestComponent {} `, [ { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { dir: { classPropertyName: 'dir', bindingPropertyName: 'dir', required: true, transform: null, isSignal: false, }, }, }, ], ); expect(messages).toEqual([]); }); it('should produce a diagnostic when a required input from a host directive is missing', () => { const messages = diagnose( `<div dir></div>`, ` class Dir {} class HostDir { input: any; } class TestComponent {}`, [ { type: 'directive', name: 'Dir', selector: '[dir]', hostDirectives: [ { directive: { type: 'directive', name: 'HostDir', selector: '', inputs: { input: { classPropertyName: 'input', bindingPropertyName: 'hostAlias', required: true, transform: null, isSignal: false, }, }, isStandalone: true, }, inputs: ['hostAlias: customAlias'], }, ], }, ], ); expect(messages).toEqual([ `TestComponent.html(1, 1): Required input 'customAlias' from directive HostDir must be specified.`, ]); }); it('should not report missing required inputs for an attribute binding with the same name', () => { const messages = diagnose( `<div [attr.maxlength]="123"></div>`, ` class MaxLengthValidator { maxlength: string; } class TestComponent {} `, [ { type: 'directive', name: 'MaxLengthValidator', selector: '[maxlength]', inputs: { maxlength: { classPropertyName: 'maxlength', bindingPropertyName: 'maxlength', required: true, transform: null, isSignal: false, }, }, }, ], ); expect(messages).toEqual([]); }); }); // https://github.com/angular/angular/issues/43970
{ "end_byte": 39640, "start_byte": 30083, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts_39643_41718
describe('template parse failures', () => { afterEach(resetParseTemplateAsSourceFileForTest); it('baseline test without parse failure', () => { const messages = diagnose( `<div (click)="test(name)"></div>`, ` export class TestComponent { name: string | undefined; test(n: string): void {} }`, ); expect(messages).toEqual([ `TestComponent.html(1, 20): Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.`, ]); }); it('should handle TypeScript parse failures gracefully', () => { setParseTemplateAsSourceFileForTest(() => { throw new Error('Simulated parse failure'); }); const messages = diagnose( `<div (click)="test(name)"></div>`, ` export class TestComponent { name: string | undefined; test(n: string): void {} }`, ); expect(messages.length).toBe(1); expect(messages[0]).toContain( `main.ts(2, 20): Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'. Failed to report an error in 'TestComponent.html' at 1:20 Error: Simulated parse failure`, ); }); it('should handle non-Error failures gracefully', () => { setParseTemplateAsSourceFileForTest(() => { throw 'Simulated parse failure'; }); const messages = diagnose( `<div (click)="test(name)"></div>`, ` export class TestComponent { name: string | undefined; test(n: string): void {} }`, ); expect(messages.length).toBe(1); expect(messages[0]).toContain( `main.ts(2, 20): Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'. Failed to report an error in 'TestComponent.html' at 1:20 Simulated parse failure`, ); }); }); });
{ "end_byte": 41718, "start_byte": 39643, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker_spec.ts_0_7891
/** * @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, ngErrorCode} from '../../diagnostics'; import {absoluteFrom, absoluteFromSourceFile, getSourceFileOrError} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {OptimizeFor} from '../api'; import {getClass, setup, TestDeclaration} from '../testing'; runInEachFileSystem(() => { describe('TemplateTypeChecker', () => { it('should batch diagnostic operations when requested in WholeProgram mode', () => { const file1 = absoluteFrom('/file1.ts'); const file2 = absoluteFrom('/file2.ts'); const {program, templateTypeChecker, programStrategy} = setup([ {fileName: file1, templates: {'Cmp1': '<div></div>'}}, {fileName: file2, templates: {'Cmp2': '<span></span>'}}, ]); templateTypeChecker.getDiagnosticsForFile( getSourceFileOrError(program, file1), OptimizeFor.WholeProgram, ); const ttcProgram1 = programStrategy.getProgram(); templateTypeChecker.getDiagnosticsForFile( getSourceFileOrError(program, file2), OptimizeFor.WholeProgram, ); const ttcProgram2 = programStrategy.getProgram(); expect(ttcProgram1).toBe(ttcProgram2); }); it('should not batch diagnostic operations when requested in SingleFile mode', () => { const file1 = absoluteFrom('/file1.ts'); const file2 = absoluteFrom('/file2.ts'); const {program, templateTypeChecker, programStrategy} = setup([ {fileName: file1, templates: {'Cmp1': '<div></div>'}}, {fileName: file2, templates: {'Cmp2': '<span></span>'}}, ]); templateTypeChecker.getDiagnosticsForFile( getSourceFileOrError(program, file1), OptimizeFor.SingleFile, ); const ttcProgram1 = programStrategy.getProgram(); // ttcProgram1 should not contain a type check block for Cmp2. const ttcSf2Before = getSourceFileOrError(ttcProgram1, absoluteFrom('/file2.ngtypecheck.ts')); expect(ttcSf2Before.text).not.toContain('Cmp2'); templateTypeChecker.getDiagnosticsForFile( getSourceFileOrError(program, file2), OptimizeFor.SingleFile, ); const ttcProgram2 = programStrategy.getProgram(); // ttcProgram2 should now contain a type check block for Cmp2. const ttcSf2After = getSourceFileOrError(ttcProgram2, absoluteFrom('/file2.ngtypecheck.ts')); expect(ttcSf2After.text).toContain('Cmp2'); expect(ttcProgram1).not.toBe(ttcProgram2); }); it('should allow access to the type-check block of a component', () => { const file1 = absoluteFrom('/file1.ts'); const file2 = absoluteFrom('/file2.ts'); const {program, templateTypeChecker, programStrategy} = setup([ {fileName: file1, templates: {'Cmp1': '<div>{{value}}</div>'}}, {fileName: file2, templates: {'Cmp2': '<span></span>'}}, ]); const cmp1 = getClass(getSourceFileOrError(program, file1), 'Cmp1'); const block = templateTypeChecker.getTypeCheckBlock(cmp1); expect(block).not.toBeNull(); expect(block!.getText()).toMatch(/: i[0-9]\.Cmp1/); expect(block!.getText()).toContain(`value`); }); it('should clear old inlines when necessary', () => { const file1 = absoluteFrom('/file1.ts'); const file2 = absoluteFrom('/file2.ts'); const dirFile = absoluteFrom('/dir.ts'); const dirDeclaration: TestDeclaration = { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', isGeneric: true, }; const {program, templateTypeChecker, programStrategy} = setup([ { fileName: file1, templates: {'CmpA': '<div dir></div>'}, declarations: [dirDeclaration], }, { fileName: file2, templates: {'CmpB': '<div dir></div>'}, declarations: [dirDeclaration], }, { fileName: dirFile, source: ` // A non-exported interface used as a type bound for a generic directive causes // an inline type constructor to be required. interface NotExported {} export abstract class TestDir<T extends NotExported> {}`, templates: {}, }, ]); const sf1 = getSourceFileOrError(program, file1); const cmpA = getClass(sf1, 'CmpA'); const sf2 = getSourceFileOrError(program, file2); const cmpB = getClass(sf2, 'CmpB'); // Prime the TemplateTypeChecker by asking for a TCB from file1. expect(templateTypeChecker.getTypeCheckBlock(cmpA)).not.toBeNull(); // Next, ask for a TCB from file2. This operation should clear data on TCBs generated for // file1. expect(templateTypeChecker.getTypeCheckBlock(cmpB)).not.toBeNull(); // This can be detected by asking for a TCB again from file1. Since no data should be // available for file1, this should cause another type-checking program step. const prevTtcProgram = programStrategy.getProgram(); expect(templateTypeChecker.getTypeCheckBlock(cmpA)).not.toBeNull(); expect(programStrategy.getProgram()).not.toBe(prevTtcProgram); }); describe('when inlining is unsupported', () => { it('should not produce errors for components that do not require inlining', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const {program, templateTypeChecker} = setup( [ { fileName, source: `export class Cmp {}`, templates: {'Cmp': '<div dir></div>'}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', }, ], }, { fileName: dirFile, source: `export class TestDir {}`, templates: {}, }, ], {inlining: false}, ); const sf = getSourceFileOrError(program, fileName); const diags = templateTypeChecker.getDiagnosticsForFile(sf, OptimizeFor.WholeProgram); expect(diags.length).toBe(0); }); it('should produce errors for components that require TCB inlining', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup( [ { fileName, source: `abstract class Cmp {} // not exported, so requires inline`, templates: {'Cmp': '<div></div>'}, }, ], {inlining: false}, ); const sf = getSourceFileOrError(program, fileName); const diags = templateTypeChecker.getDiagnosticsForFile(sf, OptimizeFor.WholeProgram); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INLINE_TCB_REQUIRED)); }); }); describe('getTemplateOfComponent()', () => { it("should provide access to a component's real template", () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: { 'Cmp': '<div>Template</div>', }, }, ]); const cmp = getClass(getSourceFileOrError(program, fileName), 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; expect(nodes).not.toBeNull(); expect(nodes[0].sourceSpan.start.file.content).toBe('<div>Template</div>'); }); }); }); });
{ "end_byte": 7891, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/test_case_helper.ts_0_4395
/** * @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 {TypeCheckingConfig} from '../api'; import {diagnose} from '../testing'; export interface TestInput { /** String type of the input. e.g. `InputSignal<string>` or just `string`. */ type: string; /** Whether the input is signal-based and should be registered as such in metadata. */ isSignal: boolean; /** Restriction modifier for the input. e.g. `private`, `protected` etc. */ restrictionModifier?: string; } export interface TestOutput { /** String type of the output. e.g. `EventEmitter<string>`. */ type: string; /** Restriction modifier for the input. e.g. `private`, `protected` etc. */ restrictionModifier?: string; } export interface TestCase { /** Unique id for the test. */ id: string; /** Record of inputs registered in the test directive. */ inputs?: Record<string, TestInput>; /** Record of outputs registered in the test directive. */ outputs?: Record<string, TestOutput>; /** Template of the test component. */ template: string; /** Additional class members to be added to the test directive */ extraDirectiveMembers?: string[]; /** Generics to be added to the test. directive */ directiveGenerics?: string; /** Additional test code that can be added to the test file. */ extraFileContent?: string; /** Test component class code. */ component?: string; /** Expected diagnostics. */ expected: (string | jasmine.AsymmetricMatcher<string>)[]; /** Additional type checking options to be used. */ options?: Partial<TypeCheckingConfig>; /** Whether the test case should exclusively run. */ focus?: boolean; } /** * Diagnoses the given test case, by constructing the test TypeScript file * and running the type checker on it. */ export function typeCheckDiagnose(c: TestCase, compilerOptions?: ts.CompilerOptions) { const inputs = c.inputs ?? {}; const outputs = c.outputs ?? {}; const inputFields = Object.keys(inputs).map( (inputName) => `${inputs[inputName].restrictionModifier ?? ''} ${inputName}: ${inputs[inputName].type}`, ); const outputFields = Object.keys(outputs).map( (name) => `${outputs[name].restrictionModifier ?? ''} ${name}: ${outputs[name].type}`, ); const testComponent = ` import { InputSignal, EventEmitter, OutputEmitterRef, InputSignalWithTransform, ModelSignal, WritableSignal, } from '@angular/core'; ${c.extraFileContent ?? ''} class Dir${c.directiveGenerics ?? ''} { ${inputFields.join('\n')} ${outputFields.join('\n')} ${c.extraDirectiveMembers?.join('\n') ?? ''} } class TestComponent { ${c.component ?? ''} } `; const inputDeclarations = Object.keys(inputs).reduce((res, inputName) => { return { ...res, [inputName]: { bindingPropertyName: inputName, classPropertyName: inputName, isSignal: inputs[inputName].isSignal, required: false, transform: null, }, }; }, {}); const outputDeclarations = Object.keys(outputs).reduce((res, outputName) => { return { ...res, [outputName]: outputName, }; }, {}); const messages = diagnose( c.template, testComponent, [ { type: 'directive', name: 'Dir', selector: '[dir]', exportAs: ['dir'], isGeneric: c.directiveGenerics !== undefined, outputs: outputDeclarations, inputs: inputDeclarations, restrictedInputFields: Object.entries(inputs) .filter(([_, i]) => i.restrictionModifier !== undefined) .map(([name]) => name), }, ], undefined, c.options, compilerOptions, ); expect(messages).toEqual(c.expected); } /** Generates Jasmine `it` specs for all test cases. */ export function generateDiagnoseJasmineSpecs(cases: TestCase[]): void { for (const c of cases) { (c.focus ? fit : it)(c.id, () => { typeCheckDiagnose(c); }); } describe('with `--strict`', () => { for (const c of cases) { (c.focus ? fit : it)(c.id, () => { typeCheckDiagnose(c, {strict: true}); }); } }); }
{ "end_byte": 4395, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/test_case_helper.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts_0_1247
/** * @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 { ASTWithSource, Binary, BindingPipe, Conditional, Interpolation, PropertyRead, TmplAstBoundAttribute, TmplAstBoundText, TmplAstElement, TmplAstForLoopBlock, TmplAstNode, TmplAstReference, TmplAstTemplate, AST, LiteralArray, LiteralMap, TmplAstIfBlock, TmplAstLetDeclaration, ParseTemplateOptions, } from '@angular/compiler'; import ts from 'typescript'; import {absoluteFrom, AbsoluteFsPath, getSourceFileOrError} from '../../file_system'; import {runInEachFileSystem} from '../../file_system/testing'; import {ClassDeclaration} from '../../reflection'; import { DirectiveSymbol, DomBindingSymbol, ElementSymbol, ExpressionSymbol, InputBindingSymbol, LetDeclarationSymbol, OutputBindingSymbol, PipeSymbol, ReferenceSymbol, Symbol, SymbolKind, TemplateSymbol, TemplateTypeChecker, TypeCheckingConfig, VariableSymbol, } from '../api'; import { getClass, ngForDeclaration, ngForTypeCheckTarget, setup as baseTestSetup, TypeCheckingTarget, } from '../testing';
{ "end_byte": 1247, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts_1249_10050
runInEachFileSystem(() => { describe('TemplateTypeChecker.getSymbolOfNode', () => { it('should get a symbol for regular attributes', () => { const fileName = absoluteFrom('/main.ts'); const templateString = `<div id="helloWorld"></div>`; const {templateTypeChecker, program} = setup([ { fileName, templates: {'Cmp': templateString}, source: `export class Cmp {}`, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const {attributes} = getAstElements(templateTypeChecker, cmp)[0]; const symbol = templateTypeChecker.getSymbolOfNode(attributes[0], cmp)!; assertDomBindingSymbol(symbol); assertElementSymbol(symbol.host); }); describe('should get a symbol for text attributes corresponding with a directive input', () => { let fileName: AbsoluteFsPath; let targets: TypeCheckingTarget[]; beforeEach(() => { fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = `<div name="helloWorld"></div>`; targets = [ { fileName, templates: {'Cmp': templateString} as {[key: string]: string}, declarations: [ { name: 'NameDiv', selector: 'div[name]', file: dirFile, type: 'directive' as const, inputs: {name: 'name'}, }, ], }, { fileName: dirFile, source: `export class NameDiv {name!: string;}`, templates: {}, }, ]; }); it('checkTypeOfAttributes = true', () => { const {templateTypeChecker, program} = setup(targets, {checkTypeOfAttributes: true}); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const {attributes} = getAstElements(templateTypeChecker, cmp)[0]; const symbol = templateTypeChecker.getSymbolOfNode(attributes[0], cmp)!; assertInputBindingSymbol(symbol); expect( (symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).name.getText(), ).toEqual('name'); // Ensure we can go back to the original location using the shim location const mapping = templateTypeChecker.getTemplateMappingAtTcbLocation( symbol.bindings[0].tcbLocation, )!; expect(mapping.span.toString()).toEqual('name'); }); it('checkTypeOfAttributes = false', () => { const {templateTypeChecker, program} = setup(targets, {checkTypeOfAttributes: false}); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const {attributes} = getAstElements(templateTypeChecker, cmp)[0]; const symbol = templateTypeChecker.getSymbolOfNode(attributes[0], cmp)!; assertInputBindingSymbol(symbol); expect( (symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).name.getText(), ).toEqual('name'); }); }); describe('templates', () => { describe('ng-templates', () => { let templateTypeChecker: TemplateTypeChecker; let cmp: ClassDeclaration<ts.ClassDeclaration>; let templateNode: TmplAstTemplate; let program: ts.Program; beforeEach(() => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = ` <ng-template dir #ref0 #ref1="dir" let-contextFoo="bar"> <div [input0]="contextFoo" [input1]="ref0" [input2]="ref1"></div> </ng-template>`; const testValues = setup([ { fileName, templates: {'Cmp': templateString}, source: ` export class Cmp { }`, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', exportAs: ['dir'], }, ], }, { fileName: dirFile, source: `export class TestDir {}`, templates: {}, }, ]); templateTypeChecker = testValues.templateTypeChecker; program = testValues.program; const sf = getSourceFileOrError(testValues.program, fileName); cmp = getClass(sf, 'Cmp'); templateNode = getAstTemplates(templateTypeChecker, cmp)[0]; }); it('should get symbol for variables at the declaration', () => { const symbol = templateTypeChecker.getSymbolOfNode(templateNode.variables[0], cmp)!; assertVariableSymbol(symbol); expect(program.getTypeChecker().typeToString(symbol.tsType!)).toEqual('any'); expect(symbol.declaration.name).toEqual('contextFoo'); }); it('should get symbol for variables when used', () => { const symbol = templateTypeChecker.getSymbolOfNode( (templateNode.children[0] as TmplAstTemplate).inputs[0].value, cmp, )!; assertVariableSymbol(symbol); expect(program.getTypeChecker().typeToString(symbol.tsType!)).toEqual('any'); expect(symbol.declaration.name).toEqual('contextFoo'); // Ensure we can map the shim locations back to the template const initializerMapping = templateTypeChecker.getTemplateMappingAtTcbLocation( symbol.initializerLocation, )!; expect(initializerMapping.span.toString()).toEqual('bar'); const localVarMapping = templateTypeChecker.getTemplateMappingAtTcbLocation( symbol.localVarLocation, )!; expect(localVarMapping.span.toString()).toEqual('contextFoo'); }); it('should get a symbol for local ref which refers to a directive', () => { const symbol = templateTypeChecker.getSymbolOfNode(templateNode.references[1], cmp)!; assertReferenceSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol)).toEqual('TestDir'); assertDirectiveReference(symbol); }); it('should get a symbol for usage local ref which refers to a directive', () => { const symbol = templateTypeChecker.getSymbolOfNode( (templateNode.children[0] as TmplAstTemplate).inputs[2].value, cmp, )!; assertReferenceSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol)).toEqual('TestDir'); assertDirectiveReference(symbol); // Ensure we can map the var shim location back to the template const localVarMapping = templateTypeChecker.getTemplateMappingAtTcbLocation( symbol.referenceVarLocation, ); expect(localVarMapping!.span.toString()).toEqual('ref1'); }); function assertDirectiveReference(symbol: ReferenceSymbol) { expect(program.getTypeChecker().typeToString(symbol.tsType)).toEqual('TestDir'); expect((symbol.target as ts.ClassDeclaration).name!.getText()).toEqual('TestDir'); expect(symbol.declaration.name).toEqual('ref1'); } it('should get a symbol for local ref which refers to the template', () => { const symbol = templateTypeChecker.getSymbolOfNode(templateNode.references[0], cmp)!; assertReferenceSymbol(symbol); assertTemplateReference(symbol); }); it('should get a symbol for usage local ref which refers to a template', () => { const symbol = templateTypeChecker.getSymbolOfNode( (templateNode.children[0] as TmplAstTemplate).inputs[1].value, cmp, )!; assertReferenceSymbol(symbol); assertTemplateReference(symbol); }); function assertTemplateReference(symbol: ReferenceSymbol) { expect(program.getTypeChecker().typeToString(symbol.tsType)).toEqual('TemplateRef<any>'); expect((symbol.target as TmplAstTemplate).tagName).toEqual('ng-template'); expect(symbol.declaration.name).toEqual('ref0'); } it('should get symbol for the template itself', () => { const symbol = templateTypeChecker.getSymbolOfNode(templateNode, cmp)!; assertTemplateSymbol(symbol); expect(symbol.directives.length).toBe(1); assertDirectiveSymbol(symbol.directives[0]); expect(symbol.directives[0].tsSymbol.getName()).toBe('TestDir'); }); });
{ "end_byte": 10050, "start_byte": 1249, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts_10058_17983
describe('structural directives', () => { let templateTypeChecker: TemplateTypeChecker; let cmp: ClassDeclaration<ts.ClassDeclaration>; let templateNode: TmplAstTemplate; let program: ts.Program; beforeEach(() => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = ` <div *ngFor="let user of users; let i = index;" dir> {{user.name}} {{user.streetNumber}} <div [tabIndex]="i"></div> </div>`; const testValues = setup([ { fileName, templates: {'Cmp': templateString}, source: ` export interface User { name: string; streetNumber: number; } export class Cmp { users: User[]; } `, declarations: [ ngForDeclaration(), { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {name: 'name'}, }, ], }, ngForTypeCheckTarget(), { fileName: dirFile, source: `export class TestDir {name:string}`, templates: {}, }, ]); templateTypeChecker = testValues.templateTypeChecker; program = testValues.program; const sf = getSourceFileOrError(testValues.program, fileName); cmp = getClass(sf, 'Cmp'); templateNode = getAstTemplates(templateTypeChecker, cmp)[0]; }); it('should retrieve a symbol for a directive on a microsyntax template', () => { const symbol = templateTypeChecker.getSymbolOfNode(templateNode, cmp); const testDir = symbol?.directives.find((dir) => dir.selector === '[dir]'); expect(testDir).toBeDefined(); expect(program.getTypeChecker().symbolToString(testDir!.tsSymbol)).toEqual('TestDir'); }); it('should retrieve a symbol for an expression inside structural binding', () => { const ngForOfBinding = templateNode.templateAttrs.find( (a) => a.name === 'ngForOf', )! as TmplAstBoundAttribute; const symbol = templateTypeChecker.getSymbolOfNode(ngForOfBinding.value, cmp)!; assertExpressionSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol!)).toEqual('users'); expect(program.getTypeChecker().typeToString(symbol.tsType)).toEqual('Array<User>'); }); it('should retrieve a symbol for property reads of implicit variable inside structural binding', () => { const boundText = (templateNode.children[0] as TmplAstElement) .children[0] as TmplAstBoundText; const interpolation = (boundText.value as ASTWithSource).ast as Interpolation; const namePropRead = interpolation.expressions[0] as PropertyRead; const streetNumberPropRead = interpolation.expressions[1] as PropertyRead; const nameSymbol = templateTypeChecker.getSymbolOfNode(namePropRead, cmp)!; assertExpressionSymbol(nameSymbol); expect(program.getTypeChecker().symbolToString(nameSymbol.tsSymbol!)).toEqual('name'); expect(program.getTypeChecker().typeToString(nameSymbol.tsType)).toEqual('string'); const streetSymbol = templateTypeChecker.getSymbolOfNode(streetNumberPropRead, cmp)!; assertExpressionSymbol(streetSymbol); expect(program.getTypeChecker().symbolToString(streetSymbol.tsSymbol!)).toEqual( 'streetNumber', ); expect(program.getTypeChecker().typeToString(streetSymbol.tsType)).toEqual('number'); const userSymbol = templateTypeChecker.getSymbolOfNode(namePropRead.receiver, cmp)!; expectUserSymbol(userSymbol); }); it('finds symbols for variables', () => { const userVar = templateNode.variables.find((v) => v.name === 'user')!; const userSymbol = templateTypeChecker.getSymbolOfNode(userVar, cmp)!; expectUserSymbol(userSymbol); const iVar = templateNode.variables.find((v) => v.name === 'i')!; const iSymbol = templateTypeChecker.getSymbolOfNode(iVar, cmp)!; expectIndexSymbol(iSymbol); }); it('finds symbol when using a template variable', () => { const innerElementNodes = onlyAstElements( (templateNode.children[0] as TmplAstElement).children, ); const indexSymbol = templateTypeChecker.getSymbolOfNode( innerElementNodes[0].inputs[0].value, cmp, )!; expectIndexSymbol(indexSymbol); }); function expectUserSymbol(userSymbol: Symbol) { assertVariableSymbol(userSymbol); expect(userSymbol.tsSymbol!.escapedName).toContain('$implicit'); expect(userSymbol.tsSymbol!.declarations![0].parent!.getText()).toContain( 'NgForOfContext', ); expect(program.getTypeChecker().typeToString(userSymbol.tsType!)).toEqual('User'); expect(userSymbol.declaration).toEqual(templateNode.variables[0]); } function expectIndexSymbol(indexSymbol: Symbol) { assertVariableSymbol(indexSymbol); expect(indexSymbol.tsSymbol!.escapedName).toContain('index'); expect(indexSymbol.tsSymbol!.declarations![0].parent!.getText()).toContain( 'NgForOfContext', ); expect(program.getTypeChecker().typeToString(indexSymbol.tsType!)).toEqual('number'); expect(indexSymbol.declaration).toEqual(templateNode.variables[1]); } }); describe('control flow @if block', () => { let templateTypeChecker: TemplateTypeChecker; let cmp: ClassDeclaration<ts.ClassDeclaration>; let ifBlockNode: TmplAstIfBlock; let program: ts.Program; beforeEach(() => { const fileName = absoluteFrom('/main.ts'); const templateString = ` @if (user; as userAlias) { {{userAlias.name}} {{userAlias.streetNumber}} }`; const testValues = setup([ { fileName, templates: {'Cmp': templateString}, source: ` export interface User { name: string; streetNumber: number; } export class Cmp { user?: User; } `, }, ]); templateTypeChecker = testValues.templateTypeChecker; program = testValues.program; const sf = getSourceFileOrError(testValues.program, fileName); cmp = getClass(sf, 'Cmp'); ifBlockNode = templateTypeChecker.getTemplate(cmp)![0] as unknown as TmplAstIfBlock; }); it('should retrieve a symbol for the loop expression', () => { const symbol = templateTypeChecker.getSymbolOfNode( ifBlockNode.branches[0].expression!, cmp, )!; assertExpressionSymbol(symbol); expectUserSymbol(symbol); }); it('should retrieve a symbol for the track expression', () => { const symbol = templateTypeChecker.getSymbolOfNode( ifBlockNode.branches[0].expressionAlias!, cmp, )!; assertVariableSymbol(symbol); expectUserSymbol(symbol); }); function expectUserSymbol(userSymbol: VariableSymbol | ExpressionSymbol) { expect(userSymbol.tsSymbol!.escapedName).toContain('user'); expect(program.getTypeChecker().typeToString(userSymbol.tsType!)).toEqual( 'User | undefined', ); } });
{ "end_byte": 17983, "start_byte": 10058, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts_17991_23274
describe('control flow @for block', () => { let templateTypeChecker: TemplateTypeChecker; let cmp: ClassDeclaration<ts.ClassDeclaration>; let forLoopNode: TmplAstForLoopBlock; let program: ts.Program; beforeEach(() => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = ` @for (user of users; let i = $index; track user) { <div dir> {{user.name}} {{user.streetNumber}} <div [tabIndex]="i"></div> </div> }`; const testValues = setup([ { fileName, templates: {'Cmp': templateString}, source: ` export interface User { name: string; streetNumber: number; } export class Cmp { users: User[]; } `, }, { fileName: dirFile, source: `export class TestDir {name:string}`, templates: {}, }, ]); templateTypeChecker = testValues.templateTypeChecker; program = testValues.program; const sf = getSourceFileOrError(testValues.program, fileName); cmp = getClass(sf, 'Cmp'); forLoopNode = templateTypeChecker.getTemplate(cmp)![0] as unknown as TmplAstForLoopBlock; }); it('should retrieve a symbol for the loop expression', () => { const symbol = templateTypeChecker.getSymbolOfNode(forLoopNode.expression.ast, cmp)!; assertExpressionSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol!)).toEqual('users'); expect(program.getTypeChecker().typeToString(symbol.tsType)).toEqual('Array<User>'); }); it('should retrieve a symbol for the track expression', () => { const userSymbol = templateTypeChecker.getSymbolOfNode(forLoopNode.trackBy.ast, cmp)!; expectUserSymbol(userSymbol); }); it('should retrieve a symbol for property reads of the loop variable', () => { const boundText = (forLoopNode.children[0] as TmplAstElement) .children[0] as TmplAstBoundText; const interpolation = (boundText.value as ASTWithSource).ast as Interpolation; const namePropRead = interpolation.expressions[0] as PropertyRead; const streetNumberPropRead = interpolation.expressions[1] as PropertyRead; const nameSymbol = templateTypeChecker.getSymbolOfNode(namePropRead, cmp)!; assertExpressionSymbol(nameSymbol); expect(program.getTypeChecker().symbolToString(nameSymbol.tsSymbol!)).toEqual('name'); expect(program.getTypeChecker().typeToString(nameSymbol.tsType)).toEqual('string'); const streetSymbol = templateTypeChecker.getSymbolOfNode(streetNumberPropRead, cmp)!; assertExpressionSymbol(streetSymbol); expect(program.getTypeChecker().symbolToString(streetSymbol.tsSymbol!)).toEqual( 'streetNumber', ); expect(program.getTypeChecker().typeToString(streetSymbol.tsType)).toEqual('number'); const userSymbol = templateTypeChecker.getSymbolOfNode(namePropRead.receiver, cmp)!; expectUserSymbol(userSymbol); }); it('finds symbols for loop variable', () => { const userVar = forLoopNode.item; const userSymbol = templateTypeChecker.getSymbolOfNode(userVar, cmp)!; expectUserSymbol(userSymbol); }); it('finds symbols for $index variable', () => { const iVar = forLoopNode.contextVariables.find((v) => v.name === '$index')!; const iSymbol = templateTypeChecker.getSymbolOfNode(iVar, cmp)!; expect(iVar).toBeTruthy(); expectIndexSymbol(iSymbol, '$index'); }); it('finds symbol when using the index in the body', () => { const innerElementNodes = onlyAstElements( (forLoopNode.children[0] as TmplAstElement).children, ); const indexSymbol = templateTypeChecker.getSymbolOfNode( innerElementNodes[0].inputs[0].value, cmp, )!; expectIndexSymbol(indexSymbol, 'i'); }); function expectUserSymbol(userSymbol: Symbol) { assertVariableSymbol(userSymbol); expect(userSymbol.tsSymbol!.escapedName).toContain('User'); expect(program.getTypeChecker().typeToString(userSymbol.tsType!)).toEqual('User'); expect(userSymbol.declaration).toEqual(forLoopNode.item); } function expectIndexSymbol(indexSymbol: Symbol, localName: string) { const indexVar = forLoopNode.contextVariables.find( (v) => v.value === '$index' && v.name === localName, )!; assertVariableSymbol(indexSymbol); expect(indexVar).toBeTruthy(); expect(indexSymbol.tsSymbol).toBeNull(); // implicit variable doesn't have a TS definition location expect(program.getTypeChecker().typeToString(indexSymbol.tsType!)).toEqual('number'); expect(indexSymbol.declaration).toEqual(indexVar); } }); });
{ "end_byte": 23274, "start_byte": 17991, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts_23280_32270
describe('for expressions', () => { it('should get a symbol for a component property used in an input binding', () => { const fileName = absoluteFrom('/main.ts'); const templateString = `<div [inputA]="helloWorld"></div>`; const {templateTypeChecker, program} = setup([ { fileName, templates: {'Cmp': templateString}, source: `export class Cmp {helloWorld?: boolean;}`, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = getAstElements(templateTypeChecker, cmp); const symbol = templateTypeChecker.getSymbolOfNode(nodes[0].inputs[0].value, cmp)!; assertExpressionSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol!)).toEqual('helloWorld'); expect(program.getTypeChecker().typeToString(symbol.tsType)).toEqual( 'false | true | undefined', ); }); it('should get a symbol for properties several levels deep', () => { const fileName = absoluteFrom('/main.ts'); const templateString = `<div [inputA]="person.address.street"></div>`; const {templateTypeChecker, program} = setup([ { fileName, templates: {'Cmp': templateString}, source: ` interface Address { street: string; } interface Person { address: Address; } export class Cmp {person?: Person;} `, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = getAstElements(templateTypeChecker, cmp); const inputNode = nodes[0].inputs[0].value as ASTWithSource; const symbol = templateTypeChecker.getSymbolOfNode(inputNode, cmp)!; assertExpressionSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol!)).toEqual('street'); expect( (symbol.tsSymbol!.declarations![0] as ts.PropertyDeclaration).parent.name!.getText(), ).toEqual('Address'); expect(program.getTypeChecker().typeToString(symbol.tsType)).toEqual('string'); const personSymbol = templateTypeChecker.getSymbolOfNode( ((inputNode.ast as PropertyRead).receiver as PropertyRead).receiver, cmp, )!; assertExpressionSymbol(personSymbol); expect(program.getTypeChecker().symbolToString(personSymbol.tsSymbol!)).toEqual('person'); expect(program.getTypeChecker().typeToString(personSymbol.tsType)).toEqual( 'Person | undefined', ); }); describe('should get symbols for conditionals', () => { let templateTypeChecker: TemplateTypeChecker; let cmp: ClassDeclaration<ts.ClassDeclaration>; let program: ts.Program; let templateString: string; beforeEach(() => { const fileName = absoluteFrom('/main.ts'); templateString = ` <div [inputA]="person?.address?.street"></div> <div [inputA]="person ? person.address : noPersonError"></div> <div [inputA]="person?.speak()"></div> <div [inputA]="person?.cars?.[1].engine"></div> `; const testValues = setup([ { fileName, templates: {'Cmp': templateString}, source: ` interface Address { street: string; } interface Car { engine: string; } interface Person { address: Address; speak(): string; cars?: Car[]; } export class Cmp {person?: Person; noPersonError = 'no person'} `, }, ]); templateTypeChecker = testValues.templateTypeChecker; program = testValues.program; const sf = getSourceFileOrError(program, fileName); cmp = getClass(sf, 'Cmp'); }); it('safe property reads', () => { const nodes = getAstElements(templateTypeChecker, cmp); const safePropertyRead = nodes[0].inputs[0].value as ASTWithSource; const propReadSymbol = templateTypeChecker.getSymbolOfNode(safePropertyRead, cmp)!; assertExpressionSymbol(propReadSymbol); expect(program.getTypeChecker().symbolToString(propReadSymbol.tsSymbol!)).toEqual( 'street', ); expect( ( propReadSymbol.tsSymbol!.declarations![0] as ts.PropertyDeclaration ).parent.name!.getText(), ).toEqual('Address'); expect(program.getTypeChecker().typeToString(propReadSymbol.tsType)).toEqual( 'string | undefined', ); }); it('safe method calls', () => { const nodes = getAstElements(templateTypeChecker, cmp); const safeMethodCall = nodes[2].inputs[0].value as ASTWithSource; const methodCallSymbol = templateTypeChecker.getSymbolOfNode(safeMethodCall, cmp)!; assertExpressionSymbol(methodCallSymbol); // Note that the symbol returned is for the return value of the safe method call. expect(methodCallSymbol.tsSymbol).toBeNull(); expect(program.getTypeChecker().typeToString(methodCallSymbol.tsType)).toBe( 'string | undefined', ); }); it('safe keyed reads', () => { const nodes = getAstElements(templateTypeChecker, cmp); const safeKeyedRead = nodes[3].inputs[0].value as ASTWithSource; const keyedReadSymbol = templateTypeChecker.getSymbolOfNode(safeKeyedRead, cmp)!; assertExpressionSymbol(keyedReadSymbol); expect(program.getTypeChecker().symbolToString(keyedReadSymbol.tsSymbol!)).toEqual( 'engine', ); expect( ( keyedReadSymbol.tsSymbol!.declarations![0] as ts.PropertyDeclaration ).parent.name!.getText(), ).toEqual('Car'); expect(program.getTypeChecker().typeToString(keyedReadSymbol.tsType)).toEqual('string'); }); it('ternary expressions', () => { const nodes = getAstElements(templateTypeChecker, cmp); const ternary = (nodes[1].inputs[0].value as ASTWithSource).ast as Conditional; const ternarySymbol = templateTypeChecker.getSymbolOfNode(ternary, cmp)!; assertExpressionSymbol(ternarySymbol); expect(ternarySymbol.tsSymbol).toBeNull(); expect(program.getTypeChecker().typeToString(ternarySymbol.tsType)).toEqual( 'string | Address', ); const addrSymbol = templateTypeChecker.getSymbolOfNode(ternary.trueExp, cmp)!; assertExpressionSymbol(addrSymbol); expect(program.getTypeChecker().symbolToString(addrSymbol.tsSymbol!)).toEqual('address'); expect(program.getTypeChecker().typeToString(addrSymbol.tsType)).toEqual('Address'); const noPersonSymbol = templateTypeChecker.getSymbolOfNode(ternary.falseExp, cmp)!; assertExpressionSymbol(noPersonSymbol); expect(program.getTypeChecker().symbolToString(noPersonSymbol.tsSymbol!)).toEqual( 'noPersonError', ); expect(program.getTypeChecker().typeToString(noPersonSymbol.tsType)).toEqual('string'); }); }); it('should get a symbol for function on a component used in an input binding', () => { const fileName = absoluteFrom('/main.ts'); const templateString = `<div [inputA]="helloWorld" [nestedFunction]="nested.helloWorld1()"></div>`; const {templateTypeChecker, program} = setup([ { fileName, templates: {'Cmp': templateString}, source: ` export class Cmp { helloWorld() { return ''; } nested = { helloWorld1() { return ''; } }; }`, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = getAstElements(templateTypeChecker, cmp); const symbol = templateTypeChecker.getSymbolOfNode(nodes[0].inputs[0].value, cmp)!; assertExpressionSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol!)).toEqual('helloWorld'); expect(program.getTypeChecker().typeToString(symbol.tsType)).toEqual('() => string'); const nestedSymbol = templateTypeChecker.getSymbolOfNode(nodes[0].inputs[1].value, cmp)!; assertExpressionSymbol(nestedSymbol); expect(program.getTypeChecker().symbolToString(nestedSymbol.tsSymbol!)).toEqual( 'helloWorld1', ); expect(program.getTypeChecker().typeToString(nestedSymbol.tsType)).toEqual('string'); });
{ "end_byte": 32270, "start_byte": 23280, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts_32278_41503
it('should get a symbol for binary expressions', () => { const fileName = absoluteFrom('/main.ts'); const templateString = `<div [inputA]="a + b"></div>`; const {templateTypeChecker, program} = setup([ { fileName, templates: {'Cmp': templateString}, source: ` export class Cmp { a!: string; b!: number; }`, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = getAstElements(templateTypeChecker, cmp); const valueAssignment = nodes[0].inputs[0].value as ASTWithSource; const wholeExprSymbol = templateTypeChecker.getSymbolOfNode(valueAssignment, cmp)!; assertExpressionSymbol(wholeExprSymbol); expect(wholeExprSymbol.tsSymbol).toBeNull(); expect(program.getTypeChecker().typeToString(wholeExprSymbol.tsType)).toEqual('string'); const aSymbol = templateTypeChecker.getSymbolOfNode( (valueAssignment.ast as Binary).left, cmp, )!; assertExpressionSymbol(aSymbol); expect(program.getTypeChecker().symbolToString(aSymbol.tsSymbol!)).toBe('a'); expect(program.getTypeChecker().typeToString(aSymbol.tsType)).toEqual('string'); const bSymbol = templateTypeChecker.getSymbolOfNode( (valueAssignment.ast as Binary).right, cmp, )!; assertExpressionSymbol(bSymbol); expect(program.getTypeChecker().symbolToString(bSymbol.tsSymbol!)).toBe('b'); expect(program.getTypeChecker().typeToString(bSymbol.tsType)).toEqual('number'); }); describe('local reference of an Element', () => { it('checkTypeOfDomReferences = true', () => { const fileName = absoluteFrom('/main.ts'); const {templateTypeChecker, program} = setup([ { fileName, templates: { 'Cmp': ` <input #myRef> <div [input]="myRef"></div>`, }, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = getAstElements(templateTypeChecker, cmp); const refSymbol = templateTypeChecker.getSymbolOfNode(nodes[0].references[0], cmp)!; assertReferenceSymbol(refSymbol); expect((refSymbol.target as TmplAstElement).name).toEqual('input'); expect((refSymbol.declaration as TmplAstReference).name).toEqual('myRef'); const myRefUsage = templateTypeChecker.getSymbolOfNode(nodes[1].inputs[0].value, cmp)!; assertReferenceSymbol(myRefUsage); expect((myRefUsage.target as TmplAstElement).name).toEqual('input'); expect((myRefUsage.declaration as TmplAstReference).name).toEqual('myRef'); }); it('checkTypeOfDomReferences = false', () => { const fileName = absoluteFrom('/main.ts'); const {templateTypeChecker, program} = setup( [ { fileName, templates: { 'Cmp': ` <input #myRef> <div [input]="myRef"></div>`, }, }, ], {checkTypeOfDomReferences: false}, ); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = getAstElements(templateTypeChecker, cmp); const refSymbol = templateTypeChecker.getSymbolOfNode(nodes[0].references[0], cmp); // Our desired behavior here is to honor the user's compiler settings and not produce a // symbol for the reference when `checkTypeOfDomReferences` is false. expect(refSymbol).toBeNull(); }); }); it('should get symbols for references which refer to directives', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = ` <div dir #myDir1="dir"></div> <div dir #myDir2="dir"></div> <div [inputA]="myDir1.dirValue" [inputB]="myDir1"></div> <div [inputA]="myDir2.dirValue" [inputB]="myDir2"></div>`; const {templateTypeChecker, program} = setup([ { fileName, templates: {'Cmp': templateString}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', exportAs: ['dir'], }, ], }, { fileName: dirFile, source: `export class TestDir { dirValue = 'helloWorld' }`, templates: {}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = getAstElements(templateTypeChecker, cmp); const ref1Declaration = templateTypeChecker.getSymbolOfNode(nodes[0].references[0], cmp)!; assertReferenceSymbol(ref1Declaration); expect((ref1Declaration.target as ts.ClassDeclaration).name!.getText()).toEqual('TestDir'); expect((ref1Declaration.declaration as TmplAstReference).name).toEqual('myDir1'); const ref2Declaration = templateTypeChecker.getSymbolOfNode(nodes[1].references[0], cmp)!; assertReferenceSymbol(ref2Declaration); expect((ref2Declaration.target as ts.ClassDeclaration).name!.getText()).toEqual('TestDir'); expect((ref2Declaration.declaration as TmplAstReference).name).toEqual('myDir2'); const dirValueSymbol = templateTypeChecker.getSymbolOfNode(nodes[2].inputs[0].value, cmp)!; assertExpressionSymbol(dirValueSymbol); expect(program.getTypeChecker().symbolToString(dirValueSymbol.tsSymbol!)).toBe('dirValue'); expect(program.getTypeChecker().typeToString(dirValueSymbol.tsType)).toEqual('string'); const dir1Symbol = templateTypeChecker.getSymbolOfNode(nodes[2].inputs[1].value, cmp)!; assertReferenceSymbol(dir1Symbol); expect((dir1Symbol.target as ts.ClassDeclaration).name!.getText()).toEqual('TestDir'); expect((dir1Symbol.declaration as TmplAstReference).name).toEqual('myDir1'); const dir2Symbol = templateTypeChecker.getSymbolOfNode(nodes[3].inputs[1].value, cmp)!; assertReferenceSymbol(dir2Symbol); expect((dir2Symbol.target as ts.ClassDeclaration).name!.getText()).toEqual('TestDir'); expect((dir2Symbol.declaration as TmplAstReference).name).toEqual('myDir2'); }); describe('literals', () => { let templateTypeChecker: TemplateTypeChecker; let cmp: ClassDeclaration<ts.ClassDeclaration>; let interpolation: Interpolation; let program: ts.Program; beforeEach(() => { const fileName = absoluteFrom('/main.ts'); const templateString = ` {{ [1, 2, 3] }} {{ { hello: "world" } }} {{ { foo } }}`; const testValues = setup([ { fileName, templates: {'Cmp': templateString}, source: ` type Foo {name: string;} export class Cmp {foo: Foo;} `, }, ]); templateTypeChecker = testValues.templateTypeChecker; program = testValues.program; const sf = getSourceFileOrError(testValues.program, fileName); cmp = getClass(sf, 'Cmp'); interpolation = ( (templateTypeChecker.getTemplate(cmp)![0] as TmplAstBoundText).value as ASTWithSource ).ast as Interpolation; }); it('literal array', () => { const literalArray = interpolation.expressions[0] as LiteralArray; const symbol = templateTypeChecker.getSymbolOfNode(literalArray, cmp)!; assertExpressionSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol!)).toEqual('Array'); expect(program.getTypeChecker().typeToString(symbol.tsType)).toEqual('Array<number>'); }); it('literal map', () => { const literalMap = interpolation.expressions[1] as LiteralMap; const symbol = templateTypeChecker.getSymbolOfNode(literalMap, cmp)!; assertExpressionSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol!)).toEqual('__object'); expect(program.getTypeChecker().typeToString(symbol.tsType)).toEqual( '{ hello: string; }', ); }); it('literal map shorthand property', () => { const shorthandProp = (interpolation.expressions[2] as LiteralMap) .values[0] as PropertyRead; const symbol = templateTypeChecker.getSymbolOfNode(shorthandProp, cmp)!; assertExpressionSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.tsSymbol!)).toEqual('foo'); expect(program.getTypeChecker().typeToString(symbol.tsType)).toEqual('Foo'); }); });
{ "end_byte": 41503, "start_byte": 32278, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts_41511_50082
describe('pipes', () => { let templateTypeChecker: TemplateTypeChecker; let cmp: ClassDeclaration<ts.ClassDeclaration>; let binding: BindingPipe; let program: ts.Program; function setupPipesTest(checkTypeOfPipes = true) { const fileName = absoluteFrom('/main.ts'); const templateString = `<div [inputA]="a | test:b:c"></div>`; const testValues = setup( [ { fileName, templates: {'Cmp': templateString}, source: ` export class Cmp { a: string; b: number; c: boolean } export class TestPipe { transform(value: string, repeat: number, commaSeparate: boolean): string[] { } } `, declarations: [ { type: 'pipe', name: 'TestPipe', pipeName: 'test', }, ], }, ], {checkTypeOfPipes}, ); program = testValues.program; templateTypeChecker = testValues.templateTypeChecker; const sf = getSourceFileOrError(testValues.program, fileName); cmp = getClass(sf, 'Cmp'); binding = (getAstElements(templateTypeChecker, cmp)[0].inputs[0].value as ASTWithSource) .ast as BindingPipe; } for (const checkTypeOfPipes of [true, false]) { it(`should get symbol for pipe, checkTypeOfPipes: ${checkTypeOfPipes}`, () => { setupPipesTest(checkTypeOfPipes); const pipeSymbol = templateTypeChecker.getSymbolOfNode(binding, cmp)!; assertPipeSymbol(pipeSymbol); expect(program.getTypeChecker().symbolToString(pipeSymbol.tsSymbol!)).toEqual( 'transform', ); expect( program.getTypeChecker().symbolToString(pipeSymbol.classSymbol.tsSymbol), ).toEqual('TestPipe'); expect(program.getTypeChecker().typeToString(pipeSymbol.tsType!)).toEqual( '(value: string, repeat: number, commaSeparate: boolean) => string[]', ); }); } it('should get symbols for pipe expression and args', () => { setupPipesTest(false); const aSymbol = templateTypeChecker.getSymbolOfNode(binding.exp, cmp)!; assertExpressionSymbol(aSymbol); expect(program.getTypeChecker().symbolToString(aSymbol.tsSymbol!)).toEqual('a'); expect(program.getTypeChecker().typeToString(aSymbol.tsType)).toEqual('string'); const bSymbol = templateTypeChecker.getSymbolOfNode(binding.args[0] as AST, cmp)!; assertExpressionSymbol(bSymbol); expect(program.getTypeChecker().symbolToString(bSymbol.tsSymbol!)).toEqual('b'); expect(program.getTypeChecker().typeToString(bSymbol.tsType)).toEqual('number'); const cSymbol = templateTypeChecker.getSymbolOfNode(binding.args[1] as AST, cmp)!; assertExpressionSymbol(cSymbol); expect(program.getTypeChecker().symbolToString(cSymbol.tsSymbol!)).toEqual('c'); expect(program.getTypeChecker().typeToString(cSymbol.tsType)).toEqual('boolean'); }); for (const checkTypeOfPipes of [true, false]) { describe(`checkTypeOfPipes: ${checkTypeOfPipes}`, () => { // Because the args are property reads, we still need information about them. it(`should get symbols for pipe expression and args`, () => { setupPipesTest(checkTypeOfPipes); const aSymbol = templateTypeChecker.getSymbolOfNode(binding.exp, cmp)!; assertExpressionSymbol(aSymbol); expect(program.getTypeChecker().symbolToString(aSymbol.tsSymbol!)).toEqual('a'); expect(program.getTypeChecker().typeToString(aSymbol.tsType)).toEqual('string'); const bSymbol = templateTypeChecker.getSymbolOfNode(binding.args[0] as AST, cmp)!; assertExpressionSymbol(bSymbol); expect(program.getTypeChecker().symbolToString(bSymbol.tsSymbol!)).toEqual('b'); expect(program.getTypeChecker().typeToString(bSymbol.tsType)).toEqual('number'); const cSymbol = templateTypeChecker.getSymbolOfNode(binding.args[1] as AST, cmp)!; assertExpressionSymbol(cSymbol); expect(program.getTypeChecker().symbolToString(cSymbol.tsSymbol!)).toEqual('c'); expect(program.getTypeChecker().typeToString(cSymbol.tsType)).toEqual('boolean'); }); }); } }); it('should get a symbol for PropertyWrite expressions', () => { const fileName = absoluteFrom('/main.ts'); const {templateTypeChecker, program} = setup([ { fileName, templates: {'Cmp': '<div (output)="lastEvent = $event"></div>'}, source: `export class Cmp { lastEvent: any; }`, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const node = getAstElements(templateTypeChecker, cmp)[0]; const writeSymbol = templateTypeChecker.getSymbolOfNode(node.outputs[0].handler, cmp)!; assertExpressionSymbol(writeSymbol); // Note that the symbol returned is for the RHS of the PropertyWrite. The AST // does not support specific designation for the RHS so we assume that's what // is wanted in this case. We don't support retrieving a symbol for the whole // expression and if you want to get a symbol for the '$event', you can // use the `value` AST of the `PropertyWrite`. expect(program.getTypeChecker().symbolToString(writeSymbol.tsSymbol!)).toEqual('lastEvent'); expect(program.getTypeChecker().typeToString(writeSymbol.tsType)).toEqual('any'); }); it('should get a symbol for Call expressions', () => { const fileName = absoluteFrom('/main.ts'); const {templateTypeChecker, program} = setup([ { fileName, templates: { 'Cmp': '<div [input]="toString(123)" [nestedFunction]="nested.toString(123)"></div>', }, source: ` export class Cmp { toString(v: any): string { return String(v); } nested = { toString(v: any): string { return String(v); } }; } `, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const node = getAstElements(templateTypeChecker, cmp)[0]; const callSymbol = templateTypeChecker.getSymbolOfNode(node.inputs[0].value, cmp)!; assertExpressionSymbol(callSymbol); // Note that the symbol returned is for the return value of the Call. expect(callSymbol.tsSymbol).toBeTruthy(); expect(callSymbol.tsSymbol?.getName()).toEqual('toString'); expect(program.getTypeChecker().typeToString(callSymbol.tsType)).toBe('string'); const nestedCallSymbol = templateTypeChecker.getSymbolOfNode(node.inputs[1].value, cmp)!; assertExpressionSymbol(nestedCallSymbol); // Note that the symbol returned is for the return value of the Call. expect(nestedCallSymbol.tsSymbol).toBeTruthy(); expect(nestedCallSymbol.tsSymbol?.getName()).toEqual('toString'); expect(program.getTypeChecker().typeToString(nestedCallSymbol.tsType)).toBe('string'); }); it('should get a symbol for SafeCall expressions', () => { const fileName = absoluteFrom('/main.ts'); const {templateTypeChecker, program} = setup([ { fileName, templates: {'Cmp': '<div [input]="toString?.(123)"></div>'}, source: `export class Cmp { toString?: (value: number) => string; }`, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const node = getAstElements(templateTypeChecker, cmp)[0]; const safeCallSymbol = templateTypeChecker.getSymbolOfNode(node.inputs[0].value, cmp)!; assertExpressionSymbol(safeCallSymbol); // Note that the symbol returned is for the return value of the SafeCall. expect(safeCallSymbol.tsSymbol).toBeNull(); expect(program.getTypeChecker().typeToString(safeCallSymbol.tsType)).toBe( 'string | undefined', ); }); });
{ "end_byte": 50082, "start_byte": 41511, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts_50088_59061
describe('input bindings', () => { it('can get a symbol for empty binding', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': `<div dir [inputA]=""></div>`}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {inputA: 'inputA'}, }, ], }, { fileName: dirFile, source: `export class TestDir {inputA?: string; }`, templates: {}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const inputAbinding = (nodes[0] as TmplAstElement).inputs[0]; const aSymbol = templateTypeChecker.getSymbolOfNode(inputAbinding, cmp)!; assertInputBindingSymbol(aSymbol); expect( (aSymbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).name.getText(), ).toEqual('inputA'); }); it('can retrieve a symbol for an input binding', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = `<div dir [inputA]="'my input A'" [inputBRenamed]="'my inputB'"></div>`; const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': templateString}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {inputA: 'inputA', inputB: 'inputBRenamed'}, }, ], }, { fileName: dirFile, source: `export class TestDir {inputA!: string; inputB!: string}`, templates: {}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const inputAbinding = (nodes[0] as TmplAstElement).inputs[0]; const aSymbol = templateTypeChecker.getSymbolOfNode(inputAbinding, cmp)!; assertInputBindingSymbol(aSymbol); expect( (aSymbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).name.getText(), ).toEqual('inputA'); const inputBbinding = (nodes[0] as TmplAstElement).inputs[1]; const bSymbol = templateTypeChecker.getSymbolOfNode(inputBbinding, cmp)!; assertInputBindingSymbol(bSymbol); expect( (bSymbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).name.getText(), ).toEqual('inputB'); }); it('can retrieve a symbol for a signal-input binding', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = `<div dir [inputA]="'my input A'" [aliased]="'my inputB'"></div>`; const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': templateString}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: { inputA: { bindingPropertyName: 'inputA', isSignal: true, classPropertyName: 'inputA', required: false, transform: null, }, inputB: { bindingPropertyName: 'aliased', isSignal: true, classPropertyName: 'inputB', required: true, transform: null, }, }, }, ], }, { fileName: dirFile, source: ` import {InputSignal} from '@angular/core'; export class TestDir { inputA: InputSignal<string> = null!; inputB: InputSignal<string> = null!; }`, templates: {}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const inputAbinding = (nodes[0] as TmplAstElement).inputs[0]; const aSymbol = templateTypeChecker.getSymbolOfNode(inputAbinding, cmp)!; assertInputBindingSymbol(aSymbol); expect( (aSymbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).name.getText(), ).toEqual('inputA'); const inputBbinding = (nodes[0] as TmplAstElement).inputs[1]; const bSymbol = templateTypeChecker.getSymbolOfNode(inputBbinding, cmp)!; assertInputBindingSymbol(bSymbol); expect( (bSymbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).name.getText(), ).toEqual('inputB'); }); // Note that `honorAccessModifiersForInputBindings` is `false` even with `--strictTemplates`, // so this captures a potential common scenario, assuming the input is restricted. it('should not throw when retrieving a symbol for a signal-input with restricted access', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = ` @if (true) { <div dir [inputA]="'ok'"></div> } `; const {program, templateTypeChecker} = setup( [ { fileName, templates: {'Cmp': templateString}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', restrictedInputFields: ['inputA'], inputs: { inputA: { bindingPropertyName: 'inputA', isSignal: true, classPropertyName: 'inputA', required: false, transform: null, }, }, }, ], }, { fileName: dirFile, source: ` import {InputSignal} from '@angular/core'; export class TestDir { protected inputA: InputSignal<string> = null!; } `, templates: {}, }, ], {honorAccessModifiersForInputBindings: false}, ); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const ifNode = nodes[0] as TmplAstIfBlock; const ifBranchNode = ifNode.branches[0]; const testElement = ifBranchNode.children[0] as TmplAstElement; const inputAbinding = testElement.inputs[0]; const aSymbol = templateTypeChecker.getSymbolOfNode(inputAbinding, cmp); expect(aSymbol) .withContext( 'Symbol builder does not return symbols for restricted inputs with ' + '`honorAccessModifiersForInputBindings = false` (same for decorator inputs)', ) .toBe(null); }); it('does not retrieve a symbol for an input when undeclared', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = `<div dir [inputA]="'my input A'"></div>`; const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': templateString}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {inputA: 'inputA'}, }, ], }, { fileName: dirFile, source: `export class TestDir {}`, templates: {}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const inputAbinding = (nodes[0] as TmplAstElement).inputs[0]; const aSymbol = templateTypeChecker.getSymbolOfNode(inputAbinding, cmp)!; expect(aSymbol).toBeNull(); });
{ "end_byte": 59061, "start_byte": 50088, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts_59069_67303
it('can retrieve a symbol for an input of structural directive', () => { const fileName = absoluteFrom('/main.ts'); const templateString = `<div *ngFor="let user of users"></div>`; const {program, templateTypeChecker} = setup([ {fileName, templates: {'Cmp': templateString}, declarations: [ngForDeclaration()]}, ngForTypeCheckTarget(), ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const ngForOfBinding = (nodes[0] as TmplAstTemplate).templateAttrs.find( (a) => a.name === 'ngForOf', )! as TmplAstBoundAttribute; const symbol = templateTypeChecker.getSymbolOfNode(ngForOfBinding, cmp)!; assertInputBindingSymbol(symbol); expect( (symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).name.getText(), ).toEqual('ngForOf'); }); it('returns dom binding input binds only to the dom element', () => { const fileName = absoluteFrom('/main.ts'); const templateString = `<div [name]="'my input'"></div>`; const {program, templateTypeChecker} = setup([ {fileName, templates: {'Cmp': templateString}, declarations: []}, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const binding = (nodes[0] as TmplAstElement).inputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(binding, cmp)!; assertDomBindingSymbol(symbol); assertElementSymbol(symbol.host); }); it('returns dom binding when directive members do not match the input', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = `<div dir [inputA]="'my input A'"></div>`; const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': templateString}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {}, }, ], }, { fileName: dirFile, source: `export class TestDir {}`, templates: {}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const inputAbinding = (nodes[0] as TmplAstElement).inputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(inputAbinding, cmp)!; assertDomBindingSymbol(symbol); assertElementSymbol(symbol.host); }); it('can match binding when there are two directives', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = `<div dir otherDir [inputA]="'my input A'"></div>`; const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': templateString}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {inputA: 'inputA'}, }, { name: 'OtherDir', selector: '[otherDir]', file: dirFile, type: 'directive', inputs: {}, }, ], }, { fileName: dirFile, source: ` export class TestDir {inputA!: string;} export class OtherDir {} `, templates: {}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const inputAbinding = (nodes[0] as TmplAstElement).inputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(inputAbinding, cmp)!; assertInputBindingSymbol(symbol); expect( (symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).name.getText(), ).toEqual('inputA'); expect( (symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).parent.name ?.text, ).toEqual('TestDir'); }); it('returns the first field match when directive maps same input to two fields', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': `<div dir [inputA]="'my input A'"></div>`}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {inputA: 'inputA', otherInputA: 'inputA'}, }, ], }, { fileName: dirFile, source: ` export class TestDir {inputA!: string; otherInputA!: string;} `, templates: {}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const inputAbinding = (nodes[0] as TmplAstElement).inputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(inputAbinding, cmp)!; assertInputBindingSymbol(symbol); expect( (symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).name.getText(), ).toEqual('otherInputA'); expect( (symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).parent.name ?.text, ).toEqual('TestDir'); }); it('returns the all inputs when two directives have the same input', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = `<div dir otherDir [inputA]="'my input A'"></div>`; const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': templateString}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {inputA: 'inputA'}, }, { name: 'OtherDir', selector: '[otherDir]', file: dirFile, type: 'directive', inputs: {otherDirInputA: 'inputA'}, }, ], }, { fileName: dirFile, source: ` export class TestDir {inputA!: string;} export class OtherDir {otherDirInputA!: string;} `, templates: {}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const inputAbinding = (nodes[0] as TmplAstElement).inputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(inputAbinding, cmp)!; assertInputBindingSymbol(symbol); expect( new Set( symbol.bindings.map((b) => (b.tsSymbol!.declarations![0] as ts.PropertyDeclaration).name.getText(), ), ), ).toEqual(new Set(['inputA', 'otherDirInputA'])); expect( new Set( symbol.bindings.map( (b) => (b.tsSymbol!.declarations![0] as ts.PropertyDeclaration).parent.name?.text, ), ), ).toEqual(new Set(['TestDir', 'OtherDir'])); }); });
{ "end_byte": 67303, "start_byte": 59069, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts_67309_75262
describe('output bindings', () => { it('should find symbol for output binding', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = `<div dir (outputA)="handle($event)" (renamedOutputB)="handle($event)"></div>`; const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': templateString}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', outputs: {outputA: 'outputA', outputB: 'renamedOutputB'}, }, ], }, { fileName: dirFile, source: ` export class TestDir {outputA!: EventEmitter<string>; outputB!: EventEmitter<string>} `, templates: {}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const outputABinding = (nodes[0] as TmplAstElement).outputs[0]; const aSymbol = templateTypeChecker.getSymbolOfNode(outputABinding, cmp)!; assertOutputBindingSymbol(aSymbol); expect( (aSymbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).name.getText(), ).toEqual('outputA'); const outputBBinding = (nodes[0] as TmplAstElement).outputs[1]; const bSymbol = templateTypeChecker.getSymbolOfNode(outputBBinding, cmp)!; assertOutputBindingSymbol(bSymbol); expect( (bSymbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).name.getText(), ).toEqual('outputB'); }); it('should find symbol for output binding when there are multiple directives', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': `<div dir otherdir (outputA)="handle($event)"></div>`}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', outputs: {outputA: 'outputA'}, }, { name: 'OtherDir', selector: '[otherdir]', file: dirFile, type: 'directive', outputs: {unusedOutput: 'unusedOutput'}, }, ], }, { fileName: dirFile, source: ` export class TestDir {outputA!: EventEmitter<string>;} export class OtherDir {unusedOutput!: EventEmitter<string>;} `, templates: {}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const outputABinding = (nodes[0] as TmplAstElement).outputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(outputABinding, cmp)!; assertOutputBindingSymbol(symbol); expect( (symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).name.getText(), ).toEqual('outputA'); expect( (symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).parent.name ?.text, ).toEqual('TestDir'); }); it('returns addEventListener binding to native element when no match to any directive output', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': `<div (click)="handle($event)"></div>`}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const outputABinding = (nodes[0] as TmplAstElement).outputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(outputABinding, cmp)!; assertOutputBindingSymbol(symbol); expect(program.getTypeChecker().symbolToString(symbol.bindings[0].tsSymbol!)).toEqual( 'addEventListener', ); const eventSymbol = templateTypeChecker.getSymbolOfNode(outputABinding.handler, cmp)!; assertExpressionSymbol(eventSymbol); }); it('still returns binding when checkTypeOfOutputEvents is false', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const {program, templateTypeChecker} = setup( [ { fileName, templates: {'Cmp': `<div dir (outputA)="handle($event)"></div>`}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', outputs: {outputA: 'outputA'}, }, ], }, { fileName: dirFile, source: `export class TestDir {outputA!: EventEmitter<string>;}`, templates: {}, }, ], {checkTypeOfOutputEvents: false}, ); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const outputABinding = (nodes[0] as TmplAstElement).outputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(outputABinding, cmp)!; assertOutputBindingSymbol(symbol); expect( (symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).name.getText(), ).toEqual('outputA'); expect( (symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).parent.name ?.text, ).toEqual('TestDir'); }); it('returns output symbol for two way binding', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': `<div dir [(ngModel)]="value"></div>`}, source: ` export class Cmp { value = ''; }`, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', inputs: {ngModel: 'ngModel'}, outputs: {ngModelChange: 'ngModelChange'}, }, ], }, { fileName: dirFile, source: ` export class TestDir { ngModel!: string; ngModelChange!: EventEmitter<string>; }`, templates: {}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const outputABinding = (nodes[0] as TmplAstElement).outputs[0]; const symbol = templateTypeChecker.getSymbolOfNode(outputABinding, cmp)!; assertOutputBindingSymbol(symbol); expect( (symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).name.getText(), ).toEqual('ngModelChange'); expect( (symbol.bindings[0].tsSymbol!.declarations![0] as ts.PropertyDeclaration).parent.name ?.text, ).toEqual('TestDir'); }); });
{ "end_byte": 75262, "start_byte": 67309, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts_75268_84400
describe('for elements', () => { it('for elements that are components with no inputs', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': `<child-component></child-component>`}, declarations: [ { name: 'ChildComponent', selector: 'child-component', isComponent: true, file: dirFile, type: 'directive', }, ], }, { fileName: dirFile, source: ` export class ChildComponent {} `, templates: {'ChildComponent': ''}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const symbol = templateTypeChecker.getSymbolOfNode(nodes[0] as TmplAstElement, cmp)!; assertElementSymbol(symbol); expect(symbol.directives.length).toBe(1); assertDirectiveSymbol(symbol.directives[0]); expect(program.getTypeChecker().typeToString(symbol.directives[0].tsType)).toEqual( 'ChildComponent', ); expect(symbol.directives[0].isComponent).toBe(true); }); it('element with directive matches', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': `<div dir dir2></div>`}, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', }, { name: 'TestDir2', selector: '[dir2]', file: dirFile, type: 'directive', }, { name: 'TestDirAllDivs', selector: 'div', file: dirFile, type: 'directive', }, ], }, { fileName: dirFile, source: ` export class TestDir {} // Allow the fake ComponentScopeReader to return a module for TestDir export class TestDirModule {} export class TestDir2 {} // Allow the fake ComponentScopeReader to return a module for TestDir2 export class TestDir2Module {} export class TestDirAllDivs {} `, templates: {}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const symbol = templateTypeChecker.getSymbolOfNode(nodes[0] as TmplAstElement, cmp)!; assertElementSymbol(symbol); expect(symbol.directives.length).toBe(3); const expectedDirectives = ['TestDir', 'TestDir2', 'TestDirAllDivs'].sort(); const actualDirectives = symbol.directives .map((dir) => program.getTypeChecker().typeToString(dir.tsType)) .sort(); expect(actualDirectives).toEqual(expectedDirectives); const expectedSelectors = ['[dir]', '[dir2]', 'div'].sort(); const actualSelectors = symbol.directives.map((dir) => dir.selector).sort(); expect(actualSelectors).toEqual(expectedSelectors); // Testing this fully requires an integration test with a real `NgCompiler` (like in the // Language Service, which uses the ngModule name for quick info). However, this path does // assert that we are able to handle when the scope reader returns `null` or a class from // the fake implementation. const expectedModules = new Set([null, 'TestDirModule', 'TestDir2Module']); const actualModules = new Set( symbol.directives.map((dir) => dir.ngModule?.name.getText() ?? null), ); expect(actualModules).toEqual(expectedModules); }); }); describe('let declarations', () => { let templateTypeChecker: TemplateTypeChecker; let cmp: ClassDeclaration<ts.ClassDeclaration>; let ast: TmplAstNode[]; let program: ts.Program; beforeEach(() => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const templateString = ` @let message = 'The value is ' + value; <div [dir]="message"></div> `; const testValues = setup([ { fileName, templates: {'Cmp': templateString}, source: ` export class Cmp { value = 1; } `, declarations: [ { name: 'TestDir', selector: '[dir]', file: dirFile, type: 'directive', exportAs: ['dir'], inputs: {dir: 'dir'}, }, ], }, { fileName: dirFile, source: `export class TestDir {dir: any;}`, templates: {}, }, ]); templateTypeChecker = testValues.templateTypeChecker; program = testValues.program; const sf = getSourceFileOrError(testValues.program, fileName); cmp = getClass(sf, 'Cmp'); ast = templateTypeChecker.getTemplate(cmp)!; }); it('should get symbol of a let declaration at the declaration location', () => { const symbol = templateTypeChecker.getSymbolOfNode(ast[0] as TmplAstLetDeclaration, cmp)!; assertLetDeclarationSymbol(symbol); expect(program.getTypeChecker().typeToString(symbol.tsType!)).toBe('string'); expect(symbol.declaration.name).toBe('message'); }); it('should get symbol of a let declaration at a usage site', () => { const symbol = templateTypeChecker.getSymbolOfNode( (ast[1] as TmplAstElement).inputs[0].value, cmp, )!; assertLetDeclarationSymbol(symbol); expect(program.getTypeChecker().typeToString(symbol.tsType!)).toEqual('string'); expect(symbol.declaration.name).toEqual('message'); // Ensure we can map the shim locations back to the template const initializerMapping = templateTypeChecker.getTemplateMappingAtTcbLocation( symbol.initializerLocation, )!; expect(initializerMapping.span.toString()).toEqual(`'The value is ' + value`); const localVarMapping = templateTypeChecker.getTemplateMappingAtTcbLocation( symbol.localVarLocation, )!; expect(localVarMapping.span.toString()).toEqual('message'); }); }); it('elements with generic directives', () => { const fileName = absoluteFrom('/main.ts'); const dirFile = absoluteFrom('/dir.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': `<div genericDir></div>`}, declarations: [ { name: 'GenericDir', selector: '[genericDir]', file: dirFile, type: 'directive', isGeneric: true, }, ], }, { fileName: dirFile, source: ` export class GenericDir<T>{} `, templates: {}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const symbol = templateTypeChecker.getSymbolOfNode(nodes[0] as TmplAstElement, cmp)!; assertElementSymbol(symbol); expect(symbol.directives.length).toBe(1); const actualDirectives = symbol.directives .map((dir) => program.getTypeChecker().typeToString(dir.tsType)) .sort(); expect(actualDirectives).toEqual(['GenericDir<any>']); }); it('has correct tcb location for components with inline TCBs', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = baseTestSetup( [ { fileName, templates: {'Cmp': '<div></div>'}, // Force an inline TCB by using a non-exported component class source: `class Cmp {}`, }, ], {inlining: true, config: {enableTemplateTypeChecker: true}}, ); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const symbol = templateTypeChecker.getSymbolOfNode(nodes[0] as TmplAstElement, cmp)!; assertElementSymbol(symbol); expect(symbol.tcbLocation.tcbPath).toBe(sf.fileName); expect(symbol.tcbLocation.isShimFile).toBe(false); });
{ "end_byte": 84400, "start_byte": 75268, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts_84406_87698
it('has correct tcb location for components with TCBs in a type-checking shim file', () => { const fileName = absoluteFrom('/main.ts'); const {program, templateTypeChecker} = setup([ { fileName, templates: {'Cmp': '<div></div>'}, }, ]); const sf = getSourceFileOrError(program, fileName); const cmp = getClass(sf, 'Cmp'); const nodes = templateTypeChecker.getTemplate(cmp)!; const symbol = templateTypeChecker.getSymbolOfNode(nodes[0] as TmplAstElement, cmp)!; assertElementSymbol(symbol); expect(symbol.tcbLocation.tcbPath).not.toBe(sf.fileName); expect(symbol.tcbLocation.isShimFile).toBe(true); }); }); }); function onlyAstTemplates(nodes: TmplAstNode[]): TmplAstTemplate[] { return nodes.filter((n): n is TmplAstTemplate => n instanceof TmplAstTemplate); } function onlyAstElements(nodes: TmplAstNode[]): TmplAstElement[] { return nodes.filter((n): n is TmplAstElement => n instanceof TmplAstElement); } function getAstElements( templateTypeChecker: TemplateTypeChecker, cmp: ts.ClassDeclaration & {name: ts.Identifier}, ) { return onlyAstElements(templateTypeChecker.getTemplate(cmp)!); } function getAstTemplates( templateTypeChecker: TemplateTypeChecker, cmp: ts.ClassDeclaration & {name: ts.Identifier}, ) { return onlyAstTemplates(templateTypeChecker.getTemplate(cmp)!); } function assertDirectiveSymbol(tSymbol: Symbol): asserts tSymbol is DirectiveSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Directive); } function assertInputBindingSymbol(tSymbol: Symbol): asserts tSymbol is InputBindingSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Input); } function assertOutputBindingSymbol(tSymbol: Symbol): asserts tSymbol is OutputBindingSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Output); } function assertVariableSymbol(tSymbol: Symbol): asserts tSymbol is VariableSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Variable); } function assertTemplateSymbol(tSymbol: Symbol): asserts tSymbol is TemplateSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Template); } function assertReferenceSymbol(tSymbol: Symbol): asserts tSymbol is ReferenceSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Reference); } function assertExpressionSymbol(tSymbol: Symbol): asserts tSymbol is ExpressionSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Expression); } function assertPipeSymbol(tSymbol: Symbol): asserts tSymbol is PipeSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Pipe); } function assertElementSymbol(tSymbol: Symbol): asserts tSymbol is ElementSymbol { expect(tSymbol.kind).toEqual(SymbolKind.Element); } function assertDomBindingSymbol(tSymbol: Symbol): asserts tSymbol is DomBindingSymbol { expect(tSymbol.kind).toEqual(SymbolKind.DomBinding); } function assertLetDeclarationSymbol(tSymbol: Symbol): asserts tSymbol is LetDeclarationSymbol { expect(tSymbol.kind).toEqual(SymbolKind.LetDeclaration); } export function setup( targets: TypeCheckingTarget[], config?: Partial<TypeCheckingConfig>, parseOptions?: ParseTemplateOptions, ) { return baseTestSetup(targets, { inlining: false, config: {...config, enableTemplateTypeChecker: true, useInlineTypeConstructors: false}, parseOptions, }); }
{ "end_byte": 87698, "start_byte": 84406, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/type_checker__get_symbol_of_template_node_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/model_signal_diagnostics_spec.ts_0_421
/** * @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('model inputs type-check diagnostics',
{ "end_byte": 421, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/model_signal_diagnostics_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/model_signal_diagnostics_spec.ts_422_8670
() => { const bindingCases: TestCase[] = [ { id: 'static binding', inputs: {show: {type: 'ModelSignal<boolean>', isSignal: true}}, outputs: {showChange: {type: 'ModelSignal<boolean>'}}, template: `<div dir show="works">`, expected: [`TestComponent.html(1, 10): Type 'string' is not assignable to type 'boolean'.`], }, { id: 'one-way property binding', inputs: {show: {type: 'ModelSignal<boolean>', isSignal: true}}, outputs: {showChange: {type: 'ModelSignal<boolean>'}}, template: `<div dir [show]="prop">`, component: 'prop = true;', expected: [], }, { id: 'complex object one-way binding', inputs: {show: {type: 'ModelSignal<{works: boolean}>', isSignal: true}}, outputs: {showChange: {type: 'ModelSignal<{works: boolean}>'}}, template: `<div dir [show]="{works: true}">`, expected: [], }, { id: 'complex object one-way binding, unexpected extra fields', inputs: {show: {type: 'ModelSignal<{works: boolean}>', isSignal: true}}, outputs: {showChange: {type: 'ModelSignal<boolean>'}}, 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: 'ModelSignal<{works: boolean}>', isSignal: true}}, outputs: {showChange: {type: 'ModelSignal<boolean>'}}, 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 input and model, valid', inputs: { zoneProp: {type: 'string', isSignal: false}, signalProp: {type: 'ModelSignal<string>', isSignal: true}, }, outputs: {signalPropChange: {type: 'ModelSignal<string>'}}, template: `<div dir [zoneProp]="'works'" [signalProp]="'stringVal'">`, expected: [], }, { id: 'mixing zone input and model, invalid zone binding', inputs: { zoneProp: {type: 'string', isSignal: false}, signalProp: {type: 'ModelSignal<string>', isSignal: true}, }, outputs: {signalPropChange: {type: 'ModelSignal<string>'}}, template: `<div dir [zoneProp]="false" [signalProp]="'stringVal'">`, expected: [`TestComponent.html(1, 11): Type 'boolean' is not assignable to type 'string'.`], }, { id: 'mixing zone input and model, invalid signal binding', inputs: { zoneProp: {type: 'string', isSignal: false}, signalProp: {type: 'ModelSignal<string>', isSignal: true}, }, outputs: {signalPropChange: {type: 'ModelSignal<string>'}}, template: `<div dir [zoneProp]="'works'" [signalProp]="{}">`, expected: [`TestComponent.html(1, 32): Type '{}' is not assignable to type 'string'.`], }, { id: 'mixing zone input and model, both invalid', inputs: { zoneProp: {type: 'string', isSignal: false}, signalProp: {type: 'ModelSignal<string>', isSignal: true}, }, outputs: {signalPropChange: {type: 'ModelSignal<string>'}}, 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 model', inputs: { pattern: {type: 'ModelSignal<string>', isSignal: true, restrictionModifier: 'private'}, }, outputs: {patternChange: {type: 'ModelSignal<string>'}}, 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 model', inputs: { pattern: {type: 'ModelSignal<string>', isSignal: true, restrictionModifier: 'protected'}, }, outputs: {patternChange: {type: 'ModelSignal<string>'}}, template: `<div dir [pattern]="'works'">`, expected: [ `TestComponent.html(1, 11): Property 'pattern' is protected and only accessible within class 'Dir' and its subclasses.`, ], }, { id: 'allows access to readonly model by default', inputs: { pattern: {type: 'ModelSignal<string>', isSignal: true, restrictionModifier: 'readonly'}, }, outputs: {patternChange: {type: 'ModelSignal<string>'}}, 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: 'ModelSignal<string>', isSignal: true, restrictionModifier: 'private'}, }, outputs: {patternChange: {type: 'ModelSignal<string>'}}, template: `<div dir [pattern]="'works'">`, expected: [], options: { honorAccessModifiersForInputBindings: false, }, }, { id: 'allow access to protected model if modifiers are explicitly ignored', inputs: { pattern: {type: 'ModelSignal<string>', isSignal: true, restrictionModifier: 'protected'}, }, outputs: {patternChange: {type: 'ModelSignal<string>'}}, template: `<div dir [pattern]="'works'">`, expected: [], options: { honorAccessModifiersForInputBindings: false, }, }, { id: 'allow access to readonly input if modifiers are explicitly ignored', inputs: { pattern: {type: 'ModelSignal<string>', isSignal: true, restrictionModifier: 'readonly'}, }, outputs: {patternChange: {type: 'ModelSignal<string>'}}, template: `<div dir [pattern]="'works'">`, expected: [], options: { honorAccessModifiersForInputBindings: false, }, }, { id: 'allow access to private model if modifiers are explicitly ignored, but error if not assignable', inputs: { pattern: {type: 'ModelSignal<string>', isSignal: true, restrictionModifier: 'private'}, }, outputs: {patternChange: {type: 'ModelSignal<string>'}}, 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: 'ModelSignal<string>', isSignal: true}}, outputs: {patternChange: {type: 'ModelSignal<string>'}}, extraDirectiveMembers: ['static ngAcceptInputType_pattern: string|boolean'], template: `<div dir [pattern]="false">`, expected: [`TestComponent.html(1, 11): Type 'boolean' is not assignable to type 'string'.`], }, // with generics (type constructor tests) { id: 'generic inference and one-way binding to directive, all model inputs', inputs: { gen: { type: 'ModelSignal<T>', isSignal: true, }, other: { type: 'ModelSignal<T>', isSignal: true, }, }, outputs: { genChange: {type: 'ModelSignal<T>'}, otherChange: {type: 'ModelSignal<T>'}, }, directiveGenerics: '<T>', template: `<div dir [gen]="false" [other]="'invalid'">`, expected: [`TestComponent.html(1, 25): Type 'string' is not assignable to type 'boolean'.`], },
{ "end_byte": 8670, "start_byte": 422, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/model_signal_diagnostics_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/model_signal_diagnostics_spec.ts_8677_16285
{ id: 'generic inference and one-way binding to directive, mix of zone input and model', inputs: { gen: { type: 'ModelSignal<T>', isSignal: true, }, other: { type: 'T', isSignal: false, }, }, outputs: {genChange: {type: 'ModelSignal<T>'}}, 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 one-way binding to directive (with `extends boolean`), all model inputs', inputs: { gen: { type: 'ModelSignal<T>', isSignal: true, }, other: { type: 'ModelSignal<T>', isSignal: true, }, }, outputs: {genChange: {type: 'ModelSignal<T>'}, otherChange: {type: 'ModelSignal<T>'}}, 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 one-way binding to directive (with `extends boolean`), mix of zone inputs and model', inputs: { gen: { type: 'ModelSignal<T>', isSignal: true, }, other: { type: 'T', isSignal: false, }, }, outputs: {genChange: {type: 'ModelSignal<T>'}}, 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 one-way bindings to directive, all model inputs', inputs: { gen: { type: 'ModelSignal<T>', isSignal: true, }, other: { type: 'ModelSignal<U>', isSignal: true, }, }, outputs: { genChange: {type: 'ModelSignal<T>'}, otherChange: {type: 'ModelSignal<U>'}, }, 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 one-way bindings to directive, mix of zone inputs and models', inputs: { gen: { type: 'ModelSignal<T>', isSignal: true, }, other: { type: 'U', isSignal: false, }, }, outputs: {genChange: {type: 'ModelSignal<T>'}}, 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 one-way bindings to directive, more complicated generic inference', inputs: { gen: { type: 'ModelSignal<T>', isSignal: true, }, other: { type: 'ModelSignal<{u: U}>', isSignal: true, }, }, outputs: { genChange: {type: 'ModelSignal<T>'}, otherChange: {type: 'ModelSignal<{u: U}>'}, }, 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'.`, ], }, { id: 'inline constructor generic inference, one-way binding', inputs: { bla: { type: 'ModelSignal<T>', isSignal: true, }, }, outputs: {blaChange: {type: 'ModelSignal<T>'}}, 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.ts` is correctly inferred to be `HTMLElement`. `TestComponent.html(1, 60): Type 'number' is not assignable to type 'HTMLElement'.`, ], }, { id: 'generic inference and two-way binding to directive, all model inputs', inputs: { gen: { type: 'ModelSignal<T>', isSignal: true, }, other: { type: 'ModelSignal<T>', isSignal: true, }, }, outputs: { genChange: {type: 'ModelSignal<T>'}, otherChange: {type: 'ModelSignal<T>'}, }, directiveGenerics: '<T>', component: ` genVal!: boolean; otherVal!: string; `, template: `<div dir [(gen)]="genVal" [(other)]="otherVal">`, expected: [`TestComponent.html(1, 29): Type 'string' is not assignable to type 'boolean'.`], }, { id: 'generic inference and two-way binding to directive, mix of zone input and model', inputs: { gen: { type: 'ModelSignal<T>', isSignal: true, }, other: { type: 'T', isSignal: false, }, }, outputs: { genChange: {type: 'ModelSignal<T>'}, otherChange: {type: 'EventEmitter<T>'}, }, directiveGenerics: '<T>', template: `<div dir [(gen)]="genVal" [(other)]="otherVal">`, component: ` genVal!: boolean; otherVal!: string; `, expected: [`TestComponent.html(1, 12): Type 'boolean' is not assignable to type 'string'.`], }, { id: 'generic inference and two-way binding to directive (with `extends boolean`), all model inputs', inputs: { gen: { type: 'ModelSignal<T>', isSignal: true, }, other: { type: 'ModelSignal<T>', isSignal: true, }, }, outputs: {genChange: {type: 'ModelSignal<T>'}, otherChange: {type: 'ModelSignal<T>'}}, directiveGenerics: '<T extends boolean>', template: `<div dir [(gen)]="genVal" [(other)]="otherVal">`, component: ` genVal!: boolean; otherVal!: string; `, expected: [`TestComponent.html(1, 29): Type 'string' is not assignable to type 'boolean'.`], },
{ "end_byte": 16285, "start_byte": 8677, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/model_signal_diagnostics_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/model_signal_diagnostics_spec.ts_16292_24184
{ id: 'generic inference and two-way binding to directive (with `extends boolean`), mix of zone inputs and model', inputs: { gen: { type: 'ModelSignal<T>', isSignal: true, }, other: { type: 'T', isSignal: false, }, }, outputs: { genChange: {type: 'ModelSignal<T>'}, otherChange: {type: 'EventEmitter<T>'}, }, directiveGenerics: '<T extends boolean>', template: `<div dir [(gen)]="genVal" [(other)]="otherVal">`, component: ` genVal!: boolean; otherVal!: string; `, expected: [`TestComponent.html(1, 29): Type 'string' is not assignable to type 'boolean'.`], }, { id: 'generic multi-inference and two-way bindings to directive, all model inputs', inputs: { gen: { type: 'ModelSignal<T>', isSignal: true, }, other: { type: 'ModelSignal<U>', isSignal: true, }, }, outputs: { genChange: {type: 'ModelSignal<T>'}, otherChange: {type: 'ModelSignal<U>'}, }, extraDirectiveMembers: ['tester: {t: T, u: U} = null!'], directiveGenerics: '<T, U>', template: ` <div dir [(gen)]="genVal" [(other)]="otherVal" #ref="dir" (click)="ref.tester = {t: 1, u: 0}">`, component: ` genVal!: boolean; otherVal!: string; `, 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 two-way bindings to directive, mix of zone inputs and models', inputs: { gen: { type: 'ModelSignal<T>', isSignal: true, }, other: { type: 'U', isSignal: false, }, }, outputs: { genChange: {type: 'ModelSignal<T>'}, otherChange: {type: 'EventEmitter<U>'}, }, extraDirectiveMembers: ['tester: {t: T, u: U} = null!'], directiveGenerics: '<T, U>', template: ` <div dir [(gen)]="genVal" [(other)]="otherVal" #ref="dir" (click)="ref.tester = {t: 1, u: 0}">`, component: ` genVal!: boolean; otherVal!: string; `, 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 two-way bindings to directive, more complicated generic inference', inputs: { gen: { type: 'ModelSignal<T>', isSignal: true, }, other: { type: 'ModelSignal<{u: U}>', isSignal: true, }, }, outputs: { genChange: {type: 'ModelSignal<T>'}, otherChange: {type: 'ModelSignal<{u: U}>'}, }, extraDirectiveMembers: ['tester: {t: T, u: U} = null!'], directiveGenerics: '<T, U>', template: ` <div dir [(gen)]="genVal" [(other)]="otherVal" #ref="dir" (click)="ref.tester = {t: 1, u: 0}">`, component: ` genVal!: boolean; otherVal!: {u: null}; `, 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'.`, ], }, { id: 'inline constructor generic inference, two-way binding', inputs: { bla: { type: 'ModelSignal<T>', isSignal: true, }, }, outputs: {blaChange: {type: 'ModelSignal<T>'}}, 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.ts` is correctly inferred to be `HTMLElement`. `TestComponent.html(1, 62): Type 'number' is not assignable to type 'HTMLElement'.`, ], }, { id: 'one-way output binding to a model', inputs: {evt: {type: 'ModelSignal<string>', isSignal: true}}, outputs: {evtChange: {type: 'ModelSignal<string>'}}, template: `<div dir (evtChange)="$event.bla">`, expected: [`TestComponent.html(1, 30): Property 'bla' does not exist on type 'string'.`], }, { id: 'one-way output to a model with a void type', inputs: {evt: {type: 'ModelSignal<string>', isSignal: true}}, outputs: {evtChange: {type: 'ModelSignal<void>'}}, template: `<div dir (evtChange)="$event.x">`, expected: [`TestComponent.html(1, 30): Property 'x' does not exist on type 'void'.`], }, { id: 'two-way binding to primitive, invalid', inputs: {value: {type: 'ModelSignal<string>', isSignal: true}}, outputs: {valueChange: {type: 'ModelSignal<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 binding to primitive, valid', inputs: {value: {type: 'ModelSignal<string>', isSignal: true}}, outputs: {valueChange: {type: 'ModelSignal<string>'}}, template: `<div dir [(value)]="bla">`, component: `bla: string = ''`, expected: [], }, // mixing cases { id: 'mixing decorator-based and model-based event bindings', inputs: {evt1: {type: 'ModelSignal<string>', isSignal: true}}, outputs: { evt1Change: {type: 'ModelSignal<string>'}, evt2: {type: 'EventEmitter<string>'}, }, template: `<div dir (evt1Change)="x1 = $event" (evt2)="x2 = $event">`, component: ` x1: never = null!; x2: never = null!; `, expected: [ `TestComponent.html(1, 24): Type 'string' is not assignable to type 'never'.`, `TestComponent.html(1, 45): Type 'string' is not assignable to type 'never'.`, ], }, // restricted fields { id: 'allows access to private output', inputs: { evt: { type: 'ModelSignal<string>', isSignal: true, restrictionModifier: 'private', }, }, outputs: {evtChange: {type: 'ModelSignal<string>', restrictionModifier: 'private'}}, template: `<div dir (evtChange)="true">`, expected: [], }, { id: 'allows access to protected output', inputs: { evt: { type: 'ModelSignal<string>', isSignal: true, restrictionModifier: 'protected', }, }, outputs: {evt: {type: 'ModelSignal<string>', restrictionModifier: 'protected'}}, template: `<div dir (evtChange)="true">`, expected: [], }, { id: 'WritableSignal binding, valid', inputs: {value: {type: 'ModelSignal<boolean>', isSignal: true}}, outputs: {valueChange: {type: 'ModelSignal<boolean>'}}, template: `<div dir [(value)]="val">`, component: `val!: WritableSignal<boolean>;`, expected: [], },
{ "end_byte": 24184, "start_byte": 16292, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/model_signal_diagnostics_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/model_signal_diagnostics_spec.ts_24191_25957
{ id: 'WritableSignal binding, invalid', inputs: {value: {type: 'ModelSignal<boolean>', isSignal: true}}, outputs: {valueChange: {type: 'ModelSignal<boolean>'}}, template: `<div dir [(value)]="val">`, component: `val!: WritableSignal<string>;`, expected: [`TestComponent.html(1, 12): Type 'string' is not assignable to type 'boolean'.`], }, { id: 'non-writable signal binding', inputs: {value: {type: 'ModelSignal<boolean>', isSignal: true}}, outputs: {valueChange: {type: 'ModelSignal<boolean>'}}, template: `<div dir [(value)]="val">`, component: `val!: InputSignal<boolean>;`, expected: [ `TestComponent.html(1, 10): Type 'InputSignal<boolean>' is not assignable to type 'boolean'.`, ], }, { id: 'getter function binding, valid', inputs: {value: {type: 'ModelSignal<(v: string) => number>', isSignal: true}}, outputs: {valueChange: {type: 'ModelSignal<(v: string) => number>'}}, template: `<div dir [(value)]="val">`, component: `val!: (v: string) => number;`, expected: [], }, { id: 'getter function binding, invalid', inputs: {value: {type: 'ModelSignal<(v: number) => number>', isSignal: true}}, outputs: {valueChange: {type: 'ModelSignal<(v: number) => number>'}}, template: `<div dir [(value)]="val">`, component: `val!: (v: string) => number;`, expected: [ jasmine.stringContaining( `TestComponent.html(1, 12): Type '(v: string) => number' is not assignable to type '(v: number) => number`, ), ], }, ]; generateDiagnoseJasmineSpecs(bindingCases); }); });
{ "end_byte": 25957, "start_byte": 24191, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/model_signal_diagnostics_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/span_comments_spec.ts_0_314
/** * @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 {initMockFileSystem} from '../../file_system/testing'; import {tcb, TestDeclaration} from '../testing';
{ "end_byte": 314, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/span_comments_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/span_comments_spec.ts_316_6513
describe('type check blocks diagnostics', () => { beforeEach(() => initMockFileSystem('Native')); describe('parse spans', () => { it('should annotate unary ops', () => { expect(tcbWithSpans('{{ -a }}')).toContain('(-((this).a /*4,5*/) /*4,5*/) /*3,5*/'); }); it('should annotate binary ops', () => { expect(tcbWithSpans('{{ a + b }}')).toContain( '(((this).a /*3,4*/) /*3,4*/) + (((this).b /*7,8*/) /*7,8*/) /*3,8*/', ); }); it('should annotate conditions', () => { expect(tcbWithSpans('{{ a ? b : c }}')).toContain( '(((this).a /*3,4*/) /*3,4*/ ? ((this).b /*7,8*/) /*7,8*/ : (((this).c /*11,12*/) /*11,12*/)) /*3,12*/', ); }); it('should annotate interpolations', () => { expect(tcbWithSpans('{{ hello }} {{ world }}')).toContain( '"" + (((this).hello /*3,8*/) /*3,8*/) + (((this).world /*15,20*/) /*15,20*/)', ); }); it('should annotate literal map expressions', () => { // The additional method call is present to avoid that the object literal is emitted as // statement, which would wrap it into parenthesis that clutter the expected output. const TEMPLATE = '{{ m({foo: a, bar: b}) }}'; expect(tcbWithSpans(TEMPLATE)).toContain( '(this).m /*3,4*/({ "foo": ((this).a /*11,12*/) /*11,12*/, "bar": ((this).b /*19,20*/) /*19,20*/ } /*5,21*/) /*3,22*/', ); }); it('should annotate literal map expressions with shorthand declarations', () => { // The additional method call is present to avoid that the object literal is emitted as // statement, which would wrap it into parenthesis that clutter the expected output. const TEMPLATE = '{{ m({a, b}) }}'; expect(tcbWithSpans(TEMPLATE)).toContain( '((this).m /*3,4*/({ "a": ((this).a /*6,7*/) /*6,7*/, "b": ((this).b /*9,10*/) /*9,10*/ } /*5,11*/) /*3,12*/)', ); }); it('should annotate literal array expressions', () => { const TEMPLATE = '{{ [a, b] }}'; expect(tcbWithSpans(TEMPLATE)).toContain( '[((this).a /*4,5*/) /*4,5*/, ((this).b /*7,8*/) /*7,8*/] /*3,9*/', ); }); it('should annotate literals', () => { const TEMPLATE = '{{ 123 }}'; expect(tcbWithSpans(TEMPLATE)).toContain('123 /*3,6*/'); }); it('should annotate non-null assertions', () => { const TEMPLATE = `{{ a! }}`; expect(tcbWithSpans(TEMPLATE)).toContain('(((this).a /*3,4*/) /*3,4*/)! /*3,5*/'); }); it('should annotate prefix not', () => { const TEMPLATE = `{{ !a }}`; expect(tcbWithSpans(TEMPLATE)).toContain('!(((this).a /*4,5*/) /*4,5*/) /*3,5*/'); }); it('should annotate method calls', () => { const TEMPLATE = `{{ method(a, b) }}`; expect(tcbWithSpans(TEMPLATE)).toContain( '(this).method /*3,9*/(((this).a /*10,11*/) /*10,11*/, ((this).b /*13,14*/) /*13,14*/) /*3,15*/', ); }); it('should annotate safe calls', () => { const TEMPLATE = `{{ method?.(a, b) }}`; expect(tcbWithSpans(TEMPLATE)).toContain( '((0 as any ? (((this).method /*3,9*/) /*3,9*/)!(((this).a /*12,13*/) /*12,13*/, ((this).b /*15,16*/) /*15,16*/) : undefined) /*3,17*/)', ); }); it('should annotate method calls of variables', () => { const TEMPLATE = `<ng-template let-method>{{ method(a, b) }}</ng-template>`; expect(tcbWithSpans(TEMPLATE)).toContain( '_t2 /*27,33*/(((this).a /*34,35*/) /*34,35*/, ((this).b /*37,38*/) /*37,38*/) /*27,39*/', ); }); it('should annotate function calls', () => { const TEMPLATE = `{{ method(a)(b, c) }}`; expect(tcbWithSpans(TEMPLATE)).toContain( '(this).method /*3,9*/(((this).a /*10,11*/) /*10,11*/) /*3,12*/(((this).b /*13,14*/) /*13,14*/, ((this).c /*16,17*/) /*16,17*/) /*3,18*/', ); }); it('should annotate property access', () => { const TEMPLATE = `{{ a.b.c }}`; expect(tcbWithSpans(TEMPLATE)).toContain( '((((((this).a /*3,4*/) /*3,4*/).b /*5,6*/) /*3,6*/).c /*7,8*/) /*3,8*/', ); }); it('should annotate property writes', () => { const TEMPLATE = `<div (click)='a.b.c = d'></div>`; expect(tcbWithSpans(TEMPLATE)).toContain( '(((((((this).a /*14,15*/) /*14,15*/).b /*16,17*/) /*14,17*/).c /*18,19*/) /*14,23*/ = (((this).d /*22,23*/) /*22,23*/)) /*14,23*/', ); }); it('should $event property writes', () => { const TEMPLATE = `<div (click)='a = $event'></div>`; expect(tcbWithSpans(TEMPLATE)).toContain( '(((this).a /*14,15*/) /*14,24*/ = ($event /*18,24*/)) /*14,24*/;', ); }); it('should annotate keyed property access', () => { const TEMPLATE = `{{ a[b] }}`; expect(tcbWithSpans(TEMPLATE)).toContain( '(((this).a /*3,4*/) /*3,4*/)[((this).b /*5,6*/) /*5,6*/] /*3,7*/', ); }); it('should annotate keyed property writes', () => { const TEMPLATE = `<div (click)="a[b] = c"></div>`; expect(tcbWithSpans(TEMPLATE)).toContain( '((((this).a /*14,15*/) /*14,15*/)[((this).b /*16,17*/) /*16,17*/] = (((this).c /*21,22*/) /*21,22*/)) /*14,22*/', ); }); it('should annotate safe property access', () => { const TEMPLATE = `{{ a?.b }}`; expect(tcbWithSpans(TEMPLATE)).toContain( '(0 as any ? (((this).a /*3,4*/) /*3,4*/)!.b /*6,7*/ : undefined) /*3,7*/', ); }); it('should annotate safe method calls', () => { const TEMPLATE = `{{ a?.method(b) }}`; expect(tcbWithSpans(TEMPLATE)).toContain( '((0 as any ? (0 as any ? (((this).a /*3,4*/) /*3,4*/)!.method /*6,12*/ : undefined) /*3,12*/!(((this).b /*13,14*/) /*13,14*/) : undefined) /*3,15*/)', ); }); it('should annotate safe keyed reads', () => { const TEMPLATE = `{{ a?.[0] }}`; expect(tcbWithSpans(TEMPLATE)).toContain( '(0 as any ? (((this).a /*3,4*/) /*3,4*/)![0 /*7,8*/] /*3,9*/ : undefined) /*3,9*/', ); }); it('should annotate $any casts', () => { const TEMPLATE = `{{ $any(a) }}`; expect(tcbWithSpans(TEMPLATE)).toContain('(((this).a /*8,9*/) /*8,9*/ as any) /*3,10*/'); });
{ "end_byte": 6513, "start_byte": 316, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/span_comments_spec.ts" }
angular/packages/compiler-cli/src/ngtsc/typecheck/test/span_comments_spec.ts_6519_10590
it('should annotate chained expressions', () => { const TEMPLATE = `<div (click)='a; b; c'></div>`; expect(tcbWithSpans(TEMPLATE)).toContain( '(((this).a /*14,15*/) /*14,15*/, ((this).b /*17,18*/) /*17,18*/, ((this).c /*20,21*/) /*20,21*/) /*14,21*/', ); }); it('should annotate pipe usages', () => { const TEMPLATE = `{{ a | test:b }}`; const PIPES: TestDeclaration[] = [ { type: 'pipe', name: 'TestPipe', pipeName: 'test', }, ]; const block = tcbWithSpans(TEMPLATE, PIPES); expect(block).toContain('var _pipe1 = null! as i0.TestPipe'); expect(block).toContain( '(_pipe1.transform /*7,11*/(((this).a /*3,4*/) /*3,4*/, ((this).b /*12,13*/) /*12,13*/) /*3,13*/);', ); }); describe('attaching multiple comments for multiple references', () => { it('should be correct for element refs', () => { const TEMPLATE = `<span #a></span>{{ a || a }}`; expect(tcbWithSpans(TEMPLATE)).toContain('((_t1 /*19,20*/) || (_t1 /*24,25*/) /*19,25*/);'); }); it('should be correct for template vars', () => { const TEMPLATE = `<ng-template let-a='b'>{{ a || a }}</ng-template>`; expect(tcbWithSpans(TEMPLATE)).toContain('((_t2 /*26,27*/) || (_t2 /*31,32*/) /*26,32*/);'); }); it('should be correct for directive refs', () => { const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'MyComponent', selector: 'my-cmp', isComponent: true, }, ]; const TEMPLATE = `<my-cmp #a></my-cmp>{{ a || a }}`; expect(tcbWithSpans(TEMPLATE, DIRECTIVES)).toContain( '((_t1 /*23,24*/) || (_t1 /*28,29*/) /*23,29*/);', ); }); }); describe('attaching comments for generic directive inputs', () => { it('should be correct for directive refs', () => { const DIRECTIVES: TestDeclaration[] = [ { type: 'directive', name: 'MyComponent', selector: 'my-cmp', isComponent: true, isGeneric: true, inputs: {'inputA': 'inputA'}, }, ]; const TEMPLATE = `<my-cmp [inputA]="''"></my-cmp>`; expect(tcbWithSpans(TEMPLATE, DIRECTIVES)).toContain( '_t1.inputA /*9,15*/ = ("" /*18,20*/) /*8,21*/;', ); }); }); describe('control flow', () => { it('@for', () => { const template = `@for (user of users; track user; let i = $index) { {{i}} }`; // user variable expect(tcbWithSpans(template, [])).toContain('const _t1 /*6,10*/'); expect(tcbWithSpans(template, [])).toContain('(this).users /*14,19*/'); // index variable expect(tcbWithSpans(template, [])).toContain( 'var _t2 /*37,38*/ = null! as number /*T:VAE*/ /*37,47*/', ); // track expression expect(tcbWithSpans(template, [])).toContain('_t1 /*27,31*/;'); }); it('@for with comma separated variables', () => { const template = `@for (x of y; track x; let i = $index, odd = $odd,e_v_e_n=$even) { {{i + odd + e_v_e_n}} }`; expect(tcbWithSpans(template, [])).toContain( 'var _t2 /*27,28*/ = null! as number /*T:VAE*/ /*27,37*/', ); expect(tcbWithSpans(template, [])).toContain( 'var _t3 /*39,42*/ = null! as boolean /*T:VAE*/ /*39,54*/', ); expect(tcbWithSpans(template, [])).toContain( 'var _t4 /*55,62*/ = null! as boolean /*T:VAE*/ /*55,68*/', ); }); it('@if', () => { const template = `@if (x; as alias) { {{alias}} }`; expect(tcbWithSpans(template, [])).toContain('var _t1 /*11,16*/'); expect(tcbWithSpans(template, [])).toContain('(this).x /*5,6*/'); }); }); }); }); function tcbWithSpans(template: string, declarations: TestDeclaration[] = []): string { return tcb(template, declarations, undefined, {emitSpans: true}); }
{ "end_byte": 10590, "start_byte": 6519, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/src/ngtsc/typecheck/test/span_comments_spec.ts" }