_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/compiler-cli/test/ngtsc/incremental_error_spec.ts_14472_18968 | describe('chained errors', () => {
it('should remember a change to a TS file across broken builds', () => {
// Two components, an NgModule, and a random file.
writeTwoComponentSystem(env);
writeRandomFile(env, 'other.ts');
// Start with a clean build.
env.driveMain();
env.flushWrittenFileTracking();
// Update ACmp
env.write(
'a.ts',
`
import {Component} from '@angular/core';
@Component({
selector: 'a-cmp',
template: 'new template',
standalone: false,
})
export class ACmp {}
`,
);
// Update the file to have an error, simultaneously.
writeRandomFile(env, 'other.ts', {error: true});
// This build should fail.
const diags = env.driveDiagnostics();
expect(diags.length).not.toBe(0);
expectToHaveWritten([]);
// Fix the error.
writeRandomFile(env, 'other.ts');
// Rebuild.
env.driveMain();
// If the compiler behaves correctly, it should remember that 'a.ts' was updated before, and
// should regenerate b.ts.
expectToHaveWritten([
// Because they directly changed
'/other.js',
'/a.js',
// Because they depend on a.ts
'/module.js',
]);
});
it('should remember a change to a template file across broken builds', () => {
// This is basically the same test as above, except a.html is changed instead of a.ts.
// Two components, an NgModule, and a random file.
writeTwoComponentSystem(env);
writeRandomFile(env, 'other.ts');
// Start with a clean build.
env.driveMain();
env.flushWrittenFileTracking();
// Invalidate ACmp's template.
env.write('a.html', 'Changed template');
// Update the file to have an error, simultaneously.
writeRandomFile(env, 'other.ts', {error: true});
// This build should fail.
const diags = env.driveDiagnostics();
expect(diags.length).not.toBe(0);
expectToHaveWritten([]);
// Fix the error.
writeRandomFile(env, 'other.ts');
// Rebuild.
env.flushWrittenFileTracking();
env.driveMain();
// If the compiler behaves correctly, it should remember that 'a.html' was updated before,
// and should regenerate a.js. Because the compiler knows a.html is a _resource_ dependency
// of a.ts, it should only regenerate a.js and not its module and dependent components (as
// it would if a.ts were itself changed like in the test above).
expectToHaveWritten([
// Because it directly changed.
'/other.js',
// Because a.html changed
'/a.js',
// module.js should not be re-emitted, as it is not affected by the change and its remote
// scope is unaffected.
// b.js and module.js should not be re-emitted, because specifically when tracking
// resource dependencies, the compiler knows that a change to a resource file only affects
// the direct emit of dependent file.
]);
});
});
});
});
/**
* Two components, ACmp and BCmp, where BCmp depends on ACmp.
*
* ACmp has its template in a separate file.
*/
export function writeTwoComponentSystem(env: NgtscTestEnvironment): void {
env.write('a.html', 'This is the template for CmpA');
env.write(
'a.ts',
`
import {Component} from '@angular/core';
@Component({
selector: 'a-cmp',
templateUrl: './a.html',
standalone: false,
})
export class ACmp {}
`,
);
env.write(
'b.ts',
`
import {Component} from '@angular/core';
@Component({
selector: 'b-cmp',
template: '<a-cmp></a-cmp>',
standalone: false,
})
export class BCmp {}
`,
);
env.write(
'module.ts',
`
import {NgModule} from '@angular/core';
import {ACmp} from './a';
import {BCmp} from './b';
@NgModule({
declarations: [ACmp, BCmp],
})
export class Module {}
`,
);
}
export function writeRandomFile(
env: NgtscTestEnvironment,
name: string,
options: {error?: true} = {},
): void {
env.write(
name,
`
// If options.error is set, this class has missing braces.
export class Other ${options.error !== true ? '{}' : ''}
`,
);
} | {
"end_byte": 18968,
"start_byte": 14472,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_error_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/incremental_spec.ts_0_523 | /**
* @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 '../../src/ngtsc/diagnostics';
import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '../../src/ngtsc/testing';
import {NgtscTestEnvironment} from './env';
const testFiles = loadStandardTestFiles();
runInEachFileSystem(() => | {
"end_byte": 523,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/incremental_spec.ts_524_9385 | {
describe('ngtsc incremental compilation', () => {
let env!: NgtscTestEnvironment;
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.enableMultipleCompilations();
env.tsconfig();
});
it('should not crash if CLI does not provide getModifiedResourceFiles()', () => {
env.write(
'component1.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'cmp', templateUrl: './component1.template.html'})
export class Cmp1 {}
`,
);
env.write('component1.template.html', 'cmp1');
env.driveMain();
// Simulate a change to `component1.html`
env.flushWrittenFileTracking();
env.invalidateCachedFile('component1.html');
env.simulateLegacyCLICompilerHost();
env.driveMain();
});
it('should skip unchanged services', () => {
env.write(
'service.ts',
`
import {Injectable} from '@angular/core';
@Injectable()
export class Service {}
`,
);
env.write(
'test.ts',
`
import {Component} from '@angular/core';
import {Service} from './service';
@Component({selector: 'cmp', template: 'cmp'})
export class Cmp {
constructor(service: Service) {}
}
`,
);
env.driveMain();
env.flushWrittenFileTracking();
// Pretend a change was made to test.ts.
env.invalidateCachedFile('test.ts');
env.driveMain();
const written = env.getFilesWrittenSinceLastFlush();
// The changed file should be recompiled, but not the service.
expect(written).toContain('/test.js');
expect(written).not.toContain('/service.js');
});
it('should rebuild components that have changed', () => {
env.tsconfig({strictTemplates: true});
env.write(
'component1.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'cmp', template: 'cmp'})
export class Cmp1 {}
`,
);
env.write(
'component2.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'cmp2', template: 'cmp'})
export class Cmp2 {}
`,
);
env.driveMain();
// Pretend a change was made to Cmp1
env.flushWrittenFileTracking();
env.invalidateCachedFile('component1.ts');
env.driveMain();
const written = env.getFilesWrittenSinceLastFlush();
expect(written).toContain('/component1.js');
expect(written).not.toContain('/component2.js');
});
it('should rebuild components whose templates have changed', () => {
env.write(
'component1.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'cmp', templateUrl: './component1.template.html'})
export class Cmp1 {}
`,
);
env.write('component1.template.html', 'cmp1');
env.write(
'component2.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'cmp2', templateUrl: './component2.template.html'})
export class Cmp2 {}
`,
);
env.write('component2.template.html', 'cmp2');
env.driveMain();
// Make a change to Cmp1 template
env.flushWrittenFileTracking();
env.write('component1.template.html', 'changed');
env.driveMain();
const written = env.getFilesWrittenSinceLastFlush();
expect(written).toContain('/component1.js');
expect(written).not.toContain('/component2.js');
});
it('should rebuild components whose partial-evaluation dependencies have changed', () => {
env.write(
'component1.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'cmp', template: 'cmp'})
export class Cmp1 {}
`,
);
env.write(
'component2.ts',
`
import {Component} from '@angular/core';
import {SELECTOR} from './constants';
@Component({selector: SELECTOR, template: 'cmp'})
export class Cmp2 {}
`,
);
env.write(
'constants.ts',
`
export const SELECTOR = 'cmp';
`,
);
env.driveMain();
// Pretend a change was made to SELECTOR
env.flushWrittenFileTracking();
env.invalidateCachedFile('constants.ts');
env.driveMain();
const written = env.getFilesWrittenSinceLastFlush();
expect(written).toContain('/constants.js');
expect(written).not.toContain('/component1.js');
expect(written).toContain('/component2.js');
});
it('should rebuild components whose imported dependencies have changed', () => {
setupFooBarProgram(env);
// Pretend a change was made to BarDir.
env.write(
'bar_directive.ts',
`
import {Directive} from '@angular/core';
@Directive({
selector: '[barr]',
standalone: false,
})
export class BarDir {}
`,
);
env.driveMain();
let written = env.getFilesWrittenSinceLastFlush();
expect(written).toContain('/bar_directive.js');
expect(written).toContain('/bar_component.js');
expect(written).toContain('/bar_module.js');
expect(written).not.toContain('/foo_component.js'); // BarDir is not exported by BarModule,
// so upstream NgModule is not affected
expect(written).not.toContain('/foo_pipe.js');
expect(written).not.toContain('/foo_module.js');
});
// https://github.com/angular/angular/issues/32416
it('should rebuild full NgModule scope when a dependency of a declaration has changed', () => {
env.write(
'component1.ts',
`
import {Component} from '@angular/core';
import {SELECTOR} from './dep';
@Component({
selector: SELECTOR,
template: 'cmp',
standalone: false,
})
export class Cmp1 {}
`,
);
env.write(
'component2.ts',
`
import {Component} from '@angular/core';
@Component({
selector: 'cmp2',
template: '<cmp></cmp>',
standalone: false,
})
export class Cmp2 {}
`,
);
env.write(
'dep.ts',
`
export const SELECTOR = 'cmp';
`,
);
env.write(
'directive.ts',
`
import {Directive} from '@angular/core';
@Directive({
selector: 'dir',
standalone: false,
})
export class Dir {}
`,
);
env.write(
'pipe.ts',
`
import {Pipe} from '@angular/core';
@Pipe({
name: 'myPipe',
standalone: false,
})
export class MyPipe {
transform() {}
}
`,
);
env.write(
'module.ts',
`
import {NgModule, NO_ERRORS_SCHEMA} from '@angular/core';
import {Cmp1} from './component1';
import {Cmp2} from './component2';
import {Dir} from './directive';
import {MyPipe} from './pipe';
@NgModule({declarations: [Cmp1, Cmp2, Dir, MyPipe], schemas: [NO_ERRORS_SCHEMA]})
export class Mod {}
`,
);
env.driveMain();
// Pretend a change was made to 'dep'. Since the selector is updated this affects the NgModule
// scope, so all components in the module scope need to be recompiled.
env.flushWrittenFileTracking();
env.write(
'dep.ts',
`
export const SELECTOR = 'cmp_updated';
`,
);
env.driveMain();
const written = env.getFilesWrittenSinceLastFlush();
expect(written).not.toContain('/directive.js');
expect(written).not.toContain('/pipe.js');
expect(written).not.toContain('/module.js');
expect(written).toContain('/component1.js');
expect(written).toContain('/component2.js');
expect(written).toContain('/dep.js');
});
it('should rebuild components where their NgModule declared dependencies have changed', () => {
setupFooBarProgram(env);
// Rename the pipe so components that use it need to be recompiled.
env.write(
'foo_pipe.ts',
`
import {Pipe} from '@angular/core';
@Pipe({name: 'foo_changed', standalone: false})
export class FooPipe {
transform() {}
}
`,
);
env.driveMain();
const written = env.getFilesWrittenSinceLastFlush();
expect(written).not.toContain('/bar_directive.js');
expect(written).not.toContain('/bar_component.js');
expect(written).not.toContain('/bar_module.js');
expect(written).toContain('/foo_component.js');
expect(written).toContain('/foo_pipe.js');
expect(written).toContain('/foo_module.js');
}); | {
"end_byte": 9385,
"start_byte": 524,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/incremental_spec.ts_9391_18597 | it('should rebuild components where their NgModule has changed', () => {
setupFooBarProgram(env);
// Pretend a change was made to FooModule.
env.write(
'foo_module.ts',
`
import {NgModule} from '@angular/core';
import {FooCmp} from './foo_component';
import {FooPipe} from './foo_pipe';
import {BarModule} from './bar_module';
@NgModule({
declarations: [FooCmp], // removed FooPipe
imports: [BarModule],
})
export class FooModule {}
`,
);
env.driveMain();
const written = env.getFilesWrittenSinceLastFlush();
expect(written).not.toContain('/bar_directive.js');
expect(written).not.toContain('/bar_component.js');
expect(written).not.toContain('/bar_module.js');
expect(written).not.toContain('/foo_pipe.js');
expect(written).toContain('/foo_component.js');
expect(written).toContain('/foo_module.js');
});
it('should rebuild a component if one of its deep NgModule dependencies changes', () => {
// This test constructs a chain of NgModules:
// - EntryModule imports MiddleAModule
// - MiddleAModule exports MiddleBModule
// - MiddleBModule exports DirModule
// The last link (MiddleBModule exports DirModule) is not present initially, but is added
// during a recompilation.
//
// Since the dependency from EntryModule on the contents of MiddleBModule is not "direct"
// (meaning MiddleBModule is not discovered during analysis of EntryModule), this test is
// verifying that NgModule dependency tracking correctly accounts for this situation.
env.write(
'entry.ts',
`
import {Component, NgModule} from '@angular/core';
import {MiddleAModule} from './middle-a';
@Component({
selector: 'test-cmp',
template: '<div dir>',
standalone: false,
})
export class TestCmp {}
@NgModule({
declarations: [TestCmp],
imports: [MiddleAModule],
})
export class EntryModule {}
`,
);
env.write(
'middle-a.ts',
`
import {NgModule} from '@angular/core';
import {MiddleBModule} from './middle-b';
@NgModule({
exports: [MiddleBModule],
})
export class MiddleAModule {}
`,
);
env.write(
'middle-b.ts',
`
import {NgModule} from '@angular/core';
@NgModule({})
export class MiddleBModule {}
`,
);
env.write(
'dir_module.ts',
`
import {NgModule} from '@angular/core';
import {Dir} from './dir';
@NgModule({
declarations: [Dir],
exports: [Dir],
})
export class DirModule {}
`,
);
env.write(
'dir.ts',
`
import {Directive} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class Dir {}
`,
);
env.driveMain();
expect(env.getContents('entry.js')).not.toContain('Dir');
env.write(
'middle-b.ts',
`
import {NgModule} from '@angular/core';
import {DirModule} from './dir_module';
@NgModule({
exports: [DirModule],
})
export class MiddleBModule {}
`,
);
env.driveMain();
expect(env.getContents('entry.js')).toContain('Dir');
});
it('should rebuild a component if removed from an NgModule', () => {
// This test consists of a component with a dependency (the directive DepDir) provided via an
// NgModule. Initially this configuration is built, then the component is removed from its
// module (which removes DepDir from the component's scope) and a rebuild is performed.
// The compiler should re-emit the component without DepDir in its scope.
//
// This is a tricky scenario due to the backwards dependency arrow from a component to its
// module.
env.write(
'dep.ts',
`
import {Directive, NgModule} from '@angular/core';
@Directive({
selector: '[dep]',
standalone: false,
})
export class DepDir {}
@NgModule({
declarations: [DepDir],
exports: [DepDir],
})
export class DepModule {}
`,
);
env.write(
'cmp.ts',
`
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div dep></div>',
standalone: false,
})
export class Cmp {}
`,
);
env.write(
'module.ts',
`
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {DepModule} from './dep';
@NgModule({
declarations: [Cmp],
imports: [DepModule],
})
export class Module {}
`,
);
env.driveMain();
env.flushWrittenFileTracking();
// Remove the component from the module and recompile.
env.write(
'module.ts',
`
import {NgModule} from '@angular/core';
import {DepModule} from './dep';
@NgModule({
declarations: [],
imports: [DepModule],
})
export class Module {}
`,
);
env.driveMain();
// After removing the component from the module, it should have been re-emitted without DepDir
// in its scope.
expect(env.getFilesWrittenSinceLastFlush()).toContain('/cmp.js');
expect(env.getContents('cmp.js')).not.toContain('DepDir');
});
it('should rebuild only a Component (but with the correct CompilationScope) if its template has changed', () => {
setupFooBarProgram(env);
// Make a change to the template of BarComponent.
env.write('bar_component.html', '<div bar>changed</div>');
env.driveMain();
const written = env.getFilesWrittenSinceLastFlush();
expect(written).not.toContain('/bar_directive.js');
expect(written).toContain('/bar_component.js');
expect(written).not.toContain('/bar_module.js');
expect(written).not.toContain('/foo_component.js');
expect(written).not.toContain('/foo_pipe.js');
expect(written).not.toContain('/foo_module.js');
// Ensure that the used directives are included in the component's generated template.
expect(env.getContents('/built/bar_component.js')).toMatch(/dependencies:\s*\[.+\.BarDir\]/);
});
it('should rebuild everything if a typings file changes', () => {
setupFooBarProgram(env);
// Pretend a change was made to a typings file.
env.invalidateCachedFile('foo_selector.d.ts');
env.driveMain();
const written = env.getFilesWrittenSinceLastFlush();
expect(written).toContain('/bar_directive.js');
expect(written).toContain('/bar_component.js');
expect(written).toContain('/bar_module.js');
expect(written).toContain('/foo_component.js');
expect(written).toContain('/foo_pipe.js');
expect(written).toContain('/foo_module.js');
});
it('should re-emit an NgModule when the provider status of its imports changes', () => {
env.write(
'provider-dep.ts',
`
import {Injectable, NgModule} from '@angular/core';
@Injectable()
export class Service {}
@NgModule({
providers: [Service],
})
export class DepModule {}
`,
);
env.write(
'standalone-cmp.ts',
`
import {Component} from '@angular/core';
import {DepModule} from './provider-dep';
@Component({
standalone: true,
template: '',
imports: [DepModule],
})
export class Cmp {}
`,
);
env.write(
'module.ts',
`
import {NgModule} from '@angular/core';
import {Cmp} from './standalone-cmp';
@NgModule({
imports: [Cmp],
})
export class Module {}
`,
);
env.driveMain();
env.write(
'provider-dep.ts',
`
import {Injectable, NgModule} from '@angular/core';
@NgModule({})
export class DepModule {}
`,
);
env.flushWrittenFileTracking();
env.driveMain();
const written = env.getFilesWrittenSinceLastFlush();
expect(written).toContain('/module.js');
});
it('should compile incrementally with template type-checking turned on', () => {
env.tsconfig({fullTemplateTypeCheck: true});
env.write(
'main.ts',
`
import {Component} from '@angular/core';
@Component({template: ''})
export class MyComponent {}
`,
);
env.driveMain();
env.invalidateCachedFile('main.ts');
env.driveMain();
// If program reuse were configured incorrectly (as was responsible for
// https://github.com/angular/angular/issues/30079), this would have crashed.
}); | {
"end_byte": 18597,
"start_byte": 9391,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/incremental_spec.ts_18603_24052 | // https://github.com/angular/angular/issues/38979
it('should retain ambient types provided by auto-discovered @types', () => {
// This test verifies that ambient types declared in node_modules/@types are still available
// in incremental compilations. In the below code, the usage of `require` should be valid
// in the original program and the incremental program.
env.tsconfig({fullTemplateTypeCheck: true});
env.write('node_modules/@types/node/index.d.ts', 'declare var require: any;');
env.write(
'main.ts',
`
import {Component} from '@angular/core';
require('path');
@Component({template: ''})
export class MyComponent {}
`,
);
env.driveMain();
env.invalidateCachedFile('main.ts');
const diags = env.driveDiagnostics();
expect(diags.length).toBe(0);
});
// https://github.com/angular/angular/pull/26036
it('should handle redirected source files', () => {
env.tsconfig({fullTemplateTypeCheck: true});
// This file structure has an identical version of "a" under the root node_modules and inside
// of "b". Because their package.json file indicates it is the exact same version of "a",
// TypeScript will transform the source file of "node_modules/b/node_modules/a/index.d.ts"
// into a redirect to "node_modules/a/index.d.ts". During incremental compilations, we must
// assure not to reintroduce "node_modules/b/node_modules/a/index.d.ts" as its redirected
// source file, but instead use its original file.
env.write('node_modules/a/index.js', `export class ServiceA {}`);
env.write('node_modules/a/index.d.ts', `export declare class ServiceA {}`);
env.write('node_modules/a/package.json', `{"name": "a", "version": "1.0"}`);
env.write('node_modules/b/node_modules/a/index.js', `export class ServiceA {}`);
env.write('node_modules/b/node_modules/a/index.d.ts', `export declare class ServiceA {}`);
env.write('node_modules/b/node_modules/a/package.json', `{"name": "a", "version": "1.0"}`);
env.write('node_modules/b/index.js', `export {ServiceA as ServiceB} from 'a';`);
env.write('node_modules/b/index.d.ts', `export {ServiceA as ServiceB} from 'a';`);
env.write(
'test.ts',
`
import {Component} from '@angular/core';
import {ServiceA} from 'a';
import {ServiceB} from 'b';
@Component({template: ''})
export class MyComponent {}
`,
);
env.driveMain();
env.flushWrittenFileTracking();
// Pretend a change was made to test.ts. If redirect sources were introduced into the new
// program, this would fail due to an assertion failure in TS.
env.invalidateCachedFile('test.ts');
env.driveMain();
});
it('should allow incremental compilation with redirected source files', () => {
env.tsconfig({fullTemplateTypeCheck: true});
// This file structure has an identical version of "a" under the root node_modules and inside
// of "b". Because their package.json file indicates it is the exact same version of "a",
// TypeScript will transform the source file of "node_modules/b/node_modules/a/index.d.ts"
// into a redirect to "node_modules/a/index.d.ts". During incremental compilations, the
// redirected "node_modules/b/node_modules/a/index.d.ts" source file should be considered as
// its unredirected source file to avoid a change in declaration files.
env.write('node_modules/a/index.js', `export class ServiceA {}`);
env.write('node_modules/a/index.d.ts', `export declare class ServiceA {}`);
env.write('node_modules/a/package.json', `{"name": "a", "version": "1.0"}`);
env.write('node_modules/b/node_modules/a/index.js', `export class ServiceA {}`);
env.write('node_modules/b/node_modules/a/index.d.ts', `export declare class ServiceA {}`);
env.write('node_modules/b/node_modules/a/package.json', `{"name": "a", "version": "1.0"}`);
env.write('node_modules/b/index.js', `export {ServiceA as ServiceB} from 'a';`);
env.write('node_modules/b/index.d.ts', `export {ServiceA as ServiceB} from 'a';`);
env.write(
'component1.ts',
`
import {Component} from '@angular/core';
import {ServiceA} from 'a';
import {ServiceB} from 'b';
@Component({selector: 'cmp', template: 'cmp'})
export class Cmp1 {}
`,
);
env.write(
'component2.ts',
`
import {Component} from '@angular/core';
import {ServiceA} from 'a';
import {ServiceB} from 'b';
@Component({selector: 'cmp2', template: 'cmp'})
export class Cmp2 {}
`,
);
env.driveMain();
env.flushWrittenFileTracking();
// Now update `component1.ts` and change its imports to avoid complete structure reuse, which
// forces recreation of source file redirects.
env.write(
'component1.ts',
`
import {Component} from '@angular/core';
import {ServiceA} from 'a';
@Component({selector: 'cmp', template: 'cmp'})
export class Cmp1 {}
`,
);
env.driveMain();
const written = env.getFilesWrittenSinceLastFlush();
expect(written).toContain('/component1.js');
expect(written).not.toContain('/component2.js');
}); | {
"end_byte": 24052,
"start_byte": 18603,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/incremental_spec.ts_24058_32625 | describe('template type-checking', () => {
beforeEach(() => {
env.tsconfig({strictTemplates: true});
});
it('should repeat type errors across rebuilds, even if nothing has changed', () => {
// This test verifies that when a project is rebuilt multiple times with no changes, all
// template diagnostics are produced each time. Different types of errors are checked:
// - a general type error
// - an unmatched binding
// - a DOM schema error
env.write(
'component.ts',
`
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: \`
{{notAProperty}}
<not-a-component></not-a-component>
<div [notMatched]="1"></div>
\`,
})
export class TestCmp {}
`,
);
let diags = env.driveDiagnostics();
// Should get a diagnostic for each line in the template.
expect(diags.length).toBe(3);
// Now rebuild without any changes, and verify they're still produced.
diags = env.driveDiagnostics();
expect(diags.length).toBe(3);
// If it's worth testing, it's worth overtesting.
//
// Actually, the above only tests the transition from "initial" to "incremental"
// compilation. The next build verifies that an "incremental to incremental" transition
// preserves the diagnostics as well.
diags = env.driveDiagnostics();
expect(diags.length).toBe(3);
});
it('should pick up errors caused by changing an unrelated interface', () => {
// The premise of this test is that `iface.ts` declares an interface which is used to type
// a property of a component. The interface is then changed in a subsequent compilation in
// a way that introduces a type error in the template. The test verifies the resulting
// diagnostic is produced.
env.write(
'iface.ts',
`
export interface SomeType {
field: string;
}
`,
);
env.write(
'component.ts',
`
import {Component} from '@angular/core';
import {SomeType} from './iface';
@Component({
selector: 'test-cmp',
template: '{{ doSomething(value.field) }}',
})
export class TestCmp {
value!: SomeType;
// Takes a string value only.
doSomething(param: string): string {
return param;
}
}
`,
);
expect(env.driveDiagnostics().length).toBe(0);
env.flushWrittenFileTracking();
// Change the interface.
env.write(
'iface.ts',
`
export interface SomeType {
field: number;
}
`,
);
expect(env.driveDiagnostics().length).toBe(1);
});
it('should retain default imports that have been converted into a value expression', () => {
// This test defines the component `TestCmp` that has a default-imported class as
// constructor parameter, and uses `TestDir` in its template. An incremental compilation
// updates `TestDir` and changes its inputs, thereby triggering re-emit of `TestCmp` without
// performing re-analysis of `TestCmp`. The output of the re-emitted file for `TestCmp`
// should continue to have retained the default import.
env.write(
'service.ts',
`
import {Injectable} from '@angular/core';
@Injectable({ providedIn: 'root' })
export default class DefaultService {}
`,
);
env.write(
'cmp.ts',
`
import {Component, Directive} from '@angular/core';
import DefaultService from './service';
@Component({
template: '<div dir></div>',
standalone: false,
})
export class TestCmp {
constructor(service: DefaultService) {}
}
`,
);
env.write(
'dir.ts',
`
import {Directive} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class TestDir {}
`,
);
env.write(
'mod.ts',
`
import {NgModule} from '@angular/core';
import {TestDir} from './dir';
import {TestCmp} from './cmp';
@NgModule({ declarations: [TestDir, TestCmp] })
export class TestMod {}
`,
);
env.driveMain();
env.flushWrittenFileTracking();
// Update `TestDir` to change its inputs, triggering a re-emit of `TestCmp` that uses
// `TestDir`.
env.write(
'dir.ts',
`
import {Directive} from '@angular/core';
@Directive({
selector: '[dir]',
inputs: ['added'],
standalone: false,
})
export class TestDir {}
`,
);
env.driveMain();
// Verify that `TestCmp` was indeed re-emitted.
const written = env.getFilesWrittenSinceLastFlush();
expect(written).toContain('/dir.js');
expect(written).toContain('/cmp.js');
// Verify that the default import is still present.
const content = env.getContents('cmp.js');
expect(content).toContain(`import DefaultService from './service';`);
});
it('should recompile when a remote change happens to a scope', () => {
// The premise of this test is that the component Cmp has a template error (a binding to an
// unknown property). Cmp is in ModuleA, which imports ModuleB, which declares Dir that has
// the property. Because ModuleB doesn't export Dir, it's not visible to Cmp - hence the
// error.
// In the test, during the incremental rebuild Dir is exported from ModuleB. This is a
// change to the scope of ModuleA made by changing ModuleB (hence, a "remote change"). The
// test verifies that incremental template type-checking.
env.write(
'cmp.ts',
`
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<div dir [someInput]="1"></div>',
standalone: false,
})
export class Cmp {}
`,
);
env.write(
'module-a.ts',
`
import {NgModule} from '@angular/core';
import {Cmp} from './cmp';
import {ModuleB} from './module-b';
@NgModule({
declarations: [Cmp],
imports: [ModuleB],
})
export class ModuleA {}
`,
);
// Declare ModuleB and a directive Dir, but ModuleB does not yet export Dir.
env.write(
'module-b.ts',
`
import {NgModule} from '@angular/core';
import {Dir} from './dir';
@NgModule({
declarations: [Dir],
})
export class ModuleB {}
`,
);
env.write(
'dir.ts',
`
import {Directive, Input} from '@angular/core';
@Directive({
selector: '[dir]',
standalone: false,
})
export class Dir {
@Input() someInput!: any;
}
`,
);
let diags = env.driveDiagnostics();
// Should get a diagnostic about [dir] not being a valid binding.
expect(diags.length).toBe(1);
// As a precautionary check, run the build a second time with no changes, to ensure the
// diagnostic is repeated.
diags = env.driveDiagnostics();
// Should get a diagnostic about [dir] not being a valid binding.
expect(diags.length).toBe(1);
// Modify ModuleB to now export Dir.
env.write(
'module-b.ts',
`
import {NgModule} from '@angular/core';
import {Dir} from './dir';
@NgModule({
declarations: [Dir],
exports: [Dir],
})
export class ModuleB {}
`,
);
diags = env.driveDiagnostics();
// Diagnostic should be gone, as the error has been fixed.
expect(diags.length).toBe(0);
}); | {
"end_byte": 32625,
"start_byte": 24058,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/incremental_spec.ts_32633_40155 | describe('inline operations', () => {
it('should still pick up on errors from inlined type check blocks', () => {
// In certain cases the template type-checker has to inline type checking blocks into user
// code, instead of placing it in a parallel template type-checking file. In these cases
// incremental checking cannot be used, and the type-checking code must be regenerated on
// each build. This test verifies that the above mechanism works properly, by performing
// type-checking on an unexported class (not exporting the class forces the inline
// checking de-optimization).
env.write(
'cmp.ts',
`
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '{{test}}',
})
class Cmp {}
`,
);
// On the first compilation, an error should be produced.
let diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
// Next, two more builds are run, one with no changes made to the file, and the other with
// changes made that should remove the error.
// The error should still be present when rebuilding.
diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
// Now, correct the error by adding the 'test' property to the component.
env.write(
'cmp.ts',
`
import {Component} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '{{test}}',
})
class Cmp {
test!: string;
}
`,
);
env.driveMain();
// The error should be gone.
diags = env.driveDiagnostics();
expect(diags.length).toBe(0);
});
it('should still pick up on errors caused by inlined type constructors', () => {
// In certain cases the template type-checker cannot generate a type constructor for a
// directive within the template type-checking file which requires it, but must inline the
// type constructor within its original source file. In these cases, template type
// checking cannot be performed incrementally. This test verifies that such cases still
// work correctly, by repeatedly performing diagnostics on a component which depends on a
// directive with an inlined type constructor.
env.write(
'dir.ts',
`
import {Directive, Input} from '@angular/core';
export interface Keys {
alpha: string;
beta: string;
}
@Directive({
selector: '[dir]',
standalone: false,
})
export class Dir<T extends keyof Keys> {
// The use of 'keyof' in the generic bound causes a deopt to an inline type
// constructor.
@Input() dir: T;
}
`,
);
env.write(
'cmp.ts',
`
import {Component, NgModule} from '@angular/core';
import {Dir} from './dir';
@Component({
selector: 'test-cmp',
template: '<div dir="gamma"></div>',
standalone: false,
})
export class Cmp {}
@NgModule({
declarations: [Cmp, Dir],
})
export class Module {}
`,
);
let diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
expect(diags[0].messageText).toContain(
`Type '"gamma"' is not assignable to type 'keyof Keys'.`,
);
// On a rebuild, the same errors should be present.
diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
expect(diags[0].messageText).toContain(
`Type '"gamma"' is not assignable to type 'keyof Keys'.`,
);
});
it('should not re-emit files that need inline type constructors', () => {
// Setup a directive that requires an inline type constructor, as it has a generic type
// parameter that refer an interface that has not been exported. The inline operation
// causes an updated dir.ts to be used in the type-check program, which should not
// confuse the incremental engine in undesirably considering dir.ts as affected in
// incremental rebuilds.
env.write(
'dir.ts',
`
import {Directive, Input} from '@angular/core';
interface Keys {
alpha: string;
beta: string;
}
@Directive({
selector: '[dir]',
standalone: false,
})
export class Dir<T extends keyof Keys> {
@Input() dir: T;
}
`,
);
env.write(
'cmp.ts',
`
import {Component, NgModule} from '@angular/core';
import {Dir} from './dir';
@Component({
selector: 'test-cmp',
template: '<div dir="alpha"></div>',
standalone: false,
})
export class Cmp {}
@NgModule({
declarations: [Cmp, Dir],
})
export class Module {}
`,
);
env.driveMain();
// Trigger a recompile by changing cmp.ts.
env.invalidateCachedFile('cmp.ts');
env.flushWrittenFileTracking();
env.driveMain();
// Verify that only cmp.ts was emitted, but not dir.ts as it was not affected.
const written = env.getFilesWrittenSinceLastFlush();
expect(written).toContain('/cmp.js');
expect(written).not.toContain('/dir.js');
});
});
});
describe('missing resource files', () => {
it('should re-analyze a component if a template file becomes available later', () => {
env.write(
'app.ts',
`
import {Component} from '@angular/core';
@Component({
selector: 'app',
templateUrl: './some-template.html',
})
export class AppComponent {}
`,
);
const firstDiagnostics = env.driveDiagnostics();
expect(firstDiagnostics.length).toBe(1);
expect(firstDiagnostics[0].code).toBe(ngErrorCode(ErrorCode.COMPONENT_RESOURCE_NOT_FOUND));
env.write(
'some-template.html',
`
<span>Test</span>
`,
);
env.driveMain();
});
it('should re-analyze if component style file becomes available later', () => {
env.write(
'app.ts',
`
import {Component} from '@angular/core';
@Component({
selector: 'app',
template: 'Works',
styleUrls: ['./some-style.css'],
})
export class AppComponent {}
`,
);
const firstDiagnostics = env.driveDiagnostics();
expect(firstDiagnostics.length).toBe(1);
expect(firstDiagnostics[0].code).toBe(ngErrorCode(ErrorCode.COMPONENT_RESOURCE_NOT_FOUND));
env.write('some-style.css', `body {}`);
env.driveMain();
});
});
}); | {
"end_byte": 40155,
"start_byte": 32633,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/incremental_spec.ts_40159_42331 | function setupFooBarProgram(env: NgtscTestEnvironment) {
env.write(
'foo_component.ts',
`
import {Component} from '@angular/core';
import {fooSelector} from './foo_selector';
@Component({
selector: fooSelector,
template: '{{ 1 | foo }}',
standalone: false,
})
export class FooCmp {}
`,
);
env.write(
'foo_pipe.ts',
`
import {Pipe} from '@angular/core';
@Pipe({
name: 'foo',
standalone: false,
})
export class FooPipe {
transform() {}
}
`,
);
env.write(
'foo_module.ts',
`
import {NgModule} from '@angular/core';
import {FooCmp} from './foo_component';
import {FooPipe} from './foo_pipe';
import {BarModule} from './bar_module';
@NgModule({
declarations: [FooCmp, FooPipe],
imports: [BarModule],
})
export class FooModule {}
`,
);
env.write(
'bar_component.ts',
`
import {Component} from '@angular/core';
@Component({
selector: 'bar',
templateUrl: './bar_component.html',
standalone: false,
})
export class BarCmp {}
`,
);
env.write('bar_component.html', '<div bar></div>');
env.write(
'bar_directive.ts',
`
import {Directive} from '@angular/core';
@Directive({
selector: '[bar]',
standalone: false,
})
export class BarDir {}
`,
);
env.write(
'bar_pipe.ts',
`
import {Pipe} from '@angular/core';
@Pipe({
name: 'foo',
standalone: false,
})
export class BarPipe {
transform() {}
}
`,
);
env.write(
'bar_module.ts',
`
import {NgModule} from '@angular/core';
import {BarCmp} from './bar_component';
import {BarDir} from './bar_directive';
import {BarPipe} from './bar_pipe';
@NgModule({
declarations: [BarCmp, BarDir, BarPipe],
exports: [BarCmp, BarPipe],
})
export class BarModule {}
`,
);
env.write(
'foo_selector.d.ts',
`
export const fooSelector = 'foo';
`,
);
env.driveMain();
env.flushWrittenFileTracking();
}
}); | {
"end_byte": 42331,
"start_byte": 40159,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/incremental_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/scope_spec.ts_0_8388 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {ErrorCode, ngErrorCode} from '../../src/ngtsc/diagnostics';
import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing';
import {diagnosticToNode, loadStandardTestFiles} from '../../src/ngtsc/testing';
import {NgtscTestEnvironment} from './env';
const testFiles = loadStandardTestFiles();
runInEachFileSystem(() => {
describe('ngtsc module scopes', () => {
let env!: NgtscTestEnvironment;
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
});
describe('diagnostics', () => {
describe('declarations', () => {
it('should detect when a random class is declared', () => {
env.write(
'test.ts',
`
import {NgModule} from '@angular/core';
export class RandomClass {}
@NgModule({
declarations: [RandomClass],
})
export class Module {}
`,
);
const diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
const node = diagnosticToNode(diags[0], ts.isIdentifier);
expect(node.text).toEqual('RandomClass');
expect(diags[0].messageText).toContain('is not a directive, a component, or a pipe.');
});
it('should detect when a declaration lives outside the current compilation', () => {
env.write(
'dir.d.ts',
`
import {ɵɵDirectiveDeclaration} from '@angular/core';
export declare class ExternalDir {
static ɵdir: ɵɵDirectiveDeclaration<ExternalDir, '[test]', never, never, never, never>;
}
`,
);
env.write(
'test.ts',
`
import {NgModule} from '@angular/core';
import {ExternalDir} from './dir';
@NgModule({
declarations: [ExternalDir],
})
export class Module {}
`,
);
const diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
const node = diagnosticToNode(diags[0], ts.isIdentifier);
expect(node.text).toEqual('ExternalDir');
expect(diags[0].messageText).toContain(`not a part of the current compilation`);
});
it('should detect when a declaration is shared between two modules', () => {
env.write(
'test.ts',
`
import {Directive, NgModule} from '@angular/core';
@Directive({
selector: '[test]',
standalone: false,
})
export class TestDir {}
@NgModule({
declarations: [TestDir]
})
export class ModuleA {}
@NgModule({
declarations: [TestDir],
})
export class ModuleB {}
`,
);
const diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
const node = findContainingClass(diagnosticToNode(diags[0], ts.isIdentifier));
expect(node.name!.text).toEqual('TestDir');
const relatedNodes = new Set(
diags[0].relatedInformation!.map(
(related) =>
findContainingClass(diagnosticToNode(related, ts.isIdentifier)).name!.text,
),
);
expect(relatedNodes).toContain('ModuleA');
expect(relatedNodes).toContain('ModuleB');
expect(relatedNodes.size).toBe(2);
});
it('should detect when a declaration is repeated within the same module', () => {
env.write(
'test.ts',
`
import {Directive, NgModule} from '@angular/core';
@Directive({
selector: '[test]',
standalone: false,
})
export class TestDir {}
@NgModule({
declarations: [TestDir, TestDir],
})
export class Module {}
`,
);
const diags = env.driveDiagnostics();
expect(diags.length).toBe(0);
});
it('should detect when a declaration is shared between two modules, and is repeated within them', () => {
env.write(
'test.ts',
`
import {Directive, NgModule} from '@angular/core';
@Directive({
selector: '[test]',
standalone: false,
})
export class TestDir {}
@NgModule({
declarations: [TestDir, TestDir]
})
export class ModuleA {}
@NgModule({
declarations: [TestDir, TestDir],
})
export class ModuleB {}
`,
);
const diags = env.driveDiagnostics();
expect(diags.length).toBe(1);
const node = findContainingClass(diagnosticToNode(diags[0], ts.isIdentifier));
expect(node.name!.text).toEqual('TestDir');
const relatedNodes = new Set(
diags[0].relatedInformation!.map(
(related) =>
findContainingClass(diagnosticToNode(related, ts.isIdentifier)).name!.text,
),
);
expect(relatedNodes).toContain('ModuleA');
expect(relatedNodes).toContain('ModuleB');
expect(relatedNodes.size).toBe(2);
});
});
describe('imports', () => {
it('should emit imports in a pure function call', () => {
env.write(
'test.ts',
`
import {NgModule} from '@angular/core';
@NgModule({})
export class OtherModule {}
@NgModule({imports: [OtherModule]})
export class TestModule {}
`,
);
env.driveMain();
const jsContents = env.getContents('test.js');
expect(jsContents).toContain('i0.ɵɵdefineNgModule({ type: TestModule });');
expect(jsContents).toContain(
'function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵɵsetNgModuleScope(TestModule, { imports: [OtherModule] }); })();',
);
const dtsContents = env.getContents('test.d.ts');
expect(dtsContents).toContain(
'static ɵmod: i0.ɵɵNgModuleDeclaration<TestModule, never, [typeof OtherModule], never>',
);
});
it('should produce an error when an invalid class is imported', () => {
env.write(
'test.ts',
`
import {NgModule} from '@angular/core';
class NotAModule {}
@NgModule({imports: [NotAModule]})
class IsAModule {}
`,
);
const [error] = env.driveDiagnostics();
expect(error).not.toBeUndefined();
expect(error.code).toEqual(ngErrorCode(ErrorCode.NGMODULE_INVALID_IMPORT));
expect(diagnosticToNode(error, ts.isIdentifier).parent.parent.getText()).toEqual(
'imports: [NotAModule]',
);
});
it('should produce an error when a non-class is imported from a .d.ts dependency', () => {
env.write('dep.d.ts', `export declare let NotAClass: Function;`);
env.write(
'test.ts',
`
import {NgModule} from '@angular/core';
import {NotAClass} from './dep';
// @ts-ignore
@NgModule({imports: [NotAClass]})
class IsAModule {}
`,
);
const [error] = env.driveDiagnostics();
expect(error).not.toBeUndefined();
const messageText = ts.flattenDiagnosticMessageText(error.messageText, '\n');
expect(messageText).toContain(
'Value at position 0 in the NgModule.imports of IsAModule is not a class',
);
expect(messageText).toContain("Value is a reference to 'NotAClass'.");
expect(error.code).toEqual(ngErrorCode(ErrorCode.VALUE_HAS_WRONG_TYPE));
expect(diagnosticToNode(error, ts.isIdentifier).text).toEqual('NotAClass');
});
});
desc | {
"end_byte": 8388,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/scope_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/scope_spec.ts_8396_15122 | ports', () => {
it('should emit exports in a pure function call', () => {
env.write(
'test.ts',
`
import {NgModule} from '@angular/core';
@NgModule({})
export class OtherModule {}
@NgModule({exports: [OtherModule]})
export class TestModule {}
`,
);
env.driveMain();
const jsContents = env.getContents('test.js');
expect(jsContents).toContain('i0.ɵɵdefineNgModule({ type: TestModule });');
expect(jsContents).toContain(
'(function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵɵsetNgModuleScope(TestModule, { exports: [OtherModule] }); })();',
);
const dtsContents = env.getContents('test.d.ts');
expect(dtsContents).toContain(
'static ɵmod: i0.ɵɵNgModuleDeclaration<TestModule, never, never, [typeof OtherModule]>',
);
});
it('should produce an error when a non-NgModule class is exported', () => {
env.write(
'test.ts',
`
import {NgModule} from '@angular/core';
class NotAModule {}
@NgModule({exports: [NotAModule]})
class IsAModule {}
`,
);
const [error] = env.driveDiagnostics();
expect(error).not.toBeUndefined();
expect(error.code).toEqual(ngErrorCode(ErrorCode.NGMODULE_INVALID_EXPORT));
expect(diagnosticToNode(error, ts.isIdentifier).parent.parent.getText()).toEqual(
'exports: [NotAModule]',
);
});
it('should produce a transitive error when an invalid NgModule is exported', () => {
env.write(
'test.ts',
`
import {NgModule} from '@angular/core';
export class NotAModule {}
@NgModule({
imports: [NotAModule],
})
class InvalidModule {}
@NgModule({exports: [InvalidModule]})
class IsAModule {}
`,
);
// Find the diagnostic referencing InvalidModule, which should have come from IsAModule.
const error = env
.driveDiagnostics()
.find((error) => diagnosticToNode(error, ts.isIdentifier).text === 'InvalidModule');
if (error === undefined) {
return fail('Expected to find a diagnostic referencing InvalidModule');
}
expect(error.code).toEqual(ngErrorCode(ErrorCode.NGMODULE_INVALID_EXPORT));
expect(diagnosticToNode(error, ts.isIdentifier).parent.parent.getText()).toEqual(
'exports: [InvalidModule]',
);
});
});
describe('re-exports', () => {
it('should produce an error when a non-declared/imported class is re-exported', () => {
env.write(
'test.ts',
`
import {Directive, NgModule} from '@angular/core';
@Directive({selector: 'test'})
class Dir {}
@NgModule({exports: [Dir]})
class IsAModule {}
`,
);
const [error] = env.driveDiagnostics();
expect(error).not.toBeUndefined();
expect(error.code).toEqual(ngErrorCode(ErrorCode.NGMODULE_INVALID_REEXPORT));
expect(diagnosticToNode(error, ts.isIdentifier).parent.parent.getText()).toEqual(
'exports: [Dir]',
);
});
});
it('should not produce component template type-check errors if its module is invalid', () => {
env.tsconfig({'fullTemplateTypeCheck': true});
// Set up 3 files, each of which declare an NgModule that's invalid in some way. This will
// produce a bunch of diagnostics related to the issues with the modules. Each module also
// declares a component with a template that references a <doesnt-exist> element. This test
// verifies that none of the produced diagnostics mention this nonexistent element, since
// no template type-checking should be performed for a component that's part of an invalid
// NgModule.
// This NgModule declares something which isn't a directive/pipe.
env.write(
'invalid-declaration.ts',
`
import {Component, NgModule} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<doesnt-exist></doesnt-exist>',
})
export class TestCmp {}
export class NotACmp {}
@NgModule({declarations: [TestCmp, NotACmp]})
export class Module {}
`,
);
// This NgModule imports something which isn't an NgModule.
env.write(
'invalid-import.ts',
`
import {Component, NgModule} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<doesnt-exist></doesnt-exist>',
})
export class TestCmp {}
export class NotAModule {}
@NgModule({
declarations: [TestCmp],
imports: [NotAModule],
})
export class Module {}
`,
);
// This NgModule imports a DepModule which itself is invalid (it declares something which
// isn't a directive/pipe).
env.write(
'transitive-error-in-import.ts',
`
import {Component, NgModule} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<doesnt-exist></doesnt-exist>',
})
export class TestCmp {}
export class NotACmp {}
@NgModule({
declarations: [NotACmp],
exports: [NotACmp],
})
export class DepModule {}
@NgModule({
declarations: [TestCmp],
imports: [DepModule],
})
export class Module {}
`,
);
for (const diag of env.driveDiagnostics()) {
// None of the diagnostics should be related to the fact that the component uses an
// unknown element, because in all cases the component's scope was invalid.
expect(diag.messageText).not.toContain(
'doesnt-exist',
"Template type-checking ran for a component, when it shouldn't have.",
);
}
});
});
});
});
function findContainingClass(node: ts.Node): ts.ClassDeclaration {
while (!ts.isClassDeclaration(node)) {
if (node.parent && node.parent !== node) {
node = node.parent;
} else {
throw new Error('Expected node to have a ClassDeclaration parent');
}
}
return node;
}
| {
"end_byte": 15122,
"start_byte": 8396,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/scope_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/docs_private_spec.ts_0_1898 | /**
* @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 {DocEntry} from '@angular/compiler-cli/src/ngtsc/docs/src/entities';
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {NgtscTestEnvironment} from '../env';
runInEachFileSystem(() => {
describe('ngtsc docs: @docsPrivate tag', () => {
let env: NgtscTestEnvironment;
beforeEach(() => {
env = NgtscTestEnvironment.setup({});
env.tsconfig();
});
function test(input: string): DocEntry[] {
env.write('index.ts', input);
return env.driveDocsExtraction('index.ts');
}
it('should omit constant annotated with `@docsPrivate`', () => {
expect(
test(`
/** @docsPrivate <reason> */
export const bla = true;
`),
).toEqual([]);
});
it('should omit class annotated with `@docsPrivate`', () => {
expect(
test(`
/** @docsPrivate <reason> */
export class Bla {}
`),
).toEqual([]);
});
it('should omit function annotated with `@docsPrivate`', () => {
expect(
test(`
/** @docsPrivate <reason> */
export function bla() {};
`),
).toEqual([]);
});
it('should omit interface annotated with `@docsPrivate`', () => {
expect(
test(`
/** @docsPrivate <reason> */
export interface BlaFunction {}
`),
).toEqual([]);
});
it('should error if marked as private without reasoning', () => {
expect(() =>
test(`
/** @docsPrivate */
export interface BlaFunction {}
`),
).toThrowError(/Entry "BlaFunction" is marked as "@docsPrivate" but without reasoning./);
});
});
});
| {
"end_byte": 1898,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/docs_private_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/ng_module_doc_extraction_spec.ts_0_1486 | /**
* @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 {DocEntry} from '@angular/compiler-cli/src/ngtsc/docs';
import {ClassEntry, EntryType} from '@angular/compiler-cli/src/ngtsc/docs/src/entities';
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import {NgtscTestEnvironment} from '../env';
const testFiles = loadStandardTestFiles({fakeCommon: true});
runInEachFileSystem(() => {
let env!: NgtscTestEnvironment;
describe('ngtsc NgModule docs extraction', () => {
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
});
it('should extract NgModule info', () => {
env.write(
'index.ts',
`
import {Directive, NgModule} from '@angular/core';
@Directive({selector: 'some-tag'})
export class SomeDirective { }
@NgModule({declarations: [SomeDirective]})
export class SomeNgModule { }
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(2);
expect(docs[1].entryType).toBe(EntryType.NgModule);
const ngModuleEntry = docs[1] as ClassEntry;
expect(ngModuleEntry.name).toBe('SomeNgModule');
});
});
});
| {
"end_byte": 1486,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/ng_module_doc_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/reexport_docs_extraction_spec.ts_0_3157 | /**
* @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 {DocEntry} from '@angular/compiler-cli/src/ngtsc/docs';
import {EntryType} from '@angular/compiler-cli/src/ngtsc/docs/src/entities';
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import {NgtscTestEnvironment} from '../env';
const testFiles = loadStandardTestFiles({fakeCommon: true});
runInEachFileSystem(() => {
let env!: NgtscTestEnvironment;
describe('ngtsc re-export docs extraction', () => {
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
});
it('should extract info from a named re-export', () => {
env.write(
'index.ts',
`
export {PI} from './implementation';
`,
);
env.write(
'implementation.ts',
`
export const PI = 3.14;
export const TAO = 6.28;
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].entryType).toBe(EntryType.Constant);
expect(docs[0].name).toBe('PI');
});
it('should extract info from an aggregate re-export', () => {
env.write(
'index.ts',
`
export * from './implementation';
`,
);
env.write(
'implementation.ts',
`
export const PI = 3.14;
export const TAO = 6.28;
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(2);
const [piEntry, taoEntry] = docs;
expect(piEntry.entryType).toBe(EntryType.Constant);
expect(piEntry.name).toBe('PI');
expect(taoEntry.entryType).toBe(EntryType.Constant);
expect(taoEntry.name).toBe('TAO');
});
it('should extract info from a transitive re-export', () => {
env.write(
'index.ts',
`
export * from './middle';
`,
);
env.write(
'middle.ts',
`
export * from 'implementation';
`,
);
env.write(
'implementation.ts',
`
export const PI = 3.14;
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].entryType).toBe(EntryType.Constant);
expect(docs[0].name).toBe('PI');
});
it('should extract info from an aliased re-export', () => {
env.write(
'index.ts',
`
export * from './implementation';
`,
);
env.write(
'implementation.ts',
`
const PI = 3.14;
export {PI as PI_CONSTANT};
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].entryType).toBe(EntryType.Constant);
expect(docs[0].name).toBe('PI_CONSTANT');
});
});
});
| {
"end_byte": 3157,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/reexport_docs_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/class_doc_extraction_spec.ts_0_698 | /**
* @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 {DocEntry} from '@angular/compiler-cli/src/ngtsc/docs';
import {
ClassEntry,
EntryType,
MemberTags,
MemberType,
MethodEntry,
PropertyEntry,
} from '@angular/compiler-cli/src/ngtsc/docs/src/entities';
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import {NgtscTestEnvironment} from '../env';
const testFiles = loadStandardTestFiles({fakeCommon: true}); | {
"end_byte": 698,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/class_doc_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/class_doc_extraction_spec.ts_700_9632 | runInEachFileSystem(() => {
let env!: NgtscTestEnvironment;
describe('ngtsc class docs extraction', () => {
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
});
it('should extract classes', () => {
env.write(
'index.ts',
`
export class UserProfile {}
export class CustomSlider {}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(2);
const [userProfileEntry, customSliderEntry] = docs as ClassEntry[];
expect(userProfileEntry.name).toBe('UserProfile');
expect(userProfileEntry.isAbstract).toBe(false);
expect(userProfileEntry.entryType).toBe(EntryType.UndecoratedClass);
expect(customSliderEntry.name).toBe('CustomSlider');
expect(customSliderEntry.isAbstract).toBe(false);
expect(customSliderEntry.entryType).toBe(EntryType.UndecoratedClass);
});
it('should extract class members', () => {
env.write(
'index.ts',
`
export class UserProfile {
firstName(): string { return 'Morgan'; }
age: number = 25;
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const classEntry = docs[0] as ClassEntry;
expect(classEntry.members.length).toBe(2);
const methodEntry = classEntry.members[0] as MethodEntry;
expect(methodEntry.memberType).toBe(MemberType.Method);
expect(methodEntry.name).toBe('firstName');
expect(methodEntry.implementation.returnType).toBe('string');
expect(methodEntry.signatures[0].returnType).toBe('string');
const propertyEntry = classEntry.members[1] as PropertyEntry;
expect(propertyEntry.memberType).toBe(MemberType.Property);
expect(propertyEntry.name).toBe('age');
expect(propertyEntry.type).toBe('number');
});
it('should extract methods with overloads', () => {
env.write(
'index.ts',
`
export class UserProfile {
ident(value: boolean): boolean
ident(value: number): number
ident(value: number|boolean|string): number|boolean {
return 0;
}
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const classEntry = docs[0] as ClassEntry;
expect(classEntry.members.length).toBe(1);
const [booleanOverloadEntry, numberOverloadEntry] = (classEntry.members[0] as MethodEntry)
.signatures;
expect(booleanOverloadEntry.name).toBe('ident');
expect(booleanOverloadEntry.params.length).toBe(1);
expect(booleanOverloadEntry.params[0].type).toBe('boolean');
expect(booleanOverloadEntry.returnType).toBe('boolean');
expect(numberOverloadEntry.name).toBe('ident');
expect(numberOverloadEntry.params.length).toBe(1);
expect(numberOverloadEntry.params[0].type).toBe('number');
expect(numberOverloadEntry.returnType).toBe('number');
});
it('should not extract Angular-internal members', () => {
env.write(
'index.ts',
`
export class UserProfile {
ɵfirstName(): string { return 'Morgan'; }
_age: number = 25;
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const classEntry = docs[0] as ClassEntry;
expect(classEntry.members.length).toBe(0);
});
it('should extract a method with a rest parameter', () => {
env.write(
'index.ts',
`
export class UserProfile {
getNames(prefix: string, ...ids: string[]): string[] {
return [];
}
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const classEntry = docs[0] as ClassEntry;
const methodEntry = classEntry.members[0] as MethodEntry;
const [prefixParamEntry, idsParamEntry] = methodEntry.implementation.params;
expect(prefixParamEntry.name).toBe('prefix');
expect(prefixParamEntry.type).toBe('string');
expect(prefixParamEntry.isRestParam).toBe(false);
expect(idsParamEntry.name).toBe('ids');
expect(idsParamEntry.type).toBe('string[]');
expect(idsParamEntry.isRestParam).toBe(true);
});
it('should extract class method params', () => {
env.write(
'index.ts',
`
export class UserProfile {
setPhone(num: string, intl: number = 1, area?: string): void {}
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const classEntry = docs[0] as ClassEntry;
expect(classEntry.members.length).toBe(1);
const methodEntry = classEntry.members[0] as MethodEntry;
expect(methodEntry.memberType).toBe(MemberType.Method);
expect(methodEntry.name).toBe('setPhone');
expect(methodEntry.implementation.params.length).toBe(3);
const [numParam, intlParam, areaParam] = methodEntry.implementation.params;
expect(numParam.name).toBe('num');
expect(numParam.isOptional).toBe(false);
expect(numParam.type).toBe('string');
expect(intlParam.name).toBe('intl');
expect(intlParam.isOptional).toBe(true);
expect(intlParam.type).toBe('number');
expect(areaParam.name).toBe('area');
expect(areaParam.isOptional).toBe(true);
expect(areaParam.type).toBe('string | undefined');
});
it('should not extract private class members', () => {
env.write(
'index.ts',
`
export class UserProfile {
private ssn: string;
private getSsn(): string { return ''; }
private static printSsn(): void { }
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const classEntry = docs[0] as ClassEntry;
expect(classEntry.members.length).toBe(0);
});
it('should extract member tags', () => {
// Test both properties and methods with zero, one, and multiple tags.
env.write(
'index.ts',
`
export class UserProfile {
eyeColor = 'brown';
protected name: string;
readonly age = 25;
address?: string;
static country = 'USA';
protected readonly birthday = '1/1/2000';
getEyeColor(): string { return 'brown'; }
protected getName(): string { return 'Morgan'; }
getAge?(): number { return 25; }
static getCountry(): string { return 'USA'; }
protected getBirthday?(): string { return '1/1/2000'; }
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const classEntry = docs[0] as ClassEntry;
expect(classEntry.members.length).toBe(11);
const [
eyeColorMember,
nameMember,
ageMember,
addressMember,
birthdayMember,
getEyeColorMember,
getNameMember,
getAgeMember,
getBirthdayMember,
countryMember,
getCountryMember,
] = classEntry.members;
// Properties
expect(eyeColorMember.memberTags.length).toBe(0);
expect(nameMember.memberTags).toEqual([MemberTags.Protected]);
expect(ageMember.memberTags).toEqual([MemberTags.Readonly]);
expect(addressMember.memberTags).toEqual([MemberTags.Optional]);
expect(countryMember.memberTags).toEqual([MemberTags.Static]);
expect(birthdayMember.memberTags).toContain(MemberTags.Protected);
expect(birthdayMember.memberTags).toContain(MemberTags.Readonly);
// Methods
expect(getEyeColorMember.memberTags.length).toBe(0);
expect(getNameMember.memberTags).toEqual([MemberTags.Protected]);
expect(getAgeMember.memberTags).toEqual([MemberTags.Optional]);
expect(getCountryMember.memberTags).toEqual([MemberTags.Static]);
expect(getBirthdayMember.memberTags).toContain(MemberTags.Protected);
expect(getBirthdayMember.memberTags).toContain(MemberTags.Optional);
});
it('should extract member tags', () => {
// Test both properties and methods with zero, one, and multiple tags.
env.write(
'index.ts',
`
export class UserProfile {
eyeColor = 'brown';
/** @internal */
uuid: string;
// @internal
foreignId: string;
/** @internal */
_doSomething() {}
// @internal
_doSomethingElse() {}
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const classEntry = docs[0] as ClassEntry;
expect(classEntry.members.length).toBe(1);
const [eyeColorMember] = classEntry.members;
// Properties
expect(eyeColorMember.memberTags.length).toBe(0);
});
| {
"end_byte": 9632,
"start_byte": 700,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/class_doc_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/class_doc_extraction_spec.ts_9638_17014 | t('should extract getters and setters', () => {
// Test getter-only, a getter + setter, and setter-only.
env.write(
'index.ts',
`
export class UserProfile {
get userId(): number { return 123; }
get userName(): string { return 'Morgan'; }
set userName(value: string) { }
set isAdmin(value: boolean) { }
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const classEntry = docs[0] as ClassEntry;
expect(classEntry.entryType).toBe(EntryType.UndecoratedClass);
expect(classEntry.members.length).toBe(4);
const [userIdGetter, userNameGetter, userNameSetter, isAdminSetter] = classEntry.members;
expect(userIdGetter.name).toBe('userId');
expect(userIdGetter.memberType).toBe(MemberType.Getter);
expect(userNameGetter.name).toBe('userName');
expect(userNameGetter.memberType).toBe(MemberType.Getter);
expect(userNameSetter.name).toBe('userName');
expect(userNameSetter.memberType).toBe(MemberType.Setter);
expect(isAdminSetter.name).toBe('isAdmin');
expect(isAdminSetter.memberType).toBe(MemberType.Setter);
});
it('should extract abstract classes', () => {
env.write(
'index.ts',
`
export abstract class UserProfile {
firstName: string;
abstract lastName: string;
save(): void { }
abstract reset(): void;
}`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const classEntry = docs[0] as ClassEntry;
expect(classEntry.isAbstract).toBe(true);
expect(classEntry.members.length).toBe(4);
const [firstNameEntry, latsNameEntry, saveEntry, resetEntry] = classEntry.members;
expect(firstNameEntry.name).toBe('firstName');
expect(firstNameEntry.memberTags).not.toContain(MemberTags.Abstract);
expect(latsNameEntry.name).toBe('lastName');
expect(latsNameEntry.memberTags).toContain(MemberTags.Abstract);
expect(saveEntry.name).toBe('save');
expect(saveEntry.memberTags).not.toContain(MemberTags.Abstract);
expect(resetEntry.name).toBe('reset');
expect(resetEntry.memberTags).toContain(MemberTags.Abstract);
});
it('should extract only once, when discovering abstract methods with overloads ', () => {
env.write(
'index.ts',
`
export abstract class UserProfile {
firstName: string;
abstract get(key: string): string;
abstract get(key: string|undefined): string|undefined;
abstract get(key: undefined): undefined;
save(): void { }
abstract reset(): void;
}`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const classEntry = docs[0] as ClassEntry;
expect(classEntry.isAbstract).toBe(true);
expect(classEntry.members.length).toBe(4);
const [firstNameEntry, getEntry, saveEntry, resetEntry] = classEntry.members;
expect(firstNameEntry.name).toBe('firstName');
expect(firstNameEntry.memberTags).not.toContain(MemberTags.Abstract);
expect(getEntry.name).toBe('get');
expect(getEntry.memberTags).toContain(MemberTags.Abstract);
expect(saveEntry.name).toBe('save');
expect(saveEntry.memberTags).not.toContain(MemberTags.Abstract);
expect(resetEntry.name).toBe('reset');
expect(resetEntry.memberTags).toContain(MemberTags.Abstract);
});
it('should extract class generic parameters', () => {
env.write(
'index.ts',
`
export class UserProfile<T> {
constructor(public name: T) { }
}
export class TwinProfile<U, V> {
constructor(public name: U, age: V) { }
}
export class AdminProfile<X extends String> {
constructor(public name: X) { }
}
export class BotProfile<Q = string> {
constructor(public name: Q) { }
}
export class ExecProfile<W extends String = string> {
constructor(public name: W) { }
}`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(5);
const [
userProfileEntry,
twinProfileEntry,
adminProfileEntry,
botProfileEntry,
execProfileEntry,
] = docs as ClassEntry[];
expect(userProfileEntry.generics.length).toBe(1);
expect(twinProfileEntry.generics.length).toBe(2);
expect(adminProfileEntry.generics.length).toBe(1);
expect(botProfileEntry.generics.length).toBe(1);
expect(execProfileEntry.generics.length).toBe(1);
const [userProfileGenericEntry] = userProfileEntry.generics;
expect(userProfileGenericEntry.name).toBe('T');
expect(userProfileGenericEntry.constraint).toBeUndefined();
expect(userProfileGenericEntry.default).toBeUndefined();
const [nameGenericEntry, ageGenericEntry] = twinProfileEntry.generics;
expect(nameGenericEntry.name).toBe('U');
expect(nameGenericEntry.constraint).toBeUndefined();
expect(nameGenericEntry.default).toBeUndefined();
expect(ageGenericEntry.name).toBe('V');
expect(ageGenericEntry.constraint).toBeUndefined();
expect(ageGenericEntry.default).toBeUndefined();
const [adminProfileGenericEntry] = adminProfileEntry.generics;
expect(adminProfileGenericEntry.name).toBe('X');
expect(adminProfileGenericEntry.constraint).toBe('String');
expect(adminProfileGenericEntry.default).toBeUndefined();
const [botProfileGenericEntry] = botProfileEntry.generics;
expect(botProfileGenericEntry.name).toBe('Q');
expect(botProfileGenericEntry.constraint).toBeUndefined();
expect(botProfileGenericEntry.default).toBe('string');
const [execProfileGenericEntry] = execProfileEntry.generics;
expect(execProfileGenericEntry.name).toBe('W');
expect(execProfileGenericEntry.constraint).toBe('String');
expect(execProfileGenericEntry.default).toBe('string');
});
it('should extract method generic parameters', () => {
env.write(
'index.ts',
`
export class UserProfile {
save<T>(data: T): void { }
}`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const classEntry = docs[0] as ClassEntry;
const [genericEntry] = (classEntry.members[0] as MethodEntry).implementation.generics;
expect(genericEntry.name).toBe('T');
expect(genericEntry.constraint).toBeUndefined();
expect(genericEntry.default).toBeUndefined();
});
it('should extract inheritence/interface conformance', () => {
env.write(
'index.ts',
`
interface Foo {}
interface Bar {}
class Parent extends Ancestor {}
export class Child extends Parent implements Foo, Bar {}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const classEntry = docs[0] as ClassEntry;
expect(classEntry.extends).toBe('Parent');
expect(classEntry.implements).toEqual(['Foo', 'Bar']);
});
| {
"end_byte": 17014,
"start_byte": 9638,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/class_doc_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/class_doc_extraction_spec.ts_17020_22108 | t('should extract inherited members', () => {
env.write(
'index.ts',
`
class Ancestor {
id: string;
value: string|number;
save(value: string|number): string|number { return 0; }
}
class Parent extends Ancestor {
name: string;
}
export class Child extends Parent {
age: number;
value: number;
save(value: number): number;
save(value: string|number): string|number { return 0; }
}`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const classEntry = docs[0] as ClassEntry;
expect(classEntry.members.length).toBe(5);
const [ageEntry, valueEntry, childSaveEntry, nameEntry, idEntry] = classEntry.members;
expect(ageEntry.name).toBe('age');
expect(ageEntry.memberType).toBe(MemberType.Property);
expect((ageEntry as PropertyEntry).type).toBe('number');
expect(ageEntry.memberTags).not.toContain(MemberTags.Inherited);
expect(valueEntry.name).toBe('value');
expect(valueEntry.memberType).toBe(MemberType.Property);
expect((valueEntry as PropertyEntry).type).toBe('number');
expect(valueEntry.memberTags).not.toContain(MemberTags.Inherited);
expect(childSaveEntry.name).toBe('save');
expect(childSaveEntry.memberType).toBe(MemberType.Method);
expect((childSaveEntry as MethodEntry).implementation.returnType).toBe('string | number');
expect(childSaveEntry.memberTags).not.toContain(MemberTags.Inherited);
expect(nameEntry.name).toBe('name');
expect(nameEntry.memberType).toBe(MemberType.Property);
expect((nameEntry as PropertyEntry).type).toBe('string');
expect(nameEntry.memberTags).toContain(MemberTags.Inherited);
expect(idEntry.name).toBe('id');
expect(idEntry.memberType).toBe(MemberType.Property);
expect((idEntry as PropertyEntry).type).toBe('string');
expect(idEntry.memberTags).toContain(MemberTags.Inherited);
});
it('should extract inherited getters/setters', () => {
env.write(
'index.ts',
`
class Ancestor {
get name(): string { return ''; }
set name(v: string) { }
get id(): string { return ''; }
set id(v: string) { }
get age(): number { return 0; }
set age(v: number) { }
}
class Parent extends Ancestor {
name: string;
}
export class Child extends Parent {
get id(): string { return ''; }
}`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const classEntry = docs[0] as ClassEntry;
expect(classEntry.members.length).toBe(4);
const [idEntry, nameEntry, ageGetterEntry, ageSetterEntry] =
classEntry.members as PropertyEntry[];
// When the child class overrides an accessor pair with another accessor, it overrides
// *both* the getter and the setter, resulting (in this case) in just a getter.
expect(idEntry.name).toBe('id');
expect(idEntry.memberType).toBe(MemberType.Getter);
expect((idEntry as PropertyEntry).type).toBe('string');
expect(idEntry.memberTags).not.toContain(MemberTags.Inherited);
// When the child class overrides an accessor with a property, the property takes precedence.
expect(nameEntry.name).toBe('name');
expect(nameEntry.memberType).toBe(MemberType.Property);
expect(nameEntry.type).toBe('string');
expect(nameEntry.memberTags).toContain(MemberTags.Inherited);
expect(ageGetterEntry.name).toBe('age');
expect(ageGetterEntry.memberType).toBe(MemberType.Getter);
expect(ageGetterEntry.type).toBe('number');
expect(ageGetterEntry.memberTags).toContain(MemberTags.Inherited);
expect(ageSetterEntry.name).toBe('age');
expect(ageSetterEntry.memberType).toBe(MemberType.Setter);
expect(ageSetterEntry.type).toBe('number');
expect(ageSetterEntry.memberTags).toContain(MemberTags.Inherited);
});
it('should extract public constructor parameters', () => {
env.write(
'index.ts',
`
export class MyClass {
myProp: string;
constructor(public foo: string, private: bar: string, protected: baz: string) {}
}`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const classEntry = docs[0] as ClassEntry;
expect(classEntry.members.length).toBe(2);
const [myPropEntry, fooEntry] = classEntry.members as PropertyEntry[];
expect(myPropEntry.name).toBe('myProp');
expect(myPropEntry.memberType).toBe(MemberType.Property);
expect((myPropEntry as PropertyEntry).type).toBe('string');
expect(fooEntry.name).toBe('foo');
expect(fooEntry.memberType).toBe(MemberType.Property);
expect((fooEntry as PropertyEntry).type).toBe('string');
});
});
});
| {
"end_byte": 22108,
"start_byte": 17020,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/class_doc_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/import_extractor_spec.ts_0_2996 | /**
* @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 '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import {NgtscTestEnvironment} from '../env';
const testFiles = loadStandardTestFiles({fakeCommon: true});
runInEachFileSystem(() => {
let env!: NgtscTestEnvironment;
describe('ngtsc function docs extraction', () => {
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
});
it('should extract imported symbols from other angular packages', () => {
env.write(
'index.ts',
`
import {ApplicationRef} from '@angular/core';
import {FormGroup} from '@angular/forms';
export function getApp(): ApplicationRef {
}
export function getForm(): FormGroup {
}
`,
);
const symbols = env.driveDocsExtractionForSymbols('index.ts');
expect(symbols.size).toBe(2);
expect(symbols.get('ApplicationRef')).toBe('@angular/core');
expect(symbols.get('FormGroup')).toBe('@angular/forms');
});
it('should not extract imported symbols from non angular packages', () => {
env.write(
'index.ts',
`
import {ApplicationRef} from '@not-angular/core';
import {FormGroup} from '@angular/forms';
export function getApp(): ApplicationRef {
}
export function getForm(): FormGroup {
}
`,
);
const symbols = env.driveDocsExtractionForSymbols('index.ts');
expect(symbols.size).toBe(1);
expect(symbols.get('FormGroup')).toBe('@angular/forms');
});
it('should not extract private symbols', () => {
env.write(
'index.ts',
`
import {ɵSafeHtml} from '@angular/core';
import {FormGroup} from '@angular/forms';
export function getApp(): ApplicationRef {
}
export function getForm(): FormGroup {
}
`,
);
const symbols = env.driveDocsExtractionForSymbols('index.ts');
expect(symbols.size).toBe(1);
expect(symbols.get('FormGroup')).toBe('@angular/forms');
});
it('should not extract symbols from private packages', () => {
env.write(
'index.ts',
`
import {REACTIVE_NODE} from '@core/primitives/signals';
import {FormGroup} from '@angular/forms';
export function getApp(): ApplicationRef {
}
export function getForm(): FormGroup {
}
`,
);
const symbols = env.driveDocsExtractionForSymbols('index.ts');
expect(symbols.size).toBe(1);
expect(symbols.get('FormGroup')).toBe('@angular/forms');
});
});
});
| {
"end_byte": 2996,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/import_extractor_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/directive_doc_extraction_spec.ts_0_687 | /**
* @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 {DocEntry} from '@angular/compiler-cli/src/ngtsc/docs';
import {
ClassEntry,
DirectiveEntry,
EntryType,
MemberTags,
PropertyEntry,
} from '@angular/compiler-cli/src/ngtsc/docs/src/entities';
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import {NgtscTestEnvironment} from '../env';
const testFiles = loadStandardTestFiles({fakeCommon: true}); | {
"end_byte": 687,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/directive_doc_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/directive_doc_extraction_spec.ts_689_9717 | runInEachFileSystem(() => {
let env!: NgtscTestEnvironment;
describe('ngtsc directive docs extraction', () => {
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
});
it('should extract standalone directive info', () => {
env.write(
'index.ts',
`
import {Directive} from '@angular/core';
@Directive({
standalone: true,
selector: 'user-profile',
exportAs: 'userProfile',
})
export class UserProfile { }
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].entryType).toBe(EntryType.Directive);
const directiveEntry = docs[0] as DirectiveEntry;
expect(directiveEntry.isStandalone).toBe(true);
expect(directiveEntry.selector).toBe('user-profile');
expect(directiveEntry.exportAs).toEqual(['userProfile']);
});
it('should extract standalone component info', () => {
env.write(
'index.ts',
`
import {Component} from '@angular/core';
@Component({
standalone: true,
selector: 'user-profile',
exportAs: 'userProfile',
template: '',
})
export class UserProfile { }
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].entryType).toBe(EntryType.Component);
const componentEntry = docs[0] as DirectiveEntry;
expect(componentEntry.isStandalone).toBe(true);
expect(componentEntry.selector).toBe('user-profile');
expect(componentEntry.exportAs).toEqual(['userProfile']);
});
it('should extract NgModule directive info', () => {
env.write(
'index.ts',
`
import {Directive, NgModule} from '@angular/core';
@NgModule({declarations: [UserProfile]})
export class ProfileModule { }
@Directive({
standalone: false,
selector: 'user-profile',
exportAs: 'userProfile',
})
export class UserProfile { }
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(2);
expect(docs[1].entryType).toBe(EntryType.Directive);
const directiveEntry = docs[1] as DirectiveEntry;
expect(directiveEntry.isStandalone).toBe(false);
expect(directiveEntry.selector).toBe('user-profile');
expect(directiveEntry.exportAs).toEqual(['userProfile']);
});
it('should extract NgModule component info', () => {
env.write(
'index.ts',
`
import {Component, NgModule} from '@angular/core';
@NgModule({declarations: [UserProfile]})
export class ProfileModule { }
@Component({
standalone: false,
selector: 'user-profile',
exportAs: 'userProfile',
template: '',
})
export class UserProfile { }
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(2);
expect(docs[1].entryType).toBe(EntryType.Component);
const componentEntry = docs[1] as DirectiveEntry;
expect(componentEntry.isStandalone).toBe(false);
expect(componentEntry.selector).toBe('user-profile');
expect(componentEntry.exportAs).toEqual(['userProfile']);
});
it('should extract input and output info for a directive', () => {
env.write(
'index.ts',
`
import {Directive, EventEmitter, Input, Output} from '@angular/core';
@Directive({
standalone: true,
selector: 'user-profile',
exportAs: 'userProfile',
})
export class UserProfile {
@Input() name: string = '';
@Input('first') firstName = '';
@Input({required: true}) middleName = '';
@Output() saved = new EventEmitter();
@Output('onReset') reset = new EventEmitter();
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].entryType).toBe(EntryType.Directive);
const directiveEntry = docs[0] as DirectiveEntry;
expect(directiveEntry.members.length).toBe(5);
const [nameEntry, firstNameEntry, middleNameEntry, savedEntry, resetEntry] =
directiveEntry.members as PropertyEntry[];
expect(nameEntry.memberTags).toEqual([MemberTags.Input]);
expect(nameEntry.inputAlias).toBe('name');
expect(nameEntry.isRequiredInput).toBe(false);
expect(nameEntry.outputAlias).toBeUndefined();
expect(firstNameEntry.memberTags).toEqual([MemberTags.Input]);
expect(firstNameEntry.inputAlias).toBe('first');
expect(firstNameEntry.isRequiredInput).toBe(false);
expect(firstNameEntry.outputAlias).toBeUndefined();
expect(middleNameEntry.memberTags).toEqual([MemberTags.Input]);
expect(middleNameEntry.inputAlias).toBe('middleName');
expect(middleNameEntry.isRequiredInput).toBe(true);
expect(middleNameEntry.outputAlias).toBeUndefined();
expect(savedEntry.memberTags).toEqual([MemberTags.Output]);
expect(savedEntry.outputAlias).toBe('saved');
expect(savedEntry.isRequiredInput).toBeFalsy();
expect(savedEntry.inputAlias).toBeUndefined();
expect(resetEntry.memberTags).toEqual([MemberTags.Output]);
expect(resetEntry.outputAlias).toBe('onReset');
expect(resetEntry.isRequiredInput).toBeFalsy();
expect(resetEntry.inputAlias).toBeUndefined();
});
it('should extract input and output info for a component', () => {
env.write(
'index.ts',
`
import {Component, EventEmitter, Input, Output} from '@angular/core';
@Component({
standalone: true,
selector: 'user-profile',
exportAs: 'userProfile',
template: '',
})
export class UserProfile {
@Input() name: string = '';
@Input('first') firstName = '';
@Output() saved = new EventEmitter();
@Output('onReset') reset = new EventEmitter();
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].entryType).toBe(EntryType.Component);
const componentEntry = docs[0] as DirectiveEntry;
expect(componentEntry.members.length).toBe(4);
const [nameEntry, firstNameEntry, savedEntry, resetEntry] = componentEntry.members;
expect(nameEntry.memberTags).toEqual([MemberTags.Input]);
expect((nameEntry as PropertyEntry).inputAlias).toBe('name');
expect((nameEntry as PropertyEntry).outputAlias).toBeUndefined();
expect(firstNameEntry.memberTags).toEqual([MemberTags.Input]);
expect((firstNameEntry as PropertyEntry).inputAlias).toBe('first');
expect((firstNameEntry as PropertyEntry).outputAlias).toBeUndefined();
expect(savedEntry.memberTags).toEqual([MemberTags.Output]);
expect((savedEntry as PropertyEntry).outputAlias).toBe('saved');
expect((savedEntry as PropertyEntry).inputAlias).toBeUndefined();
expect(resetEntry.memberTags).toEqual([MemberTags.Output]);
expect((resetEntry as PropertyEntry).outputAlias).toBe('onReset');
expect((resetEntry as PropertyEntry).inputAlias).toBeUndefined();
});
it('should extract getters and setters as inputs', () => {
// Test getter-only, a getter + setter, and setter-only.
env.write(
'index.ts',
`
import {Component, EventEmitter, Input, Output} from '@angular/core';
@Component({
standalone: true,
selector: 'user-profile',
exportAs: 'userProfile',
template: '',
})
export class UserProfile {
@Input()
get userId(): number { return 123; }
@Input()
get userName(): string { return 'Morgan'; }
set userName(value: string) { }
@Input()
set isAdmin(value: boolean) { }
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const classEntry = docs[0] as ClassEntry;
expect(classEntry.entryType).toBe(EntryType.Component);
expect(classEntry.members.length).toBe(4);
const [userIdGetter, userNameGetter, userNameSetter, isAdminSetter] = classEntry.members;
expect(userIdGetter.name).toBe('userId');
expect(userIdGetter.memberTags).toContain(MemberTags.Input);
expect(userNameGetter.name).toBe('userName');
expect(userNameGetter.memberTags).toContain(MemberTags.Input);
expect(userNameSetter.name).toBe('userName');
expect(userNameSetter.memberTags).toContain(MemberTags.Input);
expect(isAdminSetter.name).toBe('isAdmin');
expect(isAdminSetter.memberTags).toContain(MemberTags.Input);
});
});
}); | {
"end_byte": 9717,
"start_byte": 689,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/directive_doc_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/enum_doc_extraction_spec.ts_0_2969 | /**
* @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 {DocEntry} from '@angular/compiler-cli/src/ngtsc/docs';
import {EntryType, EnumEntry} from '@angular/compiler-cli/src/ngtsc/docs/src/entities';
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import {NgtscTestEnvironment} from '../env';
const testFiles = loadStandardTestFiles({fakeCommon: true});
runInEachFileSystem(() => {
let env!: NgtscTestEnvironment;
describe('ngtsc enum docs extraction', () => {
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
});
it('should extract enum info without explicit values', () => {
env.write(
'index.ts',
`
export enum PizzaTopping {
/** It is cheese */
Cheese,
/** Or "tomato" if you are British */
Tomato,
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].entryType).toBe(EntryType.Enum);
const enumEntry = docs[0] as EnumEntry;
expect(enumEntry.name).toBe('PizzaTopping');
expect(enumEntry.members.length).toBe(2);
const [cheeseEntry, tomatoEntry] = enumEntry.members;
expect(cheeseEntry.name).toBe('Cheese');
expect(cheeseEntry.description).toBe('It is cheese');
expect(cheeseEntry.value).toBe('');
expect(tomatoEntry.name).toBe('Tomato');
expect(tomatoEntry.description).toBe('Or "tomato" if you are British');
expect(tomatoEntry.value).toBe('');
});
it('should extract enum info with explicit values', () => {
env.write(
'index.ts',
`
export enum PizzaTopping {
/** It is cheese */
Cheese = 0,
/** Or "tomato" if you are British */
Tomato = "tomato",
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].entryType).toBe(EntryType.Enum);
const enumEntry = docs[0] as EnumEntry;
expect(enumEntry.name).toBe('PizzaTopping');
expect(enumEntry.members.length).toBe(2);
const [cheeseEntry, tomatoEntry] = enumEntry.members;
expect(cheeseEntry.name).toBe('Cheese');
expect(cheeseEntry.description).toBe('It is cheese');
expect(cheeseEntry.value).toBe('0');
expect(cheeseEntry.type).toBe('PizzaTopping.Cheese');
expect(tomatoEntry.name).toBe('Tomato');
expect(tomatoEntry.description).toBe('Or "tomato" if you are British');
expect(tomatoEntry.value).toBe('"tomato"');
expect(tomatoEntry.type).toBe('PizzaTopping.Tomato');
});
});
});
| {
"end_byte": 2969,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/enum_doc_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/jsdoc_extraction_spec.ts_0_8210 | /**
* @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 {DocEntry} from '@angular/compiler-cli/src/ngtsc/docs';
import {
ClassEntry,
FunctionEntry,
FunctionSignatureMetadata,
MethodEntry,
} from '@angular/compiler-cli/src/ngtsc/docs/src/entities';
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import {NgtscTestEnvironment} from '../env';
const testFiles = loadStandardTestFiles({fakeCommon: true});
runInEachFileSystem(() => {
let env!: NgtscTestEnvironment;
describe('ngtsc jsdoc extraction', () => {
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
});
it('should extract jsdoc from all types of top-level statement', () => {
env.write(
'index.ts',
`
/** This is a constant. */
export const PI = 3.14;
/** This is a class. */
export class UserProfile { }
/** This is a function. */
export function save() { }
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(3);
const [piEntry, userProfileEntry, saveEntry] = docs;
expect(piEntry.description).toBe('This is a constant.');
expect(userProfileEntry.description).toBe('This is a class.');
expect(saveEntry.description).toBe('This is a function.');
});
it('should extract raw comment blocks', () => {
env.write(
'index.ts',
`
/** This is a constant. */
export const PI = 3.14;
/**
* Long comment
* with multiple lines.
*/
export class UserProfile { }
/**
* This is a long JsDoc block
* that extends multiple lines.
*
* @deprecated in includes multiple tags.
* @experimental here is another one
*/
export function save() { }
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(3);
const [piEntry, userProfileEntry, saveEntry] = docs;
expect(piEntry.rawComment).toBe('/** This is a constant. */');
expect(userProfileEntry.rawComment).toBe(
`
/**
* Long comment
* with multiple lines.
*/`.trim(),
);
expect(saveEntry.rawComment).toBe(
`
/**
* This is a long JsDoc block
* that extends multiple lines.
*
* @deprecated in includes multiple tags.
* @experimental here is another one
*/`.trim(),
);
});
it('should extract a description from a single-line jsdoc', () => {
env.write(
'index.ts',
`
/** Framework version. */
export const VERSION = '16';
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].description).toBe('Framework version.');
expect(docs[0].jsdocTags.length).toBe(0);
});
it('should extract a description from a multi-line jsdoc', () => {
env.write(
'index.ts',
`
/**
* This is a really long description that needs
* to wrap over multiple lines.
*/
export const LONG_VERSION = '16.0.0';
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].description).toBe(
'This is a really long description that needs\nto wrap over multiple lines.',
);
expect(docs[0].jsdocTags.length).toBe(0);
});
it('should extract jsdoc with an empty tag', () => {
env.write(
'index.ts',
`
/**
* Unsupported version.
* @deprecated
*/
export const OLD_VERSION = '1.0.0';
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].description).toBe('Unsupported version.');
expect(docs[0].jsdocTags.length).toBe(1);
expect(docs[0].jsdocTags[0]).toEqual({name: 'deprecated', comment: ''});
});
it('should extract jsdoc with a single-line tag', () => {
env.write(
'index.ts',
`
/**
* Unsupported version.
* @deprecated Use the newer one.
*/
export const OLD_VERSION = '1.0.0';
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].description).toBe('Unsupported version.');
expect(docs[0].jsdocTags.length).toBe(1);
expect(docs[0].jsdocTags[0]).toEqual({name: 'deprecated', comment: 'Use the newer one.'});
});
it('should extract jsdoc with a multi-line tags', () => {
env.write(
'index.ts',
`
/**
* Unsupported version.
* @deprecated Use the newer one.
* Or use something else.
* @experimental This is another
* long comment that wraps.
*/
export const OLD_VERSION = '1.0.0';
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].description).toBe('Unsupported version.');
expect(docs[0].jsdocTags.length).toBe(2);
const [deprecatedEntry, experimentalEntry] = docs[0].jsdocTags;
expect(deprecatedEntry).toEqual({
name: 'deprecated',
comment: 'Use the newer one.\nOr use something else.',
});
expect(experimentalEntry).toEqual({
name: 'experimental',
comment: 'This is another\nlong comment that wraps.',
});
});
it('should extract jsdoc with custom tags', () => {
env.write(
'index.ts',
`
/**
* Unsupported version.
* @ancient Use the newer one.
* Or use something else.
*/
export const OLD_VERSION = '1.0.0';
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].description).toBe('Unsupported version.');
expect(docs[0].jsdocTags.length).toBe(1);
expect(docs[0].jsdocTags[0]).toEqual({
name: 'ancient',
comment: 'Use the newer one.\nOr use something else.',
});
});
it('should extract a @see jsdoc tag', () => {
// "@see" has special behavior with links, so we have tests
// specifically for this tag.
env.write(
'index.ts',
`
import {Component} from '@angular/core';
/**
* Future version.
* @see {@link Component}
*/
export const NEW_VERSION = '99.0.0';
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].description).toBe('Future version.');
expect(docs[0].jsdocTags.length).toBe(1);
expect(docs[0].jsdocTags[0]).toEqual({
name: 'see',
comment: '{@link Component}',
});
});
it('should extract function parameter descriptions', () => {
env.write(
'index.ts',
`
/**
* Save some data.
* @param data The data to save.
* @param timing Long description
* with multiple lines.
*/
export function save(data: object, timing: number): void { }
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const functionEntry = docs[0] as FunctionEntry;
expect(functionEntry.description).toBe('Save some data.');
const [dataEntry, timingEntry] = functionEntry.implementation.params;
expect(dataEntry.description).toBe('The data to save.');
expect(timingEntry.description).toBe('Long description\nwith multiple lines.');
}); | {
"end_byte": 8210,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/jsdoc_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/jsdoc_extraction_spec.ts_8216_10285 | it('should extract class member descriptions', () => {
env.write(
'index.ts',
`
export class UserProfile {
/** A user identifier. */
userId: number = 0;
/** Name of the user */
get name(): string { return ''; }
/** Name of the user */
set name(value: string) { }
/**
* Save the user.
* @param config Setting for saving.
* @returns Whether it succeeded
*/
save(config: object): boolean { return false; }
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const classEntry = docs[0] as ClassEntry;
expect(classEntry.members.length).toBe(4);
const [userIdEntry, nameGetterEntry, nameSetterEntry] = classEntry.members;
expect(userIdEntry.description).toBe('A user identifier.');
expect(nameGetterEntry.description).toBe('Name of the user');
expect(nameSetterEntry.description).toBe('Name of the user');
const saveEntry = classEntry.members[3] as MethodEntry;
expect(saveEntry.description).toBe('Save the user.');
expect(saveEntry.implementation.params[0].description).toBe('Setting for saving.');
expect(saveEntry.jsdocTags.length).toBe(2);
expect(saveEntry.jsdocTags[1]).toEqual({name: 'returns', comment: 'Whether it succeeded'});
});
it('should escape decorator names', () => {
env.write(
'index.ts',
`
/**
* Save some data.
* @Component decorators are cool.
* @deprecated for some reason
*/
export type s = string;
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const entry = docs[0];
expect(entry.description).toBe('Save some data.\n@Component decorators are cool.');
expect(entry.jsdocTags.length).toBe(1);
expect(entry.jsdocTags[0].name).toBe('deprecated');
});
});
}); | {
"end_byte": 10285,
"start_byte": 8216,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/jsdoc_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/function_doc_extraction_spec.ts_0_4942 | /**
* @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 {DocEntry} from '@angular/compiler-cli/src/ngtsc/docs';
import {EntryType, FunctionEntry} from '@angular/compiler-cli/src/ngtsc/docs/src/entities';
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import {NgtscTestEnvironment} from '../env';
const testFiles = loadStandardTestFiles({fakeCommon: true});
runInEachFileSystem(() => {
let env!: NgtscTestEnvironment;
describe('ngtsc function docs extraction', () => {
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
});
it('should extract functions', () => {
env.write(
'index.ts',
`
export function getInjector() { }
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const functionEntry = docs[0] as FunctionEntry;
expect(functionEntry.name).toBe('getInjector');
expect(functionEntry.entryType).toBe(EntryType.Function);
expect(functionEntry.implementation.params.length).toBe(0);
expect(functionEntry.implementation.returnType).toBe('void');
});
it('should extract function with parameters', () => {
env.write(
'index.ts',
`
export function go(num: string, intl = 1, area?: string): boolean {
return false;
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const functionEntry = docs[0] as FunctionEntry;
expect(functionEntry.entryType).toBe(EntryType.Function);
expect(functionEntry.implementation.returnType).toBe('boolean');
expect(functionEntry.implementation.params.length).toBe(3);
const [numParam, intlParam, areaParam] = functionEntry.implementation.params;
expect(numParam.name).toBe('num');
expect(numParam.isOptional).toBe(false);
expect(numParam.type).toBe('string');
expect(intlParam.name).toBe('intl');
expect(intlParam.isOptional).toBe(true);
expect(intlParam.type).toBe('number');
expect(areaParam.name).toBe('area');
expect(areaParam.isOptional).toBe(true);
expect(areaParam.type).toBe('string | undefined');
});
it('should extract a function with a rest parameter', () => {
env.write(
'index.ts',
`
export function getNames(prefix: string, ...ids: string[]): string[] {
return [];
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const functionEntry = docs[0] as FunctionEntry;
const [prefixParamEntry, idsParamEntry] = functionEntry.implementation.params;
expect(prefixParamEntry.name).toBe('prefix');
expect(prefixParamEntry.type).toBe('string');
expect(prefixParamEntry.isRestParam).toBe(false);
expect(idsParamEntry.name).toBe('ids');
expect(idsParamEntry.type).toBe('string[]');
expect(idsParamEntry.isRestParam).toBe(true);
});
it('should extract overloaded functions', () => {
env.write(
'index.ts',
`
export function ident(value: boolean): boolean
export function ident(value: number): number
export function ident(value: number|boolean): number|boolean {
return value;
}
`,
);
const docs = env.driveDocsExtraction('index.ts') as FunctionEntry[];
expect(docs[0].signatures?.length).toBe(2);
const [booleanOverloadEntry, numberOverloadEntry] = docs[0].signatures!;
expect(booleanOverloadEntry.name).toBe('ident');
expect(booleanOverloadEntry.params.length).toBe(1);
expect(booleanOverloadEntry.params[0].type).toBe('boolean');
expect(booleanOverloadEntry.returnType).toBe('boolean');
expect(numberOverloadEntry.name).toBe('ident');
expect(numberOverloadEntry.params.length).toBe(1);
expect(numberOverloadEntry.params[0].type).toBe('number');
expect(numberOverloadEntry.returnType).toBe('number');
});
it('should extract function generics', () => {
env.write(
'index.ts',
`
export function save<T>(data: T) { }
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const [functionEntry] = docs as FunctionEntry[];
expect(functionEntry.signatures.length).toBe(1);
const [genericEntry] = functionEntry.implementation.generics;
expect(genericEntry.name).toBe('T');
expect(genericEntry.constraint).toBeUndefined();
expect(genericEntry.default).toBeUndefined();
});
});
});
| {
"end_byte": 4942,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/function_doc_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/decorator_doc_extraction_spec.ts_0_5612 | /**
* @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 {DocEntry} from '@angular/compiler-cli/src/ngtsc/docs';
import {
DecoratorEntry,
DecoratorType,
EntryType,
} from '@angular/compiler-cli/src/ngtsc/docs/src/entities';
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import {NgtscTestEnvironment} from '../env';
const testFiles = loadStandardTestFiles({fakeCommon: true});
runInEachFileSystem(() => {
let env!: NgtscTestEnvironment;
describe('ngtsc decorator docs extraction', () => {
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
});
it('should extract class decorators that define members in an interface', () => {
env.write(
'index.ts',
`
export interface Component {
/** The template. */
template: string;
}
export interface ComponentDecorator {
/** The description. */
(obj?: Component): any;
}
function makeDecorator(): ComponentDecorator { return () => {}; }
export const Component: ComponentDecorator = makeDecorator();
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const decoratorEntry = docs[0] as DecoratorEntry;
expect(decoratorEntry.name).toBe('Component');
expect(decoratorEntry.description).toBe('The description.');
expect(decoratorEntry.entryType).toBe(EntryType.Decorator);
expect(decoratorEntry.decoratorType).toBe(DecoratorType.Class);
expect(decoratorEntry.members.length).toBe(1);
expect(decoratorEntry.members[0].name).toBe('template');
expect(decoratorEntry.members[0].type).toBe('string');
expect(decoratorEntry.members[0].description).toBe('The template.');
});
it('should extract property decorators', () => {
env.write(
'index.ts',
`
export interface Input {
/** The alias. */
alias: string;
}
export interface InputDecorator {
/** The description. */
(alias: string): any;
}
function makePropDecorator(): InputDecorator { return () => {}); }
export const Input: InputDecorator = makePropDecorator();
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const decoratorEntry = docs[0] as DecoratorEntry;
expect(decoratorEntry.name).toBe('Input');
expect(decoratorEntry.description).toBe('The description.');
expect(decoratorEntry.entryType).toBe(EntryType.Decorator);
expect(decoratorEntry.decoratorType).toBe(DecoratorType.Member);
expect(decoratorEntry.members.length).toBe(1);
expect(decoratorEntry.members[0].name).toBe('alias');
expect(decoratorEntry.members[0].type).toBe('string');
expect(decoratorEntry.members[0].description).toBe('The alias.');
});
it('should extract property decorators with a type alias', () => {
env.write(
'index.ts',
`
interface Query {
/** The read. */
read: string;
}
export type ViewChild = Query;
export interface ViewChildDecorator {
/** The description. */
(alias: string): any;
}
function makePropDecorator(): ViewChildDecorator { return () => {}); }
export const ViewChild: ViewChildDecorator = makePropDecorator();
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const decoratorEntry = docs[0] as DecoratorEntry;
expect(decoratorEntry.name).toBe('ViewChild');
expect(decoratorEntry.description).toBe('The description.');
expect(decoratorEntry.entryType).toBe(EntryType.Decorator);
expect(decoratorEntry.decoratorType).toBe(DecoratorType.Member);
expect(decoratorEntry.members.length).toBe(1);
expect(decoratorEntry.members[0].name).toBe('read');
expect(decoratorEntry.members[0].type).toBe('string');
expect(decoratorEntry.members[0].description).toBe('The read.');
});
it('should extract param decorators', () => {
env.write(
'index.ts',
`
export interface Inject {
/** The token. */
token: string;
}
export interface InjectDecorator {
/** The description. */
(token: string) => any;
}
function makePropDecorator(): InjectDecorator { return () => {}; }
export const Inject: InjectDecorator = makeParamDecorator();
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const decoratorEntry = docs[0] as DecoratorEntry;
expect(decoratorEntry.name).toBe('Inject');
expect(decoratorEntry.description).toBe('The description.');
expect(decoratorEntry.entryType).toBe(EntryType.Decorator);
expect(decoratorEntry.decoratorType).toBe(DecoratorType.Parameter);
expect(decoratorEntry.members.length).toBe(1);
expect(decoratorEntry.members[0].name).toBe('token');
expect(decoratorEntry.members[0].type).toBe('string');
expect(decoratorEntry.members[0].description).toBe('The token.');
});
});
});
| {
"end_byte": 5612,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/decorator_doc_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/constant_doc_extraction_spec.ts_0_5415 | /**
* @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 {DocEntry} from '@angular/compiler-cli/src/ngtsc/docs';
import {
ConstantEntry,
EntryType,
EnumEntry,
} from '@angular/compiler-cli/src/ngtsc/docs/src/entities';
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import {NgtscTestEnvironment} from '../env';
const testFiles = loadStandardTestFiles({fakeCommon: true});
runInEachFileSystem(() => {
let env!: NgtscTestEnvironment;
describe('ngtsc constant docs extraction', () => {
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
});
it('should extract constants', () => {
env.write(
'index.ts',
`
export const VERSION = '16.0.0';
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const constantEntry = docs[0] as ConstantEntry;
expect(constantEntry.name).toBe('VERSION');
expect(constantEntry.entryType).toBe(EntryType.Constant);
expect(constantEntry.type).toBe('string');
});
it('should extract multiple constant declarations in a single statement', () => {
env.write(
'index.ts',
`
export const PI = 3.14, VERSION = '16.0.0';
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(2);
const [pi, version] = docs as ConstantEntry[];
expect(pi.name).toBe('PI');
expect(pi.entryType).toBe(EntryType.Constant);
expect(pi.type).toBe('number');
expect(version.name).toBe('VERSION');
expect(version.entryType).toBe(EntryType.Constant);
expect(version.type).toBe('string');
});
it('should extract non-primitive constants', () => {
env.write(
'index.ts',
`
import {InjectionToken} from '@angular/core';
export const SOME_TOKEN = new InjectionToken('something');
export const TYPED_TOKEN = new InjectionToken<string>();
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(2);
const [someToken, typedToken] = docs as ConstantEntry[];
expect(someToken.name).toBe('SOME_TOKEN');
expect(someToken.entryType).toBe(EntryType.Constant);
expect(someToken.type).toBe('InjectionToken<unknown>');
expect(typedToken.name).toBe('TYPED_TOKEN');
expect(typedToken.entryType).toBe(EntryType.Constant);
expect(typedToken.type).toBe('InjectionToken<string>');
});
it('should extract an object literal marked as an enum', () => {
env.write(
'index.ts',
`
/**
* Toppings for your pizza.
* @object-literal-as-enum
*/
export const PizzaTopping = {
/** It is cheese */
Cheese: 0,
/** Or "tomato" if you are British */
Tomato: "tomato",
};
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].entryType).toBe(EntryType.Enum);
expect(docs[0].jsdocTags).toEqual([]);
const enumEntry = docs[0] as EnumEntry;
expect(enumEntry.name).toBe('PizzaTopping');
expect(enumEntry.members.length).toBe(2);
const [cheeseEntry, tomatoEntry] = enumEntry.members;
expect(cheeseEntry.name).toBe('Cheese');
expect(cheeseEntry.description).toBe('It is cheese');
expect(cheeseEntry.value).toBe('0');
expect(cheeseEntry.type).toBe('PizzaTopping.Cheese');
expect(tomatoEntry.name).toBe('Tomato');
expect(tomatoEntry.description).toBe('Or "tomato" if you are British');
expect(tomatoEntry.value).toBe('"tomato"');
expect(tomatoEntry.type).toBe('PizzaTopping.Tomato');
});
it('should extract an object literal cast to a const and marked as an enum', () => {
env.write(
'index.ts',
`
/**
* Toppings for your pizza.
* @object-literal-as-enum
*/
export const PizzaTopping = {
/** It is cheese */
Cheese: 0,
/** Or "tomato" if you are British */
Tomato: "tomato",
} as const;
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].entryType).toBe(EntryType.Enum);
expect(docs[0].jsdocTags).toEqual([]);
const enumEntry = docs[0] as EnumEntry;
expect(enumEntry.name).toBe('PizzaTopping');
expect(enumEntry.members.length).toBe(2);
const [cheeseEntry, tomatoEntry] = enumEntry.members;
expect(cheeseEntry.name).toBe('Cheese');
expect(cheeseEntry.description).toBe('It is cheese');
expect(cheeseEntry.value).toBe('0');
expect(cheeseEntry.type).toBe('PizzaTopping.Cheese');
expect(tomatoEntry.name).toBe('Tomato');
expect(tomatoEntry.description).toBe('Or "tomato" if you are British');
expect(tomatoEntry.value).toBe('"tomato"');
expect(tomatoEntry.type).toBe('PizzaTopping.Tomato');
});
});
});
| {
"end_byte": 5415,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/constant_doc_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/initializer_api_extraction_spec.ts_0_7548 | /**
* @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 {
EntryType,
FunctionSignatureMetadata,
InitializerApiFunctionEntry,
ParameterEntry,
} from '@angular/compiler-cli/src/ngtsc/docs/src/entities';
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import {NgtscTestEnvironment} from '../env';
const inputFixture = `
export interface InputSignal<T> {}
export interface InputFunction {
/** No explicit initial value */
<T>(): InputSignal<T|undefined>;
/** With explicit initial value */
<T>(initialValue: T): InputSignal<T>;
required: {
/** Required, no options */
<T>(): void;
/** Required, with transform */
<T, TransformT>(transformFn: (v: TransformT) => T): void;
}
}
/**
* This describes the overall initializer API
* function.
*
* @initializerApiFunction
*/
export const input: InputFunction = null!;
`;
const contentChildrenFixture = `\
export interface Options<ReadT = void> {}
/** Queries for children with "LocatorT". */
export function contentChildren<LocatorT>(
locator: LocatorT, opts?: Options): Signal<LocatorT>;
/** Queries for children with "LocatorT" and "read" option. */
export function contentChildren<LocatorT, ReadT>(
locator: LocatorT, opts: Options<ReadT>): Signal<ReadT>;
/**
* Overall description of "contentChildren" API.
*
* @initializerApiFunction
*/
export function contentChildren<LocatorT, ReadT>(
locator: LocatorT, opts?: Options<ReadT>): Signal<ReadT> {
return null;
}
`;
const testFiles = loadStandardTestFiles();
runInEachFileSystem(() => {
describe('ngtsc initializer API docs extraction', () => {
let env: NgtscTestEnvironment;
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
});
function test(input: string): InitializerApiFunctionEntry | undefined {
env.write('index.ts', input);
return env
.driveDocsExtraction('index.ts')
.find(
(f): f is InitializerApiFunctionEntry => f.entryType === EntryType.InitializerApiFunction,
);
}
describe('interface-based', () => {
it('should extract name', () => {
expect(test(inputFixture)?.name).toBe('input');
});
it('should extract container description', () => {
expect(test(inputFixture)?.description.replace(/\n/g, ' ')).toBe(
'This describes the overall initializer API function.',
);
});
it('should extract individual return types', () => {
expect(test(inputFixture)?.callFunction.signatures[0].returnType).toBe(
'InputSignal<T | undefined>',
);
expect(test(inputFixture)?.callFunction.signatures[1].returnType).toBe('InputSignal<T>');
});
it('should extract container tags', () => {
expect(test(inputFixture)?.jsdocTags).toEqual([
jasmine.objectContaining({name: 'initializerApiFunction'}),
]);
});
it('should extract top-level call signatures', () => {
expect(test(inputFixture)?.callFunction).toEqual({
name: 'input',
implementation: null,
signatures: [
jasmine.objectContaining<FunctionSignatureMetadata>({
generics: [{name: 'T', constraint: undefined, default: undefined}],
returnType: 'InputSignal<T | undefined>',
}),
jasmine.objectContaining<FunctionSignatureMetadata>({
generics: [{name: 'T', constraint: undefined, default: undefined}],
params: [jasmine.objectContaining<ParameterEntry>({name: 'initialValue', type: 'T'})],
returnType: 'InputSignal<T>',
}),
],
});
});
it('should extract sub-property call signatures', () => {
expect(test(inputFixture)?.subFunctions).toEqual([
{
name: 'required',
implementation: null,
signatures: [
jasmine.objectContaining<FunctionSignatureMetadata>({
generics: [{name: 'T', constraint: undefined, default: undefined}],
returnType: 'void',
}),
jasmine.objectContaining<FunctionSignatureMetadata>({
generics: [
{name: 'T', constraint: undefined, default: undefined},
{name: 'TransformT', constraint: undefined, default: undefined},
],
params: [
jasmine.objectContaining<ParameterEntry>({
name: 'transformFn',
type: '(v: TransformT) => T',
}),
],
returnType: 'void',
}),
],
},
]);
});
});
describe('function-based', () => {
it('should extract name', () => {
expect(test(contentChildrenFixture)?.name).toBe('contentChildren');
});
it('should extract container description', () => {
expect(test(contentChildrenFixture)?.description.replace(/\n/g, ' ')).toBe(
'Overall description of "contentChildren" API.',
);
});
it('should extract container tags', () => {
expect(test(contentChildrenFixture)?.jsdocTags).toEqual([
jasmine.objectContaining({name: 'initializerApiFunction'}),
]);
});
it('should extract top-level call signatures', () => {
expect(test(contentChildrenFixture)?.callFunction).toEqual({
name: 'contentChildren',
implementation: jasmine.objectContaining<FunctionSignatureMetadata>({
name: 'contentChildren',
description: jasmine.stringContaining('Overall description of "contentChildren" API'),
}),
signatures: [
jasmine.objectContaining<FunctionSignatureMetadata>({
generics: [{name: 'LocatorT', constraint: undefined, default: undefined}],
params: [
jasmine.objectContaining<ParameterEntry>({name: 'locator', type: 'LocatorT'}),
jasmine.objectContaining<ParameterEntry>({
name: 'opts',
isOptional: true,
type: 'Options<void> | undefined',
}),
],
returnType: 'Signal<LocatorT>',
}),
jasmine.objectContaining<FunctionSignatureMetadata>({
generics: [
{name: 'LocatorT', constraint: undefined, default: undefined},
{name: 'ReadT', constraint: undefined, default: undefined},
],
params: [
jasmine.objectContaining<ParameterEntry>({name: 'locator', type: 'LocatorT'}),
jasmine.objectContaining<ParameterEntry>({
name: 'opts',
isOptional: false,
type: 'Options<ReadT>',
}),
],
returnType: 'Signal<ReadT>',
}),
],
});
});
it('should have an empty list of sub-properties', () => {
// Function-based initializer APIs never have sub-properties.
expect(test(contentChildrenFixture)?.subFunctions).toEqual([]);
});
});
});
});
| {
"end_byte": 7548,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/initializer_api_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/common_doc_extraction_spec.ts_0_1094 | /**
* @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 {DocEntry} from '@angular/compiler-cli/src/ngtsc/docs';
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import {NgtscTestEnvironment} from '../env';
const testFiles = loadStandardTestFiles({fakeCommon: true});
runInEachFileSystem(() => {
let env!: NgtscTestEnvironment;
describe('ngtsc common docs extraction', () => {
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
});
it('should not extract unexported statements', () => {
env.write(
'index.ts',
`
class UserProfile {}
function getUser() { }
const name = '';
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(0);
});
});
});
| {
"end_byte": 1094,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/common_doc_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/doc_extraction_filtering_spec.ts_0_1506 | /**
* @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 {DocEntry} from '@angular/compiler-cli/src/ngtsc/docs';
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import {NgtscTestEnvironment} from '../env';
const testFiles = loadStandardTestFiles({fakeCommon: true});
runInEachFileSystem(() => {
let env!: NgtscTestEnvironment;
describe('ngtsc docs extraction filtering', () => {
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
});
it('should not extract Angular-private symbols', () => {
env.write(
'index.ts',
`
export class ɵUserProfile {}
export class _SliderWidget {}
export const ɵPI = 3.14;
export const _TAO = 6.28;
export function ɵsave() { }
export function _reset() { }
export interface ɵSavable { }
export interface _Resettable { }
export type ɵDifferentNumber = number;
export type _DifferentBoolean = boolean;
export enum ɵToppings { Tomato, Onion }
export enum _Sauces { Buffalo, Garlic }
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(0);
});
});
});
| {
"end_byte": 1506,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/doc_extraction_filtering_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/pipe_doc_extraction_spec.ts_0_2419 | /**
* @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 {DocEntry} from '@angular/compiler-cli/src/ngtsc/docs';
import {EntryType, PipeEntry} from '@angular/compiler-cli/src/ngtsc/docs/src/entities';
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import {NgtscTestEnvironment} from '../env';
const testFiles = loadStandardTestFiles({fakeCommon: true});
runInEachFileSystem(() => {
let env!: NgtscTestEnvironment;
describe('ngtsc pipe docs extraction', () => {
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
});
it('should extract standalone pipe info', () => {
env.write(
'index.ts',
`
import {Pipe} from '@angular/core';
@Pipe({
standalone: true,
name: 'shorten',
})
export class ShortenPipe {
transform(value: string): string { return ''; }
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
expect(docs[0].entryType).toBe(EntryType.Pipe);
const directiveEntry = docs[0] as PipeEntry;
expect(directiveEntry.isStandalone).toBe(true);
expect(directiveEntry.name).toBe('ShortenPipe');
expect(directiveEntry.pipeName).toBe('shorten');
});
it('should extract NgModule pipe info', () => {
env.write(
'index.ts',
`
import {Pipe, NgModule} from '@angular/core';
@Pipe({
name: 'shorten',
standalone: false,
})
export class ShortenPipe {
transform(value: string): string { return ''; }
}
@NgModule({declarations: [ShortenPipe]})
export class PipeModule { }
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(2);
expect(docs[0].entryType).toBe(EntryType.Pipe);
const directiveEntry = docs[0] as PipeEntry;
expect(directiveEntry.isStandalone).toBe(false);
expect(directiveEntry.name).toBe('ShortenPipe');
expect(directiveEntry.pipeName).toBe('shorten');
});
});
});
| {
"end_byte": 2419,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/pipe_doc_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/type_alias_doc_extraction_spec.ts_0_2011 | /**
* @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 {DocEntry} from '@angular/compiler-cli/src/ngtsc/docs';
import {EntryType, TypeAliasEntry} from '@angular/compiler-cli/src/ngtsc/docs/src/entities';
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import {NgtscTestEnvironment} from '../env';
const testFiles = loadStandardTestFiles({fakeCommon: true});
runInEachFileSystem(() => {
let env!: NgtscTestEnvironment;
describe('ngtsc type alias docs extraction', () => {
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
});
it('should extract type aliases based on primitives', () => {
env.write(
'index.ts',
`
export type SuperNumber = number | string;
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const typeAliasEntry = docs[0] as TypeAliasEntry;
expect(typeAliasEntry.name).toBe('SuperNumber');
expect(typeAliasEntry.entryType).toBe(EntryType.TypeAlias);
expect(typeAliasEntry.type).toBe('number | string');
});
it('should extract type aliases for objects', () => {
env.write(
'index.ts',
`
export type UserProfile = {
name: string;
age: number;
};
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const typeAliasEntry = docs[0] as TypeAliasEntry;
expect(typeAliasEntry.name).toBe('UserProfile');
expect(typeAliasEntry.entryType).toBe(EntryType.TypeAlias);
expect(typeAliasEntry.type).toBe(`{
name: string;
age: number;
}`);
});
});
});
| {
"end_byte": 2011,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/type_alias_doc_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/interface_doc_extraction_spec.ts_0_8571 | /**
* @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 {DocEntry} from '@angular/compiler-cli/src/ngtsc/docs';
import {
ClassEntry,
EntryType,
InterfaceEntry,
MemberTags,
MemberType,
MethodEntry,
PropertyEntry,
} from '@angular/compiler-cli/src/ngtsc/docs/src/entities';
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import {NgtscTestEnvironment} from '../env';
const testFiles = loadStandardTestFiles({fakeCommon: true});
runInEachFileSystem(() => {
let env!: NgtscTestEnvironment;
describe('ngtsc interface docs extraction', () => {
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
});
it('should extract interfaces', () => {
env.write(
'index.ts',
`
export interface UserProfile {}
export interface CustomSlider {}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(2);
expect(docs[0].name).toBe('UserProfile');
expect(docs[0].entryType).toBe(EntryType.Interface);
expect(docs[1].name).toBe('CustomSlider');
expect(docs[1].entryType).toBe(EntryType.Interface);
});
it('should extract interface members', () => {
env.write(
'index.ts',
`
export interface UserProfile {
firstName(): string;
age: number;
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const interfaceEntry = docs[0] as InterfaceEntry;
expect(interfaceEntry.members.length).toBe(2);
const methodEntry = interfaceEntry.members[0] as MethodEntry;
expect(methodEntry.memberType).toBe(MemberType.Method);
expect(methodEntry.name).toBe('firstName');
expect(methodEntry.implementation.returnType).toBe('string');
const propertyEntry = interfaceEntry.members[1] as PropertyEntry;
expect(propertyEntry.memberType).toBe(MemberType.Property);
expect(propertyEntry.name).toBe('age');
expect(propertyEntry.type).toBe('number');
});
it('should extract call signatures', () => {
env.write(
'index.ts',
`
export interface UserProfile {
(name: string): string;
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const interfaceEntry = docs[0] as InterfaceEntry;
expect(interfaceEntry.members.length).toBe(1);
const methodEntry = interfaceEntry.members[0] as MethodEntry;
expect(methodEntry.memberType).toBe(MemberType.Method);
expect(methodEntry.name).toBe('');
expect(methodEntry.implementation.returnType).toBe('string');
});
it('should extract a method with a rest parameter', () => {
env.write(
'index.ts',
`
export interface UserProfile {
getNames(prefix: string, ...ids: string[]): string[];
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const interfaceEntry = docs[0] as InterfaceEntry;
const methodEntry = interfaceEntry.members[0] as MethodEntry;
const [prefixParamEntry, idsParamEntry] = methodEntry.implementation.params;
expect(prefixParamEntry.name).toBe('prefix');
expect(prefixParamEntry.type).toBe('string');
expect(prefixParamEntry.isRestParam).toBe(false);
expect(idsParamEntry.name).toBe('ids');
expect(idsParamEntry.type).toBe('string[]');
expect(idsParamEntry.isRestParam).toBe(true);
});
it('should extract interface method params', () => {
env.write(
'index.ts',
`
export interface UserProfile {
setPhone(num: string, area?: string): void;
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const interfaceEntry = docs[0] as InterfaceEntry;
expect(interfaceEntry.members.length).toBe(1);
const methodEntry = interfaceEntry.members[0] as MethodEntry;
expect(methodEntry.memberType).toBe(MemberType.Method);
expect(methodEntry.name).toBe('setPhone');
expect(methodEntry.implementation.params.length).toBe(2);
const [numParam, areaParam] = methodEntry.implementation.params;
expect(numParam.name).toBe('num');
expect(numParam.isOptional).toBe(false);
expect(numParam.type).toBe('string');
expect(areaParam.name).toBe('area');
expect(areaParam.isOptional).toBe(true);
expect(areaParam.type).toBe('string | undefined');
});
it('should not extract private interface members', () => {
env.write(
'index.ts',
`
export interface UserProfile {
private ssn: string;
private getSsn(): string;
private static printSsn(): void;
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const interfaceEntry = docs[0] as InterfaceEntry;
expect(interfaceEntry.members.length).toBe(0);
});
it('should extract member tags', () => {
// Test both properties and methods with zero, one, and multiple tags.
env.write(
'index.ts',
`
export interface UserProfile {
eyeColor: string;
protected name: string;
readonly age: number;
address?: string;
static country: string;
protected readonly birthday: string;
getEyeColor(): string;
protected getName(): string;
getAge?(): number;
static getCountry(): string;
protected getBirthday?(): string;
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const interfaceEntry = docs[0] as InterfaceEntry;
expect(interfaceEntry.members.length).toBe(11);
const [
eyeColorMember,
nameMember,
ageMember,
addressMember,
countryMember,
birthdayMember,
getEyeColorMember,
getNameMember,
getAgeMember,
getCountryMember,
getBirthdayMember,
] = interfaceEntry.members;
// Properties
expect(eyeColorMember.memberTags.length).toBe(0);
expect(nameMember.memberTags).toEqual([MemberTags.Protected]);
expect(ageMember.memberTags).toEqual([MemberTags.Readonly]);
expect(addressMember.memberTags).toEqual([MemberTags.Optional]);
expect(countryMember.memberTags).toEqual([MemberTags.Static]);
expect(birthdayMember.memberTags).toContain(MemberTags.Protected);
expect(birthdayMember.memberTags).toContain(MemberTags.Readonly);
// Methods
expect(getEyeColorMember.memberTags.length).toBe(0);
expect(getNameMember.memberTags).toEqual([MemberTags.Protected]);
expect(getAgeMember.memberTags).toEqual([MemberTags.Optional]);
expect(getCountryMember.memberTags).toEqual([MemberTags.Static]);
expect(getBirthdayMember.memberTags).toContain(MemberTags.Protected);
expect(getBirthdayMember.memberTags).toContain(MemberTags.Optional);
});
it('should extract getters and setters', () => {
// Test getter-only, a getter + setter, and setter-only.
env.write(
'index.ts',
`
export interface UserProfile {
get userId(): number;
get userName(): string;
set userName(value: string);
set isAdmin(value: boolean);
}
`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
const interfaceEntry = docs[0] as InterfaceEntry;
expect(interfaceEntry.entryType).toBe(EntryType.Interface);
expect(interfaceEntry.members.length).toBe(4);
const [userIdGetter, userNameGetter, userNameSetter, isAdminSetter] = interfaceEntry.members;
expect(userIdGetter.name).toBe('userId');
expect(userIdGetter.memberType).toBe(MemberType.Getter);
expect(userNameGetter.name).toBe('userName');
expect(userNameGetter.memberType).toBe(MemberType.Getter);
expect(userNameSetter.name).toBe('userName');
expect(userNameSetter.memberType).toBe(MemberType.Setter);
expect(isAdminSetter.name).toBe('isAdmin');
expect(isAdminSetter.memberType).toBe(MemberType.Setter);
}); | {
"end_byte": 8571,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/interface_doc_extraction_spec.ts"
} |
angular/packages/compiler-cli/test/ngtsc/doc_extraction/interface_doc_extraction_spec.ts_8577_13043 | it('should extract inherited members', () => {
env.write(
'index.ts',
`
interface Ancestor {
id: string;
value: string|number;
save(value: string|number): string|number;
}
interface Parent extends Ancestor {
name: string;
}
export interface Child extends Parent {
age: number;
value: number;
save(value: number): number;
save(value: string|number): string|number;
}`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const interfaceEntry = docs[0] as InterfaceEntry;
expect(interfaceEntry.members.length).toBe(6);
const [ageEntry, valueEntry, numberSaveEntry, unionSaveEntry, nameEntry, idEntry] =
interfaceEntry.members;
expect(ageEntry.name).toBe('age');
expect(ageEntry.memberType).toBe(MemberType.Property);
expect((ageEntry as PropertyEntry).type).toBe('number');
expect(ageEntry.memberTags).not.toContain(MemberTags.Inherited);
expect(valueEntry.name).toBe('value');
expect(valueEntry.memberType).toBe(MemberType.Property);
expect((valueEntry as PropertyEntry).type).toBe('number');
expect(valueEntry.memberTags).not.toContain(MemberTags.Inherited);
expect(numberSaveEntry.name).toBe('save');
expect(numberSaveEntry.memberType).toBe(MemberType.Method);
expect((numberSaveEntry as MethodEntry).implementation.returnType).toBe('number');
expect(numberSaveEntry.memberTags).not.toContain(MemberTags.Inherited);
expect(unionSaveEntry.name).toBe('save');
expect(unionSaveEntry.memberType).toBe(MemberType.Method);
expect((unionSaveEntry as MethodEntry).implementation.returnType).toBe('string | number');
expect(unionSaveEntry.memberTags).not.toContain(MemberTags.Inherited);
expect(nameEntry.name).toBe('name');
expect(nameEntry.memberType).toBe(MemberType.Property);
expect((nameEntry as PropertyEntry).type).toBe('string');
expect(nameEntry.memberTags).toContain(MemberTags.Inherited);
expect(idEntry.name).toBe('id');
expect(idEntry.memberType).toBe(MemberType.Property);
expect((idEntry as PropertyEntry).type).toBe('string');
expect(idEntry.memberTags).toContain(MemberTags.Inherited);
});
it('should extract inherited getters/setters', () => {
env.write(
'index.ts',
`
interface Ancestor {
get name(): string;
set name(v: string);
get id(): string;
set id(v: string);
get age(): number;
set age(v: number);
}
interface Parent extends Ancestor {
name: string;
}
export interface Child extends Parent {
get id(): string;
}`,
);
const docs: DocEntry[] = env.driveDocsExtraction('index.ts');
expect(docs.length).toBe(1);
const interfaceEntry = docs[0] as InterfaceEntry;
expect(interfaceEntry.members.length).toBe(4);
const [idEntry, nameEntry, ageGetterEntry, ageSetterEntry] =
interfaceEntry.members as PropertyEntry[];
// When the child interface overrides an accessor pair with another accessor, it overrides
// *both* the getter and the setter, resulting (in this case) in just a getter.
expect(idEntry.name).toBe('id');
expect(idEntry.memberType).toBe(MemberType.Getter);
expect((idEntry as PropertyEntry).type).toBe('string');
expect(idEntry.memberTags).not.toContain(MemberTags.Inherited);
// When the child interface overrides an accessor with a property, the property takes
// precedence.
expect(nameEntry.name).toBe('name');
expect(nameEntry.memberType).toBe(MemberType.Property);
expect(nameEntry.type).toBe('string');
expect(nameEntry.memberTags).toContain(MemberTags.Inherited);
expect(ageGetterEntry.name).toBe('age');
expect(ageGetterEntry.memberType).toBe(MemberType.Getter);
expect(ageGetterEntry.type).toBe('number');
expect(ageGetterEntry.memberTags).toContain(MemberTags.Inherited);
expect(ageSetterEntry.name).toBe('age');
expect(ageSetterEntry.memberType).toBe(MemberType.Setter);
expect(ageSetterEntry.type).toBe('number');
expect(ageSetterEntry.memberTags).toContain(MemberTags.Inherited);
});
});
}); | {
"end_byte": 13043,
"start_byte": 8577,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/doc_extraction/interface_doc_extraction_spec.ts"
} |
angular/packages/compiler-cli/linker/README.md_0_863 | # Angular Linker
This package contains a `FileLinker` and supporting code to be able to "link" partial declarations of components, directives, etc in libraries to produce the full definitions.
The partial declaration format allows library packages to be published to npm without exposing the underlying Ivy instructions.
The tooling here allows application build tools (e.g. CLI) to produce fully compiled components, directives, etc at the point when the application is bundled.
These linked files can be cached outside `node_modules` so it does not suffer from problems of mutating packages in `node_modules`.
Generally this tooling will be wrapped in a transpiler specific plugin, such as the provided [Babel plugin](./babel).
## Unit Testing
The unit tests are built and run using Bazel:
```bash
yarn bazel test //packages/compiler-cli/linker/test
```
| {
"end_byte": 863,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/README.md"
} |
angular/packages/compiler-cli/linker/BUILD.bazel_0_554 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "linker",
srcs = ["index.ts"] + glob([
"src/**/*.ts",
]),
deps = [
"//packages/compiler",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/logging",
"//packages/compiler-cli/src/ngtsc/sourcemaps",
"//packages/compiler-cli/src/ngtsc/translator",
"@npm//@types/semver",
"@npm//semver",
"@npm//typescript",
],
)
| {
"end_byte": 554,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/BUILD.bazel"
} |
angular/packages/compiler-cli/linker/index.ts_0_723 | /**
* @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 {AstHost, Range} from './src/ast/ast_host';
export {assert} from './src/ast/utils';
export {FatalLinkerError, isFatalLinkerError} from './src/fatal_linker_error';
export {DeclarationScope} from './src/file_linker/declaration_scope';
export {FileLinker} from './src/file_linker/file_linker';
export {LinkerEnvironment} from './src/file_linker/linker_environment';
export {DEFAULT_LINKER_OPTIONS, LinkerOptions} from './src/file_linker/linker_options';
export {needsLinking} from './src/file_linker/needs_linking';
| {
"end_byte": 723,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/index.ts"
} |
angular/packages/compiler-cli/linker/test/BUILD.bazel_0_801 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "test_lib",
testonly = True,
srcs = glob([
"**/*.ts",
]),
deps = [
"//packages:types",
"//packages/compiler",
"//packages/compiler-cli/linker",
"//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/translator",
"@npm//@types/semver",
"@npm//semver",
"@npm//typescript",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node_no_angular"],
deps = [
":test_lib",
],
)
| {
"end_byte": 801,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/test/BUILD.bazel"
} |
angular/packages/compiler-cli/linker/test/fatal_linker_error_spec.ts_0_970 | /**
* @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 {FatalLinkerError, isFatalLinkerError} from '../src/fatal_linker_error';
describe('FatalLinkerError', () => {
it('should expose the `node` and `message`', () => {
const node = {};
expect(new FatalLinkerError(node, 'Some message')).toEqual(
jasmine.objectContaining({node, message: 'Some message'}),
);
});
});
describe('isFatalLinkerError()', () => {
it('should return true if the error is of type `FatalLinkerError`', () => {
const error = new FatalLinkerError({}, 'Some message');
expect(isFatalLinkerError(error)).toBe(true);
});
it('should return false if the error is not of type `FatalLinkerError`', () => {
const error = new Error('Some message');
expect(isFatalLinkerError(error)).toBe(false);
});
});
| {
"end_byte": 970,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/test/fatal_linker_error_spec.ts"
} |
angular/packages/compiler-cli/linker/test/linker_import_generator_spec.ts_0_2643 | /**
* @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 {TypeScriptAstFactory} from '../../src/ngtsc/translator';
import {LinkerImportGenerator} from '../src/linker_import_generator';
const ngImport = ts.factory.createIdentifier('ngImport');
describe('LinkerImportGenerator<TExpression>', () => {
describe('generateNamespaceImport()', () => {
it('should error if the import is not `@angular/core`', () => {
const generator = new LinkerImportGenerator<ts.Statement, ts.Expression>(
new TypeScriptAstFactory(false),
ngImport,
);
expect(() =>
generator.addImport({
exportModuleSpecifier: 'other/import',
exportSymbolName: null,
requestedFile: null,
}),
).toThrowError(`Unable to import from anything other than '@angular/core'`);
});
it('should return the ngImport expression for `@angular/core`', () => {
const generator = new LinkerImportGenerator<ts.Statement, ts.Expression>(
new TypeScriptAstFactory(false),
ngImport,
);
expect(
generator.addImport({
exportModuleSpecifier: '@angular/core',
exportSymbolName: null,
requestedFile: null,
}),
).toBe(ngImport);
});
});
describe('generateNamedImport()', () => {
it('should error if the import is not `@angular/core`', () => {
const generator = new LinkerImportGenerator<ts.Statement, ts.Expression>(
new TypeScriptAstFactory(false),
ngImport,
);
expect(() =>
generator.addImport({
exportModuleSpecifier: 'other/import',
exportSymbolName: 'someSymbol',
requestedFile: null,
}),
).toThrowError(`Unable to import from anything other than '@angular/core'`);
});
it('should return a `NamedImport` object containing the ngImport expression', () => {
const generator = new LinkerImportGenerator<ts.Statement, ts.Expression>(
new TypeScriptAstFactory(false),
ngImport,
);
const result = generator.addImport({
exportModuleSpecifier: '@angular/core',
exportSymbolName: 'someSymbol',
requestedFile: null,
});
expect(ts.isPropertyAccessExpression(result)).toBe(true);
expect((result as ts.PropertyAccessExpression).name.text).toBe('someSymbol');
expect((result as ts.PropertyAccessExpression).expression).toBe(ngImport);
});
});
});
| {
"end_byte": 2643,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/test/linker_import_generator_spec.ts"
} |
angular/packages/compiler-cli/linker/test/ast/ast_value_spec.ts_0_6591 | /**
* @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 {WrappedNodeExpr} from '@angular/compiler';
import {TypeScriptAstFactory} from '@angular/compiler-cli/src/ngtsc/translator';
import ts from 'typescript';
import {AstHost} from '../../src/ast/ast_host';
import {AstObject, AstValue} from '../../src/ast/ast_value';
import {TypeScriptAstHost} from '../../src/ast/typescript/typescript_ast_host';
interface TestObject {
a: number;
b: string;
c: boolean;
d: {x: number; y: string};
e: number[];
missing: unknown;
}
const host: AstHost<ts.Expression> = new TypeScriptAstHost();
const factory = new TypeScriptAstFactory(/* annotateForClosureCompiler */ false);
const nestedObj = factory.createObjectLiteral([
{propertyName: 'x', quoted: false, value: factory.createLiteral(42)},
{propertyName: 'y', quoted: false, value: factory.createLiteral('X')},
]);
const nestedArray = factory.createArrayLiteral([
factory.createLiteral(1),
factory.createLiteral(2),
]);
const obj = AstObject.parse<TestObject, ts.Expression>(
factory.createObjectLiteral([
{propertyName: 'a', quoted: false, value: factory.createLiteral(42)},
{propertyName: 'b', quoted: false, value: factory.createLiteral('X')},
{propertyName: 'c', quoted: false, value: factory.createLiteral(true)},
{propertyName: 'd', quoted: false, value: nestedObj},
{propertyName: 'e', quoted: false, value: nestedArray},
]),
host,
);
describe('AstObject', () => {
describe('has()', () => {
it('should return true if the property exists on the object', () => {
expect(obj.has('a')).toBe(true);
expect(obj.has('b')).toBe(true);
expect(obj.has('missing')).toBe(false);
// @ts-expect-error
expect(obj.has('x')).toBe(false);
});
});
describe('getNumber()', () => {
it('should return the number value of the property', () => {
expect(obj.getNumber('a')).toEqual(42);
});
it('should throw an error if the property is not a number', () => {
// @ts-expect-error
expect(() => obj.getNumber('b')).toThrowError(
'Unsupported syntax, expected a numeric literal.',
);
});
});
describe('getString()', () => {
it('should return the string value of the property', () => {
expect(obj.getString('b')).toEqual('X');
});
it('should throw an error if the property is not a string', () => {
// @ts-expect-error
expect(() => obj.getString('a')).toThrowError(
'Unsupported syntax, expected a string literal.',
);
});
});
describe('getBoolean()', () => {
it('should return the boolean value of the property', () => {
expect(obj.getBoolean('c')).toEqual(true);
});
it('should throw an error if the property is not a boolean', () => {
// @ts-expect-error
expect(() => obj.getBoolean('b')).toThrowError(
'Unsupported syntax, expected a boolean literal.',
);
});
});
describe('getObject()', () => {
it('should return an AstObject instance parsed from the value of the property', () => {
expect(obj.getObject('d')).toEqual(AstObject.parse(nestedObj, host));
});
it('should throw an error if the property is not an object expression', () => {
// @ts-expect-error
expect(() => obj.getObject('b')).toThrowError(
'Unsupported syntax, expected an object literal.',
);
});
});
describe('getArray()', () => {
it('should return an array of AstValue instances of parsed from the value of the property', () => {
expect(obj.getArray('e')).toEqual([
new AstValue(factory.createLiteral(1), host),
new AstValue(factory.createLiteral(2), host),
]);
});
it('should throw an error if the property is not an array of expressions', () => {
// @ts-expect-error
expect(() => obj.getArray('b')).toThrowError(
'Unsupported syntax, expected an array literal.',
);
});
});
describe('getOpaque()', () => {
it('should return the expression value of the property wrapped in a `WrappedNodeExpr`', () => {
expect(obj.getOpaque('d')).toEqual(jasmine.any(WrappedNodeExpr));
expect(obj.getOpaque('d').node).toEqual(obj.getNode('d'));
});
it('should throw an error if the property does not exist', () => {
expect(() => obj.getOpaque('missing')).toThrowError(
`Expected property 'missing' to be present.`,
);
// @ts-expect-error
expect(() => obj.getOpaque('x')).toThrowError(`Expected property 'x' to be present.`);
});
});
describe('getNode()', () => {
it('should return the original expression value of the property', () => {
expect(obj.getNode('a')).toEqual(factory.createLiteral(42));
});
it('should throw an error if the property does not exist', () => {
expect(() => obj.getNode('missing')).toThrowError(
`Expected property 'missing' to be present.`,
);
// @ts-expect-error
expect(() => obj.getNode('x')).toThrowError(`Expected property 'x' to be present.`);
});
});
describe('getValue()', () => {
it('should return the expression value of the property wrapped in an `AstValue`', () => {
expect(obj.getValue('a')).toEqual(jasmine.any(AstValue));
expect(obj.getValue('a').getNumber()).toEqual(42);
});
it('should throw an error if the property does not exist', () => {
expect(() => obj.getValue('missing')).toThrowError(
`Expected property 'missing' to be present.`,
);
// @ts-expect-error
expect(() => obj.getValue('x')).toThrowError(`Expected property 'x' to be present.`);
});
});
describe('toLiteral()', () => {
it('should convert the AstObject to a raw object with each property mapped', () => {
expect(obj.toLiteral((value) => value.getOpaque())).toEqual({
a: obj.getOpaque('a'),
b: obj.getOpaque('b'),
c: obj.getOpaque('c'),
d: obj.getOpaque('d'),
e: obj.getOpaque('e'),
});
});
});
describe('toMap()', () => {
it('should convert the AstObject to a Map with each property mapped', () => {
expect(obj.toMap((value) => value.getOpaque())).toEqual(
new Map([
['a', obj.getOpaque('a')],
['b', obj.getOpaque('b')],
['c', obj.getOpaque('c')],
['d', obj.getOpaque('d')],
['e', obj.getOpaque('e')],
]),
);
});
});
}); | {
"end_byte": 6591,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/test/ast/ast_value_spec.ts"
} |
angular/packages/compiler-cli/linker/test/ast/ast_value_spec.ts_6593_15352 | describe('AstValue', () => {
function createAstValue<T>(node: ts.Expression): AstValue<T, ts.Expression> {
return new AstValue<T, ts.Expression>(node, host);
}
describe('getSymbolName', () => {
it('should return the name of an identifier', () => {
expect(createAstValue(factory.createIdentifier('Foo')).getSymbolName()).toEqual('Foo');
});
it('should return the name of a property access', () => {
const propertyAccess = factory.createPropertyAccess(
factory.createIdentifier('Foo'),
factory.createIdentifier('Bar'),
);
expect(createAstValue(propertyAccess).getSymbolName()).toEqual('Bar');
});
it('should return null if no symbol name is available', () => {
expect(createAstValue(factory.createLiteral('a')).getSymbolName()).toBeNull();
});
});
describe('isNumber', () => {
it('should return true if the value is a number', () => {
expect(createAstValue(factory.createLiteral(42)).isNumber()).toEqual(true);
});
it('should return false if the value is not a number', () => {
expect(createAstValue(factory.createLiteral('a')).isNumber()).toEqual(false);
});
});
describe('getNumber', () => {
it('should return the number value of the AstValue', () => {
expect(createAstValue<number>(factory.createLiteral(42)).getNumber()).toEqual(42);
});
it('should throw an error if the property is not a number', () => {
// @ts-expect-error
expect(() => createAstValue<string>(factory.createLiteral('a')).getNumber()).toThrowError(
'Unsupported syntax, expected a numeric literal.',
);
});
});
describe('isString', () => {
it('should return true if the value is a string', () => {
expect(createAstValue(factory.createLiteral('a')).isString()).toEqual(true);
});
it('should return false if the value is not a string', () => {
expect(createAstValue(factory.createLiteral(42)).isString()).toEqual(false);
});
});
describe('getString', () => {
it('should return the string value of the AstValue', () => {
expect(createAstValue<string>(factory.createLiteral('X')).getString()).toEqual('X');
});
it('should throw an error if the property is not a string', () => {
// @ts-expect-error
expect(() => createAstValue<number>(factory.createLiteral(42)).getString()).toThrowError(
'Unsupported syntax, expected a string literal.',
);
});
});
describe('isBoolean', () => {
it('should return true if the value is a boolean', () => {
expect(createAstValue(factory.createLiteral(true)).isBoolean()).toEqual(true);
});
it('should return false if the value is not a boolean', () => {
expect(createAstValue(factory.createLiteral(42)).isBoolean()).toEqual(false);
});
});
describe('getBoolean', () => {
it('should return the boolean value of the AstValue', () => {
expect(createAstValue<boolean>(factory.createLiteral(true)).getBoolean()).toEqual(true);
});
it('should throw an error if the property is not a boolean', () => {
// @ts-expect-error
expect(() => createAstValue<number>(factory.createLiteral(42)).getBoolean()).toThrowError(
'Unsupported syntax, expected a boolean literal.',
);
});
});
describe('isObject', () => {
it('should return true if the value is an object literal', () => {
expect(createAstValue(nestedObj).isObject()).toEqual(true);
});
it('should return false if the value is not an object literal', () => {
expect(createAstValue(factory.createLiteral(42)).isObject()).toEqual(false);
});
});
describe('getObject', () => {
it('should return the AstObject value of the AstValue', () => {
expect(createAstValue<object>(nestedObj).getObject()).toEqual(
AstObject.parse(nestedObj, host),
);
});
it('should throw an error if the property is not an object literal', () => {
// @ts-expect-error
expect(() => createAstValue<number>(factory.createLiteral(42)).getObject()).toThrowError(
'Unsupported syntax, expected an object literal.',
);
});
});
describe('isArray', () => {
it('should return true if the value is an array literal', () => {
expect(createAstValue(nestedArray).isArray()).toEqual(true);
});
it('should return false if the value is not an object literal', () => {
expect(createAstValue(factory.createLiteral(42)).isArray()).toEqual(false);
});
});
describe('getArray', () => {
it('should return an array of AstValue objects from the AstValue', () => {
expect(createAstValue<number[]>(nestedArray).getArray()).toEqual([
createAstValue(factory.createLiteral(1)),
createAstValue(factory.createLiteral(2)),
]);
});
it('should throw an error if the property is not an array', () => {
// @ts-expect-error
expect(() => createAstValue<number>(factory.createLiteral(42)).getArray()).toThrowError(
'Unsupported syntax, expected an array literal.',
);
});
});
describe('isFunction', () => {
it('should return true if the value is a function expression', () => {
const funcExpr = factory.createFunctionExpression(
'foo',
[],
factory.createBlock([factory.createReturnStatement(factory.createLiteral(42))]),
);
expect(createAstValue(funcExpr).isFunction()).toEqual(true);
});
it('should return false if the value is not a function expression', () => {
expect(createAstValue(factory.createLiteral(42)).isFunction()).toEqual(false);
});
});
describe('getFunctionReturnValue', () => {
it('should return the "return value" of the function expression', () => {
const funcExpr = factory.createFunctionExpression(
'foo',
[],
factory.createBlock([factory.createReturnStatement(factory.createLiteral(42))]),
);
expect(createAstValue<Function>(funcExpr).getFunctionReturnValue()).toEqual(
createAstValue(factory.createLiteral(42)),
);
});
it('should throw an error if the property is not a function expression', () => {
expect(() =>
// @ts-expect-error
createAstValue<number>(factory.createLiteral(42)).getFunctionReturnValue(),
).toThrowError('Unsupported syntax, expected a function.');
});
it('should throw an error if the property is a function expression with no return value', () => {
const funcExpr = factory.createFunctionExpression(
'foo',
[],
factory.createBlock([
factory.createExpressionStatement(factory.createLiteral('do nothing')),
]),
);
expect(() => createAstValue<Function>(funcExpr).getFunctionReturnValue()).toThrowError(
'Unsupported syntax, expected a function body with a single return statement.',
);
});
});
describe('getFunctionParameters', () => {
it('should return the parameters of a function expression', () => {
const funcExpr = factory.createFunctionExpression('foo', ['a', 'b'], factory.createBlock([]));
expect(createAstValue<Function>(funcExpr).getFunctionParameters()).toEqual(
['a', 'b'].map((name) => createAstValue(factory.createIdentifier(name))),
);
});
it('should throw an error if the property is not a function declaration', () => {
expect(() =>
// @ts-expect-error
createAstValue<number>(factory.createLiteral(42)).getFunctionParameters(),
).toThrowError('Unsupported syntax, expected a function.');
});
});
describe('isCallExpression', () => {
it('should return true if the value represents a call expression', () => {
const callExpr = factory.createCallExpression(factory.createIdentifier('foo'), [], false);
expect(createAstValue<Function>(callExpr).isCallExpression()).toBe(true);
});
it('should return false if the value does not represent a call expression', () => {
const fooExpr = factory.createIdentifier('foo');
expect(createAstValue<Function>(fooExpr).isCallExpression()).toBe(false);
});
});
describe('getCallee', () => {
it('should return the callee expression as a value', () => {
const callExpr = factory.createCallExpression(factory.createIdentifier('foo'), [], false);
expect(createAstValue<Function>(callExpr).getCallee()).toEqual(
createAstValue(factory.createIdentifier('foo')),
);
});
it('should throw an error if the value is not a call expression', () => {
expect(() => createAstValue<number>(factory.createLiteral(42)).getCallee()).toThrowError(
'Unsupported syntax, expected a call expression.',
);
});
}); | {
"end_byte": 15352,
"start_byte": 6593,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/test/ast/ast_value_spec.ts"
} |
angular/packages/compiler-cli/linker/test/ast/ast_value_spec.ts_15356_17227 | describe('getArguments', () => {
it('should return the arguments as an array of values', () => {
const callExpr = factory.createCallExpression(
factory.createIdentifier('foo'),
[factory.createLiteral(1), factory.createLiteral(2)],
false,
);
expect(createAstValue<Function>(callExpr).getArguments()).toEqual([
createAstValue(factory.createLiteral(1)),
createAstValue(factory.createLiteral(2)),
]);
});
it('should throw an error if the value is not a call expression', () => {
expect(() => createAstValue<number>(factory.createLiteral(42)).getArguments()).toThrowError(
'Unsupported syntax, expected a call expression.',
);
});
});
describe('getOpaque()', () => {
it('should return the value wrapped in a `WrappedNodeExpr`', () => {
expect(createAstValue(factory.createLiteral(42)).getOpaque()).toEqual(
jasmine.any(WrappedNodeExpr),
);
expect(createAstValue(factory.createLiteral(42)).getOpaque().node).toEqual(
factory.createLiteral(42),
);
});
});
describe('getRange()', () => {
it('should return the source range of the AST node', () => {
const file = ts.createSourceFile(
'test.ts',
"// preamble\nx = 'moo';",
ts.ScriptTarget.ES2015,
/* setParentNodes */ true,
);
// Grab the `'moo'` string literal from the generated AST
const stmt = file.statements[0] as ts.ExpressionStatement;
const mooString = (
stmt.expression as ts.AssignmentExpression<ts.Token<ts.SyntaxKind.EqualsToken>>
).right;
// Check that this string literal has the expected range.
expect(createAstValue(mooString).getRange()).toEqual({
startLine: 1,
startCol: 4,
startPos: 16,
endPos: 21,
});
});
});
}); | {
"end_byte": 17227,
"start_byte": 15356,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/test/ast/ast_value_spec.ts"
} |
angular/packages/compiler-cli/linker/test/ast/typescript/typescript_ast_host_spec.ts_0_8158 | /**
* @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 {TypeScriptAstHost} from '../../../src/ast/typescript/typescript_ast_host';
describe('TypeScriptAstHost', () => {
let host: TypeScriptAstHost;
beforeEach(() => (host = new TypeScriptAstHost()));
describe('getSymbolName()', () => {
it('should return the name of an identifier', () => {
expect(host.getSymbolName(expr('someIdentifier'))).toEqual('someIdentifier');
});
it('should return the name of an identifier at the end of a property access chain', () => {
expect(host.getSymbolName(expr('a.b.c.someIdentifier'))).toEqual('someIdentifier');
});
it('should return null if the expression has no identifier', () => {
expect(host.getSymbolName(expr('42'))).toBe(null);
});
});
describe('isStringLiteral()', () => {
it('should return true if the expression is a string literal', () => {
expect(host.isStringLiteral(expr('"moo"'))).toBe(true);
expect(host.isStringLiteral(expr("'moo'"))).toBe(true);
});
it('should return false if the expression is not a string literal', () => {
expect(host.isStringLiteral(expr('true'))).toBe(false);
expect(host.isStringLiteral(expr('someIdentifier'))).toBe(false);
expect(host.isStringLiteral(expr('42'))).toBe(false);
expect(host.isStringLiteral(rhs('x = {}'))).toBe(false);
expect(host.isStringLiteral(expr('[]'))).toBe(false);
expect(host.isStringLiteral(expr('null'))).toBe(false);
expect(host.isStringLiteral(expr("'a' + 'b'"))).toBe(false);
});
it('should return false if the expression is a template string', () => {
expect(host.isStringLiteral(expr('`moo`'))).toBe(false);
});
});
describe('parseStringLiteral()', () => {
it('should extract the string value', () => {
expect(host.parseStringLiteral(expr('"moo"'))).toEqual('moo');
expect(host.parseStringLiteral(expr("'moo'"))).toEqual('moo');
});
it('should error if the value is not a string literal', () => {
expect(() => host.parseStringLiteral(expr('42'))).toThrowError(
'Unsupported syntax, expected a string literal.',
);
});
});
describe('isNumericLiteral()', () => {
it('should return true if the expression is a number literal', () => {
expect(host.isNumericLiteral(expr('42'))).toBe(true);
});
it('should return false if the expression is not a number literal', () => {
expect(host.isStringLiteral(expr('true'))).toBe(false);
expect(host.isNumericLiteral(expr('"moo"'))).toBe(false);
expect(host.isNumericLiteral(expr("'moo'"))).toBe(false);
expect(host.isNumericLiteral(expr('someIdentifier'))).toBe(false);
expect(host.isNumericLiteral(rhs('x = {}'))).toBe(false);
expect(host.isNumericLiteral(expr('[]'))).toBe(false);
expect(host.isNumericLiteral(expr('null'))).toBe(false);
expect(host.isNumericLiteral(expr("'a' + 'b'"))).toBe(false);
expect(host.isNumericLiteral(expr('`moo`'))).toBe(false);
});
});
describe('parseNumericLiteral()', () => {
it('should extract the number value', () => {
expect(host.parseNumericLiteral(expr('42'))).toEqual(42);
});
it('should error if the value is not a numeric literal', () => {
expect(() => host.parseNumericLiteral(expr('"moo"'))).toThrowError(
'Unsupported syntax, expected a numeric literal.',
);
});
});
describe('isBooleanLiteral()', () => {
it('should return true if the expression is a boolean literal', () => {
expect(host.isBooleanLiteral(expr('true'))).toBe(true);
expect(host.isBooleanLiteral(expr('false'))).toBe(true);
});
it('should return true if the expression is a minified boolean literal', () => {
expect(host.isBooleanLiteral(expr('!0'))).toBe(true);
expect(host.isBooleanLiteral(expr('!1'))).toBe(true);
});
it('should return false if the expression is not a boolean literal', () => {
expect(host.isBooleanLiteral(expr('"moo"'))).toBe(false);
expect(host.isBooleanLiteral(expr("'moo'"))).toBe(false);
expect(host.isBooleanLiteral(expr('someIdentifier'))).toBe(false);
expect(host.isBooleanLiteral(expr('42'))).toBe(false);
expect(host.isBooleanLiteral(rhs('x = {}'))).toBe(false);
expect(host.isBooleanLiteral(expr('[]'))).toBe(false);
expect(host.isBooleanLiteral(expr('null'))).toBe(false);
expect(host.isBooleanLiteral(expr("'a' + 'b'"))).toBe(false);
expect(host.isBooleanLiteral(expr('`moo`'))).toBe(false);
expect(host.isBooleanLiteral(expr('!2'))).toBe(false);
expect(host.isBooleanLiteral(expr('~1'))).toBe(false);
});
});
describe('parseBooleanLiteral()', () => {
it('should extract the boolean value', () => {
expect(host.parseBooleanLiteral(expr('true'))).toEqual(true);
expect(host.parseBooleanLiteral(expr('false'))).toEqual(false);
});
it('should extract a minified boolean value', () => {
expect(host.parseBooleanLiteral(expr('!0'))).toEqual(true);
expect(host.parseBooleanLiteral(expr('!1'))).toEqual(false);
});
it('should error if the value is not a boolean literal', () => {
expect(() => host.parseBooleanLiteral(expr('"moo"'))).toThrowError(
'Unsupported syntax, expected a boolean literal.',
);
});
});
describe('isArrayLiteral()', () => {
it('should return true if the expression is an array literal', () => {
expect(host.isArrayLiteral(expr('[]'))).toBe(true);
expect(host.isArrayLiteral(expr('[1, 2, 3]'))).toBe(true);
expect(host.isArrayLiteral(expr('[[], []]'))).toBe(true);
});
it('should return false if the expression is not an array literal', () => {
expect(host.isArrayLiteral(expr('"moo"'))).toBe(false);
expect(host.isArrayLiteral(expr("'moo'"))).toBe(false);
expect(host.isArrayLiteral(expr('someIdentifier'))).toBe(false);
expect(host.isArrayLiteral(expr('42'))).toBe(false);
expect(host.isArrayLiteral(rhs('x = {}'))).toBe(false);
expect(host.isArrayLiteral(expr('null'))).toBe(false);
expect(host.isArrayLiteral(expr("'a' + 'b'"))).toBe(false);
expect(host.isArrayLiteral(expr('`moo`'))).toBe(false);
});
});
describe('parseArrayLiteral()', () => {
it('should extract the expressions in the array', () => {
const moo = jasmine.objectContaining({text: 'moo', kind: ts.SyntaxKind.StringLiteral});
expect(host.parseArrayLiteral(expr('[]'))).toEqual([]);
expect(host.parseArrayLiteral(expr("['moo']"))).toEqual([moo]);
});
it('should error if there is an empty item', () => {
expect(() => host.parseArrayLiteral(expr('[,]'))).toThrowError(
'Unsupported syntax, expected element in array not to be empty.',
);
});
it('should error if there is a spread element', () => {
expect(() => host.parseArrayLiteral(expr('[...[0,1]]'))).toThrowError(
'Unsupported syntax, expected element in array not to use spread syntax.',
);
});
});
describe('isObjectLiteral()', () => {
it('should return true if the expression is an object literal', () => {
expect(host.isObjectLiteral(rhs('x = {}'))).toBe(true);
expect(host.isObjectLiteral(rhs("x = { foo: 'bar' }"))).toBe(true);
});
it('should return false if the expression is not an object literal', () => {
expect(host.isObjectLiteral(rhs('x = "moo"'))).toBe(false);
expect(host.isObjectLiteral(rhs("x = 'moo'"))).toBe(false);
expect(host.isObjectLiteral(rhs('x = someIdentifier'))).toBe(false);
expect(host.isObjectLiteral(rhs('x = 42'))).toBe(false);
expect(host.isObjectLiteral(rhs('x = []'))).toBe(false);
expect(host.isObjectLiteral(rhs('x = null'))).toBe(false);
expect(host.isObjectLiteral(rhs("x = 'a' + 'b'"))).toBe(false);
expect(host.isObjectLiteral(rhs('x = `moo`'))).toBe(false);
});
}); | {
"end_byte": 8158,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/test/ast/typescript/typescript_ast_host_spec.ts"
} |
angular/packages/compiler-cli/linker/test/ast/typescript/typescript_ast_host_spec.ts_8162_16349 | describe('parseObjectLiteral()', () => {
it('should extract the properties from the object', () => {
const moo = jasmine.objectContaining({text: 'moo', kind: ts.SyntaxKind.StringLiteral});
expect(host.parseObjectLiteral(rhs('x = {}'))).toEqual(new Map());
expect(host.parseObjectLiteral(rhs("x = {a: 'moo'}"))).toEqual(new Map([['a', moo]]));
});
it('should error if there is a method', () => {
expect(() => host.parseObjectLiteral(rhs('x = { foo() {} }'))).toThrowError(
'Unsupported syntax, expected a property assignment.',
);
});
it('should error if there is a spread element', () => {
expect(() => host.parseObjectLiteral(rhs("x = {...{ a: 'moo' }}"))).toThrowError(
'Unsupported syntax, expected a property assignment.',
);
});
});
describe('isFunctionExpression()', () => {
it('should return true if the expression is a function', () => {
expect(host.isFunctionExpression(rhs('x = function() {}'))).toBe(true);
expect(host.isFunctionExpression(rhs('x = function foo() {}'))).toBe(true);
expect(host.isFunctionExpression(rhs('x = () => {}'))).toBe(true);
expect(host.isFunctionExpression(rhs('x = () => true'))).toBe(true);
});
it('should return false if the expression is not a function', () => {
expect(host.isFunctionExpression(expr('[]'))).toBe(false);
expect(host.isFunctionExpression(expr('"moo"'))).toBe(false);
expect(host.isFunctionExpression(expr("'moo'"))).toBe(false);
expect(host.isFunctionExpression(expr('someIdentifier'))).toBe(false);
expect(host.isFunctionExpression(expr('42'))).toBe(false);
expect(host.isFunctionExpression(rhs('x = {}'))).toBe(false);
expect(host.isFunctionExpression(expr('null'))).toBe(false);
expect(host.isFunctionExpression(expr("'a' + 'b'"))).toBe(false);
expect(host.isFunctionExpression(expr('`moo`'))).toBe(false);
});
});
describe('parseReturnValue()', () => {
it('should extract the return value of a function', () => {
const moo = jasmine.objectContaining({text: 'moo', kind: ts.SyntaxKind.StringLiteral});
expect(host.parseReturnValue(rhs("x = function() { return 'moo'; }"))).toEqual(moo);
});
it('should extract the value of a simple arrow function', () => {
const moo = jasmine.objectContaining({text: 'moo', kind: ts.SyntaxKind.StringLiteral});
expect(host.parseReturnValue(rhs("x = () => 'moo'"))).toEqual(moo);
});
it('should extract the return value of an arrow function', () => {
const moo = jasmine.objectContaining({text: 'moo', kind: ts.SyntaxKind.StringLiteral});
expect(host.parseReturnValue(rhs("x = () => { return 'moo' }"))).toEqual(moo);
});
it('should error if the body has 0 statements', () => {
expect(() => host.parseReturnValue(rhs('x = function () { }'))).toThrowError(
'Unsupported syntax, expected a function body with a single return statement.',
);
expect(() => host.parseReturnValue(rhs('x = () => { }'))).toThrowError(
'Unsupported syntax, expected a function body with a single return statement.',
);
});
it('should error if the body has more than 1 statement', () => {
expect(() =>
host.parseReturnValue(rhs('x = function () { const x = 10; return x; }')),
).toThrowError(
'Unsupported syntax, expected a function body with a single return statement.',
);
expect(() =>
host.parseReturnValue(rhs('x = () => { const x = 10; return x; }')),
).toThrowError(
'Unsupported syntax, expected a function body with a single return statement.',
);
});
it('should error if the single statement is not a return statement', () => {
expect(() => host.parseReturnValue(rhs('x = function () { const x = 10; }'))).toThrowError(
'Unsupported syntax, expected a function body with a single return statement.',
);
expect(() => host.parseReturnValue(rhs('x = () => { const x = 10; }'))).toThrowError(
'Unsupported syntax, expected a function body with a single return statement.',
);
});
});
describe('parseParameters()', () => {
it('should return the parameters as an array of expressions', () => {
const arg1 = jasmine.objectContaining({text: 'a', kind: ts.SyntaxKind.Identifier});
const arg2 = jasmine.objectContaining({text: 'b', kind: ts.SyntaxKind.Identifier});
expect(host.parseParameters(rhs('x = function (a, b) {}'))).toEqual([arg1, arg2]);
expect(host.parseParameters(rhs('x = (a, b) => {}'))).toEqual([arg1, arg2]);
});
it('should error if the node is not a function declaration or arrow function', () => {
expect(() => host.parseParameters(expr('[]'))).toThrowError(
'Unsupported syntax, expected a function.',
);
});
it('should error if a parameter uses spread syntax', () => {
expect(() => host.parseParameters(rhs('x = function(a, ...other) {}'))).toThrowError(
'Unsupported syntax, expected an identifier.',
);
});
});
describe('isCallExpression()', () => {
it('should return true if the expression is a call expression', () => {
expect(host.isCallExpression(expr('foo()'))).toBe(true);
expect(host.isCallExpression(expr('foo.bar()'))).toBe(true);
expect(host.isCallExpression(expr('(foo)(1)'))).toBe(true);
});
it('should return false if the expression is not a call expression', () => {
expect(host.isCallExpression(expr('[]'))).toBe(false);
expect(host.isCallExpression(expr('"moo"'))).toBe(false);
expect(host.isCallExpression(expr("'moo'"))).toBe(false);
expect(host.isCallExpression(expr('someIdentifier'))).toBe(false);
expect(host.isCallExpression(expr('42'))).toBe(false);
expect(host.isCallExpression(rhs('x = {}'))).toBe(false);
expect(host.isCallExpression(expr('null'))).toBe(false);
expect(host.isCallExpression(expr("'a' + 'b'"))).toBe(false);
expect(host.isCallExpression(expr('`moo`'))).toBe(false);
});
});
describe('parseCallee()', () => {
it('should return the callee expression', () => {
const foo = jasmine.objectContaining({text: 'foo', kind: ts.SyntaxKind.Identifier});
const bar = jasmine.objectContaining({kind: ts.SyntaxKind.PropertyAccessExpression});
expect(host.parseCallee(expr('foo()'))).toEqual(foo);
expect(host.parseCallee(expr('foo.bar()'))).toEqual(bar);
});
it('should error if the node is not a call expression', () => {
expect(() => host.parseCallee(expr('[]'))).toThrowError(
'Unsupported syntax, expected a call expression.',
);
});
});
describe('parseArguments()', () => {
it('should return the arguments as an array of expressions', () => {
const arg1 = jasmine.objectContaining({text: '12', kind: ts.SyntaxKind.NumericLiteral});
const arg2 = jasmine.objectContaining({kind: ts.SyntaxKind.ArrayLiteralExpression});
expect(host.parseArguments(expr('foo(12, [])'))).toEqual([arg1, arg2]);
expect(host.parseArguments(expr('foo.bar()'))).toEqual([]);
});
it('should error if the node is not a call expression', () => {
expect(() => host.parseArguments(expr('[]'))).toThrowError(
'Unsupported syntax, expected a call expression.',
);
});
it('should error if an argument uses spread syntax', () => {
expect(() => host.parseArguments(expr('foo(1, ...[])'))).toThrowError(
'Unsupported syntax, expected argument not to use spread syntax.',
);
});
});
describe('getRange()', () => {
it('should extract the range from the expression', () => {
const moo = rhs("// preamble\nx = 'moo';");
expect(host.getRange(moo)).toEqual({startLine: 1, startCol: 4, startPos: 16, endPos: 21});
});
it('should error if the nodes do not have attached parents', () => {
const moo = rhs("// preamble\nx = 'moo';", false);
expect(() => host.getRange(moo)).toThrowError(
'Unable to read range for node - it is missing parent information.',
);
});
});
}); | {
"end_byte": 16349,
"start_byte": 8162,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/test/ast/typescript/typescript_ast_host_spec.ts"
} |
angular/packages/compiler-cli/linker/test/ast/typescript/typescript_ast_host_spec.ts_16351_16909 | function stmt(code: string, attachParents = true): ts.Statement {
const sf = ts.createSourceFile('test.ts', code, ts.ScriptTarget.ES2015, attachParents);
return sf.statements[0];
}
function expr(code: string, attachParents = true): ts.Expression {
return (stmt(code, attachParents) as ts.ExpressionStatement).expression;
}
function rhs(code: string, attachParents = true): ts.Expression {
const e = expr(code, attachParents);
if (!ts.isBinaryExpression(e)) {
throw new Error('Bad test - expected a binary expression');
}
return e.right;
} | {
"end_byte": 16909,
"start_byte": 16351,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/test/ast/typescript/typescript_ast_host_spec.ts"
} |
angular/packages/compiler-cli/linker/test/file_linker/helpers.ts_0_559 | /**
* @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';
/**
* A simple helper to render a TS Node as a string.
*/
export function generate(node: ts.Node): string {
const printer = ts.createPrinter({newLine: ts.NewLineKind.LineFeed});
const sf = ts.createSourceFile('test.ts', '', ts.ScriptTarget.ES2015, true);
return printer.printNode(ts.EmitHint.Unspecified, node, sf);
}
| {
"end_byte": 559,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/test/file_linker/helpers.ts"
} |
angular/packages/compiler-cli/linker/test/file_linker/translator_spec.ts_0_1792 | /**
* @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 * as o from '@angular/compiler';
import {TypeScriptAstFactory} from '@angular/compiler-cli/src/ngtsc/translator';
import ts from 'typescript';
import {Translator} from '../../src/file_linker/translator';
import {LinkerImportGenerator} from '../../src/linker_import_generator';
import {generate} from './helpers';
const ngImport = ts.factory.createIdentifier('ngImport');
describe('Translator', () => {
let factory: TypeScriptAstFactory;
let importGenerator: LinkerImportGenerator<ts.Statement, ts.Expression>;
beforeEach(() => {
factory = new TypeScriptAstFactory(/* annotateForClosureCompiler */ false);
importGenerator = new LinkerImportGenerator<ts.Statement, ts.Expression>(factory, ngImport);
});
describe('translateExpression()', () => {
it('should generate expression specific output', () => {
const translator = new Translator<ts.Statement, ts.Expression>(factory);
const outputAst = new o.WriteVarExpr('foo', new o.LiteralExpr(42));
const translated = translator.translateExpression(outputAst, importGenerator);
expect(generate(translated)).toEqual('(foo = 42)');
});
});
describe('translateStatement()', () => {
it('should generate statement specific output', () => {
const translator = new Translator<ts.Statement, ts.Expression>(factory);
const outputAst = new o.ExpressionStatement(new o.WriteVarExpr('foo', new o.LiteralExpr(42)));
const translated = translator.translateStatement(outputAst, importGenerator);
expect(generate(translated)).toEqual('foo = 42;');
});
});
});
| {
"end_byte": 1792,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/test/file_linker/translator_spec.ts"
} |
angular/packages/compiler-cli/linker/test/file_linker/file_linker_spec.ts_0_7760 | /**
* @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 * as o from '@angular/compiler/src/output/output_ast';
import ts from 'typescript';
import {MockFileSystemNative} from '../../../src/ngtsc/file_system/testing';
import {MockLogger} from '../../../src/ngtsc/logging/testing';
import {TypeScriptAstFactory} from '../../../src/ngtsc/translator';
import {AstHost} from '../../src/ast/ast_host';
import {TypeScriptAstHost} from '../../src/ast/typescript/typescript_ast_host';
import {DeclarationScope} from '../../src/file_linker/declaration_scope';
import {FileLinker} from '../../src/file_linker/file_linker';
import {LinkerEnvironment} from '../../src/file_linker/linker_environment';
import {DEFAULT_LINKER_OPTIONS} from '../../src/file_linker/linker_options';
import {PartialDirectiveLinkerVersion1} from '../../src/file_linker/partial_linkers/partial_directive_linker_1';
import {generate} from './helpers';
describe('FileLinker', () => {
let factory: TypeScriptAstFactory;
beforeEach(() => (factory = new TypeScriptAstFactory(/* annotateForClosureCompiler */ false)));
describe('isPartialDeclaration()', () => {
it('should return true if the callee is recognized', () => {
const {fileLinker} = createFileLinker();
expect(fileLinker.isPartialDeclaration('ɵɵngDeclareDirective')).toBe(true);
expect(fileLinker.isPartialDeclaration('ɵɵngDeclareComponent')).toBe(true);
});
it('should return false if the callee is not recognized', () => {
const {fileLinker} = createFileLinker();
expect(fileLinker.isPartialDeclaration('$foo')).toBe(false);
});
});
describe('linkPartialDeclaration()', () => {
it('should throw an error if the function name is not recognised', () => {
const {fileLinker} = createFileLinker();
const version = factory.createLiteral('0.0.0-PLACEHOLDER');
const ngImport = factory.createIdentifier('core');
const declarationArg = factory.createObjectLiteral([
{propertyName: 'minVersion', quoted: false, value: version},
{propertyName: 'version', quoted: false, value: version},
{propertyName: 'ngImport', quoted: false, value: ngImport},
]);
expect(() =>
fileLinker.linkPartialDeclaration('foo', [declarationArg], new MockDeclarationScope()),
).toThrowError('Unknown partial declaration function foo.');
});
it('should throw an error if the metadata object does not have a `minVersion` property', () => {
const {fileLinker} = createFileLinker();
const version = factory.createLiteral('0.0.0-PLACEHOLDER');
const ngImport = factory.createIdentifier('core');
const declarationArg = factory.createObjectLiteral([
{propertyName: 'version', quoted: false, value: version},
{propertyName: 'ngImport', quoted: false, value: ngImport},
]);
expect(() =>
fileLinker.linkPartialDeclaration(
'ɵɵngDeclareDirective',
[declarationArg],
new MockDeclarationScope(),
),
).toThrowError(`Expected property 'minVersion' to be present.`);
});
it('should throw an error if the metadata object does not have a `version` property', () => {
const {fileLinker} = createFileLinker();
const version = factory.createLiteral('0.0.0-PLACEHOLDER');
const ngImport = factory.createIdentifier('core');
const declarationArg = factory.createObjectLiteral([
{propertyName: 'minVersion', quoted: false, value: version},
{propertyName: 'ngImport', quoted: false, value: ngImport},
]);
expect(() =>
fileLinker.linkPartialDeclaration(
'ɵɵngDeclareDirective',
[declarationArg],
new MockDeclarationScope(),
),
).toThrowError(`Expected property 'version' to be present.`);
});
it('should throw an error if the metadata object does not have a `ngImport` property', () => {
const {fileLinker} = createFileLinker();
const version = factory.createLiteral('0.0.0-PLACEHOLDER');
const declarationArg = factory.createObjectLiteral([
{propertyName: 'minVersion', quoted: false, value: version},
{propertyName: 'version', quoted: false, value: version},
]);
expect(() =>
fileLinker.linkPartialDeclaration(
'ɵɵngDeclareDirective',
[declarationArg],
new MockDeclarationScope(),
),
).toThrowError(`Expected property 'ngImport' to be present.`);
});
it('should call `linkPartialDeclaration()` on the appropriate partial compiler', () => {
const {fileLinker} = createFileLinker();
const compileSpy = spyOn(
PartialDirectiveLinkerVersion1.prototype,
'linkPartialDeclaration',
).and.returnValue({
expression: o.literal('compilation result'),
statements: [],
});
const ngImport = factory.createIdentifier('core');
const version = factory.createLiteral('0.0.0-PLACEHOLDER');
const declarationArg = factory.createObjectLiteral([
{propertyName: 'ngImport', quoted: false, value: ngImport},
{propertyName: 'minVersion', quoted: false, value: version},
{propertyName: 'version', quoted: false, value: version},
]);
const compilationResult = fileLinker.linkPartialDeclaration(
'ɵɵngDeclareDirective',
[declarationArg],
new MockDeclarationScope(),
);
expect(compilationResult).toEqual(factory.createLiteral('compilation result'));
expect(compileSpy).toHaveBeenCalled();
expect(compileSpy.calls.mostRecent().args[1].getNode('ngImport')).toBe(ngImport);
});
});
describe('block syntax support', () => {
function linkComponentWithTemplate(version: string, template: string): string {
// Note that the `minVersion` is set to the placeholder,
// because that's what we have in the source code as well.
const source = `
ɵɵngDeclareComponent({
minVersion: "0.0.0-PLACEHOLDER",
version: "${version}",
ngImport: core,
template: \`${template}\`,
isInline: true,
type: SomeComp
});
`;
// We need to create a new source file here, because template parsing requires
// the template string to have offsets which synthetic nodes do not.
const {fileLinker} = createFileLinker(source);
const sourceFile = ts.createSourceFile('', source, ts.ScriptTarget.Latest, true);
const call = (sourceFile.statements[0] as ts.ExpressionStatement)
.expression as ts.CallExpression;
const result = fileLinker.linkPartialDeclaration(
'ɵɵngDeclareComponent',
[call.arguments[0]],
new MockDeclarationScope(),
);
return ts.createPrinter().printNode(ts.EmitHint.Unspecified, result, sourceFile);
}
it('should enable block syntax if compiled with version 17 or above', () => {
for (const version of ['17.0.0', '17.0.1', '17.1.0', '17.0.0-next.0', '18.0.0']) {
expect(linkComponentWithTemplate(version, '@defer {}')).toContain('ɵɵdefer(');
}
});
it('should enable block syntax if compiled with a local version', () => {
expect(linkComponentWithTemplate('0.0.0-PLACEHOLDER', '@defer {}')).toContain('ɵɵdefer(');
});
it('should not enable block syntax if compiled with a version older than 17', () => {
expect(
linkComponentWithTemplate('16.2.0', '@Input() is a decorator. This is a brace }'),
).toContain('@Input() is a decorator. This is a brace }');
});
});
describe('getCon | {
"end_byte": 7760,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/test/file_linker/file_linker_spec.ts"
} |
angular/packages/compiler-cli/linker/test/file_linker/file_linker_spec.ts_7764_12483 | tStatements()', () => {
it('should capture shared constant values', () => {
const {fileLinker} = createFileLinker();
spyOnLinkPartialDeclarationWithConstants(o.literal('REPLACEMENT'));
// Here we use the `core` identifier for `ngImport` to trigger the use of a shared scope for
// constant statements.
const declarationArg = factory.createObjectLiteral([
{propertyName: 'ngImport', quoted: false, value: factory.createIdentifier('core')},
{
propertyName: 'minVersion',
quoted: false,
value: factory.createLiteral('0.0.0-PLACEHOLDER'),
},
{propertyName: 'version', quoted: false, value: factory.createLiteral('0.0.0-PLACEHOLDER')},
]);
const replacement = fileLinker.linkPartialDeclaration(
'ɵɵngDeclareDirective',
[declarationArg],
new MockDeclarationScope(),
);
expect(generate(replacement)).toEqual('"REPLACEMENT"');
const results = fileLinker.getConstantStatements();
expect(results.length).toEqual(1);
const {constantScope, statements} = results[0];
expect(constantScope).toBe(MockConstantScopeRef.singleton);
expect(statements.map(generate)).toEqual(['const _c0 = [1];']);
});
it('should be no shared constant statements to capture when they are emitted into the replacement IIFE', () => {
const {fileLinker} = createFileLinker();
spyOnLinkPartialDeclarationWithConstants(o.literal('REPLACEMENT'));
// Here we use a string literal `"not-a-module"` for `ngImport` to cause constant
// statements to be emitted in an IIFE rather than added to the shared constant scope.
const declarationArg = factory.createObjectLiteral([
{propertyName: 'ngImport', quoted: false, value: factory.createLiteral('not-a-module')},
{
propertyName: 'minVersion',
quoted: false,
value: factory.createLiteral('0.0.0-PLACEHOLDER'),
},
{
propertyName: 'version',
quoted: false,
value: factory.createLiteral('0.0.0-PLACEHOLDER'),
},
]);
const replacement = fileLinker.linkPartialDeclaration(
'ɵɵngDeclareDirective',
[declarationArg],
new MockDeclarationScope(),
);
expect(generate(replacement)).toEqual(
'function () { const _c0 = [1]; return "REPLACEMENT"; }()',
);
const results = fileLinker.getConstantStatements();
expect(results.length).toEqual(0);
});
});
function createFileLinker(code = '// test code'): {
host: AstHost<ts.Expression>;
fileLinker: FileLinker<MockConstantScopeRef, ts.Statement, ts.Expression>;
} {
const fs = new MockFileSystemNative();
const logger = new MockLogger();
const linkerEnvironment = LinkerEnvironment.create<ts.Statement, ts.Expression>(
fs,
logger,
new TypeScriptAstHost(),
new TypeScriptAstFactory(/* annotateForClosureCompiler */ false),
DEFAULT_LINKER_OPTIONS,
);
const fileLinker = new FileLinker<MockConstantScopeRef, ts.Statement, ts.Expression>(
linkerEnvironment,
fs.resolve('/test.js'),
code,
);
return {host: linkerEnvironment.host, fileLinker};
}
});
/**
* This mock implementation of `DeclarationScope` will return a singleton instance of
* `MockConstantScopeRef` if the expression is an identifier, or `null` otherwise.
*
* This way we can simulate whether the constants will be shared or inlined into an IIFE.
*/
class MockDeclarationScope implements DeclarationScope<MockConstantScopeRef, ts.Expression> {
getConstantScopeRef(expression: ts.Expression): MockConstantScopeRef | null {
if (ts.isIdentifier(expression)) {
return MockConstantScopeRef.singleton;
} else {
return null;
}
}
}
class MockConstantScopeRef {
private constructor() {}
static singleton = new MockDeclarationScope();
}
/**
* Spy on the `PartialDirectiveLinkerVersion1.linkPartialDeclaration()` method, triggering
* shared constants to be created.
*/
function spyOnLinkPartialDeclarationWithConstants(replacement: o.Expression) {
let callCount = 0;
spyOn(PartialDirectiveLinkerVersion1.prototype, 'linkPartialDeclaration').and.callFake(((
constantPool,
) => {
const constArray = o.literalArr([o.literal(++callCount)]);
// We have to add the constant twice or it will not create a shared statement
constantPool.getConstLiteral(constArray);
constantPool.getConstLiteral(constArray);
return {
expression: replacement,
statements: [],
};
}) as typeof PartialDirectiveLinkerVersion1.prototype.linkPartialDeclaration);
}
| {
"end_byte": 12483,
"start_byte": 7764,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/test/file_linker/file_linker_spec.ts"
} |
angular/packages/compiler-cli/linker/test/file_linker/needs_linking_spec.ts_0_2259 | /**
* @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 {needsLinking} from '../../src/file_linker/needs_linking';
describe('needsLinking', () => {
it('should return true for directive declarations', () => {
expect(
needsLinking(
'file.js',
`
export class Dir {
ɵdir = ɵɵngDeclareDirective({type: Dir});
}
`,
),
).toBeTrue();
});
it('should return true for namespaced directive declarations', () => {
expect(
needsLinking(
'file.js',
`
export class Dir {
ɵdir = ng.ɵɵngDeclareDirective({type: Dir});
}
`,
),
).toBeTrue();
});
it('should return true for unrelated usages of ɵɵngDeclareDirective', () => {
expect(
needsLinking(
'file.js',
`
const fnName = 'ɵɵngDeclareDirective';
`,
),
).toBeTrue();
});
it('should return false when the file does not contain ɵɵngDeclareDirective', () => {
expect(
needsLinking(
'file.js',
`
const foo = ngDeclareDirective;
`,
),
).toBeFalse();
});
it('should return true for component declarations', () => {
expect(
needsLinking(
'file.js',
`
export class Cmp {
ɵdir = ɵɵngDeclareComponent({type: Cmp});
}
`,
),
).toBeTrue();
});
it('should return true for namespaced component declarations', () => {
expect(
needsLinking(
'file.js',
`
export class Cmp {
ɵdir = ng.ɵɵngDeclareComponent({type: Cmp});
}
`,
),
).toBeTrue();
});
it('should return true for unrelated usages of ɵɵngDeclareComponent', () => {
expect(
needsLinking(
'file.js',
`
const fnName = 'ɵɵngDeclareComponent';
`,
),
).toBeTrue();
});
it('should return false when the file does not contain ɵɵngDeclareComponent', () => {
expect(
needsLinking(
'file.js',
`
const foo = ngDeclareComponent;
`,
),
).toBeFalse();
});
});
| {
"end_byte": 2259,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/test/file_linker/needs_linking_spec.ts"
} |
angular/packages/compiler-cli/linker/test/file_linker/emit_scopes/emit_scope_spec.ts_0_4393 | /**
* @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 * as o from '@angular/compiler/src/output/output_ast';
import ts from 'typescript';
import {TypeScriptAstFactory} from '../../../../src/ngtsc/translator';
import {EmitScope} from '../../../src/file_linker/emit_scopes/emit_scope';
import {Translator} from '../../../src/file_linker/translator';
import {generate} from '../helpers';
describe('EmitScope', () => {
describe('translateDefinition()', () => {
it('should translate the given output AST into a TExpression', () => {
const factory = new TypeScriptAstFactory(/* annotateForClosureCompiler */ false);
const translator = new Translator<ts.Statement, ts.Expression>(factory);
const ngImport = factory.createIdentifier('core');
const emitScope = new EmitScope<ts.Statement, ts.Expression>(ngImport, translator, factory);
const def = emitScope.translateDefinition({
expression: o.fn([], [], null, null, 'foo'),
statements: [],
});
expect(generate(def)).toEqual('function foo() { }');
});
it('should use an IIFE if the definition being emitted includes associated statements', () => {
const factory = new TypeScriptAstFactory(/* annotateForClosureCompiler */ false);
const translator = new Translator<ts.Statement, ts.Expression>(factory);
const ngImport = factory.createIdentifier('core');
const emitScope = new EmitScope<ts.Statement, ts.Expression>(ngImport, translator, factory);
const def = emitScope.translateDefinition({
expression: o.fn([], [], null, null, 'foo'),
statements: [o.variable('testFn').callFn([]).toStmt()],
});
expect(generate(def)).toEqual('function () { testFn(); return function foo() { }; }()');
});
it('should use the `ngImport` identifier for imports when translating', () => {
const factory = new TypeScriptAstFactory(/* annotateForClosureCompiler */ false);
const translator = new Translator<ts.Statement, ts.Expression>(factory);
const ngImport = factory.createIdentifier('core');
const emitScope = new EmitScope<ts.Statement, ts.Expression>(ngImport, translator, factory);
const coreImportRef = new o.ExternalReference('@angular/core', 'foo');
const def = emitScope.translateDefinition({
expression: o.importExpr(coreImportRef).prop('bar').callFn([]),
statements: [],
});
expect(generate(def)).toEqual('core.foo.bar()');
});
it('should not emit any shared constants in the replacement expression', () => {
const factory = new TypeScriptAstFactory(/* annotateForClosureCompiler */ false);
const translator = new Translator<ts.Statement, ts.Expression>(factory);
const ngImport = factory.createIdentifier('core');
const emitScope = new EmitScope<ts.Statement, ts.Expression>(ngImport, translator, factory);
const constArray = o.literalArr([o.literal('CONST')]);
// We have to add the constant twice or it will not create a shared statement
emitScope.constantPool.getConstLiteral(constArray);
emitScope.constantPool.getConstLiteral(constArray);
const def = emitScope.translateDefinition({
expression: o.fn([], [], null, null, 'foo'),
statements: [],
});
expect(generate(def)).toEqual('function foo() { }');
});
});
describe('getConstantStatements()', () => {
it('should return any constant statements that were added to the `constantPool`', () => {
const factory = new TypeScriptAstFactory(/* annotateForClosureCompiler */ false);
const translator = new Translator<ts.Statement, ts.Expression>(factory);
const ngImport = factory.createIdentifier('core');
const emitScope = new EmitScope<ts.Statement, ts.Expression>(ngImport, translator, factory);
const constArray = o.literalArr([o.literal('CONST')]);
// We have to add the constant twice or it will not create a shared statement
emitScope.constantPool.getConstLiteral(constArray);
emitScope.constantPool.getConstLiteral(constArray);
const statements = emitScope.getConstantStatements();
expect(statements.map(generate)).toEqual(['const _c0 = ["CONST"];']);
});
});
});
| {
"end_byte": 4393,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/test/file_linker/emit_scopes/emit_scope_spec.ts"
} |
angular/packages/compiler-cli/linker/test/file_linker/emit_scopes/local_emit_scope_spec.ts_0_3793 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ConstantPool} from '@angular/compiler';
import * as o from '@angular/compiler/src/output/output_ast';
import ts from 'typescript';
import {TypeScriptAstFactory} from '../../../../src/ngtsc/translator';
import {LocalEmitScope} from '../../../src/file_linker/emit_scopes/local_emit_scope';
import {Translator} from '../../../src/file_linker/translator';
import {generate} from '../helpers';
describe('LocalEmitScope', () => {
describe('translateDefinition()', () => {
it('should translate the given output AST into a TExpression, wrapped in an IIFE', () => {
const factory = new TypeScriptAstFactory(/* annotateForClosureCompiler */ false);
const translator = new Translator<ts.Statement, ts.Expression>(factory);
const ngImport = factory.createIdentifier('core');
const emitScope = new LocalEmitScope<ts.Statement, ts.Expression>(
ngImport,
translator,
factory,
);
addSharedStatement(emitScope.constantPool);
const def = emitScope.translateDefinition({
expression: o.fn([], [], null, null, 'foo'),
statements: [],
});
expect(generate(def)).toEqual(
'function () { const _c0 = ["CONST"]; return function foo() { }; }()',
);
});
it('should use the `ngImport` identifier for imports when translating', () => {
const factory = new TypeScriptAstFactory(/* annotateForClosureCompiler */ false);
const translator = new Translator<ts.Statement, ts.Expression>(factory);
const ngImport = factory.createIdentifier('core');
const emitScope = new LocalEmitScope<ts.Statement, ts.Expression>(
ngImport,
translator,
factory,
);
addSharedStatement(emitScope.constantPool);
const coreImportRef = new o.ExternalReference('@angular/core', 'foo');
const def = emitScope.translateDefinition({
expression: o.importExpr(coreImportRef).prop('bar').callFn([]),
statements: [],
});
expect(generate(def)).toEqual(
'function () { const _c0 = ["CONST"]; return core.foo.bar(); }()',
);
});
it('should not emit an IIFE if there are no shared constants', () => {
const factory = new TypeScriptAstFactory(/* annotateForClosureCompiler */ false);
const translator = new Translator<ts.Statement, ts.Expression>(factory);
const ngImport = factory.createIdentifier('core');
const emitScope = new LocalEmitScope<ts.Statement, ts.Expression>(
ngImport,
translator,
factory,
);
const def = emitScope.translateDefinition({
expression: o.fn([], [], null, null, 'foo'),
statements: [],
});
expect(generate(def)).toEqual('function foo() { }');
});
});
describe('getConstantStatements()', () => {
it('should throw an error', () => {
const factory = new TypeScriptAstFactory(/* annotateForClosureCompiler */ false);
const translator = new Translator<ts.Statement, ts.Expression>(factory);
const ngImport = factory.createIdentifier('core');
const emitScope = new LocalEmitScope<ts.Statement, ts.Expression>(
ngImport,
translator,
factory,
);
expect(() => emitScope.getConstantStatements()).toThrowError();
});
});
});
function addSharedStatement(constantPool: ConstantPool): void {
const constArray = o.literalArr([o.literal('CONST')]);
// We have to add the constant twice or it will not create a shared statement
constantPool.getConstLiteral(constArray);
constantPool.getConstLiteral(constArray);
}
| {
"end_byte": 3793,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/test/file_linker/emit_scopes/local_emit_scope_spec.ts"
} |
angular/packages/compiler-cli/linker/test/file_linker/partial_linkers/partial_linker_selector_spec.ts_0_5712 | /**
* @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 semver from 'semver';
import {MockLogger} from '../../../../src/ngtsc/logging/testing';
import {PartialLinker} from '../../../src/file_linker/partial_linkers/partial_linker';
import {
LinkerRange,
PartialLinkerSelector,
} from '../../../src/file_linker/partial_linkers/partial_linker_selector';
describe('PartialLinkerSelector', () => {
let logger: MockLogger;
const linkerA = {name: 'linkerA'} as any;
const linkerA2 = {name: 'linkerA2'} as any;
const linkerB = {name: 'linkerB'} as any;
const linkerB2 = {name: 'linkerB2'} as any;
beforeEach(() => {
logger = new MockLogger();
});
describe('supportsDeclaration()', () => {
it('should return true if there is at least one linker that matches the given function name', () => {
const selector = createSelector('error');
expect(selector.supportsDeclaration('declareA')).toBe(true);
expect(selector.supportsDeclaration('invalid')).toBe(false);
});
it('should return false for methods on `Object`', () => {
const selector = createSelector('error');
expect(selector.supportsDeclaration('toString')).toBe(false);
});
});
describe('getLinker()', () => {
it('should return the linker that matches the name and version', () => {
const selector = createSelector('error');
expect(selector.getLinker('declareA', '11.1.2', '11.1.4')).toBe(linkerA);
expect(selector.getLinker('declareA', '12.0.0', '12.1.0')).toBe(linkerA);
expect(selector.getLinker('declareA', '12.0.1', '12.1.0')).toBe(linkerA2);
expect(selector.getLinker('declareB', '11.2.5', '11.3.0')).toBe(linkerB);
expect(selector.getLinker('declareB', '12.0.5', '12.0.5')).toBe(linkerB2);
});
it('should return the linker that matches the name and version, ignoring pre-releases', () => {
const selector = createSelector('error');
expect(selector.getLinker('declareA', '11.1.0-next.1', '11.1.0-next.1')).toBe(linkerA);
expect(selector.getLinker('declareA', '11.1.0-next.7', '11.1.0-next.7')).toBe(linkerA);
expect(selector.getLinker('declareA', '12.0.0-next.7', '12.0.0-next.7')).toBe(linkerA);
expect(selector.getLinker('declareA', '12.0.1-next.7', '12.0.1-next.7')).toBe(linkerA2);
});
it('should return the most recent linker if `version` is `0.0.0-PLACEHOLDER`, regardless of `minVersion`', () => {
const selector = createSelector('error');
expect(selector.getLinker('declareA', '11.1.2', '0.0.0-PLACEHOLDER')).toBe(linkerA2);
expect(selector.getLinker('declareA', '0.0.0-PLACEHOLDER', '11.1.2')).toBe(linkerA);
expect(selector.getLinker('declareA', '0.0.0-PLACEHOLDER', '0.0.0-PLACEHOLDER')).toBe(
linkerA2,
);
});
it('should throw an error if there is no linker that matches the given name', () => {
const selector = createSelector('error');
// `$foo` is not a valid name, even though `11.1.2` is a valid version for other declarations
expect(() => selector.getLinker('$foo', '11.1.2', '11.2.0')).toThrowError(
'Unknown partial declaration function $foo.',
);
});
describe('[unknown declaration version]', () => {
describe('[unknownDeclarationVersionHandling is "ignore"]', () => {
it('should use the most recent linker, with no log warning', () => {
const selector = createSelector('ignore');
expect(selector.getLinker('declareA', '13.1.0', '13.1.5')).toBe(linkerA2);
expect(logger.logs.warn).toEqual([]);
});
});
describe('[unknownDeclarationVersionHandling is "warn"]', () => {
it('should use the most recent linker and log a warning', () => {
const selector = createSelector('warn');
expect(selector.getLinker('declareA', '13.1.0', '14.0.5')).toBe(linkerA2);
expect(logger.logs.warn).toEqual([
[
`This application depends upon a library published using Angular version 14.0.5, ` +
`which requires Angular version 13.1.0 or newer to work correctly.\n` +
`Consider upgrading your application to use a more recent version of Angular.\n` +
'Attempting to continue using this version of Angular.',
],
]);
});
});
describe('[unknownDeclarationVersionHandling is "error"]', () => {
it('should throw an error', () => {
const selector = createSelector('error');
expect(() => selector.getLinker('declareA', '13.1.0', '14.0.5')).toThrowError(
`This application depends upon a library published using Angular version 14.0.5, ` +
`which requires Angular version 13.1.0 or newer to work correctly.\n` +
`Consider upgrading your application to use a more recent version of Angular.`,
);
});
});
});
});
/**
* Create a selector for testing
*/
function createSelector(unknownDeclarationVersionHandling: 'error' | 'warn' | 'ignore') {
const linkerMap = new Map<string, LinkerRange<unknown>[]>();
linkerMap.set('declareA', [
{range: new semver.Range('<=12.0.0'), linker: linkerA},
{range: new semver.Range('<=13.0.0'), linker: linkerA2},
]);
linkerMap.set('declareB', [
{range: new semver.Range('<=12.0.0'), linker: linkerB},
{range: new semver.Range('<=12.1.0'), linker: linkerB2},
]);
return new PartialLinkerSelector(linkerMap, logger, unknownDeclarationVersionHandling);
}
});
| {
"end_byte": 5712,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/test/file_linker/partial_linkers/partial_linker_selector_spec.ts"
} |
angular/packages/compiler-cli/linker/babel/README.md_0_363 | # Angular linker - Babel plugin
This package contains a Babel plugin that can be used to find and link partially compiled declarations in library source code.
See the [linker package README](../README.md) for more information.
## Unit Testing
The unit tests are built and run using Bazel:
```bash
yarn bazel test //packages/compiler-cli/linker/babel/test
```
| {
"end_byte": 363,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/README.md"
} |
angular/packages/compiler-cli/linker/babel/BUILD.bazel_0_564 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "babel",
srcs = ["index.ts"] + glob([
"src/**/*.ts",
]),
deps = [
"//packages/compiler",
"//packages/compiler-cli/linker",
"//packages/compiler-cli/private",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/logging",
"//packages/compiler-cli/src/ngtsc/translator",
"@npm//@babel/core",
"@npm//@types/babel__core",
],
)
| {
"end_byte": 564,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/BUILD.bazel"
} |
angular/packages/compiler-cli/linker/babel/index.ts_0_365 | /**
* @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 {defaultLinkerPlugin} from './src/babel_plugin';
export {createEs2015LinkerPlugin} from './src/es2015_linker_plugin';
export default defaultLinkerPlugin;
| {
"end_byte": 365,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/index.ts"
} |
angular/packages/compiler-cli/linker/babel/test/es2015_linker_plugin_spec.ts_0_926 | /**
* @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 * as o from '@angular/compiler/src/output/output_ast';
import babel, {NodePath, PluginObj, types as t} from '@babel/core';
import _generate from '@babel/generator';
// Babel is a CJS package and misuses the `default` named binding:
// https://github.com/babel/babel/issues/15269.
const generate = (_generate as any)['default'] as typeof _generate;
import {FileLinker} from '../../../linker';
import {MockFileSystemNative} from '../../../src/ngtsc/file_system/testing';
import {MockLogger} from '../../../src/ngtsc/logging/testing';
import {PartialDirectiveLinkerVersion1} from '../../src/file_linker/partial_linkers/partial_directive_linker_1';
import {createEs2015LinkerPlugin} from '../src/es2015_linker_plugin'; | {
"end_byte": 926,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/test/es2015_linker_plugin_spec.ts"
} |
angular/packages/compiler-cli/linker/babel/test/es2015_linker_plugin_spec.ts_928_7838 | describe('createEs2015LinkerPlugin()', () => {
it('should return a Babel plugin visitor that handles Program (enter/exit) and CallExpression nodes', () => {
const fileSystem = new MockFileSystemNative();
const logger = new MockLogger();
const plugin = createEs2015LinkerPlugin({fileSystem, logger});
expect(plugin.visitor).toEqual({
Program: {
enter: jasmine.any(Function),
exit: jasmine.any(Function),
},
CallExpression: jasmine.any(Function),
});
});
it('should return a Babel plugin that calls FileLinker.isPartialDeclaration() on each call expression', () => {
const isPartialDeclarationSpy = spyOn(FileLinker.prototype, 'isPartialDeclaration');
const fileSystem = new MockFileSystemNative();
const logger = new MockLogger();
const plugin = createEs2015LinkerPlugin({fileSystem, logger});
babel.transformSync(
[
'var core;',
`fn1()`,
'fn2({prop: () => fn3({})});',
`x.method(() => fn4());`,
'spread(...x);',
].join('\n'),
{
plugins: [plugin],
filename: '/test.js',
parserOpts: {sourceType: 'unambiguous'},
},
);
expect(isPartialDeclarationSpy.calls.allArgs()).toEqual([
['fn1'],
['fn2'],
['fn3'],
['method'],
['fn4'],
['spread'],
]);
});
it('should return a Babel plugin that calls FileLinker.linkPartialDeclaration() on each matching declaration', () => {
const linkSpy = spyOn(FileLinker.prototype, 'linkPartialDeclaration').and.returnValue(
t.identifier('REPLACEMENT'),
);
const fileSystem = new MockFileSystemNative();
const logger = new MockLogger();
babel.transformSync(
[
'var core;',
`ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core, x: 1});`,
`i0.ɵɵngDeclareComponent({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core, foo: () => ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core, x: 2})});`,
`x.qux(() => ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core, x: 3}));`,
'spread(...x);',
`i0['ɵɵngDeclareDirective']({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core, x: 4});`,
].join('\n'),
{
plugins: [createEs2015LinkerPlugin({fileSystem, logger})],
filename: '/test.js',
parserOpts: {sourceType: 'unambiguous'},
},
);
expect(humanizeLinkerCalls(linkSpy.calls)).toEqual([
[
'ɵɵngDeclareDirective',
"{minVersion:'0.0.0-PLACEHOLDER',version:'0.0.0-PLACEHOLDER',ngImport:core,x:1}",
],
[
'ɵɵngDeclareComponent',
"{minVersion:'0.0.0-PLACEHOLDER',version:'0.0.0-PLACEHOLDER',ngImport:core,foo:()=>ɵɵngDeclareDirective({minVersion:'0.0.0-PLACEHOLDER',version:'0.0.0-PLACEHOLDER',ngImport:core,x:2})}",
],
// Note we do not process `x:2` declaration since it is nested within another declaration
[
'ɵɵngDeclareDirective',
"{minVersion:'0.0.0-PLACEHOLDER',version:'0.0.0-PLACEHOLDER',ngImport:core,x:3}",
],
[
'ɵɵngDeclareDirective',
"{minVersion:'0.0.0-PLACEHOLDER',version:'0.0.0-PLACEHOLDER',ngImport:core,x:4}",
],
]);
});
it('should return a Babel plugin that replaces call expressions with the return value from FileLinker.linkPartialDeclaration()', () => {
let replaceCount = 0;
spyOn(FileLinker.prototype, 'linkPartialDeclaration').and.callFake(() =>
t.identifier('REPLACEMENT_' + ++replaceCount),
);
const fileSystem = new MockFileSystemNative();
const logger = new MockLogger();
const result = babel.transformSync(
[
'var core;',
"ɵɵngDeclareDirective({version: '0.0.0-PLACEHOLDER', ngImport: core});",
"ɵɵngDeclareDirective({version: '0.0.0-PLACEHOLDER', ngImport: core, foo: () => bar({})});",
'x.qux();',
'spread(...x);',
].join('\n'),
{
plugins: [createEs2015LinkerPlugin({fileSystem, logger})],
filename: '/test.js',
parserOpts: {sourceType: 'unambiguous'},
generatorOpts: {compact: true},
},
);
expect(result!.code).toEqual('var core;REPLACEMENT_1;REPLACEMENT_2;x.qux();spread(...x);');
});
it('should return a Babel plugin that adds shared statements after any imports', () => {
spyOnLinkPartialDeclarationWithConstants(o.literal('REPLACEMENT'));
const fileSystem = new MockFileSystemNative();
const logger = new MockLogger();
const result = babel.transformSync(
[
"import * as core from 'some-module';",
"import {id} from 'other-module';",
`ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core})`,
`ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core})`,
`ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core})`,
].join('\n'),
{
plugins: [createEs2015LinkerPlugin({fileSystem, logger})],
filename: '/test.js',
parserOpts: {sourceType: 'unambiguous'},
generatorOpts: {compact: true},
},
);
expect(result!.code).toEqual(
'import*as core from\'some-module\';import{id}from\'other-module\';const _c0=[1];const _c1=[2];const _c2=[3];"REPLACEMENT";"REPLACEMENT";"REPLACEMENT";',
);
});
it('should return a Babel plugin that adds shared statements after the first group of imports', () => {
spyOnLinkPartialDeclarationWithConstants(o.literal('REPLACEMENT'));
const fileSystem = new MockFileSystemNative();
const logger = new MockLogger();
const result = babel.transformSync(
[
"import * as core from 'some-module';",
"import {id} from 'other-module';",
`ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core})`,
`ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core})`,
`ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core})`,
"import {second} from 'second-module';",
].join('\n'),
{
plugins: [createEs2015LinkerPlugin({fileSystem, logger})],
filename: '/test.js',
parserOpts: {sourceType: 'unambiguous'},
generatorOpts: {compact: true},
},
);
expect(result!.code).toEqual(
'import*as core from\'some-module\';import{id}from\'other-module\';const _c0=[1];const _c1=[2];const _c2=[3];"REPLACEMENT";"REPLACEMENT";"REPLACEMENT";import{second}from\'second-module\';',
);
});
it('should return a Babel plugin | {
"end_byte": 7838,
"start_byte": 928,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/test/es2015_linker_plugin_spec.ts"
} |
angular/packages/compiler-cli/linker/babel/test/es2015_linker_plugin_spec.ts_7842_15578 | t adds shared statements at the start of the program if it is an ECMAScript Module and there are no imports', () => {
spyOnLinkPartialDeclarationWithConstants(o.literal('REPLACEMENT'));
const fileSystem = new MockFileSystemNative();
const logger = new MockLogger();
const result = babel.transformSync(
[
'var core;',
`ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core})`,
`ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core})`,
`ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core})`,
].join('\n'),
{
plugins: [createEs2015LinkerPlugin({fileSystem, logger})],
filename: '/test.js',
// We declare the file as a module because this cannot be inferred from the source
parserOpts: {sourceType: 'module'},
generatorOpts: {compact: true},
},
);
expect(result!.code).toEqual(
'const _c0=[1];const _c1=[2];const _c2=[3];var core;"REPLACEMENT";"REPLACEMENT";"REPLACEMENT";',
);
});
it('should return a Babel plugin that adds shared statements at the start of the function body if the ngImport is from a function parameter', () => {
spyOnLinkPartialDeclarationWithConstants(o.literal('REPLACEMENT'));
const fileSystem = new MockFileSystemNative();
const logger = new MockLogger();
const result = babel.transformSync(
[
'function run(core) {',
` ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core})`,
` ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core})`,
` ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core})`,
'}',
].join('\n'),
{
plugins: [createEs2015LinkerPlugin({fileSystem, logger})],
filename: '/test.js',
parserOpts: {sourceType: 'unambiguous'},
generatorOpts: {compact: true},
},
);
expect(result!.code).toEqual(
'function run(core){const _c0=[1];const _c1=[2];const _c2=[3];"REPLACEMENT";"REPLACEMENT";"REPLACEMENT";}',
);
});
it('should return a Babel plugin that adds shared statements into an IIFE if no scope could not be derived for the ngImport', () => {
spyOnLinkPartialDeclarationWithConstants(o.literal('REPLACEMENT'));
const fileSystem = new MockFileSystemNative();
const logger = new MockLogger();
const result = babel.transformSync(
[
'function run() {',
` ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core})`,
` ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core})`,
` ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core})`,
'}',
].join('\n'),
{
plugins: [createEs2015LinkerPlugin({fileSystem, logger})],
filename: '/test.js',
parserOpts: {sourceType: 'unambiguous'},
generatorOpts: {compact: true},
},
);
expect(result!.code).toEqual(
[
`function run(){`,
`(function(){const _c0=[1];return"REPLACEMENT";})();`,
`(function(){const _c0=[2];return"REPLACEMENT";})();`,
`(function(){const _c0=[3];return"REPLACEMENT";})();`,
`}`,
].join(''),
);
});
it('should still execute other plugins that match AST nodes inside the result of the replacement', () => {
spyOnLinkPartialDeclarationWithConstants(o.fn([], [], null, null, 'FOO'));
const fileSystem = new MockFileSystemNative();
const logger = new MockLogger();
const result = babel.transformSync(
[
`ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core}); FOO;`,
].join('\n'),
{
plugins: [
createEs2015LinkerPlugin({fileSystem, logger}),
createIdentifierMapperPlugin('FOO', 'BAR'),
createIdentifierMapperPlugin('_c0', 'x1'),
],
filename: '/test.js',
parserOpts: {sourceType: 'module'},
generatorOpts: {compact: true},
},
);
expect(result!.code).toEqual(
[`(function(){const x1=[1];return function BAR(){};})();BAR;`].join(''),
);
});
it('should not process call expressions within inserted functions', () => {
spyOn(PartialDirectiveLinkerVersion1.prototype, 'linkPartialDeclaration').and.callFake(((
constantPool,
) => {
// Insert a call expression into the constant pool. This is inserted into
// Babel's AST upon program exit, and will therefore be visited by Babel
// outside of an active linker context.
constantPool.statements.push(
o
.fn(
/* params */ [],
/* body */ [],
/* type */ undefined,
/* sourceSpan */ undefined,
/* name */ 'inserted',
)
.callFn([])
.toStmt(),
);
return {
expression: o.literal('REPLACEMENT'),
statements: [],
};
}) as typeof PartialDirectiveLinkerVersion1.prototype.linkPartialDeclaration);
const isPartialDeclarationSpy = spyOn(
FileLinker.prototype,
'isPartialDeclaration',
).and.callThrough();
const fileSystem = new MockFileSystemNative();
const logger = new MockLogger();
const result = babel.transformSync(
[
"import * as core from 'some-module';",
`ɵɵngDeclareDirective({minVersion: '0.0.0-PLACEHOLDER', version: '0.0.0-PLACEHOLDER', ngImport: core})`,
].join('\n'),
{
plugins: [createEs2015LinkerPlugin({fileSystem, logger})],
filename: '/test.js',
parserOpts: {sourceType: 'unambiguous'},
generatorOpts: {compact: true},
},
);
expect(result!.code).toEqual(
'import*as core from\'some-module\';(function inserted(){})();"REPLACEMENT";',
);
expect(isPartialDeclarationSpy.calls.allArgs()).toEqual([['ɵɵngDeclareDirective']]);
});
});
/**
* Convert the arguments of the spied-on `calls` into a human readable array.
*/
function humanizeLinkerCalls(
calls: jasmine.Calls<typeof FileLinker.prototype.linkPartialDeclaration>,
) {
return calls.all().map(({args: [fn, args]}) => [fn, generate(args[0], {compact: true}).code]);
}
/**
* Spy on the `PartialDirectiveLinkerVersion1.linkPartialDeclaration()` method, triggering
* shared constants to be created.
*/
function spyOnLinkPartialDeclarationWithConstants(replacement: o.Expression) {
let callCount = 0;
spyOn(PartialDirectiveLinkerVersion1.prototype, 'linkPartialDeclaration').and.callFake(((
constantPool,
) => {
const constArray = o.literalArr([o.literal(++callCount)]);
// We have to add the constant twice or it will not create a shared statement
constantPool.getConstLiteral(constArray);
constantPool.getConstLiteral(constArray);
return {
expression: replacement,
statements: [],
};
}) as typeof PartialDirectiveLinkerVersion1.prototype.linkPartialDeclaration);
}
/**
* A simple Babel plugin that will replace all identifiers that match `<src>` with identifiers
* called `<dest>`.
*/
function createIdentifierMapperPlugin(src: string, dest: string): PluginObj {
return {
visitor: {
Identifier(path: NodePath<t.Identifier>) {
if (path.node.name === src) {
path.replaceWith(t.identifier(dest));
}
},
},
};
}
| {
"end_byte": 15578,
"start_byte": 7842,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/test/es2015_linker_plugin_spec.ts"
} |
angular/packages/compiler-cli/linker/babel/test/babel_plugin_spec.ts_0_1836 | /**
* @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 babel from '@babel/core';
describe('default babel plugin entry-point', () => {
it('should work as a Babel plugin using the module specifier', async () => {
const result = (await babel.transformAsync(
`
import * as i0 from "@angular/core";
export class MyMod {}
export class MyComponent {}
MyMod.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyMod, declarations: [MyComponent] });
`,
{
plugins: ['@angular/compiler-cli/linker/babel/index.mjs'],
filename: 'test.js',
},
))!;
expect(result).not.toBeNull();
expect(result.code).not.toContain('ɵɵngDeclareNgModule');
expect(result.code).toContain('i0.ɵɵdefineNgModule');
expect(result.code).not.toMatch(/declarations:\s*\[MyComponent]/);
});
it('should be configurable', async () => {
const result = (await babel.transformAsync(
`
import * as i0 from "@angular/core";
export class MyMod {}
export class MyComponent {}
MyMod.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyMod, declarations: [MyComponent] });
`,
{
plugins: [['@angular/compiler-cli/linker/babel/index.mjs', {linkerJitMode: true}]],
filename: 'test.js',
},
))!;
expect(result).not.toBeNull();
expect(result.code).not.toContain('ɵɵngDeclareNgModule');
expect(result.code).toContain('i0.ɵɵdefineNgModule');
expect(result.code).toMatch(/declarations:\s*\[MyComponent]/);
});
});
| {
"end_byte": 1836,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/test/babel_plugin_spec.ts"
} |
angular/packages/compiler-cli/linker/babel/test/BUILD.bazel_0_863 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "test_lib",
testonly = True,
srcs = glob([
"**/*.ts",
]),
deps = [
"//packages:types",
"//packages/compiler",
"//packages/compiler-cli/linker",
"//packages/compiler-cli/linker/babel",
"//packages/compiler-cli/private",
"//packages/compiler-cli/src/ngtsc/file_system/testing",
"//packages/compiler-cli/src/ngtsc/logging/testing",
"//packages/compiler-cli/src/ngtsc/translator",
"@npm//@babel/generator",
"@npm//@types/babel__core",
"@npm//@types/babel__generator",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node_no_angular"],
deps = [
":test_lib",
],
)
| {
"end_byte": 863,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/test/BUILD.bazel"
} |
angular/packages/compiler-cli/linker/babel/test/babel_declaration_scope_spec.ts_0_4157 | /**
* @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 {NodePath, parse, traverse, types as t} from '@babel/core';
import {BabelDeclarationScope} from '../src/babel_declaration_scope';
describe('BabelDeclarationScope', () => {
describe('getConstantScopeRef()', () => {
it('should return a path to the ES module where the expression was imported', () => {
const ast = parse(
[
"import * as core from '@angular/core';",
'function foo() {',
' var TEST = core;',
'}',
].join('\n'),
{sourceType: 'module'},
) as t.File;
const nodePath = findVarDeclaration(ast, 'TEST');
const scope = new BabelDeclarationScope(nodePath.scope);
const constantScope = scope.getConstantScopeRef(nodePath.get('init').node);
expect(constantScope).not.toBe(null);
expect(constantScope!.node).toBe(ast.program);
});
it('should return a path to the ES Module where the expression is declared', () => {
const ast = parse(
['var core;', 'export function foo() {', ' var TEST = core;', '}'].join('\n'),
{sourceType: 'module'},
) as t.File;
const nodePath = findVarDeclaration(ast, 'TEST');
const scope = new BabelDeclarationScope(nodePath.scope);
const constantScope = scope.getConstantScopeRef(nodePath.get('init').node);
expect(constantScope).not.toBe(null);
expect(constantScope!.node).toBe(ast.program);
});
it('should return null if the file is not an ES module', () => {
const ast = parse(['var core;', 'function foo() {', ' var TEST = core;', '}'].join('\n'), {
sourceType: 'script',
}) as t.File;
const nodePath = findVarDeclaration(ast, 'TEST');
const scope = new BabelDeclarationScope(nodePath.scope);
const constantScope = scope.getConstantScopeRef(nodePath.get('init').node);
expect(constantScope).toBe(null);
});
it('should return the IIFE factory function where the expression is a parameter', () => {
const ast = parse(
[
'var core;',
'(function(core) {',
" var BLOCK = 'block';",
' function foo() {',
' var TEST = core;',
' }',
'})(core);',
].join('\n'),
{sourceType: 'script'},
) as t.File;
const nodePath = findVarDeclaration(ast, 'TEST');
const fnPath = findFirstFunction(ast);
const scope = new BabelDeclarationScope(nodePath.scope);
const constantScope = scope.getConstantScopeRef(nodePath.get('init').node);
expect(constantScope).not.toBe(null);
expect(constantScope!.isFunction()).toBe(true);
expect(constantScope!.node).toEqual(fnPath.node as t.FunctionDeclaration);
});
});
});
/**
* The type of a variable declarator that is known to have an initializer.
*
* Note: the `init` property is explicitly omitted to workaround a performance cliff in the
* TypeScript type checker.
*/
type InitializedVariableDeclarator = Omit<t.VariableDeclarator, 'init'> & {init: t.Expression};
function findVarDeclaration(
file: t.File,
varName: string,
): NodePath<InitializedVariableDeclarator> {
let varDecl: NodePath<t.VariableDeclarator> | undefined = undefined;
traverse(file, {
VariableDeclarator: (path: NodePath<t.VariableDeclarator>) => {
const id = path.get('id');
if (id.isIdentifier() && id.node.name === varName && path.get('init') !== null) {
varDecl = path;
path.stop();
}
},
});
if (varDecl === undefined) {
throw new Error(`TEST BUG: expected to find variable declaration for ${varName}.`);
}
return varDecl;
}
function findFirstFunction(file: t.File): NodePath<t.Function> {
let fn: NodePath<t.Function> | undefined = undefined;
traverse(file, {
Function: (path) => {
fn = path;
path.stop();
},
});
if (fn === undefined) {
throw new Error(`TEST BUG: expected to find a function.`);
}
return fn;
}
| {
"end_byte": 4157,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/test/babel_declaration_scope_spec.ts"
} |
angular/packages/compiler-cli/linker/babel/test/ast/babel_ast_host_spec.ts_0_8074 | /**
* @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 {parse, template, types as t} from '@babel/core';
import {BabelAstHost} from '../../src/ast/babel_ast_host';
describe('BabelAstHost', () => {
let host: BabelAstHost;
beforeEach(() => (host = new BabelAstHost()));
describe('getSymbolName()', () => {
it('should return the name of an identifier', () => {
expect(host.getSymbolName(expr('someIdentifier'))).toEqual('someIdentifier');
});
it('should return the name of an identifier at the end of a property access chain', () => {
expect(host.getSymbolName(expr('a.b.c.someIdentifier'))).toEqual('someIdentifier');
});
it('should return null if the expression has no identifier', () => {
expect(host.getSymbolName(expr('42'))).toBe(null);
});
});
describe('isStringLiteral()', () => {
it('should return true if the expression is a string literal', () => {
expect(host.isStringLiteral(expr('"moo"'))).toBe(true);
expect(host.isStringLiteral(expr("'moo'"))).toBe(true);
});
it('should return false if the expression is not a string literal', () => {
expect(host.isStringLiteral(expr('true'))).toBe(false);
expect(host.isStringLiteral(expr('someIdentifier'))).toBe(false);
expect(host.isStringLiteral(expr('42'))).toBe(false);
expect(host.isStringLiteral(expr('{}'))).toBe(false);
expect(host.isStringLiteral(expr('[]'))).toBe(false);
expect(host.isStringLiteral(expr('null'))).toBe(false);
expect(host.isStringLiteral(expr("'a' + 'b'"))).toBe(false);
});
it('should return false if the expression is a template string', () => {
expect(host.isStringLiteral(expr('`moo`'))).toBe(false);
});
});
describe('parseStringLiteral()', () => {
it('should extract the string value', () => {
expect(host.parseStringLiteral(expr('"moo"'))).toEqual('moo');
expect(host.parseStringLiteral(expr("'moo'"))).toEqual('moo');
});
it('should error if the value is not a string literal', () => {
expect(() => host.parseStringLiteral(expr('42'))).toThrowError(
'Unsupported syntax, expected a string literal.',
);
});
});
describe('isNumericLiteral()', () => {
it('should return true if the expression is a number literal', () => {
expect(host.isNumericLiteral(expr('42'))).toBe(true);
});
it('should return false if the expression is not a number literal', () => {
expect(host.isStringLiteral(expr('true'))).toBe(false);
expect(host.isNumericLiteral(expr('"moo"'))).toBe(false);
expect(host.isNumericLiteral(expr("'moo'"))).toBe(false);
expect(host.isNumericLiteral(expr('someIdentifier'))).toBe(false);
expect(host.isNumericLiteral(expr('{}'))).toBe(false);
expect(host.isNumericLiteral(expr('[]'))).toBe(false);
expect(host.isNumericLiteral(expr('null'))).toBe(false);
expect(host.isNumericLiteral(expr("'a' + 'b'"))).toBe(false);
expect(host.isNumericLiteral(expr('`moo`'))).toBe(false);
});
});
describe('parseNumericLiteral()', () => {
it('should extract the number value', () => {
expect(host.parseNumericLiteral(expr('42'))).toEqual(42);
});
it('should error if the value is not a numeric literal', () => {
expect(() => host.parseNumericLiteral(expr('"moo"'))).toThrowError(
'Unsupported syntax, expected a numeric literal.',
);
});
});
describe('isBooleanLiteral()', () => {
it('should return true if the expression is a boolean literal', () => {
expect(host.isBooleanLiteral(expr('true'))).toBe(true);
expect(host.isBooleanLiteral(expr('false'))).toBe(true);
});
it('should return true if the expression is a minified boolean literal', () => {
expect(host.isBooleanLiteral(expr('!0'))).toBe(true);
expect(host.isBooleanLiteral(expr('!1'))).toBe(true);
});
it('should return false if the expression is not a boolean literal', () => {
expect(host.isBooleanLiteral(expr('"moo"'))).toBe(false);
expect(host.isBooleanLiteral(expr("'moo'"))).toBe(false);
expect(host.isBooleanLiteral(expr('someIdentifier'))).toBe(false);
expect(host.isBooleanLiteral(expr('42'))).toBe(false);
expect(host.isBooleanLiteral(expr('{}'))).toBe(false);
expect(host.isBooleanLiteral(expr('[]'))).toBe(false);
expect(host.isBooleanLiteral(expr('null'))).toBe(false);
expect(host.isBooleanLiteral(expr("'a' + 'b'"))).toBe(false);
expect(host.isBooleanLiteral(expr('`moo`'))).toBe(false);
expect(host.isBooleanLiteral(expr('!2'))).toBe(false);
expect(host.isBooleanLiteral(expr('~1'))).toBe(false);
});
});
describe('parseBooleanLiteral()', () => {
it('should extract the boolean value', () => {
expect(host.parseBooleanLiteral(expr('true'))).toEqual(true);
expect(host.parseBooleanLiteral(expr('false'))).toEqual(false);
});
it('should extract a minified boolean value', () => {
expect(host.parseBooleanLiteral(expr('!0'))).toEqual(true);
expect(host.parseBooleanLiteral(expr('!1'))).toEqual(false);
});
it('should error if the value is not a boolean literal', () => {
expect(() => host.parseBooleanLiteral(expr('"moo"'))).toThrowError(
'Unsupported syntax, expected a boolean literal.',
);
});
});
describe('isArrayLiteral()', () => {
it('should return true if the expression is an array literal', () => {
expect(host.isArrayLiteral(expr('[]'))).toBe(true);
expect(host.isArrayLiteral(expr('[1, 2, 3]'))).toBe(true);
expect(host.isArrayLiteral(expr('[[], []]'))).toBe(true);
});
it('should return false if the expression is not an array literal', () => {
expect(host.isArrayLiteral(expr('"moo"'))).toBe(false);
expect(host.isArrayLiteral(expr("'moo'"))).toBe(false);
expect(host.isArrayLiteral(expr('someIdentifier'))).toBe(false);
expect(host.isArrayLiteral(expr('42'))).toBe(false);
expect(host.isArrayLiteral(expr('{}'))).toBe(false);
expect(host.isArrayLiteral(expr('null'))).toBe(false);
expect(host.isArrayLiteral(expr("'a' + 'b'"))).toBe(false);
expect(host.isArrayLiteral(expr('`moo`'))).toBe(false);
});
});
describe('parseArrayLiteral()', () => {
it('should extract the expressions in the array', () => {
const moo = expr("'moo'");
expect(host.parseArrayLiteral(expr('[]'))).toEqual([]);
expect(host.parseArrayLiteral(expr("['moo']"))).toEqual([moo]);
});
it('should error if there is an empty item', () => {
expect(() => host.parseArrayLiteral(expr('[,]'))).toThrowError(
'Unsupported syntax, expected element in array not to be empty.',
);
});
it('should error if there is a spread element', () => {
expect(() => host.parseArrayLiteral(expr('[...[0,1]]'))).toThrowError(
'Unsupported syntax, expected element in array not to use spread syntax.',
);
});
});
describe('isObjectLiteral()', () => {
it('should return true if the expression is an object literal', () => {
expect(host.isObjectLiteral(rhs('x = {}'))).toBe(true);
expect(host.isObjectLiteral(rhs("x = { foo: 'bar' }"))).toBe(true);
});
it('should return false if the expression is not an object literal', () => {
expect(host.isObjectLiteral(rhs('x = "moo"'))).toBe(false);
expect(host.isObjectLiteral(rhs("x = 'moo'"))).toBe(false);
expect(host.isObjectLiteral(rhs('x = someIdentifier'))).toBe(false);
expect(host.isObjectLiteral(rhs('x = 42'))).toBe(false);
expect(host.isObjectLiteral(rhs('x = []'))).toBe(false);
expect(host.isObjectLiteral(rhs('x = null'))).toBe(false);
expect(host.isObjectLiteral(rhs("x = 'a' + 'b'"))).toBe(false);
expect(host.isObjectLiteral(rhs('x = `moo`'))).toBe(false);
});
}); | {
"end_byte": 8074,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/test/ast/babel_ast_host_spec.ts"
} |
angular/packages/compiler-cli/linker/babel/test/ast/babel_ast_host_spec.ts_8078_16343 | describe('parseObjectLiteral()', () => {
it('should extract the properties from the object', () => {
const moo = expr("'moo'");
expect(host.parseObjectLiteral(rhs('x = {}'))).toEqual(new Map());
expect(host.parseObjectLiteral(rhs("x = {a: 'moo'}"))).toEqual(new Map([['a', moo]]));
});
it('should error if there is a method', () => {
expect(() => host.parseObjectLiteral(rhs('x = { foo() {} }'))).toThrowError(
'Unsupported syntax, expected a property assignment.',
);
});
it('should error if there is a spread element', () => {
expect(() => host.parseObjectLiteral(rhs("x = {...{a:'moo'}}"))).toThrowError(
'Unsupported syntax, expected a property assignment.',
);
});
});
describe('isFunctionExpression()', () => {
it('should return true if the expression is a function', () => {
expect(host.isFunctionExpression(rhs('x = function() {}'))).toBe(true);
expect(host.isFunctionExpression(rhs('x = function foo() {}'))).toBe(true);
expect(host.isFunctionExpression(rhs('x = () => {}'))).toBe(true);
expect(host.isFunctionExpression(rhs('x = () => true'))).toBe(true);
});
it('should return false if the expression is a function declaration', () => {
expect(host.isFunctionExpression(expr('function foo() {}'))).toBe(false);
});
it('should return false if the expression is not a function expression', () => {
expect(host.isFunctionExpression(expr('[]'))).toBe(false);
expect(host.isFunctionExpression(expr('"moo"'))).toBe(false);
expect(host.isFunctionExpression(expr("'moo'"))).toBe(false);
expect(host.isFunctionExpression(expr('someIdentifier'))).toBe(false);
expect(host.isFunctionExpression(expr('42'))).toBe(false);
expect(host.isFunctionExpression(expr('{}'))).toBe(false);
expect(host.isFunctionExpression(expr('null'))).toBe(false);
expect(host.isFunctionExpression(expr("'a' + 'b'"))).toBe(false);
expect(host.isFunctionExpression(expr('`moo`'))).toBe(false);
});
});
describe('parseReturnValue()', () => {
it('should extract the return value of a function', () => {
const moo = expr("'moo'");
expect(host.parseReturnValue(rhs("x = function() { return 'moo'; }"))).toEqual(moo);
});
it('should extract the value of a simple arrow function', () => {
const moo = expr("'moo'");
expect(host.parseReturnValue(rhs("x = () => 'moo'"))).toEqual(moo);
});
it('should extract the return value of an arrow function', () => {
const moo = expr("'moo'");
expect(host.parseReturnValue(rhs("x = () => { return 'moo' }"))).toEqual(moo);
});
it('should error if the body has 0 statements', () => {
expect(() => host.parseReturnValue(rhs('x = function () { }'))).toThrowError(
'Unsupported syntax, expected a function body with a single return statement.',
);
expect(() => host.parseReturnValue(rhs('x = () => { }'))).toThrowError(
'Unsupported syntax, expected a function body with a single return statement.',
);
});
it('should error if the body has more than 1 statement', () => {
expect(() =>
host.parseReturnValue(rhs('x = function () { const x = 10; return x; }')),
).toThrowError(
'Unsupported syntax, expected a function body with a single return statement.',
);
expect(() =>
host.parseReturnValue(rhs('x = () => { const x = 10; return x; }')),
).toThrowError(
'Unsupported syntax, expected a function body with a single return statement.',
);
});
it('should error if the single statement is not a return statement', () => {
expect(() => host.parseReturnValue(rhs('x = function () { const x = 10; }'))).toThrowError(
'Unsupported syntax, expected a function body with a single return statement.',
);
expect(() => host.parseReturnValue(rhs('x = () => { const x = 10; }'))).toThrowError(
'Unsupported syntax, expected a function body with a single return statement.',
);
});
});
describe('parseParameters()', () => {
it('should return the parameters as an array of expressions', () => {
expect(host.parseParameters(rhs('x = function(a, b) {}'))).toEqual([expr('a'), expr('b')]);
expect(host.parseParameters(rhs('x = (a, b) => {}'))).toEqual([expr('a'), expr('b')]);
});
it('should error if the node is not a function declaration or arrow function', () => {
expect(() => host.parseParameters(expr('[]'))).toThrowError(
'Unsupported syntax, expected a function.',
);
});
it('should error if a parameter uses spread syntax', () => {
expect(() => host.parseParameters(rhs('x = function(a, ...other) {}'))).toThrowError(
'Unsupported syntax, expected an identifier.',
);
});
});
describe('isCallExpression()', () => {
it('should return true if the expression is a call expression', () => {
expect(host.isCallExpression(expr('foo()'))).toBe(true);
expect(host.isCallExpression(expr('foo.bar()'))).toBe(true);
expect(host.isCallExpression(expr('(foo)(1)'))).toBe(true);
});
it('should return false if the expression is not a call expression', () => {
expect(host.isCallExpression(expr('[]'))).toBe(false);
expect(host.isCallExpression(expr('"moo"'))).toBe(false);
expect(host.isCallExpression(expr("'moo'"))).toBe(false);
expect(host.isCallExpression(expr('someIdentifier'))).toBe(false);
expect(host.isCallExpression(expr('42'))).toBe(false);
expect(host.isCallExpression(expr('{}'))).toBe(false);
expect(host.isCallExpression(expr('null'))).toBe(false);
expect(host.isCallExpression(expr("'a' + 'b'"))).toBe(false);
expect(host.isCallExpression(expr('`moo`'))).toBe(false);
});
});
describe('parseCallee()', () => {
it('should return the callee expression', () => {
expect(host.parseCallee(expr('foo()'))).toEqual(expr('foo'));
expect(host.parseCallee(expr('foo.bar()'))).toEqual(expr('foo.bar'));
});
it('should error if the node is not a call expression', () => {
expect(() => host.parseCallee(expr('[]'))).toThrowError(
'Unsupported syntax, expected a call expression.',
);
});
});
describe('parseArguments()', () => {
it('should return the arguments as an array of expressions', () => {
expect(host.parseArguments(expr('foo(12, [])'))).toEqual([expr('12'), expr('[]')]);
expect(host.parseArguments(expr('foo.bar()'))).toEqual([]);
});
it('should error if the node is not a call expression', () => {
expect(() => host.parseArguments(expr('[]'))).toThrowError(
'Unsupported syntax, expected a call expression.',
);
});
it('should error if an argument uses spread syntax', () => {
expect(() => host.parseArguments(expr('foo(1, ...[])'))).toThrowError(
'Unsupported syntax, expected argument not to use spread syntax.',
);
});
});
describe('getRange()', () => {
it('should extract the range from the expression', () => {
const file = parse("// preamble\nx = 'moo';");
const stmt = file!.program.body[0] as t.Statement;
assertExpressionStatement(stmt);
assertAssignmentExpression(stmt.expression);
expect(host.getRange(stmt.expression.right)).toEqual({
startLine: 1,
startCol: 4,
startPos: 16,
endPos: 21,
});
});
it('should error if there is no range information', () => {
const moo = rhs("// preamble\nx = 'moo';");
expect(() => host.getRange(moo)).toThrowError(
'Unable to read range for node - it is missing location information.',
);
});
});
});
function expr(code: string): t.Expression {
const stmt = template.ast(code);
return (stmt as t.ExpressionStatement).expression;
}
function rhs(code: string): t.Expression {
const e = expr(code);
assertAssignmentExpression(e);
return e.right;
}
function assertExpressionStatement(e: t.Node): asserts e is t.ExpressionStatement {
if (!t.isExpressionStatement(e)) {
throw new Error('Bad test - expected an expression statement');
}
} | {
"end_byte": 16343,
"start_byte": 8078,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/test/ast/babel_ast_host_spec.ts"
} |
angular/packages/compiler-cli/linker/babel/test/ast/babel_ast_host_spec.ts_16345_16549 | function assertAssignmentExpression(e: t.Expression): asserts e is t.AssignmentExpression {
if (!t.isAssignmentExpression(e)) {
throw new Error('Bad test - expected an assignment expression');
}
} | {
"end_byte": 16549,
"start_byte": 16345,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/test/ast/babel_ast_host_spec.ts"
} |
angular/packages/compiler-cli/linker/babel/test/ast/babel_ast_factory_spec.ts_0_802 | /**
* @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 {leadingComment} from '@angular/compiler';
import {template, types as t} from '@babel/core';
import _generate from '@babel/generator';
import {BabelAstFactory} from '../../src/ast/babel_ast_factory';
// Babel is a CJS package and misuses the `default` named binding:
// https://github.com/babel/babel/issues/15269.
const generate = (_generate as any)['default'] as typeof _generate;
// Exposes shorthands for the `expression` and `statement`
// methods exposed by `@babel/template`.
const expression = template.expression;
const statement = template.statement;
describe('BabelAstFactory', | {
"end_byte": 802,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/test/ast/babel_ast_factory_spec.ts"
} |
angular/packages/compiler-cli/linker/babel/test/ast/babel_ast_factory_spec.ts_803_8550 | () => {
let factory: BabelAstFactory;
beforeEach(() => (factory = new BabelAstFactory('/original.ts')));
describe('attachComments()', () => {
it('should add the comments to the given statement', () => {
const stmt = statement.ast`x = 10;`;
factory.attachComments(stmt, [
leadingComment('comment 1', true),
leadingComment('comment 2', false),
]);
expect(generate(stmt).code).toEqual(['/* comment 1 */', '//comment 2', 'x = 10;'].join('\n'));
});
it('should add the comments to the given statement', () => {
const expr = expression.ast`x + 10`;
factory.attachComments(expr, [
leadingComment('comment 1', true),
leadingComment('comment 2', false),
]);
expect(generate(expr).code).toEqual(
['(', '/* comment 1 */', '//comment 2', 'x + 10'].join('\n') + ')',
);
});
});
describe('createArrayLiteral()', () => {
it('should create an array node containing the provided expressions', () => {
const expr1 = expression.ast`42`;
const expr2 = expression.ast`"moo"`;
const array = factory.createArrayLiteral([expr1, expr2]);
expect(generate(array).code).toEqual('[42, "moo"]');
});
});
describe('createAssignment()', () => {
it('should create an assignment node using the target and value expressions', () => {
const target = expression.ast`x`;
const value = expression.ast`42`;
const assignment = factory.createAssignment(target, value);
expect(generate(assignment).code).toEqual('x = 42');
});
});
describe('createBinaryExpression()', () => {
it('should create a binary operation node using the left and right expressions', () => {
const left = expression.ast`17`;
const right = expression.ast`42`;
const expr = factory.createBinaryExpression(left, '+', right);
expect(generate(expr).code).toEqual('17 + 42');
});
it('should create a binary operation node for logical operators', () => {
const left = expression.ast`17`;
const right = expression.ast`42`;
const expr = factory.createBinaryExpression(left, '&&', right);
expect(t.isLogicalExpression(expr)).toBe(true);
expect(generate(expr).code).toEqual('17 && 42');
});
});
describe('createBlock()', () => {
it('should create a block statement containing the given statements', () => {
const stmt1 = statement.ast`x = 10`;
const stmt2 = statement.ast`y = 20`;
const block = factory.createBlock([stmt1, stmt2]);
expect(generate(block).code).toEqual(['{', ' x = 10;', ' y = 20;', '}'].join('\n'));
});
});
describe('createCallExpression()', () => {
it('should create a call on the `callee` with the given `args`', () => {
const callee = expression.ast`foo`;
const arg1 = expression.ast`42`;
const arg2 = expression.ast`"moo"`;
const call = factory.createCallExpression(callee, [arg1, arg2], false);
expect(generate(call).code).toEqual('foo(42, "moo")');
});
it('should create a call marked with a PURE comment if `pure` is true', () => {
const callee = expression.ast`foo`;
const arg1 = expression.ast`42`;
const arg2 = expression.ast`"moo"`;
const call = factory.createCallExpression(callee, [arg1, arg2], true);
expect(generate(call).code).toEqual('/* @__PURE__ */foo(42, "moo")');
});
});
describe('createConditional()', () => {
it('should create a condition expression', () => {
const test = expression.ast`!test`;
const thenExpr = expression.ast`42`;
const elseExpr = expression.ast`"moo"`;
const conditional = factory.createConditional(test, thenExpr, elseExpr);
expect(generate(conditional).code).toEqual('!test ? 42 : "moo"');
});
});
describe('createElementAccess()', () => {
it('should create an expression accessing the element of an array/object', () => {
const expr = expression.ast`obj`;
const element = expression.ast`"moo"`;
const access = factory.createElementAccess(expr, element);
expect(generate(access).code).toEqual('obj["moo"]');
});
});
describe('createExpressionStatement()', () => {
it('should create a statement node from the given expression', () => {
const expr = expression.ast`x = 10`;
const stmt = factory.createExpressionStatement(expr);
expect(t.isStatement(stmt)).toBe(true);
expect(generate(stmt).code).toEqual('x = 10;');
});
});
describe('createFunctionDeclaration()', () => {
it('should create a function declaration node with the given name, parameters and body statements', () => {
const stmts = statement.ast`{x = 10; y = 20;}`;
const fn = factory.createFunctionDeclaration('foo', ['arg1', 'arg2'], stmts);
expect(generate(fn).code).toEqual(
['function foo(arg1, arg2) {', ' x = 10;', ' y = 20;', '}'].join('\n'),
);
});
});
describe('createFunctionExpression()', () => {
it('should create a function expression node with the given name, parameters and body statements', () => {
const stmts = statement.ast`{x = 10; y = 20;}`;
const fn = factory.createFunctionExpression('foo', ['arg1', 'arg2'], stmts);
expect(t.isStatement(fn)).toBe(false);
expect(generate(fn).code).toEqual(
['function foo(arg1, arg2) {', ' x = 10;', ' y = 20;', '}'].join('\n'),
);
});
it('should create an anonymous function expression node if the name is null', () => {
const stmts = statement.ast`{x = 10; y = 20;}`;
const fn = factory.createFunctionExpression(null, ['arg1', 'arg2'], stmts);
expect(generate(fn).code).toEqual(
['function (arg1, arg2) {', ' x = 10;', ' y = 20;', '}'].join('\n'),
);
});
});
describe('createArrowFunctionExpression()', () => {
it('should create an arrow function with an implicit return if a single statement is provided', () => {
const expr = expression.ast`arg2 + arg1`;
const fn = factory.createArrowFunctionExpression(['arg1', 'arg2'], expr);
expect(generate(fn).code).toEqual('(arg1, arg2) => arg2 + arg1');
});
it('should create an arrow function with an implicit return object literal', () => {
const expr = expression.ast`{a: 1, b: 2}`;
const fn = factory.createArrowFunctionExpression([], expr);
expect(generate(fn).code).toEqual(['() => ({', ' a: 1,', ' b: 2', '})'].join('\n'));
});
it('should create an arrow function with a body when an array of statements is provided', () => {
const stmts = statement.ast`{x = 10; y = 20; return x + y;}`;
const fn = factory.createArrowFunctionExpression(['arg1', 'arg2'], stmts);
expect(generate(fn).code).toEqual(
['(arg1, arg2) => {', ' x = 10;', ' y = 20;', ' return x + y;', '}'].join('\n'),
);
});
});
describe('createIdentifier()', () => {
it('should create an identifier with the given name', () => {
const id = factory.createIdentifier('someId') as t.Identifier;
expect(t.isIdentifier(id)).toBe(true);
expect(id.name).toEqual('someId');
});
});
describe('createDynamicImport()', () => {
it('should create a dynamic import with a string URL', () => {
const url = './some/path';
const dynamicImport = factory.createDynamicImport(url);
expect(generate(dynamicImport).code).toEqual(`import("${url}")`);
});
it('should create a dynamic import with an expression URL', () => {
const url = expression.ast`'/' + 'abc' + '/'`;
const dynamicImport = factory.createDynamicImport(url);
expect(generate(dynamicImport).code).toEqual(`import('/' + 'abc' + '/')`);
});
}); | {
"end_byte": 8550,
"start_byte": 803,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/test/ast/babel_ast_factory_spec.ts"
} |
angular/packages/compiler-cli/linker/babel/test/ast/babel_ast_factory_spec.ts_8554_15502 | describe('createIfStatement()', () => {
it('should create an if-else statement', () => {
const test = expression.ast`!test`;
const thenStmt = statement.ast`x = 10;`;
const elseStmt = statement.ast`x = 42;`;
const ifStmt = factory.createIfStatement(test, thenStmt, elseStmt);
expect(generate(ifStmt).code).toEqual('if (!test) x = 10;else x = 42;');
});
it('should create an if statement if the else expression is null', () => {
const test = expression.ast`!test`;
const thenStmt = statement.ast`x = 10;`;
const ifStmt = factory.createIfStatement(test, thenStmt, null);
expect(generate(ifStmt).code).toEqual('if (!test) x = 10;');
});
});
describe('createLiteral()', () => {
it('should create a string literal', () => {
const literal = factory.createLiteral('moo');
expect(t.isStringLiteral(literal)).toBe(true);
expect(generate(literal).code).toEqual('"moo"');
});
it('should create a number literal', () => {
const literal = factory.createLiteral(42);
expect(t.isNumericLiteral(literal)).toBe(true);
expect(generate(literal).code).toEqual('42');
});
it('should create a number literal for `NaN`', () => {
const literal = factory.createLiteral(NaN);
expect(t.isNumericLiteral(literal)).toBe(true);
expect(generate(literal).code).toEqual('NaN');
});
it('should create a boolean literal', () => {
const literal = factory.createLiteral(true);
expect(t.isBooleanLiteral(literal)).toBe(true);
expect(generate(literal).code).toEqual('true');
});
it('should create an `undefined` literal', () => {
const literal = factory.createLiteral(undefined);
expect(t.isIdentifier(literal)).toBe(true);
expect(generate(literal).code).toEqual('undefined');
});
it('should create a null literal', () => {
const literal = factory.createLiteral(null);
expect(t.isNullLiteral(literal)).toBe(true);
expect(generate(literal).code).toEqual('null');
});
});
describe('createNewExpression()', () => {
it('should create a `new` operation on the constructor `expression` with the given `args`', () => {
const expr = expression.ast`Foo`;
const arg1 = expression.ast`42`;
const arg2 = expression.ast`"moo"`;
const call = factory.createNewExpression(expr, [arg1, arg2]);
expect(generate(call).code).toEqual('new Foo(42, "moo")');
});
});
describe('createObjectLiteral()', () => {
it('should create an object literal node, with the given properties', () => {
const prop1 = expression.ast`42`;
const prop2 = expression.ast`"moo"`;
const obj = factory.createObjectLiteral([
{propertyName: 'prop1', value: prop1, quoted: false},
{propertyName: 'prop2', value: prop2, quoted: true},
]);
expect(generate(obj).code).toEqual(['{', ' prop1: 42,', ' "prop2": "moo"', '}'].join('\n'));
});
});
describe('createParenthesizedExpression()', () => {
it('should add parentheses around the given expression', () => {
const expr = expression.ast`a + b`;
const paren = factory.createParenthesizedExpression(expr);
expect(generate(paren).code).toEqual('(a + b)');
});
});
describe('createPropertyAccess()', () => {
it('should create a property access expression node', () => {
const expr = expression.ast`obj`;
const access = factory.createPropertyAccess(expr, 'moo');
expect(generate(access).code).toEqual('obj.moo');
});
});
describe('createReturnStatement()', () => {
it('should create a return statement returning the given expression', () => {
const expr = expression.ast`42`;
const returnStmt = factory.createReturnStatement(expr);
expect(generate(returnStmt).code).toEqual('return 42;');
});
it('should create a void return statement if the expression is null', () => {
const returnStmt = factory.createReturnStatement(null);
expect(generate(returnStmt).code).toEqual('return;');
});
});
describe('createTaggedTemplate()', () => {
it('should create a tagged template node from the tag, elements and expressions', () => {
const elements = [
{raw: 'raw1', cooked: 'cooked1', range: null},
{raw: 'raw2', cooked: 'cooked2', range: null},
{raw: 'raw3', cooked: 'cooked3', range: null},
];
const expressions = [expression.ast`42`, expression.ast`"moo"`];
const tag = expression.ast`tagFn`;
const template = factory.createTaggedTemplate(tag, {elements, expressions});
expect(generate(template).code).toEqual('tagFn`raw1${42}raw2${"moo"}raw3`');
});
});
describe('createThrowStatement()', () => {
it('should create a throw statement, throwing the given expression', () => {
const expr = expression.ast`new Error("bad")`;
const throwStmt = factory.createThrowStatement(expr);
expect(generate(throwStmt).code).toEqual('throw new Error("bad");');
});
});
describe('createTypeOfExpression()', () => {
it('should create a typeof expression node', () => {
const expr = expression.ast`42`;
const typeofExpr = factory.createTypeOfExpression(expr);
expect(generate(typeofExpr).code).toEqual('typeof 42');
});
});
describe('createUnaryExpression()', () => {
it('should create a unary expression with the operator and operand', () => {
const expr = expression.ast`value`;
const unaryExpr = factory.createUnaryExpression('!', expr);
expect(generate(unaryExpr).code).toEqual('!value');
});
});
describe('createVariableDeclaration()', () => {
it('should create a variable declaration statement node for the given variable name and initializer', () => {
const initializer = expression.ast`42`;
const varDecl = factory.createVariableDeclaration('foo', initializer, 'let');
expect(generate(varDecl).code).toEqual('let foo = 42;');
});
it('should create a constant declaration statement node for the given variable name and initializer', () => {
const initializer = expression.ast`42`;
const varDecl = factory.createVariableDeclaration('foo', initializer, 'const');
expect(generate(varDecl).code).toEqual('const foo = 42;');
});
it('should create a downleveled variable declaration statement node for the given variable name and initializer', () => {
const initializer = expression.ast`42`;
const varDecl = factory.createVariableDeclaration('foo', initializer, 'var');
expect(generate(varDecl).code).toEqual('var foo = 42;');
});
it('should create an uninitialized variable declaration statement node for the given variable name and a null initializer', () => {
const varDecl = factory.createVariableDeclaration('foo', null, 'let');
expect(generate(varDecl).code).toEqual('let foo;');
});
}); | {
"end_byte": 15502,
"start_byte": 8554,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/test/ast/babel_ast_factory_spec.ts"
} |
angular/packages/compiler-cli/linker/babel/test/ast/babel_ast_factory_spec.ts_15506_16923 | describe('setSourceMapRange()', () => {
it('should attach the `sourceMapRange` to the given `node`', () => {
const expr = expression.ast`42`;
expect(expr.loc).toBeUndefined();
expect(expr.start).toBeUndefined();
expect(expr.end).toBeUndefined();
factory.setSourceMapRange(expr, {
start: {line: 0, column: 1, offset: 1},
end: {line: 2, column: 3, offset: 15},
content: '-****\n*****\n****',
url: 'other.ts',
});
// Lines are 1-based in Babel.
expect(expr.loc).toEqual({
filename: 'other.ts',
start: {line: 1, column: 1},
end: {line: 3, column: 3},
} as any); // The typings for `loc` do not include `filename`.
expect(expr.start).toEqual(1);
expect(expr.end).toEqual(15);
});
it('should use undefined if the url is the same as the one passed to the constructor', () => {
const expr = expression.ast`42`;
factory.setSourceMapRange(expr, {
start: {line: 0, column: 1, offset: 1},
end: {line: 2, column: 3, offset: 15},
content: '-****\n*****\n****',
url: '/original.ts',
});
// Lines are 1-based in Babel.
expect(expr.loc).toEqual({
filename: undefined,
start: {line: 1, column: 1},
end: {line: 3, column: 3},
} as any); // The typings for `loc` do not include `filename`.
});
});
}); | {
"end_byte": 16923,
"start_byte": 15506,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/test/ast/babel_ast_factory_spec.ts"
} |
angular/packages/compiler-cli/linker/babel/src/babel_plugin.ts_0_1650 | /**
* @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 {ConfigAPI, PluginObj} from '@babel/core';
import {NodeJSFileSystem} from '../../../src/ngtsc/file_system';
import {ConsoleLogger, LogLevel} from '../../../src/ngtsc/logging';
import {LinkerOptions} from '../../src/file_linker/linker_options';
import {createEs2015LinkerPlugin} from './es2015_linker_plugin';
/**
* This is the Babel plugin definition that is provided as a default export from the package, such
* that the plugin can be used using the module specifier of the package. This is the recommended
* way of integrating the Angular Linker into a build pipeline other than the Angular CLI.
*
* When the module specifier `@angular/compiler-cli/linker/babel` is used as a plugin in a Babel
* configuration, Babel invokes this function (by means of the default export) to create the plugin
* instance according to the provided options.
*
* The linker plugin that is created uses the native NodeJS filesystem APIs to interact with the
* filesystem. Any logging output is printed to the console.
*
* @param api Provides access to the Babel environment that is configuring this plugin.
* @param options The plugin options that have been configured.
*/
export function defaultLinkerPlugin(api: ConfigAPI, options: Partial<LinkerOptions>): PluginObj {
api.assertVersion(7);
return createEs2015LinkerPlugin({
...options,
fileSystem: new NodeJSFileSystem(),
logger: new ConsoleLogger(LogLevel.info),
});
}
| {
"end_byte": 1650,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/src/babel_plugin.ts"
} |
angular/packages/compiler-cli/linker/babel/src/linker_plugin_options.ts_0_608 | /**
* @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 {LinkerOptions} from '../..';
import {ReadonlyFileSystem} from '../../../src/ngtsc/file_system';
import {Logger} from '../../../src/ngtsc/logging';
export interface LinkerPluginOptions extends Partial<LinkerOptions> {
/**
* File-system, used to load up the input source-map and content.
*/
fileSystem: ReadonlyFileSystem;
/**
* Logger used by the linker.
*/
logger: Logger;
}
| {
"end_byte": 608,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/src/linker_plugin_options.ts"
} |
angular/packages/compiler-cli/linker/babel/src/es2015_linker_plugin.ts_0_6414 | /**
* @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 {BabelFile, NodePath, PluginObj, types as t} from '@babel/core';
import {FileLinker, isFatalLinkerError, LinkerEnvironment} from '../../../linker';
import {BabelAstFactory} from './ast/babel_ast_factory';
import {BabelAstHost} from './ast/babel_ast_host';
import {BabelDeclarationScope, ConstantScopePath} from './babel_declaration_scope';
import {LinkerPluginOptions} from './linker_plugin_options';
/**
* Create a Babel plugin that visits the program, identifying and linking partial declarations.
*
* The plugin delegates most of its work to a generic `FileLinker` for each file (`t.Program` in
* Babel) that is visited.
*/
export function createEs2015LinkerPlugin({
fileSystem,
logger,
...options
}: LinkerPluginOptions): PluginObj {
let fileLinker: FileLinker<ConstantScopePath, t.Statement, t.Expression> | null = null;
return {
visitor: {
Program: {
/**
* Create a new `FileLinker` as we enter each file (`t.Program` in Babel).
*/
enter(_, state): void {
assertNull(fileLinker);
// Babel can be configured with a `filename` or `relativeFilename` (or both, or neither) -
// possibly relative to the optional `cwd` path.
const file = state.file;
const filename = file.opts.filename ?? file.opts.filenameRelative;
if (!filename) {
throw new Error(
'No filename (nor filenameRelative) provided by Babel. This is required for the linking of partially compiled directives and components.',
);
}
const sourceUrl = fileSystem.resolve(file.opts.cwd ?? '.', filename);
const linkerEnvironment = LinkerEnvironment.create<t.Statement, t.Expression>(
fileSystem,
logger,
new BabelAstHost(),
new BabelAstFactory(sourceUrl),
options,
);
fileLinker = new FileLinker(linkerEnvironment, sourceUrl, file.code);
},
/**
* On exiting the file, insert any shared constant statements that were generated during
* linking of the partial declarations.
*/
exit(): void {
assertNotNull(fileLinker);
for (const {constantScope, statements} of fileLinker.getConstantStatements()) {
insertStatements(constantScope, statements);
}
fileLinker = null;
},
},
/**
* Test each call expression to see if it is a partial declaration; it if is then replace it
* with the results of linking the declaration.
*/
CallExpression(call: NodePath<t.CallExpression>, state): void {
if (fileLinker === null) {
// Any statements that are inserted upon program exit will be visited outside of an active
// linker context. These call expressions are known not to contain partial declarations,
// so it's safe to skip visiting those call expressions.
return;
}
try {
const calleeName = getCalleeName(call);
if (calleeName === null) {
return;
}
const args = call.node.arguments;
if (!fileLinker.isPartialDeclaration(calleeName) || !isExpressionArray(args)) {
return;
}
const declarationScope = new BabelDeclarationScope(call.scope);
const replacement = fileLinker.linkPartialDeclaration(calleeName, args, declarationScope);
call.replaceWith(replacement);
} catch (e) {
const node = isFatalLinkerError(e) ? (e.node as t.Node) : call.node;
throw buildCodeFrameError(state.file, (e as Error).message, node);
}
},
},
};
}
/**
* Insert the `statements` at the location defined by `path`.
*
* The actual insertion strategy depends upon the type of the `path`.
*/
function insertStatements(path: ConstantScopePath, statements: t.Statement[]): void {
if (path.isProgram()) {
insertIntoProgram(path, statements);
} else {
insertIntoFunction(path, statements);
}
}
/**
* Insert the `statements` at the top of the body of the `fn` function.
*/
function insertIntoFunction(
fn: NodePath<t.FunctionExpression | t.FunctionDeclaration>,
statements: t.Statement[],
): void {
const body = fn.get('body');
body.unshiftContainer('body', statements);
}
/**
* Insert the `statements` at the top of the `program`, below any import statements.
*/
function insertIntoProgram(program: NodePath<t.Program>, statements: t.Statement[]): void {
const body = program.get('body');
const insertBeforeIndex = body.findIndex((statement) => !statement.isImportDeclaration());
if (insertBeforeIndex === -1) {
program.unshiftContainer('body', statements);
} else {
body[insertBeforeIndex].insertBefore(statements);
}
}
function getCalleeName(call: NodePath<t.CallExpression>): string | null {
const callee = call.node.callee;
if (t.isIdentifier(callee)) {
return callee.name;
} else if (t.isMemberExpression(callee) && t.isIdentifier(callee.property)) {
return callee.property.name;
} else if (t.isMemberExpression(callee) && t.isStringLiteral(callee.property)) {
return callee.property.value;
} else {
return null;
}
}
/**
* Return true if all the `nodes` are Babel expressions.
*/
function isExpressionArray(nodes: t.Node[]): nodes is t.Expression[] {
return nodes.every((node) => t.isExpression(node));
}
/**
* Assert that the given `obj` is `null`.
*/
function assertNull<T>(obj: T | null): asserts obj is null {
if (obj !== null) {
throw new Error('BUG - expected `obj` to be null');
}
}
/**
* Assert that the given `obj` is not `null`.
*/
function assertNotNull<T>(obj: T | null): asserts obj is T {
if (obj === null) {
throw new Error('BUG - expected `obj` not to be null');
}
}
/**
* Create a string representation of an error that includes the code frame of the `node`.
*/
function buildCodeFrameError(file: BabelFile, message: string, node: t.Node): string {
const filename = file.opts.filename || '(unknown file)';
const error = file.hub.buildError(node, message);
return `${filename}: ${error.message}`;
}
| {
"end_byte": 6414,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/src/es2015_linker_plugin.ts"
} |
angular/packages/compiler-cli/linker/babel/src/babel_declaration_scope.ts_0_2713 | /**
* @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 {NodePath, types as t} from '@babel/core';
import {DeclarationScope} from '../../../linker';
export type ConstantScopePath =
| NodePath<t.FunctionDeclaration>
| NodePath<t.FunctionExpression>
| NodePath<t.Program>;
/**
* This class represents the lexical scope of a partial declaration in Babel source code.
*
* Its only responsibility is to compute a reference object for the scope of shared constant
* statements that will be generated during partial linking.
*/
export class BabelDeclarationScope implements DeclarationScope<ConstantScopePath, t.Expression> {
/**
* Construct a new `BabelDeclarationScope`.
*
* @param declarationScope the Babel scope containing the declaration call expression.
*/
constructor(private declarationScope: NodePath['scope']) {}
/**
* Compute the Babel `NodePath` that can be used to reference the lexical scope where any
* shared constant statements would be inserted.
*
* There will only be a shared constant scope if the expression is in an ECMAScript module, or a
* UMD module. Otherwise `null` is returned to indicate that constant statements must be emitted
* locally to the generated linked definition, to avoid polluting the global scope.
*
* @param expression the expression that points to the Angular core framework import.
*/
getConstantScopeRef(expression: t.Expression): ConstantScopePath | null {
// If the expression is of the form `a.b.c` then we want to get the far LHS (e.g. `a`).
let bindingExpression = expression;
while (t.isMemberExpression(bindingExpression)) {
bindingExpression = bindingExpression.object;
}
if (!t.isIdentifier(bindingExpression)) {
return null;
}
// The binding of the expression is where this identifier was declared.
// This could be a variable declaration, an import namespace or a function parameter.
const binding = this.declarationScope.getBinding(bindingExpression.name);
if (binding === undefined) {
return null;
}
// We only support shared constant statements if the binding was in a UMD module (i.e. declared
// within a function) or an ECMASCript module (i.e. declared at the top level of a
// `t.Program` that is marked as a module).
const path = binding.scope.path;
if (
!path.isFunctionDeclaration() &&
!path.isFunctionExpression() &&
!(path.isProgram() && path.node.sourceType === 'module')
) {
return null;
}
return path;
}
}
| {
"end_byte": 2713,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/src/babel_declaration_scope.ts"
} |
angular/packages/compiler-cli/linker/babel/src/ast/babel_ast_factory.ts_0_7056 | /**
* @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 {types as t} from '@babel/core';
import {assert} from '../../../../linker';
import {
AstFactory,
BinaryOperator,
LeadingComment,
ObjectLiteralProperty,
SourceMapRange,
TemplateLiteral,
VariableDeclarationType,
} from '../../../../src/ngtsc/translator';
/**
* A Babel flavored implementation of the AstFactory.
*/
export class BabelAstFactory implements AstFactory<t.Statement, t.Expression> {
constructor(
/** The absolute path to the source file being compiled. */
private sourceUrl: string,
) {}
attachComments(statement: t.Statement | t.Expression, leadingComments: LeadingComment[]): void {
// We must process the comments in reverse because `t.addComment()` will add new ones in front.
for (let i = leadingComments.length - 1; i >= 0; i--) {
const comment = leadingComments[i];
t.addComment(statement, 'leading', comment.toString(), !comment.multiline);
}
}
createArrayLiteral = t.arrayExpression;
createAssignment(target: t.Expression, value: t.Expression): t.Expression {
assert(target, isLExpression, 'must be a left hand side expression');
return t.assignmentExpression('=', target, value);
}
createBinaryExpression(
leftOperand: t.Expression,
operator: BinaryOperator,
rightOperand: t.Expression,
): t.Expression {
switch (operator) {
case '&&':
case '||':
case '??':
return t.logicalExpression(operator, leftOperand, rightOperand);
default:
return t.binaryExpression(operator, leftOperand, rightOperand);
}
}
createBlock = t.blockStatement;
createCallExpression(callee: t.Expression, args: t.Expression[], pure: boolean): t.Expression {
const call = t.callExpression(callee, args);
if (pure) {
t.addComment(call, 'leading', ' @__PURE__ ', /* line */ false);
}
return call;
}
createConditional = t.conditionalExpression;
createElementAccess(expression: t.Expression, element: t.Expression): t.Expression {
return t.memberExpression(expression, element, /* computed */ true);
}
createExpressionStatement = t.expressionStatement;
createFunctionDeclaration(
functionName: string,
parameters: string[],
body: t.Statement,
): t.Statement {
assert(body, t.isBlockStatement, 'a block');
return t.functionDeclaration(
t.identifier(functionName),
parameters.map((param) => t.identifier(param)),
body,
);
}
createArrowFunctionExpression(
parameters: string[],
body: t.Statement | t.Expression,
): t.Expression {
if (t.isStatement(body)) {
assert(body, t.isBlockStatement, 'a block');
}
return t.arrowFunctionExpression(
parameters.map((param) => t.identifier(param)),
body,
);
}
createFunctionExpression(
functionName: string | null,
parameters: string[],
body: t.Statement,
): t.Expression {
assert(body, t.isBlockStatement, 'a block');
const name = functionName !== null ? t.identifier(functionName) : null;
return t.functionExpression(
name,
parameters.map((param) => t.identifier(param)),
body,
);
}
createIdentifier = t.identifier;
createIfStatement = t.ifStatement;
createDynamicImport(url: string | t.Expression): t.Expression {
return this.createCallExpression(
t.import(),
[typeof url === 'string' ? t.stringLiteral(url) : url],
false /* pure */,
);
}
createLiteral(value: string | number | boolean | null | undefined): t.Expression {
if (typeof value === 'string') {
return t.stringLiteral(value);
} else if (typeof value === 'number') {
return t.numericLiteral(value);
} else if (typeof value === 'boolean') {
return t.booleanLiteral(value);
} else if (value === undefined) {
return t.identifier('undefined');
} else if (value === null) {
return t.nullLiteral();
} else {
throw new Error(`Invalid literal: ${value} (${typeof value})`);
}
}
createNewExpression = t.newExpression;
createObjectLiteral(properties: ObjectLiteralProperty<t.Expression>[]): t.Expression {
return t.objectExpression(
properties.map((prop) => {
const key = prop.quoted
? t.stringLiteral(prop.propertyName)
: t.identifier(prop.propertyName);
return t.objectProperty(key, prop.value);
}),
);
}
createParenthesizedExpression = t.parenthesizedExpression;
createPropertyAccess(expression: t.Expression, propertyName: string): t.Expression {
return t.memberExpression(expression, t.identifier(propertyName), /* computed */ false);
}
createReturnStatement = t.returnStatement;
createTaggedTemplate(tag: t.Expression, template: TemplateLiteral<t.Expression>): t.Expression {
const elements = template.elements.map((element, i) =>
this.setSourceMapRange(
t.templateElement(element, i === template.elements.length - 1),
element.range,
),
);
return t.taggedTemplateExpression(tag, t.templateLiteral(elements, template.expressions));
}
createThrowStatement = t.throwStatement;
createTypeOfExpression(expression: t.Expression): t.Expression {
return t.unaryExpression('typeof', expression);
}
createUnaryExpression = t.unaryExpression;
createVariableDeclaration(
variableName: string,
initializer: t.Expression | null,
type: VariableDeclarationType,
): t.Statement {
return t.variableDeclaration(type, [
t.variableDeclarator(t.identifier(variableName), initializer),
]);
}
setSourceMapRange<T extends t.Statement | t.Expression | t.TemplateElement>(
node: T,
sourceMapRange: SourceMapRange | null,
): T {
if (sourceMapRange === null) {
return node;
}
node.loc = {
// Add in the filename so that we can map to external template files.
// Note that Babel gets confused if you specify a filename when it is the original source
// file. This happens when the template is inline, in which case just use `undefined`.
filename: sourceMapRange.url !== this.sourceUrl ? sourceMapRange.url : undefined,
start: {
line: sourceMapRange.start.line + 1, // lines are 1-based in Babel.
column: sourceMapRange.start.column,
},
end: {
line: sourceMapRange.end.line + 1, // lines are 1-based in Babel.
column: sourceMapRange.end.column,
},
} as any; // Needed because the Babel typings for `loc` don't include `filename`.
node.start = sourceMapRange.start.offset;
node.end = sourceMapRange.end.offset;
return node;
}
}
function isLExpression(expr: t.Expression): expr is Extract<t.LVal, t.Expression> {
// Some LVal types are not expressions, which prevents us from using `t.isLVal()`
// directly with `assert()`.
return t.isLVal(expr);
}
| {
"end_byte": 7056,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/src/ast/babel_ast_factory.ts"
} |
angular/packages/compiler-cli/linker/babel/src/ast/babel_ast_host.ts_0_6908 | /**
* @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 {types as t} from '@babel/core';
import {assert, AstHost, FatalLinkerError, Range} from '../../../../linker';
/**
* This implementation of `AstHost` is able to get information from Babel AST nodes.
*/
export class BabelAstHost implements AstHost<t.Expression> {
getSymbolName(node: t.Expression): string | null {
if (t.isIdentifier(node)) {
return node.name;
} else if (t.isMemberExpression(node) && t.isIdentifier(node.property)) {
return node.property.name;
} else {
return null;
}
}
isStringLiteral = t.isStringLiteral;
parseStringLiteral(str: t.Expression): string {
assert(str, t.isStringLiteral, 'a string literal');
return str.value;
}
isNumericLiteral = t.isNumericLiteral;
parseNumericLiteral(num: t.Expression): number {
assert(num, t.isNumericLiteral, 'a numeric literal');
return num.value;
}
isBooleanLiteral(bool: t.Expression): boolean {
return t.isBooleanLiteral(bool) || isMinifiedBooleanLiteral(bool);
}
parseBooleanLiteral(bool: t.Expression): boolean {
if (t.isBooleanLiteral(bool)) {
return bool.value;
} else if (isMinifiedBooleanLiteral(bool)) {
return !bool.argument.value;
} else {
throw new FatalLinkerError(bool, 'Unsupported syntax, expected a boolean literal.');
}
}
isNull(node: t.Expression): boolean {
return t.isNullLiteral(node);
}
isArrayLiteral = t.isArrayExpression;
parseArrayLiteral(array: t.Expression): t.Expression[] {
assert(array, t.isArrayExpression, 'an array literal');
return array.elements.map((element) => {
assert(element, isNotEmptyElement, 'element in array not to be empty');
assert(element, isNotSpreadElement, 'element in array not to use spread syntax');
return element;
});
}
isObjectLiteral = t.isObjectExpression;
parseObjectLiteral(obj: t.Expression): Map<string, t.Expression> {
assert(obj, t.isObjectExpression, 'an object literal');
const result = new Map<string, t.Expression>();
for (const property of obj.properties) {
assert(property, t.isObjectProperty, 'a property assignment');
assert(property.value, t.isExpression, 'an expression');
assert(property.key, isObjectExpressionPropertyName, 'a property name');
const key = t.isIdentifier(property.key) ? property.key.name : property.key.value;
result.set(`${key}`, property.value);
}
return result;
}
isFunctionExpression(
node: t.Expression,
): node is Extract<t.Function | t.ArrowFunctionExpression, t.Expression> {
return t.isFunction(node) || t.isArrowFunctionExpression(node);
}
parseReturnValue(fn: t.Expression): t.Expression {
assert(fn, this.isFunctionExpression, 'a function');
if (!t.isBlockStatement(fn.body)) {
// it is a simple array function expression: `(...) => expr`
return fn.body;
}
// it is a function (arrow or normal) with a body. E.g.:
// * `(...) => { stmt; ... }`
// * `function(...) { stmt; ... }`
if (fn.body.body.length !== 1) {
throw new FatalLinkerError(
fn.body,
'Unsupported syntax, expected a function body with a single return statement.',
);
}
const stmt = fn.body.body[0];
assert(stmt, t.isReturnStatement, 'a function body with a single return statement');
// Babel declares `argument` as optional and nullable, so we account for both scenarios.
if (stmt.argument === null || stmt.argument === undefined) {
throw new FatalLinkerError(stmt, 'Unsupported syntax, expected function to return a value.');
}
return stmt.argument;
}
parseParameters(fn: t.Expression): t.Expression[] {
assert(fn, this.isFunctionExpression, 'a function');
return fn.params.map((param) => {
assert(param, t.isIdentifier, 'an identifier');
return param;
});
}
isCallExpression = t.isCallExpression;
parseCallee(call: t.Expression): t.Expression {
assert(call, t.isCallExpression, 'a call expression');
assert(call.callee, t.isExpression, 'an expression');
return call.callee;
}
parseArguments(call: t.Expression): t.Expression[] {
assert(call, t.isCallExpression, 'a call expression');
return call.arguments.map((arg) => {
assert(arg, isNotSpreadArgument, 'argument not to use spread syntax');
assert(arg, t.isExpression, 'argument to be an expression');
return arg;
});
}
getRange(node: t.Expression): Range {
if (node.loc == null || node.start == null || node.end == null) {
throw new FatalLinkerError(
node,
'Unable to read range for node - it is missing location information.',
);
}
return {
startLine: node.loc.start.line - 1, // Babel lines are 1-based
startCol: node.loc.start.column,
startPos: node.start,
endPos: node.end,
};
}
}
/**
* Return true if the expression does not represent an empty element in an array literal.
* For example in `[,foo]` the first element is "empty".
*/
function isNotEmptyElement(
e: t.Expression | t.SpreadElement | null,
): e is t.Expression | t.SpreadElement {
return e !== null;
}
/**
* Return true if the expression is not a spread element of an array literal.
* For example in `[x, ...rest]` the `...rest` expression is a spread element.
*/
function isNotSpreadElement(e: t.Expression | t.SpreadElement): e is t.Expression {
return !t.isSpreadElement(e);
}
/**
* Return true if the node can be considered a text based property name for an
* object expression.
*
* Notably in the Babel AST, object patterns (for destructuring) could be of type
* `t.PrivateName` so we need a distinction between object expressions and patterns.
*/
function isObjectExpressionPropertyName(
n: t.Node,
): n is t.Identifier | t.StringLiteral | t.NumericLiteral {
return t.isIdentifier(n) || t.isStringLiteral(n) || t.isNumericLiteral(n);
}
/**
* The declared type of an argument to a call expression.
*/
type ArgumentType = t.CallExpression['arguments'][number];
/**
* Return true if the argument is not a spread element.
*/
function isNotSpreadArgument(arg: ArgumentType): arg is Exclude<ArgumentType, t.SpreadElement> {
return !t.isSpreadElement(arg);
}
type MinifiedBooleanLiteral = t.Expression & t.UnaryExpression & {argument: t.NumericLiteral};
/**
* Return true if the node is either `!0` or `!1`.
*/
function isMinifiedBooleanLiteral(node: t.Expression): node is MinifiedBooleanLiteral {
return (
t.isUnaryExpression(node) &&
node.prefix &&
node.operator === '!' &&
t.isNumericLiteral(node.argument) &&
(node.argument.value === 0 || node.argument.value === 1)
);
}
| {
"end_byte": 6908,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/babel/src/ast/babel_ast_host.ts"
} |
angular/packages/compiler-cli/linker/src/fatal_linker_error.ts_0_769 | /**
* @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
*/
/**
* An unrecoverable error during linking.
*/
export class FatalLinkerError extends Error {
readonly type = 'FatalLinkerError';
/**
* Create a new FatalLinkerError.
*
* @param node The AST node where the error occurred.
* @param message A description of the error.
*/
constructor(
public node: unknown,
message: string,
) {
super(message);
}
}
/**
* Whether the given object `e` is a FatalLinkerError.
*/
export function isFatalLinkerError(e: any): e is FatalLinkerError {
return e && e.type === 'FatalLinkerError';
}
| {
"end_byte": 769,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/fatal_linker_error.ts"
} |
angular/packages/compiler-cli/linker/src/linker_import_generator.ts_0_1454 | /**
* @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 {AstFactory, ImportGenerator, ImportRequest} from '../../src/ngtsc/translator';
import {FatalLinkerError} from './fatal_linker_error';
/**
* A class that is used to generate imports when translating from Angular Output AST to an AST to
* render, such as Babel.
*
* Note that, in the linker, there can only be imports from `@angular/core` and that these imports
* must be achieved by property access on an `ng` namespace identifier, which is passed in via the
* constructor.
*/
export class LinkerImportGenerator<TStatement, TExpression>
implements ImportGenerator<null, TExpression>
{
constructor(
private factory: AstFactory<TStatement, TExpression>,
private ngImport: TExpression,
) {}
addImport(request: ImportRequest<null>): TExpression {
this.assertModuleName(request.exportModuleSpecifier);
if (request.exportSymbolName === null) {
return this.ngImport;
}
return this.factory.createPropertyAccess(this.ngImport, request.exportSymbolName);
}
private assertModuleName(moduleName: string): void {
if (moduleName !== '@angular/core') {
throw new FatalLinkerError(
this.ngImport,
`Unable to import from anything other than '@angular/core'`,
);
}
}
}
| {
"end_byte": 1454,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/linker_import_generator.ts"
} |
angular/packages/compiler-cli/linker/src/ast/ast_value.ts_0_7584 | /**
* @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 * as o from '@angular/compiler';
import {FatalLinkerError} from '../fatal_linker_error';
import {AstHost, Range} from './ast_host';
/**
* Represents only those types in `T` that are object types.
*
* Note: Excluding `Array` types as we consider object literals are "objects"
* in the AST.
*/
type ObjectType<T> = T extends Array<any> ? never : T extends Record<string, any> ? T : never;
/**
* Represents the value type of an object literal.
*/
type ObjectValueType<T> = T extends Record<string, infer R> ? R : never;
/**
* Represents the value type of an array literal.
*/
type ArrayValueType<T> = T extends Array<infer R> ? R : never;
/**
* Ensures that `This` has its generic type `Actual` conform to the expected generic type in
* `Expected`, to disallow calling a method if the generic type does not conform.
*/
type ConformsTo<This, Actual, Expected> = Actual extends Expected ? This : never;
/**
* Represents only the string keys of type `T`.
*/
type PropertyKey<T> = keyof T & string;
/**
* This helper class wraps an object expression along with an `AstHost` object, exposing helper
* methods that make it easier to extract the properties of the object.
*
* The generic `T` is used as reference type of the expected structure that is represented by this
* object. It does not achieve full type-safety for the provided operations in correspondence with
* `T`; its main goal is to provide references to a documented type and ensure that the properties
* that are read from the object are present.
*
* Unfortunately, the generic types are unable to prevent reading an optional property from the
* object without first having called `has` to ensure that the property exists. This is one example
* of where full type-safety is not achieved.
*/
export class AstObject<T extends object, TExpression> {
/**
* Create a new `AstObject` from the given `expression` and `host`.
*/
static parse<T extends object, TExpression>(
expression: TExpression,
host: AstHost<TExpression>,
): AstObject<T, TExpression> {
const obj = host.parseObjectLiteral(expression);
return new AstObject<T, TExpression>(expression, obj, host);
}
private constructor(
readonly expression: TExpression,
private obj: Map<string, TExpression>,
private host: AstHost<TExpression>,
) {}
/**
* Returns true if the object has a property called `propertyName`.
*/
has(propertyName: PropertyKey<T>): boolean {
return this.obj.has(propertyName);
}
/**
* Returns the number value of the property called `propertyName`.
*
* Throws an error if there is no such property or the property is not a number.
*/
getNumber<K extends PropertyKey<T>>(
this: ConformsTo<this, T[K], number>,
propertyName: K,
): number {
return this.host.parseNumericLiteral(this.getRequiredProperty(propertyName));
}
/**
* Returns the string value of the property called `propertyName`.
*
* Throws an error if there is no such property or the property is not a string.
*/
getString<K extends PropertyKey<T>>(
this: ConformsTo<this, T[K], string>,
propertyName: K,
): string {
return this.host.parseStringLiteral(this.getRequiredProperty(propertyName));
}
/**
* Returns the boolean value of the property called `propertyName`.
*
* Throws an error if there is no such property or the property is not a boolean.
*/
getBoolean<K extends PropertyKey<T>>(
this: ConformsTo<this, T[K], boolean>,
propertyName: K,
): boolean {
return this.host.parseBooleanLiteral(this.getRequiredProperty(propertyName)) as any;
}
/**
* Returns the nested `AstObject` parsed from the property called `propertyName`.
*
* Throws an error if there is no such property or the property is not an object.
*/
getObject<K extends PropertyKey<T>>(
this: ConformsTo<this, T[K], object>,
propertyName: K,
): AstObject<ObjectType<T[K]>, TExpression> {
const expr = this.getRequiredProperty(propertyName);
const obj = this.host.parseObjectLiteral(expr);
return new AstObject<ObjectType<T[K]>, TExpression>(expr, obj, this.host);
}
/**
* Returns an array of `AstValue` objects parsed from the property called `propertyName`.
*
* Throws an error if there is no such property or the property is not an array.
*/
getArray<K extends PropertyKey<T>>(
this: ConformsTo<this, T[K], unknown[]>,
propertyName: K,
): AstValue<ArrayValueType<T[K]>, TExpression>[] {
const arr = this.host.parseArrayLiteral(this.getRequiredProperty(propertyName));
return arr.map((entry) => new AstValue<ArrayValueType<T[K]>, TExpression>(entry, this.host));
}
/**
* Returns a `WrappedNodeExpr` object that wraps the expression at the property called
* `propertyName`.
*
* Throws an error if there is no such property.
*/
getOpaque(propertyName: PropertyKey<T>): o.WrappedNodeExpr<TExpression> {
return new o.WrappedNodeExpr(this.getRequiredProperty(propertyName));
}
/**
* Returns the raw `TExpression` value of the property called `propertyName`.
*
* Throws an error if there is no such property.
*/
getNode(propertyName: PropertyKey<T>): TExpression {
return this.getRequiredProperty(propertyName);
}
/**
* Returns an `AstValue` that wraps the value of the property called `propertyName`.
*
* Throws an error if there is no such property.
*/
getValue<K extends PropertyKey<T>>(propertyName: K): AstValue<T[K], TExpression> {
return new AstValue<T[K], TExpression>(this.getRequiredProperty(propertyName), this.host);
}
/**
* Converts the AstObject to a raw JavaScript object, mapping each property value (as an
* `AstValue`) to the generic type (`T`) via the `mapper` function.
*/
toLiteral<V>(
mapper: (value: AstValue<ObjectValueType<T>, TExpression>, key: string) => V,
): Record<string, V> {
const result: Record<string, V> = {};
for (const [key, expression] of this.obj) {
result[key] = mapper(
new AstValue<ObjectValueType<T>, TExpression>(expression, this.host),
key,
);
}
return result;
}
/**
* Converts the AstObject to a JavaScript Map, mapping each property value (as an
* `AstValue`) to the generic type (`T`) via the `mapper` function.
*/
toMap<V>(mapper: (value: AstValue<ObjectValueType<T>, TExpression>) => V): Map<string, V> {
const result = new Map<string, V>();
for (const [key, expression] of this.obj) {
result.set(key, mapper(new AstValue<ObjectValueType<T>, TExpression>(expression, this.host)));
}
return result;
}
private getRequiredProperty(propertyName: PropertyKey<T>): TExpression {
if (!this.obj.has(propertyName)) {
throw new FatalLinkerError(
this.expression,
`Expected property '${propertyName}' to be present.`,
);
}
return this.obj.get(propertyName)!;
}
}
/**
* This helper class wraps an `expression`, exposing methods that use the `host` to give
* access to the underlying value of the wrapped expression.
*
* The generic `T` is used as reference type of the expected type that is represented by this value.
* It does not achieve full type-safety for the provided operations in correspondence with `T`; its
* main goal is to provide references to a documented type.
*/ | {
"end_byte": 7584,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/ast/ast_value.ts"
} |
angular/packages/compiler-cli/linker/src/ast/ast_value.ts_7585_11657 | export class AstValue<T, TExpression> {
/** Type brand that ensures that the `T` type is respected for assignability. */
ɵtypeBrand: T = null!;
constructor(
readonly expression: TExpression,
private host: AstHost<TExpression>,
) {}
/**
* Get the name of the symbol represented by the given expression node, or `null` if it is not a
* symbol.
*/
getSymbolName(): string | null {
return this.host.getSymbolName(this.expression);
}
/**
* Is this value a number?
*/
isNumber(): boolean {
return this.host.isNumericLiteral(this.expression);
}
/**
* Parse the number from this value, or error if it is not a number.
*/
getNumber(this: ConformsTo<this, T, number>): number {
return this.host.parseNumericLiteral(this.expression);
}
/**
* Is this value a string?
*/
isString(): boolean {
return this.host.isStringLiteral(this.expression);
}
/**
* Parse the string from this value, or error if it is not a string.
*/
getString(this: ConformsTo<this, T, string>): string {
return this.host.parseStringLiteral(this.expression);
}
/**
* Is this value a boolean?
*/
isBoolean(): boolean {
return this.host.isBooleanLiteral(this.expression);
}
/**
* Parse the boolean from this value, or error if it is not a boolean.
*/
getBoolean(this: ConformsTo<this, T, boolean>): boolean {
return this.host.parseBooleanLiteral(this.expression);
}
/**
* Is this value an object literal?
*/
isObject(): boolean {
return this.host.isObjectLiteral(this.expression);
}
/**
* Parse this value into an `AstObject`, or error if it is not an object literal.
*/
getObject(this: ConformsTo<this, T, object>): AstObject<ObjectType<T>, TExpression> {
return AstObject.parse<ObjectType<T>, TExpression>(this.expression, this.host);
}
/**
* Is this value an array literal?
*/
isArray(): boolean {
return this.host.isArrayLiteral(this.expression);
}
/** Whether the value is explicitly set to `null`. */
isNull(): boolean {
return this.host.isNull(this.expression);
}
/**
* Parse this value into an array of `AstValue` objects, or error if it is not an array literal.
*/
getArray(this: ConformsTo<this, T, unknown[]>): AstValue<ArrayValueType<T>, TExpression>[] {
const arr = this.host.parseArrayLiteral(this.expression);
return arr.map((entry) => new AstValue<ArrayValueType<T>, TExpression>(entry, this.host));
}
/**
* Is this value a function expression?
*/
isFunction(): boolean {
return this.host.isFunctionExpression(this.expression);
}
/**
* Extract the return value as an `AstValue` from this value as a function expression, or error if
* it is not a function expression.
*/
getFunctionReturnValue<R>(this: ConformsTo<this, T, Function>): AstValue<R, TExpression> {
return new AstValue(this.host.parseReturnValue(this.expression), this.host);
}
/**
* Extract the parameters from this value as a function expression, or error if it is not a
* function expression.
*/
getFunctionParameters<R>(this: ConformsTo<this, T, Function>): AstValue<R, TExpression>[] {
return this.host
.parseParameters(this.expression)
.map((param) => new AstValue(param, this.host));
}
isCallExpression(): boolean {
return this.host.isCallExpression(this.expression);
}
getCallee(): AstValue<unknown, TExpression> {
return new AstValue(this.host.parseCallee(this.expression), this.host);
}
getArguments(): AstValue<unknown, TExpression>[] {
const args = this.host.parseArguments(this.expression);
return args.map((arg) => new AstValue(arg, this.host));
}
/**
* Return the `TExpression` of this value wrapped in a `WrappedNodeExpr`.
*/
getOpaque(): o.WrappedNodeExpr<TExpression> {
return new o.WrappedNodeExpr(this.expression);
}
/**
* Get the range of the location of this value in the original source.
*/
getRange(): Range {
return this.host.getRange(this.expression);
}
}
| {
"end_byte": 11657,
"start_byte": 7585,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/ast/ast_value.ts"
} |
angular/packages/compiler-cli/linker/src/ast/utils.ts_0_598 | /**
* @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 {FatalLinkerError} from '../fatal_linker_error';
/**
* Assert that the given `node` is of the type guarded by the `predicate` function.
*/
export function assert<T, K extends T>(
node: T,
predicate: (node: T) => node is K,
expected: string,
): asserts node is K {
if (!predicate(node)) {
throw new FatalLinkerError(node, `Unsupported syntax, expected ${expected}.`);
}
}
| {
"end_byte": 598,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/ast/utils.ts"
} |
angular/packages/compiler-cli/linker/src/ast/ast_host.ts_0_4268 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* An abstraction for getting information from an AST while being agnostic to the underlying AST
* implementation.
*/
export interface AstHost<TExpression> {
/**
* Get the name of the symbol represented by the given expression node, or `null` if it is not a
* symbol.
*/
getSymbolName(node: TExpression): string | null;
/**
* Return `true` if the given expression is a string literal, or false otherwise.
*/
isStringLiteral(node: TExpression): boolean;
/**
* Parse the string value from the given expression, or throw if it is not a string literal.
*/
parseStringLiteral(str: TExpression): string;
/**
* Return `true` if the given expression is a numeric literal, or false otherwise.
*/
isNumericLiteral(node: TExpression): boolean;
/**
* Parse the numeric value from the given expression, or throw if it is not a numeric literal.
*/
parseNumericLiteral(num: TExpression): number;
/**
* Return `true` if the given expression can be considered a boolean literal, or false otherwise.
*
* Note that this should also cover the special case of some minified code where `true` and
* `false` are replaced by `!0` and `!1` respectively.
*/
isBooleanLiteral(node: TExpression): boolean;
/**
* Parse the boolean value from the given expression, or throw if it is not a boolean literal.
*
* Note that this should also cover the special case of some minified code where `true` and
* `false` are replaced by `!0` and `!1` respectively.
*/
parseBooleanLiteral(bool: TExpression): boolean;
/**
* Returns `true` if the value corresponds to `null`.
*/
isNull(node: TExpression): boolean;
/**
* Return `true` if the given expression is an array literal, or false otherwise.
*/
isArrayLiteral(node: TExpression): boolean;
/**
* Parse an array of expressions from the given expression, or throw if it is not an array
* literal.
*/
parseArrayLiteral(array: TExpression): TExpression[];
/**
* Return `true` if the given expression is an object literal, or false otherwise.
*/
isObjectLiteral(node: TExpression): boolean;
/**
* Parse the given expression into a map of object property names to property expressions, or
* throw if it is not an object literal.
*/
parseObjectLiteral(obj: TExpression): Map<string, TExpression>;
/**
* Return `true` if the given expression is a function, or false otherwise.
*/
isFunctionExpression(node: TExpression): boolean;
/**
* Compute the "value" of a function expression by parsing its body for a single `return`
* statement, extracting the returned expression, or throw if it is not possible.
*/
parseReturnValue(fn: TExpression): TExpression;
/**
* Returns the parameter expressions for the function, or throw if it is not a function.
*/
parseParameters(fn: TExpression): TExpression[];
/**
* Return true if the given expression is a call expression, or false otherwise.
*/
isCallExpression(node: TExpression): boolean;
/**
* Returns the expression that is called in the provided call expression, or throw if it is not
* a call expression.
*/
parseCallee(call: TExpression): TExpression;
/**
* Returns the argument expressions for the provided call expression, or throw if it is not
* a call expression.
*/
parseArguments(call: TExpression): TExpression[];
/**
* Compute the location range of the expression in the source file, to be used for source-mapping.
*/
getRange(node: TExpression): Range;
}
/**
* The location of the start and end of an expression in the original source file.
*/
export interface Range {
/** 0-based character position of the range start in the source file text. */
startPos: number;
/** 0-based line index of the range start in the source file text. */
startLine: number;
/** 0-based column position of the range start in the source file text. */
startCol: number;
/** 0-based character position of the range end in the source file text. */
endPos: number;
}
| {
"end_byte": 4268,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/ast/ast_host.ts"
} |
angular/packages/compiler-cli/linker/src/ast/typescript/typescript_ast_host.ts_0_6943 | /**
* @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 {FatalLinkerError} from '../../fatal_linker_error';
import {AstHost, Range} from '../ast_host';
import {assert} from '../utils';
/**
* This implementation of `AstHost` is able to get information from TypeScript AST nodes.
*
* This host is not actually used at runtime in the current code.
*
* It is implemented here to ensure that the `AstHost` abstraction is not unfairly skewed towards
* the Babel implementation. It could also provide a basis for a 3rd TypeScript compiler plugin to
* do linking in the future.
*/
export class TypeScriptAstHost implements AstHost<ts.Expression> {
getSymbolName(node: ts.Expression): string | null {
if (ts.isIdentifier(node)) {
return node.text;
} else if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name)) {
return node.name.text;
} else {
return null;
}
}
isStringLiteral = ts.isStringLiteral;
parseStringLiteral(str: ts.Expression): string {
assert(str, this.isStringLiteral, 'a string literal');
return str.text;
}
isNull(node: ts.Expression): boolean {
return node.kind === ts.SyntaxKind.NullKeyword;
}
isNumericLiteral = ts.isNumericLiteral;
parseNumericLiteral(num: ts.Expression): number {
assert(num, this.isNumericLiteral, 'a numeric literal');
return parseInt(num.text);
}
isBooleanLiteral(node: ts.Expression): boolean {
return isBooleanLiteral(node) || isMinifiedBooleanLiteral(node);
}
parseBooleanLiteral(bool: ts.Expression): boolean {
if (isBooleanLiteral(bool)) {
return bool.kind === ts.SyntaxKind.TrueKeyword;
} else if (isMinifiedBooleanLiteral(bool)) {
return !+bool.operand.text;
} else {
throw new FatalLinkerError(bool, 'Unsupported syntax, expected a boolean literal.');
}
}
isArrayLiteral = ts.isArrayLiteralExpression;
parseArrayLiteral(array: ts.Expression): ts.Expression[] {
assert(array, this.isArrayLiteral, 'an array literal');
return array.elements.map((element) => {
assert(element, isNotEmptyElement, 'element in array not to be empty');
assert(element, isNotSpreadElement, 'element in array not to use spread syntax');
return element;
});
}
isObjectLiteral = ts.isObjectLiteralExpression;
parseObjectLiteral(obj: ts.Expression): Map<string, ts.Expression> {
assert(obj, this.isObjectLiteral, 'an object literal');
const result = new Map<string, ts.Expression>();
for (const property of obj.properties) {
assert(property, ts.isPropertyAssignment, 'a property assignment');
assert(property.name, isPropertyName, 'a property name');
result.set(property.name.text, property.initializer);
}
return result;
}
isFunctionExpression(node: ts.Expression): node is ts.FunctionExpression | ts.ArrowFunction {
return ts.isFunctionExpression(node) || ts.isArrowFunction(node);
}
parseReturnValue(fn: ts.Expression): ts.Expression {
assert(fn, this.isFunctionExpression, 'a function');
if (!ts.isBlock(fn.body)) {
// it is a simple array function expression: `(...) => expr`
return fn.body;
}
// it is a function (arrow or normal) with a body. E.g.:
// * `(...) => { stmt; ... }`
// * `function(...) { stmt; ... }`
if (fn.body.statements.length !== 1) {
throw new FatalLinkerError(
fn.body,
'Unsupported syntax, expected a function body with a single return statement.',
);
}
const stmt = fn.body.statements[0];
assert(stmt, ts.isReturnStatement, 'a function body with a single return statement');
if (stmt.expression === undefined) {
throw new FatalLinkerError(stmt, 'Unsupported syntax, expected function to return a value.');
}
return stmt.expression;
}
parseParameters(fn: ts.Expression): ts.Expression[] {
assert(fn, this.isFunctionExpression, 'a function');
return fn.parameters.map((param) => {
assert(param.name, ts.isIdentifier, 'an identifier');
if (param.dotDotDotToken) {
throw new FatalLinkerError(fn.body, 'Unsupported syntax, expected an identifier.');
}
return param.name;
});
}
isCallExpression = ts.isCallExpression;
parseCallee(call: ts.Expression): ts.Expression {
assert(call, ts.isCallExpression, 'a call expression');
return call.expression;
}
parseArguments(call: ts.Expression): ts.Expression[] {
assert(call, ts.isCallExpression, 'a call expression');
return call.arguments.map((arg) => {
assert(arg, isNotSpreadElement, 'argument not to use spread syntax');
return arg;
});
}
getRange(node: ts.Expression): Range {
const file = node.getSourceFile();
if (file === undefined) {
throw new FatalLinkerError(
node,
'Unable to read range for node - it is missing parent information.',
);
}
const startPos = node.getStart();
const endPos = node.getEnd();
const {line: startLine, character: startCol} = ts.getLineAndCharacterOfPosition(file, startPos);
return {startLine, startCol, startPos, endPos};
}
}
/**
* Return true if the expression does not represent an empty element in an array literal.
* For example in `[,foo]` the first element is "empty".
*/
function isNotEmptyElement(
e: ts.Expression | ts.SpreadElement | ts.OmittedExpression,
): e is ts.Expression | ts.SpreadElement {
return !ts.isOmittedExpression(e);
}
/**
* Return true if the expression is not a spread element of an array literal.
* For example in `[x, ...rest]` the `...rest` expression is a spread element.
*/
function isNotSpreadElement(e: ts.Expression | ts.SpreadElement): e is ts.Expression {
return !ts.isSpreadElement(e);
}
/**
* Return true if the expression can be considered a text based property name.
*/
function isPropertyName(
e: ts.PropertyName,
): e is ts.Identifier | ts.StringLiteral | ts.NumericLiteral {
return ts.isIdentifier(e) || ts.isStringLiteral(e) || ts.isNumericLiteral(e);
}
/**
* Return true if the node is either `true` or `false` literals.
*/
function isBooleanLiteral(node: ts.Expression): node is ts.TrueLiteral | ts.FalseLiteral {
return node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword;
}
type MinifiedBooleanLiteral = ts.PrefixUnaryExpression & {operand: ts.NumericLiteral};
/**
* Return true if the node is either `!0` or `!1`.
*/
function isMinifiedBooleanLiteral(node: ts.Expression): node is MinifiedBooleanLiteral {
return (
ts.isPrefixUnaryExpression(node) &&
node.operator === ts.SyntaxKind.ExclamationToken &&
ts.isNumericLiteral(node.operand) &&
(node.operand.text === '0' || node.operand.text === '1')
);
}
| {
"end_byte": 6943,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/ast/typescript/typescript_ast_host.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/translator.ts_0_1574 | /**
* @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 * as o from '@angular/compiler';
import {
AstFactory,
Context,
ExpressionTranslatorVisitor,
ImportGenerator,
TranslatorOptions,
} from '../../../src/ngtsc/translator';
/**
* Generic translator helper class, which exposes methods for translating expressions and
* statements.
*/
export class Translator<TStatement, TExpression> {
constructor(private factory: AstFactory<TStatement, TExpression>) {}
/**
* Translate the given output AST in the context of an expression.
*/
translateExpression(
expression: o.Expression,
imports: ImportGenerator<null, TExpression>,
options: TranslatorOptions<TExpression> = {},
): TExpression {
return expression.visitExpression(
new ExpressionTranslatorVisitor<null, TStatement, TExpression>(
this.factory,
imports,
null,
options,
),
new Context(false),
);
}
/**
* Translate the given output AST in the context of a statement.
*/
translateStatement(
statement: o.Statement,
imports: ImportGenerator<null, TExpression>,
options: TranslatorOptions<TExpression> = {},
): TStatement {
return statement.visitStatement(
new ExpressionTranslatorVisitor<null, TStatement, TExpression>(
this.factory,
imports,
null,
options,
),
new Context(true),
);
}
}
| {
"end_byte": 1574,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/translator.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/get_source_file.ts_0_1227 | /**
* @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 '../../../src/ngtsc/file_system';
import {SourceFile, SourceFileLoader} from '../../../src/ngtsc/sourcemaps';
/**
* A function that will return a `SourceFile` object (or null) for the current file being linked.
*/
export type GetSourceFileFn = () => SourceFile | null;
/**
* Create a `GetSourceFileFn` that will return the `SourceFile` being linked or `null`, if not
* available.
*/
export function createGetSourceFile(
sourceUrl: AbsoluteFsPath,
code: string,
loader: SourceFileLoader | null,
): GetSourceFileFn {
if (loader === null) {
// No source-mapping so just return a function that always returns `null`.
return () => null;
} else {
// Source-mapping is available so return a function that will load (and cache) the `SourceFile`.
let sourceFile: SourceFile | null | undefined = undefined;
return () => {
if (sourceFile === undefined) {
sourceFile = loader.loadSourceFile(sourceUrl, code);
}
return sourceFile;
};
}
}
| {
"end_byte": 1227,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/get_source_file.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/declaration_scope.ts_0_1818 | /**
* @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
*/
/**
* This interface represents the lexical scope of a partial declaration in the source code.
*
* For example, if you had the following code:
*
* ```
* function foo() {
* function bar () {
* ɵɵngDeclareDirective({...});
* }
* }
* ```
*
* The `DeclarationScope` of the `ɵɵngDeclareDirective()` call is the body of the `bar()` function.
*
* The `FileLinker` uses this object to identify the lexical scope of any constant statements that
* might be generated by the linking process (i.e. where the `ConstantPool` lives for a set of
* partial linkers).
*/
export interface DeclarationScope<TSharedConstantScope, TExpression> {
/**
* Get a `TSharedConstantScope` object that can be used to reference the lexical scope where any
* shared constant statements would be inserted.
*
* This object is generic because different AST implementations will need different
* `TConstantScope` types to be able to insert shared constant statements. For example in Babel
* this would be a `NodePath` object; in TS it would just be a `Node` object.
*
* If it is not possible to find such a shared scope, then constant statements will be wrapped up
* with their generated linked definition expression, in the form of an IIFE.
*
* @param expression the expression that points to the Angular core framework import.
* @returns a reference to a reference object for where the shared constant statements will be
* inserted, or `null` if it is not possible to have a shared scope.
*/
getConstantScopeRef(expression: TExpression): TSharedConstantScope | null;
}
| {
"end_byte": 1818,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/declaration_scope.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/linker_environment.ts_0_1905 | /**
* @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 {ReadonlyFileSystem} from '../../../src/ngtsc/file_system';
import {Logger} from '../../../src/ngtsc/logging';
import {SourceFileLoader} from '../../../src/ngtsc/sourcemaps';
import {AstFactory} from '../../../src/ngtsc/translator';
import {AstHost} from '../ast/ast_host';
import {DEFAULT_LINKER_OPTIONS, LinkerOptions} from './linker_options';
import {Translator} from './translator';
export class LinkerEnvironment<TStatement, TExpression> {
readonly translator: Translator<TStatement, TExpression>;
readonly sourceFileLoader: SourceFileLoader | null;
private constructor(
readonly fileSystem: ReadonlyFileSystem,
readonly logger: Logger,
readonly host: AstHost<TExpression>,
readonly factory: AstFactory<TStatement, TExpression>,
readonly options: LinkerOptions,
) {
this.translator = new Translator<TStatement, TExpression>(this.factory);
this.sourceFileLoader = this.options.sourceMapping
? new SourceFileLoader(this.fileSystem, this.logger, {})
: null;
}
static create<TStatement, TExpression>(
fileSystem: ReadonlyFileSystem,
logger: Logger,
host: AstHost<TExpression>,
factory: AstFactory<TStatement, TExpression>,
options: Partial<LinkerOptions>,
): LinkerEnvironment<TStatement, TExpression> {
return new LinkerEnvironment(fileSystem, logger, host, factory, {
sourceMapping: options.sourceMapping ?? DEFAULT_LINKER_OPTIONS.sourceMapping,
linkerJitMode: options.linkerJitMode ?? DEFAULT_LINKER_OPTIONS.linkerJitMode,
unknownDeclarationVersionHandling:
options.unknownDeclarationVersionHandling ??
DEFAULT_LINKER_OPTIONS.unknownDeclarationVersionHandling,
});
}
}
| {
"end_byte": 1905,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/linker_environment.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/linker_options.ts_0_1505 | /**
* @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
*/
/**
* Options to configure the linking behavior.
*/
export interface LinkerOptions {
/**
* Whether to use source-mapping to compute the original source for external templates.
* The default is `true`.
*/
sourceMapping: boolean;
/**
* This option tells the linker to generate information used by a downstream JIT compiler.
*
* Specifically, in JIT mode, NgModule definitions must describe the `declarations`, `imports`,
* `exports`, etc, which are otherwise not needed.
*/
linkerJitMode: boolean;
/**
* How to handle a situation where a partial declaration matches none of the supported
* partial-linker versions.
*
* - `error` - the version mismatch is a fatal error.
* - `warn` - a warning is sent to the logger but the most recent partial-linker
* will attempt to process the declaration anyway.
* - `ignore` - the most recent partial-linker will, silently, attempt to process
* the declaration.
*
* The default is `error`.
*/
unknownDeclarationVersionHandling: 'ignore' | 'warn' | 'error';
}
/**
* The default linker options to use if properties are not provided.
*/
export const DEFAULT_LINKER_OPTIONS: LinkerOptions = {
sourceMapping: true,
linkerJitMode: false,
unknownDeclarationVersionHandling: 'error',
};
| {
"end_byte": 1505,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/linker_options.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/file_linker.ts_0_4662 | /**
* @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 {R3PartialDeclaration} from '@angular/compiler';
import {AbsoluteFsPath} from '../../../src/ngtsc/file_system';
import {AstObject} from '../ast/ast_value';
import {DeclarationScope} from './declaration_scope';
import {EmitScope} from './emit_scopes/emit_scope';
import {LocalEmitScope} from './emit_scopes/local_emit_scope';
import {LinkerEnvironment} from './linker_environment';
import {createLinkerMap, PartialLinkerSelector} from './partial_linkers/partial_linker_selector';
export const NO_STATEMENTS: Readonly<any[]> = [] as const;
/**
* This class is responsible for linking all the partial declarations found in a single file.
*/
export class FileLinker<TConstantScope, TStatement, TExpression> {
private linkerSelector: PartialLinkerSelector<TExpression>;
private emitScopes = new Map<TConstantScope, EmitScope<TStatement, TExpression>>();
constructor(
private linkerEnvironment: LinkerEnvironment<TStatement, TExpression>,
sourceUrl: AbsoluteFsPath,
code: string,
) {
this.linkerSelector = new PartialLinkerSelector<TExpression>(
createLinkerMap(this.linkerEnvironment, sourceUrl, code),
this.linkerEnvironment.logger,
this.linkerEnvironment.options.unknownDeclarationVersionHandling,
);
}
/**
* Return true if the given callee name matches a partial declaration that can be linked.
*/
isPartialDeclaration(calleeName: string): boolean {
return this.linkerSelector.supportsDeclaration(calleeName);
}
/**
* Link the metadata extracted from the args of a call to a partial declaration function.
*
* The `declarationScope` is used to determine the scope and strategy of emission of the linked
* definition and any shared constant statements.
*
* @param declarationFn the name of the function used to declare the partial declaration - e.g.
* `ɵɵngDeclareDirective`.
* @param args the arguments passed to the declaration function, should be a single object that
* corresponds to the `R3DeclareDirectiveMetadata` or `R3DeclareComponentMetadata` interfaces.
* @param declarationScope the scope that contains this call to the declaration function.
*/
linkPartialDeclaration(
declarationFn: string,
args: TExpression[],
declarationScope: DeclarationScope<TConstantScope, TExpression>,
): TExpression {
if (args.length !== 1) {
throw new Error(
`Invalid function call: It should have only a single object literal argument, but contained ${args.length}.`,
);
}
const metaObj = AstObject.parse<R3PartialDeclaration, TExpression>(
args[0],
this.linkerEnvironment.host,
);
const ngImport = metaObj.getNode('ngImport');
const emitScope = this.getEmitScope(ngImport, declarationScope);
const minVersion = metaObj.getString('minVersion');
const version = metaObj.getString('version');
const linker = this.linkerSelector.getLinker(declarationFn, minVersion, version);
const definition = linker.linkPartialDeclaration(emitScope.constantPool, metaObj, version);
return emitScope.translateDefinition(definition);
}
/**
* Return all the shared constant statements and their associated constant scope references, so
* that they can be inserted into the source code.
*/
getConstantStatements(): {constantScope: TConstantScope; statements: TStatement[]}[] {
const results: {constantScope: TConstantScope; statements: TStatement[]}[] = [];
for (const [constantScope, emitScope] of this.emitScopes.entries()) {
const statements = emitScope.getConstantStatements();
results.push({constantScope, statements});
}
return results;
}
private getEmitScope(
ngImport: TExpression,
declarationScope: DeclarationScope<TConstantScope, TExpression>,
): EmitScope<TStatement, TExpression> {
const constantScope = declarationScope.getConstantScopeRef(ngImport);
if (constantScope === null) {
// There is no constant scope so we will emit extra statements into the definition IIFE.
return new LocalEmitScope(
ngImport,
this.linkerEnvironment.translator,
this.linkerEnvironment.factory,
);
}
if (!this.emitScopes.has(constantScope)) {
this.emitScopes.set(
constantScope,
new EmitScope(ngImport, this.linkerEnvironment.translator, this.linkerEnvironment.factory),
);
}
return this.emitScopes.get(constantScope)!;
}
}
| {
"end_byte": 4662,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/file_linker.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/needs_linking.ts_0_1211 | /**
* @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 {declarationFunctions} from './partial_linkers/partial_linker_selector';
/**
* Determines if the provided source file may need to be processed by the linker, i.e. whether it
* potentially contains any declarations. If true is returned, then the source file should be
* processed by the linker as it may contain declarations that need to be fully compiled. If false
* is returned, parsing and processing of the source file can safely be skipped to improve
* performance.
*
* This function may return true even for source files that don't actually contain any declarations
* that need to be compiled.
*
* @param path the absolute path of the source file for which to determine whether linking may be
* needed.
* @param source the source file content as a string.
* @returns whether the source file may contain declarations that need to be linked.
*/
export function needsLinking(path: string, source: string): boolean {
return declarationFunctions.some((fn) => source.includes(fn));
}
| {
"end_byte": 1211,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/needs_linking.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/emit_scopes/local_emit_scope.ts_0_1624 | /**
* @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 {LinkedDefinition} from '../partial_linkers/partial_linker';
import {EmitScope} from './emit_scope';
/**
* This class is a specialization of the `EmitScope` class that is designed for the situation where
* there is no clear shared scope for constant statements. In this case they are bundled with the
* translated definition and will be emitted into an IIFE.
*/
export class LocalEmitScope<TStatement, TExpression> extends EmitScope<TStatement, TExpression> {
/**
* Translate the given Output AST definition expression into a generic `TExpression`.
*
* Merges the `ConstantPool` statements with the definition statements when generating the
* definition expression. This means that `ConstantPool` statements will be emitted into an IIFE.
*/
override translateDefinition(definition: LinkedDefinition): TExpression {
// Treat statements from the ConstantPool as definition statements.
return super.translateDefinition({
expression: definition.expression,
statements: [...this.constantPool.statements, ...definition.statements],
});
}
/**
* It is not valid to call this method, since there will be no shared constant statements - they
* are already emitted in the IIFE alongside the translated definition.
*/
override getConstantStatements(): TStatement[] {
throw new Error('BUG - LocalEmitScope should not expose any constant statements');
}
}
| {
"end_byte": 1624,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/emit_scopes/local_emit_scope.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/emit_scopes/emit_scope.ts_0_3338 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ConstantPool, outputAst as o} from '@angular/compiler';
import {AstFactory} from '../../../../src/ngtsc/translator';
import {LinkerImportGenerator} from '../../linker_import_generator';
import {LinkedDefinition} from '../partial_linkers/partial_linker';
import {Translator} from '../translator';
/**
* This class represents (from the point of view of the `FileLinker`) the scope in which
* statements and expressions related to a linked partial declaration will be emitted.
*
* It holds a copy of a `ConstantPool` that is used to capture any constant statements that need to
* be emitted in this context.
*
* This implementation will emit the definition and the constant statements separately.
*/
export class EmitScope<TStatement, TExpression> {
readonly constantPool = new ConstantPool();
constructor(
protected readonly ngImport: TExpression,
protected readonly translator: Translator<TStatement, TExpression>,
private readonly factory: AstFactory<TStatement, TExpression>,
) {}
/**
* Translate the given Output AST definition expression into a generic `TExpression`.
*
* Use a `LinkerImportGenerator` to handle any imports in the definition.
*/
translateDefinition(definition: LinkedDefinition): TExpression {
const expression = this.translator.translateExpression(
definition.expression,
new LinkerImportGenerator(this.factory, this.ngImport),
);
if (definition.statements.length > 0) {
// Definition statements must be emitted "after" the declaration for which the definition is
// being emitted. However, the linker only transforms individual declaration calls, and can't
// insert statements after definitions. To work around this, the linker transforms the
// definition into an IIFE which executes the definition statements before returning the
// definition expression.
const importGenerator = new LinkerImportGenerator(this.factory, this.ngImport);
return this.wrapInIifeWithStatements(
expression,
definition.statements.map((statement) =>
this.translator.translateStatement(statement, importGenerator),
),
);
} else {
// Since there are no definition statements, just return the definition expression directly.
return expression;
}
}
/**
* Return any constant statements that are shared between all uses of this `EmitScope`.
*/
getConstantStatements(): TStatement[] {
const importGenerator = new LinkerImportGenerator(this.factory, this.ngImport);
return this.constantPool.statements.map((statement) =>
this.translator.translateStatement(statement, importGenerator),
);
}
private wrapInIifeWithStatements(expression: TExpression, statements: TStatement[]): TExpression {
const returnStatement = this.factory.createReturnStatement(expression);
const body = this.factory.createBlock([...statements, returnStatement]);
const fn = this.factory.createFunctionExpression(/* name */ null, /* args */ [], body);
return this.factory.createCallExpression(fn, /* args */ [], /* pure */ false);
}
}
| {
"end_byte": 3338,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/emit_scopes/emit_scope.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_linker.ts_0_1056 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ConstantPool, outputAst as o, R3PartialDeclaration} from '@angular/compiler';
import {AstObject} from '../../ast/ast_value';
/**
* A definition generated by a `PartialLinker`, ready to emit.
*/
export interface LinkedDefinition {
expression: o.Expression;
statements: o.Statement[];
}
/**
* An interface for classes that can link partial declarations into full definitions.
*/
export interface PartialLinker<TExpression> {
/**
* Link the partial declaration `metaObj` information to generate a full definition expression.
*
* @param metaObj An object that fits one of the `R3DeclareDirectiveMetadata` or
* `R3DeclareComponentMetadata` interfaces.
*/
linkPartialDeclaration(
constantPool: ConstantPool,
metaObj: AstObject<R3PartialDeclaration, TExpression>,
version: string,
): LinkedDefinition;
}
| {
"end_byte": 1056,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_linker.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_injector_linker_1.ts_0_1724 | /**
* @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 {
compileInjector,
ConstantPool,
outputAst as o,
R3DeclareInjectorMetadata,
R3InjectorMetadata,
R3PartialDeclaration,
} from '@angular/compiler';
import {AstObject} from '../../ast/ast_value';
import {FatalLinkerError} from '../../fatal_linker_error';
import {LinkedDefinition, PartialLinker} from './partial_linker';
import {wrapReference} from './util';
/**
* A `PartialLinker` that is designed to process `ɵɵngDeclareInjector()` call expressions.
*/
export class PartialInjectorLinkerVersion1<TExpression> implements PartialLinker<TExpression> {
linkPartialDeclaration(
constantPool: ConstantPool,
metaObj: AstObject<R3PartialDeclaration, TExpression>,
): LinkedDefinition {
const meta = toR3InjectorMeta(metaObj);
return compileInjector(meta);
}
}
/**
* Derives the `R3InjectorMetadata` structure from the AST object.
*/
export function toR3InjectorMeta<TExpression>(
metaObj: AstObject<R3DeclareInjectorMetadata, TExpression>,
): R3InjectorMetadata {
const typeExpr = metaObj.getValue('type');
const typeName = typeExpr.getSymbolName();
if (typeName === null) {
throw new FatalLinkerError(
typeExpr.expression,
'Unsupported type, its name could not be determined',
);
}
return {
name: typeName,
type: wrapReference(typeExpr.getOpaque()),
providers: metaObj.has('providers') ? metaObj.getOpaque('providers') : null,
imports: metaObj.has('imports') ? metaObj.getArray('imports').map((i) => i.getOpaque()) : [],
};
}
| {
"end_byte": 1724,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_injector_linker_1.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_class_metadata_linker_1.ts_0_1467 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
compileClassMetadata,
ConstantPool,
outputAst as o,
R3ClassMetadata,
R3DeclareClassMetadata,
R3PartialDeclaration,
} from '@angular/compiler';
import {AstObject} from '../../ast/ast_value';
import {LinkedDefinition, PartialLinker} from './partial_linker';
/**
* A `PartialLinker` that is designed to process `ɵɵngDeclareClassMetadata()` call expressions.
*/
export class PartialClassMetadataLinkerVersion1<TExpression> implements PartialLinker<TExpression> {
linkPartialDeclaration(
constantPool: ConstantPool,
metaObj: AstObject<R3PartialDeclaration, TExpression>,
): LinkedDefinition {
const meta = toR3ClassMetadata(metaObj);
return {
expression: compileClassMetadata(meta),
statements: [],
};
}
}
/**
* Derives the `R3ClassMetadata` structure from the AST object.
*/
export function toR3ClassMetadata<TExpression>(
metaObj: AstObject<R3DeclareClassMetadata, TExpression>,
): R3ClassMetadata {
return {
type: metaObj.getOpaque('type'),
decorators: metaObj.getOpaque('decorators'),
ctorParameters: metaObj.has('ctorParameters') ? metaObj.getOpaque('ctorParameters') : null,
propDecorators: metaObj.has('propDecorators') ? metaObj.getOpaque('propDecorators') : null,
};
}
| {
"end_byte": 1467,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_class_metadata_linker_1.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_component_linker_1.ts_0_2387 | /**
* @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 {
BoundTarget,
ChangeDetectionStrategy,
compileComponentFromMetadata,
ConstantPool,
DeclarationListEmitMode,
DEFAULT_INTERPOLATION_CONFIG,
DeferBlockDepsEmitMode,
ForwardRefHandling,
InterpolationConfig,
makeBindingParser,
outputAst as o,
parseTemplate,
R3ComponentDeferMetadata,
R3ComponentMetadata,
R3DeclareComponentMetadata,
R3DeclareDirectiveDependencyMetadata,
R3DeclarePipeDependencyMetadata,
R3DirectiveDependencyMetadata,
R3PartialDeclaration,
R3TargetBinder,
R3TemplateDependencyKind,
R3TemplateDependencyMetadata,
SelectorMatcher,
TmplAstDeferredBlock,
ViewEncapsulation,
} from '@angular/compiler';
import semver from 'semver';
import {AbsoluteFsPath} from '../../../../src/ngtsc/file_system';
import {Range} from '../../ast/ast_host';
import {AstObject, AstValue} from '../../ast/ast_value';
import {FatalLinkerError} from '../../fatal_linker_error';
import {GetSourceFileFn} from '../get_source_file';
import {toR3DirectiveMeta} from './partial_directive_linker_1';
import {LinkedDefinition, PartialLinker} from './partial_linker';
import {extractForwardRef, PLACEHOLDER_VERSION} from './util';
function makeDirectiveMetadata<TExpression>(
directiveExpr: AstObject<R3DeclareDirectiveDependencyMetadata, TExpression>,
typeExpr: o.WrappedNodeExpr<TExpression>,
isComponentByDefault: true | null = null,
): R3DirectiveDependencyMetadata {
return {
kind: R3TemplateDependencyKind.Directive,
isComponent:
isComponentByDefault ||
(directiveExpr.has('kind') && directiveExpr.getString('kind') === 'component'),
type: typeExpr,
selector: directiveExpr.getString('selector'),
inputs: directiveExpr.has('inputs')
? directiveExpr.getArray('inputs').map((input) => input.getString())
: [],
outputs: directiveExpr.has('outputs')
? directiveExpr.getArray('outputs').map((input) => input.getString())
: [],
exportAs: directiveExpr.has('exportAs')
? directiveExpr.getArray('exportAs').map((exportAs) => exportAs.getString())
: null,
};
}
/**
* A `PartialLinker` that is designed to process `ɵɵngDeclareComponent()` call expressions.
*/
e | {
"end_byte": 2387,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_component_linker_1.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_component_linker_1.ts_2388_10745 | port class PartialComponentLinkerVersion1<TStatement, TExpression>
implements PartialLinker<TExpression>
{
constructor(
private readonly getSourceFile: GetSourceFileFn,
private sourceUrl: AbsoluteFsPath,
private code: string,
) {}
linkPartialDeclaration(
constantPool: ConstantPool,
metaObj: AstObject<R3PartialDeclaration, TExpression>,
version: string,
): LinkedDefinition {
const meta = this.toR3ComponentMeta(metaObj, version);
return compileComponentFromMetadata(meta, constantPool, makeBindingParser());
}
/**
* This function derives the `R3ComponentMetadata` from the provided AST object.
*/
private toR3ComponentMeta(
metaObj: AstObject<R3DeclareComponentMetadata, TExpression>,
version: string,
): R3ComponentMetadata<R3TemplateDependencyMetadata> {
const interpolation = parseInterpolationConfig(metaObj);
const templateSource = metaObj.getValue('template');
const isInline = metaObj.has('isInline') ? metaObj.getBoolean('isInline') : false;
const templateInfo = this.getTemplateInfo(templateSource, isInline);
const {major, minor} = new semver.SemVer(version);
// Enable the new block syntax if compiled with v17 and
// above, or when using the local placeholder version.
const enableBlockSyntax = major >= 17 || version === PLACEHOLDER_VERSION;
const enableLetSyntax =
major > 18 || (major === 18 && minor >= 1) || version === PLACEHOLDER_VERSION;
const template = parseTemplate(templateInfo.code, templateInfo.sourceUrl, {
escapedString: templateInfo.isEscaped,
interpolationConfig: interpolation,
range: templateInfo.range,
enableI18nLegacyMessageIdFormat: false,
preserveWhitespaces: metaObj.has('preserveWhitespaces')
? metaObj.getBoolean('preserveWhitespaces')
: false,
// We normalize line endings if the template is was inline.
i18nNormalizeLineEndingsInICUs: isInline,
enableBlockSyntax,
enableLetSyntax,
});
if (template.errors !== null) {
const errors = template.errors.map((err) => err.toString()).join('\n');
throw new FatalLinkerError(
templateSource.expression,
`Errors found in the template:\n${errors}`,
);
}
const binder = new R3TargetBinder(new SelectorMatcher());
const boundTarget = binder.bind({template: template.nodes});
let declarationListEmitMode = DeclarationListEmitMode.Direct;
const extractDeclarationTypeExpr = (
type: AstValue<o.Expression | (() => o.Expression), TExpression>,
) => {
const {expression, forwardRef} = extractForwardRef(type);
if (forwardRef === ForwardRefHandling.Unwrapped) {
declarationListEmitMode = DeclarationListEmitMode.Closure;
}
return expression;
};
let declarations: R3TemplateDependencyMetadata[] = [];
// There are two ways that declarations (directives/pipes) can be represented in declare
// metadata. The "old style" uses separate fields for each (arrays for components/directives and
// an object literal for pipes). The "new style" uses a unified `dependencies` array. For
// backwards compatibility, both are processed and unified here:
// Process the old style fields:
if (metaObj.has('components')) {
declarations.push(
...metaObj.getArray('components').map((dir) => {
const dirExpr = dir.getObject();
const typeExpr = extractDeclarationTypeExpr(dirExpr.getValue('type'));
return makeDirectiveMetadata(dirExpr, typeExpr, /* isComponentByDefault */ true);
}),
);
}
if (metaObj.has('directives')) {
declarations.push(
...metaObj.getArray('directives').map((dir) => {
const dirExpr = dir.getObject();
const typeExpr = extractDeclarationTypeExpr(dirExpr.getValue('type'));
return makeDirectiveMetadata(dirExpr, typeExpr);
}),
);
}
if (metaObj.has('pipes')) {
const pipes = metaObj.getObject('pipes').toMap((pipe) => pipe);
for (const [name, type] of pipes) {
const typeExpr = extractDeclarationTypeExpr(type);
declarations.push({
kind: R3TemplateDependencyKind.Pipe,
name,
type: typeExpr,
});
}
}
// Process the new style field:
if (metaObj.has('dependencies')) {
for (const dep of metaObj.getArray('dependencies')) {
const depObj = dep.getObject();
const typeExpr = extractDeclarationTypeExpr(depObj.getValue('type'));
switch (depObj.getString('kind')) {
case 'directive':
case 'component':
declarations.push(makeDirectiveMetadata(depObj, typeExpr));
break;
case 'pipe':
const pipeObj = depObj as AstObject<
R3DeclarePipeDependencyMetadata & {kind: 'pipe'},
TExpression
>;
declarations.push({
kind: R3TemplateDependencyKind.Pipe,
name: pipeObj.getString('name'),
type: typeExpr,
});
break;
case 'ngmodule':
declarations.push({
kind: R3TemplateDependencyKind.NgModule,
type: typeExpr,
});
break;
default:
// Skip unknown types of dependencies.
continue;
}
}
}
return {
...toR3DirectiveMeta(metaObj, this.code, this.sourceUrl, version),
viewProviders: metaObj.has('viewProviders') ? metaObj.getOpaque('viewProviders') : null,
template: {
nodes: template.nodes,
ngContentSelectors: template.ngContentSelectors,
},
declarationListEmitMode,
styles: metaObj.has('styles')
? metaObj.getArray('styles').map((entry) => entry.getString())
: [],
defer: this.createR3ComponentDeferMetadata(metaObj, boundTarget),
encapsulation: metaObj.has('encapsulation')
? parseEncapsulation(metaObj.getValue('encapsulation'))
: ViewEncapsulation.Emulated,
interpolation,
changeDetection: metaObj.has('changeDetection')
? parseChangeDetectionStrategy(metaObj.getValue('changeDetection'))
: ChangeDetectionStrategy.Default,
animations: metaObj.has('animations') ? metaObj.getOpaque('animations') : null,
relativeContextFilePath: this.sourceUrl,
i18nUseExternalIds: false,
declarations,
};
}
/**
* Update the range to remove the start and end chars, which should be quotes around the template.
*/
private getTemplateInfo(
templateNode: AstValue<unknown, TExpression>,
isInline: boolean,
): TemplateInfo {
const range = templateNode.getRange();
if (!isInline) {
// If not marked as inline, then we try to get the template info from the original external
// template file, via source-mapping.
const externalTemplate = this.tryExternalTemplate(range);
if (externalTemplate !== null) {
return externalTemplate;
}
}
// Either the template is marked inline or we failed to find the original external template.
// So just use the literal string from the partially compiled component declaration.
return this.templateFromPartialCode(templateNode, range);
}
private tryExternalTemplate(range: Range): TemplateInfo | null {
const sourceFile = this.getSourceFile();
if (sourceFile === null) {
return null;
}
const pos = sourceFile.getOriginalLocation(range.startLine, range.startCol);
// Only interested if the original location is in an "external" template file:
// * the file is different to the current file
// * the file does not end in `.js` or `.ts` (we expect it to be something like `.html`).
// * the range starts at the beginning of the file
if (
pos === null ||
pos.file === this.sourceUrl ||
/\.[jt]s$/.test(pos.file) ||
pos.line !== 0 ||
pos.column !== 0
) {
return null;
}
const templateContents = sourceFile.sources.find(
(src) => src?.sourcePath === pos.file,
)!.contents;
return {
code: templateContents,
sourceUrl: pos.file,
range: {startPos: 0, startLine: 0, startCol: 0, endPos: templateContents.length},
isEscaped: false,
};
}
| {
"end_byte": 10745,
"start_byte": 2388,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_component_linker_1.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_component_linker_1.ts_10749_14550 | ivate templateFromPartialCode(
templateNode: AstValue<unknown, TExpression>,
{startPos, endPos, startLine, startCol}: Range,
): TemplateInfo {
if (!/["'`]/.test(this.code[startPos]) || this.code[startPos] !== this.code[endPos - 1]) {
throw new FatalLinkerError(
templateNode.expression,
`Expected the template string to be wrapped in quotes but got: ${this.code.substring(
startPos,
endPos,
)}`,
);
}
return {
code: this.code,
sourceUrl: this.sourceUrl,
range: {startPos: startPos + 1, endPos: endPos - 1, startLine, startCol: startCol + 1},
isEscaped: true,
};
}
private createR3ComponentDeferMetadata(
metaObj: AstObject<R3DeclareComponentMetadata, TExpression>,
boundTarget: BoundTarget<any>,
): R3ComponentDeferMetadata {
const deferredBlocks = boundTarget.getDeferBlocks();
const blocks = new Map<TmplAstDeferredBlock, o.Expression | null>();
const dependencies = metaObj.has('deferBlockDependencies')
? metaObj.getArray('deferBlockDependencies')
: null;
for (let i = 0; i < deferredBlocks.length; i++) {
const matchingDependencyFn = dependencies?.[i];
if (matchingDependencyFn == null) {
blocks.set(deferredBlocks[i], null);
} else {
blocks.set(
deferredBlocks[i],
matchingDependencyFn.isNull() ? null : matchingDependencyFn.getOpaque(),
);
}
}
return {mode: DeferBlockDepsEmitMode.PerBlock, blocks};
}
}
interface TemplateInfo {
code: string;
sourceUrl: string;
range: Range;
isEscaped: boolean;
}
/**
* Extract an `InterpolationConfig` from the component declaration.
*/
function parseInterpolationConfig<TExpression>(
metaObj: AstObject<R3DeclareComponentMetadata, TExpression>,
): InterpolationConfig {
if (!metaObj.has('interpolation')) {
return DEFAULT_INTERPOLATION_CONFIG;
}
const interpolationExpr = metaObj.getValue('interpolation');
const values = interpolationExpr.getArray().map((entry) => entry.getString());
if (values.length !== 2) {
throw new FatalLinkerError(
interpolationExpr.expression,
'Unsupported interpolation config, expected an array containing exactly two strings',
);
}
return InterpolationConfig.fromArray(values as [string, string]);
}
/**
* Determines the `ViewEncapsulation` mode from the AST value's symbol name.
*/
function parseEncapsulation<TExpression>(
encapsulation: AstValue<ViewEncapsulation | undefined, TExpression>,
): ViewEncapsulation {
const symbolName = encapsulation.getSymbolName();
if (symbolName === null) {
throw new FatalLinkerError(
encapsulation.expression,
'Expected encapsulation to have a symbol name',
);
}
const enumValue = ViewEncapsulation[symbolName as keyof typeof ViewEncapsulation];
if (enumValue === undefined) {
throw new FatalLinkerError(encapsulation.expression, 'Unsupported encapsulation');
}
return enumValue;
}
/**
* Determines the `ChangeDetectionStrategy` from the AST value's symbol name.
*/
function parseChangeDetectionStrategy<TExpression>(
changeDetectionStrategy: AstValue<ChangeDetectionStrategy | undefined, TExpression>,
): ChangeDetectionStrategy {
const symbolName = changeDetectionStrategy.getSymbolName();
if (symbolName === null) {
throw new FatalLinkerError(
changeDetectionStrategy.expression,
'Expected change detection strategy to have a symbol name',
);
}
const enumValue = ChangeDetectionStrategy[symbolName as keyof typeof ChangeDetectionStrategy];
if (enumValue === undefined) {
throw new FatalLinkerError(
changeDetectionStrategy.expression,
'Unsupported change detection strategy',
);
}
return enumValue;
}
| {
"end_byte": 14550,
"start_byte": 10749,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_component_linker_1.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_pipe_linker_1.ts_0_1939 | /**
* @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 {
compilePipeFromMetadata,
ConstantPool,
outputAst as o,
R3DeclarePipeMetadata,
R3PartialDeclaration,
R3PipeMetadata,
} from '@angular/compiler';
import {AstObject} from '../../ast/ast_value';
import {FatalLinkerError} from '../../fatal_linker_error';
import {LinkedDefinition, PartialLinker} from './partial_linker';
import {getDefaultStandaloneValue, wrapReference} from './util';
/**
* A `PartialLinker` that is designed to process `ɵɵngDeclarePipe()` call expressions.
*/
export class PartialPipeLinkerVersion1<TExpression> implements PartialLinker<TExpression> {
constructor() {}
linkPartialDeclaration(
constantPool: ConstantPool,
metaObj: AstObject<R3PartialDeclaration, TExpression>,
version: string,
): LinkedDefinition {
const meta = toR3PipeMeta(metaObj, version);
return compilePipeFromMetadata(meta);
}
}
/**
* Derives the `R3PipeMetadata` structure from the AST object.
*/
export function toR3PipeMeta<TExpression>(
metaObj: AstObject<R3DeclarePipeMetadata, TExpression>,
version: string,
): R3PipeMetadata {
const typeExpr = metaObj.getValue('type');
const typeName = typeExpr.getSymbolName();
if (typeName === null) {
throw new FatalLinkerError(
typeExpr.expression,
'Unsupported type, its name could not be determined',
);
}
const pure = metaObj.has('pure') ? metaObj.getBoolean('pure') : true;
const isStandalone = metaObj.has('isStandalone')
? metaObj.getBoolean('isStandalone')
: getDefaultStandaloneValue(version);
return {
name: typeName,
type: wrapReference(typeExpr.getOpaque()),
typeArgumentCount: 0,
deps: null,
pipeName: metaObj.getString('name'),
pure,
isStandalone,
};
}
| {
"end_byte": 1939,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_pipe_linker_1.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_directive_linker_1.ts_0_7844 | /**
* @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 {
compileDirectiveFromMetadata,
ConstantPool,
ForwardRefHandling,
LegacyInputPartialMapping,
makeBindingParser,
outputAst as o,
ParseLocation,
ParseSourceFile,
ParseSourceSpan,
R3DeclareDirectiveMetadata,
R3DeclareHostDirectiveMetadata,
R3DeclareQueryMetadata,
R3DirectiveMetadata,
R3HostDirectiveMetadata,
R3HostMetadata,
R3InputMetadata,
R3PartialDeclaration,
R3QueryMetadata,
} from '@angular/compiler';
import {AbsoluteFsPath} from '../../../../src/ngtsc/file_system';
import {Range} from '../../ast/ast_host';
import {AstObject, AstValue} from '../../ast/ast_value';
import {FatalLinkerError} from '../../fatal_linker_error';
import {LinkedDefinition, PartialLinker} from './partial_linker';
import {extractForwardRef, getDefaultStandaloneValue, wrapReference} from './util';
/**
* A `PartialLinker` that is designed to process `ɵɵngDeclareDirective()` call expressions.
*/
export class PartialDirectiveLinkerVersion1<TExpression> implements PartialLinker<TExpression> {
constructor(
private sourceUrl: AbsoluteFsPath,
private code: string,
) {}
linkPartialDeclaration(
constantPool: ConstantPool,
metaObj: AstObject<R3PartialDeclaration, TExpression>,
version: string,
): LinkedDefinition {
const meta = toR3DirectiveMeta(metaObj, this.code, this.sourceUrl, version);
return compileDirectiveFromMetadata(meta, constantPool, makeBindingParser());
}
}
/**
* Derives the `R3DirectiveMetadata` structure from the AST object.
*/
export function toR3DirectiveMeta<TExpression>(
metaObj: AstObject<R3DeclareDirectiveMetadata, TExpression>,
code: string,
sourceUrl: AbsoluteFsPath,
version: string,
): R3DirectiveMetadata {
const typeExpr = metaObj.getValue('type');
const typeName = typeExpr.getSymbolName();
if (typeName === null) {
throw new FatalLinkerError(
typeExpr.expression,
'Unsupported type, its name could not be determined',
);
}
return {
typeSourceSpan: createSourceSpan(typeExpr.getRange(), code, sourceUrl),
type: wrapReference(typeExpr.getOpaque()),
typeArgumentCount: 0,
deps: null,
host: toHostMetadata(metaObj),
inputs: metaObj.has('inputs') ? metaObj.getObject('inputs').toLiteral(toInputMapping) : {},
outputs: metaObj.has('outputs')
? metaObj.getObject('outputs').toLiteral((value) => value.getString())
: {},
queries: metaObj.has('queries')
? metaObj.getArray('queries').map((entry) => toQueryMetadata(entry.getObject()))
: [],
viewQueries: metaObj.has('viewQueries')
? metaObj.getArray('viewQueries').map((entry) => toQueryMetadata(entry.getObject()))
: [],
providers: metaObj.has('providers') ? metaObj.getOpaque('providers') : null,
fullInheritance: false,
selector: metaObj.has('selector') ? metaObj.getString('selector') : null,
exportAs: metaObj.has('exportAs')
? metaObj.getArray('exportAs').map((entry) => entry.getString())
: null,
lifecycle: {
usesOnChanges: metaObj.has('usesOnChanges') ? metaObj.getBoolean('usesOnChanges') : false,
},
name: typeName,
usesInheritance: metaObj.has('usesInheritance') ? metaObj.getBoolean('usesInheritance') : false,
isStandalone: metaObj.has('isStandalone')
? metaObj.getBoolean('isStandalone')
: getDefaultStandaloneValue(version),
isSignal: metaObj.has('isSignal') ? metaObj.getBoolean('isSignal') : false,
hostDirectives: metaObj.has('hostDirectives')
? toHostDirectivesMetadata(metaObj.getValue('hostDirectives'))
: null,
};
}
/**
* Decodes the AST value for a single input to its representation as used in the metadata.
*/
function toInputMapping<TExpression>(
value: AstValue<NonNullable<R3DeclareDirectiveMetadata['inputs']>[string], TExpression>,
key: string,
): R3InputMetadata {
if (value.isObject()) {
const obj = value.getObject();
const transformValue = obj.getValue('transformFunction');
return {
classPropertyName: obj.getString('classPropertyName'),
bindingPropertyName: obj.getString('publicName'),
isSignal: obj.getBoolean('isSignal'),
required: obj.getBoolean('isRequired'),
transformFunction: transformValue.isNull() ? null : transformValue.getOpaque(),
};
}
return parseLegacyInputPartialOutput(
key,
value as AstValue<LegacyInputPartialMapping, TExpression>,
);
}
/**
* Parses the legacy partial output for inputs.
*
* More details, see: `legacyInputsPartialMetadata` in `partial/directive.ts`.
* TODO(legacy-partial-output-inputs): Remove function in v18.
*/
function parseLegacyInputPartialOutput<TExpression>(
key: string,
value: AstValue<LegacyInputPartialMapping, TExpression>,
): R3InputMetadata {
if (value.isString()) {
return {
bindingPropertyName: value.getString(),
classPropertyName: key,
required: false,
transformFunction: null,
isSignal: false,
};
}
const values = value.getArray();
if (values.length !== 2 && values.length !== 3) {
throw new FatalLinkerError(
value.expression,
'Unsupported input, expected a string or an array containing two strings and an optional function',
);
}
return {
bindingPropertyName: values[0].getString(),
classPropertyName: values[1].getString(),
transformFunction: values.length > 2 ? values[2].getOpaque() : null,
required: false,
isSignal: false,
};
}
/**
* Extracts the host metadata configuration from the AST metadata object.
*/
function toHostMetadata<TExpression>(
metaObj: AstObject<R3DeclareDirectiveMetadata, TExpression>,
): R3HostMetadata {
if (!metaObj.has('host')) {
return {
attributes: {},
listeners: {},
properties: {},
specialAttributes: {},
};
}
const host = metaObj.getObject('host');
const specialAttributes: R3HostMetadata['specialAttributes'] = {};
if (host.has('styleAttribute')) {
specialAttributes.styleAttr = host.getString('styleAttribute');
}
if (host.has('classAttribute')) {
specialAttributes.classAttr = host.getString('classAttribute');
}
return {
attributes: host.has('attributes')
? host.getObject('attributes').toLiteral((value) => value.getOpaque())
: {},
listeners: host.has('listeners')
? host.getObject('listeners').toLiteral((value) => value.getString())
: {},
properties: host.has('properties')
? host.getObject('properties').toLiteral((value) => value.getString())
: {},
specialAttributes,
};
}
/**
* Extracts the metadata for a single query from an AST object.
*/
function toQueryMetadata<TExpression>(
obj: AstObject<R3DeclareQueryMetadata, TExpression>,
): R3QueryMetadata {
let predicate: R3QueryMetadata['predicate'];
const predicateExpr = obj.getValue('predicate');
if (predicateExpr.isArray()) {
predicate = predicateExpr.getArray().map((entry) => entry.getString());
} else {
predicate = extractForwardRef(predicateExpr);
}
return {
propertyName: obj.getString('propertyName'),
first: obj.has('first') ? obj.getBoolean('first') : false,
predicate,
descendants: obj.has('descendants') ? obj.getBoolean('descendants') : false,
emitDistinctChangesOnly: obj.has('emitDistinctChangesOnly')
? obj.getBoolean('emitDistinctChangesOnly')
: true,
read: obj.has('read') ? obj.getOpaque('read') : null,
static: obj.has('static') ? obj.getBoolean('static') : false,
isSignal: obj.has('isSignal') ? obj.getBoolean('isSignal') : false,
};
}
/**
* Derives the host directives structure from the AST object.
*/
f | {
"end_byte": 7844,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_directive_linker_1.ts"
} |
angular/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_directive_linker_1.ts_7845_9343 | nction toHostDirectivesMetadata<TExpression>(
hostDirectives: AstValue<R3DeclareHostDirectiveMetadata[] | undefined, TExpression>,
): R3HostDirectiveMetadata[] {
return hostDirectives.getArray().map((hostDirective) => {
const hostObject = hostDirective.getObject();
const type = extractForwardRef(hostObject.getValue('directive'));
const meta: R3HostDirectiveMetadata = {
directive: wrapReference(type.expression),
isForwardReference: type.forwardRef !== ForwardRefHandling.None,
inputs: hostObject.has('inputs')
? getHostDirectiveBindingMapping(hostObject.getArray('inputs'))
: null,
outputs: hostObject.has('outputs')
? getHostDirectiveBindingMapping(hostObject.getArray('outputs'))
: null,
};
return meta;
});
}
function getHostDirectiveBindingMapping<TExpression>(array: AstValue<string, TExpression>[]) {
let result: {[publicName: string]: string} | null = null;
for (let i = 1; i < array.length; i += 2) {
result = result || {};
result[array[i - 1].getString()] = array[i].getString();
}
return result;
}
export function createSourceSpan(range: Range, code: string, sourceUrl: string): ParseSourceSpan {
const sourceFile = new ParseSourceFile(code, sourceUrl);
const startLocation = new ParseLocation(
sourceFile,
range.startPos,
range.startLine,
range.startCol,
);
return new ParseSourceSpan(startLocation, startLocation.moveBy(range.endPos - range.startPos));
}
| {
"end_byte": 9343,
"start_byte": 7845,
"url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/linker/src/file_linker/partial_linkers/partial_directive_linker_1.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.