_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/core/schematics/test/control_flow_migration_spec.ts_74978_82115
describe('ngSwitch', () => { it('should migrate an inline template', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {ngSwitch, ngSwitchCase} from '@angular/common'; @Component({ template: \`<div [ngSwitch]="testOpts">` + `<p *ngSwitchCase="1">Option 1</p>` + `<p *ngSwitchCase="2">Option 2</p>` + `</div>\` }) class Comp { testOpts = "1"; } `, ); await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain( 'template: `<div>@switch (testOpts) { @case (1) { <p>Option 1</p> } @case (2) { <p>Option 2</p> }}</div>', ); }); it('should migrate multiple inline templates in the same file', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {ngSwitch, ngSwitchCase} from '@angular/common'; @Component({ template: \`<div [ngSwitch]="testOpts">` + `<p *ngSwitchCase="1">Option 1</p>` + `<p *ngSwitchCase="2">Option 2</p>` + `</div>\` }) class Comp1 { testOpts = "1"; } @Component({ template: \`<div [ngSwitch]="choices">` + `<p *ngSwitchCase="A">Choice A</p>` + `<p *ngSwitchCase="B">Choice B</p>` + `<p *ngSwitchDefault>Choice Default</p>` + `</div>\` }) class Comp2 { choices = "C"; } `, ); await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain( 'template: `<div>@switch (testOpts) { @case (1) { <p>Option 1</p> } @case (2) { <p>Option 2</p> }}</div>`', ); expect(content).toContain( 'template: `<div>@switch (choices) { @case (A) { <p>Choice A</p> } @case (B) { <p>Choice B</p> } @default { <p>Choice Default</p> }}</div>`', ); }); it('should migrate an external template', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; @Component({ templateUrl: './comp.html' }) class Comp { testOpts = 2; } `, ); writeFile( '/comp.html', [ `<div [ngSwitch]="testOpts">`, `<p *ngSwitchCase="1">Option 1</p>`, `<p *ngSwitchCase="2">Option 2</p>`, `<p *ngSwitchDefault>Option 3</p>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @switch (testOpts) {`, ` @case (1) {`, ` <p>Option 1</p>`, ` }`, ` @case (2) {`, ` <p>Option 2</p>`, ` }`, ` @default {`, ` <p>Option 3</p>`, ` }`, ` }`, `</div>`, ].join('\n'), ); }); it('should migrate a template referenced by multiple components', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {ngSwitch, ngSwitchCase} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { testOpts = 2; } `, ); writeFile( '/other-comp.ts', ` import {Component} from '@angular/core'; import {ngSwitch, ngSwitchCase} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class OtherComp { testOpts = 1; } `, ); writeFile( '/comp.html', [ `<div [ngSwitch]="testOpts">`, `<p *ngSwitchCase="1">Option 1</p>`, `<p *ngSwitchCase="2">Option 2</p>`, `<p *ngSwitchDefault>Option 3</p>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @switch (testOpts) {`, ` @case (1) {`, ` <p>Option 1</p>`, ` }`, ` @case (2) {`, ` <p>Option 2</p>`, ` }`, ` @default {`, ` <p>Option 3</p>`, ` }`, ` }`, `</div>`, ].join('\n'), ); }); it('should remove unnecessary ng-containers', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {ngSwitch, ngSwitchCase} from '@angular/common'; @Component({ template: \`<div [ngSwitch]="testOpts">` + `<ng-container *ngSwitchCase="1"><p>Option 1</p></ng-container>` + `<ng-container *ngSwitchCase="2"><p>Option 2</p></ng-container>` + `</div>\` }) class Comp { testOpts = "1"; } `, ); await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain( 'template: `<div>@switch (testOpts) { @case (1) { <p>Option 1</p> } @case (2) { <p>Option 2</p> }}</div>', ); }); it('should remove unnecessary ng-container on ngswitch', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {ngSwitch, ngSwitchCase} from '@angular/common'; @Component({ template: \`<div>` + `<ng-container [ngSwitch]="testOpts">` + `<p *ngSwitchCase="1">Option 1</p>` + `<p *ngSwitchCase="2">Option 2</p>` + `</ng-container>` + `</div>\` }) class Comp { testOpts = "1"; } `, ); await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain( 'template: `<div>@switch (testOpts) { @case (1) { <p>Option 1</p> } @case (2) { <p>Option 2</p> }}</div>', ); }); it('should handle cases with missing star', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {ngSwitch, ngSwitchCase} from '@angular/common'; @Component({ template: \`<div [ngSwitch]="testOpts">` + `<ng-template ngSwitchCase="1"><p>Option 1</p></ng-template>` + `<ng-template ngSwitchCase="2"><p>Option 2</p></ng-template>` + `<ng-template ngSwitchDefault><p>Option 3</p></ng-template>` + `</div>\` }) class Comp { testOpts = "1"; } `, ); await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain( 'template: `<div>@switch (testOpts) { @case (1) { <p>Option 1</p> } @case (2) { <p>Option 2</p> } @default { <p>Option 3</p> }}</div>', ); });
{ "end_byte": 82115, "start_byte": 74978, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/control_flow_migration_spec.ts_82121_86552
it('should handle cases with binding', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {ngSwitch, ngSwitchCase} from '@angular/common'; @Component({ template: \`<div [ngSwitch]="testOpts">` + `<ng-template [ngSwitchCase]="1"><p>Option 1</p></ng-template>` + `<ng-template [ngSwitchCase]="2"><p>Option 2</p></ng-template>` + `<ng-template ngSwitchDefault><p>Option 3</p></ng-template>` + `</div>\` }) class Comp { testOpts = "1"; } `, ); await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain( 'template: `<div>@switch (testOpts) { @case (1) { <p>Option 1</p> } @case (2) { <p>Option 2</p> } @default { <p>Option 3</p> }}</div>', ); }); it('should handle empty default cases', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {ngSwitch, ngSwitchCase} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { testOpts = "1"; } `, ); writeFile( '/comp.html', [ `<ng-container [ngSwitch]="type">`, `<ng-container *ngSwitchCase="'foo'"> Foo </ng-container>`, `<ng-container *ngSwitchCase="'bar'"> Bar </ng-container>`, `<ng-container *ngSwitchDefault></ng-container>`, `</ng-container>`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `\n@switch (type) {`, ` @case ('foo') {`, ` Foo`, ` }`, ` @case ('bar') {`, ` Bar`, ` }`, ` @default {`, ` }`, `}\n`, ].join('\n'); expect(actual).toBe(expected); }); it('should migrate a nested class', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {ngSwitch, ngSwitchCase} from '@angular/common'; function foo() { @Component({ template: \`<div [ngSwitch]="testOpts">` + `<p *ngSwitchCase="1">Option 1</p>` + `<p *ngSwitchCase="2">Option 2</p>` + `</div>\` }) class Comp { testOpts = "1"; } } `, ); await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain( 'template: `<div>@switch (testOpts) { @case (1) { <p>Option 1</p> } @case (2) { <p>Option 2</p> }}</div>`', ); }); it('should migrate nested switches', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgFor, NgIf], templateUrl: './comp.html' }) class Comp { show = false; nest = true; again = true; more = true; }`, ); writeFile( '/comp.html', [ `<div [ngSwitch]="thing">`, ` <div *ngSwitchCase="'item'" [ngSwitch]="anotherThing">`, ` <img *ngSwitchCase="'png'" src="/img.png" alt="PNG" />`, ` <img *ngSwitchDefault src="/default.jpg" alt="default" />`, ` </div>`, ` <img *ngSwitchDefault src="/default.jpg" alt="default" />`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, ` @switch (thing) {`, ` @case ('item') {`, ` <div>`, ` @switch (anotherThing) {`, ` @case ('png') {`, ` <img src="/img.png" alt="PNG" />`, ` }`, ` @default {`, ` <img src="/default.jpg" alt="default" />`, ` }`, ` }`, ` </div>`, ` }`, ` @default {`, ` <img src="/default.jpg" alt="default" />`, ` }`, ` }`, `</div>`, ].join('\n'), ); }); });
{ "end_byte": 86552, "start_byte": 82121, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/control_flow_migration_spec.ts_86556_94070
describe('nested structures', () => { it('should migrate an inline template with nested control flow structures and no line breaks', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgFor, NgIf], templateUrl: './comp.html' }) class Comp { show = false; nest = true; again = true; more = true; } `, ); writeFile( '/comp.html', `<div *ngIf="show"><div *ngIf="nest"><span *ngIf="again">things</span><span *ngIf="more">stuff</span></div><span *ngIf="more">stuff</span></div>`, ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( `@if (show) {<div>@if (nest) {<div>@if (again) {<span>things</span>}@if (more) {<span>stuff</span>}</div>}@if (more) {<span>stuff</span>}</div>}`, ); }); it('should migrate an inline template with multiple nested control flow structures', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgFor, NgIf], templateUrl: './comp.html' }) class Comp { show = false; nest = true; again = true; more = true; } `, ); writeFile( '/comp.html', [ `<div *ngIf="show">`, `<span>things</span>`, `<div *ngIf="nest">`, `<span>stuff</span>`, `</div>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (show) {`, ` <div>`, ` <span>things</span>`, ` @if (nest) {`, ` <div>`, ` <span>stuff</span>`, ` </div>`, ` }`, ` </div>`, `}`, ].join('\n'), ); }); it('should migrate an inline template with multiple nested control flow structures', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgFor, NgIf], templateUrl: './comp.html' }) class Comp { show = false; nest = true; again = true; more = true; } `, ); writeFile( '/comp.html', [ `<div *ngIf="show">`, `<span>things</span>`, `<div *ngIf="nest">`, `<span>stuff</span>`, `</div>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (show) {`, ` <div>`, ` <span>things</span>`, ` @if (nest) {`, ` <div>`, ` <span>stuff</span>`, ` </div>`, ` }`, ` </div>`, `}`, ].join('\n'), ); }); it('should migrate a simple nested case', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgFor, NgIf], templateUrl: './comp.html' }) class Comp { show = false; nest = true; again = true; more = true; } `, ); writeFile( '/comp.html', [`<div *ngIf="show">`, `<div *ngIf="nest">`, `</div>`, `</div>`].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (show) {`, ` <div>`, ` @if (nest) {`, ` <div>`, ` </div>`, ` }`, ` </div>`, `}`, ].join('\n'), ); }); it('should migrate an if and switch on the same container', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgFor, NgIf], templateUrl: './comp.html' }) class Comp {} `, ); writeFile( '/comp.html', [ `<div>`, ` <ng-container *ngIf="thing" [ngSwitch]="value.provider">`, ` <cmp1 *ngSwitchCase="'value1'" />`, ` <cmp2 *ngSwitchCase="'value2'" />`, ` </ng-container>`, `</div>`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `<div>`, ` @if (thing) {`, ` @switch (value.provider) {`, ` @case ('value1') {`, ` <cmp1 />`, ` }`, ` @case ('value2') {`, ` <cmp2 />`, ` }`, ` }`, ` }`, `</div>`, ].join('\n'); expect(actual).toBe(expected); }); it('should migrate a switch with for inside case', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgFor, NgIf], templateUrl: './comp.html' }) class Comp { show = false; nest = true; again = true; more = true; } `, ); writeFile( '/comp.html', [ `<div [formGroup]="form">`, `<label [attr.for]="question.key">{{question.label}}</label>`, `<div [ngSwitch]="question.controlType">`, ` <input *ngSwitchCase="'textbox'" [formControlName]="question.key"`, ` [id]="question.key" [type]="question.type" />`, ` <select [id]="question.key" *ngSwitchCase="'dropdown'" [formControlName]="question.key">`, ` <option *ngFor="let opt of question.options" [value]="opt.key">{{opt.value}}</option>`, ` </select>`, `</div>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div [formGroup]="form">`, ` <label [attr.for]="question.key">{{question.label}}</label>`, ` <div>`, ` @switch (question.controlType) {`, ` @case ('textbox') {`, ` <input [formControlName]="question.key"`, ` [id]="question.key" [type]="question.type" />`, ` }`, ` @case ('dropdown') {`, ` <select [id]="question.key" [formControlName]="question.key">`, ` @for (opt of question.options; track opt) {`, ` <option [value]="opt.key">{{opt.value}}</option>`, ` }`, ` </select>`, ` }`, ` }`, ` </div>`, `</div>`, ].join('\n'), ); });
{ "end_byte": 94070, "start_byte": 86556, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/control_flow_migration_spec.ts_94076_100437
it('should migrate a simple for inside an if', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgFor, NgIf], templateUrl: './comp.html' }) class Comp { show = false; nest = true; again = true; more = true; } `, ); writeFile( '/comp.html', [ `<ul *ngIf="show">`, `<li *ngFor="let h of heroes" [ngValue]="h">{{h.name}} ({{h.emotion}})</li>`, `</ul>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (show) {`, ` <ul>`, ` @for (h of heroes; track h) {`, ` <li [ngValue]="h">{{h.name}} ({{h.emotion}})</li>`, ` }`, ` </ul>`, `}`, ].join('\n'), ); }); it('should migrate an if inside a for loop', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgFor, NgIf], templateUrl: './comp.html' }) class Comp { heroes = [{name: 'cheese', emotion: 'happy'},{name: 'stuff', emotion: 'sad'}]; show = true; } `, ); writeFile( '/comp.html', [ `<select id="hero">`, `<span *ngFor="let h of heroes">`, `<span *ngIf="show">`, `<option [ngValue]="h">{{h.name}} ({{h.emotion}})</option>`, `</span>`, `</span>`, `</select>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<select id="hero">`, ` @for (h of heroes; track h) {`, ` <span>`, ` @if (show) {`, ` <span>`, ` <option [ngValue]="h">{{h.name}} ({{h.emotion}})</option>`, ` </span>`, ` }`, ` </span>`, ` }`, `</select>`, ].join('\n'), ); }); it('should migrate an if inside a for loop with ng-containers', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgFor, NgIf], templateUrl: './comp.html' }) class Comp { heroes = [{name: 'cheese', emotion: 'happy'},{name: 'stuff', emotion: 'sad'}]; show = true; } `, ); writeFile( '/comp.html', [ `<select id="hero">`, `<ng-container *ngFor="let h of heroes">`, `<ng-container *ngIf="show">`, `<option [ngValue]="h">{{h.name}} ({{h.emotion}})</option>`, `</ng-container>`, `</ng-container>`, `</select>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<select id="hero">`, ` @for (h of heroes; track h) {`, ` @if (show) {`, ` <option [ngValue]="h">{{h.name}} ({{h.emotion}})</option>`, ` }`, ` }`, `</select>`, ].join('\n'), ); }); it('should migrate an inline template with if and for loops', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf, NgFor} from '@angular/common'; interface Item { id: number; text: string; } @Component({ imports: [NgFor, NgIf], templateUrl: './comp.html' }) class Comp { show = false; nest = true; items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}]; } `, ); writeFile( '/comp.html', [ `<div *ngIf="show">`, `<ul *ngIf="nest">`, `<li *ngFor="let item of items">{{item.text}}</li>`, `</ul>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (show) {`, ` <div>`, ` @if (nest) {`, ` <ul>`, ` @for (item of items; track item) {`, ` <li>{{item.text}}</li>`, ` }`, ` </ul>`, ` }`, ` </div>`, `}`, ].join('\n'), ); }); it('should migrate template with if, else, and for loops', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf, NgFor} from '@angular/common'; interface Item { id: number; text: string; } @Component({ imports: [NgFor, NgIf], templateUrl: './comp.html' }) class Comp { show = false; nest = true; items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}]; } `, ); writeFile( '/comp.html', [ `<div *ngIf="show">`, `<ul *ngIf="nest; else elseTmpl">`, `<li *ngFor="let item of items">{{item.text}}</li>`, `</ul>`, `<ng-template #elseTmpl><p>Else content</p></ng-template>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (show) {`, ` <div>`, ` @if (nest) {`, ` <ul>`, ` @for (item of items; track item) {`, ` <li>{{item.text}}</li>`, ` }`, ` </ul>`, ` } @else {`, ` <p>Else content</p>`, ` }`, ` </div>`, `}`, ].join('\n'), ); });
{ "end_byte": 100437, "start_byte": 94076, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/control_flow_migration_spec.ts_100443_104746
it('should migrate an inline template with if, for loops, and switches', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf, NgFor} from '@angular/common'; interface Item { id: number; text: string; } @Component({ imports: [NgFor, NgIf], templateUrl: './comp.html' }) class Comp { show = false; nest = true; again = true; more = true; items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}]; testOpts = 2; } `, ); writeFile( '/comp.html', [ `<div *ngIf="show">`, `<div *ngIf="again">`, `<div *ngIf="more">`, `<div [ngSwitch]="testOpts">`, `<p *ngSwitchCase="1">Option 1</p>`, `<p *ngSwitchCase="2">Option 2</p>`, `<p *ngSwitchDefault>Option 3</p>`, `</div>`, `</div>`, `</div>`, `<ul *ngIf="nest">`, `<li *ngFor="let item of items">{{item.text}}</li>`, `</ul>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (show) {`, ` <div>`, ` @if (again) {`, ` <div>`, ` @if (more) {`, ` <div>`, ` <div>`, ` @switch (testOpts) {`, ` @case (1) {`, ` <p>Option 1</p>`, ` }`, ` @case (2) {`, ` <p>Option 2</p>`, ` }`, ` @default {`, ` <p>Option 3</p>`, ` }`, ` }`, ` </div>`, ` </div>`, ` }`, ` </div>`, ` }`, ` @if (nest) {`, ` <ul>`, ` @for (item of items; track item) {`, ` <li>{{item.text}}</li>`, ` }`, ` </ul>`, ` }`, ` </div>`, `}`, ].join('\n'), ); }); it('complicated case', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf, NgFor} from '@angular/common'; interface Item { id: number; text: string; } @Component({ imports: [NgFor, NgIf], templateUrl: './comp.html' }) class Comp { } `, ); writeFile( '/comp.html', [ `<div class="docs-breadcrumb" *ngFor="let breadcrumb of breadcrumbItems()">`, `<ng-container *ngIf="breadcrumb.path; else breadcrumbWithoutLinkTemplate">`, `<ng-container *ngIf="breadcrumb.isExternal; else internalLinkTemplate">`, `<a [href]="breadcrumb.path">{{ breadcrumb.label }}</a>`, `</ng-container>`, `<ng-template #internalLinkTemplate>`, `<a [routerLink]="'/' + breadcrumb.path">{{ breadcrumb.label }}</a>`, `</ng-template>`, `</ng-container>`, `<ng-template #breadcrumbWithoutLinkTemplate>`, `<span>{{ breadcrumb.label }}</span>`, `</ng-template>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); const result = [ `@for (breadcrumb of breadcrumbItems(); track breadcrumb) {`, ` <div class="docs-breadcrumb">`, ` @if (breadcrumb.path) {`, ` @if (breadcrumb.isExternal) {`, ` <a [href]="breadcrumb.path">{{ breadcrumb.label }}</a>`, ` } @else {`, ` <a [routerLink]="'/' + breadcrumb.path">{{ breadcrumb.label }}</a>`, ` }`, ` } @else {`, ` <span>{{ breadcrumb.label }}</span>`, ` }`, ` </div>`, `}`, ].join('\n'); expect(content).toBe(result); });
{ "end_byte": 104746, "start_byte": 100443, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/control_flow_migration_spec.ts_104752_110636
it('long file', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf, NgFor} from '@angular/common'; interface Item { id: number; text: string; } @Component({ imports: [NgFor, NgIf], templateUrl: './comp.html' }) class Comp { } `, ); writeFile( '/comp.html', [ `<div class="class">`, `<iframe `, `#preview `, `class="special-class" `, `*ngIf="stuff" `, `></iframe>`, `<ng-container *ngIf="shouldDoIt">`, `<ng-container `, `*ngComponentOutlet="outletComponent; inputs: {errorMessage: errorMessage()}" `, `/>`, `</ng-container>`, `<div `, `class="what"`, `*ngIf="`, `shouldWhat`, `"`, `>`, `<ng-container [ngSwitch]="currentCase()">`, `<span `, `class="case-stuff"`, `*ngSwitchCase="A"`, `>`, `Case A`, `</span>`, `<span class="b-class" *ngSwitchCase="B">`, `Case B`, `</span>`, `<span `, `class="thing-1" `, `*ngSwitchCase="C" `, `>`, `Case C`, `</span>`, `<span `, `class="thing-2"`, `*ngSwitchCase="D"`, `>`, `Case D`, `</span>`, `<span `, `class="thing-3" `, `*ngSwitchCase="E" `, `>`, `Case E`, `</span>`, `</ng-container>`, `<progress [value]="progress()" [max]="ready"></progress>`, `</div>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); const result = [ `<div class="class">`, ` @if (stuff) {`, ` <iframe`, ` #preview`, ` class="special-class"`, ` ></iframe>`, ` }`, ` @if (shouldDoIt) {`, ` <ng-container`, ` *ngComponentOutlet="outletComponent; inputs: {errorMessage: errorMessage()}"`, ` />`, ` }`, ` @if (`, ` shouldWhat`, ` ) {`, ` <div`, ` class="what"`, ` >`, ` @switch (currentCase()) {`, ` @case (A) {`, ` <span`, ` class="case-stuff"`, ` >`, ` Case A`, ` </span>`, ` }`, ` @case (B) {`, ` <span class="b-class">`, ` Case B`, ` </span>`, ` }`, ` @case (C) {`, ` <span`, ` class="thing-1"`, ` >`, ` Case C`, ` </span>`, ` }`, ` @case (D) {`, ` <span`, ` class="thing-2"`, ` >`, ` Case D`, ` </span>`, ` }`, ` @case (E) {`, ` <span`, ` class="thing-3"`, ` >`, ` Case E`, ` </span>`, ` }`, ` }`, ` <progress [value]="progress()" [max]="ready"></progress>`, ` </div>`, ` }`, `</div>`, ].join('\n'); expect(content).toBe(result); }); it('should handle empty cases safely without offset issues', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', templateUrl: 'comp.html', }) class DeclareComp {} `, ); writeFile( '/comp.html', [ `<ng-container *ngIf="generic; else specific">`, ` <ng-container [ngSwitch]="dueWhen">`, ` <ng-container *ngSwitchCase="due.NOW">`, ` <p>Now></p>`, ` </ng-container>`, ` <ng-container *ngSwitchCase="due.SOON">`, ` <p>Soon></p>`, ` </ng-container>`, ` <ng-container *ngSwitchDefault></ng-container>`, ` </ng-container>`, `</ng-container>`, `<ng-template #specific>`, ` <ng-container [ngSwitch]="dueWhen">`, ` <ng-container *ngSwitchCase="due.NOW">`, ` <p>Now></p>`, ` </ng-container>`, ` <ng-container *ngSwitchCase="due.SOON">`, ` <p>Soon></p>`, ` </ng-container>`, ` <ng-container *ngSwitchDefault>`, ` <p>Default></p>`, ` </ng-container>`, ` </ng-container>`, `</ng-template>`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `@if (generic) {`, ` @switch (dueWhen) {`, ` @case (due.NOW) {`, ` <p>Now></p>`, ` }`, ` @case (due.SOON) {`, ` <p>Soon></p>`, ` }`, ` @default {`, ` }`, ` }`, `} @else {`, ` @switch (dueWhen) {`, ` @case (due.NOW) {`, ` <p>Now></p>`, ` }`, ` @case (due.SOON) {`, ` <p>Soon></p>`, ` }`, ` @default {`, ` <p>Default></p>`, ` }`, ` }`, `}\n`, ].join('\n'); expect(actual).toBe(expected); }); });
{ "end_byte": 110636, "start_byte": 104752, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/control_flow_migration_spec.ts_110640_113132
describe('error handling', () => { it('should log template migration errors to the console', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgIf], template: \`<div><span *ngIf="toggle">This should be hidden</span></div>\` }) class Comp { toggle = false; } `, ); await runMigration(); tree.readContent('/comp.ts'); }); it('should log a migration error when duplicate ng-template names are detected', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgIf], templateUrl: './comp.html' }) class Comp { toggle = false; } `, ); writeFile( './comp.html', [ `<div *ngIf="show; else elseTmpl">Content</div>`, `<div *ngIf="hide; else elseTmpl">Content</div>`, `<ng-template #elseTmpl>Else Content</ng-template>`, `<ng-template #elseTmpl>Duplicate</ng-template>`, ].join('\n'), ); await runMigration(); tree.readContent('/comp.ts'); expect(warnOutput.join(' ')).toContain( `A duplicate ng-template name "#elseTmpl" was found. ` + `The control flow migration requires unique ng-template names within a component.`, ); }); it('should log a migration error when collection aliasing is detected in ngFor', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgIf], templateUrl: './comp.html' }) class Comp { toggle = false; } `, ); writeFile( './comp.html', [`<div *ngFor="let item of list$ | async as list;">Content</div>`].join('\n'), ); await runMigration(); tree.readContent('/comp.ts'); expect(warnOutput.join(' ')).toContain( `Found an aliased collection on an ngFor: "item of list$ | async as list". ` + `Collection aliasing is not supported with @for. ` + `Refactor the code to remove the \`as\` alias and re-run the migration.`, ); }); });
{ "end_byte": 113132, "start_byte": 110640, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/control_flow_migration_spec.ts_113136_121013
describe('template', () => { it('should migrate a root level template thats not used in control flow', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', templateUrl: './comp.html' }) class DeclareComp { } `, ); writeFile( '/comp.html', [ `<div class="content">`, ` <ng-container *ngTemplateOutlet="navigation" />`, ` <ng-container *ngIf="content()">`, ` <div class="class-1"></div>`, ` </ng-container>`, `</div>`, `<ng-template #navigation>`, ` <div class="cont">`, ` <button`, ` *ngIf="shouldShowMe()"`, ` class="holy-classname-batman"`, ` >`, ` Wow...a button!`, ` </button>`, ` </div>`, `</ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); const result = [ `<div class="content">`, ` <ng-container *ngTemplateOutlet="navigation" />`, ` @if (content()) {`, ` <div class="class-1"></div>`, ` }`, `</div>`, `<ng-template #navigation>`, ` <div class="cont">`, ` @if (shouldShowMe()) {`, ` <button`, ` class="holy-classname-batman"`, ` >`, ` Wow...a button!`, ` </button>`, ` }`, ` </div>`, `</ng-template>`, ].join('\n'); expect(content).toBe(result); }); it('should not remove a template thats not used in control flow', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', template: \` DeclareComp({{name}}) <ng-template #myTmpl let-greeting> {{greeting}} {{logName()}}! </ng-template> \` }) class DeclareComp implements DoCheck, AfterViewChecked { @ViewChild('myTmpl') myTmpl!: TemplateRef<any>; name: string = 'world'; } `, ); await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain('<ng-template #myTmpl let-greeting>'); }); it('should remove a template thats only used in control flow', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', templateUrl: 'comp.html', }) class DeclareComp {} `, ); writeFile( '/comp.html', [ `<div class="statistics">`, ` <ng-container *ngIf="null !== value; else preload">`, ` <div class="statistics__counter"`, ` *ngIf="!isMoney"`, ` >`, ` {{ value | number }}`, ` </div>`, ` <div class="statistics__counter"`, ` *ngIf="isMoney"`, ` >`, ` {{ value | number }}$`, ` </div>`, ` </ng-container>`, `</div>`, `<ng-template #preload>`, ` <preload-rect`, ` height="2rem"`, ` width="6rem" />`, `</ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); const result = [ `<div class="statistics">`, ` @if (null !== value) {`, ` @if (!isMoney) {`, ` <div class="statistics__counter"`, ` >`, ` {{ value | number }}`, ` </div>`, ` }`, ` @if (isMoney) {`, ` <div class="statistics__counter"`, ` >`, ` {{ value | number }}$`, ` </div>`, ` }`, ` } @else {`, ` <preload-rect`, ` height="2rem"`, ` width="6rem" />`, ` }`, `</div>\n`, ].join('\n'); expect(content).toBe(result); }); it('should migrate template with ngTemplateOutlet', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', templateUrl: 'comp.html', }) class DeclareComp {} `, ); writeFile( '/comp.html', [ `<ng-template [ngIf]="!thing" [ngIfElse]="elseTmpl">`, ` {{ this.value(option) }}`, `</ng-template>`, `<ng-template`, ` #elseTmpl`, ` *ngTemplateOutlet="thing; context: {option: option}">`, `</ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); const result = [ `@if (!thing) {`, ` {{ this.value(option) }}`, `} @else {`, ` <ng-container *ngTemplateOutlet="thing; context: {option: option}"></ng-container>`, `}\n`, ].join('\n'); expect(content).toBe(result); }); it('should migrate template with ngTemplateOutlet on if else template', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', templateUrl: 'comp.html', }) class DeclareComp {} `, ); writeFile( '/comp.html', [ `<ng-template`, ` [ngIf]="false"`, ` [ngIfElse]="fooTemplate"`, ` [ngTemplateOutlet]="barTemplate"`, `>`, `</ng-template>`, `<ng-template #fooTemplate>`, ` Foo`, `</ng-template>`, `<ng-template #barTemplate>`, ` Bar`, `</ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); const result = [ `@if (false) {`, ` <ng-template`, ` [ngTemplateOutlet]="barTemplate"`, ` >`, ` </ng-template>`, `} @else {`, ` Foo`, `}`, `<ng-template #barTemplate>`, ` Bar`, `</ng-template>`, ].join('\n'); expect(content).toBe(result); }); it('should migrate template with ngIfThen and remove template', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', templateUrl: 'comp.html', }) class DeclareComp {} `, ); writeFile( '/comp.html', [ `<ng-template`, ` [ngIf]="mode === 'foo'"`, ` [ngIfThen]="foo"`, ` [ngIfElse]="bar"`, `></ng-template>`, `<ng-template #foo>`, ` Foo`, `</ng-template>`, `<ng-template #bar>`, ` Bar`, `</ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); const result = [`@if (mode === 'foo') {`, ` Foo`, `} @else {`, ` Bar`, `}\n`].join('\n'); expect(content).toBe(result); });
{ "end_byte": 121013, "start_byte": 113136, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/control_flow_migration_spec.ts_121019_128316
it('should move templates after they were migrated to new syntax', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', templateUrl: 'comp.html', }) class DeclareComp {} `, ); writeFile( '/comp.html', [ `<div>`, ` <ng-container *ngIf="cond; else testTpl">`, ` bla bla`, ` </ng-container>`, `</div>`, `<ng-template #testTpl>`, ` <div class="test" *ngFor="let item of items"></div>`, `</ng-template>`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `<div>`, ` @if (cond) {`, ` bla bla`, ` } @else {`, ` @for (item of items; track item) {`, ` <div class="test"></div>`, ` }`, ` }`, `</div>\n`, ].join('\n'); expect(actual).toBe(expected); }); it('should preserve i18n attribute on ng-templates in an if/else', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', templateUrl: 'comp.html', }) class DeclareComp {} `, ); writeFile( '/comp.html', [ `<div>`, ` <ng-container *ngIf="cond; else testTpl">`, ` bla bla`, ` </ng-container>`, `</div>`, `<ng-template #testTpl i18n="@@test_key">`, ` <div class="test" *ngFor="let item of items"></div>`, `</ng-template>`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `<div>`, ` @if (cond) {`, ` bla bla`, ` } @else {`, ` <ng-container i18n="@@test_key">`, ` @for (item of items; track item) {`, `<div class="test"></div>`, `}`, `</ng-container>`, ` }`, `</div>\n`, ].join('\n'); expect(actual).toBe(expected); }); it('should migrate multiple if/else using the same ng-template', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', templateUrl: 'comp.html', }) class DeclareComp {} `, ); writeFile( '/comp.html', [ `<div>`, ` <div *ngIf="hasPermission; else noPermission">presentation</div>`, ` <div *ngIf="someOtherPermission; else noPermission">presentation</div>`, `</div>`, `<ng-template #noPermission>`, ` <p>No Permissions</p>`, `</ng-template>`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `<div>`, ` @if (hasPermission) {`, ` <div>presentation</div>`, ` } @else {`, ` <p>No Permissions</p>`, ` }`, ` @if (someOtherPermission) {`, ` <div>presentation</div>`, ` } @else {`, ` <p>No Permissions</p>`, ` }`, `</div>\n`, ].join('\n'); expect(actual).toBe(expected); }); it('should remove a template with no overlap with following elements', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<ng-container *ngIf="stuff">`, ` <div>`, ` <ul>`, ` <li>`, ` <span>`, ` <ng-container *ngIf="things; else elseTmpl">`, ` <p>Hmm</p>`, ` </ng-container>`, ` <ng-template #elseTmpl> 0 </ng-template></span>`, ` </li>`, ` </ul>`, ` </div>`, `</ng-container>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (stuff) {`, ` <div>`, ` <ul>`, ` <li>`, ` <span>`, ` @if (things) {`, ` <p>Hmm</p>`, ` } @else {`, ` 0`, ` }`, ` </span>`, ` </li>`, ` </ul>`, ` </div>`, `}`, ].join('\n'), ); }); it('should migrate nested template usage correctly', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<ng-container *ngIf="!(condition$ | async); else template">`, ` Hello!`, `</ng-container>`, `<ng-template #bar>Bar</ng-template>`, `<ng-template #foo>Foo</ng-template>`, `<ng-template #template>`, ` <ng-container`, ` *ngIf="(foo$ | async) === true; then foo; else bar"`, ` ></ng-container>`, `</ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (!(condition$ | async)) {`, ` Hello!`, `} @else {`, ` @if ((foo$ | async) === true) {`, ` Foo`, ` } @else {`, ` Bar`, ` }`, `}\n`, ].join('\n'), ); }); it('should add an ngTemplateOutlet when the template placeholder does not match a template', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [`<button *ngIf="active; else defaultTemplate">`, ` Hello!`, `</button>`].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (active) {`, ` <button>`, ` Hello!`, ` </button>`, `} @else {`, ` <ng-template [ngTemplateOutlet]="defaultTemplate"></ng-template>`, `}`, ].join('\n'), ); });
{ "end_byte": 128316, "start_byte": 121019, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/control_flow_migration_spec.ts_128322_135182
it('should handle OR logic in ngIf else case', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div *ngIf="condition; else titleTemplate || defaultTemplate">Hello!</div>`, `<ng-template #defaultTemplate> Default </ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (condition) {`, ` <div>Hello!</div>`, `} @else {`, ` <ng-template [ngTemplateOutlet]="titleTemplate || defaultTemplate"></ng-template>`, `}`, `<ng-template #defaultTemplate> Default </ng-template>`, ].join('\n'), ); }); it('should handle ternaries in ngIfElse', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<ng-template`, ` [ngIf]="customClearTemplate"`, ` [ngIfElse]="isSidebarV3 || variant === 'v3' ? clearTemplateV3 : clearTemplate"`, ` [ngTemplateOutlet]="customClearTemplate"`, `></ng-template>`, `<ng-template #clearTemplateV3>v3</ng-template>`, `<ng-template #clearTemplate>clear</ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (customClearTemplate) {`, ` <ng-template`, ` [ngTemplateOutlet]="customClearTemplate"`, ` ></ng-template>`, `} @else {`, ` <ng-template [ngTemplateOutlet]="isSidebarV3 || variant === 'v3' ? clearTemplateV3 : clearTemplate"></ng-template>`, `}`, `<ng-template #clearTemplateV3>v3</ng-template>`, `<ng-template #clearTemplate>clear</ng-template>`, ].join('\n'), ); }); it('should handle ternaries in ngIf', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div *ngIf="!vm.isEmpty; else vm.loading ? loader : empty"></div>`, `<ng-template #loader>Loading</ng-template>`, `<ng-template #empty>Empty</ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (!vm.isEmpty) {`, ` <div></div>`, `} @else {`, ` <ng-template [ngTemplateOutlet]="vm.loading ? loader : empty"></ng-template>`, `}`, `<ng-template #loader>Loading</ng-template>`, `<ng-template #empty>Empty</ng-template>`, ].join('\n'), ); }); it('should replace all instances of template placeholders', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div *ngIf="condition; else otherTemplate">`, ` <ng-container *ngIf="!defaultTemplate; else defaultTemplate">`, ` Hello!`, ` </ng-container>`, `</div>`, `<ng-template #otherTemplate>`, ` <div>`, ` <ng-container *ngIf="!defaultTemplate; else defaultTemplate">`, ` Hello again!`, ` </ng-container>`, ` </div>`, `</ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (condition) {`, ` <div>`, ` @if (!defaultTemplate) {`, ` Hello!`, ` } @else {`, ` <ng-template [ngTemplateOutlet]="defaultTemplate"></ng-template>`, ` }`, ` </div>`, `} @else {`, ` <div>`, ` @if (!defaultTemplate) {`, ` Hello again!`, ` } @else {`, ` <ng-template [ngTemplateOutlet]="defaultTemplate"></ng-template>`, ` }`, ` </div>`, `}\n`, ].join('\n'), ); }); it('should trim newlines in ngIf conditions', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<ng-template`, ` [ngIf]="customClearTemplate"`, ` [ngIfElse]="`, ` isSidebarV3 || variant === 'v3' ? clearTemplateV3 : clearTemplate`, ` "`, `></ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `@if (customClearTemplate) {`, `} @else {`, ` <ng-template [ngTemplateOutlet]="isSidebarV3 || variant === 'v3' ? clearTemplateV3 : clearTemplate"></ng-template>`, `}`, ].join('\n'), ); }); it('should migrate a template using the θδ characters', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', templateUrl: './comp.html', standalone: true, imports: [NgIf], }) class DeclareComp { show = false; } `, ); writeFile('/comp.html', `<div *ngIf="show">Some greek characters: θδ!</div>`); await runMigration(); expect(tree.readContent('/comp.html')).toBe( '@if (show) {<div>Some greek characters: θδ!</div>}', ); }); }); de
{ "end_byte": 135182, "start_byte": 128322, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/control_flow_migration_spec.ts_135186_142250
be('formatting', () => { it('should reformat else if', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', templateUrl: 'comp.html', }) class DeclareComp {} `, ); writeFile( '/comp.html', [ `<div *ngIf="true">changed</div>`, `<div>`, `@if (stuff) {`, `<h2>Title</h2>`, `<p>Stuff</p>`, `} @else if (things) {`, `<p>Things</p>`, `} @else {`, `<p>Huh</p>`, `}`, `</div>`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `@if (true) {`, ` <div>changed</div>`, `}`, `<div>`, ` @if (stuff) {`, ` <h2>Title</h2>`, ` <p>Stuff</p>`, ` } @else if (things) {`, ` <p>Things</p>`, ` } @else {`, ` <p>Huh</p>`, ` }`, `</div>`, ].join('\n'); expect(actual).toBe(expected); }); it('should reformat properly with svg', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', templateUrl: 'comp.html', }) class DeclareComp {} `, ); writeFile( '/comp.html', [ `<div *ngIf="true">changed</div>`, `<div>`, `<svg class="filterthing">`, `<filter id="stuff">`, `<feGaussianBlur in="SourceAlpha" stdDeviation="3"/>`, `<feOffset dx="0" dy="0" result="offsetblur"/>`, `<feFlood flood-color="rgba(60,64,67,0.15)"/>`, `<feComposite in2="offsetblur" operator="in"/>`, `<feMerge>`, `<feMergeNode/>`, `<feMergeNode in="SourceGraphic"/>`, `</feMerge>`, `</filter>`, `</svg>`, `</div>`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `@if (true) {`, ` <div>changed</div>`, `}`, `<div>`, ` <svg class="filterthing">`, ` <filter id="stuff">`, ` <feGaussianBlur in="SourceAlpha" stdDeviation="3"/>`, ` <feOffset dx="0" dy="0" result="offsetblur"/>`, ` <feFlood flood-color="rgba(60,64,67,0.15)"/>`, ` <feComposite in2="offsetblur" operator="in"/>`, ` <feMerge>`, ` <feMergeNode/>`, ` <feMergeNode in="SourceGraphic"/>`, ` </feMerge>`, ` </filter>`, ` </svg>`, `</div>`, ].join('\n'); expect(actual).toBe(expected); }); it('should reformat properly with if else and containers', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', templateUrl: 'comp.html', }) class DeclareComp {} `, ); writeFile( '/comp.html', [ `<div *ngIf="true">changed</div>`, `<div>`, `@if (!ruleGroupDropdownLabels?.get(JoinOperator.AND)) {`, `<ng-container`, `i18n="{{i18n}}"`, `>`, `Match <strong>EVERY</strong> rule in this group`, `</ng-container>`, `} @else {`, `{{ruleGroupDropdownLabels?.get(JoinOperator.AND)}}`, `}`, `</div>`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `@if (true) {`, ` <div>changed</div>`, `}`, `<div>`, ` @if (!ruleGroupDropdownLabels?.get(JoinOperator.AND)) {`, ` <ng-container`, ` i18n="{{i18n}}"`, ` >`, `Match <strong>EVERY</strong> rule in this group`, `</ng-container>`, ` } @else {`, ` {{ruleGroupDropdownLabels?.get(JoinOperator.AND)}}`, ` }`, `</div>`, ].join('\n'); expect(actual).toBe(expected); }); it('should remove empty lines only in parts of template that were changed', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', templateUrl: 'comp.html', }) class DeclareComp {} `, ); writeFile( '/comp.html', [ `<div>header</div>\n`, `<span>header</span>\n\n\n`, `<div *ngIf="true">changed</div>`, `<div>\n`, ` <ul>`, ` <li *ngFor="let item of items">{{ item }}</li>`, ` </ul>`, `</div>\n\n`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `<div>header</div>\n`, `<span>header</span>\n\n\n`, `@if (true) {`, ` <div>changed</div>`, `}`, `<div>\n`, ` <ul>`, ` @for (item of items; track item) {`, ` <li>{{ item }}</li>`, ` }`, ` </ul>`, `</div>\n\n`, ].join('\n'); expect(actual).toBe(expected); }); it('should reformat properly with if else and mixed content', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', templateUrl: 'comp.html', }) class DeclareComp {} `, ); writeFile( '/comp.html', [ `<div *ngIf="true">changed</div>`, `<button`, `class="things"`, `(click)="stuff">`, `@if (aCondition) {`, `Match <strong>EVERY</strong> rule group`, `} @else {`, `{{ruleGroupDropdownLabels?.get(JoinOperator.AND)}}`, `}`, `</button>`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `@if (true) {`, ` <div>changed</div>`, `}`, `<button`, ` class="things"`, ` (click)="stuff">`, ` @if (aCondition) {`, ` Match <strong>EVERY</strong> rule group`, ` } @else {`, ` {{ruleGroupDropdownLabels?.get(JoinOperator.AND)}}`, ` }`, `</button>`, ].join('\n'); expect(actual).toBe(expected); });
{ "end_byte": 142250, "start_byte": 135186, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/control_flow_migration_spec.ts_142256_149792
ould reformat self closing tags', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', templateUrl: 'comp.html', }) class DeclareComp {} `, ); writeFile( '/comp.html', [ `<div *ngIf="true">changed</div>`, `<div>`, `@if (stuff) {`, `<img src="path.png" alt="stuff" />`, `} @else {`, `<img src="path.png"`, `alt="stuff" />`, `}`, `</div>\n`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `@if (true) {`, ` <div>changed</div>`, `}`, `<div>`, ` @if (stuff) {`, ` <img src="path.png" alt="stuff" />`, ` } @else {`, ` <img src="path.png"`, ` alt="stuff" />`, ` }`, `</div>\n`, ].join('\n'); expect(actual).toBe(expected); }); it('should format input tags without self closing slash', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'declare-comp', templateUrl: 'comp.html', }) class DeclareComp {} `, ); writeFile( '/comp.html', [ `<div *ngIf="true">changed</div>`, `<div>`, `@if (stuff) {`, `<img src="path.png" alt="stuff">`, `} @else {`, `<img src="path.png"`, `alt="stuff">`, `}`, `</div>\n`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `@if (true) {`, ` <div>changed</div>`, `}`, `<div>`, ` @if (stuff) {`, ` <img src="path.png" alt="stuff">`, ` } @else {`, ` <img src="path.png"`, ` alt="stuff">`, ` }`, `</div>\n`, ].join('\n'); expect(actual).toBe(expected); }); it('should preserve inline template indentation', async () => { writeFile( '/comp.ts', [ `import {Component} from '@angular/core';`, `import {NgIf} from '@angular/common';\n`, `@Component({`, ` selector: 'declare-comp',`, ` template: \``, ` <div *ngIf="true">changed</div>`, ` <div>`, ` @if (stuff) {`, ` <img src="path.png" alt="stuff" />`, ` } @else {`, ` <img src="path.png"`, ` alt="stuff" />`, ` }`, ` </div>`, ` \`,`, `})`, `class DeclareComp {}`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.ts'); const expected = [ `import {Component} from '@angular/core';\n\n`, `@Component({`, ` selector: 'declare-comp',`, ` template: \``, ` @if (true) {`, ` <div>changed</div>`, ` }`, ` <div>`, ` @if (stuff) {`, ` <img src="path.png" alt="stuff" />`, ` } @else {`, ` <img src="path.png"`, ` alt="stuff" />`, ` }`, ` </div>`, ` \`,`, `})`, `class DeclareComp {}`, ].join('\n'); expect(actual).toBe(expected); }); it('should migrate an if else case and not format', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, `<span *ngIf="show;else elseBlock">Content here</span>`, `<ng-template #elseBlock>Else Content</ng-template>`, `</div>`, ].join('\n'), ); await runMigration(undefined, false); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div>`, `@if (show) {`, `<span>Content here</span>`, `} @else {`, `Else Content`, `}\n`, `</div>`, ].join('\n'), ); }); it('should ignore formatting on i18n sections', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div>`, ` <p i18n>`, ` blah`, `</p>`, `<span *ngIf="show;else elseBlock" i18n>Content here</span>`, `<ng-template #elseBlock i18n>`, ` `, ` <p>Else Content</p>`, `</ng-template>`, `</div>`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `<div>`, ` <p i18n>`, ` blah`, `</p>`, ` @if (show) {`, ` <span i18n>Content here</span>`, ` } @else {`, ` <ng-container i18n>`, ` `, ` <p>Else Content</p>`, `</ng-container>`, ` }`, `</div>`, ].join('\n'); expect(actual).toBe(expected); }); it('should indent multi-line attribute strings to the right place', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div *ngIf="show">show</div>`, `<span i18n-message="this is a multi-`, ` line attribute`, ` with cool things">`, ` Content here`, `</span>`, `<span`, ` i18n-message="this is a multi-`, ` line attribute`, ` that starts`, ` on a newline">`, ` Different Content`, `</span>`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `@if (show) {`, ` <div>show</div>`, `}`, `<span i18n-message="this is a multi-`, ` line attribute`, ` with cool things">`, ` Content here`, `</span>`, `<span`, ` i18n-message="this is a multi-`, ` line attribute`, ` that starts`, ` on a newline">`, ` Different Content`, `</span>`, ].join('\n'); expect(actual).toBe(expected); });
{ "end_byte": 149792, "start_byte": 142256, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/control_flow_migration_spec.ts_149798_153494
ould indent multi-line attribute strings as single quotes to the right place', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div *ngIf="show">show</div>`, `<span i18n-message='this is a multi-`, ` line attribute`, ` with cool things'>`, ` Content here`, `</span>`, `<span`, ` i18n-message='this is a multi-`, ` line attribute`, ` that starts`, ` on a newline'>`, ` Different here`, `</span>`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `@if (show) {`, ` <div>show</div>`, `}`, `<span i18n-message='this is a multi-`, ` line attribute`, ` with cool things'>`, ` Content here`, `</span>`, `<span`, ` i18n-message='this is a multi-`, ` line attribute`, ` that starts`, ` on a newline'>`, ` Different here`, `</span>`, ].join('\n'); expect(actual).toBe(expected); }); it('should handle dom nodes with underscores mixed in', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ templateUrl: './comp.html' }) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<div *ngIf="show">show</div>`, `<a-very-long-component-name-that-has_underscores-too`, ` [selected]="selected | async "`, `>`, `</a-very-long-component-name-that-has_underscores-too>`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `@if (show) {`, ` <div>show</div>`, `}`, `<a-very-long-component-name-that-has_underscores-too`, ` [selected]="selected | async "`, ` >`, `</a-very-long-component-name-that-has_underscores-too>`, ].join('\n'); expect(actual).toBe(expected); }); it('should handle single-line element with a log tag name and a closing bracket on a new line', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({templateUrl: './comp.html'}) class Comp { show = false; } `, ); writeFile( '/comp.html', [ `<ng-container *ngIf="true">`, `<component-name-with-several-dashes></component-name-with-several-dashes`, `></ng-container>`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.html'); const expected = [ `@if (true) {`, ` <component-name-with-several-dashes></component-name-with-several-dashes`, ` >`, ` }`, ].join('\n'); expect(actual).toBe(expected); }); }); de
{ "end_byte": 153494, "start_byte": 149798, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/control_flow_migration_spec.ts_153498_161178
be('imports', () => { it('should remove common module imports post migration', async () => { writeFile( '/comp.ts', [ `import {Component} from '@angular/core';`, `import {NgIf} from '@angular/common';`, `@Component({`, ` imports: [NgIf],`, ` template: \`<div><span *ngIf="toggle">shrug</span></div>\``, `})`, `class Comp {`, ` toggle = false;`, `}`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.ts'); const expected = [ `import {Component} from '@angular/core';\n`, `@Component({`, ` imports: [],`, ` template: \`<div>@if (toggle) {<span>shrug</span>}</div>\``, `})`, `class Comp {`, ` toggle = false;`, `}`, ].join('\n'); expect(actual).toBe(expected); }); it('should not remove common module imports post migration if errors prevented migrating the external template file', async () => { writeFile( '/comp.ts', [ `import {Component} from '@angular/core';`, `import {NgIf} from '@angular/common';`, `@Component({`, ` imports: [NgIf],`, ` templateUrl: './comp.html',`, `})`, `class Comp {`, ` toggle = false;`, `}`, ].join('\n'), ); writeFile( '/comp.html', [ `<div>`, ` <span *ngIf="toggle; else elseTmpl">shrug</span>`, `</div>`, `<ng-template #elseTmpl>else content</ng-template>`, `<ng-template #elseTmpl>different</ng-template>`, ].join('\n'), ); await runMigration(); const actualCmp = tree.readContent('/comp.ts'); const expectedCmp = [ `import {Component} from '@angular/core';`, `import {NgIf} from '@angular/common';`, `@Component({`, ` imports: [NgIf],`, ` templateUrl: './comp.html',`, `})`, `class Comp {`, ` toggle = false;`, `}`, ].join('\n'); const actualTemplate = tree.readContent('/comp.html'); const expectedTemplate = [ `<div>`, ` <span *ngIf="toggle; else elseTmpl">shrug</span>`, `</div>`, `<ng-template #elseTmpl>else content</ng-template>`, `<ng-template #elseTmpl>different</ng-template>`, ].join('\n'); expect(actualCmp).toBe(expectedCmp); expect(actualTemplate).toBe(expectedTemplate); }); it('should not remove common module imports post migration if other items used', async () => { writeFile( '/comp.ts', [ `import {CommonModule} from '@angular/common';`, `import {Component} from '@angular/core';\n`, `@Component({`, ` imports: [NgIf, DatePipe],`, ` template: \`<div><span *ngIf="toggle">{{ d | date }}</span></div>\``, `})`, `class Comp {`, ` toggle = false;`, `}`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.ts'); const expected = [ `import {CommonModule} from '@angular/common';`, `import {Component} from '@angular/core';\n`, `@Component({`, ` imports: [DatePipe],`, ` template: \`<div>@if (toggle) {<span>{{ d | date }}</span>}</div>\``, `})`, `class Comp {`, ` toggle = false;`, `}`, ].join('\n'); expect(actual).toBe(expected); }); it('should not duplicate comments post migration if other items used', async () => { writeFile( '/comp.ts', [ `// comment here`, `import {NgIf, CommonModule} from '@angular/common';`, `import {Component} from '@angular/core';\n`, `@Component({`, ` imports: [NgIf, DatePipe],`, ` template: \`<div><span *ngIf="toggle">{{ d | date }}</span></div>\``, `})`, `class Comp {`, ` toggle = false;`, `}`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.ts'); const expected = [ `// comment here`, `import { CommonModule } from '@angular/common';`, `import {Component} from '@angular/core';\n`, `@Component({`, ` imports: [DatePipe],`, ` template: \`<div>@if (toggle) {<span>{{ d | date }}</span>}</div>\``, `})`, `class Comp {`, ` toggle = false;`, `}`, ].join('\n'); expect(actual).toBe(expected); }); it('should leave non-cf common module imports post migration', async () => { writeFile( '/comp.ts', [ `import {Component} from '@angular/core';`, `import {NgIf, AsyncPipe} from '@angular/common';\n`, `@Component({`, ` imports: [NgIf, AsyncPipe],`, ` template: \`<div><span *ngIf="toggle">shrug</span></div>\``, `})`, `class Comp {`, ` toggle = false;`, `}`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.ts'); const expected = [ `import {Component} from '@angular/core';`, `import { AsyncPipe } from '@angular/common';\n`, `@Component({`, ` imports: [AsyncPipe],`, ` template: \`<div>@if (toggle) {<span>shrug</span>}</div>\``, `})`, `class Comp {`, ` toggle = false;`, `}`, ].join('\n'); expect(actual).toBe(expected); }); it('should remove common module post migration', async () => { writeFile( '/comp.ts', [ `import {Component} from '@angular/core';`, `import {CommonModule} from '@angular/common';`, `@Component({`, ` imports: [CommonModule],`, ` template: \`<div><span *ngIf="toggle">shrug</span></div>\``, `})`, `class Comp {`, ` toggle = false;`, `}`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.ts'); const expected = [ `import {Component} from '@angular/core';\n`, `@Component({`, ` imports: [],`, ` template: \`<div>@if (toggle) {<span>shrug</span>}</div>\``, `})`, `class Comp {`, ` toggle = false;`, `}`, ].join('\n'); expect(actual).toBe(expected); }); it('should leave common module post migration if other common module deps exist', async () => { writeFile( '/comp.ts', [ `import {Component} from '@angular/core';`, `import {CommonModule} from '@angular/common';\n`, `@Component({`, ` imports: [CommonModule],`, ` template: \`<div><span *ngIf="toggle">{{ shrug | lowercase }}</span></div>\``, `})`, `class Comp {`, ` toggle = false;`, `}`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.ts'); const expected = [ `import {Component} from '@angular/core';`, `import {CommonModule} from '@angular/common';\n`, `@Component({`, ` imports: [CommonModule],`, ` template: \`<div>@if (toggle) {<span>{{ shrug | lowercase }}</span>}</div>\``, `})`, `class Comp {`, ` toggle = false;`, `}`, ].join('\n'); expect(actual).toBe(expected); });
{ "end_byte": 161178, "start_byte": 153498, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/control_flow_migration_spec.ts_161184_167947
ould remove common module post migration if using external template', async () => { writeFile( '/comp.ts', [ `import {Component} from '@angular/core';`, `import {CommonModule} from '@angular/common';\n`, `@Component({`, ` imports: [CommonModule],`, ` templateUrl: './comp.html',`, `})`, `class Comp {`, ` toggle = false;`, `}`, ].join('\n'), ); writeFile( '/comp.html', [`<div>`, `<span *ngIf="show">Content here</span>`, `</div>`].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.ts'); const expected = [ `import {Component} from '@angular/core';\n\n`, `@Component({`, ` imports: [],`, ` templateUrl: './comp.html',`, `})`, `class Comp {`, ` toggle = false;`, `}`, ].join('\n'); expect(actual).toBe(expected); }); it('should not remove common module when more common module symbols are found', async () => { writeFile( '/comp.ts', [ `import {Component, NgModule} from '@angular/core';`, `import {CommonModule} from '@angular/common';\n`, `@Component({`, ` selector: 'example-cmp',`, ` templateUrl: './comp.html',`, `})`, `export class ExampleCmp {`, `}`, `@Component({`, ` standalone: true`, ` selector: 'example2-cmp',`, ` imports: [CommonModule],`, ` templateUrl: './comp.html',`, `})`, `export class Example2Cmp {`, `}`, `const NG_MODULE_IMPORTS = [CommonModule, OtherModule];`, ``, `@NgModule({`, ` declarations: [ExampleCmp],`, ` exports: [ExampleCmp],`, ` imports: [NG_MODULE_IMPORTS],`, `})`, `export class ExampleModule {}`, ].join('\n'), ); writeFile( '/comp.html', [`<div>`, `<span *ngIf="show">Content here</span>`, `</div>`].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.ts'); const expected = [ `import {Component, NgModule} from '@angular/core';`, `import {CommonModule} from '@angular/common';\n`, `@Component({`, ` selector: 'example-cmp',`, ` templateUrl: './comp.html',`, `})`, `export class ExampleCmp {`, `}`, `@Component({`, ` standalone: true`, ` selector: 'example2-cmp',`, ` imports: [],`, ` templateUrl: './comp.html',`, `})`, `export class Example2Cmp {`, `}`, `const NG_MODULE_IMPORTS = [CommonModule, OtherModule];`, ``, `@NgModule({`, ` declarations: [ExampleCmp],`, ` exports: [ExampleCmp],`, ` imports: [NG_MODULE_IMPORTS],`, `})`, `export class ExampleModule {}`, ].join('\n'); expect(actual).toBe(expected); }); it('should not remove common module when second run of migration and common module symbols are found', async () => { writeFile( '/comp.ts', [ `import {Component} from '@angular/core';`, `import {CommonModule} from '@angular/common';\n`, `@Component({`, ` standalone: true`, ` selector: 'example-cmp',`, ` templateUrl: './comp.html',`, ` imports: [CommonModule],`, `})`, `export class ExampleCmp {`, `}`, ].join('\n'), ); writeFile( '/comp.html', [ `<div>`, ` @if (state$ | async; as state) {`, ` <div>`, ` <span>Content here {{state}}</span>`, ` </div>`, ` }`, `</div>`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.ts'); const expected = [ `import {Component} from '@angular/core';`, `import {CommonModule} from '@angular/common';\n`, `@Component({`, ` standalone: true`, ` selector: 'example-cmp',`, ` templateUrl: './comp.html',`, ` imports: [CommonModule],`, `})`, `export class ExampleCmp {`, `}`, ].join('\n'); expect(actual).toBe(expected); }); it('should not remove imports when mismatch in counts', async () => { writeFile( '/comp.ts', [ `import {CommonModule} from '@angular/common';`, `import {Component, NgModule, Pipe, PipeTransform} from '@angular/core';`, `@Component({`, ` selector: 'description',`, ` template: \`<span>{{getDescription()}}</span>\`,`, `})`, `export class DescriptionController {`, ` getDescription(): string {`, ` return 'stuff';`, ` }`, `}`, ``, `@Pipe({name: 'description'})`, `export class DescriptionPipe implements PipeTransform {`, ` transform(nameString?: string): string {`, ` return nameString ?? '';`, ` }`, `}`, `@NgModule({`, ` declarations: [DescriptionController, DescriptionPipe],`, ` imports: [CommonModule],`, ` providers: [],`, ` exports: [DescriptionController, DescriptionPipe],`, `})`, `export class DescriptionModule {}`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.ts'); const expected = [ `import {CommonModule} from '@angular/common';`, `import {Component, NgModule, Pipe, PipeTransform} from '@angular/core';`, `@Component({`, ` selector: 'description',`, ` template: \`<span>{{getDescription()}}</span>\`,`, `})`, `export class DescriptionController {`, ` getDescription(): string {`, ` return 'stuff';`, ` }`, `}`, ``, `@Pipe({name: 'description'})`, `export class DescriptionPipe implements PipeTransform {`, ` transform(nameString?: string): string {`, ` return nameString ?? '';`, ` }`, `}`, `@NgModule({`, ` declarations: [DescriptionController, DescriptionPipe],`, ` imports: [CommonModule],`, ` providers: [],`, ` exports: [DescriptionController, DescriptionPipe],`, `})`, `export class DescriptionModule {}`, ].join('\n'); expect(actual).toBe(expected); });
{ "end_byte": 167947, "start_byte": 161184, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/control_flow_migration_spec.ts_167953_171767
ould not remove other imports when mismatch in counts', async () => { writeFile( '/comp.ts', [ `import {DatePipe, NgIf} from '@angular/common';`, `import {Component, NgModule, Pipe, PipeTransform} from '@angular/core';`, `@Component({`, ` selector: 'example',`, ` template: \`<span>{{ example | date }}</span>\`,`, `})`, `export class ExampleCmp {`, ` example: 'stuff',`, `}`, `const NG_MODULE_IMPORTS = [`, ` DatePipe,`, ` NgIf,`, `];`, `@NgModule({`, ` declarations: [ExampleCmp],`, ` imports: [NG_MODULE_IMPORTS],`, ` exports: [ExampleCmp],`, `})`, `export class ExampleModule {}`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.ts'); const expected = [ `import {DatePipe, NgIf} from '@angular/common';`, `import {Component, NgModule, Pipe, PipeTransform} from '@angular/core';`, `@Component({`, ` selector: 'example',`, ` template: \`<span>{{ example | date }}</span>\`,`, `})`, `export class ExampleCmp {`, ` example: 'stuff',`, `}`, `const NG_MODULE_IMPORTS = [`, ` DatePipe,`, ` NgIf,`, `];`, `@NgModule({`, ` declarations: [ExampleCmp],`, ` imports: [NG_MODULE_IMPORTS],`, ` exports: [ExampleCmp],`, `})`, `export class ExampleModule {}`, ].join('\n'); expect(actual).toBe(expected); }); it('should not modify `imports` initialized to a variable reference', async () => { writeFile( '/comp.ts', [ `import {Component} from '@angular/core';`, `import {CommonModule} from '@angular/common';\n`, `const IMPORTS = [CommonModule];\n`, `@Component({`, ` imports: IMPORTS,`, ` template: '<span *ngIf="show">Content here</span>',`, `})`, `class Comp {`, ` show = false;`, `}`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.ts'); const expected = [ `import {Component} from '@angular/core';`, `import {CommonModule} from '@angular/common';\n`, `const IMPORTS = [CommonModule];\n`, `@Component({`, ` imports: IMPORTS,`, ` template: '@if (show) {<span>Content here</span>}',`, `})`, `class Comp {`, ` show = false;`, `}`, ].join('\n'); expect(actual).toBe(expected); }); it('should handle spread elements in the `imports` array', async () => { writeFile( '/comp.ts', [ `import {Component} from '@angular/core';`, `import {CommonModule} from '@angular/common';\n`, `const BEFORE = [];\n`, `const AFTER = [];\n`, `@Component({`, ` imports: [...BEFORE, CommonModule, ...AFTER],`, ` template: '<span *ngIf="show">Content here</span>',`, `})`, `class Comp {`, ` show = false;`, `}`, ].join('\n'), ); await runMigration(); const actual = tree.readContent('/comp.ts'); const expected = [ `import {Component} from '@angular/core';\n\n`, `const BEFORE = [];\n`, `const AFTER = [];\n`, `@Component({`, ` imports: [...BEFORE, ...AFTER],`, ` template: '@if (show) {<span>Content here</span>}',`, `})`, `class Comp {`, ` show = false;`, `}`, ].join('\n'); expect(actual).toBe(expected); }); }); de
{ "end_byte": 171767, "start_byte": 167953, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/control_flow_migration_spec.ts_171771_176045
be('no migration needed', () => { it('should do nothing when no control flow is present', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgIf], template: \`<div><span>shrug</span></div>\` }) class Comp { toggle = false; } `, ); await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain('template: `<div><span>shrug</span></div>`'); }); it('should do nothing with already present updated control flow', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgIf], template: \`<div>@if (toggle) {<span>shrug</span>}</div>\` }) class Comp { toggle = false; } `, ); await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain('template: `<div>@if (toggle) {<span>shrug</span>}</div>`'); }); it('should migrate an ngif inside a block', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgIf], template: \`<div>@if (toggle) {<div><span *ngIf="show">shrug</span></div>}</div>\` }) class Comp { toggle = false; show = false; } `, ); await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain( 'template: `<div>@if (toggle) {<div>@if (show) {<span>shrug</span>}</div>}</div>`', ); }); it('should update let value in a build if block to as value for the new control flow', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ imports: [NgIf], template: \`<ng-container *ngIf="value$ | async; let value"> {{value}} </ng-container>\` }) class Comp { value$ = of('Rica'); } `, ); await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain('template: `@if (value$ | async; as value) { {{value}} }`'); }); it('should update let value in a standard if else block to as value for the new control flow', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {CommonModule} from '@angular/common'; @Component({ imports: [CommonModule], template: \`<div *ngIf="(logStatus$ | async)?.name; let userName; else loggedOut"> Hello {{ userName }} ! </div><ng-template #loggedOut></ng-template>\` }) class Comp { logStatus$ = of({ name: 'Robert' }); } `, ); await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain( 'template: `@if ((logStatus$ | async)?.name; as userName) {<div> Hello {{ userName }} ! </div>} @else {}`', ); }); it('should update let value in a standard if else, then block to as value for the new control flow', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; import {CommonModule} from '@angular/common'; @Component({ imports: [CommonModule], template: \`<div *ngIf="isLoggedIn$ | async; let logIn; then loggedIn; else loggedOut"></div><ng-template #loggedIn>Log In</ng-template> <ng-template #loggedOut>Log Out</ng-template>\` }) class Comp { isLoggedIn$ = of(true); } `, ); await runMigration(); const content = tree.readContent('/comp.ts'); expect(content).toContain( 'template: `@if (isLoggedIn$ | async; as logIn) {\n Log In\n} @else {\n Log Out\n}\n`', ); }); }); de
{ "end_byte": 176045, "start_byte": 171771, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/control_flow_migration_spec.ts_176049_180033
be('error handling', () => { it('should not migrate a template that would result in invalid html', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; @Component({ templateUrl: './comp.html' }) class Comp { testOpts = 2; } `, ); writeFile( '/comp.html', [ `<div *ngIf="stuff; else elseTmpl">`, ` Stuff`, `</div>`, `<ng-template #elseTmpl>`, ` <div>things</div>`, `<ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div *ngIf="stuff; else elseTmpl">`, ` Stuff`, `</div>`, `<ng-template #elseTmpl>`, ` <div>things</div>`, `<ng-template>`, ].join('\n'), ); const warnings = warnOutput.join(' '); expect(warnings).toContain('The migration resulted in invalid HTML for'); expect(warnings).toContain( 'Please check the template for valid HTML structures and run the migration again.', ); }); it('should not migrate a template that would result in invalid switch block contents', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; @Component({ templateUrl: './comp.html' }) class Comp { testOpts = 2; } `, ); writeFile( '/comp.html', [ `<div [ngSwitch]="testOpts">`, `<strong>`, `<p *ngSwitchCase="1">Option 1</p>`, `<p *ngSwitchCase="2">Option 2</p>`, `<p *ngSwitchDefault>Option 3</p>`, `</strong>`, `</div>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<div [ngSwitch]="testOpts">`, `<strong>`, `<p *ngSwitchCase="1">Option 1</p>`, `<p *ngSwitchCase="2">Option 2</p>`, `<p *ngSwitchDefault>Option 3</p>`, `</strong>`, `</div>`, ].join('\n'), ); expect(warnOutput.join(' ')).toContain( `Element node: "strong" would result in invalid migrated @switch block structure. ` + `@switch can only have @case or @default as children.`, ); }); it('should not migrate a template that would result in invalid i18n nesting', async () => { writeFile( '/comp.ts', ` import {Component} from '@angular/core'; @Component({ templateUrl: './comp.html' }) class Comp { testOpts = 2; } `, ); writeFile( '/comp.html', [ `<ng-container i18n="messageid">`, ` <div *ngIf="condition; else elseTmpl">`, ` If content here`, ` </div>`, `</ng-container>`, `<ng-template #elseTmpl i18n="elsemessageid">`, ` <div>Else content here</div>`, `</ng-template>`, ].join('\n'), ); await runMigration(); const content = tree.readContent('/comp.html'); expect(content).toBe( [ `<ng-container i18n="messageid">`, ` <div *ngIf="condition; else elseTmpl">`, ` If content here`, ` </div>`, `</ng-container>`, `<ng-template #elseTmpl i18n="elsemessageid">`, ` <div>Else content here</div>`, `</ng-template>`, ].join('\n'), ); expect(warnOutput.join(' ')).toContain( `Element with i18n attribute "ng-container" would result having a child of element with i18n attribute ` + `"ng-container". Please fix and re-run the migration.`, ); }); }); });
{ "end_byte": 180033, "start_byte": 176049, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts" }
angular/packages/core/schematics/test/queries_migration_spec.ts_0_2167
/** * @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 {getSystemPath, normalize, virtualFs} from '@angular-devkit/core'; import {TempScopedNodeJsSyncHost} from '@angular-devkit/core/node/testing'; import {HostTree} from '@angular-devkit/schematics'; import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing'; import {runfiles} from '@bazel/runfiles'; import shx from 'shelljs'; describe('signal queries migration', () => { let runner: SchematicTestRunner; let host: TempScopedNodeJsSyncHost; let tree: UnitTestTree; let tmpDirPath: string; let previousWorkingDir: string; function writeFile(filePath: string, contents: string) { host.sync.write(normalize(filePath), virtualFs.stringToFileBuffer(contents)); } function runMigration(options?: {path?: string}) { return runner.runSchematic('signal-queries-migration', options, tree); } beforeEach(() => { runner = new SchematicTestRunner('test', runfiles.resolvePackageRelative('../collection.json')); host = new TempScopedNodeJsSyncHost(); tree = new UnitTestTree(new HostTree(host)); writeFile('/tsconfig.json', '{}'); writeFile( '/angular.json', JSON.stringify({ version: 1, projects: {t: {root: '', architect: {build: {options: {tsConfig: './tsconfig.json'}}}}}, }), ); previousWorkingDir = shx.pwd(); tmpDirPath = getSystemPath(host.root); shx.cd(tmpDirPath); }); afterEach(() => { shx.cd(previousWorkingDir); shx.rm('-r', tmpDirPath); }); it('should work', async () => { writeFile( '/index.ts', ` import {ContentChild, ElementRef, Directive} from '@angular/core'; @Directive({}) export class SomeDirective { @ContentChild('ref') ref!: ElementRef; }`, ); await runMigration(); const content = tree.readContent('/index.ts').replace(/\s+/g, ' '); expect(content).toContain("readonly ref = contentChild.required<ElementRef>('ref');"); }); });
{ "end_byte": 2167, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/queries_migration_spec.ts" }
angular/packages/core/schematics/test/BUILD.bazel_0_1288
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = glob(["*.ts"]), deps = [ "//packages/core/schematics/utils", "//packages/core/schematics/utils/tsurge", "@npm//@angular-devkit/core", "@npm//@angular-devkit/schematics", "@npm//@bazel/runfiles", "@npm//@types/shelljs", "@npm//tslint", ], ) jasmine_node_test( name = "test", data = [ "//packages/core/schematics:bundles", "//packages/core/schematics:collection.json", "//packages/core/schematics:migrations.json", "//packages/core/schematics/ng-generate/control-flow-migration:static_files", "//packages/core/schematics/ng-generate/inject-migration:static_files", "//packages/core/schematics/ng-generate/output-migration:static_files", "//packages/core/schematics/ng-generate/route-lazy-loading:static_files", "//packages/core/schematics/ng-generate/signal-queries-migration:static_files", "//packages/core/schematics/ng-generate/signals:static_files", "//packages/core/schematics/ng-generate/standalone-migration:static_files", ], deps = [ ":test_lib", "@npm//shelljs", ], )
{ "end_byte": 1288, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/BUILD.bazel" }
angular/packages/core/schematics/test/inject_migration_spec.ts_0_561
/** * @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 {getSystemPath, normalize, virtualFs} from '@angular-devkit/core'; import {TempScopedNodeJsSyncHost} from '@angular-devkit/core/node/testing'; import {HostTree} from '@angular-devkit/schematics'; import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing'; import {runfiles} from '@bazel/runfiles'; import shx from 'shelljs';
{ "end_byte": 561, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/inject_migration_spec.ts" }
angular/packages/core/schematics/test/inject_migration_spec.ts_563_8292
describe('inject migration', () => { let runner: SchematicTestRunner; let host: TempScopedNodeJsSyncHost; let tree: UnitTestTree; let tmpDirPath: string; let previousWorkingDir: string; function writeFile(filePath: string, contents: string) { host.sync.write(normalize(filePath), virtualFs.stringToFileBuffer(contents)); } function runMigration(options?: { path?: string; backwardsCompatibleConstructors?: boolean; migrateAbstractClasses?: boolean; nonNullableOptional?: boolean; _internalCombineMemberInitializers?: boolean; }) { return runner.runSchematic('inject-migration', options, tree); } beforeEach(() => { runner = new SchematicTestRunner('test', runfiles.resolvePackageRelative('../collection.json')); host = new TempScopedNodeJsSyncHost(); tree = new UnitTestTree(new HostTree(host)); writeFile('/tsconfig.json', '{}'); writeFile( '/angular.json', JSON.stringify({ version: 1, projects: {t: {root: '', architect: {build: {options: {tsConfig: './tsconfig.json'}}}}}, }), ); previousWorkingDir = shx.pwd(); tmpDirPath = getSystemPath(host.root); shx.cd(tmpDirPath); }); afterEach(() => { shx.cd(previousWorkingDir); shx.rm('-r', tmpDirPath); }); ['Directive', 'Component', 'Pipe', 'NgModule'].forEach((decorator) => { it(`should migrate a @${decorator} to use inject()`, async () => { writeFile( '/dir.ts', [ `import { ${decorator} } from '@angular/core';`, `import { Foo } from 'foo';`, `import { Bar } from 'bar';`, ``, `@${decorator}()`, `class MyClass {`, ` constructor(private foo: Foo, readonly bar: Bar) {}`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { ${decorator}, inject } from '@angular/core';`, `import { Foo } from 'foo';`, `import { Bar } from 'bar';`, ``, `@${decorator}()`, `class MyClass {`, ` private foo = inject(Foo);`, ` readonly bar = inject(Bar);`, `}`, ]); }); }); it('should take the injected type from @Inject()', async () => { writeFile( '/dir.ts', [ `import { Directive, Inject } from '@angular/core';`, `import { Foo } from 'foo';`, `import { FOO_TOKEN } from './token';`, ``, `@Directive()`, `class MyDir {`, ` constructor(@Inject(FOO_TOKEN) private foo: Foo) {}`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, `import { FOO_TOKEN } from './token';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject<Foo>(FOO_TOKEN);`, `}`, ]); }); it('should account for string tokens in @Inject()', async () => { writeFile( '/dir.ts', [ `import { Directive, Inject } from '@angular/core';`, ``, `@Directive()`, `class MyDir {`, ` constructor(@Inject('not-officially-supported') private foo: number) {}`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject<number>('not-officially-supported' as any);`, `}`, ]); }); it('should account for injected generic parameters', async () => { writeFile( '/dir.ts', [ `import { Directive, Inject, ElementRef } from '@angular/core';`, ``, `@Directive()`, `class MyDir {`, ` constructor(`, ` private one: ElementRef<HTMLElement>`, ` @Inject(ElementRef) private two: ElementRef<HTMLButtonElement> | ElementRef<HTMLSpanElement>`, ` ) {}`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, ElementRef, inject } from '@angular/core';`, ``, `@Directive()`, `class MyDir {`, ` private one = inject<ElementRef<HTMLElement>>(ElementRef);`, ` private two = inject<ElementRef<HTMLButtonElement> | ElementRef<HTMLSpanElement>>(ElementRef);`, `}`, ]); }); it('should transform @Attribute() to HostAttributeToken', async () => { writeFile( '/dir.ts', [ `import { Directive, Attribute } from '@angular/core';`, ``, `@Directive()`, `class MyDir {`, ` constructor(@Attribute('foo') private foo: string) {}`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, HostAttributeToken, inject } from '@angular/core';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(new HostAttributeToken('foo'));`, `}`, ]); }); it('should generate the options object if additional decorators are used', async () => { writeFile( '/dir.ts', [ `import { Directive, Inject, Optional, Self, Host } from '@angular/core';`, `import { FOO_TOKEN, BAR_TOKEN, Foo } from './tokens';`, ``, `@Directive()`, `class MyDir {`, ` constructor(`, ` @Inject(FOO_TOKEN) @Optional() private a: number`, ` @Self() @Inject(BAR_TOKEN) protected b: string`, ` @Optional() @Host() readonly c: Foo`, ` ) {}`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { FOO_TOKEN, BAR_TOKEN, Foo } from './tokens';`, ``, `@Directive()`, `class MyDir {`, ` private a = inject(FOO_TOKEN, { optional: true });`, ` protected b = inject(BAR_TOKEN, { self: true });`, ` readonly c = inject(Foo, { optional: true, host: true });`, `}`, ]); }); it('should preserve parameter decorators if they are used outside of the migrated class', async () => { writeFile( '/dir.ts', [ `import { Directive, Inject, Optional } from '@angular/core';`, `import { Foo } from 'foo';`, `import { FOO_TOKEN } from './token';`, ``, `@Directive({`, ` providers: [`, ` {`, ` provide: FOO_TOKEN,`, ` deps: [new Inject(FOO_TOKEN), new Optional()]`, ` useFactory: (defaultValue?: any) => defaultValue || 'hello'`, ` }`, ` ]`, `})`, `class MyDir {`, ` constructor(@Inject(FOO_TOKEN) @Optional() private foo: Foo) {}`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, Inject, Optional, inject } from '@angular/core';`, `import { Foo } from 'foo';`, `import { FOO_TOKEN } from './token';`, ``, `@Directive({`, ` providers: [`, ` {`, ` provide: FOO_TOKEN,`, ` deps: [new Inject(FOO_TOKEN), new Optional()]`, ` useFactory: (defaultValue?: any) => defaultValue || 'hello'`, ` }`, ` ]`, `})`, `class MyDir {`, ` private foo = inject<Foo>(FOO_TOKEN, { optional: true });`, `}`, ]); });
{ "end_byte": 8292, "start_byte": 563, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/inject_migration_spec.ts" }
angular/packages/core/schematics/test/inject_migration_spec.ts_8296_15391
it('should migrate an aliased decorator to use inject()', async () => { writeFile( '/dir.ts', [ `import { Directive as NgDirective } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@NgDirective()`, `class MyDir {`, ` constructor(private foo: Foo) {}`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive as NgDirective, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@NgDirective()`, `class MyDir {`, ` private foo = inject(Foo);`, `}`, ]); }); it('should migrate an aliased decorator to use inject()', async () => { writeFile( '/dir.ts', [ `import { Directive as NgDirective } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@NgDirective()`, `class MyDir {`, ` constructor(private foo: Foo) {}`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive as NgDirective, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@NgDirective()`, `class MyDir {`, ` private foo = inject(Foo);`, `}`, ]); }); it('should only migrate classes in the specified directory', async () => { writeFile( '/should-migrate/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` constructor(private foo: Foo) {}`, `}`, ].join('\n'), ); writeFile( '/should-not-migrate/other-dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyOtherDir {`, ` constructor(private foo: Foo) {}`, `}`, ].join('\n'), ); await runMigration({path: '/should-migrate'}); expect(tree.readContent('/should-migrate/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, `}`, ]); expect(tree.readContent('/should-not-migrate/other-dir.ts').split('\n')).toEqual([ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyOtherDir {`, ` constructor(private foo: Foo) {}`, `}`, ]); }); it('should not migrate classes decorated with a non-Angular decorator', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@not-angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` constructor(private foo: Foo) {}`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive } from '@not-angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` constructor(private foo: Foo) {}`, `}`, ]); }); it('should migrate a nested class', async () => { writeFile( '/comp.spec.ts', [ `import { Component } from '@angular/core';`, `import { TestBed } from '@angular/core/testing';`, `import { Foo } from 'foo';`, ``, `describe('MyComp', () => {`, ` it('should work', () => {`, ` @Component({standalone: true})`, ` class MyComp {`, ` constructor(private foo: Foo) {}`, ` }`, ``, ` TestBed.createComponent(MyComp);`, ` });`, `});`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/comp.spec.ts').split('\n')).toEqual([ `import { Component, inject } from '@angular/core';`, `import { TestBed } from '@angular/core/testing';`, `import { Foo } from 'foo';`, ``, `describe('MyComp', () => {`, ` it('should work', () => {`, ` @Component({standalone: true})`, ` class MyComp {`, ` private foo = inject(Foo);`, ` }`, ``, ` TestBed.createComponent(MyComp);`, ` });`, `});`, ]); }); it('should preserve the constructor if it has other expressions', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` constructor(private foo: Foo) {`, ` console.log('hello');`, ` }`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ``, ` constructor() {`, ` console.log('hello');`, ` }`, `}`, ]); }); it('should declare a variable if an injected parameter without modifiers is referenced in the constructor', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` constructor(foo: Foo) {`, ` console.log(foo.bar + 123);`, ` }`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` constructor() {`, ` const foo = inject(Foo);`, ``, ` console.log(foo.bar + 123);`, ` }`, `}`, ]); }); it('should declare a variable if an injected parameter with modifiers is referenced in the constructor', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` constructor(readonly foo: Foo) {`, ` console.log(foo.bar + 123);`, ` }`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` readonly foo = inject(Foo);`, ``, ` constructor() {`, ` const foo = this.foo;`, ``, ` console.log(foo.bar + 123);`, ` }`, `}`, ]); });
{ "end_byte": 15391, "start_byte": 8296, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/inject_migration_spec.ts" }
angular/packages/core/schematics/test/inject_migration_spec.ts_15395_22698
it('should declare a variable if an injected parameter with modifiers is referenced in the constructor via shorthand assignment', async () => { writeFile( '/dir.ts', [ `import { Directive, Inject, LOCALE_ID } from '@angular/core';`, ``, `@Directive()`, `class MyDir {`, ` constructor(@Inject(LOCALE_ID) locale: string) {`, ` console.log({ locale });`, ` }`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, LOCALE_ID, inject } from '@angular/core';`, ``, `@Directive()`, `class MyDir {`, ` constructor() {`, ` const locale = inject(LOCALE_ID);`, ``, ` console.log({ locale });`, ` }`, `}`, ]); }); it('should not declare a variable in the constructor if the only references to the parameter are shadowed', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` constructor(private foo: Foo) {`, ` console.log([1, 2, 3].map(foo => foo * 2));`, ` }`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ``, ` constructor() {`, ` console.log([1, 2, 3].map(foo => foo * 2));`, ` }`, `}`, ]); }); it('should remove all constructor signatures when deleting its implementation', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, `import { Bar } from 'bar';`, ``, `@Directive()`, `class MyDir {`, ` constructor(foo: Foo);`, ` constructor(foo: Foo, bar: Bar);`, ` constructor(private foo: Foo, bar?: Bar) {}`, ``, ` log() {`, ` console.log(this.foo.bar());`, ` }`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, `import { Bar } from 'bar';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ``, ``, ` log() {`, ` console.log(this.foo.bar());`, ` }`, `}`, ]); }); it('should remove constructor overloads when preserving its implementation', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, `import { Bar } from 'bar';`, ``, `@Directive()`, `class MyDir {`, ` constructor(foo: Foo);`, ` constructor(foo: Foo, bar: Bar);`, ` constructor(private foo: Foo, bar?: Bar) {`, ` console.log(this.foo.bar);`, ` }`, ``, ` log() {`, ` console.log(this.foo.bar());`, ` }`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, `import { Bar } from 'bar';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ``, ` constructor() {`, ` console.log(this.foo.bar);`, ` }`, ``, ` log() {`, ` console.log(this.foo.bar());`, ` }`, `}`, ]); }); it('should handle multi-line constructor parameters', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, `import { Bar } from 'bar';`, `import { Baz } from './baz';`, ``, `@Directive()`, `class MyDir {`, ` constructor(`, ` private foo: Foo,`, ` readonly bar: Bar,`, ` readonly baz: Baz`, ` ) {`, ` console.log(this.foo, bar.value() + baz.otherValue());`, ` }`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, `import { Bar } from 'bar';`, `import { Baz } from './baz';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ` readonly bar = inject(Bar);`, ` readonly baz = inject(Baz);`, ``, ` constructor() {`, ` const bar = this.bar;`, ` const baz = this.baz;`, ``, ` console.log(this.foo, bar.value() + baz.otherValue());`, ` }`, `}`, ]); }); it('should handle multi-line constructor parameters with a trailing comma', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, `import { Bar } from 'bar';`, ``, `@Directive()`, `class MyDir {`, ` constructor(`, ` private foo: Foo,`, ` readonly bar: Bar,`, ` ) {`, ` console.log(this.foo, bar.value());`, ` }`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, `import { Bar } from 'bar';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ` readonly bar = inject(Bar);`, ``, ` constructor() {`, ` const bar = this.bar;`, ``, ` console.log(this.foo, bar.value());`, ` }`, `}`, ]); }); it('should insert the new class members before any pre-existing ones', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private hello = 1;`, ` readonly goodbye = 0;`, ``, ` constructor(private foo: Foo) {}`, ``, ` log() {`, ` console.log(this.foo, this.hello, this.goodbye);`, ` }`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ``, ` private hello = 1;`, ` readonly goodbye = 0;`, ``, ` log() {`, ` console.log(this.foo, this.hello, this.goodbye);`, ` }`, `}`, ]); });
{ "end_byte": 22698, "start_byte": 15395, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/inject_migration_spec.ts" }
angular/packages/core/schematics/test/inject_migration_spec.ts_22702_29967
it('should exclude the public modifier from newly-created members', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` constructor(public readonly foo: Foo) {}`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` readonly foo = inject(Foo);`, `}`, ]); }); it('should account for super() calls', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Parent } from './parent';`, `import { A, B, C, D } from './types';`, ``, `@Directive()`, `class MyDir extends Parent {`, ` constructor(`, ` readonly usedInSuperAndDeclared: A,`, ` protected declaredButNotUsedInSuper: B,`, ` usedInSuperUndeclared: C,`, ` usedInConstructorUndeclared: D) {`, ` super(usedInSuperAndDeclared, usedInSuperUndeclared);`, ` console.log(usedInConstructorUndeclared + 1);`, ` }`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Parent } from './parent';`, `import { A, B, C, D } from './types';`, ``, `@Directive()`, `class MyDir extends Parent {`, ` readonly usedInSuperAndDeclared: A;`, ` protected declaredButNotUsedInSuper = inject(B);`, ``, ` constructor() {`, ` const usedInSuperAndDeclared = inject(A);`, ` const usedInSuperUndeclared = inject(C);`, ` const usedInConstructorUndeclared = inject(D);`, ``, ` super(usedInSuperAndDeclared, usedInSuperUndeclared);`, ` this.usedInSuperAndDeclared = usedInSuperAndDeclared;`, ``, ` console.log(usedInConstructorUndeclared + 1);`, ` }`, `}`, ]); }); it('should remove the constructor if it only has a super() call after the migration', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Parent } from './parent';`, `import { SomeService } from './service';`, ``, `@Directive()`, `class MyDir extends Parent {`, ` constructor(private service: SomeService) {`, ` super();`, ` }`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Parent } from './parent';`, `import { SomeService } from './service';`, ``, `@Directive()`, `class MyDir extends Parent {`, ` private service = inject(SomeService);`, `}`, ]); }); it('should be able to opt into generating backwards-compatible constructors for a class with existing members', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private hello = 1;`, ` readonly goodbye = 0;`, ``, ` constructor(private foo: Foo) {}`, ``, ` log() {`, ` console.log(this.foo, this.hello, this.goodbye);`, ` }`, `}`, ].join('\n'), ); await runMigration({backwardsCompatibleConstructors: true}); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ``, ` private hello = 1;`, ` readonly goodbye = 0;`, ``, ` /** Inserted by Angular inject() migration for backwards compatibility */`, ` constructor(...args: unknown[]);`, ``, ` constructor() {}`, ``, ` log() {`, ` console.log(this.foo, this.hello, this.goodbye);`, ` }`, `}`, ]); }); it('should be able to opt into generating backwards-compatible constructors for a class that only has a constructor', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` constructor(private foo: Foo) {}`, ``, ` log() {`, ` console.log(this.foo, this.hello, this.goodbye);`, ` }`, `}`, ].join('\n'), ); await runMigration({backwardsCompatibleConstructors: true}); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ``, ` /** Inserted by Angular inject() migration for backwards compatibility */`, ` constructor(...args: unknown[]);`, ``, ` constructor() {}`, ``, ` log() {`, ` console.log(this.foo, this.hello, this.goodbye);`, ` }`, `}`, ]); }); it('should not remove the constructor, even if it only has a super call, if backwards compatible constructors are enabled', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Parent } from './parent';`, `import { SomeService } from './service';`, ``, `@Directive()`, `class MyDir extends Parent {`, ` constructor(private service: SomeService) {`, ` super();`, ` }`, `}`, ].join('\n'), ); await runMigration({backwardsCompatibleConstructors: true}); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Parent } from './parent';`, `import { SomeService } from './service';`, ``, `@Directive()`, `class MyDir extends Parent {`, ` private service = inject(SomeService);`, ``, ` /** Inserted by Angular inject() migration for backwards compatibility */`, ` constructor(...args: unknown[]);`, ``, ` constructor() {`, ` super();`, ` }`, `}`, ]); }); it('should not migrate abstract classes by default', async () => { const initialContent = [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `abstract class MyDir {`, ` constructor(private foo: Foo) {}`, `}`, ].join('\n'); writeFile('/dir.ts', initialContent); await runMigration(); expect(tree.readContent('/dir.ts')).toBe(initialContent); });
{ "end_byte": 29967, "start_byte": 22702, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/inject_migration_spec.ts" }
angular/packages/core/schematics/test/inject_migration_spec.ts_29971_37568
it('should be able to opt into migrating abstract classes', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `abstract class MyDir {`, ` constructor(readonly foo: Foo) {}`, `}`, ].join('\n'), ); await runMigration({migrateAbstractClasses: true}); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `abstract class MyDir {`, ` readonly foo = inject(Foo);`, `}`, ]); }); it('should migrate a file that uses tabs for indentation', async () => { // Note: these strings specifically use tabs for indentation. // It might not be visible depending on the IDE settings. writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, `import { Bar } from './bar';`, ``, `@Directive()`, `class MyDir {`, ` private hello = 1;`, ``, ` constructor(`, ` protected foo: Foo,`, ` bar: Bar,`, ` ) {`, ` console.log(this.foo, bar);`, ` }`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, `import { Bar } from './bar';`, ``, `@Directive()`, `class MyDir {`, ` protected foo = inject(Foo);`, ``, ` private hello = 1;`, ``, ` constructor() {`, ` const bar = inject(Bar);`, ``, ` console.log(this.foo, bar);`, ` }`, `}`, ]); }); it('should migrate a file that uses CRLF line endings', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, `import { Bar } from './bar';`, ``, `@Directive()`, `class MyDir {`, ` constructor(private foo: Foo, bar: Bar) {`, ` console.log(this.foo, bar);`, ` }`, `}`, ].join('\r\n'), ); await runMigration(); // We also split on `\n`, because the code we insert always uses `\n`. expect(tree.readContent('/dir.ts').split(/\r\n|\n/g)).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, `import { Bar } from './bar';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ``, ` constructor() {`, ` const bar = inject(Bar);`, ``, ` console.log(this.foo, bar);`, ` }`, `}`, ]); }); it('should allow users to opt into generating non-nullable optional calls', async () => { writeFile( '/dir.ts', [ `import { Directive, Optional } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` constructor(@Optional() private foo: Foo) {}`, `}`, ].join('\n'), ); await runMigration({nonNullableOptional: true}); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo, { optional: true })!;`, `}`, ]); }); it('should not add non-null assertions around sites that were nullable before the migration', async () => { writeFile( '/dir.ts', [ `import { Directive, Inject, Optional } from '@angular/core';`, `import { A, B, C, D, E, F, G, H } from './types';`, ``, `@Directive()`, `class MyDir {`, ` constructor(`, ` @Optional() private a?: A,`, ` @Inject(B) @Optional() readonly b: number | null,`, ` @Inject(C) @Optional() protected c: number | undefined`, ` @Inject(D) @Optional() public d: null`, ` @Inject(E) @Optional() private e: string | null | number`, ` @Inject(F) @Optional() readonly f: string | number | undefined`, ` @Inject(G) @Optional() protected g: undefined`, ` @Inject(H) @Optional() public h: number | void`, ` ) {}`, `}`, ].join('\n'), ); await runMigration({nonNullableOptional: true}); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { A, B, C, D, E, F, G, H } from './types';`, ``, `@Directive()`, `class MyDir {`, ` private a = inject(A, { optional: true });`, ` readonly b = inject(B, { optional: true });`, ` protected c = inject(C, { optional: true });`, ` d = inject(D, { optional: true });`, ` private e = inject(E, { optional: true });`, ` readonly f = inject(F, { optional: true });`, ` protected g = inject(G, { optional: true });`, ` h = inject(H, { optional: true });`, `}`, ]); }); it('should pick up the first non-literal type if a parameter has a union type', async () => { writeFile( '/dir.ts', [ `import { Directive, Optional } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` constructor(@Optional() private foo: null | Foo) {}`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo, { optional: true });`, `}`, ]); }); it('should unwrap forwardRef with an implicit return', async () => { writeFile( '/dir.ts', [ `import { Directive, Inject, forwardRef } from '@angular/core';`, ``, `@Directive()`, `class MyDir {`, ` constructor(@Inject(forwardRef(() => Foo)) readonly foo: Foo) {}`, `}`, ``, `@Directive()`, `class Foo {}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, ``, `@Directive()`, `class MyDir {`, ` readonly foo = inject(Foo);`, `}`, ``, `@Directive()`, `class Foo {}`, ]); }); it('should unwrap forwardRef with an explicit return', async () => { writeFile( '/dir.ts', [ `import { Directive, Inject, forwardRef } from '@angular/core';`, ``, `@Directive()`, `class MyDir {`, ` constructor(@Inject(forwardRef(() => {`, ` return Foo;`, ` })) readonly foo: Foo) {}`, `}`, ``, `@Directive()`, `class Foo {}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, ``, `@Directive()`, `class MyDir {`, ` readonly foo = inject(Foo);`, `}`, ``, `@Directive()`, `class Foo {}`, ]); });
{ "end_byte": 37568, "start_byte": 29971, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/inject_migration_spec.ts" }
angular/packages/core/schematics/test/inject_migration_spec.ts_37572_41727
it('should unwrap an aliased forwardRef', async () => { writeFile( '/dir.ts', [ `import { Directive, Inject, forwardRef as aliasedForwardRef } from '@angular/core';`, ``, `@Directive()`, `class MyDir {`, ` constructor(@Inject(aliasedForwardRef(() => Foo)) readonly foo: Foo) {}`, `}`, ``, `@Directive()`, `class Foo {}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, ``, `@Directive()`, `class MyDir {`, ` readonly foo = inject(Foo);`, `}`, ``, `@Directive()`, `class Foo {}`, ]); }); it('should preserve the forwardRef import if it is used outside of the constructor', async () => { writeFile( '/dir.ts', [ `import { Directive, Inject, forwardRef } from '@angular/core';`, ``, `@Directive({`, ` providers: [`, ` {provide: forwardRef(() => MyDir), useClass: MyDir}`, ` ]`, `})`, `class MyDir {`, ` constructor(@Inject(forwardRef(() => MyDir)) readonly foo: MyDir) {}`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, forwardRef, inject } from '@angular/core';`, ``, `@Directive({`, ` providers: [`, ` {provide: forwardRef(() => MyDir), useClass: MyDir}`, ` ]`, `})`, `class MyDir {`, ` readonly foo = inject(MyDir);`, `}`, ]); }); it('should mark optional members if they correspond to optional parameters', async () => { writeFile( '/dir.ts', [ `import { Directive, Optional } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` constructor(@Optional() public foo?: Foo) {}`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` foo? = inject(Foo, { optional: true });`, `}`, ]); }); it('should not mark private members as optional', async () => { writeFile( '/dir.ts', [ `import { Directive, Optional } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` constructor(@Optional() private foo?: Foo) {}`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo, { optional: true });`, `}`, ]); }); it('should insert generated variables on top of statements that appear before the `super` call', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Parent } from './parent';`, `import { SomeService } from './service';`, ``, `@Directive()`, `class MyDir extends Parent {`, ` constructor(service: SomeService) {`, ` console.log(service.getId());`, ` super(service);`, ` }`, `}`, ].join('\n'), ); await runMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Parent } from './parent';`, `import { SomeService } from './service';`, ``, `@Directive()`, `class MyDir extends Parent {`, ` constructor() {`, ` const service = inject(SomeService);`, ``, ` console.log(service.getId());`, ` super(service);`, ` }`, `}`, ]); });
{ "end_byte": 41727, "start_byte": 37572, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/inject_migration_spec.ts" }
angular/packages/core/schematics/test/inject_migration_spec.ts_41731_49461
describe('internal-only behavior', () => { function runInternalMigration() { return runMigration({_internalCombineMemberInitializers: true}); } it('should inline initializers that depend on DI', async () => { writeFile( '/dir.ts', [ `import { Directive, Inject } from '@angular/core';`, `import { Foo } from 'foo';`, `import { BAR_TOKEN, Bar } from './bar';`, ``, `@Directive()`, `class MyDir {`, ` private value: number;`, ` private otherValue: string;`, ``, ` constructor(private foo: Foo, @Inject(BAR_TOKEN) readonly bar: Bar) {`, ` this.value = this.foo.getValue();`, ` this.otherValue = this.bar.getOtherValue();`, ` }`, `}`, ].join('\n'), ); await runInternalMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, `import { BAR_TOKEN, Bar } from './bar';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ` readonly bar = inject<Bar>(BAR_TOKEN);`, ``, ` private value: number = this.foo.getValue();`, ` private otherValue: string = this.bar.getOtherValue();`, `}`, ]); }); it('should not inline initializers that access injected parameters without `this`', async () => { writeFile( '/dir.ts', [ `import { Directive, Inject } from '@angular/core';`, `import { Foo } from 'foo';`, `import { BAR_TOKEN, Bar } from './bar';`, ``, `@Directive()`, `class MyDir {`, ` private value: number;`, ` private otherValue: string;`, ``, ` constructor(private foo: Foo, @Inject(BAR_TOKEN) readonly bar: Bar) {`, ` this.value = this.foo.getValue();`, ` this.otherValue = bar.getOtherValue();`, ` }`, `}`, ].join('\n'), ); await runInternalMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, `import { BAR_TOKEN, Bar } from './bar';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ` readonly bar = inject<Bar>(BAR_TOKEN);`, ``, ` private value: number = this.foo.getValue();`, ` private otherValue: string;`, ``, ` constructor() {`, ` const bar = this.bar;`, ``, ` this.otherValue = bar.getOtherValue();`, ` }`, `}`, ]); }); it('should not inline initializers that depend on local symbols from the constructor', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private value: number;`, ``, ` constructor(private foo: Foo) {`, ` const val = 456;`, ` this.value = this.foo.getValue([123, [val]]);`, ` }`, `}`, ].join('\n'), ); await runInternalMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ``, ` private value: number;`, ``, ` constructor() {`, ` const val = 456;`, ` this.value = this.foo.getValue([123, [val]]);`, ` }`, `}`, ]); }); it('should inline initializers that depend on local symbols defined outside of the constructor', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `const val = 456;`, ``, `@Directive()`, `class MyDir {`, ` private value: number;`, ``, ` constructor(private foo: Foo) {`, ` this.value = this.getValue(this.foo, extra);`, ` }`, ``, ` private getValue(foo: Foo, extra: number) {`, ` return foo.getValue([123, [extra]]);`, ` }`, `}`, ].join('\n'), ); await runInternalMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `const val = 456;`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ``, ` private value: number = this.getValue(this.foo, extra);`, ``, ` private getValue(foo: Foo, extra: number) {`, ` return foo.getValue([123, [extra]]);`, ` }`, `}`, ]); }); it('should inline initializers defined through an element access', async () => { writeFile( '/dir.ts', [ `import { Directive, Inject } from '@angular/core';`, `import { Foo } from 'foo';`, `import { BAR_TOKEN, Bar } from './bar';`, ``, `@Directive()`, `class MyDir {`, ` private 'my-value': number;`, ` private 'my-other-value': string;`, ``, ` constructor(private foo: Foo, @Inject(BAR_TOKEN) readonly bar: Bar) {`, ` this['my-value'] = this.foo.getValue();`, ` this['my-other-value'] = this.bar.getOtherValue();`, ` }`, `}`, ].join('\n'), ); await runInternalMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, `import { BAR_TOKEN, Bar } from './bar';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ` readonly bar = inject<Bar>(BAR_TOKEN);`, ``, ` private 'my-value': number = this.foo.getValue();`, ` private 'my-other-value': string = this.bar.getOtherValue();`, `}`, ]); }); it('should take the first initializer for properties initialized multiple times', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private value: number;`, ``, ` constructor(private foo: Foo) {`, ` this.value = this.foo.getValue();`, ``, ` this.value = this.foo.getOtherValue();`, ` }`, `}`, ].join('\n'), ); await runInternalMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ``, ` private value: number = this.foo.getValue();`, ``, ` constructor() {`, ``, ` this.value = this.foo.getOtherValue();`, ` }`, `}`, ]); });
{ "end_byte": 49461, "start_byte": 41731, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/inject_migration_spec.ts" }
angular/packages/core/schematics/test/inject_migration_spec.ts_49467_56576
it('should not inline initializers that are not at the top level', async () => { writeFile( '/dir.ts', [ `import { Directive, Optional } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private value: number;`, ``, ` constructor(@Optional() private foo: Foo | null) {`, ` if (this.foo) {`, ` this.value = this.foo.getValue();`, ` }`, ` }`, `}`, ].join('\n'), ); await runInternalMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo, { optional: true });`, ``, ` private value: number;`, ``, ` constructor() {`, ` if (this.foo) {`, ` this.value = this.foo.getValue();`, ` }`, ` }`, `}`, ]); }); it('should inline initializers that have expressions using local parameters', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private ids: number[];`, ` private names: string[];`, ``, ` constructor(private foo: Foo) {`, ` this.ids = this.foo.getValue().map(val => val.id);`, ` this.names = this.foo.getValue().map(function(current) { return current.name; });`, ` }`, `}`, ].join('\n'), ); await runInternalMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ``, ` private ids: number[] = this.foo.getValue().map(val => val.id);`, ` private names: string[] = this.foo.getValue().map(function (current) { return current.name; });`, `}`, ]); }); it('should inline initializers that have expressions using local variables', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private ids: number[];`, ` private names: string[];`, ``, ` constructor(private foo: Foo) {`, ` this.ids = this.foo.getValue().map(val => {`, ` const id = val.id;`, ` return id;`, ` });`, ` this.names = this.foo.getValue().map(function(current) {`, ` const name = current.name;`, ` return name;`, ` });`, ` }`, `}`, ].join('\n'), ); await runInternalMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ``, // The indentation of the closing braces here is slightly off, // but it's not a problem because this code is internal-only. ` private ids: number[] = this.foo.getValue().map(val => {`, ` const id = val.id;`, ` return id;`, `});`, ` private names: string[] = this.foo.getValue().map(function (current) {`, ` const name = current.name;`, ` return name;`, `});`, `}`, ]); }); it('should account for doc strings when inlining initializers', async () => { writeFile( '/dir.ts', [ `import { Directive } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` /** Value of Foo */`, ` private readonly value: number;`, ``, ` /** ID of Foo */`, ` id: string;`, ``, ` constructor(private foo: Foo) {`, ` this.value = this.foo.getValue();`, ` this.id = this.foo.getId();`, ` }`, `}`, ].join('\n'), ); await runInternalMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, inject } from '@angular/core';`, `import { Foo } from 'foo';`, ``, `@Directive()`, `class MyDir {`, ` private foo = inject(Foo);`, ``, ` /** Value of Foo */`, ` private readonly value: number = this.foo.getValue();`, ``, ` /** ID of Foo */`, ` id: string = this.foo.getId();`, `}`, ]); }); it('should hoist property declarations that were not combined above the inject() calls', async () => { writeFile( '/dir.ts', [ `import { Injectable } from '@angular/core';`, `import { Observable } from 'rxjs';`, `import { StateService, State } from './state';`, ``, `@Injectable()`, `export class SomeService {`, ` /** Public state */`, ` readonly state: Observable<State>;`, ``, ` /** Private state */`, ` private internalState?: State;`, ``, ` constructor(readonly stateService: StateService) {`, ` this.initializeInternalState();`, ` this.state = this.internalState;`, ` }`, ``, ` private initializeInternalState() {`, ` this.internalState = new State();`, ` }`, `}`, ].join('\n'), ); await runInternalMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Injectable, inject } from '@angular/core';`, `import { Observable } from 'rxjs';`, `import { StateService, State } from './state';`, ``, `@Injectable()`, `export class SomeService {`, ` /** Private state */`, // The indentation here is slightly off, but it's not a problem because this code is internal-only. `private internalState?: State;`, ``, ` readonly stateService = inject(StateService);`, ``, ` /** Public state */`, ` readonly state: Observable<State> = this.internalState;`, ``, ` constructor() {`, ` this.initializeInternalState();`, ` }`, ``, ` private initializeInternalState() {`, ` this.internalState = new State();`, ` }`, `}`, ]); });
{ "end_byte": 56576, "start_byte": 49467, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/inject_migration_spec.ts" }
angular/packages/core/schematics/test/inject_migration_spec.ts_56582_59312
it('should be able to insert statements after the `super` call when running in internal migration mode', async () => { writeFile( '/dir.ts', [ `import { Directive, Inject, ElementRef } from '@angular/core';`, `import { Foo } from 'foo';`, `import { Parent } from './parent';`, ``, `@Directive()`, `class MyDir extends Parent {`, ` private value: number;`, ``, ` constructor(private foo: Foo, readonly elementRef: ElementRef) {`, ` super();`, ` this.value = this.foo.getValue();`, ` console.log(elementRef.nativeElement.tagName);`, ` }`, `}`, ].join('\n'), ); await runInternalMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Directive, ElementRef, inject } from '@angular/core';`, `import { Foo } from 'foo';`, `import { Parent } from './parent';`, ``, `@Directive()`, `class MyDir extends Parent {`, ` private foo = inject(Foo);`, ` readonly elementRef = inject(ElementRef);`, ``, ` private value: number = this.foo.getValue();`, ``, ` constructor() {`, ` super();`, ` const elementRef = this.elementRef;`, ``, ` console.log(elementRef.nativeElement.tagName);`, ` }`, `}`, ]); }); it('should not inline properties initialized to identifiers referring to constructor parameters', async () => { writeFile( '/dir.ts', [ `import { Injectable } from '@angular/core';`, `import { OtherService } from './other-service';`, ``, `@Injectable()`, `export class SomeService {`, ` readonly otherService: OtherService;`, ``, ` constructor(readonly differentName: OtherService) {`, ` this.otherService = differentName;`, ` }`, `}`, ].join('\n'), ); await runInternalMigration(); expect(tree.readContent('/dir.ts').split('\n')).toEqual([ `import { Injectable, inject } from '@angular/core';`, `import { OtherService } from './other-service';`, ``, `@Injectable()`, `export class SomeService {`, ` readonly differentName = inject(OtherService);`, ``, ` readonly otherService: OtherService;`, ``, ` constructor() {`, ` const differentName = this.differentName;`, ``, ` this.otherService = differentName;`, ` }`, `}`, ]); }); }); });
{ "end_byte": 59312, "start_byte": 56582, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/inject_migration_spec.ts" }
angular/packages/core/schematics/test/signals_migration_spec.ts_0_3704
/** * @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 {getSystemPath, normalize, virtualFs} from '@angular-devkit/core'; import {TempScopedNodeJsSyncHost} from '@angular-devkit/core/node/testing'; import {HostTree} from '@angular-devkit/schematics'; import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing'; import {runfiles} from '@bazel/runfiles'; import shx from 'shelljs'; describe('combined signals migration', () => { let runner: SchematicTestRunner; let host: TempScopedNodeJsSyncHost; let tree: UnitTestTree; let tmpDirPath: string; let previousWorkingDir: string; function writeFile(filePath: string, contents: string) { host.sync.write(normalize(filePath), virtualFs.stringToFileBuffer(contents)); } function runMigration(migrations: string[]) { return runner.runSchematic('signals', {migrations}, tree); } function stripWhitespace(value: string) { return value.replace(/\s/g, ''); } beforeEach(() => { runner = new SchematicTestRunner('test', runfiles.resolvePackageRelative('../collection.json')); host = new TempScopedNodeJsSyncHost(); tree = new UnitTestTree(new HostTree(host)); writeFile('/tsconfig.json', '{}'); writeFile( '/angular.json', JSON.stringify({ version: 1, projects: {t: {root: '', architect: {build: {options: {tsConfig: './tsconfig.json'}}}}}, }), ); previousWorkingDir = shx.pwd(); tmpDirPath = getSystemPath(host.root); shx.cd(tmpDirPath); }); afterEach(() => { shx.cd(previousWorkingDir); shx.rm('-r', tmpDirPath); }); it('should be able to run multiple migrations at the same time', async () => { writeFile( '/index.ts', ` import {ContentChild, Input, ElementRef, Output, Component, EventEmitter} from '@angular/core'; @Component({ template: 'The value is {{value}}', }) export class SomeComponent { @ContentChild('ref') ref!: ElementRef; @Input('alias') value: string = 'initial'; @Output() clicked = new EventEmitter<void>(); }`, ); await runMigration(['inputs', 'queries', 'outputs']); expect(stripWhitespace(tree.readContent('/index.ts'))).toBe( stripWhitespace(` import {ElementRef, Component, input, output, contentChild} from '@angular/core'; @Component({ template: 'The value is {{value()}}', }) export class SomeComponent { readonly ref = contentChild.required<ElementRef>('ref'); readonly value = input<string>('initial', { alias: "alias" }); readonly clicked = output<void>(); } `), ); }); it('should be able to run only specific migrations', async () => { writeFile( '/index.ts', ` import {ContentChild, Input, ElementRef, Component} from '@angular/core'; @Component({ template: 'The value is {{value}}', }) export class SomeComponent { @ContentChild('ref') ref!: ElementRef; @Input('alias') value: string = 'initial'; }`, ); await runMigration(['queries']); expect(stripWhitespace(tree.readContent('/index.ts'))).toBe( stripWhitespace(` import {Input, ElementRef, Component, contentChild} from '@angular/core'; @Component({ template: 'The value is {{value}}', }) export class SomeComponent { readonly ref = contentChild.required<ElementRef>('ref'); @Input('alias') value: string = 'initial'; } `), ); }); });
{ "end_byte": 3704, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/signals_migration_spec.ts" }
angular/packages/core/schematics/test/explicit_standalone_flag_spec.ts_0_6176
/** * @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 {getSystemPath, normalize, virtualFs} from '@angular-devkit/core'; import {TempScopedNodeJsSyncHost} from '@angular-devkit/core/node/testing'; import {HostTree} from '@angular-devkit/schematics'; import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing'; import {runfiles} from '@bazel/runfiles'; import shx from 'shelljs'; describe('explicit-standalone-flag migration', () => { let runner: SchematicTestRunner; let host: TempScopedNodeJsSyncHost; let tree: UnitTestTree; let tmpDirPath: string; let previousWorkingDir: string; function writeFile(filePath: string, contents: string) { host.sync.write(normalize(filePath), virtualFs.stringToFileBuffer(contents)); } function runMigration() { return runner.runSchematic('explicit-standalone-flag', {}, tree); } beforeEach(() => { runner = new SchematicTestRunner('test', runfiles.resolvePackageRelative('../migrations.json')); host = new TempScopedNodeJsSyncHost(); tree = new UnitTestTree(new HostTree(host)); writeFile( '/tsconfig.json', JSON.stringify({ compilerOptions: { lib: ['es2015'], strictNullChecks: true, }, }), ); writeFile( '/angular.json', JSON.stringify({ version: 1, projects: {t: {root: '', architect: {build: {options: {tsConfig: './tsconfig.json'}}}}}, }), ); previousWorkingDir = shx.pwd(); tmpDirPath = getSystemPath(host.root); // Switch into the temporary directory path. This allows us to run // the schematic against our custom unit test tree. shx.cd(tmpDirPath); }); it('should update standalone to false for Directive', async () => { writeFile( '/index.ts', ` import { Directive } from '@angular/core'; @Directive({ selector: '[someDirective]' }) export class SomeDirective { }`, ); await runMigration(); const content = tree.readContent('/index.ts').replace(/\s+/g, ' '); expect(content).toContain('standalone: false'); }); it('should update standalone to false for Component', async () => { writeFile( '/index.ts', ` import { Component } from '@angular/core'; @Component({ selector: '[someComponent]' }) export class SomeComponent { }`, ); await runMigration(); const content = tree.readContent('/index.ts').replace(/\s+/g, ' '); expect(content).toContain('standalone: false'); }); it('should update standalone to false for Pipe', async () => { writeFile( '/index.ts', ` import { Pipe } from '@angular/core'; @Pipe({ name: 'somePipe' }) export class SomePipe { }`, ); await runMigration(); const content = tree.readContent('/index.ts').replace(/\s+/g, ' '); expect(content).toContain('standalone: false'); }); it('should remove standalone:true', async () => { writeFile( '/index.ts', ` import { Directive } from '@angular/core'; @Directive({ selector: '[someDirective]', standalone: true }) export class SomeDirective { }`, ); await runMigration(); const content = tree.readContent('/index.ts').replace(/\s+/g, ' '); expect(content).not.toContain('standalone: true'); }); it('should not update a directive with standalone:false', async () => { writeFile( '/index.ts', ` import { Directive } from '@angular/core'; @Directive({ selector: '[someDirective]', standalone: false }) export class SomeDirective { }`, ); await runMigration(); const content = tree.readContent('/index.ts').replace(/\s+/g, ' '); expect(content).not.toContain('standalone: true'); expect(content).toContain('standalone: false'); }); it('should not update an empty directive', async () => { writeFile( '/index.ts', ` import { Directive } from '@angular/core'; @Directive() export class SomeDirective {}`, ); await runMigration(); const content = tree.readContent('/index.ts').replace(/\s+/g, ' '); expect(content).not.toContain('standalone'); }); it('should not migrate standalone if its a shorthard property assignment', async () => { writeFile( '/index.ts', ` import { Directive } from '@angular/core'; const standalone = true; function directiveFactory(standalone: boolean) { @Directive({ selector: '[someDirective]', standalone, }) export class SomeDirective { } return SomeDirective }`, ); await runMigration(); const content = tree.readContent('/index.ts').replace(/\s+/g, ' '); expect(content).not.toContain('standalone: true'); expect(content).not.toContain('standalone: false'); expect(content).toContain('standalone,'); }); it('should not migrate standalone if the property is assigned by a variable', async () => { writeFile( '/index.ts', ` import { Directive } from '@angular/core'; const isStandalone = true; function directiveFactory(standalone: boolean) { @Directive({ selector: '[someDirective]', standalone: isStandalone, }) export class SomeDirective { } return SomeDirective }`, ); await runMigration(); const content = tree.readContent('/index.ts').replace(/\s+/g, ' '); expect(content).not.toContain('standalone: true'); expect(content).not.toContain('standalone: false'); expect(content).toContain('standalone'); }); });
{ "end_byte": 6176, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/explicit_standalone_flag_spec.ts" }
angular/packages/core/schematics/test/google3/wait_for_async_spec.ts_0_6008
/** * @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 {readFileSync, writeFileSync} from 'fs'; import {dirname, join} from 'path'; import shx from 'shelljs'; import {Configuration, Linter} from 'tslint'; describe('Google3 waitForAsync TSLint rule', () => { const rulesDirectory = dirname( runfiles.resolvePackageRelative('../../migrations/google3/waitForAsyncCjsRule.js'), ); let tmpDir: string; beforeEach(() => { tmpDir = join(process.env['TEST_TMPDIR']!, 'google3-test'); shx.mkdir('-p', tmpDir); // We need to declare the Angular symbols we're testing for, otherwise type checking won't work. writeFile( 'testing.d.ts', ` export declare function async(fn: Function): any; `, ); writeFile( 'tsconfig.json', JSON.stringify({ compilerOptions: { module: 'es2015', baseUrl: './', paths: { '@angular/core/testing': ['testing.d.ts'], }, }, }), ); }); afterEach(() => shx.rm('-r', tmpDir)); function runTSLint(fix: boolean) { const program = Linter.createProgram(join(tmpDir, 'tsconfig.json')); const linter = new Linter({fix, rulesDirectory: [rulesDirectory]}, program); const config = Configuration.parseConfigFile({rules: {'wait-for-async-cjs': true}}); program.getRootFileNames().forEach((fileName) => { linter.lint(fileName, program.getSourceFile(fileName)!.getFullText(), config); }); return linter; } function writeFile(fileName: string, content: string) { writeFileSync(join(tmpDir, fileName), content); } function getFile(fileName: string) { return readFileSync(join(tmpDir, fileName), 'utf8'); } it('should flag async imports and usages', () => { writeFile( '/index.ts', ` import { async, inject } from '@angular/core/testing'; it('should work', async(() => { expect(inject('foo')).toBe('foo'); })); it('should also work', async(() => { expect(inject('bar')).toBe('bar'); })); `, ); const linter = runTSLint(false); const failures = linter.getResult().failures.map((failure) => failure.getFailure()); expect(failures.length).toBe(3); expect(failures[0]).toMatch(/Imports of the deprecated async function are not allowed/); expect(failures[1]).toMatch(/References to the deprecated async function are not allowed/); expect(failures[2]).toMatch(/References to the deprecated async function are not allowed/); }); it('should change async imports to waitForAsync', () => { writeFile( '/index.ts', ` import { async, inject } from '@angular/core/testing'; it('should work', async(() => { expect(inject('foo')).toBe('foo'); })); `, ); runTSLint(true); expect(getFile('/index.ts')).toContain( `import { inject, waitForAsync } from '@angular/core/testing';`, ); }); it('should change aliased async imports to waitForAsync', () => { writeFile( '/index.ts', ` import { async as renamedAsync, inject } from '@angular/core/testing'; it('should work', renamedAsync(() => { expect(inject('foo')).toBe('foo'); })); `, ); runTSLint(true); expect(getFile('/index.ts')).toContain( `import { inject, waitForAsync as renamedAsync } from '@angular/core/testing';`, ); }); it('should not change async imports if they are not from @angular/core/testing', () => { writeFile( '/index.ts', ` import { inject } from '@angular/core/testing'; import { async } from './my-test-library'; it('should work', async(() => { expect(inject('foo')).toBe('foo'); })); `, ); runTSLint(true); const content = getFile('/index.ts'); expect(content).toContain(`import { inject } from '@angular/core/testing';`); expect(content).toContain(`import { async } from './my-test-library';`); }); it('should not change imports if waitForAsync was already imported', () => { writeFile( '/index.ts', ` import { async, inject, waitForAsync } from '@angular/core/testing'; it('should work', async(() => { expect(inject('foo')).toBe('foo'); })); it('should also work', waitForAsync(() => { expect(inject('bar')).toBe('bar'); })); `, ); runTSLint(true); expect(getFile('/index.ts')).toContain( `import { async, inject, waitForAsync } from '@angular/core/testing';`, ); }); it('should change calls from `async` to `waitForAsync`', () => { writeFile( '/index.ts', ` import { async, inject } from '@angular/core/testing'; it('should work', async(() => { expect(inject('foo')).toBe('foo'); })); it('should also work', async(() => { expect(inject('bar')).toBe('bar'); })); `, ); runTSLint(true); const content = getFile('/index.ts'); expect(content).toContain(`import { inject, waitForAsync } from '@angular/core/testing';`); expect(content).toContain(`it('should work', waitForAsync(() => {`); expect(content).toContain(`it('should also work', waitForAsync(() => {`); }); it('should not change aliased calls', () => { writeFile( '/index.ts', ` import { async as renamedAsync, inject } from '@angular/core/testing'; it('should work', renamedAsync(() => { expect(inject('foo')).toBe('foo'); })); `, ); runTSLint(true); const content = getFile('/index.ts'); expect(content).toContain( `import { inject, waitForAsync as renamedAsync } from '@angular/core/testing';`, ); expect(content).toContain(`it('should work', renamedAsync(() => {`); }); });
{ "end_byte": 6008, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/google3/wait_for_async_spec.ts" }
angular/packages/core/schematics/test/google3/BUILD.bazel_0_508
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = glob(["**/*.ts"]), deps = [ "@npm//@bazel/runfiles", "@npm//@types/shelljs", "@npm//tslint", ], ) jasmine_node_test( name = "google3", data = [ "//packages/core/schematics/migrations/google3:google3_cjs", ], templated_args = ["--nobazel_run_linker"], deps = [ ":test_lib", "@npm//shelljs", ], )
{ "end_byte": 508, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/google3/BUILD.bazel" }
angular/packages/core/schematics/utils/template_ast_visitor.ts_0_4136
/** * @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 type { TmplAstBoundAttribute, TmplAstBoundEvent, TmplAstBoundText, TmplAstContent, TmplAstDeferredBlock, TmplAstDeferredBlockError, TmplAstDeferredBlockLoading, TmplAstDeferredBlockPlaceholder, TmplAstDeferredTrigger, TmplAstElement, TmplAstIfBlockBranch, TmplAstForLoopBlock, TmplAstForLoopBlockEmpty, TmplAstIcu, TmplAstIfBlock, TmplAstNode, TmplAstRecursiveVisitor, TmplAstReference, TmplAstSwitchBlock, TmplAstSwitchBlockCase, TmplAstTemplate, TmplAstText, TmplAstTextAttribute, TmplAstVariable, TmplAstUnknownBlock, TmplAstLetDeclaration, } from '@angular/compiler'; /** * A base class that can be used to implement a Render3 Template AST visitor. * Schematics are also currently required to be CommonJS to support execution within the Angular * CLI. As a result, the ESM `@angular/compiler` package must be loaded via a native dynamic import. * Using a dynamic import makes classes extending from classes present in `@angular/compiler` * complicated due to the class not being present at module evaluation time. The classes using a * base class found within `@angular/compiler` must be wrapped in a factory to allow the class value * to be accessible at runtime after the dynamic import has completed. This class implements the * interface of the `TmplAstRecursiveVisitor` class (but does not extend) as the * `TmplAstRecursiveVisitor` as an interface provides the required set of visit methods. The base * interface `Visitor<T>` is not exported. */ export class TemplateAstVisitor implements TmplAstRecursiveVisitor { /** * Creates a new Render3 Template AST visitor using an instance of the `@angular/compiler` * package. Passing in the compiler is required due to the need to dynamically import the * ESM `@angular/compiler` into a CommonJS schematic. * * @param compilerModule The compiler instance that should be used within the visitor. */ constructor(protected readonly compilerModule: typeof import('@angular/compiler')) {} visitElement(element: TmplAstElement): void {} visitTemplate(template: TmplAstTemplate): void {} visitContent(content: TmplAstContent): void {} visitVariable(variable: TmplAstVariable): void {} visitReference(reference: TmplAstReference): void {} visitTextAttribute(attribute: TmplAstTextAttribute): void {} visitBoundAttribute(attribute: TmplAstBoundAttribute): void {} visitBoundEvent(attribute: TmplAstBoundEvent): void {} visitText(text: TmplAstText): void {} visitBoundText(text: TmplAstBoundText): void {} visitIcu(icu: TmplAstIcu): void {} visitDeferredBlock(deferred: TmplAstDeferredBlock): void {} visitDeferredBlockPlaceholder(block: TmplAstDeferredBlockPlaceholder): void {} visitDeferredBlockError(block: TmplAstDeferredBlockError): void {} visitDeferredBlockLoading(block: TmplAstDeferredBlockLoading): void {} visitDeferredTrigger(trigger: TmplAstDeferredTrigger): void {} visitUnknownBlock(block: TmplAstUnknownBlock): void {} visitSwitchBlock(block: TmplAstSwitchBlock): void {} visitSwitchBlockCase(block: TmplAstSwitchBlockCase): void {} visitForLoopBlock(block: TmplAstForLoopBlock): void {} visitForLoopBlockEmpty(block: TmplAstForLoopBlockEmpty): void {} visitIfBlock(block: TmplAstIfBlock): void {} visitIfBlockBranch(block: TmplAstIfBlockBranch): void {} visitLetDeclaration(decl: TmplAstLetDeclaration): void {} /** * Visits all the provided nodes in order using this Visitor's visit methods. * This is a simplified variant of the `visitAll` function found inside of (but not * exported from) the `@angular/compiler` that does not support returning a value * since the migrations do not directly transform the nodes. * * @param nodes An iterable of nodes to visit using this visitor. */ visitAll(nodes: Iterable<TmplAstNode>): void { for (const node of nodes) { node.visit(this); } } }
{ "end_byte": 4136, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/template_ast_visitor.ts" }
angular/packages/core/schematics/utils/change_tracker.ts_0_8407
/** * @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 {ImportManager} from '@angular/compiler-cli/private/migrations'; /** Function that can be used to remap a generated import. */ export type ImportRemapper = (moduleName: string, inFile: string) => string; /** Mapping between a source file and the changes that have to be applied to it. */ export type ChangesByFile = ReadonlyMap<ts.SourceFile, PendingChange[]>; /** Change that needs to be applied to a file. */ export interface PendingChange { /** Index at which to start changing the file. */ start: number; /** * Amount of text that should be removed after the `start`. * No text will be removed if omitted. */ removeLength?: number; /** New text that should be inserted. */ text: string; } /** Supported quotes for generated imports. */ const enum QuoteKind { SINGLE, DOUBLE, } /** Tracks changes that have to be made for specific files. */ export class ChangeTracker { private readonly _changes = new Map<ts.SourceFile, PendingChange[]>(); private readonly _importManager: ImportManager; private readonly _quotesCache = new WeakMap<ts.SourceFile, QuoteKind>(); constructor( private _printer: ts.Printer, private _importRemapper?: ImportRemapper, ) { this._importManager = new ImportManager({ shouldUseSingleQuotes: (file) => this._getQuoteKind(file) === QuoteKind.SINGLE, }); } /** * Tracks the insertion of some text. * @param sourceFile File in which the text is being inserted. * @param start Index at which the text is insert. * @param text Text to be inserted. */ insertText(sourceFile: ts.SourceFile, index: number, text: string): void { this._trackChange(sourceFile, {start: index, text}); } /** * Replaces text within a file. * @param sourceFile File in which to replace the text. * @param start Index from which to replace the text. * @param removeLength Length of the text being replaced. * @param text Text to be inserted instead of the old one. */ replaceText(sourceFile: ts.SourceFile, start: number, removeLength: number, text: string): void { this._trackChange(sourceFile, {start, removeLength, text}); } /** * Replaces the text of an AST node with a new one. * @param oldNode Node to be replaced. * @param newNode New node to be inserted. * @param emitHint Hint when formatting the text of the new node. * @param sourceFileWhenPrinting File to use when printing out the new node. This is important * when copying nodes from one file to another, because TypeScript might not output literal nodes * without it. */ replaceNode( oldNode: ts.Node, newNode: ts.Node, emitHint = ts.EmitHint.Unspecified, sourceFileWhenPrinting?: ts.SourceFile, ): void { const sourceFile = oldNode.getSourceFile(); this.replaceText( sourceFile, oldNode.getStart(), oldNode.getWidth(), this._printer.printNode(emitHint, newNode, sourceFileWhenPrinting || sourceFile), ); } /** * Removes the text of an AST node from a file. * @param node Node whose text should be removed. */ removeNode(node: ts.Node): void { this._trackChange(node.getSourceFile(), { start: node.getStart(), removeLength: node.getWidth(), text: '', }); } /** * Adds an import to a file. * @param sourceFile File to which to add the import. * @param symbolName Symbol being imported. * @param moduleName Module from which the symbol is imported. * @param alias Alias to use for the import. */ addImport( sourceFile: ts.SourceFile, symbolName: string, moduleName: string, alias?: string, ): ts.Expression { if (this._importRemapper) { moduleName = this._importRemapper(moduleName, sourceFile.fileName); } // It's common for paths to be manipulated with Node's `path` utilties which // can yield a path with back slashes. Normalize them since outputting such // paths will also cause TS to escape the forward slashes. moduleName = normalizePath(moduleName); if (!this._changes.has(sourceFile)) { this._changes.set(sourceFile, []); } return this._importManager.addImport({ requestedFile: sourceFile, exportSymbolName: symbolName, exportModuleSpecifier: moduleName, unsafeAliasOverride: alias, }); } /** * Removes an import from a file. * @param sourceFile File from which to remove the import. * @param symbolName Original name of the symbol to be removed. Used even if the import is aliased. * @param moduleName Module from which the symbol is imported. */ removeImport(sourceFile: ts.SourceFile, symbolName: string, moduleName: string): void { // It's common for paths to be manipulated with Node's `path` utilties which // can yield a path with back slashes. Normalize them since outputting such // paths will also cause TS to escape the forward slashes. moduleName = normalizePath(moduleName); if (!this._changes.has(sourceFile)) { this._changes.set(sourceFile, []); } this._importManager.removeImport(sourceFile, symbolName, moduleName); } /** * Gets the changes that should be applied to all the files in the migration. * The changes are sorted in the order in which they should be applied. */ recordChanges(): ChangesByFile { this._recordImports(); return this._changes; } /** * Clear the tracked changes */ clearChanges(): void { this._changes.clear(); } /** * Adds a change to a `ChangesByFile` map. * @param file File that the change is associated with. * @param change Change to be added. */ private _trackChange(file: ts.SourceFile, change: PendingChange): void { const changes = this._changes.get(file); if (changes) { // Insert the changes in reverse so that they're applied in reverse order. // This ensures that the offsets of subsequent changes aren't affected by // previous changes changing the file's text. const insertIndex = changes.findIndex((current) => current.start <= change.start); if (insertIndex === -1) { changes.push(change); } else { changes.splice(insertIndex, 0, change); } } else { this._changes.set(file, [change]); } } /** Determines what kind of quotes to use for a specific file. */ private _getQuoteKind(sourceFile: ts.SourceFile): QuoteKind { if (this._quotesCache.has(sourceFile)) { return this._quotesCache.get(sourceFile)!; } let kind = QuoteKind.SINGLE; for (const statement of sourceFile.statements) { if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) { kind = statement.moduleSpecifier.getText()[0] === '"' ? QuoteKind.DOUBLE : QuoteKind.SINGLE; this._quotesCache.set(sourceFile, kind); break; } } return kind; } /** Records the pending import changes from the import manager. */ private _recordImports(): void { const {newImports, updatedImports, deletedImports} = this._importManager.finalize(); for (const [original, replacement] of updatedImports) { this.replaceNode(original, replacement); } for (const node of deletedImports) { this.removeNode(node); } for (const [sourceFile] of this._changes) { const importsToAdd = newImports.get(sourceFile.fileName); if (!importsToAdd) { continue; } const importLines: string[] = []; let lastImport: ts.ImportDeclaration | null = null; for (const statement of sourceFile.statements) { if (ts.isImportDeclaration(statement)) { lastImport = statement; } } for (const decl of importsToAdd) { importLines.push(this._printer.printNode(ts.EmitHint.Unspecified, decl, sourceFile)); } this.insertText( sourceFile, lastImport ? lastImport.getEnd() : 0, (lastImport ? '\n' : '') + importLines.join('\n'), ); } } } /** Normalizes a path to use posix separators. */ export function normalizePath(path: string): string { return path.replace(/\\/g, '/'); }
{ "end_byte": 8407, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/change_tracker.ts" }
angular/packages/core/schematics/utils/line_mappings.ts_0_2030
/** * @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 LF_CHAR = 10; const CR_CHAR = 13; const LINE_SEP_CHAR = 8232; const PARAGRAPH_CHAR = 8233; /** Gets the line and character for the given position from the line starts map. */ export function getLineAndCharacterFromPosition(lineStartsMap: number[], position: number) { const lineIndex = findClosestLineStartPosition(lineStartsMap, position); return {character: position - lineStartsMap[lineIndex], line: lineIndex}; } /** * Computes the line start map of the given text. This can be used in order to * retrieve the line and character of a given text position index. */ export function computeLineStartsMap(text: string): number[] { const result: number[] = [0]; let pos = 0; while (pos < text.length) { const char = text.charCodeAt(pos++); // Handles the "CRLF" line break. In that case we peek the character // after the "CR" and check if it is a line feed. if (char === CR_CHAR) { if (text.charCodeAt(pos) === LF_CHAR) { pos++; } result.push(pos); } else if (char === LF_CHAR || char === LINE_SEP_CHAR || char === PARAGRAPH_CHAR) { result.push(pos); } } result.push(pos); return result; } /** Finds the closest line start for the given position. */ function findClosestLineStartPosition<T>( linesMap: T[], position: T, low = 0, high = linesMap.length - 1, ) { while (low <= high) { const pivotIdx = Math.floor((low + high) / 2); const pivotEl = linesMap[pivotIdx]; if (pivotEl === position) { return pivotIdx; } else if (position > pivotEl) { low = pivotIdx + 1; } else { high = pivotIdx - 1; } } // In case there was no exact match, return the closest "lower" line index. We also // subtract the index by one because want the index of the previous line start. return low - 1; }
{ "end_byte": 2030, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/line_mappings.ts" }
angular/packages/core/schematics/utils/load_esm.ts_0_2380
/** * @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 {URL} from 'url'; /** * This uses a dynamic import to load a module which may be ESM. * CommonJS code can load ESM code via a dynamic import. Unfortunately, TypeScript * will currently, unconditionally downlevel dynamic import into a require call. * require calls cannot load ESM code and will result in a runtime error. To workaround * this, a Function constructor is used to prevent TypeScript from changing the dynamic import. * Once TypeScript provides support for keeping the dynamic import this workaround can * be dropped. * This is only intended to be used with Angular framework packages. * * @param modulePath The path of the module to load. * @returns A Promise that resolves to the dynamically imported module. */ export async function loadEsmModule<T>(modulePath: string | URL): Promise<T> { const namespaceObject = await new Function('modulePath', `return import(modulePath);`)( modulePath, ); // If it is not ESM then the values needed will be stored in the `default` property. // TODO_ESM: This can be removed once `@angular/*` packages are ESM only. if (namespaceObject.default) { return namespaceObject.default; } else { return namespaceObject; } } /** * Attempt to load the new `@angular/compiler-cli/private/migrations` entry. If not yet present * the previous deep imports are used to constructor an equivalent object. * * @returns A Promise that resolves to the dynamically imported compiler-cli private migrations * entry or an equivalent object if not available. */ export async function loadCompilerCliMigrationsModule(): Promise< typeof import('@angular/compiler-cli/private/migrations') > { try { return await loadEsmModule('@angular/compiler-cli/private/migrations'); } catch { // rules_nodejs currently does not support exports field entries. This is a temporary workaround // that leverages devmode currently being CommonJS. If that changes before rules_nodejs supports // exports then this workaround needs to be reworked. // TODO_ESM: This can be removed once Bazel supports exports fields. return require('@angular/compiler-cli/private/migrations.js'); } }
{ "end_byte": 2380, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/load_esm.ts" }
angular/packages/core/schematics/utils/ng_decorators.ts_0_1188
/** * @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 {getCallDecoratorImport} from './typescript/decorators'; export type CallExpressionDecorator = ts.Decorator & { expression: ts.CallExpression; }; export interface NgDecorator { name: string; moduleName: string; node: CallExpressionDecorator; importNode: ts.ImportDeclaration; } /** * Gets all decorators which are imported from an Angular package (e.g. "@angular/core") * from a list of decorators. */ export function getAngularDecorators( typeChecker: ts.TypeChecker, decorators: ReadonlyArray<ts.Decorator>, ): NgDecorator[] { return decorators .map((node) => ({node, importData: getCallDecoratorImport(typeChecker, node)})) .filter(({importData}) => importData && importData.importModule.startsWith('@angular/')) .map(({node, importData}) => ({ node: node as CallExpressionDecorator, name: importData!.name, moduleName: importData!.importModule, importNode: importData!.node, })); }
{ "end_byte": 1188, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/ng_decorators.ts" }
angular/packages/core/schematics/utils/parse_html.ts_0_850
/** * @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 type {TmplAstNode} from '@angular/compiler'; /** * Parses the given HTML content using the Angular compiler. In case the parsing * fails, null is being returned. */ export function parseHtmlGracefully( htmlContent: string, filePath: string, compilerModule: typeof import('@angular/compiler'), ): TmplAstNode[] | null { try { return compilerModule.parseTemplate(htmlContent, filePath).nodes; } catch { // Do nothing if the template couldn't be parsed. We don't want to throw any // exception if a template is syntactically not valid. e.g. template could be // using preprocessor syntax. return null; } }
{ "end_byte": 850, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/parse_html.ts" }
angular/packages/core/schematics/utils/BUILD.bazel_0_465
load("//tools:defaults.bzl", "ts_library") ts_library( name = "utils", srcs = glob(["**/*.ts"]), tsconfig = "//packages/core/schematics:tsconfig.json", visibility = ["//packages/core/schematics:__subpackages__"], deps = [ "//packages/compiler", "//packages/compiler-cli/private", "@npm//@angular-devkit/core", "@npm//@angular-devkit/schematics", "@npm//@types/node", "@npm//typescript", ], )
{ "end_byte": 465, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/BUILD.bazel" }
angular/packages/core/schematics/utils/ng_component_template.ts_0_5306
/** * @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 {Tree} from '@angular-devkit/schematics'; import {dirname, relative, resolve} from 'path'; import ts from 'typescript'; import {extractAngularClassMetadata} from './extract_metadata'; import {computeLineStartsMap, getLineAndCharacterFromPosition} from './line_mappings'; import {getPropertyNameText} from './typescript/property_name'; export interface ResolvedTemplate { /** Class declaration that contains this template. */ container: ts.ClassDeclaration; /** File content of the given template. */ content: string; /** Start offset of the template content (e.g. in the inline source file) */ start: number; /** Whether the given template is inline or not. */ inline: boolean; /** Path to the file that contains this template. */ filePath: string; /** * Gets the character and line of a given position index in the template. * If the template is declared inline within a TypeScript source file, the line and * character are based on the full source file content. */ getCharacterAndLineOfPosition: (pos: number) => { character: number; line: number; }; } /** * Visitor that can be used to determine Angular templates referenced within given * TypeScript source files (inline templates or external referenced templates) */ export class NgComponentTemplateVisitor { resolvedTemplates: ResolvedTemplate[] = []; constructor( public typeChecker: ts.TypeChecker, private _basePath: string, private _tree: Tree, ) {} visitNode(node: ts.Node) { if (node.kind === ts.SyntaxKind.ClassDeclaration) { this.visitClassDeclaration(node as ts.ClassDeclaration); } ts.forEachChild(node, (n) => this.visitNode(n)); } private visitClassDeclaration(node: ts.ClassDeclaration) { const metadata = extractAngularClassMetadata(this.typeChecker, node); if (metadata === null || metadata.type !== 'component') { return; } const sourceFile = node.getSourceFile(); const sourceFileName = sourceFile.fileName; // Walk through all component metadata properties and determine the referenced // HTML templates (either external or inline) metadata.node.properties.forEach((property) => { if (!ts.isPropertyAssignment(property)) { return; } const propertyName = getPropertyNameText(property.name); // In case there is an inline template specified, ensure that the value is statically // analyzable by checking if the initializer is a string literal-like node. if (propertyName === 'template' && ts.isStringLiteralLike(property.initializer)) { // Need to add an offset of one to the start because the template quotes are // not part of the template content. // The `getText()` method gives us the original raw text. // We could have used the `text` property, but if the template is defined as a backtick // string then the `text` property contains a "cooked" version of the string. Such cooked // strings will have converted CRLF characters to only LF. This messes up string // replacements in template migrations. // The raw text returned by `getText()` includes the enclosing quotes so we change the // `content` and `start` values accordingly. const content = property.initializer.getText().slice(1, -1); const start = property.initializer.getStart() + 1; this.resolvedTemplates.push({ filePath: sourceFileName, container: node, content, inline: true, start: start, getCharacterAndLineOfPosition: (pos) => ts.getLineAndCharacterOfPosition(sourceFile, pos + start), }); } if (propertyName === 'templateUrl' && ts.isStringLiteralLike(property.initializer)) { const templateDiskPath = resolve(dirname(sourceFileName), property.initializer.text); // TODO(devversion): Remove this when the TypeScript compiler host is fully virtual // relying on the devkit virtual tree and not dealing with disk paths. This is blocked on // providing common utilities for schematics/migrations, given this is done in the // Angular CDK already: // https://github.com/angular/components/blob/3704400ee67e0190c9783e16367587489c803ebc/src/cdk/schematics/update-tool/utils/virtual-host.ts. const templateDevkitPath = relative(this._basePath, templateDiskPath); // In case the template does not exist in the file system, skip this // external template. if (!this._tree.exists(templateDevkitPath)) { return; } const fileContent = this._tree.read(templateDevkitPath)!.toString(); const lineStartsMap = computeLineStartsMap(fileContent); this.resolvedTemplates.push({ filePath: templateDiskPath, container: node, content: fileContent, inline: false, start: 0, getCharacterAndLineOfPosition: (pos) => getLineAndCharacterFromPosition(lineStartsMap, pos), }); } }); } }
{ "end_byte": 5306, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/ng_component_template.ts" }
angular/packages/core/schematics/utils/project_tsconfig_paths.ts_0_3184
/** * @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 {json, normalize, virtualFs, workspaces} from '@angular-devkit/core'; import {Tree} from '@angular-devkit/schematics'; /** * Gets all tsconfig paths from a CLI project by reading the workspace configuration * and looking for common tsconfig locations. */ export async function getProjectTsConfigPaths( tree: Tree, ): Promise<{buildPaths: string[]; testPaths: string[]}> { // Start with some tsconfig paths that are generally used within CLI projects. Note // that we are not interested in IDE-specific tsconfig files (e.g. /tsconfig.json) const buildPaths = new Set<string>(); const testPaths = new Set<string>(); const workspace = await getWorkspace(tree); for (const [, project] of workspace.projects) { for (const [name, target] of project.targets) { if (name !== 'build' && name !== 'test') { continue; } for (const [, options] of allTargetOptions(target)) { const tsConfig = options['tsConfig']; // Filter out tsconfig files that don't exist in the CLI project. if (typeof tsConfig !== 'string' || !tree.exists(tsConfig)) { continue; } if (name === 'build') { buildPaths.add(normalize(tsConfig)); } else { testPaths.add(normalize(tsConfig)); } } } } return { buildPaths: [...buildPaths], testPaths: [...testPaths], }; } /** Get options for all configurations for the passed builder target. */ function* allTargetOptions( target: workspaces.TargetDefinition, ): Iterable<[string | undefined, Record<string, json.JsonValue | undefined>]> { if (target.options) { yield [undefined, target.options]; } if (!target.configurations) { return; } for (const [name, options] of Object.entries(target.configurations)) { if (options) { yield [name, options]; } } } function createHost(tree: Tree): workspaces.WorkspaceHost { return { async readFile(path: string): Promise<string> { const data = tree.read(path); if (!data) { throw new Error('File not found.'); } return virtualFs.fileBufferToString(data); }, async writeFile(path: string, data: string): Promise<void> { return tree.overwrite(path, data); }, async isDirectory(path: string): Promise<boolean> { // Approximate a directory check. // We don't need to consider empty directories and hence this is a good enough approach. // This is also per documentation, see: // https://angular.dev/tools/cli/schematics-for-libraries#get-the-project-configuration return !tree.exists(path) && tree.getDir(path).subfiles.length > 0; }, async isFile(path: string): Promise<boolean> { return tree.exists(path); }, }; } async function getWorkspace(tree: Tree): Promise<workspaces.WorkspaceDefinition> { const host = createHost(tree); const {workspace} = await workspaces.readWorkspace('/', host); return workspace; }
{ "end_byte": 3184, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/project_tsconfig_paths.ts" }
angular/packages/core/schematics/utils/extract_metadata.ts_0_1744
/** * @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 {getAngularDecorators} from './ng_decorators'; import {unwrapExpression} from './typescript/functions'; /** Interface describing metadata of an Angular class. */ export interface AngularClassMetadata { type: 'component' | 'directive'; node: ts.ObjectLiteralExpression; } /** Extracts `@Directive` or `@Component` metadata from the given class. */ export function extractAngularClassMetadata( typeChecker: ts.TypeChecker, node: ts.ClassDeclaration, ): AngularClassMetadata | null { const decorators = ts.getDecorators(node); if (!decorators || !decorators.length) { return null; } const ngDecorators = getAngularDecorators(typeChecker, decorators); const componentDecorator = ngDecorators.find((dec) => dec.name === 'Component'); const directiveDecorator = ngDecorators.find((dec) => dec.name === 'Directive'); const decorator = componentDecorator ?? directiveDecorator; // In case no decorator could be found on the current class, skip. if (!decorator) { return null; } const decoratorCall = decorator.node.expression; // In case the decorator call is not valid, skip this class declaration. if (decoratorCall.arguments.length !== 1) { return null; } const metadata = unwrapExpression(decoratorCall.arguments[0]); // Ensure that the metadata is an object literal expression. if (!ts.isObjectLiteralExpression(metadata)) { return null; } return { type: componentDecorator ? 'component' : 'directive', node: metadata, }; }
{ "end_byte": 1744, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/extract_metadata.ts" }
angular/packages/core/schematics/utils/tslint/tslint_html_source_file.ts_0_1552
/** * @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'; /** * Creates a fake TypeScript source file that can contain content of templates or stylesheets. * The fake TypeScript source file then can be passed to TSLint in combination with a rule failure. */ export function createHtmlSourceFile(filePath: string, content: string): ts.SourceFile { const sourceFile = ts.createSourceFile(filePath, `\`${content}\``, ts.ScriptTarget.ES5); // Subtract two characters because the string literal quotes are only needed for parsing // and are not part of the actual source file. (sourceFile.end as number) = sourceFile.end - 2; // Note: This does not affect the way TSLint applies replacements for external resource files. // At the time of writing, TSLint loads files manually if the actual rule source file is not // equal to the source file of the replacement. This means that the replacements need proper // offsets without the string literal quote symbols. sourceFile.getFullText = function () { return sourceFile.text.substring(1, sourceFile.text.length - 1); }; sourceFile.getText = sourceFile.getFullText; // Update the "text" property to be set to the template content without quotes. This is // necessary so that the TypeScript line starts map is properly computed. sourceFile.text = sourceFile.getFullText(); return sourceFile; }
{ "end_byte": 1552, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tslint/tslint_html_source_file.ts" }
angular/packages/core/schematics/utils/tslint/BUILD.bazel_0_292
load("//tools:defaults.bzl", "ts_library") ts_library( name = "tslint", srcs = glob(["**/*.ts"]), tsconfig = "//packages/core/schematics:tsconfig.json", visibility = [ "//packages/core/schematics/migrations/google3:__pkg__", ], deps = ["@npm//typescript"], )
{ "end_byte": 292, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tslint/BUILD.bazel" }
angular/packages/core/schematics/utils/typescript/decorators.ts_0_831
/** * @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 {getImportOfIdentifier, Import} from './imports'; export function getCallDecoratorImport( typeChecker: ts.TypeChecker, decorator: ts.Decorator, ): Import | null { // Note that this does not cover the edge case where decorators are called from // a namespace import: e.g. "@core.Component()". This is not handled by Ngtsc either. if ( !ts.isCallExpression(decorator.expression) || !ts.isIdentifier(decorator.expression.expression) ) { return null; } const identifier = decorator.expression.expression; return getImportOfIdentifier(typeChecker, identifier); }
{ "end_byte": 831, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/typescript/decorators.ts" }
angular/packages/core/schematics/utils/typescript/class_declaration.ts_0_1699
/** * @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'; /** Determines the base type identifiers of a specified class declaration. */ export function getBaseTypeIdentifiers(node: ts.ClassDeclaration): ts.Identifier[] | null { if (!node.heritageClauses) { return null; } return node.heritageClauses .filter((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword) .reduce((types, clause) => types.concat(clause.types), [] as ts.ExpressionWithTypeArguments[]) .map((typeExpression) => typeExpression.expression) .filter(ts.isIdentifier); } /** Gets the first found parent class declaration of a given node. */ export function findParentClassDeclaration(node: ts.Node): ts.ClassDeclaration | null { while (!ts.isClassDeclaration(node)) { if (ts.isSourceFile(node)) { return null; } node = node.parent; } return node; } /** * Finds the class declaration that is being referred to by a node. * @param reference Node referring to a class declaration. * @param typeChecker */ export function findClassDeclaration( reference: ts.Node, typeChecker: ts.TypeChecker, ): ts.ClassDeclaration | null { return ( typeChecker .getTypeAtLocation(reference) .getSymbol() ?.declarations?.find(ts.isClassDeclaration) || null ); } /** Checks whether the given class declaration has an explicit constructor or not. */ export function hasExplicitConstructor(node: ts.ClassDeclaration): boolean { return node.members.some(ts.isConstructorDeclaration); }
{ "end_byte": 1699, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/typescript/class_declaration.ts" }
angular/packages/core/schematics/utils/typescript/nodes.ts_0_2176
/** * @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'; /** Checks whether the given TypeScript node has the specified modifier set. */ export function hasModifier(node: ts.Node, modifierKind: ts.SyntaxKind) { return ( ts.canHaveModifiers(node) && !!node.modifiers && node.modifiers.some((m) => m.kind === modifierKind) ); } /** Find the closest parent node of a particular kind. */ export function closestNode<T extends ts.Node>( node: ts.Node, predicate: (n: ts.Node) => n is T, ): T | null { let current = node.parent; while (current && !ts.isSourceFile(current)) { if (predicate(current)) { return current; } current = current.parent; } return null; } /** * Checks whether a particular node is part of a null check. E.g. given: * `foo.bar ? foo.bar.value : null` the null check would be `foo.bar`. */ export function isNullCheck(node: ts.Node): boolean { if (!node.parent) { return false; } // `foo.bar && foo.bar.value` where `node` is `foo.bar`. if (ts.isBinaryExpression(node.parent) && node.parent.left === node) { return true; } // `foo.bar && foo.bar.parent && foo.bar.parent.value` // where `node` is `foo.bar`. if ( node.parent.parent && ts.isBinaryExpression(node.parent.parent) && node.parent.parent.left === node.parent ) { return true; } // `if (foo.bar) {...}` where `node` is `foo.bar`. if (ts.isIfStatement(node.parent) && node.parent.expression === node) { return true; } // `foo.bar ? foo.bar.value : null` where `node` is `foo.bar`. if (ts.isConditionalExpression(node.parent) && node.parent.condition === node) { return true; } return false; } /** Checks whether a property access is safe (e.g. `foo.parent?.value`). */ export function isSafeAccess(node: ts.Node): boolean { return ( node.parent != null && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node && node.parent.questionDotToken != null ); }
{ "end_byte": 2176, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/typescript/nodes.ts" }
angular/packages/core/schematics/utils/typescript/imports.ts_0_5838
/** * @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'; export type Import = { name: string; importModule: string; node: ts.ImportDeclaration; }; /** Gets import information about the specified identifier by using the Type checker. */ export function getImportOfIdentifier( typeChecker: ts.TypeChecker, node: ts.Identifier, ): Import | null { const symbol = typeChecker.getSymbolAtLocation(node); if (!symbol || symbol.declarations === undefined || !symbol.declarations.length) { return null; } const decl = symbol.declarations[0]; if (!ts.isImportSpecifier(decl)) { return null; } const importDecl = decl.parent.parent.parent; if (!ts.isImportDeclaration(importDecl) || !ts.isStringLiteral(importDecl.moduleSpecifier)) { return null; } return { // Handles aliased imports: e.g. "import {Component as myComp} from ..."; name: decl.propertyName ? decl.propertyName.text : decl.name.text, importModule: importDecl.moduleSpecifier.text, node: importDecl, }; } /** * Gets a top-level import specifier with a specific name that is imported from a particular module. * E.g. given a file that looks like: * * ``` * import { Component, Directive } from '@angular/core'; * import { Foo } from './foo'; * ``` * * Calling `getImportSpecifier(sourceFile, '@angular/core', 'Directive')` will yield the node * referring to `Directive` in the top import. * * @param sourceFile File in which to look for imports. * @param moduleName Name of the import's module. * @param specifierName Original name of the specifier to look for. Aliases will be resolved to * their original name. */ export function getImportSpecifier( sourceFile: ts.SourceFile, moduleName: string | RegExp, specifierName: string, ): ts.ImportSpecifier | null { return getImportSpecifiers(sourceFile, moduleName, specifierName)[0] ?? null; } export function getImportSpecifiers( sourceFile: ts.SourceFile, moduleName: string | RegExp, specifierOrSpecifiers: string | string[], ): ts.ImportSpecifier[] { const matches: ts.ImportSpecifier[] = []; for (const node of sourceFile.statements) { if (!ts.isImportDeclaration(node) || !ts.isStringLiteral(node.moduleSpecifier)) { continue; } const namedBindings = node.importClause?.namedBindings; const isMatch = typeof moduleName === 'string' ? node.moduleSpecifier.text === moduleName : moduleName.test(node.moduleSpecifier.text); if (!isMatch || !namedBindings || !ts.isNamedImports(namedBindings)) { continue; } if (typeof specifierOrSpecifiers === 'string') { const match = findImportSpecifier(namedBindings.elements, specifierOrSpecifiers); if (match) { matches.push(match); } } else { for (const specifierName of specifierOrSpecifiers) { const match = findImportSpecifier(namedBindings.elements, specifierName); if (match) { matches.push(match); } } } } return matches; } export function getNamedImports( sourceFile: ts.SourceFile, moduleName: string | RegExp, ): ts.NamedImports | null { for (const node of sourceFile.statements) { if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) { const isMatch = typeof moduleName === 'string' ? node.moduleSpecifier.text === moduleName : moduleName.test(node.moduleSpecifier.text); const namedBindings = node.importClause?.namedBindings; if (isMatch && namedBindings && ts.isNamedImports(namedBindings)) { return namedBindings; } } } return null; } /** * Replaces an import inside a named imports node with a different one. * * @param node Node that contains the imports. * @param existingImport Import that should be replaced. * @param newImportName Import that should be inserted. */ export function replaceImport( node: ts.NamedImports, existingImport: string, newImportName: string, ) { const isAlreadyImported = findImportSpecifier(node.elements, newImportName); if (isAlreadyImported) { return node; } const existingImportNode = findImportSpecifier(node.elements, existingImport); if (!existingImportNode) { return node; } const importPropertyName = existingImportNode.propertyName ? ts.factory.createIdentifier(newImportName) : undefined; const importName = existingImportNode.propertyName ? existingImportNode.name : ts.factory.createIdentifier(newImportName); return ts.factory.updateNamedImports(node, [ ...node.elements.filter((current) => current !== existingImportNode), // Create a new import while trying to preserve the alias of the old one. ts.factory.createImportSpecifier(false, importPropertyName, importName), ]); } /** * Removes a symbol from the named imports and updates a node * that represents a given named imports. * * @param node Node that contains the imports. * @param symbol Symbol that should be removed. * @returns An updated node (ts.NamedImports). */ export function removeSymbolFromNamedImports(node: ts.NamedImports, symbol: ts.ImportSpecifier) { return ts.factory.updateNamedImports(node, [ ...node.elements.filter((current) => current !== symbol), ]); } /** Finds an import specifier with a particular name. */ export function findImportSpecifier( nodes: ts.NodeArray<ts.ImportSpecifier>, specifierName: string, ): ts.ImportSpecifier | undefined { return nodes.find((element) => { const {name, propertyName} = element; return propertyName ? propertyName.text === specifierName : name.text === specifierName; }); }
{ "end_byte": 5838, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/typescript/imports.ts" }
angular/packages/core/schematics/utils/typescript/symbol.ts_0_3521
/** * @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'; export function getValueSymbolOfDeclaration( node: ts.Node, typeChecker: ts.TypeChecker, ): ts.Symbol | undefined { let symbol = typeChecker.getSymbolAtLocation(node); while (symbol && symbol.flags & ts.SymbolFlags.Alias) { symbol = typeChecker.getAliasedSymbol(symbol); } return symbol; } /** Checks whether a node is referring to a specific import specifier. */ export function isReferenceToImport( typeChecker: ts.TypeChecker, node: ts.Node, importSpecifier: ts.ImportSpecifier, ): boolean { // If this function is called on an identifier (should be most cases), we can quickly rule out // non-matches by comparing the identifier's string and the local name of the import specifier // which saves us some calls to the type checker. if (ts.isIdentifier(node) && node.text !== importSpecifier.name.text) { return false; } const nodeSymbol = typeChecker.getTypeAtLocation(node).getSymbol(); const importSymbol = typeChecker.getTypeAtLocation(importSpecifier).getSymbol(); return ( !!(nodeSymbol?.declarations?.[0] && importSymbol?.declarations?.[0]) && nodeSymbol.declarations[0] === importSymbol.declarations[0] ); } /** Checks whether a node's type is nullable (`null`, `undefined` or `void`). */ export function isNullableType(typeChecker: ts.TypeChecker, node: ts.Node) { // Skip expressions in the form of `foo.bar!.baz` since the `TypeChecker` seems // to identify them as null, even though the user indicated that it won't be. if (node.parent && ts.isNonNullExpression(node.parent)) { return false; } const type = typeChecker.getTypeAtLocation(node); const typeNode = typeChecker.typeToTypeNode(type, undefined, ts.NodeBuilderFlags.None); let hasSeenNullableType = false; // Trace the type of the node back to a type node, walk // through all of its sub-nodes and look for nullable types. if (typeNode) { (function walk(current: ts.Node) { if ( current.kind === ts.SyntaxKind.NullKeyword || current.kind === ts.SyntaxKind.UndefinedKeyword || current.kind === ts.SyntaxKind.VoidKeyword ) { hasSeenNullableType = true; // Note that we don't descend into type literals, because it may cause // us to mis-identify the root type as nullable, because it has a nullable // property (e.g. `{ foo: string | null }`). } else if (!hasSeenNullableType && !ts.isTypeLiteralNode(current)) { current.forEachChild(walk); } })(typeNode); } return hasSeenNullableType; } /** * Walks through the types and sub-types of a node, looking for a * type that has the same name as one of the passed-in ones. */ export function hasOneOfTypes( typeChecker: ts.TypeChecker, node: ts.Node, types: string[], ): boolean { const type = typeChecker.getTypeAtLocation(node); const typeNode = type ? typeChecker.typeToTypeNode(type, undefined, ts.NodeBuilderFlags.None) : undefined; let hasMatch = false; if (typeNode) { (function walk(current: ts.Node) { if (ts.isIdentifier(current) && types.includes(current.text)) { hasMatch = true; } else if (!hasMatch && !ts.isTypeLiteralNode(current)) { current.forEachChild(walk); } })(typeNode); } return hasMatch; }
{ "end_byte": 3521, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/typescript/symbol.ts" }
angular/packages/core/schematics/utils/typescript/find_base_classes.ts_0_1229
/** * @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 {getBaseTypeIdentifiers} from './class_declaration'; /** Gets all base class declarations of the specified class declaration. */ export function findBaseClassDeclarations(node: ts.ClassDeclaration, typeChecker: ts.TypeChecker) { const result: {identifier: ts.Identifier; node: ts.ClassDeclaration}[] = []; let currentClass = node; while (currentClass) { const baseTypes = getBaseTypeIdentifiers(currentClass); if (!baseTypes || baseTypes.length !== 1) { break; } const symbol = typeChecker.getTypeAtLocation(baseTypes[0]).getSymbol(); // Note: `ts.Symbol#valueDeclaration` can be undefined. TypeScript has an incorrect type // for this: https://github.com/microsoft/TypeScript/issues/24706. if (!symbol || !symbol.valueDeclaration || !ts.isClassDeclaration(symbol.valueDeclaration)) { break; } result.push({identifier: baseTypes[0], node: symbol.valueDeclaration}); currentClass = symbol.valueDeclaration; } return result; }
{ "end_byte": 1229, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/typescript/find_base_classes.ts" }
angular/packages/core/schematics/utils/typescript/property_name.ts_0_1221
/** * @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'; /** Type that describes a property name with an obtainable text. */ type PropertyNameWithText = Exclude<ts.PropertyName, ts.ComputedPropertyName>; /** * Gets the text of the given property name. Returns null if the property * name couldn't be determined statically. */ export function getPropertyNameText(node: ts.PropertyName): string | null { if (ts.isIdentifier(node) || ts.isStringLiteralLike(node)) { return node.text; } return null; } /** Checks whether the given property name has a text. */ export function hasPropertyNameText(node: ts.PropertyName): node is PropertyNameWithText { return ts.isStringLiteral(node) || ts.isNumericLiteral(node) || ts.isIdentifier(node); } /** Finds a property with a specific name in an object literal expression. */ export function findLiteralProperty(literal: ts.ObjectLiteralExpression, name: string) { return literal.properties.find( (prop) => prop.name && ts.isIdentifier(prop.name) && prop.name.text === name, ); }
{ "end_byte": 1221, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/typescript/property_name.ts" }
angular/packages/core/schematics/utils/typescript/parse_tsconfig.ts_0_1106
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as path from 'path'; import ts from 'typescript'; export function parseTsconfigFile(tsconfigPath: string, basePath: string): ts.ParsedCommandLine { const {config} = ts.readConfigFile(tsconfigPath, ts.sys.readFile); const parseConfigHost = { useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames, fileExists: ts.sys.fileExists, readDirectory: ts.sys.readDirectory, readFile: ts.sys.readFile, }; // Throw if incorrect arguments are passed to this function. Passing relative base paths // results in root directories not being resolved and in later type checking runtime errors. // More details can be found here: https://github.com/microsoft/TypeScript/issues/37731. if (!path.isAbsolute(basePath)) { throw Error('Unexpected relative base path has been specified.'); } return ts.parseJsonConfigFileContent(config, parseConfigHost, basePath, {}); }
{ "end_byte": 1106, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/typescript/parse_tsconfig.ts" }
angular/packages/core/schematics/utils/typescript/compiler_host.ts_0_5438
/** * @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 {Tree} from '@angular-devkit/schematics'; import {dirname, relative, resolve} from 'path'; import ts from 'typescript'; import {parseTsconfigFile} from './parse_tsconfig'; type FakeReadFileFn = (fileName: string) => string | undefined; /** * Creates a TypeScript program instance for a TypeScript project within * the virtual file system tree. * @param tree Virtual file system tree that contains the source files. * @param tsconfigPath Virtual file system path that resolves to the TypeScript project. * @param basePath Base path for the virtual file system tree. * @param fakeFileRead Optional file reader function. Can be used to overwrite files in * the TypeScript program, or to add in-memory files (e.g. to add global types). * @param additionalFiles Additional file paths that should be added to the program. */ export function createMigrationProgram( tree: Tree, tsconfigPath: string, basePath: string, fakeFileRead?: FakeReadFileFn, additionalFiles?: string[], ) { const {rootNames, options, host} = createProgramOptions( tree, tsconfigPath, basePath, fakeFileRead, additionalFiles, ); return ts.createProgram(rootNames, options, host); } /** * Creates the options necessary to instantiate a TypeScript program. * @param tree Virtual file system tree that contains the source files. * @param tsconfigPath Virtual file system path that resolves to the TypeScript project. * @param basePath Base path for the virtual file system tree. * @param fakeFileRead Optional file reader function. Can be used to overwrite files in * the TypeScript program, or to add in-memory files (e.g. to add global types). * @param additionalFiles Additional file paths that should be added to the program. * @param optionOverrides Overrides of the parsed compiler options. */ export function createProgramOptions( tree: Tree, tsconfigPath: string, basePath: string, fakeFileRead?: FakeReadFileFn, additionalFiles?: string[], optionOverrides?: ts.CompilerOptions, ) { // Resolve the tsconfig path to an absolute path. This is needed as TypeScript otherwise // is not able to resolve root directories in the given tsconfig. More details can be found // in the following issue: https://github.com/microsoft/TypeScript/issues/37731. tsconfigPath = resolve(basePath, tsconfigPath); const parsed = parseTsconfigFile(tsconfigPath, dirname(tsconfigPath)); const options = optionOverrides ? {...parsed.options, ...optionOverrides} : parsed.options; const host = createMigrationCompilerHost(tree, options, basePath, fakeFileRead); return {rootNames: parsed.fileNames.concat(additionalFiles || []), options, host}; } function createMigrationCompilerHost( tree: Tree, options: ts.CompilerOptions, basePath: string, fakeRead?: FakeReadFileFn, ): ts.CompilerHost { const host = ts.createCompilerHost(options, true); const defaultReadFile = host.readFile; // We need to overwrite the host "readFile" method, as we want the TypeScript // program to be based on the file contents in the virtual file tree. Otherwise // if we run multiple migrations we might have intersecting changes and // source files. host.readFile = (fileName) => { const treeRelativePath = relative(basePath, fileName); let result: string | undefined = fakeRead?.(treeRelativePath); if (typeof result !== 'string') { // If the relative path resolved to somewhere outside of the tree, fall back to // TypeScript's default file reading function since the `tree` will throw an error. result = treeRelativePath.startsWith('..') ? defaultReadFile.call(host, fileName) : tree.read(treeRelativePath)?.toString(); } // Strip BOM as otherwise TSC methods (Ex: getWidth) will return an offset, // which breaks the CLI UpdateRecorder. // See: https://github.com/angular/angular/pull/30719 return typeof result === 'string' ? result.replace(/^\uFEFF/, '') : undefined; }; return host; } /** * Checks whether a file can be migrate by our automated migrations. * @param basePath Absolute path to the project. * @param sourceFile File being checked. * @param program Program that includes the source file. */ export function canMigrateFile( basePath: string, sourceFile: ts.SourceFile, program: ts.Program, ): boolean { // We shouldn't migrate .d.ts files, files from an external library or type checking files. if ( sourceFile.fileName.endsWith('.ngtypecheck.ts') || sourceFile.isDeclarationFile || program.isSourceFileFromExternalLibrary(sourceFile) ) { return false; } // Our migrations are set up to create a `Program` from the project's tsconfig and to migrate all // the files within the program. This can include files that are outside of the Angular CLI // project. We can't migrate files outside of the project, because our file system interactions // go through the CLI's `Tree` which assumes that all files are within the project. See: // https://github.com/angular/angular-cli/blob/0b0961c9c233a825b6e4bb59ab7f0790f9b14676/packages/angular_devkit/schematics/src/tree/host-tree.ts#L131 return !relative(basePath, sourceFile.fileName).startsWith('..'); }
{ "end_byte": 5438, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/typescript/compiler_host.ts" }
angular/packages/core/schematics/utils/typescript/functions.ts_0_1139
/** * @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'; /** Checks whether a given node is a function like declaration. */ export function isFunctionLikeDeclaration(node: ts.Node): node is ts.FunctionLikeDeclaration { return ( ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isGetAccessorDeclaration(node) || ts.isSetAccessorDeclaration(node) ); } /** * Unwraps a given expression TypeScript node. Expressions can be wrapped within multiple * parentheses or as expression. e.g. "(((({exp}))))()". The function should return the * TypeScript node referring to the inner expression. e.g "exp". */ export function unwrapExpression(node: ts.Expression | ts.ParenthesizedExpression): ts.Expression { if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node)) { return unwrapExpression(node.expression); } else { return node; } }
{ "end_byte": 1139, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/typescript/functions.ts" }
angular/packages/core/schematics/utils/tsurge/project_paths.ts_0_4559
/** * @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, FileSystem, getFileSystem, isLocalRelativePath, } from '@angular/compiler-cli/src/ngtsc/file_system'; import ts from 'typescript'; import {ProgramInfo} from './program_info'; /** * Branded type representing a file ID. Practically, this * is a relative path based on the most appropriate root dir. * * A project-relative path is relative to the longest root * directory of the project. A project-relative path is always * unique in the context of the project (like google3). * * This is a requirement and the fundamental concept of root directories. * See: https://www.typescriptlang.org/tsconfig/#rootDirs. * * Note that compilation units are only sub-parts of the project * and are assumed, and expected to always have the same root directories. * * File IDs are important for Tsurge, as replacements and paths * should never refer to absolute paths. That is because the project * may be put into different temporary directories in workers. * * E.g. Tsunami may have different project roots in different * stages, or we can't reliably relativize paths after Tsunami completed. * Or, paths may exist inside `blaze-out/XX/google3` but instead should be * matching associable with the same path in its `.ts` compilation unit * * See {@link ProjectFile#id} */ export type ProjectFileID = string & {__projectFileID: true}; /** * Branded type representing an unsafe file path, relative to the * primary project root. * * The path is unsafe for unique ID generation as it does not respect * virtual roots as configured via `tsconfig#rootDirs`. Though, the * path is useful for replacements, writing to disk. * * See {@link ProjectFile#rootRelativePath} */ export type ProjectRootRelativePath = string & {__unsafeProjectRootRelative: true}; /** * Type representing a file in the project. * * This construct is fully serializable between stages and * workers. */ export interface ProjectFile { /** * Unique ID for the file. * * In practice, this is a file path relative to the most appropriate * root directory. This allows identifying files, respecting the virtual * root configuration. See: https://www.typescriptlang.org/tsconfig/#rootDirs. * * Use this for matching files, contributing to global metadata. IDs consider * the following files as the same: `/blaze-out/fast-build/file.ts` and `/file.ts`. */ id: ProjectFileID; /** * Unsafe path for the file, relative to the primary * project root ({@link ProgramInfo.projectRoot}) * * Use this with caution, and preferably not for unique ID * generation across workers and stages because {@link id} * is more suitable and respects virtual TS roots (`rootDirs`). */ rootRelativePath: ProjectRootRelativePath; } /** * Gets a project file instance for the given file. * * Use this helper for dealing with project paths throughout your * migration. The return type is serializable. * * See {@link ProjectFile}. */ export function projectFile( file: ts.SourceFile | AbsoluteFsPath, {sortedRootDirs, projectRoot}: Pick<ProgramInfo, 'sortedRootDirs' | 'projectRoot'>, ): ProjectFile { const fs = getFileSystem(); const filePath = fs.resolve(typeof file === 'string' ? file : file.fileName); // Sorted root directories are sorted longest to shortest. First match // is the appropriate root directory for ID computation. for (const rootDir of sortedRootDirs) { if (!isWithinBasePath(fs, rootDir, filePath)) { continue; } return { id: fs.relative(rootDir, filePath) as string as ProjectFileID, rootRelativePath: fs.relative(projectRoot, filePath) as string as ProjectRootRelativePath, }; } // E.g. project directory may be `src/`, but files may be looked up // from `node_modules/`. This is fine, but in those cases, no root // directory matches. const rootRelativePath = fs.relative(projectRoot, filePath); return { id: rootRelativePath as string as ProjectFileID, rootRelativePath: rootRelativePath as string as ProjectRootRelativePath, }; } /** * Whether `path` is a descendant of the `base`? * E.g. `a/b/c` is within `a/b` but not within `a/x`. */ function isWithinBasePath(fs: FileSystem, base: AbsoluteFsPath, path: AbsoluteFsPath): boolean { return isLocalRelativePath(fs.relative(base, path)); }
{ "end_byte": 4559, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/project_paths.ts" }
angular/packages/core/schematics/utils/tsurge/migration.ts_0_3781
/** * @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 {TsurgeBaseMigration} from './base_migration'; import {ProgramInfo} from './program_info'; import {Replacement} from './replacement'; /** Type describing the result of a Tsurge `migrate` stage. */ interface MigrateResult { replacements: Replacement[]; } /** * A Tsurge migration is split into three stages: * - analyze phase * - merge phase * - migrate phase * * The motivation for such split is that migrations may be executed * on individual workers, e.g. via go/tsunami or a Beam pipeline. The * individual workers are never seeing the full project, e.g. Google3. * * The analysis phases can operate on smaller TS project units, and later * then expect the isolated unit data to be merged into some sort of global * metadata via the `merge` phase. As a final step then, the migration * replacements will be computed. * * There are subtle differences in how the final stage can compute migration * replacements. Some migrations need program access again, while other's don't. * For this reason, there are two possible variants of Tsurge migrations: * * - {@link TsurgeFunnelMigration} * - {@link TsurgeComplexMigration} * * TODO: Link design doc */ export type TsurgeMigration<UnitAnalysisMetadata, CombinedGlobalMetadata> = | TsurgeComplexMigration<UnitAnalysisMetadata, CombinedGlobalMetadata> | TsurgeFunnelMigration<UnitAnalysisMetadata, CombinedGlobalMetadata>; /** * A simpler variant of a {@link TsurgeComplexMigration} that does not * fan-out into multiple workers per compilation unit to compute * the final migration replacements. * * This is faster and less resource intensive as workers and TS programs * are only ever created once. * * This is commonly the case when migrations are refactored to eagerly * compute replacements in the analyze stage, and then leverage the * global unit data to filter replacements that turned out to be "invalid". */ export abstract class TsurgeFunnelMigration< UnitAnalysisMetadata, CombinedGlobalMetadata, > extends TsurgeBaseMigration<UnitAnalysisMetadata, CombinedGlobalMetadata> { /** * Finalizes the migration result. * * This stage can be used to filter replacements, leveraging global combined analysis * data to compute the overall migration result, without needing new "migrate" workers * for every unit, as with a standard {@link TsurgeMigration}. * * @returns All replacements for the whole project. */ abstract migrate(globalData: CombinedGlobalMetadata): Promise<MigrateResult>; } /** * Complex variant of a `Tsurge` migration. * * For example, every analyze worker may contribute to a list of TS * references that are later combined. The migrate phase can then compute actual * file updates for all individual compilation units, leveraging the global metadata * to e.g. see if there are any references from other compilation units that may be * problematic and prevent migration of a given file. */ export abstract class TsurgeComplexMigration< UnitAnalysisMetadata, CombinedGlobalMetadata, > extends TsurgeBaseMigration<UnitAnalysisMetadata, CombinedGlobalMetadata> { /** * Migration phase. Workers will be started for every compilation unit again, * instantiating a new program for every unit to compute the final migration * replacements, leveraging combined global metadata. * * @returns Replacements for the given compilation unit (**not** the whole project!) */ abstract migrate( globalMetadata: CombinedGlobalMetadata, info: ProgramInfo, ): Promise<MigrateResult>; }
{ "end_byte": 3781, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/migration.ts" }
angular/packages/core/schematics/utils/tsurge/program_info.ts_0_1647
/** * @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 {NgCompilerOptions} from '@angular/compiler-cli/src/ngtsc/core/api'; import {AbsoluteFsPath} from '@angular/compiler-cli/src/ngtsc/file_system'; import ts from 'typescript'; import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core'; /** * Base information for a TypeScript project, including an instantiated * TypeScript program. Base information may be extended by user-overridden * migration preparation methods to extend the stages with more data. */ export interface BaseProgramInfo { ngCompiler: NgCompiler | null; program: ts.Program; userOptions: NgCompilerOptions; programAbsoluteRootFileNames: string[]; host: Pick<ts.CompilerHost, 'getCanonicalFileName' | 'getCurrentDirectory'>; } /** * Full program information for a TypeScript project. This is the default "extension" * of the {@link BaseProgramInfo} with additional commonly accessed information. * * A different interface may be used as full program information, configured via a * {@link TsurgeMigration.prepareProgram} override. */ export interface ProgramInfo extends BaseProgramInfo { sourceFiles: ts.SourceFile[]; fullProgramSourceFiles: readonly ts.SourceFile[]; /** * Root directories of the project. * Sorted longest first for easy lookups. */ sortedRootDirs: AbsoluteFsPath[]; /** * Primary root directory. * This is the shortest root directory, including all others. */ projectRoot: AbsoluteFsPath; }
{ "end_byte": 1647, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/program_info.ts" }
angular/packages/core/schematics/utils/tsurge/replacement.ts_0_1019
/** * @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 MagicString from 'magic-string'; import {ProjectFile} from './project_paths'; /** A text replacement for the given file. */ export class Replacement { constructor( public projectFile: ProjectFile, public update: TextUpdate, ) {} } /** An isolated text update that may be applied to a file. */ export class TextUpdate { constructor( public data: { position: number; end: number; toInsert: string; }, ) {} } /** Helper that applies updates to the given text. */ export function applyTextUpdates(input: string, updates: TextUpdate[]): string { const res = new MagicString(input); for (const update of updates) { res.remove(update.data.position, update.data.end); res.appendLeft(update.data.position, update.data.toInsert); } return res.toString(); }
{ "end_byte": 1019, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/replacement.ts" }
angular/packages/core/schematics/utils/tsurge/BUILD.bazel_0_901
load("//tools:defaults.bzl", "ts_library") package_group( name = "users", packages = [ "//packages/core/schematics/...", "//packages/language-service/src/refactorings/...", ], ) ts_library( name = "tsurge", srcs = glob(["**/*.ts"]), visibility = [":users"], deps = [ "//packages/compiler-cli", "//packages/compiler-cli/src/ngtsc/core", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/compiler-cli/src/ngtsc/shims", "//packages/compiler-cli/src/ngtsc/translator", "//packages/compiler-cli/src/ngtsc/util", "@npm//@types/diff", "@npm//@types/node", "@npm//chalk", "@npm//diff", "@npm//magic-string", "@npm//typescript", ], )
{ "end_byte": 901, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/BUILD.bazel" }
angular/packages/core/schematics/utils/tsurge/index.ts_0_440
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './base_migration'; export * from './migration'; export * from './program_info'; export * from './replacement'; export * from './helpers/unique_id'; export * from './helpers/serializable'; export * from './project_paths';
{ "end_byte": 440, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/index.ts" }
angular/packages/core/schematics/utils/tsurge/base_migration.ts_0_3435
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {absoluteFrom, FileSystem} from '@angular/compiler-cli/src/ngtsc/file_system'; import {isShim} from '@angular/compiler-cli/src/ngtsc/shims'; import {createNgtscProgram} from './helpers/ngtsc_program'; import {BaseProgramInfo, ProgramInfo} from './program_info'; import {getRootDirs} from '@angular/compiler-cli/src/ngtsc/util/src/typescript'; import {Serializable} from './helpers/serializable'; /** * Type describing statistics that could be tracked * by migrations. * * Statistics may be tracked depending on the runner. */ export interface MigrationStats { counters: Record<string, number>; } /** * @private * * Base class for the possible Tsurge migration variants. * * For example, this class exposes methods to conveniently create * TypeScript programs, while also allowing migration authors to override. */ export abstract class TsurgeBaseMigration<UnitAnalysisMetadata, CombinedGlobalMetadata> { // By default, ngtsc programs are being created. createProgram(tsconfigAbsPath: string, fs?: FileSystem): BaseProgramInfo { return createNgtscProgram(tsconfigAbsPath, fs); } // Optional function to prepare the base `ProgramInfo` even further, // for the analyze and migrate phases. E.g. determining source files. prepareProgram(info: BaseProgramInfo): ProgramInfo { const fullProgramSourceFiles = [...info.program.getSourceFiles()]; const sourceFiles = fullProgramSourceFiles.filter( (f) => !f.isDeclarationFile && // Note `isShim` will work for the initial program, but for TCB programs, the shims are no longer annotated. !isShim(f) && !f.fileName.endsWith('.ngtypecheck.ts'), ); // Sort it by length in reverse order (longest first). This speeds up lookups, // since there's no need to keep going through the array once a match is found. const sortedRootDirs = getRootDirs(info.host, info.userOptions).sort( (a, b) => b.length - a.length, ); // TODO: Consider also following TS's logic here, finding the common source root. // See: Program#getCommonSourceDirectory. const primaryRoot = absoluteFrom( info.userOptions.rootDir ?? sortedRootDirs.at(-1) ?? info.program.getCurrentDirectory(), ); return { ...info, sourceFiles, fullProgramSourceFiles, sortedRootDirs, projectRoot: primaryRoot, }; } /** Analyzes the given TypeScript project and returns serializable compilation unit data. */ abstract analyze(info: ProgramInfo): Promise<Serializable<UnitAnalysisMetadata>>; /** * Combines two unit analyses into a single analysis metadata. * This is necessary to allow for parallel merging of metadata. */ abstract combine( unitA: UnitAnalysisMetadata, unitB: UnitAnalysisMetadata, ): Promise<Serializable<UnitAnalysisMetadata>>; /** * Converts combined compilation into global metadata result that * is then available for migrate and stats stages. */ abstract globalMeta( combinedData: UnitAnalysisMetadata, ): Promise<Serializable<CombinedGlobalMetadata>>; /** Extract statistics based on the global metadata. */ abstract stats(globalMetadata: CombinedGlobalMetadata): Promise<MigrationStats>; }
{ "end_byte": 3435, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/base_migration.ts" }
angular/packages/core/schematics/utils/tsurge/test/output_migration.ts_0_4590
/** * @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 {DtsMetadataReader} from '@angular/compiler-cli/src/ngtsc/metadata'; import {TypeScriptReflectionHost} from '@angular/compiler-cli/src/ngtsc/reflection'; import {confirmAsSerializable, Serializable} from '../helpers/serializable'; import {TsurgeComplexMigration} from '../migration'; import {ProgramInfo} from '../program_info'; import {Replacement, TextUpdate} from '../replacement'; import {findOutputDeclarationsAndReferences, OutputID} from './output_helpers'; import {projectFile} from '../project_paths'; import {MigrationStats} from '../base_migration'; type AnalysisUnit = {[id: OutputID]: {seenProblematicUsage: boolean}}; type GlobalMetadata = {[id: OutputID]: {canBeMigrated: boolean}}; /** * A `Tsurge` migration that can migrate instances of `@Output()` to * the new `output()` API. * * Note that this is simply a testing construct for now, to verify the migration * framework works as expected. This is **not a full migration**, but rather an example. */ export class OutputMigration extends TsurgeComplexMigration<AnalysisUnit, GlobalMetadata> { override async analyze(info: ProgramInfo) { const program = info.program; const typeChecker = program.getTypeChecker(); const reflector = new TypeScriptReflectionHost(typeChecker, false); const dtsReader = new DtsMetadataReader(typeChecker, reflector); const {sourceOutputs, problematicReferencedOutputs} = findOutputDeclarationsAndReferences( info, typeChecker, reflector, dtsReader, ); const discoveredOutputs: AnalysisUnit = {}; for (const id of sourceOutputs.keys()) { discoveredOutputs[id] = {seenProblematicUsage: false}; } for (const id of problematicReferencedOutputs) { discoveredOutputs[id] = {seenProblematicUsage: true}; } // Here we confirm it as serializable.. return confirmAsSerializable(discoveredOutputs); } override async combine(unitA: AnalysisUnit, unitB: AnalysisUnit) { const merged: AnalysisUnit = {}; // Merge information from two compilation units. Mark // outputs that cannot be migrated due to seen problematic usages. for (const unit of [unitA, unitB]) { for (const [idStr, info] of Object.entries(unit)) { const id = idStr as OutputID; const existing = merged[id]; if (existing === undefined) { merged[id] = {seenProblematicUsage: info.seenProblematicUsage}; } else if (!existing.seenProblematicUsage && info.seenProblematicUsage) { merged[id].seenProblematicUsage = true; } } } return confirmAsSerializable(merged); } override async globalMeta(combinedData: AnalysisUnit) { const globalMeta: GlobalMetadata = {}; for (const [idStr, info] of Object.entries(combinedData)) { globalMeta[idStr as OutputID] = { canBeMigrated: info.seenProblematicUsage === false, }; } return confirmAsSerializable(globalMeta); } override async migrate(globalAnalysisData: GlobalMetadata, info: ProgramInfo) { const program = info.program; const typeChecker = program.getTypeChecker(); const reflector = new TypeScriptReflectionHost(typeChecker, false); const dtsReader = new DtsMetadataReader(typeChecker, reflector); const {sourceOutputs} = findOutputDeclarationsAndReferences( info, typeChecker, reflector, dtsReader, ); const replacements: Replacement[] = []; for (const [id, node] of sourceOutputs.entries()) { // Output cannot be migrated as per global analysis metadata; skip. if (globalAnalysisData[id].canBeMigrated === false) { continue; } replacements.push( new Replacement( projectFile(node.getSourceFile(), info), new TextUpdate({ position: node.getStart(), end: node.getStart(), toInsert: `// TODO: Actual migration logic\n`, }), ), ); } return {replacements}; } override async stats(globalMetadata: GlobalMetadata): Promise<MigrationStats> { let allOutputs = 0; let migratedOutputs = 0; for (const output of Object.values(globalMetadata)) { allOutputs++; if (output.canBeMigrated) { migratedOutputs++; } } return { counters: { allOutputs, migratedOutputs, }, }; } }
{ "end_byte": 4590, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/test/output_migration.ts" }
angular/packages/core/schematics/utils/tsurge/test/BUILD.bazel_0_1020
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") ts_library( name = "migration_lib", srcs = glob( ["**/*.ts"], exclude = ["*.spec.ts"], ), deps = [ "//packages/compiler-cli", "//packages/compiler-cli/src/ngtsc/annotations", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/imports", "//packages/compiler-cli/src/ngtsc/metadata", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/core/schematics/utils/tsurge", "@npm//@types/node", "@npm//typescript", ], ) ts_library( name = "test_lib", testonly = True, srcs = glob( ["**/*.spec.ts"], ), deps = [ ":migration_lib", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/file_system/testing", "//packages/core/schematics/utils/tsurge", ], ) jasmine_node_test( name = "test", deps = [":test_lib"], )
{ "end_byte": 1020, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/test/BUILD.bazel" }
angular/packages/core/schematics/utils/tsurge/test/output_migration.spec.ts_0_3022
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {absoluteFrom} from '@angular/compiler-cli/src/ngtsc/file_system'; import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing'; import {runTsurgeMigration} from '../testing'; import {OutputMigration} from './output_migration'; describe('output migration', () => { beforeEach(() => { initMockFileSystem('Native'); }); it('should work', async () => { const migration = new OutputMigration(); const {fs} = await runTsurgeMigration(migration, [ { name: absoluteFrom('/app.component.ts'), isProgramRootFile: true, contents: ` import {Output, Component, EventEmitter} from '@angular/core'; @Component() class AppComponent { @Output() clicked = new EventEmitter<void>(); } `, }, ]); expect(fs.readFile(absoluteFrom('/app.component.ts'))).toContain( '// TODO: Actual migration logic', ); }); it('should not migrate if there is a problematic usage', async () => { const migration = new OutputMigration(); const {fs} = await runTsurgeMigration(migration, [ { name: absoluteFrom('/app.component.ts'), isProgramRootFile: true, contents: ` import {Output, Component, EventEmitter} from '@angular/core'; @Component() export class AppComponent { @Output() clicked = new EventEmitter<void>(); } `, }, { name: absoluteFrom('/other.component.ts'), isProgramRootFile: true, contents: ` import {AppComponent} from './app.component'; const cmp: AppComponent = null!; cmp.clicked.pipe().subscribe(); `, }, ]); expect(fs.readFile(absoluteFrom('/app.component.ts'))).not.toContain('TODO'); }); it('should compute statistics', async () => { const migration = new OutputMigration(); const {getStatistics} = await runTsurgeMigration(migration, [ { name: absoluteFrom('/app.component.ts'), isProgramRootFile: true, contents: ` import {Output, Component, EventEmitter} from '@angular/core'; @Component() export class AppComponent { @Output() clicked = new EventEmitter<void>(); @Output() canBeMigrated = new EventEmitter<void>(); } `, }, { name: absoluteFrom('/other.component.ts'), isProgramRootFile: true, contents: ` import {AppComponent} from './app.component'; const cmp: AppComponent = null!; cmp.clicked.pipe().subscribe(); `, }, ]); expect(await getStatistics()).toEqual({ counters: { allOutputs: 2, migratedOutputs: 1, }, }); }); });
{ "end_byte": 3022, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/test/output_migration.spec.ts" }
angular/packages/core/schematics/utils/tsurge/test/output_helpers.ts_0_3596
/** * @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 path from 'path'; import {UniqueID} from '../helpers/unique_id'; import ts from 'typescript'; import {ProgramInfo} from '../program_info'; import {DtsMetadataReader} from '@angular/compiler-cli/src/ngtsc/metadata'; import {ClassDeclaration, ReflectionHost} from '@angular/compiler-cli/src/ngtsc/reflection'; import {Reference} from '@angular/compiler-cli/src/ngtsc/imports'; import {getAngularDecorators} from '@angular/compiler-cli/src/ngtsc/annotations'; import {projectFile} from '../project_paths'; export type OutputID = UniqueID<'output-node'>; export function getIdOfOutput(info: ProgramInfo, prop: ts.PropertyDeclaration): OutputID { const fileId = projectFile(prop.getSourceFile(), info).id.replace(/\.d\.ts/, '.ts'); return `${fileId}@@${prop.parent.name ?? 'unknown-class'}@@${prop.name.getText()}` as OutputID; } export function findOutputDeclarationsAndReferences( info: ProgramInfo, checker: ts.TypeChecker, reflector: ReflectionHost, dtsReader: DtsMetadataReader, ) { const {sourceFiles} = info; const sourceOutputs = new Map<OutputID, ts.PropertyDeclaration>(); const problematicReferencedOutputs = new Set<OutputID>(); for (const sf of sourceFiles) { const visitor = (node: ts.Node) => { // Detect output declarations. if ( ts.isPropertyDeclaration(node) && node.initializer !== undefined && ts.isNewExpression(node.initializer) && ts.isIdentifier(node.initializer.expression) && node.initializer.expression.text === 'EventEmitter' ) { sourceOutputs.set(getIdOfOutput(info, node), node); } // Detect problematic output references. if ( ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && node.name.text === 'pipe' ) { const targetSymbol = checker.getSymbolAtLocation(node.expression); if ( targetSymbol !== undefined && targetSymbol.valueDeclaration !== undefined && ts.isPropertyDeclaration(targetSymbol.valueDeclaration) && isOutputDeclaration(targetSymbol.valueDeclaration, reflector, dtsReader) ) { // Mark output to indicate a seen problematic usage. problematicReferencedOutputs.add(getIdOfOutput(info, targetSymbol.valueDeclaration)); } } ts.forEachChild(node, visitor); }; ts.forEachChild(sf, visitor); } return {sourceOutputs, problematicReferencedOutputs}; } function isOutputDeclaration( node: ts.PropertyDeclaration, reflector: ReflectionHost, dtsReader: DtsMetadataReader, ): boolean { // `.d.ts` file, so we check the `static ecmp` metadata on the `declare class`. if (node.getSourceFile().isDeclarationFile) { if ( !ts.isIdentifier(node.name) || !ts.isClassDeclaration(node.parent) || node.parent.name === undefined ) { return false; } const ref = new Reference(node.parent as ClassDeclaration); const directiveMeta = dtsReader.getDirectiveMetadata(ref); return !!directiveMeta?.outputs.getByClassPropertyName(node.name.text); } // `.ts` file, so we check for the `@Output()` decorator. const decorators = reflector.getDecoratorsOfDeclaration(node); const ngDecorators = decorators !== null ? getAngularDecorators(decorators, ['Output'], /* isCore */ false) : []; return ngDecorators.length > 0; }
{ "end_byte": 3596, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/test/output_helpers.ts" }
angular/packages/core/schematics/utils/tsurge/testing/jasmine.ts_0_1304
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /// <reference types="jasmine" /> import chalk from 'chalk'; import {dedent} from './dedent'; import {diffText} from './diff'; declare global { namespace jasmine { interface Matchers<T> { toMatchWithDiff(expected: string): void; } } } export function setupTsurgeJasmineHelpers() { jasmine.addMatchers({ toMatchWithDiff: () => { return { compare(actual: string, expected: string) { actual = dedent`${actual}`; expected = dedent`${expected}`; if (actual === expected) { return {pass: true}; } const diffWithColors = diffText(expected, actual); return { pass: false, message: `${chalk.bold('Expected contents to match.')}\n\n` + ` - ${chalk.green('■■■■■■■')}: Unexpected text in your test assertion.\n` + ` - ${chalk.red(`■■■■■■■`)}: Text that is missing in your assertion.\n` + `${chalk.bold('Diff below')}:\n${diffWithColors}`, }; }, }; }, }); }
{ "end_byte": 1304, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/testing/jasmine.ts" }
angular/packages/core/schematics/utils/tsurge/testing/diff.ts_0_2345
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as diff from 'diff'; import chalk from 'chalk'; /** * Diffs the given two strings and creates a human-readable * colored diff string. */ export function diffText(expected: string, actual: string, diffLineContextRange = 10): string { const redColorCode = chalk.red('ɵɵ').split('ɵɵ')[0]; const greenColorCode = chalk.green('ɵɵ').split('ɵɵ')[0]; const goldenDiff = diff.diffChars(actual, expected); let fullResult = ''; for (const part of goldenDiff) { // whitespace cannot be highlighted, so we use a tiny indicator character. const valueForColor = part.value.replace(/[ \t]/g, '·'); // green for additions, red for deletions const text = part.added ? chalk.green(valueForColor) : part.removed ? chalk.red(valueForColor) : chalk.reset(part.value); fullResult += text; } const lines = fullResult.split(/\n/g); const linesToRender = new Set<number>(); // Find lines with diff, and include context lines around them. for (const [index, l] of lines.entries()) { if (l.includes(redColorCode) || l.includes(greenColorCode)) { const contextBottom = index - diffLineContextRange; const contextTop = index + diffLineContextRange; numbersFromTo(Math.max(0, contextBottom), index).forEach((lineNum) => linesToRender.add(lineNum), ); numbersFromTo(index, Math.min(contextTop, lines.length - 1)).forEach((lineNum) => linesToRender.add(lineNum), ); } } let result = ''; let previous = -1; // Compute full diff text. Add markers if lines were skipped. for (const lineIndex of Array.from(linesToRender).sort((a, b) => a - b)) { if (lineIndex - 1 !== previous) { result += `${chalk.grey('... (lines above) ...')}\n`; } result += `${lines[lineIndex]}\n`; previous = lineIndex; } if (previous < lines.length - 1) { result += `${chalk.grey('... (lines below) ...\n')}`; } return result; } function numbersFromTo(start: number, end: number): number[] { const list: number[] = []; for (let i = start; i <= end; i++) { list.push(i); } return list; }
{ "end_byte": 2345, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/testing/diff.ts" }
angular/packages/core/schematics/utils/tsurge/testing/run_single.ts_0_2729
/** * @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 {TsurgeFunnelMigration, TsurgeMigration} from '../migration'; import {MockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing'; import { absoluteFrom, AbsoluteFsPath, getFileSystem, } from '@angular/compiler-cli/src/ngtsc/file_system'; import {groupReplacementsByFile} from '../helpers/group_replacements'; import {applyTextUpdates} from '../replacement'; import ts from 'typescript'; import {TestRun} from './test_run'; /** * Runs the given migration against a fake set of files, emulating * migration of a real TypeScript Angular project. * * Note: This helper does not execute the migration in batch mode, where * e.g. the migration runs per single file and merges the unit data. * * TODO: Add helper/solution to test batch execution, like with Tsunami. * * @returns a mock file system with the applied replacements of the migration. */ export async function runTsurgeMigration<UnitData, GlobalData>( migration: TsurgeMigration<UnitData, GlobalData>, files: {name: AbsoluteFsPath; contents: string; isProgramRootFile?: boolean}[], compilerOptions: ts.CompilerOptions = {}, ): Promise<TestRun> { const mockFs = getFileSystem(); if (!(mockFs instanceof MockFileSystem)) { throw new Error('Expected a mock file system for `runTsurgeMigration`.'); } for (const file of files) { mockFs.ensureDir(mockFs.dirname(file.name)); mockFs.writeFile(file.name, file.contents); } const rootFiles = files.filter((f) => f.isProgramRootFile).map((f) => f.name); mockFs.writeFile( absoluteFrom('/tsconfig.json'), JSON.stringify({ compilerOptions: { strict: true, rootDir: '/', ...compilerOptions, }, files: rootFiles, }), ); const baseInfo = migration.createProgram('/tsconfig.json', mockFs); const info = migration.prepareProgram(baseInfo); const unitData = await migration.analyze(info); const globalMeta = await migration.globalMeta(unitData); const {replacements} = migration instanceof TsurgeFunnelMigration ? await migration.migrate(globalMeta) : await migration.migrate(globalMeta, info); const updates = groupReplacementsByFile(replacements); for (const [rootRelativePath, changes] of updates.entries()) { const absolutePath = mockFs.join(info.projectRoot, rootRelativePath); mockFs.writeFile(absolutePath, applyTextUpdates(mockFs.readFile(absolutePath), changes)); } return { fs: mockFs, getStatistics: () => migration.stats(globalMeta), }; }
{ "end_byte": 2729, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/testing/run_single.ts" }
angular/packages/core/schematics/utils/tsurge/testing/dedent.ts_0_1118
/** * @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 */ /** * Template string function that can be used to dedent the resulting * string literal. The smallest common indentation will be omitted. * Additionally, whitespace in empty lines is removed. */ export function dedent(strings: TemplateStringsArray, ...values: any[]) { let joinedString = ''; for (let i = 0; i < values.length; i++) { joinedString += `${strings[i]}${values[i]}`; } joinedString += strings[strings.length - 1]; const matches = joinedString.match(/^[ \t]*(?=\S)/gm); if (matches === null) { return joinedString; } const minLineIndent = Math.min(...matches.map((el) => el.length)); const omitMinIndentRegex = new RegExp(`^[ \\t]{${minLineIndent}}`, 'gm'); const omitEmptyLineWhitespaceRegex = /^[ \t]+$/gm; const result = minLineIndent > 0 ? joinedString.replace(omitMinIndentRegex, '') : joinedString; return result.replace(omitEmptyLineWhitespaceRegex, ''); }
{ "end_byte": 1118, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/testing/dedent.ts" }
angular/packages/core/schematics/utils/tsurge/testing/test_run.ts_0_648
/** * @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 {MockFileSystem} from '../../../../../compiler-cli/src/ngtsc/file_system/testing'; import {MigrationStats} from '../base_migration'; /** Type describing results of a Tsurge migration test run. */ export interface TestRun { /** File system that can be used to read migrated file contents. */ fs: MockFileSystem; /** Function that can be invoked to compute migration statistics. */ getStatistics: () => Promise<MigrationStats>; }
{ "end_byte": 648, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/testing/test_run.ts" }
angular/packages/core/schematics/utils/tsurge/testing/index.ts_0_339
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './diff'; export * from './run_single'; export * from './dedent'; export * from './jasmine'; export * from './test_run';
{ "end_byte": 339, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/testing/index.ts" }
angular/packages/core/schematics/utils/tsurge/executors/combine_exec.ts_0_691
/** * @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 {Serializable} from '../helpers/serializable'; import {TsurgeMigration} from '../migration'; /** * Executes the combine phase for the given migration against * two unit analyses. * * @returns the serializable combined unit data. */ export async function executeCombinePhase<UnitData, GlobalData>( migration: TsurgeMigration<UnitData, GlobalData>, unitA: UnitData, unitB: UnitData, ): Promise<Serializable<UnitData>> { return await migration.combine(unitA, unitB); }
{ "end_byte": 691, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/executors/combine_exec.ts" }
angular/packages/core/schematics/utils/tsurge/executors/analyze_exec.ts_0_810
/** * @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 {TsurgeMigration} from '../migration'; import {Serializable} from '../helpers/serializable'; /** * Executes the analyze phase of the given migration against * the specified TypeScript project. * * @returns the serializable migration unit data. */ export async function executeAnalyzePhase<UnitData, GlobalData>( migration: TsurgeMigration<UnitData, GlobalData>, tsconfigAbsolutePath: string, ): Promise<Serializable<UnitData>> { const baseInfo = migration.createProgram(tsconfigAbsolutePath); const info = migration.prepareProgram(baseInfo); return await migration.analyze(info); }
{ "end_byte": 810, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/executors/analyze_exec.ts" }
angular/packages/core/schematics/utils/tsurge/executors/migrate_exec.ts_0_1196
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {AbsoluteFsPath} from '@angular/compiler-cli/src/ngtsc/file_system'; import {TsurgeMigration} from '../migration'; import {Replacement} from '../replacement'; /** * Executes the migrate phase of the given migration against * the specified TypeScript project. * * This requires the global migration data, computed by the * analysis and merge phases of the migration. * * @returns a list of text replacements to apply to disk and the * absolute project directory path (to allow for applying). */ export async function executeMigratePhase<UnitData, GlobalData>( migration: TsurgeMigration<UnitData, GlobalData>, globalMetadata: GlobalData, tsconfigAbsolutePath: string, ): Promise<{replacements: Replacement[]; projectRoot: AbsoluteFsPath}> { const baseInfo = migration.createProgram(tsconfigAbsolutePath); const info = migration.prepareProgram(baseInfo); return { ...(await migration.migrate(globalMetadata, info)), projectRoot: info.projectRoot, }; }
{ "end_byte": 1196, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/executors/migrate_exec.ts" }
angular/packages/core/schematics/utils/tsurge/executors/global_meta_exec.ts_0_718
/** * @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 {Serializable} from '../helpers/serializable'; import {TsurgeMigration} from '../migration'; /** * Executes the `globalMeta` stage for the given migration * to convert the combined unit data into global meta. * * @returns the serializable global meta. */ export async function executeGlobalMetaPhase<UnitData, GlobalData>( migration: TsurgeMigration<UnitData, GlobalData>, combinedUnitData: UnitData, ): Promise<Serializable<GlobalData>> { return await migration.globalMeta(combinedUnitData); }
{ "end_byte": 718, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/executors/global_meta_exec.ts" }
angular/packages/core/schematics/utils/tsurge/beam_pipeline/read_units_blob.ts_0_1798
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as fs from 'fs'; import * as readline from 'readline'; import {TsurgeMigration} from '../migration'; /** * Integrating a `Tsurge` migration requires the "merging" of all * compilation unit data into a single "global migration data". * * This is achieved in a Beam pipeline by having a pipeline stage that * takes all compilation unit worker data and writing it into a single * buffer, delimited by new lines (`\n`). * * This "merged bytes files", containing all unit data, one per line, can * then be parsed by this function and fed into the migration merge logic. * * @returns All compilation unit data for the migration. */ export function readCompilationUnitBlob<UnitData, GlobalData>( _migrationForTypeSafety: TsurgeMigration<UnitData, GlobalData>, mergedUnitDataByteAbsFilePath: string, ): Promise<UnitData[]> { return new Promise((resolve, reject) => { const rl = readline.createInterface({ input: fs.createReadStream(mergedUnitDataByteAbsFilePath, 'utf8'), crlfDelay: Infinity, }); const unitData: UnitData[] = []; let failed = false; rl.on('line', (line) => { const trimmedLine = line.trim(); if (trimmedLine === '') { return; } try { const parsed = JSON.parse(trimmedLine) as UnitData; unitData.push(parsed); } catch (e) { failed = true; reject(new Error(`Could not parse data line: ${e} — ${trimmedLine}`)); rl.close(); } }); rl.on('close', async () => { if (!failed) { resolve(unitData); } }); }); }
{ "end_byte": 1798, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/beam_pipeline/read_units_blob.ts" }
angular/packages/core/schematics/utils/tsurge/helpers/apply_import_manager.ts_0_3371
/** * @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 {ImportManager} from '@angular/compiler-cli/src/ngtsc/translator'; import {absoluteFrom} from '@angular/compiler-cli/src/ngtsc/file_system'; import {Replacement, TextUpdate} from '../replacement'; import {projectFile} from '../project_paths'; import {ProgramInfo} from '../program_info'; /** * Applies import manager changes, and writes them as replacements the * given result array. */ export function applyImportManagerChanges( importManager: ImportManager, replacements: Replacement[], sourceFiles: readonly ts.SourceFile[], info: Pick<ProgramInfo, 'sortedRootDirs' | 'projectRoot'>, ) { const {newImports, updatedImports, deletedImports} = importManager.finalize(); const printer = ts.createPrinter({}); const pathToFile = new Map<string, ts.SourceFile>(sourceFiles.map((s) => [s.fileName, s])); // Capture new imports newImports.forEach((newImports, fileName) => { newImports.forEach((newImport) => { const printedImport = printer.printNode( ts.EmitHint.Unspecified, newImport, pathToFile.get(fileName)!, ); replacements.push( new Replacement( projectFile(absoluteFrom(fileName), info), new TextUpdate({position: 0, end: 0, toInsert: `${printedImport}\n`}), ), ); }); }); // Capture updated imports for (const [oldBindings, newBindings] of updatedImports.entries()) { // The import will be generated as multi-line if it already is multi-line, // or if the number of elements significantly increased and it previously // consisted of very few specifiers. const isMultiline = oldBindings.getText().includes('\n') || (newBindings.elements.length >= 6 && oldBindings.elements.length <= 3); const hasSpaceBetweenBraces = oldBindings.getText().startsWith('{ '); let formatFlags = ts.ListFormat.NamedImportsOrExportsElements | ts.ListFormat.Indented | ts.ListFormat.Braces | ts.ListFormat.PreserveLines | (isMultiline ? ts.ListFormat.MultiLine : ts.ListFormat.SingleLine); if (hasSpaceBetweenBraces) { formatFlags |= ts.ListFormat.SpaceBetweenBraces; } else { formatFlags &= ~ts.ListFormat.SpaceBetweenBraces; } const printedBindings = printer.printList( formatFlags, newBindings.elements, oldBindings.getSourceFile(), ); replacements.push( new Replacement( projectFile(oldBindings.getSourceFile(), info), new TextUpdate({ position: oldBindings.getStart(), end: oldBindings.getEnd(), // TS uses four spaces as indent. We migrate to two spaces as we // assume this to be more common. toInsert: printedBindings.replace(/^ {4}/gm, ' '), }), ), ); } // Update removed imports for (const removedImport of deletedImports) { replacements.push( new Replacement( projectFile(removedImport.getSourceFile(), info), new TextUpdate({ position: removedImport.getStart(), end: removedImport.getEnd(), toInsert: '', }), ), ); } }
{ "end_byte": 3371, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/helpers/apply_import_manager.ts" }
angular/packages/core/schematics/utils/tsurge/helpers/group_replacements.ts_0_949
/** * @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 {Replacement, TextUpdate} from '../replacement'; import {ProjectRootRelativePath} from '../project_paths'; /** * Groups the given replacements per project relative * file path. * * This allows for simple execution of the replacements * against a given file. E.g. via {@link applyTextUpdates}. */ export function groupReplacementsByFile( replacements: Replacement[], ): Map<ProjectRootRelativePath, TextUpdate[]> { const result = new Map<ProjectRootRelativePath, TextUpdate[]>(); for (const {projectFile, update} of replacements) { if (!result.has(projectFile.rootRelativePath)) { result.set(projectFile.rootRelativePath, []); } result.get(projectFile.rootRelativePath)!.push(update); } return result; }
{ "end_byte": 949, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/helpers/group_replacements.ts" }
angular/packages/core/schematics/utils/tsurge/helpers/combine_units.ts_0_989
/** * @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 {TsurgeMigration} from '../migration'; /** * Synchronously combines unit data for the given migration. * * Note: This helper is useful for testing and execution of * Tsurge migrations in non-batchable environments. In general, * prefer parallel execution of combining via e.g. Beam combiners. */ export async function synchronouslyCombineUnitData<UnitData>( migration: TsurgeMigration<UnitData, unknown>, unitDatas: UnitData[], ): Promise<UnitData | null> { if (unitDatas.length === 0) { return null; } if (unitDatas.length === 1) { return unitDatas[0]; } let combined = unitDatas[0]; for (let i = 1; i < unitDatas.length; i++) { const other = unitDatas[i]; combined = await migration.combine(combined, other); } return combined; }
{ "end_byte": 989, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/helpers/combine_units.ts" }
angular/packages/core/schematics/utils/tsurge/helpers/serializable.ts_0_497
/** * @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 */ /** Branded type indicating that the given data `T` is serializable. */ export type Serializable<T> = T & {__serializable: true}; /** Confirms that the given data `T` is serializable. */ export function confirmAsSerializable<T>(data: T): Serializable<T> { return data as Serializable<T>; }
{ "end_byte": 497, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/helpers/serializable.ts" }
angular/packages/core/schematics/utils/tsurge/helpers/unique_id.ts_0_767
/** * @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 */ /** * Helper type for creating unique branded IDs. * * Unique IDs are a fundamental piece for a `Tsurge` migration because * they allow for serializable analysis data between the stages. * * This is important to e.g. uniquely identify an Angular input across * compilation units, so that shared global data can be built via * the `merge` phase. * * E.g. a unique ID for an input may be the project-relative file path, * in combination with the name of its owning class, plus the field name. */ export type UniqueID<Name> = string & {__branded: Name};
{ "end_byte": 767, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/helpers/unique_id.ts" }
angular/packages/core/schematics/utils/tsurge/helpers/ngtsc_program.ts_0_2182
/** * @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 {readConfiguration} from '@angular/compiler-cli/src/perform_compile'; import {NgCompilerOptions} from '@angular/compiler-cli/src/ngtsc/core/api'; import { FileSystem, NgtscCompilerHost, NodeJSFileSystem, setFileSystem, } from '@angular/compiler-cli/src/ngtsc/file_system'; import {NgtscProgram} from '@angular/compiler-cli/src/ngtsc/program'; import {BaseProgramInfo} from '../program_info'; /** Code of the error raised by TypeScript when a tsconfig doesn't match any files. */ const NO_INPUTS_ERROR_CODE = 18003; /** * Parses the configuration of the given TypeScript project and creates * an instance of the Angular compiler for the project. */ export function createNgtscProgram( absoluteTsconfigPath: string, fs?: FileSystem, optionOverrides: NgCompilerOptions = {}, ): BaseProgramInfo { if (fs === undefined) { fs = new NodeJSFileSystem(); setFileSystem(fs); } const tsconfig = readConfiguration(absoluteTsconfigPath, {}, fs); // Skip the "No inputs found..." error since we don't want to interrupt the migration if a // tsconfig doesn't match a file. This will result in an empty `Program` which is still valid. const errors = tsconfig.errors.filter((diag) => diag.code !== NO_INPUTS_ERROR_CODE); if (errors.length) { throw new Error( `Tsconfig could not be parsed or is invalid:\n\n` + `${errors.map((e) => e.messageText)}`, ); } const tsHost = new NgtscCompilerHost(fs, tsconfig.options); const ngtscProgram = new NgtscProgram( tsconfig.rootNames, { ...tsconfig.options, // Avoid checking libraries to speed up migrations. skipLibCheck: true, skipDefaultLibCheck: true, // Additional override options. ...optionOverrides, }, tsHost, ); return { ngCompiler: ngtscProgram.compiler, program: ngtscProgram.getTsProgram(), userOptions: tsconfig.options, programAbsoluteRootFileNames: tsconfig.rootNames, host: tsHost, }; }
{ "end_byte": 2182, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/helpers/ngtsc_program.ts" }
angular/packages/core/schematics/utils/tsurge/helpers/string_manipulation/cut_string_line_length.ts_0_1047
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Cuts the given string into lines basing around the specified * line length limit. This function breaks the string on a per-word basis. */ export function cutStringToLineLimit(str: string, limit: number): string[] { const words = str.split(' '); const chunks: string[] = []; let chunkIdx = 0; while (words.length) { // New line if we exceed limit. if (chunks[chunkIdx] !== undefined && chunks[chunkIdx].length > limit) { chunkIdx++; } // Ensure line is initialized for the given index. if (chunks[chunkIdx] === undefined) { chunks[chunkIdx] = ''; } const word = words.shift(); const needsSpace = chunks[chunkIdx].length > 0; // Insert word. Add space before, if the line already contains text. chunks[chunkIdx] += `${needsSpace ? ' ' : ''}${word}`; } return chunks; }
{ "end_byte": 1047, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/helpers/string_manipulation/cut_string_line_length.ts" }
angular/packages/core/schematics/utils/tsurge/helpers/ast/leading_space.ts_0_915
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import ts from 'typescript'; /** * Gets the leading line whitespace of a given node. * * Useful for inserting e.g. TODOs without breaking indentation. */ export function getLeadingLineWhitespaceOfNode(node: ts.Node): string { const fullText = node.getFullText().substring(0, node.getStart() - node.getFullStart()); let result = ''; for (let i = fullText.length - 1; i > -1; i--) { // Note: LF line endings are `\n` while CRLF are `\r\n`. This logic should cover both, because // we start from the beginning of the node and go backwards so will always hit `\n` first. if (fullText[i] !== '\n') { result = fullText[i] + result; } else { break; } } return result; }
{ "end_byte": 915, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/helpers/ast/leading_space.ts" }
angular/packages/core/schematics/utils/tsurge/helpers/ast/BUILD.bazel_0_849
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//packages/core/schematics/utils/tsurge:users"]) ts_library( name = "ast", srcs = glob(["**/*.ts"]), deps = [ "//packages/compiler", "//packages/compiler-cli/src/ngtsc/annotations", "//packages/compiler-cli/src/ngtsc/annotations/common", "//packages/compiler-cli/src/ngtsc/annotations/component", "//packages/compiler-cli/src/ngtsc/core:api", "//packages/compiler-cli/src/ngtsc/file_system", "//packages/compiler-cli/src/ngtsc/partial_evaluator", "//packages/compiler-cli/src/ngtsc/reflection", "//packages/compiler-cli/src/ngtsc/transform", "//packages/compiler-cli/src/ngtsc/typecheck/api", "//packages/core/schematics/utils/tsurge", "@npm//typescript", ], )
{ "end_byte": 849, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/helpers/ast/BUILD.bazel" }
angular/packages/core/schematics/utils/tsurge/helpers/ast/insert_preceding_line.ts_0_967
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import ts from 'typescript'; import {Replacement, TextUpdate} from '../../replacement'; import {getLeadingLineWhitespaceOfNode} from './leading_space'; import {ProgramInfo} from '../../program_info'; import {projectFile} from '../../project_paths'; /** * Inserts a leading string for the given node, respecting * indentation of the given anchor node. * * Useful for inserting TODOs. */ export function insertPrecedingLine(node: ts.Node, info: ProgramInfo, text: string): Replacement { const leadingSpace = getLeadingLineWhitespaceOfNode(node); return new Replacement( projectFile(node.getSourceFile(), info), new TextUpdate({ position: node.getStart(), end: node.getStart(), toInsert: `${text}\n${leadingSpace}`, }), ); }
{ "end_byte": 967, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/helpers/ast/insert_preceding_line.ts" }
angular/packages/core/schematics/utils/tsurge/helpers/ast/lookup_property_access.ts_0_1548
/** * @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'; /** * Attempts to look up the given property access chain using * the type checker. * * Notably this is not as safe as using the type checker directly to * retrieve symbols of a given identifier, but in some cases this is * a necessary approach to compensate e.g. for a lack of TCB information * when processing Angular templates. * * The path is a list of properties to be accessed sequentially on the * given type. */ export function lookupPropertyAccess( checker: ts.TypeChecker, type: ts.Type, path: string[], options: {ignoreNullability?: boolean} = {}, ): {symbol: ts.Symbol; type: ts.Type} | null { let symbol: ts.Symbol | null = null; for (const propName of path) { // Note: We support assuming `NonNullable` for the pathl This is necessary // in some situations as otherwise the lookups would fail to resolve the target // symbol just because of e.g. a ternary. This is used in the signal input migration // for host bindings. type = options.ignoreNullability ? type.getNonNullableType() : type; const propSymbol = type.getProperty(propName); if (propSymbol === undefined) { return null; } symbol = propSymbol; type = checker.getTypeOfSymbol(propSymbol); } if (symbol === null) { return null; } return {symbol, type}; }
{ "end_byte": 1548, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/helpers/ast/lookup_property_access.ts" }
angular/packages/core/schematics/utils/tsurge/helpers/angular_devkit/devkit_filesystem.ts_0_5700
/** * @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 { normalize, join, extname, relative, dirname, Path as DevkitAbsPath, PathFragment as DevkitPathFragment, } from '@angular-devkit/core'; import {DirEntry, FileEntry, Tree} from '@angular-devkit/schematics'; import { AbsoluteFsPath, FileStats, FileSystem, PathSegment, PathString, } from '@angular/compiler-cli/src/ngtsc/file_system'; import * as posixPath from 'node:path/posix'; /** * Angular compiler file system implementation that leverages an * CLI schematic virtual file tree. */ export class DevkitMigrationFilesystem implements FileSystem { constructor(private readonly tree: Tree) {} extname(path: AbsoluteFsPath | PathSegment): string { return extname(path as string as DevkitAbsPath | DevkitPathFragment); } isRoot(path: AbsoluteFsPath): boolean { return (path as string as DevkitAbsPath) === normalize('/'); } isRooted(path: string): boolean { return this.normalize(path).startsWith('/'); } dirname<T extends PathString>(file: T): T { return this.normalize(dirname(file as DevkitAbsPath | DevkitPathFragment)) as string as T; } join<T extends PathString>(basePath: T, ...paths: string[]): T { return this.normalize( join(basePath as DevkitAbsPath | DevkitPathFragment, ...paths), ) as string as T; } relative<T extends PathString>(from: T, to: T): PathSegment | AbsoluteFsPath { return this.normalize( relative( from as DevkitAbsPath | DevkitPathFragment, to as DevkitAbsPath | DevkitPathFragment, ), ) as string as PathSegment | AbsoluteFsPath; } basename(filePath: string, extension?: string): PathSegment { return posixPath.basename(filePath, extension) as PathSegment; } normalize<T extends PathString>(path: T): T { return normalize(path as string) as string as T; } resolve(...paths: string[]): AbsoluteFsPath { const normalizedPaths = paths.map((p) => normalize(p)); // In dev-kit, the NodeJS working directory should never be // considered, so `/` is the last resort over `cwd`. return this.normalize( posixPath.resolve(normalize('/'), ...normalizedPaths), ) as string as AbsoluteFsPath; } pwd(): AbsoluteFsPath { return '/' as AbsoluteFsPath; } isCaseSensitive(): boolean { return true; } exists(path: AbsoluteFsPath): boolean { return statPath(this.tree, path) !== null; } readFile(path: AbsoluteFsPath): string { return this.tree.readText(path); } readFileBuffer(path: AbsoluteFsPath): Uint8Array { const buffer = this.tree.read(path); if (buffer === null) { throw new Error(`File does not exist: ${path}`); } return buffer; } readdir(path: AbsoluteFsPath): PathSegment[] { const dir = this.tree.getDir(path); return [ ...(dir.subdirs as string[] as PathSegment[]), ...(dir.subfiles as string[] as PathSegment[]), ]; } lstat(path: AbsoluteFsPath): FileStats { const stat = statPath(this.tree, path); if (stat === null) { throw new Error(`File does not exist for "lstat": ${path}`); } return stat; } stat(path: AbsoluteFsPath): FileStats { const stat = statPath(this.tree, path); if (stat === null) { throw new Error(`File does not exist for "stat": ${path}`); } return stat; } realpath(filePath: AbsoluteFsPath): AbsoluteFsPath { return filePath; } getDefaultLibLocation(): AbsoluteFsPath { return 'node_modules/typescript/lib' as AbsoluteFsPath; } ensureDir(path: AbsoluteFsPath): void { // Migrations should compute replacements and not write directly. throw new Error('DevkitFilesystem#ensureDir is not supported.'); } writeFile(path: AbsoluteFsPath, data: string | Uint8Array): void { // Migrations should compute replacements and not write directly. throw new Error('DevkitFilesystem#writeFile is not supported.'); } removeFile(path: AbsoluteFsPath): void { // Migrations should compute replacements and not write directly. throw new Error('DevkitFilesystem#removeFile is not supported.'); } copyFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void { // Migrations should compute replacements and not write directly. throw new Error('DevkitFilesystem#copyFile is not supported.'); } moveFile(from: AbsoluteFsPath, to: AbsoluteFsPath): void { // Migrations should compute replacements and not write directly. throw new Error('DevkitFilesystem#moveFile is not supported.'); } removeDeep(path: AbsoluteFsPath): void { // Migrations should compute replacements and not write directly. throw new Error('DevkitFilesystem#removeDeep is not supported.'); } chdir(_path: AbsoluteFsPath): void { throw new Error('FileSystem#chdir is not supported.'); } symlink(): void { throw new Error('FileSystem#symlink is not supported.'); } } /** Stats the given path in the virtual tree. */ function statPath(tree: Tree, path: AbsoluteFsPath): FileStats | null { let fileInfo: FileEntry | null = null; let dirInfo: DirEntry | null = null; try { fileInfo = tree.get(path); } catch (e) { if ((e as any).constructor.name === 'PathIsDirectoryException') { dirInfo = tree.getDir(path); } else { throw e; } } if (fileInfo !== null || dirInfo !== null) { return { isDirectory: () => dirInfo !== null, isFile: () => fileInfo !== null, isSymbolicLink: () => false, }; } return null; }
{ "end_byte": 5700, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/helpers/angular_devkit/devkit_filesystem.ts" }
angular/packages/core/schematics/utils/tsurge/helpers/angular_devkit/BUILD.bazel_0_395
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//packages/core/schematics/ng-generate:__subpackages__"]) ts_library( name = "angular_devkit", srcs = glob(["**/*.ts"]), deps = [ "//packages/compiler-cli/src/ngtsc/file_system", "@npm//@angular-devkit/core", "@npm//@angular-devkit/schematics", "@npm//@types/node", ], )
{ "end_byte": 395, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/utils/tsurge/helpers/angular_devkit/BUILD.bazel" }
angular/packages/core/schematics/ng-generate/route-lazy-loading/to-lazy-routes.ts_0_9221
/*! * @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 {ChangeTracker, PendingChange} from '../../utils/change_tracker'; import {findClassDeclaration} from '../../utils/typescript/class_declaration'; import {findLiteralProperty} from '../../utils/typescript/property_name'; import { isAngularRoutesArray, isProvideRoutesCallExpression, isRouterCallExpression, isRouterModuleCallExpression, isRouterProviderCallExpression, isStandaloneComponent, } from './util'; interface RouteData { routeFilePath: string; routeFileImports: ts.ImportDeclaration[]; array: ts.ArrayLiteralExpression; } export interface RouteMigrationData { path: string; file: string; } /** * Converts all application routes that are using standalone components to be lazy loaded. * @param sourceFile File that should be migrated. * @param program */ export function migrateFileToLazyRoutes( sourceFile: ts.SourceFile, program: ts.Program, ): { pendingChanges: PendingChange[]; migratedRoutes: RouteMigrationData[]; skippedRoutes: RouteMigrationData[]; } { const typeChecker = program.getTypeChecker(); const printer = ts.createPrinter(); const tracker = new ChangeTracker(printer); const routeArraysToMigrate = findRoutesArrayToMigrate(sourceFile, typeChecker); if (routeArraysToMigrate.length === 0) { return {pendingChanges: [], skippedRoutes: [], migratedRoutes: []}; } const {skippedRoutes, migratedRoutes} = migrateRoutesArray( routeArraysToMigrate, typeChecker, tracker, ); return { pendingChanges: tracker.recordChanges().get(sourceFile) || [], skippedRoutes, migratedRoutes, }; } /** Finds route object that can be migrated */ function findRoutesArrayToMigrate(sourceFile: ts.SourceFile, typeChecker: ts.TypeChecker) { const routesArrays: RouteData[] = []; sourceFile.forEachChild(function walk(node) { if (ts.isCallExpression(node)) { if ( isRouterModuleCallExpression(node, typeChecker) || isRouterProviderCallExpression(node, typeChecker) || isRouterCallExpression(node, typeChecker) || isProvideRoutesCallExpression(node, typeChecker) ) { const arg = node.arguments[0]; // ex: RouterModule.forRoot(routes) or provideRouter(routes) const routeFileImports = sourceFile.statements.filter(ts.isImportDeclaration); if (ts.isArrayLiteralExpression(arg) && arg.elements.length > 0) { // ex: inline routes array: RouterModule.forRoot([{ path: 'test', component: TestComponent }]) routesArrays.push({ routeFilePath: sourceFile.fileName, array: arg as ts.ArrayLiteralExpression, routeFileImports, }); } else if (ts.isIdentifier(arg)) { // ex: reference to routes array: RouterModule.forRoot(routes) // RouterModule.forRoot(routes), provideRouter(routes), provideRoutes(routes) const symbol = typeChecker.getSymbolAtLocation(arg); if (!symbol?.declarations) return; for (const declaration of symbol.declarations) { if (ts.isVariableDeclaration(declaration)) { const initializer = declaration.initializer; if (initializer && ts.isArrayLiteralExpression(initializer)) { // ex: const routes = [{ path: 'test', component: TestComponent }]; routesArrays.push({ routeFilePath: sourceFile.fileName, array: initializer, routeFileImports, }); } } } } } } if (ts.isVariableDeclaration(node)) { if (isAngularRoutesArray(node, typeChecker)) { const initializer = node.initializer; if ( initializer && ts.isArrayLiteralExpression(initializer) && initializer.elements.length > 0 ) { // ex: const routes: Routes = [{ path: 'test', component: TestComponent }]; if (routesArrays.find((x) => x.array === initializer)) { // already exists return; } routesArrays.push({ routeFilePath: sourceFile.fileName, array: initializer, routeFileImports: sourceFile.statements.filter(ts.isImportDeclaration), }); } } } node.forEachChild(walk); }); return routesArrays; } /** Migrate a routes object standalone components to be lazy loaded. */ function migrateRoutesArray( routesArray: RouteData[], typeChecker: ts.TypeChecker, tracker: ChangeTracker, ): {migratedRoutes: RouteMigrationData[]; skippedRoutes: RouteMigrationData[]} { const migratedRoutes: RouteMigrationData[] = []; const skippedRoutes: RouteMigrationData[] = []; const importsToRemove: ts.ImportDeclaration[] = []; for (const route of routesArray) { route.array.elements.forEach((element) => { if (ts.isObjectLiteralExpression(element)) { const { migratedRoutes: migrated, skippedRoutes: toBeSkipped, importsToRemove: toBeRemoved, } = migrateRoute(element, route, typeChecker, tracker); migratedRoutes.push(...migrated); skippedRoutes.push(...toBeSkipped); importsToRemove.push(...toBeRemoved); } }); } for (const importToRemove of importsToRemove) { tracker.removeNode(importToRemove); } return {migratedRoutes, skippedRoutes}; } /** * Migrates a single route object and returns the results of the migration * It recursively migrates the children routes if they exist */ function migrateRoute( element: ts.ObjectLiteralExpression, route: RouteData, typeChecker: ts.TypeChecker, tracker: ChangeTracker, ): { migratedRoutes: RouteMigrationData[]; skippedRoutes: RouteMigrationData[]; importsToRemove: ts.ImportDeclaration[]; } { const skippedRoutes: RouteMigrationData[] = []; const migratedRoutes: RouteMigrationData[] = []; const importsToRemove: ts.ImportDeclaration[] = []; const component = findLiteralProperty(element, 'component'); // this can be empty string or a variable that is not a string, or not present at all const routePath = findLiteralProperty(element, 'path')?.getText() ?? ''; const children = findLiteralProperty(element, 'children') as ts.PropertyAssignment | undefined; // recursively migrate children routes first if they exist if (children && ts.isArrayLiteralExpression(children.initializer)) { for (const childRoute of children.initializer.elements) { if (ts.isObjectLiteralExpression(childRoute)) { const { migratedRoutes: migrated, skippedRoutes: toBeSkipped, importsToRemove: toBeRemoved, } = migrateRoute(childRoute, route, typeChecker, tracker); migratedRoutes.push(...migrated); skippedRoutes.push(...toBeSkipped); importsToRemove.push(...toBeRemoved); } } } const routeMigrationResults = {migratedRoutes, skippedRoutes, importsToRemove}; if (!component) { return routeMigrationResults; } const componentDeclaration = findClassDeclaration(component, typeChecker); if (!componentDeclaration) { return routeMigrationResults; } // if component is not a standalone component, skip it if (!isStandaloneComponent(componentDeclaration)) { skippedRoutes.push({path: routePath, file: route.routeFilePath}); return routeMigrationResults; } const componentClassName = componentDeclaration.name && ts.isIdentifier(componentDeclaration.name) ? componentDeclaration.name.text : null; if (!componentClassName) { return routeMigrationResults; } // if component is in the same file as the routes array, skip it if (componentDeclaration.getSourceFile().fileName === route.routeFilePath) { return routeMigrationResults; } const componentImport = route.routeFileImports.find((importDecl) => importDecl.importClause?.getText().includes(componentClassName), )!; // remove single and double quotes from the import path let componentImportPath = ts.isStringLiteral(componentImport?.moduleSpecifier) ? componentImport.moduleSpecifier.text : null; // if the import path is not a string literal, skip it if (!componentImportPath) { skippedRoutes.push({path: routePath, file: route.routeFilePath}); return routeMigrationResults; } const isDefaultExport = componentDeclaration.modifiers?.some((x) => x.kind === ts.SyntaxKind.DefaultKeyword) ?? false; const loadComponent = createLoadComponentPropertyAssignment( componentImportPath, componentClassName, isDefaultExport, ); tracker.replaceNode(component, loadComponent); // Add the import statement for the standalone component if (!importsToRemove.includes(componentImport)) { importsToRemove.push(componentImport); } migratedRoutes.push({path: routePath, file: route.routeFilePath}); // the component was migrated, so we return the results return routeMigrationResults; }
{ "end_byte": 9221, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/route-lazy-loading/to-lazy-routes.ts" }
angular/packages/core/schematics/ng-generate/route-lazy-loading/to-lazy-routes.ts_9223_11095
/** * Generates the loadComponent property assignment for a given component. * * Example: * loadComponent: () => import('./path').then(m => m.componentName) * or * loadComponent: () => import('./path') // when isDefaultExport is true */ function createLoadComponentPropertyAssignment( componentImportPath: string, componentDeclarationName: string, isDefaultExport: boolean, ) { return ts.factory.createPropertyAssignment( 'loadComponent', ts.factory.createArrowFunction( undefined, undefined, [], undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), isDefaultExport ? createImportCallExpression(componentImportPath) // will generate import('./path) and will skip the then() call : ts.factory.createCallExpression( // will generate import('./path).then(m => m.componentName) ts.factory.createPropertyAccessExpression( createImportCallExpression(componentImportPath), 'then', ), undefined, [createImportThenCallExpression(componentDeclarationName)], ), ), ); } // import('./path) const createImportCallExpression = (componentImportPath: string) => ts.factory.createCallExpression(ts.factory.createIdentifier('import'), undefined, [ ts.factory.createStringLiteral(componentImportPath, true), ]); // m => m.componentName const createImportThenCallExpression = (componentDeclarationName: string) => ts.factory.createArrowFunction( undefined, undefined, [ts.factory.createParameterDeclaration(undefined, undefined, 'm', undefined, undefined)], undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), ts.factory.createPropertyAccessExpression( ts.factory.createIdentifier('m'), componentDeclarationName, ), );
{ "end_byte": 11095, "start_byte": 9223, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/route-lazy-loading/to-lazy-routes.ts" }
angular/packages/core/schematics/ng-generate/route-lazy-loading/README.md_0_2298
# Route lazy loading migration This schematic helps developers to convert eagerly loaded component routes to lazy loaded routes. By lazy loading components we can split the production bundle into smaller chunks, to avoid big JS bundle that includes all routes, which negatively affects initial page load of an application. ## How to run this migration? The migration can be run using the following command: ```bash ng generate @angular/core:route-lazy-loading ``` By default, migration will go over the entire application. If you want to apply this migration to a subset of the files, you can pass the path argument as shown below: ```bash ng generate @angular/core:route-lazy-loading --path src/app/sub-component ``` The value of the path parameter is a relative path within the project. ### How does it work? The schematic will attempt to find all the places where the application routes as defined: - `RouterModule.forRoot` and `RouterModule.forChild` - `Router.resetConfig` - `provideRouter` - `provideRoutes` - variables of type `Routes` or `Route[]` (e.g. `const routes: Routes = [{...}]`) The migration will check all the components in the routes, check if they are standalone and eagerly loaded, and if so, it will convert them to lazy loaded routes. **Before:** ```typescript // app.module.ts import { HomeComponent } from './home/home.component'; @NgModule({ imports: [ RouterModule.forRoot([ { path: 'home', component: HomeComponent, // HomeComponent is standalone and eagerly loaded }, ]), ], }) export class AppModule {} ``` **After:** ```typescript // app.module.ts @NgModule({ imports: [ RouterModule.forRoot([ { path: 'home', // ↓ HomeComponent is now lazy loaded loadComponent: () => import('./home/home.component').then(m => m.HomeComponent), }, ]), ], }) export class AppModule {} ``` > This migration will also collect information about all the components declared in NgModules and output the list of routes that use them (including corresponding location of the file). Consider making those components standalone and run this migration again. You can use an existing migration (see https://angular.dev/reference/migrations/standalone) to convert those components to standalone.
{ "end_byte": 2298, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/route-lazy-loading/README.md" }
angular/packages/core/schematics/ng-generate/route-lazy-loading/util.ts_0_3971
/*! * @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 {findLiteralProperty} from '../../utils/typescript/property_name'; /** * Checks whether a component is standalone. * @param node Class being checked. */ export function isStandaloneComponent(node: ts.ClassDeclaration): boolean { const decorator = node.modifiers?.find((m) => m.kind === ts.SyntaxKind.Decorator); if (!decorator) { return false; } if (ts.isCallExpression(decorator.expression)) { const arg = decorator.expression.arguments[0]; if (ts.isObjectLiteralExpression(arg)) { const property = findLiteralProperty(arg, 'standalone') as ts.PropertyAssignment; return property ? property.initializer.getText() === 'true' : false; } } return false; } /** * Checks whether a node is variable declaration of type Routes or Route[] and comes from @angular/router * @param node Variable declaration being checked. * @param typeChecker */ export function isAngularRoutesArray(node: ts.Node, typeChecker: ts.TypeChecker) { if (ts.isVariableDeclaration(node)) { const type = typeChecker.getTypeAtLocation(node); if (type && typeChecker.isArrayType(type)) { // Route[] is an array type const typeArguments = typeChecker.getTypeArguments(type as ts.TypeReference); const symbol = typeArguments[0]?.getSymbol(); return ( symbol?.name === 'Route' && symbol?.declarations?.some((decl) => { return decl.getSourceFile().fileName.includes('@angular/router'); }) ); } } return false; } /** * Checks whether a node is a call expression to a router module method. * Examples: * - RouterModule.forRoot(routes) * - RouterModule.forChild(routes) */ export function isRouterModuleCallExpression(node: ts.CallExpression, typeChecker: ts.TypeChecker) { if (ts.isPropertyAccessExpression(node.expression)) { const propAccess = node.expression; const moduleSymbol = typeChecker.getSymbolAtLocation(propAccess.expression); return ( moduleSymbol?.name === 'RouterModule' && (propAccess.name.text === 'forRoot' || propAccess.name.text === 'forChild') ); } return false; } /** * Checks whether a node is a call expression to a router method. * Example: this.router.resetConfig(routes) */ export function isRouterCallExpression(node: ts.CallExpression, typeChecker: ts.TypeChecker) { if ( ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === 'resetConfig' ) { const calleeExpression = node.expression.expression; const symbol = typeChecker.getSymbolAtLocation(calleeExpression); if (symbol) { const type = typeChecker.getTypeOfSymbolAtLocation(symbol, calleeExpression); // if type of router is Router, then it is a router call expression return type.aliasSymbol?.escapedName === 'Router'; } } return false; } /** * Checks whether a node is a call expression to router provide function. * Example: provideRoutes(routes) */ export function isRouterProviderCallExpression( node: ts.CallExpression, typeChecker: ts.TypeChecker, ) { if (ts.isIdentifier(node.expression)) { const moduleSymbol = typeChecker.getSymbolAtLocation(node.expression); return moduleSymbol && moduleSymbol.name === 'provideRoutes'; } return false; } /** * Checks whether a node is a call expression to provideRouter function. * Example: provideRouter(routes) */ export function isProvideRoutesCallExpression( node: ts.CallExpression, typeChecker: ts.TypeChecker, ) { if (ts.isIdentifier(node.expression)) { const moduleSymbol = typeChecker.getSymbolAtLocation(node.expression); return moduleSymbol && moduleSymbol.name === 'provideRouter'; } return false; }
{ "end_byte": 3971, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/route-lazy-loading/util.ts" }
angular/packages/core/schematics/ng-generate/route-lazy-loading/BUILD.bazel_0_700
load("//tools:defaults.bzl", "ts_library") package( default_visibility = [ "//packages/core/schematics:__pkg__", "//packages/core/schematics/migrations/google3:__pkg__", "//packages/core/schematics/test:__pkg__", ], ) filegroup( name = "static_files", srcs = ["schema.json"], ) ts_library( name = "route-lazy-loading", srcs = glob(["**/*.ts"]), tsconfig = "//packages/core/schematics:tsconfig.json", deps = [ "//packages/compiler-cli", "//packages/compiler-cli/private", "//packages/core/schematics/utils", "@npm//@angular-devkit/schematics", "@npm//@types/node", "@npm//typescript", ], )
{ "end_byte": 700, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/route-lazy-loading/BUILD.bazel" }
angular/packages/core/schematics/ng-generate/route-lazy-loading/index.ts_0_4762
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Rule, SchematicsException, Tree} from '@angular-devkit/schematics'; import {existsSync, statSync} from 'fs'; import {join, relative} from 'path'; import {normalizePath} from '../../utils/change_tracker'; import {getProjectTsConfigPaths} from '../../utils/project_tsconfig_paths'; import {canMigrateFile, createMigrationProgram} from '../../utils/typescript/compiler_host'; import {RouteMigrationData, migrateFileToLazyRoutes} from './to-lazy-routes'; interface Options { path: string; } export function migrate(options: Options): Rule { return async (tree, context) => { const {buildPaths} = await getProjectTsConfigPaths(tree); const basePath = process.cwd(); // TS and Schematic use paths in POSIX format even on Windows. This is needed as otherwise // string matching such as `sourceFile.fileName.startsWith(pathToMigrate)` might not work. const pathToMigrate = normalizePath(join(basePath, options.path)); if (!buildPaths.length) { throw new SchematicsException( 'Could not find any tsconfig file. Cannot run the route lazy loading migration.', ); } let migratedRoutes: RouteMigrationData[] = []; let skippedRoutes: RouteMigrationData[] = []; for (const tsconfigPath of buildPaths) { const {migratedRoutes: migrated, skippedRoutes: skipped} = standaloneRoutesMigration( tree, tsconfigPath, basePath, pathToMigrate, options, ); migratedRoutes.push(...migrated); skippedRoutes.push(...skipped); } if (migratedRoutes.length === 0 && skippedRoutes.length === 0) { throw new SchematicsException( `Could not find any files to migrate under the path ${pathToMigrate}.`, ); } context.logger.info('🎉 Automated migration step has finished! 🎉'); context.logger.info(`Number of updated routes: ${migratedRoutes.length}`); context.logger.info(`Number of skipped routes: ${skippedRoutes.length}`); if (skippedRoutes.length > 0) { context.logger.info( `Note: this migration was unable to optimize the following routes, since they use components declared in NgModules:`, ); for (const route of skippedRoutes) { context.logger.info(`- \`${route.path}\` path at \`${route.file}\``); } context.logger.info( `Consider making those components standalone and run this migration again. More information about standalone migration can be found at https://angular.dev/reference/migrations/standalone`, ); } context.logger.info( 'IMPORTANT! Please verify manually that your application builds and behaves as expected.', ); context.logger.info( `See https://angular.dev/reference/migrations/route-lazy-loading for more information.`, ); }; } function standaloneRoutesMigration( tree: Tree, tsconfigPath: string, basePath: string, pathToMigrate: string, schematicOptions: Options, ): {migratedRoutes: RouteMigrationData[]; skippedRoutes: RouteMigrationData[]} { if (schematicOptions.path.startsWith('..')) { throw new SchematicsException( 'Cannot run route lazy loading migration outside of the current project.', ); } if (existsSync(pathToMigrate) && !statSync(pathToMigrate).isDirectory()) { throw new SchematicsException( `Migration path ${pathToMigrate} has to be a directory. Cannot run the route lazy loading migration.`, ); } const program = createMigrationProgram(tree, tsconfigPath, basePath); const sourceFiles = program .getSourceFiles() .filter( (sourceFile) => sourceFile.fileName.startsWith(pathToMigrate) && canMigrateFile(basePath, sourceFile, program), ); const migratedRoutes: RouteMigrationData[] = []; const skippedRoutes: RouteMigrationData[] = []; if (sourceFiles.length === 0) { return {migratedRoutes, skippedRoutes}; } for (const sourceFile of sourceFiles) { const { pendingChanges, skippedRoutes: skipped, migratedRoutes: migrated, } = migrateFileToLazyRoutes(sourceFile, program); skippedRoutes.push(...skipped); migratedRoutes.push(...migrated); const update = tree.beginUpdate(relative(basePath, sourceFile.fileName)); pendingChanges.forEach((change) => { if (change.removeLength != null) { update.remove(change.start, change.removeLength); } update.insertRight(change.start, change.text); }); tree.commitUpdate(update); } return {migratedRoutes, skippedRoutes}; }
{ "end_byte": 4762, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/route-lazy-loading/index.ts" }
angular/packages/core/schematics/ng-generate/inject-migration/migration.ts_0_4677
/** * @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 {PendingChange, ChangeTracker} from '../../utils/change_tracker'; import { analyzeFile, getSuperParameters, getConstructorUnusedParameters, hasGenerics, isNullableType, parameterDeclaresProperty, DI_PARAM_SYMBOLS, } from './analysis'; import {getAngularDecorators} from '../../utils/ng_decorators'; import {getImportOfIdentifier} from '../../utils/typescript/imports'; import {closestNode} from '../../utils/typescript/nodes'; import {findUninitializedPropertiesToCombine} from './internal'; import {getLeadingLineWhitespaceOfNode} from '../../utils/tsurge/helpers/ast/leading_space'; /** * Placeholder used to represent expressions inside the AST. * Includes Unicode characters to reduce the chance of collisions. */ const PLACEHOLDER = 'ɵɵngGeneratePlaceholderɵɵ'; /** Options that can be used to configure the migration. */ export interface MigrationOptions { /** Whether to generate code that keeps injectors backwards compatible. */ backwardsCompatibleConstructors?: boolean; /** Whether to migrate abstract classes. */ migrateAbstractClasses?: boolean; /** Whether to make the return type of `@Optinal()` parameters to be non-nullable. */ nonNullableOptional?: boolean; /** * Internal-only option that determines whether the migration should try to move the * initializers of class members from the constructor back into the member itself. E.g. * * ``` * // Before * private foo; * * constructor(@Inject(BAR) private bar: Bar) { * this.foo = this.bar.getValue(); * } * * // After * private bar = inject(BAR); * private foo = this.bar.getValue(); * ``` */ _internalCombineMemberInitializers?: boolean; } /** * Migrates all of the classes in a `SourceFile` away from constructor injection. * @param sourceFile File to be migrated. * @param options Options that configure the migration. */ export function migrateFile(sourceFile: ts.SourceFile, options: MigrationOptions): PendingChange[] { // Note: even though externally we have access to the full program with a proper type // checker, we create a new one that is local to the file for a couple of reasons: // 1. Not having to depend on a program makes running the migration internally faster and easier. // 2. All the necessary information for this migration is local so using a file-specific type // checker should speed up the lookups. const localTypeChecker = getLocalTypeChecker(sourceFile); const analysis = analyzeFile(sourceFile, localTypeChecker); if (analysis === null || analysis.classes.length === 0) { return []; } const printer = ts.createPrinter(); const tracker = new ChangeTracker(printer); analysis.classes.forEach(({node, constructor, superCall}) => { const memberIndentation = getLeadingLineWhitespaceOfNode(node.members[0]); const prependToClass: string[] = []; const removedStatements = new Set<ts.Statement>(); if (options._internalCombineMemberInitializers) { applyInternalOnlyChanges( node, constructor, localTypeChecker, tracker, printer, removedStatements, prependToClass, memberIndentation, ); } migrateClass( node, constructor, superCall, options, memberIndentation, prependToClass, removedStatements, localTypeChecker, printer, tracker, ); }); DI_PARAM_SYMBOLS.forEach((name) => { // Both zero and undefined are fine here. if (!analysis.nonDecoratorReferences[name]) { tracker.removeImport(sourceFile, name, '@angular/core'); } }); return tracker.recordChanges().get(sourceFile) || []; } /** * Migrates a class away from constructor injection. * @param node Class to be migrated. * @param constructor Reference to the class' constructor node. * @param superCall Reference to the constructor's `super()` call, if any. * @param options Options used to configure the migration. * @param memberIndentation Indentation string of the members of the class. * @param prependToClass Text that should be prepended to the class. * @param removedStatements Statements that have been removed from the constructor already. * @param localTypeChecker Type checker set up for the specific file. * @param printer Printer used to output AST nodes as strings. * @param tracker Object keeping track of the changes made to the file. */ fun
{ "end_byte": 4677, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/inject-migration/migration.ts" }
angular/packages/core/schematics/ng-generate/inject-migration/migration.ts_4678_10650
tion migrateClass( node: ts.ClassDeclaration, constructor: ts.ConstructorDeclaration, superCall: ts.CallExpression | null, options: MigrationOptions, memberIndentation: string, prependToClass: string[], removedStatements: Set<ts.Statement>, localTypeChecker: ts.TypeChecker, printer: ts.Printer, tracker: ChangeTracker, ): void { const isAbstract = !!node.modifiers?.some((m) => m.kind === ts.SyntaxKind.AbstractKeyword); // Don't migrate abstract classes by default, because // their parameters aren't guaranteed to be injectable. if (isAbstract && !options.migrateAbstractClasses) { return; } const sourceFile = node.getSourceFile(); const unusedParameters = getConstructorUnusedParameters( constructor, localTypeChecker, removedStatements, ); const superParameters = superCall ? getSuperParameters(constructor, superCall, localTypeChecker) : null; const removedStatementCount = removedStatements.size; const firstConstructorStatement = constructor.body?.statements.find( (statement) => !removedStatements.has(statement), ); const innerReference = superCall || firstConstructorStatement || constructor; const innerIndentation = getLeadingLineWhitespaceOfNode(innerReference); const prependToConstructor: string[] = []; const afterSuper: string[] = []; const removedMembers = new Set<ts.ClassElement>(); for (const param of constructor.parameters) { const usedInSuper = superParameters !== null && superParameters.has(param); const usedInConstructor = !unusedParameters.has(param); migrateParameter( param, options, localTypeChecker, printer, tracker, superCall, usedInSuper, usedInConstructor, memberIndentation, innerIndentation, prependToConstructor, prependToClass, afterSuper, ); } // Delete all of the constructor overloads since below we're either going to // remove the implementation, or we're going to delete all of the parameters. for (const member of node.members) { if (ts.isConstructorDeclaration(member) && member !== constructor) { removedMembers.add(member); tracker.replaceText(sourceFile, member.getFullStart(), member.getFullWidth(), ''); } } if (canRemoveConstructor(options, constructor, removedStatementCount, superCall)) { // Drop the constructor if it was empty. removedMembers.add(constructor); tracker.replaceText(sourceFile, constructor.getFullStart(), constructor.getFullWidth(), ''); } else { // If the constructor contains any statements, only remove the parameters. // We always do this no matter what is passed into `backwardsCompatibleConstructors`. stripConstructorParameters(constructor, tracker); if (prependToConstructor.length > 0) { tracker.insertText( sourceFile, (firstConstructorStatement || innerReference).getFullStart(), `\n${prependToConstructor.join('\n')}\n`, ); } } if (afterSuper.length > 0 && superCall !== null) { // Note that if we can, we should insert before the next statement after the `super` call, // rather than after the end of it. Otherwise the string buffering implementation may drop // the text if the statement after the `super` call is being deleted. This appears to be because // the full start of the next statement appears to always be the end of the `super` call plus 1. const nextStatement = getNextPreservedStatement(superCall, removedStatements); tracker.insertText( sourceFile, nextStatement ? nextStatement.getFullStart() : superCall.getEnd() + 1, `\n${afterSuper.join('\n')}\n`, ); } // Need to resolve this once all constructor signatures have been removed. const memberReference = node.members.find((m) => !removedMembers.has(m)) || node.members[0]; // If `backwardsCompatibleConstructors` is enabled, we maintain // backwards compatibility by adding a catch-all signature. if (options.backwardsCompatibleConstructors) { const extraSignature = `\n${memberIndentation}/** Inserted by Angular inject() migration for backwards compatibility */\n` + `${memberIndentation}constructor(...args: unknown[]);`; // The new signature always has to be right before the constructor implementation. if (memberReference === constructor) { prependToClass.push(extraSignature); } else { tracker.insertText(sourceFile, constructor.getFullStart(), '\n' + extraSignature); } } if (prependToClass.length > 0) { if (removedMembers.size === node.members.length) { tracker.insertText(sourceFile, constructor.getEnd() + 1, `${prependToClass.join('\n')}\n`); } else { // Insert the new properties after the first member that hasn't been deleted. tracker.insertText( sourceFile, memberReference.getFullStart(), `\n${prependToClass.join('\n')}\n`, ); } } } /** * Migrates a single parameter to `inject()` DI. * @param node Parameter to be migrated. * @param options Options used to configure the migration. * @param localTypeChecker Type checker set up for the specific file. * @param printer Printer used to output AST nodes as strings. * @param tracker Object keeping track of the changes made to the file. * @param superCall Call to `super()` from the class' constructor. * @param usedInSuper Whether the parameter is referenced inside of `super`. * @param usedInConstructor Whether the parameter is referenced inside the body of the constructor. * @param memberIndentation Indentation string to use when inserting new class members. * @param innerIndentation Indentation string to use when inserting new constructor statements. * @param prependToConstructor Statements to be prepended to the constructor. * @param propsToAdd Properties to be added to the class. * @param afterSuper Statements to be added after the `super` call. */ fun
{ "end_byte": 10650, "start_byte": 4678, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/inject-migration/migration.ts" }
angular/packages/core/schematics/ng-generate/inject-migration/migration.ts_10651_18158
tion migrateParameter( node: ts.ParameterDeclaration, options: MigrationOptions, localTypeChecker: ts.TypeChecker, printer: ts.Printer, tracker: ChangeTracker, superCall: ts.CallExpression | null, usedInSuper: boolean, usedInConstructor: boolean, memberIndentation: string, innerIndentation: string, prependToConstructor: string[], propsToAdd: string[], afterSuper: string[], ): void { if (!ts.isIdentifier(node.name)) { return; } const name = node.name.text; const replacementCall = createInjectReplacementCall( node, options, localTypeChecker, printer, tracker, ); const declaresProp = parameterDeclaresProperty(node); // If the parameter declares a property, we need to declare it (e.g. `private foo: Foo`). if (declaresProp) { const prop = ts.factory.createPropertyDeclaration( cloneModifiers( node.modifiers?.filter((modifier) => { // Strip out the DI decorators, as well as `public` which is redundant. return !ts.isDecorator(modifier) && modifier.kind !== ts.SyntaxKind.PublicKeyword; }), ), name, // Don't add the question token to private properties since it won't affect interface implementation. node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.PrivateKeyword) ? undefined : node.questionToken, // We can't initialize the property if it's referenced within a `super` call. // See the logic further below for the initialization. usedInSuper ? node.type : undefined, usedInSuper ? undefined : ts.factory.createIdentifier(PLACEHOLDER), ); propsToAdd.push( memberIndentation + replaceNodePlaceholder(node.getSourceFile(), prop, replacementCall, printer), ); } // If the parameter is referenced within the constructor, we need to declare it as a variable. if (usedInConstructor) { if (usedInSuper) { // Usages of `this` aren't allowed before `super` calls so we need to // create a variable which calls `inject()` directly instead... prependToConstructor.push(`${innerIndentation}const ${name} = ${replacementCall};`); // ...then we can initialize the property after the `super` call. if (declaresProp) { afterSuper.push(`${innerIndentation}this.${name} = ${name};`); } } else if (declaresProp) { // If the parameter declares a property (`private foo: foo`) and is used inside the class // at the same time, we need to ensure that it's initialized to the value from the variable // and that we only reference `this` after the `super` call. const initializer = `${innerIndentation}const ${name} = this.${name};`; if (superCall === null) { prependToConstructor.push(initializer); } else { afterSuper.push(initializer); } } else { // If the parameter is only referenced in the constructor, we // don't need to declare any new properties. prependToConstructor.push(`${innerIndentation}const ${name} = ${replacementCall};`); } } } /** * Creates a replacement `inject` call from a function parameter. * @param param Parameter for which to generate the `inject` call. * @param options Options used to configure the migration. * @param localTypeChecker Type checker set up for the specific file. * @param printer Printer used to output AST nodes as strings. * @param tracker Object keeping track of the changes made to the file. */ function createInjectReplacementCall( param: ts.ParameterDeclaration, options: MigrationOptions, localTypeChecker: ts.TypeChecker, printer: ts.Printer, tracker: ChangeTracker, ): string { const moduleName = '@angular/core'; const sourceFile = param.getSourceFile(); const decorators = getAngularDecorators(localTypeChecker, ts.getDecorators(param) || []); const literalProps: ts.ObjectLiteralElementLike[] = []; const type = param.type; let injectedType = ''; let typeArguments = type && hasGenerics(type) ? [type] : undefined; let hasOptionalDecorator = false; if (type) { // Remove the type arguments from generic type references, because // they'll be specified as type arguments to `inject()`. if (ts.isTypeReferenceNode(type) && type.typeArguments && type.typeArguments.length > 0) { injectedType = type.typeName.getText(); } else if (ts.isUnionTypeNode(type)) { injectedType = (type.types.find((t) => !ts.isLiteralTypeNode(t)) || type.types[0]).getText(); } else { injectedType = type.getText(); } } for (const decorator of decorators) { if (decorator.moduleName !== moduleName) { continue; } const firstArg = decorator.node.expression.arguments[0] as ts.Expression | undefined; switch (decorator.name) { case 'Inject': if (firstArg) { const injectResult = migrateInjectDecorator(firstArg, type, localTypeChecker); injectedType = injectResult.injectedType; if (injectResult.typeArguments) { typeArguments = injectResult.typeArguments; } } break; case 'Attribute': if (firstArg) { const constructorRef = tracker.addImport(sourceFile, 'HostAttributeToken', moduleName); const expression = ts.factory.createNewExpression(constructorRef, undefined, [firstArg]); injectedType = printer.printNode(ts.EmitHint.Unspecified, expression, sourceFile); typeArguments = undefined; } break; case 'Optional': hasOptionalDecorator = true; literalProps.push(ts.factory.createPropertyAssignment('optional', ts.factory.createTrue())); break; case 'SkipSelf': literalProps.push(ts.factory.createPropertyAssignment('skipSelf', ts.factory.createTrue())); break; case 'Self': literalProps.push(ts.factory.createPropertyAssignment('self', ts.factory.createTrue())); break; case 'Host': literalProps.push(ts.factory.createPropertyAssignment('host', ts.factory.createTrue())); break; } } // The injected type might be a `TypeNode` which we can't easily convert into an `Expression`. // Since the value gets passed through directly anyway, we generate the call using a placeholder // which we then replace with the raw text of the `TypeNode`. const injectRef = tracker.addImport(param.getSourceFile(), 'inject', moduleName); const args: ts.Expression[] = [ts.factory.createIdentifier(PLACEHOLDER)]; if (literalProps.length > 0) { args.push(ts.factory.createObjectLiteralExpression(literalProps)); } let expression: ts.Expression = ts.factory.createCallExpression(injectRef, typeArguments, args); if (hasOptionalDecorator && options.nonNullableOptional) { const hasNullableType = param.questionToken != null || (param.type != null && isNullableType(param.type)); // Only wrap the expression if the type wasn't already nullable. // If it was, the app was likely accounting for it already. if (!hasNullableType) { expression = ts.factory.createNonNullExpression(expression); } } return replaceNodePlaceholder(param.getSourceFile(), expression, injectedType, printer); } /** * Migrates a parameter based on its `@Inject()` decorator. * @param firstArg First argument to `@Inject()`. * @param type Type of the parameter. * @param localTypeChecker Type checker set up for the specific file. */ fun
{ "end_byte": 18158, "start_byte": 10651, "url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/inject-migration/migration.ts" }