_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/ng_template_interpolated_prop_template.js_0_278
consts: [[__AttributeMarker.Bindings__, "dir"]], template: function TestComp_Template(rf, ctx) { if (rf & 1) { $i0$.ɵɵtemplate(0, $TestComp_ng_template_0_Template$, 0, 0, "ng-template", 0); } if (rf & 2) { $i0$.ɵɵpropertyInterpolate("dir", ctx.message); } }
{ "end_byte": 278, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/ng_template_interpolated_prop_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/template_context_skip.ts_0_450
import {Component, NgModule} from '@angular/core'; @Component({ selector: 'my-component', template: ` <div *ngFor="let outer of items"> <div *ngFor="let middle of outer.items"> <div *ngFor="let inner of middle.items"> {{ middle.value }} - {{ name }} </div> </div> </div>`, standalone: false }) export class MyComponent { } @NgModule({declarations: [MyComponent]}) export class MyModule { }
{ "end_byte": 450, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/template_context_skip.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/attr_binding_on_structural_inside_ng_template.js_0_730
function MyComponent_ng_template_0_span_0_Template(rf, ctx) { if (rf & 1) { i0.ɵɵelement(0, "span"); } if (rf & 2) { const $ctx_r2$ = i0.ɵɵnextContext(2); i0.ɵɵattribute("someAttr", $ctx_r2$.someField); } } function MyComponent_ng_template_0_Template(rf, ctx) { if (rf & 1) { i0.ɵɵtemplate(0, MyComponent_ng_template_0_span_0_Template, 1, 1, "span", 1); } if (rf & 2) { const $ctx_r0$ = i0.ɵɵnextContext(); i0.ɵɵproperty("ngIf", $ctx_r0$.someBooleanField); } } … consts: [["someLocalRef", ""], [4, "ngIf"]], template: function MyComponent_Template(rf, ctx) { if (rf & 1) { i0.ɵɵtemplate(0, MyComponent_ng_template_0_Template, 1, 1, "ng-template", null, 0, i0.ɵɵtemplateRefExtractor); } }
{ "end_byte": 730, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/attr_binding_on_structural_inside_ng_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/create_many_elements.ts_0_4332
import { Component, NgModule } from '@angular/core'; @Component({ selector: 'my-component', template: ` <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> `, standalone: false }) export class MyComponent { }
{ "end_byte": 4332, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/create_many_elements.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/shorthand_property_declaration.ts_0_310
import {Component, NgModule} from '@angular/core'; @Component({ template: ` <div (click)="_handleClick({a, b: 2, c})"></div> `, standalone: false }) export class MyComponent { a = 1; c = 3; _handleClick(_value: any) {} } @NgModule({declarations: [MyComponent]}) export class MyModule { }
{ "end_byte": 310, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/shorthand_property_declaration.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/template_binding_pipe_template.js_0_413
function MyComponent_div_0_Template(rf, ctx) { if (rf & 1) { $i0$.ɵɵelement(0, "div"); } } … consts: [[__AttributeMarker.Template__, "ngIf"]], template: function MyComponent_Template(rf, ctx) { if (rf & 1) { $i0$.ɵɵtemplate(0, MyComponent_div_0_Template, 1, 0, "div", 0); $i0$.ɵɵpipe(1, "pipe"); } if (rf & 2) { $i0$.ɵɵproperty("ngIf", $i0$.ɵɵpipeBind1(1, 1, ctx.val)); } }
{ "end_byte": 413, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/template_binding_pipe_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/unique_listener_function_names.js_0_82
… // NOTE: the assertions for this test happen through `verifyUniqueFunctions`.
{ "end_byte": 82, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/unique_listener_function_names.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/template_with_structural_directive.ts_0_182
import {Component} from '@angular/core'; @Component({ selector: 'my-component', template: ` <ng-template *ngIf="true">Content</ng-template> `, }) export class MyComponent { }
{ "end_byte": 182, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/template_with_structural_directive.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/ng_for_context_variables.ts_0_327
import {Component, NgModule} from '@angular/core'; @Component({ selector: 'my-component', template: ` <span *ngFor="let item of items; index as i"> {{ i }} - {{ item }} </span> `, standalone: false }) export class MyComponent { } @NgModule({declarations: [MyComponent]}) export class MyModule { }
{ "end_byte": 327, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/ng_for_context_variables.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/unique_template_function_names.ts_0_1263
import {Component, NgModule} from '@angular/core'; @Component({ selector: 'a-component', template: ` <div *ngFor="let item of items"> <p *ngIf="item < 10">less than 10</p> <p *ngIf="item < 10">less than 10</p> </div> <div *ngFor="let item of items"> <p *ngIf="item > 10">more than 10</p> </div> `, standalone: false }) export class AComponent { items = [4, 2]; } @NgModule({declarations: [AComponent]}) export class AModule { } @Component({ selector: 'b-component', template: ` <div *ngFor="let item of items"> <ng-container *ngFor="let subitem of item.subitems"> <p *ngIf="subitem < 10">less than 10</p> <p *ngIf="subitem < 10">less than 10</p> </ng-container> <ng-container *ngFor="let subitem of item.subitems"> <p *ngIf="subitem < 10">less than 10</p> </ng-container> </div> <div *ngFor="let item of items"> <ng-container *ngFor="let subitem of item.subitems"> <p *ngIf="subitem > 10">more than 10</p> </ng-container> </div> `, standalone: false }) export class BComponent { items = [ {subitems: [1, 3]}, {subitems: [3, 7]}, ]; } @NgModule({declarations: [BComponent]}) export class BModule { }
{ "end_byte": 1263, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/unique_template_function_names.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/template_context_skip_template.js_0_1354
function MyComponent_div_0_div_1_div_1_Template(rf, ctx) { if (rf & 1) { $i0$.ɵɵelementStart(0, "div"); $i0$.ɵɵtext(1); $i0$.ɵɵelementEnd(); } if (rf & 2) { const $middle$ = $i0$.ɵɵnextContext().$implicit; const $myComp$ = $i0$.ɵɵnextContext(2); $r3$.ɵɵadvance(); $i0$.ɵɵtextInterpolate2(" ", $middle$.value, " - ", $myComp$.name, " "); } } function MyComponent_div_0_div_1_Template(rf, ctx) { if (rf & 1) { $i0$.ɵɵelementStart(0, "div"); $i0$.ɵɵtemplate(1, MyComponent_div_0_div_1_div_1_Template, 2, 2, "div", 0); $i0$.ɵɵelementEnd(); } if (rf & 2) { const $middle$ = ctx.$implicit; $r3$.ɵɵadvance(); $i0$.ɵɵproperty("ngForOf", $middle$.items); } } function MyComponent_div_0_Template(rf, ctx) { if (rf & 1) { $i0$.ɵɵelementStart(0, "div"); $i0$.ɵɵtemplate(1, MyComponent_div_0_div_1_Template, 2, 1, "div", 0); $i0$.ɵɵelementEnd(); } if (rf & 2) { const $outer$ = ctx.$implicit; $r3$.ɵɵadvance(); $i0$.ɵɵproperty("ngForOf", $outer$.items); } } … consts: [[__AttributeMarker.Template__, "ngFor", "ngForOf"]], template: function MyComponent_Template(rf, ctx){ if (rf & 1) { $i0$.ɵɵtemplate(0, MyComponent_div_0_Template, 2, 1, "div", 0); } if (rf & 2) { $i0$.ɵɵproperty("ngForOf", ctx.items); } }
{ "end_byte": 1354, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/template_context_skip_template.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/ng_template_implicit.ts_0_219
import {Component} from '@angular/core'; @Component({ selector: 'my-component', template: '<ng-template let-a [ngIf]="true">{{a}}</ng-template>', }) export class MyComponent { p1!: any; a1!: any; c1!: any; }
{ "end_byte": 219, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/ng_template_implicit.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/nested_ternary_operation.ts_0_268
import {Component, NgModule} from '@angular/core'; @Component({ selector: 'my-component', template: ` {{a?.b ? 1 : 2 }}`, standalone: false }) export class MyComponent { a!: any; } @NgModule({declarations: [MyComponent]}) export class MyModule { }
{ "end_byte": 268, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/nested_ternary_operation.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/self_closing_structural_directives.js_0_3349
function MyComponent_img_2_Template(rf, ctx) { if (rf & 1) { i0.ɵɵi18nStart(0, 0, 1); i0.ɵɵelement(1, "img"); i0.ɵɵi18nEnd(); } } function MyComponent_other_component_3_Template(rf, ctx) { if (rf & 1) { i0.ɵɵi18nStart(0, 0, 2); i0.ɵɵelement(1, "other-component"); i0.ɵɵi18nEnd(); } } function MyComponent_4_ng_template_1_Template(rf, ctx) { if (rf & 1) { i0.ɵɵi18n(0, 0, 4); } } function MyComponent_4_Template(rf, ctx) { if (rf & 1) { i0.ɵɵi18nStart(0, 0, 3); i0.ɵɵtemplate(1, MyComponent_4_ng_template_1_Template, 1, 0, "ng-template"); i0.ɵɵi18nEnd(); } } function MyComponent_ng_container_5_Template(rf, ctx) { if (rf & 1) { i0.ɵɵi18nStart(0, 0, 5); i0.ɵɵelementContainer(1); i0.ɵɵi18nEnd(); } } function MyComponent_ng_content_6_Template(rf, ctx) { if (rf & 1) { i0.ɵɵi18nStart(0, 0, 6); i0.ɵɵprojection(1, 0, ["*ngIf", "flag"]); i0.ɵɵi18nEnd(); } } … decls: 7, vars: 5, consts: () => { __i18nMsgWithPostprocess__('{$tagImg}{$startTagOtherComponent}{$closeTagOtherComponent}{$startTagNgTemplate}{$closeTagNgTemplate}{$startTagNgContainer}{$closeTagNgContainer}{$startTagNgContent}{$closeTagNgContent}', [['closeTagNgContainer', String.raw`\uFFFD/#1:5\uFFFD\uFFFD/*5:5\uFFFD`], ['closeTagNgContent', String.raw`\uFFFD/#1:6\uFFFD\uFFFD/*6:6\uFFFD`], ['closeTagNgTemplate', String.raw`[\uFFFD/*1:4\uFFFD|\uFFFD/*4:3\uFFFD]`], ['closeTagOtherComponent', String.raw`\uFFFD/#1:2\uFFFD\uFFFD/*3:2\uFFFD`], ['startTagNgContainer', String.raw`\uFFFD*5:5\uFFFD\uFFFD#1:5\uFFFD`], ['startTagNgContent', String.raw`\uFFFD*6:6\uFFFD\uFFFD#1:6\uFFFD`], ['startTagNgTemplate', String.raw`[\uFFFD*4:3\uFFFD|\uFFFD*1:4\uFFFD]`], ['startTagOtherComponent', String.raw`\uFFFD*3:2\uFFFD\uFFFD#1:2\uFFFD`], ['tagImg', String.raw`\uFFFD*2:1\uFFFD\uFFFD/*2:1\uFFFD\uFFFD#1:1\uFFFD\uFFFD/#1:1\uFFFD\uFFFD*2:1\uFFFD\uFFFD/*2:1\uFFFD`]], {original_code: { 'closeTagNgContainer': '<ng-container *ngIf=\"flag\" />', 'closeTagNgContent': '<ng-content *ngIf=\"flag\" />', 'closeTagNgTemplate': '<ng-template *ngIf=\"flag\" />', 'closeTagOtherComponent': '<other-component *ngIf=\"flag\" />', 'startTagNgContainer': '<ng-container *ngIf=\"flag\" />', 'startTagNgContent': '<ng-content *ngIf=\"flag\" />', 'startTagNgTemplate': '<ng-template *ngIf=\"flag\" />', 'startTagOtherComponent': '<other-component *ngIf=\"flag\" />', 'tagImg': '<img *ngIf=\"flag\" />'}}, {}, []) return [$i18n_0$, [4, "ngIf"]]; }, template: function MyComponent_Template(rf, ctx) { if (rf & 1) { i0.ɵɵprojectionDef(); i0.ɵɵelementStart(0, "div"); i0.ɵɵi18nStart(1, 0); i0.ɵɵtemplate(2, MyComponent_img_2_Template, 2, 0, "img", 1)(3, MyComponent_other_component_3_Template, 2, 0, "other-component", 1)(4, MyComponent_4_Template, 2, 0, null, 1)(5, MyComponent_ng_container_5_Template, 2, 0, "ng-container", 1)(6, MyComponent_ng_content_6_Template, 2, 0, "ng-content", 1); i0.ɵɵi18nEnd(); i0.ɵɵelementEnd(); } if (rf & 2) { i0.ɵɵadvance(2); i0.ɵɵproperty("ngIf", ctx.flag); i0.ɵɵadvance(); i0.ɵɵproperty("ngIf", ctx.flag); i0.ɵɵadvance(); i0.ɵɵproperty("ngIf", ctx.flag); i0.ɵɵadvance(); i0.ɵɵproperty("ngIf", ctx.flag); i0.ɵɵadvance(); i0.ɵɵproperty("ngIf", ctx.flag); } }
{ "end_byte": 3349, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/self_closing_structural_directives.js" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/ng_for_parent_context_variables.ts_0_373
import {Component, NgModule} from '@angular/core'; @Component({ selector: 'my-component', template: ` <div *ngFor="let item of items; index as i"> <span *ngIf="showing"> {{ i }} - {{ item }} </span> </div>`, standalone: false }) export class MyComponent { } @NgModule({declarations: [MyComponent]}) export class MyModule { }
{ "end_byte": 373, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/ng_for_parent_context_variables.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/unique_template_function_names_ng_content.ts_0_479
import {Component, NgModule} from '@angular/core'; @Component({ selector: 'a-component', template: ` <ng-content *ngIf="show"></ng-content> `, standalone: false }) export class AComponent { show = true; } @Component({ selector: 'b-component', template: ` <ng-content *ngIf="show"></ng-content> `, standalone: false }) export class BComponent { show = true; } @NgModule({declarations: [AComponent, BComponent]}) export class AModule { }
{ "end_byte": 479, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/unique_template_function_names_ng_content.ts" }
angular/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/ng_for_parent_context_variables.pipeline.js_0_1024
function MyComponent_div_0_span_1_Template(rf, ctx) { if (rf & 1) { $i0$.ɵɵelementStart(0, "span"); $i0$.ɵɵtext(1); $i0$.ɵɵelementEnd(); } if (rf & 2) { const $div$ = $i0$.ɵɵnextContext(); const $item$ = $div$.$implicit; const $i$ = $div$.index; $r3$.ɵɵadvance(); $i0$.ɵɵtextInterpolate2(" ", $i$, " - ", $item$, " "); } } function MyComponent_div_0_Template(rf, ctx) { if (rf & 1) { $i0$.ɵɵelementStart(0, "div"); $i0$.ɵɵtemplate(1, MyComponent_div_0_span_1_Template, 2, 2, "span", 1); $i0$.ɵɵelementEnd(); } if (rf & 2) { const $app$ = $i0$.ɵɵnextContext(); $r3$.ɵɵadvance(); $i0$.ɵɵproperty("ngIf", $app$.showing); } } … consts: [ [__AttributeMarker.Template__, "ngFor", "ngForOf"], [__AttributeMarker.Template__, "ngIf"] ], template:function MyComponent_Template(rf, ctx){ if (rf & 1) { $i0$.ɵɵtemplate(0, MyComponent_div_0_Template, 2, 1, "div", 0); } if (rf & 2) { $i0$.ɵɵproperty("ngForOf", ctx.items); } }
{ "end_byte": 1024, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_template/ng_for_parent_context_variables.pipeline.js" }
angular/packages/compiler-cli/test/compliance/local/local_compile_spec.ts_0_994
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {FileSystem} from '../../../src/ngtsc/file_system'; import {CompileResult, compileTest} from '../test_helpers/compile_test'; import {ComplianceTest} from '../test_helpers/get_compliance_tests'; import {runTests} from '../test_helpers/test_runner'; runTests('local compile', compileTests, {isLocalCompilation: true}); /** * Compile all the input files in the given `test` using local compilation mode. * * @param fs The mock file-system where the input files can be found. * @param test The compliance test whose input files should be compiled. */ function compileTests(fs: FileSystem, test: ComplianceTest): CompileResult { return compileTest(fs, test.inputFiles, test.compilerOptions, { ...test.angularCompilerOptions, compilationMode: 'experimental-local', }); }
{ "end_byte": 994, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/local/local_compile_spec.ts" }
angular/packages/compiler-cli/test/compliance/local/BUILD.bazel_0_580
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = ["local_compile_spec.ts"], deps = [ "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/test/compliance/test_helpers", ], ) jasmine_node_test( name = "local", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/compiler-cli/test/compliance/test_cases", "//packages/core:npm_package", ], shard_count = 2, deps = [ ":test_lib", ], )
{ "end_byte": 580, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/local/BUILD.bazel" }
angular/packages/compiler-cli/test/compliance/linked/linked_compile_spec.ts_0_4815
/** * @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, {PluginObj} from '@babel/core'; import {needsLinking} from '../../../linker'; import {createEs2015LinkerPlugin} from '../../../linker/babel'; import {AbsoluteFsPath, FileSystem} from '../../../src/ngtsc/file_system'; import {ConsoleLogger, LogLevel} from '../../../src/ngtsc/logging'; import {MapAndPath, RawSourceMap, SourceFileLoader} from '../../../src/ngtsc/sourcemaps'; import {CompileResult, getBuildOutputDirectory} from '../test_helpers/compile_test'; import {ComplianceTest} from '../test_helpers/get_compliance_tests'; import {parseGoldenPartial} from '../test_helpers/golden_partials'; import {runTests} from '../test_helpers/test_runner'; runTests('linked compile', linkPartials, { // TODO: Remove when https://github.com/angular/angular/issues/51647 is resolved. skipMappingChecks: true, }); /** * Link all the partials specified in the given `test`. * * @param fileSystem The mock file-system to use for linking the partials. * @param test The compliance test whose partials will be linked. */ function linkPartials(fileSystem: FileSystem, test: ComplianceTest): CompileResult { const logger = new ConsoleLogger(LogLevel.debug); const loader = new SourceFileLoader(fileSystem, logger, {}); const builtDirectory = getBuildOutputDirectory(fileSystem); const linkerPlugin = createEs2015LinkerPlugin({ fileSystem, logger, sourceMapping: test.compilerOptions?.['sourceMap'] === true, ...test.angularCompilerOptions, }); const goldenPartialPath = fileSystem.resolve('/GOLDEN_PARTIAL.js'); if (!fileSystem.exists(goldenPartialPath)) { throw new Error( 'Golden partial does not exist for this test\n' + 'Try generating it by running:\n' + `bazel run //packages/compiler-cli/test/compliance/test_cases:${test.relativePath}.golden.update`, ); } const partialFile = fileSystem.readFile(goldenPartialPath); const partialFiles = parseGoldenPartial(partialFile); partialFiles.forEach((f) => safeWrite(fileSystem, fileSystem.resolve(builtDirectory, f.path), f.content), ); for (const expectation of test.expectations) { for (const {generated} of expectation.files) { const fileName = fileSystem.resolve(builtDirectory, generated); if (!fileSystem.exists(fileName)) { continue; } const source = fileSystem.readFile(fileName); const sourceMapPath = fileSystem.resolve(fileName + '.map'); const sourceMap = fileSystem.exists(sourceMapPath) ? (JSON.parse(fileSystem.readFile(sourceMapPath)) as RawSourceMap) : undefined; const {linkedSource, linkedSourceMap} = applyLinker( builtDirectory, fileName, source, sourceMap, linkerPlugin, ); if (linkedSourceMap !== undefined) { const mapAndPath: MapAndPath = {map: linkedSourceMap, mapPath: sourceMapPath}; const sourceFile = loader.loadSourceFile(fileName, linkedSource, mapAndPath); safeWrite(fileSystem, sourceMapPath, JSON.stringify(sourceFile.renderFlattenedSourceMap())); } safeWrite(fileSystem, fileName, linkedSource); } } return {emittedFiles: [], errors: []}; } /** * Run the file through the Babel linker plugin. * * It will ignore files that do not have a `.js` extension. * * @param file The absolute file path and its source to be transformed using the linker. * @param linkerPlugin The linker plugin to apply. * @returns The file's source content, which has been transformed using the linker if necessary. */ function applyLinker( cwd: string, filename: string, source: string, sourceMap: RawSourceMap | undefined, linkerPlugin: PluginObj, ): {linkedSource: string; linkedSourceMap: RawSourceMap | undefined} { if (!filename.endsWith('.js') || !needsLinking(filename, source)) { return {linkedSource: source, linkedSourceMap: sourceMap}; } const result = babel.transformSync(source, { cwd, filename, sourceMaps: !!sourceMap, plugins: [linkerPlugin], parserOpts: {sourceType: 'unambiguous'}, }); if (result === null) { throw fail('Babel transform did not have output'); } if (result.code == null) { throw fail('Babel transform result does not have any code'); } return {linkedSource: result.code, linkedSourceMap: result.map || undefined}; } /** * Write the `content` to the `path` on the `fs` file-system, first ensuring that the containing * directory exists. */ function safeWrite(fs: FileSystem, path: AbsoluteFsPath, content: string): void { fs.ensureDir(fs.dirname(path)); fs.writeFile(path, content); }
{ "end_byte": 4815, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/linked/linked_compile_spec.ts" }
angular/packages/compiler-cli/test/compliance/linked/BUILD.bazel_0_860
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = ["linked_compile_spec.ts"], deps = [ "//packages/compiler-cli/linker", "//packages/compiler-cli/linker/babel", "//packages/compiler-cli/private", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/logging", "//packages/compiler-cli/src/ngtsc/sourcemaps", "//packages/compiler-cli/test/compliance/test_helpers", "@npm//@types/babel__core", ], ) jasmine_node_test( name = "linked", bootstrap = ["//tools/testing:node_no_angular"], data = [ "//packages/compiler-cli/test/compliance/test_cases", "//packages/core:npm_package", ], shard_count = 2, deps = [ ":test_lib", ], )
{ "end_byte": 860, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/linked/BUILD.bazel" }
angular/packages/compiler-cli/test/compliance/test_helpers/di_checks.ts_0_518
/** * @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 */ /** * Verifies that there is exactly one factory definition for the provided type. */ export function verifyUniqueFactory(output: string, type: string): boolean { const matches = output.match(new RegExp(type + '.ɵfac =', 'g')); if (matches === null) { return false; } return matches.length === 1; }
{ "end_byte": 518, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_helpers/di_checks.ts" }
angular/packages/compiler-cli/test/compliance/test_helpers/compile_test.ts_0_6341
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import ts from 'typescript'; import { AbsoluteFsPath, FileSystem, PathManipulation, ReadonlyFileSystem, } from '../../../src/ngtsc/file_system'; import {initMockFileSystem} from '../../../src/ngtsc/file_system/testing'; import { loadStandardTestFiles, loadTestDirectory, NgtscTestCompilerHost, } from '../../../src/ngtsc/testing'; import {performCompilation} from '../../../src/perform_compile'; import {CompilerOptions} from '../../../src/transformers/api'; import {ConfigOptions} from './get_compliance_tests'; /** * Setup a mock file-system that is used to generate the partial files. * * @param realTestPath Absolute path (on the real file-system) to the test case being processed. * @returns a mock file-system containing the test case files. */ export function initMockTestFileSystem(realTestPath: AbsoluteFsPath): FileSystem { const fs = initMockFileSystem('Native'); const testFiles = loadStandardTestFiles(); fs.init(testFiles); loadTestDirectory(fs, realTestPath, getRootDirectory(fs)); monkeyPatchReadFile(fs); return fs; } /** The result of compiling a test-case. */ export interface CompileResult { emittedFiles: AbsoluteFsPath[]; errors: string[]; } /** * Compile the input source `files` stored in `fs`, writing the generated files to `fs`. * * @param fs The mock file-system where the input and generated files live. * @param files An array of paths (relative to the testPath) of input files to be compiled. * @param compilerOptions Any extra options to pass to the TypeScript compiler. * @param angularCompilerOptions Any extra options to pass to the Angular compiler. * @returns A collection of paths of the generated files (absolute within the mock file-system). */ export function compileTest( fs: FileSystem, files: string[], compilerOptions: ConfigOptions | undefined, angularCompilerOptions: ConfigOptions | undefined, ): CompileResult { const rootDir = getRootDirectory(fs); const outDir = getBuildOutputDirectory(fs); const options = getOptions(rootDir, outDir, compilerOptions, angularCompilerOptions); const rootNames = files.map((f) => fs.resolve(f)); const host = new NgtscTestCompilerHost(fs, options); const {diagnostics, emitResult} = performCompilation({rootNames, host, options}); const emittedFiles = emitResult ? emitResult.emittedFiles!.map((p) => fs.resolve(rootDir, p)) : []; const errors = parseDiagnostics(diagnostics); return {errors, emittedFiles}; } /** * Gets an absolute path (in the mock file-system) of the root directory where the compilation is to * be done. * * @param fs the mock file-system where the compilation is happening. */ export function getRootDirectory(fs: PathManipulation): AbsoluteFsPath { return fs.resolve('/'); } /** * Gets an absolute path (in the mock file-system) of the directory where the compiled files are * stored. * * @param fs the mock file-system where the compilation is happening. */ export function getBuildOutputDirectory(fs: PathManipulation): AbsoluteFsPath { return fs.resolve('/built'); } /** * Get the options object to pass to the compiler. * * @param rootDir The absolute path (within the mock file-system) that is the root of the * compilation. * @param outDir The absolute path (within the mock file-system) where compiled files will be * written. * @param compilerOptions Additional options for the TypeScript compiler. * @param angularCompilerOptions Additional options for the Angular compiler. */ function getOptions( rootDir: AbsoluteFsPath, outDir: AbsoluteFsPath, compilerOptions: ConfigOptions | undefined, angularCompilerOptions: ConfigOptions | undefined, ): CompilerOptions { const convertedCompilerOptions = ts.convertCompilerOptionsFromJson(compilerOptions, rootDir); if (convertedCompilerOptions.errors.length > 0) { throw new Error( 'Invalid compilerOptions in test-case::\n' + convertedCompilerOptions.errors.map((d) => d.messageText).join('\n'), ); } return { emitDecoratorMetadata: true, experimentalDecorators: true, skipLibCheck: true, noImplicitAny: true, noEmitOnError: true, listEmittedFiles: true, strictNullChecks: true, outDir, rootDir, baseUrl: '.', allowJs: true, declaration: true, target: ts.ScriptTarget.ES2015, newLine: ts.NewLineKind.LineFeed, module: ts.ModuleKind.ES2015, moduleResolution: ts.ModuleResolutionKind.Node10, typeRoots: ['node_modules/@types'], ...convertedCompilerOptions.options, enableI18nLegacyMessageIdFormat: false, ...angularCompilerOptions, }; } /** * Replace escaped line-ending markers (\r\n) with real line-ending characters. * * This allows us to simulate, more reliably, files that have `\r\n` line-endings. * (See `test_cases/r3_view_compiler_i18n/line_ending_normalization/template.html`.) */ function monkeyPatchReadFile(fs: ReadonlyFileSystem): void { const originalReadFile = fs.readFile; fs.readFile = (path: AbsoluteFsPath): string => { const file = originalReadFile.call(fs, path); return ( file // First convert actual `\r\n` sequences to `\n` .replace(/\r\n/g, '\n') // unescape `\r\n` at the end of a line .replace(/\\r\\n\n/g, '\r\n') // unescape `\\r\\n`, at the end of a line, to `\r\n` .replace(/\\\\r\\\\n(\r?\n)/g, '\\r\\n$1') ); }; } /** * Parse the `diagnostics` to extract an error message string. * * The error message includes the location if available. * * @param diagnostics The diagnostics to parse. */ function parseDiagnostics(diagnostics: readonly ts.Diagnostic[]): string[] { return diagnostics.map((diagnostic) => { const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); if ('file' in diagnostic && diagnostic.file !== undefined && diagnostic.start !== undefined) { const {line, character} = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); return `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`; } else { return message; } }); }
{ "end_byte": 6341, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_helpers/compile_test.ts" }
angular/packages/compiler-cli/test/compliance/test_helpers/golden_partials.ts_0_1630
/** * @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 */ const headerStart = '/****************************************************************************************************\n' + ' * PARTIAL FILE: '; const headerEnd = '\n ****************************************************************************************************/\n'; /** * Render the partially compiled files into a single golden partial output string. * * @param files The partially compiled files to be rendered. */ export function renderGoldenPartial(files: PartiallyCompiledFile[]): string { return files.map((file) => `${headerStart + file.path + headerEnd}${file.content}`).join('\n'); } /** * Parse the `partialContent` into a set of partially compiled files. * * The `partialContent` is a single string that can contains multiple files. * Each file is delimited by a header comment that also contains its original path. * * @param partialContent The partial content to parse. */ export function parseGoldenPartial(partialContent: string): PartiallyCompiledFile[] { const files: PartiallyCompiledFile[] = []; const partials = partialContent.split(headerStart); for (const partial of partials) { const [path, content] = partial.split(headerEnd); if (path) { files.push({path, content}); } } return files; } /** * Represents the path and contents of a partially compiled file. */ export interface PartiallyCompiledFile { path: string; content: string; }
{ "end_byte": 1630, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_helpers/golden_partials.ts" }
angular/packages/compiler-cli/test/compliance/test_helpers/get_compliance_tests.ts_0_8192
/** * @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 {runfiles} from '@bazel/runfiles'; import { AbsoluteFsPath, NodeJSFileSystem, PathSegment, ReadonlyFileSystem, } from '../../../src/ngtsc/file_system'; export const fs = new NodeJSFileSystem(); /** Path to the test case sources. */ const basePath = fs.resolve( runfiles.resolveWorkspaceRelative('packages/compiler-cli/test/compliance/test_cases'), ); /** * Search the `test_cases` directory, in the real file-system, for all the compliance tests. * * Test are indicated by a `TEST_CASES.json` file which contains one or more test cases. */ export function* getAllComplianceTests(): Generator<ComplianceTest> { const testConfigPaths = collectPaths(basePath, (segment) => segment === 'TEST_CASES.json'); for (const testConfigPath of testConfigPaths) { yield* getComplianceTests(testConfigPath); } } /** * Extract all the compliance tests from the TEST_CASES.json file at the `testConfigPath`. * * @param testConfigPath Absolute disk path of the `TEST_CASES.json` file that describes the tests. */ export function* getComplianceTests(absTestConfigPath: AbsoluteFsPath): Generator<ComplianceTest> { const realTestPath = fs.dirname(absTestConfigPath); const testConfigJSON = loadTestCasesFile(fs, absTestConfigPath, basePath).cases; const testConfig = Array.isArray(testConfigJSON) ? testConfigJSON : [testConfigJSON]; for (const test of testConfig) { const inputFiles = getStringArrayOrDefault(test, 'inputFiles', realTestPath, ['test.ts']); const compilationModeFilter = getStringArrayOrDefault( test, 'compilationModeFilter', realTestPath, ['linked compile', 'full compile'], ) as CompilationMode[]; yield { relativePath: fs.relative(basePath, realTestPath), realTestPath, description: getStringOrFail(test, 'description', realTestPath), inputFiles, compilationModeFilter, expectations: parseExpectations(test.expectations, realTestPath, inputFiles), compilerOptions: getConfigOptions(test, 'compilerOptions', realTestPath), angularCompilerOptions: getConfigOptions(test, 'angularCompilerOptions', realTestPath), skipForTemplatePipeline: test.skipForTemplatePipeline, focusTest: test.focusTest, excludeTest: test.excludeTest, }; } } function loadTestCasesFile( fs: ReadonlyFileSystem, testCasesPath: AbsoluteFsPath, basePath: AbsoluteFsPath, ) { try { return JSON.parse(fs.readFile(testCasesPath)) as {cases: TestCaseJson | TestCaseJson[]}; } catch (e) { throw new Error( `Failed to load test-cases at "${fs.relative(basePath, testCasesPath)}":\n ${ (e as Error).message }`, ); } } /** * Search the file-system from the `current` path to find all paths that satisfy the `predicate`. */ function* collectPaths( current: AbsoluteFsPath, predicate: (segment: PathSegment) => boolean, ): Generator<AbsoluteFsPath> { if (!fs.exists(current)) { return; } for (const segment of fs.readdir(current)) { const absPath = fs.resolve(current, segment); if (predicate(segment)) { yield absPath; } else { if (fs.lstat(absPath).isDirectory()) { yield* collectPaths(absPath, predicate); } } } } function getStringOrFail(container: any, property: string, testPath: AbsoluteFsPath): string { const value = container[property]; if (typeof value !== 'string') { throw new Error(`Test is missing "${property}" property in TEST_CASES.json: ` + testPath); } return value; } function getStringArrayOrDefault( container: any, property: string, testPath: AbsoluteFsPath, defaultValue: string[], ): string[] { const value = container[property]; if (typeof value === 'undefined') { return defaultValue; } if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) { throw new Error( `Test has invalid "${property}" property in TEST_CASES.json - expected array of strings: ` + testPath, ); } return value; } function parseExpectations( value: any, testPath: AbsoluteFsPath, inputFiles: string[], ): Expectation[] { const defaultFailureMessage = 'Incorrect generated output.'; const tsFiles = inputFiles.filter((f) => f.endsWith('.ts') && !f.endsWith('.d.ts')); const defaultFiles = tsFiles.map((inputFile) => { const outputFile = inputFile.replace(/\.ts$/, '.js'); return {expected: outputFile, generated: outputFile}; }); if (typeof value === 'undefined') { return [ { failureMessage: defaultFailureMessage, files: defaultFiles, expectedErrors: [], extraChecks: [], }, ]; } if (!Array.isArray(value)) { return parseExpectations([value], testPath, inputFiles); } return value.map((expectation, i) => { if (typeof expectation !== 'object') { throw new Error( `Test has invalid "expectations" property in TEST_CASES.json - expected array of "expectation" objects: ${testPath}`, ); } const failureMessage: string = expectation.failureMessage ?? defaultFailureMessage; const expectedErrors = parseExpectedErrors(expectation.expectedErrors, testPath); const extraChecks = parseExtraChecks(expectation.extraChecks, testPath); if (typeof expectation.files === 'undefined') { return {failureMessage, files: defaultFiles, expectedErrors, extraChecks}; } if (!Array.isArray(expectation.files)) { throw new Error( `Test has invalid "expectations[${i}].files" property in TEST_CASES.json - expected array of "expected files": ${testPath}`, ); } const files: ExpectedFile[] = expectation.files.map((file: any) => { if (typeof file === 'string') { return {expected: file, generated: file}; } if ( typeof file === 'object' && typeof file.expected === 'string' && typeof file.generated === 'string' ) { return file; } throw new Error( `Test has invalid "expectations[${i}].files" property in TEST_CASES.json - expected each item to be a string or an "expected file" object: ${testPath}`, ); }); return {failureMessage, files, expectedErrors, extraChecks}; }); } function parseExpectedErrors(expectedErrors: any = [], testPath: AbsoluteFsPath): ExpectedError[] { if (!Array.isArray(expectedErrors)) { throw new Error( 'Test has invalid "expectedErrors" property in TEST_CASES.json - expected an array: ' + testPath, ); } return expectedErrors.map((error) => { if ( typeof error !== 'object' || typeof error.message !== 'string' || (error.location && typeof error.location !== 'string') ) { throw new Error( `Test has invalid "expectedErrors" property in TEST_CASES.json - expected an array of ExpectedError objects: ` + testPath, ); } return {message: parseRegExp(error.message), location: parseRegExp(error.location)}; }); } function parseExtraChecks(extraChecks: any = [], testPath: AbsoluteFsPath): ExtraCheck[] { if ( !Array.isArray(extraChecks) || !extraChecks.every((i) => typeof i === 'string' || Array.isArray(i)) ) { throw new Error( `Test has invalid "extraChecks" property in TEST_CASES.json - expected an array of strings or arrays: ` + testPath, ); } return extraChecks as ExtraCheck[]; } function parseRegExp(str: string | undefined): RegExp { return new RegExp(str || ''); } function getConfigOptions( container: any, property: string, testPath: AbsoluteFsPath, ): ConfigOptions | undefined { const options = container[property]; if (options !== undefined && typeof options !== 'object') { throw new Error( `Test have invalid "${property}" property in TEST_CASES.json - expected config option object: ` + testPath, ); } return options; } /** * Describes a compliance test, as defined in a `TEST_CASES.json` file. */
{ "end_byte": 8192, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_helpers/get_compliance_tests.ts" }
angular/packages/compiler-cli/test/compliance/test_helpers/get_compliance_tests.ts_8193_11472
export interface ComplianceTest { /** The path, relative to the test_cases directory, of the directory containing this test. */ relativePath: string; /** The absolute path (on the real file-system) to the test case containing this test. */ realTestPath: AbsoluteFsPath; /** A description of this particular test. */ description: string; /** * Any additional options to pass to the TypeScript compiler when compiling this test's source * files. These are equivalent to what you would put in `tsconfig.json`. */ compilerOptions?: ConfigOptions; /** * Any additional options to pass to the Angular compiler when compiling this test's source * files. These are equivalent to what you would put in `tsconfig.json`. */ angularCompilerOptions?: ConfigOptions; /** A list of paths to source files that should be compiled for this test case. */ inputFiles: string[]; /** * Only run this test when the input files are compiled using the given compilation * modes. The default is to run for all modes. */ compilationModeFilter: CompilationMode[]; /** A list of expectations to check for this test case. */ expectations: Expectation[]; /** If set to `true` this test is skipped when testing with use_template_pipeline */ skipForTemplatePipeline?: boolean; /** If set to `true`, then focus on this test (equivalent to jasmine's 'fit()`). */ focusTest?: boolean; /** If set to `true`, then exclude this test (equivalent to jasmine's 'xit()`). */ excludeTest?: boolean; } export type CompilationMode = 'linked compile' | 'full compile' | 'local compile'; export interface Expectation { /** The message to display if this expectation fails. */ failureMessage: string; /** A list of pairs of paths to expected and generated files to compare. */ files: ExpectedFile[]; /** A collection of errors that should be reported when compiling the generated file. */ expectedErrors: ExpectedError[]; /** Additional checks to run against the generated code. */ extraChecks: ExtraCheck[]; } /** * A pair of paths to expected and generated files that should be compared in an `Expectation`. */ export interface ExpectedFile { expected: string; generated: string; } /** * Regular expressions that should match an error message. */ export interface ExpectedError { message: RegExp; location: RegExp; } /** * The name (or name and arguments) of a function to call to run additional checks against the * generated code. */ export type ExtraCheck = string | [string, ...any]; /** * Options to pass to configure the compiler. */ export type ConfigOptions = Record<string, string | boolean | null>; /** * Interface espressing the type for the json object found at ../test_cases/test_case_schema.json. */ export interface TestCaseJson { description: string; compilationModeFilter?: ('fulll compile' | 'linked compile')[]; inputFiles?: string[]; expectations?: { failureMessage?: string; files?: ExpectedFile[] | string; expectedErrors?: {message: string; location?: string}; extraChecks?: (string | string[])[]; }; compilerOptions?: ConfigOptions; angularCompilerOptions?: ConfigOptions; skipForTemplatePipeline?: boolean; focusTest?: boolean; excludeTest?: boolean; }
{ "end_byte": 11472, "start_byte": 8193, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_helpers/get_compliance_tests.ts" }
angular/packages/compiler-cli/test/compliance/test_helpers/sourcemap_helpers.ts_0_8753
/** * @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, ReadonlyFileSystem} from '../../../src/ngtsc/file_system'; import {ConsoleLogger, LogLevel} from '../../../src/ngtsc/logging'; import {SourceFileLoader} from '../../../src/ngtsc/sourcemaps'; /** * Check the source-mappings of the generated source file against mappings stored in the expected * source file. * * The source-mappings are encoded into the expected source file in the form of an end-of-line * comment that has the following syntax: * * ``` * <generated code> // SOURCE: "</path/to/original>" "<original source>" * ``` * * The `path/to/original` path will be absolute within the mock file-system, where the root is the * directory containing the `TEST_CASES.json` file. The `generated code` and the `original source` * are not trimmed of whitespace - but there is a single space after the generated and a single * space before the original source. * * @param fs The test file-system where the source, generated and expected files are stored. * @param generated The content of the generated source file. * @param generatedPath The absolute path, within the test file-system, of the generated source * file. * @param expectedSource The content of the expected source file, containing mapping information. * @returns The content of the expected source file, stripped of the mapping information. */ export function stripAndCheckMappings( fs: ReadonlyFileSystem, generated: string, generatedPath: AbsoluteFsPath, expectedSource: string, expectedPath: AbsoluteFsPath, skipMappingCheck: boolean, ): string { // Generate the candidate source maps. const actualMappings = getMappedSegments(fs, generatedPath, generated); const {expected, mappings} = extractMappings(fs, expectedSource); // TODO: Remove when https://github.com/angular/angular/issues/51647 is fixed. if (skipMappingCheck) { return expected; } const failures: string[] = []; for (const expectedMapping of mappings) { const failure = checkMapping(actualMappings, expectedMapping); if (failure !== null) { failures.push(failure); } } if (failures.length > 0) { throw new Error( `When checking mappings for ${generatedPath} against ${expectedPath} expected...\n\n` + `${failures.join('\n\n')}\n\n` + `All the mappings:\n\n${dumpMappings(actualMappings)}`, ); } return expected; } /** * A mapping of a segment of generated text to a segment of source text. */ interface SegmentMapping { /** The generated text in this segment. */ generated: string; /** The source text in this segment. */ source: string; /** The URL of the source file for this segment. */ sourceUrl: string; } /** * Extract the source-map information (encoded in comments - see `checkMappings()`) from the given * `expected` source content, returning both the `mappings` and the `expected` source code, stripped * of the source-mapping comments. * * @param expected The content of the expected file containing source-map information. */ function extractMappings( fs: ReadonlyFileSystem, expected: string, ): {expected: string; mappings: SegmentMapping[]} { const mappings: SegmentMapping[] = []; // capture and remove source mapping info // Any newline at the end of an expectation line is removed, as a mapping expectation for a // segment within a template literal would otherwise force a newline to be matched in the template // literal. expected = expected.replace( /^(.*?) \/\/ SOURCE: "([^"]*?)" "(.*?)"(?:\n|$)/gm, (_, rawGenerated: string, rawSourceUrl: string, rawSource: string) => { // Since segments need to appear on a single line in the expected file, any newlines in the // segment being checked must be escaped in the expected file and then unescaped here before // being checked. const generated = unescape(rawGenerated); const source = unescape(rawSource); const sourceUrl = fs.resolve(rawSourceUrl); mappings.push({generated, sourceUrl, source}); return generated; }, ); return {expected, mappings}; } function unescape(str: string): string { const replacements: Record<any, string> = {'\\n': '\n', '\\r': '\r', '\\\\': '\\', '\\"': '"'}; return str.replace(/\\[rn"\\]/g, (match) => replacements[match]); } /** * Process a generated file to extract human understandable segment mappings. * * These mappings are easier to compare in unit tests than the raw SourceMap mappings. * * @param fs the test file-system that holds the source and generated files. * @param generatedPath The path of the generated file to process. * @param generatedContents The contents of the generated file to process. * @returns An array of segment mappings for each mapped segment in the given generated file. An * empty array is returned if there is no source-map file found. */ function getMappedSegments( fs: ReadonlyFileSystem, generatedPath: AbsoluteFsPath, generatedContents: string, ): SegmentMapping[] { const logger = new ConsoleLogger(LogLevel.debug); const loader = new SourceFileLoader(fs, logger, {}); const generatedFile = loader.loadSourceFile(generatedPath, generatedContents); if (generatedFile === null) { return []; } const segments: SegmentMapping[] = []; for (let i = 0; i < generatedFile.flattenedMappings.length - 1; i++) { const mapping = generatedFile.flattenedMappings[i]; const generatedStart = mapping.generatedSegment; const generatedEnd = generatedFile.flattenedMappings[i + 1].generatedSegment; const originalFile = mapping.originalSource; const originalStart = mapping.originalSegment; let originalEnd = originalStart.next; // Skip until we find an end segment that is after the start segment while ( originalEnd !== undefined && originalEnd.next !== originalEnd && originalEnd.position === originalStart.position ) { originalEnd = originalEnd.next; } if (originalEnd === undefined || originalEnd.next === originalEnd) { continue; } const segment = { generated: generatedFile.contents.substring(generatedStart.position, generatedEnd.position), source: originalFile.contents.substring(originalStart.position, originalEnd!.position), sourceUrl: originalFile.sourcePath, }; segments.push(segment); } return segments; } /** * Check that the `expected` segment appears in the collection of `mappings`. * * @returns An error message if a matching segment cannot be found, or null if it can. */ function checkMapping(mappings: SegmentMapping[], expected: SegmentMapping): string | null { if ( mappings.some( (m) => m.generated === expected.generated && m.source === expected.source && m.sourceUrl === expected.sourceUrl, ) ) { return null; } const matchingGenerated = mappings.filter((m) => m.generated === expected.generated); const matchingSource = mappings.filter((m) => m.source === expected.source); const message = [ 'Expected mappings to contain the following mapping', prettyPrintMapping(expected), ]; if (matchingGenerated.length > 0) { message.push(''); message.push('There are the following mappings that match the generated text:'); matchingGenerated.forEach((m) => message.push(prettyPrintMapping(m))); } if (matchingSource.length > 0) { message.push(''); message.push('There are the following mappings that match the source text:'); matchingSource.forEach((m) => message.push(prettyPrintMapping(m))); } return message.join('\n'); } function prettyPrintMapping(mapping: SegmentMapping): string { return [ '{', ` generated: ${JSON.stringify(mapping.generated)}`, ` source : ${JSON.stringify(mapping.source)}`, ` sourceUrl: ${JSON.stringify(mapping.sourceUrl)}`, '}', ].join('\n'); } /** * Helper function for debugging failed mappings. * This lays out the segment mappings in the console to make it easier to compare. */ function dumpMappings(mappings: SegmentMapping[]): string { return mappings .map( (mapping) => padValue(mapping.sourceUrl, 20, 0) + ' : ' + padValue(JSON.stringify(mapping.source), 100, 23) + ' : ' + JSON.stringify(mapping.generated), ) .join('\n'); } function padValue(value: string, max: number, start: number): string { const padding = value.length > max ? '\n' + ' '.repeat(max + start) : ' '.repeat(max - value.length); return value + padding; }
{ "end_byte": 8753, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_helpers/sourcemap_helpers.ts" }
angular/packages/compiler-cli/test/compliance/test_helpers/function_checks.ts_0_1358
/** * @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 */ /** * Verify that all functions in the output have a unique name. * @param output Compiler output. * @param functionNamePattern Only match function whose names match this pattern. * Will be converted into a regular expression. * @param expectedCount Expected number of functions. */ export function verifyUniqueFunctions( output: string, functionNamePattern?: string, expectedCount?: number, ): boolean { const pattern = functionNamePattern ? new RegExp(functionNamePattern) : null; const allTemplateFunctionsNames = (output.match(/function ([^\s(]+)/g) || []) .map((match) => match.slice(9)) .filter((name) => !pattern || pattern.test(name)); const uniqueTemplateFunctionNames = new Set(allTemplateFunctionsNames); const lengthMatches = allTemplateFunctionsNames.length === uniqueTemplateFunctionNames.size; const expectedCountMatches = expectedCount == null ? allTemplateFunctionsNames.length > 0 : allTemplateFunctionsNames.length === expectedCount; return ( lengthMatches && expectedCountMatches && allTemplateFunctionsNames.every((name) => uniqueTemplateFunctionNames.has(name)) ); }
{ "end_byte": 1358, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_helpers/function_checks.ts" }
angular/packages/compiler-cli/test/compliance/test_helpers/expect_emit.ts_0_7708
/** * @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 {escapeRegExp} from '@angular/compiler/src/util'; const IDENTIFIER = /[A-Za-z_$ɵ][A-Za-z0-9_$]*/; const COMMENT_START = /\/\*/; const COMMENT_END = /\*\//; const OPERATOR = /!|\?|%|\*|\/|\^|&&?|\|\|?|\(|\)|\{|\}|\[|\]|:|;|<=?|>=?|={1,3}|!==?|=>|\+\+?|--?|@|,|\.|\.\.\.|\\`|\\'/; const STRING = /'(\\'|[^'])*'|"(\\"|[^"])*"/; const INLINE_BACKTICK_STRING = /`(?:[\s\S]|(?:\$\{[^}]*?\}))*?[^\\]`/; const SINGLE_BACKTICK_STRING = new RegExp('^' + INLINE_BACKTICK_STRING.source); const BACKTICK_INTERPOLATION = /(\$\{[^}]*\})/; const NUMBER = /\d+/; const ELLIPSIS = '…'; const TOKEN = new RegExp( `\\s*((${COMMENT_START.source})|(${COMMENT_END.source})|(${IDENTIFIER.source})|(${INLINE_BACKTICK_STRING.source})|(${OPERATOR.source})|(${STRING.source})|${NUMBER.source}|${ELLIPSIS})\\s*`, 'y', ); type Piece = string | RegExp; const SKIP = /(?:.|\n|\r)*/; const ERROR_CONTEXT_WIDTH = 30; // Transform the expected output to set of tokens function tokenize(text: string): Piece[] { // TOKEN.lastIndex is stateful so we cache the `lastIndex` and restore it at the end of the call. const lastIndex = TOKEN.lastIndex; TOKEN.lastIndex = 0; let match: RegExpMatchArray | null; let tokenizedTextEnd = 0; let inComment = false; const pieces: Piece[] = []; while ((match = TOKEN.exec(text)) !== null) { const [, token] = match; if (token === 'IDENT') { pieces.push(IDENTIFIER); } else if (token === ELLIPSIS) { pieces.push(SKIP); } else if ((match = SINGLE_BACKTICK_STRING.exec(token))) { if (inComment) { // We are in a comment block so just treat a backtick as a normal token. // Store the token and reset the matcher. pieces.push('`'); TOKEN.lastIndex = tokenizedTextEnd + 1; } else { pieces.push(...tokenizeBackTickString(token)); } } else { updateCommentState(token); pieces.push(token); } tokenizedTextEnd = TOKEN.lastIndex; } if (pieces.length === 0 || tokenizedTextEnd < text.length) { // The new token that could not be found is located after the // last tokenized character. const from = tokenizedTextEnd; const to = from + ERROR_CONTEXT_WIDTH; throw Error( `Invalid test, no token found for "${text[tokenizedTextEnd]}" ` + `(context = '${text.slice(from, to)}...'`, ); } // Reset the lastIndex in case we are in a recursive `tokenize()` call. TOKEN.lastIndex = lastIndex; return pieces; function updateCommentState(token: string) { if (token === '/*') { inComment = true; } else if (token === '*/') { inComment = false; } } } /** * Back-ticks are escaped as "\`" so we must strip the backslashes. * Also the string will likely contain interpolations and if an interpolation holds an * identifier we will need to match that later. So tokenize the interpolation too! */ function tokenizeBackTickString(str: string): Piece[] { const pieces: Piece[] = ['`']; const backTickPieces = str.slice(1, -1).split(BACKTICK_INTERPOLATION); backTickPieces.forEach((backTickPiece) => { if (BACKTICK_INTERPOLATION.test(backTickPiece)) { // An interpolation so tokenize this expression pieces.push(...tokenize(backTickPiece)); } else { // Not an interpolation so just add it as a piece pieces.push(backTickPiece); } }); pieces.push('`'); return pieces; } const RESET = '\x1b[0m'; const BLUE = '\x1b[36m'; const RED = '\x1b[31m'; const GREEN = '\x1b[32m'; export function expectEmit( source: string, expected: string, description: string, assertIdentifiers?: {[name: string]: RegExp}, ) { expected = expected // turns `// ...` into `…` .replace(/\/\/\s*\.\.\./g, ELLIPSIS) // remove `// TODO` comment lines .replace(/\/\/\s*TODO.*?\n/g, '') // remove `// NOTE` comment lines .replace(/\/\/\s*NOTE.*?\n/g, ''); const pieces = tokenize(expected); const {regexp, groups} = buildMatcher(pieces); const matches = source.match(regexp); if (matches === null) { let last: number = 0; for (let i = 1; i < pieces.length; i++) { const {regexp} = buildMatcher(pieces.slice(0, i)); const m = source.match(regexp); const expectedPiece = pieces[i - 1] == IDENTIFIER ? '<IDENT>' : pieces[i - 1]; if (!m) { // display at most `contextLength` characters of the line preceding the error location const contextLength = 50; const fullContext = source.substring(source.lastIndexOf('\n', last) + 1, last); const context = fullContext.length > contextLength ? `...${fullContext.slice(-contextLength)}` : fullContext; throw new Error( `${RED}${description}:\n${RESET}${BLUE}Failed to find${RESET} "${expectedPiece}"\n` + `${BLUE}After ${RESET}"${context}"\n` + `${BLUE}In generated file:${RESET}\n\n` + `${source.slice(0, last)}` + `${RED}[[[ <<<<---HERE expected "${GREEN}${expectedPiece}${RED}" ]]]${RESET}` + `${source.slice(last)}`, ); } else { last = (m.index || 0) + m[0].length; } } throw new Error( `Test helper failure: Expected expression failed but the reporting logic could not find where it failed in: ${source}`, ); } else { if (assertIdentifiers) { // It might be possible to add the constraints in the original regexp (see `buildMatcher`) // by transforming the assertion regexps when using anchoring, grouping, back references, // flags, ... // // Checking identifiers after they have matched allows for a simple and flexible // implementation. // The overall performance are not impacted when `assertIdentifiers` is empty. const ids = Object.keys(assertIdentifiers); for (let i = 0; i < ids.length; i++) { const id = ids[i]; if (groups.has(id)) { const name = matches[groups.get(id) as number]; const regexp = assertIdentifiers[id]; if (!regexp.test(name)) { throw Error( `${description}: The matching identifier "${id}" is "${name}" which doesn't match ${regexp}`, ); } } } } } } const IDENT_LIKE = /^[a-z][A-Z]/; const MATCHING_IDENT = /^\$.*\$$/; /* * Builds a regexp that matches the given `pieces` * * It returns: * - the `regexp` to be used to match the generated code, * - the `groups` which maps `$...$` identifier to their position in the regexp matches. */ function buildMatcher(pieces: (string | RegExp)[]): {regexp: RegExp; groups: Map<string, number>} { const results: string[] = []; let first = true; let group = 0; const groups = new Map<string, number>(); for (const piece of pieces) { if (!first) results.push(`\\s${typeof piece === 'string' && IDENT_LIKE.test(piece) ? '+' : '*'}`); first = false; if (typeof piece === 'string') { if (MATCHING_IDENT.test(piece)) { const matchGroup = groups.get(piece); if (!matchGroup) { results.push('(' + IDENTIFIER.source + ')'); const newGroup = ++group; groups.set(piece, newGroup); } else { results.push(`\\${matchGroup}`); } } else { results.push(escapeRegExp(piece)); } } else { results.push('(?:' + piece.source + ')'); } } return { regexp: new RegExp(results.join('')), groups, }; }
{ "end_byte": 7708, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_helpers/expect_emit.ts" }
angular/packages/compiler-cli/test/compliance/test_helpers/expected_file_macros.ts_0_7595
/** * @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 {AttributeMarker, SelectorFlags} from '@angular/compiler/src/core'; import {QueryFlags} from '@angular/compiler/src/render3/view/query_generation'; import { i18nIcuMsg, i18nMsg, i18nMsgWithPostprocess, Options, Placeholder, resetMessageIndex, } from './i18n_helpers'; const EXPECTED_FILE_MACROS: [RegExp, (...args: string[]) => string][] = [ [ // E.g. `__i18nMsg__('message string', [ ['placeholder', 'pair'] // ], {original_code: {'placeholder': '{{ foo }}'}}, {meta: 'properties'})` macroFn(/__i18nMsg__/, stringParam(), arrayParam(), objectParam(), objectParam()), (_match, message, placeholders, options, meta) => i18nMsg( message, parsePlaceholders(placeholders), parseOptions(options), parseMetaProperties(meta), ), ], [ // E.g. `__i18nMsgWithPostprocess__('message', [ ['placeholder', 'pair'] ], { meta: 'props'})` macroFn( /__i18nMsgWithPostprocess__/, stringParam(), arrayParam(), objectParam(), objectParam(), arrayParam(), ), (_match, message, placeholders, options, meta, postProcessPlaceholders) => i18nMsgWithPostprocess( message, parsePlaceholders(placeholders), parseOptions(options), parseMetaProperties(meta), parsePlaceholders(postProcessPlaceholders), ), ], [ // E.g. `__i18nIcuMsg__('message string', [ ['placeholder', 'pair'] ])` macroFn(/__i18nIcuMsg__/, stringParam(), arrayParam(), objectParam()), (_match, message, placeholders, options) => i18nIcuMsg(message, parsePlaceholders(placeholders), parseOptions(options)), ], [ // E.g. `__AttributeMarker.Bindings__` /__AttributeMarker\.([^_]+)__/g, (_match, member) => getAttributeMarker(member), ], // E.g. `__SelectorFlags.ELEMENT__` flagUnion(/__SelectorFlags\.([^_]+)__/, (_match, member) => getSelectorFlag(member)), // E.g. `__QueryFlags.ELEMENT__` flagUnion(/__QueryFlags\.([^_]+)__/, (_match, member) => getQueryFlag(member)), ]; /** * Replace any known macros in the expected content with the result of evaluating the macro. * * @param expectedContent The content to process. */ export function replaceMacros(expectedContent: string): string { resetMessageIndex(); for (const [regex, replacer] of EXPECTED_FILE_MACROS) { expectedContent = expectedContent.replace(regex, replacer); } return expectedContent; } function parsePlaceholders(str: string): Placeholder[] { const placeholders = eval(`(${str})`); if ( !Array.isArray(placeholders) || !placeholders.every( (p) => Array.isArray(p) && p.length >= 2 && typeof p[0] === 'string' && typeof p[1] === 'string' && (p.length === 2 || typeof p[2] === 'string'), ) ) { throw new Error( 'Expected an array of Placeholder arrays (`[name: string, identifier: string, associatedId?: string]`) but got ' + str, ); } return placeholders; } function parseOptions(str: string): Options { const inputObj = eval(`(${str})`) as unknown; if (typeof inputObj !== 'object') { throw new Error(`Expected an object of properties but got:\n\n${str}.`); } const obj = inputObj as Record<string, unknown>; // Verify the object does not have any unexpected properties, as this is likely a sign that it was // authored incorrectly. const unexpectedKeys = Object.keys(obj).filter((key) => key !== 'original_code'); if (unexpectedKeys.length > 0) { throw new Error( `Expected an i18n options object with \`original_code\`, but got ${unexpectedKeys.join( ', ', )}`, ); } // Validate `original_code`. const original = obj?.['original_code']; if (typeof original !== 'undefined' && typeof original !== 'object') { throw new Error( `Expected an i18n options object with \`original_code\`, as a nested object, but got ${JSON.stringify( obj, null, 4, )}`, ); } for (const [key, value] of Object.entries(original ?? {})) { if (typeof value !== 'string') { throw new Error( `Expected an object whose values are strings, but property ${key} has type ${typeof value}, when parsing:\n\n${str}`, ); } } return obj; } function parseMetaProperties(str: string): Record<string, string> { const obj = eval(`(${str})`); if (typeof obj !== 'object') { throw new Error(`Expected an object of properties but got:\n\n${str}.`); } for (const key in obj) { if (typeof obj[key] !== 'string') { throw new Error( `Expected an object whose values are strings, but property ${key} has type ${typeof obj[ key ]}, when parsing:\n\n${str}`, ); } } return obj; } const AttributeMarkerMap: Record<string, AttributeMarker> = { NamespaceURI: AttributeMarker.NamespaceURI, Classes: AttributeMarker.Classes, Styles: AttributeMarker.Styles, Bindings: AttributeMarker.Bindings, Template: AttributeMarker.Template, ProjectAs: AttributeMarker.ProjectAs, I18n: AttributeMarker.I18n, }; function getAttributeMarker(member: string): string { const marker = AttributeMarkerMap[member]; if (typeof marker !== 'number') { throw new Error('Unknown AttributeMarker: ' + member); } return `${marker}`; } const SelectorFlagsMap: Record<string, SelectorFlags> = { NOT: SelectorFlags.NOT, ATTRIBUTE: SelectorFlags.ATTRIBUTE, ELEMENT: SelectorFlags.ELEMENT, CLASS: SelectorFlags.CLASS, }; function getSelectorFlag(member: string): number { const marker = SelectorFlagsMap[member]; if (typeof marker !== 'number') { throw new Error('Unknown SelectorFlag: ' + member); } return marker; } const QueryFlagsMap: Record<string, QueryFlags> = { none: QueryFlags.none, descendants: QueryFlags.descendants, isStatic: QueryFlags.isStatic, emitDistinctChangesOnly: QueryFlags.emitDistinctChangesOnly, }; function getQueryFlag(member: string): number { const marker = QueryFlagsMap[member]; if (typeof marker !== 'number') { throw new Error('Unknown SelectorFlag: ' + member); } return marker; } function stringParam() { return /'([^']*?[^\\])'/; } function arrayParam() { return /(\[.*?\])/; } function objectParam() { // Matches a JavaScript object literal with up to 6 levels of indentation. Regular expressions // cannot use recursion so it is impossible to match an arbitrarily deep object. While it looks // complicated it is really just the same pattern nested inside itself n times: // (?:\{[^{}]*RECURSE_HERE\}[^{}]*) // // Each nested level uses (?:) for a non-matching group so the whole expression is the only match // and avoids generating multiple macro arguments for each nested level. return /(\{[^{}]*(?:\{[^{}]*(?:\{[^{}]*(?:\{[^{}]*(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^{}]*)*\}[^{}]*)*\}[^{}]*)*\}[^{}]*)*\})/; } function macroFn(fnName: RegExp, ...args: RegExp[]): RegExp { const ws = /[\s\r\n]*/.source; return new RegExp( ws + fnName.source + '\\(' + args.map((r) => `${ws}${r.source}${ws}`).join(',') + '\\)' + ws, 'g', ); } /** * Creates a macro to replace a union of flags with its numeric constant value. * * @param pattern The regex to match a single occurrence of the flag. * @param getFlagValue A function to extract the numeric flag value from the pattern. */
{ "end_byte": 7595, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_helpers/expected_file_macros.ts" }
angular/packages/compiler-cli/test/compliance/test_helpers/expected_file_macros.ts_7596_8263
function flagUnion( pattern: RegExp, getFlagValue: (...match: string[]) => number, ): (typeof EXPECTED_FILE_MACROS)[number] { return [ // Match at least one occurrence of the pattern, optionally followed by more occurrences // separated by a pipe. new RegExp(pattern.source + '(?:s*\\|s*' + pattern.source + ')*', 'g'), (match: string) => { // Replace all matches with the union of the individually matched flags. return String( match .split('|') .map((flag) => getFlagValue(...flag.trim().match(pattern)!)) .reduce((accumulator, flagValue) => accumulator | flagValue, 0), ); }, ]; }
{ "end_byte": 8263, "start_byte": 7596, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_helpers/expected_file_macros.ts" }
angular/packages/compiler-cli/test/compliance/test_helpers/check_errors.ts_0_1203
/** * @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 {inspect} from 'util'; import {ExpectedError} from './get_compliance_tests'; export function checkErrors( testPath: string, failureMessage: string, expectedErrors: ExpectedError[], actualErrors: string[], ): void { for (const expectedError of expectedErrors) { if ( !actualErrors.some( (actualError) => expectedError.message.test(actualError) && expectedError.location.test(actualError), ) ) { throw new Error( `When checking expected errors for test case at "${testPath}"\n` + failureMessage + '\n' + `Expected errors: ${inspect(expectedErrors)}\n` + `Actual errors: ${inspect(actualErrors)}.`, ); } } } export function checkNoUnexpectedErrors(testPath: string, actualErrors: string[]): void { if (actualErrors.length > 0) { throw new Error( `Unexpected errors occurred for test case at "${testPath}"\n` + `Errors: ${inspect(actualErrors)}.`, ); } }
{ "end_byte": 1203, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_helpers/check_errors.ts" }
angular/packages/compiler-cli/test/compliance/test_helpers/test_runner.ts_0_3434
/** * @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 {FileSystem} from '../../../src/ngtsc/file_system'; import {checkErrors, checkNoUnexpectedErrors} from './check_errors'; import {checkExpectations} from './check_expectations'; import {CompileResult, initMockTestFileSystem} from './compile_test'; import { CompilationMode, ComplianceTest, Expectation, getAllComplianceTests, } from './get_compliance_tests'; function transformExpectation(expectation: Expectation, isLocalCompilation: boolean): void { expectation.files = expectation.files.map((pair) => ({ expected: pair.expected, generated: pair.generated, })); if (isLocalCompilation) { expectation.files = expectation.files.map((pair) => ({ expected: getFilenameForLocalCompilation(pair.expected), generated: pair.generated, })); } } /** Adds a '.local' pre-extension, e.g., basic_full.js -> basic_full.local.js */ function getFilenameForLocalCompilation(fileName: string): string { return fileName.replace(/\.([cm]?js)$/, '.local.$1'); } /** * Set up jasmine specs for each of the compliance tests. * * @param type A description of the type of tests being run. * @param compileFn The function that will do the compilation of the source files * @param options Extra options. Currently the only option is the flag `isLocalCompilation` which * indicates whether we are testing in local compilation mode. */ export function runTests( type: CompilationMode, compileFn: (fs: FileSystem, test: ComplianceTest) => CompileResult, options: {isLocalCompilation?: boolean; skipMappingChecks?: boolean} = {}, ) { describe(`compliance tests (${type})`, () => { for (const test of getAllComplianceTests()) { if (!test.compilationModeFilter.includes(type)) { continue; } if (test.skipForTemplatePipeline) { continue; } describe(`[${test.relativePath}]`, () => { const itFn = test.focusTest ? fit : test.excludeTest ? xit : it; itFn(test.description, () => { if (type === 'linked compile' && test.compilerOptions?.['target'] === 'ES5') { throw new Error( `The "${type}" scenario does not support ES5 output.\n` + `Did you mean to set \`"compilationModeFilter": ["full compile"]\` in "${test.relativePath}"?`, ); } const fs = initMockTestFileSystem(test.realTestPath); const {errors} = compileFn(fs, test); for (const expectation of test.expectations) { transformExpectation(expectation, !!options.isLocalCompilation); if (expectation.expectedErrors.length > 0) { checkErrors( test.relativePath, expectation.failureMessage, expectation.expectedErrors, errors, ); } else { checkNoUnexpectedErrors(test.relativePath, errors); checkExpectations( fs, test.relativePath, expectation.failureMessage, expectation.files, expectation.extraChecks, options.skipMappingChecks, ); } } }); }); } }); }
{ "end_byte": 3434, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_helpers/test_runner.ts" }
angular/packages/compiler-cli/test/compliance/test_helpers/i18n_helpers.ts_0_5390
/** * @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 */ /** * Unique message id index that is needed to avoid different i18n vars with the same name to appear * in the i18n block while generating an output string (used to verify compiler-generated code). */ let msgIndex = 0; export function resetMessageIndex(): void { msgIndex = 0; } /** * Generate a string that represents expected i18n block content for a simple message. */ export function i18nMsg( message: string, placeholders: Placeholder[], options: Options, meta: Meta, ): string { const varName = `$I18N_${msgIndex++}$`; const closurePlaceholders = i18nPlaceholdersToString(placeholders); const closureOptions = i18nOptionsToString(options); const locMessageWithPlaceholders = i18nMsgInsertLocalizePlaceholders(message, placeholders); return ` let ${varName}; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { ${i18nMsgClosureMeta(meta)} const $MSG_EXTERNAL_${msgIndex}$ = goog.getMsg("${message}"${closurePlaceholders}${closureOptions}); ${varName} = $MSG_EXTERNAL_${msgIndex}$; } else { ${varName} = $localize \`${i18nMsgLocalizeMeta(meta)}${locMessageWithPlaceholders}\`; }`; } /** Describes options bag passed to `goog.getMsg()`. */ export interface Options { original_code?: Record<string /* placeholderName */, string /* original */>; } /** * Generate a string that represents expected i18n block content for a message that requires * post-processing. */ export function i18nMsgWithPostprocess( message: string, placeholders: Placeholder[], options: Options, meta: Meta, postprocessPlaceholders: Placeholder[], ): string { const varName = `$I18N_${msgIndex}$`; const ppPlaceholders = i18nPlaceholdersToString(postprocessPlaceholders); return String.raw` ${i18nMsg(message, placeholders, options, meta)} ${varName} = $r3$.ɵɵi18nPostprocess($${varName}$${ppPlaceholders}); `; } /** * Generates a string that represents expected i18n block content for an ICU. */ export function i18nIcuMsg(message: string, placeholders: Placeholder[], options: Options): string { return i18nMsgWithPostprocess(message, [], options, {}, placeholders); } /** * Describes placeholder type used in tests. * * - The first item is the placeholder name. * - The second item is the identifier of the variable that contains the placeholder. * - The third (optional) items is the id of the message that this placeholder references. * This is used for matching ICU placeholders to ICU messages. */ export type Placeholder = [name: string, indentifier: string, associatedId: string]; /** * Describes message metadata object. */ interface Meta { desc?: string; meaning?: string; id?: string; } /** * Convert a set of placeholders to a string (as it's expected from compiler). */ function i18nPlaceholdersToString(placeholders: Placeholder[]): string { if (placeholders.length === 0) return ''; const result = placeholders.map(([name, identifier]) => `"${name}": ${quotedValue(identifier)}`); return `, { ${result.join(',')} }`; } /** Convert an object of `goog.getMsg()` options to the expected string. */ function i18nOptionsToString({original_code: originals = {}}: Options = {}): string { if (Object.keys(originals).length === 0) return ''; const result = Object.entries(originals).map(([key, value]) => `"${key}": ${quotedValue(value)}`); return `, { original_code: {\n${result.join(',\n')}\n} }`; } /** * Transform a message in a Closure format to a $localize version. */ function i18nMsgInsertLocalizePlaceholders(message: string, placeholders: Placeholder[]): string { if (placeholders.length > 0) { message = message.replace(/{\$(.*?)}/g, function (_, name) { const placeholder = placeholders.find((p) => p[0] === name)!; // e.g. startDivTag -> START_DIV_TAG const key = name.replace(/[A-Z]/g, (ch: string) => '_' + ch).toUpperCase(); const associated = placeholder.length === 3 ? `@@${placeholder[2]}` : ''; return '$' + `{${quotedValue(placeholder[1])}}:${key}${associated}:`; }); } return message; } /** * Generate a string that represents expected Closure metadata output comment. */ function i18nMsgClosureMeta(meta?: Meta): string { if (!meta) return ''; return ` /** * ${meta.desc ? '@desc ' + meta.desc : '@suppress {msgDescriptions}'} ${meta.meaning ? '* @meaning ' + meta.meaning : ''} */ `; } /** * Generate a string that represents expected $localize metadata output. */ function i18nMsgLocalizeMeta(meta?: Meta): string { if (!meta) return ''; let localizeMeta = ''; if (meta.meaning) localizeMeta += `${meta.meaning}|`; if (meta.desc) localizeMeta += meta.desc; if (meta.id) localizeMeta += `@@${meta.id}`; return localizeMeta !== '' ? `:${localizeMeta}:` : ''; } /** * Wrap a string into quotes if needed. * * Note: if `value` starts with `$` it is a special case in tests when ICU reference is used as a * placeholder value. Such special cases should not be wrapped in quotes. */ function quotedValue(value: string): string { return value.startsWith('$') ? value : `"${value.replace(/"/g, '\\"')}"`; }
{ "end_byte": 5390, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_helpers/i18n_helpers.ts" }
angular/packages/compiler-cli/test/compliance/test_helpers/i18n_checks.ts_0_2766
/** * @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 */ const EXTRACT_GENERATED_TRANSLATIONS_REGEXP = /const\s*(.*?)\s*=\s*goog\.getMsg\("(.*?)",?\s*(.*?)\)/g; /** * Verify that placeholders in translation strings match placeholders in the object defined in the * `goog.getMsg()` function arguments. */ export function verifyPlaceholdersIntegrity(output: string): boolean { const translations = extractTranslations(output); for (const [msg, args] of translations) { const bodyPhs = extractPlaceholdersFromMsg(msg); const argsPhs = extractPlaceholdersFromArgs(args); if (bodyPhs.size !== argsPhs.size || diff(bodyPhs, argsPhs).size) { return false; } } return true; } /** * Verify that all the variables initialized with `goog.getMsg()` calls have * unique names. */ export function verifyUniqueConsts(output: string): boolean { extract( output, EXTRACT_GENERATED_TRANSLATIONS_REGEXP, (current: string[], state: Set<string>): string => { const key = current[1]; if (state.has(key)) { throw new Error(`Duplicate const ${key} found in generated output!`); } return key; }, ); return true; } /** * Extract pairs of `[msg, placeholders]`, in calls to `goog.getMsg()`, from the `source`. * * @param source The source code to parse. */ function extractTranslations(source: string): Set<string[]> { return extract(source, EXTRACT_GENERATED_TRANSLATIONS_REGEXP, ([, , msg, placeholders]) => [ msg, placeholders, ]); } /** * Extract placeholder names (of the form `{$PLACEHOLDER}`) from the `msg`. * * @param msg The text of the message to parse. */ function extractPlaceholdersFromMsg(msg: string): Set<string> { const regex = /{\$(.*?)}/g; return extract(msg, regex, ([, placeholders]) => placeholders); } /** * Extract the placeholder names (of the form `"PLACEHOLDER": "XXX"`) from the body of the argument * provided as `args`. * * @param args The body of an object literal containing placeholder info. */ function extractPlaceholdersFromArgs(args: string): Set<string> { const regex = /\s+"(.+?)":\s/g; return extract(args, regex, ([, placeholders]) => placeholders); } function extract<T>( from: string, regex: RegExp, transformFn: (match: string[], state: Set<T>) => T, ): Set<T> { const result = new Set<T>(); let item: RegExpExecArray | null; while ((item = regex.exec(from)) !== null) { result.add(transformFn(item, result)); } return result; } function diff(a: Set<string>, b: Set<string>): Set<string> { return new Set(Array.from(a).filter((x) => !b.has(x))); }
{ "end_byte": 2766, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_helpers/i18n_checks.ts" }
angular/packages/compiler-cli/test/compliance/test_helpers/BUILD.bazel_0_703
load("//tools:defaults.bzl", "ts_library") ts_library( name = "test_helpers", testonly = True, srcs = glob( ["**/*.ts"], ), visibility = [ "//packages/compiler-cli/test/compliance:__subpackages__", ], deps = [ "//packages:types", "//packages/compiler", "//packages/compiler-cli", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/logging", "//packages/compiler-cli/src/ngtsc/sourcemaps", "//packages/compiler-cli/src/ngtsc/testing", "@npm//@bazel/runfiles", "@npm//typescript", ], )
{ "end_byte": 703, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_helpers/BUILD.bazel" }
angular/packages/compiler-cli/test/compliance/test_helpers/check_expectations.ts_0_4217
/** * @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 {getBuildOutputDirectory, getRootDirectory} from './compile_test'; import {verifyUniqueFactory} from './di_checks'; import {expectEmit} from './expect_emit'; import {replaceMacros} from './expected_file_macros'; import {verifyUniqueFunctions} from './function_checks'; import {ExpectedFile, ExtraCheck} from './get_compliance_tests'; import {verifyPlaceholdersIntegrity, verifyUniqueConsts} from './i18n_checks'; import {stripAndCheckMappings} from './sourcemap_helpers'; type ExtraCheckFunction = (generated: string, ...extraArgs: any[]) => boolean; const EXTRA_CHECK_FUNCTIONS: Record<string, ExtraCheckFunction> = { verifyPlaceholdersIntegrity, verifyUniqueConsts, verifyUniqueFactory, verifyUniqueFunctions, }; /** * Check that each of the generated files matches the expected files. * * @param fs The mock file-system that holds the expected and generated files to compare. * @param testPath Path to the current test case (relative to the basePath). * @param failureMessage The message to display if the expectation fails. * @param expectedFiles The list of expected-generated pairs to compare. * @param skipMappingCheck Whether to skip checking source mappings. * TODO: Remove this option. This only exists until we fix: * https://github.com/angular/angular/issues/51647. */ export function checkExpectations( fs: ReadonlyFileSystem, testPath: string, failureMessage: string, expectedFiles: ExpectedFile[], extraChecks: ExtraCheck[], skipMappingCheck = false, ): void { const builtDirectory = getBuildOutputDirectory(fs); for (const expectedFile of expectedFiles) { const expectedPath = fs.resolve(getRootDirectory(fs), expectedFile.expected); if (!fs.exists(expectedPath)) { throw new Error( `The expected file at ${expectedPath} does not exist. Please check the TEST_CASES.json file for this test case.`, ); } const generatedPath = fs.resolve(builtDirectory, expectedFile.generated); if (!fs.exists(generatedPath)) { const error = new Error( `The generated file at ${generatedPath} does not exist.\n` + 'Perhaps there is no matching input source file in the TEST_CASES.json file for this test case.\n' + 'Or maybe you need to regenerate the GOLDEN_PARTIAL.js file by running:\n\n' + ` yarn bazel run //packages/compiler-cli/test/compliance/test_cases:${testPath}.golden.update`, ); // Clear the stack so that we get a nice error message error.stack = ''; throw error; } const generated = fs.readFile(generatedPath); let expected = fs.readFile(expectedPath); expected = replaceMacros(expected); expected = stripAndCheckMappings( fs, generated, generatedPath, expected, expectedPath, /** skipMappingCheck */ !!skipMappingCheck, ); expectEmit( generated, expected, `When checking against expected file "${testPath}/${expectedFile.expected}"\n` + failureMessage, ); runExtraChecks(testPath, generated, extraChecks); } } function runExtraChecks( testPath: string, generated: string, extraChecks: (string | [string, ...any])[], ): void { for (const check of extraChecks) { let fnName: string; let args: any[]; if (Array.isArray(check)) { [fnName, ...args] = check; } else { fnName = check; args = []; } const fn = EXTRA_CHECK_FUNCTIONS[fnName]; if (fn === undefined) { throw new Error( `Unknown extra-check function: "${fnName}" in ${testPath}.\n` + `Possible choices are: ${Object.keys(EXTRA_CHECK_FUNCTIONS).map((f) => `\n - ${f}`)}.`, ); } if (!fn(generated, ...args)) { throw new Error( `Extra check ${fnName}(${args .map((arg) => JSON.stringify(arg)) .join(',')}) in ${testPath} failed for generated code:\n\n${generated}`, ); } } }
{ "end_byte": 4217, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/compliance/test_helpers/check_expectations.ts" }
angular/packages/compiler-cli/test/ngtsc/template_mapping_spec.ts_0_4698
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /// <reference types="node" /> import {inspect} from 'util'; import ts from 'typescript'; import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env'; import {getMappedSegments, SegmentMapping} from './sourcemap_utils'; const testFiles = loadStandardTestFiles(); runInEachFileSystem((os) => { describe('template source-mapping', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.tsconfig({ sourceMap: true, target: ts.ScriptTarget.ES2015, enableI18nLegacyMessageIdFormat: false, }); }); describe('Inline templates', () => { describe('(element creation)', () => { it('should map simple element with content', async () => { const mappings = await compileAndMap('<h1>Heading 1</h1>'); expectMapping(mappings, { source: '<h1>', generated: 'i0.ɵɵelementStart(0, "h1")', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: 'Heading 1', generated: 'i0.ɵɵtext(1, "Heading 1")', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '</h1>', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); }); it('should map void element', async () => { const mappings = await compileAndMap('<hr>'); expectMapping(mappings, { source: '<hr>', generated: 'i0.ɵɵelement(0, "hr")', sourceUrl: '../test.ts', }); }); }); describe('(interpolations)', () => { it('should map a mix of interpolated and static content', async () => { const mappings = await compileAndMap('<h3>Hello {{ name }}</h3>'); expectMapping(mappings, { source: '<h3>', generated: 'i0.ɵɵelementStart(0, "h3")', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: 'Hello {{ name }}', generated: 'i0.ɵɵtextInterpolate1("Hello ", ctx.name, "")', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '</h3>', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); }); it('should map a complex interpolated expression', async () => { const mappings = await compileAndMap('<h2>{{ greeting + " " + name }}</h2>'); expectMapping(mappings, { source: '<h2>', generated: 'i0.ɵɵelementStart(0, "h2")', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '{{ greeting + " " + name }}', generated: 'i0.ɵɵtextInterpolate(ctx.greeting + " " + ctx.name)', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '</h2>', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); }); it('should map interpolated properties', async () => { const mappings = await compileAndMap('<div id="{{name}}"></div>'); expectMapping(mappings, { source: '<div id="{{name}}"></div>', generated: 'i0.ɵɵelement(0, "div", 0)', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: 'id="{{name}}"', generated: 'i0.ɵɵpropertyInterpolate("id", ctx.name)', sourceUrl: '../test.ts', }); }); it('should map interpolation with pipe', async () => { const mappings = await compileAndMap('<div>{{200.3 | percent : 2 }}</div>'); expectMapping(mappings, { source: '<div>', generated: 'i0.ɵɵelementStart(0, "div")', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '{{200.3 | percent : 2 }}', generated: 'i0.ɵɵtextInterpolate(i0.ɵɵpipeBind2(2, 1, 200.3, 2))', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '</div>', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); }); }); describe('(property bind
{ "end_byte": 4698, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_mapping_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_mapping_spec.ts_4706_12118
() => { it('should map a simple input binding expression', async () => { const mappings = await compileAndMap('<div [attr]="name"></div>'); expectMapping(mappings, { source: '<div [attr]="name"></div>', generated: 'i0.ɵɵelement(0, "div", 0)', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '[attr]="name"', generated: 'i0.ɵɵproperty("attr", ctx.name)', sourceUrl: '../test.ts', }); }); it('should map a complex input binding expression', async () => { const mappings = await compileAndMap('<div [attr]="greeting + name"></div>'); expectMapping(mappings, { source: '<div [attr]="greeting + name"></div>', generated: 'i0.ɵɵelement(0, "div", 0)', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '[attr]="greeting + name"', generated: 'i0.ɵɵproperty("attr", ctx.greeting + ctx.name)', sourceUrl: '../test.ts', }); }); it('should map a longhand input binding expression', async () => { const mappings = await compileAndMap('<div bind-attr="name"></div>'); expectMapping(mappings, { source: '<div bind-attr="name"></div>', generated: 'i0.ɵɵelement(0, "div", 0)', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: 'bind-attr="name"', generated: 'i0.ɵɵproperty("attr", ctx.name)', sourceUrl: '../test.ts', }); }); it('should map a simple output binding expression', async () => { const mappings = await compileAndMap('<button (click)="doSomething()">Do it</button>'); expectMapping(mappings, { source: '<button (click)="doSomething()">', generated: 'i0.ɵɵelementStart(0, "button", 0)', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: 'Do it', generated: 'i0.ɵɵtext(1, "Do it")', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: 'doSomething()', generated: 'ctx.doSomething()', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '</button>', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); }); it('should map a complex output binding expression', async () => { const mappings = await compileAndMap( `<button (click)="items.push('item' + items.length)">Add Item</button>`, ); expectMapping(mappings, { source: `<button (click)="items.push('item' + items.length)">`, generated: 'i0.ɵɵelementStart(0, "button", 0)', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: 'Add Item', generated: 'i0.ɵɵtext(1, "Add Item")', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: 'items.push(', generated: 'ctx.items.push(', sourceUrl: '../test.ts', }); expectMapping(mappings, {source: `'item'`, generated: `"item"`, sourceUrl: '../test.ts'}); expectMapping(mappings, { source: ' + items.length)', generated: ' + ctx.items.length)', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '</button>', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); }); it('should map a longhand output binding expression', async () => { const mappings = await compileAndMap('<button on-click="doSomething()">Do it</button>'); expectMapping(mappings, { source: '<button on-click="doSomething()">', generated: 'i0.ɵɵelementStart(0, "button", 0)', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: 'Do it', generated: 'i0.ɵɵtext(1, "Do it")', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: 'doSomething()', generated: 'ctx.doSomething()', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '</button>', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); }); it('should map a two-way binding expression', async () => { const mappings = await compileAndMap('Name: <input [(ngModel)]="name">'); expectMapping(mappings, { source: '<input [(ngModel)]="name">', generated: 'i0.ɵɵelementStart(1, "input", 0)', sourceUrl: '../test.ts', }); // TODO: improve mappings here expectMapping(mappings, { source: '[(ngModel)]="name"', generated: 'i0.ɵɵtwoWayListener("ngModelChange", function TestCmp_Template_input_ngModelChange_1_listener($event) { i0.ɵɵtwoWayBindingSet(ctx.name, $event) || (ctx.name = $event); return $event; })', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '<input [(ngModel)]="name">', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); }); it('should map a longhand two-way binding expression', async () => { const mappings = await compileAndMap('Name: <input bindon-ngModel="name">'); expectMapping(mappings, { source: '<input bindon-ngModel="name">', generated: 'i0.ɵɵelementStart(1, "input", 0)', sourceUrl: '../test.ts', }); // TODO: improve mappings here expectMapping(mappings, { source: 'bindon-ngModel="name"', generated: 'i0.ɵɵtwoWayListener("ngModelChange", function TestCmp_Template_input_ngModelChange_1_listener($event) { i0.ɵɵtwoWayBindingSet(ctx.name, $event) || (ctx.name = $event); return $event; })', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '<input bindon-ngModel="name">', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); }); it('should map a class input binding', async () => { const mappings = await compileAndMap('<div [class.initial]="isInitial">Message</div>'); expectMapping(mappings, { source: '<div [class.initial]="isInitial">', generated: 'i0.ɵɵelementStart(0, "div")', sourceUrl: '../test.ts', }); // TODO: Add better mappings for binding expectMapping(mappings, { source: 'Message', generated: 'i0.ɵɵtext(1, "Message")', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '</div>', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); }); }); describe('(structural directives)', () => { it('should map *ngIf sce
{ "end_byte": 12118, "start_byte": 4706, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_mapping_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_mapping_spec.ts_12126_16288
async () => { const mappings = await compileAndMap('<div *ngIf="showMessage()">{{ name }}</div>'); expectMapping(mappings, { source: '<div *ngIf="showMessage()">', generated: 'i0.ɵɵelementStart(0, "div")', sourceUrl: '../test.ts', }); // TODO - map the bindings better expectMapping(mappings, { source: '</div>', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); // TODO: the `ctx_r...` appears to be dependent upon previous tests!!! // expectMapping(mappings, { // source: '{{ name }}', // generated: 'i0.ɵɵtextInterpolate(ctx_r0.name)', // sourceUrl: '../test.ts' // }); }); it('should map ng-template [ngIf] scenario', async () => { const mappings = await compileAndMap( `<ng-template [ngIf]="showMessage()">\n` + ` <div>{{ name }}</div>\n` + ` <hr>\n` + `</ng-template>`, ); expectMapping(mappings, { source: '<div>', generated: 'i0.ɵɵelementStart(0, "div")', sourceUrl: '../test.ts', }); // TODO - map the bindings better expectMapping(mappings, { source: '</div>', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); // TODO: the `ctx_r...` appears to be dependent upon previous tests!!! // expectMapping(mappings, { // source: '{{ name }}', // generated: 'i0.ɵɵtextInterpolate(ctx_r0.name)', // sourceUrl: '../test.ts' // }); }); it('should map *ngFor scenario', async () => { const mappings = await compileAndMap( '<div *ngFor="let item of items; index as i; trackBy: trackByFn">{{ item }}</div>', ); expectMapping(mappings, { source: '<div *ngFor="let item of items; index as i; trackBy: trackByFn">', generated: 'i0.ɵɵelementStart(0, "div")', sourceUrl: '../test.ts', }); // TODO - map the bindings better expectMapping(mappings, { source: '</div>', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); }); it('should map ng-template [ngFor] scenario', () => { const mappings = compileAndMap( `<ng-template ngFor [ngForOf]="items" let-item>{{ item }}</ng-template>`, ); // TODO - map the bindings better }); }); describe('(content projection)', () => { it('should map default and selected projection', async () => { const mappings = await compileAndMap( `<h3><ng-content select="title"></ng-content></h3>\n` + `<div><ng-content></ng-content></div>`, ); expectMapping(mappings, { source: '<h3>', generated: 'i0.ɵɵelementStart(0, "h3")', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '<ng-content select="title"></ng-content>', generated: 'i0.ɵɵprojection(1)', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '</h3>', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '<div>', generated: 'i0.ɵɵelementStart(2, "div")', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '<ng-content></ng-content>', generated: 'i0.ɵɵprojection(3, 1)', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '</div>', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); }); }); describe('$localize', () => { it('should create simple i18n message source-mapping', async () =>
{ "end_byte": 16288, "start_byte": 12126, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_mapping_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_mapping_spec.ts_16296_24706
const mappings = await compileAndMap(`<div i18n>Hello, World!</div>`); expectMapping(mappings, { source: '<div i18n>', generated: 'i0.ɵɵelementStart(0, "div")', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: 'Hello, World!', generated: '`Hello, World!`', sourceUrl: '../test.ts', }); }); it('should create placeholder source-mappings', async () => { const mappings = await compileAndMap(`<div i18n>Hello, {{name}}!</div>`); expectMapping(mappings, { source: '<div i18n>', generated: 'i0.ɵɵelementStart(0, "div")', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '</div>', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: 'Hello, ', generated: '`Hello, ${', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '{{name}}', generated: '"\\uFFFD0\\uFFFD"', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '!', generated: '}:INTERPOLATION:!`', sourceUrl: '../test.ts', }); }); // TODO: Temporarily disabled because Template Pipeline produces different const indices // than TemplateDefinitionBuilder. Re-enable after Template Pipeline is the default, and // update the test with the new const index. xit('should correctly handle collapsed whitespace in interpolation placeholder source-mappings', async () => { const mappings = await compileAndMap( `<div i18n title=" pre-title {{name}} post-title" i18n-title> pre-body {{greeting}} post-body</div>`, ); expectMapping(mappings, { source: '<div i18n title=" pre-title {{name}} post-title" i18n-title>', generated: 'i0.ɵɵelementStart(0, "div", 0)', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '</div>', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: ' pre-body ', generated: '` pre-body ${', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '{{greeting}}', generated: '"\\uFFFD0\\uFFFD"', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: ' post-body', generated: '}:INTERPOLATION: post-body`', sourceUrl: '../test.ts', }); }); it('should correctly handle collapsed whitespace in element placeholder source-mappings', async () => { const mappings = await compileAndMap( `<div i18n>\n pre-p\n <p>\n in-p\n </p>\n post-p\n</div>`, ); // $localize expressions expectMapping(mappings, { sourceUrl: '../test.ts', source: '\n pre-p\n ', generated: '` pre-p ${', }); expectMapping(mappings, { sourceUrl: '../test.ts', source: '<p>', generated: '"\\uFFFD#2\\uFFFD"', }); expectMapping(mappings, { sourceUrl: '../test.ts', source: '\n in-p\n ', generated: '}:START_PARAGRAPH: in-p ${', }); expectMapping(mappings, { sourceUrl: '../test.ts', source: '</p>', generated: '"\\uFFFD/#2\\uFFFD"', }); expectMapping(mappings, { sourceUrl: '../test.ts', source: '\n post-p\n', generated: '}:CLOSE_PARAGRAPH: post-p\n`', }); // ivy instructions expectMapping(mappings, { sourceUrl: '../test.ts', source: '<div i18n>', generated: 'i0.ɵɵelementStart(0, "div")', }); expectMapping(mappings, { sourceUrl: '../test.ts', source: '<div i18n>', generated: 'i0.ɵɵi18nStart(1, 0)', }); expectMapping(mappings, { sourceUrl: '../test.ts', source: '<p>\n in-p\n </p>', generated: 'i0.ɵɵelement(2, "p")', }); expectMapping(mappings, { sourceUrl: '../test.ts', source: '</div>', generated: 'i0.ɵɵi18nEnd()', }); expectMapping(mappings, { sourceUrl: '../test.ts', source: '</div>', generated: 'i0.ɵɵelementEnd()', }); }); it('should create tag (container) placeholder source-mappings', async () => { const mappings = await compileAndMap(`<div i18n>Hello, <b>World</b>!</div>`); expectMapping(mappings, { source: '<div i18n>', generated: 'i0.ɵɵelementStart(0, "div")', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '</div>', generated: 'i0.ɵɵelementEnd()', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: 'Hello, ', generated: '`Hello, ${', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '<b>', generated: '"\\uFFFD#2\\uFFFD"', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: 'World', generated: '}:START_BOLD_TEXT:World${', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '</b>', generated: '"\\uFFFD/#2\\uFFFD"', sourceUrl: '../test.ts', }); expectMapping(mappings, { source: '!', generated: '}:CLOSE_BOLD_TEXT:!`', sourceUrl: '../test.ts', }); }); }); it('should create (simple string) inline template source-mapping', async () => { const mappings = await compileAndMap('<div>this is a test</div><div>{{ 1 + 2 }}</div>'); // Creation mode expectMapping(mappings, { generated: 'i0.ɵɵelementStart(0, "div")', source: '<div>', sourceUrl: '../test.ts', }); expectMapping(mappings, { generated: 'i0.ɵɵtext(1, "this is a test")', source: 'this is a test', sourceUrl: '../test.ts', }); expectMapping(mappings, { generated: 'i0.ɵɵelementEnd()', source: '</div>', sourceUrl: '../test.ts', }); expectMapping(mappings, { generated: 'i0.ɵɵelementStart(2, "div")', source: '<div>', sourceUrl: '../test.ts', }); expectMapping(mappings, { generated: 'i0.ɵɵtext(3)', source: '{{ 1 + 2 }}', sourceUrl: '../test.ts', }); expectMapping(mappings, { generated: 'i0.ɵɵelementEnd()', source: '</div>', sourceUrl: '../test.ts', }); // Update mode expectMapping(mappings, { generated: 'i0.ɵɵtextInterpolate(1 + 2)', source: '{{ 1 + 2 }}', sourceUrl: '../test.ts', }); }); it('should create correct inline template source-mapping when the source contains escape sequences', async () => { // Note that the escaped double quotes, which need un-escaping to be parsed correctly. const mappings = await compileAndMap('<div class=\\"some-class\\">this is a test</div>'); expectMapping(mappings, { generated: 'i0.ɵɵelementStart(0, "div", 0)', source: '<div class=\\"some-class\\">', sourceUrl: '../test.ts', }); const attrsMapping = mappings.find((mapping) => /consts: \[\[1, "some-class"\]\]/.test(mapping.generated), ); expect(attrsMapping).toBeDefined(); }); }); describe('External templates (where TS supports source-mapping)', () => { it('should create external template source-mapping', async () =>
{ "end_byte": 24706, "start_byte": 16296, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_mapping_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/template_mapping_spec.ts_24706_31440
{ const mappings = await compileAndMap( '<div>this is a test</div><div>{{ 1 + 2 }}</div>', './dir/test.html', ); // Creation mode expectMapping(mappings, { generated: 'i0.ɵɵelementStart(0, "div")', source: '<div>', sourceUrl: '../dir/test.html', }); expectMapping(mappings, { generated: 'i0.ɵɵtext(1, "this is a test")', source: 'this is a test', sourceUrl: '../dir/test.html', }); expectMapping(mappings, { generated: 'i0.ɵɵelementEnd()', source: '</div>', sourceUrl: '../dir/test.html', }); expectMapping(mappings, { generated: 'i0.ɵɵelementStart(2, "div")', source: '<div>', sourceUrl: '../dir/test.html', }); expectMapping(mappings, { generated: 'i0.ɵɵtext(3)', source: '{{ 1 + 2 }}', sourceUrl: '../dir/test.html', }); expectMapping(mappings, { generated: 'i0.ɵɵelementEnd()', source: '</div>', sourceUrl: '../dir/test.html', }); // Update mode expectMapping(mappings, { generated: 'i0.ɵɵtextInterpolate(1 + 2)', source: '{{ 1 + 2 }}', sourceUrl: '../dir/test.html', }); }); it('should create correct mappings when templateUrl is in a different rootDir', async () => { const mappings = await compileAndMap( '<div>this is a test</div><div>{{ 1 + 2 }}</div>', 'extraRootDir/test.html', ); // Creation mode expectMapping(mappings, { generated: 'i0.ɵɵelementStart(0, "div")', source: '<div>', sourceUrl: '../extraRootDir/test.html', }); expectMapping(mappings, { generated: 'i0.ɵɵtext(1, "this is a test")', source: 'this is a test', sourceUrl: '../extraRootDir/test.html', }); expectMapping(mappings, { generated: 'i0.ɵɵelementEnd()', source: '</div>', sourceUrl: '../extraRootDir/test.html', }); expectMapping(mappings, { generated: 'i0.ɵɵelementStart(2, "div")', source: '<div>', sourceUrl: '../extraRootDir/test.html', }); expectMapping(mappings, { generated: 'i0.ɵɵtext(3)', source: '{{ 1 + 2 }}', sourceUrl: '../extraRootDir/test.html', }); expectMapping(mappings, { generated: 'i0.ɵɵelementEnd()', source: '</div>', sourceUrl: '../extraRootDir/test.html', }); // Update mode expectMapping(mappings, { generated: 'i0.ɵɵtextInterpolate(1 + 2)', source: '{{ 1 + 2 }}', sourceUrl: '../extraRootDir/test.html', }); }); }); async function compileAndMap(template: string, templateUrl: string | null = null) { const templateConfig = templateUrl ? `templateUrl: '${templateUrl}'` : 'template: `' + template.replace(/\`/g, '\\`') + '`'; env.write( 'test.ts', ` import {Component, Directive, Input, Output, EventEmitter, Pipe, NgModule} from '@angular/core'; @Directive({ selector: '[ngModel],[attr],[ngModelChange]', standalone: false, }) export class AllDirective { @Input() ngModel!: any; @Output() ngModelChange = new EventEmitter<any>(); @Input() attr!: any; } @Pipe({ name: 'percent', standalone: false, }) export class PercentPipe { transform(v: any) {} } @Component({ selector: 'test-cmp', ${templateConfig}, standalone: false, }) export class TestCmp { name = ''; isInitial = false; doSomething() {} items: any[] = []; greeting = ''; } @NgModule({ declarations: [TestCmp, AllDirective, PercentPipe], }) export class Module {} `, ); if (templateUrl) { env.write(templateUrl, template); } env.driveMain(); return await getMappedSegments(env, 'test.js'); } /** * Helper function for debugging failed mappings. * This lays out the segment mappings in the console to make it easier to compare. */ function dumpMappings(mappings: SegmentMapping[]) { mappings.forEach((map) => { // tslint:disable-next-line:no-console console.log( padValue(map.sourceUrl, 20, 0) + ' : ' + padValue(inspect(map.source), 100, 23) + ' : ' + inspect(map.generated), ); }); function padValue(value: string, max: number, start: number) { const padding = value.length > max ? '\n' + ' '.repeat(max + start) : ' '.repeat(max - value.length); return value + padding; } } function expectMapping(mappings: SegmentMapping[], expected: SegmentMapping): void { if ( mappings.some( (m) => m.generated === expected.generated && m.source === expected.source && m.sourceUrl === expected.sourceUrl, ) ) { return; } const matchingGenerated = mappings.filter((m) => m.generated === expected.generated); const matchingSource = mappings.filter((m) => m.source === expected.source); const message = [ 'Expected mappings to contain the following mapping', prettyPrintMapping(expected), ]; if (matchingGenerated.length > 0) { message.push(''); message.push('There are the following mappings that match the generated text:'); matchingGenerated.forEach((m) => message.push(prettyPrintMapping(m))); } if (matchingSource.length > 0) { message.push(''); message.push('There are the following mappings that match the source text:'); matchingSource.forEach((m) => message.push(prettyPrintMapping(m))); } fail(message.join('\n')); } function prettyPrintMapping(mapping: SegmentMapping): string { return [ '{', ` generated: ${JSON.stringify(mapping.generated)}`, ` source: ${JSON.stringify(mapping.source)}`, ` sourceUrl: ${JSON.stringify(mapping.sourceUrl)}`, '}', ].join('\n'); } }); });
{ "end_byte": 31440, "start_byte": 24706, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/template_mapping_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/extended_template_diagnostics_spec.ts_0_8138
/** * @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 {getSourceCodeForDiagnostic, loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles({fakeCommon: true}); runInEachFileSystem(() => { describe('ngtsc extended template checks', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.tsconfig({strictTemplates: true}); }); it('should produce invalid banana in box warning', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '<div ([notARealThing])="bar"></div>', }) class TestCmp { bar: string = "text"; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INVALID_BANANA_IN_BOX)); expect(getSourceCodeForDiagnostic(diags[0])).toBe('([notARealThing])="bar"'); }); it('should produce invalid banana in box warning with external html file', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test', templateUrl: './test.html', }) class TestCmp { bar: string = "text"; } `, ); env.write( 'test.html', ` <div ([notARealThing])="bar"></div> `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.INVALID_BANANA_IN_BOX)); expect(getSourceCodeForDiagnostic(diags[0])).toBe('([notARealThing])="bar"'); }); it(`should produce nullish coalescing not nullable warning`, () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '{{ bar ?? "foo" }}', }) export class TestCmp { bar: string = "text"; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].category).toBe(ts.DiagnosticCategory.Warning); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.NULLISH_COALESCING_NOT_NULLABLE)); expect(getSourceCodeForDiagnostic(diags[0])).toBe('bar ?? "foo"'); }); describe('handles diagnostic configuration', () => { // Component definition which emits one warning. const warningComponent = ` import {Component} from '@angular/core'; @Component({ selector: 'test-component', // Invalid banana in box (should be \`[(foo)]="bar"\`). template: '<div ([foo])="bar"></div>', }) class TestComponent { bar = 'test'; } `; it('by enabling extended template diagnostics when `strictTemplates` is enabled', () => { env.tsconfig({strictTemplates: true}); env.write('test.ts', warningComponent); const diagnostics = env.driveDiagnostics(0 /* expectedExitCode */); expect(diagnostics.length).toBe(1); expect(diagnostics[0]).toEqual( jasmine.objectContaining({ code: ngErrorCode(ErrorCode.INVALID_BANANA_IN_BOX), category: ts.DiagnosticCategory.Warning, }), ); }); it('by disabling extended template diagnostics when `strictTemplates` is disabled', () => { env.tsconfig({strictTemplates: false}); env.write('test.ts', warningComponent); const diagnostics = env.driveDiagnostics(0 /* expectedExitCode */); expect(diagnostics).toEqual([]); }); it('by emitting unconfigured diagnostics as is', () => { env.tsconfig({ strictTemplates: true, extendedDiagnostics: {}, // No configured diagnostics. }); env.write('test.ts', warningComponent); const diagnostics = env.driveDiagnostics(0 /* expectedExitCode */); expect(diagnostics.length).toBe(1); expect(diagnostics[0]).toEqual( jasmine.objectContaining({ code: ngErrorCode(ErrorCode.INVALID_BANANA_IN_BOX), category: ts.DiagnosticCategory.Warning, }), ); }); it('by emitting diagnostics with the default category', () => { env.tsconfig({ strictTemplates: true, extendedDiagnostics: { defaultCategory: 'error', }, }); env.write('test.ts', warningComponent); const diagnostics = env.driveDiagnostics(1 /* expectedExitCode */); expect(diagnostics.length).toBe(1); expect(diagnostics[0]).toEqual( jasmine.objectContaining({ code: ngErrorCode(ErrorCode.INVALID_BANANA_IN_BOX), category: ts.DiagnosticCategory.Error, }), ); }); it('by emitting diagnostics configured as `warning`', () => { env.tsconfig({ strictTemplates: true, extendedDiagnostics: { checks: { invalidBananaInBox: 'warning', }, }, }); env.write('test.ts', warningComponent); const diagnostics = env.driveDiagnostics(0 /* expectedExitCode */); expect(diagnostics.length).toBe(1); expect(diagnostics[0]).toEqual( jasmine.objectContaining({ code: ngErrorCode(ErrorCode.INVALID_BANANA_IN_BOX), category: ts.DiagnosticCategory.Warning, }), ); }); it('by promoting diagnostics configured as `error`', () => { env.tsconfig({ strictTemplates: true, extendedDiagnostics: { checks: { invalidBananaInBox: 'error', }, }, }); env.write('test.ts', warningComponent); const diagnostics = env.driveDiagnostics(1 /* expectedExitCode */); expect(diagnostics.length).toBe(1); expect(diagnostics[0]).toEqual( jasmine.objectContaining({ code: ngErrorCode(ErrorCode.INVALID_BANANA_IN_BOX), category: ts.DiagnosticCategory.Error, }), ); }); it('by suppressing diagnostics configured as `suppress`', () => { env.tsconfig({ strictTemplates: true, extendedDiagnostics: { checks: { invalidBananaInBox: 'suppress', }, }, }); env.write('test.ts', warningComponent); const diagnostics = env.driveDiagnostics(0 /* expectedExitCode */); expect(diagnostics).toEqual([]); }); it('by throwing an error when given a bad category', () => { env.tsconfig({ strictTemplates: true, extendedDiagnostics: { defaultCategory: 'not-a-category', }, }); env.write('test.ts', warningComponent); const diagnostics = env.driveDiagnostics(1 /* expectedExitCode */); expect(diagnostics.length).toBe(1); expect(diagnostics[0]).toEqual( jasmine.objectContaining({ code: ngErrorCode(ErrorCode.CONFIG_EXTENDED_DIAGNOSTICS_UNKNOWN_CATEGORY_LABEL), category: ts.DiagnosticCategory.Error, }), ); }); }); }); });
{ "end_byte": 8138, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/extended_template_diagnostics_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/authoring_inputs_spec.ts_0_458
/** * @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 {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles();
{ "end_byte": 458, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/authoring_inputs_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/authoring_inputs_spec.ts_460_9684
runInEachFileSystem(() => { describe('initializer-based input() API', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.tsconfig({strictTemplates: true}); }); it('should handle a basic, primitive valued input', () => { env.write( 'test.ts', ` import {Directive, input} from '@angular/core'; @Directive() export class TestDir { data = input('test'); } `, ); env.driveMain(); const js = env.getContents('test.js'); expect(js).toContain('inputs: { data: [1, "data"] }'); }); it('should fail if @Input is applied on signal input member', () => { env.write( 'test.ts', ` import {Directive, Input, input} from '@angular/core'; @Directive() export class TestDir { @Input() data = input('test'); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: `Using @Input with a signal input is not allowed.`, }), ]); }); it('should fail if signal input is also declared in `inputs` decorator field.', () => { env.write( 'test.ts', ` import {Directive, input} from '@angular/core'; @Directive({ inputs: ['data'], }) export class TestDir { data = input('test'); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: 'Input "data" is also declared as non-signal in @Directive.', }), ]); }); it('should fail if signal input declares a non-statically analyzable alias', () => { env.write( 'test.ts', ` import {Directive, input} from '@angular/core'; const ALIAS = 'bla'; @Directive({ inputs: ['data'], }) export class TestDir { data = input('test', {alias: ALIAS}); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: 'Alias needs to be a string that is statically analyzable.', }), ]); }); it('should fail if signal input declares a non-statically analyzable options', () => { env.write( 'test.ts', ` import {Directive, input} from '@angular/core'; const OPTIONS = {}; @Directive({ inputs: ['data'], }) export class TestDir { data = input('test', OPTIONS); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: 'Argument needs to be an object literal that is statically analyzable.', }), ]); }); it('should fail if signal input is declared on static member', () => { env.write( 'test.ts', ` import {Directive, input} from '@angular/core'; @Directive() export class TestDir { static data = input('test'); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: 'Input "data" is incorrectly declared as static member of "TestDir".', }), ]); }); it('should handle an alias configured, primitive valued input', () => { env.write( 'test.ts', ` import {Directive, input} from '@angular/core'; @Directive() export class TestDir { data = input('test', { alias: 'publicName', }); } `, ); env.driveMain(); const js = env.getContents('test.js'); expect(js).toContain('inputs: { data: [1, "publicName", "data"] }'); }); it('should error if a required input declares an initial value', () => { env.write( 'test.ts', ` import {Directive, input} from '@angular/core'; @Directive() export class TestDir { data = input.required({ initialValue: 'bla', }); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics[0].messageText).toEqual( jasmine.objectContaining({ messageText: 'No overload matches this call.', }), ); }); it('should handle a transform and required input', () => { env.write( 'test.ts', ` import {Directive, input} from '@angular/core'; @Directive() export class TestDir { data = input.required({ transform: (v: string|number) => 'works', }); } `, ); env.driveMain(); expect(env.getContents('test.js')).toContain(`inputs: { data: [1, "data"] }`); expect(env.getContents('test.d.ts')).toContain('"required": true; "isSignal": true;'); expect(env.getContents('test.d.ts')) .withContext( 'Expected no coercion member as input signal captures the write type of the transform', ) .not.toContain('ngAcceptInputType'); }); it('should handle a non-primitive initial value', () => { env.write( 'test.ts', ` import {Directive, input} from '@angular/core'; @Directive() export class TestDir { data = input(/default pattern/); } `, ); env.driveMain(); expect(env.getContents('test.js')).toContain(`inputs: { data: [1, "data"] }`); }); it('should report mixed two-way binding with a signal input', () => { env.write( 'test.ts', ` import {Component, Directive, input, Output, EventEmitter} from '@angular/core'; @Directive({standalone: true, selector: '[dir]'}) export class TestDir { value = input('hello'); @Output() valueChange = new EventEmitter<string>(); } @Component({ standalone: true, template: \`<div dir [(value)]="value"></div>\`, imports: [TestDir], }) export class TestComp { value = 1; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`Type 'number' is not assignable to type 'string'.`); }); describe('type checking', () => { it('should work', () => { env.write( 'test.ts', ` import {Component, Directive, input} from '@angular/core'; @Directive({ selector: '[directiveName]', standalone: true, }) export class TestDir { data = input(1); } @Component({ standalone: true, template: \`<div directiveName [data]="false"></div>\`, imports: [TestDir], }) export class TestComp { } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics[0].messageText).toBe( `Type 'boolean' is not assignable to type 'number'.`, ); }); it('should work with transforms', () => { env.write( 'test.ts', ` import {Component, Directive, input} from '@angular/core'; @Directive({ selector: '[directiveName]', standalone: true, }) export class TestDir { data = input.required({ transform: (v: string|number) => 'works', }); } @Component({ standalone: true, template: \`<div directiveName [data]="false"></div>\`, imports: [TestDir], }) export class TestComp { } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics[0].messageText).toBe( `Type 'boolean' is not assignable to type 'string | number'.`, ); }); it('should report unset required inputs', () => { env.write( 'test.ts', ` import {Component, Directive, input} from '@angular/core'; @Directive({ selector: '[directiveName]', standalone: true, }) export class TestDir { data = input.required<boolean>(); } @Component({ standalone: true, template: \`<div directiveName></div>\`, imports: [TestDir], }) export class TestComp { } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics[0].messageText).toBe( `Required input 'data' from directive TestDir must be specified.`, ); }); });
{ "end_byte": 9684, "start_byte": 460, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/authoring_inputs_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/authoring_inputs_spec.ts_9690_11904
describe('diagnostics', () => { it('should error when declared using an ES private field', () => { env.write( 'test.ts', ` import {Directive, input} from '@angular/core'; @Directive({ selector: '[directiveName]', standalone: true, }) export class TestDir { #data = input.required<boolean>(); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics).toEqual([ jasmine.objectContaining<ts.Diagnostic>({ messageText: jasmine.objectContaining<ts.DiagnosticMessageChain>({ messageText: `Cannot use "input" on a class member that is declared as ES private.`, }), }), ]); }); it('should error when declared using a `private` field', () => { env.write( 'test.ts', ` import {Directive, input} from '@angular/core'; @Directive({ selector: '[directiveName]', standalone: true, }) export class TestDir { private data = input.required<boolean>(); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(1); expect(diagnostics).toEqual([ jasmine.objectContaining<ts.Diagnostic>({ messageText: jasmine.objectContaining<ts.DiagnosticMessageChain>({ messageText: `Cannot use "input" on a class member that is declared as private.`, }), }), ]); }); it('should allow declaring using a `protected` field', () => { env.write( 'test.ts', ` import {Directive, input} from '@angular/core'; @Directive({ selector: '[directiveName]', standalone: true, }) export class TestDir { protected data = input.required<boolean>(); } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toBe(0); }); }); }); });
{ "end_byte": 11904, "start_byte": 9690, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/authoring_inputs_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/authoring_diagnostics_spec.ts_0_7802
/** * @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 '../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('authoring API diagnostics', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.tsconfig({strictTemplates: true}); }); it('should report when an initializer function is used outside of an initializer', () => { env.write( 'test.ts', ` import {Component, input} from '@angular/core'; function myInput() { return input(); } @Component({template: ''}) export class TestDir { inp = myInput(); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( 'Unsupported call to the input function. This function can only be called in the initializer of a class member', ); }); it('should report when a required initializer function is used outside of an initializer', () => { env.write( 'test.ts', ` import {Component, input} from '@angular/core'; function myInput() { return input.required<boolean>(); } @Component({template: ''}) export class TestDir { inp = myInput(); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( 'Unsupported call to the input.required function. This function can only be called in the initializer of a class member', ); }); it('should report when an aliased initializer function is used outside of an initializer', () => { env.write( 'test.ts', ` import {Component, input as notInput} from '@angular/core'; function myInput() { return notInput(); } @Component({template: ''}) export class TestDir { inp = myInput(); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( 'Unsupported call to the input function. This function can only be called in the initializer of a class member', ); }); it('should report when an initializer function accessed through a namespace import is used outside of an initializer', () => { env.write( 'test.ts', ` import * as ng from '@angular/core'; function myInput() { return ng.input(); } @ng.Component({template: ''}) export class TestDir { inp = myInput(); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( 'Unsupported call to the input function. This function can only be called in the initializer of a class member', ); }); it('should report when an initializer function is used outside of an initializer in a file that does not have any decorated classes', () => { env.write( 'test.ts', ` import {input} from '@angular/core'; export function myInput() { return input(); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( 'Unsupported call to the input function. This function can only be called in the initializer of a class member', ); }); it('should report when an initializer function is used in a constructor', () => { env.write( 'test.ts', ` import {Component, input} from '@angular/core'; @Component({template: ''}) export class TestDir { inp: any; constructor() { this.inp = input(); } } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( 'Unsupported call to the input function. This function can only be called in the initializer of a class member', ); }); it('should report when an initializer function is an indirect descendant of the initializer', () => { env.write( 'test.ts', ` import {Component, input} from '@angular/core'; @Component({template: ''}) export class TestDir { inp = (() => { return input(); })(); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( 'Unsupported call to the input function. This function can only be called in the initializer of a class member', ); }); it('should not report a correct usage of an initializer API', () => { env.write( 'test.ts', ` import {Component, input} from '@angular/core'; @Component({template: ''}) export class TestDir { inp = input(); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not report if an initializer function is wrapped in a parenthesized expression', () => { env.write( 'test.ts', ` import {Component, input} from '@angular/core'; @Component({template: ''}) export class TestDir { inp = (input()); inp2 = (((((((((input()))))))))); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not report if an initializer function is wrapped in an `as` expression', () => { env.write( 'test.ts', ` import {Component, input} from '@angular/core'; @Component({template: ''}) export class TestDir { inp = input() as any; inp2 = input() as unknown as any as {}; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should report initializer function being used in an undecorated class', () => { env.write( 'test.ts', ` import {input} from '@angular/core'; export class Test { inp = input(); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( 'Unsupported call to the input function. This function can only be used as the initializer of a property on a @Component or @Directive class.', ); }); it('should report initializer function being used in an unsupported Angular class', () => { env.write( 'test.ts', ` import {input, Pipe} from '@angular/core'; @Pipe({name: 'test'}) export class Test { inp = input(); } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( 'Unsupported call to the input function. This function can only be used as the initializer of a property on a @Component or @Directive class.', ); }); }); });
{ "end_byte": 7802, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/authoring_diagnostics_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/imports_spec.ts_0_4278
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import ts from 'typescript'; import {absoluteFrom} from '../../src/ngtsc/file_system'; import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('import generation', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); const tsconfig: {[key: string]: any} = { extends: '../tsconfig-base.json', compilerOptions: { baseUrl: '.', rootDirs: ['/app'], }, angularCompilerOptions: {}, }; env.write('tsconfig.json', JSON.stringify(tsconfig, null, 2)); }); it('should report an error when using a directive outside of rootDirs', () => { env.write( '/app/module.ts', ` import {NgModule} from '@angular/core'; import {ExternalDir} from '../lib/dir'; import {MyComponent} from './comp'; @NgModule({ declarations: [ExternalDir, MyComponent], }) export class MyModule {} `, ); env.write( '/app/comp.ts', ` import {Component} from '@angular/core'; @Component({ template: '<div external></div>', }) export class MyComponent {} `, ); env.write( '/lib/dir.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[external]'}) export class ExternalDir {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '\n')) .toEqual(`Unable to import class ExternalDir. The file ${absoluteFrom('/lib/dir.ts')} is outside of the configured 'rootDir'.`); expect(diags[0].file!.fileName).toEqual(absoluteFrom('/app/module.ts')); expect(getDiagnosticSourceCode(diags[0])).toEqual('ExternalDir'); }); it('should report an error when a library entry-point does not export the symbol', () => { env.write( '/app/module.ts', ` import {NgModule} from '@angular/core'; import {ExternalModule} from 'lib'; import {MyComponent} from './comp'; @NgModule({ imports: [ExternalModule], declarations: [MyComponent], }) export class MyModule {} `, ); env.write( '/app/comp.ts', ` import {Component} from '@angular/core'; @Component({ template: '<div external></div>', standalone: false, }) export class MyComponent {} `, ); env.write( '/node_modules/lib/index.d.ts', ` import {ɵɵNgModuleDeclaration} from '@angular/core'; import {ExternalDir} from './dir'; export class ExternalModule { static ɵmod: ɵɵNgModuleDeclaration<ExternalModule, [typeof ExternalDir], never, [typeof ExternalDir]>; } `, ); env.write( '/node_modules/lib/dir.d.ts', ` import {ɵɵDirectiveDeclaration} from '@angular/core'; export class ExternalDir { static ɵdir: ɵɵDirectiveDeclaration<ExternalDir, '[external]', never, never, never, never>; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '\n')) .toEqual(`Unable to import directive ExternalDir. The symbol is not exported from ${absoluteFrom('/node_modules/lib/index.d.ts')} (module 'lib').`); expect(diags[0].file!.fileName).toEqual(absoluteFrom('/app/comp.ts')); expect(getDiagnosticSourceCode(diags[0])).toEqual('MyComponent'); }); }); }); function getDiagnosticSourceCode(diag: ts.Diagnostic): string { return diag.file!.text.substring(diag.start!, diag.start! + diag.length!); }
{ "end_byte": 4278, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/imports_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ls_typecheck_helpers_spec.ts_0_7841
/** * @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 {PotentialImportMode} from '@angular/compiler-cli/src/ngtsc/typecheck/api'; import ts from 'typescript'; import {DiagnosticCategoryLabel} from '../../src/ngtsc/core/api'; import {ErrorCode, ngErrorCode} from '../../src/ngtsc/diagnostics'; import {absoluteFrom as _, getSourceFileOrError} from '../../src/ngtsc/file_system'; import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import { expectCompleteReuse, getSourceCodeForDiagnostic, loadStandardTestFiles, } from '../../src/ngtsc/testing'; import {factory as invalidBananaInBoxFactory} from '../../src/ngtsc/typecheck/extended/checks/invalid_banana_in_box'; import {NgtscTestEnvironment} from './env'; import {getClass} from './util'; const testFiles = loadStandardTestFiles({fakeCommon: true}); runInEachFileSystem(() => { describe('full type checking', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.tsconfig({strictTemplates: true, _enableTemplateTypeChecker: true}); }); describe('supports `getPrimaryAngularDecorator()` ', () => { it('for components', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'test-cmp', template: '<div></div>', }) export class TestCmp {} `, ); const {program, checker} = env.driveTemplateTypeChecker(); const sf = program.getSourceFile(_('/test.ts')); expect(sf).not.toBeNull(); const decorator = checker.getPrimaryAngularDecorator(getClass(sf!, 'TestCmp')); expect(decorator?.getText()).toContain(`selector: 'test-cmp'`); }); it('for pipes', () => { env.write( 'test.ts', ` import {Pipe, PipeTransform} from '@angular/core'; @Pipe({name: 'expPipe'}) export class ExpPipe implements PipeTransform { transform(value: number, exponent = 1): number { return Math.pow(value, exponent); } } `, ); const {program, checker} = env.driveTemplateTypeChecker(); const sf = program.getSourceFile(_('/test.ts')); expect(sf).not.toBeNull(); const decorator = checker.getPrimaryAngularDecorator(getClass(sf!, 'ExpPipe')); expect(decorator?.getText()).toContain(`name: 'expPipe'`); }); it('for NgModules', () => { env.write( 'test.ts', ` import {NgModule} from '@angular/core'; @NgModule({ declarations: [], imports: [], providers: [], bootstrap: [] }) export class AppModule {} `, ); const {program, checker} = env.driveTemplateTypeChecker(); const sf = program.getSourceFile(_('/test.ts')); expect(sf).not.toBeNull(); const decorator = checker.getPrimaryAngularDecorator(getClass(sf!, 'AppModule')); expect(decorator?.getText()).toContain(`declarations: []`); }); }); describe('supports `getOwningNgModule()` ', () => { it('for components', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @NgModule({ declarations: [AppCmp], imports: [], providers: [], bootstrap: [AppCmp] }) export class AppModule {} @Component({ selector: 'app-cmp', template: '<div></div>', standalone: false, }) export class AppCmp {} `, ); const {program, checker} = env.driveTemplateTypeChecker(); const sf = program.getSourceFile(_('/test.ts')); expect(sf).not.toBeNull(); const ngModuleKnownClass = getClass(sf!, 'AppModule'); expect(ngModuleKnownClass).not.toBeNull(); const ngModuleRetrievedClass = checker.getOwningNgModule(getClass(sf!, 'AppCmp')); expect(ngModuleRetrievedClass).toEqual(ngModuleKnownClass); }); it('for standalone components (which should be null)', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @NgModule({ declarations: [AppCmp], imports: [], providers: [], bootstrap: [AppCmp] }) export class AppModule {} @Component({ selector: 'app-cmp', template: '<div></div>', standalone: true, }) export class AppCmp {} `, ); const {program, checker} = env.driveTemplateTypeChecker(); const sf = program.getSourceFile(_('/test.ts')); expect(sf).not.toBeNull(); const ngModuleKnownClass = getClass(sf!, 'AppModule'); expect(ngModuleKnownClass).not.toBeNull(); const ngModuleRetrievedClass = checker.getOwningNgModule(getClass(sf!, 'AppCmp')); expect(ngModuleRetrievedClass).toBe(null); }); it('for pipes', () => { env.write( 'test.ts', ` import {Component, NgModule, Pipe, PipeTransform} from '@angular/core'; @NgModule({ declarations: [ExpPipe], imports: [], providers: [], }) export class PipeModule {} @Pipe({name: 'expPipe'}) export class ExpPipe implements PipeTransform { transform(value: number, exponent = 1): number { return Math.pow(value, exponent); } } `, ); const {program, checker} = env.driveTemplateTypeChecker(); const sf = program.getSourceFile(_('/test.ts')); expect(sf).not.toBeNull(); const ngModuleKnownClass = getClass(sf!, 'PipeModule'); expect(ngModuleKnownClass).not.toBeNull(); const ngModuleRetrievedClass = checker.getOwningNgModule(getClass(sf!, 'ExpPipe')); expect(ngModuleRetrievedClass).toEqual(ngModuleKnownClass); }); }); describe('can retrieve candidate directives` ', () => { it('which are out of scope', () => { env.write( 'one.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'one-cmp', template: '<div></div>', }) export class OneCmp {} `, ); env.write( 'two.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'two-cmp', template: '<div></div>', }) export class TwoCmp {} `, ); const {program, checker} = env.driveTemplateTypeChecker(); const sf = program.getSourceFile(_('/one.ts')); expect(sf).not.toBeNull(); const directives = checker.getPotentialTemplateDirectives(getClass(sf!, 'OneCmp')); expect(directives.map((d) => d.selector)).toContain('two-cmp'); }); }); describe('can retrieve candidate pipes` ', () => { it('which are out of scope', () => { env.write( 'one.ts', ` import {Pipe} from '@angular/core'; @Pipe({ name: 'foo-pipe', standalone: true, }) export class OnePipe { } `, ); env.write( 'two.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'two-cmp', template: '<div></div>', }) export class TwoCmp {} `, ); const {program, checker} = env.driveTemplateTypeChecker(); const sf = program.getSourceFile(_('/one.ts')); expect(sf).not.toBeNull(); const pipes = checker.getPotentialPipes(getClass(sf!, 'OnePipe')); expect(pipes.map((p) => p.name)).toContain('foo-pipe'); }); });
{ "end_byte": 7841, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ls_typecheck_helpers_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ls_typecheck_helpers_spec.ts_7847_12040
describe('can generate imports` ', () => { it('for out of scope standalone components', () => { env.write( 'one.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'one-cmp', template: '<div></div>', }) export class OneCmp {} `, ); env.write( 'two.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'two-cmp', template: '<div></div>', }) export class TwoCmp {} `, ); const {program, checker} = env.driveTemplateTypeChecker(); const sfOne = program.getSourceFile(_('/one.ts')); expect(sfOne).not.toBeNull(); const OneCmpClass = getClass(sfOne!, 'OneCmp'); const TwoCmpDir = checker .getPotentialTemplateDirectives(OneCmpClass) .filter((d) => d.selector === 'two-cmp')[0]; const imports = checker.getPotentialImportsFor( TwoCmpDir.ref, OneCmpClass, PotentialImportMode.Normal, ); expect(imports.length).toBe(1); expect(imports[0].moduleSpecifier).toBe('./two'); expect(imports[0].symbolName).toBe('TwoCmp'); expect(imports[0].isForwardReference).toBe(false); }); it('for out of scope ngModules', () => { env.write( 'one.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'one-cmp', template: '<div></div>', }) export class OneCmp {} `, ); env.write( 'two.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'two-cmp', template: '<div></div>', standalone: false, }) export class TwoCmp {} `, ); env.write( 'twomod.ts', ` import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { TwoCmp } from './two'; @NgModule({ declarations: [ TwoCmp ], exports: [ TwoCmp ], imports: [ CommonModule ] }) export class TwoModule { } `, ); const {program, checker} = env.driveTemplateTypeChecker(); const sfOne = program.getSourceFile(_('/one.ts')); expect(sfOne).not.toBeNull(); const OneCmpClass = getClass(sfOne!, 'OneCmp'); const TwoNgMod = checker .getPotentialTemplateDirectives(OneCmpClass) .filter((d) => d.selector === 'two-cmp')[0]; const imports = checker.getPotentialImportsFor( TwoNgMod.ref, OneCmpClass, PotentialImportMode.Normal, ); expect(imports.length).toBe(1); expect(imports[0].moduleSpecifier).toBe('./twomod'); expect(imports[0].symbolName).toBe('TwoModule'); expect(imports[0].isForwardReference).toBe(false); }); it('for forward references in the same file', () => { env.write( 'decls.ts', ` import {Component} from '@angular/core'; @Component({ standalone: true, selector: 'one-cmp', template: '<div></div>', }) export class OneCmp {} @Component({ standalone: true, selector: 'two-cmp', template: '<div></div>', }) export class TwoCmp {} `, ); const {program, checker} = env.driveTemplateTypeChecker(); const sfOne = program.getSourceFile(_('/decls.ts')); expect(sfOne).not.toBeNull(); const OneCmpClass = getClass(sfOne!, 'OneCmp'); const TwoCmpDir = checker .getPotentialTemplateDirectives(OneCmpClass) .filter((d) => d.selector === 'two-cmp')[0]; const imports = checker.getPotentialImportsFor( TwoCmpDir.ref, OneCmpClass, PotentialImportMode.Normal, ); expect(imports.length).toBe(1); expect(imports[0].moduleSpecifier).toBeUndefined(); expect(imports[0].symbolName).toBe('TwoCmp'); expect(imports[0].isForwardReference).toBe(true); }); }); }); });
{ "end_byte": 12040, "start_byte": 7847, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ls_typecheck_helpers_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/host_directives_spec.ts_0_8157
/** * @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 {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('ngtsc host directives compilation', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.tsconfig({strictTemplates: true}); }); function extractMessage(diag: ts.Diagnostic) { return typeof diag.messageText === 'string' ? diag.messageText : diag.messageText.messageText; } it('should generate a basic hostDirectives definition', () => { env.write( 'test.ts', ` import {Directive, Component} from '@angular/core'; @Directive({ selector: '[dir-a]', standalone: true }) export class DirectiveA {} @Directive({ selector: '[dir-b]', standalone: true }) export class DirectiveB {} @Component({ selector: 'my-comp', template: '', hostDirectives: [DirectiveA, DirectiveB], standalone: false, }) export class MyComp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain('ɵɵdefineDirective({ type: DirectiveA'); expect(jsContents).toContain('ɵɵdefineDirective({ type: DirectiveB'); expect(jsContents).toContain( 'features: [i0.ɵɵHostDirectivesFeature([DirectiveA, DirectiveB])]', ); expect(dtsContents).toContain( 'ɵɵComponentDeclaration<MyComp, "my-comp", never, {}, {}, never, never, false, ' + '[{ directive: typeof DirectiveA; inputs: {}; outputs: {}; }, ' + '{ directive: typeof DirectiveB; inputs: {}; outputs: {}; }]>;', ); }); it('should generate a hostDirectives definition that has inputs and outputs', () => { env.write( 'test.ts', ` import {Directive, Component, Input, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[dir-a]', standalone: true }) export class HostDir { @Input() value: number; @Input() color: string; @Output() opened = new EventEmitter(); @Output() closed = new EventEmitter(); } @Component({ selector: 'my-comp', template: '', hostDirectives: [{ directive: HostDir, inputs: ['value', 'color: colorAlias'], outputs: ['opened', 'closed: closedAlias'], }], standalone: false, }) export class MyComp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain('ɵɵdefineDirective({ type: HostDir'); expect(jsContents).toContain( 'features: [i0.ɵɵHostDirectivesFeature([{ directive: HostDir, ' + 'inputs: ["value", "value", "color", "colorAlias"], ' + 'outputs: ["opened", "opened", "closed", "closedAlias"] }])]', ); expect(dtsContents).toContain( 'ɵɵComponentDeclaration<MyComp, "my-comp", never, {}, ' + '{}, never, never, false, [{ directive: typeof HostDir; ' + 'inputs: { "value": "value"; "color": "colorAlias"; }; ' + 'outputs: { "opened": "opened"; "closed": "closedAlias"; }; }]>;', ); }); it('should generate a hostDirectives definition that has aliased inputs and outputs', () => { env.write( 'test.ts', ` import {Directive, Component, Input, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[dir-a]', standalone: true }) export class HostDir { @Input('valueAlias') value: number; @Input('colorAlias') color: string; @Output('openedAlias') opened = new EventEmitter(); @Output('closedAlias') closed = new EventEmitter(); } @Component({ selector: 'my-comp', template: '', hostDirectives: [{ directive: HostDir, inputs: ['valueAlias', 'colorAlias: customColorAlias'], outputs: ['openedAlias', 'closedAlias: customClosedAlias'], }], standalone: false, }) export class MyComp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain('ɵɵdefineDirective({ type: HostDir'); expect(jsContents).toContain( 'features: [i0.ɵɵHostDirectivesFeature([{ directive: HostDir, ' + 'inputs: ["valueAlias", "valueAlias", "colorAlias", "customColorAlias"], ' + 'outputs: ["openedAlias", "openedAlias", "closedAlias", "customClosedAlias"] }])]', ); expect(dtsContents).toContain( 'ɵɵComponentDeclaration<MyComp, "my-comp", never, {}, ' + '{}, never, never, false, [{ directive: typeof HostDir; ' + 'inputs: { "valueAlias": "valueAlias"; "colorAlias": "customColorAlias"; }; ' + 'outputs: { "openedAlias": "openedAlias"; "closedAlias": "customClosedAlias"; }; }]>;', ); }); it('should generate hostDirectives definitions for a chain of host directives', () => { env.write( 'test.ts', ` import {Directive, Component} from '@angular/core'; @Directive({standalone: true}) export class DirectiveA { } @Directive({ standalone: true, hostDirectives: [DirectiveA], }) export class DirectiveB { } @Directive({ standalone: true, hostDirectives: [DirectiveB], }) export class DirectiveC { } @Component({ selector: 'my-comp', template: '', hostDirectives: [DirectiveC], standalone: false, }) export class MyComp { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain('ɵɵdefineDirective({ type: DirectiveA });'); expect(jsContents).toContain( 'ɵɵdefineDirective({ type: DirectiveB, ' + 'features: [i0.ɵɵHostDirectivesFeature([DirectiveA])] });', ); expect(jsContents).toContain( 'ɵɵdefineDirective({ type: DirectiveC, ' + 'features: [i0.ɵɵHostDirectivesFeature([DirectiveB])] });', ); expect(jsContents).toContain( 'ɵɵdefineComponent({ type: MyComp, selectors: [["my-comp"]], standalone: false,' + ' features: [i0.ɵɵHostDirectivesFeature([DirectiveC])]', ); expect(dtsContents).toContain( 'ɵɵDirectiveDeclaration<DirectiveA, never, never, {}, ' + '{}, never, never, true, never>;', ); expect(dtsContents).toContain( 'ɵɵDirectiveDeclaration<DirectiveB, never, never, {}, ' + '{}, never, never, true, [{ directive: typeof DirectiveA; ' + 'inputs: {}; outputs: {}; }]>;', ); expect(dtsContents).toContain( 'ɵɵDirectiveDeclaration<DirectiveC, never, never, {}, ' + '{}, never, never, true, [{ directive: typeof DirectiveB; ' + 'inputs: {}; outputs: {}; }]>;', ); expect(dtsContents).toContain( 'ɵɵComponentDeclaration<MyComp, "my-comp", never, {}, ' + '{}, never, never, false, [{ directive: typeof DirectiveC; ' + 'inputs: {}; outputs: {}; }]>;', ); }); it('should generate a hostDirectives
{ "end_byte": 8157, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/host_directives_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/host_directives_spec.ts_8163_16742
ition with forward references', () => { env.write( 'test.ts', ` import {Component, Directive, forwardRef, Input} from '@angular/core'; @Component({ selector: 'my-component', template: '', hostDirectives: [forwardRef(() => DirectiveB)], standalone: false, }) export class MyComponent { } @Directive({ standalone: true, hostDirectives: [{directive: forwardRef(() => DirectiveA), inputs: ['value']}], }) export class DirectiveB { } @Directive({}) export class DirectiveA { @Input() value: any; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain( 'features: [i0.ɵɵHostDirectivesFeature(function () { return [DirectiveB]; })]', ); expect(jsContents).toContain( 'features: [i0.ɵɵHostDirectivesFeature(function () { return [{ directive: DirectiveA, inputs: ["value", "value"] }]; })]', ); expect(jsContents).toContain( 'ɵɵdefineDirective({ type: DirectiveA, ' + 'inputs: { value: "value" } });', ); expect(dtsContents).toContain( 'ɵɵComponentDeclaration<MyComponent, "my-component", ' + 'never, {}, {}, never, never, false, [{ directive: typeof DirectiveB; ' + 'inputs: {}; outputs: {}; }]>;', ); expect(dtsContents).toContain( 'ɵɵDirectiveDeclaration<DirectiveB, never, never, {}, ' + '{}, never, never, true, [{ directive: typeof DirectiveA; ' + 'inputs: { "value": "value"; }; outputs: {}; }]>;', ); expect(dtsContents).toContain( 'ɵɵDirectiveDeclaration<DirectiveA, never, never, ' + '{ "value": { "alias": "value"; "required": false; }; }, {}, never, never, true, never>;', ); }); it('should generate a definition if the host directives are imported from other files', () => { env.write( 'dir-a.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir-a]', standalone: true }) export class DirectiveA {} `, ); env.write( 'dir-b.ts', ` import {Directive, Input, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[dir-b]', standalone: true }) export class DirectiveB { @Input() input: any; @Output() output = new EventEmitter<any>(); } `, ); env.write( 'test.ts', ` import {Component, forwardRef} from '@angular/core'; import {DirectiveA} from './dir-a'; import {DirectiveB} from './dir-b'; @Component({ selector: 'my-comp', template: '', hostDirectives: [ forwardRef(() => DirectiveA), { directive: forwardRef(() => DirectiveB), inputs: ['input: inputAlias'], outputs: ['output: outputAlias'] } ], standalone: false, }) export class MyComp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain(`import { DirectiveA } from './dir-a'`); expect(jsContents).toContain(`import { DirectiveB } from './dir-b'`); expect(jsContents).toContain( 'features: [i0.ɵɵHostDirectivesFeature(function () { ' + 'return [i1.DirectiveA, { directive: i2.DirectiveB, inputs: ["input", "inputAlias"], ' + 'outputs: ["output", "outputAlias"] }]; })]', ); expect(dtsContents).toContain('import * as i1 from "./dir-a";'); expect(dtsContents).toContain('import * as i2 from "./dir-b";'); expect(dtsContents).toContain( 'ɵɵComponentDeclaration<MyComp, "my-comp", never, {}, ' + '{}, never, never, false, [{ directive: typeof i1.DirectiveA; ' + 'inputs: {}; outputs: {}; }, { directive: typeof i2.DirectiveB; ' + 'inputs: { "input": "inputAlias"; }; outputs: { "output": "outputAlias"; }; }]>;', ); }); it('should generate a hostDirectives definition referring to external directives', () => { env.write( 'node_modules/external/index.d.ts', ` import {ɵɵDirectiveDeclaration} from '@angular/core'; export declare class ExternalDir { static ɵdir: ɵɵDirectiveDeclaration<ExternalDir, '[test]', never, {input: "input"}, {output: "output"}, never, never, true, never>; } `, ); env.write( 'test.ts', ` import {Component, Directive, NgModule} from '@angular/core'; import {ExternalDir} from 'external'; @Component({ template: '', hostDirectives: [{directive: ExternalDir, inputs: ['input: inputAlias'], outputs: ['output: outputAlias']}], standalone: false, }) export class MyComp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain(`import * as i1 from "external";`); expect(jsContents).toContain( 'features: [i0.ɵɵHostDirectivesFeature([{ directive: i1.ExternalDir, ' + 'inputs: ["input", "inputAlias"], outputs: ["output", "outputAlias"] }])]', ); expect(dtsContents).toContain('import * as i1 from "external";'); expect(dtsContents).toContain( 'ɵɵComponentDeclaration<MyComp, "ng-component", never, {}, ' + '{}, never, never, false, [{ directive: typeof i1.ExternalDir; ' + 'inputs: { "input": "inputAlias"; }; outputs: { "output": "outputAlias"; }; }]>;', ); }); it('should reference host directives by their external name', () => { env.write( 'node_modules/external/index.d.ts', ` import {InternalDir} from './internal'; export {InternalDir as ExternalDir} from './internal'; `, ); env.write( 'node_modules/external/internal.d.ts', ` export declare class InternalDir { static ɵdir: ɵɵDirectiveDeclaration<ExternalDir, '[test]', never, never, {}, {}, never, true, never>; } `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {ExternalDir} from 'external'; @Component({ template: '', hostDirectives: [ExternalDir], standalone: false, }) export class MyComp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain(`import * as i1 from "external";`); expect(jsContents).toContain('features: [i0.ɵɵHostDirectivesFeature([i1.ExternalDir])]'); expect(dtsContents).toContain('import * as i1 from "external";'); expect(dtsContents).toContain( 'ɵɵComponentDeclaration<MyComp, "ng-component", never, {}, {}, ' + 'never, never, false, [{ directive: typeof i1.ExternalDir; inputs: {}; outputs: {}; }]>;', ); }); it('should produce a template diagnostic if a required input from a host directive is missing', () => { env.write( 'test.ts', ` import {Directive, Component, Input} from '@angular/core'; @Directive({standalone: true}) export class HostDir { @Input({alias: 'inputAlias', required: true}) input: any; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['inputAlias: customAlias']}], standalone: true }) export class Dir {} @Component({ template: '<div dir></div>', standalone: true, imports: [Dir] }) class App {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual([ `Required input 'customAlias' from directive HostDir must be specified.`, ]); }); it('should not produce a template diagnostic if a required input fro
{ "end_byte": 16742, "start_byte": 8163, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/host_directives_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/host_directives_spec.ts_16748_17743
st directive is bound', () => { env.write( 'test.ts', ` import {Directive, Component, Input} from '@angular/core'; @Directive({standalone: true}) export class HostDir { @Input({alias: 'inputAlias', required: true}) input: any; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['inputAlias: customAlias']}], standalone: true }) export class Dir {} @Component({ template: '<div dir [customAlias]="value"></div>', standalone: true, imports: [Dir] }) class App { value = 123; } `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual([]); }); describe('validations', () => { it('should produce a diagnosti
{ "end_byte": 17743, "start_byte": 16748, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/host_directives_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/host_directives_spec.ts_17749_27548
host directive is not standalone', () => { env.write( 'test.ts', ` import {Directive, Component, NgModule} from '@angular/core'; @Directive({ standalone: false }) export class HostDir {} @Directive({ hostDirectives: [HostDir], standalone: false, }) export class Dir {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual(['Host directive HostDir must be standalone']); }); it('should produce a diagnostic if a host directive is not a directive', () => { env.write( 'test.ts', ` import {Directive, Pipe, Component, NgModule} from '@angular/core'; @Pipe({name: 'hostDir'}) export class HostDir {} @Directive({ hostDirectives: [HostDir], }) export class Dir {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual([ 'HostDir must be a standalone directive to be used as a host directive', ]); }); it('should produce a diagnostic if a host directive is a component', () => { env.write( 'test.ts', ` import {Directive, Component, NgModule} from '@angular/core'; @Component({ template: '', standalone: true, }) export class HostComp {} @Directive({ hostDirectives: [HostComp], }) export class Dir {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual(['Host directive HostComp cannot be a component']); }); it('should produce a diagnostic if hostDirectives is not an array', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '', // @ts-ignore hostDirectives: {} }) export class MyComp {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toContain('hostDirectives must be an array'); }); it('should produce a diagnostic if a host directive is not a reference', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; const hostA = {} as any; @Component({ template: '', hostDirectives: [hostA] }) export class MyComp {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual(['Host directive must be a reference']); }); it('should produce a diagnostic if a host directive is not a reference to a class', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; function hostA() {} @Component({ template: '', // @ts-ignore hostDirectives: [hostA] }) export class MyComp {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual(['Host directive reference must be a class']); }); it('should only produce a diagnostic once in a chain of directives', () => { env.write( 'test.ts', ` import {Directive, Component, NgModule} from '@angular/core'; @Directive({ selector: '[dir-b]', standalone: false, }) export class HostDirB {} @Directive({ selector: '[dir-a]', standalone: true, hostDirectives: [HostDirB] }) export class HostDirA {} @Component({ selector: '[dir]', template: '', hostDirectives: [HostDirA], standalone: false, }) export class Host {} `, ); // What we're checking here is that the diagnostics aren't produced recursively. If that // were the case, the same diagnostic would show up more than once in the diagnostics since // `HostDirB` is in the chain of both `Host` and `HostDirA`. const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual(['Host directive HostDirB must be standalone']); }); it('should produce a diagnostic if a host directive output does not exist', () => { env.write( 'test.ts', ` import {Directive, Output, EventEmitter} from '@angular/core'; @Directive({standalone: true}) class HostDir { @Output() foo = new EventEmitter(); } @Directive({ selector: '[dir]', hostDirectives: [{ directive: HostDir, outputs: ['doesNotExist'], }], standalone: false, }) class Dir {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual([ 'Directive HostDir does not have an output with a public name of doesNotExist.', ]); }); it('should produce a diagnostic if a host directive output alias does not exist', () => { env.write( 'test.ts', ` import {Directive, Output, EventEmitter} from '@angular/core'; @Directive({standalone: true}) class HostDir { @Output('alias') foo = new EventEmitter(); } @Directive({ selector: '[dir]', hostDirectives: [{ directive: HostDir, outputs: ['foo'], }], standalone: false, }) class Dir {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual([ 'Directive HostDir does not have an output with a public name of foo.', ]); }); it('should produce a diagnostic if a host directive input does not exist', () => { env.write( 'test.ts', ` import {Directive, Input} from '@angular/core'; @Directive({standalone: true}) class HostDir { @Input() foo: any; } @Directive({ selector: '[dir]', hostDirectives: [{ directive: HostDir, inputs: ['doesNotExist'], }], standalone: false, }) class Dir {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual([ 'Directive HostDir does not have an input with a public name of doesNotExist.', ]); }); it('should produce a diagnostic if a host directive input alias does not exist', () => { env.write( 'test.ts', ` import {Directive, Input} from '@angular/core'; @Directive({standalone: true}) class HostDir { @Input('alias') foo: any; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['foo']}], standalone: false, }) class Dir {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual([ 'Directive HostDir does not have an input with a public name of foo.', ]); }); it('should produce a diagnostic if a host directive tries to alias to an existing input', () => { env.write( 'test.ts', ` import {Directive, Input} from '@angular/core'; @Directive({selector: '[host-dir]', standalone: true}) class HostDir { @Input('colorAlias') color?: string; @Input() buttonColor?: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['colorAlias: buttonColor']}], standalone: false, }) class Dir {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual([ 'Cannot alias input colorAlias of host directive HostDir to buttonColor, because it ' + 'already has a different input with the same public name.', ]); }); it('should produce a diagnostic if a host directive tries to alias to an existing input alias', () => { env.write( 'test.ts', ` import {Directive, Input} from '@angular/core'; @Directive({selector: '[host-dir]', standalone: true}) class HostDir { @Input('colorAlias') color?: string; @Input('buttonColorAlias') buttonColor?: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['colorAlias: buttonColorAlias']}] }) class Dir {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual([ 'Cannot alias input colorAlias of host directive HostDir to buttonColorAlias, ' + 'because it already has a different input with the same public name.', ]); }); it('should not produce a diagnostic if a host directive input alia
{ "end_byte": 27548, "start_byte": 17749, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/host_directives_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/host_directives_spec.ts_27556_34923
he same name', () => { env.write( 'test.ts', ` import {Directive, Input} from '@angular/core'; @Directive({selector: '[host-dir]', standalone: true}) class HostDir { @Input('color') color?: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['color: buttonColor']}] }) class Dir {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual([]); }); it('should produce a diagnostic if a host directive tries to alias to an existing output alias', () => { env.write( 'test.ts', ` import {Directive, Output, EventEmitter} from '@angular/core'; @Directive({selector: '[host-dir]', standalone: true}) class HostDir { @Output('clickedAlias') clicked = new EventEmitter(); @Output('tappedAlias') tapped = new EventEmitter(); } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, outputs: ['clickedAlias: tappedAlias']}] }) class Dir {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual([ 'Cannot alias output clickedAlias of host directive HostDir ' + 'to tappedAlias, because it already has a different output with the same public name.', ]); }); it('should not produce a diagnostic if a host directive output aliases to the same name', () => { env.write( 'test.ts', ` import {Directive, Output, EventEmitter} from '@angular/core'; @Directive({selector: '[host-dir]', standalone: true}) class HostDir { @Output('clicked') clicked = new EventEmitter(); } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, outputs: ['clicked: wasClicked']}] }) class Dir {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual([]); }); it('should produce a diagnostic if a required input is not exposed on the host', () => { env.write( 'test.ts', ` import {Directive, Component, Input} from '@angular/core'; @Directive({ selector: '[dir-a]', standalone: true }) export class HostDir { @Input({required: true}) input: any; } @Component({ selector: 'my-comp', template: '', hostDirectives: [HostDir] }) export class MyComp {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual([ `Required input 'input' from host directive HostDir must be exposed.`, ]); }); it('should use the public name when producing diagnostics about missing required inputs', () => { env.write( 'test.ts', ` import {Directive, Component, Input} from '@angular/core'; @Directive({ selector: '[dir-a]', standalone: true }) export class HostDir { @Input({required: true, alias: 'inputAlias'}) input: any; } @Component({ selector: 'my-comp', template: '', hostDirectives: [HostDir] }) export class MyComp {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual([ `Required input 'inputAlias' from host directive HostDir must be exposed.`, ]); }); it('should not produce required input diagnostic when exposed through alias', () => { env.write( 'test.ts', ` import {Directive, Component, Input} from '@angular/core'; @Directive({ selector: '[dir-a]', standalone: true }) export class HostDir { @Input({required: true, alias: 'inputAlias'}) input: any; } @Component({ selector: 'my-comp', template: '', hostDirectives: [{directive: HostDir, inputs: ['inputAlias']}] }) export class MyComp {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual([]); }); it('should not produce required input diagnostic when exposed through alias to another alias', () => { env.write( 'test.ts', ` import {Directive, Component, Input} from '@angular/core'; @Directive({ selector: '[dir-a]', standalone: true }) export class HostDir { @Input({required: true, alias: 'inputAlias'}) input: any; } @Component({ selector: 'my-comp', template: '', hostDirectives: [{directive: HostDir, inputs: ['inputAlias: customAlias']}] }) export class MyComp {} `, ); const messages = env.driveDiagnostics().map(extractMessage); expect(messages).toEqual([]); }); it('should not produce a diagnostic when exposing an aliased binding', () => { env.write( 'test.ts', ` import {Directive, EventEmitter} from '@angular/core'; @Directive({ outputs: ['opened: triggerOpened'], selector: '[trigger]', standalone: true, }) export class Trigger { opened = new EventEmitter(); } @Directive({ standalone: true, selector: '[host]', hostDirectives: [{directive: Trigger, outputs: ['triggerOpened']}] }) export class Host {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not produce a diagnostic when exposing an inherited aliased binding', () => { env.write( 'test.ts', ` import {Directive, EventEmitter} from '@angular/core'; @Directive({standalone: true}) export abstract class Base { opened = new EventEmitter(); } @Directive({ outputs: ['opened: triggerOpened'], selector: '[trigger]', standalone: true, }) export class Trigger extends Base {} @Directive({ standalone: true, selector: '[host]', hostDirectives: [{directive: Trigger, outputs: ['triggerOpened: hostOpened']}] }) export class Host {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); }); }); });
{ "end_byte": 34923, "start_byte": 27556, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/host_directives_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/xi18n_spec.ts_0_3742
/** * @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 {platform} from 'os'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles({fakeCommon: true}); runInEachFileSystem((os) => { let env!: NgtscTestEnvironment; if (os === 'Windows' || platform() === 'win32') { // xi18n tests are skipped on Windows as the paths in the expected message files are platform- // sensitive. These tests will be deleted when xi18n is removed, so it's not a major priority // to make them work with Windows. We have a blank test here, because Jasmine logs a warning // when there's a `describe` with no tests. it('should pass', () => expect(1).toBe(1)); return; } describe('ngtsc xi18n', () => { beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.tsconfig(); writeTestCode(env); }); it('should extract xmb', () => { env.driveXi18n('xmb', 'messages.xmb'); expect(env.getContents('messages.xmb')).toEqual(EXPECTED_XMB); }); it('should extract xlf', () => { // Note that only in XLF mode do we pass a locale into the extraction. env.driveXi18n('xlf', 'messages.xlf', 'fr'); expect(env.getContents('messages.xlf')).toEqual(EXPECTED_XLIFF); }); it('should extract xlf', () => { env.driveXi18n('xlf2', 'messages.xliff2.xlf'); expect(env.getContents('messages.xliff2.xlf')).toEqual(EXPECTED_XLIFF2); }); it('should not emit js', () => { env.driveXi18n('xlf2', 'messages.xliff2.xlf'); env.assertDoesNotExist('src/module.js'); }); }); }); const EXPECTED_XMB = `<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE messagebundle [ <!ELEMENT messagebundle (msg)*> <!ATTLIST messagebundle class CDATA #IMPLIED> <!ELEMENT msg (#PCDATA|ph|source)*> <!ATTLIST msg id CDATA #IMPLIED> <!ATTLIST msg seq CDATA #IMPLIED> <!ATTLIST msg name CDATA #IMPLIED> <!ATTLIST msg desc CDATA #IMPLIED> <!ATTLIST msg meaning CDATA #IMPLIED> <!ATTLIST msg obsolete (obsolete) #IMPLIED> <!ATTLIST msg xml:space (default|preserve) "default"> <!ATTLIST msg is_hidden CDATA #IMPLIED> <!ELEMENT source (#PCDATA)> <!ELEMENT ph (#PCDATA|ex)*> <!ATTLIST ph name CDATA #REQUIRED> <!ELEMENT ex (#PCDATA)> ]> <messagebundle handler="angular"> <msg id="8136548302122759730" desc="desc" meaning="meaning"><source>src/basic.html:1</source><source>src/comp2.ts:1</source><source>src/basic.html:1</source>translate me</msg> <msg id="9038505069473852515"><source>src/basic.html:3,4</source><source>src/comp2.ts:3,4</source><source>src/comp2.ts:2,3</source><source>src/basic.html:3,4</source> Welcome</msg> <msg id="5611534349548281834" desc="with ICU"><source>src/icu.html:1,3</source><source>src/icu.html:5</source>{VAR_PLURAL, plural, =1 {book} other {books} }</msg> <msg id="5811701742971715242" desc="with ICU and other things"><source>src/icu.html:4,6</source> foo <ph name="ICU"><ex>{ count, plural, =1 {...} other {...}}</ex>{ count, plural, =1 {...} other {...}}</ph> </msg> <msg id="7254052530614200029" desc="with placeholders"><source>src/placeholders.html:1,3</source>Name: <ph name="START_BOLD_TEXT"><ex>&lt;b&gt;</ex>&lt;b&gt;</ph><ph name="NAME"><ex>{{ name // i18n(ph=&quot;name&quot;) }}</ex>{{ name // i18n(ph=&quot;name&quot;) }}</ph><ph name="CLOSE_BOLD_TEXT"><ex>&lt;/b&gt;</ex>&lt;/b&gt;</ph></msg> </messagebundle> `;
{ "end_byte": 3742, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/xi18n_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/xi18n_spec.ts_3744_9871
const EXPECTED_XLIFF = `<?xml version="1.0" encoding="UTF-8" ?> <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> <file source-language="fr" datatype="plaintext" original="ng2.template"> <body> <trans-unit id="76e1eccb1b772fa9f294ef9c146ea6d0efa8a2d4" datatype="html"> <source>translate me</source> <context-group purpose="location"> <context context-type="sourcefile">src/basic.html</context> <context context-type="linenumber">1</context> </context-group> <context-group purpose="location"> <context context-type="sourcefile">src/comp2.ts</context> <context context-type="linenumber">1</context> </context-group> <context-group purpose="location"> <context context-type="sourcefile">src/basic.html</context> <context context-type="linenumber">1</context> </context-group> <note priority="1" from="description">desc</note> <note priority="1" from="meaning">meaning</note> </trans-unit> <trans-unit id="085a5ecc40cc87451d216725b2befd50866de18a" datatype="html"> <source> Welcome</source> <context-group purpose="location"> <context context-type="sourcefile">src/basic.html</context> <context context-type="linenumber">3</context> </context-group> <context-group purpose="location"> <context context-type="sourcefile">src/comp2.ts</context> <context context-type="linenumber">3</context> </context-group> <context-group purpose="location"> <context context-type="sourcefile">src/comp2.ts</context> <context context-type="linenumber">2</context> </context-group> <context-group purpose="location"> <context context-type="sourcefile">src/basic.html</context> <context context-type="linenumber">3</context> </context-group> </trans-unit> <trans-unit id="83937c05b1216e7f4c02a85454260e28fd72d1e3" datatype="html"> <source>{VAR_PLURAL, plural, =1 {book} other {books} }</source> <context-group purpose="location"> <context context-type="sourcefile">src/icu.html</context> <context context-type="linenumber">1</context> </context-group> <note priority="1" from="description">with ICU</note> </trans-unit> <trans-unit id="540c5f481129419ef21017f396b6c2d0869ca4d2" datatype="html"> <source> foo <x id="ICU" equiv-text="{ count, plural, =1 {...} other {...}}"/> </source> <context-group purpose="location"> <context context-type="sourcefile">src/icu.html</context> <context context-type="linenumber">4</context> </context-group> <note priority="1" from="description">with ICU and other things</note> </trans-unit> <trans-unit id="ca7678090fddd04441d63b1218177af65f23342d" datatype="html"> <source>{VAR_PLURAL, plural, =1 {book} other {books} }</source> <context-group purpose="location"> <context context-type="sourcefile">src/icu.html</context> <context context-type="linenumber">5</context> </context-group> </trans-unit> <trans-unit id="9311399c1ca7c75f771d77acb129e50581c6ec1f" datatype="html"> <source>Name: <x id="START_BOLD_TEXT" ctype="x-b" equiv-text="&lt;b&gt;"/><x id="NAME" equiv-text="{{ name // i18n(ph=&quot;name&quot;) }}"/><x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="&lt;/b&gt;"/></source> <context-group purpose="location"> <context context-type="sourcefile">src/placeholders.html</context> <context context-type="linenumber">1</context> </context-group> <note priority="1" from="description">with placeholders</note> </trans-unit> </body> </file> </xliff> `; const EXPECTED_XLIFF2 = `<?xml version="1.0" encoding="UTF-8" ?> <xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en"> <file original="ng.template" id="ngi18n"> <unit id="8136548302122759730"> <notes> <note category="description">desc</note> <note category="meaning">meaning</note> <note category="location">src/basic.html:1</note> <note category="location">src/comp2.ts:1</note> <note category="location">src/basic.html:1</note> </notes> <segment> <source>translate me</source> </segment> </unit> <unit id="9038505069473852515"> <notes> <note category="location">src/basic.html:3,4</note> <note category="location">src/comp2.ts:3,4</note> <note category="location">src/comp2.ts:2,3</note> <note category="location">src/basic.html:3,4</note> </notes> <segment> <source> Welcome</source> </segment> </unit> <unit id="5611534349548281834"> <notes> <note category="description">with ICU</note> <note category="location">src/icu.html:1,3</note> <note category="location">src/icu.html:5</note> </notes> <segment> <source>{VAR_PLURAL, plural, =1 {book} other {books} }</source> </segment> </unit> <unit id="5811701742971715242"> <notes> <note category="description">with ICU and other things</note> <note category="location">src/icu.html:4,6</note> </notes> <segment> <source> foo <ph id="0" equiv="ICU" disp="{ count, plural, =1 {...} other {...}}"/> </source> </segment> </unit> <unit id="7254052530614200029"> <notes> <note category="description">with placeholders</note> <note category="location">src/placeholders.html:1,3</note> </notes> <segment> <source>Name: <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="&lt;b&gt;" dispEnd="&lt;/b&gt;"><ph id="1" equiv="NAME" disp="{{ name // i18n(ph=&quot;name&quot;) }}"/></pc></source> </segment> </unit> </file> </xliff> `; /** * Note: the indentation here is load-bearing. */
{ "end_byte": 9871, "start_byte": 3744, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/xi18n_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/xi18n_spec.ts_9872_12626
function writeTestCode(env: NgtscTestEnvironment): void { const welcomeMessage = ` <!--i18n--> Welcome<!--/i18n--> `; env.write( 'src/basic.html', `<div title="translate me" i18n-title="meaning|desc"></div> <p id="welcomeMessage">${welcomeMessage}</p>`, ); env.write( 'src/comp1.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'basic', templateUrl: './basic.html', standalone: false, }) export class BasicCmp1 {}`, ); env.write( 'src/comp2.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'basic2', template: \`<div title="translate me" i18n-title="meaning|desc"></div> <p id="welcomeMessage">${welcomeMessage}</p>\`, standalone: false, }) export class BasicCmp2 {} @Component({ selector: 'basic4', template: \`<p id="welcomeMessage">${welcomeMessage}</p>\`, standalone: false, }) export class BasicCmp4 {}`, ); env.write( 'src/comp3.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'basic3', templateUrl: './basic.html', standalone: false, }) export class BasicCmp3 {}`, ); env.write( 'src/placeholders.html', `<div i18n="with placeholders">Name: <b>{{ name // i18n(ph="name") }}</b></div>`, ); env.write( 'src/placeholder_cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'placeholders', templateUrl: './placeholders.html', standalone: false, }) export class PlaceholderCmp { name = 'whatever'; }`, ); env.write( 'src/icu.html', `<div i18n="with ICU">{ count, plural, =1 {book} other {books} }</div> <div i18n="with ICU and other things"> foo { count, plural, =1 {book} other {books} } </div>`, ); env.write( 'src/icu_cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'icu', templateUrl: './icu.html', standalone: false, }) export class IcuCmp { count = 3; }`, ); env.write( 'src/module.ts', ` import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {BasicCmp1} from './comp1'; import {BasicCmp2, BasicCmp4} from './comp2'; import {BasicCmp3} from './comp3'; import {PlaceholderCmp} from './placeholder_cmp'; import {IcuCmp} from './icu_cmp'; @NgModule({ declarations: [ BasicCmp1, BasicCmp2, BasicCmp3, BasicCmp4, PlaceholderCmp, IcuCmp, ], imports: [CommonModule], }) export class I18nModule {} `, ); }
{ "end_byte": 12626, "start_byte": 9872, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/xi18n_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_0_1862
/** * @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 {NgtscProgram} from '@angular/compiler-cli/src/ngtsc/program'; import {CompilerOptions} from '@angular/compiler-cli/src/transformers/api'; import {createCompilerHost} from '@angular/compiler-cli/src/transformers/compiler_host'; import {platform} from 'os'; import ts from 'typescript'; import {ErrorCode, ngErrorCode} from '../../src/ngtsc/diagnostics'; import {absoluteFrom, NgtscCompilerHost} from '../../src/ngtsc/file_system'; import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../src/ngtsc/testing'; import { restoreTypeScriptVersionForTesting, setTypeScriptVersionForTesting, } from '../../src/typescript_support'; import {NgtscTestEnvironment} from './env'; const trim = (input: string): string => input.replace(/\s+/g, ' ').trim(); const varRegExp = (name: string): RegExp => new RegExp(`const \\w+ = \\[\"${name}\"\\];`); const viewQueryRegExp = (predicate: string, flags: number, ref?: string): RegExp => { const maybeRef = ref ? `, ${ref}` : ``; return new RegExp(`i0\\.ɵɵviewQuery\\(${predicate}, ${flags}${maybeRef}\\)`); }; const contentQueryRegExp = (predicate: string, flags: number, ref?: string): RegExp => { const maybeRef = ref ? `, ${ref}` : ``; return new RegExp(`i0\\.ɵɵcontentQuery\\(dirIndex, ${predicate}, ${flags}${maybeRef}\\)`); }; const setClassMetadataRegExp = (expectedType: string): RegExp => new RegExp(`setClassMetadata(.*?${expectedType}.*?)`); const testFiles = loadStandardTestFiles(); function getDiagnosticSourceCode(diag: ts.Diagnostic): string { return diag.file!.text.slice(diag.start!, diag.start! + diag.length!); } ru
{ "end_byte": 1862, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_1864_9561
nEachFileSystem((os: string) => { describe('ngtsc behavioral tests', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.tsconfig(); }); it('should accept relative file paths as command line argument', () => { env.addCommandLineArgs('--rootDir', './rootDir'); env.write('rootDir/test.html', '<p>Hello World</p>'); env.write( 'rootDir/test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', templateUrl: 'test.html', standalone: false, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('Hello World'); }); it('should compile Injectables without errors', () => { env.write( 'test.ts', ` import {Injectable} from '@angular/core'; @Injectable() export class Dep {} @Injectable() export class Service { constructor(dep: Dep) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('Dep.ɵprov ='); expect(jsContents).toContain('Service.ɵprov ='); expect(jsContents).not.toContain('__decorate'); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain('static ɵprov: i0.ɵɵInjectableDeclaration<Dep>;'); expect(dtsContents).toContain('static ɵprov: i0.ɵɵInjectableDeclaration<Service>;'); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<Dep, never>;'); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<Service, never>;'); }); it('should compile Injectables with a generic service', () => { env.write( 'test.ts', ` import {Injectable} from '@angular/core'; @Injectable() export class Store<T> {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('Store.ɵprov ='); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<Store<any>, never>;'); expect(dtsContents).toContain('static ɵprov: i0.ɵɵInjectableDeclaration<Store<any>>;'); }); it('should compile Injectables with providedIn without errors', () => { env.write( 'test.ts', ` import {Injectable} from '@angular/core'; @Injectable() export class Dep {} @Injectable({ providedIn: 'root' }) export class Service { constructor(dep: Dep) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('Dep.ɵprov ='); expect(jsContents).toContain('Service.ɵprov ='); expect(jsContents).toContain( 'Service.ɵfac = function Service_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || Service)(i0.ɵɵinject(Dep)); };', ); expect(jsContents).toContain("providedIn: 'root' })"); expect(jsContents).not.toContain('__decorate'); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain('static ɵprov: i0.ɵɵInjectableDeclaration<Dep>;'); expect(dtsContents).toContain('static ɵprov: i0.ɵɵInjectableDeclaration<Service>;'); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<Dep, never>;'); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<Service, never>;'); }); it('should compile Injectables with providedIn and factory without errors', () => { env.write( 'test.ts', ` import {Injectable} from '@angular/core'; @Injectable({ providedIn: 'root', useFactory: () => new Service() }) export class Service { constructor() {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('Service.ɵprov ='); expect(jsContents).toContain('factory: () => (() => new Service())()'); expect(jsContents).toContain( 'Service_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || Service)(); }', ); expect(jsContents).toContain(", providedIn: 'root' });"); expect(jsContents).not.toContain('__decorate'); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain('static ɵprov: i0.ɵɵInjectableDeclaration<Service>;'); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<Service, never>;'); }); it('should compile Injectables with providedIn and factory with deps without errors', () => { env.write( 'test.ts', ` import {Injectable} from '@angular/core'; @Injectable() export class Dep {} @Injectable({ providedIn: 'root', useFactory: (dep: Dep) => new Service(dep), deps: [Dep] }) export class Service { constructor(dep: Dep) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('Service.ɵprov ='); expect(jsContents).toContain( 'factory: function Service_Factory(__ngFactoryType__) { let __ngConditionalFactory__ = null; if (__ngFactoryType__) {', ); expect(jsContents).toContain('return new (__ngFactoryType__ || Service)(i0.ɵɵinject(Dep));'); expect(jsContents).toContain( '__ngConditionalFactory__ = ((dep) => new Service(dep))(i0.ɵɵinject(Dep));', ); expect(jsContents).toContain("return __ngConditionalFactory__; }, providedIn: 'root' });"); expect(jsContents).not.toContain('__decorate'); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain('static ɵprov: i0.ɵɵInjectableDeclaration<Service>;'); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<Service, never>;'); }); it('should compile Injectables with providedIn and factory with deps with array literal tokens', () => { env.write( 'test.ts', ` import {Injectable, Optional, Self} from '@angular/core'; @Injectable() export class Dep {} @Injectable({ providedIn: 'root', useFactory: (dep: Dep) => new Service(dep), deps: [[new Optional(), new Self(), Dep]], }) export class Service { constructor(dep: Dep) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('Service.ɵprov ='); expect(jsContents).toContain( 'factory: function Service_Factory(__ngFactoryType__) { let __ngConditionalFactory__ = null; if (__ngFactoryType__) {', ); expect(jsContents).toContain('return new (__ngFactoryType__ || Service)(i0.ɵɵinject(Dep));'); expect(jsContents).toContain( '__ngConditionalFactory__ = ((dep) => new Service(dep))(i0.ɵɵinject(Dep, 10));', ); expect(jsContents).toContain(`return __ngConditionalFactory__; }, providedIn: 'root' });`); expect(jsContents).not.toContain('__decorate'); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain('static ɵprov: i0.ɵɵInjectableDeclaration<Service>;'); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<Service, never>;'); }); it('should compile Injectables with providedIn using forwardRef w
{ "end_byte": 9561, "start_byte": 1864, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_9567_17822
errors', () => { env.write( 'test.ts', ` import {Injectable, NgModule, forwardRef} from '@angular/core'; @Injectable() export class Dep {} @Injectable({ providedIn: forwardRef(() => Mod) }) export class Service { constructor(dep: Dep) {} } @NgModule() export class Mod {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('Dep.ɵprov ='); expect(jsContents).toContain('Service.ɵprov ='); expect(jsContents).toContain('Mod.ɵmod ='); expect(jsContents).toContain( 'Service.ɵfac = function Service_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || Service)(i0.ɵɵinject(Dep)); };', ); expect(jsContents).toContain('providedIn: i0.forwardRef(() => Mod) })'); expect(jsContents).not.toContain('__decorate'); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain('static ɵprov: i0.ɵɵInjectableDeclaration<Dep>;'); expect(dtsContents).toContain('static ɵprov: i0.ɵɵInjectableDeclaration<Service>;'); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<Dep, never>;'); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<Service, never>;'); expect(dtsContents).toContain('i0.ɵɵFactoryDeclaration<Mod, never>;'); }); it('should compile @Injectable with an @Optional dependency', () => { env.write( 'test.ts', ` import {Injectable, Optional as Opt} from '@angular/core'; @Injectable() class Dep {} @Injectable() class Service { constructor(@Opt() dep: Dep) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('inject(Dep, 8)'); }); it('should compile @Injectable with constructor overloads', () => { env.write( 'test.ts', ` import {Injectable, Optional} from '@angular/core'; @Injectable() class Dep {} @Injectable() class OptionalDep {} @Injectable() class Service { constructor(dep: Dep); constructor(dep: Dep, @Optional() optionalDep?: OptionalDep) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `Service.ɵfac = function Service_Factory(__ngFactoryType__) { ` + `return new (__ngFactoryType__ || Service)(i0.ɵɵinject(Dep), i0.ɵɵinject(OptionalDep, 8)); };`, ); }); it('should compile Directives without errors', () => { env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class TestDir {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('TestDir.ɵdir = /*@__PURE__*/ i0.ɵɵdefineDirective'); expect(jsContents).toContain('TestDir.ɵfac = function'); expect(jsContents).not.toContain('__decorate'); const dtsContents = env.getContents('test.d.ts'); const expectedDirectiveDeclaration = 'static ɵdir: i0.ɵɵDirectiveDeclaration<TestDir, "[dir]", never, {}, {}, never, never, false, never>'; expect(dtsContents).toContain(expectedDirectiveDeclaration); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<TestDir, never>'); }); it('should compile abstract Directives without errors', () => { env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive() export class TestDir {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('TestDir.ɵdir = /*@__PURE__*/ i0.ɵɵdefineDirective'); expect(jsContents).toContain('TestDir.ɵfac = function'); expect(jsContents).not.toContain('__decorate'); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain( 'static ɵdir: i0.ɵɵDirectiveDeclaration<TestDir, never, never, {}, {}, never, never, true, never>', ); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<TestDir, never>'); }); it('should compile Components (inline template) without errors', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: 'this is a test', standalone: false, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('TestCmp.ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent'); expect(jsContents).toContain('TestCmp.ɵfac = function'); expect(jsContents).not.toContain('__decorate'); const dtsContents = env.getContents('test.d.ts'); const expectedComponentDeclaration = 'static ɵcmp: i0.ɵɵComponentDeclaration<TestCmp, "test-cmp", never, {}, {}, never, never, false, never>'; expect(dtsContents).toContain(expectedComponentDeclaration); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<TestCmp, never>'); }); it('should compile Components (dynamic inline template) without errors', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: 'this is ' + 'a test', standalone: false, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('TestCmp.ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent'); expect(jsContents).toContain('TestCmp.ɵfac = function'); expect(jsContents).not.toContain('__decorate'); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain( 'static ɵcmp: i0.ɵɵComponentDeclaration' + '<TestCmp, "test-cmp", never, {}, {}, never, never, false, never>', ); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<TestCmp, never>'); }); it('should compile Components (function call inline template) without errors', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; function getTemplate() { return 'this is a test'; } @Component({ selector: 'test-cmp', template: getTemplate(), standalone: false, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('TestCmp.ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent'); expect(jsContents).toContain('TestCmp.ɵfac = function'); expect(jsContents).not.toContain('__decorate'); const dtsContents = env.getContents('test.d.ts'); const expectedComponentDeclaration = 'static ɵcmp: i0.ɵɵComponentDeclaration<TestCmp, "test-cmp", never, {}, {}, never, never, false, never>'; expect(dtsContents).toContain(expectedComponentDeclaration); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<TestCmp, never>'); }); it('should compile Components (external template) without errors', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', templateUrl: './dir/test.html', standalone: false, }) export class TestCmp {} `, ); env.write('dir/test.html', '<p>Hello World</p>'); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('Hello World'); }); it('should not report that broken components in modules are not components', () => { env.write( 'test.ts', ` i
{ "end_byte": 17822, "start_byte": 9567, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_17828_23121
{Component, NgModule} from '@angular/core'; @Component({ selector: 'broken-cmp', template: '{{ broken = "true" }}', // assignment not legal in this context standalone: false, }) export class BrokenCmp {} @NgModule({ declarations: [BrokenCmp], }) export class Module { broken = "false"; } `, ); const diags = env.driveDiagnostics(); if (diags.some((diag) => diag.code === ngErrorCode(ErrorCode.NGMODULE_INVALID_DECLARATION))) { fail('Should not produce a diagnostic that BrokenCmp is not a component'); } }); it('should only list public declarations in NgModule .d.ts when requested', () => { env.tsconfig({ onlyPublishPublicTypingsForNgModules: true, }); env.write( 'test.ts', ` import {Directive, NgModule} from '@angular/core'; @Directive({ selector: 'internal', standalone: false, }) export class InternalDir {} @Directive({ selector: 'external', standalone: false, }) export class ExternalDir {} @NgModule({ declarations: [InternalDir, ExternalDir], exports: [ExternalDir], }) export class Module {} `, ); env.driveMain(); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain( 'static ɵmod: i0.ɵɵNgModuleDeclaration<Module, ' + '[typeof ExternalDir], never, [typeof ExternalDir]>', ); }); it('should not list imports in NgModule .d.ts when requested', () => { env.tsconfig({ onlyPublishPublicTypingsForNgModules: true, }); env.write( 'test.ts', ` import {Directive, NgModule} from '@angular/core'; @Directive({ selector: 'internal', standalone: false, }) export class InternalDir {} @NgModule({ declarations: [InternalDir], exports: [InternalDir], }) export class DepModule {} @Directive({ selector: 'external', standalone: false, }) export class ExternalDir {} @NgModule({ imports: [DepModule], }) export class Module {} `, ); env.driveMain(); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain( 'static ɵmod: i0.ɵɵNgModuleDeclaration<Module, ' + 'never, never, never>', ); }); it('should error when supportJitMode is false and forbidOrphanComponents is true', () => { env.tsconfig({ supportJitMode: false, forbidOrphanComponents: true, }); env.write('test.ts', ''); const diagnostics = env.driveDiagnostics(); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: jasmine.stringMatching( /JIT mode support \("supportJitMode" option\) cannot be disabled when forbidOrphanComponents is set to true/, ), }), ]); }); it('should run JIT transform for components marked as `jit: true`', () => { env.write( 'test.ts', ` import {Component, input} from '@angular/core'; @Component({ template: '<non-existent />', jit: true, }) class MyTestComponent { name = input('John'); } @Component({ template: '', }) class NonJitComponent { nonJitInput = input(true); } `, ); env.driveMain(); expect(trim(env.getContents('test.js'))).toContain( trim(` MyTestComponent.propDecorators = { name: [{ type: i0.Input, args: [{ isSignal: true, alias: "name", required: false, transform: undefined },] }] }; `), ); expect(env.getContents('test.js')).not.toContain('NonJitComponent.propDecorators'); }); it('should run JIT transform for `NgModule` marked as `jit: true`', () => { env.write( 'test.ts', ` import {NgModule, Injector} from '@angular/core'; @NgModule({ jit: true }) class MyJitModule { constructor(dep: Injector) {} } @NgModule({}) class NonJitModule { constructor(dep: Injector) {} } `, ); env.driveMain(); expect(trim(env.getContents('test.js'))).toContain( trim(` MyJitModule.ctorParameters = () => [ { type: Injector } ];`), ); expect(env.getContents('test.js')).not.toContain('NonJitModule.ctorParameters'); }); // This test triggers the Tsickle compiler which asserts that the file-paths // are valid for the real OS. When on non-Windows systems it doesn't like paths // that start with `C:`. if (os !== 'Windows' || platform() === 'win32') { describe('when closure annotations are requested', () => { it('should add @pureOrBr
{ "end_byte": 23121, "start_byte": 17828, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_23126_30854
Code to getInheritedFactory calls', () => { env.tsconfig({ 'annotateForClosureCompiler': true, }); env.write( `test.ts`, ` import {Directive} from '@angular/core'; @Directive({ selector: '[base]', }) class Base {} @Directive({ selector: '[test]', }) class Dir extends Base { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('Dir.ɵfac = /** @pureOrBreakMyCode */ (() => {'); expect(jsContents).toContain( '(ɵDir_BaseFactory || (ɵDir_BaseFactory = i0.ɵɵgetInheritedFactory(Dir)))(__ngFactoryType__ || Dir);', ); }); it('should add @nocollapse to static fields', () => { env.tsconfig({ 'annotateForClosureCompiler': true, }); env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', templateUrl: './dir/test.html', }) export class TestCmp {} `, ); env.write('dir/test.html', '<p>Hello World</p>'); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('/** @nocollapse */ TestCmp.ɵcmp'); }); it('should still perform schema checks in embedded views', () => { env.tsconfig({ 'fullTemplateTypeCheck': false, 'annotateForClosureCompiler': true, }); env.write( 'test.ts', ` import {Component, Directive, NgModule} from '@angular/core'; @Component({ selector: 'test-cmp', template: \` <ng-template> <some-dir>Has a directive, should be okay</some-dir> <not-a-cmp>Should trigger a schema error</not-a-cmp> </ng-template> \`, standalone: false, }) export class TestCmp {} @Directive({ selector: 'some-dir', standalone: false, }) export class TestDir {} @NgModule({ declarations: [TestCmp, TestDir], }) export class TestModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.SCHEMA_INVALID_ELEMENT)); expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '\n')).toContain( 'not-a-cmp', ); }); /** * The following set of tests verify that after Tsickle run we do not have cases * which trigger automatic semicolon insertion, which breaks the code. In order * to avoid the problem, we wrap all function expressions in certain fields * ("providers" and "viewProviders") in parentheses. More info on Tsickle * processing related to this case can be found here: * https://github.com/angular/tsickle/blob/d7974262571c8a17d684e5ba07680e1b1993afdd/src/jsdoc_transformer.ts#L1021 */ describe('wrap functions in certain fields in parentheses', () => { const providers = ` [{ provide: 'token-a', useFactory: (service: Service) => { return () => service.id; } }, { provide: 'token-b', useFactory: function(service: Service) { return function() { return service.id; } } }] `; const service = ` export class Service { id: string = 'service-id'; } `; const verifyOutput = (jsContents: string) => { // verify that there is no pattern that triggers automatic semicolon // insertion by checking that there are no function return statements // not wrapped in parentheses expect(trim(jsContents)).not.toMatch(/return\s+function/); expect(trim(jsContents)).toContain( trim(` [{ provide: 'token-a', useFactory: ((service) => { return (() => service.id); }) }, { provide: 'token-b', useFactory: (function (service) { return (function () { return service.id; }); }) }] `), ); }; it('should wrap functions in "providers" list in NgModule', () => { env.tsconfig({ 'annotateForClosureCompiler': true, }); env.write('service.ts', service); env.write( 'test.ts', ` import {NgModule} from '@angular/core'; import {Service} from './service'; @NgModule({ providers: ${providers} }) export class SomeModule {} `, ); env.driveMain(); verifyOutput(env.getContents('test.js')); }); it('should wrap functions in "providers" list in Component', () => { env.tsconfig({ 'annotateForClosureCompiler': true, }); env.write('service.ts', service); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {Service} from './service'; @Component({ template: '...', providers: ${providers} }) export class SomeComponent {} `, ); env.driveMain(); verifyOutput(env.getContents('test.js')); }); it('should wrap functions in "viewProviders" list in Component', () => { env.tsconfig({ 'annotateForClosureCompiler': true, }); env.write('service.ts', service); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {Service} from './service'; @Component({ template: '...', viewProviders: ${providers} }) export class SomeComponent {} `, ); env.driveMain(); verifyOutput(env.getContents('test.js')); }); it('should wrap functions in "providers" list in Directive', () => { env.tsconfig({ 'annotateForClosureCompiler': true, }); env.write('service.ts', service); env.write( 'test.ts', ` import {Directive} from '@angular/core'; import {Service} from './service'; @Directive({ providers: ${providers} }) export class SomeDirective {} `, ); env.driveMain(); verifyOutput(env.getContents('test.js')); }); }); }); } it('should recognize aliased decorators', () => { env.write( 'test.ts', ` import { Component as AngularComponent,
{ "end_byte": 30854, "start_byte": 23126, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_30860_39642
Directive as AngularDirective, Pipe as AngularPipe, Injectable as AngularInjectable, NgModule as AngularNgModule, Input as AngularInput, Output as AngularOutput } from '@angular/core'; @AngularDirective() export class TestBase { @AngularInput() input: any; @AngularOutput() output: any; } @AngularComponent({ selector: 'test-component', template: '...', standalone: false, }) export class TestComponent { @AngularInput() input: any; @AngularOutput() output: any; } @AngularDirective({ selector: 'test-directive', standalone: false, }) export class TestDirective {} @AngularPipe({ name: 'test-pipe', standalone: false, }) export class TestPipe {} @AngularInjectable() export class TestInjectable {} @AngularNgModule({ declarations: [ TestComponent, TestDirective, TestPipe ], exports: [ TestComponent, TestDirective, TestPipe ] }) class MyModule {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('TestBase.ɵdir = /*@__PURE__*/ i0.ɵɵdefineDirective'); expect(jsContents).toContain('TestComponent.ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent'); expect(jsContents).toContain('TestDirective.ɵdir = /*@__PURE__*/ i0.ɵɵdefineDirective'); expect(jsContents).toContain('TestPipe.ɵpipe = /*@__PURE__*/ i0.ɵɵdefinePipe'); expect(jsContents).toContain('TestInjectable.ɵprov = /*@__PURE__*/ i0.ɵɵdefineInjectable'); expect(jsContents).toContain('MyModule.ɵmod = /*@__PURE__*/ i0.ɵɵdefineNgModule'); expect(jsContents).toContain('MyModule.ɵinj = /*@__PURE__*/ i0.ɵɵdefineInjector'); expect(jsContents).toContain('inputs: { input: "input" }'); expect(jsContents).toContain('outputs: { output: "output" }'); }); it('should pick a Pipe defined in `declarations` over imported Pipes', () => { env.tsconfig({}); env.write( 'test.ts', ` import {Component, Pipe, NgModule} from '@angular/core'; // ModuleA classes @Pipe({ name: 'number', standalone: false, }) class PipeA { transform() {} } @NgModule({ declarations: [PipeA], exports: [PipeA] }) class ModuleA {} // ModuleB classes @Pipe({ name: 'number', standalone: false, }) class PipeB { transform() {} } @Component({ selector: 'app', template: '{{ count | number }}', standalone: false, }) export class App { count = 0; } @NgModule({ imports: [ModuleA], declarations: [PipeB, App], }) class ModuleB {} `, ); env.driveMain(); const jsContents = trim(env.getContents('test.js')); expect(jsContents).toContain('dependencies: [PipeB]'); }); it('should respect imported module order when selecting Pipe (last imported Pipe is used)', () => { env.tsconfig({}); env.write( 'test.ts', ` import {Component, Pipe, NgModule} from '@angular/core'; // ModuleA classes @Pipe({ name: 'number', standalone: false, }) class PipeA { transform() {} } @NgModule({ declarations: [PipeA], exports: [PipeA] }) class ModuleA {} // ModuleB classes @Pipe({ name: 'number', standalone: false, }) class PipeB { transform() {} } @NgModule({ declarations: [PipeB], exports: [PipeB] }) class ModuleB {} // ModuleC classes @Component({ selector: 'app', template: '{{ count | number }}', standalone: false, }) export class App { count = 0; } @NgModule({ imports: [ModuleA, ModuleB], declarations: [App], }) class ModuleC {} `, ); env.driveMain(); const jsContents = trim(env.getContents('test.js')); expect(jsContents).toContain('dependencies: [PipeB]'); }); it('should add Directives and Components from `declarations` at the end of the list', () => { env.tsconfig({}); env.write( 'test.ts', ` import {Component, Directive, NgModule} from '@angular/core'; // ModuleA classes @Directive({ selector: '[dir]', standalone: false, }) class DirectiveA {} @Component({ selector: 'comp', template: '...', standalone: false, }) class ComponentA {} @NgModule({ declarations: [DirectiveA, ComponentA], exports: [DirectiveA, ComponentA] }) class ModuleA {} // ModuleB classes @Directive({ selector: '[dir]', standalone: false, }) class DirectiveB {} @Component({ selector: 'comp', template: '...', standalone: false, }) export class ComponentB {} @Component({ selector: 'app', template: \` <div dir></div> <comp></comp> \`, standalone: false, }) export class App {} @NgModule({ imports: [ModuleA], declarations: [DirectiveB, ComponentB, App], }) class ModuleB {} `, ); env.driveMain(); const jsContents = trim(env.getContents('test.js')); expect(jsContents).toContain( 'dependencies: [DirectiveA, ComponentA, DirectiveB, ComponentB]', ); }); it('should respect imported module order while processing Directives and Components', () => { env.tsconfig({}); env.write( 'test.ts', ` import {Component, Directive, NgModule} from '@angular/core'; // ModuleA classes @Directive({ selector: '[dir]', standalone: false, }) class DirectiveA {} @Component({ selector: 'comp', template: '...', standalone: false, }) class ComponentA {} @NgModule({ declarations: [DirectiveA, ComponentA], exports: [DirectiveA, ComponentA] }) class ModuleA {} // ModuleB classes @Directive({ selector: '[dir]', standalone: false, }) class DirectiveB {} @Component({ selector: 'comp', template: '...', standalone: false, }) class ComponentB {} @NgModule({ declarations: [DirectiveB, ComponentB], exports: [DirectiveB, ComponentB] }) class ModuleB {} // ModuleC classes @Component({ selector: 'app', template: \` <div dir></div> <comp></comp> \`, standalone: false, }) export class App {} @NgModule({ imports: [ModuleA, ModuleB], declarations: [App], }) class ModuleC {} `, ); env.driveMain(); const jsContents = trim(env.getContents('test.js')); expect(jsContents).toContain( 'dependencies: [DirectiveA, ComponentA, DirectiveB, ComponentB]', ); }); it('should compile Components with a templateUrl in a different rootDir', () => { env.tsconfig({}, ['./extraRootDir']); env.write('extraRootDir/test.html', '<p>Hello World</p>'); env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', templateUrl: 'test.html', standalone: false, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('Hello World'); }); it('should compile Components with an absolute templateUrl in a different rootDir', () => { env.tsconfig({}, ['./extraRootDir']); env.write('extraRootDir/test.ht
{ "end_byte": 39642, "start_byte": 30860, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_39648_48347
<p>Hello World</p>'); env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', templateUrl: '/test.html', standalone: false, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('Hello World'); }); it('should compile components with styleUrls', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', styleUrls: ['./dir/style.css'], template: '', standalone: false, }) export class TestCmp {} `, ); env.write('dir/style.css', ':host { background-color: blue; }'); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('background-color: blue'); }); it('should compile components with styleUrls with fallback to .css extension', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', styleUrls: ['./dir/style.scss'], template: '', standalone: false, }) export class TestCmp {} `, ); env.write('dir/style.css', ':host { background-color: blue; }'); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('background-color: blue'); }); it('should include generic type in directive definition', () => { env.write( 'test.ts', ` import {Directive, Input, NgModule} from '@angular/core'; @Directive() export class TestBase { @Input() input: any; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'i0.ɵɵdefineDirective({ type: TestBase, inputs: { input: "input" } });', ); const dtsContents = env.getContents('test.d.ts'); const expectedDirectiveDeclaration = `static ɵdir: i0.ɵɵDirectiveDeclaration<TestBase, never, never, { "input": { "alias": "input"; "required": false; }; }, {}, never, never, true, never>;`; expect(dtsContents).toContain(expectedDirectiveDeclaration); }); describe('undecorated classes using Angular features', () => { it('should error if @Input has been discovered', () => assertErrorUndecoratedClassWithField('Input')); it('should error if @Output has been discovered', () => assertErrorUndecoratedClassWithField('Output')); it('should error if @ViewChild has been discovered', () => assertErrorUndecoratedClassWithField('ViewChild')); it('should error if @ViewChildren has been discovered', () => assertErrorUndecoratedClassWithField('ViewChildren')); it('should error if @ContentChild has been discovered', () => assertErrorUndecoratedClassWithField('ContentChildren')); it('should error if @HostBinding has been discovered', () => assertErrorUndecoratedClassWithField('HostBinding')); it('should error if @HostListener has been discovered', () => assertErrorUndecoratedClassWithField('HostListener')); it(`should error if ngOnChanges lifecycle hook has been discovered`, () => assertErrorUndecoratedClassWithLifecycleHook('ngOnChanges')); it(`should error if ngOnInit lifecycle hook has been discovered`, () => assertErrorUndecoratedClassWithLifecycleHook('ngOnInit')); it(`should error if ngOnDestroy lifecycle hook has been discovered`, () => assertErrorUndecoratedClassWithLifecycleHook('ngOnDestroy')); it(`should error if ngDoCheck lifecycle hook has been discovered`, () => assertErrorUndecoratedClassWithLifecycleHook('ngDoCheck')); it(`should error if ngAfterViewInit lifecycle hook has been discovered`, () => assertErrorUndecoratedClassWithLifecycleHook('ngAfterViewInit')); it(`should error if ngAfterViewChecked lifecycle hook has been discovered`, () => assertErrorUndecoratedClassWithLifecycleHook('ngAfterViewChecked')); it(`should error if ngAfterContentInit lifecycle hook has been discovered`, () => assertErrorUndecoratedClassWithLifecycleHook('ngAfterContentInit')); it(`should error if ngAfterContentChecked lifecycle hook has been discovered`, () => assertErrorUndecoratedClassWithLifecycleHook('ngAfterContentChecked')); function assertErrorUndecoratedClassWithField(fieldDecoratorName: string) { env.write( 'test.ts', ` import {Component, ${fieldDecoratorName}, NgModule} from '@angular/core'; export class SomeBaseClass { // @ts-ignore — Because no arguments are specified. @${fieldDecoratorName}() someMember: any; } `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); expect(trim(errors[0].messageText as string)).toContain( 'Class is using Angular features but is not decorated. Please add an explicit ' + 'Angular decorator.', ); } function assertErrorUndecoratedClassWithLifecycleHook(lifecycleName: string) { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; export class SomeBaseClass { ${lifecycleName}() { // empty } } `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); expect(trim(errors[0].messageText as string)).toContain( 'Class is using Angular features but is not decorated. Please add an explicit ' + 'Angular decorator.', ); } }); it('should compile NgModules without errors', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'test-cmp', template: 'this is a test', standalone: false, }) export class TestCmp {} @NgModule({ declarations: [TestCmp], bootstrap: [TestCmp], }) export class TestModule {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'i0.ɵɵdefineNgModule({ type: TestModule, bootstrap: [TestCmp] });', ); expect(jsContents).toContain( 'function () { (typeof ngJitMode === "undefined" || ngJitMode) && i0.ɵɵsetNgModuleScope(TestModule, { declarations: [TestCmp] }); })();', ); expect(jsContents).toContain( 'TestModule.ɵfac = function TestModule_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || TestModule)(); }', ); expect(jsContents).toContain('i0.ɵɵdefineInjector({});'); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain( 'static ɵcmp: i0.ɵɵComponentDeclaration<TestCmp, "test-cmp", never, {}, {}, never, never, false, never>', ); expect(dtsContents).toContain( 'static ɵmod: i0.ɵɵNgModuleDeclaration<TestModule, [typeof TestCmp], never, never>', ); expect(dtsContents).not.toContain('__decorate'); }); it('should not emit a ɵɵsetNgModuleScope call when no scope metadata is present', () => { env.write( 'test.ts', ` import {NgModule} from '@angular/core'; @NgModule({}) export class TestModule {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('i0.ɵɵdefineNgModule({ type: TestModule });'); expect(jsContents).not.toContain('ɵɵsetNgModuleScope(TestModule,'); }); it("should emit the id when the module's id is a string", () => { env.write( 'test.ts', ` import {NgModule} from '@angular/core'; @NgModule({id: 'test'}) export class TestModule {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain(`i0.ɵɵdefineNgModule({ type: TestModule, id: 'test' })`); }); it('should warn when an NgModule id is defined as module.id, and not emit it', () => { env.write( 'index.d.ts', ` declare const module = {id: string}; `, );
{ "end_byte": 48347, "start_byte": 39648, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_48353_56731
env.write( 'test.ts', ` import {NgModule} from '@angular/core'; @NgModule({id: module.id}) export class TestModule {} `, ); const diags = env.driveDiagnostics(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('i0.ɵɵdefineNgModule({ type: TestModule })'); expect(jsContents).not.toContain('i0.ɵɵregisterNgModuleType'); expect(diags.length).toEqual(1); expect(diags[0].category).toEqual(ts.DiagnosticCategory.Warning); expect(diags[0].code).toEqual(ngErrorCode(ErrorCode.WARN_NGMODULE_ID_UNNECESSARY)); expect(getDiagnosticSourceCode(diags[0])).toEqual('module.id'); }); it('should emit a side-effectful registration call when an @NgModule has an id', () => { env.write( 'test.ts', ` import {NgModule} from '@angular/core'; @NgModule({id: 'test'}) export class TestModule {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain(`i0.ɵɵregisterNgModuleType(TestModule, 'test')`); }); it('should filter out directives and pipes from module exports in the injector def', () => { env.write( 'test.ts', ` import {NgModule} from '@angular/core'; import {RouterComp, RouterModule} from '@angular/router'; import {Dir, OtherDir, MyPipe, Comp} from './decls'; @NgModule({ declarations: [OtherDir], exports: [OtherDir], }) export class OtherModule {} const EXPORTS = [Dir, MyPipe, Comp, OtherModule, OtherDir, RouterModule, RouterComp]; @NgModule({ declarations: [Dir, MyPipe, Comp], imports: [OtherModule, RouterModule.forRoot()], exports: [EXPORTS], }) export class TestModule {} `, ); env.write( `decls.ts`, ` import {Component, Directive, Pipe} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir {} @Directive({ selector: '[other]', standalone: false, }) export class OtherDir {} @Pipe({ name:'pipe', standalone: false, }) export class MyPipe {} @Component({ selector: 'test', template: '', standalone: false }) export class Comp {} `, ); env.write( 'node_modules/@angular/router/index.d.ts', ` import {ɵɵComponentDeclaration, ModuleWithProviders, ɵɵNgModuleDeclaration} from '@angular/core'; export declare class RouterComp { static ɵcmp: ɵɵComponentDeclaration<RouterComp, "lib-cmp", never, {}, {}, never> } declare class RouterModule { static forRoot(): ModuleWithProviders<RouterModule>; static ɵmod: ɵɵNgModuleDeclaration<RouterModule, [typeof RouterComp], never, [typeof RouterComp]>; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'TestModule.ɵfac = function TestModule_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || TestModule)(); }', ); expect(jsContents).toContain( 'i0.ɵɵdefineInjector({ imports: [OtherModule, RouterModule.forRoot(),' + ' OtherModule, RouterModule] });', ); }); it('should compile NgModules with services without errors', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; export class Token {} @NgModule({}) export class OtherModule {} @Component({ selector: 'test-cmp', template: 'this is a test', standalone: false, }) export class TestCmp {} @NgModule({ declarations: [TestCmp], providers: [{provide: Token, useValue: 'test'}], imports: [OtherModule], }) export class TestModule {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'TestModule.ɵfac = function TestModule_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || TestModule)(); }', ); expect(jsContents).toContain('i0.ɵɵdefineNgModule({ type: TestModule });'); expect(jsContents).toContain( `TestModule.ɵinj = /*@__PURE__*/ i0.ɵɵdefineInjector({ ` + `providers: [{ provide: Token, useValue: 'test' }], ` + `imports: [OtherModule] });`, ); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain( 'static ɵmod: i0.ɵɵNgModuleDeclaration<TestModule, [typeof TestCmp], [typeof OtherModule], never>', ); expect(dtsContents).toContain('static ɵinj: i0.ɵɵInjectorDeclaration'); }); it('should compile NgModules with factory providers without errors', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; export class Token {} @NgModule({}) export class OtherModule {} @Component({ selector: 'test-cmp', template: 'this is a test', standalone: false, }) export class TestCmp {} @NgModule({ declarations: [TestCmp], providers: [{provide: Token, useFactory: () => new Token()}], imports: [OtherModule], }) export class TestModule {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'TestModule.ɵfac = function TestModule_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || TestModule)(); }', ); expect(jsContents).toContain('i0.ɵɵdefineNgModule({ type: TestModule });'); expect(jsContents).toContain( `TestModule.ɵinj = /*@__PURE__*/ i0.ɵɵdefineInjector({ ` + `providers: [{ provide: Token, useFactory: () => new Token() }], ` + `imports: [OtherModule] });`, ); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain( 'static ɵmod: i0.ɵɵNgModuleDeclaration<TestModule, [typeof TestCmp], [typeof OtherModule], never>', ); expect(dtsContents).toContain('static ɵinj: i0.ɵɵInjectorDeclaration'); }); it('should compile NgModules with factory providers and deps without errors', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; export class Dep {} export class Token { constructor(dep: Dep) {} } @NgModule({}) export class OtherModule {} @Component({ selector: 'test-cmp', template: 'this is a test', standalone: false, }) export class TestCmp {} @NgModule({ declarations: [TestCmp], providers: [{provide: Token, useFactory: (dep: Dep) => new Token(dep), deps: [Dep]}], imports: [OtherModule], }) export class TestModule {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'TestModule.ɵfac = function TestModule_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || TestModule)(); }', ); expect(jsContents).toContain('i0.ɵɵdefineNgModule({ type: TestModule });'); expect(jsContents).toContain( `TestModule.ɵinj = /*@__PURE__*/ i0.ɵɵdefineInjector({ ` + `providers: [{ provide: Token, useFactory: (dep) => new Token(dep), deps: [Dep] }], ` + `imports: [OtherModule] });`, ); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain( 'static ɵmod: i0.ɵɵNgModuleDeclaration<TestModule, [typeof TestCmp], [typeof OtherModule], never>', ); expect(dtsContents).toContain('static ɵinj: i0.ɵɵInjectorDeclaration'); }); it('should compile NgModules with references to local components', () => { env.write( 'test.ts', ` import {NgModule} from '@angular/core'; import {Foo} from './foo'; @NgModule({ declarations: [Foo], })
{ "end_byte": 56731, "start_byte": 48353, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_56737_64852
export class FooModule {} `, ); env.write( 'foo.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'foo', template: '', standalone: false, }) export class Foo {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain("import { Foo } from './foo';"); expect(jsContents).not.toMatch(/as i[0-9] from ".\/foo"/); expect(dtsContents).toContain('as i1 from "./foo";'); }); it('should compile NgModules with references to absolute components', () => { env.write( 'tsconfig.json', JSON.stringify({ extends: './tsconfig-base.json', compilerOptions: { baseUrl: '.', paths: { '*': ['*', 'shared/*'], }, }, }), ); env.write( 'test.ts', ` import {NgModule} from '@angular/core'; import {Foo} from 'foo'; @NgModule({ declarations: [Foo], }) export class FooModule {} `, ); env.write( 'shared/foo/index.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'foo', template: '', standalone: false, }) export class Foo { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain("import { Foo } from 'foo';"); expect(jsContents).not.toMatch(/as i[0-9] from "foo"/); expect(dtsContents).toContain('as i1 from "foo";'); }); it('should compile NgModules with references to forward declared bootstrap components', () => { env.write( 'test.ts', ` import {Component, forwardRef, NgModule} from '@angular/core'; @NgModule({ bootstrap: [forwardRef(() => Foo)], }) export class FooModule {} @Component({ selector: 'foo', template: 'foo', standalone: false, }) export class Foo {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('bootstrap: () => [Foo]'); }); it('should compile NgModules with references to forward declared directives', () => { env.write( 'test.ts', ` import {Directive, forwardRef, NgModule} from '@angular/core'; @NgModule({ declarations: [forwardRef(() => Foo)], }) export class FooModule {} @Directive({ selector: 'foo', standalone: false, }) export class Foo {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('declarations: () => [Foo]'); }); it('should compile NgModules with references to forward declared imports', () => { env.write( 'test.ts', ` import {forwardRef, NgModule} from '@angular/core'; @NgModule({ imports: [forwardRef(() => BarModule)], }) export class FooModule {} @NgModule({}) export class BarModule {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('imports: () => [BarModule]'); }); it('should compile NgModules with references to forward declared exports', () => { env.write( 'test.ts', ` import {forwardRef, NgModule} from '@angular/core'; @NgModule({ exports: [forwardRef(() => BarModule)], }) export class FooModule {} @NgModule({}) export class BarModule {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('exports: () => [BarModule]'); }); it('should use relative import for forward references that were resolved from a relative file', () => { env.write( 'dir.ts', ` import {Directive, forwardRef} from '@angular/core'; export const useFoo = forwardRef(() => Foo); @Directive({ selector: 'foo', standalone: false, }) export class Foo {} `, ); env.write( 'test.ts', ` import {NgModule} from '@angular/core'; import {useFoo} from './dir'; @NgModule({ declarations: [useFoo], }) export class FooModule {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('import * as i1 from "./dir";'); expect(jsContents).toContain('declarations: [i1.Foo]'); }); it('should use absolute import for forward references that were resolved from an absolute file', () => { env.write( 'dir.ts', ` import {Directive, forwardRef} from '@angular/core'; export const useFoo = forwardRef(() => Foo); @Directive({ selector: 'foo', standalone: false, }) export class Foo {} `, ); env.write( 'test.ts', ` import {forwardRef, NgModule} from '@angular/core'; import {useFoo} from 'dir'; @NgModule({ declarations: [useFoo], }) export class FooModule {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('import * as i1 from "dir";'); expect(jsContents).toContain('declarations: [i1.Foo]'); }); it('should compile Pipes without errors', () => { env.write( 'test.ts', ` import {Pipe} from '@angular/core'; @Pipe({ name: 'test-pipe', pure: false, standalone: false, }) export class TestPipe {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain( 'TestPipe.ɵpipe = /*@__PURE__*/ i0.ɵɵdefinePipe({ name: "test-pipe", type: TestPipe, pure: false, standalone: false })', ); expect(jsContents).toContain( 'TestPipe.ɵfac = function TestPipe_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || TestPipe)(); }', ); expect(dtsContents).toContain( 'static ɵpipe: i0.ɵɵPipeDeclaration<TestPipe, "test-pipe", false>;', ); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<TestPipe, never>;'); }); it('should compile pure Pipes without errors', () => { env.write( 'test.ts', ` import {Pipe} from '@angular/core'; @Pipe({ name: 'test-pipe', standalone: false, }) export class TestPipe {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); expect(jsContents).toContain( 'TestPipe.ɵpipe = /*@__PURE__*/ i0.ɵɵdefinePipe({ name: "test-pipe", type: TestPipe, pure: true, standalone: false })', ); expect(jsContents).toContain( 'TestPipe.ɵfac = function TestPipe_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || TestPipe)(); }', ); expect(dtsContents).toContain( 'static ɵpipe: i0.ɵɵPipeDeclaration<TestPipe, "test-pipe", false>;', ); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<TestPipe, never>;'); }); it('should compile Pipes with dependencies', () => { env.write( 'test.ts', ` import {Pipe} from '@angular/core'; export class Dep {} @Pipe({ name: 'test-pipe', pure: false, standalone: false,
{ "end_byte": 64852, "start_byte": 56737, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_64858_71108
export class TestPipe { constructor(dep: Dep) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'return new (__ngFactoryType__ || TestPipe)(i0.ɵɵdirectiveInject(Dep, 16));', ); }); it('should compile Pipes with generic types', () => { env.write( 'test.ts', ` import {Pipe} from '@angular/core'; @Pipe({ name: 'test-pipe', standalone: false, }) export class TestPipe<T> {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('TestPipe.ɵpipe ='); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain( 'static ɵpipe: i0.ɵɵPipeDeclaration<TestPipe<any>, "test-pipe", false>;', ); expect(dtsContents).toContain('static ɵfac: i0.ɵɵFactoryDeclaration<TestPipe<any>, never>;'); }); it('should include @Pipes in @NgModule scopes', () => { env.write( 'test.ts', ` import {Component, NgModule, Pipe} from '@angular/core'; @Pipe({ name: 'test', standalone: false, }) export class TestPipe { transform() {} } @Component({ selector: 'test-cmp', template: '{{value | test}}', standalone: false, }) export class TestCmp { value = ''; } @NgModule({declarations: [TestPipe, TestCmp]}) export class TestModule {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('dependencies: [TestPipe]'); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain( 'i0.ɵɵNgModuleDeclaration<TestModule, [typeof TestPipe, typeof TestCmp], never, never>', ); }); describe('empty and missing selectors', () => { it('should use default selector for Components when no selector present', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '...', standalone: false, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('selectors: [["ng-component"]]'); }); it('should use default selector for Components with empty string selector', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: '', template: '...', standalone: false, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('selectors: [["ng-component"]]'); }); it('should allow directives with no selector that are not in NgModules', () => { env.write( 'main.ts', ` import {Directive} from '@angular/core'; @Directive({}) export class BaseDir {} @Directive({}) export abstract class AbstractBaseDir {} @Directive() export abstract class EmptyDir {} @Directive({ inputs: ['a', 'b'], standalone: false, }) export class TestDirWithInputs {} `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(0); }); it('should be able to use abstract directive in other compilation units', () => { env.write( 'tsconfig.json', JSON.stringify({ extends: './tsconfig-base.json', compilerOptions: {rootDir: '.', outDir: '../node_modules/lib1_built'}, }), ); env.write( 'index.ts', ` import {Directive} from '@angular/core'; @Directive() export class BaseClass {} `, ); expect(env.driveDiagnostics().length).toBe(0); env.tsconfig(); env.write( 'index.ts', ` import {NgModule, Directive} from '@angular/core'; import {BaseClass} from 'lib1_built'; @Directive({ selector: 'my-dir', standalone: false, }) export class MyDirective extends BaseClass {} @NgModule({declarations: [MyDirective]}) export class AppModule {} `, ); expect(env.driveDiagnostics().length).toBe(0); }); it('should not allow directives with no selector that are in NgModules', () => { env.write( 'main.ts', ` import {Directive, NgModule} from '@angular/core'; @Directive({ standalone: false, }) export class BaseDir {} @NgModule({ declarations: [BaseDir], }) export class MyModule {} `, ); const errors = env.driveDiagnostics(); expect(trim(errors[0].messageText as string)).toContain( 'Directive BaseDir has no selector, please add it!', ); }); it('should throw if Directive selector is an empty string', () => { env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '', standalone: false, }) export class TestDir {} `, ); const errors = env.driveDiagnostics(); expect(trim(errors[0].messageText as string)).toContain( 'Directive TestDir has no selector, please add it!', ); }); }); describe('error handling', () => { function verifyThrownError(errorCode: ErrorCode, errorMessage: string) { const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); const {code, messageText} = errors[0]; expect(code).toBe(ngErrorCode(errorCode));
{ "end_byte": 71108, "start_byte": 64858, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_71108_80917
const text = ts.flattenDiagnosticMessageText(messageText, '\n'); expect(trim(text)).toContain(errorMessage); } it('should throw if invalid arguments are provided in @NgModule', () => { env.tsconfig({}); env.write( 'test.ts', ` import {NgModule} from '@angular/core'; // @ts-ignore @NgModule('invalidNgModuleArgumentType') export class MyModule {} `, ); verifyThrownError( ErrorCode.DECORATOR_ARG_NOT_LITERAL, '@NgModule argument must be an object literal', ); }); it('should throw if multiple query decorators are used on the same field', () => { env.tsconfig({}); env.write( 'test.ts', ` import {Component, ContentChild} from '@angular/core'; @Component({ selector: 'test-cmp', template: '...' }) export class TestCmp { @ContentChild('bar', {static: true}) @ContentChild('foo') foo: any; } `, ); verifyThrownError( ErrorCode.DECORATOR_COLLISION, 'Cannot combine multiple query decorators.', ); }); ['ViewChild', 'ViewChildren', 'ContentChild', 'ContentChildren'].forEach((decorator) => { it(`should throw if @Input and @${decorator} decorators are applied to the same property`, () => { env.tsconfig({}); env.write( 'test.ts', ` import {Component, ${decorator}, Input} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<ng-content></ng-content>' }) export class TestCmp { @Input() @${decorator}('foo') foo: any; } `, ); verifyThrownError( ErrorCode.DECORATOR_COLLISION, 'Cannot combine @Input decorators with query decorators', ); }); it(`should throw if invalid options are provided in ${decorator}`, () => { env.tsconfig({}); env.write( 'test.ts', ` import {Component, ${decorator}, Input} from '@angular/core'; @Component({ selector: 'test-cmp', template: '...' }) export class TestCmp { // @ts-ignore @${decorator}('foo', 'invalidOptionsArgumentType') foo: any; } `, ); verifyThrownError( ErrorCode.DECORATOR_ARG_NOT_LITERAL, `@${decorator} options must be an object literal`, ); }); it(`should throw if @${decorator} is used on non property-type member`, () => { env.tsconfig({}); env.write( 'test.ts', ` import {Component, ${decorator}} from '@angular/core'; @Component({ selector: 'test-cmp', template: '...' }) export class TestCmp { @${decorator}('foo') private someFn() {} } `, ); verifyThrownError( ErrorCode.DECORATOR_UNEXPECTED, 'Query decorator must go on a property-type member', ); }); it(`should throw error if @${decorator} has too many arguments`, () => { env.tsconfig({}); env.write( 'test.ts', ` import {Component, ${decorator}} from '@angular/core'; @Component({ selector: 'test-cmp', template: '...' }) export class TestCmp { // @ts-ignore @${decorator}('foo', {}, 'invalid-extra-arg') foo: any; } `, ); verifyThrownError( ErrorCode.DECORATOR_ARITY_WRONG, `@${decorator} has too many arguments`, ); }); it(`should throw error if @${decorator} predicate argument has wrong type`, () => { env.tsconfig({}); env.write( 'test.ts', ` import {Component, ${decorator}} from '@angular/core'; @Component({ selector: 'test-cmp', template: '...' }) export class TestCmp { // @ts-ignore @${decorator}({'invalid-predicate-type': true}) foo: any; } `, ); verifyThrownError( ErrorCode.VALUE_HAS_WRONG_TYPE, `@${decorator} predicate cannot be interpreted`, ); }); it(`should throw error if one of @${decorator}'s predicate has wrong type`, () => { env.tsconfig({}); env.write( 'test.ts', ` import {Component, ${decorator}} from '@angular/core'; @Component({ selector: 'test-cmp', template: '...' }) export class TestCmp { // @ts-ignore @${decorator}(['predicate-a', {'invalid-predicate-type': true}]) foo: any; } `, ); verifyThrownError( ErrorCode.VALUE_HAS_WRONG_TYPE, `Failed to resolve @${decorator} predicate at position 1 to a string`, ); }); }); it(`should throw error if @Directive.inputs has wrong type`, () => { env.tsconfig({}); env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: 'test-dir', // @ts-ignore inputs: 'invalid-field-type', }) export class TestDir {} `, ); verifyThrownError( ErrorCode.VALUE_HAS_WRONG_TYPE, `Failed to resolve @Directive.inputs to an array Value is of type 'string'.`, ); }); it('should throw if decorator input is declared on static member', () => { env.write( 'test.ts', ` import {Directive, Input} from '@angular/core'; @Directive() export class TestDir { @Input() static someInput: string = ''; } `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics).toEqual([ jasmine.objectContaining({ messageText: 'Input "someInput" is incorrectly declared as static member of "TestDir".', }), ]); }); it(`should throw error if @Directive.outputs has wrong type`, () => { env.tsconfig({}); env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: 'test-dir', // @ts-ignore outputs: 'invalid-field-type', }) export class TestDir {} `, ); verifyThrownError( ErrorCode.VALUE_HAS_WRONG_TYPE, `Failed to resolve @Directive.outputs to a string array`, ); }); ['ContentChild', 'ContentChildren'].forEach((decorator) => { it(`should throw if \`descendants\` field of @${decorator}'s options argument has wrong type`, () => { env.tsconfig({}); env.write( 'test.ts', ` import {Component, ContentChild} from '@angular/core'; @Component({ selector: 'test-cmp', template: '...' }) export class TestCmp { // @ts-ignore @ContentChild('foo', {descendants: 'invalid'}) foo: any; } `, ); verifyThrownError( ErrorCode.VALUE_HAS_WRONG_TYPE, '@ContentChild options.descendants must be a boolean', ); }); }); ['Input', 'Output'].forEach((decorator) => { it(`should throw error if @${decorator} decorator argument has unsupported type`, () => { env.tsconfig({}); env.write( 'test.ts', ` import {Component, ${decorator}} from '@angular/core'; @Component({ selector: 'test-cmp', template: '...' }) export class TestCmp { // @ts-ignore @${decorator}(['invalid-arg-type']) foo: any; } `, ); verifyThrownError( ErrorCode.VALUE_HAS_WRONG_TYPE, `@${decorator} decorator argument must resolve to a string`, ); }); it(`should throw error if @${decorator} decorator has too many arguments`, () => { env.tsconfig({}); env.write( 'test.ts', ` import {Component, ${decorator}} from '@angular/core'; @Component({ selector: 'test-cmp', template: '...' }) export class TestCmp { // @ts-ignore @${decorator}('name', 'invalid-extra-arg') foo: any; } `, ); verifyThrownError( ErrorCode.DECORATOR_ARITY_WRONG, `@${decorator} can have at most one argument, got 2 argument(s)`, ); }); }); it('should throw error if @HostBinding decorator argument has unsupported type', () => { env.tsconfig({}); env.write( 'test.ts', ` import {Component, HostBinding} from '@angular/core'; @Component({ selector: 'test-cm
{ "end_byte": 80917, "start_byte": 71108, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_80925_90567
template: '...' }) export class TestCmp { // @ts-ignore @HostBinding(['invalid-arg-type']) foo: any; } `, ); verifyThrownError( ErrorCode.VALUE_HAS_WRONG_TYPE, `@HostBinding's argument must be a string`, ); }); it('should throw error if @HostBinding decorator has too many arguments', () => { env.tsconfig({}); env.write( 'test.ts', ` import {Component, HostBinding} from '@angular/core'; @Component({ selector: 'test-cmp', template: '...' }) export class TestCmp { // @ts-ignore @HostBinding('name', 'invalid-extra-arg') foo: any; } `, ); verifyThrownError( ErrorCode.DECORATOR_ARITY_WRONG, '@HostBinding can have at most one argument', ); }); it('should throw error if @Directive.host field has wrong type', () => { env.tsconfig({}); env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: 'test-dir', // @ts-ignore host: 'invalid-host-type' }) export class TestDir {} `, ); verifyThrownError( ErrorCode.VALUE_HAS_WRONG_TYPE, 'Decorator host metadata must be an object', ); }); it('should throw error if @Directive.host field is an object with values that have wrong types', () => { env.tsconfig({}); env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: 'test-dir', // @ts-ignore host: {'key': ['invalid-host-value']} }) export class TestDir {} `, ); verifyThrownError( ErrorCode.VALUE_HAS_WRONG_TYPE, 'Decorator host metadata must be a string -> string object, but found unparseable value', ); }); it('should throw error if @Directive.queries field has wrong type', () => { env.tsconfig({}); env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: 'test-dir', // @ts-ignore queries: 'invalid-queries-type' }) export class TestDir {} `, ); verifyThrownError( ErrorCode.VALUE_HAS_WRONG_TYPE, 'Decorator queries metadata must be an object', ); }); it('should throw error if @Directive.queries object has incorrect values', () => { env.tsconfig({}); env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: 'test-dir', queries: { myViewQuery: 'invalid-query-type' } }) export class TestDir {} `, ); verifyThrownError( ErrorCode.VALUE_HAS_WRONG_TYPE, 'Decorator query metadata must be an instance of a query type', ); }); it('should throw error if @Directive.queries object has incorrect values (refs to other decorators)', () => { env.tsconfig({}); env.write( 'test.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: 'test-dir', queries: { myViewQuery: new Input() } }) export class TestDir {} `, ); verifyThrownError( ErrorCode.VALUE_HAS_WRONG_TYPE, 'Decorator query metadata must be an instance of a query type', ); }); it('should throw error if @Injectable has incorrect argument', () => { env.tsconfig({}); env.write( 'test.ts', ` import {Injectable} from '@angular/core'; // @ts-ignore @Injectable('invalid') export class TestProvider {} `, ); verifyThrownError( ErrorCode.DECORATOR_ARG_NOT_LITERAL, '@Injectable argument must be an object literal', ); }); it('should produce a diagnostic if the transform value is not a function', () => { env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; const NOT_A_FUNCTION: any = null!; @Directive({selector: '[dir]', standalone: true}) export class Dir { @Input({transform: NOT_A_FUNCTION}) value!: number; } `, ); verifyThrownError(ErrorCode.VALUE_HAS_WRONG_TYPE, `Input transform must be a function`); }); it('should produce a diagnostic if the transform value in the inputs array is not a function', () => { env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; const NOT_A_FUNCTION: any = null!; @Directive({ selector: '[dir]', standalone: true, inputs: [{ name: 'value', transform: NOT_A_FUNCTION }] }) export class Dir { value!: number; } `, ); verifyThrownError( ErrorCode.VALUE_HAS_WRONG_TYPE, `Transform of value at position 0 of @Directive.inputs array must be a function Value is of type 'null'.`, ); }); it('should produce a diangostic if the transform function first parameter has no arguments', () => { env.tsconfig({noImplicitAny: false}); env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; @Directive({selector: '[dir]', standalone: true}) export class Dir { @Input({transform: (val) => 1}) value!: number; } `, ); verifyThrownError( ErrorCode.VALUE_HAS_WRONG_TYPE, `Input transform function first parameter must have a type`, ); }); it('should produce a diangostic if the transform function is generic', () => { env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; @Directive({selector: '[dir]', standalone: true}) export class Dir { @Input({transform: <T>(val: T) => 1}) value!: number; } `, ); verifyThrownError( ErrorCode.VALUE_HAS_WRONG_TYPE, `Input transform function cannot be generic`, ); }); it('should produce a diangostic if there is a conflicting coercion member', () => { env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; @Directive({selector: '[dir]', standalone: true}) export class Dir { @Input({transform: (val: string) => 1}) value!: number; static ngAcceptInputType_value: boolean; } `, ); verifyThrownError( ErrorCode.CONFLICTING_INPUT_TRANSFORM, `Class cannot have both a transform function on Input value and a static member called ngAcceptInputType_value`, ); }); it('should produce a diangostic if the transform function type cannot be referenced from the source file', () => { env.write( '/util.ts', ` interface InternalType { foo: boolean; } export function toNumber(val: InternalType) { return 1; } `, ); env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; import {toNumber} from './util'; @Directive({selector: '[dir]', standalone: true}) export class Dir { @Input({transform: toNumber}) value!: number; } `, ); verifyThrownError( ErrorCode.IMPORT_GENERATION_FAILURE, 'Unable to import type InternalType.', ); }); it('should produce a diangostic if a sub-type of the transform function cannot be referenced from the source file', () => { env.write( '/util.ts', ` interface InternalType { foo: boolean; } export function toNumber(val: {value: InternalType}) { return 1; } `, ); env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; import {toNumber} from './util'; @Directive({selector: '[dir]', standalone: true}) export class Dir { @Input({transform: toNumber}) value!: number; } `, ); verifyThrownError( ErrorCode.IMPORT_GENERATION_FAILURE, 'Unable to import type InternalType.', ); }); it('should produce a diangostic if a generic parameter of the transform function cannot be referenced from the source file', () => { env.write( '/util.ts', ` export interface GenericWrapper<T> { value: T; }
{ "end_byte": 90567, "start_byte": 80925, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_90575_97902
interface InternalType { foo: boolean; } export function toNumber(val: GenericWrapper<InternalType>) { return 1; } `, ); env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; import {toNumber} from './util'; @Directive({selector: '[dir]', standalone: true}) export class Dir { @Input({transform: toNumber}) value!: number; } `, ); verifyThrownError( ErrorCode.IMPORT_GENERATION_FAILURE, 'Unable to import type InternalType.', ); }); it('should produce a diangostic if transform type is not exported', () => { env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; interface InternalType { foo: boolean; } @Directive({selector: '[dir]', standalone: true}) export class Dir { @Input({transform: (val: InternalType) => 1}) val!: number; } `, ); verifyThrownError( ErrorCode.SYMBOL_NOT_EXPORTED, 'Symbol must be exported in order to be used as the type of an Input transform function', ); }); it('should produce a diangostic if the transform value is not a function', () => { env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; function createTransform(outerValue: number) { return (innerValue: string) => outerValue; } @Directive({selector: '[dir]', standalone: true}) export class Dir { @Input({transform: createTransform(1)}) value!: number; } `, ); verifyThrownError(ErrorCode.VALUE_HAS_WRONG_TYPE, `Input transform must be a function`); }); it('should produce a diangostic if the first parameter of a transform is a spread', () => { env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; function toNumber(...value: (string | boolean)[]) { return 1; } @Directive({standalone: true}) export class Dir { @Input({transform: toNumber}) value!: number; } `, ); verifyThrownError( ErrorCode.VALUE_HAS_WRONG_TYPE, `Input transform function first parameter cannot be a spread parameter`, ); }); it('should produce a diangostic if a transform function has multiple signatures', () => { env.write( '/test.ts', ` import {Directive, Input} from '@angular/core'; function toNumber(value: boolean): number; function toNumber(value: string): number; function toNumber(value: boolean | string) { return 1; } @Directive({standalone: true}) export class Dir { @Input({transform: toNumber}) value!: number; } `, ); verifyThrownError( ErrorCode.VALUE_HAS_WRONG_TYPE, `Input transform function cannot have multiple signatures`, ); }); }); describe('multiple decorators on classes', () => { it('should compile @Injectable on Components, Directives, Pipes, and Modules', () => { env.write( 'test.ts', ` import {Component, Directive, Injectable, NgModule, Pipe} from '@angular/core'; @Component({ selector: 'test', template: 'test', standalone: false, }) @Injectable() export class TestCmp {} @Directive({ selector: 'test', standalone: false, }) @Injectable() export class TestDir {} @Pipe({ name: 'test', standalone: false, }) @Injectable() export class TestPipe {} @NgModule({declarations: [TestCmp, TestDir, TestPipe]}) @Injectable() export class TestNgModule {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const dtsContents = env.getContents('test.d.ts'); // Validate that each class has the primary definition. expect(jsContents).toContain('TestCmp.ɵcmp ='); expect(jsContents).toContain('TestDir.ɵdir ='); expect(jsContents).toContain('TestPipe.ɵpipe ='); expect(jsContents).toContain('TestNgModule.ɵmod ='); // Validate that each class also has an injectable definition. expect(jsContents).toContain('TestCmp.ɵprov ='); expect(jsContents).toContain('TestDir.ɵprov ='); expect(jsContents).toContain('TestPipe.ɵprov ='); expect(jsContents).toContain('TestNgModule.ɵprov ='); // Validate that each class's .d.ts declaration has the primary definition. expect(dtsContents).toContain('ComponentDeclaration<TestCmp'); expect(dtsContents).toContain('DirectiveDeclaration<TestDir'); expect(dtsContents).toContain('PipeDeclaration<TestPipe'); expect(dtsContents).toContain('ɵɵNgModuleDeclaration<TestNgModule'); // Validate that each class's .d.ts declaration also has an injectable // definition. expect(dtsContents).toContain('ɵɵInjectableDeclaration<TestCmp'); expect(dtsContents).toContain('ɵɵInjectableDeclaration<TestDir'); expect(dtsContents).toContain('ɵɵInjectableDeclaration<TestPipe'); expect(dtsContents).toContain('ɵɵInjectableDeclaration<TestNgModule'); }); it('should not compile a component and a directive annotation on the same class', () => { env.write( 'test.ts', ` import {Component, Directive} from '@angular/core'; @Component({ selector: 'test', template: 'test', standalone: false, }) @Directive({selector: 'test'}) class ShouldNotCompile {} `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); expect(errors[0].messageText).toContain('Two incompatible decorators on class'); }); it('should leave decorators present on jit: true directives', () => { env.write( 'test.ts', ` import {Directive, Inject} from '@angular/core'; @Directive({ selector: 'test', jit: true, standalone: false, }) export class Test { constructor(@Inject('foo') foo: string) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('Directive({'); expect(jsContents).toContain( ` { type: String, decorators: [{ type: Inject, args: ['foo',] }] }`, ); }); }); describe('compiling invalid @Injectables', () => { describe('with strictInjectionParameters = true', () => { it('should give a compile-time error if an invalid @Injectable is used with no arguments', () => { env.tsconfig({strictInjectionParameters: true}); env.write(
{ "end_byte": 97902, "start_byte": 90575, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_97908_106331
'test.ts', ` import {Injectable} from '@angular/core'; @Injectable() export class Test { constructor(private notInjectable: string) {} } `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); expect(ts.flattenDiagnosticMessageText(errors[0].messageText, '\n')).toBe( `No suitable injection token for parameter 'notInjectable' of class 'Test'.\n` + ` Consider using the @Inject decorator to specify an injection token.`, ); expect(errors[0].relatedInformation!.length).toBe(1); expect(errors[0].relatedInformation![0].messageText).toBe( 'This type is not supported as injection token.', ); }); it('should give a compile-time error if an invalid @Injectable is used with an argument', () => { env.tsconfig({strictInjectionParameters: true}); env.write( 'test.ts', ` import {Injectable} from '@angular/core'; @Injectable({providedIn: 'root'}) export class Test { constructor(private notInjectable: string) {} } `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); expect(ts.flattenDiagnosticMessageText(errors[0].messageText, '\n')).toBe( `No suitable injection token for parameter 'notInjectable' of class 'Test'.\n` + ` Consider using the @Inject decorator to specify an injection token.`, ); expect(errors[0].relatedInformation!.length).toBe(1); expect(errors[0].relatedInformation![0].messageText).toBe( 'This type is not supported as injection token.', ); }); it('should report an error when using a symbol from a type-only import clause as injection token', () => { env.tsconfig({strictInjectionParameters: true}); env.write( `types.ts`, ` export class TypeOnly {} `, ); env.write( `test.ts`, ` import {Injectable} from '@angular/core'; import type {TypeOnly} from './types'; @Injectable() export class MyService { constructor(param: TypeOnly) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '\n')).toBe( `No suitable injection token for parameter 'param' of class 'MyService'.\n` + ` Consider changing the type-only import to a regular import, ` + `or use the @Inject decorator to specify an injection token.`, ); expect(diags[0].relatedInformation!.length).toBe(2); expect(diags[0].relatedInformation![0].messageText).toBe( 'This type is imported using a type-only import, ' + 'which prevents it from being usable as an injection token.', ); expect(diags[0].relatedInformation![1].messageText).toBe( 'The type-only import occurs here.', ); }); it('should report an error when using a symbol from a type-only import specifier as injection token', () => { env.tsconfig({strictInjectionParameters: true}); env.write( `types.ts`, ` export class TypeOnly {} `, ); env.write( `test.ts`, ` import {Injectable} from '@angular/core'; import {type TypeOnly} from './types'; @Injectable() export class MyService { constructor(param: TypeOnly) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '\n')).toBe( `No suitable injection token for parameter 'param' of class 'MyService'.\n` + ` Consider changing the type-only import to a regular import, ` + `or use the @Inject decorator to specify an injection token.`, ); expect(diags[0].relatedInformation!.length).toBe(2); expect(diags[0].relatedInformation![0].messageText).toBe( 'This type is imported using a type-only import, ' + 'which prevents it from being usable as an injection token.', ); expect(diags[0].relatedInformation![1].messageText).toBe( 'The type-only import occurs here.', ); }); it('should report an error when using a primitive type as injection token', () => { env.tsconfig({strictInjectionParameters: true}); env.write( `test.ts`, ` import {Injectable} from '@angular/core'; @Injectable() export class MyService { constructor(param: string) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '\n')).toBe( `No suitable injection token for parameter 'param' of class 'MyService'.\n` + ` Consider using the @Inject decorator to specify an injection token.`, ); expect(diags[0].relatedInformation!.length).toBe(1); expect(diags[0].relatedInformation![0].messageText).toBe( 'This type is not supported as injection token.', ); }); it('should report an error when using a union type as injection token', () => { env.tsconfig({strictInjectionParameters: true}); env.write( `test.ts`, ` import {Injectable} from '@angular/core'; export class ClassA {} export class ClassB {} @Injectable() export class MyService { constructor(param: ClassA|ClassB) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '\n')).toBe( `No suitable injection token for parameter 'param' of class 'MyService'.\n` + ` Consider using the @Inject decorator to specify an injection token.`, ); expect(diags[0].relatedInformation!.length).toBe(1); expect(diags[0].relatedInformation![0].messageText).toBe( 'This type is not supported as injection token.', ); }); it('should report an error when using an interface as injection token', () => { env.tsconfig({strictInjectionParameters: true}); env.write( `test.ts`, ` import {Injectable} from '@angular/core'; export interface Interface {} @Injectable() export class MyService { constructor(param: Interface) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '\n')).toBe( `No suitable injection token for parameter 'param' of class 'MyService'.\n` + ` Consider using the @Inject decorator to specify an injection token.`, ); expect(diags[0].relatedInformation!.length).toBe(2); expect(diags[0].relatedInformation![0].messageText).toBe( 'This type does not have a value, so it cannot be used as injection token.', ); expect(diags[0].relatedInformation![1].messageText).toBe('The type is declared here.'); }); it('should report an error when using a missing type as injection token', () => { // This test replicates the situation where a symbol does not have any // declarations at all, e.g. because it's imported from a missing module. This // would result in a semantic TypeScrip
{ "end_byte": 106331, "start_byte": 97908, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_106341_115927
ic which we ignore in this // test to verify that ngtsc's analysis is able to operate in this situation. env.tsconfig({strictInjectionParameters: true}); env.write( `test.ts`, ` import {Injectable} from '@angular/core'; // @ts-expect-error import {Interface} from 'missing'; @Injectable() export class MyService { constructor(param: Interface) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '\n')).toBe( `No suitable injection token for parameter 'param' of ` + `class 'MyService'.\n` + ` Consider using the @Inject decorator to specify an injection token.`, ); expect(diags[0].relatedInformation!.length).toBe(1); expect(diags[0].relatedInformation![0].messageText).toBe( 'This type does not have a value, so it cannot be used as injection token.', ); }); it('should report an error when no type is present', () => { env.tsconfig({strictInjectionParameters: true, noImplicitAny: false}); env.write( `test.ts`, ` import {Injectable} from '@angular/core'; @Injectable() export class MyService { constructor(param) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '\n')).toBe( `No suitable injection token for parameter 'param' of class 'MyService'.\n` + ` Consider adding a type to the parameter or ` + `use the @Inject decorator to specify an injection token.`, ); expect(diags[0].relatedInformation).toBeUndefined(); }); it('should not give a compile-time error if an invalid @Injectable is used with useValue', () => { env.tsconfig({strictInjectionParameters: true}); env.write( 'test.ts', ` import {Injectable} from '@angular/core'; @Injectable({ providedIn: 'root', useValue: '42', }) export class Test { constructor(private notInjectable: string) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toMatch( /function Test_Factory\(__ngFactoryType__\) { i0\.ɵɵinvalidFactory\(\)/m, ); }); it('should not give a compile-time error if an invalid @Injectable is used with useFactory', () => { env.tsconfig({strictInjectionParameters: true}); env.write( 'test.ts', ` import {Injectable} from '@angular/core'; @Injectable({ providedIn: 'root', useFactory: () => '42', }) export class Test { constructor(private notInjectable: string) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toMatch( /function Test_Factory\(__ngFactoryType__\) { i0\.ɵɵinvalidFactory\(\)/m, ); }); it('should not give a compile-time error if an invalid @Injectable is used with useExisting', () => { env.tsconfig({strictInjectionParameters: true}); env.write( 'test.ts', ` import {Injectable} from '@angular/core'; export class MyService {} @Injectable({ providedIn: 'root', useExisting: MyService, }) export class Test { constructor(private notInjectable: string) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toMatch( /function Test_Factory\(__ngFactoryType__\) { i0\.ɵɵinvalidFactory\(\)/m, ); }); it('should not give a compile-time error if an invalid @Injectable is used with useClass', () => { env.tsconfig({strictInjectionParameters: true}); env.write( 'test.ts', ` import {Injectable} from '@angular/core'; export class MyService {} @Injectable({ providedIn: 'root', useClass: MyService, }) export class Test { constructor(private notInjectable: string) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toMatch( /function Test_Factory\(__ngFactoryType__\) { i0\.ɵɵinvalidFactory\(\)/m, ); }); it('should not give a compile-time error if an invalid @Injectable without providedIn is an abstract class', () => { env.tsconfig({strictInjectionParameters: true}); env.write( 'test.ts', ` import {Injectable} from '@angular/core'; @Injectable() export abstract class Test { constructor(private notInjectable: string) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toMatch( /function Test_Factory\(__ngFactoryType__\) { i0\.ɵɵinvalidFactory\(\)/m, ); }); it('should not give a compile-time error if an invalid @Injectable with providedIn is an abstract class', () => { env.tsconfig({strictInjectionParameters: true}); env.write( 'test.ts', ` import {Injectable} from '@angular/core'; @Injectable({ providedIn: 'root', }) export abstract class Test { constructor(private notInjectable: string) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toMatch( /function Test_Factory\(__ngFactoryType__\) { i0\.ɵɵinvalidFactory\(\)/m, ); }); it('should give a compile-time error when a derived Directive inherits an invalid constructor', () => { env.tsconfig({strictInjectionParameters: true}); env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive() export abstract class ParentDir { constructor(private notInjectable: string) {} } @Directive() export abstract class AbstractMiddleDir extends ParentDir {} @Directive() export class ConcreteMiddleDir extends AbstractMiddleDir {} @Directive() export class ConcreteDirWithoutCtor extends ConcreteMiddleDir {} @Directive() export class ConcreteDirWithCtor extends ConcreteMiddleDir { constructor() { super('correct'); } } @Directive() export class ConcreteDerivedDirWithoutCtor extends ConcreteDirWithCtor {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].code).toBe( ngErrorCode(ErrorCode.INJECTABLE_INHERITS_INVALID_CONSTRUCTOR), ); expect(diags[0].messageText).toEqual( `The directive ConcreteMiddleDir inherits its constructor from ParentDir, but the latter has ` + `a constructor parameter that is not compatible with dependency injection. Either add an explicit ` + `constructor to ConcreteMiddleDir or change ParentDir's constructor to use parameters that are ` + `valid for DI.`, ); expect(getDiagnosticSourceCode(diags[0])).toBe('ConcreteMiddleDir'); expect(diags[1].code).toBe( ngErrorCode(ErrorCode.INJECTABLE_INHERITS_INVALID_CONSTRUCTOR), ); expect(diags[1].messageText).toEqual( `The directive ConcreteDirWithoutCtor inherits its constructor from ParentDir, but the latter ` + `has a constructor parameter that is not compatible with dependency injection. Either add an ` + `explicit constructor to ConcreteDirWithoutCtor or change ParentDir's constructor to use ` + `parameters that are valid for DI.`, ); expect(getDiagnosticSourceCode(diags[1])).toBe('ConcreteDirWithoutCtor'); }); it('should give a compile-time error when a derived Injectable inherits an invalid constructor', () => { env.tsconfig({strictInjectionParameters: true}); env.write( 'test.ts', ` import {Injectable} from '@angular/core'; @Injectable()
{ "end_byte": 115927, "start_byte": 106341, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_115937_124305
export abstract class ParentService { constructor(private notInjectable: string) {} } @Injectable() export abstract class AbstractMiddleService extends ParentService {} @Injectable() export class ConcreteMiddleService extends AbstractMiddleService {} @Injectable() export class ConcreteServiceWithoutCtor extends ConcreteMiddleService {} @Injectable() export class ConcreteServiceWithCtor extends ConcreteMiddleService { constructor() { super('correct'); } } @Injectable() export class ConcreteDerivedServiceWithoutCtor extends ConcreteServiceWithCtor {} @Injectable({ providedIn: 'root' }) export class ProvidedInRootService extends ParentService {} @Injectable({ providedIn: 'root', useFactory: () => null }) export class UseFactoryService extends ParentService {} @Injectable({ providedIn: 'root', useValue: null }) export class UseValueService extends ParentService {} @Injectable({ providedIn: 'root', useClass: ConcreteServiceWithCtor }) export class UseClassService extends ParentService {} @Injectable({ providedIn: 'root', useExisting: ConcreteServiceWithCtor }) export class UseExistingService extends ParentService {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(3); expect(diags[0].code).toBe( ngErrorCode(ErrorCode.INJECTABLE_INHERITS_INVALID_CONSTRUCTOR), ); expect(diags[0].messageText).toEqual( `The injectable ConcreteMiddleService inherits its constructor from ParentService, but the ` + `latter has a constructor parameter that is not compatible with dependency injection. Either add ` + `an explicit constructor to ConcreteMiddleService or change ParentService's constructor to use ` + `parameters that are valid for DI.`, ); expect(getDiagnosticSourceCode(diags[0])).toBe('ConcreteMiddleService'); expect(diags[1].code).toBe( ngErrorCode(ErrorCode.INJECTABLE_INHERITS_INVALID_CONSTRUCTOR), ); expect(diags[1].messageText).toEqual( `The injectable ConcreteServiceWithoutCtor inherits its constructor from ParentService, but the ` + `latter has a constructor parameter that is not compatible with dependency injection. Either add ` + `an explicit constructor to ConcreteServiceWithoutCtor or change ParentService's constructor to ` + `use parameters that are valid for DI.`, ); expect(getDiagnosticSourceCode(diags[1])).toBe('ConcreteServiceWithoutCtor'); expect(diags[2].code).toBe( ngErrorCode(ErrorCode.INJECTABLE_INHERITS_INVALID_CONSTRUCTOR), ); expect(diags[2].messageText).toEqual( `The injectable ProvidedInRootService inherits its constructor from ParentService, but the ` + `latter has a constructor parameter that is not compatible with dependency injection. Either add ` + `an explicit constructor to ProvidedInRootService or change ParentService's constructor to use ` + `parameters that are valid for DI.`, ); expect(getDiagnosticSourceCode(diags[2])).toBe('ProvidedInRootService'); }); it('should give a compile-time error when a derived Directive inherits from a non-decorated class', () => { env.tsconfig({strictInjectionParameters: true}); env.write( 'test.ts', ` import {Directive} from '@angular/core'; export abstract class ParentClass { constructor(private notInjectable: string) {} } @Directive() export abstract class AbstractMiddleDir extends ParentClass {} @Directive() export class ConcreteMiddleDir extends AbstractMiddleDir {} @Directive() export class ConcreteDirWithoutCtor extends ConcreteMiddleDir {} @Directive() export class ConcreteDirWithCtor extends ConcreteMiddleDir { constructor() { super('correct'); } } @Directive() export class ConcreteDerivedDirWithoutCtor extends ConcreteDirWithCtor {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(3); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.DIRECTIVE_INHERITS_UNDECORATED_CTOR)); expect(diags[0].messageText).toEqual( `The directive AbstractMiddleDir inherits its constructor from ParentClass, but the latter ` + `does not have an Angular decorator of its own. Dependency injection will not be able to resolve ` + `the parameters of ParentClass's constructor. Either add a @Directive decorator to ParentClass, ` + `or add an explicit constructor to AbstractMiddleDir.`, ); expect(getDiagnosticSourceCode(diags[0])).toBe('AbstractMiddleDir'); expect(diags[1].code).toBe(ngErrorCode(ErrorCode.DIRECTIVE_INHERITS_UNDECORATED_CTOR)); expect(diags[1].messageText).toEqual( `The directive ConcreteMiddleDir inherits its constructor from ParentClass, but the latter ` + `does not have an Angular decorator of its own. Dependency injection will not be able to resolve ` + `the parameters of ParentClass's constructor. Either add a @Directive decorator to ParentClass, or ` + `add an explicit constructor to ConcreteMiddleDir.`, ); expect(getDiagnosticSourceCode(diags[1])).toBe('ConcreteMiddleDir'); expect(diags[2].code).toBe(ngErrorCode(ErrorCode.DIRECTIVE_INHERITS_UNDECORATED_CTOR)); expect(diags[2].messageText).toEqual( `The directive ConcreteDirWithoutCtor inherits its constructor from ParentClass, but the latter ` + `does not have an Angular decorator of its own. Dependency injection will not be able to resolve ` + `the parameters of ParentClass's constructor. Either add a @Directive decorator to ParentClass, ` + `or add an explicit constructor to ConcreteDirWithoutCtor.`, ); expect(getDiagnosticSourceCode(diags[2])).toBe('ConcreteDirWithoutCtor'); }); // https://github.com/angular/angular/issues/48152 it('should not give a compile-time error when a class inherits from foreign compilation unit', () => { env.tsconfig({strictInjectionParameters: true}); env.write( 'node_modules/external/index.d.ts', ` import * as i0 from '@angular/core'; export abstract class ExternalClass { static ɵprov: i0.ɵɵInjectableDeclaration<ExternalClass>; static ɵfac: i0.ɵɵFactoryDeclaration<ExternalClass, never> constructor(invalid: string) {} } `, ); env.write( 'test.ts', ` import {Directive} from '@angular/core'; import {ExternalClass} from 'external'; @Directive() export abstract class AbstractMiddleDir extends ExternalClass {} @Directive() export class ConcreteMiddleDir extends AbstractMiddleDir {} @Directive() export class ConcreteDirWithoutCtor extends ConcreteMiddleDir {} `, ); env.driveMain(); }); }); describe('with strictInjectionParameters = false', () => { it('should compile an @Injectable on a class with a non-injectable constructor', () => { env.tsconfig({strictInjectionParameters: false}); env.write( 'test.ts', ` import {Injectable} from '@angular/
{ "end_byte": 124305, "start_byte": 115937, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_124313_134284
@Injectable() export class Test { constructor(private notInjectable: string) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'Test.ɵfac = function Test_Factory(__ngFactoryType__) { i0.ɵɵinvalidFactory()', ); }); it('should compile an @Injectable provided in the root on a class with a non-injectable constructor', () => { env.tsconfig({strictInjectionParameters: false}); env.write( 'test.ts', ` import {Injectable} from '@angular/core'; @Injectable({providedIn: 'root'}) export class Test { constructor(private notInjectable: string) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'Test.ɵfac = function Test_Factory(__ngFactoryType__) { i0.ɵɵinvalidFactory()', ); }); it('should compile when a derived Directive inherits an invalid constructor', () => { env.tsconfig({strictInjectionParameters: false}); env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive() export abstract class ParentDir { constructor(private notInjectable: string) {} } @Directive() export abstract class AbstractMiddleDir extends ParentDir {} @Directive() export class ConcreteMiddleDir extends AbstractMiddleDir {} @Directive() export class ConcreteDirWithoutCtor extends ConcreteMiddleDir {} @Directive() export class ConcreteDirWithCtor extends ConcreteMiddleDir { constructor() { super('correct'); } } @Directive() export class ConcreteDerivedDirWithoutCtor extends ConcreteDirWithCtor {} `, ); env.driveMain(); }); it('should compile when a derived Injectable inherits an invalid constructor', () => { env.tsconfig({strictInjectionParameters: false}); env.write( 'test.ts', ` import {Injectable} from '@angular/core'; @Injectable() export abstract class ParentService { constructor(private notInjectable: string) {} } @Injectable() export abstract class AbstractMiddleService extends ParentService {} @Injectable() export class ConcreteMiddleService extends AbstractMiddleService {} @Injectable() export class ConcreteServiceWithoutCtor extends ConcreteMiddleService {} @Injectable() export class ConcreteServiceWithCtor extends ConcreteMiddleService { constructor() { super('correct'); } } @Injectable() export class ConcreteDerivedServiceWithoutCtor extends ConcreteServiceWithCtor {} @Injectable({ providedIn: 'root' }) export class ProvidedInRootService extends ParentService {} @Injectable({ providedIn: 'root', useFactory: () => null }) export class UseFactoryService extends ParentService {} @Injectable({ providedIn: 'root', useValue: null }) export class UseValueService extends ParentService {} @Injectable({ providedIn: 'root', useClass: ConcreteServiceWithCtor }) export class UseClassService extends ParentService {} @Injectable({ providedIn: 'root', useExisting: ConcreteServiceWithCtor }) export class UseExistingService extends ParentService {} `, ); env.driveMain(); }); it('should give a compile-time error when a derived Directive inherits from a non-decorated class', () => { // Errors for undecorated base classes should always be reported, even under // `strictInjectionParameters`. env.tsconfig({strictInjectionParameters: false}); env.write( 'test.ts', ` import {Directive} from '@angular/core'; export abstract class ParentClass { constructor(private notInjectable: string) {} } @Directive() export abstract class AbstractMiddleDir extends ParentClass {} @Directive() export class ConcreteMiddleDir extends AbstractMiddleDir {} @Directive() export class ConcreteDirWithoutCtor extends ConcreteMiddleDir {} @Directive() export class ConcreteDirWithCtor extends ConcreteMiddleDir { constructor() { super('correct'); } } @Directive() export class ConcreteDerivedDirWithoutCtor extends ConcreteDirWithCtor {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(3); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.DIRECTIVE_INHERITS_UNDECORATED_CTOR)); expect(diags[0].messageText).toEqual( `The directive AbstractMiddleDir inherits its constructor from ParentClass, but the latter ` + `does not have an Angular decorator of its own. Dependency injection will not be able to resolve ` + `the parameters of ParentClass's constructor. Either add a @Directive decorator to ParentClass, ` + `or add an explicit constructor to AbstractMiddleDir.`, ); expect(getDiagnosticSourceCode(diags[0])).toBe('AbstractMiddleDir'); expect(diags[1].code).toBe(ngErrorCode(ErrorCode.DIRECTIVE_INHERITS_UNDECORATED_CTOR)); expect(diags[1].messageText).toEqual( `The directive ConcreteMiddleDir inherits its constructor from ParentClass, but the latter ` + `does not have an Angular decorator of its own. Dependency injection will not be able to resolve ` + `the parameters of ParentClass's constructor. Either add a @Directive decorator to ParentClass, ` + `or add an explicit constructor to ConcreteMiddleDir.`, ); expect(getDiagnosticSourceCode(diags[1])).toBe('ConcreteMiddleDir'); expect(diags[2].code).toBe(ngErrorCode(ErrorCode.DIRECTIVE_INHERITS_UNDECORATED_CTOR)); expect(diags[2].messageText).toEqual( `The directive ConcreteDirWithoutCtor inherits its constructor from ParentClass, but the latter ` + `does not have an Angular decorator of its own. Dependency injection will not be able to resolve ` + `the parameters of ParentClass's constructor. Either add a @Directive decorator to ParentClass, ` + `or add an explicit constructor to ConcreteDirWithoutCtor.`, ); expect(getDiagnosticSourceCode(diags[2])).toBe('ConcreteDirWithoutCtor'); }); }); }); describe('compiling invalid @Directives', () => { describe('directives with a selector', () => { it('should give a compile-time error if an invalid constructor is used', () => { env.tsconfig({strictInjectionParameters: true}); env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive({selector: 'app-test'}) export class Test { constructor(private notInjectable: string) {} } `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); expect(ts.flattenDiagnosticMessageText(errors[0].messageText, '\n')).toContain( 'No suitable injection token for parameter', ); }); }); describe('abstract directives', () => { it('should generate a factory function that throws', () => { env.tsconfig({strictInjectionParameters: false}); env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive() export class Test { constructor(private notInjectable: string) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'Test.ɵfac = function Test_Factory(__ngFactoryType__) { i0.ɵɵinvalidFactory()', ); }); }); it('should generate a factory function that throws, even under strictInjectionParameters', () => { env.tsconfig({strictInjectionParameters: true}); env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive() export class Test { constructor(private notInjectable: string) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'Test.ɵfac = function Test_Factory(__ngFactoryType__) { i0.ɵɵinvalidFactory()', ); }); }); describe('templateUrl and styleUrls processing', () => { const testsForResource = (resource: string) => [ // [component location, resource location, resource reference] // component and resource are in the same folder [`a/app.ts`, `a/${resource}`, `./${resource}`], // [`a/app.ts`, `a/${resource}
{ "end_byte": 134284, "start_byte": 124313, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_134290_137810
ource], // [`a/app.ts`, `a/${resource}`, `/a/${resource}`], // resource is one level up [`a/app.ts`, resource, `../${resource}`], // [`a/app.ts`, resource, `/${resource}`], // component and resource are in different folders [`a/app.ts`, `b/${resource}`, `../b/${resource}`], // [`a/app.ts`, `b/${resource}`, `/b/${resource}`], // resource is in subfolder of component directory [`a/app.ts`, `a/b/c/${resource}`, `./b/c/${resource}`], // [`a/app.ts`, `a/b/c/${resource}`, `b/c/${resource}`], // [`a/app.ts`, `a/b/c/${resource}`, `/a/b/c/${resource}`], ]; testsForResource('style.css').forEach((test) => { const [compLoc, styleLoc, styleRef] = test; it(`should handle ${styleRef}`, () => { env.write(styleLoc, ':host { background-color: blue; }'); env.write( compLoc, ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', styleUrls: ['${styleRef}'], template: '...', }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents(compLoc.replace('.ts', '.js')); expect(jsContents).toContain('background-color: blue'); }); }); testsForResource('template.html').forEach((test) => { const [compLoc, templateLoc, templateRef] = test; it(`should handle ${templateRef}`, () => { env.write(templateLoc, 'Template Content'); env.write( compLoc, ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', templateUrl: '${templateRef}' }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents(compLoc.replace('.ts', '.js')); expect(jsContents).toContain('Template Content'); }); }); }); describe('former View Engine AST transform bugs', () => { it('should compile array literals behind conditionals', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '{{value ? "yes" : [no]}}', }) class TestCmp { value = true; no = 'no'; } `, ); env.driveMain(); expect(env.getContents('test.js')).toContain('i0.ɵɵpureFunction1'); }); it('should compile array literals inside function arguments', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '{{fn([test])}}', }) class TestCmp { fn(arg: any): string { return 'test'; } test = 'test'; } `, ); env.driveMain(); expect(env.getContents('test.js')).toContain('i0.ɵɵpureFunction1'); }); }); describe('unwrapping ModuleWithProviders functions', () => { it('should use a local ModuleWithProviders-annotated return type if a function is not statically analyzable', () => { env.write( `module.ts`, ` import {NgModule, ModuleWithProviders} from '@angular/core'; export functio
{ "end_byte": 137810, "start_byte": 134290, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_137816_146822
taticallyAnalyzable(): ModuleWithProviders<SomeModule> { console.log('this interferes with static analysis'); return { ngModule: SomeModule, providers: [], }; } @NgModule() export class SomeModule {} `, ); env.write( 'test.ts', ` import {NgModule} from '@angular/core'; import {notStaticallyAnalyzable} from './module'; @NgModule({ imports: [notStaticallyAnalyzable()] }) export class TestModule {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('imports: [notStaticallyAnalyzable()]'); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain(`import * as i1 from "./module";`); expect(dtsContents).toContain( 'i0.ɵɵNgModuleDeclaration<TestModule, never, [typeof i1.SomeModule], never>', ); }); it("should extract the generic type and include it in the module's declaration", () => { env.write( `test.ts`, ` import {NgModule} from '@angular/core'; import {RouterModule} from 'router'; @NgModule({imports: [RouterModule.forRoot()]}) export class TestModule {} `, ); env.write( 'node_modules/router/index.d.ts', ` import {ModuleWithProviders, ɵɵNgModuleDeclaration} from '@angular/core'; declare class RouterModule { static forRoot(): ModuleWithProviders<RouterModule>; static ɵmod: ɵɵNgModuleDeclaration<RouterModule, never, never, never>; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('imports: [RouterModule.forRoot()]'); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain(`import * as i1 from "router";`); expect(dtsContents).toContain( 'i0.ɵɵNgModuleDeclaration<TestModule, never, [typeof i1.RouterModule], never>', ); }); it('should throw if ModuleWithProviders is missing its generic type argument', () => { env.write( `test.ts`, ` import {NgModule} from '@angular/core'; import {RouterModule} from 'router'; @NgModule({imports: [RouterModule.forRoot()]}) export class TestModule {} `, ); env.write( 'node_modules/router/index.d.ts', ` import {ModuleWithProviders, ɵɵNgModuleDeclaration} from '@angular/core'; declare class RouterModule { static forRoot(): ModuleWithProviders; static ɵmod: ɵɵNgModuleDeclaration<RouterModule, never, never, never>; } `, ); const errors = env.driveDiagnostics(); expect(trim(errors[0].messageText as string)).toContain( `RouterModule.forRoot returns a ModuleWithProviders type without a generic type argument. ` + `Please add a generic type argument to the ModuleWithProviders type. If this ` + `occurrence is in library code you don't control, please contact the library authors.`, ); }); it('should extract the generic type if it is provided as qualified type name', () => { env.write( `test.ts`, ` import {NgModule} from '@angular/core'; import {RouterModule} from 'router'; @NgModule({imports: [RouterModule.forRoot()]}) export class TestModule {} `, ); env.write( 'node_modules/router/index.d.ts', ` import {ModuleWithProviders} from '@angular/core'; import * as internal from './internal'; export {InternalRouterModule} from './internal'; declare export class RouterModule { static forRoot(): ModuleWithProviders<internal.InternalRouterModule>; } `, ); env.write( 'node_modules/router/internal.d.ts', ` import {ɵɵNgModuleDeclaration} from '@angular/core'; export declare class InternalRouterModule { static ɵmod: ɵɵNgModuleDeclaration<InternalRouterModule, never, never, never>; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('imports: [RouterModule.forRoot()]'); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain(`import * as i1 from "router";`); expect(dtsContents).toContain( 'i0.ɵɵNgModuleDeclaration<TestModule, never, [typeof i1.InternalRouterModule], never>', ); }); it('should extract the generic type if it is provided as qualified type name from another package', () => { env.write( `test.ts`, ` import {NgModule} from '@angular/core'; import {RouterModule} from 'router'; @NgModule({imports: [RouterModule.forRoot()]}) export class TestModule {}`, ); env.write( 'node_modules/router/index.d.ts', ` import {ModuleWithProviders} from '@angular/core'; import * as router2 from 'router2'; declare export class RouterModule { static forRoot(): ModuleWithProviders<router2.Router2Module>; }`, ); env.write( 'node_modules/router2/index.d.ts', ` import {ɵɵNgModuleDeclaration} from '@angular/core'; export declare class Router2Module { static ɵmod: ɵɵNgModuleDeclaration<Router2Module, never, never, never>; }`, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('imports: [RouterModule.forRoot()]'); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain(`import * as i1 from "router2";`); expect(dtsContents).toContain( 'i0.ɵɵNgModuleDeclaration<TestModule, never, [typeof i1.Router2Module], never>', ); }); it('should not reference a constant with a ModuleWithProviders value in module def imports', () => { env.write( 'dep.d.ts', ` import {ModuleWithProviders, ɵɵNgModuleDeclaration as ɵɵNgModuleDeclaration} from '@angular/core'; export declare class DepModule { static forRoot(arg1: any, arg2: any): ModuleWithProviders<DepModule>; static ɵmod: ɵɵNgModuleDeclaration<DepModule, never, never, never>; } `, ); env.write( 'test.ts', ` import {NgModule, ModuleWithProviders} from '@angular/core'; import {DepModule} from './dep'; @NgModule({}) export class Base {} const mwp = DepModule.forRoot(1,2); @NgModule({ imports: [mwp], }) export class Module {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('imports: [i1.DepModule]'); }); }); it('should unwrap a ModuleWithProviders-like function if a matching literal type is provided for it', () => { env.write( `test.ts`, ` import {NgModule} from '@angular/core'; import {RouterModule} from 'router'; @NgModule({imports: [RouterModule.forRoot()]}) export class TestModule {} `, ); env.write( 'node_modules/router/index.d.ts', ` import {ModuleWithProviders, ɵɵNgModuleDeclaration} from '@angular/core'; export interface MyType extends ModuleWithProviders {} declare class RouterModule { static forRoot(): (MyType)&{ngModule: typeof RouterModule}; static ɵmod: ɵɵNgModuleDeclaration<RouterModule, never, never, never>; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('imports: [RouterModule.forRoot()]'); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain(`import * as i1 from "router";`); expect(dtsContents).toContain( 'i0.ɵɵNgModuleDeclaration<TestModule, never, [typeof i1.RouterModule], never>', ); }); it('should unwrap a namespace imported ModuleWithProviders function if a generic type is provided for it', () => { env.write( `test.ts`, ` import {NgModule} from '@angular/core'; import {RouterModule} from 'router'; @NgModule({imports: [RouterModule.forRoot()]}) export class TestModule {} `, ); env.write(
{ "end_byte": 146822, "start_byte": 137816, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_146828_154760
'node_modules/router/index.d.ts', ` import * as core from '@angular/core'; import {RouterModule} from 'router'; declare class RouterModule { static forRoot(): core.ModuleWithProviders<RouterModule>; static ɵmod: ɵɵNgModuleDeclaration<RouterModule, never, never, never>; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('imports: [RouterModule.forRoot()]'); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain(`import * as i1 from "router";`); expect(dtsContents).toContain( 'i0.ɵɵNgModuleDeclaration<TestModule, never, [typeof i1.RouterModule], never>', ); }); it('should inject special types according to the metadata', () => { env.write( `test.ts`, ` import { Attribute, ChangeDetectorRef, Component, ElementRef, Injector, Renderer2, TemplateRef, ViewContainerRef, } from '@angular/core'; @Component({ selector: 'test', template: 'Test', }) class FooCmp { constructor( @Attribute("test") attr: string, cdr: ChangeDetectorRef, er: ElementRef, i: Injector, r2: Renderer2, tr: TemplateRef<unknown>, vcr: ViewContainerRef, ) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( `FooCmp.ɵfac = function FooCmp_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || FooCmp)(i0.ɵɵinjectAttribute("test"), i0.ɵɵdirectiveInject(i0.ChangeDetectorRef), i0.ɵɵdirectiveInject(i0.ElementRef), i0.ɵɵdirectiveInject(i0.Injector), i0.ɵɵdirectiveInject(i0.Renderer2), i0.ɵɵdirectiveInject(i0.TemplateRef), i0.ɵɵdirectiveInject(i0.ViewContainerRef)); }`, ); }); it('should include constructor dependency metadata for directives/components/pipes', () => { env.write( `test.ts`, ` import {Attribute, Component, Directive, Pipe, Self, SkipSelf, Host, Optional} from '@angular/core'; export class MyService {} export function dynamic() {return ''}; @Directive() export class WithDecorators { constructor( @Self() withSelf: MyService, @SkipSelf() withSkipSelf: MyService, @Host() withHost: MyService, @Optional() withOptional: MyService, @Attribute("attr") withAttribute: string, @Attribute(dynamic()) withAttributeDynamic: string, @Optional() @SkipSelf() @Host() withMany: MyService, noDecorators: MyService) {} } @Directive() export class NoCtor {} @Directive() export class EmptyCtor { constructor() {} } @Directive() export class WithoutDecorators { constructor(noDecorators: MyService) {} } @Component({ template: 'test' }) export class MyCmp { constructor(@Host() withHost: MyService) {} } @Pipe({ name: 'test' }) export class MyPipe { constructor(@Host() withHost: MyService) {} } `, ); env.driveMain(); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain( 'static ɵfac: i0.ɵɵFactoryDeclaration<WithDecorators, [' + '{ self: true; }, { skipSelf: true; }, { host: true; }, ' + '{ optional: true; }, { attribute: "attr"; }, { attribute: unknown; }, ' + '{ optional: true; host: true; skipSelf: true; }, null]>', ); expect(dtsContents).toContain(`static ɵfac: i0.ɵɵFactoryDeclaration<NoCtor, never>`); expect(dtsContents).toContain(`static ɵfac: i0.ɵɵFactoryDeclaration<EmptyCtor, never>`); expect(dtsContents).toContain( `static ɵfac: i0.ɵɵFactoryDeclaration<WithoutDecorators, never>`, ); expect(dtsContents).toContain( `static ɵfac: i0.ɵɵFactoryDeclaration<MyCmp, [{ host: true; }]>`, ); expect(dtsContents).toContain( `static ɵfac: i0.ɵɵFactoryDeclaration<MyPipe, [{ host: true; }]>`, ); }); it('should include constructor dependency metadata for @Injectable', () => { env.write( `test.ts`, ` import {Injectable, Self, Host} from '@angular/core'; export class MyService {} @Injectable() export class Inj { constructor(@Self() service: MyService) {} } @Injectable({ useExisting: MyService, providedIn: 'root' }) export class InjUseExisting { constructor(@Self() service: MyService) {} } @Injectable({ useClass: MyService, providedIn: 'root' }) export class InjUseClass { constructor(@Self() service: MyService) {} } @Injectable({ useClass: MyService, deps: [[new Host(), MyService]], providedIn: 'root' }) export class InjUseClassWithDeps { constructor(@Self() service: MyService) {} } @Injectable({ useFactory: () => new MyService(), providedIn: 'root' }) export class InjUseFactory { constructor(@Self() service: MyService) {} } @Injectable({ useFactory: (service: MyService) => service, deps: [[new Host(), MyService]], providedIn: 'root'}) export class InjUseFactoryWithDeps { constructor(@Self() service: MyService) {} } @Injectable({ useValue: new MyService(), providedIn: 'root' }) export class InjUseValue { constructor(@Self() service: MyService) {} } `, ); env.driveMain(); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain(`static ɵfac: i0.ɵɵFactoryDeclaration<Inj, [{ self: true; }]>`); expect(dtsContents).toContain( `static ɵfac: i0.ɵɵFactoryDeclaration<InjUseExisting, [{ self: true; }]>`, ); expect(dtsContents).toContain( `static ɵfac: i0.ɵɵFactoryDeclaration<InjUseClass, [{ self: true; }]>`, ); expect(dtsContents).toContain( `static ɵfac: i0.ɵɵFactoryDeclaration<InjUseClassWithDeps, [{ self: true; }]>`, ); expect(dtsContents).toContain( `static ɵfac: i0.ɵɵFactoryDeclaration<InjUseFactory, [{ self: true; }]>`, ); expect(dtsContents).toContain( `static ɵfac: i0.ɵɵFactoryDeclaration<InjUseFactoryWithDeps, [{ self: true; }]>`, ); expect(dtsContents).toContain( `static ɵfac: i0.ɵɵFactoryDeclaration<InjUseValue, [{ self: true; }]>`, ); }); it('should include ng-content selectors in the metadata', () => { env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '<ng-content></ng-content> <ng-content select=".foo"></ng-content>', standalone: false, }) export class TestCmp { } `, ); env.driveMain(); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain( 'static ɵcmp: i0.ɵɵComponentDeclaration<TestCmp, "test", never, {}, {}, never, ["*", ".foo"], false, never>', ); }); it('should generate queries for components', () => { env.write( `test.ts`, ` import {Component, ContentChild, ContentChildren, TemplateRef, ViewChild} from '@angular/core'; @Component({ selector: 'test', template: '<div #foo></div>', queries: { 'mview': new ViewChild('test1'), 'mcontent': new ContentChild('test2'), } }) cl
{ "end_byte": 154760, "start_byte": 146828, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_154766_163107
oCmp { @ContentChild('bar', {read: TemplateRef}) child: any; @ContentChildren(TemplateRef) children: any; get aview(): any { return null; } @ViewChild('accessor') set aview(value: any) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toMatch(varRegExp('bar')); expect(jsContents).toMatch(varRegExp('test1')); expect(jsContents).toMatch(varRegExp('test2')); expect(jsContents).toMatch(varRegExp('accessor')); // match `i0.ɵɵcontentQuery(dirIndex, _c1, 5, TemplateRef)` expect(jsContents).toMatch(contentQueryRegExp('\\w+', 5, 'TemplateRef')); // match `i0.ɵɵviewQuery(_c2, 5, null)` expect(jsContents).toMatch(viewQueryRegExp('\\w+', 5)); }); it('should generate queries for directives', () => { env.write( `test.ts`, ` import {Directive, ContentChild, ContentChildren, TemplateRef, ViewChild} from '@angular/core'; import * as core from '@angular/core'; @Directive({ selector: '[test]', queries: { 'mview': new ViewChild('test1'), 'mcontent': new core.ContentChild('test2'), } }) class FooCmp { @ContentChild('bar', {read: TemplateRef}) child: any; @ContentChildren(TemplateRef) children: any; get aview(): any { return null; } @ViewChild('accessor') set aview(value: any) {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toMatch(varRegExp('bar')); expect(jsContents).toMatch(varRegExp('test1')); expect(jsContents).toMatch(varRegExp('test2')); expect(jsContents).toMatch(varRegExp('accessor')); // match `i0.ɵɵcontentQuery(dirIndex, _c1, 5, TemplateRef)` expect(jsContents).toMatch(contentQueryRegExp('\\w+', 5, 'TemplateRef')); // match `i0.ɵɵviewQuery(_c2, 5)` // Note that while ViewQuery doesn't necessarily make sense on a directive, // because it doesn't have a view, we still need to handle it because a component // could extend the directive. expect(jsContents).toMatch(viewQueryRegExp('\\w+', 5)); }); it('should handle queries that use forwardRef', () => { env.write( `test.ts`, ` import {Component, ContentChild, TemplateRef, ViewContainerRef, forwardRef} from '@angular/core'; @Component({ selector: 'test', template: '<div #foo></div>', }) class FooCmp { @ContentChild(forwardRef(() => TemplateRef)) child: any; @ContentChild(forwardRef(function() { return ViewContainerRef; })) child2: any; @ContentChild((forwardRef((function() { return 'parens'; }) as any))) childInParens: any; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // match `i0.ɵɵcontentQuery(dirIndex, TemplateRef, 5, null)` expect(jsContents).toMatch(contentQueryRegExp('TemplateRef', 5)); // match `i0.ɵɵcontentQuery(dirIndex, ViewContainerRef, 5, null)` expect(jsContents).toMatch(contentQueryRegExp('ViewContainerRef', 5)); // match `i0.ɵɵcontentQuery(dirIndex, _c0, 5, null)` expect(jsContents).toContain('_c0 = ["parens"];'); expect(jsContents).toMatch(contentQueryRegExp('_c0', 5)); }); it('should handle queries that use an InjectionToken', () => { env.write( `test.ts`, ` import {Component, ContentChild, InjectionToken, ViewChild} from '@angular/core'; const TOKEN = new InjectionToken('token'); @Component({ selector: 'test', template: '<div></div>', }) class FooCmp { @ViewChild(TOKEN) viewChild: any; @ContentChild(TOKEN) contentChild: any; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // match `i0.ɵɵviewQuery(TOKEN, 5, null)` expect(jsContents).toMatch(viewQueryRegExp('TOKEN', 5)); // match `i0.ɵɵcontentQuery(dirIndex, TOKEN, 5, null)` expect(jsContents).toMatch(contentQueryRegExp('TOKEN', 5)); }); it('should compile expressions that write keys', () => { env.write( `test.ts`, ` import {Component, ContentChild, TemplateRef, ViewContainerRef, forwardRef} from '@angular/core'; @Component({ selector: 'test', template: '<div (click)="test[key] = $event">', }) class TestCmp { test: any; key: string; } `, ); env.driveMain(); expect(env.getContents('test.js')).toContain('test[key] = $event'); }); it('should generate host listeners for components', () => { env.write( `test.ts`, ` import {Component, HostListener} from '@angular/core'; @Component({ selector: 'test', template: 'Test' }) class FooCmp { @HostListener('click') onClick(event: any): void {} @HostListener('document:click', ['$event.target']) onDocumentClick(eventTarget: HTMLElement): void {} @HostListener('window:scroll') onWindowScroll(event: any): void {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const hostBindingsFn = ` hostBindings: function FooCmp_HostBindings(rf, ctx) { if (rf & 1) { i0.ɵɵlistener("click", function FooCmp_click_HostBindingHandler() { return ctx.onClick(); })("click", function FooCmp_click_HostBindingHandler($event) { return ctx.onDocumentClick($event.target); }, false, i0.ɵɵresolveDocument)("scroll", function FooCmp_scroll_HostBindingHandler() { return ctx.onWindowScroll(); }, false, i0.ɵɵresolveWindow); } } `; expect(trim(jsContents)).toContain(trim(hostBindingsFn)); }); it('should throw in case unknown global target is provided', () => { env.write( `test.ts`, ` import {Component, HostListener} from '@angular/core'; @Component({ selector: 'test', template: 'Test' }) class FooCmp { @HostListener('UnknownTarget:click') onClick(event: any): void {} } `, ); const errors = env.driveDiagnostics(); expect(trim(errors[0].messageText as string)).toContain( `Unexpected global target 'UnknownTarget' defined for 'click' event. Supported list of global targets: window,document,body.`, ); }); it('should provide error location for invalid host properties', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '...', host: { '(click)': 'act() | pipe', } }) class FooCmp {} `, ); const errors = env.driveDiagnostics(); expect(getDiagnosticSourceCode(errors[0])).toBe(`{ '(click)': 'act() | pipe', }`); expect(errors[0].messageText).toContain('/test.ts@7:17'); }); it('should throw in case pipes are used in host listeners', () => { env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '...', host: { '(click)': 'doSmth() | myPipe' } }) class FooCmp {} `, ); const errors = env.driveDiagnostics(); expect(trim(errors[0].messageText as string)).toContain( 'Cannot have a pipe in an action expression', ); }); it('should throw in case pipes are used in host bindings (defined as `value | pipe`)', () => { env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '...', host: { '[id]': 'id | myPipe' } }) class FooCmp {} `, ); const errors = env.driveDiagnostics();
{ "end_byte": 163107, "start_byte": 154766, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_163113_171447
expect(trim(errors[0].messageText as string)).toContain( 'Host binding expression cannot contain pipes', ); }); it('should generate host bindings for directives', () => { env.write( `test.ts`, ` import {Component, HostBinding, HostListener, TemplateRef} from '@angular/core'; @Component({ selector: 'test', template: 'Test', host: { '[attr.hello]': 'foo', '(click)': 'onClick($event)', '(body:click)': 'onBodyClick($event)', '[prop]': 'bar', }, }) class FooCmp { onClick(event: any): void {} @HostBinding('class.someclass') get someClass(): boolean { return false; } @HostListener('change', ['arg1', 'arg2', 'arg3']) onChange(event: any, arg: any): void {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const hostBindingsFn = ` hostVars: 4, hostBindings: function FooCmp_HostBindings(rf, ctx) { if (rf & 1) { i0.ɵɵlistener("click", function FooCmp_click_HostBindingHandler($event) { return ctx.onClick($event); })("click", function FooCmp_click_HostBindingHandler($event) { return ctx.onBodyClick($event); }, false, i0.ɵɵresolveBody)("change", function FooCmp_change_HostBindingHandler() { return ctx.onChange(ctx.arg1, ctx.arg2, ctx.arg3); }); } if (rf & 2) { i0.ɵɵhostProperty("prop", ctx.bar); i0.ɵɵattribute("hello", ctx.foo); i0.ɵɵclassProp("someclass", ctx.someClass); } } `; expect(trim(jsContents)).toContain(trim(hostBindingsFn)); }); // https://github.com/angular/angular/issues/46936 it('should support bindings with Object builtin names', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div [valueOf]="123"></div>', }) export class TestCmp {} `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); expect(errors[0].messageText).toContain( `Can't bind to 'valueOf' since it isn't a known property of 'div'.`, ); }); it('should handle $any used inside a listener', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div (click)="$any(123)"></div>', }) export class TestCmp {} `, ); env.driveMain(); expect(env.getContents('test.js')).toContain( `ɵɵlistener("click", function TestCmp_Template_div_click_0_listener() { return 123; });`, ); }); it('should accept dynamic host attribute bindings', () => { env.write( 'other.d.ts', ` export declare const foo: any; `, ); env.write( 'test.ts', ` import {Component} from '@angular/core'; import {foo} from './other'; const test = foo.bar(); @Component({ selector: 'test', template: '', host: { 'test': test, }, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('hostAttrs: ["test", test]'); }); it('should accept enum values as host bindings', () => { env.write( `test.ts`, ` import {Component, HostBinding, HostListener, TemplateRef} from '@angular/core'; enum HostBindings { Hello = 'foo' } @Component({ selector: 'test', template: 'Test', host: { '[attr.hello]': HostBindings.Hello, }, }) class FooCmp { foo = 'test'; } `, ); env.driveMain(); expect(env.getContents('test.js')).toContain('i0.ɵɵattribute("hello", ctx.foo)'); }); it('should generate host listeners for directives within hostBindings section', () => { env.write( `test.ts`, ` import {Directive, HostListener} from '@angular/core'; @Directive({ selector: '[test]', }) class Dir { @HostListener('change', ['$event', 'arg']) onChange(event: any, arg: any): void {} } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const hostBindingsFn = ` hostBindings: function Dir_HostBindings(rf, ctx) { if (rf & 1) { i0.ɵɵlistener("change", function Dir_change_HostBindingHandler($event) { return ctx.onChange($event, ctx.arg); }); } } `; expect(trim(jsContents)).toContain(trim(hostBindingsFn)); }); it('should use proper default value for preserveWhitespaces config param', () => { env.tsconfig(); // default is `false` env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ selector: 'test', preserveWhitespaces: false, template: \` <div> Template with whitespaces </div> \` }) class FooCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('text(1, " Template with whitespaces ");'); }); it('should take preserveWhitespaces config option into account', () => { env.tsconfig({preserveWhitespaces: true}); env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: \` <div> Template with whitespaces </div> \` }) class FooCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'text(2, "\\n Template with whitespaces\\n ");', ); }); it("@Component's preserveWhitespaces should override the one defined in config", () => { env.tsconfig({preserveWhitespaces: true}); env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ selector: 'test', preserveWhitespaces: false, template: \` <div> Template with whitespaces </div> \` }) class FooCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('text(1, " Template with whitespaces ");'); }); it('should use proper default value for i18nUseExternalIds config param', () => { env.tsconfig(); // default is `true` env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '<div i18n>Some text</div>' }) class FooCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('MSG_EXTERNAL_8321000940098097247$$TEST_TS_0'); }); it('should take i18nUseExternalIds config option into account', () => { env.tsconfig({i18nUseExternalIds: false}); env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '<div i18n>Some text</div>' }) class FooCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).not.toContain('MSG_EXTERNAL_'); }); it('should render legacy ids when `enableI18nLegacyMessageIdFormat` is not false', () => { env.tsconfig({}); env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '<div i18n>Some text</div>' }) class FooCmp {}`, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( '`:\u241F5
{ "end_byte": 171447, "start_byte": 163113, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_171453_179454
3da8dff890e20cf76eb075d58900fbcd3\u241F8321000940098097247:Some text`', ); }); it('should render custom id and legacy ids if `enableI18nLegacyMessageIdFormat` is not false', () => { env.tsconfig({i18nFormatIn: 'xlf'}); env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '<div i18n="@@custom">Some text</div>' }) class FooCmp {}`, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( ':@@custom\u241F5dbba0a3da8dff890e20cf76eb075d58900fbcd3\u241F8321000940098097247:Some text', ); }); it('should not render legacy ids when `enableI18nLegacyMessageIdFormat` is set to false', () => { env.tsconfig({enableI18nLegacyMessageIdFormat: false, i18nInFormat: 'xmb'}); env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '<div i18n>Some text</div>' }) class FooCmp {}`, ); env.driveMain(); const jsContents = env.getContents('test.js'); // Note that the colon would only be there if there is an id attached to the // string. expect(jsContents).not.toContain(':Some text'); }); it('should also render legacy ids for ICUs when normal messages are using legacy ids', () => { env.tsconfig({i18nInFormat: 'xliff'}); env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '<div i18n="@@custom">Some text {age, plural, 10 {ten} other {other}}</div>' }) class FooCmp { age = 1; }`, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( ':\u241F720ba589d043a0497ac721ff972f41db0c919efb\u241F3221232817843005870:{VAR_PLURAL, plural, 10 {ten} other {other}}', ); expect(jsContents).toContain( ':@@custom\u241Fdcb6170595f5d548a3d00937e87d11858f51ad04\u241F7419139165339437596:Some text', ); }); it("@Component's `interpolation` should override default interpolation config", () => { env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-with-custom-interpolation-a', template: \`<div>{%text%}</div>\`, interpolation: ['{%', '%}'] }) class ComponentWithCustomInterpolationA { text = 'Custom Interpolation A'; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('ɵɵtextInterpolate(ctx.text)'); }); it('should handle `encapsulation` field', () => { env.write( `test.ts`, ` import {Component, ViewEncapsulation} from '@angular/core'; @Component({ selector: 'comp-a', template: '...', encapsulation: ViewEncapsulation.None }) class CompA {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('encapsulation: 2'); }); it('should throw if `encapsulation` contains invalid value', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp-a', template: '...', // @ts-ignore encapsulation: 'invalid-value' }) class CompA {} `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); const messageText = ts.flattenDiagnosticMessageText(errors[0].messageText, '\n'); expect(messageText).toContain( 'encapsulation must be a member of ViewEncapsulation enum from @angular/core', ); expect(messageText).toContain("Value is of type 'string'."); }); it('should handle `changeDetection` field', () => { env.write( `test.ts`, ` import {Component, ChangeDetectionStrategy} from '@angular/core'; @Component({ selector: 'comp-a', template: '...', changeDetection: ChangeDetectionStrategy.OnPush }) class CompA {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('changeDetection: 0'); }); it('should throw if `changeDetection` contains invalid value', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp-a', template: '...', // @ts-ignore changeDetection: 'invalid-value' }) class CompA {} `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); const messageText = ts.flattenDiagnosticMessageText(errors[0].messageText, '\n'); expect(messageText).toContain( 'changeDetection must be a member of ChangeDetectionStrategy enum from @angular/core', ); expect(messageText).toContain("Value is of type 'string'."); }); it('should ignore empty bindings', () => { env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '<div [class]></div>' }) class FooCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).not.toContain('i0.ɵɵproperty'); }); it('should correctly recognize local symbols', () => { env.write( 'module.ts', ` import {NgModule} from '@angular/core'; import {Dir, Comp} from './test'; @NgModule({ declarations: [Dir, Comp], exports: [Dir, Comp], }) class Module {} `, ); env.write( `test.ts`, ` import {Component, Directive} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class Dir {} @Component({ selector: 'test', template: '<div dir>Test</div>', standalone: false, }) export class Comp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).not.toMatch(/import \* as i[0-9] from ['"].\/test['"]/); }); it('should generate exportAs declarations', () => { env.write( 'test.ts', ` import {Component, Directive} from '@angular/core'; @Directive({ selector: '[test]', exportAs: 'foo', standalone: false, }) class Dir {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain(`exportAs: ["foo"]`); }); it('should generate multiple exportAs declarations', () => { env.write( 'test.ts', ` import {Component, Directive} from '@angular/core'; @Directive({ selector: '[test]', exportAs: 'foo, bar', standalone: false, }) class Dir {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain(`exportAs: ["foo", "bar"]`); }); it('should compile a banana-in-a-box inside of a template', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '<div *tmpl [(bananaInABox)]="prop"></div>', selector: 'test', standalone: false, }) class TestCmp {} `, ); env.driveMain(); }); it('generates inherited factory definitions', () => { env.write( `test.ts`,
{ "end_byte": 179454, "start_byte": 171453, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_179460_187847
` import {Injectable} from '@angular/core'; class Dep {} @Injectable() class Base { constructor(dep: Dep) {} } @Injectable() class Child extends Base {} @Injectable() class GrandChild extends Child { constructor() { super(null!); } } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'function Base_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || Base)(i0.ɵɵinject(Dep)); }', ); expect(jsContents).toContain( '(() => { let ɵChild_BaseFactory; return function Child_Factory(__ngFactoryType__) { return (ɵChild_BaseFactory || (ɵChild_BaseFactory = i0.ɵɵgetInheritedFactory(Child)))(__ngFactoryType__ || Child); }; })();', ); expect(jsContents).toContain( 'function GrandChild_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || GrandChild)(); }', ); }); it('generates base factories for directives', () => { env.write( `test.ts`, ` import {Directive} from '@angular/core'; @Directive({ selector: '[base]', }) class Base {} @Directive({ selector: '[test]', }) class Dir extends Base { } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( '/*@__PURE__*/ (() => { let ɵDir_BaseFactory; return function Dir_Factory(__ngFactoryType__) { return (ɵDir_BaseFactory || (ɵDir_BaseFactory = i0.ɵɵgetInheritedFactory(Dir)))(__ngFactoryType__ || Dir); }; })();', ); }); it('should wrap "directives" in component metadata in a closure when forward references are present', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'cmp-a', template: '<cmp-b></cmp-b>', standalone: false, }) class CmpA {} @Component({ selector: 'cmp-b', template: 'This is B', standalone: false, }) class CmpB {} @NgModule({ declarations: [CmpA, CmpB], }) class Module {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('dependencies: () => [CmpB]'); }); it('should wrap setClassMetadata in an iife with ngDevMode guard', () => { env.write( 'test.ts', ` import {Injectable} from '@angular/core'; @Injectable({providedIn: 'root'}) export class Service {} `, ); env.driveMain(); const jsContents = env.getContents('test.js').replace(/\s+/g, ' '); expect(jsContents).toContain( `(() => { (typeof ngDevMode === "undefined" || ngDevMode) && ` + `i0.ɵsetClassMetadata(Service, [{ type: Injectable, args: [{ providedIn: 'root' }] }], null, null); })();`, ); }); it('should not include `schemas` in component and module defs', () => { env.write( 'test.ts', ` import {Component, NgModule, NO_ERRORS_SCHEMA} from '@angular/core'; @Component({ selector: 'comp', template: '<custom-el></custom-el>', standalone: false, }) class MyComp {} @NgModule({ declarations: [MyComp], schemas: [NO_ERRORS_SCHEMA], }) class MyModule {} `, ); env.driveMain(); const jsContents = trim(env.getContents('test.js')); expect(jsContents).toContain( trim(` MyComp.ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: MyComp, selectors: [["comp"]], standalone: false, decls: 1, vars: 0, template: function MyComp_Template(rf, ctx) { if (rf & 1) { i0.ɵɵelement(0, "custom-el"); } }, encapsulation: 2 }); `), ); expect(jsContents).toContain( trim('MyModule.ɵmod = /*@__PURE__*/ i0.ɵɵdefineNgModule({ type: MyModule });'), ); }); it('should emit setNgModuleScope calls for NgModules by default', () => { env.write( 'test.ts', ` import {Component, Directive, Injectable, NgModule, Pipe} from '@angular/core'; @Component({selector: 'cmp', template: 'I am a component!', standalone: false}) class TestComponent {} @Directive({selector: 'dir', standalone: false}) class TestDirective {} @Injectable() class TestInjectable {} @NgModule({declarations: [TestComponent, TestDirective]}) class TestNgModule {} @Pipe({name: 'pipe', standalone: false}) class TestPipe {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('\u0275setNgModuleScope(TestNgModule, '); }); it('should emit setNgModuleScope calls for NgModules when supportJitMode is true', () => { env.tsconfig({ 'supportJitMode': true, }); env.write( 'test.ts', ` import {Component, Directive, Injectable, NgModule, Pipe} from '@angular/core'; @Component({selector: 'cmp', template: 'I am a component!', standalone: false}) class TestComponent {} @Directive({selector: 'dir', standalone: false}) class TestDirective {} @Injectable() class TestInjectable {} @NgModule({declarations: [TestComponent, TestDirective]}) class TestNgModule {} @Pipe({name: 'pipe', standalone: false}) class TestPipe {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('\u0275setNgModuleScope(TestNgModule, '); }); it('should not emit setNgModuleScope calls for NgModules when supportJitMode is false', () => { env.tsconfig({ 'supportJitMode': false, }); env.write( 'test.ts', ` import {Component, Directive, Injectable, NgModule, Pipe} from '@angular/core'; @Component({selector: 'cmp', template: 'I am a component!', standalone: false}) class TestComponent {} @Directive({selector: 'dir', standalone: false}) class TestDirective {} @Injectable() class TestInjectable {} @NgModule({declarations: [TestComponent, TestDirective]}) class TestNgModule {} @Pipe({name: 'pipe', standalone: false}) class TestPipe {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).not.toContain('\u0275setNgModuleScope('); }); it('should emit setClassMetadata calls for all types by default', () => { env.write( 'test.ts', ` import {Component, Directive, Injectable, NgModule, Pipe} from '@angular/core'; @Component({selector: 'cmp', template: 'I am a component!', standalone: false}) class TestComponent {} @Directive({selector: 'dir', standalone: false}) class TestDirective {} @Injectable() class TestInjectable {} @NgModule({declarations: [TestComponent, TestDirective]}) class TestNgModule {} @Pipe({name: 'pipe', standalone: false}) class TestPipe {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('\u0275setClassMetadata(TestComponent, '); expect(jsContents).toContain('\u0275setClassMetadata(TestDirective, '); expect(jsContents).toContain('\u0275setClassMetadata(TestInjectable, '); expect(jsContents).toContain('\u0275setClassMetadata(TestNgModule, '); expect(jsContents).toContain('\u0275setClassMetadata(TestPipe, '); }); it('should emit setClassMetadata calls for all types when supportTestBed is true', () => { env.tsconfig({ 'supportTestBed': true, }); env.write( 'test.ts', ` import {Component, Directive, Injectable, NgModule, Pipe} from '@angular/core'; @Component({selector: 'cmp', template: 'I am a component!', standalone: false}) class TestComponent {} @Directive({selector: 'dir', standalone: false}) class TestDirective {} @Injectable() class TestInje
{ "end_byte": 187847, "start_byte": 179460, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_187853_193764
{} @NgModule({declarations: [TestComponent, TestDirective]}) class TestNgModule {} @Pipe({name: 'pipe', standalone: false}) class TestPipe {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('\u0275setClassMetadata(TestComponent, '); expect(jsContents).toContain('\u0275setClassMetadata(TestDirective, '); expect(jsContents).toContain('\u0275setClassMetadata(TestInjectable, '); expect(jsContents).toContain('\u0275setClassMetadata(TestNgModule, '); expect(jsContents).toContain('\u0275setClassMetadata(TestPipe, '); }); it('should not emit setClassMetadata calls for all types when supportTestBed is false', () => { env.tsconfig({ 'supportTestBed': false, }); env.write( 'test.ts', ` import {Component, Directive, Injectable, NgModule, Pipe} from '@angular/core'; @Component({selector: 'cmp', template: 'I am a component!', standalone: false}) class TestComponent {} @Directive({selector: 'dir', standalone: false}) class TestDirective {} @Injectable() class TestInjectable {} @NgModule({declarations: [TestComponent, TestDirective]}) class TestNgModule {} @Pipe({name: 'pipe', standalone: false}) class TestPipe {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).not.toContain('\u0275setClassMetadata('); }); it('should use imported types in setClassMetadata if they can be represented as values', () => { env.write( `types.ts`, ` export class MyTypeA {} export class MyTypeB {} `, ); env.write( `test.ts`, ` import {Component, Inject, Injectable} from '@angular/core'; import {MyTypeA, MyTypeB} from './types'; @Injectable({providedIn: 'root'}) export class SomeService { constructor(arg: MyTypeA) {} } @Component({ selector: 'some-comp', template: '...', }) export class SomeComp { constructor(@Inject('arg-token') arg: MyTypeB) {} } `, ); env.driveMain(); const jsContents = trim(env.getContents('test.js')); expect(jsContents).toContain(`import * as i1 from "./types";`); expect(jsContents).toMatch(setClassMetadataRegExp('type: i1\\.MyTypeA')); expect(jsContents).toMatch(setClassMetadataRegExp('type: i1\\.MyTypeB')); }); it('should use imported types in setClassMetadata if they can be represented as values and imported as `* as foo`', () => { env.write( `types.ts`, ` export class MyTypeA {} export class MyTypeB {} `, ); env.write( `test.ts`, ` import {Component, Inject, Injectable} from '@angular/core'; import * as types from './types'; @Injectable({providedIn: 'root'}) export class SomeService { constructor(arg: types.MyTypeA) {} } @Component({ selector: 'some-comp', template: '...', }) export class SomeComp { constructor(@Inject('arg-token') arg: types.MyTypeB) {} } `, ); env.driveMain(); const jsContents = trim(env.getContents('test.js')); expect(jsContents).toContain(`import * as i1 from "./types";`); expect(jsContents).toMatch(setClassMetadataRegExp('type: i1.MyTypeA')); expect(jsContents).toMatch(setClassMetadataRegExp('type: i1.MyTypeB')); }); it('should use default-imported types if they can be represented as values', () => { env.write( `types.ts`, ` export default class Default {} export class Other {} `, ); env.write( `test.ts`, ` import {Component} from '@angular/core'; import {Other} from './types'; import Default from './types'; @Component({selector: 'test', template: 'test'}) export class SomeCmp { constructor(arg: Default, other: Other) {} } `, ); env.driveMain(); const jsContents = trim(env.getContents('test.js')); expect(jsContents).toContain(`import Default from './types';`); expect(jsContents).toContain(`import * as i1 from "./types";`); expect(jsContents).toContain('i0.ɵɵdirectiveInject(Default)'); expect(jsContents).toContain('i0.ɵɵdirectiveInject(i1.Other)'); expect(jsContents).toMatch(setClassMetadataRegExp('type: Default')); expect(jsContents).toMatch(setClassMetadataRegExp('type: i1.Other')); }); it('should not throw when using an SVG-specific `title` tag', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ template: \` <svg> <rect> <svg:title>I'm a title tag</svg:title> </rect> </svg> \`, standalone: false, }) export class SvgCmp {} @NgModule({ declarations: [SvgCmp], }) export class SvgModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); describe('namespace support', () => { it('should generate correct imports for type references to namespaced symbols using a namespace import', () => { env.write( `/node_modules/ns/index.d.ts`, ` export declare class Zero {} export declare namespace one { export declare class One {} } export declare namespace one.two { export declare class Two {} } `, );
{ "end_byte": 193764, "start_byte": 187853, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_193770_202069
env.write( `test.ts`, ` import {Inject, Injectable, InjectionToken} from '@angular/core'; import * as ns from 'ns'; @Injectable() export class MyService { constructor( zero: ns.Zero, one: ns.one.One, two: ns.one.two.Two, ) {} } `, ); env.driveMain(); const jsContents = trim(env.getContents('test.js')); expect(jsContents).toContain(`import * as i1 from "ns";`); expect(jsContents).toContain('i0.ɵɵinject(i1.Zero)'); expect(jsContents).toContain('i0.ɵɵinject(i1.one.One)'); expect(jsContents).toContain('i0.ɵɵinject(i1.one.two.Two)'); expect(jsContents).toMatch(setClassMetadataRegExp('type: i1.Zero')); expect(jsContents).toMatch(setClassMetadataRegExp('type: i1.one.One')); expect(jsContents).toMatch(setClassMetadataRegExp('type: i1.one.two.Two')); }); it('should generate correct imports for type references to namespaced symbols using named imports', () => { env.write( `/node_modules/ns/index.d.ts`, ` export namespace ns { export declare class Zero {} export declare namespace one { export declare class One {} } export declare namespace one.two { export declare class Two {} } } `, ); env.write( `test.ts`, ` import {Inject, Injectable, InjectionToken} from '@angular/core'; import {ns} from 'ns'; import {ns as alias} from 'ns'; @Injectable() export class MyService { constructor( zero: ns.Zero, one: ns.one.One, two: ns.one.two.Two, aliasedZero: alias.Zero, aliasedOne: alias.one.One, aliasedTwo: alias.one.two.Two, ) {} } `, ); env.driveMain(); const jsContents = trim(env.getContents('test.js')); expect(jsContents).toContain(`import * as i1 from "ns";`); expect(jsContents).toContain( 'i0.ɵɵinject(i1.ns.Zero), ' + 'i0.ɵɵinject(i1.ns.one.One), ' + 'i0.ɵɵinject(i1.ns.one.two.Two), ' + 'i0.ɵɵinject(i1.ns.Zero), ' + 'i0.ɵɵinject(i1.ns.one.One), ' + 'i0.ɵɵinject(i1.ns.one.two.Two)', ); expect(jsContents).toMatch(setClassMetadataRegExp('type: i1.ns.Zero')); expect(jsContents).toMatch(setClassMetadataRegExp('type: i1.ns.one.One')); expect(jsContents).toMatch(setClassMetadataRegExp('type: i1.ns.one.two.Two')); }); it('should not error for a namespace import as parameter type when @Inject is used', () => { env.tsconfig({'strictInjectionParameters': true}); env.write( `/node_modules/foo/index.d.ts`, ` export = Foo; declare class Foo {} declare namespace Foo {} `, ); env.write( `test.ts`, ` import {Inject, Injectable, InjectionToken} from '@angular/core'; import * as Foo from 'foo'; export const TOKEN = new InjectionToken<Foo>('Foo'); @Injectable() export class MyService { constructor(@Inject(TOKEN) foo: Foo) {} } `, ); env.driveMain(); const jsContents = trim(env.getContents('test.js')); expect(jsContents).toContain('i0.ɵɵinject(TOKEN)'); expect(jsContents).toMatch(setClassMetadataRegExp('type: undefined')); }); it('should error for a namespace import as parameter type used for DI', () => { env.tsconfig({'strictInjectionParameters': true}); env.write( `/node_modules/foo/index.d.ts`, ` export = Foo; declare class Foo {} declare namespace Foo {} `, ); env.write( `test.ts`, ` import {Injectable} from '@angular/core'; import * as Foo from 'foo'; @Injectable() export class MyService { constructor(foo: Foo) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '\n')).toBe( `No suitable injection token for parameter 'foo' of class 'MyService'.\n` + ` Consider using the @Inject decorator to specify an injection token.`, ); expect(diags[0].relatedInformation!.length).toBe(2); expect(diags[0].relatedInformation![0].messageText).toBe( 'This type corresponds with a namespace, which cannot be used as injection token.', ); expect(diags[0].relatedInformation![1].messageText).toBe( 'The namespace import occurs here.', ); }); }); it("should use `undefined` in setClassMetadata if types can't be represented as values", () => { env.write( `types.ts`, ` export type MyType = Map<any, any>; `, ); env.write( `test.ts`, ` import {Component, Inject, Injectable} from '@angular/core'; import {MyType} from './types'; @Component({ selector: 'some-comp', template: '...', }) export class SomeComp { constructor(@Inject('arg-token') arg: MyType) {} } `, ); env.driveMain(); const jsContents = trim(env.getContents('test.js')); expect(jsContents).not.toContain(`import { MyType } from './types';`); // Note: `type: undefined` below, since MyType can't be represented as a value expect(jsContents).toMatch(setClassMetadataRegExp('type: undefined')); }); it('should use `undefined` in setClassMetadata for const enums', () => { env.write( `keycodes.ts`, ` export const enum KeyCodes {A, B}; `, ); env.write( `test.ts`, ` import {Component, Inject} from '@angular/core'; import {KeyCodes} from './keycodes'; @Component({ selector: 'some-comp', template: '...', }) export class SomeComp { constructor(@Inject('arg-token') arg: KeyCodes) {} } `, ); env.driveMain(); const jsContents = trim(env.getContents('test.js')); expect(jsContents).not.toContain(`import { KeyCodes } from './keycodes';`); // Note: `type: undefined` below, since KeyCodes can't be represented as a value expect(jsContents).toMatch(setClassMetadataRegExp('type: undefined')); }); it('should preserve the types of non-const enums in setClassMetadata', () => { env.write( `keycodes.ts`, ` export enum KeyCodes {A, B}; `, ); env.write( `test.ts`, ` import {Component, Inject} from '@angular/core'; import {KeyCodes} from './keycodes'; @Component({ selector: 'some-comp', template: '...', }) export class SomeComp { constructor(@Inject('arg-token') arg: KeyCodes) {} } `, ); env.driveMain(); const jsContents = trim(env.getContents('test.js')); expect(jsContents).toContain(`import * as i1 from "./keycodes";`); expect(jsContents).toMatch(setClassMetadataRegExp('type: i1.KeyCodes')); }); it('should use `undefined` in setClassMetadata if types originate from type-only imports', () => { env.write( `types.ts`, ` export default class {} export class TypeOnlyOne {} export class TypeOnlyTwo {} `, ); env.write( `test.ts`, ` import {Component, Inject, Injectable} from '@angular/core'; import type DefaultImport from './types'; import type {TypeOnlyOne} from './types'; import {type Type
{ "end_byte": 202069, "start_byte": 193770, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_202075_205173
o} from './types'; import type * as types from './types'; @Component({ selector: 'some-comp', template: '...', }) export class SomeComp { constructor( @Inject('token') namedImport: TypeOnlyOne, @Inject('token') defaultImport: DefaultImport, @Inject('token') namespacedImport: types.TypeOnlyOne, @Inject('token') typeOnlySpecifier: TypeOnlyTwo, ) {} } `, ); env.driveMain(); const jsContents = trim(env.getContents('test.js')); // Module specifier for type-only import should not be emitted expect(jsContents).not.toContain('./types'); // Default type-only import should not be emitted expect(jsContents).not.toContain('DefaultImport'); // Named type-only import should not be emitted expect(jsContents).not.toContain('TypeOnlyOne'); // Symbols from type-only specifiers should not be emitted expect(jsContents).not.toContain('TypeOnlyTwo'); // The parameter type in class metadata should be undefined expect(jsContents).toMatch(setClassMetadataRegExp('type: undefined')); }); it('should not throw in case whitespaces and HTML comments are present inside <ng-content>', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-a', template: \` <ng-content> <!-- Some comments --> </ng-content> \`, }) class CmpA {} `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(0); }); it('should compile a template using multiple directives with the same selector', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule} from '@angular/core'; @Directive({ selector: '[test]', standalone: false, }) class DirA {} @Directive({ selector: '[test]', standalone: false, }) class DirB {} @Component({ template: '<div test></div>', standalone: false, }) class Cmp {} @NgModule({ declarations: [Cmp, DirA, DirB], }) class Module {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toMatch(/dependencies: \[DirA,\s+DirB\]/); }); describe('cycle detection', () => { it('should detect a simple cycle and use remote component scoping', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; import {NormalComponent} from './cyclic'; @Component({ selector: 'cyclic-component', template: 'Importing this causes a cycle', standalone: false, }) export class CyclicComponent {} @NgModule({ declarations: [NormalCompon
{ "end_byte": 205173, "start_byte": 202075, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_205179_214856
yclicComponent], }) export class Module {} `, ); env.write( 'cyclic.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'normal-component', template: '<cyclic-component></cyclic-component>', standalone: false, }) export class NormalComponent {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toMatch( /i\d\.ɵɵsetComponentScope\(NormalComponent,\s+\[CyclicComponent\],\s+\[\]\)/, ); expect(jsContents).not.toContain('/*__PURE__*/ i0.ɵɵsetComponentScope'); }); it('should detect a cycle added entirely during compilation', () => { env.write( 'test.ts', ` import {NgModule} from '@angular/core'; import {ACmp} from './a'; import {BCmp} from './b'; @NgModule({declarations: [ACmp, BCmp]}) export class Module {} `, ); env.write( 'a.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'a-cmp', template: '<b-cmp></b-cmp>', 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.driveMain(); const aJsContents = env.getContents('a.js'); const bJsContents = env.getContents('b.js'); expect(aJsContents).toMatch(/import \* as i\d? from ".\/b"/); expect(bJsContents).not.toMatch(/import \* as i\d? from ".\/a"/); }); it("should not detect a potential cycle if it doesn't actually happen", () => { env.write( 'test.ts', ` import {NgModule} from '@angular/core'; import {ACmp} from './a'; import {BCmp} from './b'; @NgModule({declarations: [ACmp, BCmp]}) export class Module {} `, ); env.write( 'a.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'a-cmp', template: '<b-cmp></b-cmp>', standalone: false, }) export class ACmp {} `, ); env.write( 'b.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'b-cmp', template: 'does not use a-cmp', standalone: false, }) export class BCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).not.toContain('setComponentScope'); }); it('should not consider type-only import clauses during cycle detection', () => { env.write( 'test.ts', ` import {NgModule} from '@angular/core'; import {ACmp} from './a'; import {BCmp} from './b'; @NgModule({declarations: [ACmp, BCmp]}) export class Module {} `, ); env.write( 'a.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'a-cmp', template: '<b-cmp></b-cmp>', standalone: false, }) export class ACmp {} `, ); env.write( 'b.ts', ` import {Component} from '@angular/core'; import type {ACmp} from './a'; @Component({ selector: 'b-cmp', template: 'does not use a-cmp', standalone: false, }) export class BCmp { a: ACmp; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).not.toContain('setComponentScope'); }); it('should not consider import clauses where all the specifiers are type-only during cycle detection', () => { env.write( 'test.ts', ` import {NgModule} from '@angular/core'; import {SharedOne, SharedTwo} from './shared'; import {CyclicCmp} from './cyclic'; @NgModule({declarations: [SharedOne, SharedTwo, CyclicCmp]}) export class Module {} `, ); env.write( 'shared.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'shared-one-cmp', template: '<cyclic-cmp></cyclic-cmp>', standalone: false, }) export class SharedOne {} @Component({ selector: 'shared-two-cmp', template: '<cyclic-cmp></cyclic-cmp>', standalone: false, }) export class SharedTwo {} `, ); env.write( 'cyclic.ts', ` import {Component} from '@angular/core'; import {type SharedOne, type SharedTwo} from './shared'; @Component({ selector: 'cyclic-cmp', template: 'does not use shared components', standalone: false, }) export class CyclicCmp { one: SharedOne; two: SharedTwo; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).not.toContain('setComponentScope'); }); it('should only pass components actually used to setComponentScope', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; import {NormalComponent} from './cyclic'; import {OtherComponent} from './other'; @Component({ selector: 'cyclic-component', template: 'Importing this causes a cycle', standalone: false, }) export class CyclicComponent {} @NgModule({ declarations: [NormalComponent, CyclicComponent, OtherComponent], }) export class Module {} `, ); env.write( 'cyclic.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'normal-component', template: '<cyclic-component></cyclic-component>', standalone: false, }) export class NormalComponent {} `, ); env.write( 'other.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'other-component', template: 'An unused other component', standalone: false, }) export class OtherComponent {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).not.toMatch(/i\d\.ɵɵsetComponentScope\([^)]*OtherComponent[^)]*\)/); }); it('should detect a simple cycle and fatally error if doing partial-compilation', () => { env.tsconfig({ compilationMode: 'partial', }); env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; import {NormalComponent} from './cyclic'; @Component({ selector: 'cyclic-component', template: 'Importing this causes a cycle', standalone: false, }) export class CyclicComponent {} @NgModule({ declarations: [NormalComponent, CyclicComponent], }) export class Module {} `, ); env.write( 'cyclic.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'normal-component', template: '<cyclic-component></cyclic-component>', standalone: false, }) export class NormalComponent {} `, ); const diagnostics = env.driveDiagnostics(); expect(diagnostics.length).toEqual(1); const error = diagnostics[0]; expect(error.code).toBe(ngErrorCode(ErrorCode.IMPORT_CYCLE_DETECTED)); expect(error.messageText).toEqual( 'One or more import cycles would need to be created to compile this component, ' + 'which is not supported by the current compiler configuration.', ); const _abs = absoluteFrom; expect(error.relatedInformation?.map((diag) => diag.messageText)).toEqual([ `The component 'CyclicComponent' is used in the template ` + `but importing it would create a cycle: ` + `${_abs('/cyclic.ts')} -> ${_abs('/test.ts')} -> ${_abs('/cyclic.ts')}`, ]); }); }); describe('local refs', () => { it('should not generate an error when a local ref is unresolved (outside of template type-checking)', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '<div #ref="unknownTarget"></div>', }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toEqual(`No dire
{ "end_byte": 214856, "start_byte": 205179, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_214862_220616
found with exportAs 'unknownTarget'.`); }); }); describe('multiple local refs', () => { const getComponentScript = (template: string): string => ` import {Component, Directive, NgModule} from '@angular/core'; @Component({ selector: 'my-cmp', template: \`${template}\`, standalone: false, }) class Cmp {} @NgModule({declarations: [Cmp]}) class Module {} `; const cases = [ ` <div #ref></div> <div #ref></div> `, ` <ng-container> <div #ref></div> </ng-container> <div #ref></div> `, ` <ng-template> <div #ref></div> </ng-template> <div #ref></div> `, ` <div *ngIf="visible" #ref></div> <div #ref></div> `, ` <div *ngFor="let item of items" #ref></div> <div #ref></div> `, ]; cases.forEach((template) => { it('should not throw', () => { env.write('test.ts', getComponentScript(template)); const errors = env.driveDiagnostics(); expect(errors.length).toBe(0); }); }); }); it('should wrap "inputs" and "outputs" keys if they contain unsafe characters', () => { env.write( `test.ts`, ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[somedir]', inputs: ['track-type', 'track-name', 'inputTrackName', 'src.xl'], outputs: ['output-track-type', 'output-track-name', 'outputTrackName', 'output.event'] }) export class SomeDir { @Input('track-type') trackType: string; @Input('track-name') trackName: string; } `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const inputsAndOutputs = ` inputs: { "track-type": "track-type", "track-name": "track-name", inputTrackName: "inputTrackName", "src.xl": "src.xl", trackType: [0, "track-type", "trackType"], trackName: [0, "track-name", "trackName"] }, outputs: { "output-track-type": "output-track-type", "output-track-name": "output-track-name", outputTrackName: "outputTrackName", "output.event": "output.event" } `; expect(trim(jsContents)).toContain(trim(inputsAndOutputs)); }); it('should generate the correct declaration for class members decorated with @Input', () => { env.write( 'test.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class TestDir { @Input() noArgs: any; @Input('aliasedStringArg') stringArg: any; @Input({required: true}) requiredNoAlias: any; @Input({alias: 'aliasedRequiredWithAlias', required: true}) requiredWithAlias: any; } `, ); env.driveMain(); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain( 'static ɵdir: i0.ɵɵDirectiveDeclaration<TestDir, "[dir]", never, ' + '{ "noArgs": { "alias": "noArgs"; "required": false; }; "stringArg": ' + '{ "alias": "aliasedStringArg"; "required": false; }; "requiredNoAlias": ' + '{ "alias": "requiredNoAlias"; "required": true; }; "requiredWithAlias": ' + '{ "alias": "aliasedRequiredWithAlias"; "required": true; }; }, {}, never, never, false, never>;', ); }); it('should generate the correct declaration for directives using the `inputs` array', () => { env.write( 'test.ts', ` import {Directive, Input} from '@angular/core'; @Directive({ selector: '[dir]', inputs: [ 'plain', 'withAlias: aliasedWithAlias', {name: 'plainLiteral'}, {name: 'aliasedLiteral', alias: 'alisedLiteralAlias'}, {name: 'requiredLiteral', required: true}, {name: 'requiredAlisedLiteral', alias: 'requiredAlisedLiteralAlias', required: true} ], standalone: false, }) export class TestDir { plainLiteral: any; aliasedLiteral: any; requiredLiteral: any; requiredAlisedLiteral: any; } `, ); env.driveMain(); const dtsContents = env.getContents('test.d.ts'); expect(dtsContents).toContain( 'static ɵdir: i0.ɵɵDirectiveDeclaration<TestDir, "[dir]", never, ' + '{ "plain": { "alias": "plain"; "required": false; }; ' + '"withAlias": { "alias": "aliasedWithAlias"; "required": false; }; ' + '"plainLiteral": { "alias": "plainLiteral"; "required": false; }; ' + '"aliasedLiteral": { "alias": "alisedLiteralAlias"; "required": false; }; ' + '"requiredLiteral": { "alias": "requiredLiteral"; "required": true; }; ' + '"requiredAlisedLiteral": { "alias": "requiredAlisedLiteralAlias"; "required": true; }; }, {}, never, never, false, never>;', ); }); describe('NgModule invalid import/export errors', () => { function verifyThrownError(errorCode: ErrorCode, errorMessage: string) { const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); let {code, messageText} = errors[0]; if (errors[0].relatedInformation !== undefined) { messageText += errors[0].relatedInformation.map((info) => info.messageText).join('\n'); } expect(code).toBe(ngErrorCode(errorCode)); expect(trim(messageText as string)).toContain(error
{ "end_byte": 220616, "start_byte": 214862, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_220622_227203
e); } it('should provide a hint when importing an invalid NgModule from node_modules', () => { env.write( 'node_modules/external/index.d.ts', ` export declare class NotAModule {} `, ); env.write( 'test.ts', ` import {NgModule} from '@angular/core'; import {NotAModule} from 'external'; @NgModule({ imports: [NotAModule], }) export class Module {} `, ); verifyThrownError( ErrorCode.NGMODULE_INVALID_IMPORT, 'This likely means that the library (external) which declares NotAModule is not ' + 'compatible with Angular Ivy.', ); }); it('should provide a hint when importing an invalid NgModule from a local library', () => { env.write( 'libs/external/index.d.ts', ` export declare class NotAModule {} `, ); env.write( 'test.ts', ` import {NgModule} from '@angular/core'; import {NotAModule} from './libs/external'; @NgModule({ imports: [NotAModule], }) export class Module {} `, ); verifyThrownError( ErrorCode.NGMODULE_INVALID_IMPORT, 'This likely means that the dependency which declares NotAModule is not ' + 'compatible with Angular Ivy.', ); }); it('should provide a hint when importing an invalid NgModule in the current program', () => { env.write( 'invalid.ts', ` export class NotAModule {} `, ); env.write( 'test.ts', ` import {NgModule} from '@angular/core'; import {NotAModule} from './invalid'; @NgModule({ imports: [NotAModule], }) export class Module {} `, ); verifyThrownError( ErrorCode.NGMODULE_INVALID_IMPORT, 'Is it missing an @NgModule annotation?', ); }); it('should report if an NgModule imports itself', () => { env.write( 'test.ts', ` import {NgModule} from '@angular/core'; @NgModule({imports: [MyModule]}) export class MyModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe('NgModule "import" field contains a cycle'); }); it('should report if an NgModule exports itself', () => { env.write( 'test.ts', ` import {NgModule} from '@angular/core'; @NgModule({exports: [MyModule]}) export class MyModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe('NgModule "export" field contains a cycle'); }); it('should report if an NgModule imports itself transitively', () => { env.write( 'dep-2.ts', ` import {NgModule} from '@angular/core'; import {MyModule} from './test'; @NgModule({imports: [MyModule]}) export class DepModule2 {} `, ); env.write( 'dep.ts', ` import {NgModule} from '@angular/core'; import {DepModule2} from './dep-2'; @NgModule({imports: [DepModule2]}) export class DepModule {} `, ); env.write( 'test.ts', ` import {NgModule} from '@angular/core'; import {DepModule} from './dep'; @NgModule({imports: [DepModule]}) export class MyModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(3); expect(diags[0].messageText).toBe( 'This import contains errors, which may affect components that depend on this NgModule.', ); expect(diags[1].messageText).toBe('NgModule "import" field contains a cycle'); expect(diags[2].messageText).toBe( 'This import contains errors, which may affect components that depend on this NgModule.', ); }); it('should report if an NgModule imports itself via a forwardRef', () => { env.write( 'test.ts', ` import {NgModule, forwardRef} from '@angular/core'; @NgModule({imports: [forwardRef(() => MyModule)]}) export class DepModule {} @NgModule({imports: [DepModule]}) export class MyModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toBe( 'This import contains errors, which may affect components that depend on this NgModule.', ); expect(diags[1].messageText).toBe('NgModule "import" field contains a cycle'); }); it('should report if an NgModule imports itself via a forwardRef', () => { env.write( 'test.ts', ` import {NgModule, forwardRef} from '@angular/core'; @NgModule({imports: [forwardRef(() => ModB)]}) class ModA {} @NgModule({imports: [forwardRef(() => ModC)]}) class ModB {} @NgModule({imports: [ModB]}) class ModC {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(3); expect(diags[0].messageText).toBe( 'This import contains errors, which may affect components that depend on this NgModule.', ); expect(diags[1].messageText).toBe( 'This import contains errors, which may affect components that depend on this NgModule.', ); expect(diags[2].messageText).toBe('NgModule "import" field contains a cycle'); }); }); describe('when processing external directives', () => { it('should not emit multiple references to the same directive', () => { env.write( 'node_modules/external/index.d.ts', ` import {ɵɵDirectiveDeclaration, ɵɵNgModuleDeclaration} from '@angular/core'; export declare class ExternalDir { static ɵdir: ɵɵDirectiveDeclaration<ExternalDir, '[test]', never, never, never, never>; } export declare class ExternalModule { static ɵmod: ɵɵNgModuleDeclaration<Exte
{ "end_byte": 227203, "start_byte": 220622, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_227209_232082
dule, [typeof ExternalDir], never, [typeof ExternalDir]>; } `, ); env.write( 'test.ts', ` import {Component, Directive, NgModule} from '@angular/core'; import {ExternalModule} from 'external'; @Component({ template: '<div test></div>', standalone: false, }) class Cmp {} @NgModule({ declarations: [Cmp], // Multiple imports of the same module used to result in duplicate directive references // in the output. imports: [ExternalModule, ExternalModule], }) class Module {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toMatch(/dependencies: \[i1\.ExternalDir\]/); }); it('should import directives by their external name', () => { env.write( 'node_modules/external/index.d.ts', ` import {ɵɵDirectiveDeclaration, ɵɵNgModuleDeclaration} from '@angular/core'; import {InternalDir} from './internal'; export {InternalDir as ExternalDir} from './internal'; export declare class ExternalModule { static ɵmod: ɵɵNgModuleDeclaration<ExternalModule, [typeof InternalDir], never, [typeof InternalDir]>; } `, ); env.write( 'node_modules/external/internal.d.ts', ` export declare class InternalDir { static ɵdir: ɵɵDirectiveDeclaration<InternalDir, '[test]', never, never, never, never>; } `, ); env.write( 'test.ts', ` import {Component, Directive, NgModule} from '@angular/core'; import {ExternalModule} from 'external'; @Component({ template: '<div test></div>', standalone: false, }) class Cmp {} @NgModule({ declarations: [Cmp], imports: [ExternalModule], }) class Module {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toMatch(/dependencies: \[i1\.ExternalDir\]/); }); }); // Run checks that are present in preanalysis phase in both sync and async mode, to // make sure the error messages are consistently thrown from `analyzeSync` and // `analyzeAsync` functions. ['sync', 'async'].forEach((mode) => { describe(`preanalysis phase checks [${mode}]`, () => { let driveDiagnostics: () => Promise<ReadonlyArray<ts.Diagnostic>>; beforeEach(() => { if (mode === 'async') { env.enablePreloading(); driveDiagnostics = () => env.driveDiagnosticsAsync(); } else { driveDiagnostics = () => Promise.resolve(env.driveDiagnostics()); } }); it('should throw if @Component is missing a template', async () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test', }) export class TestCmp {} `, ); const diags = await driveDiagnostics(); expect(diags[0].messageText).toBe('component is missing a template'); expect(diags[0].file!.fileName).toBe(absoluteFrom('/test.ts')); }); it('should throw if `styleUrls` is defined incorrectly in @Component', async () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '...', // @ts-ignore styleUrls: '...' }) export class TestCmp {} `, ); const diags = await driveDiagnostics(); expect(diags.length).toBe(1); const messageText = ts.flattenDiagnosticMessageText(diags[0].messageText, '\n'); expect(messageText).toContain('styleUrls must be an array of strings'); expect(messageText).toContain("Value is of type 'string'."); expect(diags[0].file!.fileName).toBe(absoluteFrom('/test.ts')); }); }); }); describe('flat module indices', () => { it('should generate a basic flat module index', () => { env.tsconfig({ 'flatModuleOutFile': 'flat.js', }); env.write('test.ts', 'export const TEST = "this is a test";'); env.driveMain(); const jsContents = env.getContents('flat.js'); expect(jsContents).toContain("export * from './test';"); }); it('should determine the flat module entry-point within multiple root files', () => { env.tsconfig({ 'flatModuleOutFile': 'flat.js',
{ "end_byte": 232082, "start_byte": 227209, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_232088_240790
}); env.write('ignored.ts', 'export const TEST = "this is ignored";'); env.write('index.ts', 'export const ENTRY = "this is the entry";'); env.driveMain(); const jsContents = env.getContents('flat.js'); expect(jsContents).toContain( "export * from './index';", 'Should detect the "index.ts" file as flat module entry-point.', ); }); it('should generate a flat module with an id', () => { env.tsconfig({ 'flatModuleOutFile': 'flat.js', 'flatModuleId': '@mymodule', }); env.write('test.ts', 'export const TEST = "this is a test";'); env.driveMain(); const dtsContents = env.getContents('flat.d.ts'); expect(dtsContents).toContain('/// <amd-module name="@mymodule" />'); }); it('should generate a proper flat module index file when nested', () => { env.tsconfig({ 'flatModuleOutFile': './public-api/index.js', }); env.write('test.ts', `export const SOME_EXPORT = 'some-export'`); env.driveMain(); expect(env.getContents('./public-api/index.js')).toContain(`export * from '../test';`); }); it('should not throw if "flatModuleOutFile" is set to null', () => { env.tsconfig({ 'flatModuleOutFile': null, }); env.write('test.ts', `export const SOME_EXPORT = 'some-export'`); // The "driveMain" method automatically ensures that there is no // exception and that the build succeeded. env.driveMain(); }); it( 'should not throw or produce flat module index if "flatModuleOutFile" is set to ' + 'empty string', () => { env.tsconfig({ 'flatModuleOutFile': '', }); env.write('test.ts', `export const SOME_EXPORT = 'some-export'`); // The "driveMain" method automatically ensures that there is no // exception and that the build succeeded. env.driveMain(); // Previously ngtsc incorrectly tried generating a flat module index // file if the "flatModuleOutFile" was set to an empty string. ngtsc // just wrote the bundle file with an empty filename (just extension). env.assertDoesNotExist('.js'); env.assertDoesNotExist('.d.ts'); }, ); it('should report an error when a flat module index is requested but no entrypoint can be determined', () => { env.tsconfig({'flatModuleOutFile': 'flat.js'}); env.write('test.ts', 'export class Foo {}'); env.write('test2.ts', 'export class Bar {}'); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); expect(errors[0].messageText).toBe( 'Angular compiler option "flatModuleOutFile" requires one and only one .ts file in the "files" field.', ); }); it('should report an error when a visible directive is not exported', () => { env.tsconfig({'flatModuleOutFile': 'flat.js'}); env.write( 'test.ts', ` import {Directive, NgModule} from '@angular/core'; // The directive is not exported. @Directive({ selector: 'test', standalone: false, }) class Dir {} // The module is, which makes the directive visible. @NgModule({declarations: [Dir], exports: [Dir]}) export class Module {} `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); expect(errors[0].messageText).toBe( 'Unsupported private class Dir. This class is visible ' + 'to consumers via Module -> Dir, but is not exported from the top-level library ' + 'entrypoint.', ); // Verify that the error is for the correct class. const error = errors[0] as ts.Diagnostic; const id = expectTokenAtPosition(error.file!, error.start!, ts.isIdentifier); expect(id.text).toBe('Dir'); expect(ts.isClassDeclaration(id.parent)).toBe(true); }); it('should report an error when a visible host directive is not exported', () => { env.tsconfig({'flatModuleOutFile': 'flat.js'}); env.write( 'test.ts', ` import {Directive, NgModule} from '@angular/core'; @Directive({ standalone: true, }) class HostDir {} // The directive is not exported. @Directive({selector: 'test', hostDirectives: [HostDir]}) export class Dir {} `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); expect(errors[0].code).toBe(ngErrorCode(ErrorCode.SYMBOL_NOT_EXPORTED)); }); it('should report an error when a deeply visible directive is not exported', () => { env.tsconfig({'flatModuleOutFile': 'flat.js'}); env.write( 'test.ts', ` import {Directive, NgModule} from '@angular/core'; // The directive is not exported. @Directive({ selector: 'test', standalone: false, }) class Dir {} // Neither is the module which declares it - meaning the directive is not visible here. @NgModule({declarations: [Dir], exports: [Dir]}) class DirModule {} // The module is, which makes the directive visible. @NgModule({exports: [DirModule]}) export class Module {} `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(2); expect(errors[0].messageText).toBe( 'Unsupported private class DirModule. This class is ' + 'visible to consumers via Module -> DirModule, but is not exported from the top-level ' + 'library entrypoint.', ); expect(errors[1].messageText).toBe( 'Unsupported private class Dir. This class is visible ' + 'to consumers via Module -> DirModule -> Dir, but is not exported from the top-level ' + 'library entrypoint.', ); }); it('should report an error when a deeply visible module is not exported', () => { env.tsconfig({'flatModuleOutFile': 'flat.js'}); env.write( 'test.ts', ` import {Directive, NgModule} from '@angular/core'; // The directive is exported. @Directive({ selector: 'test', standalone: false, }) export class Dir {} // The module which declares it is not. @NgModule({declarations: [Dir], exports: [Dir]}) class DirModule {} // The module is, which makes the module and directive visible. @NgModule({exports: [DirModule]}) export class Module {} `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(1); expect(errors[0].messageText).toBe( 'Unsupported private class DirModule. This class is ' + 'visible to consumers via Module -> DirModule, but is not exported from the top-level ' + 'library entrypoint.', ); }); it('should not report an error when a non-exported module is imported by a visible one', () => { env.tsconfig({'flatModuleOutFile': 'flat.js'}); env.write( 'test.ts', ` import {Directive, NgModule} from '@angular/core'; // The directive is not exported. @Directive({ selector: 'test', standalone: false, }) class Dir {} // Neither is the module which declares it. @NgModule({declarations: [Dir], exports: [Dir]}) class DirModule {} // This module is, but it doesn't re-export the module, so it doesn't make the module and // directive visible. @NgModule({imports: [DirModule]}) export class Module {} `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(0); }); it('should not report an error when re-exporting an external symbol', () => { env.tsconfig({'flatModuleOutFile': 'flat.js'}); env.write( 'test.ts', ` import {Directive, NgModule} from '@angular/core'; import {ExternalModule} from 'external'; // This module makes ExternalModule and ExternalDir visible. @NgModule({exports: [ExternalModule]}) export class Module {} `, ); env.write( 'node_modules/external/index.d.ts', ` import {ɵɵDirec
{ "end_byte": 240790, "start_byte": 232088, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_240798_249947
aration, ɵɵNgModuleDeclaration} from '@angular/core'; export declare class ExternalDir { static ɵdir: ɵɵDirectiveDeclaration<ExternalDir, '[test]', never, never, never, never>; } export declare class ExternalModule { static ɵmod: ɵɵNgModuleDeclaration<ExternalModule, [typeof ExternalDir], never, [typeof ExternalDir]>; } `, ); const errors = env.driveDiagnostics(); expect(errors.length).toBe(0); }); }); describe('aliasing re-exports', () => { beforeEach(() => { env.tsconfig({ 'generateDeepReexports': true, }); }); it('should re-export a directive from a different file under a private symbol name', () => { env.write( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: 'dir', standalone: false, }) export class Dir {} `, ); env.write( 'module.ts', ` import {Directive, NgModule} from '@angular/core'; import {Dir} from './dir'; @Directive({ selector: '[inline]', standalone: false, }) export class InlineDir {} @NgModule({ declarations: [Dir, InlineDir], exports: [Dir, InlineDir], }) export class Module {} `, ); env.driveMain(); const jsContents = env.getContents('module.js'); const dtsContents = env.getContents('module.d.ts'); expect(jsContents).toContain('export { Dir as ɵngExportɵModuleɵDir } from "./dir";'); expect(jsContents).not.toContain('ɵngExportɵModuleɵInlineDir'); expect(dtsContents).toContain('export { Dir as ɵngExportɵModuleɵDir } from "./dir";'); expect(dtsContents).not.toContain('ɵngExportɵModuleɵInlineDir'); }); it('should re-export a directive from an exported NgModule under a private symbol name', () => { env.write( 'dir.ts', ` import {Directive, NgModule} from '@angular/core'; @Directive({ selector: 'dir', standalone: false, }) export class Dir {} @NgModule({ declarations: [Dir], exports: [Dir], }) export class DirModule {} `, ); env.write( 'module.ts', ` import {NgModule} from '@angular/core'; import {DirModule} from './dir'; @NgModule({ exports: [DirModule], }) export class Module {} `, ); env.driveMain(); const jsContents = env.getContents('module.js'); const dtsContents = env.getContents('module.d.ts'); expect(jsContents).toContain('export { Dir as ɵngExportɵModuleɵDir } from "./dir";'); expect(dtsContents).toContain('export { Dir as ɵngExportɵModuleɵDir } from "./dir";'); }); it("should not re-export a directive that's not exported from the NgModule", () => { env.write( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: 'dir', standalone: false, }) export class Dir {} `, ); env.write( 'module.ts', ` import {NgModule} from '@angular/core'; import {Dir} from './dir'; @NgModule({ declarations: [Dir], exports: [], }) export class Module {} `, ); env.driveMain(); const jsContents = env.getContents('module.js'); const dtsContents = env.getContents('module.d.ts'); expect(jsContents).not.toContain('ɵngExportɵModuleɵDir'); expect(dtsContents).not.toContain('ɵngExportɵModuleɵDir'); }); it("should not re-export a directive that's already exported", () => { env.write( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: 'dir', standalone: false, }) export class Dir {} `, ); env.write( 'module.ts', ` import {NgModule} from '@angular/core'; import {Dir} from './dir'; @NgModule({ declarations: [Dir], exports: [Dir], }) export class Module {} export {Dir}; `, ); env.driveMain(); const jsContents = env.getContents('module.js'); const dtsContents = env.getContents('module.d.ts'); expect(jsContents).not.toContain('ɵngExportɵModuleɵDir'); expect(dtsContents).not.toContain('ɵngExportɵModuleɵDir'); }); it('should not re-export a directive from an exported, external NgModule', () => { env.write( `node_modules/external/index.d.ts`, ` import {ɵɵDirectiveDeclaration, ɵɵNgModuleDeclaration} from '@angular/core'; export declare class ExternalDir { static ɵdir: ɵɵDirectiveDeclaration<ExternalDir, '[test]', never, never, never, never>; } export declare class ExternalModule { static ɵmod: ɵɵNgModuleDeclaration<ExternalModule, [typeof ExternalDir], never, [typeof ExternalDir]>; } `, ); env.write( 'module.ts', ` import {NgModule} from '@angular/core'; import {ExternalModule} from 'external'; @NgModule({ exports: [ExternalModule], }) export class Module {} `, ); env.driveMain(); const jsContents = env.getContents('module.js'); expect(jsContents).not.toContain('ɵngExportɵExternalModuleɵExternalDir'); }); it('should error when two directives with the same declared name are exported from the same NgModule', () => { env.write( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: 'dir', standalone: false, }) export class Dir {} `, ); env.write( 'dir2.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: 'dir', standalone: false, }) export class Dir {} `, ); env.write( 'module.ts', ` import {NgModule} from '@angular/core'; import {Dir} from './dir'; import {Dir as Dir2} from './dir2'; @NgModule({ declarations: [Dir, Dir2], exports: [Dir, Dir2], }) export class Module {} `, ); const diag = env.driveDiagnostics(); expect(diag.length).toBe(1); expect(diag[0]!.code).toEqual(ngErrorCode(ErrorCode.NGMODULE_REEXPORT_NAME_COLLISION)); }); it('should not error when two directives with the same declared name are exported from the same NgModule, but one is exported from the file directly', () => { env.write( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: 'dir', standalone: false, }) export class Dir {} `, ); env.write( 'dir2.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: 'dir', standalone: false, }) export class Dir {} `, ); env.write( 'module.ts', ` import {NgModule} from '@angular/core'; import {Dir} from './dir'; import {Dir as Dir2} from './dir2'; @NgModule({ declarations: [Dir, Dir2], exports: [Dir, Dir2], }) export class Module {} export {Dir} from './dir2'; `, ); env.driveMain(); const jsContents = env.getContents('module.js'); expect(jsContents).toContain('export { Dir as ɵngExportɵModuleɵDir } from "./dir";'); }); it('should choose a re-exported symbol if one is present', () => { env.write( `node_modules/external/dir.d.ts`, ` import {ɵɵDirectiveDeclaration} from '@angular/core'; export declare class ExternalDir { static ɵdir: ɵɵDirectiveDeclaration<ExternalDir, '[test]', never, never, never, never>; } `, ); env.write( 'node_modules/external/module.d.ts', ` import {ɵɵNgModuleDeclaration} from '@angular/core'; import {ExternalDir} from './dir'; export declare class ExternalModu
{ "end_byte": 249947, "start_byte": 240798, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_249955_258094
static ɵmod: ɵɵNgModuleDeclaration<ExternalModule, [typeof ExternalDir], never, [typeof ExternalDir]>; } export {ExternalDir as ɵngExportɵExternalModuleɵExternalDir}; `, ); env.write( 'test.ts', ` import {Component, Directive, NgModule} from '@angular/core'; import {ExternalModule} from 'external/module'; @Component({ selector: 'test-cmp', template: '<div test></div>', standalone: false, }) class Cmp {} @NgModule({ declarations: [Cmp], imports: [ExternalModule], }) class Module {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('import * as i1 from "external/module";'); expect(jsContents).toContain('dependencies: [i1.ɵngExportɵExternalModuleɵExternalDir]'); }); it('should not generate re-exports when disabled', () => { // Return to the default configuration, which has re-exports disabled. env.tsconfig(); env.write( 'dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: 'dir', standalone: false, }) export class Dir {} `, ); env.write( 'module.ts', ` import {NgModule} from '@angular/core'; import {Dir} from './dir'; @NgModule({ declarations: [Dir], exports: [Dir], }) export class Module {} `, ); env.driveMain(); const jsContents = env.getContents('module.js'); const dtsContents = env.getContents('module.d.ts'); expect(jsContents).not.toContain('ɵngExportɵModuleɵDir'); expect(dtsContents).not.toContain('ɵngExportɵModuleɵDir'); }); }); it('should execute custom transformers', () => { let beforeCount = 0; let afterCount = 0; env.write( 'test.ts', ` import {NgModule} from '@angular/core'; @NgModule({}) class Module {} `, ); env.driveMain({ beforeTs: [ () => (sourceFile: ts.SourceFile) => { beforeCount++; return sourceFile; }, ], afterTs: [ () => (sourceFile: ts.SourceFile) => { afterCount++; return sourceFile; }, ], }); expect(beforeCount).toBe(1); expect(afterCount).toBe(1); }); describe('sanitization', () => { it('should generate sanitizers for unsafe attributes in hostBindings fn in Directives', () => { env.write( `test.ts`, ` import {Component, Directive, HostBinding, NgModule, Input} from '@angular/core'; @Directive({ selector: '[unsafeAttrs]', standalone: false, }) class UnsafeAttrsDirective { @HostBinding('attr.href') attrHref: string; @HostBinding('attr.src') attrSrc: string; @HostBinding('attr.action') attrAction: string; @HostBinding('attr.profile') attrProfile: string; @HostBinding('attr.innerHTML') attrInnerHTML: string; @HostBinding('attr.title') attrSafeTitle: string; @Input() unsafeAttrs: any; } @Component({ selector: 'foo', template: '<a [unsafeAttrs]="ctxProp">Link Title</a>', standalone: false, }) class FooCmp { ctxProp = ''; } @NgModule({declarations: [FooCmp, UnsafeAttrsDirective]}) export class Module {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const hostBindingsFn = ` hostVars: 6, hostBindings: function UnsafeAttrsDirective_HostBindings(rf, ctx) { if (rf & 2) { i0.ɵɵattribute("href", ctx.attrHref, i0.ɵɵsanitizeUrlOrResourceUrl)("src", ctx.attrSrc, i0.ɵɵsanitizeUrlOrResourceUrl)("action", ctx.attrAction, i0.ɵɵsanitizeUrl)("profile", ctx.attrProfile, i0.ɵɵsanitizeResourceUrl)("innerHTML", ctx.attrInnerHTML, i0.ɵɵsanitizeHtml)("title", ctx.attrSafeTitle); } } `; expect(trim(jsContents)).toContain(trim(hostBindingsFn)); }); it('should generate sanitizers for unsafe properties in hostBindings fn in Directives', () => { env.write( `test.ts`, ` import {Component, Directive, HostBinding, Input, NgModule} from '@angular/core'; @Directive({ selector: '[unsafeProps]', standalone: false, }) class UnsafePropsDirective { @HostBinding('href') propHref: string; @HostBinding('src') propSrc: string; @HostBinding('action') propAction: string; @HostBinding('profile') propProfile: string; @HostBinding('innerHTML') propInnerHTML: string; @HostBinding('title') propSafeTitle: string; @Input() unsafeProps: any; } @Component({ selector: 'foo', template: '<a [unsafeProps]="ctxProp">Link Title</a>', standalone: false, }) class FooCmp { ctxProp = ''; } @NgModule({declarations: [FooCmp, UnsafePropsDirective]}) class MyModule {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const hostBindingsFn = ` hostVars: 6, hostBindings: function UnsafePropsDirective_HostBindings(rf, ctx) { if (rf & 2) { i0.ɵɵhostProperty("href", ctx.propHref, i0.ɵɵsanitizeUrlOrResourceUrl)("src", ctx.propSrc, i0.ɵɵsanitizeUrlOrResourceUrl)("action", ctx.propAction, i0.ɵɵsanitizeUrl)("profile", ctx.propProfile, i0.ɵɵsanitizeResourceUrl)("innerHTML", ctx.propInnerHTML, i0.ɵɵsanitizeHtml)("title", ctx.propSafeTitle); } } `; expect(trim(jsContents)).toContain(trim(hostBindingsFn)); }); it('should not generate sanitizers for URL properties in hostBindings fn in Component', () => { env.write( `test.ts`, ` import {Component} from '@angular/core'; @Component({ selector: 'foo', template: '<a href="example.com">Link Title</a>', host: { '[src]': 'srcProp', '[href]': 'hrefProp', '[title]': 'titleProp', '[attr.src]': 'srcAttr', '[attr.href]': 'hrefAttr', '[attr.title]': 'titleAttr', } }) class FooCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); const hostBindingsFn = ` hostVars: 6, hostBindings: function FooCmp_HostBindings(rf, ctx) { if (rf & 2) { i0.ɵɵhostProperty("src", ctx.srcProp)("href", ctx.hrefProp)("title", ctx.titleProp); i0.ɵɵattribute("src", ctx.srcAttr)("href", ctx.hrefAttr)("title", ctx.titleAttr); } } `; expect(trim(jsContents)).toContain(trim(hostBindingsFn)); }); }); describe('NgModule export aliasing', () => { it('should use an alias to import a directive from a deep dependency when _useHostForImportAndAliasGeneration is set', () => { env.tsconfig({'_useHostForImportAndAliasGeneration': true}); // 'alpha' declares the directive which will ultimately be imported. env.write( 'alpha.d.ts', ` import {ɵɵDirectiveDeclaration, ɵɵNgModuleDeclaration} from '@angular/core'; export declare class ExternalDir { static ɵdir: ɵɵDirectiveDeclaration<ExternalDir, '[test]', never, never, never, never>; } export declare class AlphaModule {
{ "end_byte": 258094, "start_byte": 249955, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_258100_266978
c ɵmod: ɵɵNgModuleDeclaration<AlphaModule, [typeof ExternalDir], never, [typeof ExternalDir]>; } `, ); // 'beta' re-exports AlphaModule from alpha. env.write( 'beta.d.ts', ` import {ɵɵNgModuleDeclaration} from '@angular/core'; import {AlphaModule} from './alpha'; export declare class BetaModule { static ɵmod: ɵɵNgModuleDeclaration<AlphaModule, never, never, [typeof AlphaModule]>; } `, ); // The application imports BetaModule from beta, gaining visibility of // ExternalDir from alpha. env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; import {BetaModule} from './beta'; @Component({ selector: 'cmp', template: '<div test></div>', standalone: false, }) export class Cmp {} @NgModule({ declarations: [Cmp], imports: [BetaModule], }) export class Module {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // Expect that ExternalDir from alpha is imported via the re-export from beta. expect(jsContents).toContain('import * as i1 from "root/beta";'); expect(jsContents).toContain('dependencies: [i1.\u0275ng$root$alpha$$ExternalDir]'); }); it('should directly import a directive from a deep dependency when _useHostForImportGeneration is set', () => { env.tsconfig({'_useHostForImportGeneration': true}); // 'alpha' declares the directive which will ultimately be imported. env.write( 'alpha.d.ts', ` import {ɵɵDirectiveDeclaration, ɵɵNgModuleDeclaration} from '@angular/core'; export declare class ExternalDir { static ɵdir: ɵɵDirectiveDeclaration<ExternalDir, '[test]', never, never, never, never>; } export declare class AlphaModule { static ɵmod: ɵɵNgModuleDeclaration<AlphaModule, [typeof ExternalDir], never, [typeof ExternalDir]>; } `, ); // 'beta' re-exports AlphaModule from alpha. env.write( 'beta.d.ts', ` import {ɵɵNgModuleDeclaration} from '@angular/core'; import {AlphaModule} from './alpha'; export declare class BetaModule { static ɵmod: ɵɵNgModuleDeclaration<AlphaModule, never, never, [typeof AlphaModule]>; } `, ); // The application imports BetaModule from beta, gaining visibility of // ExternalDir from alpha. env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; import {BetaModule} from './beta'; @Component({ selector: 'cmp', template: '<div test></div>', standalone: false, }) export class Cmp {} @NgModule({ declarations: [Cmp], imports: [BetaModule], }) export class Module {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // Expect that ExternalDir from alpha is imported via the re-export from beta. expect(jsContents).toContain('import * as i1 from "root/alpha";'); expect(jsContents).toContain('dependencies: [i1.ExternalDir]'); }); it('should write alias ES2015 exports for NgModule exported directives when _useHostForImportAndAliasGeneration is set', () => { env.tsconfig({'_useHostForImportAndAliasGeneration': true}); env.write( 'external.d.ts', ` import {ɵɵDirectiveDeclaration, ɵɵNgModuleDeclaration} from '@angular/core'; import {LibModule} from './lib'; export declare class ExternalDir { static ɵdir: ɵɵDirectiveDeclaration<ExternalDir, '[test]', never, never, never, never>; } export declare class ExternalModule { static ɵmod: ɵɵNgModuleDeclaration<ExternalModule, [typeof ExternalDir], never, [typeof ExternalDir, typeof LibModule]>; } `, ); env.write( 'lib.d.ts', ` import {ɵɵDirectiveDeclaration, ɵɵNgModuleDeclaration} from '@angular/core'; export declare class LibDir { static ɵdir: ɵɵDirectiveDeclaration<LibDir, '[lib]', never, never, never, never>; } export declare class LibModule { static ɵmod: ɵɵNgModuleDeclaration<LibModule, [typeof LibDir], never, [typeof LibDir]>; } `, ); env.write( 'foo.ts', ` import {Directive, NgModule} from '@angular/core'; import {ExternalModule} from './external'; @Directive({ selector: '[foo]', standalone: false, }) export class FooDir {} @NgModule({ declarations: [FooDir], exports: [FooDir, ExternalModule] }) export class FooModule {} `, ); env.write( 'index.ts', ` import {Component, NgModule} from '@angular/core'; import {FooModule} from './foo'; @Component({ selector: 'index', template: '<div foo test lib></div>', standalone: false, }) export class IndexCmp {} @NgModule({ declarations: [IndexCmp], exports: [FooModule], }) export class IndexModule {} `, ); env.driveMain(); const jsContents = env.getContents('index.js'); expect(jsContents).toContain( 'export { FooDir as \u0275ng$root$foo$$FooDir } from "root/foo";', ); }); it('should not write alias ES2015 exports for NgModule exported directives when _useHostForImportGeneration is set', () => { env.tsconfig({'_useHostForImportGeneration': true}); env.write( 'external.d.ts', ` import {ɵɵDirectiveDeclaration, ɵɵNgModuleDeclaration} from '@angular/core'; import {LibModule} from './lib'; export declare class ExternalDir { static ɵdir: ɵɵDirectiveDeclaration<ExternalDir, '[test]', never, never, never, never>; } export declare class ExternalModule { static ɵmod: ɵɵNgModuleDeclaration<ExternalModule, [typeof ExternalDir], never, [typeof ExternalDir, typeof LibModule]>; } `, ); env.write( 'lib.d.ts', ` import {ɵɵDirectiveDeclaration, ɵɵNgModuleDeclaration} from '@angular/core'; export declare class LibDir { static ɵdir: ɵɵDirectiveDeclaration<LibDir, '[lib]', never, never, never, never>; } export declare class LibModule { static ɵmod: ɵɵNgModuleDeclaration<LibModule, [typeof LibDir], never, [typeof LibDir]>; } `, ); env.write( 'foo.ts', ` import {Directive, NgModule} from '@angular/core'; import {ExternalModule} from './external'; @Directive({ selector: '[foo]', standalone: false, }) export class FooDir {} @NgModule({ declarations: [FooDir], exports: [FooDir, ExternalModule] }) export class FooModule {} `, ); env.write( 'index.ts', ` import {Component, NgModule} from '@angular/core'; import {FooModule} from './foo'; @Component({ selector: 'index', template: '<div foo test lib></div>', standalone: false, }) export class IndexCmp {} @NgModule({ declarations: [IndexCmp], exports: [FooModule], }) export class IndexModule {} `, ); env.driveMain(); const jsContents = env.getContents('index.js'); expect(jsContents).not.toMatch( /export\s+\{\s*FooDir\s+as\s+ \u0275ng$root$foo$$FooDir\s*\}\s+from\s+"root\/foo";/, ); }); it('should escape unusual characters in aliased filenames', () => { env.tsconfig({'_useHostForImportAndAliasGeneration': true}); env.write( 'other._$test.ts', ` import {Directive, NgModule} from '@angular/core'; @Directive({ selector: 'test', standalone: false, }) export class TestDir {} @NgModule({ declarations: [TestDir], exports: [TestDir], }) export class OtherModule {} `, ); env.write( 'index.ts', ` import {NgModule} from '@angular/core'; import {OtherModule} from './other._$test'; @NgModule({ exports: [OtherModule],
{ "end_byte": 266978, "start_byte": 258100, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_266986_269652
}) export class IndexModule {} `, ); env.driveMain(); const jsContents = env.getContents('index.js'); expect(jsContents).toContain( 'export { TestDir as \u0275ng$root$other___test$$TestDir } from "root/other._$test";', ); }); }); describe('disableTypeScriptVersionCheck', () => { afterEach(() => restoreTypeScriptVersionForTesting()); it('produces an error when not supported and version check is enabled', () => { setTypeScriptVersionForTesting('3.4.0'); env.tsconfig({disableTypeScriptVersionCheck: false}); env.write('empty.ts', ''); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain('but 3.4.0 was found instead'); }); it('does not produce an error when supported and version check is enabled', () => { env.tsconfig({disableTypeScriptVersionCheck: false}); env.write('empty.ts', ''); // The TypeScript version is not overwritten, so the version // that is actually used should be supported const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('does not produce an error when not supported but version check is disabled', () => { setTypeScriptVersionForTesting('3.4.0'); env.tsconfig({disableTypeScriptVersionCheck: true}); env.write('empty.ts', ''); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('produces an error when not supported using default configuration', () => { setTypeScriptVersionForTesting('3.4.0'); env.write('empty.ts', ''); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain('but 3.4.0 was found instead'); }); }); describe('inherited directives', () => { beforeEach(() => { env.write( 'local.ts', ` import {Component, Directive, ElementRef} from '@angular/core'; export class BasePlain {} export class BasePlainWithBlankConstructor { constructor() {} } export class BasePlainWithConstructorParameters { constructor(elementRef: ElementRef) {} } @Component({ selector: 'base-cmp', template: 'BaseCmp', }) export class BaseCmp {} @Directive({ selector: '[base]', }) export class BaseDir {} `, ); env.write(
{ "end_byte": 269652, "start_byte": 266986, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_269658_278774
ib.d.ts', ` import {ɵɵComponentDeclaration, ɵɵDirectiveDeclaration, ElementRef} from '@angular/core'; export declare class BasePlain {} export declare class BasePlainWithBlankConstructor { constructor() {} } export declare class BasePlainWithConstructorParameters { constructor(elementRef: ElementRef) {} } export declare class BaseCmp { static ɵcmp: ɵɵComponentDeclaration<BaseCmp, "base-cmp", never, {}, {}, never> } export declare class BaseDir { static ɵdir: ɵɵDirectiveDeclaration<BaseDir, '[base]', never, never, never, never>; } `, ); }); it('should not error when inheriting a constructor from a decorated directive class', () => { env.tsconfig(); env.write( 'test.ts', ` import {Directive, Component} from '@angular/core'; import {BaseDir, BaseCmp} from './local'; @Directive({ selector: '[dir]', }) export class Dir extends BaseDir {} @Component({ selector: 'test-cmp', template: 'TestCmp', }) export class Cmp extends BaseCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not error when inheriting a constructor without parameters', () => { env.tsconfig(); env.write( 'test.ts', ` import {Directive, Component} from '@angular/core'; import {BasePlainWithBlankConstructor} from './local'; @Directive({ selector: '[dir]', }) export class Dir extends BasePlainWithBlankConstructor {} @Component({ selector: 'test-cmp', template: 'TestCmp', }) export class Cmp extends BasePlainWithBlankConstructor {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not error when inheriting from a class without a constructor', () => { env.tsconfig(); env.write( 'test.ts', ` import {Directive, Component} from '@angular/core'; import {BasePlain} from './local'; @Directive({ selector: '[dir]', }) export class Dir extends BasePlain {} @Component({ selector: 'test-cmp', template: 'TestCmp', }) export class Cmp extends BasePlain {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should error when inheriting a constructor from an undecorated class', () => { env.tsconfig(); env.write( 'test.ts', ` import {Directive, Component} from '@angular/core'; import {BasePlainWithConstructorParameters} from './local'; @Directive({ selector: '[dir]', }) export class Dir extends BasePlainWithConstructorParameters {} @Component({ selector: 'test-cmp', template: 'TestCmp', }) export class Cmp extends BasePlainWithConstructorParameters {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toContain('Dir'); expect(diags[0].messageText).toContain('BasePlainWithConstructorParameters'); expect(diags[1].messageText).toContain('Cmp'); expect(diags[1].messageText).toContain('BasePlainWithConstructorParameters'); }); it('should error when inheriting a constructor from undecorated grand super class', () => { env.tsconfig(); env.write( 'test.ts', ` import {Directive, Component} from '@angular/core'; import {BasePlainWithConstructorParameters} from './local'; class Parent extends BasePlainWithConstructorParameters {} @Directive({ selector: '[dir]', }) export class Dir extends Parent {} @Component({ selector: 'test-cmp', template: 'TestCmp', }) export class Cmp extends Parent {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toContain('Dir'); expect(diags[0].messageText).toContain('BasePlainWithConstructorParameters'); expect(diags[1].messageText).toContain('Cmp'); expect(diags[1].messageText).toContain('BasePlainWithConstructorParameters'); }); it('should error when inheriting a constructor from undecorated grand grand super class', () => { env.tsconfig(); env.write( 'test.ts', ` import {Directive, Component} from '@angular/core'; import {BasePlainWithConstructorParameters} from './local'; class GrandParent extends BasePlainWithConstructorParameters {} class Parent extends GrandParent {} @Directive({ selector: '[dir]', }) export class Dir extends Parent {} @Component({ selector: 'test-cmp', template: 'TestCmp', }) export class Cmp extends Parent {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toContain('Dir'); expect(diags[0].messageText).toContain('BasePlainWithConstructorParameters'); expect(diags[1].messageText).toContain('Cmp'); expect(diags[1].messageText).toContain('BasePlainWithConstructorParameters'); }); it('should not error when inheriting a constructor from decorated directive or component classes in a .d.ts file', () => { env.tsconfig(); env.write( 'test.ts', ` import {Component, Directive} from '@angular/core'; import {BaseDir, BaseCmp} from './lib'; @Directive({ selector: '[dir]', }) export class Dir extends BaseDir {} @Component({ selector: 'test-cmp', template: 'TestCmp', }) export class Cmp extends BaseCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should error when inheriting a constructor from an undecorated class in a .d.ts file', () => { env.tsconfig(); env.write( 'test.ts', ` import {Directive} from '@angular/core'; import {BasePlainWithConstructorParameters} from './lib'; @Directive({ selector: '[dir]', }) export class Dir extends BasePlainWithConstructorParameters {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain('Dir'); expect(diags[0].messageText).toContain('Base'); }); it('should produce a diagnostic if an inherited required input is not bound', () => { env.tsconfig(); env.write( 'test.ts', ` import {Directive, Component, Input} from '@angular/core'; @Directive() export class BaseDir { @Input({required: true}) input: any; } @Directive({ selector: '[dir]', standalone: true }) export class Dir extends BaseDir {} @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: true, imports: [Dir] }) export class Cmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Required input 'input' from directive Dir must be specified.`, ); }); it('should not produce a diagnostic if an inherited required input is bound', () => { env.tsconfig(); env.write( 'test.ts', ` import {Directive, Component, Input} from '@angular/core'; @Directive() export class BaseDir { @Input({required: true}) input: any; } @Directive({ selector: '[dir]', standalone: true }) export class Dir extends BaseDir {} @Component({ selector: 'test-cmp', template: '<div dir [input]="value"></div>', standalone: true, imports: [Dir] }) export class Cmp { value = 123; }
{ "end_byte": 278774, "start_byte": 269658, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_278782_287491
); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); }); describe('inline resources', () => { it('should process inline <style> tags', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '<style>h1 {font-size: larger}</style>', styles: ['h2 {width: 10px}'] }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain( 'styles: ["h2[_ngcontent-%COMP%] {width: 10px}", "h1[_ngcontent-%COMP%] {font-size: larger}"]', ); }); it('should process inline <link> tags', () => { env.write('style.css', `h1 {font-size: larger}`); env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: '<link rel="stylesheet" href="./style.css">', }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('styles: ["h1[_ngcontent-%COMP%] {font-size: larger}"]'); }); it('should share same styles declared in different components in the same file', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp-a', template: 'Comp A', styles: [ 'span { font-size: larger; }', 'div { background: url(/some-very-very-long-path.png); }', 'img { background: url(/a/some-very-very-long-path.png); }' ] }) export class CompA {} @Component({ selector: 'comp-b', template: 'Comp B', styles: [ 'span { font-size: larger; }', 'div { background: url(/some-very-very-long-path.png); }', 'img { background: url(/b/some-very-very-long-path.png); }' ] }) export class CompB {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // Verify that long styles present in both components are extracted to a // separate var. expect(jsContents).toContain( '_c0 = "div[_ngcontent-%COMP%] { background: url(/some-very-very-long-path.png); }";', ); expect(jsContents).toContain( 'styles: [' + // This style is present in both components, but was not extracted into // a separate var since it doesn't reach length threshold (50 chars) in // `ConstantPool`. '"span[_ngcontent-%COMP%] { font-size: larger; }", ' + // Style that is present in both components, but reaches length // threshold - extracted to a separate var. '_c0, ' + // Style that is unique to this component, but that reaches length // threshold - remains a string in the `styles` array. '"img[_ngcontent-%COMP%] { background: url(/a/some-very-very-long-path.png); }"]', ); expect(jsContents).toContain( 'styles: [' + // This style is present in both components, but was not extracted into // a separate var since it doesn't reach length threshold (50 chars) in // `ConstantPool`. '"span[_ngcontent-%COMP%] { font-size: larger; }", ' + // Style that is present in both components, but reaches length // threshold - extracted to a separate var. '_c0, ' + // Style that is unique to this component, but that reaches length // threshold - remains a string in the `styles` array. '"img[_ngcontent-%COMP%] { background: url(/b/some-very-very-long-path.png); }"]', ); }); it('large strings are wrapped in a function for Closure', () => { env.tsconfig({ annotateForClosureCompiler: true, }); env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'comp-a', template: 'Comp A', styles: [ 'div { background: url(/a.png); }', 'div { background: url(/some-very-very-long-path.png); }', ] }) export class CompA {} @Component({ selector: 'comp-b', template: 'Comp B', styles: [ 'div { background: url(/b.png); }', 'div { background: url(/some-very-very-long-path.png); }', ] }) export class CompB {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // Verify that long strings are extracted to a separate var. This should be // wrapped in a function to trick Closure not to inline the contents for very // large strings. See: https://github.com/angular/angular/pull/38253. expect(jsContents).toContain( '_c0 = function () {' + ' return "div[_ngcontent-%COMP%] {' + ' background: url(/some-very-very-long-path.png);' + ' }";' + ' };', ); expect(jsContents).toContain( 'styles: [' + // Check styles for component A. '"div[_ngcontent-%COMP%] { background: url(/a.png); }", ' + // Large string should be called from function definition. '_c0()]', ); expect(jsContents).toContain( 'styles: [' + // Check styles for component B. '"div[_ngcontent-%COMP%] { background: url(/b.png); }", ' + // Large string should be called from function definition. '_c0()]', ); }); it('should process `styles` as a string', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '', styles: 'h2 {width: 10px}' }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('styles: ["h2[_ngcontent-%COMP%] {width: 10px}"]'); }); it('should process `styleUrl`', () => { env.write('dir/styles.css', 'h2 {width: 10px}'); env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', styleUrl: 'dir/styles.css', template: '', }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).not.toContain('styleUrl'); expect(jsContents).toContain('styles: ["h2[_ngcontent-%COMP%] {width: 10px}"]'); }); it('should produce a diagnostic if both `styleUrls` and `styleUrl` are defined', () => { env.write('dir/styles.css', 'h2 {width: 10px}'); env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', styleUrl: 'dir/styles.css', styleUrls: ['dir/styles.css'], template: '', }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain( '@Component cannot define both `styleUrl` and `styleUrls`', ); }); }); describe('empty resources', () => { it('should not include empty inline styles in the compiled output', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; const someStyle = ' '; @Component({ selector: 'test-cmp', styles: ['', someStyle, ' '], template: '', }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).not.toContain('styles'); expect(jsContents).not.toContain('styleUrls'); }); it('should not include empty external styles in the compiled output', () => { env.wr
{ "end_byte": 287491, "start_byte": 278782, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_287497_297074
ir/a.css', ''); env.write('dir/b.css', ' '); env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', styleUrls: ['./dir/a.css', './dir/b.css'], template: '', }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).not.toContain('styles'); expect(jsContents).not.toContain('styleUrls'); }); it('should not include empty <link> tags that resolve to empty stylesheets', () => { env.write('dir/a.css', ''); env.write('dir/b.css', ' '); env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: \` <link rel="stylesheet" href="./dir/a.css"> <link rel="stylesheet" href="./dir/b.css"> \`, }) export class TestCmp {} `, ); env.driveMain(); const jsContents = env.getContents('test.js').replace(/<link [^>]*>/g, ''); expect(jsContents).not.toContain('styles'); expect(jsContents).not.toContain('styleUrls'); }); }); describe('non-exported classes', () => { beforeEach(() => env.tsconfig({compileNonExportedClasses: false})); it('should not emit directive definitions for non-exported classes if configured', () => { env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[test]' }) class TestDirective {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).not.toContain('defineDirective('); expect(jsContents).toContain('Directive({'); }); it('should not emit component definitions for non-exported classes if configured', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test', template: 'hello' }) class TestComponent {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).not.toContain('defineComponent('); expect(jsContents).toContain('Component({'); }); it('should not emit module definitions for non-exported classes if configured', () => { env.write( 'test.ts', ` import {NgModule} from '@angular/core'; @NgModule({ declarations: [] }) class TestModule {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).not.toContain('defineNgModule('); expect(jsContents).toContain('NgModule({'); }); it('should still compile a class that is indirectly exported', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: 'Test Cmp', }) class TestCmp {} export {TestCmp}; `, ); env.driveMain(); const jsContents = env.getContents('test.js'); expect(jsContents).toContain('defineComponent'); }); }); describe('iframe processing', () => { it('should generate attribute and property bindings with a validator fn when on <iframe>', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` <iframe src="http://angular.io" [sandbox]="''" [attr.allow]="''" [title]="'Hi!'" ></iframe> \` }) export class SomeComponent {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // Only `sandbox` has an extra validation fn (since it's security-sensitive), // the `title` property doesn't have an extra validation fn. expect(jsContents).toContain( 'ɵɵproperty("sandbox", "", i0.ɵɵvalidateIframeAttribute)("title", "Hi!")', ); // The `allow` property is also security-sensitive, thus an extra validation fn. expect(jsContents).toContain('ɵɵattribute("allow", "", i0.ɵɵvalidateIframeAttribute)'); }); it( 'should generate an attribute binding instruction with a validator function ' + "(making sure it's case-insensitive, since this is allowed in Angular templates)", () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` <IFRAME src="http://angular.io" [attr.SANDBOX]="''" ></IFRAME> \` }) export class SomeComponent {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // Make sure that the `sandbox` has an extra validation fn, // and the check is case-insensitive (since the `setAttribute` DOM API // is case-insensitive as well). expect(jsContents).toContain('ɵɵattribute("SANDBOX", "", i0.ɵɵvalidateIframeAttribute)'); }, ); it('should *not* generate a validator fn for attribute and property bindings when *not* on <iframe>', () => { env.write( 'test.ts', ` import {Component, Directive} from '@angular/core'; @Directive({ standalone: true, selector: '[sandbox]', inputs: ['sandbox'] }) class Dir {} @Component({ standalone: true, imports: [Dir], template: \` <div [sandbox]="''" [title]="'Hi!'"></div> \` }) export class SomeComponent {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // Note: no extra validation fn, since a security-sensitive attribute is *not* on an // <iframe>. expect(jsContents).toContain('ɵɵproperty("sandbox", "")("title", "Hi!")'); }); it('should generate a validator fn for attribute and property host bindings on a directive', () => { env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive({ host: { '[sandbox]': "''", '[attr.allow]': "''", 'src': 'http://angular.io' } }) export class SomeDir {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // The `sandbox` is potentially a security-sensitive attribute of an <iframe>. // Generate an extra validation function to invoke at runtime, which would // check if an underlying host element is an <iframe>. expect(jsContents).toContain('ɵɵhostProperty("sandbox", "", i0.ɵɵvalidateIframeAttribute)'); // Similar to the above, but for an attribute binding (host attributes are // represented via `ɵɵattribute`). expect(jsContents).toContain('ɵɵattribute("allow", "", i0.ɵɵvalidateIframeAttribute)'); }); it( 'should generate a validator fn for attribute host bindings on a directive ' + '(making sure the check is case-insensitive)', () => { env.write( 'test.ts', ` import {Directive} from '@angular/core'; @Directive({ host: { '[attr.SANDBOX]': "''" } }) export class SomeDir {} `, ); env.driveMain(); const jsContents = env.getContents('test.js'); // Make sure that we generate a validation fn for the `sandbox` attribute, // even when it was declared as `SANDBOX`. expect(jsContents).toContain('ɵɵattribute("SANDBOX", "", i0.ɵɵvalidateIframeAttribute)'); }, ); }); describe('undecorated providers', () => { it('should error when an undecorated class, with a non-trivial constructor, is provided directly in a module', () => { env.write( 'test.ts', ` import {NgModule, NgZone} from '@angular/core'; class NotAService { constructor(ngZone: NgZone) {} } @NgModule({ providers: [NotAService] }) export class SomeModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain('cannot be created via dependency injection'); }); it('should error when an undecorated class is provided via useClass',
{ "end_byte": 297074, "start_byte": 287497, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_297080_305925
{ env.write( 'test.ts', ` import {NgModule, Injectable, NgZone} from '@angular/core'; @Injectable({providedIn: 'root'}) class Service {} class NotAService { constructor(ngZone: NgZone) {} } @NgModule({ providers: [{provide: Service, useClass: NotAService}] }) export class SomeModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain('cannot be created via dependency injection'); }); it('should not error when an undecorated class is provided via useClass with deps', () => { env.write( 'test.ts', ` import {NgModule, Injectable, NgZone} from '@angular/core'; @Injectable({providedIn: 'root'}) class Service {} class NotAService { constructor(ngZone: NgZone) {} } @NgModule({ providers: [{provide: Service, useClass: NotAService, deps: [NgZone]}] }) export class SomeModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should error when an undecorated class is provided via an array', () => { env.write( 'test.ts', ` import {NgModule, Injectable, NgZone} from '@angular/core'; @Injectable({providedIn: 'root'}) class Service {} class NotAService { constructor(ngZone: NgZone) {} } @NgModule({ providers: [Service, [NotAService]] }) export class SomeModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain('cannot be created via dependency injection'); }); it('should error when an undecorated class is provided to a directive', () => { env.write( 'test.ts', ` import {NgModule, Directive, NgZone} from '@angular/core'; class NotAService { constructor(ngZone: NgZone) {} } @Directive({ selector: '[some-dir]', providers: [NotAService], standalone: false, }) class SomeDirective {} @NgModule({ declarations: [SomeDirective] }) export class SomeModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain('cannot be created via dependency injection'); }); it('should error when an undecorated class is provided to a component', () => { env.write( 'test.ts', ` import {NgModule, Component, NgZone} from '@angular/core'; class NotAService { constructor(ngZone: NgZone) {} } @Component({ selector: 'some-comp', template: '', providers: [NotAService], standalone: false, }) class SomeComponent {} @NgModule({ declarations: [SomeComponent] }) export class SomeModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain('cannot be created via dependency injection'); }); it('should error when an undecorated class is provided to a component via viewProviders', () => { env.write( 'test.ts', ` import {NgModule, Component, NgZone} from '@angular/core'; class NotAService { constructor(ngZone: NgZone) {} } @Component({ selector: 'some-comp', template: '', viewProviders: [NotAService], standalone: false, }) class SomeComponent {} @NgModule({ declarations: [SomeComponent] }) export class SomeModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain('cannot be created via dependency injection'); }); it('should not error when a class with a factory is provided', () => { env.write( 'test.ts', ` import {NgModule, Pipe} from '@angular/core'; @Pipe({ name: 'some-pipe', standalone: false, }) class SomePipe {} @NgModule({ declarations: [SomePipe], providers: [SomePipe] }) export class SomeModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not error when an NgModule is provided', () => { env.write( 'test.ts', ` import {Injectable, NgModule} from '@angular/core'; @Injectable() export class Service {} @NgModule({ }) class SomeModule { constructor(dep: Service) {} } @NgModule({ providers: [SomeModule], }) export class Module {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not error when an undecorated class from a declaration file is provided', () => { env.write( 'node_modules/@angular/core/testing/index.d.ts', ` export declare class Testability { } `, ); env.write( 'test.ts', ` import {NgModule} from '@angular/core'; import {Testability} from '@angular/core/testing'; @NgModule({ providers: [Testability] }) export class SomeModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not error when an undecorated class without a constructor from a declaration file is provided via useClass', () => { env.write( 'node_modules/@angular/core/testing/index.d.ts', ` export declare class Testability { } `, ); env.write( 'test.ts', ` import {NgModule, Injectable} from '@angular/core'; import {Testability} from '@angular/core/testing'; @Injectable() class TestingService {} @NgModule({ providers: [{provide: TestingService, useClass: Testability}] }) export class SomeModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not error if the undecorated class does not have a constructor or the constructor is blank', () => { env.write( 'test.ts', ` import {NgModule, NgZone} from '@angular/core'; class NoConstructorService { } class BlankConstructorService { } @NgModule({ providers: [NoConstructorService, BlankConstructorService] }) export class SomeModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); // TODO(alxhub): this test never worked correctly, as it used to declare a constructor // with a body, which real declaration files don't have. Without the body, the // ReflectionHost used to not return any constructor data, preventing an error from // showing. That bug was fixed, but the error for declaration files is disabled until g3 // can be updated. xit('should error when an undecorated class with a non-trivial constructor in a declaration file is provided via useClass', () => { env.write( 'node_modules/@angular/core/testing/index.d.ts', ` export declare class NgZone {} export declare class Testability { constructor(ngZone: NgZone); } `, ); env.write( 'test.ts', ` import {NgModule, Injectable} from '@angular/core'; import {Testability} from '@angular/core/testing'; @Injectable() class TestingService {} @NgModule({ providers: [{provide: TestingService, useClass: Testability}] }) export class
{ "end_byte": 305925, "start_byte": 297080, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_305932_315216
ule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toContain('cannot be created via dependency injection'); }); it('should not error when an class with a factory definition and a non-trivial constructor in a declaration file is provided via useClass', () => { env.write( 'node_modules/@angular/core/testing/index.d.ts', ` import * as i0 from '@angular/core'; export declare class NgZone {} export declare class Testability { static ɵfac: i0.ɵɵFactoryDeclaration<Testability, never>; constructor(ngZone: NgZone); } `, ); env.write( 'test.ts', ` import {NgModule, Injectable} from '@angular/core'; import {Testability} from '@angular/core/testing'; @Injectable() class TestingService {} @NgModule({ providers: [{provide: TestingService, useClass: Testability}] }) export class SomeModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); describe('template parsing diagnostics', () => { // These tests validate that errors which occur during template parsing are // expressed as diagnostics instead of a compiler crash (which used to be the // case). They only assert that the error is produced with an accurate span - // the exact semantics of the errors are tested separately, via the parser // tests. it('should emit a diagnostic for a template parsing error', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '<div></span>', selector: 'test-cmp', }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(getDiagnosticSourceCode(diags[0])).toBe('</span>'); }); it('should emit a diagnostic for an expression parsing error', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '<input [value]="x ? y"/>', selector: 'test-cmp', }) export class TestCmp { x = null; y = null; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(getDiagnosticSourceCode(diags[0])).toBe('x ? y'); }); it('should use a single character span for an unexpected EOF parsing error', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '<input [value]="x/>', selector: 'test-cmp', }) export class TestCmp { x = null; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(getDiagnosticSourceCode(diags[0])).toBe("'"); }); it('should emit both type-check diagnostics and parse error diagnostics', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \`<input (click)="x = 'invalid'"/> {{x = 2}}\`, selector: 'test-cmp', }) export class TestCmp { x: number = 1; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toEqual(`Type 'string' is not assignable to type 'number'.`); expect(diags[1].messageText).toContain( 'Parser Error: Bindings cannot contain assignments at column 5 in [ {{x = 2}}]', ); }); }); describe('shadow DOM selector diagnostics', () => { it('should emit a diagnostic when a selector does not include a hyphen', () => { env.write( 'test.ts', ` import {Component, ViewEncapsulation} from '@angular/core'; @Component({ template: '', selector: 'cmp', encapsulation: ViewEncapsulation.ShadowDom }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( 'Selector of a component that uses ViewEncapsulation.ShadowDom must contain a hyphen.', ); expect(getDiagnosticSourceCode(diags[0])).toBe(`'cmp'`); }); it('should emit a diagnostic when a selector includes uppercase letters', () => { env.write( 'test.ts', ` import {Component, ViewEncapsulation} from '@angular/core'; @Component({ template: '', selector: 'my-Comp', encapsulation: ViewEncapsulation.ShadowDom }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( 'Selector of a ShadowDom-encapsulated component must all be in lower case.', ); expect(getDiagnosticSourceCode(diags[0])).toBe(`'my-Comp'`); }); it('should emit a diagnostic when a selector starts with a digit', () => { env.write( 'test.ts', ` import {Component, ViewEncapsulation} from '@angular/core'; @Component({ template: '', selector: '123-comp', encapsulation: ViewEncapsulation.ShadowDom }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( 'Selector of a ShadowDom-encapsulated component must start with a lower case letter.', ); expect(getDiagnosticSourceCode(diags[0])).toBe(`'123-comp'`); }); it('should emit a diagnostic when a selector starts with a hyphen', () => { env.write( 'test.ts', ` import {Component, ViewEncapsulation} from '@angular/core'; @Component({ template: '', selector: '-comp', encapsulation: ViewEncapsulation.ShadowDom }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( 'Selector of a ShadowDom-encapsulated component must start with a lower case letter.', ); expect(getDiagnosticSourceCode(diags[0])).toBe(`'-comp'`); }); it('should not emit a diagnostic for a component using an attribute selector', () => { env.write( 'test.ts', ` import {Component, ViewEncapsulation} from '@angular/core'; @Component({ template: '', selector: '[button]', encapsulation: ViewEncapsulation.ShadowDom }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not emit a diagnostic for a component using a class selector', () => { env.write( 'test.ts', ` import {Component, ViewEncapsulation} from '@angular/core'; @Component({ template: '', selector: '.button', encapsulation: ViewEncapsulation.ShadowDom }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); }); describe('i18n errors', () => { it('reports a diagnostics on nested i18n sections', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-component', template: '<div i18n><div i18n>Content</div></div>' }) class TestComponent {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toEqual(1); expect(diags[0].messageText).toEqual( 'Cannot mark an element as translatable inside of a translatable section.' + ' Please remove the nested i18n marker.', ); expect(diags[0].file?.fileName).toEqual(absolute
{ "end_byte": 315216, "start_byte": 305932, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }
angular/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts_315224_323714
est.ts')); expect( diags[0].file?.text.slice(diags[0].start!, diags[0].start! + diags[0].length!), ).toEqual('<div i18n>Content</div>'); }); it('reports a diagnostic on nested i18n sections with tags in between', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-component', template: '<div i18n><div><div i18n>Content</div></div></div>' }) class TestComponent {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toEqual(1); expect(diags[0].messageText).toEqual( 'Cannot mark an element as translatable inside of a translatable section.' + ' Please remove the nested i18n marker.', ); expect(diags[0].file?.fileName).toEqual(absoluteFrom('/test.ts')); expect( diags[0].file?.text.slice(diags[0].start!, diags[0].start! + diags[0].length!), ).toEqual('<div i18n>Content</div>'); }); it('reports a diagnostic on nested i18n sections represented with <ng-continers>s', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-component', template: '<div i18n><div><ng-container i18n>Content</ng-container></div></div>' }) class TestComponent {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toEqual(1); expect(diags[0].messageText).toEqual( 'Cannot mark an element as translatable inside of a translatable section.' + ' Please remove the nested i18n marker.', ); expect(diags[0].file?.fileName).toEqual(absoluteFrom('/test.ts')); expect( diags[0].file?.text.slice(diags[0].start!, diags[0].start! + diags[0].length!), ).toEqual('<ng-container i18n>Content</ng-container>'); }); }); }); it( 'reports a COMPONENT_RESOURCE_NOT_FOUND for a component with a templateUrl' + ' that points to a non-existent file', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-component', templateUrl: './non-existent-file.html' }) class TestComponent {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toEqual(1); expect(diags[0].code).toEqual(ngErrorCode(ErrorCode.COMPONENT_RESOURCE_NOT_FOUND)); expect(diags[0].messageText).toEqual( `Could not find template file './non-existent-file.html'.`, ); }, ); it( `reports a COMPONENT_RESOURCE_NOT_FOUND when style sheet link in a component's template` + ` does not exist`, () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-component', templateUrl: './test.html' }) class TestComponent {} `, ); env.write( 'test.html', ` <link rel="stylesheet" href="./non-existent-file.css"> `, ); const diags = env.driveDiagnostics(); expect(diags.length).toEqual(1); expect(diags[0].code).toEqual(ngErrorCode(ErrorCode.COMPONENT_RESOURCE_NOT_FOUND)); expect(diags[0].messageText).toEqual( `Could not find stylesheet file './non-existent-file.css' linked from the template.`, ); }, ); it( 'reports a COMPONENT_RESOURCE_NOT_FOUND for a component with a style url ' + 'defined in a spread that points to a non-existent file', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-component', template: '', styleUrls: [...['./non-existent-file.css']] }) class TestComponent {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toEqual(1); expect(diags[0].code).toEqual(ngErrorCode(ErrorCode.COMPONENT_RESOURCE_NOT_FOUND)); expect(diags[0].messageText).toEqual( `Could not find stylesheet file './non-existent-file.css'.`, ); }, ); it('passes the build when only warnings are emitted', () => { env.tsconfig({strictTemplates: true}); env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-component', // Invalid banana in box (should be \`[(foo)]="bar"\`). template: '<div ([foo])="bar"></div>', }) class TestComponent { bar = 'test'; } `, ); const diagnostics = env.driveDiagnostics(0 /* expectedExitCode */); const codes = diagnostics.map((diag) => diag.code); expect(codes).toEqual([ngErrorCode(ErrorCode.INVALID_BANANA_IN_BOX)]); }); it('should produce an error when standalone component is used in @NgModule.bootstrap', () => { env.tsconfig(); env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ standalone: true, selector: 'standalone-component', template: '...', }) class StandaloneComponent {} @NgModule({ bootstrap: [StandaloneComponent] }) class BootstrapModule {} `, ); const diagnostics = env.driveDiagnostics(); const codes = diagnostics.map((diag) => diag.code); expect(codes).toEqual([ngErrorCode(ErrorCode.NGMODULE_BOOTSTRAP_IS_STANDALONE)]); }); it('should produce an error when standalone component wrapped in `forwardRef` is used in @NgModule.bootstrap', () => { env.tsconfig(); env.write( 'test.ts', ` import {Component, NgModule, forwardRef} from '@angular/core'; @Component({ standalone: true, selector: 'standalone-component', template: '...', }) class StandaloneComponent {} @NgModule({ bootstrap: [forwardRef(() => StandaloneComponent)] }) class BootstrapModule {} `, ); const diagnostics = env.driveDiagnostics(); const codes = diagnostics.map((diag) => diag.code); expect(codes).toEqual([ngErrorCode(ErrorCode.NGMODULE_BOOTSTRAP_IS_STANDALONE)]); }); it('should be able to turn off control flow using a compiler flag', () => { env.tsconfig({_enableBlockSyntax: false}); env.write( '/test.ts', ` import { Component } from '@angular/core'; @Component({ standalone: true, template: 'My email is foo@bar.com', }) export class TestCmp {} `, ); env.driveMain(); // If blocks are enabled, this test will fail since `@bar.com` is an incomplete block. const jsContents = env.getContents('test.js'); expect(jsContents).toContain('text(0, "My email is foo@bar.com")'); }); describe('InjectorDef emit optimizations for standalone', () => { it('should not filter components out of NgModule.imports', () => { env.write( 'test.ts', ` import {Component, Injectable, NgModule} from '@angular/core'; @Injectable() export class Service {} @NgModule({ providers: [Service] }) export class DepModule {} @Component({ standalone: true, selector: 'standalone-cmp', imports: [DepModule], template: '', }) export class StandaloneCmp {} @NgModule({ imports: [StandaloneCmp], exports: [StandaloneCmp], }) export class Module {}
{ "end_byte": 323714, "start_byte": 315224, "url": "https://github.com/angular/angular/blob/main/packages/compiler-cli/test/ngtsc/ngtsc_spec.ts" }