_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/core/schematics/ng-generate/inject-migration/migration.ts_18159_26661 | tion migrateInjectDecorator(
firstArg: ts.Expression,
type: ts.TypeNode | undefined,
localTypeChecker: ts.TypeChecker,
) {
let injectedType = firstArg.getText();
let typeArguments: ts.TypeNode[] | null = null;
// `inject` no longer officially supports string injection so we need
// to cast to any. We maintain the type by passing it as a generic.
if (ts.isStringLiteralLike(firstArg)) {
typeArguments = [type || ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)];
injectedType += ' as any';
} else if (
ts.isCallExpression(firstArg) &&
ts.isIdentifier(firstArg.expression) &&
firstArg.arguments.length === 1
) {
const callImport = getImportOfIdentifier(localTypeChecker, firstArg.expression);
const arrowFn = firstArg.arguments[0];
// If the first parameter is a `forwardRef`, unwrap it for a more
// accurate type and because it's no longer necessary.
if (
callImport !== null &&
callImport.name === 'forwardRef' &&
callImport.importModule === '@angular/core' &&
ts.isArrowFunction(arrowFn)
) {
if (ts.isBlock(arrowFn.body)) {
const returnStatement = arrowFn.body.statements.find((stmt) => ts.isReturnStatement(stmt));
if (returnStatement && returnStatement.expression) {
injectedType = returnStatement.expression.getText();
}
} else {
injectedType = arrowFn.body.getText();
}
}
} else if (
// Pass the type for cases like `@Inject(FOO_TOKEN) foo: Foo`, because:
// 1. It guarantees that the type stays the same as before.
// 2. Avoids leaving unused imports behind.
// We only do this for type references since the `@Inject` pattern above is fairly common and
// apps don't necessarily type their injection tokens correctly, whereas doing it for literal
// types will add a lot of noise to the generated code.
type &&
(ts.isTypeReferenceNode(type) ||
(ts.isUnionTypeNode(type) && type.types.some(ts.isTypeReferenceNode)))
) {
typeArguments = [type];
}
return {injectedType, typeArguments};
}
/**
* Removes the parameters from a constructor. This is a bit more complex than just replacing an AST
* node, because `NodeArray.pos` includes any leading whitespace, but `NodeArray.end` does **not**
* include trailing whitespace. Since we want to produce somewhat formatted code, we need to find
* the end of the arguments ourselves. We do it by finding the next parenthesis after the last
* parameter.
* @param node Constructor from which to remove the parameters.
* @param tracker Object keeping track of the changes made to the file.
*/
function stripConstructorParameters(node: ts.ConstructorDeclaration, tracker: ChangeTracker): void {
if (node.parameters.length === 0) {
return;
}
const constructorText = node.getText();
const lastParamText = node.parameters[node.parameters.length - 1].getText();
const lastParamStart = constructorText.indexOf(lastParamText);
const whitespacePattern = /\s/;
let trailingCharacters = 0;
if (lastParamStart > -1) {
let lastParamEnd = lastParamStart + lastParamText.length;
let closeParenIndex = -1;
for (let i = lastParamEnd; i < constructorText.length; i++) {
const char = constructorText[i];
if (char === ')') {
closeParenIndex = i;
break;
} else if (!whitespacePattern.test(char)) {
// The end of the last parameter won't include
// any trailing commas which we need to account for.
lastParamEnd = i + 1;
}
}
if (closeParenIndex > -1) {
trailingCharacters = closeParenIndex - lastParamEnd;
}
}
tracker.replaceText(
node.getSourceFile(),
node.parameters.pos,
node.parameters.end - node.parameters.pos + trailingCharacters,
'',
);
}
/**
* Creates a type checker scoped to a specific file.
* @param sourceFile File for which to create the type checker.
*/
function getLocalTypeChecker(sourceFile: ts.SourceFile) {
const options: ts.CompilerOptions = {noEmit: true, skipLibCheck: true};
const host = ts.createCompilerHost(options);
host.getSourceFile = (fileName) => (fileName === sourceFile.fileName ? sourceFile : undefined);
const program = ts.createProgram({
rootNames: [sourceFile.fileName],
options,
host,
});
return program.getTypeChecker();
}
/**
* Prints out an AST node and replaces the placeholder inside of it.
* @param sourceFile File in which the node will be inserted.
* @param node Node to be printed out.
* @param replacement Replacement for the placeholder.
* @param printer Printer used to output AST nodes as strings.
*/
function replaceNodePlaceholder(
sourceFile: ts.SourceFile,
node: ts.Node,
replacement: string,
printer: ts.Printer,
): string {
const result = printer.printNode(ts.EmitHint.Unspecified, node, sourceFile);
return result.replace(PLACEHOLDER, replacement);
}
/**
* Clones an optional array of modifiers. Can be useful to
* strip the comments from a node with modifiers.
*/
function cloneModifiers(modifiers: ts.ModifierLike[] | ts.NodeArray<ts.ModifierLike> | undefined) {
return modifiers?.map((modifier) => {
return ts.isDecorator(modifier)
? ts.factory.createDecorator(modifier.expression)
: ts.factory.createModifier(modifier.kind);
});
}
/**
* Clones the name of a property. Can be useful to strip away
* the comments of a property without modifiers.
*/
function cloneName(node: ts.PropertyName): ts.PropertyName {
switch (node.kind) {
case ts.SyntaxKind.Identifier:
return ts.factory.createIdentifier(node.text);
case ts.SyntaxKind.StringLiteral:
return ts.factory.createStringLiteral(node.text, node.getText()[0] === `'`);
case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
return ts.factory.createNoSubstitutionTemplateLiteral(node.text, node.rawText);
case ts.SyntaxKind.NumericLiteral:
return ts.factory.createNumericLiteral(node.text);
case ts.SyntaxKind.ComputedPropertyName:
return ts.factory.createComputedPropertyName(node.expression);
case ts.SyntaxKind.PrivateIdentifier:
return ts.factory.createPrivateIdentifier(node.text);
default:
return node;
}
}
/**
* Determines whether it's safe to delete a class constructor.
* @param options Options used to configure the migration.
* @param constructor Node representing the constructor.
* @param removedStatementCount Number of statements that were removed by the migration.
* @param superCall Node representing the `super()` call within the constructor.
*/
function canRemoveConstructor(
options: MigrationOptions,
constructor: ts.ConstructorDeclaration,
removedStatementCount: number,
superCall: ts.CallExpression | null,
): boolean {
if (options.backwardsCompatibleConstructors) {
return false;
}
const statementCount = constructor.body
? constructor.body.statements.length - removedStatementCount
: 0;
return (
statementCount === 0 ||
(statementCount === 1 && superCall !== null && superCall.arguments.length === 0)
);
}
/**
* Gets the next statement after a node that *won't* be deleted by the migration.
* @param startNode Node from which to start the search.
* @param removedStatements Statements that have been removed by the migration.
* @returns
*/
function getNextPreservedStatement(
startNode: ts.Node,
removedStatements: Set<ts.Statement>,
): ts.Statement | null {
const body = closestNode(startNode, ts.isBlock);
const closestStatement = closestNode(startNode, ts.isStatement);
if (body === null || closestStatement === null) {
return null;
}
const index = body.statements.indexOf(closestStatement);
if (index === -1) {
return null;
}
for (let i = index + 1; i < body.statements.length; i++) {
if (!removedStatements.has(body.statements[i])) {
return body.statements[i];
}
}
return null;
}
/**
* Applies the internal-specific migrations to a class.
* @param node Class being migrated.
* @param constructor The migrated class' constructor.
* @param localTypeChecker File-specific type checker.
* @param tracker Object keeping track of the changes.
* @param printer Printer used to output AST nodes as text.
* @param removedStatements Statements that have been removed by the migration.
* @param prependToClass Text that will be prepended to a class.
* @param memberIndentation Indentation string of the class' members.
*/
fun | {
"end_byte": 26661,
"start_byte": 18159,
"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_26662_28075 | tion applyInternalOnlyChanges(
node: ts.ClassDeclaration,
constructor: ts.ConstructorDeclaration,
localTypeChecker: ts.TypeChecker,
tracker: ChangeTracker,
printer: ts.Printer,
removedStatements: Set<ts.Statement>,
prependToClass: string[],
memberIndentation: string,
) {
const result = findUninitializedPropertiesToCombine(node, constructor, localTypeChecker);
result?.toCombine.forEach((initializer, property) => {
const statement = closestNode(initializer, ts.isStatement);
if (!statement) {
return;
}
const newProperty = ts.factory.createPropertyDeclaration(
cloneModifiers(property.modifiers),
cloneName(property.name),
property.questionToken,
property.type,
initializer,
);
tracker.replaceText(
statement.getSourceFile(),
statement.getFullStart(),
statement.getFullWidth(),
'',
);
tracker.replaceNode(property, newProperty);
removedStatements.add(statement);
});
result?.toHoist.forEach((decl) => {
prependToClass.push(
memberIndentation + printer.printNode(ts.EmitHint.Unspecified, decl, decl.getSourceFile()),
);
tracker.replaceText(decl.getSourceFile(), decl.getFullStart(), decl.getFullWidth(), '');
});
// If we added any hoisted properties, separate them visually with a new line.
if (prependToClass.length > 0) {
prependToClass.push('');
}
}
| {
"end_byte": 28075,
"start_byte": 26662,
"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/README.md_0_3900 | ## Inject migration
Automated migration that converts classes using constructor-based injection to the `inject`
function. It can be run using:
```bash
ng generate @angular/core:inject-migration
```
**Before:**
```typescript
import { Component, Inject, Optional } from '@angular/core';
import { MyService } from './service';
import { DI_TOKEN } from './token';
@Component({})
export class MyComp {
constructor(private service: MyService, @Inject(TOKEN) @Optional() readonly token: string) {}
}
```
**After:**
```typescript
import { Component, inject } from '@angular/core';
import { MyService } from './service';
import { DI_TOKEN } from './token';
@Component({})
export class MyComp {
private service = inject(MyService);
readonly token = inject(DI_TOKEN, { optional: true });
}
```
### Options
The migration includes several options to customize its output.
#### `path`
Determines which sub-path in your project should be migrated. Pass in `.` or leave it blank to
migrate the entire directory.
#### `migrateAbstractClasses`
Angular doesn't validate that parameters of abstract classes are injectable. This means that the
migration can't reliably migrate them to `inject` without risking breakages which is why they're
disabled by default. Enable this option if you want abstract classes to be migrated, but note
that you may have to **fix some breakages manually**.
#### `backwardsCompatibleConstructors`
By default the migration tries to clean up the code as much as it can, which includes deleting
parameters from the constructor, or even the entire constructor if it doesn't include any code.
In some cases this can lead to compilation errors when classes with Angular decorators inherit from
other classes with Angular decorators. If you enable this option, the migration will generate an
additional constructor signature to keep it backwards compatible, at the expense of more code.
**Before:**
```typescript
import { Component } from '@angular/core';
import { MyService } from './service';
@Component({})
export class MyComp {
constructor(private service: MyService) {}
}
```
**After:**
```typescript
import { Component } from '@angular/core';
import { MyService } from './service';
@Component({})
export class MyComp {
private service = inject(MyService);
/** Inserted by Angular inject() migration for backwards compatibility */
constructor(...args: unknown[]);
constructor() {}
}
```
#### `nonNullableOptional`
If injection fails for a parameter with the `@Optional` decorator, Angular returns `null` which
means that the real type of any `@Optional` parameter will be `| null`. However, because decorators
cannot influence their types, there is a lot of existing code whose type is incorrect. The type is
fixed in `inject()` which can cause new compilation errors to show up. If you enable this option,
the migration will produce a non-null assertion after the `inject()` call to match the old type,
at the expense of potentially hiding type errors.
**Note:** non-null assertions won't be added to parameters that are already typed to be nullable,
because the code that depends on them likely already accounts for their nullability.
**Before:**
```typescript
import { Component, Inject, Optional } from '@angular/core';
import { TOKEN_ONE, TOKEN_TWO } from './token';
@Component({})
export class MyComp {
constructor(
@Inject(TOKEN_ONE) @Optional() private tokenOne: number,
@Inject(TOKEN_TWO) @Optional() private tokenTwo: string | null) {}
}
```
**After:**
```typescript
import { Component, inject } from '@angular/core';
import { TOKEN_ONE, TOKEN_TWO } from './token';
@Component({})
export class MyComp {
// Note the `!` at the end.
private tokenOne = inject(TOKEN_ONE, { optional: true })!;
// Does not have `!` at the end, because the type was already nullable.
private tokenTwo = inject(TOKEN_TWO, { optional: true });
}
```
| {
"end_byte": 3900,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/inject-migration/README.md"
} |
angular/packages/core/schematics/ng-generate/inject-migration/BUILD.bazel_0_683 | 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 = "inject-migration",
srcs = glob(["**/*.ts"]),
tsconfig = "//packages/core/schematics:tsconfig.json",
deps = [
"//packages/core/schematics/utils",
"//packages/core/schematics/utils/tsurge/helpers/ast",
"@npm//@angular-devkit/schematics",
"@npm//@types/node",
"@npm//typescript",
],
)
| {
"end_byte": 683,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/inject-migration/BUILD.bazel"
} |
angular/packages/core/schematics/ng-generate/inject-migration/index.ts_0_2435 | /**
* @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 {join, relative} from 'path';
import {normalizePath} from '../../utils/change_tracker';
import {canMigrateFile, createMigrationProgram} from '../../utils/typescript/compiler_host';
import {migrateFile, MigrationOptions} from './migration';
interface Options extends MigrationOptions {
path: string;
}
export function migrate(options: Options): Rule {
return async (tree: Tree) => {
const basePath = process.cwd();
const pathToMigrate = normalizePath(join(basePath, options.path));
let allPaths = [];
if (pathToMigrate.trim() !== '') {
allPaths.push(pathToMigrate);
}
if (!allPaths.length) {
throw new SchematicsException(
'Could not find any tsconfig file. Cannot run the inject migration.',
);
}
for (const tsconfigPath of allPaths) {
runInjectMigration(tree, tsconfigPath, basePath, pathToMigrate, options);
}
};
}
function runInjectMigration(
tree: Tree,
tsconfigPath: string,
basePath: string,
pathToMigrate: string,
schematicOptions: Options,
): void {
if (schematicOptions.path.startsWith('..')) {
throw new SchematicsException('Cannot run inject migration outside of the current project.');
}
const program = createMigrationProgram(tree, tsconfigPath, basePath);
const sourceFiles = program
.getSourceFiles()
.filter(
(sourceFile) =>
sourceFile.fileName.startsWith(pathToMigrate) &&
canMigrateFile(basePath, sourceFile, program),
);
if (sourceFiles.length === 0) {
throw new SchematicsException(
`Could not find any files to migrate under the path ${pathToMigrate}. Cannot run the inject migration.`,
);
}
for (const sourceFile of sourceFiles) {
const changes = migrateFile(sourceFile, schematicOptions);
if (changes.length > 0) {
const update = tree.beginUpdate(relative(basePath, sourceFile.fileName));
for (const change of changes) {
if (change.removeLength != null) {
update.remove(change.start, change.removeLength);
}
update.insertRight(change.start, change.text);
}
tree.commitUpdate(update);
}
}
}
| {
"end_byte": 2435,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/inject-migration/index.ts"
} |
angular/packages/core/schematics/ng-generate/inject-migration/analysis.ts_0_8845 | /*!
* @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 '../../utils/ng_decorators';
import {getNamedImports} from '../../utils/typescript/imports';
/** Names of decorators that enable DI on a class declaration. */
const DECORATORS_SUPPORTING_DI = new Set([
'Component',
'Directive',
'Pipe',
'NgModule',
'Injectable',
]);
/** Names of symbols used for DI on parameters. */
export const DI_PARAM_SYMBOLS = new Set([
'Inject',
'Attribute',
'Optional',
'SkipSelf',
'Self',
'Host',
'forwardRef',
]);
/**
* Finds the necessary information for the `inject` migration in a file.
* @param sourceFile File which to analyze.
* @param localTypeChecker Type checker scoped to the specific file.
*/
export function analyzeFile(sourceFile: ts.SourceFile, localTypeChecker: ts.TypeChecker) {
const coreSpecifiers = getNamedImports(sourceFile, '@angular/core');
// Exit early if there are no Angular imports.
if (coreSpecifiers === null || coreSpecifiers.elements.length === 0) {
return null;
}
const classes: {
node: ts.ClassDeclaration;
constructor: ts.ConstructorDeclaration;
superCall: ts.CallExpression | null;
}[] = [];
const nonDecoratorReferences: Record<string, number | undefined> = {};
const importsToSpecifiers = coreSpecifiers.elements.reduce((map, specifier) => {
const symbolName = (specifier.propertyName || specifier.name).text;
if (DI_PARAM_SYMBOLS.has(symbolName)) {
map.set(symbolName, specifier);
}
return map;
}, new Map<string, ts.ImportSpecifier>());
sourceFile.forEachChild(function walk(node) {
// Skip import declarations since they can throw off the identifier
// could below and we don't care about them in this migration.
if (ts.isImportDeclaration(node)) {
return;
}
// Only visit the initializer of parameters, because we won't exclude
// their decorators from the identifier counting result below.
if (ts.isParameter(node)) {
if (node.initializer) {
walk(node.initializer);
}
return;
}
if (ts.isIdentifier(node) && importsToSpecifiers.size > 0) {
let symbol: ts.Symbol | undefined;
for (const [name, specifier] of importsToSpecifiers) {
const localName = (specifier.propertyName || specifier.name).text;
// Quick exit if the two symbols don't match up.
if (localName === node.text) {
if (!symbol) {
symbol = localTypeChecker.getSymbolAtLocation(node);
// If the symbol couldn't be resolved the first time, it won't be resolved the next
// time either. Stop the loop since we won't be able to get an accurate result.
if (!symbol || !symbol.declarations) {
break;
} else if (symbol.declarations.some((decl) => decl === specifier)) {
nonDecoratorReferences[name] = (nonDecoratorReferences[name] || 0) + 1;
}
}
}
}
} else if (ts.isClassDeclaration(node)) {
const decorators = getAngularDecorators(localTypeChecker, ts.getDecorators(node) || []);
const supportsDI = decorators.some((dec) => DECORATORS_SUPPORTING_DI.has(dec.name));
const constructorNode = node.members.find(
(member) =>
ts.isConstructorDeclaration(member) &&
member.body != null &&
member.parameters.length > 0,
) as ts.ConstructorDeclaration | undefined;
if (supportsDI && constructorNode) {
classes.push({
node,
constructor: constructorNode,
superCall: node.heritageClauses ? findSuperCall(constructorNode) : null,
});
}
}
node.forEachChild(walk);
});
return {classes, nonDecoratorReferences};
}
/**
* Returns the parameters of a function that aren't used within its body.
* @param declaration Function in which to search for unused parameters.
* @param localTypeChecker Type checker scoped to the file in which the function was declared.
* @param removedStatements Statements that were already removed from the constructor.
*/
export function getConstructorUnusedParameters(
declaration: ts.ConstructorDeclaration,
localTypeChecker: ts.TypeChecker,
removedStatements: Set<ts.Statement>,
): Set<ts.Declaration> {
const accessedTopLevelParameters = new Set<ts.Declaration>();
const topLevelParameters = new Set<ts.Declaration>();
const topLevelParameterNames = new Set<string>();
const unusedParams = new Set<ts.Declaration>();
// Prepare the parameters for quicker checks further down.
for (const param of declaration.parameters) {
if (ts.isIdentifier(param.name)) {
topLevelParameters.add(param);
topLevelParameterNames.add(param.name.text);
}
}
if (!declaration.body) {
return topLevelParameters;
}
declaration.body.forEachChild(function walk(node) {
// Don't descend into statements that were removed already.
if (ts.isStatement(node) && removedStatements.has(node)) {
return;
}
if (!ts.isIdentifier(node) || !topLevelParameterNames.has(node.text)) {
node.forEachChild(walk);
return;
}
// Don't consider `this.<name>` accesses as being references to
// parameters since they'll be moved to property declarations.
if (isAccessedViaThis(node)) {
return;
}
localTypeChecker.getSymbolAtLocation(node)?.declarations?.forEach((decl) => {
if (ts.isParameter(decl) && topLevelParameters.has(decl)) {
accessedTopLevelParameters.add(decl);
}
if (ts.isShorthandPropertyAssignment(decl)) {
const symbol = localTypeChecker.getShorthandAssignmentValueSymbol(decl);
if (symbol && symbol.valueDeclaration && ts.isParameter(symbol.valueDeclaration)) {
accessedTopLevelParameters.add(symbol.valueDeclaration);
}
}
});
});
for (const param of topLevelParameters) {
if (!accessedTopLevelParameters.has(param)) {
unusedParams.add(param);
}
}
return unusedParams;
}
/**
* Determines which parameters of a function declaration are used within its `super` call.
* @param declaration Function whose parameters to search for.
* @param superCall `super()` call within the function.
* @param localTypeChecker Type checker scoped to the file in which the function is declared.
*/
export function getSuperParameters(
declaration: ts.FunctionLikeDeclaration,
superCall: ts.CallExpression,
localTypeChecker: ts.TypeChecker,
): Set<ts.ParameterDeclaration> {
const usedParams = new Set<ts.ParameterDeclaration>();
const topLevelParameters = new Set<ts.ParameterDeclaration>();
const topLevelParameterNames = new Set<string>();
// Prepare the parameters for quicker checks further down.
for (const param of declaration.parameters) {
if (ts.isIdentifier(param.name)) {
topLevelParameters.add(param);
topLevelParameterNames.add(param.name.text);
}
}
superCall.forEachChild(function walk(node) {
if (ts.isIdentifier(node) && topLevelParameterNames.has(node.text)) {
localTypeChecker.getSymbolAtLocation(node)?.declarations?.forEach((decl) => {
if (ts.isParameter(decl) && topLevelParameters.has(decl)) {
usedParams.add(decl);
}
});
} else {
node.forEachChild(walk);
}
});
return usedParams;
}
/** Checks whether a parameter node declares a property on its class. */
export function parameterDeclaresProperty(node: ts.ParameterDeclaration): boolean {
return !!node.modifiers?.some(
({kind}) =>
kind === ts.SyntaxKind.PublicKeyword ||
kind === ts.SyntaxKind.PrivateKeyword ||
kind === ts.SyntaxKind.ProtectedKeyword ||
kind === ts.SyntaxKind.ReadonlyKeyword,
);
}
/** Checks whether a type node is nullable. */
export function isNullableType(node: ts.TypeNode): boolean {
// Apparently `foo: null` is `Parameter<TypeNode<NullKeyword>>`,
// while `foo: undefined` is `Parameter<UndefinedKeyword>`...
if (node.kind === ts.SyntaxKind.UndefinedKeyword || node.kind === ts.SyntaxKind.VoidKeyword) {
return true;
}
if (ts.isLiteralTypeNode(node)) {
return node.literal.kind === ts.SyntaxKind.NullKeyword;
}
if (ts.isUnionTypeNode(node)) {
return node.types.some(isNullableType);
}
return false;
}
/** Checks whether a type node has generic arguments. */
export function hasGenerics(node: ts.TypeNode): boolean {
if (ts.isTypeReferenceNode(node)) {
return node.typeArguments != null && node.typeArguments.length > 0;
}
if (ts.isUnionTypeNode(node)) {
return node.types.some(hasGenerics);
}
return false;
} | {
"end_byte": 8845,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/inject-migration/analysis.ts"
} |
angular/packages/core/schematics/ng-generate/inject-migration/analysis.ts_8847_9592 | /** Checks whether an identifier is accessed through `this`, e.g. `this.<some identifier>`. */
export function isAccessedViaThis(node: ts.Identifier): boolean {
return (
ts.isPropertyAccessExpression(node.parent) &&
node.parent.expression.kind === ts.SyntaxKind.ThisKeyword &&
node.parent.name === node
);
}
/** Finds a `super` call inside of a specific node. */
function findSuperCall(root: ts.Node): ts.CallExpression | null {
let result: ts.CallExpression | null = null;
root.forEachChild(function find(node) {
if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.SuperKeyword) {
result = node;
} else if (result === null) {
node.forEachChild(find);
}
});
return result;
} | {
"end_byte": 9592,
"start_byte": 8847,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/inject-migration/analysis.ts"
} |
angular/packages/core/schematics/ng-generate/inject-migration/internal.ts_0_7114 | /*!
* @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 {isAccessedViaThis} from './analysis';
/**
* Finds class property declarations without initializers whose constructor-based initialization
* can be inlined into the declaration spot after migrating to `inject`. For example:
*
* ```
* private foo: number;
*
* constructor(private service: MyService) {
* this.foo = this.service.getFoo();
* }
* ```
*
* The initializer of `foo` can be inlined, because `service` will be initialized
* before it after the `inject` migration has finished running.
*
* @param node Class declaration that is being migrated.
* @param constructor Constructor declaration of the class being migrated.
* @param localTypeChecker Type checker scoped to the current file.
*/
export function findUninitializedPropertiesToCombine(
node: ts.ClassDeclaration,
constructor: ts.ConstructorDeclaration,
localTypeChecker: ts.TypeChecker,
): {
toCombine: Map<ts.PropertyDeclaration, ts.Expression>;
toHoist: ts.PropertyDeclaration[];
} | null {
let toCombine: Map<ts.PropertyDeclaration, ts.Expression> | null = null;
let toHoist: ts.PropertyDeclaration[] = [];
const membersToDeclarations = new Map<string, ts.PropertyDeclaration>();
for (const member of node.members) {
if (
ts.isPropertyDeclaration(member) &&
!member.initializer &&
!ts.isComputedPropertyName(member.name)
) {
membersToDeclarations.set(member.name.text, member);
}
}
if (membersToDeclarations.size === 0) {
return null;
}
const memberInitializers = getMemberInitializers(constructor);
if (memberInitializers === null) {
return null;
}
for (const [name, decl] of membersToDeclarations.entries()) {
if (memberInitializers.has(name)) {
const initializer = memberInitializers.get(name)!;
if (!hasLocalReferences(initializer, constructor, localTypeChecker)) {
toCombine = toCombine || new Map();
toCombine.set(membersToDeclarations.get(name)!, initializer);
}
} else {
// Mark members that have no initializers and can't be combined to be hoisted above the
// injected members. This is either a no-op or it allows us to avoid some patterns internally
// like the following:
// ```
// class Foo {
// publicFoo: Foo;
// private privateFoo: Foo;
//
// constructor() {
// this.initializePrivateFooSomehow();
// this.publicFoo = this.privateFoo;
// }
// }
// ```
toHoist.push(decl);
}
}
// If no members need to be combined, none need to be hoisted either.
return toCombine === null ? null : {toCombine, toHoist};
}
/**
* Finds the expressions from the constructor that initialize class members, for example:
*
* ```
* private foo: number;
*
* constructor() {
* this.foo = 123;
* }
* ```
*
* @param constructor Constructor declaration being analyzed.
*/
function getMemberInitializers(constructor: ts.ConstructorDeclaration) {
let memberInitializers: Map<string, ts.Expression> | null = null;
if (!constructor.body) {
return memberInitializers;
}
// Only look at top-level constructor statements.
for (const node of constructor.body.statements) {
// Only look for statements in the form of `this.<name> = <expr>;` or `this[<name>] = <expr>;`.
if (
!ts.isExpressionStatement(node) ||
!ts.isBinaryExpression(node.expression) ||
node.expression.operatorToken.kind !== ts.SyntaxKind.EqualsToken ||
(!ts.isPropertyAccessExpression(node.expression.left) &&
!ts.isElementAccessExpression(node.expression.left)) ||
node.expression.left.expression.kind !== ts.SyntaxKind.ThisKeyword
) {
continue;
}
let name: string | undefined;
if (ts.isPropertyAccessExpression(node.expression.left)) {
name = node.expression.left.name.text;
} else if (ts.isElementAccessExpression(node.expression.left)) {
name = ts.isStringLiteralLike(node.expression.left.argumentExpression)
? node.expression.left.argumentExpression.text
: undefined;
}
// If the member is initialized multiple times, take the first one.
if (name && (!memberInitializers || !memberInitializers.has(name))) {
memberInitializers = memberInitializers || new Map();
memberInitializers.set(name, node.expression.right);
}
}
return memberInitializers;
}
/**
* Determines if a node has references to local symbols defined in the constructor.
* @param root Expression to check for local references.
* @param constructor Constructor within which the expression is used.
* @param localTypeChecker Type checker scoped to the current file.
*/
function hasLocalReferences(
root: ts.Expression,
constructor: ts.ConstructorDeclaration,
localTypeChecker: ts.TypeChecker,
): boolean {
const sourceFile = root.getSourceFile();
let hasLocalRefs = false;
const walk = (node: ts.Node) => {
// Stop searching if we know that it has local references.
if (hasLocalRefs) {
return;
}
// Skip identifiers that are accessed via `this` since they're accessing class members
// that aren't local to the constructor. This is here primarily to catch cases like this
// where `foo` is defined inside the constructor, but is a class member:
// ```
// constructor(private foo: Foo) {
// this.bar = this.foo.getFoo();
// }
// ```
if (ts.isIdentifier(node) && !isAccessedViaThis(node)) {
const declarations = localTypeChecker.getSymbolAtLocation(node)?.declarations;
const isReferencingLocalSymbol = declarations?.some(
(decl) =>
// The source file check is a bit redundant since the type checker
// is local to the file, but it's inexpensive and it can prevent
// bugs in the future if we decide to use a full type checker.
decl.getSourceFile() === sourceFile &&
decl.getStart() >= constructor.getStart() &&
decl.getEnd() <= constructor.getEnd() &&
!isInsideInlineFunction(decl, constructor),
);
if (isReferencingLocalSymbol) {
hasLocalRefs = true;
}
}
if (!hasLocalRefs) {
node.forEachChild(walk);
}
};
walk(root);
return hasLocalRefs;
}
/**
* Determines if a node is defined inside of an inline function.
* @param startNode Node from which to start checking for inline functions.
* @param boundary Node at which to stop searching.
*/
function isInsideInlineFunction(startNode: ts.Node, boundary: ts.Node): boolean {
let current = startNode;
while (current) {
if (current === boundary) {
return false;
}
if (
ts.isFunctionDeclaration(current) ||
ts.isFunctionExpression(current) ||
ts.isArrowFunction(current)
) {
return true;
}
current = current.parent;
}
return false;
}
| {
"end_byte": 7114,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/inject-migration/internal.ts"
} |
angular/packages/core/schematics/ng-generate/output-migration/BUILD.bazel_0_916 | load("//tools:defaults.bzl", "ts_library")
package(
default_visibility = [
"//packages/core/schematics:__pkg__",
"//packages/core/schematics/migrations/google3:__pkg__",
"//packages/core/schematics/ng-generate/signals:__pkg__",
"//packages/core/schematics/test:__pkg__",
],
)
filegroup(
name = "static_files",
srcs = ["schema.json"],
)
ts_library(
name = "output-migration",
srcs = glob(["**/*.ts"]),
tsconfig = "//packages/core/schematics:tsconfig.json",
deps = [
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/core/schematics/migrations/output-migration:migration",
"//packages/core/schematics/utils",
"//packages/core/schematics/utils/tsurge",
"//packages/core/schematics/utils/tsurge/helpers/angular_devkit",
"@npm//@angular-devkit/schematics",
"@npm//@types/node",
],
)
| {
"end_byte": 916,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/output-migration/BUILD.bazel"
} |
angular/packages/core/schematics/ng-generate/output-migration/index.ts_0_4525 | /**
* @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} from '@angular-devkit/schematics';
import {getProjectTsConfigPaths} from '../../utils/project_tsconfig_paths';
import {DevkitMigrationFilesystem} from '../../utils/tsurge/helpers/angular_devkit/devkit_filesystem';
import {groupReplacementsByFile} from '../../utils/tsurge/helpers/group_replacements';
import {setFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system';
import {
CompilationUnitData,
OutputMigration,
} from '../../migrations/output-migration/output-migration';
import {ProjectRootRelativePath, TextUpdate} from '../../utils/tsurge';
import {synchronouslyCombineUnitData} from '../../utils/tsurge/helpers/combine_units';
interface Options {
path: string;
analysisDir: string;
}
export function migrate(options: Options): Rule {
return async (tree, context) => {
const {buildPaths, testPaths} = await getProjectTsConfigPaths(tree);
if (!buildPaths.length && !testPaths.length) {
throw new SchematicsException(
'Could not find any tsconfig file. Cannot run output migration.',
);
}
const fs = new DevkitMigrationFilesystem(tree);
setFileSystem(fs);
const migration = new OutputMigration({
shouldMigrate: (_, file) => {
return (
file.rootRelativePath.startsWith(fs.normalize(options.path)) &&
!/(^|\/)node_modules\//.test(file.rootRelativePath)
);
},
});
const analysisPath = fs.resolve(options.analysisDir);
const unitResults: CompilationUnitData[] = [];
const programInfos = [...buildPaths, ...testPaths].map((tsconfigPath) => {
context.logger.info(`Preparing analysis for: ${tsconfigPath}..`);
const baseInfo = migration.createProgram(tsconfigPath, fs);
const info = migration.prepareProgram(baseInfo);
// Support restricting the analysis to subfolders for larger projects.
if (analysisPath !== '/') {
info.sourceFiles = info.sourceFiles.filter((sf) => sf.fileName.startsWith(analysisPath));
info.fullProgramSourceFiles = info.fullProgramSourceFiles.filter((sf) =>
sf.fileName.startsWith(analysisPath),
);
}
return {info, tsconfigPath};
});
// Analyze phase. Treat all projects as compilation units as
// this allows us to support references between those.
for (const {info, tsconfigPath} of programInfos) {
context.logger.info(`Scanning for outputs: ${tsconfigPath}..`);
unitResults.push(await migration.analyze(info));
}
context.logger.info(``);
context.logger.info(`Processing analysis data between targets..`);
context.logger.info(``);
const combined = await synchronouslyCombineUnitData(migration, unitResults);
if (combined === null) {
context.logger.error('Migration failed unexpectedly with no analysis data');
return;
}
const globalMeta = await migration.globalMeta(combined);
const replacementsPerFile: Map<ProjectRootRelativePath, TextUpdate[]> = new Map();
for (const {info, tsconfigPath} of programInfos) {
context.logger.info(`Migrating: ${tsconfigPath}..`);
const {replacements} = await migration.migrate(globalMeta);
const changesPerFile = groupReplacementsByFile(replacements);
for (const [file, changes] of changesPerFile) {
if (!replacementsPerFile.has(file)) {
replacementsPerFile.set(file, changes);
}
}
}
context.logger.info(`Applying changes..`);
for (const [file, changes] of replacementsPerFile) {
const recorder = tree.beginUpdate(file);
for (const c of changes) {
recorder
.remove(c.data.position, c.data.end - c.data.position)
.insertLeft(c.data.position, c.data.toInsert);
}
tree.commitUpdate(recorder);
}
const {
counters: {detectedOutputs, problematicOutputs, successRate},
} = await migration.stats(globalMeta);
const migratedOutputs = detectedOutputs - problematicOutputs;
const successRatePercent = (successRate * 100).toFixed(2);
context.logger.info('');
context.logger.info(`Successfully migrated to outputs as functions 🎉`);
context.logger.info(
` -> Migrated ${migratedOutputs} out of ${detectedOutputs} detected outputs (${successRatePercent} %).`,
);
};
}
| {
"end_byte": 4525,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/output-migration/index.ts"
} |
angular/packages/core/schematics/ng-generate/signal-queries-migration/BUILD.bazel_0_932 | load("//tools:defaults.bzl", "ts_library")
package(
default_visibility = [
"//packages/core/schematics:__pkg__",
"//packages/core/schematics/migrations/google3:__pkg__",
"//packages/core/schematics/ng-generate/signals:__pkg__",
"//packages/core/schematics/test:__pkg__",
],
)
filegroup(
name = "static_files",
srcs = ["schema.json"],
)
ts_library(
name = "signal-queries-migration",
srcs = glob(["**/*.ts"]),
tsconfig = "//packages/core/schematics:tsconfig.json",
deps = [
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/core/schematics/migrations/signal-queries-migration:migration",
"//packages/core/schematics/utils",
"//packages/core/schematics/utils/tsurge",
"//packages/core/schematics/utils/tsurge/helpers/angular_devkit",
"@npm//@angular-devkit/schematics",
"@npm//@types/node",
],
)
| {
"end_byte": 932,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/signal-queries-migration/BUILD.bazel"
} |
angular/packages/core/schematics/ng-generate/signal-queries-migration/index.ts_0_5151 | /**
* @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} from '@angular-devkit/schematics';
import {getProjectTsConfigPaths} from '../../utils/project_tsconfig_paths';
import {DevkitMigrationFilesystem} from '../../utils/tsurge/helpers/angular_devkit/devkit_filesystem';
import {groupReplacementsByFile} from '../../utils/tsurge/helpers/group_replacements';
import {setFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system';
import {ProjectRootRelativePath, TextUpdate} from '../../utils/tsurge';
import {
CompilationUnitData,
SignalQueriesMigration,
} from '../../migrations/signal-queries-migration/migration';
import {synchronouslyCombineUnitData} from '../../utils/tsurge/helpers/combine_units';
interface Options {
path: string;
analysisDir: string;
bestEffortMode?: boolean;
insertTodos?: boolean;
}
export function migrate(options: Options): Rule {
return async (tree, context) => {
const {buildPaths, testPaths} = await getProjectTsConfigPaths(tree);
if (!buildPaths.length && !testPaths.length) {
throw new SchematicsException(
'Could not find any tsconfig file. Cannot run signal queries migration.',
);
}
const fs = new DevkitMigrationFilesystem(tree);
setFileSystem(fs);
const migration = new SignalQueriesMigration({
bestEffortMode: options.bestEffortMode,
insertTodosForSkippedFields: options.insertTodos,
shouldMigrateQuery: (_query, file) => {
return (
file.rootRelativePath.startsWith(fs.normalize(options.path)) &&
!/(^|\/)node_modules\//.test(file.rootRelativePath)
);
},
});
const analysisPath = fs.resolve(options.analysisDir);
const unitResults: CompilationUnitData[] = [];
const programInfos = [...buildPaths, ...testPaths].map((tsconfigPath) => {
context.logger.info(`Preparing analysis for: ${tsconfigPath}..`);
const baseInfo = migration.createProgram(tsconfigPath, fs);
const info = migration.prepareProgram(baseInfo);
// Support restricting the analysis to subfolders for larger projects.
if (analysisPath !== '/') {
info.sourceFiles = info.sourceFiles.filter((sf) => sf.fileName.startsWith(analysisPath));
info.fullProgramSourceFiles = info.fullProgramSourceFiles.filter((sf) =>
sf.fileName.startsWith(analysisPath),
);
}
return {info, tsconfigPath};
});
// Analyze phase. Treat all projects as compilation units as
// this allows us to support references between those.
for (const {info, tsconfigPath} of programInfos) {
context.logger.info(`Scanning for queries: ${tsconfigPath}..`);
unitResults.push(await migration.analyze(info));
}
context.logger.info(``);
context.logger.info(`Processing analysis data between targets..`);
context.logger.info(``);
const combined = await synchronouslyCombineUnitData(migration, unitResults);
if (combined === null) {
context.logger.error('Migration failed unexpectedly with no analysis data');
return;
}
const globalMeta = await migration.globalMeta(combined);
const replacementsPerFile: Map<ProjectRootRelativePath, TextUpdate[]> = new Map();
for (const {info, tsconfigPath} of programInfos) {
context.logger.info(`Migrating: ${tsconfigPath}..`);
const {replacements} = await migration.migrate(globalMeta, info);
const changesPerFile = groupReplacementsByFile(replacements);
for (const [file, changes] of changesPerFile) {
if (!replacementsPerFile.has(file)) {
replacementsPerFile.set(file, changes);
}
}
}
context.logger.info(`Applying changes..`);
for (const [file, changes] of replacementsPerFile) {
const recorder = tree.beginUpdate(file);
for (const c of changes) {
recorder
.remove(c.data.position, c.data.end - c.data.position)
.insertLeft(c.data.position, c.data.toInsert);
}
tree.commitUpdate(recorder);
}
context.logger.info('');
context.logger.info(`Successfully migrated to signal queries 🎉`);
const {
counters: {queriesCount, incompatibleQueries, multiQueries},
} = await migration.stats(globalMeta);
const migratedQueries = queriesCount - incompatibleQueries;
context.logger.info('');
context.logger.info(`Successfully migrated to signal queries 🎉`);
context.logger.info(` -> Migrated ${migratedQueries}/${queriesCount} queries.`);
if (incompatibleQueries > 0 && !options.insertTodos) {
context.logger.warn(`To see why ${incompatibleQueries} queries couldn't be migrated`);
context.logger.warn(`consider re-running with "--insert-todos" or "--best-effort-mode".`);
}
if (options.bestEffortMode) {
context.logger.warn(
`You ran with best effort mode. Manually verify all code ` +
`works as intended, and fix where necessary.`,
);
}
};
}
| {
"end_byte": 5151,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/signal-queries-migration/index.ts"
} |
angular/packages/core/schematics/ng-generate/signals/README.md_0_647 | # Combined signals migration
Combines all signal-related migrations into a single migration. It includes the following migrations:
* Converting `@Input` to the signal-based `input`.
* Converting `@Output` to `output`.
* Converting `@ViewChild`/`@ViewChildren` and `@ContentChild`/`@ContentChildren` to
`viewChild`/`viewChildren` and `contentChild`/`contentChildren`.
The primary use case for this migration is to offer developers interested in switching to signals a
single entrypoint from which they can do so.
## How to run this migration?
The migration can be run using the following command:
```bash
ng generate @angular/core:signals
```
| {
"end_byte": 647,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/signals/README.md"
} |
angular/packages/core/schematics/ng-generate/signals/BUILD.bazel_0_828 | 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 = "signals",
srcs = glob(["**/*.ts"]),
tsconfig = "//packages/core/schematics:tsconfig.json",
deps = [
"//packages/core/schematics/ng-generate/output-migration",
"//packages/core/schematics/ng-generate/signal-input-migration",
"//packages/core/schematics/ng-generate/signal-queries-migration",
"//packages/core/schematics/utils/tsurge/helpers/angular_devkit",
"@npm//@angular-devkit/schematics",
"@npm//@types/node",
],
)
| {
"end_byte": 828,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/signals/BUILD.bazel"
} |
angular/packages/core/schematics/ng-generate/signals/index.ts_0_1562 | /**
* @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 {chain, Rule, SchematicsException} from '@angular-devkit/schematics';
import {migrate as toSignalQueries} from '../signal-queries-migration';
import {migrate as toSignalInputs} from '../signal-input-migration';
import {migrate as toInitializerOutputs} from '../output-migration';
const enum SupportedMigrations {
inputs = 'inputs',
outputs = 'outputs',
queries = 'queries',
}
interface Options {
path: string;
migrations: SupportedMigrations[];
analysisDir: string;
bestEffortMode?: boolean;
insertTodos?: boolean;
}
export function migrate(options: Options): Rule {
// The migrations are independent so we can run them in any order, but we sort them here
// alphabetically so we get a consistent execution order in case of issue reports.
const migrations = options.migrations.slice().sort();
const rules: Rule[] = [];
for (const migration of migrations) {
switch (migration) {
case SupportedMigrations.inputs:
rules.push(toSignalInputs(options));
break;
case SupportedMigrations.outputs:
rules.push(toInitializerOutputs(options));
break;
case SupportedMigrations.queries:
rules.push(toSignalQueries(options));
break;
default:
throw new SchematicsException(`Unsupported migration "${migration}"`);
}
}
return chain(rules);
}
| {
"end_byte": 1562,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/signals/index.ts"
} |
angular/packages/core/schematics/ng-generate/signal-input-migration/BUILD.bazel_0_916 | load("//tools:defaults.bzl", "ts_library")
package(
default_visibility = [
"//packages/core/schematics:__pkg__",
"//packages/core/schematics/migrations/google3:__pkg__",
"//packages/core/schematics/ng-generate/signals:__pkg__",
"//packages/core/schematics/test:__pkg__",
],
)
filegroup(
name = "static_files",
srcs = ["schema.json"],
)
ts_library(
name = "signal-input-migration",
srcs = glob(["**/*.ts"]),
tsconfig = "//packages/core/schematics:tsconfig.json",
deps = [
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/core/schematics/migrations/signal-migration/src",
"//packages/core/schematics/utils",
"//packages/core/schematics/utils/tsurge",
"//packages/core/schematics/utils/tsurge/helpers/angular_devkit",
"@npm//@angular-devkit/schematics",
"@npm//@types/node",
],
)
| {
"end_byte": 916,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/signal-input-migration/BUILD.bazel"
} |
angular/packages/core/schematics/ng-generate/signal-input-migration/index.ts_0_5068 | /**
* @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} from '@angular-devkit/schematics';
import {SignalInputMigration} from '../../migrations/signal-migration/src';
import {getProjectTsConfigPaths} from '../../utils/project_tsconfig_paths';
import {DevkitMigrationFilesystem} from '../../utils/tsurge/helpers/angular_devkit/devkit_filesystem';
import {groupReplacementsByFile} from '../../utils/tsurge/helpers/group_replacements';
import {setFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system';
import {CompilationUnitData} from '../../migrations/signal-migration/src/batch/unit_data';
import {ProjectRootRelativePath, TextUpdate} from '../../utils/tsurge';
import {synchronouslyCombineUnitData} from '../../utils/tsurge/helpers/combine_units';
interface Options {
path: string;
bestEffortMode?: boolean;
insertTodos?: boolean;
analysisDir: string;
}
export function migrate(options: Options): Rule {
return async (tree, context) => {
const {buildPaths, testPaths} = await getProjectTsConfigPaths(tree);
if (!buildPaths.length && !testPaths.length) {
throw new SchematicsException(
'Could not find any tsconfig file. Cannot run signal input migration.',
);
}
const fs = new DevkitMigrationFilesystem(tree);
setFileSystem(fs);
const migration = new SignalInputMigration({
bestEffortMode: options.bestEffortMode,
insertTodosForSkippedFields: options.insertTodos,
shouldMigrateInput: (input) => {
return (
input.file.rootRelativePath.startsWith(fs.normalize(options.path)) &&
!/(^|\/)node_modules\//.test(input.file.rootRelativePath)
);
},
});
const analysisPath = fs.resolve(options.analysisDir);
const unitResults: CompilationUnitData[] = [];
const programInfos = [...buildPaths, ...testPaths].map((tsconfigPath) => {
context.logger.info(`Preparing analysis for: ${tsconfigPath}..`);
const baseInfo = migration.createProgram(tsconfigPath, fs);
const info = migration.prepareProgram(baseInfo);
// Support restricting the analysis to subfolders for larger projects.
if (analysisPath !== '/') {
info.sourceFiles = info.sourceFiles.filter((sf) => sf.fileName.startsWith(analysisPath));
info.fullProgramSourceFiles = info.fullProgramSourceFiles.filter((sf) =>
sf.fileName.startsWith(analysisPath),
);
}
return {info, tsconfigPath};
});
// Analyze phase. Treat all projects as compilation units as
// this allows us to support references between those.
for (const {info, tsconfigPath} of programInfos) {
context.logger.info(`Scanning for inputs: ${tsconfigPath}..`);
unitResults.push(await migration.analyze(info));
}
context.logger.info(``);
context.logger.info(`Processing analysis data between targets..`);
context.logger.info(``);
const combined = await synchronouslyCombineUnitData(migration, unitResults);
if (combined === null) {
context.logger.error('Migration failed unexpectedly with no analysis data');
return;
}
const globalMeta = await migration.globalMeta(combined);
const replacementsPerFile: Map<ProjectRootRelativePath, TextUpdate[]> = new Map();
for (const {info, tsconfigPath} of programInfos) {
context.logger.info(`Migrating: ${tsconfigPath}..`);
const {replacements} = await migration.migrate(globalMeta, info);
const changesPerFile = groupReplacementsByFile(replacements);
for (const [file, changes] of changesPerFile) {
if (!replacementsPerFile.has(file)) {
replacementsPerFile.set(file, changes);
}
}
}
context.logger.info(`Applying changes..`);
for (const [file, changes] of replacementsPerFile) {
const recorder = tree.beginUpdate(file);
for (const c of changes) {
recorder
.remove(c.data.position, c.data.end - c.data.position)
.insertLeft(c.data.position, c.data.toInsert);
}
tree.commitUpdate(recorder);
}
const {counters} = await migration.stats(globalMeta);
const migratedInputs = counters.sourceInputs - counters.incompatibleInputs;
context.logger.info('');
context.logger.info(`Successfully migrated to signal inputs 🎉`);
context.logger.info(` -> Migrated ${migratedInputs}/${counters.sourceInputs} inputs.`);
if (counters.incompatibleInputs > 0 && !options.insertTodos) {
context.logger.warn(`To see why ${counters.incompatibleInputs} inputs couldn't be migrated`);
context.logger.warn(`consider re-running with "--insert-todos" or "--best-effort-mode".`);
}
if (options.bestEffortMode) {
context.logger.warn(
`You ran with best effort mode. Manually verify all code ` +
`works as intended, and fix where necessary.`,
);
}
};
}
| {
"end_byte": 5068,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/signal-input-migration/index.ts"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/to-standalone.ts_0_8985 | /*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgtscProgram} from '@angular/compiler-cli';
import {
PotentialImport,
PotentialImportKind,
PotentialImportMode,
Reference,
TemplateTypeChecker,
} from '@angular/compiler-cli/private/migrations';
import ts from 'typescript';
import {ChangesByFile, ChangeTracker, ImportRemapper} from '../../utils/change_tracker';
import {getAngularDecorators, NgDecorator} from '../../utils/ng_decorators';
import {getImportSpecifier} from '../../utils/typescript/imports';
import {closestNode} from '../../utils/typescript/nodes';
import {isReferenceToImport} from '../../utils/typescript/symbol';
import {
findClassDeclaration,
findLiteralProperty,
isClassReferenceInAngularModule,
NamedClassDeclaration,
} from './util';
/**
* Function that can be used to prcess the dependencies that
* are going to be added to the imports of a component.
*/
export type ComponentImportsRemapper = (
imports: PotentialImport[],
component: ts.ClassDeclaration,
) => PotentialImport[];
/**
* Converts all declarations in the specified files to standalone.
* @param sourceFiles Files that should be migrated.
* @param program
* @param printer
* @param fileImportRemapper Optional function that can be used to remap file-level imports.
* @param componentImportRemapper Optional function that can be used to remap component-level
* imports.
*/
export function toStandalone(
sourceFiles: ts.SourceFile[],
program: NgtscProgram,
printer: ts.Printer,
fileImportRemapper?: ImportRemapper,
componentImportRemapper?: ComponentImportsRemapper,
): ChangesByFile {
const templateTypeChecker = program.compiler.getTemplateTypeChecker();
const typeChecker = program.getTsProgram().getTypeChecker();
const modulesToMigrate = new Set<ts.ClassDeclaration>();
const testObjectsToMigrate = new Set<ts.ObjectLiteralExpression>();
const declarations = new Set<ts.ClassDeclaration>();
const tracker = new ChangeTracker(printer, fileImportRemapper);
for (const sourceFile of sourceFiles) {
const modules = findNgModuleClassesToMigrate(sourceFile, typeChecker);
const testObjects = findTestObjectsToMigrate(sourceFile, typeChecker);
for (const module of modules) {
const allModuleDeclarations = extractDeclarationsFromModule(module, templateTypeChecker);
const unbootstrappedDeclarations = filterNonBootstrappedDeclarations(
allModuleDeclarations,
module,
templateTypeChecker,
typeChecker,
);
if (unbootstrappedDeclarations.length > 0) {
modulesToMigrate.add(module);
unbootstrappedDeclarations.forEach((decl) => declarations.add(decl));
}
}
testObjects.forEach((obj) => testObjectsToMigrate.add(obj));
}
for (const declaration of declarations) {
convertNgModuleDeclarationToStandalone(
declaration,
declarations,
tracker,
templateTypeChecker,
componentImportRemapper,
);
}
for (const node of modulesToMigrate) {
migrateNgModuleClass(node, declarations, tracker, typeChecker, templateTypeChecker);
}
migrateTestDeclarations(
testObjectsToMigrate,
declarations,
tracker,
templateTypeChecker,
typeChecker,
);
return tracker.recordChanges();
}
/**
* Converts a single declaration defined through an NgModule to standalone.
* @param decl Declaration being converted.
* @param tracker Tracker used to track the file changes.
* @param allDeclarations All the declarations that are being converted as a part of this migration.
* @param typeChecker
* @param importRemapper
*/
export function convertNgModuleDeclarationToStandalone(
decl: ts.ClassDeclaration,
allDeclarations: Set<ts.ClassDeclaration>,
tracker: ChangeTracker,
typeChecker: TemplateTypeChecker,
importRemapper?: ComponentImportsRemapper,
): void {
const directiveMeta = typeChecker.getDirectiveMetadata(decl);
if (directiveMeta && directiveMeta.decorator && !directiveMeta.isStandalone) {
let decorator = markDecoratorAsStandalone(directiveMeta.decorator);
if (directiveMeta.isComponent) {
const importsToAdd = getComponentImportExpressions(
decl,
allDeclarations,
tracker,
typeChecker,
importRemapper,
);
if (importsToAdd.length > 0) {
const hasTrailingComma =
importsToAdd.length > 2 &&
!!extractMetadataLiteral(directiveMeta.decorator)?.properties.hasTrailingComma;
decorator = setPropertyOnAngularDecorator(
decorator,
'imports',
ts.factory.createArrayLiteralExpression(
// Create a multi-line array when it has a trailing comma.
ts.factory.createNodeArray(importsToAdd, hasTrailingComma),
hasTrailingComma,
),
);
}
}
tracker.replaceNode(directiveMeta.decorator, decorator);
} else {
const pipeMeta = typeChecker.getPipeMetadata(decl);
if (pipeMeta && pipeMeta.decorator && !pipeMeta.isStandalone) {
tracker.replaceNode(pipeMeta.decorator, markDecoratorAsStandalone(pipeMeta.decorator));
}
}
}
/**
* Gets the expressions that should be added to a component's
* `imports` array based on its template dependencies.
* @param decl Component class declaration.
* @param allDeclarations All the declarations that are being converted as a part of this migration.
* @param tracker
* @param typeChecker
* @param importRemapper
*/
function getComponentImportExpressions(
decl: ts.ClassDeclaration,
allDeclarations: Set<ts.ClassDeclaration>,
tracker: ChangeTracker,
typeChecker: TemplateTypeChecker,
importRemapper?: ComponentImportsRemapper,
): ts.Expression[] {
const templateDependencies = findTemplateDependencies(decl, typeChecker);
const usedDependenciesInMigration = new Set(
templateDependencies.filter((dep) => allDeclarations.has(dep.node)),
);
const seenImports = new Set<string>();
const resolvedDependencies: PotentialImport[] = [];
for (const dep of templateDependencies) {
const importLocation = findImportLocation(
dep as Reference<NamedClassDeclaration>,
decl,
usedDependenciesInMigration.has(dep)
? PotentialImportMode.ForceDirect
: PotentialImportMode.Normal,
typeChecker,
);
if (importLocation && !seenImports.has(importLocation.symbolName)) {
seenImports.add(importLocation.symbolName);
resolvedDependencies.push(importLocation);
}
}
return potentialImportsToExpressions(resolvedDependencies, decl, tracker, importRemapper);
}
/**
* Converts an array of potential imports to an array of expressions that can be
* added to the `imports` array.
* @param potentialImports Imports to be converted.
* @param component Component class to which the imports will be added.
* @param tracker
* @param importRemapper
*/
export function potentialImportsToExpressions(
potentialImports: PotentialImport[],
component: ts.ClassDeclaration,
tracker: ChangeTracker,
importRemapper?: ComponentImportsRemapper,
): ts.Expression[] {
const processedDependencies = importRemapper
? importRemapper(potentialImports, component)
: potentialImports;
return processedDependencies.map((importLocation) => {
if (importLocation.moduleSpecifier) {
return tracker.addImport(
component.getSourceFile(),
importLocation.symbolName,
importLocation.moduleSpecifier,
);
}
const identifier = ts.factory.createIdentifier(importLocation.symbolName);
if (!importLocation.isForwardReference) {
return identifier;
}
const forwardRefExpression = tracker.addImport(
component.getSourceFile(),
'forwardRef',
'@angular/core',
);
const arrowFunction = ts.factory.createArrowFunction(
undefined,
undefined,
[],
undefined,
undefined,
identifier,
);
return ts.factory.createCallExpression(forwardRefExpression, undefined, [arrowFunction]);
});
}
/**
* Moves all of the declarations of a class decorated with `@NgModule` to its imports.
* @param node Class being migrated.
* @param allDeclarations All the declarations that are being converted as a part of this migration.
* @param tracker
* @param typeChecker
* @param templateTypeChecker
*/
function migrateNgModuleClass(
node: ts.ClassDeclaration,
allDeclarations: Set<ts.ClassDeclaration>,
tracker: ChangeTracker,
typeChecker: ts.TypeChecker,
templateTypeChecker: TemplateTypeChecker,
) {
const decorator = templateTypeChecker.getNgModuleMetadata(node)?.decorator;
const metadata = decorator ? extractMetadataLiteral(decorator) : null;
if (metadata) {
moveDeclarationsToImports(metadata, allDeclarations, typeChecker, templateTypeChecker, tracker);
}
} | {
"end_byte": 8985,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/to-standalone.ts"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/to-standalone.ts_8987_18110 | /**
* Moves all the symbol references from the `declarations` array to the `imports`
* array of an `NgModule` class and removes the `declarations`.
* @param literal Object literal used to configure the module that should be migrated.
* @param allDeclarations All the declarations that are being converted as a part of this migration.
* @param typeChecker
* @param tracker
*/
function moveDeclarationsToImports(
literal: ts.ObjectLiteralExpression,
allDeclarations: Set<ts.ClassDeclaration>,
typeChecker: ts.TypeChecker,
templateTypeChecker: TemplateTypeChecker,
tracker: ChangeTracker,
): void {
const declarationsProp = findLiteralProperty(literal, 'declarations');
if (!declarationsProp) {
return;
}
const declarationsToPreserve: ts.Expression[] = [];
const declarationsToCopy: ts.Expression[] = [];
const properties: ts.ObjectLiteralElementLike[] = [];
const importsProp = findLiteralProperty(literal, 'imports');
const hasAnyArrayTrailingComma = literal.properties.some(
(prop) =>
ts.isPropertyAssignment(prop) &&
ts.isArrayLiteralExpression(prop.initializer) &&
prop.initializer.elements.hasTrailingComma,
);
// Separate the declarations that we want to keep and ones we need to copy into the `imports`.
if (ts.isPropertyAssignment(declarationsProp)) {
// If the declarations are an array, we can analyze it to
// find any classes from the current migration.
if (ts.isArrayLiteralExpression(declarationsProp.initializer)) {
for (const el of declarationsProp.initializer.elements) {
if (ts.isIdentifier(el)) {
const correspondingClass = findClassDeclaration(el, typeChecker);
if (
!correspondingClass ||
// Check whether the declaration is either standalone already or is being converted
// in this migration. We need to check if it's standalone already, in order to correct
// some cases where the main app and the test files are being migrated in separate
// programs.
isStandaloneDeclaration(correspondingClass, allDeclarations, templateTypeChecker)
) {
declarationsToCopy.push(el);
} else {
declarationsToPreserve.push(el);
}
} else {
declarationsToCopy.push(el);
}
}
} else {
// Otherwise create a spread that will be copied into the `imports`.
declarationsToCopy.push(ts.factory.createSpreadElement(declarationsProp.initializer));
}
}
// If there are no `imports`, create them with the declarations we want to copy.
if (!importsProp && declarationsToCopy.length > 0) {
properties.push(
ts.factory.createPropertyAssignment(
'imports',
ts.factory.createArrayLiteralExpression(
ts.factory.createNodeArray(
declarationsToCopy,
hasAnyArrayTrailingComma && declarationsToCopy.length > 2,
),
),
),
);
}
for (const prop of literal.properties) {
if (!isNamedPropertyAssignment(prop)) {
properties.push(prop);
continue;
}
// If we have declarations to preserve, update the existing property, otherwise drop it.
if (prop === declarationsProp) {
if (declarationsToPreserve.length > 0) {
const hasTrailingComma = ts.isArrayLiteralExpression(prop.initializer)
? prop.initializer.elements.hasTrailingComma
: hasAnyArrayTrailingComma;
properties.push(
ts.factory.updatePropertyAssignment(
prop,
prop.name,
ts.factory.createArrayLiteralExpression(
ts.factory.createNodeArray(
declarationsToPreserve,
hasTrailingComma && declarationsToPreserve.length > 2,
),
),
),
);
}
continue;
}
// If we have an `imports` array and declarations
// that should be copied, we merge the two arrays.
if (prop === importsProp && declarationsToCopy.length > 0) {
let initializer: ts.Expression;
if (ts.isArrayLiteralExpression(prop.initializer)) {
initializer = ts.factory.updateArrayLiteralExpression(
prop.initializer,
ts.factory.createNodeArray(
[...prop.initializer.elements, ...declarationsToCopy],
prop.initializer.elements.hasTrailingComma,
),
);
} else {
initializer = ts.factory.createArrayLiteralExpression(
ts.factory.createNodeArray(
[ts.factory.createSpreadElement(prop.initializer), ...declarationsToCopy],
// Expect the declarations to be greater than 1 since
// we have the pre-existing initializer already.
hasAnyArrayTrailingComma && declarationsToCopy.length > 1,
),
);
}
properties.push(ts.factory.updatePropertyAssignment(prop, prop.name, initializer));
continue;
}
// Retain any remaining properties.
properties.push(prop);
}
tracker.replaceNode(
literal,
ts.factory.updateObjectLiteralExpression(
literal,
ts.factory.createNodeArray(properties, literal.properties.hasTrailingComma),
),
ts.EmitHint.Expression,
);
}
/** Sets a decorator node to be standalone. */
function markDecoratorAsStandalone(node: ts.Decorator): ts.Decorator {
const metadata = extractMetadataLiteral(node);
if (metadata === null || !ts.isCallExpression(node.expression)) {
return node;
}
const standaloneProp = metadata.properties.find((prop) => {
return isNamedPropertyAssignment(prop) && prop.name.text === 'standalone';
}) as ts.PropertyAssignment | undefined;
// In v19 standalone is the default so don't do anything if there's no `standalone`
// property or it's initialized to anything other than `false`.
if (!standaloneProp || standaloneProp.initializer.kind !== ts.SyntaxKind.FalseKeyword) {
return node;
}
const newProperties = metadata.properties.filter((element) => element !== standaloneProp);
// Use `createDecorator` instead of `updateDecorator`, because
// the latter ends up duplicating the node's leading comment.
return ts.factory.createDecorator(
ts.factory.createCallExpression(node.expression.expression, node.expression.typeArguments, [
ts.factory.createObjectLiteralExpression(
ts.factory.createNodeArray(newProperties, metadata.properties.hasTrailingComma),
newProperties.length > 1,
),
]),
);
}
/**
* Sets a property on an Angular decorator node. If the property
* already exists, its initializer will be replaced.
* @param node Decorator to which to add the property.
* @param name Name of the property to be added.
* @param initializer Initializer for the new property.
*/
function setPropertyOnAngularDecorator(
node: ts.Decorator,
name: string,
initializer: ts.Expression,
): ts.Decorator {
// Invalid decorator.
if (!ts.isCallExpression(node.expression) || node.expression.arguments.length > 1) {
return node;
}
let literalProperties: ts.ObjectLiteralElementLike[];
let hasTrailingComma = false;
if (node.expression.arguments.length === 0) {
literalProperties = [ts.factory.createPropertyAssignment(name, initializer)];
} else if (ts.isObjectLiteralExpression(node.expression.arguments[0])) {
const literal = node.expression.arguments[0];
const existingProperty = findLiteralProperty(literal, name);
hasTrailingComma = literal.properties.hasTrailingComma;
if (existingProperty && ts.isPropertyAssignment(existingProperty)) {
literalProperties = literal.properties.slice();
literalProperties[literalProperties.indexOf(existingProperty)] =
ts.factory.updatePropertyAssignment(existingProperty, existingProperty.name, initializer);
} else {
literalProperties = [
...literal.properties,
ts.factory.createPropertyAssignment(name, initializer),
];
}
} else {
// Unsupported case (e.g. `@Component(SOME_CONST)`). Return the original node.
return node;
}
// Use `createDecorator` instead of `updateDecorator`, because
// the latter ends up duplicating the node's leading comment.
return ts.factory.createDecorator(
ts.factory.createCallExpression(node.expression.expression, node.expression.typeArguments, [
ts.factory.createObjectLiteralExpression(
ts.factory.createNodeArray(literalProperties, hasTrailingComma),
literalProperties.length > 1,
),
]),
);
}
/** Checks if a node is a `PropertyAssignment` with a name. */
function isNamedPropertyAssignment(
node: ts.Node,
): node is ts.PropertyAssignment & {name: ts.Identifier} {
return ts.isPropertyAssignment(node) && node.name && ts.isIdentifier(node.name);
}
/**
* Finds the import from which to bring in a template dependency of a component.
* @param target Dependency that we're searching for.
* @param inComponent Component in which the dependency is used.
* @param importMode Mode in which to resolve the import target.
* @param typeChecker
*/ | {
"end_byte": 18110,
"start_byte": 8987,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/to-standalone.ts"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/to-standalone.ts_18111_26098 | export function findImportLocation(
target: Reference<NamedClassDeclaration>,
inComponent: ts.ClassDeclaration,
importMode: PotentialImportMode,
typeChecker: TemplateTypeChecker,
): PotentialImport | null {
const importLocations = typeChecker.getPotentialImportsFor(target, inComponent, importMode);
let firstSameFileImport: PotentialImport | null = null;
let firstModuleImport: PotentialImport | null = null;
for (const location of importLocations) {
// Prefer a standalone import, if we can find one.
// Otherwise fall back to the first module-based import.
if (location.kind === PotentialImportKind.Standalone) {
return location;
}
if (!location.moduleSpecifier && !firstSameFileImport) {
firstSameFileImport = location;
}
if (
location.kind === PotentialImportKind.NgModule &&
!firstModuleImport &&
// ɵ is used for some internal Angular modules that we want to skip over.
!location.symbolName.startsWith('ɵ')
) {
firstModuleImport = location;
}
}
return firstSameFileImport || firstModuleImport || importLocations[0] || null;
}
/**
* Checks whether a node is an `NgModule` metadata element with at least one element.
* E.g. `declarations: [Foo]` or `declarations: SOME_VAR` would match this description,
* but not `declarations: []`.
*/
function hasNgModuleMetadataElements(node: ts.Node): node is ts.PropertyAssignment {
return (
ts.isPropertyAssignment(node) &&
(!ts.isArrayLiteralExpression(node.initializer) || node.initializer.elements.length > 0)
);
}
/** Finds all modules whose declarations can be migrated. */
function findNgModuleClassesToMigrate(sourceFile: ts.SourceFile, typeChecker: ts.TypeChecker) {
const modules: ts.ClassDeclaration[] = [];
if (getImportSpecifier(sourceFile, '@angular/core', 'NgModule')) {
sourceFile.forEachChild(function walk(node) {
if (ts.isClassDeclaration(node)) {
const decorator = getAngularDecorators(typeChecker, ts.getDecorators(node) || []).find(
(current) => current.name === 'NgModule',
);
const metadata = decorator ? extractMetadataLiteral(decorator.node) : null;
if (metadata) {
const declarations = findLiteralProperty(metadata, 'declarations');
if (declarations != null && hasNgModuleMetadataElements(declarations)) {
modules.push(node);
}
}
}
node.forEachChild(walk);
});
}
return modules;
}
/** Finds all testing object literals that need to be migrated. */
export function findTestObjectsToMigrate(sourceFile: ts.SourceFile, typeChecker: ts.TypeChecker) {
const testObjects: ts.ObjectLiteralExpression[] = [];
const testBedImport = getImportSpecifier(sourceFile, '@angular/core/testing', 'TestBed');
const catalystImport = getImportSpecifier(sourceFile, /testing\/catalyst$/, 'setupModule');
if (testBedImport || catalystImport) {
sourceFile.forEachChild(function walk(node) {
const isObjectLiteralCall =
ts.isCallExpression(node) &&
node.arguments.length > 0 &&
// `arguments[0]` is the testing module config.
ts.isObjectLiteralExpression(node.arguments[0]);
const config = isObjectLiteralCall ? (node.arguments[0] as ts.ObjectLiteralExpression) : null;
const isTestBedCall =
isObjectLiteralCall &&
testBedImport &&
ts.isPropertyAccessExpression(node.expression) &&
node.expression.name.text === 'configureTestingModule' &&
isReferenceToImport(typeChecker, node.expression.expression, testBedImport);
const isCatalystCall =
isObjectLiteralCall &&
catalystImport &&
ts.isIdentifier(node.expression) &&
isReferenceToImport(typeChecker, node.expression, catalystImport);
if ((isTestBedCall || isCatalystCall) && config) {
const declarations = findLiteralProperty(config, 'declarations');
if (
declarations &&
ts.isPropertyAssignment(declarations) &&
ts.isArrayLiteralExpression(declarations.initializer) &&
declarations.initializer.elements.length > 0
) {
testObjects.push(config);
}
}
node.forEachChild(walk);
});
}
return testObjects;
}
/**
* Finds the classes corresponding to dependencies used in a component's template.
* @param decl Component in whose template we're looking for dependencies.
* @param typeChecker
*/
export function findTemplateDependencies(
decl: ts.ClassDeclaration,
typeChecker: TemplateTypeChecker,
): Reference<NamedClassDeclaration>[] {
const results: Reference<NamedClassDeclaration>[] = [];
const usedDirectives = typeChecker.getUsedDirectives(decl);
const usedPipes = typeChecker.getUsedPipes(decl);
if (usedDirectives !== null) {
for (const dir of usedDirectives) {
if (ts.isClassDeclaration(dir.ref.node)) {
results.push(dir.ref as Reference<NamedClassDeclaration>);
}
}
}
if (usedPipes !== null) {
const potentialPipes = typeChecker.getPotentialPipes(decl);
for (const pipe of potentialPipes) {
if (
ts.isClassDeclaration(pipe.ref.node) &&
usedPipes.some((current) => pipe.name === current)
) {
results.push(pipe.ref as Reference<NamedClassDeclaration>);
}
}
}
return results;
}
/**
* Removes any declarations that are a part of a module's `bootstrap`
* array from an array of declarations.
* @param declarations Anaalyzed declarations of the module.
* @param ngModule Module whote declarations are being filtered.
* @param templateTypeChecker
* @param typeChecker
*/
function filterNonBootstrappedDeclarations(
declarations: ts.ClassDeclaration[],
ngModule: ts.ClassDeclaration,
templateTypeChecker: TemplateTypeChecker,
typeChecker: ts.TypeChecker,
) {
const metadata = templateTypeChecker.getNgModuleMetadata(ngModule);
const metaLiteral =
metadata && metadata.decorator ? extractMetadataLiteral(metadata.decorator) : null;
const bootstrapProp = metaLiteral ? findLiteralProperty(metaLiteral, 'bootstrap') : null;
// If there's no `bootstrap`, we can't filter.
if (!bootstrapProp) {
return declarations;
}
// If we can't analyze the `bootstrap` property, we can't safely determine which
// declarations aren't bootstrapped so we assume that all of them are.
if (
!ts.isPropertyAssignment(bootstrapProp) ||
!ts.isArrayLiteralExpression(bootstrapProp.initializer)
) {
return [];
}
const bootstrappedClasses = new Set<ts.ClassDeclaration>();
for (const el of bootstrapProp.initializer.elements) {
const referencedClass = ts.isIdentifier(el) ? findClassDeclaration(el, typeChecker) : null;
// If we can resolve an element to a class, we can filter it out,
// otherwise assume that the array isn't static.
if (referencedClass) {
bootstrappedClasses.add(referencedClass);
} else {
return [];
}
}
return declarations.filter((ref) => !bootstrappedClasses.has(ref));
}
/**
* Extracts all classes that are referenced in a module's `declarations` array.
* @param ngModule Module whose declarations are being extraced.
* @param templateTypeChecker
*/
export function extractDeclarationsFromModule(
ngModule: ts.ClassDeclaration,
templateTypeChecker: TemplateTypeChecker,
): ts.ClassDeclaration[] {
const metadata = templateTypeChecker.getNgModuleMetadata(ngModule);
return metadata
? (metadata.declarations
.filter((decl) => ts.isClassDeclaration(decl.node))
.map((decl) => decl.node) as ts.ClassDeclaration[])
: [];
}
/**
* Migrates the `declarations` from a unit test file to standalone.
* @param testObjects Object literals used to configure the testing modules.
* @param declarationsOutsideOfTestFiles Non-testing declarations that are part of this migration.
* @param tracker
* @param templateTypeChecker
* @param typeChecker
*/
e | {
"end_byte": 26098,
"start_byte": 18111,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/to-standalone.ts"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/to-standalone.ts_26099_32656 | port function migrateTestDeclarations(
testObjects: Set<ts.ObjectLiteralExpression>,
declarationsOutsideOfTestFiles: Set<ts.ClassDeclaration>,
tracker: ChangeTracker,
templateTypeChecker: TemplateTypeChecker,
typeChecker: ts.TypeChecker,
) {
const {decorators, componentImports} = analyzeTestingModules(testObjects, typeChecker);
const allDeclarations = new Set(declarationsOutsideOfTestFiles);
for (const decorator of decorators) {
const closestClass = closestNode(decorator.node, ts.isClassDeclaration);
if (decorator.name === 'Pipe' || decorator.name === 'Directive') {
tracker.replaceNode(decorator.node, markDecoratorAsStandalone(decorator.node));
if (closestClass) {
allDeclarations.add(closestClass);
}
} else if (decorator.name === 'Component') {
const newDecorator = markDecoratorAsStandalone(decorator.node);
const importsToAdd = componentImports.get(decorator.node);
if (closestClass) {
allDeclarations.add(closestClass);
}
if (importsToAdd && importsToAdd.size > 0) {
const hasTrailingComma =
importsToAdd.size > 2 &&
!!extractMetadataLiteral(decorator.node)?.properties.hasTrailingComma;
const importsArray = ts.factory.createNodeArray(Array.from(importsToAdd), hasTrailingComma);
tracker.replaceNode(
decorator.node,
setPropertyOnAngularDecorator(
newDecorator,
'imports',
ts.factory.createArrayLiteralExpression(importsArray),
),
);
} else {
tracker.replaceNode(decorator.node, newDecorator);
}
}
}
for (const obj of testObjects) {
moveDeclarationsToImports(obj, allDeclarations, typeChecker, templateTypeChecker, tracker);
}
}
/**
* Analyzes a set of objects used to configure testing modules and returns the AST
* nodes that need to be migrated and the imports that should be added to the imports
* of any declared components.
* @param testObjects Object literals that should be analyzed.
*/
function analyzeTestingModules(
testObjects: Set<ts.ObjectLiteralExpression>,
typeChecker: ts.TypeChecker,
) {
const seenDeclarations = new Set<ts.Declaration>();
const decorators: NgDecorator[] = [];
const componentImports = new Map<ts.Decorator, Set<ts.Expression>>();
for (const obj of testObjects) {
const declarations = extractDeclarationsFromTestObject(obj, typeChecker);
if (declarations.length === 0) {
continue;
}
const importsProp = findLiteralProperty(obj, 'imports');
const importElements =
importsProp &&
hasNgModuleMetadataElements(importsProp) &&
ts.isArrayLiteralExpression(importsProp.initializer)
? importsProp.initializer.elements.filter((el) => {
// Filter out calls since they may be a `ModuleWithProviders`.
return (
!ts.isCallExpression(el) &&
// Also filter out the animations modules since they throw errors if they're imported
// multiple times and it's common for apps to use the `NoopAnimationsModule` to
// disable animations in screenshot tests.
!isClassReferenceInAngularModule(
el,
/^BrowserAnimationsModule|NoopAnimationsModule$/,
'platform-browser/animations',
typeChecker,
)
);
})
: null;
for (const decl of declarations) {
if (seenDeclarations.has(decl)) {
continue;
}
const [decorator] = getAngularDecorators(typeChecker, ts.getDecorators(decl) || []);
if (decorator) {
seenDeclarations.add(decl);
decorators.push(decorator);
if (decorator.name === 'Component' && importElements) {
// We try to de-duplicate the imports being added to a component, because it may be
// declared in different testing modules with a different set of imports.
let imports = componentImports.get(decorator.node);
if (!imports) {
imports = new Set();
componentImports.set(decorator.node, imports);
}
importElements.forEach((imp) => imports!.add(imp));
}
}
}
}
return {decorators, componentImports};
}
/**
* Finds the class declarations that are being referred
* to in the `declarations` of an object literal.
* @param obj Object literal that may contain the declarations.
* @param typeChecker
*/
function extractDeclarationsFromTestObject(
obj: ts.ObjectLiteralExpression,
typeChecker: ts.TypeChecker,
): ts.ClassDeclaration[] {
const results: ts.ClassDeclaration[] = [];
const declarations = findLiteralProperty(obj, 'declarations');
if (
declarations &&
hasNgModuleMetadataElements(declarations) &&
ts.isArrayLiteralExpression(declarations.initializer)
) {
for (const element of declarations.initializer.elements) {
const declaration = findClassDeclaration(element, typeChecker);
// Note that we only migrate classes that are in the same file as the testing module,
// because external fixture components are somewhat rare and handling them is going
// to involve a lot of assumptions that are likely to be incorrect.
if (declaration && declaration.getSourceFile().fileName === obj.getSourceFile().fileName) {
results.push(declaration);
}
}
}
return results;
}
/** Extracts the metadata object literal from an Angular decorator. */
function extractMetadataLiteral(decorator: ts.Decorator): ts.ObjectLiteralExpression | null {
// `arguments[0]` is the metadata object literal.
return ts.isCallExpression(decorator.expression) &&
decorator.expression.arguments.length === 1 &&
ts.isObjectLiteralExpression(decorator.expression.arguments[0])
? decorator.expression.arguments[0]
: null;
}
/**
* Checks whether a class is a standalone declaration.
* @param node Class being checked.
* @param declarationsInMigration Classes that are being converted to standalone in this migration.
* @param templateTypeChecker
*/
function isStandaloneDeclaration(
node: ts.ClassDeclaration,
declarationsInMigration: Set<ts.ClassDeclaration>,
templateTypeChecker: TemplateTypeChecker,
): boolean {
if (declarationsInMigration.has(node)) {
return true;
}
const metadata =
templateTypeChecker.getDirectiveMetadata(node) || templateTypeChecker.getPipeMetadata(node);
return metadata != null && metadata.isStandalone;
}
| {
"end_byte": 32656,
"start_byte": 26099,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/to-standalone.ts"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/standalone-bootstrap.ts_0_6260 | /*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgtscProgram} from '@angular/compiler-cli';
import {TemplateTypeChecker} from '@angular/compiler-cli/private/migrations';
import {dirname, join} from 'path';
import ts from 'typescript';
import {ChangeTracker, ImportRemapper} from '../../utils/change_tracker';
import {getAngularDecorators} from '../../utils/ng_decorators';
import {closestNode} from '../../utils/typescript/nodes';
import {
ComponentImportsRemapper,
convertNgModuleDeclarationToStandalone,
extractDeclarationsFromModule,
findTestObjectsToMigrate,
migrateTestDeclarations,
} from './to-standalone';
import {
closestOrSelf,
findClassDeclaration,
findLiteralProperty,
getNodeLookup,
getRelativeImportPath,
isClassReferenceInAngularModule,
NamedClassDeclaration,
NodeLookup,
offsetsToNodes,
ReferenceResolver,
UniqueItemTracker,
} from './util';
/** Information extracted from a `bootstrapModule` call necessary to migrate it. */
interface BootstrapCallAnalysis {
/** The call itself. */
call: ts.CallExpression;
/** Class that is being bootstrapped. */
module: ts.ClassDeclaration;
/** Metadata of the module class being bootstrapped. */
metadata: ts.ObjectLiteralExpression;
/** Component that the module is bootstrapping. */
component: NamedClassDeclaration;
/** Classes declared by the bootstrapped module. */
declarations: ts.ClassDeclaration[];
}
export function toStandaloneBootstrap(
program: NgtscProgram,
host: ts.CompilerHost,
basePath: string,
rootFileNames: string[],
sourceFiles: ts.SourceFile[],
printer: ts.Printer,
importRemapper?: ImportRemapper,
referenceLookupExcludedFiles?: RegExp,
componentImportRemapper?: ComponentImportsRemapper,
) {
const tracker = new ChangeTracker(printer, importRemapper);
const typeChecker = program.getTsProgram().getTypeChecker();
const templateTypeChecker = program.compiler.getTemplateTypeChecker();
const referenceResolver = new ReferenceResolver(
program,
host,
rootFileNames,
basePath,
referenceLookupExcludedFiles,
);
const bootstrapCalls: BootstrapCallAnalysis[] = [];
const testObjects = new Set<ts.ObjectLiteralExpression>();
const allDeclarations = new Set<ts.ClassDeclaration>();
// `bootstrapApplication` doesn't include Protractor support by default
// anymore so we have to opt the app in, if we detect it being used.
const additionalProviders = hasImport(program, rootFileNames, 'protractor')
? new Map([['provideProtractorTestingSupport', '@angular/platform-browser']])
: null;
for (const sourceFile of sourceFiles) {
sourceFile.forEachChild(function walk(node) {
if (
ts.isCallExpression(node) &&
ts.isPropertyAccessExpression(node.expression) &&
node.expression.name.text === 'bootstrapModule' &&
isClassReferenceInAngularModule(node.expression, 'PlatformRef', 'core', typeChecker)
) {
const call = analyzeBootstrapCall(node, typeChecker, templateTypeChecker);
if (call) {
bootstrapCalls.push(call);
}
}
node.forEachChild(walk);
});
findTestObjectsToMigrate(sourceFile, typeChecker).forEach((obj) => testObjects.add(obj));
}
for (const call of bootstrapCalls) {
call.declarations.forEach((decl) => allDeclarations.add(decl));
migrateBootstrapCall(
call,
tracker,
additionalProviders,
referenceResolver,
typeChecker,
printer,
);
}
// The previous migrations explicitly skip over bootstrapped
// declarations so we have to migrate them now.
for (const declaration of allDeclarations) {
convertNgModuleDeclarationToStandalone(
declaration,
allDeclarations,
tracker,
templateTypeChecker,
componentImportRemapper,
);
}
migrateTestDeclarations(testObjects, allDeclarations, tracker, templateTypeChecker, typeChecker);
return tracker.recordChanges();
}
/**
* Extracts all of the information from a `bootstrapModule` call
* necessary to convert it to `bootstrapApplication`.
* @param call Call to be analyzed.
* @param typeChecker
* @param templateTypeChecker
*/
function analyzeBootstrapCall(
call: ts.CallExpression,
typeChecker: ts.TypeChecker,
templateTypeChecker: TemplateTypeChecker,
): BootstrapCallAnalysis | null {
if (call.arguments.length === 0 || !ts.isIdentifier(call.arguments[0])) {
return null;
}
const declaration = findClassDeclaration(call.arguments[0], typeChecker);
if (!declaration) {
return null;
}
const decorator = getAngularDecorators(typeChecker, ts.getDecorators(declaration) || []).find(
(decorator) => decorator.name === 'NgModule',
);
if (
!decorator ||
decorator.node.expression.arguments.length === 0 ||
!ts.isObjectLiteralExpression(decorator.node.expression.arguments[0])
) {
return null;
}
const metadata = decorator.node.expression.arguments[0];
const bootstrapProp = findLiteralProperty(metadata, 'bootstrap');
if (
!bootstrapProp ||
!ts.isPropertyAssignment(bootstrapProp) ||
!ts.isArrayLiteralExpression(bootstrapProp.initializer) ||
bootstrapProp.initializer.elements.length === 0 ||
!ts.isIdentifier(bootstrapProp.initializer.elements[0])
) {
return null;
}
const component = findClassDeclaration(bootstrapProp.initializer.elements[0], typeChecker);
if (component && component.name && ts.isIdentifier(component.name)) {
return {
module: declaration,
metadata,
component: component as NamedClassDeclaration,
call,
declarations: extractDeclarationsFromModule(declaration, templateTypeChecker),
};
}
return null;
}
/**
* Converts a `bootstrapModule` call to `bootstrapApplication`.
* @param analysis Analysis result of the call.
* @param tracker Tracker in which to register the changes.
* @param additionalFeatures Additional providers, apart from the auto-detected ones, that should
* be added to the bootstrap call.
* @param referenceResolver
* @param typeChecker
* @param printer
*/ | {
"end_byte": 6260,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/standalone-bootstrap.ts"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/standalone-bootstrap.ts_6261_12303 | function migrateBootstrapCall(
analysis: BootstrapCallAnalysis,
tracker: ChangeTracker,
additionalProviders: Map<string, string> | null,
referenceResolver: ReferenceResolver,
typeChecker: ts.TypeChecker,
printer: ts.Printer,
) {
const sourceFile = analysis.call.getSourceFile();
const moduleSourceFile = analysis.metadata.getSourceFile();
const providers = findLiteralProperty(analysis.metadata, 'providers');
const imports = findLiteralProperty(analysis.metadata, 'imports');
const nodesToCopy = new Set<ts.Node>();
const providersInNewCall: ts.Expression[] = [];
const moduleImportsInNewCall: ts.Expression[] = [];
let nodeLookup: NodeLookup | null = null;
// Comment out the metadata so that it'll be removed when we run the module pruning afterwards.
// If the pruning is left for some reason, the user will still have an actionable TODO.
tracker.insertText(
moduleSourceFile,
analysis.metadata.getStart(),
'/* TODO(standalone-migration): clean up removed NgModule class manually. \n',
);
tracker.insertText(moduleSourceFile, analysis.metadata.getEnd(), ' */');
if (providers && ts.isPropertyAssignment(providers)) {
nodeLookup = nodeLookup || getNodeLookup(moduleSourceFile);
if (ts.isArrayLiteralExpression(providers.initializer)) {
providersInNewCall.push(...providers.initializer.elements);
} else {
providersInNewCall.push(ts.factory.createSpreadElement(providers.initializer));
}
addNodesToCopy(sourceFile, providers, nodeLookup, tracker, nodesToCopy, referenceResolver);
}
if (imports && ts.isPropertyAssignment(imports)) {
nodeLookup = nodeLookup || getNodeLookup(moduleSourceFile);
migrateImportsForBootstrapCall(
sourceFile,
imports,
nodeLookup,
moduleImportsInNewCall,
providersInNewCall,
tracker,
nodesToCopy,
referenceResolver,
typeChecker,
);
}
if (additionalProviders) {
additionalProviders.forEach((moduleSpecifier, name) => {
providersInNewCall.push(
ts.factory.createCallExpression(
tracker.addImport(sourceFile, name, moduleSpecifier),
undefined,
undefined,
),
);
});
}
if (nodesToCopy.size > 0) {
let text = '\n\n';
nodesToCopy.forEach((node) => {
const transformedNode = remapDynamicImports(sourceFile.fileName, node);
// Use `getText` to try an preserve the original formatting. This only works if the node
// hasn't been transformed. If it has, we have to fall back to the printer.
if (transformedNode === node) {
text += transformedNode.getText() + '\n';
} else {
text += printer.printNode(ts.EmitHint.Unspecified, transformedNode, node.getSourceFile());
}
});
text += '\n';
tracker.insertText(sourceFile, getLastImportEnd(sourceFile), text);
}
replaceBootstrapCallExpression(analysis, providersInNewCall, moduleImportsInNewCall, tracker);
}
/**
* Replaces a `bootstrapModule` call with `bootstrapApplication`.
* @param analysis Analysis result of the `bootstrapModule` call.
* @param providers Providers that should be added to the new call.
* @param modules Modules that are being imported into the new call.
* @param tracker Object keeping track of the changes to the different files.
*/
function replaceBootstrapCallExpression(
analysis: BootstrapCallAnalysis,
providers: ts.Expression[],
modules: ts.Expression[],
tracker: ChangeTracker,
): void {
const sourceFile = analysis.call.getSourceFile();
const componentPath = getRelativeImportPath(
sourceFile.fileName,
analysis.component.getSourceFile().fileName,
);
const args = [tracker.addImport(sourceFile, analysis.component.name.text, componentPath)];
const bootstrapExpression = tracker.addImport(
sourceFile,
'bootstrapApplication',
'@angular/platform-browser',
);
if (providers.length > 0 || modules.length > 0) {
const combinedProviders: ts.Expression[] = [];
if (modules.length > 0) {
const importProvidersExpression = tracker.addImport(
sourceFile,
'importProvidersFrom',
'@angular/core',
);
combinedProviders.push(
ts.factory.createCallExpression(importProvidersExpression, [], modules),
);
}
// Push the providers after `importProvidersFrom` call for better readability.
combinedProviders.push(...providers);
const providersArray = ts.factory.createNodeArray(
combinedProviders,
analysis.metadata.properties.hasTrailingComma && combinedProviders.length > 2,
);
const initializer = remapDynamicImports(
sourceFile.fileName,
ts.factory.createArrayLiteralExpression(providersArray, combinedProviders.length > 1),
);
args.push(
ts.factory.createObjectLiteralExpression(
[ts.factory.createPropertyAssignment('providers', initializer)],
true,
),
);
}
tracker.replaceNode(
analysis.call,
ts.factory.createCallExpression(bootstrapExpression, [], args),
// Note: it's important to pass in the source file that the nodes originated from!
// Otherwise TS won't print out literals inside of the providers that we're copying
// over from the module file.
undefined,
analysis.metadata.getSourceFile(),
);
}
/**
* Processes the `imports` of an NgModule so that they can be used in the `bootstrapApplication`
* call inside of a different file.
* @param sourceFile File to which the imports will be moved.
* @param imports Node declaring the imports.
* @param nodeLookup Map used to look up nodes based on their positions in a file.
* @param importsForNewCall Array keeping track of the imports that are being added to the new call.
* @param providersInNewCall Array keeping track of the providers in the new call.
* @param tracker Tracker in which changes to files are being stored.
* @param nodesToCopy Nodes that should be copied to the new file.
* @param referenceResolver
* @param typeChecker
*/ | {
"end_byte": 12303,
"start_byte": 6261,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/standalone-bootstrap.ts"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/standalone-bootstrap.ts_12304_21129 | function migrateImportsForBootstrapCall(
sourceFile: ts.SourceFile,
imports: ts.PropertyAssignment,
nodeLookup: NodeLookup,
importsForNewCall: ts.Expression[],
providersInNewCall: ts.Expression[],
tracker: ChangeTracker,
nodesToCopy: Set<ts.Node>,
referenceResolver: ReferenceResolver,
typeChecker: ts.TypeChecker,
): void {
if (!ts.isArrayLiteralExpression(imports.initializer)) {
importsForNewCall.push(imports.initializer);
return;
}
for (const element of imports.initializer.elements) {
// If the reference is to a `RouterModule.forRoot` call, we can try to migrate it.
if (
ts.isCallExpression(element) &&
ts.isPropertyAccessExpression(element.expression) &&
element.arguments.length > 0 &&
element.expression.name.text === 'forRoot' &&
isClassReferenceInAngularModule(
element.expression.expression,
'RouterModule',
'router',
typeChecker,
)
) {
const options = element.arguments[1] as ts.Expression | undefined;
const features = options ? getRouterModuleForRootFeatures(sourceFile, options, tracker) : [];
// If the features come back as null, it means that the router
// has a configuration that can't be migrated automatically.
if (features !== null) {
providersInNewCall.push(
ts.factory.createCallExpression(
tracker.addImport(sourceFile, 'provideRouter', '@angular/router'),
[],
[element.arguments[0], ...features],
),
);
addNodesToCopy(
sourceFile,
element.arguments[0],
nodeLookup,
tracker,
nodesToCopy,
referenceResolver,
);
if (options) {
addNodesToCopy(sourceFile, options, nodeLookup, tracker, nodesToCopy, referenceResolver);
}
continue;
}
}
if (ts.isIdentifier(element)) {
// `BrowserAnimationsModule` can be replaced with `provideAnimations`.
const animationsModule = 'platform-browser/animations';
const animationsImport = `@angular/${animationsModule}`;
if (
isClassReferenceInAngularModule(
element,
'BrowserAnimationsModule',
animationsModule,
typeChecker,
)
) {
providersInNewCall.push(
ts.factory.createCallExpression(
tracker.addImport(sourceFile, 'provideAnimations', animationsImport),
[],
[],
),
);
continue;
}
// `NoopAnimationsModule` can be replaced with `provideNoopAnimations`.
if (
isClassReferenceInAngularModule(
element,
'NoopAnimationsModule',
animationsModule,
typeChecker,
)
) {
providersInNewCall.push(
ts.factory.createCallExpression(
tracker.addImport(sourceFile, 'provideNoopAnimations', animationsImport),
[],
[],
),
);
continue;
}
// `HttpClientModule` can be replaced with `provideHttpClient()`.
const httpClientModule = 'common/http';
const httpClientImport = `@angular/${httpClientModule}`;
if (
isClassReferenceInAngularModule(element, 'HttpClientModule', httpClientModule, typeChecker)
) {
const callArgs = [
// we add `withInterceptorsFromDi()` to the call to ensure that class-based interceptors
// still work
ts.factory.createCallExpression(
tracker.addImport(sourceFile, 'withInterceptorsFromDi', httpClientImport),
[],
[],
),
];
providersInNewCall.push(
ts.factory.createCallExpression(
tracker.addImport(sourceFile, 'provideHttpClient', httpClientImport),
[],
callArgs,
),
);
continue;
}
}
const target =
// If it's a call, it'll likely be a `ModuleWithProviders`
// expression so the target is going to be call's expression.
ts.isCallExpression(element) && ts.isPropertyAccessExpression(element.expression)
? element.expression.expression
: element;
const classDeclaration = findClassDeclaration(target, typeChecker);
const decorators = classDeclaration
? getAngularDecorators(typeChecker, ts.getDecorators(classDeclaration) || [])
: undefined;
if (
!decorators ||
decorators.length === 0 ||
decorators.every(({name}) => name !== 'Directive' && name !== 'Component' && name !== 'Pipe')
) {
importsForNewCall.push(element);
addNodesToCopy(sourceFile, element, nodeLookup, tracker, nodesToCopy, referenceResolver);
}
}
}
/**
* Generates the call expressions that can be used to replace the options
* object that is passed into a `RouterModule.forRoot` call.
* @param sourceFile File that the `forRoot` call is coming from.
* @param options Node that is passed as the second argument to the `forRoot` call.
* @param tracker Tracker in which to track imports that need to be inserted.
* @returns Null if the options can't be migrated, otherwise an array of call expressions.
*/
function getRouterModuleForRootFeatures(
sourceFile: ts.SourceFile,
options: ts.Expression,
tracker: ChangeTracker,
): ts.CallExpression[] | null {
// Options that aren't a static object literal can't be migrated.
if (!ts.isObjectLiteralExpression(options)) {
return null;
}
const featureExpressions: ts.CallExpression[] = [];
const configOptions: ts.PropertyAssignment[] = [];
const inMemoryScrollingOptions: ts.PropertyAssignment[] = [];
const features = new UniqueItemTracker<string, ts.Expression | null>();
for (const prop of options.properties) {
// We can't migrate options that we can't easily analyze.
if (
!ts.isPropertyAssignment(prop) ||
(!ts.isIdentifier(prop.name) && !ts.isStringLiteralLike(prop.name))
) {
return null;
}
switch (prop.name.text) {
// `preloadingStrategy` maps to the `withPreloading` function.
case 'preloadingStrategy':
features.track('withPreloading', prop.initializer);
break;
// `enableTracing: true` maps to the `withDebugTracing` feature.
case 'enableTracing':
if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) {
features.track('withDebugTracing', null);
}
break;
// `initialNavigation: 'enabled'` and `initialNavigation: 'enabledBlocking'` map to the
// `withEnabledBlockingInitialNavigation` feature, while `initialNavigation: 'disabled'` maps
// to the `withDisabledInitialNavigation` feature.
case 'initialNavigation':
if (!ts.isStringLiteralLike(prop.initializer)) {
return null;
}
if (prop.initializer.text === 'enabledBlocking' || prop.initializer.text === 'enabled') {
features.track('withEnabledBlockingInitialNavigation', null);
} else if (prop.initializer.text === 'disabled') {
features.track('withDisabledInitialNavigation', null);
}
break;
// `useHash: true` maps to the `withHashLocation` feature.
case 'useHash':
if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) {
features.track('withHashLocation', null);
}
break;
// `errorHandler` maps to the `withNavigationErrorHandler` feature.
case 'errorHandler':
features.track('withNavigationErrorHandler', prop.initializer);
break;
// `anchorScrolling` and `scrollPositionRestoration` arguments have to be combined into an
// object literal that is passed into the `withInMemoryScrolling` feature.
case 'anchorScrolling':
case 'scrollPositionRestoration':
inMemoryScrollingOptions.push(prop);
break;
// All remaining properties can be passed through the `withRouterConfig` feature.
default:
configOptions.push(prop);
break;
}
}
if (inMemoryScrollingOptions.length > 0) {
features.track(
'withInMemoryScrolling',
ts.factory.createObjectLiteralExpression(inMemoryScrollingOptions),
);
}
if (configOptions.length > 0) {
features.track('withRouterConfig', ts.factory.createObjectLiteralExpression(configOptions));
}
for (const [feature, featureArgs] of features.getEntries()) {
const callArgs: ts.Expression[] = [];
featureArgs.forEach((arg) => {
if (arg !== null) {
callArgs.push(arg);
}
});
featureExpressions.push(
ts.factory.createCallExpression(
tracker.addImport(sourceFile, feature, '@angular/router'),
[],
callArgs,
),
);
}
return featureExpressions;
} | {
"end_byte": 21129,
"start_byte": 12304,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/standalone-bootstrap.ts"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/standalone-bootstrap.ts_21131_30065 | /**
* Finds all the nodes that are referenced inside a root node and would need to be copied into a
* new file in order for the node to compile, and tracks them.
* @param targetFile File to which the nodes will be copied.
* @param rootNode Node within which to look for references.
* @param nodeLookup Map used to look up nodes based on their positions in a file.
* @param tracker Tracker in which changes to files are stored.
* @param nodesToCopy Set that keeps track of the nodes being copied.
* @param referenceResolver
*/
function addNodesToCopy(
targetFile: ts.SourceFile,
rootNode: ts.Node,
nodeLookup: NodeLookup,
tracker: ChangeTracker,
nodesToCopy: Set<ts.Node>,
referenceResolver: ReferenceResolver,
): void {
const refs = findAllSameFileReferences(rootNode, nodeLookup, referenceResolver);
for (const ref of refs) {
const importSpecifier = closestOrSelf(ref, ts.isImportSpecifier);
const importDeclaration = importSpecifier
? closestNode(importSpecifier, ts.isImportDeclaration)
: null;
// If the reference is in an import, we need to add an import to the main file.
if (
importDeclaration &&
importSpecifier &&
ts.isStringLiteralLike(importDeclaration.moduleSpecifier)
) {
const moduleName = importDeclaration.moduleSpecifier.text.startsWith('.')
? remapRelativeImport(targetFile.fileName, importDeclaration.moduleSpecifier)
: importDeclaration.moduleSpecifier.text;
const symbolName = importSpecifier.propertyName
? importSpecifier.propertyName.text
: importSpecifier.name.text;
const alias = importSpecifier.propertyName ? importSpecifier.name.text : undefined;
tracker.addImport(targetFile, symbolName, moduleName, alias);
continue;
}
const variableDeclaration = closestOrSelf(ref, ts.isVariableDeclaration);
const variableStatement = variableDeclaration
? closestNode(variableDeclaration, ts.isVariableStatement)
: null;
// If the reference is a variable, we can attempt to import it or copy it over.
if (variableDeclaration && variableStatement && ts.isIdentifier(variableDeclaration.name)) {
if (isExported(variableStatement)) {
tracker.addImport(
targetFile,
variableDeclaration.name.text,
getRelativeImportPath(targetFile.fileName, ref.getSourceFile().fileName),
);
} else {
nodesToCopy.add(variableStatement);
}
continue;
}
// Otherwise check if the reference is inside of an exportable declaration, e.g. a function.
// This code that is safe to copy over into the new file or import it, if it's exported.
const closestExportable = closestOrSelf(ref, isExportableDeclaration);
if (closestExportable) {
if (isExported(closestExportable) && closestExportable.name) {
tracker.addImport(
targetFile,
closestExportable.name.text,
getRelativeImportPath(targetFile.fileName, ref.getSourceFile().fileName),
);
} else {
nodesToCopy.add(closestExportable);
}
}
}
}
/**
* Finds all the nodes referenced within the root node in the same file.
* @param rootNode Node from which to start looking for references.
* @param nodeLookup Map used to look up nodes based on their positions in a file.
* @param referenceResolver
*/
function findAllSameFileReferences(
rootNode: ts.Node,
nodeLookup: NodeLookup,
referenceResolver: ReferenceResolver,
): Set<ts.Node> {
const results = new Set<ts.Node>();
const traversedTopLevelNodes = new Set<ts.Node>();
const excludeStart = rootNode.getStart();
const excludeEnd = rootNode.getEnd();
(function walk(node) {
if (!isReferenceIdentifier(node)) {
node.forEachChild(walk);
return;
}
const refs = referencesToNodeWithinSameFile(
node,
nodeLookup,
excludeStart,
excludeEnd,
referenceResolver,
);
if (refs === null) {
return;
}
for (const ref of refs) {
if (results.has(ref)) {
continue;
}
results.add(ref);
const closestTopLevel = closestNode(ref, isTopLevelStatement);
// Avoid re-traversing the same top-level nodes since we know what the result will be.
if (!closestTopLevel || traversedTopLevelNodes.has(closestTopLevel)) {
continue;
}
// Keep searching, starting from the closest top-level node. We skip import declarations,
// because we already know about them and they may put the search into an infinite loop.
if (
!ts.isImportDeclaration(closestTopLevel) &&
isOutsideRange(
excludeStart,
excludeEnd,
closestTopLevel.getStart(),
closestTopLevel.getEnd(),
)
) {
traversedTopLevelNodes.add(closestTopLevel);
walk(closestTopLevel);
}
}
})(rootNode);
return results;
}
/**
* Finds all the nodes referring to a specific node within the same file.
* @param node Node whose references we're lookip for.
* @param nodeLookup Map used to look up nodes based on their positions in a file.
* @param excludeStart Start of a range that should be excluded from the results.
* @param excludeEnd End of a range that should be excluded from the results.
* @param referenceResolver
*/
function referencesToNodeWithinSameFile(
node: ts.Identifier,
nodeLookup: NodeLookup,
excludeStart: number,
excludeEnd: number,
referenceResolver: ReferenceResolver,
): Set<ts.Node> | null {
const offsets = referenceResolver
.findSameFileReferences(node, node.getSourceFile().fileName)
.filter(([start, end]) => isOutsideRange(excludeStart, excludeEnd, start, end));
if (offsets.length > 0) {
const nodes = offsetsToNodes(nodeLookup, offsets, new Set());
if (nodes.size > 0) {
return nodes;
}
}
return null;
}
/**
* Transforms a node so that any dynamic imports with relative file paths it contains are remapped
* as if they were specified in a different file. If no transformations have occurred, the original
* node will be returned.
* @param targetFileName File name to which to remap the imports.
* @param rootNode Node being transformed.
*/
function remapDynamicImports<T extends ts.Node>(targetFileName: string, rootNode: T): T {
let hasChanged = false;
const transformer: ts.TransformerFactory<ts.Node> = (context) => {
return (sourceFile) =>
ts.visitNode(sourceFile, function walk(node: ts.Node): ts.Node {
if (
ts.isCallExpression(node) &&
node.expression.kind === ts.SyntaxKind.ImportKeyword &&
node.arguments.length > 0 &&
ts.isStringLiteralLike(node.arguments[0]) &&
node.arguments[0].text.startsWith('.')
) {
hasChanged = true;
return context.factory.updateCallExpression(node, node.expression, node.typeArguments, [
context.factory.createStringLiteral(
remapRelativeImport(targetFileName, node.arguments[0]),
),
...node.arguments.slice(1),
]);
}
return ts.visitEachChild(node, walk, context);
});
};
const result = ts.transform(rootNode, [transformer]).transformed[0] as T;
return hasChanged ? result : rootNode;
}
/**
* Checks whether a node is a statement at the top level of a file.
* @param node Node to be checked.
*/
function isTopLevelStatement(node: ts.Node): node is ts.Node {
return node.parent != null && ts.isSourceFile(node.parent);
}
/**
* Asserts that a node is an identifier that might be referring to a symbol. This excludes
* identifiers of named nodes like property assignments.
* @param node Node to be checked.
*/
function isReferenceIdentifier(node: ts.Node): node is ts.Identifier {
return (
ts.isIdentifier(node) &&
((!ts.isPropertyAssignment(node.parent) && !ts.isParameter(node.parent)) ||
node.parent.name !== node)
);
}
/**
* Checks whether a range is completely outside of another range.
* @param excludeStart Start of the exclusion range.
* @param excludeEnd End of the exclusion range.
* @param start Start of the range that is being checked.
* @param end End of the range that is being checked.
*/
function isOutsideRange(
excludeStart: number,
excludeEnd: number,
start: number,
end: number,
): boolean {
return (start < excludeStart && end < excludeStart) || start > excludeEnd;
}
/**
* Remaps the specifier of a relative import from its original location to a new one.
* @param targetFileName Name of the file that the specifier will be moved to.
* @param specifier Specifier whose path is being remapped.
*/
function remapRelativeImport(targetFileName: string, specifier: ts.StringLiteralLike): string {
return getRelativeImportPath(
targetFileName,
join(dirname(specifier.getSourceFile().fileName), specifier.text),
);
} | {
"end_byte": 30065,
"start_byte": 21131,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/standalone-bootstrap.ts"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/standalone-bootstrap.ts_30067_32160 | /**
* Whether a node is exported.
* @param node Node to be checked.
*/
function isExported(node: ts.Node): node is ts.Node {
return ts.canHaveModifiers(node) && node.modifiers
? node.modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)
: false;
}
/**
* Asserts that a node is an exportable declaration, which means that it can either be exported or
* it can be safely copied into another file.
* @param node Node to be checked.
*/
function isExportableDeclaration(
node: ts.Node,
): node is
| ts.EnumDeclaration
| ts.ClassDeclaration
| ts.FunctionDeclaration
| ts.InterfaceDeclaration
| ts.TypeAliasDeclaration {
return (
ts.isEnumDeclaration(node) ||
ts.isClassDeclaration(node) ||
ts.isFunctionDeclaration(node) ||
ts.isInterfaceDeclaration(node) ||
ts.isTypeAliasDeclaration(node)
);
}
/**
* Gets the index after the last import in a file. Can be used to insert new code into the file.
* @param sourceFile File in which to search for imports.
*/
function getLastImportEnd(sourceFile: ts.SourceFile): number {
let index = 0;
for (const statement of sourceFile.statements) {
if (ts.isImportDeclaration(statement)) {
index = Math.max(index, statement.getEnd());
} else {
break;
}
}
return index;
}
/** Checks if any of the program's files has an import of a specific module. */
function hasImport(program: NgtscProgram, rootFileNames: string[], moduleName: string): boolean {
const tsProgram = program.getTsProgram();
const deepImportStart = moduleName + '/';
for (const fileName of rootFileNames) {
const sourceFile = tsProgram.getSourceFile(fileName);
if (!sourceFile) {
continue;
}
for (const statement of sourceFile.statements) {
if (
ts.isImportDeclaration(statement) &&
ts.isStringLiteralLike(statement.moduleSpecifier) &&
(statement.moduleSpecifier.text === moduleName ||
statement.moduleSpecifier.text.startsWith(deepImportStart))
) {
return true;
}
}
}
return false;
} | {
"end_byte": 32160,
"start_byte": 30067,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/standalone-bootstrap.ts"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/prune-modules.ts_0_7974 | /*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgtscProgram} from '@angular/compiler-cli';
import ts from 'typescript';
import {ChangeTracker, ImportRemapper} from '../../utils/change_tracker';
import {getAngularDecorators, NgDecorator} from '../../utils/ng_decorators';
import {closestNode} from '../../utils/typescript/nodes';
import {
findClassDeclaration,
findLiteralProperty,
getNodeLookup,
NamedClassDeclaration,
offsetsToNodes,
ReferenceResolver,
UniqueItemTracker,
} from './util';
import {
PotentialImport,
PotentialImportMode,
Reference,
TemplateTypeChecker,
} from '@angular/compiler-cli/private/migrations';
import {
ComponentImportsRemapper,
findImportLocation,
findTemplateDependencies,
potentialImportsToExpressions,
} from './to-standalone';
/** Keeps track of the places from which we need to remove AST nodes. */
interface RemovalLocations {
arrays: UniqueItemTracker<ts.ArrayLiteralExpression, ts.Node>;
imports: UniqueItemTracker<ts.NamedImports, ts.Node>;
exports: UniqueItemTracker<ts.NamedExports, ts.Node>;
unknown: Set<ts.Node>;
}
export function pruneNgModules(
program: NgtscProgram,
host: ts.CompilerHost,
basePath: string,
rootFileNames: string[],
sourceFiles: ts.SourceFile[],
printer: ts.Printer,
importRemapper?: ImportRemapper,
referenceLookupExcludedFiles?: RegExp,
componentImportRemapper?: ComponentImportsRemapper,
) {
const filesToRemove = new Set<ts.SourceFile>();
const tracker = new ChangeTracker(printer, importRemapper);
const tsProgram = program.getTsProgram();
const typeChecker = tsProgram.getTypeChecker();
const templateTypeChecker = program.compiler.getTemplateTypeChecker();
const referenceResolver = new ReferenceResolver(
program,
host,
rootFileNames,
basePath,
referenceLookupExcludedFiles,
);
const removalLocations: RemovalLocations = {
arrays: new UniqueItemTracker<ts.ArrayLiteralExpression, ts.Node>(),
imports: new UniqueItemTracker<ts.NamedImports, ts.Node>(),
exports: new UniqueItemTracker<ts.NamedExports, ts.Node>(),
unknown: new Set<ts.Node>(),
};
const classesToRemove = new Set<ts.ClassDeclaration>();
const barrelExports = new UniqueItemTracker<ts.SourceFile, ts.ExportDeclaration>();
const componentImportArrays = new UniqueItemTracker<ts.ArrayLiteralExpression, ts.Node>();
const nodesToRemove = new Set<ts.Node>();
sourceFiles.forEach(function walk(node: ts.Node) {
if (ts.isClassDeclaration(node) && canRemoveClass(node, typeChecker)) {
collectChangeLocations(
node,
removalLocations,
componentImportArrays,
templateTypeChecker,
referenceResolver,
program,
);
classesToRemove.add(node);
} else if (
ts.isExportDeclaration(node) &&
!node.exportClause &&
node.moduleSpecifier &&
ts.isStringLiteralLike(node.moduleSpecifier) &&
node.moduleSpecifier.text.startsWith('.')
) {
const exportedSourceFile = typeChecker
.getSymbolAtLocation(node.moduleSpecifier)
?.valueDeclaration?.getSourceFile();
if (exportedSourceFile) {
barrelExports.track(exportedSourceFile, node);
}
}
node.forEachChild(walk);
});
replaceInImportsArray(
componentImportArrays,
classesToRemove,
tracker,
typeChecker,
templateTypeChecker,
componentImportRemapper,
);
// We collect all the places where we need to remove references first before generating the
// removal instructions since we may have to remove multiple references from one node.
removeArrayReferences(removalLocations.arrays, tracker);
removeImportReferences(removalLocations.imports, tracker);
removeExportReferences(removalLocations.exports, tracker);
addRemovalTodos(removalLocations.unknown, tracker);
// Collect all the nodes to be removed before determining which files to delete since we need
// to know it ahead of time when deleting barrel files that export other barrel files.
(function trackNodesToRemove(nodes: Set<ts.Node>) {
for (const node of nodes) {
const sourceFile = node.getSourceFile();
if (!filesToRemove.has(sourceFile) && canRemoveFile(sourceFile, nodes)) {
const barrelExportsForFile = barrelExports.get(sourceFile);
nodesToRemove.add(node);
filesToRemove.add(sourceFile);
barrelExportsForFile && trackNodesToRemove(barrelExportsForFile);
} else {
nodesToRemove.add(node);
}
}
})(classesToRemove);
for (const node of nodesToRemove) {
const sourceFile = node.getSourceFile();
if (!filesToRemove.has(sourceFile) && canRemoveFile(sourceFile, nodesToRemove)) {
filesToRemove.add(sourceFile);
} else {
tracker.removeNode(node);
}
}
return {pendingChanges: tracker.recordChanges(), filesToRemove};
}
/**
* Collects all the nodes that a module needs to be removed from.
* @param ngModule Module being removed.
* @param removalLocations Tracks the different places from which the class should be removed.
* @param componentImportArrays Set of `imports` arrays of components that need to be adjusted.
* @param referenceResolver
* @param program
*/
function collectChangeLocations(
ngModule: ts.ClassDeclaration,
removalLocations: RemovalLocations,
componentImportArrays: UniqueItemTracker<ts.ArrayLiteralExpression, ts.Node>,
templateTypeChecker: TemplateTypeChecker,
referenceResolver: ReferenceResolver,
program: NgtscProgram,
) {
const refsByFile = referenceResolver.findReferencesInProject(ngModule.name!);
const tsProgram = program.getTsProgram();
const nodes = new Set<ts.Node>();
for (const [fileName, refs] of refsByFile) {
const sourceFile = tsProgram.getSourceFile(fileName);
if (sourceFile) {
offsetsToNodes(getNodeLookup(sourceFile), refs, nodes);
}
}
for (const node of nodes) {
const closestArray = closestNode(node, ts.isArrayLiteralExpression);
if (closestArray) {
const closestAssignment = closestNode(closestArray, ts.isPropertyAssignment);
// If the module was flagged as being removable, but it's still being used in a standalone
// component's `imports` array, it means that it was likely changed outside of the migration
// and deleting it now will be breaking. Track it separately so it can be handled properly.
if (closestAssignment && isInImportsArray(closestAssignment, closestArray)) {
const closestDecorator = closestNode(closestAssignment, ts.isDecorator);
const closestClass = closestDecorator
? closestNode(closestDecorator, ts.isClassDeclaration)
: null;
const directiveMeta = closestClass
? templateTypeChecker.getDirectiveMetadata(closestClass)
: null;
if (directiveMeta && directiveMeta.isComponent && directiveMeta.isStandalone) {
componentImportArrays.track(closestArray, node);
continue;
}
}
removalLocations.arrays.track(closestArray, node);
continue;
}
const closestImport = closestNode(node, ts.isNamedImports);
if (closestImport) {
removalLocations.imports.track(closestImport, node);
continue;
}
const closestExport = closestNode(node, ts.isNamedExports);
if (closestExport) {
removalLocations.exports.track(closestExport, node);
continue;
}
removalLocations.unknown.add(node);
}
}
/**
* Replaces all the leftover modules in imports arrays with their exports.
* @param componentImportArrays All the imports arrays and their nodes that represent NgModules.
* @param classesToRemove Set of classes that were marked for removal.
* @param tracker
* @param typeChecker
* @param templateTypeChecker
* @param importRemapper
*/ | {
"end_byte": 7974,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/prune-modules.ts"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/prune-modules.ts_7975_14547 | function replaceInImportsArray(
componentImportArrays: UniqueItemTracker<ts.ArrayLiteralExpression, ts.Node>,
classesToRemove: Set<ts.ClassDeclaration>,
tracker: ChangeTracker,
typeChecker: ts.TypeChecker,
templateTypeChecker: TemplateTypeChecker,
importRemapper?: ComponentImportsRemapper,
) {
for (const [array, toReplace] of componentImportArrays.getEntries()) {
const closestClass = closestNode(array, ts.isClassDeclaration);
if (!closestClass) {
continue;
}
const replacements = new UniqueItemTracker<ts.Node, Reference<NamedClassDeclaration>>();
const usedImports = new Set(
findTemplateDependencies(closestClass, templateTypeChecker).map((ref) => ref.node),
);
for (const node of toReplace) {
const moduleDecl = findClassDeclaration(node, typeChecker);
if (moduleDecl) {
const moduleMeta = templateTypeChecker.getNgModuleMetadata(moduleDecl);
if (moduleMeta) {
moduleMeta.exports.forEach((exp) => {
if (usedImports.has(exp.node as NamedClassDeclaration)) {
replacements.track(node, exp as Reference<NamedClassDeclaration>);
}
});
} else {
// It's unlikely not to have module metadata at this point, but just in
// case unmark the class for removal to reduce the chance of breakages.
classesToRemove.delete(moduleDecl);
}
}
}
replaceModulesInImportsArray(
array,
closestClass,
replacements,
tracker,
templateTypeChecker,
importRemapper,
);
}
}
/**
* Replaces any leftover modules in `imports` arrays with their exports that are used within a
* component.
* @param array Imports array which is being migrated.
* @param componentClass Class that the imports array belongs to.
* @param replacements Map of NgModule references to their exports.
* @param tracker
* @param templateTypeChecker
* @param importRemapper
*/
function replaceModulesInImportsArray(
array: ts.ArrayLiteralExpression,
componentClass: ts.ClassDeclaration,
replacements: UniqueItemTracker<ts.Node, Reference<NamedClassDeclaration>>,
tracker: ChangeTracker,
templateTypeChecker: TemplateTypeChecker,
importRemapper?: ComponentImportsRemapper,
): void {
const newElements: ts.Expression[] = [];
for (const element of array.elements) {
const replacementRefs = replacements.get(element);
if (!replacementRefs) {
newElements.push(element);
continue;
}
const potentialImports: PotentialImport[] = [];
for (const ref of replacementRefs) {
const importLocation = findImportLocation(
ref,
componentClass,
PotentialImportMode.Normal,
templateTypeChecker,
);
if (importLocation) {
potentialImports.push(importLocation);
}
}
newElements.push(
...potentialImportsToExpressions(potentialImports, componentClass, tracker, importRemapper),
);
}
tracker.replaceNode(array, ts.factory.updateArrayLiteralExpression(array, newElements));
}
/**
* Removes all tracked array references.
* @param locations Locations from which to remove the references.
* @param tracker Tracker in which to register the changes.
*/
function removeArrayReferences(
locations: UniqueItemTracker<ts.ArrayLiteralExpression, ts.Node>,
tracker: ChangeTracker,
): void {
for (const [array, toRemove] of locations.getEntries()) {
const newElements = filterRemovedElements(array.elements, toRemove);
tracker.replaceNode(
array,
ts.factory.updateArrayLiteralExpression(
array,
ts.factory.createNodeArray(newElements, array.elements.hasTrailingComma),
),
);
}
}
/**
* Removes all tracked import references.
* @param locations Locations from which to remove the references.
* @param tracker Tracker in which to register the changes.
*/
function removeImportReferences(
locations: UniqueItemTracker<ts.NamedImports, ts.Node>,
tracker: ChangeTracker,
) {
for (const [namedImports, toRemove] of locations.getEntries()) {
const newElements = filterRemovedElements(namedImports.elements, toRemove);
// If no imports are left, we can try to drop the entire import.
if (newElements.length === 0) {
const importClause = closestNode(namedImports, ts.isImportClause);
// If the import clause has a name we can only drop then named imports.
// e.g. `import Foo, {ModuleToRemove} from './foo';` becomes `import Foo from './foo';`.
if (importClause && importClause.name) {
tracker.replaceNode(
importClause,
ts.factory.updateImportClause(
importClause,
importClause.isTypeOnly,
importClause.name,
undefined,
),
);
} else {
// Otherwise we can drop the entire declaration.
const declaration = closestNode(namedImports, ts.isImportDeclaration);
if (declaration) {
tracker.removeNode(declaration);
}
}
} else {
// Otherwise we just drop the imported symbols and keep the declaration intact.
tracker.replaceNode(namedImports, ts.factory.updateNamedImports(namedImports, newElements));
}
}
}
/**
* Removes all tracked export references.
* @param locations Locations from which to remove the references.
* @param tracker Tracker in which to register the changes.
*/
function removeExportReferences(
locations: UniqueItemTracker<ts.NamedExports, ts.Node>,
tracker: ChangeTracker,
) {
for (const [namedExports, toRemove] of locations.getEntries()) {
const newElements = filterRemovedElements(namedExports.elements, toRemove);
// If no exports are left, we can drop the entire declaration.
if (newElements.length === 0) {
const declaration = closestNode(namedExports, ts.isExportDeclaration);
if (declaration) {
tracker.removeNode(declaration);
}
} else {
// Otherwise we just drop the exported symbols and keep the declaration intact.
tracker.replaceNode(namedExports, ts.factory.updateNamedExports(namedExports, newElements));
}
}
}
/**
* Determines whether an `@NgModule` class is safe to remove. A module is safe to remove if:
* 1. It has no `declarations`.
* 2. It has no `providers`.
* 3. It has no `bootstrap` components.
* 4. It has no `ModuleWithProviders` in its `imports`.
* 5. It has no class members. Empty construstors are ignored.
* @param node Class that is being checked.
* @param typeChecker
*/ | {
"end_byte": 14547,
"start_byte": 7975,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/prune-modules.ts"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/prune-modules.ts_14548_21669 | function canRemoveClass(node: ts.ClassDeclaration, typeChecker: ts.TypeChecker): boolean {
const decorator = findNgModuleDecorator(node, typeChecker)?.node;
// We can't remove a declaration if it's not a valid `NgModule`.
if (!decorator || !ts.isCallExpression(decorator.expression)) {
return false;
}
// Unsupported case, e.g. `@NgModule(SOME_VALUE)`.
if (
decorator.expression.arguments.length > 0 &&
!ts.isObjectLiteralExpression(decorator.expression.arguments[0])
) {
return false;
}
// We can't remove modules that have class members. We make an exception for an
// empty constructor which may have been generated by a tool and forgotten.
if (node.members.length > 0 && node.members.some((member) => !isEmptyConstructor(member))) {
return false;
}
// An empty `NgModule` call can be removed.
if (decorator.expression.arguments.length === 0) {
return true;
}
const literal = decorator.expression.arguments[0] as ts.ObjectLiteralExpression;
const imports = findLiteralProperty(literal, 'imports');
if (imports && isNonEmptyNgModuleProperty(imports)) {
// We can't remove the class if at least one import isn't identifier, because it may be a
// `ModuleWithProviders` which is the equivalent of having something in the `providers` array.
for (const dep of imports.initializer.elements) {
if (!ts.isIdentifier(dep)) {
return false;
}
const depDeclaration = findClassDeclaration(dep, typeChecker);
const depNgModule = depDeclaration
? findNgModuleDecorator(depDeclaration, typeChecker)
: null;
// If any of the dependencies of the class is an `NgModule` that can't be removed, the class
// itself can't be removed either, because it may be part of a transitive dependency chain.
if (
depDeclaration !== null &&
depNgModule !== null &&
!canRemoveClass(depDeclaration, typeChecker)
) {
return false;
}
}
}
// We can't remove classes that have any `declarations`, `providers` or `bootstrap` elements.
// Also err on the side of caution and don't remove modules where any of the aforementioned
// properties aren't initialized to an array literal.
for (const prop of literal.properties) {
if (
isNonEmptyNgModuleProperty(prop) &&
(prop.name.text === 'declarations' ||
prop.name.text === 'providers' ||
prop.name.text === 'bootstrap')
) {
return false;
}
}
return true;
}
/**
* Checks whether a node is a non-empty property from an NgModule's metadata. This is defined as a
* property assignment with a static name, initialized to an array literal with more than one
* element.
* @param node Node to be checked.
*/
function isNonEmptyNgModuleProperty(
node: ts.Node,
): node is ts.PropertyAssignment & {name: ts.Identifier; initializer: ts.ArrayLiteralExpression} {
return (
ts.isPropertyAssignment(node) &&
ts.isIdentifier(node.name) &&
ts.isArrayLiteralExpression(node.initializer) &&
node.initializer.elements.length > 0
);
}
/**
* Determines if a file is safe to delete. A file is safe to delete if all it contains are
* import statements, class declarations that are about to be deleted and non-exported code.
* @param sourceFile File that is being checked.
* @param nodesToBeRemoved Nodes that are being removed as a part of the migration.
*/
function canRemoveFile(sourceFile: ts.SourceFile, nodesToBeRemoved: Set<ts.Node>) {
for (const node of sourceFile.statements) {
if (ts.isImportDeclaration(node) || nodesToBeRemoved.has(node)) {
continue;
}
if (
ts.isExportDeclaration(node) ||
(ts.canHaveModifiers(node) &&
ts.getModifiers(node)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword))
) {
return false;
}
}
return true;
}
/**
* Gets whether an AST node contains another AST node.
* @param parent Parent node that may contain the child.
* @param child Child node that is being checked.
*/
function contains(parent: ts.Node, child: ts.Node): boolean {
return (
parent === child ||
(parent.getSourceFile().fileName === child.getSourceFile().fileName &&
child.getStart() >= parent.getStart() &&
child.getStart() <= parent.getEnd())
);
}
/**
* Removes AST nodes from a node array.
* @param elements Array from which to remove the nodes.
* @param toRemove Nodes that should be removed.
*/
function filterRemovedElements<T extends ts.Node>(
elements: ts.NodeArray<T>,
toRemove: Set<ts.Node>,
): T[] {
return elements.filter((el) => {
for (const node of toRemove) {
// Check that the element contains the node, despite knowing with relative certainty that it
// does, because this allows us to unwrap some nodes. E.g. if we have `[((toRemove))]`, we
// want to remove the entire parenthesized expression, rather than just `toRemove`.
if (contains(el, node)) {
return false;
}
}
return true;
});
}
/** Returns whether a node as an empty constructor. */
function isEmptyConstructor(node: ts.Node): boolean {
return (
ts.isConstructorDeclaration(node) &&
node.parameters.length === 0 &&
(node.body == null || node.body.statements.length === 0)
);
}
/**
* Adds TODO comments to nodes that couldn't be removed manually.
* @param nodes Nodes to which to add the TODO.
* @param tracker Tracker in which to register the changes.
*/
function addRemovalTodos(nodes: Set<ts.Node>, tracker: ChangeTracker) {
for (const node of nodes) {
// Note: the comment is inserted using string manipulation, instead of going through the AST,
// because this way we preserve more of the app's original formatting.
// Note: in theory this can duplicate comments if the module pruning runs multiple times on
// the same node. In practice it is unlikely, because the second time the node won't be picked
// up by the language service as a reference, because the class won't exist anymore.
tracker.insertText(
node.getSourceFile(),
node.getFullStart(),
` /* TODO(standalone-migration): clean up removed NgModule reference manually. */ `,
);
}
}
/** Finds the `NgModule` decorator in a class, if it exists. */
function findNgModuleDecorator(
node: ts.ClassDeclaration,
typeChecker: ts.TypeChecker,
): NgDecorator | null {
const decorators = getAngularDecorators(typeChecker, ts.getDecorators(node) || []);
return decorators.find((decorator) => decorator.name === 'NgModule') || null;
}
/**
* Checks whether a node is used inside of an `imports` array.
* @param closestAssignment The closest property assignment to the node.
* @param closestArray The closest array to the node.
*/
function isInImportsArray(
closestAssignment: ts.PropertyAssignment,
closestArray: ts.ArrayLiteralExpression,
): boolean {
return (
closestAssignment.initializer === closestArray &&
(ts.isIdentifier(closestAssignment.name) || ts.isStringLiteralLike(closestAssignment.name)) &&
closestAssignment.name.text === 'imports'
);
} | {
"end_byte": 21669,
"start_byte": 14548,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/prune-modules.ts"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/README.md_0_1824 | # Standalone migration
`ng generate` schematic that helps users to convert an application to `standalone` components,
directives and pipes. The migration can be run with `ng generate @angular/core:standalone` and it
has the following options:
* `mode` - Configures the mode that migration should run in. The different modes are clarified
further down in this document.
* `path` - Relative path within the project that the migration should apply to. Can be used to
migrate specific sub-directories individually. Defaults to the project root.
## Migration flow
The standalone migration involves multiple distinct operations, and as such has to be run multiple
times. Authors should verify that the app still works between each of the steps. If the application
is large, it can be easier to use the `path` option to migrate specific sub-sections of the app
individually.
**Note:** The schematic often needs to generate new code or copy existing code to different places.
This means that likely the formatting won't match your app anymore and there may be some lint
failures. The application should compile, but it's expected that the author will fix up any
formatting and linting failures.
An example migration could look as follows:
1. `ng generate @angular/core:standalone`.
2. Select the "Convert all components, directives and pipes to standalone" option.
3. Verify that the app works and commit the changes.
4. `ng generate @angular/core:standalone`.
5. Select the "Remove unnecessary NgModule classes" option.
6. Verify that the app works and commit the changes.
7. `ng generate @angular/core:standalone`.
8. Select the "Bootstrap the application using standalone APIs" option.
9. Verify that the app works and commit the changes.
10. Run your linting and formatting checks, and fix any failures. Commit the result.
| {
"end_byte": 1824,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/README.md"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/README.md_1824_10183 | ## Migration modes
The migration is made up the following modes that are intended to be run in the order they are
listed in:
1. Convert declarations to standalone.
2. Remove unnecessary NgModules.
3. Switch to standalone bootstrapping API.
### Convert declarations to standalone
In this mode, the migration will find all of the components, directives and pipes, and convert them
to standalone by removing `standalone: false` and adding any dependencies to the `imports` array.
**Note:** NgModules which bootstrap a component are explicitly ignored in this step, because they
are likely to be root modules and they would have to be bootstrapped using `bootstrapApplication`
instead of `bootstrapModule`. Their declarations will be converted automatically as a part of the
"Switch to standalone bootstrapping API" step.
**Before:**
```typescript
// app.module.ts
@NgModule({
imports: [CommonModule],
declarations: [MyComp, MyDir, MyPipe]
})
export class AppModule {}
```
```typescript
// my-comp.ts
@Component({
selector: 'my-comp',
template: '<div my-dir *ngIf="showGreeting">{{ "Hello" | myPipe }}</div>',
standalone: false,
})
export class MyComp {
public showGreeting = true;
}
```
```typescript
// my-dir.ts
@Directive({selector: '[my-dir]', standalone: false})
export class MyDir {}
```
```typescript
// my-pipe.ts
@Pipe({name: 'myPipe', pure: true, standalone: false})
export class MyPipe {}
```
**After:**
```typescript
// app.module.ts
@NgModule({
imports: [CommonModule, MyComp, MyDir, MyPipe]
})
export class AppModule {}
```
```typescript
// my-comp.ts
@Component({
selector: 'my-comp',
template: '<div my-dir *ngIf="showGreeting">{{ "Hello" | myPipe }}</div>',
imports: [NgIf, MyDir, MyPipe]
})
export class MyComp {
public showGreeting = true;
}
```
```typescript
// my-dir.ts
@Directive({selector: '[my-dir]'})
export class MyDir {}
```
```typescript
// my-pipe.ts
@Pipe({name: 'myPipe', pure: true})
export class MyPipe {}
```
### Remove unnecessary NgModules
After converting all declarations to standalone, a lot of NgModules won't be necessary anymore!
This step identifies such modules and deletes them, including as many references to them, as
possible. If a module reference can't be deleted automatically, the migration will leave a TODO
comment saying `TODO(standalone-migration): clean up removed NgModule reference manually` so that
the author can delete it themselves.
A module is considered "safe to remove" if it:
* Has no `declarations`.
* Has no `providers`.
* Has no `bootstrap` components.
* Has no `imports` that reference a `ModuleWithProviders` symbol or a module that can't be removed.
* Has no class members. Empty constructors are ignored.
**Before:**
```typescript
// importer.module.ts
@NgModule({
imports: [FooComp, BarPipe],
exports: [FooComp, BarPipe]
})
export class ImporterModule {}
```
```typescript
// configurer.module.ts
import {ImporterModule} from './importer.module';
console.log(ImporterModule);
@NgModule({
imports: [ImporterModule],
exports: [ImporterModule],
providers: [{provide: FOO, useValue: 123}]
})
export class ConfigurerModule {}
```
```typescript
// index.ts
export {ImporterModule, ConfigurerModule} from './modules/index';
```
**After:**
```typescript
// importer.module.ts
// Deleted!
```
```typescript
// configurer.module.ts
console.log(/* TODO(standalone-migration): clean up removed NgModule reference manually */ ImporterModule);
@NgModule({
imports: [],
exports: [],
providers: [{provide: FOO, useValue: 123}]
})
export class ConfigurerModule {}
```
```typescript
// index.ts
export {ConfigurerModule} from './modules/index';
```
### Switch to standalone bootstrapping API
Converts any usages of the old `bootstrapModule` API to the new `bootstrapApplication`. To do this
in a safe way, the migration has to make the following changes to the application's code:
1. Generate the `bootstrapApplication` call to replace the `bootstrapModule` one.
2. Convert the `declarations` of the module that is being bootstrapped to `standalone`. These
modules were skipped explicitly in the first step of the migration.
3. Copy any `providers` from the bootstrapped module into the `providers` option of
`bootstrapApplication`.
4. Copy any classes from the `imports` array of the rootModule to the `providers` option of
`bootstrapApplication` and wrap them in an `importsProvidersFrom` function call.
5. Adjust any dynamic import paths so that they're correct when they're copied over.
6. If an API with a standalone equivalent is detected, it may be converted automatically as well.
E.g. `RouterModule.forRoot` will become `provideRouter`.
7. Remove the root module.
If the migration detects that the `providers` or `imports` of the root module are referencing code
outside of the class declaration, it will attempt to carry over as much of it as it can to the new
location. If some of that code is exported, it will be imported in the new location, otherwise it
will be copied over.
**Before:**
```typescript
// ./app/app.module.ts
import {NgModule, InjectionToken} from '@angular/core';
import {RouterModule} from '@angular/router';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {AppComponent} from './app.component.ts';
import {SharedModule} from './shared.module';
import {ImportedInterface} from './some-interface';
import {CONFIG} from './config';
interface NonImportedInterface {
foo: any;
baz: ImportedInterface;
}
const token = new InjectionToken<NonImportedInterface>('token');
export class ExportedConfigClass {}
@NgModule({
imports: [
SharedModule,
BrowserAnimationsModule,
RouterModule.forRoot([{
path: 'shop',
loadComponent: () => import('./shop/shop.component').then(m => m.ShopComponent)
}], {
initialNavigation: 'enabledBlocking'
})
],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [
{provide: token, useValue: {foo: true, bar: {baz: false}}},
{provide: CONFIG, useClass: ExportedConfigClass}
]
})
export class AppModule {}
```
```typescript
// ./app/app.component.ts
@Component({selector: 'app', template: 'hello', standalone: false})
export class AppComponent {}
```
```typescript
// ./main.ts
import {platformBrowser} from '@angular/platform-browser';
import {AppModule} from './app/app.module';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
```
**After:**
```typescript
// ./app/app.module.ts
import {NgModule, InjectionToken} from '@angular/core';
import {RouterModule} from '@angular/router';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {AppComponent} from './app.component.ts';
import {SharedModule} from '../shared/shared.module';
import {ImportedInterface} from './some-interface';
import {CONFIG} from './config';
interface NonImportedInterface {
foo: any;
bar: ImportedInterface;
}
const token = new InjectionToken<NonImportedInterface>('token');
export class ExportedConfigClass {}
```
```typescript
// ./app/app.component.ts
@Component({selector: 'app', template: 'hello'})
export class AppComponent {}
```
```typescript
// ./main.ts
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {InjectionToken, importProvidersFrom} from '@angular/core';
import {withEnabledBlockingInitialNavigation, provideRouter} from '@angular/router';
import {provideAnimations} from '@angular/platform-browser/animations';
import {AppModule, ExportedConfigClass} from './app/app.module';
import {AppComponent} from './app/app.component';
import {CONFIG} from './app/config';
import {SharedModule} from './shared/shared.module';
import {ImportedInterface} from './app/some-interface';
interface NonImportedInterface {
foo: any;
bar: ImportedInterface;
}
const token = new InjectionToken<NonImportedInterface>('token');
bootstrapApplication(AppComponent, {
providers: [
importProvidersFrom(SharedModule),
{provide: token, useValue: {foo: true, bar: {baz: false}}},
{provide: CONFIG, useClass: ExportedConfigClass},
provideAnimations(),
provideRouter([{
path: 'shop',
loadComponent: () => import('./app/shop/shop.component').then(m => m.ShopComponent)
}], withEnabledBlockingInitialNavigation())
]
}).catch(e => console.error(e));
```
| {
"end_byte": 10183,
"start_byte": 1824,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/README.md"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/util.ts_0_8455 | /*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgtscProgram} from '@angular/compiler-cli';
import {PotentialImport} from '@angular/compiler-cli/private/migrations';
import {dirname, relative} from 'path';
import ts from 'typescript';
import {normalizePath} from '../../utils/change_tracker';
import {closestNode} from '../../utils/typescript/nodes';
/** Map used to look up nodes based on their positions in a source file. */
export type NodeLookup = Map<number, ts.Node[]>;
/** Utility to type a class declaration with a name. */
export type NamedClassDeclaration = ts.ClassDeclaration & {name: ts.Identifier};
/** Text span of an AST node. */
export type ReferenceSpan = [start: number, end: number];
/** Mapping between a file name and spans for node references inside of it. */
export type ReferencesByFile = Map<string, ReferenceSpan[]>;
/** Utility class used to track a one-to-many relationship where all the items are unique. */
export class UniqueItemTracker<K, V> {
private _nodes = new Map<K, Set<V>>();
track(key: K, item: V) {
const set = this._nodes.get(key);
if (set) {
set.add(item);
} else {
this._nodes.set(key, new Set([item]));
}
}
get(key: K): Set<V> | undefined {
return this._nodes.get(key);
}
getEntries(): IterableIterator<[K, Set<V>]> {
return this._nodes.entries();
}
}
/** Resolves references to nodes. */
export class ReferenceResolver {
private _languageService: ts.LanguageService | undefined;
/**
* If set, allows the language service to *only* read a specific file.
* Used to speed up single-file lookups.
*/
private _tempOnlyFile: string | null = null;
constructor(
private _program: NgtscProgram,
private _host: ts.CompilerHost,
private _rootFileNames: string[],
private _basePath: string,
private _excludedFiles?: RegExp,
) {}
/** Finds all references to a node within the entire project. */
findReferencesInProject(node: ts.Node): ReferencesByFile {
const languageService = this._getLanguageService();
const fileName = node.getSourceFile().fileName;
const start = node.getStart();
let referencedSymbols: ts.ReferencedSymbol[];
// The language service can throw if it fails to read a file.
// Silently continue since we're making the lookup on a best effort basis.
try {
referencedSymbols = languageService.findReferences(fileName, start) || [];
} catch (e: any) {
console.error('Failed reference lookup for node ' + node.getText(), e.message);
referencedSymbols = [];
}
const results: ReferencesByFile = new Map();
for (const symbol of referencedSymbols) {
for (const ref of symbol.references) {
if (!ref.isDefinition || symbol.definition.kind === ts.ScriptElementKind.alias) {
if (!results.has(ref.fileName)) {
results.set(ref.fileName, []);
}
results
.get(ref.fileName)!
.push([ref.textSpan.start, ref.textSpan.start + ref.textSpan.length]);
}
}
}
return results;
}
/** Finds all references to a node within a single file. */
findSameFileReferences(node: ts.Node, fileName: string): ReferenceSpan[] {
// Even though we're only passing in a single file into `getDocumentHighlights`, the language
// service ends up traversing the entire project. Prevent it from reading any files aside from
// the one we're interested in by intercepting it at the compiler host level.
// This is an order of magnitude faster on a large project.
this._tempOnlyFile = fileName;
const nodeStart = node.getStart();
const results: ReferenceSpan[] = [];
let highlights: ts.DocumentHighlights[] | undefined;
// The language service can throw if it fails to read a file.
// Silently continue since we're making the lookup on a best effort basis.
try {
highlights = this._getLanguageService().getDocumentHighlights(fileName, nodeStart, [
fileName,
]);
} catch (e: any) {
console.error('Failed reference lookup for node ' + node.getText(), e.message);
}
if (highlights) {
for (const file of highlights) {
// We are pretty much guaranteed to only have one match from the current file since it is
// the only one being passed in `getDocumentHighlight`, but we check here just in case.
if (file.fileName === fileName) {
for (const {
textSpan: {start, length},
kind,
} of file.highlightSpans) {
if (kind !== ts.HighlightSpanKind.none) {
results.push([start, start + length]);
}
}
}
}
}
// Restore full project access to the language service.
this._tempOnlyFile = null;
return results;
}
/** Used by the language service */
private _readFile(path: string) {
if (
(this._tempOnlyFile !== null && path !== this._tempOnlyFile) ||
this._excludedFiles?.test(path)
) {
return '';
}
return this._host.readFile(path);
}
/** Gets a language service that can be used to perform lookups. */
private _getLanguageService(): ts.LanguageService {
if (!this._languageService) {
const rootFileNames = this._rootFileNames.slice();
this._program
.getTsProgram()
.getSourceFiles()
.forEach(({fileName}) => {
if (!this._excludedFiles?.test(fileName) && !rootFileNames.includes(fileName)) {
rootFileNames.push(fileName);
}
});
this._languageService = ts.createLanguageService(
{
getCompilationSettings: () => this._program.getTsProgram().getCompilerOptions(),
getScriptFileNames: () => rootFileNames,
// The files won't change so we can return the same version.
getScriptVersion: () => '0',
getScriptSnapshot: (path: string) => {
const content = this._readFile(path);
return content ? ts.ScriptSnapshot.fromString(content) : undefined;
},
getCurrentDirectory: () => this._basePath,
getDefaultLibFileName: (options) => ts.getDefaultLibFilePath(options),
readFile: (path) => this._readFile(path),
fileExists: (path: string) => this._host.fileExists(path),
},
ts.createDocumentRegistry(),
ts.LanguageServiceMode.PartialSemantic,
);
}
return this._languageService;
}
}
/** Creates a NodeLookup object from a source file. */
export function getNodeLookup(sourceFile: ts.SourceFile): NodeLookup {
const lookup: NodeLookup = new Map();
sourceFile.forEachChild(function walk(node) {
const nodesAtStart = lookup.get(node.getStart());
if (nodesAtStart) {
nodesAtStart.push(node);
} else {
lookup.set(node.getStart(), [node]);
}
node.forEachChild(walk);
});
return lookup;
}
/**
* Converts node offsets to the nodes they correspond to.
* @param lookup Data structure used to look up nodes at particular positions.
* @param offsets Offsets of the nodes.
* @param results Set in which to store the results.
*/
export function offsetsToNodes(
lookup: NodeLookup,
offsets: ReferenceSpan[],
results: Set<ts.Node>,
): Set<ts.Node> {
for (const [start, end] of offsets) {
const match = lookup.get(start)?.find((node) => node.getEnd() === end);
if (match) {
results.add(match);
}
}
return results;
}
/**
* 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
);
}
/** 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,
);
}
/** Gets a relative path between two files that can be used inside a TypeScript import. */ | {
"end_byte": 8455,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/util.ts"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/util.ts_8456_10856 | export function getRelativeImportPath(fromFile: string, toFile: string): string {
let path = relative(dirname(fromFile), toFile).replace(/\.ts$/, '');
// `relative` returns paths inside the same directory without `./`
if (!path.startsWith('.')) {
path = './' + path;
}
// Using the Node utilities can yield paths with forward slashes on Windows.
return normalizePath(path);
}
/** Function used to remap the generated `imports` for a component to known shorter aliases. */
export function knownInternalAliasRemapper(imports: PotentialImport[]) {
return imports.map((current) =>
current.moduleSpecifier === '@angular/common' && current.symbolName === 'NgForOf'
? {...current, symbolName: 'NgFor'}
: current,
);
}
/**
* Gets the closest node that matches a predicate, including the node that the search started from.
* @param node Node from which to start the search.
* @param predicate Predicate that the result needs to pass.
*/
export function closestOrSelf<T extends ts.Node>(
node: ts.Node,
predicate: (n: ts.Node) => n is T,
): T | null {
return predicate(node) ? node : closestNode(node, predicate);
}
/**
* Checks whether a node is referring to a specific class declaration.
* @param node Node that is being checked.
* @param className Name of the class that the node might be referring to.
* @param moduleName Name of the Angular module that should contain the class.
* @param typeChecker
*/
export function isClassReferenceInAngularModule(
node: ts.Node,
className: string | RegExp,
moduleName: string,
typeChecker: ts.TypeChecker,
): boolean {
const symbol = typeChecker.getTypeAtLocation(node).getSymbol();
const externalName = `@angular/${moduleName}`;
const internalName = `angular2/rc/packages/${moduleName}`;
return !!symbol?.declarations?.some((decl) => {
const closestClass = closestOrSelf(decl, ts.isClassDeclaration);
const closestClassFileName = closestClass?.getSourceFile().fileName;
if (
!closestClass ||
!closestClassFileName ||
!closestClass.name ||
!ts.isIdentifier(closestClass.name) ||
(!closestClassFileName.includes(externalName) && !closestClassFileName.includes(internalName))
) {
return false;
}
return typeof className === 'string'
? closestClass.name.text === className
: className.test(closestClass.name.text);
});
} | {
"end_byte": 10856,
"start_byte": 8456,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/util.ts"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/BUILD.bazel_0_702 | 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 = "standalone-migration",
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": 702,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/BUILD.bazel"
} |
angular/packages/core/schematics/ng-generate/standalone-migration/index.ts_0_6254 | /**
* @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 {createProgram, NgtscProgram} from '@angular/compiler-cli';
import {existsSync, statSync} from 'fs';
import {join, relative} from 'path';
import ts from 'typescript';
import {ChangesByFile, normalizePath} from '../../utils/change_tracker';
import {getProjectTsConfigPaths} from '../../utils/project_tsconfig_paths';
import {canMigrateFile, createProgramOptions} from '../../utils/typescript/compiler_host';
import {pruneNgModules} from './prune-modules';
import {toStandaloneBootstrap} from './standalone-bootstrap';
import {toStandalone} from './to-standalone';
import {knownInternalAliasRemapper} from './util';
enum MigrationMode {
toStandalone = 'convert-to-standalone',
pruneModules = 'prune-ng-modules',
standaloneBootstrap = 'standalone-bootstrap',
}
interface Options {
path: string;
mode: MigrationMode;
}
export function migrate(options: Options): Rule {
return async (tree, context) => {
const {buildPaths, testPaths} = await getProjectTsConfigPaths(tree);
const basePath = process.cwd();
const allPaths = [...buildPaths, ...testPaths];
// 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));
let migratedFiles = 0;
if (!allPaths.length) {
throw new SchematicsException(
'Could not find any tsconfig file. Cannot run the standalone migration.',
);
}
for (const tsconfigPath of allPaths) {
migratedFiles += standaloneMigration(tree, tsconfigPath, basePath, pathToMigrate, options);
}
if (migratedFiles === 0) {
throw new SchematicsException(
`Could not find any files to migrate under the path ${pathToMigrate}. Cannot run the standalone migration.`,
);
}
context.logger.info('🎉 Automated migration step has finished! 🎉');
context.logger.info(
'IMPORTANT! Please verify manually that your application builds and behaves as expected.',
);
context.logger.info(
`See https://angular.dev/reference/migrations/standalone for more information.`,
);
};
}
function standaloneMigration(
tree: Tree,
tsconfigPath: string,
basePath: string,
pathToMigrate: string,
schematicOptions: Options,
oldProgram?: NgtscProgram,
): number {
if (schematicOptions.path.startsWith('..')) {
throw new SchematicsException(
'Cannot run standalone migration outside of the current project.',
);
}
const {host, options, rootNames} = createProgramOptions(
tree,
tsconfigPath,
basePath,
undefined,
undefined,
{
_enableTemplateTypeChecker: true, // Required for the template type checker to work.
compileNonExportedClasses: true, // We want to migrate non-exported classes too.
// Avoid checking libraries to speed up the migration.
skipLibCheck: true,
skipDefaultLibCheck: true,
},
);
const referenceLookupExcludedFiles = /node_modules|\.ngtypecheck\.ts/;
const program = createProgram({rootNames, host, options, oldProgram}) as NgtscProgram;
const printer = ts.createPrinter();
if (existsSync(pathToMigrate) && !statSync(pathToMigrate).isDirectory()) {
throw new SchematicsException(
`Migration path ${pathToMigrate} has to be a directory. Cannot run the standalone migration.`,
);
}
const sourceFiles = program
.getTsProgram()
.getSourceFiles()
.filter(
(sourceFile) =>
sourceFile.fileName.startsWith(pathToMigrate) &&
canMigrateFile(basePath, sourceFile, program.getTsProgram()),
);
if (sourceFiles.length === 0) {
return 0;
}
let pendingChanges: ChangesByFile;
let filesToRemove: Set<ts.SourceFile> | null = null;
if (schematicOptions.mode === MigrationMode.pruneModules) {
const result = pruneNgModules(
program,
host,
basePath,
rootNames,
sourceFiles,
printer,
undefined,
referenceLookupExcludedFiles,
knownInternalAliasRemapper,
);
pendingChanges = result.pendingChanges;
filesToRemove = result.filesToRemove;
} else if (schematicOptions.mode === MigrationMode.standaloneBootstrap) {
pendingChanges = toStandaloneBootstrap(
program,
host,
basePath,
rootNames,
sourceFiles,
printer,
undefined,
referenceLookupExcludedFiles,
knownInternalAliasRemapper,
);
} else {
// This shouldn't happen, but default to `MigrationMode.toStandalone` just in case.
pendingChanges = toStandalone(
sourceFiles,
program,
printer,
undefined,
knownInternalAliasRemapper,
);
}
for (const [file, changes] of pendingChanges.entries()) {
// Don't attempt to edit a file if it's going to be deleted.
if (filesToRemove?.has(file)) {
continue;
}
const update = tree.beginUpdate(relative(basePath, file.fileName));
changes.forEach((change) => {
if (change.removeLength != null) {
update.remove(change.start, change.removeLength);
}
update.insertRight(change.start, change.text);
});
tree.commitUpdate(update);
}
if (filesToRemove) {
for (const file of filesToRemove) {
tree.delete(relative(basePath, file.fileName));
}
}
// Run the module pruning after the standalone bootstrap to automatically remove the root module.
// Note that we can't run the module pruning internally without propagating the changes to disk,
// because there may be conflicting AST node changes.
if (schematicOptions.mode === MigrationMode.standaloneBootstrap) {
return (
standaloneMigration(
tree,
tsconfigPath,
basePath,
pathToMigrate,
{...schematicOptions, mode: MigrationMode.pruneModules},
program,
) + sourceFiles.length
);
}
return sourceFiles.length;
}
| {
"end_byte": 6254,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/standalone-migration/index.ts"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/migration.ts_0_3850 | /**
* @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 {migrateCase} from './cases';
import {migrateFor} from './fors';
import {migrateIf} from './ifs';
import {migrateSwitch} from './switches';
import {
AnalyzedFile,
endI18nMarker,
endMarker,
MigrateError,
startI18nMarker,
startMarker,
} from './types';
import {
canRemoveCommonModule,
formatTemplate,
processNgTemplates,
removeImports,
validateMigratedTemplate,
} from './util';
/**
* Actually migrates a given template to the new syntax
*/
export function migrateTemplate(
template: string,
templateType: string,
node: ts.Node,
file: AnalyzedFile,
format: boolean = true,
analyzedFiles: Map<string, AnalyzedFile> | null,
): {migrated: string; errors: MigrateError[]} {
let errors: MigrateError[] = [];
let migrated = template;
if (templateType === 'template' || templateType === 'templateUrl') {
const ifResult = migrateIf(template);
const forResult = migrateFor(ifResult.migrated);
const switchResult = migrateSwitch(forResult.migrated);
if (switchResult.errors.length > 0) {
return {migrated: template, errors: switchResult.errors};
}
const caseResult = migrateCase(switchResult.migrated);
const templateResult = processNgTemplates(caseResult.migrated);
if (templateResult.err !== undefined) {
return {migrated: template, errors: [{type: 'template', error: templateResult.err}]};
}
migrated = templateResult.migrated;
const changed =
ifResult.changed || forResult.changed || switchResult.changed || caseResult.changed;
if (changed) {
// determine if migrated template is a valid structure
// if it is not, fail out
const errors = validateMigratedTemplate(migrated, file.sourceFile.fileName);
if (errors.length > 0) {
return {migrated: template, errors};
}
}
if (format && changed) {
migrated = formatTemplate(migrated, templateType);
}
const markerRegex = new RegExp(
`${startMarker}|${endMarker}|${startI18nMarker}|${endI18nMarker}`,
'gm',
);
migrated = migrated.replace(markerRegex, '');
file.removeCommonModule = canRemoveCommonModule(template);
file.canRemoveImports = true;
// when migrating an external template, we have to pass back
// whether it's safe to remove the CommonModule to the
// original component class source file
if (
templateType === 'templateUrl' &&
analyzedFiles !== null &&
analyzedFiles.has(file.sourceFile.fileName)
) {
const componentFile = analyzedFiles.get(file.sourceFile.fileName)!;
componentFile.getSortedRanges();
// we have already checked the template file to see if it is safe to remove the imports
// and common module. This check is passed off to the associated .ts file here so
// the class knows whether it's safe to remove from the template side.
componentFile.removeCommonModule = file.removeCommonModule;
componentFile.canRemoveImports = file.canRemoveImports;
// At this point, we need to verify the component class file doesn't have any other imports
// that prevent safe removal of common module. It could be that there's an associated ngmodule
// and in that case we can't safely remove the common module import.
componentFile.verifyCanRemoveImports();
}
file.verifyCanRemoveImports();
errors = [
...ifResult.errors,
...forResult.errors,
...switchResult.errors,
...caseResult.errors,
];
} else if (file.canRemoveImports) {
migrated = removeImports(template, node, file);
}
return {migrated, errors};
}
| {
"end_byte": 3850,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/migration.ts"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/ifs.ts_0_7134 | /**
* @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 {visitAll} from '@angular/compiler';
import {
ElementCollector,
ElementToMigrate,
endMarker,
MigrateError,
Result,
startMarker,
} from './types';
import {
calculateNesting,
getMainBlock,
getOriginals,
getPlaceholder,
hasLineBreaks,
parseTemplate,
reduceNestingOffset,
} from './util';
export const ngif = '*ngIf';
export const boundngif = '[ngIf]';
export const nakedngif = 'ngIf';
const ifs = [ngif, nakedngif, boundngif];
/**
* Replaces structural directive ngif instances with new if.
* Returns null if the migration failed (e.g. there was a syntax error).
*/
export function migrateIf(template: string): {
migrated: string;
errors: MigrateError[];
changed: boolean;
} {
let errors: MigrateError[] = [];
let parsed = parseTemplate(template);
if (parsed.tree === undefined) {
return {migrated: template, errors, changed: false};
}
let result = template;
const visitor = new ElementCollector(ifs);
visitAll(visitor, parsed.tree.rootNodes);
calculateNesting(visitor, hasLineBreaks(template));
// this tracks the character shift from different lengths of blocks from
// the prior directives so as to adjust for nested block replacement during
// migration. Each block calculates length differences and passes that offset
// to the next migrating block to adjust character offsets properly.
let offset = 0;
let nestLevel = -1;
let postOffsets: number[] = [];
for (const el of visitor.elements) {
let migrateResult: Result = {tmpl: result, offsets: {pre: 0, post: 0}};
// applies the post offsets after closing
offset = reduceNestingOffset(el, nestLevel, offset, postOffsets);
try {
migrateResult = migrateNgIf(el, result, offset);
} catch (error: unknown) {
errors.push({type: ngif, error});
}
result = migrateResult.tmpl;
offset += migrateResult.offsets.pre;
postOffsets.push(migrateResult.offsets.post);
nestLevel = el.nestCount;
}
const changed = visitor.elements.length > 0;
return {migrated: result, errors, changed};
}
function migrateNgIf(etm: ElementToMigrate, tmpl: string, offset: number): Result {
const matchThen = etm.attr.value.match(/[^\w\d];?\s*then/gm);
const matchElse = etm.attr.value.match(/[^\w\d];?\s*else/gm);
if (etm.thenAttr !== undefined || etm.elseAttr !== undefined) {
// bound if then / if then else
return buildBoundIfElseBlock(etm, tmpl, offset);
} else if (matchThen && matchThen.length > 0 && matchElse && matchElse.length > 0) {
// then else
return buildStandardIfThenElseBlock(etm, tmpl, matchThen[0], matchElse![0], offset);
} else if (matchThen && matchThen.length > 0) {
// just then
return buildStandardIfThenBlock(etm, tmpl, matchThen[0], offset);
} else if (matchElse && matchElse.length > 0) {
// just else
return buildStandardIfElseBlock(etm, tmpl, matchElse![0], offset);
}
return buildIfBlock(etm, tmpl, offset);
}
function buildIfBlock(etm: ElementToMigrate, tmpl: string, offset: number): Result {
const aliasAttrs = etm.aliasAttrs!;
const aliases = [...aliasAttrs.aliases.keys()];
if (aliasAttrs.item) {
aliases.push(aliasAttrs.item);
}
// includes the mandatory semicolon before as
const lbString = etm.hasLineBreaks ? '\n' : '';
let condition = etm.attr.value
.replace(' as ', '; as ')
// replace 'let' with 'as' whatever spaces are between ; and 'let'
.replace(/;\s*let/g, '; as');
if (aliases.length > 1 || (aliases.length === 1 && condition.indexOf('; as') > -1)) {
// only 1 alias allowed
throw new Error(
'Found more than one alias on your ngIf. Remove one of them and re-run the migration.',
);
} else if (aliases.length === 1) {
condition += `; as ${aliases[0]}`;
}
const originals = getOriginals(etm, tmpl, offset);
const {start, middle, end} = getMainBlock(etm, tmpl, offset);
const startBlock = `${startMarker}@if (${condition}) {${lbString}${start}`;
const endBlock = `${end}${lbString}}${endMarker}`;
const ifBlock = startBlock + middle + endBlock;
const updatedTmpl = tmpl.slice(0, etm.start(offset)) + ifBlock + tmpl.slice(etm.end(offset));
// this should be the difference between the starting element up to the start of the closing
// element and the mainblock sans }
const pre = originals.start.length - startBlock.length;
const post = originals.end.length - endBlock.length;
return {tmpl: updatedTmpl, offsets: {pre, post}};
}
function buildStandardIfElseBlock(
etm: ElementToMigrate,
tmpl: string,
elseString: string,
offset: number,
): Result {
// includes the mandatory semicolon before as
const condition = etm
.getCondition()
.replace(' as ', '; as ')
// replace 'let' with 'as' whatever spaces are between ; and 'let'
.replace(/;\s*let/g, '; as');
const elsePlaceholder = getPlaceholder(etm.getTemplateName(elseString));
return buildIfElseBlock(etm, tmpl, condition, elsePlaceholder, offset);
}
function buildBoundIfElseBlock(etm: ElementToMigrate, tmpl: string, offset: number): Result {
const aliasAttrs = etm.aliasAttrs!;
const aliases = [...aliasAttrs.aliases.keys()];
if (aliasAttrs.item) {
aliases.push(aliasAttrs.item);
}
// includes the mandatory semicolon before as
let condition = etm.attr.value.replace(' as ', '; as ');
if (aliases.length > 1 || (aliases.length === 1 && condition.indexOf('; as') > -1)) {
// only 1 alias allowed
throw new Error(
'Found more than one alias on your ngIf. Remove one of them and re-run the migration.',
);
} else if (aliases.length === 1) {
condition += `; as ${aliases[0]}`;
}
const elsePlaceholder = getPlaceholder(etm.elseAttr!.value.trim());
if (etm.thenAttr !== undefined) {
const thenPlaceholder = getPlaceholder(etm.thenAttr!.value.trim());
return buildIfThenElseBlock(etm, tmpl, condition, thenPlaceholder, elsePlaceholder, offset);
}
return buildIfElseBlock(etm, tmpl, condition, elsePlaceholder, offset);
}
function buildIfElseBlock(
etm: ElementToMigrate,
tmpl: string,
condition: string,
elsePlaceholder: string,
offset: number,
): Result {
const lbString = etm.hasLineBreaks ? '\n' : '';
const originals = getOriginals(etm, tmpl, offset);
const {start, middle, end} = getMainBlock(etm, tmpl, offset);
const startBlock = `${startMarker}@if (${condition}) {${lbString}${start}`;
const elseBlock = `${end}${lbString}} @else {${lbString}`;
const postBlock = elseBlock + elsePlaceholder + `${lbString}}${endMarker}`;
const ifElseBlock = startBlock + middle + postBlock;
const tmplStart = tmpl.slice(0, etm.start(offset));
const tmplEnd = tmpl.slice(etm.end(offset));
const updatedTmpl = tmplStart + ifElseBlock + tmplEnd;
const pre = originals.start.length - startBlock.length;
const post = originals.end.length - postBlock.length;
return {tmpl: updatedTmpl, offsets: {pre, post}};
} | {
"end_byte": 7134,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/ifs.ts"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/ifs.ts_7136_10266 | function buildStandardIfThenElseBlock(
etm: ElementToMigrate,
tmpl: string,
thenString: string,
elseString: string,
offset: number,
): Result {
// includes the mandatory semicolon before as
const condition = etm
.getCondition()
.replace(' as ', '; as ')
// replace 'let' with 'as' whatever spaces are between ; and 'let'
.replace(/;\s*let/g, '; as');
const thenPlaceholder = getPlaceholder(etm.getTemplateName(thenString, elseString));
const elsePlaceholder = getPlaceholder(etm.getTemplateName(elseString));
return buildIfThenElseBlock(etm, tmpl, condition, thenPlaceholder, elsePlaceholder, offset);
}
function buildStandardIfThenBlock(
etm: ElementToMigrate,
tmpl: string,
thenString: string,
offset: number,
): Result {
// includes the mandatory semicolon before as
const condition = etm
.getCondition()
.replace(' as ', '; as ')
// replace 'let' with 'as' whatever spaces are between ; and 'let'
.replace(/;\s*let/g, '; as');
const thenPlaceholder = getPlaceholder(etm.getTemplateName(thenString));
return buildIfThenBlock(etm, tmpl, condition, thenPlaceholder, offset);
}
function buildIfThenElseBlock(
etm: ElementToMigrate,
tmpl: string,
condition: string,
thenPlaceholder: string,
elsePlaceholder: string,
offset: number,
): Result {
const lbString = etm.hasLineBreaks ? '\n' : '';
const originals = getOriginals(etm, tmpl, offset);
const startBlock = `${startMarker}@if (${condition}) {${lbString}`;
const elseBlock = `${lbString}} @else {${lbString}`;
const postBlock = thenPlaceholder + elseBlock + elsePlaceholder + `${lbString}}${endMarker}`;
const ifThenElseBlock = startBlock + postBlock;
const tmplStart = tmpl.slice(0, etm.start(offset));
const tmplEnd = tmpl.slice(etm.end(offset));
const updatedTmpl = tmplStart + ifThenElseBlock + tmplEnd;
// We ignore the contents of the element on if then else.
// If there's anything there, we need to account for the length in the offset.
const pre = originals.start.length + originals.childLength - startBlock.length;
const post = originals.end.length - postBlock.length;
return {tmpl: updatedTmpl, offsets: {pre, post}};
}
function buildIfThenBlock(
etm: ElementToMigrate,
tmpl: string,
condition: string,
thenPlaceholder: string,
offset: number,
): Result {
const lbString = etm.hasLineBreaks ? '\n' : '';
const originals = getOriginals(etm, tmpl, offset);
const startBlock = `${startMarker}@if (${condition}) {${lbString}`;
const postBlock = thenPlaceholder + `${lbString}}${endMarker}`;
const ifThenBlock = startBlock + postBlock;
const tmplStart = tmpl.slice(0, etm.start(offset));
const tmplEnd = tmpl.slice(etm.end(offset));
const updatedTmpl = tmplStart + ifThenBlock + tmplEnd;
// We ignore the contents of the element on if then else.
// If there's anything there, we need to account for the length in the offset.
const pre = originals.start.length + originals.childLength - startBlock.length;
const post = originals.end.length - postBlock.length;
return {tmpl: updatedTmpl, offsets: {pre, post}};
} | {
"end_byte": 10266,
"start_byte": 7136,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/ifs.ts"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/identifier-lookup.ts_0_613 | /**
* @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 lookupIdentifiersInSourceFile(
sourceFile: ts.SourceFile,
names: string[],
): Set<ts.Identifier> {
const results = new Set<ts.Identifier>();
const visit = (node: ts.Node): void => {
if (ts.isIdentifier(node) && names.includes(node.text)) {
results.add(node);
}
ts.forEachChild(node, visit);
};
visit(sourceFile);
return results;
}
| {
"end_byte": 613,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/identifier-lookup.ts"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/README.md_0_856 | ## Control Flow Syntax migration
Angular v17 introduces a new control flow syntax. This migration replaces the
existing usages of `*ngIf`, `*ngFor`, and `*ngSwitch` to their equivalent block
syntax. Existing ng-templates are preserved in case they are used elsewhere in
the template. It has the following option:
* `path` - Relative path within the project that the migration should apply to. Can be used to
migrate specific sub-directories individually. Defaults to the project root.
#### Before
```ts
import {Component} from '@angular/core';
@Component({
template: `<div><span *ngIf="show">Content here</span></div>`
})
export class MyComp {
show = false;
}
```
#### After
```ts
import {Component} from '@angular/core';
@Component({
template: `<div>@if (show) {<span>Content here</span>}</div>`
})
export class MyComp {
show = false
}
```
| {
"end_byte": 856,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/README.md"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/types.ts_0_7532 | /**
* @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 {
Attribute,
Block,
Element,
ParseTreeResult,
RecursiveVisitor,
Text,
} from '@angular/compiler';
import ts from 'typescript';
import {lookupIdentifiersInSourceFile} from './identifier-lookup';
export const ngtemplate = 'ng-template';
export const boundngifelse = '[ngIfElse]';
export const boundngifthenelse = '[ngIfThenElse]';
export const boundngifthen = '[ngIfThen]';
export const nakedngfor = 'ngFor';
export const startMarker = '◬';
export const endMarker = '✢';
export const startI18nMarker = '⚈';
export const endI18nMarker = '⚉';
export const importRemovals = [
'NgIf',
'NgIfElse',
'NgIfThenElse',
'NgFor',
'NgForOf',
'NgForTrackBy',
'NgSwitch',
'NgSwitchCase',
'NgSwitchDefault',
];
export const importWithCommonRemovals = [...importRemovals, 'CommonModule'];
function allFormsOf(selector: string): string[] {
return [selector, `*${selector}`, `[${selector}]`];
}
const commonModuleDirectives = new Set([
...allFormsOf('ngComponentOutlet'),
...allFormsOf('ngTemplateOutlet'),
...allFormsOf('ngClass'),
...allFormsOf('ngPlural'),
...allFormsOf('ngPluralCase'),
...allFormsOf('ngStyle'),
...allFormsOf('ngTemplateOutlet'),
...allFormsOf('ngComponentOutlet'),
'[NgForOf]',
'[NgForTrackBy]',
'[ngIfElse]',
'[ngIfThenElse]',
]);
function pipeMatchRegExpFor(name: string): RegExp {
return new RegExp(`\\|\\s*${name}`);
}
const commonModulePipes = [
'date',
'async',
'currency',
'number',
'i18nPlural',
'i18nSelect',
'json',
'keyvalue',
'slice',
'lowercase',
'uppercase',
'titlecase',
'percent',
].map((name) => pipeMatchRegExpFor(name));
/**
* Represents a range of text within a file. Omitting the end
* means that it's until the end of the file.
*/
type Range = {
start: number;
end?: number;
node: ts.Node;
type: string;
remove: boolean;
};
export type Offsets = {
pre: number;
post: number;
};
export type Result = {
tmpl: string;
offsets: Offsets;
};
export interface ForAttributes {
forOf: string;
trackBy: string;
}
export interface AliasAttributes {
item: string;
aliases: Map<string, string>;
}
export interface ParseResult {
tree: ParseTreeResult | undefined;
errors: MigrateError[];
}
/**
* Represents an error that happened during migration
*/
export type MigrateError = {
type: string;
error: unknown;
};
/**
* Represents an element with a migratable attribute
*/
export class ElementToMigrate {
el: Element;
attr: Attribute;
elseAttr: Attribute | undefined;
thenAttr: Attribute | undefined;
forAttrs: ForAttributes | undefined;
aliasAttrs: AliasAttributes | undefined;
nestCount = 0;
hasLineBreaks = false;
constructor(
el: Element,
attr: Attribute,
elseAttr: Attribute | undefined = undefined,
thenAttr: Attribute | undefined = undefined,
forAttrs: ForAttributes | undefined = undefined,
aliasAttrs: AliasAttributes | undefined = undefined,
) {
this.el = el;
this.attr = attr;
this.elseAttr = elseAttr;
this.thenAttr = thenAttr;
this.forAttrs = forAttrs;
this.aliasAttrs = aliasAttrs;
}
normalizeConditionString(value: string): string {
value = this.insertSemicolon(value, value.indexOf(' else '));
value = this.insertSemicolon(value, value.indexOf(' then '));
value = this.insertSemicolon(value, value.indexOf(' let '));
return value.replace(';;', ';');
}
insertSemicolon(str: string, ix: number): string {
return ix > -1 ? `${str.slice(0, ix)};${str.slice(ix)}` : str;
}
getCondition(): string {
const chunks = this.normalizeConditionString(this.attr.value).split(';');
let condition = chunks[0];
// checks for case of no usage of `;` in if else / if then else
const elseIx = condition.indexOf(' else ');
const thenIx = condition.indexOf(' then ');
if (thenIx > -1) {
condition = condition.slice(0, thenIx);
} else if (elseIx > -1) {
condition = condition.slice(0, elseIx);
}
let letVar = chunks.find((c) => c.search(/\s*let\s/) > -1);
return condition + (letVar ? ';' + letVar : '');
}
getTemplateName(targetStr: string, secondStr?: string): string {
const targetLocation = this.attr.value.indexOf(targetStr);
const secondTargetLocation = secondStr ? this.attr.value.indexOf(secondStr) : undefined;
let templateName = this.attr.value.slice(
targetLocation + targetStr.length,
secondTargetLocation,
);
if (templateName.startsWith(':')) {
templateName = templateName.slice(1).trim();
}
return templateName.split(';')[0].trim();
}
getValueEnd(offset: number): number {
return (
(this.attr.valueSpan ? this.attr.valueSpan.end.offset + 1 : this.attr.keySpan!.end.offset) -
offset
);
}
hasChildren(): boolean {
return this.el.children.length > 0;
}
getChildSpan(offset: number): {childStart: number; childEnd: number} {
const childStart = this.el.children[0].sourceSpan.start.offset - offset;
const childEnd = this.el.children[this.el.children.length - 1].sourceSpan.end.offset - offset;
return {childStart, childEnd};
}
shouldRemoveElseAttr(): boolean {
return (
(this.el.name === 'ng-template' || this.el.name === 'ng-container') &&
this.elseAttr !== undefined
);
}
getElseAttrStr(): string {
if (this.elseAttr !== undefined) {
const elseValStr = this.elseAttr.value !== '' ? `="${this.elseAttr.value}"` : '';
return `${this.elseAttr.name}${elseValStr}`;
}
return '';
}
start(offset: number): number {
return this.el.sourceSpan?.start.offset - offset;
}
end(offset: number): number {
return this.el.sourceSpan?.end.offset - offset;
}
length(): number {
return this.el.sourceSpan?.end.offset - this.el.sourceSpan?.start.offset;
}
}
/**
* Represents an ng-template inside a template being migrated to new control flow
*/
export class Template {
el: Element;
name: string;
count: number = 0;
contents: string = '';
children: string = '';
i18n: Attribute | null = null;
attributes: Attribute[];
constructor(el: Element, name: string, i18n: Attribute | null) {
this.el = el;
this.name = name;
this.attributes = el.attrs;
this.i18n = i18n;
}
get isNgTemplateOutlet() {
return this.attributes.find((attr) => attr.name === '*ngTemplateOutlet') !== undefined;
}
get outletContext() {
const letVar = this.attributes.find((attr) => attr.name.startsWith('let-'));
return letVar ? `; context: {$implicit: ${letVar.name.split('-')[1]}}` : '';
}
generateTemplateOutlet() {
const attr = this.attributes.find((attr) => attr.name === '*ngTemplateOutlet');
const outletValue = attr?.value ?? this.name.slice(1);
return `<ng-container *ngTemplateOutlet="${outletValue}${this.outletContext}"></ng-container>`;
}
generateContents(tmpl: string) {
this.contents = tmpl.slice(this.el.sourceSpan.start.offset, this.el.sourceSpan.end.offset);
this.children = '';
if (this.el.children.length > 0) {
this.children = tmpl.slice(
this.el.children[0].sourceSpan.start.offset,
this.el.children[this.el.children.length - 1].sourceSpan.end.offset,
);
}
}
}
/** Represents a file that was analyzed by the migration. */
export | {
"end_byte": 7532,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/types.ts"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/types.ts_7533_14086 | lass AnalyzedFile {
private ranges: Range[] = [];
removeCommonModule = false;
canRemoveImports = false;
sourceFile: ts.SourceFile;
importRanges: Range[] = [];
templateRanges: Range[] = [];
constructor(sourceFile: ts.SourceFile) {
this.sourceFile = sourceFile;
}
/** Returns the ranges in the order in which they should be migrated. */
getSortedRanges(): Range[] {
// templates first for checking on whether certain imports can be safely removed
this.templateRanges = this.ranges
.slice()
.filter((x) => x.type === 'template' || x.type === 'templateUrl')
.sort((aStart, bStart) => bStart.start - aStart.start);
this.importRanges = this.ranges
.slice()
.filter((x) => x.type === 'importDecorator' || x.type === 'importDeclaration')
.sort((aStart, bStart) => bStart.start - aStart.start);
return [...this.templateRanges, ...this.importRanges];
}
/**
* Adds a text range to an `AnalyzedFile`.
* @param path Path of the file.
* @param analyzedFiles Map keeping track of all the analyzed files.
* @param range Range to be added.
*/
static addRange(
path: string,
sourceFile: ts.SourceFile,
analyzedFiles: Map<string, AnalyzedFile>,
range: Range,
): void {
let analysis = analyzedFiles.get(path);
if (!analysis) {
analysis = new AnalyzedFile(sourceFile);
analyzedFiles.set(path, analysis);
}
const duplicate = analysis.ranges.find(
(current) => current.start === range.start && current.end === range.end,
);
if (!duplicate) {
analysis.ranges.push(range);
}
}
/**
* This verifies whether a component class is safe to remove module imports.
* It is only run on .ts files.
*/
verifyCanRemoveImports() {
const importDeclaration = this.importRanges.find((r) => r.type === 'importDeclaration');
const instances = lookupIdentifiersInSourceFile(this.sourceFile, importWithCommonRemovals);
let foundImportDeclaration = false;
let count = 0;
for (let range of this.importRanges) {
for (let instance of instances) {
if (instance.getStart() >= range.start && instance.getEnd() <= range.end!) {
if (range === importDeclaration) {
foundImportDeclaration = true;
}
count++;
}
}
}
if (instances.size !== count && importDeclaration !== undefined && foundImportDeclaration) {
importDeclaration.remove = false;
}
}
}
/** Finds all non-control flow elements from common module. */
export class CommonCollector extends RecursiveVisitor {
count = 0;
override visitElement(el: Element): void {
if (el.attrs.length > 0) {
for (const attr of el.attrs) {
if (this.hasDirectives(attr.name) || this.hasPipes(attr.value)) {
this.count++;
}
}
}
super.visitElement(el, null);
}
override visitBlock(ast: Block): void {
for (const blockParam of ast.parameters) {
if (this.hasPipes(blockParam.expression)) {
this.count++;
}
}
}
override visitText(ast: Text) {
if (this.hasPipes(ast.value)) {
this.count++;
}
}
private hasDirectives(input: string): boolean {
return commonModuleDirectives.has(input);
}
private hasPipes(input: string): boolean {
return commonModulePipes.some((regexp) => regexp.test(input));
}
}
/** Finds all elements that represent i18n blocks. */
export class i18nCollector extends RecursiveVisitor {
readonly elements: Element[] = [];
override visitElement(el: Element): void {
if (el.attrs.find((a) => a.name === 'i18n') !== undefined) {
this.elements.push(el);
}
super.visitElement(el, null);
}
}
/** Finds all elements with ngif structural directives. */
export class ElementCollector extends RecursiveVisitor {
readonly elements: ElementToMigrate[] = [];
constructor(private _attributes: string[] = []) {
super();
}
override visitElement(el: Element): void {
if (el.attrs.length > 0) {
for (const attr of el.attrs) {
if (this._attributes.includes(attr.name)) {
const elseAttr = el.attrs.find((x) => x.name === boundngifelse);
const thenAttr = el.attrs.find(
(x) => x.name === boundngifthenelse || x.name === boundngifthen,
);
const forAttrs = attr.name === nakedngfor ? this.getForAttrs(el) : undefined;
const aliasAttrs = this.getAliasAttrs(el);
this.elements.push(
new ElementToMigrate(el, attr, elseAttr, thenAttr, forAttrs, aliasAttrs),
);
}
}
}
super.visitElement(el, null);
}
private getForAttrs(el: Element): ForAttributes {
let trackBy = '';
let forOf = '';
for (const attr of el.attrs) {
if (attr.name === '[ngForTrackBy]') {
trackBy = attr.value;
}
if (attr.name === '[ngForOf]') {
forOf = attr.value;
}
}
return {forOf, trackBy};
}
private getAliasAttrs(el: Element): AliasAttributes {
const aliases = new Map<string, string>();
let item = '';
for (const attr of el.attrs) {
if (attr.name.startsWith('let-')) {
if (attr.value === '') {
// item
item = attr.name.replace('let-', '');
} else {
// alias
aliases.set(attr.name.replace('let-', ''), attr.value);
}
}
}
return {item, aliases};
}
}
/** Finds all elements with ngif structural directives. */
export class TemplateCollector extends RecursiveVisitor {
readonly elements: ElementToMigrate[] = [];
readonly templates: Map<string, Template> = new Map();
override visitElement(el: Element): void {
if (el.name === ngtemplate) {
let i18n = null;
let templateAttr = null;
for (const attr of el.attrs) {
if (attr.name === 'i18n') {
i18n = attr;
}
if (attr.name.startsWith('#')) {
templateAttr = attr;
}
}
if (templateAttr !== null && !this.templates.has(templateAttr.name)) {
this.templates.set(templateAttr.name, new Template(el, templateAttr.name, i18n));
this.elements.push(new ElementToMigrate(el, templateAttr));
} else if (templateAttr !== null) {
throw new Error(
`A duplicate ng-template name "${templateAttr.name}" was found. ` +
`The control flow migration requires unique ng-template names within a component.`,
);
}
}
super.visitElement(el, null);
}
}
| {
"end_byte": 14086,
"start_byte": 7533,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/types.ts"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/cases.ts_0_5034 | /**
* @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 {visitAll} from '@angular/compiler';
import {
ElementCollector,
ElementToMigrate,
endMarker,
MigrateError,
Result,
startMarker,
} from './types';
import {
calculateNesting,
getMainBlock,
getOriginals,
hasLineBreaks,
parseTemplate,
reduceNestingOffset,
} from './util';
export const boundcase = '[ngSwitchCase]';
export const switchcase = '*ngSwitchCase';
export const nakedcase = 'ngSwitchCase';
export const switchdefault = '*ngSwitchDefault';
export const nakeddefault = 'ngSwitchDefault';
export const cases = [boundcase, switchcase, nakedcase, switchdefault, nakeddefault];
/**
* Replaces structural directive ngSwitch instances with new switch.
* Returns null if the migration failed (e.g. there was a syntax error).
*/
export function migrateCase(template: string): {
migrated: string;
errors: MigrateError[];
changed: boolean;
} {
let errors: MigrateError[] = [];
let parsed = parseTemplate(template);
if (parsed.tree === undefined) {
return {migrated: template, errors, changed: false};
}
let result = template;
const visitor = new ElementCollector(cases);
visitAll(visitor, parsed.tree.rootNodes);
calculateNesting(visitor, hasLineBreaks(template));
// this tracks the character shift from different lengths of blocks from
// the prior directives so as to adjust for nested block replacement during
// migration. Each block calculates length differences and passes that offset
// to the next migrating block to adjust character offsets properly.
let offset = 0;
let nestLevel = -1;
let postOffsets: number[] = [];
for (const el of visitor.elements) {
let migrateResult: Result = {tmpl: result, offsets: {pre: 0, post: 0}};
// applies the post offsets after closing
offset = reduceNestingOffset(el, nestLevel, offset, postOffsets);
if (el.attr.name === switchcase || el.attr.name === nakedcase || el.attr.name === boundcase) {
try {
migrateResult = migrateNgSwitchCase(el, result, offset);
} catch (error: unknown) {
errors.push({type: switchcase, error});
}
} else if (el.attr.name === switchdefault || el.attr.name === nakeddefault) {
try {
migrateResult = migrateNgSwitchDefault(el, result, offset);
} catch (error: unknown) {
errors.push({type: switchdefault, error});
}
}
result = migrateResult.tmpl;
offset += migrateResult.offsets.pre;
postOffsets.push(migrateResult.offsets.post);
nestLevel = el.nestCount;
}
const changed = visitor.elements.length > 0;
return {migrated: result, errors, changed};
}
function migrateNgSwitchCase(etm: ElementToMigrate, tmpl: string, offset: number): Result {
// includes the mandatory semicolon before as
const lbString = etm.hasLineBreaks ? '\n' : '';
const leadingSpace = etm.hasLineBreaks ? '' : ' ';
// ngSwitchCases with no values results into `case ()` which isn't valid, based off empty
// value we add quotes instead of generating empty case
const condition = etm.attr.value.length === 0 ? `''` : etm.attr.value;
const originals = getOriginals(etm, tmpl, offset);
const {start, middle, end} = getMainBlock(etm, tmpl, offset);
const startBlock = `${startMarker}${leadingSpace}@case (${condition}) {${leadingSpace}${lbString}${start}`;
const endBlock = `${end}${lbString}${leadingSpace}}${endMarker}`;
const defaultBlock = startBlock + middle + endBlock;
const updatedTmpl = tmpl.slice(0, etm.start(offset)) + defaultBlock + tmpl.slice(etm.end(offset));
// this should be the difference between the starting element up to the start of the closing
// element and the mainblock sans }
const pre = originals.start.length - startBlock.length;
const post = originals.end.length - endBlock.length;
return {tmpl: updatedTmpl, offsets: {pre, post}};
}
function migrateNgSwitchDefault(etm: ElementToMigrate, tmpl: string, offset: number): Result {
// includes the mandatory semicolon before as
const lbString = etm.hasLineBreaks ? '\n' : '';
const leadingSpace = etm.hasLineBreaks ? '' : ' ';
const originals = getOriginals(etm, tmpl, offset);
const {start, middle, end} = getMainBlock(etm, tmpl, offset);
const startBlock = `${startMarker}${leadingSpace}@default {${leadingSpace}${lbString}${start}`;
const endBlock = `${end}${lbString}${leadingSpace}}${endMarker}`;
const defaultBlock = startBlock + middle + endBlock;
const updatedTmpl = tmpl.slice(0, etm.start(offset)) + defaultBlock + tmpl.slice(etm.end(offset));
// this should be the difference between the starting element up to the start of the closing
// element and the mainblock sans }
const pre = originals.start.length - startBlock.length;
const post = originals.end.length - endBlock.length;
return {tmpl: updatedTmpl, offsets: {pre, post}};
}
| {
"end_byte": 5034,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/cases.ts"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/fors.ts_0_6428 | /**
* @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 {visitAll} from '@angular/compiler';
import {
ElementCollector,
ElementToMigrate,
endMarker,
MigrateError,
Result,
startMarker,
} from './types';
import {
calculateNesting,
getMainBlock,
getOriginals,
getPlaceholder,
hasLineBreaks,
parseTemplate,
PlaceholderKind,
reduceNestingOffset,
} from './util';
export const ngfor = '*ngFor';
export const nakedngfor = 'ngFor';
const fors = [ngfor, nakedngfor];
export const commaSeparatedSyntax = new Map([
['(', ')'],
['{', '}'],
['[', ']'],
]);
export const stringPairs = new Map([
[`"`, `"`],
[`'`, `'`],
]);
/**
* Replaces structural directive ngFor instances with new for.
* Returns null if the migration failed (e.g. there was a syntax error).
*/
export function migrateFor(template: string): {
migrated: string;
errors: MigrateError[];
changed: boolean;
} {
let errors: MigrateError[] = [];
let parsed = parseTemplate(template);
if (parsed.tree === undefined) {
return {migrated: template, errors, changed: false};
}
let result = template;
const visitor = new ElementCollector(fors);
visitAll(visitor, parsed.tree.rootNodes);
calculateNesting(visitor, hasLineBreaks(template));
// this tracks the character shift from different lengths of blocks from
// the prior directives so as to adjust for nested block replacement during
// migration. Each block calculates length differences and passes that offset
// to the next migrating block to adjust character offsets properly.
let offset = 0;
let nestLevel = -1;
let postOffsets: number[] = [];
for (const el of visitor.elements) {
let migrateResult: Result = {tmpl: result, offsets: {pre: 0, post: 0}};
// applies the post offsets after closing
offset = reduceNestingOffset(el, nestLevel, offset, postOffsets);
try {
migrateResult = migrateNgFor(el, result, offset);
} catch (error: unknown) {
errors.push({type: ngfor, error});
}
result = migrateResult.tmpl;
offset += migrateResult.offsets.pre;
postOffsets.push(migrateResult.offsets.post);
nestLevel = el.nestCount;
}
const changed = visitor.elements.length > 0;
return {migrated: result, errors, changed};
}
function migrateNgFor(etm: ElementToMigrate, tmpl: string, offset: number): Result {
if (etm.forAttrs !== undefined) {
return migrateBoundNgFor(etm, tmpl, offset);
}
return migrateStandardNgFor(etm, tmpl, offset);
}
function migrateStandardNgFor(etm: ElementToMigrate, tmpl: string, offset: number): Result {
const aliasWithEqualRegexp = /=\s*(count|index|first|last|even|odd)/gm;
const aliasWithAsRegexp = /(count|index|first|last|even|odd)\s+as/gm;
const aliases = [];
const lbString = etm.hasLineBreaks ? '\n' : '';
const parts = getNgForParts(etm.attr.value);
const originals = getOriginals(etm, tmpl, offset);
// first portion should always be the loop definition prefixed with `let`
const condition = parts[0].replace('let ', '');
if (condition.indexOf(' as ') > -1) {
let errorMessage =
`Found an aliased collection on an ngFor: "${condition}".` +
' Collection aliasing is not supported with @for.' +
' Refactor the code to remove the `as` alias and re-run the migration.';
throw new Error(errorMessage);
}
const loopVar = condition.split(' of ')[0];
let trackBy = loopVar;
let aliasedIndex: string | null = null;
let tmplPlaceholder = '';
for (let i = 1; i < parts.length; i++) {
const part = parts[i].trim();
if (part.startsWith('trackBy:')) {
// build trackby value
const trackByFn = part.replace('trackBy:', '').trim();
trackBy = `${trackByFn}($index, ${loopVar})`;
}
// template
if (part.startsWith('template:')) {
// use an alternate placeholder here to avoid conflicts
tmplPlaceholder = getPlaceholder(part.split(':')[1].trim(), PlaceholderKind.Alternate);
}
// aliases
// declared with `let myIndex = index`
if (part.match(aliasWithEqualRegexp)) {
// 'let myIndex = index' -> ['let myIndex', 'index']
const aliasParts = part.split('=');
const aliasedName = aliasParts[0].replace('let', '').trim();
const originalName = aliasParts[1].trim();
if (aliasedName !== '$' + originalName) {
// -> 'let myIndex = $index'
aliases.push(` let ${aliasedName} = $${originalName}`);
}
// if the aliased variable is the index, then we store it
if (originalName === 'index') {
// 'let myIndex' -> 'myIndex'
aliasedIndex = aliasedName;
}
}
// declared with `index as myIndex`
if (part.match(aliasWithAsRegexp)) {
// 'index as myIndex' -> ['index', 'myIndex']
const aliasParts = part.split(/\s+as\s+/);
const originalName = aliasParts[0].trim();
const aliasedName = aliasParts[1].trim();
if (aliasedName !== '$' + originalName) {
// -> 'let myIndex = $index'
aliases.push(` let ${aliasedName} = $${originalName}`);
}
// if the aliased variable is the index, then we store it
if (originalName === 'index') {
aliasedIndex = aliasedName;
}
}
}
// if an alias has been defined for the index, then the trackBy function must use it
if (aliasedIndex !== null && trackBy !== loopVar) {
// byId($index, user) -> byId(i, user)
trackBy = trackBy.replace('$index', aliasedIndex);
}
const aliasStr = aliases.length > 0 ? `;${aliases.join(';')}` : '';
let startBlock = `${startMarker}@for (${condition}; track ${trackBy}${aliasStr}) {${lbString}`;
let endBlock = `${lbString}}${endMarker}`;
let forBlock = '';
if (tmplPlaceholder !== '') {
startBlock = startBlock + tmplPlaceholder;
forBlock = startBlock + endBlock;
} else {
const {start, middle, end} = getMainBlock(etm, tmpl, offset);
startBlock += start;
endBlock = end + endBlock;
forBlock = startBlock + middle + endBlock;
}
const updatedTmpl = tmpl.slice(0, etm.start(offset)) + forBlock + tmpl.slice(etm.end(offset));
const pre = originals.start.length - startBlock.length;
const post = originals.end.length - endBlock.length;
return {tmpl: updatedTmpl, offsets: {pre, post}};
} | {
"end_byte": 6428,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/fors.ts"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/fors.ts_6430_9035 | function migrateBoundNgFor(etm: ElementToMigrate, tmpl: string, offset: number): Result {
const forAttrs = etm.forAttrs!;
const aliasAttrs = etm.aliasAttrs!;
const aliasMap = aliasAttrs.aliases;
const originals = getOriginals(etm, tmpl, offset);
const condition = `${aliasAttrs.item} of ${forAttrs.forOf}`;
const aliases = [];
let aliasedIndex = '$index';
for (const [key, val] of aliasMap) {
aliases.push(` let ${key.trim()} = $${val}`);
if (val.trim() === 'index') {
aliasedIndex = key;
}
}
const aliasStr = aliases.length > 0 ? `;${aliases.join(';')}` : '';
let trackBy = aliasAttrs.item;
if (forAttrs.trackBy !== '') {
// build trackby value
trackBy = `${forAttrs.trackBy.trim()}(${aliasedIndex}, ${aliasAttrs.item})`;
}
const {start, middle, end} = getMainBlock(etm, tmpl, offset);
const startBlock = `${startMarker}@for (${condition}; track ${trackBy}${aliasStr}) {\n${start}`;
const endBlock = `${end}\n}${endMarker}`;
const forBlock = startBlock + middle + endBlock;
const updatedTmpl = tmpl.slice(0, etm.start(offset)) + forBlock + tmpl.slice(etm.end(offset));
const pre = originals.start.length - startBlock.length;
const post = originals.end.length - endBlock.length;
return {tmpl: updatedTmpl, offsets: {pre, post}};
}
function getNgForParts(expression: string): string[] {
const parts: string[] = [];
const commaSeparatedStack: string[] = [];
const stringStack: string[] = [];
let current = '';
for (let i = 0; i < expression.length; i++) {
const char = expression[i];
const isInString = stringStack.length === 0;
const isInCommaSeparated = commaSeparatedStack.length === 0;
// Any semicolon is a delimiter, as well as any comma outside
// of comma-separated syntax, as long as they're outside of a string.
if (
isInString &&
current.length > 0 &&
(char === ';' || (char === ',' && isInCommaSeparated))
) {
parts.push(current);
current = '';
continue;
}
if (stringStack.length > 0 && stringStack[stringStack.length - 1] === char) {
stringStack.pop();
} else if (stringPairs.has(char)) {
stringStack.push(stringPairs.get(char)!);
}
if (commaSeparatedSyntax.has(char)) {
commaSeparatedStack.push(commaSeparatedSyntax.get(char)!);
} else if (
commaSeparatedStack.length > 0 &&
commaSeparatedStack[commaSeparatedStack.length - 1] === char
) {
commaSeparatedStack.pop();
}
current += char;
}
if (current.length > 0) {
parts.push(current);
}
return parts;
} | {
"end_byte": 9035,
"start_byte": 6430,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/fors.ts"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/switches.ts_0_4051 | /**
* @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 {Element, Node, Text, visitAll} from '@angular/compiler';
import {cases} from './cases';
import {
ElementCollector,
ElementToMigrate,
endMarker,
MigrateError,
Result,
startMarker,
} from './types';
import {
calculateNesting,
getMainBlock,
getOriginals,
hasLineBreaks,
parseTemplate,
reduceNestingOffset,
} from './util';
export const ngswitch = '[ngSwitch]';
const switches = [ngswitch];
/**
* Replaces structural directive ngSwitch instances with new switch.
* Returns null if the migration failed (e.g. there was a syntax error).
*/
export function migrateSwitch(template: string): {
migrated: string;
errors: MigrateError[];
changed: boolean;
} {
let errors: MigrateError[] = [];
let parsed = parseTemplate(template);
if (parsed.tree === undefined) {
return {migrated: template, errors, changed: false};
}
let result = template;
const visitor = new ElementCollector(switches);
visitAll(visitor, parsed.tree.rootNodes);
calculateNesting(visitor, hasLineBreaks(template));
// this tracks the character shift from different lengths of blocks from
// the prior directives so as to adjust for nested block replacement during
// migration. Each block calculates length differences and passes that offset
// to the next migrating block to adjust character offsets properly.
let offset = 0;
let nestLevel = -1;
let postOffsets: number[] = [];
for (const el of visitor.elements) {
let migrateResult: Result = {tmpl: result, offsets: {pre: 0, post: 0}};
// applies the post offsets after closing
offset = reduceNestingOffset(el, nestLevel, offset, postOffsets);
if (el.attr.name === ngswitch) {
try {
migrateResult = migrateNgSwitch(el, result, offset);
} catch (error: unknown) {
errors.push({type: ngswitch, error});
}
}
result = migrateResult.tmpl;
offset += migrateResult.offsets.pre;
postOffsets.push(migrateResult.offsets.post);
nestLevel = el.nestCount;
}
const changed = visitor.elements.length > 0;
return {migrated: result, errors, changed};
}
function assertValidSwitchStructure(children: Node[]): void {
for (const child of children) {
if (child instanceof Text && child.value.trim() !== '') {
throw new Error(
`Text node: "${child.value}" would result in invalid migrated @switch block structure. ` +
`@switch can only have @case or @default as children.`,
);
} else if (child instanceof Element) {
let hasCase = false;
for (const attr of child.attrs) {
if (cases.includes(attr.name)) {
hasCase = true;
}
}
if (!hasCase) {
throw new Error(
`Element node: "${child.name}" would result in invalid migrated @switch block structure. ` +
`@switch can only have @case or @default as children.`,
);
}
}
}
}
function migrateNgSwitch(etm: ElementToMigrate, tmpl: string, offset: number): Result {
const lbString = etm.hasLineBreaks ? '\n' : '';
const condition = etm.attr.value;
const originals = getOriginals(etm, tmpl, offset);
assertValidSwitchStructure(originals.childNodes);
const {start, middle, end} = getMainBlock(etm, tmpl, offset);
const startBlock = `${startMarker}${start}${lbString}@switch (${condition}) {`;
const endBlock = `}${lbString}${end}${endMarker}`;
const switchBlock = startBlock + middle + endBlock;
const updatedTmpl = tmpl.slice(0, etm.start(offset)) + switchBlock + tmpl.slice(etm.end(offset));
// this should be the difference between the starting element up to the start of the closing
// element and the mainblock sans }
const pre = originals.start.length - startBlock.length;
const post = originals.end.length - endBlock.length;
return {tmpl: updatedTmpl, offsets: {pre, post}};
}
| {
"end_byte": 4051,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/switches.ts"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/util.ts_0_8450 | /**
* @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 {Attribute, Element, HtmlParser, Node, ParseTreeResult, visitAll} from '@angular/compiler';
import {dirname, join} from 'path';
import ts from 'typescript';
import {
AnalyzedFile,
CommonCollector,
ElementCollector,
ElementToMigrate,
endI18nMarker,
endMarker,
i18nCollector,
importRemovals,
importWithCommonRemovals,
MigrateError,
ParseResult,
startI18nMarker,
startMarker,
Template,
TemplateCollector,
} from './types';
const startMarkerRegex = new RegExp(startMarker, 'gm');
const endMarkerRegex = new RegExp(endMarker, 'gm');
const startI18nMarkerRegex = new RegExp(startI18nMarker, 'gm');
const endI18nMarkerRegex = new RegExp(endI18nMarker, 'gm');
const replaceMarkerRegex = new RegExp(`${startMarker}|${endMarker}`, 'gm');
/**
* Analyzes a source file to find file that need to be migrated and the text ranges within them.
* @param sourceFile File to be analyzed.
* @param analyzedFiles Map in which to store the results.
*/
export function analyze(sourceFile: ts.SourceFile, analyzedFiles: Map<string, AnalyzedFile>) {
forEachClass(sourceFile, (node) => {
if (ts.isClassDeclaration(node)) {
analyzeDecorators(node, sourceFile, analyzedFiles);
} else {
analyzeImportDeclarations(node, sourceFile, analyzedFiles);
}
});
}
function checkIfShouldChange(decl: ts.ImportDeclaration, file: AnalyzedFile) {
const range = file.importRanges.find((r) => r.type === 'importDeclaration');
if (range === undefined || !range.remove) {
return false;
}
// should change if you can remove the common module
// if it's not safe to remove the common module
// and that's the only thing there, we should do nothing.
const clause = decl.getChildAt(1) as ts.ImportClause;
return !(
!file.removeCommonModule &&
clause.namedBindings &&
ts.isNamedImports(clause.namedBindings) &&
clause.namedBindings.elements.length === 1 &&
clause.namedBindings.elements[0].getText() === 'CommonModule'
);
}
function updateImportDeclaration(decl: ts.ImportDeclaration, removeCommonModule: boolean): string {
const clause = decl.getChildAt(1) as ts.ImportClause;
const updatedClause = updateImportClause(clause, removeCommonModule);
if (updatedClause === null) {
return '';
}
// removeComments is set to true to prevent duplication of comments
// when the import declaration is at the top of the file, but right after a comment
// without this, the comment gets duplicated when the declaration is updated.
// the typescript AST includes that preceding comment as part of the import declaration full text.
const printer = ts.createPrinter({
removeComments: true,
});
const updated = ts.factory.updateImportDeclaration(
decl,
decl.modifiers,
updatedClause,
decl.moduleSpecifier,
undefined,
);
return printer.printNode(ts.EmitHint.Unspecified, updated, clause.getSourceFile());
}
function updateImportClause(
clause: ts.ImportClause,
removeCommonModule: boolean,
): ts.ImportClause | null {
if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) {
const removals = removeCommonModule ? importWithCommonRemovals : importRemovals;
const elements = clause.namedBindings.elements.filter((el) => !removals.includes(el.getText()));
if (elements.length === 0) {
return null;
}
clause = ts.factory.updateImportClause(
clause,
clause.isTypeOnly,
clause.name,
ts.factory.createNamedImports(elements),
);
}
return clause;
}
function updateClassImports(
propAssignment: ts.PropertyAssignment,
removeCommonModule: boolean,
): string | null {
const printer = ts.createPrinter();
const importList = propAssignment.initializer;
// Can't change non-array literals.
if (!ts.isArrayLiteralExpression(importList)) {
return null;
}
const removals = removeCommonModule ? importWithCommonRemovals : importRemovals;
const elements = importList.elements.filter(
(el) => !ts.isIdentifier(el) || !removals.includes(el.text),
);
if (elements.length === importList.elements.length) {
// nothing changed
return null;
}
const updatedElements = ts.factory.updateArrayLiteralExpression(importList, elements);
const updatedAssignment = ts.factory.updatePropertyAssignment(
propAssignment,
propAssignment.name,
updatedElements,
);
return printer.printNode(
ts.EmitHint.Unspecified,
updatedAssignment,
updatedAssignment.getSourceFile(),
);
}
function analyzeImportDeclarations(
node: ts.ImportDeclaration,
sourceFile: ts.SourceFile,
analyzedFiles: Map<string, AnalyzedFile>,
) {
if (node.getText().indexOf('@angular/common') === -1) {
return;
}
const clause = node.getChildAt(1) as ts.ImportClause;
if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) {
const elements = clause.namedBindings.elements.filter((el) =>
importWithCommonRemovals.includes(el.getText()),
);
if (elements.length > 0) {
AnalyzedFile.addRange(sourceFile.fileName, sourceFile, analyzedFiles, {
start: node.getStart(),
end: node.getEnd(),
node,
type: 'importDeclaration',
remove: true,
});
}
}
}
function analyzeDecorators(
node: ts.ClassDeclaration,
sourceFile: ts.SourceFile,
analyzedFiles: Map<string, AnalyzedFile>,
) {
// Note: we have a utility to resolve the Angular decorators from a class declaration already.
// We don't use it here, because it requires access to the type checker which makes it more
// time-consuming to run internally.
const decorator = ts.getDecorators(node)?.find((dec) => {
return (
ts.isCallExpression(dec.expression) &&
ts.isIdentifier(dec.expression.expression) &&
dec.expression.expression.text === 'Component'
);
}) as (ts.Decorator & {expression: ts.CallExpression}) | undefined;
const metadata =
decorator &&
decorator.expression.arguments.length > 0 &&
ts.isObjectLiteralExpression(decorator.expression.arguments[0])
? decorator.expression.arguments[0]
: null;
if (!metadata) {
return;
}
for (const prop of metadata.properties) {
// All the properties we care about should have static
// names and be initialized to a static string.
if (
!ts.isPropertyAssignment(prop) ||
(!ts.isIdentifier(prop.name) && !ts.isStringLiteralLike(prop.name))
) {
continue;
}
switch (prop.name.text) {
case 'template':
// +1/-1 to exclude the opening/closing characters from the range.
AnalyzedFile.addRange(sourceFile.fileName, sourceFile, analyzedFiles, {
start: prop.initializer.getStart() + 1,
end: prop.initializer.getEnd() - 1,
node: prop,
type: 'template',
remove: true,
});
break;
case 'imports':
AnalyzedFile.addRange(sourceFile.fileName, sourceFile, analyzedFiles, {
start: prop.name.getStart(),
end: prop.initializer.getEnd(),
node: prop,
type: 'importDecorator',
remove: true,
});
break;
case 'templateUrl':
// Leave the end as undefined which means that the range is until the end of the file.
if (ts.isStringLiteralLike(prop.initializer)) {
const path = join(dirname(sourceFile.fileName), prop.initializer.text);
AnalyzedFile.addRange(path, sourceFile, analyzedFiles, {
start: 0,
node: prop,
type: 'templateUrl',
remove: true,
});
}
break;
}
}
}
/**
* returns the level deep a migratable element is nested
*/
function getNestedCount(etm: ElementToMigrate, aggregator: number[]) {
if (aggregator.length === 0) {
return 0;
}
if (
etm.el.sourceSpan.start.offset < aggregator[aggregator.length - 1] &&
etm.el.sourceSpan.end.offset !== aggregator[aggregator.length - 1]
) {
// element is nested
aggregator.push(etm.el.sourceSpan.end.offset);
return aggregator.length - 1;
} else {
// not nested
aggregator.pop()!;
return getNestedCount(etm, aggregator);
}
}
/**
* parses the template string into the Html AST
*/ | {
"end_byte": 8450,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/util.ts"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/util.ts_8451_14891 | export function parseTemplate(template: string): ParseResult {
let parsed: ParseTreeResult;
try {
// Note: we use the HtmlParser here, instead of the `parseTemplate` function, because the
// latter returns an Ivy AST, not an HTML AST. The HTML AST has the advantage of preserving
// interpolated text as text nodes containing a mixture of interpolation tokens and text tokens,
// rather than turning them into `BoundText` nodes like the Ivy AST does. This allows us to
// easily get the text-only ranges without having to reconstruct the original text.
parsed = new HtmlParser().parse(template, '', {
// Allows for ICUs to be parsed.
tokenizeExpansionForms: true,
// Explicitly disable blocks so that their characters are treated as plain text.
tokenizeBlocks: true,
preserveLineEndings: true,
});
// Don't migrate invalid templates.
if (parsed.errors && parsed.errors.length > 0) {
const errors = parsed.errors.map((e) => ({type: 'parse', error: e}));
return {tree: undefined, errors};
}
} catch (e: any) {
return {tree: undefined, errors: [{type: 'parse', error: e}]};
}
return {tree: parsed, errors: []};
}
export function validateMigratedTemplate(migrated: string, fileName: string): MigrateError[] {
const parsed = parseTemplate(migrated);
let errors: MigrateError[] = [];
if (parsed.errors.length > 0) {
errors.push({
type: 'parse',
error: new Error(
`The migration resulted in invalid HTML for ${fileName}. ` +
`Please check the template for valid HTML structures and run the migration again.`,
),
});
}
if (parsed.tree) {
const i18nError = validateI18nStructure(parsed.tree, fileName);
if (i18nError !== null) {
errors.push({type: 'i18n', error: i18nError});
}
}
return errors;
}
export function validateI18nStructure(parsed: ParseTreeResult, fileName: string): Error | null {
const visitor = new i18nCollector();
visitAll(visitor, parsed.rootNodes);
const parents = visitor.elements.filter((el) => el.children.length > 0);
for (const p of parents) {
for (const el of visitor.elements) {
if (el === p) continue;
if (isChildOf(p, el)) {
return new Error(
`i18n Nesting error: The migration would result in invalid i18n nesting for ` +
`${fileName}. Element with i18n attribute "${p.name}" would result having a child of ` +
`element with i18n attribute "${el.name}". Please fix and re-run the migration.`,
);
}
}
}
return null;
}
function isChildOf(parent: Element, el: Element): boolean {
return (
parent.sourceSpan.start.offset < el.sourceSpan.start.offset &&
parent.sourceSpan.end.offset > el.sourceSpan.end.offset
);
}
/** Possible placeholders that can be generated by `getPlaceholder`. */
export enum PlaceholderKind {
Default,
Alternate,
}
/**
* Wraps a string in a placeholder that makes it easier to identify during replacement operations.
*/
export function getPlaceholder(
value: string,
kind: PlaceholderKind = PlaceholderKind.Default,
): string {
const name = `<<<ɵɵngControlFlowMigration_${kind}ɵɵ>>>`;
return `___${name}${value}${name}___`;
}
/**
* calculates the level of nesting of the items in the collector
*/
export function calculateNesting(
visitor: ElementCollector | TemplateCollector,
hasLineBreaks: boolean,
): void {
// start from top of template
// loop through each element
let nestedQueue: number[] = [];
for (let i = 0; i < visitor.elements.length; i++) {
let currEl = visitor.elements[i];
if (i === 0) {
nestedQueue.push(currEl.el.sourceSpan.end.offset);
currEl.hasLineBreaks = hasLineBreaks;
continue;
}
currEl.hasLineBreaks = hasLineBreaks;
currEl.nestCount = getNestedCount(currEl, nestedQueue);
if (currEl.el.sourceSpan.end.offset !== nestedQueue[nestedQueue.length - 1]) {
nestedQueue.push(currEl.el.sourceSpan.end.offset);
}
}
}
function escapeRegExp(val: string) {
return val.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
/**
* determines if a given template string contains line breaks
*/
export function hasLineBreaks(template: string): boolean {
return /\r|\n/.test(template);
}
/**
* properly adjusts template offsets based on current nesting levels
*/
export function reduceNestingOffset(
el: ElementToMigrate,
nestLevel: number,
offset: number,
postOffsets: number[],
): number {
if (el.nestCount <= nestLevel) {
const count = nestLevel - el.nestCount;
// reduced nesting, add postoffset
for (let i = 0; i <= count; i++) {
offset += postOffsets.pop() ?? 0;
}
}
return offset;
}
/**
* Replaces structural directive control flow instances with block control flow equivalents.
* Returns null if the migration failed (e.g. there was a syntax error).
*/
export function getTemplates(template: string): Map<string, Template> {
const parsed = parseTemplate(template);
if (parsed.tree !== undefined) {
const visitor = new TemplateCollector();
visitAll(visitor, parsed.tree.rootNodes);
// count usages of each ng-template
for (let [key, tmpl] of visitor.templates) {
const escapeKey = escapeRegExp(key.slice(1));
const regex = new RegExp(`[^a-zA-Z0-9-<(\']${escapeKey}\\W`, 'gm');
const matches = template.match(regex);
tmpl.count = matches?.length ?? 0;
tmpl.generateContents(template);
}
return visitor.templates;
}
return new Map<string, Template>();
}
export function updateTemplates(
template: string,
templates: Map<string, Template>,
): Map<string, Template> {
const updatedTemplates = getTemplates(template);
for (let [key, tmpl] of updatedTemplates) {
templates.set(key, tmpl);
}
return templates;
}
function wrapIntoI18nContainer(i18nAttr: Attribute, content: string) {
const {start, middle, end} = generatei18nContainer(i18nAttr, content);
return `${start}${middle}${end}`;
}
function generatei18nContainer(
i18nAttr: Attribute,
middle: string,
): {start: string; middle: string; end: string} {
const i18n = i18nAttr.value === '' ? 'i18n' : `i18n="${i18nAttr.value}"`;
return {start: `<ng-container ${i18n}>`, middle, end: `</ng-container>`};
}
/**
* Counts, replaces, and removes any necessary ng-templates post control flow migration
*/
exp | {
"end_byte": 14891,
"start_byte": 8451,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/util.ts"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/util.ts_14892_21368 | rt function processNgTemplates(template: string): {migrated: string; err: Error | undefined} {
// count usage
try {
const templates = getTemplates(template);
// swap placeholders and remove
for (const [name, t] of templates) {
const replaceRegex = new RegExp(getPlaceholder(name.slice(1)), 'g');
const forRegex = new RegExp(getPlaceholder(name.slice(1), PlaceholderKind.Alternate), 'g');
const forMatches = [...template.matchAll(forRegex)];
const matches = [...forMatches, ...template.matchAll(replaceRegex)];
let safeToRemove = true;
if (matches.length > 0) {
if (t.i18n !== null) {
const container = wrapIntoI18nContainer(t.i18n, t.children);
template = template.replace(replaceRegex, container);
} else if (t.children.trim() === '' && t.isNgTemplateOutlet) {
template = template.replace(replaceRegex, t.generateTemplateOutlet());
} else if (forMatches.length > 0) {
if (t.count === 2) {
template = template.replace(forRegex, t.children);
} else {
template = template.replace(forRegex, t.generateTemplateOutlet());
safeToRemove = false;
}
} else {
template = template.replace(replaceRegex, t.children);
}
// the +1 accounts for the t.count's counting of the original template
if (t.count === matches.length + 1 && safeToRemove) {
template = template.replace(t.contents, `${startMarker}${endMarker}`);
}
// templates may have changed structure from nested replaced templates
// so we need to reprocess them before the next loop.
updateTemplates(template, templates);
}
}
// template placeholders may still exist if the ng-template name is not
// present in the component. This could be because it's passed in from
// another component. In that case, we need to replace any remaining
// template placeholders with template outlets.
template = replaceRemainingPlaceholders(template);
return {migrated: template, err: undefined};
} catch (err) {
return {migrated: template, err: err as Error};
}
}
function replaceRemainingPlaceholders(template: string): string {
const pattern = '.*';
const placeholderPattern = getPlaceholder(pattern);
const replaceRegex = new RegExp(placeholderPattern, 'g');
const [placeholderStart, placeholderEnd] = placeholderPattern.split(pattern);
const placeholders = [...template.matchAll(replaceRegex)];
for (let ph of placeholders) {
const placeholder = ph[0];
const name = placeholder.slice(
placeholderStart.length,
placeholder.length - placeholderEnd.length,
);
template = template.replace(
placeholder,
`<ng-template [ngTemplateOutlet]="${name}"></ng-template>`,
);
}
return template;
}
/**
* determines if the CommonModule can be safely removed from imports
*/
export function canRemoveCommonModule(template: string): boolean {
const parsed = parseTemplate(template);
let removeCommonModule = false;
if (parsed.tree !== undefined) {
const visitor = new CommonCollector();
visitAll(visitor, parsed.tree.rootNodes);
removeCommonModule = visitor.count === 0;
}
return removeCommonModule;
}
/**
* removes imports from template imports and import declarations
*/
export function removeImports(template: string, node: ts.Node, file: AnalyzedFile): string {
if (template.startsWith('imports') && ts.isPropertyAssignment(node)) {
const updatedImport = updateClassImports(node, file.removeCommonModule);
return updatedImport ?? template;
} else if (ts.isImportDeclaration(node) && checkIfShouldChange(node, file)) {
return updateImportDeclaration(node, file.removeCommonModule);
}
return template;
}
/**
* retrieves the original block of text in the template for length comparison during migration
* processing
*/
export function getOriginals(
etm: ElementToMigrate,
tmpl: string,
offset: number,
): {start: string; end: string; childLength: number; children: string[]; childNodes: Node[]} {
// original opening block
if (etm.el.children.length > 0) {
const childStart = etm.el.children[0].sourceSpan.start.offset - offset;
const childEnd = etm.el.children[etm.el.children.length - 1].sourceSpan.end.offset - offset;
const start = tmpl.slice(
etm.el.sourceSpan.start.offset - offset,
etm.el.children[0].sourceSpan.start.offset - offset,
);
// original closing block
const end = tmpl.slice(
etm.el.children[etm.el.children.length - 1].sourceSpan.end.offset - offset,
etm.el.sourceSpan.end.offset - offset,
);
const childLength = childEnd - childStart;
return {
start,
end,
childLength,
children: getOriginalChildren(etm.el.children, tmpl, offset),
childNodes: etm.el.children,
};
}
// self closing or no children
const start = tmpl.slice(
etm.el.sourceSpan.start.offset - offset,
etm.el.sourceSpan.end.offset - offset,
);
// original closing block
return {start, end: '', childLength: 0, children: [], childNodes: []};
}
function getOriginalChildren(children: Node[], tmpl: string, offset: number) {
return children.map((child) => {
return tmpl.slice(child.sourceSpan.start.offset - offset, child.sourceSpan.end.offset - offset);
});
}
function isI18nTemplate(etm: ElementToMigrate, i18nAttr: Attribute | undefined): boolean {
let attrCount = countAttributes(etm);
const safeToRemove = etm.el.attrs.length === attrCount + (i18nAttr !== undefined ? 1 : 0);
return etm.el.name === 'ng-template' && i18nAttr !== undefined && safeToRemove;
}
function isRemovableContainer(etm: ElementToMigrate): boolean {
let attrCount = countAttributes(etm);
const safeToRemove = etm.el.attrs.length === attrCount;
return (etm.el.name === 'ng-container' || etm.el.name === 'ng-template') && safeToRemove;
}
function countAttributes(etm: ElementToMigrate): number {
let attrCount = 1;
if (etm.elseAttr !== undefined) {
attrCount++;
}
if (etm.thenAttr !== undefined) {
attrCount++;
}
attrCount += etm.aliasAttrs?.aliases.size ?? 0;
attrCount += etm.aliasAttrs?.item ? 1 : 0;
attrCount += etm.forAttrs?.trackBy ? 1 : 0;
attrCount += etm.forAttrs?.forOf ? 1 : 0;
return attrCount;
}
/**
* builds the proper contents of what goes inside a given control flow block after migration
*/
exp | {
"end_byte": 21368,
"start_byte": 14892,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/util.ts"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/util.ts_21369_24640 | rt function getMainBlock(
etm: ElementToMigrate,
tmpl: string,
offset: number,
): {start: string; middle: string; end: string} {
const i18nAttr = etm.el.attrs.find((x) => x.name === 'i18n');
// removable containers are ng-templates or ng-containers that no longer need to exist
// post migration
if (isRemovableContainer(etm)) {
let middle = '';
if (etm.hasChildren()) {
const {childStart, childEnd} = etm.getChildSpan(offset);
middle = tmpl.slice(childStart, childEnd);
} else {
middle = '';
}
return {start: '', middle, end: ''};
} else if (isI18nTemplate(etm, i18nAttr)) {
// here we're removing an ng-template used for control flow and i18n and
// converting it to an ng-container with i18n
const {childStart, childEnd} = etm.getChildSpan(offset);
return generatei18nContainer(i18nAttr!, tmpl.slice(childStart, childEnd));
}
// the index of the start of the attribute adjusting for offset shift
const attrStart = etm.attr.keySpan!.start.offset - 1 - offset;
// the index of the very end of the attribute value adjusted for offset shift
const valEnd = etm.getValueEnd(offset);
// the index of the children start and end span, if they exist. Otherwise use the value end.
const {childStart, childEnd} = etm.hasChildren()
? etm.getChildSpan(offset)
: {childStart: valEnd, childEnd: valEnd};
// the beginning of the updated string in the main block, for example: <div some="attributes">
let start = tmpl.slice(etm.start(offset), attrStart) + tmpl.slice(valEnd, childStart);
// the middle is the actual contents of the element
const middle = tmpl.slice(childStart, childEnd);
// the end is the closing part of the element, example: </div>
let end = tmpl.slice(childEnd, etm.end(offset));
if (etm.shouldRemoveElseAttr()) {
// this removes a bound ngIfElse attribute that's no longer needed
// this could be on the start or end
start = start.replace(etm.getElseAttrStr(), '');
end = end.replace(etm.getElseAttrStr(), '');
}
return {start, middle, end};
}
function generateI18nMarkers(tmpl: string): string {
let parsed = parseTemplate(tmpl);
if (parsed.tree !== undefined) {
const visitor = new i18nCollector();
visitAll(visitor, parsed.tree.rootNodes);
for (const [ix, el] of visitor.elements.entries()) {
// we only care about elements with children and i18n tags
// elements without children have nothing to translate
// offset accounts for the addition of the 2 marker characters with each loop.
const offset = ix * 2;
if (el.children.length > 0) {
tmpl = addI18nMarkers(tmpl, el, offset);
}
}
}
return tmpl;
}
function addI18nMarkers(tmpl: string, el: Element, offset: number): string {
const startPos = el.children[0].sourceSpan.start.offset + offset;
const endPos = el.children[el.children.length - 1].sourceSpan.end.offset + offset;
return (
tmpl.slice(0, startPos) +
startI18nMarker +
tmpl.slice(startPos, endPos) +
endI18nMarker +
tmpl.slice(endPos)
);
}
const selfClosingList = 'input|br|img|base|wbr|area|col|embed|hr|link|meta|param|source|track';
/**
* re-indents all the lines in the template properly post migration
*/
exp | {
"end_byte": 24640,
"start_byte": 21369,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/util.ts"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/util.ts_24641_31738 | rt function formatTemplate(tmpl: string, templateType: string): string {
if (tmpl.indexOf('\n') > -1) {
tmpl = generateI18nMarkers(tmpl);
// tracks if a self closing element opened without closing yet
let openSelfClosingEl = false;
// match any type of control flow block as start of string ignoring whitespace
// @if | @switch | @case | @default | @for | } @else
const openBlockRegex = /^\s*\@(if|switch|case|default|for)|^\s*\}\s\@else/;
// regex for matching an html element opening
// <div thing="stuff" [binding]="true"> || <div thing="stuff" [binding]="true"
const openElRegex = /^\s*<([a-z0-9]+)(?![^>]*\/>)[^>]*>?/;
// regex for matching an attribute string that was left open at the endof a line
// so we can ensure we have the proper indent
// <div thing="aefaefwe
const openAttrDoubleRegex = /="([^"]|\\")*$/;
const openAttrSingleRegex = /='([^']|\\')*$/;
// regex for matching an attribute string that was closes on a separate line
// from when it was opened.
// <div thing="aefaefwe
// i18n message is here">
const closeAttrDoubleRegex = /^\s*([^><]|\\")*"/;
const closeAttrSingleRegex = /^\s*([^><]|\\')*'/;
// regex for matching a self closing html element that has no />
// <input type="button" [binding]="true">
const selfClosingRegex = new RegExp(`^\\s*<(${selfClosingList}).+\\/?>`);
// regex for matching a self closing html element that is on multi lines
// <input type="button" [binding]="true"> || <input type="button" [binding]="true"
const openSelfClosingRegex = new RegExp(`^\\s*<(${selfClosingList})(?![^>]*\\/>)[^>]*$`);
// match closing block or else block
// } | } @else
const closeBlockRegex = /^\s*\}\s*$|^\s*\}\s\@else/;
// matches closing of an html element
// </element>
const closeElRegex = /\s*<\/([a-zA-Z0-9\-_]+)\s*>/m;
// matches closing of a self closing html element when the element is on multiple lines
// [binding]="value" />
const closeMultiLineElRegex = /^\s*([a-zA-Z0-9\-_\[\]]+)?=?"?([^”<]+)?"?\s?\/>$/;
// matches closing of a self closing html element when the element is on multiple lines
// with no / in the closing: [binding]="value">
const closeSelfClosingMultiLineRegex = /^\s*([a-zA-Z0-9\-_\[\]]+)?=?"?([^”\/<]+)?"?\s?>$/;
// matches an open and close of an html element on a single line with no breaks
// <div>blah</div>
const singleLineElRegex = /\s*<([a-zA-Z0-9]+)(?![^>]*\/>)[^>]*>.*<\/([a-zA-Z0-9\-_]+)\s*>/;
const lines = tmpl.split('\n');
const formatted = [];
// the indent applied during formatting
let indent = '';
// the pre-existing indent in an inline template that we'd like to preserve
let mindent = '';
let depth = 0;
let i18nDepth = 0;
let inMigratedBlock = false;
let inI18nBlock = false;
let inAttribute = false;
let isDoubleQuotes = false;
for (let [index, line] of lines.entries()) {
depth +=
[...line.matchAll(startMarkerRegex)].length - [...line.matchAll(endMarkerRegex)].length;
inMigratedBlock = depth > 0;
i18nDepth +=
[...line.matchAll(startI18nMarkerRegex)].length -
[...line.matchAll(endI18nMarkerRegex)].length;
let lineWasMigrated = false;
if (line.match(replaceMarkerRegex)) {
line = line.replace(replaceMarkerRegex, '');
lineWasMigrated = true;
}
if (
line.trim() === '' &&
index !== 0 &&
index !== lines.length - 1 &&
(inMigratedBlock || lineWasMigrated) &&
!inI18nBlock &&
!inAttribute
) {
// skip blank lines except if it's the first line or last line
// this preserves leading and trailing spaces if they are already present
continue;
}
// preserves the indentation of an inline template
if (templateType === 'template' && index <= 1) {
// first real line of an inline template
const ind = line.search(/\S/);
mindent = ind > -1 ? line.slice(0, ind) : '';
}
// if a block closes, an element closes, and it's not an element on a single line or the end
// of a self closing tag
if (
(closeBlockRegex.test(line) ||
(closeElRegex.test(line) &&
!singleLineElRegex.test(line) &&
!closeMultiLineElRegex.test(line))) &&
indent !== ''
) {
// close block, reduce indent
indent = indent.slice(2);
}
// if a line ends in an unclosed attribute, we need to note that and close it later
const isOpenDoubleAttr = openAttrDoubleRegex.test(line);
const isOpenSingleAttr = openAttrSingleRegex.test(line);
if (!inAttribute && isOpenDoubleAttr) {
inAttribute = true;
isDoubleQuotes = true;
} else if (!inAttribute && isOpenSingleAttr) {
inAttribute = true;
isDoubleQuotes = false;
}
const newLine =
inI18nBlock || inAttribute
? line
: mindent + (line.trim() !== '' ? indent : '') + line.trim();
formatted.push(newLine);
if (
!isOpenDoubleAttr &&
!isOpenSingleAttr &&
((inAttribute && isDoubleQuotes && closeAttrDoubleRegex.test(line)) ||
(inAttribute && !isDoubleQuotes && closeAttrSingleRegex.test(line)))
) {
inAttribute = false;
}
// this matches any self closing element that actually has a />
if (closeMultiLineElRegex.test(line)) {
// multi line self closing tag
indent = indent.slice(2);
if (openSelfClosingEl) {
openSelfClosingEl = false;
}
}
// this matches a self closing element that doesn't have a / in the >
if (closeSelfClosingMultiLineRegex.test(line) && openSelfClosingEl) {
openSelfClosingEl = false;
indent = indent.slice(2);
}
// this matches an open control flow block, an open HTML element, but excludes single line
// self closing tags
if (
(openBlockRegex.test(line) || openElRegex.test(line)) &&
!singleLineElRegex.test(line) &&
!selfClosingRegex.test(line) &&
!openSelfClosingRegex.test(line)
) {
// open block, increase indent
indent += ' ';
}
// This is a self closing element that is definitely not fully closed and is on multiple lines
if (openSelfClosingRegex.test(line)) {
openSelfClosingEl = true;
// add to the indent for the properties on it to look nice
indent += ' ';
}
inI18nBlock = i18nDepth > 0;
}
tmpl = formatted.join('\n');
}
return tmpl;
}
/** Executes a callback on each class declaration in a file. */
function forEachClass(
sourceFile: ts.SourceFile,
callback: (node: ts.ClassDeclaration | ts.ImportDeclaration) => void,
) {
sourceFile.forEachChild(function walk(node) {
if (ts.isClassDeclaration(node) || ts.isImportDeclaration(node)) {
callback(node);
}
node.forEachChild(walk);
});
}
| {
"end_byte": 31738,
"start_byte": 24641,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/util.ts"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/BUILD.bazel_0_657 | 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 = "control-flow-migration",
srcs = glob(["**/*.ts"]),
tsconfig = "//packages/core/schematics:tsconfig.json",
deps = [
"//packages/compiler",
"//packages/core/schematics/utils",
"@npm//@angular-devkit/schematics",
"@npm//@types/node",
"@npm//typescript",
],
)
| {
"end_byte": 657,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/BUILD.bazel"
} |
angular/packages/core/schematics/ng-generate/control-flow-migration/index.ts_0_4242 | /**
* @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, SchematicContext, SchematicsException, Tree} from '@angular-devkit/schematics';
import {join, relative} from 'path';
import {normalizePath} from '../../utils/change_tracker';
import {canMigrateFile, createMigrationProgram} from '../../utils/typescript/compiler_host';
import {migrateTemplate} from './migration';
import {AnalyzedFile, MigrateError} from './types';
import {analyze} from './util';
interface Options {
path: string;
format: boolean;
}
export function migrate(options: Options): Rule {
return async (tree: Tree, context: SchematicContext) => {
const basePath = process.cwd();
const pathToMigrate = normalizePath(join(basePath, options.path));
let allPaths = [];
if (pathToMigrate.trim() !== '') {
allPaths.push(pathToMigrate);
}
if (!allPaths.length) {
throw new SchematicsException(
'Could not find any tsconfig file. Cannot run the control flow migration.',
);
}
let errors: string[] = [];
for (const tsconfigPath of allPaths) {
const migrateErrors = runControlFlowMigration(
tree,
tsconfigPath,
basePath,
pathToMigrate,
options,
);
errors = [...errors, ...migrateErrors];
}
if (errors.length > 0) {
context.logger.warn(`WARNING: ${errors.length} errors occurred during your migration:\n`);
errors.forEach((err: string) => {
context.logger.warn(err);
});
}
};
}
function runControlFlowMigration(
tree: Tree,
tsconfigPath: string,
basePath: string,
pathToMigrate: string,
schematicOptions: Options,
): string[] {
if (schematicOptions.path.startsWith('..')) {
throw new SchematicsException(
'Cannot run control flow migration outside of the current project.',
);
}
const program = createMigrationProgram(tree, tsconfigPath, basePath);
const sourceFiles = program
.getSourceFiles()
.filter(
(sourceFile) =>
sourceFile.fileName.startsWith(pathToMigrate) &&
canMigrateFile(basePath, sourceFile, program),
);
if (sourceFiles.length === 0) {
throw new SchematicsException(
`Could not find any files to migrate under the path ${pathToMigrate}. Cannot run the control flow migration.`,
);
}
const analysis = new Map<string, AnalyzedFile>();
const migrateErrors = new Map<string, MigrateError[]>();
for (const sourceFile of sourceFiles) {
analyze(sourceFile, analysis);
}
// sort files with .html files first
// this ensures class files know if it's safe to remove CommonModule
const paths = sortFilePaths([...analysis.keys()]);
for (const path of paths) {
const file = analysis.get(path)!;
const ranges = file.getSortedRanges();
const relativePath = relative(basePath, path);
const content = tree.readText(relativePath);
const update = tree.beginUpdate(relativePath);
for (const {start, end, node, type} of ranges) {
const template = content.slice(start, end);
const length = (end ?? content.length) - start;
const {migrated, errors} = migrateTemplate(
template,
type,
node,
file,
schematicOptions.format,
analysis,
);
if (migrated !== null) {
update.remove(start, length);
update.insertLeft(start, migrated);
}
if (errors.length > 0) {
migrateErrors.set(path, errors);
}
}
tree.commitUpdate(update);
}
const errorList: string[] = [];
for (let [template, errors] of migrateErrors) {
errorList.push(generateErrorMessage(template, errors));
}
return errorList;
}
function sortFilePaths(names: string[]): string[] {
names.sort((a, _) => (a.endsWith('.html') ? -1 : 0));
return names;
}
function generateErrorMessage(path: string, errors: MigrateError[]): string {
let errorMessage = `Template "${path}" encountered ${errors.length} errors during migration:\n`;
errorMessage += errors.map((e) => ` - ${e.type}: ${e.error}\n`);
return errorMessage;
}
| {
"end_byte": 4242,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/ng-generate/control-flow-migration/index.ts"
} |
angular/packages/core/global/PACKAGE.md_0_367 | Exposes a set of functions in the global namespace which are useful for debugging the current state
of your application.
These functions are exposed via the global `ng` "namespace" variable automatically when you import
from `@angular/core` and run your application in development mode. These functions are not exposed
when the application runs in a production mode.
| {
"end_byte": 367,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/global/PACKAGE.md"
} |
angular/packages/core/global/BUILD.bazel_0_472 | load("//tools:defaults.bzl", "generate_api_docs")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "files_for_docgen",
srcs = [
"index.ts",
],
)
generate_api_docs(
name = "core_global_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
],
entry_point = ":index.ts",
module_label = "<code>window.ng</code> globals",
module_name = "@angular/core/globals",
)
| {
"end_byte": 472,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/global/BUILD.bazel"
} |
angular/packages/core/global/index.ts_0_444 | /**
* @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
*/
// The global utilities are re-exported through here so that they get their own separate `global`
// section in the API docs which makes it more visible that they can't be imported directly.
export * from '../src/render3/global_utils_api';
| {
"end_byte": 444,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/global/index.ts"
} |
angular/packages/core/src/profiler.ts_0_1835 | /**
* @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 const PERFORMANCE_MARK_PREFIX = '🅰️';
let enablePerfLogging = false;
/**
* Function that will start measuring against the performance API
* Should be used in pair with stopMeasuring
*/
export function startMeasuring<T>(label: string): void {
if (!enablePerfLogging) {
return;
}
const {startLabel} = labels(label);
/* tslint:disable:ban */
performance.mark(startLabel);
/* tslint:enable:ban */
}
/**
* Function that will stop measuring against the performance API
* Should be used in pair with stopMeasuring
*/
export function stopMeasuring(label: string): void {
if (!enablePerfLogging) {
return;
}
const {startLabel, labelName, endLabel} = labels(label);
/* tslint:disable:ban */
performance.mark(endLabel);
performance.measure(labelName, startLabel, endLabel);
performance.clearMarks(startLabel);
performance.clearMarks(endLabel);
/* tslint:enable:ban */
}
export function labels(label: string) {
const labelName = `${PERFORMANCE_MARK_PREFIX}:${label}`;
return {
labelName,
startLabel: `start:${labelName}`,
endLabel: `end:${labelName}`,
};
}
let warningLogged = false;
/**
* This enables an internal performance profiler
*
* It should not be imported in application code
*/
export function enableProfiling() {
if (
!warningLogged &&
(typeof performance === 'undefined' || !performance.mark || !performance.measure)
) {
warningLogged = true;
console.warn('Performance API is not supported on this platform');
return;
}
enablePerfLogging = true;
}
export function disableProfiling() {
enablePerfLogging = false;
}
| {
"end_byte": 1835,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/profiler.ts"
} |
angular/packages/core/src/event_emitter.ts_0_5923 | /**
* @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 {setActiveConsumer} from '@angular/core/primitives/signals';
import {PartialObserver, Subject, Subscription} from 'rxjs';
import {OutputRef} from './authoring/output/output_ref';
import {isInInjectionContext} from './di/contextual';
import {inject} from './di/injector_compatibility';
import {DestroyRef} from './linker/destroy_ref';
import {PendingTasksInternal} from './pending_tasks';
/**
* Use in components with the `@Output` directive to emit custom events
* synchronously or asynchronously, and register handlers for those events
* by subscribing to an instance.
*
* @usageNotes
*
* Extends
* [RxJS `Subject`](https://rxjs.dev/api/index/class/Subject)
* for Angular by adding the `emit()` method.
*
* In the following example, a component defines two output properties
* that create event emitters. When the title is clicked, the emitter
* emits an open or close event to toggle the current visibility state.
*
* ```html
* @Component({
* selector: 'zippy',
* template: `
* <div class="zippy">
* <div (click)="toggle()">Toggle</div>
* <div [hidden]="!visible">
* <ng-content></ng-content>
* </div>
* </div>`})
* export class Zippy {
* visible: boolean = true;
* @Output() open: EventEmitter<any> = new EventEmitter();
* @Output() close: EventEmitter<any> = new EventEmitter();
*
* toggle() {
* this.visible = !this.visible;
* if (this.visible) {
* this.open.emit(null);
* } else {
* this.close.emit(null);
* }
* }
* }
* ```
*
* Access the event object with the `$event` argument passed to the output event
* handler:
*
* ```html
* <zippy (open)="onOpen($event)" (close)="onClose($event)"></zippy>
* ```
*
* @publicApi
*/
export interface EventEmitter<T> extends Subject<T>, OutputRef<T> {
/**
* @internal
*/
__isAsync: boolean;
/**
* Creates an instance of this class that can
* deliver events synchronously or asynchronously.
*
* @param [isAsync=false] When true, deliver events asynchronously.
*
*/
new (isAsync?: boolean): EventEmitter<T>;
/**
* Emits an event containing a given value.
* @param value The value to emit.
*/
emit(value?: T): void;
/**
* Registers handlers for events emitted by this instance.
* @param next When supplied, a custom handler for emitted events.
* @param error When supplied, a custom handler for an error notification from this emitter.
* @param complete When supplied, a custom handler for a completion notification from this
* emitter.
*/
subscribe(
next?: (value: T) => void,
error?: (error: any) => void,
complete?: () => void,
): Subscription;
/**
* Registers handlers for events emitted by this instance.
* @param observerOrNext When supplied, a custom handler for emitted events, or an observer
* object.
* @param error When supplied, a custom handler for an error notification from this emitter.
* @param complete When supplied, a custom handler for a completion notification from this
* emitter.
*/
subscribe(observerOrNext?: any, error?: any, complete?: any): Subscription;
}
class EventEmitter_ extends Subject<any> implements OutputRef<any> {
__isAsync: boolean; // tslint:disable-line
destroyRef: DestroyRef | undefined = undefined;
private readonly pendingTasks: PendingTasksInternal | undefined = undefined;
constructor(isAsync: boolean = false) {
super();
this.__isAsync = isAsync;
// Attempt to retrieve a `DestroyRef` and `PendingTasks` optionally.
// For backwards compatibility reasons, this cannot be required.
if (isInInjectionContext()) {
// `DestroyRef` is optional because it is not available in all contexts.
// But it is useful to properly complete the `EventEmitter` if used with `outputToObservable`
// when the component/directive is destroyed. (See `outputToObservable` for more details.)
this.destroyRef = inject(DestroyRef, {optional: true}) ?? undefined;
this.pendingTasks = inject(PendingTasksInternal, {optional: true}) ?? undefined;
}
}
emit(value?: any) {
const prevConsumer = setActiveConsumer(null);
try {
super.next(value);
} finally {
setActiveConsumer(prevConsumer);
}
}
override subscribe(observerOrNext?: any, error?: any, complete?: any): Subscription {
let nextFn = observerOrNext;
let errorFn = error || (() => null);
let completeFn = complete;
if (observerOrNext && typeof observerOrNext === 'object') {
const observer = observerOrNext as PartialObserver<unknown>;
nextFn = observer.next?.bind(observer);
errorFn = observer.error?.bind(observer);
completeFn = observer.complete?.bind(observer);
}
if (this.__isAsync) {
errorFn = this.wrapInTimeout(errorFn);
if (nextFn) {
nextFn = this.wrapInTimeout(nextFn);
}
if (completeFn) {
completeFn = this.wrapInTimeout(completeFn);
}
}
const sink = super.subscribe({next: nextFn, error: errorFn, complete: completeFn});
if (observerOrNext instanceof Subscription) {
observerOrNext.add(sink);
}
return sink;
}
private wrapInTimeout(fn: (value: unknown) => any) {
return (value: unknown) => {
const taskId = this.pendingTasks?.add();
setTimeout(() => {
fn(value);
if (taskId !== undefined) {
this.pendingTasks?.remove(taskId);
}
});
};
}
}
/**
* @publicApi
*/
export const EventEmitter: {
new (isAsync?: boolean): EventEmitter<any>;
new <T>(isAsync?: boolean): EventEmitter<T>;
readonly prototype: EventEmitter<any>;
} = EventEmitter_ as any;
| {
"end_byte": 5923,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/event_emitter.ts"
} |
angular/packages/core/src/cached_injector_service.ts_0_1792 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ɵɵdefineInjectable as defineInjectable} from './di/interface/defs';
import {Provider} from './di/interface/provider';
import {EnvironmentInjector} from './di/r3_injector';
import {OnDestroy} from './interface/lifecycle_hooks';
import {createEnvironmentInjector} from './render3/ng_module_ref';
/**
* A service used by the framework to create and cache injector instances.
*
* This service is used to create a single injector instance for each defer
* block definition, to avoid creating an injector for each defer block instance
* of a certain type.
*/
export class CachedInjectorService implements OnDestroy {
private cachedInjectors = new Map<unknown, EnvironmentInjector | null>();
getOrCreateInjector(
key: unknown,
parentInjector: EnvironmentInjector,
providers: Provider[],
debugName?: string,
) {
if (!this.cachedInjectors.has(key)) {
const injector =
providers.length > 0
? createEnvironmentInjector(providers, parentInjector, debugName)
: null;
this.cachedInjectors.set(key, injector);
}
return this.cachedInjectors.get(key)!;
}
ngOnDestroy() {
try {
for (const injector of this.cachedInjectors.values()) {
if (injector !== null) {
injector.destroy();
}
}
} finally {
this.cachedInjectors.clear();
}
}
/** @nocollapse */
static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ defineInjectable({
token: CachedInjectorService,
providedIn: 'environment',
factory: () => new CachedInjectorService(),
});
}
| {
"end_byte": 1792,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/cached_injector_service.ts"
} |
angular/packages/core/src/error_handler.ts_0_1693 | /**
* @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 {inject, InjectionToken} from './di';
import {NgZone} from './zone';
/**
* Provides a hook for centralized exception handling.
*
* The default implementation of `ErrorHandler` prints error messages to the `console`. To
* intercept error handling, write a custom exception handler that replaces this default as
* appropriate for your app.
*
* @usageNotes
* ### Example
*
* ```
* class MyErrorHandler implements ErrorHandler {
* handleError(error) {
* // do something with the exception
* }
* }
*
* @NgModule({
* providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
* })
* class MyModule {}
* ```
*
* @publicApi
*/
export class ErrorHandler {
/**
* @internal
*/
_console: Console = console;
handleError(error: any): void {
this._console.error('ERROR', error);
}
}
/**
* `InjectionToken` used to configure how to call the `ErrorHandler`.
*
* `NgZone` is provided by default today so the default (and only) implementation for this
* is calling `ErrorHandler.handleError` outside of the Angular zone.
*/
export const INTERNAL_APPLICATION_ERROR_HANDLER = new InjectionToken<(e: any) => void>(
typeof ngDevMode === 'undefined' || ngDevMode ? 'internal error handler' : '',
{
providedIn: 'root',
factory: () => {
const zone = inject(NgZone);
const userErrorHandler = inject(ErrorHandler);
return (e: unknown) => zone.runOutsideAngular(() => userErrorHandler.handleError(e));
},
},
);
| {
"end_byte": 1693,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/error_handler.ts"
} |
angular/packages/core/src/errors.ts_0_5746 | /**
* @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 {ERROR_DETAILS_PAGE_BASE_URL} from './error_details_base_url';
/**
* The list of error codes used in runtime code of the `core` package.
* Reserved error code range: 100-999.
*
* Note: the minus sign denotes the fact that a particular code has a detailed guide on
* angular.io. This extra annotation is needed to avoid introducing a separate set to store
* error codes which have guides, which might leak into runtime code.
*
* Full list of available error guides can be found at https://angular.dev/errors.
*
* Error code ranges per package:
* - core (this package): 100-999
* - forms: 1000-1999
* - common: 2000-2999
* - animations: 3000-3999
* - router: 4000-4999
* - platform-browser: 5000-5500
*/
export const enum RuntimeErrorCode {
// Change Detection Errors
EXPRESSION_CHANGED_AFTER_CHECKED = -100,
RECURSIVE_APPLICATION_REF_TICK = 101,
INFINITE_CHANGE_DETECTION = 103,
// Dependency Injection Errors
CYCLIC_DI_DEPENDENCY = -200,
PROVIDER_NOT_FOUND = -201,
INVALID_FACTORY_DEPENDENCY = 202,
MISSING_INJECTION_CONTEXT = -203,
INVALID_INJECTION_TOKEN = 204,
INJECTOR_ALREADY_DESTROYED = 205,
PROVIDER_IN_WRONG_CONTEXT = 207,
MISSING_INJECTION_TOKEN = 208,
INVALID_MULTI_PROVIDER = -209,
MISSING_DOCUMENT = 210,
// Template Errors
MULTIPLE_COMPONENTS_MATCH = -300,
EXPORT_NOT_FOUND = -301,
PIPE_NOT_FOUND = -302,
UNKNOWN_BINDING = 303,
UNKNOWN_ELEMENT = 304,
TEMPLATE_STRUCTURE_ERROR = 305,
INVALID_EVENT_BINDING = 306,
HOST_DIRECTIVE_UNRESOLVABLE = 307,
HOST_DIRECTIVE_NOT_STANDALONE = 308,
DUPLICATE_DIRECTIVE = 309,
HOST_DIRECTIVE_COMPONENT = 310,
HOST_DIRECTIVE_UNDEFINED_BINDING = 311,
HOST_DIRECTIVE_CONFLICTING_ALIAS = 312,
MULTIPLE_MATCHING_PIPES = 313,
UNINITIALIZED_LET_ACCESS = 314,
// Bootstrap Errors
MULTIPLE_PLATFORMS = 400,
PLATFORM_NOT_FOUND = 401,
MISSING_REQUIRED_INJECTABLE_IN_BOOTSTRAP = 402,
BOOTSTRAP_COMPONENTS_NOT_FOUND = -403,
PLATFORM_ALREADY_DESTROYED = 404,
ASYNC_INITIALIZERS_STILL_RUNNING = 405,
APPLICATION_REF_ALREADY_DESTROYED = 406,
RENDERER_NOT_FOUND = 407,
PROVIDED_BOTH_ZONE_AND_ZONELESS = 408,
// Hydration Errors
HYDRATION_NODE_MISMATCH = -500,
HYDRATION_MISSING_SIBLINGS = -501,
HYDRATION_MISSING_NODE = -502,
UNSUPPORTED_PROJECTION_DOM_NODES = -503,
INVALID_SKIP_HYDRATION_HOST = -504,
MISSING_HYDRATION_ANNOTATIONS = -505,
HYDRATION_STABLE_TIMEDOUT = -506,
MISSING_SSR_CONTENT_INTEGRITY_MARKER = -507,
// Signal Errors
SIGNAL_WRITE_FROM_ILLEGAL_CONTEXT = 600,
REQUIRE_SYNC_WITHOUT_SYNC_EMIT = 601,
ASSERTION_NOT_INSIDE_REACTIVE_CONTEXT = -602,
// Styling Errors
// Declarations Errors
// i18n Errors
INVALID_I18N_STRUCTURE = 700,
MISSING_LOCALE_DATA = 701,
// Defer errors (750-799 range)
DEFER_LOADING_FAILED = 750,
// standalone errors
IMPORT_PROVIDERS_FROM_STANDALONE = 800,
// JIT Compilation Errors
// Other
INVALID_DIFFER_INPUT = 900,
NO_SUPPORTING_DIFFER_FACTORY = 901,
VIEW_ALREADY_ATTACHED = 902,
INVALID_INHERITANCE = 903,
UNSAFE_VALUE_IN_RESOURCE_URL = 904,
UNSAFE_VALUE_IN_SCRIPT = 905,
MISSING_GENERATED_DEF = 906,
TYPE_IS_NOT_STANDALONE = 907,
MISSING_ZONEJS = 908,
UNEXPECTED_ZONE_STATE = 909,
UNSAFE_IFRAME_ATTRS = -910,
VIEW_ALREADY_DESTROYED = 911,
COMPONENT_ID_COLLISION = -912,
IMAGE_PERFORMANCE_WARNING = -913,
UNEXPECTED_ZONEJS_PRESENT_IN_ZONELESS_MODE = 914,
// Signal integration errors
REQUIRED_INPUT_NO_VALUE = -950,
REQUIRED_QUERY_NO_VALUE = -951,
REQUIRED_MODEL_NO_VALUE = 952,
// Output()
OUTPUT_REF_DESTROYED = 953,
// Repeater errors
LOOP_TRACK_DUPLICATE_KEYS = -955,
LOOP_TRACK_RECREATE = -956,
// Runtime dependency tracker errors
RUNTIME_DEPS_INVALID_IMPORTED_TYPE = 980,
RUNTIME_DEPS_ORPHAN_COMPONENT = 981,
// Upper bounds for core runtime errors is 999
}
/**
* Class that represents a runtime error.
* Formats and outputs the error message in a consistent way.
*
* Example:
* ```
* throw new RuntimeError(
* RuntimeErrorCode.INJECTOR_ALREADY_DESTROYED,
* ngDevMode && 'Injector has already been destroyed.');
* ```
*
* Note: the `message` argument contains a descriptive error message as a string in development
* mode (when the `ngDevMode` is defined). In production mode (after tree-shaking pass), the
* `message` argument becomes `false`, thus we account for it in the typings and the runtime
* logic.
*/
export class RuntimeError<T extends number = RuntimeErrorCode> extends Error {
constructor(
public code: T,
message: null | false | string,
) {
super(formatRuntimeError<T>(code, message));
}
}
/**
* Called to format a runtime error.
* See additional info on the `message` argument type in the `RuntimeError` class description.
*/
export function formatRuntimeError<T extends number = RuntimeErrorCode>(
code: T,
message: null | false | string,
): string {
// Error code might be a negative number, which is a special marker that instructs the logic to
// generate a link to the error details page on angular.io.
// We also prepend `0` to non-compile-time errors.
const fullCode = `NG0${Math.abs(code)}`;
let errorMessage = `${fullCode}${message ? ': ' + message : ''}`;
if (ngDevMode && code < 0) {
const addPeriodSeparator = !errorMessage.match(/[.,;!?\n]$/);
const separator = addPeriodSeparator ? '.' : '';
errorMessage = `${errorMessage}${separator} Find more at ${ERROR_DETAILS_PAGE_BASE_URL}/${fullCode}`;
}
return errorMessage;
}
| {
"end_byte": 5746,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/errors.ts"
} |
angular/packages/core/src/core_private_export.ts_0_6959 | /**
* @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 {setAlternateWeakRefImpl as ɵsetAlternateWeakRefImpl} from '../primitives/signals';
export {
detectChangesInViewIfRequired as ɵdetectChangesInViewIfRequired,
whenStable as ɵwhenStable,
} from './application/application_ref';
export {INTERNAL_APPLICATION_ERROR_HANDLER as ɵINTERNAL_APPLICATION_ERROR_HANDLER} from './error_handler';
export {
IMAGE_CONFIG as ɵIMAGE_CONFIG,
IMAGE_CONFIG_DEFAULTS as ɵIMAGE_CONFIG_DEFAULTS,
ImageConfig as ɵImageConfig,
} from './application/application_tokens';
export {internalCreateApplication as ɵinternalCreateApplication} from './application/create_application';
export {
defaultIterableDiffers as ɵdefaultIterableDiffers,
defaultKeyValueDiffers as ɵdefaultKeyValueDiffers,
} from './change_detection/change_detection';
export {
internalProvideZoneChangeDetection as ɵinternalProvideZoneChangeDetection,
PROVIDED_NG_ZONE as ɵPROVIDED_NG_ZONE,
} from './change_detection/scheduling/ng_zone_scheduling';
export {ChangeDetectionSchedulerImpl as ɵChangeDetectionSchedulerImpl} from './change_detection/scheduling/zoneless_scheduling_impl';
export {
ChangeDetectionScheduler as ɵChangeDetectionScheduler,
NotificationSource as ɵNotificationSource,
ZONELESS_ENABLED as ɵZONELESS_ENABLED,
} from './change_detection/scheduling/zoneless_scheduling';
export {Console as ɵConsole} from './console';
export {
DeferBlockDetails as ɵDeferBlockDetails,
getDeferBlocks as ɵgetDeferBlocks,
} from './defer/discovery';
export {
renderDeferBlockState as ɵrenderDeferBlockState,
triggerResourceLoading as ɵtriggerResourceLoading,
} from './defer/instructions';
export {
DeferBlockBehavior as ɵDeferBlockBehavior,
DeferBlockConfig as ɵDeferBlockConfig,
DeferBlockState as ɵDeferBlockState,
} from './defer/interfaces';
export {
convertToBitFlags as ɵconvertToBitFlags,
setCurrentInjector as ɵsetCurrentInjector,
} from './di/injector_compatibility';
export {
getInjectableDef as ɵgetInjectableDef,
ɵɵInjectableDeclaration,
ɵɵInjectorDef,
} from './di/interface/defs';
export {
InternalEnvironmentProviders as ɵInternalEnvironmentProviders,
isEnvironmentProviders as ɵisEnvironmentProviders,
} from './di/interface/provider';
export {INJECTOR_SCOPE as ɵINJECTOR_SCOPE} from './di/scope';
export {XSS_SECURITY_URL as ɵXSS_SECURITY_URL} from './error_details_base_url';
export {
formatRuntimeError as ɵformatRuntimeError,
RuntimeError as ɵRuntimeError,
RuntimeErrorCode as ɵRuntimeErrorCode,
} from './errors';
export {annotateForHydration as ɵannotateForHydration} from './hydration/annotate';
export {
withDomHydration as ɵwithDomHydration,
withI18nSupport as ɵwithI18nSupport,
withIncrementalHydration as ɵwithIncrementalHydration,
} from './hydration/api';
export {withEventReplay as ɵwithEventReplay} from './hydration/event_replay';
export {JSACTION_EVENT_CONTRACT as ɵJSACTION_EVENT_CONTRACT} from './event_delegation_utils';
export {
IS_HYDRATION_DOM_REUSE_ENABLED as ɵIS_HYDRATION_DOM_REUSE_ENABLED,
IS_INCREMENTAL_HYDRATION_ENABLED as ɵIS_INCREMENTAL_HYDRATION_ENABLED,
} from './hydration/tokens';
export {
HydratedNode as ɵHydratedNode,
HydrationInfo as ɵHydrationInfo,
readHydrationInfo as ɵreadHydrationInfo,
SSR_CONTENT_INTEGRITY_MARKER as ɵSSR_CONTENT_INTEGRITY_MARKER,
} from './hydration/utils';
export {
CurrencyIndex as ɵCurrencyIndex,
ExtraLocaleDataIndex as ɵExtraLocaleDataIndex,
findLocaleData as ɵfindLocaleData,
getLocaleCurrencyCode as ɵgetLocaleCurrencyCode,
getLocalePluralCase as ɵgetLocalePluralCase,
LocaleDataIndex as ɵLocaleDataIndex,
registerLocaleData as ɵregisterLocaleData,
unregisterAllLocaleData as ɵunregisterLocaleData,
} from './i18n/locale_data_api';
export {DEFAULT_LOCALE_ID as ɵDEFAULT_LOCALE_ID} from './i18n/localization';
export {Writable as ɵWritable} from './interface/type';
export {ComponentFactory as ɵComponentFactory} from './linker/component_factory';
export {
clearResolutionOfComponentResourcesQueue as ɵclearResolutionOfComponentResourcesQueue,
isComponentDefPendingResolution as ɵisComponentDefPendingResolution,
resolveComponentResources as ɵresolveComponentResources,
restoreComponentResolutionQueue as ɵrestoreComponentResolutionQueue,
} from './metadata/resource_loading';
export {
PendingTasksInternal as ɵPendingTasks, // TODO(atscott): remove once there is a release with PendingTasksInternal so adev can be updated
PendingTasksInternal as ɵPendingTasksInternal,
} from './pending_tasks';
export {ALLOW_MULTIPLE_PLATFORMS as ɵALLOW_MULTIPLE_PLATFORMS} from './platform/platform';
export {ReflectionCapabilities as ɵReflectionCapabilities} from './reflection/reflection_capabilities';
export {AnimationRendererType as ɵAnimationRendererType} from './render/api';
export {
InjectorProfilerContext as ɵInjectorProfilerContext,
ProviderRecord as ɵProviderRecord,
setInjectorProfilerContext as ɵsetInjectorProfilerContext,
} from './render3/debug/injector_profiler';
export {
allowSanitizationBypassAndThrow as ɵallowSanitizationBypassAndThrow,
BypassType as ɵBypassType,
getSanitizationBypassType as ɵgetSanitizationBypassType,
SafeHtml as ɵSafeHtml,
SafeResourceUrl as ɵSafeResourceUrl,
SafeScript as ɵSafeScript,
SafeStyle as ɵSafeStyle,
SafeUrl as ɵSafeUrl,
SafeValue as ɵSafeValue,
unwrapSafeValue as ɵunwrapSafeValue,
} from './sanitization/bypass';
export {_sanitizeHtml as ɵ_sanitizeHtml} from './sanitization/html_sanitizer';
export {_sanitizeUrl as ɵ_sanitizeUrl} from './sanitization/url_sanitizer';
export {
TESTABILITY as ɵTESTABILITY,
TESTABILITY_GETTER as ɵTESTABILITY_GETTER,
} from './testability/testability';
export {booleanAttribute, numberAttribute} from './util/coercion';
export {devModeEqual as ɵdevModeEqual} from './util/comparison';
export {global as ɵglobal} from './util/global';
export {isPromise as ɵisPromise, isSubscribable as ɵisSubscribable} from './util/lang';
export {performanceMarkFeature as ɵperformanceMarkFeature} from './util/performance';
export {stringify as ɵstringify, truncateMiddle as ɵtruncateMiddle} from './util/stringify';
export {NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR as ɵNOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR} from './view/provider_flags';
export {type InputSignalNode as ɵInputSignalNode} from './authoring/input/input_signal_node';
export {
startMeasuring as ɵstartMeasuring,
stopMeasuring as ɵstopMeasuring,
PERFORMANCE_MARK_PREFIX as ɵPERFORMANCE_MARK_PREFIX,
enableProfiling as ɵenableProfiling,
disableProfiling as ɵdisableProfiling,
} from './profiler';
export {getClosestComponentName as ɵgetClosestComponentName} from './internal/get_closest_component_name';
| {
"end_byte": 6959,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/core_private_export.ts"
} |
angular/packages/core/src/error_details_base_url.ts_0_612 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* Base URL for the error details page.
*
* Keep this constant in sync across:
* - packages/compiler-cli/src/ngtsc/diagnostics/src/error_details_base_url.ts
* - packages/core/src/error_details_base_url.ts
*/
export const ERROR_DETAILS_PAGE_BASE_URL = 'https://angular.dev/errors';
/**
* URL for the XSS security documentation.
*/
export const XSS_SECURITY_URL = 'https://g.co/ng/security#xss';
| {
"end_byte": 612,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/error_details_base_url.ts"
} |
angular/packages/core/src/zone.ts_0_294 | /**
* @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
*/
// Public API for Zone
export {NgZone, NoopNgZone as ɵNoopNgZone} from './zone/ng_zone';
| {
"end_byte": 294,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/zone.ts"
} |
angular/packages/core/src/linker.ts_0_999 | /**
* @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
*/
// Public API for compiler
export {
Compiler,
COMPILER_OPTIONS,
CompilerFactory,
CompilerOptions,
ModuleWithComponentFactories,
} from './linker/compiler';
export {ComponentFactory, ComponentRef} from './linker/component_factory';
export {ComponentFactoryResolver} from './linker/component_factory_resolver';
export {DestroyRef} from './linker/destroy_ref';
export {ElementRef} from './linker/element_ref';
export {NgModuleFactory, NgModuleRef} from './linker/ng_module_factory';
export {getModuleFactory, getNgModuleById} from './linker/ng_module_factory_loader';
export {QueryList} from './linker/query_list';
export {TemplateRef} from './linker/template_ref';
export {ViewContainerRef} from './linker/view_container_ref';
export {EmbeddedViewRef, ViewRef} from './linker/view_ref';
| {
"end_byte": 999,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/linker.ts"
} |
angular/packages/core/src/core_reactivity_export_internal.ts_0_1240 | /**
* @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 {SIGNAL as ɵSIGNAL} from '@angular/core/primitives/signals';
export {isSignal, Signal, ValueEqualityFn} from './render3/reactivity/api';
export {computed, CreateComputedOptions} from './render3/reactivity/computed';
export {
CreateSignalOptions,
signal,
WritableSignal,
ɵunwrapWritableSignal,
} from './render3/reactivity/signal';
export {linkedSignal} from './render3/reactivity/linked_signal';
export {untracked} from './render3/reactivity/untracked';
export {
CreateEffectOptions,
effect,
EffectRef,
EffectCleanupFn,
EffectCleanupRegisterFn,
} from './render3/reactivity/effect';
export {
MicrotaskEffectScheduler as ɵMicrotaskEffectScheduler,
microtaskEffect as ɵmicrotaskEffect,
} from './render3/reactivity/microtask_effect';
export {EffectScheduler as ɵEffectScheduler} from './render3/reactivity/root_effect_scheduler';
export {afterRenderEffect, ɵFirstAvailableSignal} from './render3/reactivity/after_render_effect';
export {assertNotInReactiveContext} from './render3/reactivity/asserts';
| {
"end_byte": 1240,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/core_reactivity_export_internal.ts"
} |
angular/packages/core/src/authoring.ts_0_1186 | /**
* @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
*/
// Note: `input` and `model` are exported in `core.ts` due to:
// https://docs.google.com/document/d/1RXb1wYwsbJotO1KBgSDsAtKpduGmIHod9ADxuXcAvV4/edit?tab=t.0.
export {InputFunction} from './authoring/input/input';
export {
InputOptions,
InputOptionsWithoutTransform,
InputOptionsWithTransform,
InputSignal,
InputSignalWithTransform,
ɵINPUT_SIGNAL_BRAND_WRITE_TYPE,
} from './authoring/input/input_signal';
export {ɵUnwrapDirectiveSignalInputs} from './authoring/input/input_type_checking';
export {ModelFunction} from './authoring/model/model';
export {ModelOptions, ModelSignal} from './authoring/model/model_signal';
export {output, OutputOptions} from './authoring/output/output';
export {
getOutputDestroyRef as ɵgetOutputDestroyRef,
OutputEmitterRef,
} from './authoring/output/output_emitter_ref';
export {OutputRef, OutputRefSubscription} from './authoring/output/output_ref';
export {ContentChildFunction, ViewChildFunction} from './authoring/queries';
| {
"end_byte": 1186,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/authoring.ts"
} |
angular/packages/core/src/core_reactivity_export.ts_0_390 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// This file exists to allow the set of reactivity exports to be modified in g3, as these APIs are
// only "beta" for the time being.
export * from './core_reactivity_export_internal';
| {
"end_byte": 390,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/core_reactivity_export.ts"
} |
angular/packages/core/src/image_performance_warning.ts_0_8907 | /**
* @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 {IMAGE_CONFIG, ImageConfig, PLATFORM_ID} from './application/application_tokens';
import {Injectable} from './di';
import {inject} from './di/injector_compatibility';
import {formatRuntimeError, RuntimeErrorCode} from './errors';
import {OnDestroy} from './interface/lifecycle_hooks';
import {getDocument} from './render3/interfaces/document';
// A delay in milliseconds before the scan is run after onLoad, to avoid any
// potential race conditions with other LCP-related functions. This delay
// happens outside of the main JavaScript execution and will only effect the timing
// on when the warning becomes visible in the console.
const SCAN_DELAY = 200;
const OVERSIZED_IMAGE_TOLERANCE = 1200;
@Injectable({providedIn: 'root'})
export class ImagePerformanceWarning implements OnDestroy {
// Map of full image URLs -> original `ngSrc` values.
private window: Window | null = null;
private observer: PerformanceObserver | null = null;
private options: ImageConfig = inject(IMAGE_CONFIG);
private readonly isBrowser = inject(PLATFORM_ID) === 'browser';
private lcpImageUrl?: string;
public start() {
if (
!this.isBrowser ||
typeof PerformanceObserver === 'undefined' ||
(this.options?.disableImageSizeWarning && this.options?.disableImageLazyLoadWarning)
) {
return;
}
this.observer = this.initPerformanceObserver();
const doc = getDocument();
const win = doc.defaultView;
if (typeof win !== 'undefined') {
this.window = win;
// Wait to avoid race conditions where LCP image triggers
// load event before it's recorded by the performance observer
const waitToScan = () => {
setTimeout(this.scanImages.bind(this), SCAN_DELAY);
};
const setup = () => {
// Consider the case when the application is created and destroyed multiple times.
// Typically, applications are created instantly once the page is loaded, and the
// `window.load` listener is always triggered. However, the `window.load` event will never
// be fired if the page is loaded, and the application is created later. Checking for
// `readyState` is the easiest way to determine whether the page has been loaded or not.
if (doc.readyState === 'complete') {
waitToScan();
} else {
this.window?.addEventListener('load', waitToScan, {once: true});
}
};
// Angular doesn't have to run change detection whenever any asynchronous tasks are invoked in
// the scope of this functionality.
if (typeof Zone !== 'undefined') {
Zone.root.run(() => setup());
} else {
setup();
}
}
}
ngOnDestroy() {
this.observer?.disconnect();
}
private initPerformanceObserver(): PerformanceObserver | null {
if (typeof PerformanceObserver === 'undefined') {
return null;
}
const observer = new PerformanceObserver((entryList) => {
const entries = entryList.getEntries();
if (entries.length === 0) return;
// We use the latest entry produced by the `PerformanceObserver` as the best
// signal on which element is actually an LCP one. As an example, the first image to load on
// a page, by virtue of being the only thing on the page so far, is often a LCP candidate
// and gets reported by PerformanceObserver, but isn't necessarily the LCP element.
const lcpElement = entries[entries.length - 1];
// Cast to `any` due to missing `element` on the `LargestContentfulPaint` type of entry.
// See https://developer.mozilla.org/en-US/docs/Web/API/LargestContentfulPaint
const imgSrc = (lcpElement as any).element?.src ?? '';
// Exclude `data:` and `blob:` URLs, since they are fetched resources.
if (imgSrc.startsWith('data:') || imgSrc.startsWith('blob:')) return;
this.lcpImageUrl = imgSrc;
});
observer.observe({type: 'largest-contentful-paint', buffered: true});
return observer;
}
private scanImages(): void {
const images = getDocument().querySelectorAll('img');
let lcpElementFound,
lcpElementLoadedCorrectly = false;
images.forEach((image) => {
if (!this.options?.disableImageSizeWarning) {
// Image elements using the NgOptimizedImage directive are excluded,
// as that directive has its own version of this check.
if (!image.getAttribute('ng-img') && this.isOversized(image)) {
logOversizedImageWarning(image.src);
}
}
if (!this.options?.disableImageLazyLoadWarning && this.lcpImageUrl) {
if (image.src === this.lcpImageUrl) {
lcpElementFound = true;
if (image.loading !== 'lazy' || image.getAttribute('ng-img')) {
// This variable is set to true and never goes back to false to account
// for the case where multiple images have the same src url, and some
// have lazy loading while others don't.
// Also ignore NgOptimizedImage because there's a different warning for that.
lcpElementLoadedCorrectly = true;
}
}
}
});
if (
lcpElementFound &&
!lcpElementLoadedCorrectly &&
this.lcpImageUrl &&
!this.options?.disableImageLazyLoadWarning
) {
logLazyLCPWarning(this.lcpImageUrl);
}
}
private isOversized(image: HTMLImageElement): boolean {
if (!this.window) {
return false;
}
// The `isOversized` check may not be applicable or may require adjustments
// for several types of image formats or scenarios. Currently, we specify only
// `svg`, but this may also include `gif` since their quality isn’t tied to
// dimensions in the same way as raster images.
const nonOversizedImageExtentions = [
// SVG images are vector-based, which means they can scale
// to any size without losing quality.
'.svg',
];
// Convert it to lowercase because this may have uppercase
// extensions, such as `IMAGE.SVG`.
// We fallback to an empty string because `src` may be `undefined`
// if it is explicitly set to `null` by some third-party code
// (e.g., `image.src = null`).
const imageSource = (image.src || '').toLowerCase();
if (nonOversizedImageExtentions.some((extension) => imageSource.endsWith(extension))) {
return false;
}
const computedStyle = this.window.getComputedStyle(image);
let renderedWidth = parseFloat(computedStyle.getPropertyValue('width'));
let renderedHeight = parseFloat(computedStyle.getPropertyValue('height'));
const boxSizing = computedStyle.getPropertyValue('box-sizing');
const objectFit = computedStyle.getPropertyValue('object-fit');
if (objectFit === `cover`) {
// Object fit cover may indicate a use case such as a sprite sheet where
// this warning does not apply.
return false;
}
if (boxSizing === 'border-box') {
// If the image `box-sizing` is set to `border-box`, we adjust the rendered
// dimensions by subtracting padding values.
const paddingTop = computedStyle.getPropertyValue('padding-top');
const paddingRight = computedStyle.getPropertyValue('padding-right');
const paddingBottom = computedStyle.getPropertyValue('padding-bottom');
const paddingLeft = computedStyle.getPropertyValue('padding-left');
renderedWidth -= parseFloat(paddingRight) + parseFloat(paddingLeft);
renderedHeight -= parseFloat(paddingTop) + parseFloat(paddingBottom);
}
const intrinsicWidth = image.naturalWidth;
const intrinsicHeight = image.naturalHeight;
const recommendedWidth = this.window.devicePixelRatio * renderedWidth;
const recommendedHeight = this.window.devicePixelRatio * renderedHeight;
const oversizedWidth = intrinsicWidth - recommendedWidth >= OVERSIZED_IMAGE_TOLERANCE;
const oversizedHeight = intrinsicHeight - recommendedHeight >= OVERSIZED_IMAGE_TOLERANCE;
return oversizedWidth || oversizedHeight;
}
}
function logLazyLCPWarning(src: string) {
console.warn(
formatRuntimeError(
RuntimeErrorCode.IMAGE_PERFORMANCE_WARNING,
`An image with src ${src} is the Largest Contentful Paint (LCP) element ` +
`but was given a "loading" value of "lazy", which can negatively impact ` +
`application loading performance. This warning can be addressed by ` +
`changing the loading value of the LCP image to "eager", or by using the ` +
`NgOptimizedImage directive's prioritization utilities. For more ` +
`information about addressing or disabling this warning, see ` +
`https://angular.dev/errors/NG0913`,
),
);
}
| {
"end_byte": 8907,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/image_performance_warning.ts"
} |
angular/packages/core/src/image_performance_warning.ts_8909_9363 | nction logOversizedImageWarning(src: string) {
console.warn(
formatRuntimeError(
RuntimeErrorCode.IMAGE_PERFORMANCE_WARNING,
`An image with src ${src} has intrinsic file dimensions much larger than its ` +
`rendered size. This can negatively impact application loading performance. ` +
`For more information about addressing or disabling this warning, see ` +
`https://angular.dev/errors/NG0913`,
),
);
}
| {
"end_byte": 9363,
"start_byte": 8909,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/image_performance_warning.ts"
} |
angular/packages/core/src/core.ts_0_4687 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @module
* @description
* Entry point from which you should import all public core APIs.
*/
export * from './authoring';
// Authoring functions are exported separately as this file is exempted from
// JSCompiler's conformance requirement for inferred const exports. See:
// https://docs.google.com/document/d/1RXb1wYwsbJotO1KBgSDsAtKpduGmIHod9ADxuXcAvV4/edit?tab=t.0
export {input} from './authoring/input/input';
export {contentChild, contentChildren, viewChild, viewChildren} from './authoring/queries';
export {model} from './authoring/model/model';
export * from './metadata';
export * from './version';
export {TypeDecorator} from './util/decorators';
export * from './di';
export {
BootstrapOptions,
ApplicationRef,
NgProbeToken,
APP_BOOTSTRAP_LISTENER,
} from './application/application_ref';
export {PlatformRef} from './platform/platform_ref';
export {
createPlatform,
createPlatformFactory,
assertPlatform,
destroyPlatform,
getPlatform,
providePlatformInitializer,
} from './platform/platform';
export {
provideZoneChangeDetection,
NgZoneOptions,
} from './change_detection/scheduling/ng_zone_scheduling';
export {provideExperimentalZonelessChangeDetection} from './change_detection/scheduling/zoneless_scheduling_impl';
export {PendingTasks} from './pending_tasks';
export {provideExperimentalCheckNoChangesForDebug} from './change_detection/scheduling/exhaustive_check_no_changes';
export {enableProdMode, isDevMode} from './util/is_dev_mode';
export {
APP_ID,
PACKAGE_ROOT_URL,
PLATFORM_INITIALIZER,
PLATFORM_ID,
ANIMATION_MODULE_TYPE,
CSP_NONCE,
} from './application/application_tokens';
export {
APP_INITIALIZER,
ApplicationInitStatus,
provideAppInitializer,
} from './application/application_init';
export * from './zone';
export * from './render';
export * from './linker';
export * from './linker/ng_module_factory_loader_impl';
export {
DebugElement,
DebugEventListener,
DebugNode,
asNativeElements,
getDebugNode,
Predicate,
} from './debug/debug_node';
export {
GetTestability,
Testability,
TestabilityRegistry,
setTestabilityGetter,
} from './testability/testability';
export * from './change_detection';
export * from './platform/platform_core_providers';
export {
TRANSLATIONS,
TRANSLATIONS_FORMAT,
LOCALE_ID,
DEFAULT_CURRENCY_CODE,
MissingTranslationStrategy,
} from './i18n/tokens';
export {ApplicationModule} from './application/application_module';
export {AbstractType, Type} from './interface/type';
export {EventEmitter} from './event_emitter';
export {ErrorHandler} from './error_handler';
export * from './core_private_export';
export * from './core_render3_private_export';
export * from './core_reactivity_export';
export * from './resource';
export {SecurityContext} from './sanitization/security';
export {Sanitizer} from './sanitization/sanitizer';
export {
createNgModule,
createNgModuleRef,
createEnvironmentInjector,
} from './render3/ng_module_ref';
export {createComponent, reflectComponentType, ComponentMirror} from './render3/component';
export {isStandalone} from './render3/def_getters';
export {AfterRenderPhase, AfterRenderRef} from './render3/after_render/api';
export {publishExternalGlobalUtil as ɵpublishExternalGlobalUtil} from './render3/util/global_utils';
export {
AfterRenderOptions,
afterRender,
afterNextRender,
ɵFirstAvailable,
} from './render3/after_render/hooks';
export {ApplicationConfig, mergeApplicationConfig} from './application/application_config';
export {makeStateKey, StateKey, TransferState} from './transfer_state';
export {booleanAttribute, numberAttribute} from './util/coercion';
import {global} from './util/global';
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
// This helper is to give a reasonable error message to people upgrading to v9 that have not yet
// installed `@angular/localize` in their app.
// tslint:disable-next-line: no-toplevel-property-access
global.$localize ??= function () {
throw new Error(
'It looks like your application or one of its dependencies is using i18n.\n' +
'Angular 9 introduced a global `$localize()` function that needs to be loaded.\n' +
'Please run `ng add @angular/localize` from the Angular CLI.\n' +
"(For non-CLI projects, add `import '@angular/localize/init';` to your `polyfills.ts` file.\n" +
'For server-side rendering applications add the import to your `main.server.ts` file.)',
);
};
}
| {
"end_byte": 4687,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/core.ts"
} |
angular/packages/core/src/di.ts_0_912 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* This file should not be necessary because node resolution should just default to `./di/index`!
*
* However it does not seem to work and it breaks:
* - //packages/animations/browser/test:test_web_chromium-local
* - //packages/compiler-cli/test:extract_i18n
* - //packages/compiler-cli/test:ngc
* - //packages/compiler-cli/test:perform_watch
* - //packages/compiler-cli/test/diagnostics:check_types
* - //packages/compiler-cli/test/transformers:test
* - //packages/compiler/test:test
* - //tools/public_api_guard:core_api
*
* Remove this file once the above is solved or wait until `ngc` is deleted and then it should be
* safe to delete this file.
*/
export * from './di/index';
| {
"end_byte": 912,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/di.ts"
} |
angular/packages/core/src/core.externs.js_0_349 | /**
* @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
*
* @externs
*/
/**
* This is needed to declare global `$localize` to let closure compiler know
* about the global variable.
*/
var $localize;
| {
"end_byte": 349,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/core.externs.js"
} |
angular/packages/core/src/core_render3_private_export.ts_0_1606 | /**
* @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
*/
// we reexport these symbols just so that they are retained during the dead code elimination
// performed by rollup while it's creating fesm files.
//
// no code actually imports these symbols from the @angular/core entry point
export {isBoundToModule as ɵisBoundToModule} from './application/application_ref';
export {compileNgModuleFactory as ɵcompileNgModuleFactory} from './application/application_ngmodule_factory_compiler';
export {injectChangeDetectorRef as ɵinjectChangeDetectorRef} from './change_detection/change_detector_ref';
export {getDebugNode as ɵgetDebugNode} from './debug/debug_node';
export {
NG_INJ_DEF as ɵNG_INJ_DEF,
NG_PROV_DEF as ɵNG_PROV_DEF,
isInjectable as ɵisInjectable,
} from './di/interface/defs';
export {createInjector as ɵcreateInjector} from './di/create_injector';
export {
registerNgModuleType as ɵɵregisterNgModuleType,
setAllowDuplicateNgModuleIdsForTest as ɵsetAllowDuplicateNgModuleIdsForTest,
} from './linker/ng_module_registration';
export {
NgModuleDef as ɵNgModuleDef,
NgModuleTransitiveScopes as ɵNgModuleTransitiveScopes,
} from './metadata/ng_module_def';
export {getLContext as ɵgetLContext} from './render3/context_discovery';
export {
NG_COMP_DEF as ɵNG_COMP_DEF,
NG_DIR_DEF as ɵNG_DIR_DEF,
NG_ELEMENT_ID as ɵNG_ELEMENT_ID,
NG_MOD_DEF as ɵNG_MOD_DEF,
NG_PIPE_DEF as ɵNG_PIPE_DEF,
} from './render3/fields';
export {
Attribu | {
"end_byte": 1606,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/core_render3_private_export.ts"
} |
angular/packages/core/src/core_render3_private_export.ts_1607_7250 | eMarker as ɵAttributeMarker,
ComponentDef as ɵComponentDef,
ComponentDebugMetadata as ɵComponentDebugMetadata,
ComponentFactory as ɵRender3ComponentFactory,
ComponentRef as ɵRender3ComponentRef,
ComponentType as ɵComponentType,
CssSelectorList as ɵCssSelectorList,
DirectiveDef as ɵDirectiveDef,
DirectiveType as ɵDirectiveType,
getDirectives as ɵgetDirectives,
getHostElement as ɵgetHostElement,
LifecycleHooksFeature as ɵLifecycleHooksFeature,
NgModuleFactory as ɵNgModuleFactory,
NgModuleRef as ɵRender3NgModuleRef,
NgModuleType as ɵNgModuleType,
NO_CHANGE as ɵNO_CHANGE,
PipeDef as ɵPipeDef,
RenderFlags as ɵRenderFlags,
setClassMetadata as ɵsetClassMetadata,
setClassMetadataAsync as ɵsetClassMetadataAsync,
ɵsetClassDebugInfo,
setLocaleId as ɵsetLocaleId,
store as ɵstore,
ɵDeferBlockDependencyInterceptor,
ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR,
ɵDEFER_BLOCK_CONFIG,
ɵɵadvance,
ɵɵattribute,
ɵɵattributeInterpolate1,
ɵɵattributeInterpolate2,
ɵɵattributeInterpolate3,
ɵɵattributeInterpolate4,
ɵɵattributeInterpolate5,
ɵɵattributeInterpolate6,
ɵɵattributeInterpolate7,
ɵɵattributeInterpolate8,
ɵɵattributeInterpolateV,
ɵɵclassMap,
ɵɵclassMapInterpolate1,
ɵɵclassMapInterpolate2,
ɵɵclassMapInterpolate3,
ɵɵclassMapInterpolate4,
ɵɵclassMapInterpolate5,
ɵɵclassMapInterpolate6,
ɵɵclassMapInterpolate7,
ɵɵclassMapInterpolate8,
ɵɵclassMapInterpolateV,
ɵɵclassProp,
ɵɵComponentDeclaration,
ɵɵconditional,
ɵɵcontentQuery,
ɵɵcontentQuerySignal,
ɵɵcomponentInstance,
ɵɵCopyDefinitionFeature,
ɵɵdefineComponent,
ɵɵdefineDirective,
ɵɵdefineNgModule,
ɵɵdefinePipe,
ɵɵDirectiveDeclaration,
ɵɵdirectiveInject,
ɵɵdisableBindings,
ɵɵelement,
ɵɵelementContainer,
ɵɵelementContainerEnd,
ɵɵelementContainerStart,
ɵɵelementEnd,
ɵɵelementStart,
ɵɵenableBindings,
ɵɵFactoryDeclaration,
ɵɵgetCurrentView,
ɵɵgetInheritedFactory,
ɵɵhostProperty,
ɵɵi18n,
ɵɵi18nApply,
ɵɵi18nAttributes,
ɵɵi18nEnd,
ɵɵi18nExp,
ɵɵi18nPostprocess,
ɵɵi18nStart,
ɵɵInheritDefinitionFeature,
ɵɵInputTransformsFeature,
ɵɵinjectAttribute,
ɵɵInjectorDeclaration,
ɵɵinvalidFactory,
ɵɵlistener,
ɵɵloadQuery,
ɵɵnamespaceHTML,
ɵɵnamespaceMathML,
ɵɵnamespaceSVG,
ɵɵnextContext,
ɵɵNgModuleDeclaration,
ɵɵNgOnChangesFeature,
ɵɵpipe,
ɵɵpipeBind1,
ɵɵpipeBind2,
ɵɵpipeBind3,
ɵɵpipeBind4,
ɵɵpipeBindV,
ɵɵPipeDeclaration,
ɵɵprojection,
ɵɵprojectionDef,
ɵɵproperty,
ɵɵpropertyInterpolate,
ɵɵpropertyInterpolate1,
ɵɵpropertyInterpolate2,
ɵɵpropertyInterpolate3,
ɵɵpropertyInterpolate4,
ɵɵpropertyInterpolate5,
ɵɵpropertyInterpolate6,
ɵɵpropertyInterpolate7,
ɵɵpropertyInterpolate8,
ɵɵpropertyInterpolateV,
ɵɵProvidersFeature,
ɵɵHostDirectivesFeature,
ɵɵpureFunction0,
ɵɵpureFunction1,
ɵɵpureFunction2,
ɵɵpureFunction3,
ɵɵpureFunction4,
ɵɵpureFunction5,
ɵɵpureFunction6,
ɵɵpureFunction7,
ɵɵpureFunction8,
ɵɵpureFunctionV,
ɵɵqueryAdvance,
ɵɵqueryRefresh,
ɵɵreference,
ɵɵresetView,
ɵɵresolveBody,
ɵɵresolveDocument,
ɵɵresolveWindow,
ɵɵrestoreView,
ɵɵrepeater,
ɵɵrepeaterCreate,
ɵɵrepeaterTrackByIdentity,
ɵɵrepeaterTrackByIndex,
ɵɵsetComponentScope,
ɵɵsetNgModuleScope,
ɵɵgetComponentDepsFactory,
ɵɵExternalStylesFeature,
ɵɵstyleMap,
ɵɵstyleMapInterpolate1,
ɵɵstyleMapInterpolate2,
ɵɵstyleMapInterpolate3,
ɵɵstyleMapInterpolate4,
ɵɵstyleMapInterpolate5,
ɵɵstyleMapInterpolate6,
ɵɵstyleMapInterpolate7,
ɵɵstyleMapInterpolate8,
ɵɵstyleMapInterpolateV,
ɵɵstyleProp,
ɵɵstylePropInterpolate1,
ɵɵstylePropInterpolate2,
ɵɵstylePropInterpolate3,
ɵɵstylePropInterpolate4,
ɵɵstylePropInterpolate5,
ɵɵstylePropInterpolate6,
ɵɵstylePropInterpolate7,
ɵɵstylePropInterpolate8,
ɵɵstylePropInterpolateV,
ɵɵsyntheticHostListener,
ɵɵsyntheticHostProperty,
ɵɵtemplate,
ɵɵtemplateRefExtractor,
ɵɵdefer,
ɵɵdeferWhen,
ɵɵdeferOnIdle,
ɵɵdeferOnImmediate,
ɵɵdeferOnTimer,
ɵɵdeferOnHover,
ɵɵdeferOnInteraction,
ɵɵdeferOnViewport,
ɵɵdeferPrefetchWhen,
ɵɵdeferPrefetchOnIdle,
ɵɵdeferPrefetchOnImmediate,
ɵɵdeferPrefetchOnTimer,
ɵɵdeferPrefetchOnHover,
ɵɵdeferPrefetchOnInteraction,
ɵɵdeferPrefetchOnViewport,
ɵɵdeferEnableTimerScheduling,
ɵɵdeferHydrateWhen,
ɵɵdeferHydrateNever,
ɵɵdeferHydrateOnIdle,
ɵɵdeferHydrateOnImmediate,
ɵɵdeferHydrateOnTimer,
ɵɵdeferHydrateOnHover,
ɵɵdeferHydrateOnInteraction,
ɵɵdeferHydrateOnViewport,
ɵɵtext,
ɵɵtextInterpolate,
ɵɵtextInterpolate1,
ɵɵtextInterpolate2,
ɵɵtextInterpolate3,
ɵɵtextInterpolate4,
ɵɵtextInterpolate5,
ɵɵtextInterpolate6,
ɵɵtextInterpolate7,
ɵɵtextInterpolate8,
ɵɵtextInterpolateV,
ɵɵviewQuery,
ɵɵviewQuerySignal,
ɵɵtwoWayProperty,
ɵɵtwoWayBindingSet,
ɵɵtwoWayListener,
ɵgetUnknownElementStrictMode,
ɵsetUnknownElementStrictMode,
ɵgetUnknownPropertyStrictMode,
ɵsetUnknownPropertyStrictMode,
ɵɵdeclareLet,
ɵɵstoreLet,
ɵɵreadContextLet,
ɵɵreplaceMetadata,
} from './render3/index';
export {CONTAINER_HEADER_OFFSET as ɵCONTAINER_HEADER_OFFSET} from './render3/interfaces/container';
export {LContext as ɵLContext} from './render3/interfaces/context';
export {setDocument as ɵsetDocument} from './render3/interfaces/document';
export {
compileComponent as ɵcompileComponent,
compileDirective as ɵcompileDirective,
} from './render3/jit/directive';
export {resetJitOptions as ɵresetJitOptions} from './render3/jit/jit_options';
export {
compileNgModule as ɵcompileNgModule,
compileNgModuleDefs as ɵcompileNgModuleDefs,
flushModuleScopingQueueAsMuchAsPossibl | {
"end_byte": 7250,
"start_byte": 1607,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/core_render3_private_export.ts"
} |
angular/packages/core/src/core_render3_private_export.ts_7251_9951 | as ɵflushModuleScopingQueueAsMuchAsPossible,
patchComponentDefWithScope as ɵpatchComponentDefWithScope,
resetCompiledComponents as ɵresetCompiledComponents,
transitiveScopesFor as ɵtransitiveScopesFor,
} from './render3/jit/module';
export {
FactoryTarget as ɵɵFactoryTarget,
ɵɵngDeclareClassMetadata,
ɵɵngDeclareClassMetadataAsync,
ɵɵngDeclareComponent,
ɵɵngDeclareDirective,
ɵɵngDeclareFactory,
ɵɵngDeclareInjectable,
ɵɵngDeclareInjector,
ɵɵngDeclareNgModule,
ɵɵngDeclarePipe,
} from './render3/jit/partial';
export {compilePipe as ɵcompilePipe} from './render3/jit/pipe';
export {isNgModule as ɵisNgModule} from './render3/jit/util';
export {Profiler as ɵProfiler, ProfilerEvent as ɵProfilerEvent} from './render3/profiler_types';
export {GlobalDevModeUtils as ɵGlobalDevModeUtils} from './render3/util/global_utils';
export {ViewRef as ɵViewRef} from './render3/view_ref';
export {
bypassSanitizationTrustHtml as ɵbypassSanitizationTrustHtml,
bypassSanitizationTrustResourceUrl as ɵbypassSanitizationTrustResourceUrl,
bypassSanitizationTrustScript as ɵbypassSanitizationTrustScript,
bypassSanitizationTrustStyle as ɵbypassSanitizationTrustStyle,
bypassSanitizationTrustUrl as ɵbypassSanitizationTrustUrl,
} from './sanitization/bypass';
export {
ɵɵsanitizeHtml,
ɵɵsanitizeResourceUrl,
ɵɵsanitizeScript,
ɵɵsanitizeStyle,
ɵɵsanitizeUrl,
ɵɵsanitizeUrlOrResourceUrl,
ɵɵtrustConstantHtml,
ɵɵtrustConstantResourceUrl,
} from './sanitization/sanitization';
export {ɵɵvalidateIframeAttribute} from './sanitization/iframe_attrs_validation';
export {noSideEffects as ɵnoSideEffects} from './util/closure';
export {AfterRenderManager as ɵAfterRenderManager} from './render3/after_render/manager';
export {
depsTracker as ɵdepsTracker,
USE_RUNTIME_DEPS_TRACKER_FOR_JIT as ɵUSE_RUNTIME_DEPS_TRACKER_FOR_JIT,
} from './render3/deps_tracker/deps_tracker';
export {generateStandaloneInDeclarationsError as ɵgenerateStandaloneInDeclarationsError} from './render3/jit/module';
export {getAsyncClassMetadataFn as ɵgetAsyncClassMetadataFn} from './render3/metadata';
export {NG_STANDALONE_DEFAULT_VALUE as ɵNG_STANDALONE_DEFAULT_VALUE} from './render3/standalone-default-value';
| {
"end_byte": 9951,
"start_byte": 7251,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/core_render3_private_export.ts"
} |
angular/packages/core/src/transfer_state.ts_0_4831 | /**
* @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 {APP_ID, PLATFORM_ID} from './application/application_tokens';
import {inject} from './di/injector_compatibility';
import {ɵɵdefineInjectable} from './di/interface/defs';
import {getDocument} from './render3/interfaces/document';
/**
* A type-safe key to use with `TransferState`.
*
* Example:
*
* ```
* const COUNTER_KEY = makeStateKey<number>('counter');
* let value = 10;
*
* transferState.set(COUNTER_KEY, value);
* ```
*
* @publicApi
*/
export type StateKey<T> = string & {
__not_a_string: never;
__value_type?: T;
};
/**
* Create a `StateKey<T>` that can be used to store value of type T with `TransferState`.
*
* Example:
*
* ```
* const COUNTER_KEY = makeStateKey<number>('counter');
* let value = 10;
*
* transferState.set(COUNTER_KEY, value);
* ```
*
* @publicApi
*/
export function makeStateKey<T = void>(key: string): StateKey<T> {
return key as StateKey<T>;
}
function initTransferState(): TransferState {
const transferState = new TransferState();
if (inject(PLATFORM_ID) === 'browser') {
transferState.store = retrieveTransferredState(getDocument(), inject(APP_ID));
}
return transferState;
}
/**
* A key value store that is transferred from the application on the server side to the application
* on the client side.
*
* The `TransferState` is available as an injectable token.
* On the client, just inject this token using DI and use it, it will be lazily initialized.
* On the server it's already included if `renderApplication` function is used. Otherwise, import
* the `ServerTransferStateModule` module to make the `TransferState` available.
*
* The values in the store are serialized/deserialized using JSON.stringify/JSON.parse. So only
* boolean, number, string, null and non-class objects will be serialized and deserialized in a
* non-lossy manner.
*
* @publicApi
*/
export class TransferState {
/** @nocollapse */
static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
token: TransferState,
providedIn: 'root',
factory: initTransferState,
});
/** @internal */
store: Record<string, unknown | undefined> = {};
private onSerializeCallbacks: {[k: string]: () => unknown | undefined} = {};
/**
* Get the value corresponding to a key. Return `defaultValue` if key is not found.
*/
get<T>(key: StateKey<T>, defaultValue: T): T {
return this.store[key] !== undefined ? (this.store[key] as T) : defaultValue;
}
/**
* Set the value corresponding to a key.
*/
set<T>(key: StateKey<T>, value: T): void {
this.store[key] = value;
}
/**
* Remove a key from the store.
*/
remove<T>(key: StateKey<T>): void {
delete this.store[key];
}
/**
* Test whether a key exists in the store.
*/
hasKey<T>(key: StateKey<T>): boolean {
return this.store.hasOwnProperty(key);
}
/**
* Indicates whether the state is empty.
*/
get isEmpty(): boolean {
return Object.keys(this.store).length === 0;
}
/**
* Register a callback to provide the value for a key when `toJson` is called.
*/
onSerialize<T>(key: StateKey<T>, callback: () => T): void {
this.onSerializeCallbacks[key] = callback;
}
/**
* Serialize the current state of the store to JSON.
*/
toJson(): string {
// Call the onSerialize callbacks and put those values into the store.
for (const key in this.onSerializeCallbacks) {
if (this.onSerializeCallbacks.hasOwnProperty(key)) {
try {
this.store[key] = this.onSerializeCallbacks[key]();
} catch (e) {
console.warn('Exception in onSerialize callback: ', e);
}
}
}
// Escape script tag to avoid break out of <script> tag in serialized output.
// Encoding of `<` is the same behaviour as G3 script_builders.
return JSON.stringify(this.store).replace(/</g, '\\u003C');
}
}
function retrieveTransferredState(
doc: Document,
appId: string,
): Record<string, unknown | undefined> {
// Locate the script tag with the JSON data transferred from the server.
// The id of the script tag is set to the Angular appId + 'state'.
const script = doc.getElementById(appId + '-state');
if (script?.textContent) {
try {
// Avoid using any here as it triggers lint errors in google3 (any is not allowed).
// Decoding of `<` is done of the box by browsers and node.js, same behaviour as G3
// script_builders.
return JSON.parse(script.textContent) as {};
} catch (e) {
console.warn('Exception while restoring TransferState for app ' + appId, e);
}
}
return {};
}
| {
"end_byte": 4831,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/transfer_state.ts"
} |
angular/packages/core/src/change_detection.ts_0_714 | /**
* @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
*/
/**
* @module
* @description
* Change detection enables data binding in Angular.
*/
export {
ChangeDetectionStrategy,
ChangeDetectorRef,
DefaultIterableDiffer,
IterableChangeRecord,
IterableChanges,
IterableDiffer,
IterableDifferFactory,
IterableDiffers,
KeyValueChangeRecord,
KeyValueChanges,
KeyValueDiffer,
KeyValueDifferFactory,
KeyValueDiffers,
NgIterable,
PipeTransform,
SimpleChange,
SimpleChanges,
TrackByFunction,
} from './change_detection/change_detection';
| {
"end_byte": 714,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection.ts"
} |
angular/packages/core/src/render.ts_0_358 | /**
* @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
*/
// Public API for render
export {Renderer2, RendererFactory2} from './render/api';
export {RendererStyleFlags2, RendererType2} from './render/api_flags';
| {
"end_byte": 358,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render.ts"
} |
angular/packages/core/src/event_delegation_utils.ts_0_3809 | /**
* @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
*/
// tslint:disable:no-duplicate-imports
import {EventContract} from '@angular/core/primitives/event-dispatch';
import {Attribute} from '@angular/core/primitives/event-dispatch';
import {InjectionToken, Injector} from './di';
import {RElement} from './render3/interfaces/renderer_dom';
import {BLOCK_ELEMENT_MAP} from './hydration/tokens';
export const DEFER_BLOCK_SSR_ID_ATTRIBUTE = 'ngb';
declare global {
interface Element {
__jsaction_fns: Map<string, Function[]> | undefined;
}
}
export function invokeRegisteredDelegationListeners(event: Event) {
const handlerFns = (event.currentTarget as Element)?.__jsaction_fns?.get(event.type);
if (!handlerFns) {
return;
}
for (const handler of handlerFns) {
handler(event);
}
}
export function setJSActionAttributes(
nativeElement: Element,
eventTypes: string[],
parentDeferBlockId: string | null = null,
) {
// jsaction attributes specifically should be applied to elements and not comment nodes.
// Comment nodes also have no setAttribute function. So this avoids errors.
if (eventTypes.length === 0 || nativeElement.nodeType !== Node.ELEMENT_NODE) {
return;
}
const existingAttr = nativeElement.getAttribute(Attribute.JSACTION);
// we dedupe cases where hydrate triggers are used as it's possible that
// someone may have added an event binding to the root node that matches what the
// hydrate trigger adds.
const parts = eventTypes.reduce((prev, curr) => {
// if there is no existing attribute OR it's not in the existing one, we need to add it
return (existingAttr?.indexOf(curr) ?? -1) === -1 ? prev + curr + ':;' : prev;
}, '');
// This is required to be a module accessor to appease security tests on setAttribute.
nativeElement.setAttribute(Attribute.JSACTION, `${existingAttr ?? ''}${parts}`);
const blockName = parentDeferBlockId ?? '';
if (blockName !== '' && parts.length > 0) {
nativeElement.setAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE, blockName);
}
}
export const sharedStashFunction = (rEl: RElement, eventType: string, listenerFn: Function) => {
const el = rEl as unknown as Element;
const eventListenerMap = el.__jsaction_fns ?? new Map();
const eventListeners = eventListenerMap.get(eventType) ?? [];
eventListeners.push(listenerFn);
eventListenerMap.set(eventType, eventListeners);
el.__jsaction_fns = eventListenerMap;
};
export const sharedMapFunction = (rEl: RElement, jsActionMap: Map<string, Set<Element>>) => {
let blockName = rEl.getAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE) ?? '';
const el = rEl as unknown as Element;
const blockSet = jsActionMap.get(blockName) ?? new Set<Element>();
if (!blockSet.has(el)) {
blockSet.add(el);
}
jsActionMap.set(blockName, blockSet);
};
export function removeListenersFromBlocks(blockNames: string[], injector: Injector) {
let blockList: Element[] = [];
const jsActionMap = injector.get(BLOCK_ELEMENT_MAP);
for (let blockName of blockNames) {
if (jsActionMap.has(blockName)) {
blockList = [...blockList, ...jsActionMap.get(blockName)!];
}
}
const replayList = new Set(blockList);
replayList.forEach(removeListeners);
}
export const removeListeners = (el: Element) => {
el.removeAttribute(Attribute.JSACTION);
el.removeAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE);
el.__jsaction_fns = undefined;
};
export interface EventContractDetails {
instance?: EventContract;
}
export const JSACTION_EVENT_CONTRACT = new InjectionToken<EventContractDetails>(
ngDevMode ? 'EVENT_CONTRACT_DETAILS' : '',
{
providedIn: 'root',
factory: () => ({}),
},
);
| {
"end_byte": 3809,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/event_delegation_utils.ts"
} |
angular/packages/core/src/r3_symbols.ts_0_1787 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/*
* This file exists to support compilation of @angular/core in Ivy mode.
*
* When the Angular compiler processes a compilation unit, it normally writes imports to
* @angular/core. When compiling the core package itself this strategy isn't usable. Instead, the
* compiler writes imports to this file.
*
* Only a subset of such imports are supported - core is not allowed to declare components or pipes.
* A check in ngtsc's `R3SymbolsImportRewriter` validates this condition. The rewriter is only used
* when compiling @angular/core and is responsible for translating an external name (prefixed with
* ɵ) to the internal symbol name as exported below.
*
* The below symbols are used for @Injectable and @NgModule compilation.
*/
export {ɵɵinject} from './di/injector_compatibility';
export {ɵɵdefineInjectable, ɵɵdefineInjector, ɵɵInjectableDeclaration} from './di/interface/defs';
export {NgModuleDef} from './metadata/ng_module_def';
export {ɵɵdefineNgModule} from './render3/definition';
export {
ɵɵFactoryDeclaration,
ɵɵInjectorDeclaration,
ɵɵNgModuleDeclaration,
} from './render3/interfaces/public_definitions';
export {setClassMetadata, setClassMetadataAsync} from './render3/metadata';
export {NgModuleFactory} from './render3/ng_module_ref';
export {noSideEffects as ɵnoSideEffects} from './util/closure';
/**
* The existence of this constant (in this particular file) informs the Angular compiler that the
* current program is actually @angular/core, which needs to be compiled specially.
*/
export const ITS_JUST_ANGULAR = true;
| {
"end_byte": 1787,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/r3_symbols.ts"
} |
angular/packages/core/src/metadata.ts_0_1337 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* This indirection is needed to free up Component, etc symbols in the public API
* to be used by the decorator versions of these annotations.
*/
export {Attribute, AttributeDecorator} from './di/metadata_attr';
export {
AfterContentChecked,
AfterContentInit,
AfterViewChecked,
AfterViewInit,
DoCheck,
OnChanges,
OnDestroy,
OnInit,
} from './interface/lifecycle_hooks';
export {
ContentChild,
ContentChildDecorator,
ContentChildren,
ContentChildrenDecorator,
Query,
ViewChild,
ViewChildDecorator,
ViewChildren,
ViewChildrenDecorator,
} from './metadata/di';
export {
Component,
ComponentDecorator,
Directive,
DirectiveDecorator,
HostBinding,
HostBindingDecorator,
HostListener,
HostListenerDecorator,
Input,
InputDecorator,
Output,
OutputDecorator,
Pipe,
PipeDecorator,
} from './metadata/directives';
export {DoBootstrap} from './metadata/do_bootstrap';
export {NgModule, NgModuleDecorator} from './metadata/ng_module';
export {CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA, SchemaMetadata} from './metadata/schema';
export {ViewEncapsulation} from './metadata/view';
| {
"end_byte": 1337,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/metadata.ts"
} |
angular/packages/core/src/version.ts_0_657 | /**
* @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
*/
/**
* @description Represents the version of Angular
*
* @publicApi
*/
export class Version {
public readonly major: string;
public readonly minor: string;
public readonly patch: string;
constructor(public full: string) {
const parts = full.split('.');
this.major = parts[0];
this.minor = parts[1];
this.patch = parts.slice(2).join('.');
}
}
/**
* @publicApi
*/
export const VERSION = new Version('0.0.0-PLACEHOLDER');
| {
"end_byte": 657,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/version.ts"
} |
angular/packages/core/src/console.ts_0_591 | /**
* @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 {Injectable} from './di';
@Injectable({providedIn: 'platform'})
export class Console {
log(message: string): void {
// tslint:disable-next-line:no-console
console.log(message);
}
// Note: for reporting errors use `DOM.logError()` as it is platform specific
warn(message: string): void {
// tslint:disable-next-line:no-console
console.warn(message);
}
}
| {
"end_byte": 591,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/console.ts"
} |
angular/packages/core/src/pending_tasks.ts_0_4311 | /**
* @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 {BehaviorSubject} from 'rxjs';
import {inject} from './di/injector_compatibility';
import {ɵɵdefineInjectable} from './di/interface/defs';
import {OnDestroy} from './interface/lifecycle_hooks';
import {
ChangeDetectionScheduler,
NotificationSource,
} from './change_detection/scheduling/zoneless_scheduling';
/**
* Internal implementation of the pending tasks service.
*/
export class PendingTasksInternal implements OnDestroy {
private taskId = 0;
private pendingTasks = new Set<number>();
private get _hasPendingTasks() {
return this.hasPendingTasks.value;
}
hasPendingTasks = new BehaviorSubject<boolean>(false);
add(): number {
if (!this._hasPendingTasks) {
this.hasPendingTasks.next(true);
}
const taskId = this.taskId++;
this.pendingTasks.add(taskId);
return taskId;
}
has(taskId: number): boolean {
return this.pendingTasks.has(taskId);
}
remove(taskId: number): void {
this.pendingTasks.delete(taskId);
if (this.pendingTasks.size === 0 && this._hasPendingTasks) {
this.hasPendingTasks.next(false);
}
}
ngOnDestroy(): void {
this.pendingTasks.clear();
if (this._hasPendingTasks) {
this.hasPendingTasks.next(false);
}
}
/** @nocollapse */
static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
token: PendingTasksInternal,
providedIn: 'root',
factory: () => new PendingTasksInternal(),
});
}
/**
* Service that keeps track of pending tasks contributing to the stableness of Angular
* application. While several existing Angular services (ex.: `HttpClient`) will internally manage
* tasks influencing stability, this API gives control over stability to library and application
* developers for specific cases not covered by Angular internals.
*
* The concept of stability comes into play in several important scenarios:
* - SSR process needs to wait for the application stability before serializing and sending rendered
* HTML;
* - tests might want to delay assertions until the application becomes stable;
*
* @usageNotes
* ```typescript
* const pendingTasks = inject(PendingTasks);
* const taskCleanup = pendingTasks.add();
* // do work that should block application's stability and then:
* taskCleanup();
* ```
*
* @publicApi
* @developerPreview
*/
export class PendingTasks {
private internalPendingTasks = inject(PendingTasksInternal);
private scheduler = inject(ChangeDetectionScheduler);
/**
* Adds a new task that should block application's stability.
* @returns A cleanup function that removes a task when called.
*/
add(): () => void {
const taskId = this.internalPendingTasks.add();
return () => {
if (!this.internalPendingTasks.has(taskId)) {
// This pending task has already been cleared.
return;
}
// Notifying the scheduler will hold application stability open until the next tick.
this.scheduler.notify(NotificationSource.PendingTaskRemoved);
this.internalPendingTasks.remove(taskId);
};
}
/**
* Runs an asynchronous function and blocks the application's stability until the function completes.
*
* ```
* pendingTasks.run(async () => {
* const userData = await fetch('/api/user');
* this.userData.set(userData);
* });
* ```
*
* Application stability is at least delayed until the next tick after the `run` method resolves
* so it is safe to make additional updates to application state that would require UI synchronization:
*
* ```
* const userData = await pendingTasks.run(() => fetch('/api/user'));
* this.userData.set(userData);
* ```
*
* @param fn The asynchronous function to execute
*/
async run<T>(fn: () => Promise<T>): Promise<T> {
const removeTask = this.add();
try {
return await fn();
} finally {
removeTask();
}
}
/** @nocollapse */
static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
token: PendingTasks,
providedIn: 'root',
factory: () => new PendingTasks(),
});
}
| {
"end_byte": 4311,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/pending_tasks.ts"
} |
angular/packages/core/src/interface/type.ts_0_1528 | /**
* @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
*/
/**
* @description
*
* Represents a type that a Component or other object is instances of.
*
* An example of a `Type` is `MyCustomComponent` class, which in JavaScript is represented by
* the `MyCustomComponent` constructor function.
*
* @publicApi
*/
export const Type = Function;
export function isType(v: any): v is Type<any> {
return typeof v === 'function';
}
/**
* @description
*
* Represents an abstract class `T`, if applied to a concrete class it would stop being
* instantiable.
*
* @publicApi
*/
export interface AbstractType<T> extends Function {
prototype: T;
}
export interface Type<T> extends Function {
new (...args: any[]): T;
}
/**
* Returns a writable type version of type.
*
* USAGE:
* Given:
* ```
* interface Person {readonly name: string}
* ```
*
* We would like to get a read/write version of `Person`.
* ```
* const WritablePerson = Writable<Person>;
* ```
*
* The result is that you can do:
*
* ```
* const readonlyPerson: Person = {name: 'Marry'};
* readonlyPerson.name = 'John'; // TypeError
* (readonlyPerson as WritablePerson).name = 'John'; // OK
*
* // Error: Correctly detects that `Person` did not have `age` property.
* (readonlyPerson as WritablePerson).age = 30;
* ```
*/
export type Writable<T> = {
-readonly [K in keyof T]: T[K];
};
| {
"end_byte": 1528,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/interface/type.ts"
} |
angular/packages/core/src/interface/lifecycle_hooks.ts_0_7448 | /**
* @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 {SimpleChanges} from './simple_change';
/**
* @description
* A lifecycle hook that is called when any data-bound property of a directive changes.
* Define an `ngOnChanges()` method to handle the changes.
*
* @see {@link DoCheck}
* @see {@link OnInit}
* @see [Lifecycle hooks guide](guide/components/lifecycle)
*
* @usageNotes
* The following snippet shows how a component can implement this interface to
* define an on-changes handler for an input property.
*
* {@example core/ts/metadata/lifecycle_hooks_spec.ts region='OnChanges'}
*
* @publicApi
*/
export interface OnChanges {
/**
* A callback method that is invoked immediately after the
* default change detector has checked data-bound properties
* if at least one has changed, and before the view and content
* children are checked.
* @param changes The changed properties.
*/
ngOnChanges(changes: SimpleChanges): void;
}
/**
* @description
* A lifecycle hook that is called after Angular has initialized
* all data-bound properties of a directive.
* Define an `ngOnInit()` method to handle any additional initialization tasks.
*
* @see {@link AfterContentInit}
* @see [Lifecycle hooks guide](guide/components/lifecycle)
*
* @usageNotes
* The following snippet shows how a component can implement this interface to
* define its own initialization method.
*
* {@example core/ts/metadata/lifecycle_hooks_spec.ts region='OnInit'}
*
* @publicApi
*/
export interface OnInit {
/**
* A callback method that is invoked immediately after the
* default change detector has checked the directive's
* data-bound properties for the first time,
* and before any of the view or content children have been checked.
* It is invoked only once when the directive is instantiated.
*/
ngOnInit(): void;
}
/**
* A lifecycle hook that invokes a custom change-detection function for a directive,
* in addition to the check performed by the default change-detector.
*
* The default change-detection algorithm looks for differences by comparing
* bound-property values by reference across change detection runs. You can use this
* hook to check for and respond to changes by some other means.
*
* When the default change detector detects changes, it invokes `ngOnChanges()` if supplied,
* regardless of whether you perform additional change detection.
* Typically, you should not use both `DoCheck` and `OnChanges` to respond to
* changes on the same input.
*
* @see {@link OnChanges}
* @see [Lifecycle hooks guide](guide/components/lifecycle)
*
* @usageNotes
* The following snippet shows how a component can implement this interface
* to invoke it own change-detection cycle.
*
* {@example core/ts/metadata/lifecycle_hooks_spec.ts region='DoCheck'}
*
* For a more complete example and discussion, see
* [Defining custom change detection](guide/components/lifecycle#defining-custom-change-detection).
*
* @publicApi
*/
export interface DoCheck {
/**
* A callback method that performs change-detection, invoked
* after the default change-detector runs.
* See `KeyValueDiffers` and `IterableDiffers` for implementing
* custom change checking for collections.
*
*/
ngDoCheck(): void;
}
/**
* A lifecycle hook that is called when a directive, pipe, or service is destroyed.
* Use for any custom cleanup that needs to occur when the
* instance is destroyed.
* @see [Lifecycle hooks guide](guide/components/lifecycle)
*
* @usageNotes
* The following snippet shows how a component can implement this interface
* to define its own custom clean-up method.
*
* {@example core/ts/metadata/lifecycle_hooks_spec.ts region='OnDestroy'}
*
* @publicApi
*/
export interface OnDestroy {
/**
* A callback method that performs custom clean-up, invoked immediately
* before a directive, pipe, or service instance is destroyed.
*/
ngOnDestroy(): void;
}
/**
* @description
* A lifecycle hook that is called after Angular has fully initialized
* all content of a directive. It will run only once when the projected content is initialized.
* Define an `ngAfterContentInit()` method to handle any additional initialization tasks.
*
* @see {@link OnInit}
* @see {@link AfterViewInit}
* @see [Lifecycle hooks guide](guide/components/lifecycle)
*
* @usageNotes
* The following snippet shows how a component can implement this interface to
* define its own content initialization method.
*
* {@example core/ts/metadata/lifecycle_hooks_spec.ts region='AfterContentInit'}
*
* @publicApi
*/
export interface AfterContentInit {
/**
* A callback method that is invoked immediately after
* Angular has completed initialization of all of the directive's
* content.
* It is invoked only once when the directive is instantiated.
*/
ngAfterContentInit(): void;
}
/**
* @description
* A lifecycle hook that is called after the default change detector has
* completed checking all content of a directive. It will run after the content
* has been checked and most of the time it's during a change detection cycle.
*
* @see {@link AfterViewChecked}
* @see [Lifecycle hooks guide](guide/components/lifecycle)
*
* @usageNotes
* The following snippet shows how a component can implement this interface to
* define its own after-check functionality.
*
* {@example core/ts/metadata/lifecycle_hooks_spec.ts region='AfterContentChecked'}
*
* @publicApi
*/
export interface AfterContentChecked {
/**
* A callback method that is invoked immediately after the
* default change detector has completed checking all of the directive's
* content.
*/
ngAfterContentChecked(): void;
}
/**
* @description
* A lifecycle hook that is called after Angular has fully initialized
* a component's view.
* Define an `ngAfterViewInit()` method to handle any additional initialization tasks.
*
* @see {@link OnInit}
* @see {@link AfterContentInit}
* @see [Lifecycle hooks guide](guide/components/lifecycle)
*
* @usageNotes
* The following snippet shows how a component can implement this interface to
* define its own view initialization method.
*
* {@example core/ts/metadata/lifecycle_hooks_spec.ts region='AfterViewInit'}
*
* @publicApi
*/
export interface AfterViewInit {
/**
* A callback method that is invoked immediately after
* Angular has completed initialization of a component's view.
* It is invoked only once when the view is instantiated.
*
*/
ngAfterViewInit(): void;
}
/**
* @description
* A lifecycle hook that is called after the default change detector has
* completed checking a component's view for changes.
*
* @see {@link AfterContentChecked}
* @see [Lifecycle hooks guide](guide/components/lifecycle)
*
* @usageNotes
* The following snippet shows how a component can implement this interface to
* define its own after-check functionality.
*
* {@example core/ts/metadata/lifecycle_hooks_spec.ts region='AfterViewChecked'}
*
* @publicApi
*/
export interface AfterViewChecked {
/**
* A callback method that is invoked immediately after the
* default change detector has completed one change-check cycle
* for a component's view.
*/
ngAfterViewChecked(): void;
}
| {
"end_byte": 7448,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/interface/lifecycle_hooks.ts"
} |
angular/packages/core/src/interface/simple_change.ts_0_1066 | /**
* @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
*/
/**
* Represents a basic change from a previous to a new value for a single
* property on a directive instance. Passed as a value in a
* {@link SimpleChanges} object to the `ngOnChanges` hook.
*
* @see {@link OnChanges}
*
* @publicApi
*/
export class SimpleChange {
constructor(
public previousValue: any,
public currentValue: any,
public firstChange: boolean,
) {}
/**
* Check whether the new value is the first value assigned.
*/
isFirstChange(): boolean {
return this.firstChange;
}
}
/**
* A hashtable of changes represented by {@link SimpleChange} objects stored
* at the declared property name they belong to on a Directive or Component. This is
* the type passed to the `ngOnChanges` hook.
*
* @see {@link OnChanges}
*
* @publicApi
*/
export interface SimpleChanges {
[propName: string]: SimpleChange;
}
| {
"end_byte": 1066,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/interface/simple_change.ts"
} |
angular/packages/core/src/interface/BUILD.bazel_0_534 | load("//tools:defaults.bzl", "ts_library", "tsec_test")
package(default_visibility = [
"//packages:__pkg__",
"//packages/core:__subpackages__",
"//tools/public_api_guard:__pkg__",
])
ts_library(
name = "interface",
srcs = glob(
[
"*.ts",
],
),
)
tsec_test(
name = "tsec_test",
target = "interface",
tsconfig = "//packages:tsec_config",
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
]),
visibility = ["//visibility:public"],
)
| {
"end_byte": 534,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/interface/BUILD.bazel"
} |
angular/packages/core/src/di/null_injector.ts_0_702 | /**
* @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 {stringify} from '../util/stringify';
import type {Injector} from './injector';
import {THROW_IF_NOT_FOUND} from './injector_compatibility';
export class NullInjector implements Injector {
get(token: any, notFoundValue: any = THROW_IF_NOT_FOUND): any {
if (notFoundValue === THROW_IF_NOT_FOUND) {
const error = new Error(`NullInjectorError: No provider for ${stringify(token)}!`);
error.name = 'NullInjectorError';
throw error;
}
return notFoundValue;
}
}
| {
"end_byte": 702,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/di/null_injector.ts"
} |
angular/packages/core/src/di/scope.ts_0_677 | /**
* @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 {InjectionToken} from './injection_token';
export type InjectorScope = 'root' | 'platform' | 'environment';
/**
* An internal token whose presence in an injector indicates that the injector should treat itself
* as a root scoped injector when processing requests for unknown tokens which may indicate
* they are provided in the root scope.
*/
export const INJECTOR_SCOPE = new InjectionToken<InjectorScope | null>(
ngDevMode ? 'Set Injector scope.' : '',
);
| {
"end_byte": 677,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/di/scope.ts"
} |
angular/packages/core/src/di/r3_injector.ts_0_5886 | /**
* @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 '../util/ng_dev_mode';
import {RuntimeError, RuntimeErrorCode} from '../errors';
import {OnDestroy} from '../interface/lifecycle_hooks';
import {Type} from '../interface/type';
import {
emitInstanceCreatedByInjectorEvent,
emitProviderConfiguredEvent,
InjectorProfilerContext,
runInInjectorProfilerContext,
setInjectorProfilerContext,
} from '../render3/debug/injector_profiler';
import {FactoryFn, getFactoryDef} from '../render3/definition_factory';
import {
throwCyclicDependencyError,
throwInvalidProviderError,
throwMixedMultiProviderError,
} from '../render3/errors_di';
import {NG_ENV_ID} from '../render3/fields';
import {newArray} from '../util/array_utils';
import {EMPTY_ARRAY} from '../util/empty';
import {stringify} from '../util/stringify';
import {resolveForwardRef} from './forward_ref';
import {ENVIRONMENT_INITIALIZER} from './initializer_token';
import {setInjectImplementation} from './inject_switch';
import {InjectionToken} from './injection_token';
import type {Injector} from './injector';
import {
catchInjectorError,
convertToBitFlags,
injectArgs,
NG_TEMP_TOKEN_PATH,
setCurrentInjector,
THROW_IF_NOT_FOUND,
ɵɵinject,
} from './injector_compatibility';
import {INJECTOR} from './injector_token';
import {
getInheritedInjectableDef,
getInjectableDef,
InjectorType,
ɵɵInjectableDeclaration,
} from './interface/defs';
import {InjectFlags, InjectOptions} from './interface/injector';
import {
ClassProvider,
ConstructorProvider,
EnvironmentProviders,
InternalEnvironmentProviders,
isEnvironmentProviders,
Provider,
StaticClassProvider,
TypeProvider,
} from './interface/provider';
import {INJECTOR_DEF_TYPES} from './internal_tokens';
import {NullInjector} from './null_injector';
import {
isExistingProvider,
isFactoryProvider,
isTypeProvider,
isValueProvider,
SingleProvider,
} from './provider_collection';
import {ProviderToken} from './provider_token';
import {INJECTOR_SCOPE, InjectorScope} from './scope';
import {setActiveConsumer} from '@angular/core/primitives/signals';
/**
* Marker which indicates that a value has not yet been created from the factory function.
*/
const NOT_YET = {};
/**
* Marker which indicates that the factory function for a token is in the process of being called.
*
* If the injector is asked to inject a token with its value set to CIRCULAR, that indicates
* injection of a dependency has recursively attempted to inject the original token, and there is
* a circular dependency among the providers.
*/
const CIRCULAR = {};
/**
* A lazily initialized NullInjector.
*/
let NULL_INJECTOR: Injector | undefined = undefined;
export function getNullInjector(): Injector {
if (NULL_INJECTOR === undefined) {
NULL_INJECTOR = new NullInjector();
}
return NULL_INJECTOR;
}
/**
* An entry in the injector which tracks information about the given token, including a possible
* current value.
*/
interface Record<T> {
factory: (() => T) | undefined;
value: T | {};
multi: any[] | undefined;
}
/**
* An `Injector` that's part of the environment injector hierarchy, which exists outside of the
* component tree.
*/
export abstract class EnvironmentInjector implements Injector {
/**
* Retrieves an instance from the injector based on the provided token.
* @returns The instance from the injector if defined, otherwise the `notFoundValue`.
* @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.
*/
abstract get<T>(
token: ProviderToken<T>,
notFoundValue: undefined,
options: InjectOptions & {
optional?: false;
},
): T;
/**
* Retrieves an instance from the injector based on the provided token.
* @returns The instance from the injector if defined, otherwise the `notFoundValue`.
* @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.
*/
abstract get<T>(
token: ProviderToken<T>,
notFoundValue: null | undefined,
options: InjectOptions,
): T | null;
/**
* Retrieves an instance from the injector based on the provided token.
* @returns The instance from the injector if defined, otherwise the `notFoundValue`.
* @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.
*/
abstract get<T>(token: ProviderToken<T>, notFoundValue?: T, options?: InjectOptions): T;
/**
* Retrieves an instance from the injector based on the provided token.
* @returns The instance from the injector if defined, otherwise the `notFoundValue`.
* @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.
* @deprecated use object-based flags (`InjectOptions`) instead.
*/
abstract get<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): T;
/**
* @deprecated from v4.0.0 use ProviderToken<T>
* @suppress {duplicate}
*/
abstract get(token: any, notFoundValue?: any): any;
/**
* Runs the given function in the context of this `EnvironmentInjector`.
*
* Within the function's stack frame, [`inject`](api/core/inject) can be used to inject
* dependencies from this injector. Note that `inject` is only usable synchronously, and cannot be
* used in any asynchronous callbacks or after any `await` points.
*
* @param fn the closure to be run in the context of this injector
* @returns the return value of the function, if any
* @deprecated use the standalone function `runInInjectionContext` instead
*/
abstract runInContext<ReturnT>(fn: () => ReturnT): ReturnT;
abstract destroy(): void;
/**
* @internal
*/
abstract onDestroy(callback: () => void): () => void;
}
ex | {
"end_byte": 5886,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/di/r3_injector.ts"
} |
angular/packages/core/src/di/r3_injector.ts_5888_14657 | rt class R3Injector extends EnvironmentInjector {
/**
* Map of tokens to records which contain the instances of those tokens.
* - `null` value implies that we don't have the record. Used by tree-shakable injectors
* to prevent further searches.
*/
private records = new Map<ProviderToken<any>, Record<any> | null>();
/**
* Set of values instantiated by this injector which contain `ngOnDestroy` lifecycle hooks.
*/
private _ngOnDestroyHooks = new Set<OnDestroy>();
private _onDestroyHooks: Array<() => void> = [];
/**
* Flag indicating that this injector was previously destroyed.
*/
get destroyed(): boolean {
return this._destroyed;
}
private _destroyed = false;
private injectorDefTypes: Set<Type<unknown>>;
constructor(
providers: Array<Provider | EnvironmentProviders>,
readonly parent: Injector,
readonly source: string | null,
readonly scopes: Set<InjectorScope>,
) {
super();
// Start off by creating Records for every provider.
forEachSingleProvider(providers as Array<Provider | InternalEnvironmentProviders>, (provider) =>
this.processProvider(provider),
);
// Make sure the INJECTOR token provides this injector.
this.records.set(INJECTOR, makeRecord(undefined, this));
// And `EnvironmentInjector` if the current injector is supposed to be env-scoped.
if (scopes.has('environment')) {
this.records.set(EnvironmentInjector, makeRecord(undefined, this));
}
// Detect whether this injector has the APP_ROOT_SCOPE token and thus should provide
// any injectable scoped to APP_ROOT_SCOPE.
const record = this.records.get(INJECTOR_SCOPE) as Record<InjectorScope | null>;
if (record != null && typeof record.value === 'string') {
this.scopes.add(record.value as InjectorScope);
}
this.injectorDefTypes = new Set(this.get(INJECTOR_DEF_TYPES, EMPTY_ARRAY, InjectFlags.Self));
}
/**
* Destroy the injector and release references to every instance or provider associated with it.
*
* Also calls the `OnDestroy` lifecycle hooks of every instance that was created for which a
* hook was found.
*/
override destroy(): void {
assertNotDestroyed(this);
// Set destroyed = true first, in case lifecycle hooks re-enter destroy().
this._destroyed = true;
const prevConsumer = setActiveConsumer(null);
try {
// Call all the lifecycle hooks.
for (const service of this._ngOnDestroyHooks) {
service.ngOnDestroy();
}
const onDestroyHooks = this._onDestroyHooks;
// Reset the _onDestroyHooks array before iterating over it to prevent hooks that unregister
// themselves from mutating the array during iteration.
this._onDestroyHooks = [];
for (const hook of onDestroyHooks) {
hook();
}
} finally {
// Release all references.
this.records.clear();
this._ngOnDestroyHooks.clear();
this.injectorDefTypes.clear();
setActiveConsumer(prevConsumer);
}
}
override onDestroy(callback: () => void): () => void {
assertNotDestroyed(this);
this._onDestroyHooks.push(callback);
return () => this.removeOnDestroy(callback);
}
override runInContext<ReturnT>(fn: () => ReturnT): ReturnT {
assertNotDestroyed(this);
const previousInjector = setCurrentInjector(this);
const previousInjectImplementation = setInjectImplementation(undefined);
let prevInjectContext: InjectorProfilerContext | undefined;
if (ngDevMode) {
prevInjectContext = setInjectorProfilerContext({injector: this, token: null});
}
try {
return fn();
} finally {
setCurrentInjector(previousInjector);
setInjectImplementation(previousInjectImplementation);
ngDevMode && setInjectorProfilerContext(prevInjectContext!);
}
}
override get<T>(
token: ProviderToken<T>,
notFoundValue: any = THROW_IF_NOT_FOUND,
flags: InjectFlags | InjectOptions = InjectFlags.Default,
): T {
assertNotDestroyed(this);
if (token.hasOwnProperty(NG_ENV_ID)) {
return (token as any)[NG_ENV_ID](this);
}
flags = convertToBitFlags(flags) as InjectFlags;
// Set the injection context.
let prevInjectContext: InjectorProfilerContext;
if (ngDevMode) {
prevInjectContext = setInjectorProfilerContext({injector: this, token: token as Type<T>});
}
const previousInjector = setCurrentInjector(this);
const previousInjectImplementation = setInjectImplementation(undefined);
try {
// Check for the SkipSelf flag.
if (!(flags & InjectFlags.SkipSelf)) {
// SkipSelf isn't set, check if the record belongs to this injector.
let record: Record<T> | undefined | null = this.records.get(token);
if (record === undefined) {
// No record, but maybe the token is scoped to this injector. Look for an injectable
// def with a scope matching this injector.
const def = couldBeInjectableType(token) && getInjectableDef(token);
if (def && this.injectableDefInScope(def)) {
// Found an injectable def and it's scoped to this injector. Pretend as if it was here
// all along.
if (ngDevMode) {
runInInjectorProfilerContext(this, token as Type<T>, () => {
emitProviderConfiguredEvent(token as TypeProvider);
});
}
record = makeRecord(injectableDefOrInjectorDefFactory(token), NOT_YET);
} else {
record = null;
}
this.records.set(token, record);
}
// If a record was found, get the instance for it and return it.
if (record != null /* NOT null || undefined */) {
return this.hydrate(token, record);
}
}
// Select the next injector based on the Self flag - if self is set, the next injector is
// the NullInjector, otherwise it's the parent.
const nextInjector = !(flags & InjectFlags.Self) ? this.parent : getNullInjector();
// Set the notFoundValue based on the Optional flag - if optional is set and notFoundValue
// is undefined, the value is null, otherwise it's the notFoundValue.
notFoundValue =
flags & InjectFlags.Optional && notFoundValue === THROW_IF_NOT_FOUND ? null : notFoundValue;
return nextInjector.get(token, notFoundValue);
} catch (e: any) {
if (e.name === 'NullInjectorError') {
const path: any[] = (e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || []);
path.unshift(stringify(token));
if (previousInjector) {
// We still have a parent injector, keep throwing
throw e;
} else {
// Format & throw the final error message when we don't have any previous injector
return catchInjectorError(e, token, 'R3InjectorError', this.source);
}
} else {
throw e;
}
} finally {
// Lastly, restore the previous injection context.
setInjectImplementation(previousInjectImplementation);
setCurrentInjector(previousInjector);
ngDevMode && setInjectorProfilerContext(prevInjectContext!);
}
}
/** @internal */
resolveInjectorInitializers() {
const prevConsumer = setActiveConsumer(null);
const previousInjector = setCurrentInjector(this);
const previousInjectImplementation = setInjectImplementation(undefined);
let prevInjectContext: InjectorProfilerContext | undefined;
if (ngDevMode) {
prevInjectContext = setInjectorProfilerContext({injector: this, token: null});
}
try {
const initializers = this.get(ENVIRONMENT_INITIALIZER, EMPTY_ARRAY, InjectFlags.Self);
if (ngDevMode && !Array.isArray(initializers)) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_MULTI_PROVIDER,
'Unexpected type of the `ENVIRONMENT_INITIALIZER` token value ' +
`(expected an array, but got ${typeof initializers}). ` +
'Please check that the `ENVIRONMENT_INITIALIZER` token is configured as a ' +
'`multi: true` provider.',
);
}
for (const initializer of initializers) {
initializer();
}
} finally {
setCurrentInjector(previousInjector);
setInjectImplementation(previousInjectImplementation);
ngDevMode && setInjectorProfilerContext(prevInjectContext!);
setActiveConsumer(prevConsumer);
}
}
override toString() {
const tokens: string[] = [];
const records = this.records;
for (const token of records.keys()) {
tokens.push(stringify(token));
}
return `R3Injector[${tokens.join(', ')}]`;
}
/**
* Process a `SingleProvider` and add it.
*/
p | {
"end_byte": 14657,
"start_byte": 5888,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/di/r3_injector.ts"
} |
angular/packages/core/src/di/r3_injector.ts_14660_23295 | ate processProvider(provider: SingleProvider): void {
// Determine the token from the provider. Either it's its own token, or has a {provide: ...}
// property.
provider = resolveForwardRef(provider);
let token: any = isTypeProvider(provider)
? provider
: resolveForwardRef(provider && provider.provide);
// Construct a `Record` for the provider.
const record = providerToRecord(provider);
if (ngDevMode) {
runInInjectorProfilerContext(this, token, () => {
// Emit InjectorProfilerEventType.Create if provider is a value provider because
// these are the only providers that do not go through the value hydration logic
// where this event would normally be emitted from.
if (isValueProvider(provider)) {
emitInstanceCreatedByInjectorEvent(provider.useValue);
}
emitProviderConfiguredEvent(provider);
});
}
if (!isTypeProvider(provider) && provider.multi === true) {
// If the provider indicates that it's a multi-provider, process it specially.
// First check whether it's been defined already.
let multiRecord = this.records.get(token);
if (multiRecord) {
// It has. Throw a nice error if
if (ngDevMode && multiRecord.multi === undefined) {
throwMixedMultiProviderError();
}
} else {
multiRecord = makeRecord(undefined, NOT_YET, true);
multiRecord.factory = () => injectArgs(multiRecord!.multi!);
this.records.set(token, multiRecord);
}
token = provider;
multiRecord.multi!.push(provider);
} else {
if (ngDevMode) {
const existing = this.records.get(token);
if (existing && existing.multi !== undefined) {
throwMixedMultiProviderError();
}
}
}
this.records.set(token, record);
}
private hydrate<T>(token: ProviderToken<T>, record: Record<T>): T {
const prevConsumer = setActiveConsumer(null);
try {
if (ngDevMode && record.value === CIRCULAR) {
throwCyclicDependencyError(stringify(token));
} else if (record.value === NOT_YET) {
record.value = CIRCULAR;
if (ngDevMode) {
runInInjectorProfilerContext(this, token as Type<T>, () => {
record.value = record.factory!();
emitInstanceCreatedByInjectorEvent(record.value);
});
} else {
record.value = record.factory!();
}
}
if (typeof record.value === 'object' && record.value && hasOnDestroy(record.value)) {
this._ngOnDestroyHooks.add(record.value);
}
return record.value as T;
} finally {
setActiveConsumer(prevConsumer);
}
}
private injectableDefInScope(def: ɵɵInjectableDeclaration<any>): boolean {
if (!def.providedIn) {
return false;
}
const providedIn = resolveForwardRef(def.providedIn);
if (typeof providedIn === 'string') {
return providedIn === 'any' || this.scopes.has(providedIn);
} else {
return this.injectorDefTypes.has(providedIn);
}
}
private removeOnDestroy(callback: () => void): void {
const destroyCBIdx = this._onDestroyHooks.indexOf(callback);
if (destroyCBIdx !== -1) {
this._onDestroyHooks.splice(destroyCBIdx, 1);
}
}
}
function injectableDefOrInjectorDefFactory(token: ProviderToken<any>): FactoryFn<any> {
// Most tokens will have an injectable def directly on them, which specifies a factory directly.
const injectableDef = getInjectableDef(token);
const factory = injectableDef !== null ? injectableDef.factory : getFactoryDef(token);
if (factory !== null) {
return factory;
}
// InjectionTokens should have an injectable def (ɵprov) and thus should be handled above.
// If it's missing that, it's an error.
if (token instanceof InjectionToken) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_INJECTION_TOKEN,
ngDevMode && `Token ${stringify(token)} is missing a ɵprov definition.`,
);
}
// Undecorated types can sometimes be created if they have no constructor arguments.
if (token instanceof Function) {
return getUndecoratedInjectableFactory(token);
}
// There was no way to resolve a factory for this token.
throw new RuntimeError(RuntimeErrorCode.INVALID_INJECTION_TOKEN, ngDevMode && 'unreachable');
}
function getUndecoratedInjectableFactory(token: Function) {
// If the token has parameters then it has dependencies that we cannot resolve implicitly.
const paramLength = token.length;
if (paramLength > 0) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_INJECTION_TOKEN,
ngDevMode &&
`Can't resolve all parameters for ${stringify(token)}: (${newArray(paramLength, '?').join(
', ',
)}).`,
);
}
// The constructor function appears to have no parameters.
// This might be because it inherits from a super-class. In which case, use an injectable
// def from an ancestor if there is one.
// Otherwise this really is a simple class with no dependencies, so return a factory that
// just instantiates the zero-arg constructor.
const inheritedInjectableDef = getInheritedInjectableDef(token);
if (inheritedInjectableDef !== null) {
return () => inheritedInjectableDef.factory(token as Type<any>);
} else {
return () => new (token as Type<any>)();
}
}
function providerToRecord(provider: SingleProvider): Record<any> {
if (isValueProvider(provider)) {
return makeRecord(undefined, provider.useValue);
} else {
const factory: (() => any) | undefined = providerToFactory(provider);
return makeRecord(factory, NOT_YET);
}
}
/**
* Converts a `SingleProvider` into a factory function.
*
* @param provider provider to convert to factory
*/
export function providerToFactory(
provider: SingleProvider,
ngModuleType?: InjectorType<any>,
providers?: any[],
): () => any {
let factory: (() => any) | undefined = undefined;
if (ngDevMode && isEnvironmentProviders(provider)) {
throwInvalidProviderError(undefined, providers, provider);
}
if (isTypeProvider(provider)) {
const unwrappedProvider = resolveForwardRef(provider);
return getFactoryDef(unwrappedProvider) || injectableDefOrInjectorDefFactory(unwrappedProvider);
} else {
if (isValueProvider(provider)) {
factory = () => resolveForwardRef(provider.useValue);
} else if (isFactoryProvider(provider)) {
factory = () => provider.useFactory(...injectArgs(provider.deps || []));
} else if (isExistingProvider(provider)) {
factory = () => ɵɵinject(resolveForwardRef(provider.useExisting));
} else {
const classRef = resolveForwardRef(
provider &&
((provider as StaticClassProvider | ClassProvider).useClass || provider.provide),
);
if (ngDevMode && !classRef) {
throwInvalidProviderError(ngModuleType, providers, provider);
}
if (hasDeps(provider)) {
factory = () => new classRef(...injectArgs(provider.deps));
} else {
return getFactoryDef(classRef) || injectableDefOrInjectorDefFactory(classRef);
}
}
}
return factory;
}
export function assertNotDestroyed(injector: R3Injector): void {
if (injector.destroyed) {
throw new RuntimeError(
RuntimeErrorCode.INJECTOR_ALREADY_DESTROYED,
ngDevMode && 'Injector has already been destroyed.',
);
}
}
function makeRecord<T>(
factory: (() => T) | undefined,
value: T | {},
multi: boolean = false,
): Record<T> {
return {
factory: factory,
value: value,
multi: multi ? [] : undefined,
};
}
function hasDeps(
value: ClassProvider | ConstructorProvider | StaticClassProvider,
): value is ClassProvider & {deps: any[]} {
return !!(value as any).deps;
}
function hasOnDestroy(value: any): value is OnDestroy {
return (
value !== null &&
typeof value === 'object' &&
typeof (value as OnDestroy).ngOnDestroy === 'function'
);
}
function couldBeInjectableType(value: any): value is ProviderToken<any> {
return (
typeof value === 'function' || (typeof value === 'object' && value instanceof InjectionToken)
);
}
function forEachSingleProvider(
providers: Array<Provider | EnvironmentProviders>,
fn: (provider: SingleProvider) => void,
): void {
for (const provider of providers) {
if (Array.isArray(provider)) {
forEachSingleProvider(provider, fn);
} else if (provider && isEnvironmentProviders(provider)) {
forEachSingleProvider(provider.ɵproviders, fn);
} else {
fn(provider as SingleProvider);
}
}
}
| {
"end_byte": 23295,
"start_byte": 14660,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/di/r3_injector.ts"
} |
angular/packages/core/src/di/initializer_token.ts_0_805 | /**
* @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 {InjectionToken} from './injection_token';
/**
* A multi-provider token for initialization functions that will run upon construction of an
* environment injector.
*
* @deprecated from v19.0.0, use provideEnvironmentInitializer instead
*
* @see {@link provideEnvironmentInitializer}
*
* Note: As opposed to the `APP_INITIALIZER` token, the `ENVIRONMENT_INITIALIZER` functions are not awaited,
* hence they should not be `async`.
*
* @publicApi
*/
export const ENVIRONMENT_INITIALIZER = new InjectionToken<ReadonlyArray<() => void>>(
ngDevMode ? 'ENVIRONMENT_INITIALIZER' : '',
);
| {
"end_byte": 805,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/di/initializer_token.ts"
} |
angular/packages/core/src/di/inject_switch.ts_0_2734 | /**
* @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 {throwProviderNotFoundError} from '../render3/errors_di';
import {assertNotEqual} from '../util/assert';
import {stringify} from '../util/stringify';
import {getInjectableDef, ɵɵInjectableDeclaration} from './interface/defs';
import {InjectFlags} from './interface/injector';
import {ProviderToken} from './provider_token';
/**
* Current implementation of inject.
*
* By default, it is `injectInjectorOnly`, which makes it `Injector`-only aware. It can be changed
* to `directiveInject`, which brings in the `NodeInjector` system of ivy. It is designed this
* way for two reasons:
* 1. `Injector` should not depend on ivy logic.
* 2. To maintain tree shake-ability we don't want to bring in unnecessary code.
*/
let _injectImplementation:
| (<T>(token: ProviderToken<T>, flags?: InjectFlags) => T | null)
| undefined;
export function getInjectImplementation() {
return _injectImplementation;
}
/**
* Sets the current inject implementation.
*/
export function setInjectImplementation(
impl: (<T>(token: ProviderToken<T>, flags?: InjectFlags) => T | null) | undefined,
): (<T>(token: ProviderToken<T>, flags?: InjectFlags) => T | null) | undefined {
const previous = _injectImplementation;
_injectImplementation = impl;
return previous;
}
/**
* Injects `root` tokens in limp mode.
*
* If no injector exists, we can still inject tree-shakable providers which have `providedIn` set to
* `"root"`. This is known as the limp mode injection. In such case the value is stored in the
* injectable definition.
*/
export function injectRootLimpMode<T>(
token: ProviderToken<T>,
notFoundValue: T | undefined,
flags: InjectFlags,
): T | null {
const injectableDef: ɵɵInjectableDeclaration<T> | null = getInjectableDef(token);
if (injectableDef && injectableDef.providedIn == 'root') {
return injectableDef.value === undefined
? (injectableDef.value = injectableDef.factory())
: injectableDef.value;
}
if (flags & InjectFlags.Optional) return null;
if (notFoundValue !== undefined) return notFoundValue;
throwProviderNotFoundError(token, 'Injector');
}
/**
* Assert that `_injectImplementation` is not `fn`.
*
* This is useful, to prevent infinite recursion.
*
* @param fn Function which it should not equal to
*/
export function assertInjectImplementationNotEqual(
fn: <T>(token: ProviderToken<T>, flags?: InjectFlags) => T | null,
) {
ngDevMode &&
assertNotEqual(_injectImplementation, fn, 'Calling ɵɵinject would cause infinite recursion');
}
| {
"end_byte": 2734,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/di/inject_switch.ts"
} |
angular/packages/core/src/di/forward_ref.ts_0_2739 | /**
* @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} from '../interface/type';
import {getClosureSafeProperty} from '../util/property';
import {stringify} from '../util/stringify';
/**
* An interface that a function passed into `forwardRef` has to implement.
*
* @usageNotes
* ### Example
*
* {@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref_fn'}
* @publicApi
*/
export interface ForwardRefFn {
(): any;
}
const __forward_ref__ = getClosureSafeProperty({__forward_ref__: getClosureSafeProperty});
/**
* Allows to refer to references which are not yet defined.
*
* For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of
* DI is declared, but not yet defined. It is also used when the `token` which we use when creating
* a query is not yet defined.
*
* `forwardRef` is also used to break circularities in standalone components imports.
*
* @usageNotes
* ### Circular dependency example
* {@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref'}
*
* ### Circular standalone reference import example
* ```ts
* @Component({
* standalone: true,
* imports: [ChildComponent],
* selector: 'app-parent',
* template: `<app-child [hideParent]="hideParent"></app-child>`,
* })
* export class ParentComponent {
* @Input() hideParent: boolean;
* }
*
*
* @Component({
* standalone: true,
* imports: [CommonModule, forwardRef(() => ParentComponent)],
* selector: 'app-child',
* template: `<app-parent *ngIf="!hideParent"></app-parent>`,
* })
* export class ChildComponent {
* @Input() hideParent: boolean;
* }
* ```
*
* @publicApi
*/
export function forwardRef(forwardRefFn: ForwardRefFn): Type<any> {
(<any>forwardRefFn).__forward_ref__ = forwardRef;
(<any>forwardRefFn).toString = function () {
return stringify(this());
};
return <Type<any>>(<any>forwardRefFn);
}
/**
* Lazily retrieves the reference value from a forwardRef.
*
* Acts as the identity function when given a non-forward-ref value.
*
* @usageNotes
* ### Example
*
* {@example core/di/ts/forward_ref/forward_ref_spec.ts region='resolve_forward_ref'}
*
* @see {@link forwardRef}
* @publicApi
*/
export function resolveForwardRef<T>(type: T): T {
return isForwardRef(type) ? type() : type;
}
/** Checks whether a function is wrapped by a `forwardRef`. */
export function isForwardRef(fn: any): fn is () => any {
return (
typeof fn === 'function' &&
fn.hasOwnProperty(__forward_ref__) &&
fn.__forward_ref__ === forwardRef
);
}
| {
"end_byte": 2739,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/di/forward_ref.ts"
} |
angular/packages/core/src/di/host_tag_name_token.ts_0_2407 | /**
* @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 {RuntimeError, RuntimeErrorCode} from '../errors';
import {TNode, TNodeType} from '../render3/interfaces/node';
import {getCurrentTNode} from '../render3/state';
import {InjectionToken} from './injection_token';
import {InjectFlags} from './interface/injector';
/**
* A token that can be used to inject the tag name of the host node.
*
* @usageNotes
* ### Injecting a tag name that is known to exist
* ```typescript
* @Directive()
* class MyDir {
* tagName: string = inject(HOST_TAG_NAME);
* }
* ```
*
* ### Optionally injecting a tag name
* ```typescript
* @Directive()
* class MyDir {
* tagName: string | null = inject(HOST_TAG_NAME, {optional: true});
* }
* ```
* @publicApi
*/
export const HOST_TAG_NAME = new InjectionToken<string>(ngDevMode ? 'HOST_TAG_NAME' : '');
// HOST_TAG_NAME should be resolved at the current node, similar to e.g. ElementRef,
// so we manually specify __NG_ELEMENT_ID__ here, instead of using a factory.
// tslint:disable-next-line:no-toplevel-property-access
(HOST_TAG_NAME as any).__NG_ELEMENT_ID__ = (flags: InjectFlags) => {
const tNode = getCurrentTNode();
if (tNode === null) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_INJECTION_TOKEN,
ngDevMode &&
'HOST_TAG_NAME can only be injected in directives and components ' +
'during construction time (in a class constructor or as a class field initializer)',
);
}
if (tNode.type & TNodeType.Element) {
return tNode.value;
}
if (flags & InjectFlags.Optional) {
return null;
}
throw new RuntimeError(
RuntimeErrorCode.INVALID_INJECTION_TOKEN,
ngDevMode &&
`HOST_TAG_NAME was used on ${getDevModeNodeName(
tNode,
)} which doesn't have an underlying element in the DOM. ` +
`This is invalid, and so the dependency should be marked as optional.`,
);
};
function getDevModeNodeName(tNode: TNode) {
if (tNode.type & TNodeType.ElementContainer) {
return 'an <ng-container>';
} else if (tNode.type & TNodeType.Container) {
return 'an <ng-template>';
} else if (tNode.type & TNodeType.LetDeclaration) {
return 'an @let declaration';
} else {
return 'a node';
}
}
| {
"end_byte": 2407,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/di/host_tag_name_token.ts"
} |
angular/packages/core/src/di/host_attribute_token.ts_0_1028 | /*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ɵɵinjectAttribute} from '../render3/instructions/di_attr';
/**
* Creates a token that can be used to inject static attributes of the host node.
*
* @usageNotes
* ### Injecting an attribute that is known to exist
* ```typescript
* @Directive()
* class MyDir {
* attr: string = inject(new HostAttributeToken('some-attr'));
* }
* ```
*
* ### Optionally injecting an attribute
* ```typescript
* @Directive()
* class MyDir {
* attr: string | null = inject(new HostAttributeToken('some-attr'), {optional: true});
* }
* ```
* @publicApi
*/
export class HostAttributeToken {
constructor(private attributeName: string) {}
/** @internal */
__NG_ELEMENT_ID__ = () => ɵɵinjectAttribute(this.attributeName);
toString(): string {
return `HostAttributeToken ${this.attributeName}`;
}
}
| {
"end_byte": 1028,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/di/host_attribute_token.ts"
} |
angular/packages/core/src/di/injector.ts_0_5173 | /**
* @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 {createInjector} from './create_injector';
import {THROW_IF_NOT_FOUND, ɵɵinject} from './injector_compatibility';
import {InjectorMarkers} from './injector_marker';
import {INJECTOR} from './injector_token';
import {ɵɵdefineInjectable} from './interface/defs';
import {InjectFlags, InjectOptions} from './interface/injector';
import {Provider, StaticProvider} from './interface/provider';
import {NullInjector} from './null_injector';
import {ProviderToken} from './provider_token';
/**
* Concrete injectors implement this interface. Injectors are configured
* with [providers](guide/di/dependency-injection-providers) that associate
* dependencies of various types with [injection tokens](guide/di/dependency-injection-providers).
*
* @see [DI Providers](guide/di/dependency-injection-providers).
* @see {@link StaticProvider}
*
* @usageNotes
*
* The following example creates a service injector instance.
*
* {@example core/di/ts/provider_spec.ts region='ConstructorProvider'}
*
* ### Usage example
*
* {@example core/di/ts/injector_spec.ts region='Injector'}
*
* `Injector` returns itself when given `Injector` as a token:
*
* {@example core/di/ts/injector_spec.ts region='injectInjector'}
*
* @publicApi
*/
export abstract class Injector {
static THROW_IF_NOT_FOUND = THROW_IF_NOT_FOUND;
static NULL: Injector = /* @__PURE__ */ new NullInjector();
/**
* Internal note on the `options?: InjectOptions|InjectFlags` override of the `get`
* method: consider dropping the `InjectFlags` part in one of the major versions.
* It can **not** be done in minor/patch, since it's breaking for custom injectors
* that only implement the old `InjectorFlags` interface.
*/
/**
* Retrieves an instance from the injector based on the provided token.
* @returns The instance from the injector if defined, otherwise the `notFoundValue`.
* @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.
*/
abstract get<T>(
token: ProviderToken<T>,
notFoundValue: undefined,
options: InjectOptions & {
optional?: false;
},
): T;
/**
* Retrieves an instance from the injector based on the provided token.
* @returns The instance from the injector if defined, otherwise the `notFoundValue`.
* @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.
*/
abstract get<T>(
token: ProviderToken<T>,
notFoundValue: null | undefined,
options: InjectOptions,
): T | null;
/**
* Retrieves an instance from the injector based on the provided token.
* @returns The instance from the injector if defined, otherwise the `notFoundValue`.
* @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.
*/
abstract get<T>(
token: ProviderToken<T>,
notFoundValue?: T,
options?: InjectOptions | InjectFlags,
): T;
/**
* Retrieves an instance from the injector based on the provided token.
* @returns The instance from the injector if defined, otherwise the `notFoundValue`.
* @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.
* @deprecated use object-based flags (`InjectOptions`) instead.
*/
abstract get<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): T;
/**
* @deprecated from v4.0.0 use ProviderToken<T>
* @suppress {duplicate}
*/
abstract get(token: any, notFoundValue?: any): any;
/**
* @deprecated from v5 use the new signature Injector.create(options)
*/
static create(providers: StaticProvider[], parent?: Injector): Injector;
/**
* Creates a new injector instance that provides one or more dependencies,
* according to a given type or types of `StaticProvider`.
*
* @param options An object with the following properties:
* * `providers`: An array of providers of the [StaticProvider type](api/core/StaticProvider).
* * `parent`: (optional) A parent injector.
* * `name`: (optional) A developer-defined identifying name for the new injector.
*
* @returns The new injector instance.
*
*/
static create(options: {
providers: Array<Provider | StaticProvider>;
parent?: Injector;
name?: string;
}): Injector;
static create(
options:
| StaticProvider[]
| {providers: Array<Provider | StaticProvider>; parent?: Injector; name?: string},
parent?: Injector,
): Injector {
if (Array.isArray(options)) {
return createInjector({name: ''}, parent, options, '');
} else {
const name = options.name ?? '';
return createInjector({name}, options.parent, options.providers, name);
}
}
/** @nocollapse */
static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
token: Injector,
providedIn: 'any',
factory: () => ɵɵinject(INJECTOR),
});
/**
* @internal
* @nocollapse
*/
static __NG_ELEMENT_ID__ = InjectorMarkers.Injector;
}
| {
"end_byte": 5173,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/di/injector.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.