_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/core/schematics/migrations/signal-migration/src/batch/merge_unit_data.ts_0_5206 | /**
* @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 {
FieldIncompatibilityReason,
pickFieldIncompatibility,
} from '../passes/problematic_patterns/incompatibility';
import {GraphNode, topologicalSort} from '../utils/inheritance_sort';
import {CompilationUnitData} from './unit_data';
type InputData = {key: string; info: CompilationUnitData['knownInputs'][string]};
/** Merges a list of compilation units into a combined unit. */
export function combineCompilationUnitData(
unitA: CompilationUnitData,
unitB: CompilationUnitData,
): CompilationUnitData {
const result: CompilationUnitData = {
knownInputs: {},
};
for (const file of [unitA, unitB]) {
for (const [key, info] of Object.entries(file.knownInputs)) {
const existing = result.knownInputs[key];
if (existing === undefined) {
result.knownInputs[key] = info;
continue;
}
// Merge metadata.
if (existing.extendsFrom === null && info.extendsFrom !== null) {
existing.extendsFrom = info.extendsFrom;
}
if (!existing.seenAsSourceInput && info.seenAsSourceInput) {
existing.seenAsSourceInput = true;
}
// Merge member incompatibility.
if (info.memberIncompatibility !== null) {
if (existing.memberIncompatibility === null) {
existing.memberIncompatibility = info.memberIncompatibility;
} else {
// Input might not be incompatible in one target, but others might invalidate it.
// merge the incompatibility state.
existing.memberIncompatibility = pickFieldIncompatibility(
{reason: info.memberIncompatibility, context: null},
{reason: existing.memberIncompatibility, context: null},
).reason;
}
}
// Merge incompatibility of the class owning the input.
// Note: This metadata is stored per field for simplicity currently,
// but in practice it could be a separate field in the compilation data.
if (
info.owningClassIncompatibility !== null &&
existing.owningClassIncompatibility === null
) {
existing.owningClassIncompatibility = info.owningClassIncompatibility;
}
}
}
return result;
}
export function convertToGlobalMeta(combinedData: CompilationUnitData): CompilationUnitData {
const globalMeta: CompilationUnitData = {
knownInputs: {},
};
const idToGraphNode = new Map<string, GraphNode<InputData>>();
const inheritanceGraph: GraphNode<InputData>[] = [];
const isNodeIncompatible = (node: InputData) =>
node.info.memberIncompatibility !== null || node.info.owningClassIncompatibility !== null;
for (const [key, info] of Object.entries(combinedData.knownInputs)) {
const existing = globalMeta.knownInputs[key];
if (existing !== undefined) {
continue;
}
const node: GraphNode<InputData> = {
incoming: new Set(),
outgoing: new Set(),
data: {info, key},
};
inheritanceGraph.push(node);
idToGraphNode.set(key, node);
globalMeta.knownInputs[key] = info;
}
for (const [key, info] of Object.entries(globalMeta.knownInputs)) {
if (info.extendsFrom !== null) {
const from = idToGraphNode.get(key)!;
const target = idToGraphNode.get(info.extendsFrom)!;
from.outgoing.add(target);
target.incoming.add(from);
}
}
// Sort topologically and iterate super classes first, so that we can trivially
// propagate incompatibility statuses (and other checks) without having to check
// in both directions (derived classes, or base classes). This simplifies the
// propagation.
for (const node of topologicalSort(inheritanceGraph).reverse()) {
const existingMemberIncompatibility =
node.data.info.memberIncompatibility !== null
? {reason: node.data.info.memberIncompatibility, context: null}
: null;
for (const parent of node.outgoing) {
// If parent is incompatible and not migrated, then this input
// cannot be migrated either. Try propagating parent incompatibility then.
if (isNodeIncompatible(parent.data)) {
node.data.info.memberIncompatibility = pickFieldIncompatibility(
{reason: FieldIncompatibilityReason.ParentIsIncompatible, context: null},
existingMemberIncompatibility,
).reason;
break;
}
}
}
for (const info of Object.values(combinedData.knownInputs)) {
// We never saw a source file for this input, globally. Try marking it as incompatible,
// so that all references and inheritance checks can propagate accordingly.
if (!info.seenAsSourceInput) {
const existingMemberIncompatibility =
info.memberIncompatibility !== null
? {reason: info.memberIncompatibility, context: null}
: null;
info.memberIncompatibility = pickFieldIncompatibility(
{reason: FieldIncompatibilityReason.OutsideOfMigrationScope, context: null},
existingMemberIncompatibility,
).reason;
}
}
return globalMeta;
}
| {
"end_byte": 5206,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/batch/merge_unit_data.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/src/batch/test_bin.ts_0_2164 | /**
* @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 fs from 'fs';
import path from 'path';
import {executeAnalyzePhase} from '../../../../utils/tsurge/executors/analyze_exec';
import {executeMigratePhase} from '../../../../utils/tsurge/executors/migrate_exec';
import {SignalInputMigration} from '../migration';
import {writeMigrationReplacements} from '../write_replacements';
import {CompilationUnitData} from './unit_data';
import {executeGlobalMetaPhase} from '../../../../utils/tsurge/executors/global_meta_exec';
import {synchronouslyCombineUnitData} from '../../../../utils/tsurge/helpers/combine_units';
main().catch((e) => {
console.error(e);
process.exitCode = 1;
});
async function main() {
const [mode, ...args] = process.argv.slice(2);
const migration = new SignalInputMigration({insertTodosForSkippedFields: true});
if (mode === 'extract') {
const analyzeResult = await executeAnalyzePhase(migration, path.resolve(args[0]));
process.stdout.write(JSON.stringify(analyzeResult));
} else if (mode === 'combine-all') {
const unitPromises = args.map((f) => readUnitMeta(path.resolve(f)));
const units = await Promise.all(unitPromises);
const mergedResult = await synchronouslyCombineUnitData(migration, units);
process.stdout.write(JSON.stringify(mergedResult));
} else if (mode === 'global-meta') {
const metaResult = await executeGlobalMetaPhase(migration, await readUnitMeta(args[0]));
process.stdout.write(JSON.stringify(metaResult));
} else if (mode === 'migrate') {
const {replacements, projectRoot} = await executeMigratePhase(
migration,
JSON.parse(fs.readFileSync(path.resolve(args[1]), 'utf8')) as CompilationUnitData,
path.resolve(args[0]),
);
writeMigrationReplacements(replacements, projectRoot);
}
}
async function readUnitMeta(filePath: string): Promise<CompilationUnitData> {
return fs.promises
.readFile(filePath, 'utf8')
.then((data) => JSON.parse(data) as CompilationUnitData);
}
| {
"end_byte": 2164,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/batch/test_bin.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/src/flow_analysis/flow_node_internals.ts_0_4209 | /**
* @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: This file contains derived code from original sources
// created by Microsoft, licensed under an Apache License.
// This is the formal `NOTICE` for the modified/copied code.
// Original license: https://github.com/microsoft/TypeScript/blob/main/LICENSE.txt.
// Original ref: https://github.com/microsoft/TypeScript/pull/58036
import ts from 'typescript';
/** @internal */
export enum FlowFlags {
Unreachable = 1 << 0, // Unreachable code
Start = 1 << 1, // Start of flow graph
BranchLabel = 1 << 2, // Non-looping junction
LoopLabel = 1 << 3, // Looping junction
Assignment = 1 << 4, // Assignment
TrueCondition = 1 << 5, // Condition known to be true
FalseCondition = 1 << 6, // Condition known to be false
SwitchClause = 1 << 7, // Switch statement clause
ArrayMutation = 1 << 8, // Potential array mutation
Call = 1 << 9, // Potential assertion call
ReduceLabel = 1 << 10, // Temporarily reduce antecedents of label
Referenced = 1 << 11, // Referenced as antecedent once
Shared = 1 << 12, // Referenced as antecedent more than once
Label = BranchLabel | LoopLabel,
Condition = TrueCondition | FalseCondition,
}
/** @internal */
export type FlowNode =
| FlowUnreachable
| FlowStart
| FlowLabel
| FlowAssignment
| FlowCondition
| FlowSwitchClause
| FlowArrayMutation
| FlowCall
| FlowReduceLabel;
/** @internal */
export interface FlowNodeBase {
flags: FlowFlags;
id: number; // Node id used by flow type cache in checker
node: unknown; // Node or other data
antecedent: FlowNode | FlowNode[] | undefined;
}
/** @internal */
export interface FlowUnreachable extends FlowNodeBase {
node: undefined;
antecedent: undefined;
}
// FlowStart represents the start of a control flow. For a function expression or arrow
// function, the node property references the function (which in turn has a flowNode
// property for the containing control flow).
/** @internal */
export interface FlowStart extends FlowNodeBase {
node:
| ts.FunctionExpression
| ts.ArrowFunction
| ts.MethodDeclaration
| ts.GetAccessorDeclaration
| ts.SetAccessorDeclaration
| undefined;
antecedent: undefined;
}
// FlowLabel represents a junction with multiple possible preceding control flows.
/** @internal */
export interface FlowLabel extends FlowNodeBase {
node: undefined;
antecedent: FlowNode[] | undefined;
}
// FlowAssignment represents a node that assigns a value to a narrowable reference,
// i.e. an identifier or a dotted name that starts with an identifier or 'this'.
/** @internal */
export interface FlowAssignment extends FlowNodeBase {
node: ts.Expression | ts.VariableDeclaration | ts.BindingElement;
antecedent: FlowNode;
}
/** @internal */
export interface FlowCall extends FlowNodeBase {
node: ts.CallExpression;
antecedent: FlowNode;
}
// FlowCondition represents a condition that is known to be true or false at the
// node's location in the control flow.
/** @internal */
export interface FlowCondition extends FlowNodeBase {
node: ts.Expression;
antecedent: FlowNode;
}
// dprint-ignore
/** @internal */
export interface FlowSwitchClause extends FlowNodeBase {
node: FlowSwitchClauseData;
antecedent: FlowNode;
}
/** @internal */
export interface FlowSwitchClauseData {
switchStatement: ts.SwitchStatement;
clauseStart: number; // Start index of case/default clause range
clauseEnd: number; // End index of case/default clause range
}
// FlowArrayMutation represents a node potentially mutates an array, i.e. an
// operation of the form 'x.push(value)', 'x.unshift(value)' or 'x[n] = value'.
/** @internal */
export interface FlowArrayMutation extends FlowNodeBase {
node: ts.CallExpression | ts.BinaryExpression;
antecedent: FlowNode;
}
/** @internal */
export interface FlowReduceLabel extends FlowNodeBase {
node: FlowReduceLabelData;
antecedent: FlowNode;
}
/** @internal */
export interface FlowReduceLabelData {
target: FlowLabel;
antecedents: FlowNode[];
}
| {
"end_byte": 4209,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/flow_analysis/flow_node_internals.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/src/flow_analysis/flow_node_traversal.ts_0_5046 | /**
* @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 {
FlowArrayMutation,
FlowAssignment,
FlowCall,
FlowCondition,
FlowFlags,
FlowLabel,
FlowNode,
FlowReduceLabel,
FlowSwitchClause,
} from './flow_node_internals';
/**
* Traverses the graph of the TypeScript flow nodes, exploring all possible branches
* and keeps track of interesting nodes that may contribute to "narrowing".
*
* This allows us to figure out which nodes may be narrowed or not, and need
* temporary variables in the migration to allowing narrowing to continue working.
*
* Some resources on flow nodes by TypeScript:
* https://effectivetypescript.com/2024/03/24/flownodes/.
*/
export function traverseFlowForInterestingNodes(flow: FlowNode): ts.Node[] | null {
let flowDepth = 0;
let interestingNodes: ts.Node[] = [];
const queue = new Set<FlowNode>([flow]);
// Queue is evolved during iteration, and new items will be added
// to the end of the iteration. Effectively implementing a queue
// with deduping out of the box.
for (const flow of queue) {
if (++flowDepth === 2000) {
// We have made 2000 recursive invocations. To avoid overflowing the call stack we report an
// error and disable further control flow analysis in the containing function or module body.
return interestingNodes;
}
const flags = flow.flags;
if (flags & FlowFlags.Assignment) {
const assignment = flow as FlowAssignment;
queue.add(assignment.antecedent);
if (ts.isVariableDeclaration(assignment.node)) {
interestingNodes.push(assignment.node.name);
} else if (ts.isBindingElement(assignment.node)) {
interestingNodes.push(assignment.node.name);
} else {
interestingNodes.push(assignment.node);
}
} else if (flags & FlowFlags.Call) {
queue.add((flow as FlowCall).antecedent);
// Arguments can be narrowed using `FlowCall`s.
// See: node_modules/typescript/stable/src/compiler/checker.ts;l=28786-28810
interestingNodes.push(...(flow as FlowCall).node.arguments);
} else if (flags & FlowFlags.Condition) {
queue.add((flow as FlowCondition).antecedent);
interestingNodes.push((flow as FlowCondition).node);
} else if (flags & FlowFlags.SwitchClause) {
queue.add((flow as FlowSwitchClause).antecedent);
// The switch expression can be narrowed, so it's an interesting node.
interestingNodes.push((flow as FlowSwitchClause).node.switchStatement.expression);
} else if (flags & FlowFlags.Label) {
// simple label, a single ancestor.
if ((flow as FlowLabel).antecedent?.length === 1) {
queue.add((flow as FlowLabel).antecedent![0]);
continue;
}
if (flags & FlowFlags.BranchLabel) {
// Normal branches. e.g. switch.
for (const f of (flow as FlowLabel).antecedent ?? []) {
queue.add(f);
}
} else {
// Branch for loops.
// The first antecedent always points to the flow node before the loop
// was entered. All other narrowing expressions, if present, are direct
// antecedents of the starting flow node, so we only need to look at the first.
// See: node_modules/typescript/stable/src/compiler/checker.ts;l=28108-28109
queue.add((flow as FlowLabel).antecedent![0]);
}
} else if (flags & FlowFlags.ArrayMutation) {
queue.add((flow as FlowArrayMutation).antecedent);
// Array mutations are never interesting for inputs, as we cannot migrate
// assignments to inputs.
} else if (flags & FlowFlags.ReduceLabel) {
// reduce label is a try/catch re-routing.
// visit all possible branches.
// TODO: explore this more.
// See: node_modules/typescript/stable/src/compiler/binder.ts;l=1636-1649.
queue.add((flow as FlowReduceLabel).antecedent);
for (const f of (flow as FlowReduceLabel).node.antecedents) {
queue.add(f);
}
} else if (flags & FlowFlags.Start) {
// Note: TS itself only ever continues with parent control flows, if the pre-determined `flowContainer`
// of the referenced is different. E.g. narrowing might decide to choose a higher flow container if we
// reference a constant. In which case, TS allows escaping the flow container for narrowing. See:
// http://google3/third_party/javascript/node_modules/typescript/stable/src/compiler/checker.ts;l=29399-29414;rcl=623599846.
// and TypeScript's `narrowedConstInMethod` baseline test.
// --> We don't need this as an input cannot be a constant!
return interestingNodes;
} else {
break;
}
}
return null;
}
/** Gets the flow node for the given node. */
export function getFlowNode(node: ts.FlowContainer & {flowNode?: FlowNode}): FlowNode | null {
return node.flowNode ?? null;
}
| {
"end_byte": 5046,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/flow_analysis/flow_node_traversal.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/src/flow_analysis/flow_containers.ts_0_1556 | /**
* @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';
/**
* Whether the given node represents a control flow container boundary.
* E.g. variables cannot be narrowed when descending into children of `node`.
*/
export function isControlFlowBoundary(node: ts.Node): boolean {
return (
(ts.isFunctionLike(node) && !getImmediatelyInvokedFunctionExpression(node)) ||
node.kind === ts.SyntaxKind.ModuleBlock ||
node.kind === ts.SyntaxKind.SourceFile ||
node.kind === ts.SyntaxKind.PropertyDeclaration
);
}
/** Determines the current flow container of a given node. */
export function getControlFlowContainer(node: ts.Node): ts.Node {
return ts.findAncestor(node.parent, (node) => isControlFlowBoundary(node))!;
}
/** Checks whether the given node refers to an IIFE declaration. */
function getImmediatelyInvokedFunctionExpression(func: ts.Node): ts.CallExpression | undefined {
if (func.kind === ts.SyntaxKind.FunctionExpression || func.kind === ts.SyntaxKind.ArrowFunction) {
let prev = func;
let parent = func.parent;
while (parent.kind === ts.SyntaxKind.ParenthesizedExpression) {
prev = parent;
parent = parent.parent;
}
if (
parent.kind === ts.SyntaxKind.CallExpression &&
(parent as ts.CallExpression).expression === prev
) {
return parent as ts.CallExpression;
}
}
return undefined;
}
| {
"end_byte": 1556,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/flow_analysis/flow_containers.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/src/flow_analysis/index.ts_0_8676 | /**
* @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 {getControlFlowContainer, isControlFlowBoundary} from './flow_containers';
import {getFlowNode, traverseFlowForInterestingNodes} from './flow_node_traversal';
import {unwrapParent} from '../utils/unwrap_parent';
import assert from 'assert';
/**
* Type describing an index of a node inside a control flow
* container.
*/
export type ControlFlowNodeIndex = number;
/**
* Representation of a reference inside a control flow
* container.
*
* This node structure is used to link multiple nodes together
* that may be narrowed, as an example.
*/
export interface ControlFlowAnalysisNode {
/** Unique id of the node inside the container. */
id: number;
/** Original TypeScript node of the reference in the container. */
originalNode: ts.Identifier;
/**
* Recommended node for the reference in the container. For example:
* - may be "preserve" to indicate it's not narrowed.
* - may point to a different flow node. This means they will share for narrowing.
* - may point to a block, source file or arrow function to indicate at what level this
* node may be shared. I.e. a location where we generate the temporary variable
* for subsequent sharing.
*/
recommendedNode:
| ControlFlowNodeIndex
| 'preserve'
| (ts.Block | ts.SourceFile | ts.ArrowFunction);
/** Flow container this reference is part of. */
flowContainer: ts.Node;
}
/** Type describing a map from reference to its flow information. */
type ReferenceMetadata = Map<
ts.Identifier,
{
resultIndex: number;
flowContainer: ts.Node;
}
>;
/**
* Analyzes the control flow of a list of references and returns
* information about which nodes can be shared via a temporary variable
* to enable narrowing.
*
* E.g. consider the following snippet:
*
* ```
* someMethod() {
* if (this.bla) {
* this.bla.charAt(0);
* }
* }
* ```
*
* The analysis would inform the caller that `this.bla.charAt` can
* be shared with the `this.bla` of the `if` condition.
*
* This is useful for the signal migration as it allows us to efficiently,
* and minimally transform references into shared variables where needed.
* Needed because signals are not narrowable by default, as they are functions.
*/
export function analyzeControlFlow(
entries: ts.Identifier[],
checker: ts.TypeChecker,
): ControlFlowAnalysisNode[] {
const result: ControlFlowAnalysisNode[] = [];
const referenceToMetadata: ReferenceMetadata = new Map();
// Prepare easy lookups for reference nodes to flow info.
for (const [idx, entry] of entries.entries()) {
referenceToMetadata.set(entry, {
flowContainer: getControlFlowContainer(entry),
resultIndex: idx,
});
}
for (const entry of entries) {
const {flowContainer, resultIndex} = referenceToMetadata.get(entry)!;
const flowPathInterestingNodes = traverseFlowForInterestingNodes(getFlowNode(entry)!);
assert(
flowContainer !== null && flowPathInterestingNodes !== null,
'Expected a flow container to exist.',
);
const narrowPartners = getAllMatchingReferencesInFlowPath(
flowPathInterestingNodes,
entry,
referenceToMetadata,
flowContainer,
checker,
);
result.push({
id: resultIndex,
originalNode: entry,
flowContainer,
recommendedNode: 'preserve',
});
if (narrowPartners.length !== 0) {
connectSharedReferences(result, narrowPartners, resultIndex);
}
}
return result;
}
/**
* Iterates through all partner flow nodes and connects them so that
* the first node will act as the share partner, while all subsequent
* nodes will point to the share node.
*/
function connectSharedReferences(
result: ControlFlowAnalysisNode[],
flowPartners: number[],
refId: number,
) {
const refFlowContainer = result[refId].flowContainer;
// Inside the list of flow partners (i.e. references to the same target),
// find the node that is the first one in the flow container (via its start pos).
let earliestPartner: ts.Node | null = null;
let earliestPartnerId: number | null = null;
for (const partnerId of flowPartners) {
if (
earliestPartner === null ||
result[partnerId].originalNode.getStart() < earliestPartner.getStart()
) {
earliestPartner = result[partnerId].originalNode;
earliestPartnerId = partnerId;
}
}
assert(earliestPartner !== null, 'Expected an earliest partner to be found.');
assert(earliestPartnerId !== null, 'Expected an earliest partner to be found.');
// Then, incorporate all similar references (or flow nodes) in between
// the reference and the earliest partner. References in between can also
// use the shared flow node and not preserve their original reference— as
// this would be rather unreadable and inefficient.
let highestBlock: ts.Block | ts.SourceFile | ts.ArrowFunction | null = null;
for (let i = earliestPartnerId; i <= refId; i++) {
// Different flow container captured sequentially in result. Ignore.
if (result[i].flowContainer !== refFlowContainer) {
continue;
}
// Iterate up the block, find the highest block within the flow container.
let block: ts.Node = result[i].originalNode.parent;
while (!isBlockLikeAncestor(block)) {
block = block.parent;
}
if (highestBlock === null || block.getStart() < highestBlock.getStart()) {
highestBlock = block;
}
if (i !== earliestPartnerId) {
result[i].recommendedNode = earliestPartnerId;
}
}
assert(highestBlock, 'Expected a block anchor to be found');
result[earliestPartnerId].recommendedNode = highestBlock;
}
function isBlockLikeAncestor(node: ts.Node): node is ts.ArrowFunction | ts.Block | ts.SourceFile {
// Note: Arrow functions may not have a block, but instead use an expression
// directly. This still signifies a "block" as we can convert the concise body
// to a block.
return ts.isSourceFile(node) || ts.isBlock(node) || ts.isArrowFunction(node);
}
/**
* Looks through the flow path and interesting nodes to determine which
* of the potential "interesting" nodes point to the same reference.
*
* These nodes are then considered "partners" and will be returned via
* their IDs (or practically their result indices).
*/
function getAllMatchingReferencesInFlowPath(
flowPathInterestingNodes: ts.Node[],
reference: ts.Identifier,
referenceToMetadata: ReferenceMetadata,
restrainingFlowContainer: ts.Node,
checker: ts.TypeChecker,
): number[] {
const partners: number[] = [];
for (const flowNode of flowPathInterestingNodes) {
// quick naive perf-optimized check to see if the flow node has a potential
// similar reference.
if (!flowNode.getText().includes(reference.getText())) {
continue;
}
const similarRefNodeId = findSimilarReferenceNode(
flowNode,
reference,
referenceToMetadata,
restrainingFlowContainer,
checker,
);
if (similarRefNodeId !== null) {
partners.push(similarRefNodeId);
}
}
return partners;
}
/**
* Checks if the given node contains an identifier that
* matches the given reference. If so, returns its flow ID.
*/
function findSimilarReferenceNode(
start: ts.Node,
reference: ts.Identifier,
referenceToMetadata: ReferenceMetadata,
restrainingFlowContainer: ts.Node,
checker: ts.TypeChecker,
): number | null {
return (
ts.forEachChild<{idx: number}>(start, function visitChild(node: ts.Node) {
// do not descend into control flow boundaries.
// only references sharing the same container are relevant.
// This is a performance optimization.
if (isControlFlowBoundary(node)) {
return;
}
// If this is not a potential matching identifier, check its children.
if (
!ts.isIdentifier(node) ||
referenceToMetadata.get(node)?.flowContainer !== restrainingFlowContainer
) {
return ts.forEachChild<{idx: number}>(node, visitChild);
}
// If this refers to a different instantiation of the input reference,
// continue looking.
if (!isLexicalSameReference(checker, node, reference)) {
return;
}
return {idx: referenceToMetadata.get(node)!.resultIndex};
})?.idx ?? null
);
}
/**
* Checks whether a given identifier is lexically equivalent.
* e.g. checks that they have similar property receiver accesses.
*/
f | {
"end_byte": 8676,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/flow_analysis/index.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/src/flow_analysis/index.ts_8677_9631 | nction isLexicalSameReference(
checker: ts.TypeChecker,
sharePartner: ts.Identifier,
reference: ts.Identifier,
): boolean {
const aParent = unwrapParent(reference.parent);
// If the reference is not part a property access, return true. The references
// are guaranteed symbol matches.
if (!ts.isPropertyAccessExpression(aParent) && !ts.isElementAccessExpression(aParent)) {
return sharePartner.text === reference.text;
}
// If reference parent is part of a property expression, but the share
// partner not, then this cannot be shared.
const bParent = unwrapParent(sharePartner.parent);
if (aParent.kind !== bParent.kind) {
return false;
}
const aParentExprSymbol = checker.getSymbolAtLocation(aParent.expression);
const bParentExprSymbol = checker.getSymbolAtLocation(
(bParent as ts.PropertyAccessExpression | ts.ElementAccessExpression).expression,
);
return aParentExprSymbol === bParentExprSymbol;
}
| {
"end_byte": 9631,
"start_byte": 8677,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/flow_analysis/index.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/src/input_detection/input_node.ts_0_986 | /**
* @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 {getMemberName} from '../utils/class_member_names';
/** Variants of input names supported by Angular compiler's input detection. */
export type InputNameNode = ts.Identifier | ts.StringLiteral | ts.PrivateIdentifier;
/** Describes a TypeScript node that can be an Angular `@Input()` declaration. */
export type InputNode = (ts.AccessorDeclaration | ts.PropertyDeclaration) & {
name: InputNameNode;
parent: ts.ClassDeclaration;
};
/** Checks whether the given node can be an `@Input()` declaration node. */
export function isInputContainerNode(node: ts.Node): node is InputNode {
return (
((ts.isAccessor(node) && ts.isClassDeclaration(node.parent)) ||
ts.isPropertyDeclaration(node)) &&
getMemberName(node) !== null
);
}
| {
"end_byte": 986,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/input_detection/input_node.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/src/input_detection/known_inputs.ts_0_6570 | /**
* @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 {InputDescriptor} from '../utils/input_id';
import {ExtractedInput} from './input_decorator';
import {InputNode} from './input_node';
import {DirectiveInfo} from './directive_info';
import {
ClassIncompatibilityReason,
FieldIncompatibility,
FieldIncompatibilityReason,
isFieldIncompatibility,
pickFieldIncompatibility,
} from '../passes/problematic_patterns/incompatibility';
import {ClassFieldUniqueKey, KnownFields} from '../passes/reference_resolution/known_fields';
import {attemptRetrieveInputFromSymbol} from './nodes_to_input';
import {ProgramInfo, projectFile, ProjectFile} from '../../../../utils/tsurge';
import {MigrationConfig} from '../migration_config';
import {ProblematicFieldRegistry} from '../passes/problematic_patterns/problematic_field_registry';
import {InheritanceTracker} from '../passes/problematic_patterns/check_inheritance';
/**
* Public interface describing a single known `@Input()` in the
* compilation.
*
* A known `@Input()` may be defined in sources, or inside some `d.ts` files
* loaded into the program.
*/
export type KnownInputInfo = {
file: ProjectFile;
metadata: ExtractedInput;
descriptor: InputDescriptor;
container: DirectiveInfo;
extendsFrom: InputDescriptor | null;
isIncompatible: () => boolean;
};
/**
* Registry keeping track of all known `@Input()`s in the compilation.
*
* A known `@Input()` may be defined in sources, or inside some `d.ts` files
* loaded into the program.
*/
export class KnownInputs
implements
KnownFields<InputDescriptor>,
ProblematicFieldRegistry<InputDescriptor>,
InheritanceTracker<InputDescriptor>
{
/**
* Known inputs from the whole program.
*/
knownInputIds = new Map<ClassFieldUniqueKey, KnownInputInfo>();
/** Known container classes of inputs. */
private _allClasses = new Set<ts.ClassDeclaration>();
/** Maps classes to their directive info. */
private _classToDirectiveInfo = new Map<ts.ClassDeclaration, DirectiveInfo>();
constructor(
private readonly programInfo: ProgramInfo,
private readonly config: MigrationConfig,
) {}
/** Whether the given input exists. */
has(descr: Pick<InputDescriptor, 'key'>): boolean {
return this.knownInputIds.has(descr.key);
}
/** Whether the given class contains `@Input`s. */
isInputContainingClass(clazz: ts.ClassDeclaration): boolean {
return this._classToDirectiveInfo.has(clazz);
}
/** Gets precise `@Input()` information for the given class. */
getDirectiveInfoForClass(clazz: ts.ClassDeclaration): DirectiveInfo | undefined {
return this._classToDirectiveInfo.get(clazz);
}
/** Gets known input information for the given `@Input()`. */
get(descr: Pick<InputDescriptor, 'key'>): KnownInputInfo | undefined {
return this.knownInputIds.get(descr.key);
}
/** Gets all classes containing `@Input`s in the compilation. */
getAllInputContainingClasses(): ts.ClassDeclaration[] {
return Array.from(this._allClasses.values());
}
/** Registers an `@Input()` in the registry. */
register(data: {descriptor: InputDescriptor; node: InputNode; metadata: ExtractedInput}) {
if (!this._classToDirectiveInfo.has(data.node.parent)) {
this._classToDirectiveInfo.set(data.node.parent, new DirectiveInfo(data.node.parent));
}
const directiveInfo = this._classToDirectiveInfo.get(data.node.parent)!;
const inputInfo: KnownInputInfo = {
file: projectFile(data.node.getSourceFile(), this.programInfo),
metadata: data.metadata,
descriptor: data.descriptor,
container: directiveInfo,
extendsFrom: null,
isIncompatible: () => directiveInfo.isInputMemberIncompatible(data.descriptor),
};
directiveInfo.inputFields.set(data.descriptor.key, {
descriptor: data.descriptor,
metadata: data.metadata,
});
this.knownInputIds.set(data.descriptor.key, inputInfo);
this._allClasses.add(data.node.parent);
}
/** Whether the given input is incompatible for migration. */
isFieldIncompatible(descriptor: InputDescriptor): boolean {
return !!this.get(descriptor)?.isIncompatible();
}
/** Marks the given input as incompatible for migration. */
markFieldIncompatible(input: InputDescriptor, incompatibility: FieldIncompatibility) {
if (!this.knownInputIds.has(input.key)) {
throw new Error(`Input cannot be marked as incompatible because it's not registered.`);
}
const inputInfo = this.knownInputIds.get(input.key)!;
const existingIncompatibility = inputInfo.container.getInputMemberIncompatibility(input);
// Ensure an existing more significant incompatibility is not overridden.
if (existingIncompatibility !== null && isFieldIncompatibility(existingIncompatibility)) {
incompatibility = pickFieldIncompatibility(existingIncompatibility, incompatibility);
}
this.knownInputIds
.get(input.key)!
.container.memberIncompatibility.set(input.key, incompatibility);
}
/** Marks the given class as incompatible for migration. */
markClassIncompatible(clazz: ts.ClassDeclaration, incompatibility: ClassIncompatibilityReason) {
if (!this._classToDirectiveInfo.has(clazz)) {
throw new Error(`Class cannot be marked as incompatible because it's not known.`);
}
this._classToDirectiveInfo.get(clazz)!.incompatible = incompatibility;
}
attemptRetrieveDescriptorFromSymbol(symbol: ts.Symbol): InputDescriptor | null {
return attemptRetrieveInputFromSymbol(this.programInfo, symbol, this)?.descriptor ?? null;
}
shouldTrackClassReference(clazz: ts.ClassDeclaration): boolean {
return this.isInputContainingClass(clazz);
}
captureKnownFieldInheritanceRelationship(
derived: InputDescriptor,
parent: InputDescriptor,
): void {
if (!this.has(derived)) {
throw new Error(`Expected input to exist in registry: ${derived.key}`);
}
this.get(derived)!.extendsFrom = parent;
}
captureUnknownDerivedField(field: InputDescriptor): void {
this.markFieldIncompatible(field, {
context: null,
reason: FieldIncompatibilityReason.OverriddenByDerivedClass,
});
}
captureUnknownParentField(field: InputDescriptor): void {
this.markFieldIncompatible(field, {
context: null,
reason: FieldIncompatibilityReason.TypeConflictWithBaseClass,
});
}
}
| {
"end_byte": 6570,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/input_detection/known_inputs.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/src/input_detection/input_decorator.ts_0_6019 | /**
* @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 '@angular/compiler-cli/src/ngtsc/annotations';
import {parseDecoratorInputTransformFunction} from '@angular/compiler-cli/src/ngtsc/annotations/directive';
import {FatalDiagnosticError} from '@angular/compiler-cli/src/ngtsc/diagnostics';
import {Reference, ReferenceEmitter} from '@angular/compiler-cli/src/ngtsc/imports';
import {
DecoratorInputTransform,
DtsMetadataReader,
InputMapping,
} from '@angular/compiler-cli/src/ngtsc/metadata';
import {
DynamicValue,
PartialEvaluator,
ResolvedValueMap,
} from '@angular/compiler-cli/src/ngtsc/partial_evaluator';
import {
ClassDeclaration,
Decorator,
ReflectionHost,
} from '@angular/compiler-cli/src/ngtsc/reflection';
import {CompilationMode} from '@angular/compiler-cli/src/ngtsc/transform';
import {MigrationHost} from '../migration_host';
import {InputNode, isInputContainerNode} from '../input_detection/input_node';
/** Metadata extracted of an input declaration (in `.ts` or `.d.ts` files). */
export interface ExtractedInput extends InputMapping {
inSourceFile: boolean;
inputDecorator: Decorator | null;
fieldDecorators: Decorator[];
}
/** Attempts to extract metadata of a potential TypeScript `@Input()` declaration. */
export function extractDecoratorInput(
node: ts.Node,
host: MigrationHost,
reflector: ReflectionHost,
metadataReader: DtsMetadataReader,
evaluator: PartialEvaluator,
refEmitter: ReferenceEmitter,
): ExtractedInput | null {
return (
extractSourceCodeInput(node, host, reflector, evaluator, refEmitter) ??
extractDtsInput(node, metadataReader)
);
}
/**
* Attempts to extract `@Input()` information for the given node, assuming it's
* part of a `.d.ts` file.
*/
function extractDtsInput(node: ts.Node, metadataReader: DtsMetadataReader): ExtractedInput | null {
if (
!isInputContainerNode(node) ||
!ts.isIdentifier(node.name) ||
!node.getSourceFile().isDeclarationFile
) {
return null;
}
// If the potential node is not part of a valid input class, skip.
if (
!ts.isClassDeclaration(node.parent) ||
node.parent.name === undefined ||
!ts.isIdentifier(node.parent.name)
) {
return null;
}
const directiveMetadata = metadataReader.getDirectiveMetadata(
new Reference(node.parent as ClassDeclaration),
);
const inputMapping = directiveMetadata?.inputs.getByClassPropertyName(node.name.text);
// Signal inputs are never tracked and migrated.
if (inputMapping?.isSignal) {
return null;
}
return inputMapping == null
? null
: {
...inputMapping,
inputDecorator: null,
inSourceFile: false,
// Inputs from `.d.ts` cannot have any field decorators applied.
fieldDecorators: [],
};
}
/**
* Attempts to extract `@Input()` information for the given node, assuming it's
* directly defined inside a source file (`.ts`).
*/
function extractSourceCodeInput(
node: ts.Node,
host: MigrationHost,
reflector: ReflectionHost,
evaluator: PartialEvaluator,
refEmitter: ReferenceEmitter,
): ExtractedInput | null {
if (
!isInputContainerNode(node) ||
!ts.isIdentifier(node.name) ||
node.getSourceFile().isDeclarationFile
) {
return null;
}
const decorators = reflector.getDecoratorsOfDeclaration(node);
if (decorators === null) {
return null;
}
const ngDecorators = getAngularDecorators(decorators, ['Input'], host.isMigratingCore);
if (ngDecorators.length === 0) {
return null;
}
const inputDecorator = ngDecorators[0];
let publicName = node.name.text;
let isRequired = false;
let transformResult: DecoratorInputTransform | null = null;
// Check options object from `@Input()`.
if (inputDecorator.args?.length === 1) {
const evaluatedInputOpts = evaluator.evaluate(inputDecorator.args[0]);
if (typeof evaluatedInputOpts === 'string') {
publicName = evaluatedInputOpts;
} else if (evaluatedInputOpts instanceof Map) {
if (evaluatedInputOpts.has('alias') && typeof evaluatedInputOpts.get('alias') === 'string') {
publicName = evaluatedInputOpts.get('alias')! as string;
}
if (
evaluatedInputOpts.has('required') &&
typeof evaluatedInputOpts.get('required') === 'boolean'
) {
isRequired = !!evaluatedInputOpts.get('required');
}
if (evaluatedInputOpts.has('transform') && evaluatedInputOpts.get('transform') != null) {
transformResult = parseTransformOfInput(evaluatedInputOpts, node, reflector, refEmitter);
}
}
}
return {
bindingPropertyName: publicName,
classPropertyName: node.name.text,
required: isRequired,
isSignal: false,
inSourceFile: true,
transform: transformResult,
inputDecorator,
fieldDecorators: decorators,
};
}
/**
* Gracefully attempts to parse the `transform` option of an `@Input()`
* and extracts its metadata.
*/
function parseTransformOfInput(
evaluatedInputOpts: ResolvedValueMap,
node: InputNode,
reflector: ReflectionHost,
refEmitter: ReferenceEmitter,
): DecoratorInputTransform | null {
const transformValue = evaluatedInputOpts.get('transform');
if (!(transformValue instanceof DynamicValue) && !(transformValue instanceof Reference)) {
return null;
}
try {
return parseDecoratorInputTransformFunction(
node.parent as ClassDeclaration,
node.name.text,
transformValue,
reflector,
refEmitter,
CompilationMode.FULL,
);
} catch (e: unknown) {
if (!(e instanceof FatalDiagnosticError)) {
throw e;
}
// TODO: implement error handling.
// See failing case: e.g. inherit_definition_feature_spec.ts
console.error(`${e.node.getSourceFile().fileName}: ${e.toString()}`);
return null;
}
}
| {
"end_byte": 6019,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/input_detection/input_decorator.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/src/input_detection/nodes_to_input.ts_0_1443 | /**
* @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 {isInputContainerNode} from '../input_detection/input_node';
import {getInputDescriptor} from '../utils/input_id';
import type {KnownInputInfo, KnownInputs} from './known_inputs';
import {ProgramInfo} from '../../../../utils/tsurge';
/**
* Attempts to resolve the known `@Input` metadata for the given
* type checking symbol. Returns `null` if it's not for an input.
*/
export function attemptRetrieveInputFromSymbol(
programInfo: ProgramInfo,
memberSymbol: ts.Symbol,
knownInputs: KnownInputs,
): KnownInputInfo | null {
// Even for declared classes from `.d.ts`, the value declaration
// should exist and point to the property declaration.
if (
memberSymbol.valueDeclaration !== undefined &&
isInputContainerNode(memberSymbol.valueDeclaration)
) {
const member = memberSymbol.valueDeclaration;
// If the member itself is an input that is being migrated, we
// do not need to check, as overriding would be fine then— like before.
const memberInputDescr = isInputContainerNode(member)
? getInputDescriptor(programInfo, member)
: null;
return memberInputDescr !== null ? (knownInputs.get(memberInputDescr) ?? null) : null;
}
return null;
}
| {
"end_byte": 1443,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/input_detection/nodes_to_input.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/src/input_detection/directive_info.ts_0_2209 | /**
* @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 {ExtractedInput} from './input_decorator';
import {InputDescriptor} from '../utils/input_id';
import {
ClassIncompatibilityReason,
FieldIncompatibility,
} from '../passes/problematic_patterns/incompatibility';
import {ClassFieldUniqueKey} from '../passes/reference_resolution/known_fields';
/**
* Class that holds information about a given directive and its input fields.
*/
export class DirectiveInfo {
/**
* Map of inputs detected in the given class.
* Maps string-based input ids to the detailed input metadata.
*/
inputFields = new Map<
ClassFieldUniqueKey,
{descriptor: InputDescriptor; metadata: ExtractedInput}
>();
/** Map of input IDs and their incompatibilities. */
memberIncompatibility = new Map<ClassFieldUniqueKey, FieldIncompatibility>();
/**
* Whether the whole class is incompatible.
*
* Class incompatibility precedes individual member incompatibility.
* All members in the class are considered incompatible.
*/
incompatible: ClassIncompatibilityReason | null = null;
constructor(public clazz: ts.ClassDeclaration) {}
/**
* Checks whether there are any migrated inputs for the
* given class.
*
* Returns `false` if all inputs are incompatible.
*/
hasMigratedFields(): boolean {
return Array.from(this.inputFields.values()).some(
({descriptor}) => !this.isInputMemberIncompatible(descriptor),
);
}
/**
* Whether the given input member is incompatible. If the class is incompatible,
* then the member is as well.
*/
isInputMemberIncompatible(input: InputDescriptor): boolean {
return this.getInputMemberIncompatibility(input) !== null;
}
/** Get incompatibility of the given member, if it's incompatible for migration. */
getInputMemberIncompatibility(
input: InputDescriptor,
): ClassIncompatibilityReason | FieldIncompatibility | null {
return this.memberIncompatibility.get(input.key) ?? this.incompatible ?? null;
}
}
| {
"end_byte": 2209,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/src/input_detection/directive_info.ts"
} |
angular/packages/core/schematics/migrations/google3/waitForAsyncRule.ts_0_3554 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Replacement, RuleFailure, Rules} from 'tslint';
import ts from 'typescript';
import {getImportSpecifier, replaceImport} from '../../utils/typescript/imports';
import {closestNode} from '../../utils/typescript/nodes';
import {isReferenceToImport} from '../../utils/typescript/symbol';
// This rule is also used inside of Google by Typescript linting.
/** Name of the deprecated function that we're removing. */
const deprecatedFunction = 'async';
/** Name of the function that will replace the deprecated one. */
const newFunction = 'waitForAsync';
/** TSLint rule that migrates from `async` to `waitForAsync`. */
export class Rule extends Rules.TypedRule {
override applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): RuleFailure[] {
const failures: RuleFailure[] = [];
const asyncImportSpecifier = getImportSpecifier(
sourceFile,
'@angular/core/testing',
deprecatedFunction,
);
const asyncImport = asyncImportSpecifier
? closestNode(asyncImportSpecifier, ts.isNamedImports)
: null;
// If there are no imports of `async`, we can exit early.
if (asyncImportSpecifier && asyncImport) {
const typeChecker = program.getTypeChecker();
const printer = ts.createPrinter();
failures.push(this._getNamedImportsFailure(asyncImport, sourceFile, printer));
this.findAsyncReferences(sourceFile, typeChecker, asyncImportSpecifier).forEach((node) =>
failures.push(this._getIdentifierNodeFailure(node, sourceFile)),
);
}
return failures;
}
/** Gets a failure for an import of the `async` function. */
private _getNamedImportsFailure(
node: ts.NamedImports,
sourceFile: ts.SourceFile,
printer: ts.Printer,
): RuleFailure {
const replacementText = printer.printNode(
ts.EmitHint.Unspecified,
replaceImport(node, deprecatedFunction, newFunction),
sourceFile,
);
return new RuleFailure(
sourceFile,
node.getStart(),
node.getEnd(),
`Imports of the deprecated ${deprecatedFunction} function are not allowed. Use ${newFunction} instead.`,
this.ruleName,
new Replacement(node.getStart(), node.getWidth(), replacementText),
);
}
/** Gets a failure for an identifier node. */
private _getIdentifierNodeFailure(node: ts.Identifier, sourceFile: ts.SourceFile): RuleFailure {
return new RuleFailure(
sourceFile,
node.getStart(),
node.getEnd(),
`References to the deprecated ${deprecatedFunction} function are not allowed. Use ${newFunction} instead.`,
this.ruleName,
new Replacement(node.getStart(), node.getWidth(), newFunction),
);
}
/** Finds calls to the `async` function. */
private findAsyncReferences(
sourceFile: ts.SourceFile,
typeChecker: ts.TypeChecker,
asyncImportSpecifier: ts.ImportSpecifier,
) {
const results = new Set<ts.Identifier>();
ts.forEachChild(sourceFile, function visitNode(node: ts.Node) {
if (
ts.isCallExpression(node) &&
ts.isIdentifier(node.expression) &&
node.expression.text === deprecatedFunction &&
isReferenceToImport(typeChecker, node.expression, asyncImportSpecifier)
) {
results.add(node.expression);
}
ts.forEachChild(node, visitNode);
});
return results;
}
}
| {
"end_byte": 3554,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/google3/waitForAsyncRule.ts"
} |
angular/packages/core/schematics/migrations/google3/BUILD.bazel_0_712 | load("//tools:defaults.bzl", "esbuild", "ts_library")
ts_library(
name = "google3",
srcs = glob(["**/*.ts"]),
tsconfig = "//packages/core/schematics:tsconfig.json",
deps = [
"//packages/core/schematics/utils",
"//packages/core/schematics/utils/tslint",
"@npm//tslint",
"@npm//typescript",
],
)
esbuild(
name = "wait_for_async_rule_cjs",
entry_point = ":waitForAsyncRule.ts",
format = "cjs",
output = "waitForAsyncCjsRule.js",
platform = "node",
deps = [":google3"],
)
filegroup(
name = "google3_cjs",
srcs = [
":wait_for_async_rule_cjs",
],
visibility = ["//packages/core/schematics/test/google3:__pkg__"],
)
| {
"end_byte": 712,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/google3/BUILD.bazel"
} |
angular/packages/core/schematics/migrations/google3/index.ts_0_265 | /**
* @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 {Rule as WaitForAsyncRule} from './waitForAsyncRule';
| {
"end_byte": 265,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/google3/index.ts"
} |
angular/packages/core/schematics/migrations/output-migration/output-migration.spec.ts_0_6411 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {initMockFileSystem} from '../../../../compiler-cli/src/ngtsc/file_system/testing';
import {runTsurgeMigration} from '../../utils/tsurge/testing';
import {diffText} from '../../utils/tsurge/testing/diff';
import {absoluteFrom} from '@angular/compiler-cli';
import {OutputMigration} from './output-migration';
describe('outputs', () => {
beforeEach(() => {
initMockFileSystem('Native');
});
describe('outputs migration', () => {
describe('EventEmitter declarations without problematic access patterns', () => {
it('should migrate declaration with a primitive type hint', async () => {
await verifyDeclaration({
before: '@Output() readonly someChange = new EventEmitter<string>();',
after: 'readonly someChange = output<string>();',
});
});
it('should migrate declaration with complex type hint', async () => {
await verifyDeclaration({
before: '@Output() readonly someChange = new EventEmitter<string | number>();',
after: 'readonly someChange = output<string | number>();',
});
});
it('should migrate declaration without type hint', async () => {
await verifyDeclaration({
before: '@Output() readonly someChange = new EventEmitter();',
after: 'readonly someChange = output();',
});
});
it('should take alias into account', async () => {
await verifyDeclaration({
before: `@Output({alias: 'otherChange'}) readonly someChange = new EventEmitter();`,
after: `readonly someChange = output({ alias: 'otherChange' });`,
});
});
it('should support alias as statically analyzable reference', async () => {
await verify({
before: `
import {Directive, Output, EventEmitter} from '@angular/core';
const aliasParam = { alias: 'otherChange' } as const;
@Directive()
export class TestDir {
@Output(aliasParam) someChange = new EventEmitter();
}
`,
after: `
import {Directive, output} from '@angular/core';
const aliasParam = { alias: 'otherChange' } as const;
@Directive()
export class TestDir {
readonly someChange = output(aliasParam);
}
`,
});
});
it('should add readonly modifier', async () => {
await verifyDeclaration({
before: '@Output() someChange = new EventEmitter();',
after: 'readonly someChange = output();',
});
});
it('should respect visibility modifiers', async () => {
await verifyDeclaration({
before: `@Output() protected someChange = new EventEmitter();`,
after: `protected readonly someChange = output();`,
});
});
it('should preserve single line JSdoc comments when migrating outputs', async () => {
await verify({
before: `
import {Directive, Output, EventEmitter} from '@angular/core';
@Directive()
export class TestDir {
/** Whenever there is change, emits an event. */
@Output() someChange = new EventEmitter();
}
`,
after: `
import {Directive, output} from '@angular/core';
@Directive()
export class TestDir {
/** Whenever there is change, emits an event. */
readonly someChange = output();
}
`,
});
});
it('should preserve multiline JSdoc comments when migrating outputs', async () => {
await verify({
before: `
import {Directive, Output, EventEmitter} from '@angular/core';
@Directive()
export class TestDir {
/**
* Whenever there is change, emits an event.
*/
@Output() someChange = new EventEmitter();
}
`,
after: `
import {Directive, output} from '@angular/core';
@Directive()
export class TestDir {
/**
* Whenever there is change, emits an event.
*/
readonly someChange = output();
}
`,
});
});
it('should preserve multiline comments when migrating outputs', async () => {
await verify({
before: `
import {Directive, Output, EventEmitter} from '@angular/core';
@Directive()
export class TestDir {
/* Whenever there is change,emits an event. */
@Output() someChange = new EventEmitter();
}
`,
after: `
import {Directive, output} from '@angular/core';
@Directive()
export class TestDir {
/* Whenever there is change,emits an event. */
readonly someChange = output();
}
`,
});
});
it('should migrate multiple outputs', async () => {
await verifyDeclaration({
before:
'@Output() someChange1 = new EventEmitter();\n@Output() someChange2 = new EventEmitter();',
after: `readonly someChange1 = output();\nreadonly someChange2 = output();`,
});
});
it('should migrate only EventEmitter outputs when multiple outputs exist', async () => {
await verify({
before: `
import {Directive, Output, EventEmitter, Subject} from '@angular/core';
@Directive()
export class TestDir {
@Output() someChange1 = new EventEmitter();
@Output() someChange2 = new Subject();
}
`,
after: `
import {Directive, Subject, output} from '@angular/core';
@Directive()
export class TestDir {
readonly someChange1 = output();
@Output() someChange2 = new Subject();
}
`,
});
});
}); | {
"end_byte": 6411,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/output-migration/output-migration.spec.ts"
} |
angular/packages/core/schematics/migrations/output-migration/output-migration.spec.ts_6417_16697 | describe('.next migration', () => {
it('should migrate .next usages that should have been .emit', async () => {
await verify({
before: `
import {Directive, Output, EventEmitter} from '@angular/core';
@Directive()
export class TestDir {
@Output() someChange = new EventEmitter<string>();
onClick() {
this.someChange.next('clicked');
}
}
`,
after: `
import {Directive, output} from '@angular/core';
@Directive()
export class TestDir {
readonly someChange = output<string>();
onClick() {
this.someChange.emit('clicked');
}
}
`,
});
});
it('should _not_ migrate .next usages when problematic output usage is detected', async () => {
await verifyNoChange(
`
import {Directive, Output, EventEmitter} from '@angular/core';
@Directive()
export class TestDir {
@Output() someChange = new EventEmitter<string>();
onClick() {
this.someChange.next('clicked');
}
someMethod() {
this.someChange.pipe();
}
}
`,
);
});
it('should migrate .next usage inside inlined template expressions', async () => {
await verify({
before: `
import {Component, Output, EventEmitter} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<button (click)="someChange.next()">click me</button>'
})
export class TestCmpWithTemplate {
@Output() someChange = new EventEmitter();
}
`,
after: `
import {Component, output} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<button (click)="someChange.emit()">click me</button>'
})
export class TestCmpWithTemplate {
readonly someChange = output();
}
`,
});
});
it('should migrate .next usage inside external template expressions', async () => {
const {fs} = await runTsurgeMigration(new OutputMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: `
import {Component, Output, EventEmitter} from '@angular/core';
@Component({
selector: 'test-cmp',
templateUrl: '/app.component.html'
})
export class TestCmpWithTemplate {
@Output() someChange = new EventEmitter();
}
`,
},
{
name: absoluteFrom('/app.component.html'),
contents: `<button (click)="someChange.next()">click me</button>`,
},
]);
const cmpActual = fs.readFile(absoluteFrom('/app.component.ts'));
const htmlActual = fs.readFile(absoluteFrom('/app.component.html'));
const cmpExpected = `
import {Component, output} from '@angular/core';
@Component({
selector: 'test-cmp',
templateUrl: '/app.component.html'
})
export class TestCmpWithTemplate {
readonly someChange = output();
}
`;
const htmlExpected = `<button (click)="someChange.emit()">click me</button>`;
expect(cmpActual).withContext(diffText(cmpExpected, cmpActual)).toEqual(cmpExpected);
expect(htmlActual).withContext(diffText(htmlExpected, htmlActual)).toEqual(htmlExpected);
});
it('should migrate .next usage inside host listeners', async () => {
await verify({
before: `
import {Component, Output, EventEmitter} from '@angular/core';
@Component({
selector: 'test-cmp',
host: {
'(click)': 'someChange.next()'
},
template: ''
})
export class TestCmpWithTemplate {
@Output() someChange = new EventEmitter();
}
`,
after: `
import {Component, output} from '@angular/core';
@Component({
selector: 'test-cmp',
host: {
'(click)': 'someChange.emit()'
},
template: ''
})
export class TestCmpWithTemplate {
readonly someChange = output();
}
`,
});
});
it('should migrate .next usage in @HostListener', async () => {
await verify({
before: `
import {Component, Output, EventEmitter, HostListener} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<button (click)="triggerSomeChange()">click me</button>'
})
export class TestCmpWithTemplate {
@Output() someChange = new EventEmitter();
@HostListener('click')
triggerSomeChange() {
this.someChange.next();
}
}
`,
after: `
import {Component, HostListener, output} from '@angular/core';
@Component({
selector: 'test-cmp',
template: '<button (click)="triggerSomeChange()">click me</button>'
})
export class TestCmpWithTemplate {
readonly someChange = output();
@HostListener('click')
triggerSomeChange() {
this.someChange.emit();
}
}
`,
});
});
});
describe('.complete migration', () => {
it('should remove .complete usage for migrated outputs', async () => {
await verify({
before: `
import {Directive, Output, EventEmitter} from '@angular/core';
@Directive()
export class TestDir {
@Output() someChange = new EventEmitter<string>();
ngOnDestroy() {
this.someChange.complete();
}
}
`,
after: `
import {Directive, output} from '@angular/core';
@Directive()
export class TestDir {
readonly someChange = output<string>();
ngOnDestroy() {
}
}
`,
});
});
it('should remove .complete usage with comments', async () => {
await verify({
before: `
import {Directive, Output, EventEmitter} from '@angular/core';
@Directive()
export class TestDir {
@Output() someChange = new EventEmitter<string>();
ngOnDestroy() {
// maybe complete before the destroy?
this.someChange.complete();
}
}
`,
after: `
import {Directive, output} from '@angular/core';
@Directive()
export class TestDir {
readonly someChange = output<string>();
ngOnDestroy() {
}
}
`,
});
});
it('should _not_ migrate .complete usage outside of expression statements', async () => {
await verifyNoChange(
`
import {Directive, Output, EventEmitter} from '@angular/core';
@Directive()
export class TestDir {
@Output() someChange = new EventEmitter<string>();
ngOnDestroy() {
// play it safe and skip replacement for any .complete usage that are not
// trivial expression statements
(this.someChange.complete());
}
}
`,
);
});
});
describe('.pipe migration', () => {
describe('in test files', () => {
it('should convert to observable in a test file importing jasmine', async () => {
await verify({
before: `
import {Directive, Output, EventEmitter} from '@angular/core';
import {map} from 'rxjs';
import 'jasmine';
@Directive()
export class TestDir {
@Output() someChange = new EventEmitter<number>();
someChange$ = this.someChange.pipe(map((c) => c + 1)).pipe(map((d) => d - 1));
}
`,
after: `
import { outputToObservable } from "@angular/core/rxjs-interop";
import {Directive, output} from '@angular/core';
import {map} from 'rxjs';
import 'jasmine';
@Directive()
export class TestDir {
readonly someChange = output<number>();
someChange$ = outputToObservable(this.someChange).pipe(map((c) => c + 1)).pipe(map((d) => d - 1));
}
`,
});
});
});
describe('declarations _with_ problematic access patterns', () => {
it('should _not_ migrate outputs that are used with .pipe', () => {
verifyNoChange(`
import {Directive, Output, EventEmitter} from '@angular/core';
@Directive()
export class TestDir {
@Output() someChange = new EventEmitter();
someMethod() {
this.someChange.pipe();
}
}
`);
});
it('should _not_ migrate outputs that are used with .pipe outside of a component class', () => {
verifyNoChange(`
import {Directive, Output, EventEmitter} from '@angular/core';
@Directive()
export class TestDir {
@Output() someChange = new EventEmitter();
}
let instance: TestDir;
instance.someChange.pipe();
`);
});
});
});
}); | {
"end_byte": 16697,
"start_byte": 6417,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/output-migration/output-migration.spec.ts"
} |
angular/packages/core/schematics/migrations/output-migration/output-migration.spec.ts_16701_19927 | describe('declarations other than EventEmitter', () => {
it('should _not_ migrate outputs that are initialized with sth else than EventEmitter', async () => {
await verify({
before: populateDeclarationTestCase('@Output() protected someChange = new Subject();'),
after: populateDeclarationTestCase('@Output() protected someChange = new Subject();'),
});
});
});
describe('statistics', () => {
it('should capture migration statistics with problematic usage detected', async () => {
const runResults = await runTsurgeMigration(new OutputMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: populateDeclarationTestCase(`
@Output() protected ok1 = new EventEmitter();
@Output() protected ok2 = new EventEmitter();
@Output() protected ko1 = new EventEmitter();
@Output() protected ko2 = new Subject();
doSth() {
this.ko1.pipe();
}
`),
},
]);
const stats = await runResults.getStatistics();
expect(stats.counters['detectedOutputs']).toBe(4);
expect(stats.counters['problematicOutputs']).toBe(2);
expect(stats.counters['successRate']).toBe(0.5);
});
it('should capture migration statistics without problematic usages', async () => {
const runResults = await runTsurgeMigration(new OutputMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: populateDeclarationTestCase(`
@Output() protected ok = new EventEmitter();
@Output() protected ko = new EventEmitter();
`),
},
]);
const stats = await runResults.getStatistics();
expect(stats.counters['detectedOutputs']).toBe(2);
expect(stats.counters['problematicOutputs']).toBe(0);
expect(stats.counters['successRate']).toBe(1);
});
});
});
async function verifyDeclaration(testCase: {before: string; after: string}) {
await verify({
before: populateDeclarationTestCase(testCase.before),
after: populateExpectedResult(testCase.after),
});
}
async function verifyNoChange(beforeAndAfter: string) {
await verify({before: beforeAndAfter, after: beforeAndAfter});
}
async function verify(testCase: {before: string; after: string}) {
const {fs} = await runTsurgeMigration(new OutputMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: testCase.before,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts')).trim();
const expected = testCase.after.trim();
expect(actual).withContext(diffText(expected, actual)).toEqual(expected);
}
function populateDeclarationTestCase(declaration: string): string {
return `
import {
Directive,
Output,
EventEmitter,
Subject
} from '@angular/core';
@Directive()
export class TestDir {
${declaration}
}
`;
}
function populateExpectedResult(declaration: string): string {
return `
import {
Directive,
Subject,
output
} from '@angular/core';
@Directive()
export class TestDir {
${declaration}
}
`;
} | {
"end_byte": 19927,
"start_byte": 16701,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/output-migration/output-migration.spec.ts"
} |
angular/packages/core/schematics/migrations/output-migration/output-replacements.ts_0_5497 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {ImportManager} from '../../../../compiler-cli/private/migrations';
import {
ProgramInfo,
ProjectFile,
projectFile,
ProjectFileID,
Replacement,
TextUpdate,
} from '../../utils/tsurge';
import {applyImportManagerChanges} from '../../utils/tsurge/helpers/apply_import_manager';
import {AbsoluteSourceSpan} from '@angular/compiler';
const printer = ts.createPrinter();
export function calculateDeclarationReplacement(
info: ProgramInfo,
node: ts.PropertyDeclaration,
aliasParam?: ts.Expression,
): Replacement {
const sf = node.getSourceFile();
const payloadTypes =
node.initializer !== undefined && ts.isNewExpression(node.initializer)
? node.initializer?.typeArguments
: undefined;
const outputCall = ts.factory.createCallExpression(
ts.factory.createIdentifier('output'),
payloadTypes,
aliasParam ? [aliasParam] : [],
);
const existingModifiers = (node.modifiers ?? []).filter(
(modifier) => !ts.isDecorator(modifier) && modifier.kind !== ts.SyntaxKind.ReadonlyKeyword,
);
const updatedOutputDeclaration = ts.factory.createPropertyDeclaration(
// Think: this logic of dealing with modifiers is applicable to all signal-based migrations
ts.factory.createNodeArray([
...existingModifiers,
ts.factory.createModifier(ts.SyntaxKind.ReadonlyKeyword),
]),
node.name,
undefined,
undefined,
outputCall,
);
return prepareTextReplacementForNode(
info,
node,
printer.printNode(ts.EmitHint.Unspecified, updatedOutputDeclaration, sf),
);
}
export function calculateImportReplacements(info: ProgramInfo, sourceFiles: Set<ts.SourceFile>) {
const importReplacements: Record<
ProjectFileID,
{add: Replacement[]; addAndRemove: Replacement[]}
> = {};
const importManager = new ImportManager();
for (const sf of sourceFiles) {
const addOnly: Replacement[] = [];
const addRemove: Replacement[] = [];
const file = projectFile(sf, info);
importManager.addImport({
requestedFile: sf,
exportModuleSpecifier: '@angular/core',
exportSymbolName: 'output',
});
applyImportManagerChanges(importManager, addOnly, [sf], info);
importManager.removeImport(sf, 'Output', '@angular/core');
importManager.removeImport(sf, 'EventEmitter', '@angular/core');
applyImportManagerChanges(importManager, addRemove, [sf], info);
importReplacements[file.id] = {
add: addOnly,
addAndRemove: addRemove,
};
}
return importReplacements;
}
export function calculateNextFnReplacement(info: ProgramInfo, node: ts.MemberName): Replacement {
return prepareTextReplacementForNode(info, node, 'emit');
}
export function calculateNextFnReplacementInTemplate(
file: ProjectFile,
span: AbsoluteSourceSpan,
): Replacement {
return prepareTextReplacement(file, 'emit', span.start, span.end);
}
export function calculateNextFnReplacementInHostBinding(
file: ProjectFile,
offset: number,
span: AbsoluteSourceSpan,
): Replacement {
return prepareTextReplacement(file, 'emit', offset + span.start, offset + span.end);
}
export function calculateCompleteCallReplacement(
info: ProgramInfo,
node: ts.ExpressionStatement,
): Replacement {
return prepareTextReplacementForNode(info, node, '', node.getFullStart());
}
export function calculatePipeCallReplacement(
info: ProgramInfo,
node: ts.CallExpression,
): Replacement[] {
if (ts.isPropertyAccessExpression(node.expression)) {
const sf = node.getSourceFile();
const importManager = new ImportManager();
const outputToObservableIdent = importManager.addImport({
requestedFile: sf,
exportModuleSpecifier: '@angular/core/rxjs-interop',
exportSymbolName: 'outputToObservable',
});
const toObsCallExp = ts.factory.createCallExpression(outputToObservableIdent, undefined, [
node.expression.expression,
]);
const pipePropAccessExp = ts.factory.updatePropertyAccessExpression(
node.expression,
toObsCallExp,
node.expression.name,
);
const pipeCallExp = ts.factory.updateCallExpression(
node,
pipePropAccessExp,
[],
node.arguments,
);
const replacements = [
prepareTextReplacementForNode(
info,
node,
printer.printNode(ts.EmitHint.Unspecified, pipeCallExp, sf),
),
];
applyImportManagerChanges(importManager, replacements, [sf], info);
return replacements;
} else {
// TODO: assert instead?
throw new Error(
`Unexpected call expression for .pipe - expected a property access but got "${node.getText()}"`,
);
}
}
function prepareTextReplacementForNode(
info: ProgramInfo,
node: ts.Node,
replacement: string,
start?: number,
): Replacement {
const sf = node.getSourceFile();
return new Replacement(
projectFile(sf, info),
new TextUpdate({
position: start ?? node.getStart(),
end: node.getEnd(),
toInsert: replacement,
}),
);
}
function prepareTextReplacement(
file: ProjectFile,
replacement: string,
start: number,
end: number,
): Replacement {
return new Replacement(
file,
new TextUpdate({
position: start,
end: end,
toInsert: replacement,
}),
);
}
| {
"end_byte": 5497,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/output-migration/output-replacements.ts"
} |
angular/packages/core/schematics/migrations/output-migration/output-migration.ts_0_2795 | /**
* @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 assert from 'assert';
import {
confirmAsSerializable,
MigrationStats,
ProgramInfo,
projectFile,
ProjectFile,
ProjectFileID,
Replacement,
Serializable,
TsurgeFunnelMigration,
} from '../../utils/tsurge';
import {DtsMetadataReader} from '../../../../compiler-cli/src/ngtsc/metadata';
import {TypeScriptReflectionHost} from '../../../../compiler-cli/src/ngtsc/reflection';
import {PartialEvaluator} from '@angular/compiler-cli/private/migrations';
import {
getUniqueIdForProperty,
isTargetOutputDeclaration,
isPotentialCompleteCallUsage,
isPotentialNextCallUsage,
isPotentialPipeCallUsage,
isTestRunnerImport,
getTargetPropertyDeclaration,
checkNonTsReferenceCallsField,
getOutputDecorator,
isOutputDeclarationEligibleForMigration,
} from './output_helpers';
import {
calculateImportReplacements,
calculateDeclarationReplacement,
calculateNextFnReplacement,
calculateCompleteCallReplacement,
calculatePipeCallReplacement,
calculateNextFnReplacementInTemplate,
calculateNextFnReplacementInHostBinding,
} from './output-replacements';
import {createFindAllSourceFileReferencesVisitor} from '../signal-migration/src/passes/reference_resolution';
import {
ClassFieldDescriptor,
ClassFieldUniqueKey,
KnownFields,
} from '../signal-migration/src/passes/reference_resolution/known_fields';
import {ReferenceResult} from '../signal-migration/src/passes/reference_resolution/reference_result';
import {ReferenceKind} from '../signal-migration/src/passes/reference_resolution/reference_kinds';
export interface MigrationConfig {
/**
* Whether the given output definition should be migrated.
*
* Treating an output as non-migrated means that no references to it are
* migrated, nor the actual declaration (if it's part of the sources).
*
* If no function is specified here, the migration will migrate all
* output and references it discovers in compilation units. This is the
* running assumption for batch mode and LSC mode where the migration
* assumes all seen output are migrated.
*/
shouldMigrate?: (definition: ClassFieldDescriptor, containingFile: ProjectFile) => boolean;
}
export interface OutputMigrationData {
file: ProjectFile;
replacements: Replacement[];
}
export interface CompilationUnitData {
problematicDeclarationCount: number;
outputFields: Record<ClassFieldUniqueKey, OutputMigrationData>;
problematicUsages: Record<ClassFieldUniqueKey, true>;
importReplacements: Record<ProjectFileID, {add: Replacement[]; addAndRemove: Replacement[]}>;
} | {
"end_byte": 2795,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/output-migration/output-migration.ts"
} |
angular/packages/core/schematics/migrations/output-migration/output-migration.ts_2797_12147 | export class OutputMigration extends TsurgeFunnelMigration<
CompilationUnitData,
CompilationUnitData
> {
constructor(private readonly config: MigrationConfig = {}) {
super();
}
override async analyze(info: ProgramInfo): Promise<Serializable<CompilationUnitData>> {
const {sourceFiles, program} = info;
const outputFieldReplacements: Record<ClassFieldUniqueKey, OutputMigrationData> = {};
const problematicUsages: Record<ClassFieldUniqueKey, true> = {};
let problematicDeclarationCount = 0;
const filesWithOutputDeclarations = new Set<ts.SourceFile>();
const checker = program.getTypeChecker();
const reflector = new TypeScriptReflectionHost(checker);
const dtsReader = new DtsMetadataReader(checker, reflector);
const evaluator = new PartialEvaluator(reflector, checker, null);
const ngCompiler = info.ngCompiler;
assert(ngCompiler !== null, 'Requires ngCompiler to run the migration');
const resourceLoader = ngCompiler['resourceManager'];
// Pre-Analyze the program and get access to the template type checker.
const {templateTypeChecker} = ngCompiler['ensureAnalyzed']();
const knownFields: KnownFields<ClassFieldDescriptor> = {
// Note: We don't support cross-target migration of `Partial<T>` usages.
// This is an acceptable limitation for performance reasons.
shouldTrackClassReference: (node) => false,
attemptRetrieveDescriptorFromSymbol: (s) => {
const propDeclaration = getTargetPropertyDeclaration(s);
if (propDeclaration !== null) {
const classFieldID = getUniqueIdForProperty(info, propDeclaration);
if (classFieldID !== null) {
return {
node: propDeclaration,
key: classFieldID,
};
}
}
return null;
},
};
let isTestFile = false;
const outputMigrationVisitor = (node: ts.Node) => {
// detect output declarations
if (ts.isPropertyDeclaration(node)) {
const outputDecorator = getOutputDecorator(node, reflector);
if (outputDecorator !== null) {
if (isOutputDeclarationEligibleForMigration(node)) {
const outputDef = {
id: getUniqueIdForProperty(info, node),
aliasParam: outputDecorator.args?.at(0),
};
const outputFile = projectFile(node.getSourceFile(), info);
if (
this.config.shouldMigrate === undefined ||
this.config.shouldMigrate(
{
key: outputDef.id,
node: node,
},
outputFile,
)
) {
filesWithOutputDeclarations.add(node.getSourceFile());
addOutputReplacement(
outputFieldReplacements,
outputDef.id,
outputFile,
calculateDeclarationReplacement(info, node, outputDef.aliasParam),
);
}
} else {
problematicDeclarationCount++;
}
}
}
// detect .next usages that should be migrated to .emit
if (isPotentialNextCallUsage(node) && ts.isPropertyAccessExpression(node.expression)) {
const propertyDeclaration = isTargetOutputDeclaration(
node.expression.expression,
checker,
reflector,
dtsReader,
);
if (propertyDeclaration !== null) {
const id = getUniqueIdForProperty(info, propertyDeclaration);
const outputFile = projectFile(node.getSourceFile(), info);
addOutputReplacement(
outputFieldReplacements,
id,
outputFile,
calculateNextFnReplacement(info, node.expression.name),
);
}
}
// detect .complete usages that should be removed
if (isPotentialCompleteCallUsage(node) && ts.isPropertyAccessExpression(node.expression)) {
const propertyDeclaration = isTargetOutputDeclaration(
node.expression.expression,
checker,
reflector,
dtsReader,
);
if (propertyDeclaration !== null) {
const id = getUniqueIdForProperty(info, propertyDeclaration);
const outputFile = projectFile(node.getSourceFile(), info);
if (ts.isExpressionStatement(node.parent)) {
addOutputReplacement(
outputFieldReplacements,
id,
outputFile,
calculateCompleteCallReplacement(info, node.parent),
);
} else {
problematicUsages[id] = true;
}
}
}
// detect imports of test runners
if (isTestRunnerImport(node)) {
isTestFile = true;
}
// detect unsafe access of the output property
if (isPotentialPipeCallUsage(node) && ts.isPropertyAccessExpression(node.expression)) {
const propertyDeclaration = isTargetOutputDeclaration(
node.expression.expression,
checker,
reflector,
dtsReader,
);
if (propertyDeclaration !== null) {
const id = getUniqueIdForProperty(info, propertyDeclaration);
if (isTestFile) {
const outputFile = projectFile(node.getSourceFile(), info);
addOutputReplacement(
outputFieldReplacements,
id,
outputFile,
...calculatePipeCallReplacement(info, node),
);
} else {
problematicUsages[id] = true;
}
}
}
ts.forEachChild(node, outputMigrationVisitor);
};
// calculate output migration replacements
for (const sf of sourceFiles) {
isTestFile = false;
ts.forEachChild(sf, outputMigrationVisitor);
}
// take care of the references in templates and host bindings
const referenceResult: ReferenceResult<ClassFieldDescriptor> = {references: []};
const {visitor: templateHostRefVisitor} = createFindAllSourceFileReferencesVisitor(
info,
checker,
reflector,
resourceLoader,
evaluator,
templateTypeChecker,
knownFields,
null, // TODO: capture known output names as an optimization
referenceResult,
);
// calculate template / host binding replacements
for (const sf of sourceFiles) {
ts.forEachChild(sf, templateHostRefVisitor);
}
for (const ref of referenceResult.references) {
// detect .next usages that should be migrated to .emit in template and host binding expressions
if (ref.kind === ReferenceKind.InTemplate) {
const callExpr = checkNonTsReferenceCallsField(ref, 'next');
if (callExpr !== null) {
addOutputReplacement(
outputFieldReplacements,
ref.target.key,
ref.from.templateFile,
calculateNextFnReplacementInTemplate(ref.from.templateFile, callExpr.nameSpan),
);
}
} else if (ref.kind === ReferenceKind.InHostBinding) {
const callExpr = checkNonTsReferenceCallsField(ref, 'next');
if (callExpr !== null) {
addOutputReplacement(
outputFieldReplacements,
ref.target.key,
ref.from.file,
calculateNextFnReplacementInHostBinding(
ref.from.file,
ref.from.hostPropertyNode.getStart() + 1,
callExpr.nameSpan,
),
);
}
}
}
// calculate import replacements but do so only for files that have output declarations
const importReplacements = calculateImportReplacements(info, filesWithOutputDeclarations);
return confirmAsSerializable({
problematicDeclarationCount,
outputFields: outputFieldReplacements,
importReplacements,
problematicUsages,
});
}
override async combine(
unitA: CompilationUnitData,
unitB: CompilationUnitData,
): Promise<Serializable<CompilationUnitData>> {
const outputFields: Record<ClassFieldUniqueKey, OutputMigrationData> = {};
const importReplacements: Record<
ProjectFileID,
{add: Replacement[]; addAndRemove: Replacement[]}
> = {};
const problematicUsages: Record<ClassFieldUniqueKey, true> = {};
let problematicDeclarationCount = 0;
for (const unit of [unitA, unitB]) {
for (const declIdStr of Object.keys(unit.outputFields)) {
const declId = declIdStr as ClassFieldUniqueKey;
// THINK: detect clash? Should we have an utility to merge data based on unique IDs?
outputFields[declId] = unit.outputFields[declId];
}
for (const fileIDStr of Object.keys(unit.importReplacements)) {
const fileID = fileIDStr as ProjectFileID;
importReplacements[fileID] = unit.importReplacements[fileID];
}
problematicDeclarationCount += unit.problematicDeclarationCount;
}
for (const unit of [unitA, unitB]) {
for (const declIdStr of Object.keys(unit.problematicUsages)) {
const declId = declIdStr as ClassFieldUniqueKey;
problematicUsages[declId] = unit.problematicUsages[declId];
}
}
return confirmAsSerializable({
problematicDeclarationCount,
outputFields,
importReplacements,
problematicUsages,
});
} | {
"end_byte": 12147,
"start_byte": 2797,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/output-migration/output-migration.ts"
} |
angular/packages/core/schematics/migrations/output-migration/output-migration.ts_12151_15230 | override async globalMeta(
combinedData: CompilationUnitData,
): Promise<Serializable<CompilationUnitData>> {
const globalMeta: CompilationUnitData = {
importReplacements: combinedData.importReplacements,
outputFields: combinedData.outputFields,
problematicDeclarationCount: combinedData.problematicDeclarationCount,
problematicUsages: {},
};
for (const keyStr of Object.keys(combinedData.problematicUsages)) {
const key = keyStr as ClassFieldUniqueKey;
// it might happen that a problematic usage is detected but we didn't see the declaration - skipping those
if (globalMeta.outputFields[key] !== undefined) {
globalMeta.problematicUsages[key] = true;
}
}
// Noop here as we don't have any form of special global metadata.
return confirmAsSerializable(combinedData);
}
override async stats(globalMetadata: CompilationUnitData): Promise<MigrationStats> {
const detectedOutputs =
new Set(Object.keys(globalMetadata.outputFields)).size +
globalMetadata.problematicDeclarationCount;
const problematicOutputs =
new Set(Object.keys(globalMetadata.problematicUsages)).size +
globalMetadata.problematicDeclarationCount;
const successRate =
detectedOutputs > 0 ? (detectedOutputs - problematicOutputs) / detectedOutputs : 1;
return {
counters: {
detectedOutputs,
problematicOutputs,
successRate,
},
};
}
override async migrate(globalData: CompilationUnitData) {
const migratedFiles = new Set<ProjectFileID>();
const problematicFiles = new Set<ProjectFileID>();
const replacements: Replacement[] = [];
for (const declIdStr of Object.keys(globalData.outputFields)) {
const declId = declIdStr as ClassFieldUniqueKey;
const outputField = globalData.outputFields[declId];
if (!globalData.problematicUsages[declId]) {
replacements.push(...outputField.replacements);
migratedFiles.add(outputField.file.id);
} else {
problematicFiles.add(outputField.file.id);
}
}
for (const fileIDStr of Object.keys(globalData.importReplacements)) {
const fileID = fileIDStr as ProjectFileID;
if (migratedFiles.has(fileID)) {
const importReplacements = globalData.importReplacements[fileID];
if (problematicFiles.has(fileID)) {
replacements.push(...importReplacements.add);
} else {
replacements.push(...importReplacements.addAndRemove);
}
}
}
return {replacements};
}
}
function addOutputReplacement(
outputFieldReplacements: Record<ClassFieldUniqueKey, OutputMigrationData>,
outputId: ClassFieldUniqueKey,
file: ProjectFile,
...replacements: Replacement[]
): void {
let existingReplacements = outputFieldReplacements[outputId];
if (existingReplacements === undefined) {
outputFieldReplacements[outputId] = existingReplacements = {
file: file,
replacements: [],
};
}
existingReplacements.replacements.push(...replacements);
} | {
"end_byte": 15230,
"start_byte": 12151,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/output-migration/output-migration.ts"
} |
angular/packages/core/schematics/migrations/output-migration/BUILD.bazel_0_1341 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
ts_library(
name = "migration",
srcs = glob(
["**/*.ts"],
exclude = ["*.spec.ts"],
),
visibility = [
"//packages/core/schematics/ng-generate/output-migration:__pkg__",
"//packages/language-service/src/refactorings:__pkg__",
],
deps = [
"//packages/compiler",
"//packages/compiler-cli",
"//packages/compiler-cli/private",
"//packages/compiler-cli/src/ngtsc/annotations",
"//packages/compiler-cli/src/ngtsc/annotations/directive",
"//packages/compiler-cli/src/ngtsc/imports",
"//packages/compiler-cli/src/ngtsc/metadata",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/core/schematics/migrations/signal-migration/src",
"//packages/core/schematics/utils/tsurge",
"@npm//@types/node",
"@npm//typescript",
],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(
["**/*.spec.ts"],
),
deps = [
":migration",
"//packages/compiler-cli",
"//packages/compiler-cli/src/ngtsc/file_system/testing",
"//packages/core/schematics/utils/tsurge",
],
)
jasmine_node_test(
name = "test",
srcs = [":test_lib"],
env = {"FORCE_COLOR": "3"},
)
| {
"end_byte": 1341,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/output-migration/BUILD.bazel"
} |
angular/packages/core/schematics/migrations/output-migration/output_helpers.ts_0_6509 | /**
* @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 {
ReflectionHost,
ClassDeclaration,
Decorator,
} from '../../../../compiler-cli/src/ngtsc/reflection';
import {DtsMetadataReader} from '../../../../compiler-cli/src/ngtsc/metadata';
import {Reference} from '../../../../compiler-cli/src/ngtsc/imports';
import {getAngularDecorators} from '../../../../compiler-cli/src/ngtsc/annotations';
import {ProgramInfo, projectFile} from '../../utils/tsurge';
import {
ClassFieldDescriptor,
ClassFieldUniqueKey,
} from '../signal-migration/src/passes/reference_resolution/known_fields';
import {
HostBindingReference,
TemplateReference,
} from '../signal-migration/src/passes/reference_resolution/reference_kinds';
import {AST, PropertyRead} from '@angular/compiler';
/** Type describing an extracted output query that can be migrated. */
export interface ExtractedOutput {
id: ClassFieldUniqueKey;
aliasParam?: ts.Expression;
}
export function isOutputDeclarationEligibleForMigration(node: ts.PropertyDeclaration) {
return (
node.initializer !== undefined &&
ts.isNewExpression(node.initializer) &&
ts.isIdentifier(node.initializer.expression) &&
node.initializer.expression.text === 'EventEmitter'
);
}
function isPotentialOutputCallUsage(node: ts.Node, name: string): node is ts.CallExpression {
if (
ts.isCallExpression(node) &&
ts.isPropertyAccessExpression(node.expression) &&
ts.isIdentifier(node.expression.name)
) {
return node.expression?.name.text === name;
} else {
return false;
}
}
export function isPotentialPipeCallUsage(node: ts.Node): node is ts.CallExpression {
return isPotentialOutputCallUsage(node, 'pipe');
}
export function isPotentialNextCallUsage(node: ts.Node): node is ts.CallExpression {
return isPotentialOutputCallUsage(node, 'next');
}
export function isPotentialCompleteCallUsage(node: ts.Node): node is ts.CallExpression {
return isPotentialOutputCallUsage(node, 'complete');
}
export function isTargetOutputDeclaration(
node: ts.Node,
checker: ts.TypeChecker,
reflector: ReflectionHost,
dtsReader: DtsMetadataReader,
): ts.PropertyDeclaration | null {
const targetSymbol = checker.getSymbolAtLocation(node);
if (targetSymbol !== undefined) {
const propertyDeclaration = getTargetPropertyDeclaration(targetSymbol);
if (
propertyDeclaration !== null &&
isOutputDeclaration(propertyDeclaration, reflector, dtsReader)
) {
return propertyDeclaration;
}
}
return null;
}
/** Gets whether the given property is an Angular `@Output`. */
function isOutputDeclaration(
node: ts.PropertyDeclaration,
reflector: ReflectionHost,
dtsReader: DtsMetadataReader,
): boolean {
// `.d.ts` file, so we check the `static ecmp` metadata on the `declare class`.
if (node.getSourceFile().isDeclarationFile) {
if (
!ts.isIdentifier(node.name) ||
!ts.isClassDeclaration(node.parent) ||
node.parent.name === undefined
) {
return false;
}
const ref = new Reference(node.parent as ClassDeclaration);
const directiveMeta = dtsReader.getDirectiveMetadata(ref);
return !!directiveMeta?.outputs.getByClassPropertyName(node.name.text);
}
// `.ts` file, so we check for the `@Output()` decorator.
return getOutputDecorator(node, reflector) !== null;
}
export function getTargetPropertyDeclaration(
targetSymbol: ts.Symbol,
): ts.PropertyDeclaration | null {
const valDeclaration = targetSymbol.valueDeclaration;
if (valDeclaration !== undefined && ts.isPropertyDeclaration(valDeclaration)) {
return valDeclaration;
}
return null;
}
/** Returns Angular `@Output` decorator or null when a given property declaration is not an @Output */
export function getOutputDecorator(
node: ts.PropertyDeclaration,
reflector: ReflectionHost,
): Decorator | null {
const decorators = reflector.getDecoratorsOfDeclaration(node);
const ngDecorators =
decorators !== null ? getAngularDecorators(decorators, ['Output'], /* isCore */ false) : [];
return ngDecorators.length > 0 ? ngDecorators[0] : null;
}
// THINK: this utility + type is not specific to @Output, really, maybe move it to tsurge?
/** Computes an unique ID for a given Angular `@Output` property. */
export function getUniqueIdForProperty(
info: ProgramInfo,
prop: ts.PropertyDeclaration,
): ClassFieldUniqueKey {
const {id} = projectFile(prop.getSourceFile(), info);
id.replace(/\.d\.ts$/, '.ts');
return `${id}@@${prop.parent.name ?? 'unknown-class'}@@${prop.name.getText()}` as ClassFieldUniqueKey;
}
export function isTestRunnerImport(node: ts.Node) {
if (ts.isImportDeclaration(node)) {
const moduleSpecifier = node.moduleSpecifier.getText();
return moduleSpecifier.includes('jasmine') || moduleSpecifier.includes('catalyst');
}
return false;
}
// TODO: code duplication with signals migration - sort it out
/**
* Gets whether the given read is used to access
* the specified field.
*
* E.g. whether `<my-read>.toArray` is detected.
*/
export function checkNonTsReferenceAccessesField(
ref: HostBindingReference<ClassFieldDescriptor> | TemplateReference<ClassFieldDescriptor>,
fieldName: string,
): PropertyRead | null {
const readFromPath = ref.from.readAstPath.at(-1) as PropertyRead | AST | undefined;
const parentRead = ref.from.readAstPath.at(-2) as PropertyRead | AST | undefined;
if (ref.from.read !== readFromPath) {
return null;
}
if (!(parentRead instanceof PropertyRead) || parentRead.name !== fieldName) {
return null;
}
return parentRead;
}
/**
* Gets whether the given reference is accessed to call the
* specified function on it.
*
* E.g. whether `<my-read>.toArray()` is detected.
*/
export function checkNonTsReferenceCallsField(
ref: TemplateReference<ClassFieldDescriptor> | HostBindingReference<ClassFieldDescriptor>,
fieldName: string,
): PropertyRead | null {
const propertyAccess = checkNonTsReferenceAccessesField(ref, fieldName);
if (propertyAccess === null) {
return null;
}
const accessIdx = ref.from.readAstPath.indexOf(propertyAccess);
if (accessIdx === -1) {
return null;
}
const potentialRead = ref.from.readAstPath[accessIdx];
if (potentialRead === undefined) {
return null;
}
return potentialRead as PropertyRead;
}
| {
"end_byte": 6509,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/output-migration/output_helpers.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/fn_get_replacement.ts_0_2209 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ProgramInfo, projectFile, Replacement, TextUpdate} from '../../utils/tsurge';
import {ClassFieldDescriptor} from '../signal-migration/src';
import {
isHostBindingReference,
isTemplateReference,
isTsReference,
Reference,
} from '../signal-migration/src/passes/reference_resolution/reference_kinds';
import {KnownQueries} from './known_queries';
import type {GlobalUnitData} from './migration';
import {checkNonTsReferenceCallsField, checkTsReferenceCallsField} from './property_accesses';
export function replaceQueryListGetCall(
ref: Reference<ClassFieldDescriptor>,
info: ProgramInfo,
globalMetadata: GlobalUnitData,
knownQueries: KnownQueries,
replacements: Replacement[],
): void {
if (!isHostBindingReference(ref) && !isTemplateReference(ref) && !isTsReference(ref)) {
return;
}
if (knownQueries.isFieldIncompatible(ref.target)) {
return;
}
if (!globalMetadata.knownQueryFields[ref.target.key]?.isMulti) {
return;
}
if (isTsReference(ref)) {
const getCallExpr = checkTsReferenceCallsField(ref, 'get');
if (getCallExpr === null) {
return;
}
const getExpr = getCallExpr.expression;
replacements.push(
new Replacement(
projectFile(getExpr.getSourceFile(), info),
new TextUpdate({
position: getExpr.name.getStart(),
end: getExpr.name.getEnd(),
toInsert: 'at',
}),
),
);
return;
}
// Template and host binding references.
const callExpr = checkNonTsReferenceCallsField(ref, 'get');
if (callExpr === null) {
return;
}
const file = isHostBindingReference(ref) ? ref.from.file : ref.from.templateFile;
const offset = isHostBindingReference(ref) ? ref.from.hostPropertyNode.getStart() + 1 : 0;
replacements.push(
new Replacement(
file,
new TextUpdate({
position: offset + callExpr.receiver.nameSpan.start,
end: offset + callExpr.receiver.nameSpan.end,
toInsert: 'at',
}),
),
);
}
| {
"end_byte": 2209,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/fn_get_replacement.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/migration.ts_0_4756 | /**
* @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 {ImportManager, PartialEvaluator} from '@angular/compiler-cli/private/migrations';
import {getAngularDecorators, QueryFunctionName} from '@angular/compiler-cli/src/ngtsc/annotations';
import {TypeScriptReflectionHost} from '@angular/compiler-cli/src/ngtsc/reflection';
import assert from 'assert';
import ts from 'typescript';
import {
confirmAsSerializable,
MigrationStats,
ProgramInfo,
projectFile,
Replacement,
Serializable,
TsurgeComplexMigration,
} from '../../utils/tsurge';
import {applyImportManagerChanges} from '../../utils/tsurge/helpers/apply_import_manager';
import {
ClassFieldDescriptor,
ClassIncompatibilityReason,
FieldIncompatibilityReason,
} from '../signal-migration/src';
import {checkIncompatiblePatterns} from '../signal-migration/src/passes/problematic_patterns/common_incompatible_patterns';
import {migrateHostBindings} from '../signal-migration/src/passes/reference_migration/migrate_host_bindings';
import {migrateTemplateReferences} from '../signal-migration/src/passes/reference_migration/migrate_template_references';
import {migrateTypeScriptReferences} from '../signal-migration/src/passes/reference_migration/migrate_ts_references';
import {migrateTypeScriptTypeReferences} from '../signal-migration/src/passes/reference_migration/migrate_ts_type_references';
import {ReferenceMigrationHost} from '../signal-migration/src/passes/reference_migration/reference_migration_host';
import {createFindAllSourceFileReferencesVisitor} from '../signal-migration/src/passes/reference_resolution';
import {
ClassFieldUniqueKey,
KnownFields,
} from '../signal-migration/src/passes/reference_resolution/known_fields';
import {
isHostBindingReference,
isTemplateReference,
isTsReference,
Reference,
} from '../signal-migration/src/passes/reference_resolution/reference_kinds';
import {ReferenceResult} from '../signal-migration/src/passes/reference_resolution/reference_result';
import {GroupedTsAstVisitor} from '../signal-migration/src/utils/grouped_ts_ast_visitor';
import {InheritanceGraph} from '../signal-migration/src/utils/inheritance_graph';
import {computeReplacementsToMigrateQuery} from './convert_query_property';
import {getClassFieldDescriptorForSymbol, getUniqueIDForClassProperty} from './field_tracking';
import {ExtractedQuery, extractSourceQueryDefinition} from './identify_queries';
import {KnownQueries} from './known_queries';
import {queryFunctionNameToDecorator} from './query_api_names';
import {removeQueryListToArrayCall} from './fn_to_array_removal';
import {replaceQueryListGetCall} from './fn_get_replacement';
import {checkForIncompatibleQueryListAccesses} from './incompatible_query_list_fns';
import {replaceQueryListFirstAndLastReferences} from './fn_first_last_replacement';
import {MigrationConfig} from './migration_config';
import {
filterBestEffortIncompatibilities,
markFieldIncompatibleInMetadata,
} from './incompatibility';
import {insertTodoForIncompatibility} from '../signal-migration/src/passes/problematic_patterns/incompatibility_todos';
import {checkInheritanceOfKnownFields} from '../signal-migration/src/passes/problematic_patterns/check_inheritance';
export interface CompilationUnitData {
knownQueryFields: Record<ClassFieldUniqueKey, {fieldName: string; isMulti: boolean}>;
// Potential queries problematic. We don't know what fields are queries during
// analysis, so this is very eagerly tracking all potential problematic "class fields".
potentialProblematicQueries: GlobalUnitData['problematicQueries'];
// Potential multi queries problematic. We don't know what fields are queries, or which
// ones are "multi" queries during analysis, so this is very eagerly tracking all
// potential problematic "class fields", but noting for later that those only would be
// problematic if they end up being multi-result queries.
potentialProblematicReferenceForMultiQueries: Record<ClassFieldUniqueKey, true>;
// NOTE: Not serializable — ONLY works when we know it's not running in batch mode!
reusableAnalysisReferences: Reference<ClassFieldDescriptor>[] | null;
}
export interface GlobalUnitData {
knownQueryFields: Record<ClassFieldUniqueKey, {fieldName: string; isMulti: boolean}>;
problematicQueries: Record<
ClassFieldUniqueKey,
{classReason: ClassIncompatibilityReason | null; fieldReason: FieldIncompatibilityReason | null}
>;
// NOTE: Not serializable — ONLY works when we know it's not running in batch mode!
reusableAnalysisReferences: Reference<ClassFieldDescriptor>[] | null;
}
ex | {
"end_byte": 4756,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/migration.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/migration.ts_4758_13341 | rt class SignalQueriesMigration extends TsurgeComplexMigration<
CompilationUnitData,
GlobalUnitData
> {
constructor(private readonly config: MigrationConfig = {}) {
super();
}
override async analyze(info: ProgramInfo): Promise<Serializable<CompilationUnitData>> {
assert(info.ngCompiler !== null, 'Expected queries migration to have an Angular program.');
// Pre-Analyze the program and get access to the template type checker.
const {templateTypeChecker} = info.ngCompiler['ensureAnalyzed']();
const {sourceFiles, program} = info;
const checker = program.getTypeChecker();
const reflector = new TypeScriptReflectionHost(checker);
const evaluator = new PartialEvaluator(reflector, checker, null);
const res: CompilationUnitData = {
knownQueryFields: {},
potentialProblematicQueries: {},
potentialProblematicReferenceForMultiQueries: {},
reusableAnalysisReferences: null,
};
const groupedAstVisitor = new GroupedTsAstVisitor(sourceFiles);
const referenceResult: ReferenceResult<ClassFieldDescriptor> = {references: []};
const classesWithFilteredQueries = new Set<ts.ClassDeclaration>();
const filteredQueriesForCompilationUnit = new Map<ClassFieldUniqueKey, {fieldName: string}>();
const findQueryDefinitionsVisitor = (node: ts.Node) => {
const extractedQuery = extractSourceQueryDefinition(node, reflector, evaluator, info);
if (extractedQuery !== null) {
const queryNode = extractedQuery.node;
const descriptor = {
key: extractedQuery.id,
node: queryNode,
};
const containingFile = projectFile(queryNode.getSourceFile(), info);
// If we have a config filter function, use it here for later
// perf-boosted reference lookups. Useful in non-batch mode.
if (
this.config.shouldMigrateQuery === undefined ||
this.config.shouldMigrateQuery(descriptor, containingFile)
) {
classesWithFilteredQueries.add(queryNode.parent);
filteredQueriesForCompilationUnit.set(extractedQuery.id, {
fieldName: extractedQuery.queryInfo.propertyName,
});
}
res.knownQueryFields[extractedQuery.id] = {
fieldName: extractedQuery.queryInfo.propertyName,
isMulti: extractedQuery.queryInfo.first === false,
};
if (ts.isAccessor(queryNode)) {
markFieldIncompatibleInMetadata(
res.potentialProblematicQueries,
extractedQuery.id,
FieldIncompatibilityReason.Accessor,
);
}
// Detect queries with union types that are uncommon to be
// automatically migrate-able. E.g. `refs: ElementRef|null`,
// or `ElementRef|SomeOtherType`.
if (
queryNode.type !== undefined &&
ts.isUnionTypeNode(queryNode.type) &&
// Either too large union, or doesn't match `T|undefined`.
(queryNode.type.types.length > 2 ||
!queryNode.type.types.some((t) => t.kind === ts.SyntaxKind.UndefinedKeyword))
) {
markFieldIncompatibleInMetadata(
res.potentialProblematicQueries,
extractedQuery.id,
FieldIncompatibilityReason.SignalQueries__IncompatibleMultiUnionType,
);
}
// Migrating fields with `@HostBinding` is incompatible as
// the host binding decorator does not invoke the signal.
const hostBindingDecorators = getAngularDecorators(
extractedQuery.fieldDecorators,
['HostBinding'],
/* isCore */ false,
);
if (hostBindingDecorators.length > 0) {
markFieldIncompatibleInMetadata(
res.potentialProblematicQueries,
extractedQuery.id,
FieldIncompatibilityReason.SignalIncompatibleWithHostBinding,
);
}
}
};
this.config.reportProgressFn?.(20, 'Scanning for queries..');
groupedAstVisitor.register(findQueryDefinitionsVisitor);
groupedAstVisitor.execute();
const allFieldsOrKnownQueries: KnownFields<ClassFieldDescriptor> = {
// Note: We don't support cross-target migration of `Partial<T>` usages.
// This is an acceptable limitation for performance reasons.
shouldTrackClassReference: (node) => classesWithFilteredQueries.has(node),
attemptRetrieveDescriptorFromSymbol: (s) => {
const descriptor = getClassFieldDescriptorForSymbol(s, info);
// If we are executing in upgraded analysis phase mode, we know all
// of the queries since there aren't any other compilation units.
// Ignore references to non-query class fields.
if (
this.config.assumeNonBatch &&
descriptor !== null &&
!filteredQueriesForCompilationUnit.has(descriptor.key)
) {
return null;
}
// In batch mode, we eagerly, rather expensively, track all references.
// We don't know yet if something refers to a different query or not, so we
// eagerly detect such and later filter those problematic references that
// turned out to refer to queries (once we have the global metadata).
return descriptor;
},
};
groupedAstVisitor.register(
createFindAllSourceFileReferencesVisitor(
info,
checker,
reflector,
info.ngCompiler['resourceManager'],
evaluator,
templateTypeChecker,
allFieldsOrKnownQueries,
// In non-batch mode, we know what inputs exist and can optimize the reference
// resolution significantly (for e.g. VSCode integration)— as we know what
// field names may be used to reference potential queries.
this.config.assumeNonBatch
? new Set(Array.from(filteredQueriesForCompilationUnit.values()).map((f) => f.fieldName))
: null,
referenceResult,
).visitor,
);
const inheritanceGraph = new InheritanceGraph(checker).expensivePopulate(info.sourceFiles);
checkIncompatiblePatterns(
inheritanceGraph,
checker,
groupedAstVisitor,
{
...allFieldsOrKnownQueries,
isFieldIncompatible: (f) =>
res.potentialProblematicQueries[f.key]?.fieldReason !== null ||
res.potentialProblematicQueries[f.key]?.classReason !== null,
markClassIncompatible: (clazz, reason) => {
for (const field of clazz.members) {
const key = getUniqueIDForClassProperty(field, info);
if (key !== null) {
res.potentialProblematicQueries[key] ??= {classReason: null, fieldReason: null};
res.potentialProblematicQueries[key].classReason = reason;
}
}
},
markFieldIncompatible: (f, incompatibility) =>
markFieldIncompatibleInMetadata(
res.potentialProblematicQueries,
f.key,
incompatibility.reason,
),
},
() => Array.from(classesWithFilteredQueries),
);
this.config.reportProgressFn?.(60, 'Scanning for references and problematic patterns..');
groupedAstVisitor.execute();
// Determine incompatible queries based on problematic references
// we saw in TS code, templates or host bindings.
for (const ref of referenceResult.references) {
if (isTsReference(ref) && ref.from.isWrite) {
markFieldIncompatibleInMetadata(
res.potentialProblematicQueries,
ref.target.key,
FieldIncompatibilityReason.WriteAssignment,
);
}
if ((isTemplateReference(ref) || isHostBindingReference(ref)) && ref.from.isWrite) {
markFieldIncompatibleInMetadata(
res.potentialProblematicQueries,
ref.target.key,
FieldIncompatibilityReason.WriteAssignment,
);
}
// TODO: Remove this when we support signal narrowing in templates.
// https://github.com/angular/angular/pull/55456.
if (isTemplateReference(ref) && ref.from.isLikelyPartOfNarrowing) {
markFieldIncompatibleInMetadata(
res.potentialProblematicQueries,
ref.target.key,
FieldIncompatibilityReason.PotentiallyNarrowedInTemplateButNoSupportYet,
);
}
// Check for other incompatible query list accesses.
checkForIncompatibleQueryListAccesses(ref, res);
}
if (this.config.assumeNonBatch) {
res.reusableAnalysisReferences = referenceResult.references;
}
return confirmAsSerializable(res);
}
ov | {
"end_byte": 13341,
"start_byte": 4758,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/migration.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/migration.ts_13345_16218 | de async combine(
unitA: CompilationUnitData,
unitB: CompilationUnitData,
): Promise<Serializable<CompilationUnitData>> {
const combined: CompilationUnitData = {
knownQueryFields: {},
potentialProblematicQueries: {},
potentialProblematicReferenceForMultiQueries: {},
reusableAnalysisReferences: null,
};
for (const unit of [unitA, unitB]) {
for (const [id, value] of Object.entries(unit.knownQueryFields)) {
combined.knownQueryFields[id as ClassFieldUniqueKey] = value;
}
for (const [id, info] of Object.entries(unit.potentialProblematicQueries)) {
if (info.fieldReason !== null) {
markFieldIncompatibleInMetadata(
combined.potentialProblematicQueries,
id as ClassFieldUniqueKey,
info.fieldReason,
);
}
if (info.classReason !== null) {
combined.potentialProblematicQueries[id as ClassFieldUniqueKey] ??= {
classReason: null,
fieldReason: null,
};
combined.potentialProblematicQueries[id as ClassFieldUniqueKey].classReason =
info.classReason;
}
}
for (const id of Object.keys(unit.potentialProblematicReferenceForMultiQueries)) {
combined.potentialProblematicReferenceForMultiQueries[id as ClassFieldUniqueKey] = true;
}
if (unit.reusableAnalysisReferences !== null) {
combined.reusableAnalysisReferences = unit.reusableAnalysisReferences;
}
}
for (const unit of [unitA, unitB]) {
for (const id of Object.keys(unit.potentialProblematicReferenceForMultiQueries)) {
if (combined.knownQueryFields[id as ClassFieldUniqueKey]?.isMulti) {
markFieldIncompatibleInMetadata(
combined.potentialProblematicQueries,
id as ClassFieldUniqueKey,
FieldIncompatibilityReason.SignalQueries__QueryListProblematicFieldAccessed,
);
}
}
}
return confirmAsSerializable(combined);
}
override async globalMeta(
combinedData: CompilationUnitData,
): Promise<Serializable<GlobalUnitData>> {
const globalUnitData: GlobalUnitData = {
knownQueryFields: combinedData.knownQueryFields,
problematicQueries: combinedData.potentialProblematicQueries,
reusableAnalysisReferences: combinedData.reusableAnalysisReferences,
};
for (const id of Object.keys(combinedData.potentialProblematicReferenceForMultiQueries)) {
if (combinedData.knownQueryFields[id as ClassFieldUniqueKey]?.isMulti) {
markFieldIncompatibleInMetadata(
globalUnitData.problematicQueries,
id as ClassFieldUniqueKey,
FieldIncompatibilityReason.SignalQueries__QueryListProblematicFieldAccessed,
);
}
}
return confirmAsSerializable(globalUnitData);
}
ov | {
"end_byte": 16218,
"start_byte": 13345,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/migration.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/migration.ts_16222_24171 | de async migrate(globalMetadata: GlobalUnitData, info: ProgramInfo) {
assert(info.ngCompiler !== null, 'Expected queries migration to have an Angular program.');
// Pre-Analyze the program and get access to the template type checker.
const {templateTypeChecker, metaReader} = info.ngCompiler['ensureAnalyzed']();
const {program, sourceFiles} = info;
const checker = program.getTypeChecker();
const reflector = new TypeScriptReflectionHost(checker);
const evaluator = new PartialEvaluator(reflector, checker, null);
const replacements: Replacement[] = [];
const importManager = new ImportManager();
const printer = ts.createPrinter();
const filesWithSourceQueries = new Map<ts.SourceFile, Set<QueryFunctionName>>();
const filesWithIncompleteMigration = new Map<ts.SourceFile, Set<QueryFunctionName>>();
const filesWithQueryListOutsideOfDeclarations = new WeakSet<ts.SourceFile>();
const knownQueries = new KnownQueries(info, this.config, globalMetadata);
const referenceResult: ReferenceResult<ClassFieldDescriptor> = {references: []};
const sourceQueries: ExtractedQuery[] = [];
// Detect all queries in this unit.
const queryWholeProgramVisitor = (node: ts.Node) => {
// Detect all SOURCE queries and migrate them, if possible.
const extractedQuery = extractSourceQueryDefinition(node, reflector, evaluator, info);
if (extractedQuery !== null) {
knownQueries.registerQueryField(extractedQuery.node, extractedQuery.id);
sourceQueries.push(extractedQuery);
return;
}
// Detect OTHER queries, inside `.d.ts`. Needed for reference resolution below.
if (
ts.isPropertyDeclaration(node) ||
(ts.isAccessor(node) && ts.isClassDeclaration(node.parent))
) {
const classFieldID = getUniqueIDForClassProperty(node, info);
if (classFieldID !== null && globalMetadata.knownQueryFields[classFieldID] !== undefined) {
knownQueries.registerQueryField(
node as typeof node & {parent: ts.ClassDeclaration},
classFieldID,
);
return;
}
}
// Detect potential usages of `QueryList` outside of queries or imports.
// Those prevent us from removing the import later.
if (
ts.isIdentifier(node) &&
node.text === 'QueryList' &&
ts.findAncestor(node, ts.isImportDeclaration) === undefined
) {
filesWithQueryListOutsideOfDeclarations.add(node.getSourceFile());
}
ts.forEachChild(node, queryWholeProgramVisitor);
};
this.config.reportProgressFn?.(40, 'Tracking query declarations..');
for (const sf of info.fullProgramSourceFiles) {
ts.forEachChild(sf, queryWholeProgramVisitor);
}
// Set of all queries in the program. Useful for speeding up reference
// lookups below.
const fieldNamesToConsiderForReferenceLookup = new Set(
Object.values(globalMetadata.knownQueryFields).map((f) => f.fieldName),
);
// Find all references.
const groupedAstVisitor = new GroupedTsAstVisitor(sourceFiles);
// Re-use previous reference result if available, instead of
// looking for references which is quite expensive.
if (globalMetadata.reusableAnalysisReferences !== null) {
referenceResult.references = globalMetadata.reusableAnalysisReferences;
} else {
groupedAstVisitor.register(
createFindAllSourceFileReferencesVisitor(
info,
checker,
reflector,
info.ngCompiler['resourceManager'],
evaluator,
templateTypeChecker,
knownQueries,
fieldNamesToConsiderForReferenceLookup,
referenceResult,
).visitor,
);
}
// Check inheritance.
// NOTE: Inheritance is only checked in the migrate stage as we cannot reliably
// check during analyze— where we don't know what fields from foreign `.d.ts`
// files refer to queries or not.
const inheritanceGraph = new InheritanceGraph(checker).expensivePopulate(info.sourceFiles);
checkInheritanceOfKnownFields(inheritanceGraph, metaReader, knownQueries, {
getFieldsForClass: (n) => knownQueries.getQueryFieldsOfClass(n) ?? [],
isClassWithKnownFields: (clazz) => knownQueries.getQueryFieldsOfClass(clazz) !== undefined,
});
this.config.reportProgressFn?.(70, 'Checking inheritance..');
groupedAstVisitor.execute();
if (this.config.bestEffortMode) {
filterBestEffortIncompatibilities(knownQueries);
}
this.config.reportProgressFn?.(80, 'Migrating queries..');
// Migrate declarations.
for (const extractedQuery of sourceQueries) {
const node = extractedQuery.node;
const sf = node.getSourceFile();
const descriptor = {key: extractedQuery.id, node: extractedQuery.node};
const incompatibility = knownQueries.getIncompatibilityForField(descriptor);
updateFileState(filesWithSourceQueries, sf, extractedQuery.kind);
if (incompatibility !== null) {
// Add a TODO for the incompatible query, if desired.
if (this.config.insertTodosForSkippedFields) {
replacements.push(
...insertTodoForIncompatibility(node, info, incompatibility, {
single: 'query',
plural: 'queries',
}),
);
}
updateFileState(filesWithIncompleteMigration, sf, extractedQuery.kind);
continue;
}
replacements.push(
...computeReplacementsToMigrateQuery(
node as ts.PropertyDeclaration,
extractedQuery,
importManager,
info,
printer,
info.userOptions,
checker,
),
);
}
// Migrate references.
const referenceMigrationHost: ReferenceMigrationHost<ClassFieldDescriptor> = {
printer,
replacements,
shouldMigrateReferencesToField: (field) => !knownQueries.isFieldIncompatible(field),
shouldMigrateReferencesToClass: (clazz) =>
!!knownQueries
.getQueryFieldsOfClass(clazz)
?.some((q) => !knownQueries.isFieldIncompatible(q)),
};
migrateTypeScriptReferences(referenceMigrationHost, referenceResult.references, checker, info);
migrateTemplateReferences(referenceMigrationHost, referenceResult.references);
migrateHostBindings(referenceMigrationHost, referenceResult.references, info);
migrateTypeScriptTypeReferences(
referenceMigrationHost,
referenceResult.references,
importManager,
info,
);
// Fix problematic calls, like `QueryList#toArray`, or `QueryList#get`.
for (const ref of referenceResult.references) {
removeQueryListToArrayCall(ref, info, globalMetadata, knownQueries, replacements);
replaceQueryListGetCall(ref, info, globalMetadata, knownQueries, replacements);
replaceQueryListFirstAndLastReferences(ref, info, globalMetadata, knownQueries, replacements);
}
// Remove imports if possible.
for (const [file, types] of filesWithSourceQueries) {
let seenIncompatibleMultiQuery = false;
for (const type of types) {
const incompatibleQueryTypesForFile = filesWithIncompleteMigration.get(file);
// Query type is fully migrated. No incompatible queries in file.
if (!incompatibleQueryTypesForFile?.has(type)) {
importManager.removeImport(file, queryFunctionNameToDecorator(type), '@angular/core');
} else if (type === 'viewChildren' || type === 'contentChildren') {
seenIncompatibleMultiQuery = true;
}
}
if (!seenIncompatibleMultiQuery && !filesWithQueryListOutsideOfDeclarations.has(file)) {
importManager.removeImport(file, 'QueryList', '@angular/core');
}
}
applyImportManagerChanges(importManager, replacements, sourceFiles, info);
return {replacements, knownQueries};
}
over | {
"end_byte": 24171,
"start_byte": 16222,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/migration.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/migration.ts_24175_26061 | async stats(globalMetadata: GlobalUnitData) {
let queriesCount = 0;
let multiQueries = 0;
let incompatibleQueries = 0;
const fieldIncompatibleCounts: Partial<Record<`incompat-field-${string}`, number>> = {};
const classIncompatibleCounts: Partial<Record<`incompat-class-${string}`, number>> = {};
for (const query of Object.values(globalMetadata.knownQueryFields)) {
queriesCount++;
if (query.isMulti) {
multiQueries++;
}
}
for (const [id, info] of Object.entries(globalMetadata.problematicQueries)) {
if (globalMetadata.knownQueryFields[id as ClassFieldUniqueKey] === undefined) {
continue;
}
incompatibleQueries++;
if (info.classReason !== null) {
const reasonName = ClassIncompatibilityReason[info.classReason];
const key = `incompat-class-${reasonName}` as const;
classIncompatibleCounts[key] ??= 0;
classIncompatibleCounts[key]++;
}
if (info.fieldReason !== null) {
const reasonName = FieldIncompatibilityReason[info.fieldReason];
const key = `incompat-field-${reasonName}` as const;
fieldIncompatibleCounts[key] ??= 0;
fieldIncompatibleCounts[key]++;
}
}
return {
counters: {
queriesCount,
multiQueries,
incompatibleQueries,
...fieldIncompatibleCounts,
...classIncompatibleCounts,
},
};
}
}
/**
* Updates the given map to capture the given query type.
* The map may track migrated queries in a file, or query types
* that couldn't be migrated.
*/
function updateFileState(
stateMap: Map<ts.SourceFile, Set<string>>,
node: ts.Node,
queryType: QueryFunctionName,
): void {
const file = node.getSourceFile();
if (!stateMap.has(file)) {
stateMap.set(file, new Set());
}
stateMap.get(file)!.add(queryType);
}
| {
"end_byte": 26061,
"start_byte": 24175,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/migration.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/convert_query_property.ts_0_5941 | /**
* @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 {ExtractedQuery} from './identify_queries';
import {ProgramInfo, projectFile, Replacement, TextUpdate} from '../../utils/tsurge';
import {ImportManager} from '@angular/compiler-cli/private/migrations';
import assert from 'assert';
import {WrappedNodeExpr} from '@angular/compiler';
import {removeFromUnionIfPossible} from '../signal-migration/src/utils/remove_from_union';
import {extractQueryListType} from './query_list_type';
/**
* A few notes on changes:
*
* @ViewChild()
* --> static is gone!
* --> read stays
*
* @ViewChildren()
* --> emitDistinctChangesOnly is gone!
* --> read stays
*
* @ContentChild()
* --> descendants stays
* --> read stays
* --> static is gone!
*
* @ContentChildren()
* --> descendants stays
* --> read stays
* --> emitDistinctChangesOnly is gone!
*/
export function computeReplacementsToMigrateQuery(
node: ts.PropertyDeclaration,
metadata: ExtractedQuery,
importManager: ImportManager,
info: ProgramInfo,
printer: ts.Printer,
options: ts.CompilerOptions,
checker: ts.TypeChecker,
): Replacement[] {
const sf = node.getSourceFile();
let newQueryFn = importManager.addImport({
requestedFile: sf,
exportModuleSpecifier: '@angular/core',
exportSymbolName: metadata.kind,
});
// The default value for descendants is `true`, except for `ContentChildren`.
const defaultDescendants = metadata.kind !== 'contentChildren';
const optionProperties: ts.PropertyAssignment[] = [];
const args: ts.Expression[] = [
metadata.args[0], // Locator.
];
let type = node.type;
// For multi queries, attempt to unwrap `QueryList` types, or infer the
// type from the initializer, if possible.
if (!metadata.queryInfo.first) {
if (type === undefined && node.initializer !== undefined) {
type = extractQueryListType(node.initializer);
} else if (type !== undefined) {
type = extractQueryListType(type);
}
}
if (metadata.queryInfo.read !== null) {
assert(metadata.queryInfo.read instanceof WrappedNodeExpr);
optionProperties.push(
ts.factory.createPropertyAssignment('read', metadata.queryInfo.read.node),
);
}
if (metadata.queryInfo.descendants !== defaultDescendants) {
optionProperties.push(
ts.factory.createPropertyAssignment(
'descendants',
metadata.queryInfo.descendants ? ts.factory.createTrue() : ts.factory.createFalse(),
),
);
}
if (optionProperties.length > 0) {
args.push(ts.factory.createObjectLiteralExpression(optionProperties));
}
const strictNullChecksEnabled = options.strict === true || options.strictNullChecks === true;
const strictPropertyInitialization =
options.strict === true || options.strictPropertyInitialization === true;
let isRequired = node.exclamationToken !== undefined;
// If we come across an application with strict null checks enabled, but strict
// property initialization is disabled, there are two options:
// - Either the query is already typed to include `undefined` explicitly,
// in which case an option query makes sense.
// - OR, the query is not typed to include `undefined`. In which case, the query
// should be marked as required to not break the app. The user-code throughout
// the application (given strict null checks) already assumes non-nullable!
if (
strictNullChecksEnabled &&
!strictPropertyInitialization &&
node.initializer === undefined &&
node.questionToken === undefined &&
type !== undefined &&
!checker.isTypeAssignableTo(checker.getUndefinedType(), checker.getTypeFromTypeNode(type))
) {
isRequired = true;
}
if (isRequired && metadata.queryInfo.first) {
// If the query is required already via some indicators, and this is a "single"
// query, use the available `.required` method.
newQueryFn = ts.factory.createPropertyAccessExpression(newQueryFn, 'required');
}
// If this query is still nullable (i.e. not required), attempt to remove
// explicit `undefined` types if possible.
if (!isRequired && type !== undefined && ts.isUnionTypeNode(type)) {
type = removeFromUnionIfPossible(type, (v) => v.kind !== ts.SyntaxKind.UndefinedKeyword);
}
let locatorType = Array.isArray(metadata.queryInfo.predicate)
? null
: metadata.queryInfo.predicate.expression;
let resolvedReadType = metadata.queryInfo.read ?? locatorType;
// If the original property type and the read type are matching, we can rely
// on the TS inference, instead of repeating types, like in `viewChild<Button>(Button)`.
if (
type !== undefined &&
resolvedReadType instanceof WrappedNodeExpr &&
ts.isIdentifier(resolvedReadType.node) &&
ts.isTypeReferenceNode(type) &&
ts.isIdentifier(type.typeName) &&
type.typeName.text === resolvedReadType.node.text
) {
locatorType = null;
}
const call = ts.factory.createCallExpression(
newQueryFn,
// If there is no resolved `ReadT` (e.g. string predicate), we use the
// original type explicitly as generic. Otherwise, query API is smart
// enough to always infer.
resolvedReadType === null && type !== undefined ? [type] : undefined,
args,
);
const updated = ts.factory.createPropertyDeclaration(
[ts.factory.createModifier(ts.SyntaxKind.ReadonlyKeyword)],
node.name,
undefined,
undefined,
call,
);
return [
new Replacement(
projectFile(node.getSourceFile(), info),
new TextUpdate({
position: node.getStart(),
end: node.getEnd(),
toInsert: printer.printNode(ts.EmitHint.Unspecified, updated, sf),
}),
),
];
}
| {
"end_byte": 5941,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/convert_query_property.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/identify_queries.ts_0_3234 | /**
* @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 {PartialEvaluator} from '@angular/compiler-cli/private/migrations';
import {
getAngularDecorators,
queryDecoratorNames,
} from '@angular/compiler-cli/src/ngtsc/annotations';
import {extractDecoratorQueryMetadata} from '@angular/compiler-cli/src/ngtsc/annotations/directive';
import {Decorator, ReflectionHost} from '@angular/compiler-cli/src/ngtsc/reflection';
import ts from 'typescript';
import {R3QueryMetadata} from '../../../../compiler';
import {ProgramInfo} from '../../utils/tsurge';
import {ClassFieldUniqueKey} from '../signal-migration/src/passes/reference_resolution/known_fields';
import {getUniqueIDForClassProperty} from './field_tracking';
import {FatalDiagnosticError} from '@angular/compiler-cli/src/ngtsc/diagnostics';
/** Type describing an extracted decorator query that can be migrated. */
export interface ExtractedQuery {
id: ClassFieldUniqueKey;
kind: 'viewChild' | 'viewChildren' | 'contentChild' | 'contentChildren';
args: ts.Expression[];
queryInfo: R3QueryMetadata;
node: (ts.PropertyDeclaration | ts.AccessorDeclaration) & {parent: ts.ClassDeclaration};
fieldDecorators: Decorator[];
}
/**
* Determines if the given node refers to a decorator-based query, and
* returns its resolved metadata if possible.
*/
export function extractSourceQueryDefinition(
node: ts.Node,
reflector: ReflectionHost,
evaluator: PartialEvaluator,
info: ProgramInfo,
): ExtractedQuery | null {
if (
(!ts.isPropertyDeclaration(node) && !ts.isAccessor(node)) ||
!ts.isClassDeclaration(node.parent) ||
node.parent.name === undefined ||
!ts.isIdentifier(node.name)
) {
return null;
}
const decorators = reflector.getDecoratorsOfDeclaration(node) ?? [];
const ngDecorators = getAngularDecorators(decorators, queryDecoratorNames, /* isCore */ false);
if (ngDecorators.length === 0) {
return null;
}
const decorator = ngDecorators[0];
const id = getUniqueIDForClassProperty(node, info);
if (id === null) {
return null;
}
let kind: ExtractedQuery['kind'];
if (decorator.name === 'ViewChild') {
kind = 'viewChild';
} else if (decorator.name === 'ViewChildren') {
kind = 'viewChildren';
} else if (decorator.name === 'ContentChild') {
kind = 'contentChild';
} else if (decorator.name === 'ContentChildren') {
kind = 'contentChildren';
} else {
throw new Error('Unexpected query decorator detected.');
}
let queryInfo: R3QueryMetadata | null = null;
try {
queryInfo = extractDecoratorQueryMetadata(
node,
decorator.name,
decorator.args ?? [],
node.name.text,
reflector,
evaluator,
);
} catch (e) {
if (!(e instanceof FatalDiagnosticError)) {
throw e;
}
console.error(`Skipping query: ${e.node.getSourceFile().fileName}: ${e.toString()}`);
return null;
}
return {
id,
kind,
args: decorator.args ?? [],
queryInfo,
node: node as typeof node & {parent: ts.ClassDeclaration},
fieldDecorators: decorators,
};
}
| {
"end_byte": 3234,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/identify_queries.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/fn_to_array_removal.ts_0_2419 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ProgramInfo, projectFile, Replacement, TextUpdate} from '../../utils/tsurge';
import {ClassFieldDescriptor} from '../signal-migration/src';
import {
isHostBindingReference,
isTemplateReference,
isTsReference,
Reference,
} from '../signal-migration/src/passes/reference_resolution/reference_kinds';
import {KnownQueries} from './known_queries';
import type {GlobalUnitData} from './migration';
import {checkNonTsReferenceCallsField, checkTsReferenceCallsField} from './property_accesses';
export function removeQueryListToArrayCall(
ref: Reference<ClassFieldDescriptor>,
info: ProgramInfo,
globalMetadata: GlobalUnitData,
knownQueries: KnownQueries,
replacements: Replacement[],
): void {
if (!isHostBindingReference(ref) && !isTemplateReference(ref) && !isTsReference(ref)) {
return;
}
if (knownQueries.isFieldIncompatible(ref.target)) {
return;
}
if (!globalMetadata.knownQueryFields[ref.target.key]?.isMulti) {
return;
}
// TS references.
if (isTsReference(ref)) {
const toArrayCallExpr = checkTsReferenceCallsField(ref, 'toArray');
if (toArrayCallExpr === null) {
return;
}
const toArrayExpr = toArrayCallExpr.expression;
replacements.push(
new Replacement(
projectFile(toArrayExpr.getSourceFile(), info),
new TextUpdate({
// Delete from expression end to call end. E.g. `.toArray(<..>)`.
position: toArrayExpr.expression.getEnd(),
end: toArrayCallExpr.getEnd(),
toInsert: '',
}),
),
);
return;
}
// Template and host binding references.
const callExpr = checkNonTsReferenceCallsField(ref, 'toArray');
if (callExpr === null) {
return;
}
const file = isHostBindingReference(ref) ? ref.from.file : ref.from.templateFile;
const offset = isHostBindingReference(ref) ? ref.from.hostPropertyNode.getStart() + 1 : 0;
replacements.push(
new Replacement(
file,
new TextUpdate({
// Delete from expression end to call end. E.g. `.toArray(<..>)`.
position: offset + callExpr.receiver.receiver.sourceSpan.end,
end: offset + callExpr.sourceSpan.end,
toInsert: '',
}),
),
);
}
| {
"end_byte": 2419,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/fn_to_array_removal.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/incompatible_query_list_fns.ts_0_1506 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ClassFieldDescriptor} from '../signal-migration/src';
import {
isHostBindingReference,
isTemplateReference,
isTsReference,
Reference,
} from '../signal-migration/src/passes/reference_resolution/reference_kinds';
import type {CompilationUnitData} from './migration';
import {checkNonTsReferenceAccessesField, checkTsReferenceAccessesField} from './property_accesses';
const problematicQueryListMethods = [
'dirty',
'changes',
'setDirty',
'reset',
'notifyOnChanges',
'destroy',
];
export function checkForIncompatibleQueryListAccesses(
ref: Reference<ClassFieldDescriptor>,
result: CompilationUnitData,
) {
if (isTsReference(ref)) {
for (const problematicFn of problematicQueryListMethods) {
const access = checkTsReferenceAccessesField(ref, problematicFn);
if (access !== null) {
result.potentialProblematicReferenceForMultiQueries[ref.target.key] = true;
return;
}
}
}
if (isHostBindingReference(ref) || isTemplateReference(ref)) {
for (const problematicFn of problematicQueryListMethods) {
const access = checkNonTsReferenceAccessesField(ref, problematicFn);
if (access !== null) {
result.potentialProblematicReferenceForMultiQueries[ref.target.key] = true;
return;
}
}
}
}
| {
"end_byte": 1506,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/incompatible_query_list_fns.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/migration_config.ts_0_1850 | /**
* @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 {ProjectFile} from '../../utils/tsurge';
import {ClassFieldDescriptor} from '../signal-migration/src/passes/reference_resolution/known_fields';
export interface MigrationConfig {
/**
* Whether to migrate as much as possible, even if certain
* queries would otherwise be marked as incompatible for migration.
*/
bestEffortMode?: boolean;
/**
* Whether to insert TODOs for skipped fields, and reasons on why they
* were skipped.
*/
insertTodosForSkippedFields?: boolean;
/**
* Whether the given query should be migrated. With batch execution, this
* callback fires for foreign queries from other compilation units too.
*
* Treating a query as non-migrated means that no references to it are
* migrated, nor the actual declaration (if it's part of the sources).
*
* If no function is specified here, the migration will migrate all
* inputs and references it discovers in compilation units. This is the
* running assumption for batch mode and LSC mode where the migration
* assumes all seen queries are migrated.
*/
shouldMigrateQuery?: (queryID: ClassFieldDescriptor, containingFile: ProjectFile) => boolean;
/**
* Whether to assume non-batch execution for speeding up things.
*
* This is useful for integration with the language service.
*/
assumeNonBatch?: boolean;
/**
* Optional function to receive updates on progress of the migration. Useful
* for integration with the language service to give some kind of indication
* what the migration is currently doing.
*/
reportProgressFn?: (percentage: number, updateMessage: string) => void;
}
| {
"end_byte": 1850,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/migration_config.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/known_queries.ts_0_6680 | /**
* @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 {ProgramInfo, projectFile} from '../../utils/tsurge';
import {ProblematicFieldRegistry} from '../signal-migration/src/passes/problematic_patterns/problematic_field_registry';
import {
ClassFieldDescriptor,
ClassFieldUniqueKey,
KnownFields,
} from '../signal-migration/src/passes/reference_resolution/known_fields';
import {getClassFieldDescriptorForSymbol} from './field_tracking';
import type {GlobalUnitData} from './migration';
import {InheritanceTracker} from '../signal-migration/src/passes/problematic_patterns/check_inheritance';
import {
FieldIncompatibility,
getMessageForClassIncompatibility,
getMessageForFieldIncompatibility,
} from '../signal-migration/src';
import {
ClassIncompatibilityReason,
FieldIncompatibilityReason,
} from '../signal-migration/src/passes/problematic_patterns/incompatibility';
import {markFieldIncompatibleInMetadata} from './incompatibility';
import {ExtractedQuery} from './identify_queries';
import {MigrationConfig} from './migration_config';
export class KnownQueries
implements
KnownFields<ClassFieldDescriptor>,
ProblematicFieldRegistry<ClassFieldDescriptor>,
InheritanceTracker<ClassFieldDescriptor>
{
private readonly classToQueryFields = new Map<ts.ClassLikeDeclaration, ClassFieldDescriptor[]>();
readonly knownQueryIDs = new Map<ClassFieldUniqueKey, ClassFieldDescriptor>();
constructor(
private readonly info: ProgramInfo,
private readonly config: MigrationConfig,
public globalMetadata: GlobalUnitData,
) {}
isFieldIncompatible(descriptor: ClassFieldDescriptor): boolean {
return this.getIncompatibilityForField(descriptor) !== null;
}
markFieldIncompatible(field: ClassFieldDescriptor, incompatibility: FieldIncompatibility): void {
markFieldIncompatibleInMetadata(
this.globalMetadata.problematicQueries,
field.key,
incompatibility.reason,
);
}
markClassIncompatible(node: ts.ClassDeclaration, reason: ClassIncompatibilityReason): void {
this.classToQueryFields.get(node)?.forEach((f) => {
this.globalMetadata.problematicQueries[f.key] ??= {classReason: null, fieldReason: null};
this.globalMetadata.problematicQueries[f.key].classReason = reason;
});
}
registerQueryField(queryField: ExtractedQuery['node'], id: ClassFieldUniqueKey) {
if (!this.classToQueryFields.has(queryField.parent)) {
this.classToQueryFields.set(queryField.parent, []);
}
this.classToQueryFields.get(queryField.parent)!.push({
key: id,
node: queryField,
});
this.knownQueryIDs.set(id, {key: id, node: queryField});
const descriptor: ClassFieldDescriptor = {key: id, node: queryField};
const file = projectFile(queryField.getSourceFile(), this.info);
if (
this.config.shouldMigrateQuery !== undefined &&
!this.config.shouldMigrateQuery(descriptor, file)
) {
this.markFieldIncompatible(descriptor, {
context: null,
reason: FieldIncompatibilityReason.SkippedViaConfigFilter,
});
}
}
attemptRetrieveDescriptorFromSymbol(symbol: ts.Symbol): ClassFieldDescriptor | null {
const descriptor = getClassFieldDescriptorForSymbol(symbol, this.info);
if (descriptor !== null && this.knownQueryIDs.has(descriptor.key)) {
return descriptor;
}
return null;
}
shouldTrackClassReference(clazz: ts.ClassDeclaration): boolean {
return this.classToQueryFields.has(clazz);
}
getQueryFieldsOfClass(clazz: ts.ClassDeclaration): ClassFieldDescriptor[] | undefined {
return this.classToQueryFields.get(clazz);
}
getAllClassesWithQueries(): ts.ClassDeclaration[] {
return Array.from(this.classToQueryFields.keys()).filter((c) => ts.isClassDeclaration(c));
}
captureKnownFieldInheritanceRelationship(
derived: ClassFieldDescriptor,
parent: ClassFieldDescriptor,
): void {
// Note: The edge problematic pattern recognition is not as good as the one
// we have in the signal input migration. That is because we couldn't trivially
// build up an inheritance graph during analyze phase where we DON'T know what
// fields refer to queries. Usually we'd use the graph to smartly propagate
// incompatibilities using topological sort. This doesn't work here and is
// unnecessarily complex, so we try our best at detecting direct edge
// incompatibilities (which are quite order dependent).
if (this.isFieldIncompatible(parent) && !this.isFieldIncompatible(derived)) {
this.markFieldIncompatible(derived, {
context: null,
reason: FieldIncompatibilityReason.ParentIsIncompatible,
});
return;
}
if (this.isFieldIncompatible(derived) && !this.isFieldIncompatible(parent)) {
this.markFieldIncompatible(parent, {
context: null,
reason: FieldIncompatibilityReason.DerivedIsIncompatible,
});
}
}
captureUnknownDerivedField(field: ClassFieldDescriptor): void {
this.markFieldIncompatible(field, {
context: null,
reason: FieldIncompatibilityReason.OverriddenByDerivedClass,
});
}
captureUnknownParentField(field: ClassFieldDescriptor): void {
this.markFieldIncompatible(field, {
context: null,
reason: FieldIncompatibilityReason.TypeConflictWithBaseClass,
});
}
getIncompatibilityForField(
descriptor: ClassFieldDescriptor,
): FieldIncompatibility | ClassIncompatibilityReason | null {
const problematicInfo = this.globalMetadata.problematicQueries[descriptor.key];
if (problematicInfo === undefined) {
return null;
}
if (problematicInfo.fieldReason !== null) {
return {context: null, reason: problematicInfo.fieldReason};
}
if (problematicInfo.classReason !== null) {
return problematicInfo.classReason;
}
return null;
}
getIncompatibilityTextForField(
field: ClassFieldDescriptor,
): {short: string; extra: string} | null {
const incompatibilityInfo = this.globalMetadata.problematicQueries[field.key];
if (incompatibilityInfo.fieldReason !== null) {
return getMessageForFieldIncompatibility(incompatibilityInfo.fieldReason, {
single: 'query',
plural: 'queries',
});
}
if (incompatibilityInfo.classReason !== null) {
return getMessageForClassIncompatibility(incompatibilityInfo.classReason, {
single: 'query',
plural: 'queries',
});
}
return null;
}
}
| {
"end_byte": 6680,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/known_queries.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/incompatibility.ts_0_1559 | /**
* @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 {FieldIncompatibilityReason} from '../signal-migration/src';
import {
nonIgnorableFieldIncompatibilities,
pickFieldIncompatibility,
} from '../signal-migration/src/passes/problematic_patterns/incompatibility';
import {ClassFieldUniqueKey} from '../signal-migration/src/passes/reference_resolution/known_fields';
import type {KnownQueries} from './known_queries';
import type {GlobalUnitData} from './migration';
export function markFieldIncompatibleInMetadata(
data: GlobalUnitData['problematicQueries'],
id: ClassFieldUniqueKey,
reason: FieldIncompatibilityReason,
) {
const existing = data[id as ClassFieldUniqueKey];
if (existing === undefined) {
data[id as ClassFieldUniqueKey] = {
fieldReason: reason,
classReason: null,
};
} else if (existing.fieldReason === null) {
existing.fieldReason = reason;
} else {
existing.fieldReason = pickFieldIncompatibility(
{reason, context: null},
{reason: existing.fieldReason, context: null},
).reason;
}
}
export function filterBestEffortIncompatibilities(knownQueries: KnownQueries) {
for (const query of Object.values(knownQueries.globalMetadata.problematicQueries)) {
if (
query.fieldReason !== null &&
!nonIgnorableFieldIncompatibilities.includes(query.fieldReason)
) {
query.fieldReason = null;
}
}
}
| {
"end_byte": 1559,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/incompatibility.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/migration.spec.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 {absoluteFrom} from '@angular/compiler-cli';
import {runTsurgeMigration} from '../../utils/tsurge/testing';
import {SignalQueriesMigration} from './migration';
import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {diffText} from '../../utils/tsurge/testing/diff';
import {dedent} from '../../utils/tsurge/testing/dedent';
import {setupTsurgeJasmineHelpers} from '../../utils/tsurge/testing/jasmine';
import ts from 'typescript';
interface TestCase {
id: string;
before: string;
after: string;
focus?: boolean;
options?: ts.CompilerOptions;
} | {
"end_byte": 805,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/migration.spec.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/migration.spec.ts_807_8517 | const declarationTestCases: TestCase[] = [
// View Child
{
id: 'viewChild with string locator and nullable',
before: `@ViewChild('myBtn') button: MyButton|undefined = undefined;`,
after: `readonly button = viewChild<MyButton>('myBtn');`,
},
{
id: 'viewChild with class type locator and nullable',
before: `@ViewChild(MyButton) button: MyButton|undefined = undefined;`,
after: `readonly button = viewChild(MyButton);`,
},
{
id: 'viewChild with class type locator and nullable via question-mark shorthand',
before: `@ViewChild(MyButton) button?: MyButton;`,
after: `readonly button = viewChild(MyButton);`,
},
{
id: 'viewChild with class type locator and exclamation mark to simulate required',
before: `@ViewChild(MyButton) button!: MyButton;`,
after: `readonly button = viewChild.required(MyButton);`,
},
{
id: 'viewChild with string locator and read option, nullable shorthand',
before: `@ViewChild('myBtn', {read: ElementRef}) buttonEl?: ElementRef;`,
after: `readonly buttonEl = viewChild('myBtn', { read: ElementRef });`,
},
{
id: 'viewChild with string locator and read option, required',
before: `@ViewChild('myBtn', {read: ElementRef}) buttonEl!: ElementRef;`,
after: `readonly buttonEl = viewChild.required('myBtn', { read: ElementRef });`,
},
// Content Child
{
id: 'contentChild with string locator and nullable',
before: `@ContentChild('myBtn') button: MyButton|undefined = undefined;`,
after: `readonly button = contentChild<MyButton>('myBtn');`,
},
{
id: 'contentChild with class type locator and nullable',
before: `@ContentChild(MyButton) button: MyButton|undefined = undefined;`,
after: `readonly button = contentChild(MyButton);`,
},
{
id: 'contentChild with class type locator and nullable via question-mark shorthand',
before: `@ContentChild(MyButton) button?: MyButton;`,
after: `readonly button = contentChild(MyButton);`,
},
{
id: 'contentChild with class type locator and exclamation mark to simulate required',
before: `@ContentChild(MyButton) button!: MyButton;`,
after: `readonly button = contentChild.required(MyButton);`,
},
{
id: 'contentChild with string locator and read option, nullable shorthand',
before: `@ContentChild('myBtn', {read: ElementRef}) buttonEl?: ElementRef;`,
after: `readonly buttonEl = contentChild('myBtn', { read: ElementRef });`,
},
{
id: 'contentChild with string locator and read option, required',
before: `@ContentChild('myBtn', {read: ElementRef}) buttonEl!: ElementRef;`,
after: `readonly buttonEl = contentChild.required('myBtn', { read: ElementRef });`,
},
{
id: 'contentChild with string locator and read option, required',
before: `@ContentChild('myBtn', {read: ElementRef}) buttonEl!: ElementRef;`,
after: `readonly buttonEl = contentChild.required('myBtn', { read: ElementRef });`,
},
{
id: 'contentChild with descendants option',
before: `@ContentChild('myBtn', {descendants: false}) buttonEl!: ElementRef;`,
after: `readonly buttonEl = contentChild.required<ElementRef>('myBtn', { descendants: false });`,
},
// ViewChildren
{
id: 'viewChildren with string locator and nullable',
before: `@ViewChildren('myBtn') button?: QueryList<ElementRef>;`,
after: `readonly button = viewChildren<ElementRef>('myBtn');`,
},
{
id: 'viewChildren with class type locator and nullable',
before: `@ViewChildren(MyButton) button?: QueryList<MyButton>;`,
after: `readonly button = viewChildren(MyButton);`,
},
{
id: 'viewChildren with class type locator and exclamation mark',
before: `@ViewChildren(MyButton) button!: QueryList<MyButton>;`,
after: `readonly button = viewChildren(MyButton);`,
},
{
id: 'viewChild with string locator and read option, nullable shorthand',
before: `@ViewChildren('myBtn', {read: ElementRef}) buttonEl?: QueryList<ElementRef>;`,
after: `readonly buttonEl = viewChildren('myBtn', { read: ElementRef });`,
},
{
id: 'viewChildren with string locator and read option, required',
before: `@ViewChildren('myBtn', {read: ElementRef}) buttonEl!: QueryList<ElementRef>;`,
after: `readonly buttonEl = viewChildren('myBtn', { read: ElementRef });`,
},
{
id: 'viewChildren with query list as initializer value',
before: `@ViewChildren('myBtn') buttonEl = new QueryList<ElementRef>()`,
after: `readonly buttonEl = viewChildren<ElementRef>('myBtn');`,
},
{
id: 'viewChildren with query list as initializer value, and descendants option',
before: `@ViewChildren('myBtn', {descendants: false}) buttonEl = new QueryList<ElementRef>()`,
after: `readonly buttonEl = viewChildren<ElementRef>('myBtn', { descendants: false });`,
},
{
id: 'viewChildren with query list as initializer value, and descendants option but same as default',
before: `@ViewChildren('myBtn', {descendants: true}) buttonEl = new QueryList<ElementRef>()`,
after: `readonly buttonEl = viewChildren<ElementRef>('myBtn');`,
},
// ContentChildren
{
id: 'contentChildren with string locator and nullable',
before: `@ContentChildren('myBtn') button?: QueryList<ElementRef>;`,
after: `readonly button = contentChildren<ElementRef>('myBtn');`,
},
{
id: 'contentChildren with class type locator and nullable',
before: `@ContentChildren(MyButton) button?: QueryList<MyButton>;`,
after: `readonly button = contentChildren(MyButton);`,
},
{
id: 'contentChildren with class type locator and exclamation mark',
before: `@ContentChildren(MyButton) button!: QueryList<MyButton>;`,
after: `readonly button = contentChildren(MyButton);`,
},
{
id: 'contentChildren with string locator and read option, nullable shorthand',
before: `@ContentChildren('myBtn', {read: ElementRef}) buttonEl?: QueryList<ElementRef>;`,
after: `readonly buttonEl = contentChildren('myBtn', { read: ElementRef });`,
},
{
id: 'contentChildren with string locator and read option, required',
before: `@ContentChildren('myBtn', {read: ElementRef}) buttonEl!: QueryList<ElementRef>;`,
after: `readonly buttonEl = contentChildren('myBtn', { read: ElementRef });`,
},
{
id: 'contentChildren with query list as initializer value',
before: `@ContentChildren('myBtn') buttonEl = new QueryList<ElementRef>()`,
after: `readonly buttonEl = contentChildren<ElementRef>('myBtn');`,
},
{
id: 'contentChildren with query list as initializer value, and descendants option',
before: `@ContentChildren('myBtn', {descendants: true}) buttonEl = new QueryList<ElementRef>()`,
after: `readonly buttonEl = contentChildren<ElementRef>('myBtn', { descendants: true });`,
},
{
id: 'contentChildren with query list as initializer value, and descendants option but same as default',
before: `@ContentChildren('myBtn', {descendants: false}) buttonEl = new QueryList<ElementRef>()`,
after: `readonly buttonEl = contentChildren<ElementRef>('myBtn');`,
},
// custom cases.
{
id: 'query with no resolvable ReadT',
before: `@ContentChild('myBtn') buttonEl?: ElementRef`,
after: `readonly buttonEl = contentChild<ElementRef>('myBtn');`,
},
{
id: 'query with explicit ReadT',
before: `@ContentChild('myBtn', {read: ButtonEl}) buttonEl?: ButtonEl`,
after: `readonly buttonEl = contentChild('myBtn', { read: ButtonEl });`,
},
{
id: 'query with explicit ReadT',
before: `@ContentChild(SomeDir, {read: ElementRef}) buttonEl!: ElementRef`,
after: `readonly buttonEl = contentChild.required(SomeDir, { read: ElementRef });`,
}, | {
"end_byte": 8517,
"start_byte": 807,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/migration.spec.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/migration.spec.ts_8520_9802 | {
id: 'query with no initializer and strict null checks enabled',
before: `@ContentChild(ButtonEl) buttonEl: ElementRef;`,
// with --strictNullChecks, `buttonEl` is technically required and the
// user code assumes that throughout the project; as the type does not include
// `undefined.`
after: `readonly buttonEl = contentChild.required(ButtonEl);`,
options: {strict: false, strictNullChecks: true},
},
{
id: 'query with no initializer, strict null checks enabled, but includes `undefined` in type',
before: `@ContentChild(ButtonEl) buttonEl: ElementRef|undefined;`,
// `undefined` is explicitly included, so keeping as an optional query
// is a reasonable migration without runtime changes.
after: `readonly buttonEl = contentChild(ButtonEl);`,
options: {strict: false, strictNullChecks: true},
},
{
id: 'query with no initializer, strict null checks enabled, includes `undefined` via question mark',
before: `@ContentChild(ButtonEl) buttonEl?: ElementRef;`,
// `undefined` is explicitly included, so keeping as an optional query
// is a reasonable migration without runtime changes.
after: `readonly buttonEl = contentChild(ButtonEl);`,
options: {strict: false, strictNullChecks: true},
},
]; | {
"end_byte": 9802,
"start_byte": 8520,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/migration.spec.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/migration.spec.ts_9804_18717 | describe('signal queries migration', () => {
beforeEach(() => {
setupTsurgeJasmineHelpers();
initMockFileSystem('Native');
});
describe('declaration test cases', () => {
for (const c of declarationTestCases) {
(c.focus ? fit : it)(c.id, async () => {
const {fs} = await runTsurgeMigration(
new SignalQueriesMigration(),
[
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: populateDeclarationTestCaseComponent(c.before),
},
],
c.options,
);
let actual = fs.readFile(absoluteFrom('/app.component.ts'));
let expected = populateDeclarationTestCaseComponent(c.after);
// Cut off the string before the class declaration.
// The import diff is irrelevant here for now.
actual = actual.substring(actual.indexOf('@Directive'));
expected = expected.substring(expected.indexOf('@Directive'));
if (actual !== expected) {
expect(diffText(expected, actual)).toBe('');
}
});
}
});
it('should not migrate if there is a write to a query', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: `
import {ViewChild, ElementRef, Directive} from '@angular/core';
@Directive()
class MyComp {
@ViewChild('labelRef') label?: ElementRef;
click() {
this.label = undefined;
}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).not.toContain(`viewChild`);
expect(actual).toContain(`@ViewChild('labelRef') label?: ElementRef;`);
});
it('should update imports when migrating', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: `
import {ViewChild, ElementRef, Directive} from '@angular/core';
@Directive()
class MyComp {
@ViewChild('labelRef') label?: ElementRef;
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toContain(`import {ElementRef, Directive, viewChild} from '@angular/core';`);
expect(actual).toContain(`label = viewChild<ElementRef>('labelRef')`);
});
it('should update TS references when migrating', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChild, ElementRef, Directive} from '@angular/core';
@Directive()
class MyComp {
@ViewChild('labelRef') label?: ElementRef;
@ViewChild('always', {read: ElementRef}) always!: ElementRef;
doSmth() {
if (this.label !== undefined) {
this.label.nativeElement.textContent;
}
this.always.nativeElement.textContent;
}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ElementRef, Directive, viewChild} from '@angular/core';
@Directive()
class MyComp {
readonly label = viewChild<ElementRef>('labelRef');
readonly always = viewChild.required('always', { read: ElementRef });
doSmth() {
const label = this.label();
if (label !== undefined) {
label.nativeElement.textContent;
}
this.always().nativeElement.textContent;
}
}
`);
});
it('should update template references when migrating', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChild, ElementRef, Component} from '@angular/core';
@Component({
template: '<div>{{label}}</div>'
})
class MyComp {
@ViewChild('labelRef') label?: ElementRef;
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ElementRef, Component, viewChild} from '@angular/core';
@Component({
template: '<div>{{label()}}</div>'
})
class MyComp {
readonly label = viewChild<ElementRef>('labelRef');
}
`);
});
it(
'should update references part of control flow expressions that cannot narrow ' +
'(due to no second usage inside the template)',
async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChild, ElementRef, Component} from '@angular/core';
@Component({
template: '<div *ngIf="label !== undefined">Showing</div>'
})
class MyComp {
@ViewChild('labelRef') label?: ElementRef;
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ElementRef, Component, viewChild} from '@angular/core';
@Component({
template: '<div *ngIf="label() !== undefined">Showing</div>'
})
class MyComp {
readonly label = viewChild<ElementRef>('labelRef');
}
`);
},
);
it('should not update references part of narrowing template expressions', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChild, ElementRef, Component} from '@angular/core';
@Component({
template: \`
<div *ngIf="label !== undefined">
{{label.nativeElement.textContent}}
</div>\`
})
class MyComp {
@ViewChild('labelRef') label?: ElementRef;
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ViewChild, ElementRef, Component} from '@angular/core';
@Component({
template: \`
<div *ngIf="label !== undefined">
{{label.nativeElement.textContent}}
</div>\`
})
class MyComp {
@ViewChild('labelRef') label?: ElementRef;
}
`);
});
it('should update references in host bindings', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChild, ElementRef, Component} from '@angular/core';
@Component({
template: '',
host: {
'(click)': 'label.textContent',
}
})
class MyComp {
@ViewChild('labelRef') label?: ElementRef;
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ElementRef, Component, viewChild} from '@angular/core';
@Component({
template: '',
host: {
'(click)': 'label().textContent',
}
})
class MyComp {
readonly label = viewChild<ElementRef>('labelRef');
}
`);
});
it('should not remove imports when partially migrating', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: `
import {ViewChild, ElementRef, Directive} from '@angular/core';
@Directive()
class MyComp {
@ViewChild('labelRef') label?: ElementRef;
@ViewChild('labelRef2') label2?: ElementRef;
click() {
this.label2 = undefined;
}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toContain(
`import {ViewChild, ElementRef, Directive, viewChild} from '@angular/core';`,
);
expect(actual).toContain(`label = viewChild<ElementRef>('labelRef')`);
expect(actual).toContain(`@ViewChild('labelRef2') label2?: ElementRef;`);
}); | {
"end_byte": 18717,
"start_byte": 9804,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/migration.spec.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/migration.spec.ts_18721_27326 | it('should not migrate if query class is manually instantiated', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: `
import {ViewChild, ElementRef, Directive} from '@angular/core';
@Directive()
class MyComp implements CompInterface {
@ViewChild('labelRef') label?: ElementRef;
}
new MyComp();
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).not.toContain(`viewChild`);
expect(actual).toContain(`@ViewChild`);
});
describe('inheritance', () => {
it('should not migrate if member is inherited from interface', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: `
import {ViewChild, ElementRef, Directive} from '@angular/core';
interface CompInterface {
label: ElementRef;
}
@Directive()
class MyComp implements CompInterface {
@ViewChild('labelRef') label?: ElementRef;
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).not.toContain(`viewChild`);
expect(actual).toContain(`@ViewChild`);
});
it('should not migrate if member is overridden via derived class', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: `
import {ViewChild, ElementRef, Directive} from '@angular/core';
@Directive()
class MyComp implements CompInterface {
@ViewChild('labelRef') label?: ElementRef;
}
class Derived extends MyComp {
override label: ElementRef;
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).not.toContain(`viewChild`);
expect(actual).toContain(`@ViewChild`);
});
});
it('should remove QueryList imports', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: ''
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ElementRef, Component, viewChildren} from '@angular/core';
@Component({
template: ''
})
class MyComp {
readonly labels = viewChildren<ElementRef>('label');
}
`);
});
it('should not remove QueryList import when used elsewhere', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: ''
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
bla: QueryList<ElementRef> = null!;
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {QueryList, ElementRef, Component, viewChildren} from '@angular/core';
@Component({
template: ''
})
class MyComp {
readonly labels = viewChildren<ElementRef>('label');
bla: QueryList<ElementRef> = null!;
}
`);
});
it('should not remove QueryList import when part of skipped query', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: ''
})
class MyComp {
@ViewChildren('label') labels: QueryList|null = new QueryList<ElementRef>();
click() {
this.labels = null;
}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: ''
})
class MyComp {
@ViewChildren('label') labels: QueryList|null = new QueryList<ElementRef>();
click() {
this.labels = null;
}
}
`);
});
it('should remove `toArray` function calls for multi queries', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: ''
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
click() {
this.labels.toArray().some(bla);
}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ElementRef, Component, viewChildren} from '@angular/core';
@Component({
template: ''
})
class MyComp {
readonly labels = viewChildren<ElementRef>('label');
click() {
this.labels().some(bla);
}
}
`);
});
it('should remove `toArray` function calls for multi queries, with control flow', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: ''
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
click() {
if (this.labels) {
this.labels.toArray().some(bla);
}
}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ElementRef, Component, viewChildren} from '@angular/core';
@Component({
template: ''
})
class MyComp {
readonly labels = viewChildren<ElementRef>('label');
click() {
const labels = this.labels();
if (labels) {
labels.some(bla);
}
}
}
`);
});
it('should remove `toArray` function calls in templates and host bindings', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '{{ labels.toArray().some(bla) }}',
host: {
'[id]': 'labels.toArray().find(bla)',
}
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ElementRef, Component, viewChildren} from '@angular/core';
@Component({
template: '{{ labels().some(bla) }}',
host: {
'[id]': 'labels().find(bla)',
}
})
class MyComp {
readonly labels = viewChildren<ElementRef>('label');
}
`);
}); | {
"end_byte": 27326,
"start_byte": 18721,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/migration.spec.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/migration.spec.ts_27330_36209 | it('should not update `toArray` function calls if query is incompatible', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: ''
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
click() {
this.labels.destroy();
this.labels.toArray().some(bla);
}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: ''
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
click() {
this.labels.destroy();
this.labels.toArray().some(bla);
}
}
`);
});
it('should replace `get` function calls for multi queries', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: ''
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
click() {
if (this.labels) {
this.labels.get(1)?.nativeElement;
}
}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ElementRef, Component, viewChildren} from '@angular/core';
@Component({
template: ''
})
class MyComp {
readonly labels = viewChildren<ElementRef>('label');
click() {
const labels = this.labels();
if (labels) {
labels.at(1)?.nativeElement;
}
}
}
`);
});
it('should replace `get` function calls in templates and host bindings', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ContentChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '{{ labels.get(0).nativeElement.textContent }}',
host: {
'[id]': 'labels.get(0).nativeElement.textContent',
}
})
class MyComp {
@ContentChildren('label') labels = new QueryList<ElementRef>();
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ElementRef, Component, contentChildren} from '@angular/core';
@Component({
template: '{{ labels().at(0).nativeElement.textContent }}',
host: {
'[id]': 'labels().at(0).nativeElement.textContent',
}
})
class MyComp {
readonly labels = contentChildren<ElementRef>('label');
}
`);
});
it('should not migrate a query relying on QueryList#changes', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ContentChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ContentChildren('label') labels = new QueryList<ElementRef>();
ngOnInit() {
this.labels.changes.subscribe(() => {});
}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ContentChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ContentChildren('label') labels = new QueryList<ElementRef>();
ngOnInit() {
this.labels.changes.subscribe(() => {});
}
}
`);
});
it('should not migrate a query relying on QueryList#reset', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ContentChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ContentChildren('label') labels = new QueryList<ElementRef>();
ngOnInit() {
this.labels.reset();
}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ContentChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ContentChildren('label') labels = new QueryList<ElementRef>();
ngOnInit() {
this.labels.reset();
}
}
`);
});
it('should not migrate a query relying on QueryList#dirty', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ContentChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ContentChildren('label') labels = new QueryList<ElementRef>();
ngOnInit() {
const isDirty = this.labels.dirty;
}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ContentChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ContentChildren('label') labels = new QueryList<ElementRef>();
ngOnInit() {
const isDirty = this.labels.dirty;
}
}
`);
});
it('should not migrate a query relying on QueryList#setDirty', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
ngOnInit() {
this.labels.setDirty();
}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
ngOnInit() {
this.labels.setDirty();
}
}
`);
});
it('should not migrate a query relying on QueryList#notifyOnChanges', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
ngOnInit() {
this.labels.notifyOnChanges();
}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
ngOnInit() {
this.labels.notifyOnChanges();
}
}
`);
}); | {
"end_byte": 36209,
"start_byte": 27330,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/migration.spec.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/migration.spec.ts_36213_43579 | it('should not migrate a query relying on QueryList#destroy', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '<button (click)="labels.destroy()"></button>',
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '<button (click)="labels.destroy()"></button>',
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
}
`);
});
it(
'should migrate a single-result query that accesses a `.changes` field, ' +
'unrelated to QueryList',
async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChild, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ViewChild('label') label!: ElementRef;
ngOnInit() {
this.label.changes;
}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ElementRef, Component, viewChild} from '@angular/core';
@Component({
template: '',
})
class MyComp {
readonly label = viewChild.required<ElementRef>('label');
ngOnInit() {
this.label().changes;
}
}
`);
},
);
it('should migrate `QueryList#first`', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
ngOnInit() {
if (this.labels.first.nativeElement.textContent) {
// do smth.
};
}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ElementRef, Component, viewChildren} from '@angular/core';
@Component({
template: '',
})
class MyComp {
readonly labels = viewChildren<ElementRef>('label');
ngOnInit() {
if (this.labels().at(0)!.nativeElement.textContent) {
// do smth.
};
}
}
`);
});
it('should migrate `QueryList#last`', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
ngOnInit() {
if (this.labels.last.nativeElement.textContent) {
// do smth.
};
}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ElementRef, Component, viewChildren} from '@angular/core';
@Component({
template: '',
})
class MyComp {
readonly labels = viewChildren<ElementRef>('label');
ngOnInit() {
if (this.labels().at(-1)!.nativeElement.textContent) {
// do smth.
};
}
}
`);
});
it('should preserve existing property comments', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
/** works */
@ViewChildren('label') labels = new QueryList<ElementRef>();
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ElementRef, Component, viewChildren} from '@angular/core';
@Component({
template: '',
})
class MyComp {
/** works */
readonly labels = viewChildren<ElementRef>('label');
}
`);
});
it('should not break at runtime if there is an invalid query', async () => {
await expectAsync(
runTsurgeMigration(new SignalQueriesMigration(), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ContentChild, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
// missing predicate/selector.
@ContentChild() labels = new QueryList<ElementRef>();
}
`,
},
]),
).not.toBeRejected();
});
it('should properly deal with union types of single queries', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration({}), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChild, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ViewChild(MyService) bla: MyService|undefined = undefined;
@ViewChild(MyService) bla2?: MyService;
@ViewChild(MyService) bla3: MyService|null = null;
@ViewChild(MyService) bla4: MyService|SomethingUnrelated = null!;
@ViewChild(MyService) bla5!: MyService|SomethingUnrelated;
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ViewChild, ElementRef, Component, viewChild} from '@angular/core';
@Component({
template: '',
})
class MyComp {
readonly bla = viewChild(MyService);
readonly bla2 = viewChild(MyService);
@ViewChild(MyService) bla3: MyService|null = null;
@ViewChild(MyService) bla4: MyService|SomethingUnrelated = null!;
@ViewChild(MyService) bla5!: MyService|SomethingUnrelated;
}
`);
}); | {
"end_byte": 43579,
"start_byte": 36213,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/migration.spec.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/migration.spec.ts_43583_51073 | describe('--best-effort-mode', () => {
it('should be possible to forcibly migrate even with a detected `.changes` access', async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration({bestEffortMode: true}), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
click() {
this.labels.changes.subscribe();
}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ElementRef, Component, viewChildren} from '@angular/core';
@Component({
template: '',
})
class MyComp {
readonly labels = viewChildren<ElementRef>('label');
click() {
this.labels().changes.subscribe();
}
}
`);
});
it(`should not forcibly migrate if it's an accessor field`, async () => {
const {fs} = await runTsurgeMigration(new SignalQueriesMigration({bestEffortMode: true}), [
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ViewChildren('label')
set labels(list: QueryList<ElementRef>) {}
}
`,
},
]);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ViewChildren('label')
set labels(list: QueryList<ElementRef>) {}
}
`);
});
});
describe('--insert-todos-for-skipped-fields', () => {
it('should add a TODO for queries accessing QueryList#changes', async () => {
const {fs} = await runTsurgeMigration(
new SignalQueriesMigration({insertTodosForSkippedFields: true}),
[
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ViewChildren('label') labels = new QueryList<ElementRef>();
click() {
this.labels.changes.subscribe();
}
}
`,
},
],
);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
// TODO: Skipped for migration because:
// There are references to this query that cannot be migrated automatically.
@ViewChildren('label') labels = new QueryList<ElementRef>();
click() {
this.labels.changes.subscribe();
}
}
`);
});
it(`should add a TODO for incompatible accessor fields`, async () => {
const {fs} = await runTsurgeMigration(
new SignalQueriesMigration({insertTodosForSkippedFields: true}),
[
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ViewChildren('label')
set labels(list: QueryList<ElementRef>) {}
}
`,
},
],
);
const actual = fs.readFile(absoluteFrom('/app.component.ts'));
expect(actual).toMatchWithDiff(`
import {ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
// TODO: Skipped for migration because:
// Accessor queries cannot be migrated as they are too complex.
@ViewChildren('label')
set labels(list: QueryList<ElementRef>) {}
}
`);
});
});
it(`should be able to compute statistics`, async () => {
const {getStatistics} = await runTsurgeMigration(
new SignalQueriesMigration({insertTodosForSkippedFields: true}),
[
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChild, ViewChildren, QueryList, ElementRef, Component} from '@angular/core';
@Component({
template: '',
})
class MyComp {
@ViewChildren('label')
set labels(list: QueryList<ElementRef>) {}
@ViewChildren('refs') bla!: QueryList<ElementRef>;
@ViewChild('refs') blaWrittenTo?: ElementRef;
click() {
this.blaWrittenTo = undefined;
}
}
`,
},
],
);
expect(await getStatistics()).toEqual({
counters: {
queriesCount: 3,
multiQueries: 2,
incompatibleQueries: 2,
'incompat-field-Accessor': 1,
'incompat-field-WriteAssignment': 1,
},
});
});
it(`should skip queries that are annotated with @HostBinding`, async () => {
const {fs} = await runTsurgeMigration(
new SignalQueriesMigration({insertTodosForSkippedFields: true}),
[
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: dedent`
import {ViewChild, HostBinding, Component, ElementRef} from '@angular/core';
@Component({template: ''})
class MyComp {
@HostBinding('[attr.ref-name]')
@ViewChild('ref', {read: RefNameStringToken})
ref!: string;
}
`,
},
],
);
expect(fs.readFile(absoluteFrom('/app.component.ts'))).toMatchWithDiff(`
import {ViewChild, HostBinding, Component, ElementRef} from '@angular/core';
@Component({template: ''})
class MyComp {
// TODO: Skipped for migration because:
// This query is used in combination with \`@HostBinding\` and migrating would
// break.
@HostBinding('[attr.ref-name]')
@ViewChild('ref', {read: RefNameStringToken})
ref!: string;
}
`);
});
});
function populateDeclarationTestCaseComponent(declaration: string): string {
return `
import {
ViewChild,
ViewChildren,
ContentChild,
ContentChildren,
Directive
} from '@angular/core';
type ElementRef = {};
@Directive()
export class TestDir {
${declaration}
}
`;
} | {
"end_byte": 51073,
"start_byte": 43583,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/migration.spec.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/BUILD.bazel_0_1384 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
ts_library(
name = "migration",
srcs = glob(
["**/*.ts"],
exclude = ["*.spec.ts"],
),
visibility = [
"//packages/core/schematics/ng-generate/signal-queries-migration:__pkg__",
"//packages/language-service/src/refactorings:__pkg__",
],
deps = [
"//packages/compiler",
"//packages/compiler-cli",
"//packages/compiler-cli/private",
"//packages/compiler-cli/src/ngtsc/annotations",
"//packages/compiler-cli/src/ngtsc/annotations/directive",
"//packages/compiler-cli/src/ngtsc/diagnostics",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/core/schematics/migrations/signal-migration/src",
"//packages/core/schematics/utils/tsurge",
"@npm//@types/node",
"@npm//typescript",
],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(
["**/*.spec.ts"],
),
deps = [
":migration",
"//packages/compiler-cli",
"//packages/compiler-cli/src/ngtsc/file_system/testing",
"//packages/core/schematics/utils/tsurge",
"@npm//typescript",
],
)
jasmine_node_test(
name = "test",
srcs = [":test_lib"],
env = {"FORCE_COLOR": "3"},
)
| {
"end_byte": 1384,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/BUILD.bazel"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/index.ts_0_269 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './migration_config';
export * from './migration';
| {
"end_byte": 269,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/index.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/field_tracking.ts_0_2067 | /**
* @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 {ProgramInfo, projectFile} from '../../utils/tsurge';
import {
ClassFieldDescriptor,
ClassFieldUniqueKey,
} from '../signal-migration/src/passes/reference_resolution/known_fields';
/**
* Attempts to get a class field descriptor if the given symbol
* points to a class field.
*/
export function getClassFieldDescriptorForSymbol(
symbol: ts.Symbol,
info: ProgramInfo,
): ClassFieldDescriptor | null {
if (
symbol?.valueDeclaration === undefined ||
!ts.isPropertyDeclaration(symbol.valueDeclaration)
) {
return null;
}
const key = getUniqueIDForClassProperty(symbol.valueDeclaration, info);
if (key === null) {
return null;
}
return {
key,
node: symbol.valueDeclaration,
};
}
/**
* Gets a unique ID for the given class property.
*
* This is useful for matching class fields across compilation units.
* E.g. a reference may point to the field via `.d.ts`, while the other
* may reference it via actual `.ts` sources. IDs for the same fields
* would then match identity.
*/
export function getUniqueIDForClassProperty(
property: ts.ClassElement,
info: ProgramInfo,
): ClassFieldUniqueKey | null {
if (!ts.isClassDeclaration(property.parent) || property.parent.name === undefined) {
return null;
}
if (property.name === undefined) {
return null;
}
const id = projectFile(property.getSourceFile(), info).id.replace(/\.d\.ts$/, '.ts');
// Note: If a class is nested, there could be an ID clash.
// This is highly unlikely though, and this is not a problem because
// in such cases, there is even less chance there are any references to
// a non-exported classes; in which case, cross-compilation unit references
// likely can't exist anyway.
return `${id}-${property.parent.name.text}-${property.name.getText()}` as ClassFieldUniqueKey;
}
| {
"end_byte": 2067,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/field_tracking.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/fn_first_last_replacement.ts_0_2364 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ProgramInfo, projectFile, Replacement, TextUpdate} from '../../utils/tsurge';
import {ClassFieldDescriptor} from '../signal-migration/src';
import {
isHostBindingReference,
isTemplateReference,
isTsReference,
Reference,
} from '../signal-migration/src/passes/reference_resolution/reference_kinds';
import {KnownQueries} from './known_queries';
import type {GlobalUnitData} from './migration';
import {checkNonTsReferenceAccessesField, checkTsReferenceAccessesField} from './property_accesses';
const mapping = new Map([
['first', 'at(0)!'],
['last', 'at(-1)!'],
]);
export function replaceQueryListFirstAndLastReferences(
ref: Reference<ClassFieldDescriptor>,
info: ProgramInfo,
globalMetadata: GlobalUnitData,
knownQueries: KnownQueries,
replacements: Replacement[],
): void {
if (!isHostBindingReference(ref) && !isTemplateReference(ref) && !isTsReference(ref)) {
return;
}
if (knownQueries.isFieldIncompatible(ref.target)) {
return;
}
if (!globalMetadata.knownQueryFields[ref.target.key]?.isMulti) {
return;
}
if (isTsReference(ref)) {
const expr =
checkTsReferenceAccessesField(ref, 'first') ?? checkTsReferenceAccessesField(ref, 'last');
if (expr === null) {
return;
}
replacements.push(
new Replacement(
projectFile(expr.getSourceFile(), info),
new TextUpdate({
position: expr.name.getStart(),
end: expr.name.getEnd(),
toInsert: mapping.get(expr.name.text)!,
}),
),
);
return;
}
// Template and host binding references.
const expr =
checkNonTsReferenceAccessesField(ref, 'first') ?? checkNonTsReferenceAccessesField(ref, 'last');
if (expr === null) {
return;
}
const file = isHostBindingReference(ref) ? ref.from.file : ref.from.templateFile;
const offset = isHostBindingReference(ref) ? ref.from.hostPropertyNode.getStart() + 1 : 0;
replacements.push(
new Replacement(
file,
new TextUpdate({
position: offset + expr.nameSpan.start,
end: offset + expr.nameSpan.end,
toInsert: mapping.get(expr.name)!,
}),
),
);
}
| {
"end_byte": 2364,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/fn_first_last_replacement.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/query_api_names.ts_0_768 | /**
* @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 {QueryFunctionName} from '@angular/compiler-cli/src/ngtsc/annotations';
/** Converts an initializer query API name to its decorator-equivalent. */
export function queryFunctionNameToDecorator(name: QueryFunctionName): string {
if (name === 'viewChild') {
return 'ViewChild';
} else if (name === 'viewChildren') {
return 'ViewChildren';
} else if (name === 'contentChild') {
return 'ContentChild';
} else if (name === 'contentChildren') {
return 'ContentChildren';
}
throw new Error(`Unexpected query function name: ${name}`);
}
| {
"end_byte": 768,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/query_api_names.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/query_list_type.ts_0_854 | /**
* @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';
/**
* Extracts the type `T` of expressions referencing `QueryList<T>`.
*/
export function extractQueryListType(node: ts.TypeNode | ts.Expression): ts.TypeNode | undefined {
// Initializer variant of `new QueryList<T>()`.
if (
ts.isNewExpression(node) &&
ts.isIdentifier(node.expression) &&
node.expression.text === 'QueryList'
) {
return node.typeArguments?.[0];
}
// Type variant of `: QueryList<T>`.
if (
ts.isTypeReferenceNode(node) &&
ts.isIdentifier(node.typeName) &&
node.typeName.text === 'QueryList'
) {
return node.typeArguments?.[0];
}
return undefined;
}
| {
"end_byte": 854,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/query_list_type.ts"
} |
angular/packages/core/schematics/migrations/signal-queries-migration/property_accesses.ts_0_3599 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import ts from 'typescript';
import {traverseAccess} from '../signal-migration/src/utils/traverse_access';
import {
HostBindingReference,
TemplateReference,
TsReference,
} from '../signal-migration/src/passes/reference_resolution/reference_kinds';
import {ClassFieldDescriptor} from '../signal-migration/src';
import {AST, Call, PropertyRead} from '@angular/compiler';
/**
* Gets whether the given field is accessed via the
* given reference.
*
* E.g. whether `<my-read>.toArray` is detected.
*/
export function checkTsReferenceAccessesField(
ref: TsReference<ClassFieldDescriptor>,
fieldName: string,
): (ts.PropertyAccessExpression & {name: ts.Identifier}) | null {
const accessNode = traverseAccess(ref.from.node);
// Check if the reference is part of a property access.
if (
!ts.isPropertyAccessExpression(accessNode.parent) ||
!ts.isIdentifier(accessNode.parent.name)
) {
return null;
}
// Check if the reference is refers to the given field name.
if (accessNode.parent.name.text !== fieldName) {
return null;
}
return accessNode.parent as ReturnType<typeof checkTsReferenceAccessesField>;
}
/**
* Gets whether the given read is used to access
* the specified field.
*
* E.g. whether `<my-read>.toArray` is detected.
*/
export function checkNonTsReferenceAccessesField(
ref: HostBindingReference<ClassFieldDescriptor> | TemplateReference<ClassFieldDescriptor>,
fieldName: string,
): PropertyRead | null {
const readFromPath = ref.from.readAstPath.at(-1) as PropertyRead | AST | undefined;
const parentRead = ref.from.readAstPath.at(-2) as PropertyRead | AST | undefined;
if (ref.from.read !== readFromPath) {
return null;
}
if (!(parentRead instanceof PropertyRead) || parentRead.name !== fieldName) {
return null;
}
return parentRead;
}
export interface FnCallExpression extends ts.CallExpression {
expression: ts.PropertyAccessExpression & {
name: ts.Identifier;
};
}
/**
* Gets whether the given reference is accessed to call the
* specified function on it.
*
* E.g. whether `<my-read>.toArray()` is detected.
*/
export function checkTsReferenceCallsField(
ref: TsReference<ClassFieldDescriptor>,
fieldName: string,
): FnCallExpression | null {
const propertyAccess = checkTsReferenceAccessesField(ref, fieldName);
if (propertyAccess === null) {
return null;
}
if (
ts.isCallExpression(propertyAccess.parent) &&
propertyAccess.parent.expression === propertyAccess
) {
return propertyAccess.parent as FnCallExpression;
}
return null;
}
/**
* Gets whether the given reference is accessed to call the
* specified function on it.
*
* E.g. whether `<my-read>.toArray()` is detected.
*/
export function checkNonTsReferenceCallsField(
ref: TemplateReference<ClassFieldDescriptor> | HostBindingReference<ClassFieldDescriptor>,
fieldName: string,
): (Call & {receiver: PropertyRead}) | null {
const propertyAccess = checkNonTsReferenceAccessesField(ref, fieldName);
if (propertyAccess === null) {
return null;
}
const accessIdx = ref.from.readAstPath.indexOf(propertyAccess);
if (accessIdx === -1) {
return null;
}
const potentialCall = ref.from.readAstPath[accessIdx - 1];
if (potentialCall === undefined || !(potentialCall instanceof Call)) {
return null;
}
return potentialCall as Call & {receiver: PropertyRead};
}
| {
"end_byte": 3599,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-queries-migration/property_accesses.ts"
} |
angular/packages/core/schematics/migrations/provide-initializer/utils.ts_0_5481 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import ts from 'typescript';
import {ChangeTracker} from '../../utils/change_tracker';
import {getImportSpecifier} from '../../utils/typescript/imports';
import {closestNode} from '../../utils/typescript/nodes';
export type RewriteFn = (startPos: number, width: number, text: string) => void;
export function migrateFile(sourceFile: ts.SourceFile, rewriteFn: RewriteFn) {
const changeTracker = new ChangeTracker(ts.createPrinter());
const visitNode = (node: ts.Node) => {
const provider = tryParseProviderExpression(node);
if (provider) {
replaceProviderWithNewApi({
sourceFile: sourceFile,
node: node,
provider: provider,
changeTracker,
});
return;
}
ts.forEachChild(node, visitNode);
};
ts.forEachChild(sourceFile, visitNode);
for (const change of changeTracker.recordChanges().get(sourceFile)?.values() ?? []) {
rewriteFn(change.start, change.removeLength ?? 0, change.text);
}
}
function replaceProviderWithNewApi({
sourceFile,
node,
provider,
changeTracker,
}: {
sourceFile: ts.SourceFile;
node: ts.Node;
provider: ProviderInfo;
changeTracker: ChangeTracker;
}) {
const {initializerCode, importInject, provideInitializerFunctionName, initializerToken} =
provider;
const initializerTokenSpecifier = getImportSpecifier(
sourceFile,
angularCoreModule,
initializerToken,
);
// The token doesn't come from `@angular/core`.
if (!initializerTokenSpecifier) {
return;
}
// Replace the provider with the new provide function.
changeTracker.replaceText(
sourceFile,
node.getStart(),
node.getWidth(),
`${provideInitializerFunctionName}(${initializerCode})`,
);
// Import declaration and named imports are necessarily there.
const namedImports = closestNode(initializerTokenSpecifier, ts.isNamedImports)!;
// `provide*Initializer` function is already imported.
const hasProvideInitializeFunction = namedImports.elements.some(
(element) => element.name.getText() === provideInitializerFunctionName,
);
const newNamedImports = ts.factory.updateNamedImports(namedImports, [
// Remove the `*_INITIALIZER` token from imports.
...namedImports.elements.filter((element) => element !== initializerTokenSpecifier),
// Add the `inject` function to imports if needed.
...(importInject ? [createImportSpecifier('inject')] : []),
// Add the `provide*Initializer` function to imports.
...(!hasProvideInitializeFunction
? [createImportSpecifier(provideInitializerFunctionName)]
: []),
]);
changeTracker.replaceNode(namedImports, newNamedImports);
}
function createImportSpecifier(name: string): ts.ImportSpecifier {
return ts.factory.createImportSpecifier(false, undefined, ts.factory.createIdentifier(name));
}
function tryParseProviderExpression(node: ts.Node): ProviderInfo | undefined {
if (!ts.isObjectLiteralExpression(node)) {
return;
}
let deps: string[] = [];
let initializerToken: string | undefined;
let useExisting: ts.Expression | undefined;
let useFactory: ts.Expression | undefined;
let useValue: ts.Expression | undefined;
let multi = false;
for (const property of node.properties) {
if (!ts.isPropertyAssignment(property) || !ts.isIdentifier(property.name)) {
continue;
}
switch (property.name.text) {
case 'deps':
if (ts.isArrayLiteralExpression(property.initializer)) {
deps = property.initializer.elements.map((el) => el.getText());
}
break;
case 'provide':
initializerToken = property.initializer.getText();
break;
case 'useExisting':
useExisting = property.initializer;
break;
case 'useFactory':
useFactory = property.initializer;
break;
case 'useValue':
useValue = property.initializer;
break;
case 'multi':
multi = property.initializer.kind === ts.SyntaxKind.TrueKeyword;
break;
}
}
if (!initializerToken || !multi) {
return;
}
const provideInitializerFunctionName = initializerTokenToFunctionMap.get(initializerToken);
if (!provideInitializerFunctionName) {
return;
}
const info = {
initializerToken,
provideInitializerFunctionName,
importInject: false,
} satisfies Partial<ProviderInfo>;
if (useExisting) {
return {
...info,
importInject: true,
initializerCode: `() => inject(${useExisting.getText()})()`,
};
}
if (useFactory) {
const args = deps.map((dep) => `inject(${dep})`);
return {
...info,
importInject: deps.length > 0,
initializerCode: `() => { return (${useFactory.getText()})(${args.join(', ')}); }`,
};
}
if (useValue) {
return {...info, initializerCode: useValue.getText()};
}
return;
}
const angularCoreModule = '@angular/core';
const initializerTokenToFunctionMap = new Map<string, string>([
['APP_INITIALIZER', 'provideAppInitializer'],
['ENVIRONMENT_INITIALIZER', 'provideEnvironmentInitializer'],
['PLATFORM_INITIALIZER', 'providePlatformInitializer'],
]);
interface ProviderInfo {
initializerToken: string;
provideInitializerFunctionName: string;
initializerCode: string;
importInject: boolean;
}
| {
"end_byte": 5481,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/provide-initializer/utils.ts"
} |
angular/packages/core/schematics/migrations/provide-initializer/README.md_0_675 | ## Replace `APP_INITIALIZER`, `ENVIRONMENT_INITIALIZER`, and `PLATFORM_INITIALIZER` with provider functions
Replaces `APP_INITIALIZER`, `ENVIRONMENT_INITIALIZER`, and `PLATFORM_INITIALIZER` with their respective provider functions: `provideAppInitializer`, `provideEnvironmentInitializer`, and `providePlatformInitializer`.
#### Before
```ts
import {APP_INITIALIZER} from '@angular/core';
const providers = [
{
provide: APP_INITIALIZER,
useValue: () => { console.log('hello'); },
multi: true,
}
];
```
#### After
```ts
import {provideAppInitializer} from '@angular/core';
const providers = [provideAppInitializer(() => { console.log('hello'); })];
```
| {
"end_byte": 675,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/provide-initializer/README.md"
} |
angular/packages/core/schematics/migrations/provide-initializer/BUILD.bazel_0_554 | load("//tools:defaults.bzl", "ts_library")
package(
default_visibility = [
"//packages/core/schematics:__pkg__",
"//packages/core/schematics/migrations/google3:__pkg__",
"//packages/core/schematics/test:__pkg__",
],
)
ts_library(
name = "provide-initializer",
srcs = glob(["**/*.ts"]),
tsconfig = "//packages/core/schematics:tsconfig.json",
deps = [
"//packages/core/schematics/utils",
"@npm//@angular-devkit/schematics",
"@npm//@types/node",
"@npm//typescript",
],
)
| {
"end_byte": 554,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/provide-initializer/BUILD.bazel"
} |
angular/packages/core/schematics/migrations/provide-initializer/index.ts_0_1921 | /**
* @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, UpdateRecorder} from '@angular-devkit/schematics';
import {relative} from 'path';
import {getProjectTsConfigPaths} from '../../utils/project_tsconfig_paths';
import {canMigrateFile, createMigrationProgram} from '../../utils/typescript/compiler_host';
import {migrateFile} from './utils';
export function migrate(): Rule {
return async (tree: Tree) => {
const {buildPaths, testPaths} = await getProjectTsConfigPaths(tree);
const basePath = process.cwd();
const allPaths = [...buildPaths, ...testPaths];
if (!allPaths.length) {
throw new SchematicsException(
'Could not find any tsconfig file. Cannot run the provide initializer migration.',
);
}
for (const tsconfigPath of allPaths) {
runMigration(tree, tsconfigPath, basePath);
}
};
}
function runMigration(tree: Tree, tsconfigPath: string, basePath: string) {
const program = createMigrationProgram(tree, tsconfigPath, basePath);
const sourceFiles = program
.getSourceFiles()
.filter((sourceFile) => canMigrateFile(basePath, sourceFile, program));
for (const sourceFile of sourceFiles) {
let update: UpdateRecorder | null = null;
const rewriter = (startPos: number, width: number, text: string | null) => {
if (update === null) {
// Lazily initialize update, because most files will not require migration.
update = tree.beginUpdate(relative(basePath, sourceFile.fileName));
}
update.remove(startPos, width);
if (text !== null) {
update.insertLeft(startPos, text);
}
};
migrateFile(sourceFile, rewriter);
if (update !== null) {
tree.commitUpdate(update);
}
}
}
| {
"end_byte": 1921,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/provide-initializer/index.ts"
} |
angular/packages/core/schematics/migrations/pending-tasks/migration.ts_0_1964 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import ts from 'typescript';
import {ChangeTracker} from '../../utils/change_tracker';
import {
getImportOfIdentifier,
getImportSpecifier,
getNamedImports,
} from '../../utils/typescript/imports';
const CORE = '@angular/core';
const EXPERIMENTAL_PENDING_TASKS = 'ExperimentalPendingTasks';
type RewriteFn = (startPos: number, width: number, text: string) => void;
export function migrateFile(
sourceFile: ts.SourceFile,
typeChecker: ts.TypeChecker,
rewriteFn: RewriteFn,
) {
const changeTracker = new ChangeTracker(ts.createPrinter());
// Check if there are any imports of the `AfterRenderPhase` enum.
const coreImports = getNamedImports(sourceFile, CORE);
if (!coreImports) {
return;
}
const importSpecifier = getImportSpecifier(sourceFile, CORE, EXPERIMENTAL_PENDING_TASKS);
if (!importSpecifier) {
return;
}
const nodeToReplace = importSpecifier.propertyName ?? importSpecifier.name;
if (!ts.isIdentifier(nodeToReplace)) {
return;
}
changeTracker.replaceNode(nodeToReplace, ts.factory.createIdentifier('PendingTasks'));
ts.forEachChild(sourceFile, function visit(node: ts.Node) {
// import handled above
if (ts.isImportDeclaration(node)) {
return;
}
if (
ts.isIdentifier(node) &&
node.text === EXPERIMENTAL_PENDING_TASKS &&
getImportOfIdentifier(typeChecker, node)?.name === EXPERIMENTAL_PENDING_TASKS
) {
changeTracker.replaceNode(node, ts.factory.createIdentifier('PendingTasks'));
}
ts.forEachChild(node, visit);
});
// Write the changes.
for (const changesInFile of changeTracker.recordChanges().values()) {
for (const change of changesInFile) {
rewriteFn(change.start, change.removeLength ?? 0, change.text);
}
}
}
| {
"end_byte": 1964,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/pending-tasks/migration.ts"
} |
angular/packages/core/schematics/migrations/pending-tasks/BUILD.bazel_0_548 | load("//tools:defaults.bzl", "ts_library")
package(
default_visibility = [
"//packages/core/schematics:__pkg__",
"//packages/core/schematics/migrations/google3:__pkg__",
"//packages/core/schematics/test:__pkg__",
],
)
ts_library(
name = "pending-tasks",
srcs = glob(["**/*.ts"]),
tsconfig = "//packages/core/schematics:tsconfig.json",
deps = [
"//packages/core/schematics/utils",
"@npm//@angular-devkit/schematics",
"@npm//@types/node",
"@npm//typescript",
],
)
| {
"end_byte": 548,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/pending-tasks/BUILD.bazel"
} |
angular/packages/core/schematics/migrations/pending-tasks/index.ts_0_1948 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Rule, SchematicsException, Tree, UpdateRecorder} from '@angular-devkit/schematics';
import {relative} from 'path';
import {getProjectTsConfigPaths} from '../../utils/project_tsconfig_paths';
import {canMigrateFile, createMigrationProgram} from '../../utils/typescript/compiler_host';
import {migrateFile} from './migration';
export function migrate(): Rule {
return async (tree: Tree) => {
const {buildPaths, testPaths} = await getProjectTsConfigPaths(tree);
const basePath = process.cwd();
const allPaths = [...buildPaths, ...testPaths];
if (!allPaths.length) {
throw new SchematicsException(
'Could not find any tsconfig file. Cannot run the afterRender phase migration.',
);
}
for (const tsconfigPath of allPaths) {
runMigration(tree, tsconfigPath, basePath);
}
};
}
function runMigration(tree: Tree, tsconfigPath: string, basePath: string) {
const program = createMigrationProgram(tree, tsconfigPath, basePath);
const sourceFiles = program
.getSourceFiles()
.filter((sourceFile) => canMigrateFile(basePath, sourceFile, program));
for (const sourceFile of sourceFiles) {
let update: UpdateRecorder | null = null;
const rewriter = (startPos: number, width: number, text: string | null) => {
if (update === null) {
// Lazily initialize update, because most files will not require migration.
update = tree.beginUpdate(relative(basePath, sourceFile.fileName));
}
update.remove(startPos, width);
if (text !== null) {
update.insertLeft(startPos, text);
}
};
migrateFile(sourceFile, program.getTypeChecker(), rewriter);
if (update !== null) {
tree.commitUpdate(update);
}
}
}
| {
"end_byte": 1948,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/pending-tasks/index.ts"
} |
angular/packages/core/schematics/migrations/explicit-standalone-flag/migration.ts_0_4507 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {ChangeTracker} from '../../utils/change_tracker';
import {getImportSpecifier, getNamedImports} from '../../utils/typescript/imports';
const CORE = '@angular/core';
const DIRECTIVE = 'Directive';
const COMPONENT = 'Component';
const PIPE = 'Pipe';
type RewriteFn = (startPos: number, width: number, text: string) => void;
export function migrateFile(sourceFile: ts.SourceFile, rewriteFn: RewriteFn) {
const changeTracker = new ChangeTracker(ts.createPrinter());
// Check if there are any imports of the `AfterRenderPhase` enum.
const coreImports = getNamedImports(sourceFile, CORE);
if (!coreImports) {
return;
}
const directive = getImportSpecifier(sourceFile, CORE, DIRECTIVE);
const component = getImportSpecifier(sourceFile, CORE, COMPONENT);
const pipe = getImportSpecifier(sourceFile, CORE, PIPE);
if (!directive && !component && !pipe) {
return;
}
ts.forEachChild(sourceFile, function visit(node: ts.Node) {
ts.forEachChild(node, visit);
// First we need to check for class declarations
// Decorators will come after
if (!ts.isClassDeclaration(node)) {
return;
}
ts.getDecorators(node)?.forEach((decorator) => {
if (!ts.isDecorator(decorator)) {
return;
}
const callExpression = decorator.expression;
if (!ts.isCallExpression(callExpression)) {
return;
}
const decoratorIdentifier = callExpression.expression;
if (!ts.isIdentifier(decoratorIdentifier)) {
return;
}
// Checking the identifier of the decorator by comparing to the import specifier
switch (decoratorIdentifier.text) {
case directive?.name.text:
case component?.name.text:
case pipe?.name.text:
break;
default:
// It's not a decorator to migrate
return;
}
const [decoratorArgument] = callExpression.arguments;
if (!decoratorArgument || !ts.isObjectLiteralExpression(decoratorArgument)) {
return;
}
const properties = decoratorArgument.properties;
const standaloneProp = getStandaloneProperty(properties);
// Need to take care of 3 cases
// - standalone: true => remove the property
// - standalone: false => nothing
// - No standalone property => add a standalone: false property
let newProperties: undefined | ts.ObjectLiteralElementLike[];
if (!standaloneProp) {
const standaloneFalseProperty = ts.factory.createPropertyAssignment(
'standalone',
ts.factory.createFalse(),
);
newProperties = [...properties, standaloneFalseProperty];
} else if (standaloneProp.value === ts.SyntaxKind.TrueKeyword) {
newProperties = properties.filter((p) => p !== standaloneProp.property);
}
if (newProperties) {
// At this point we know that we need to add standalone: false or
// remove an existing standalone: true property.
const newPropsArr = ts.factory.createNodeArray(newProperties);
const newFirstArg = ts.factory.createObjectLiteralExpression(newPropsArr, true);
changeTracker.replaceNode(decoratorArgument, newFirstArg);
}
});
});
// Write the changes.
for (const changesInFile of changeTracker.recordChanges().values()) {
for (const change of changesInFile) {
rewriteFn(change.start, change.removeLength ?? 0, change.text);
}
}
}
function getStandaloneProperty(properties: ts.NodeArray<ts.ObjectLiteralElementLike>) {
for (const prop of properties) {
if (ts.isShorthandPropertyAssignment(prop) && prop.name.text) {
return {property: prop, value: prop.objectAssignmentInitializer};
}
if (isStandaloneProperty(prop)) {
if (
prop.initializer.kind === ts.SyntaxKind.TrueKeyword ||
prop.initializer.kind === ts.SyntaxKind.FalseKeyword
) {
return {property: prop, value: prop.initializer.kind};
} else {
return {property: prop, value: prop.initializer};
}
}
}
return undefined;
}
function isStandaloneProperty(prop: ts.Node): prop is ts.PropertyAssignment {
return (
ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.text === 'standalone'
);
}
| {
"end_byte": 4507,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/explicit-standalone-flag/migration.ts"
} |
angular/packages/core/schematics/migrations/explicit-standalone-flag/BUILD.bazel_0_559 | load("//tools:defaults.bzl", "ts_library")
package(
default_visibility = [
"//packages/core/schematics:__pkg__",
"//packages/core/schematics/migrations/google3:__pkg__",
"//packages/core/schematics/test:__pkg__",
],
)
ts_library(
name = "explicit-standalone-flag",
srcs = glob(["**/*.ts"]),
tsconfig = "//packages/core/schematics:tsconfig.json",
deps = [
"//packages/core/schematics/utils",
"@npm//@angular-devkit/schematics",
"@npm//@types/node",
"@npm//typescript",
],
)
| {
"end_byte": 559,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/explicit-standalone-flag/BUILD.bazel"
} |
angular/packages/core/schematics/migrations/explicit-standalone-flag/index.ts_0_1930 | /**
* @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, UpdateRecorder} from '@angular-devkit/schematics';
import {relative} from 'path';
import {getProjectTsConfigPaths} from '../../utils/project_tsconfig_paths';
import {canMigrateFile, createMigrationProgram} from '../../utils/typescript/compiler_host';
import {migrateFile} from './migration';
export function migrate(): Rule {
return async (tree: Tree) => {
const {buildPaths, testPaths} = await getProjectTsConfigPaths(tree);
const basePath = process.cwd();
const allPaths = [...buildPaths, ...testPaths];
if (!allPaths.length) {
throw new SchematicsException(
'Could not find any tsconfig file. Cannot run the explicit-standalone-flag migration.',
);
}
for (const tsconfigPath of allPaths) {
runMigration(tree, tsconfigPath, basePath);
}
};
}
function runMigration(tree: Tree, tsconfigPath: string, basePath: string) {
const program = createMigrationProgram(tree, tsconfigPath, basePath);
const sourceFiles = program
.getSourceFiles()
.filter((sourceFile) => canMigrateFile(basePath, sourceFile, program));
for (const sourceFile of sourceFiles) {
let update: UpdateRecorder | null = null;
const rewriter = (startPos: number, width: number, text: string | null) => {
if (update === null) {
// Lazily initialize update, because most files will not require migration.
update = tree.beginUpdate(relative(basePath, sourceFile.fileName));
}
update.remove(startPos, width);
if (text !== null) {
update.insertLeft(startPos, text);
}
};
migrateFile(sourceFile, rewriter);
if (update !== null) {
tree.commitUpdate(update);
}
}
}
| {
"end_byte": 1930,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/explicit-standalone-flag/index.ts"
} |
angular/packages/core/schematics/test/all-migrations.spec.ts_0_3134 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {getSystemPath, normalize, virtualFs} from '@angular-devkit/core';
import {TempScopedNodeJsSyncHost} from '@angular-devkit/core/node/testing';
import {HostTree} from '@angular-devkit/schematics';
import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing';
import {runfiles} from '@bazel/runfiles';
import fs from 'fs';
import shx from 'shelljs';
describe('all migrations', () => {
let runner: SchematicTestRunner;
let host: TempScopedNodeJsSyncHost;
let tree: UnitTestTree;
let tmpDirPath: string;
let previousWorkingDir: string;
const migrationCollectionPath = runfiles.resolvePackageRelative('../migrations.json');
const allMigrationSchematics = Object.keys(
(JSON.parse(fs.readFileSync(migrationCollectionPath, 'utf8')) as any).schematics,
);
beforeEach(() => {
runner = new SchematicTestRunner('test', migrationCollectionPath);
host = new TempScopedNodeJsSyncHost();
tree = new UnitTestTree(new HostTree(host));
writeFile('/node_modules/@angular/core/index.d.ts', `export const MODULE: any;`);
writeFile(
'/angular.json',
JSON.stringify({
version: 1,
projects: {t: {root: '', architect: {build: {options: {tsConfig: './tsconfig.json'}}}}},
}),
);
writeFile('/tsconfig.json', `{}`);
previousWorkingDir = shx.pwd();
tmpDirPath = getSystemPath(host.root);
// Switch into the temporary directory path. This allows us to run
// the schematic against our custom unit test tree.
shx.cd(tmpDirPath);
});
afterEach(() => {
shx.cd(previousWorkingDir);
shx.rm('-r', tmpDirPath);
});
function writeFile(filePath: string, contents: string) {
host.sync.write(normalize(filePath), virtualFs.stringToFileBuffer(contents));
}
async function runMigration(migrationName: string) {
await runner.runSchematic(migrationName, undefined, tree);
}
if (allMigrationSchematics.length) {
allMigrationSchematics.forEach((name) => {
describe(name, () => createTests(name));
});
} else {
it('should pass', () => {
expect(true).toBe(true);
});
}
function createTests(migrationName: string) {
// Regression test for: https://github.com/angular/angular/issues/36346.
it('should not throw if non-existent symbols are imported with rootDirs', async () => {
writeFile(
`/tsconfig.json`,
JSON.stringify({
compilerOptions: {
rootDirs: ['./generated'],
},
}),
);
writeFile(
'/index.ts',
`
import {Renderer} from '@angular/core';
const variableDecl: Renderer = null;
export class Test {
constructor(renderer: Renderer) {}
}
`,
);
let error: any = null;
try {
await runMigration(migrationName);
} catch (e) {
error = e;
}
expect(error).toBe(null);
});
}
});
| {
"end_byte": 3134,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/all-migrations.spec.ts"
} |
angular/packages/core/schematics/test/standalone_migration_spec.ts_0_8259 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {getSystemPath, normalize, virtualFs} from '@angular-devkit/core';
import {TempScopedNodeJsSyncHost} from '@angular-devkit/core/node/testing';
import {HostTree} from '@angular-devkit/schematics';
import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing';
import {runfiles} from '@bazel/runfiles';
import shx from 'shelljs';
describe('standalone migration', () => {
let runner: SchematicTestRunner;
let host: TempScopedNodeJsSyncHost;
let tree: UnitTestTree;
let tmpDirPath: string;
let previousWorkingDir: string;
function writeFile(filePath: string, contents: string) {
host.sync.write(normalize(filePath), virtualFs.stringToFileBuffer(contents));
}
function runMigration(mode: string, path = './') {
return runner.runSchematic('standalone-migration', {mode, path}, tree);
}
function stripWhitespace(content: string) {
return content.replace(/\s+/g, '');
}
beforeEach(() => {
runner = new SchematicTestRunner('test', runfiles.resolvePackageRelative('../collection.json'));
host = new TempScopedNodeJsSyncHost();
tree = new UnitTestTree(new HostTree(host));
writeFile(
'/tsconfig.json',
JSON.stringify({
compilerOptions: {
lib: ['es2015'],
strictNullChecks: true,
},
}),
);
writeFile(
'/angular.json',
JSON.stringify({
version: 1,
projects: {t: {root: '', architect: {build: {options: {tsConfig: './tsconfig.json'}}}}},
}),
);
// We need to declare the Angular symbols we're testing for, otherwise type checking won't work.
writeFile(
'/node_modules/@angular/core/index.d.ts',
`
export declare class PlatformRef {
bootstrapModule(module: any): any;
}
export declare function forwardRef<T>(fn: () => T): T;
`,
);
writeFile(
'/node_modules/@angular/platform-browser/index.d.ts',
`
import {PlatformRef} from '@angular/core';
export const platformBrowser: () => PlatformRef;
`,
);
writeFile(
'/node_modules/@angular/platform-browser/animations/index.d.ts',
`
import {ModuleWithProviders} from '@angular/core';
export declare class BrowserAnimationsModule {
static withConfig(config: any): ModuleWithProviders<BrowserAnimationsModule>;
}
export declare class NoopAnimationsModule {}
`,
);
writeFile(
'/node_modules/@angular/platform-browser-dynamic/index.d.ts',
`
import {PlatformRef} from '@angular/core';
export const platformBrowserDynamic: () => PlatformRef;
`,
);
writeFile(
'/node_modules/@angular/common/index.d.ts',
`
import {ɵɵDirectiveDeclaration, ɵɵNgModuleDeclaration} from '@angular/core';
export declare class NgIf {
ngIf: any;
ngIfThen: TemplateRef<any>|null;
ngIfElse: TemplateRef<any>|null;
static ɵdir: ɵɵDirectiveDeclaration<NgIf, '[ngIf]', never, {
'ngIf': 'ngIf';
'ngIfThen': 'ngIfThen';
'ngIfElse': 'ngIfElse';
}, {}, never, never, true>;
}
export declare class NgForOf {
ngForOf: any;
static ɵdir: ɵɵDirectiveDeclaration<NgForOf, '[ngFor][ngForOf]', never, {
'ngForOf': 'ngForOf';
}, {}, never, never, true>;
}
export declare class CommonModule {
static ɵmod: ɵɵNgModuleDeclaration<CommonModule, never,
[typeof NgIf, typeof NgForOf], [typeof NgIf, typeof NgForOf]>;
}
export {NgForOf as NgFor};
`,
);
writeFile(
'/node_modules/@angular/router/index.d.ts',
`
import {ModuleWithProviders, ɵɵDirectiveDeclaration, ɵɵNgModuleDeclaration} from '@angular/core';
export declare class RouterLink {
// Router link is intentionally not standalone.
static ɵdir: ɵɵDirectiveDeclaration<RouterLink, '[routerLink]', never, {}, {}, never, never, false>;
}
export declare class RouterModule {
static forRoot(routes: any[], config?: any): ModuleWithProviders<RouterModule>;
static ɵmod: ɵɵNgModuleDeclaration<CommonModule, [typeof RouterLink], [], [typeof RouterLink]>;
}
`,
);
writeFile(
'/node_modules/@angular/common/http/index.d.ts',
`
import {ModuleWithProviders} from '@angular/core';
export declare class HttpClientModule {
static ɵfac: i0.ɵɵFactoryDeclaration<HttpClientModule, never>;
static ɵmod: i0.ɵɵNgModuleDeclaration<HttpClientModule, never, never, never>;
static ɵinj: i0.ɵɵInjectorDeclaration<HttpClientModule>;
}
`,
);
writeFile(
'/node_modules/@angular/core/testing/index.d.ts',
`
export declare class TestBed {
static configureTestingModule(config: any): any;
}
`,
);
writeFile(
'/node_modules/some_internal_path/angular/testing/catalyst/index.d.ts',
`
export declare function setupModule(config: any);
`,
);
previousWorkingDir = shx.pwd();
tmpDirPath = getSystemPath(host.root);
// Switch into the temporary directory path. This allows us to run
// the schematic against our custom unit test tree.
shx.cd(tmpDirPath);
});
afterEach(() => {
shx.cd(previousWorkingDir);
shx.rm('-r', tmpDirPath);
});
it('should throw an error if no files match the passed-in path', async () => {
let error: string | null = null;
writeFile(
'dir.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[dir]'})
export class MyDir {}
`,
);
try {
await runMigration('convert-to-standalone', './foo');
} catch (e: any) {
error = e.message;
}
expect(error).toMatch(
/Could not find any files to migrate under the path .*\/foo\. Cannot run the standalone migration/,
);
});
it('should throw an error if a path outside of the project is passed in', async () => {
let error: string | null = null;
writeFile(
'dir.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[dir]'})
export class MyDir {}
`,
);
try {
await runMigration('convert-to-standalone', '../foo');
} catch (e: any) {
error = e.message;
}
expect(error).toBe('Cannot run standalone migration outside of the current project.');
});
it('should throw an error if the passed in path is a file', async () => {
let error: string | null = null;
writeFile('dir.ts', '');
try {
await runMigration('convert-to-standalone', './dir.ts');
} catch (e: any) {
error = e.message;
}
expect(error).toMatch(
/Migration path .*\/dir\.ts has to be a directory\. Cannot run the standalone migration/,
);
});
it('should create an `imports` array if the module does not have one already', async () => {
writeFile(
'module.ts',
`
import {NgModule, Directive} from '@angular/core';
@Directive({selector: '[dir]'})
export class MyDir {}
@NgModule({declarations: [MyDir]})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(`@NgModule({imports: [MyDir]})`),
);
});
it('should combine the `declarations` array with a static `imports` array', async () => {
writeFile(
'module.ts',
`
import {NgModule, Directive} from '@angular/core';
import {CommonModule} from '@angular/common';
@Directive({selector: '[dir]'})
export class MyDir {}
@NgModule({declarations: [MyDir], imports: [CommonModule]})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(`@NgModule({imports: [CommonModule, MyDir]})`),
);
});
it('should combine a `declar | {
"end_byte": 8259,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_migration_spec.ts"
} |
angular/packages/core/schematics/test/standalone_migration_spec.ts_8263_15995 | ns` array with a spread expression into the `imports`', async () => {
writeFile(
'module.ts',
`
import {NgModule, Directive} from '@angular/core';
import {CommonModule} from '@angular/common';
@Directive({selector: '[dir]'})
export class MyDir {}
@Directive({selector: '[dir]'})
export class MyOtherDir {}
const extraDeclarations = [MyOtherDir];
@NgModule({declarations: [MyDir, ...extraDeclarations], imports: [CommonModule]})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(`@NgModule({imports: [CommonModule, MyDir, ...extraDeclarations]})`),
);
});
it('should combine a `declarations` array with an `imports` array that has a spread expression', async () => {
writeFile(
'module.ts',
`
import {NgModule, Directive} from '@angular/core';
import {CommonModule} from '@angular/common';
@Directive({selector: '[dir]'})
export class MyDir {}
@Directive({selector: '[dir]', standalone: true})
export class MyOtherDir {}
const extraImports = [MyOtherDir];
@NgModule({declarations: [MyDir], imports: [CommonModule, ...extraImports]})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(`@NgModule({imports: [CommonModule, ...extraImports, MyDir]})`),
);
});
it('should use a spread expression if the `declarations` is an expression when combining with the `imports`', async () => {
writeFile(
'module.ts',
`
import {NgModule, Directive} from '@angular/core';
import {CommonModule} from '@angular/common';
@Directive({selector: '[dir]'})
export class MyDir {}
const DECLARATIONS = [MyDir];
@NgModule({declarations: DECLARATIONS, imports: [CommonModule]})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(`@NgModule({imports: [CommonModule, ...DECLARATIONS]})`),
);
});
it('should use a spread expression if the `imports` is an expression when combining with the `declarations`', async () => {
writeFile(
'module.ts',
`
import {NgModule, Directive} from '@angular/core';
import {CommonModule} from '@angular/common';
@Directive({selector: '[dir]'})
export class MyDir {}
const IMPORTS = [CommonModule];
@NgModule({declarations: [MyDir], imports: IMPORTS})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(`@NgModule({imports: [...IMPORTS, MyDir]})`),
);
});
it('should use a spread expression if both the `declarations` and the `imports` are not static arrays', async () => {
writeFile(
'module.ts',
`
import {NgModule, Directive} from '@angular/core';
import {CommonModule} from '@angular/common';
@Directive({selector: '[dir]'})
export class MyDir {}
const IMPORTS = [CommonModule];
const DECLARATIONS = [MyDir];
@NgModule({declarations: DECLARATIONS, imports: IMPORTS})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(`@NgModule({imports: [...IMPORTS, ...DECLARATIONS]})`),
);
});
it('should convert a directive in the same file as its module to standalone', async () => {
writeFile(
'module.ts',
`
import {NgModule, Directive} from '@angular/core';
@Directive({selector: '[dir]', standalone: false})
export class MyDir {}
@NgModule({declarations: [MyDir], exports: [MyDir]})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
const result = tree.readContent('module.ts');
expect(stripWhitespace(result)).toContain(stripWhitespace(`@Directive({selector: '[dir]'})`));
expect(stripWhitespace(result)).toContain(
stripWhitespace(`@NgModule({imports: [MyDir], exports: [MyDir]})`),
);
});
it('should convert a pipe in the same file as its module to standalone', async () => {
writeFile(
'module.ts',
`
import {NgModule, Pipe} from '@angular/core';
@Pipe({name: 'myPipe', standalone: false})
export class MyPipe {}
@NgModule({declarations: [MyPipe], exports: [MyPipe]})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
const result = tree.readContent('module.ts');
expect(stripWhitespace(result)).toContain(stripWhitespace(`@Pipe({name: 'myPipe'})`));
expect(stripWhitespace(result)).toContain(
stripWhitespace(`@NgModule({imports: [MyPipe], exports: [MyPipe]})`),
);
});
it('should only migrate declarations under a specific path', async () => {
const content = `
import {NgModule, Directive} from '@angular/core';
@Directive({selector: '[dir]', standalone: false})
export class MyDir {}
@NgModule({declarations: [MyDir], exports: [MyDir]})
export class Mod {}
`;
writeFile('./apps/app-1/module.ts', content);
writeFile('./apps/app-2/module.ts', content);
await runMigration('convert-to-standalone', './apps/app-2');
expect(tree.readContent('./apps/app-1/module.ts')).toContain('standalone: false');
expect(tree.readContent('./apps/app-2/module.ts')).toContain(`@Directive({ selector: '[dir]'`);
});
it('should convert a directive in a different file from its module to standalone', async () => {
writeFile(
'module.ts',
`
import {NgModule} from '@angular/core';
import {MyDir} from './dir';
@NgModule({declarations: [MyDir], exports: [MyDir]})
export class Mod {}
`,
);
writeFile(
'dir.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[dir]', standalone: false})
export class MyDir {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(`@NgModule({imports: [MyDir], exports: [MyDir]})`),
);
expect(stripWhitespace(tree.readContent('dir.ts'))).toContain(
stripWhitespace(`@Directive({selector: '[dir]'})`),
);
});
it('should convert a component with no template dependencies to standalone', async () => {
writeFile(
'module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
@NgModule({declarations: [MyComp], exports: [MyComp]})
export class Mod {}
`,
);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-comp', template: '<h1>Hello</h1>', standalone: false})
export class MyComp {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(`@NgModule({imports: [MyComp], exports: [MyComp]})`),
);
expect(stripWhitespace(tree.readContent('comp.ts'))).toContain(
stripWhitespace(`
@Component({
selector: 'my-comp',
template: '<h1>Hello</h1>'
})
`),
);
});
it('should add imports to de | {
"end_byte": 15995,
"start_byte": 8263,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_migration_spec.ts"
} |
angular/packages/core/schematics/test/standalone_migration_spec.ts_15999_23121 | encies within the same module', async () => {
writeFile(
'module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import {MyButton} from './button';
import {MyTooltip} from './tooltip';
@NgModule({declarations: [MyComp, MyButton, MyTooltip], exports: [MyComp]})
export class Mod {}
`,
);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-comp', template: '<my-button tooltip="Click me">Hello</my-button>', standalone: false})
export class MyComp {}
`,
);
writeFile(
'button.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-button', template: '<ng-content></ng-content>', standalone: false})
export class MyButton {}
`,
);
writeFile(
'tooltip.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[tooltip]', standalone: false})
export class MyTooltip {}
`,
);
await runMigration('convert-to-standalone');
const myCompContent = tree.readContent('comp.ts');
expect(myCompContent).toContain(`import { MyButton } from './button';`);
expect(myCompContent).toContain(`import { MyTooltip } from './tooltip';`);
expect(stripWhitespace(myCompContent)).toContain(
stripWhitespace(`
@Component({
selector: 'my-comp',
template: '<my-button tooltip="Click me">Hello</my-button>',
imports: [MyButton, MyTooltip]
})
`),
);
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(`@NgModule({imports: [MyComp, MyButton, MyTooltip], exports: [MyComp]})`),
);
expect(stripWhitespace(tree.readContent('button.ts'))).toContain(
stripWhitespace(`@Component({selector: 'my-button', template: '<ng-content></ng-content>'})`),
);
expect(stripWhitespace(tree.readContent('tooltip.ts'))).toContain(
stripWhitespace(`@Directive({selector: '[tooltip]'})`),
);
});
it('should reuse existing import statements when adding imports to a component', async () => {
writeFile(
'module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import {MyButton} from './button';
@NgModule({declarations: [MyComp, MyButton], exports: [MyComp]})
export class Mod {}
`,
);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
import {helper} from './button';
helper();
@Component({selector: 'my-comp', template: '<my-button>Hello</my-button>', standalone: false})
export class MyComp {}
`,
);
writeFile(
'button.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-button', template: '<ng-content></ng-content>', standalone: false})
export class MyButton {}
export function helper() {}
`,
);
await runMigration('convert-to-standalone');
const myCompContent = tree.readContent('comp.ts');
expect(myCompContent).toContain(`import { helper, MyButton } from './button';`);
expect(stripWhitespace(myCompContent)).toContain(
stripWhitespace(`
@Component({
selector: 'my-comp',
template: '<my-button>Hello</my-button>',
imports: [MyButton]
})
`),
);
});
it('should refer to pre-existing standalone dependencies directly when adding to the `imports`', async () => {
writeFile(
'module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import {MyButton} from './button';
@NgModule({imports: [MyButton], declarations: [MyComp], exports: [MyComp]})
export class Mod {}
`,
);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-comp', template: '<my-button>Hello</my-button>', standalone: false})
export class MyComp {}
`,
);
writeFile(
'button.ts',
`
import {Component} from '@angular/core';
import {MyComp} from './comp';
@Component({selector: 'my-button', template: '<ng-content></ng-content>', standalone: true})
export class MyButton {}
`,
);
await runMigration('convert-to-standalone');
const myCompContent = tree.readContent('comp.ts');
expect(myCompContent).toContain(`import { MyButton } from './button';`);
expect(stripWhitespace(myCompContent)).toContain(
stripWhitespace(`
@Component({
selector: 'my-comp',
template: '<my-button>Hello</my-button>',
imports: [MyButton]
})
`),
);
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace('@NgModule({imports: [MyButton, MyComp], exports: [MyComp]})'),
);
});
it('should refer to dependencies being handled in the same migration directly', async () => {
writeFile(
'module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import {ButtonModule} from './button.module';
@NgModule({imports: [ButtonModule], declarations: [MyComp], exports: [MyComp]})
export class Mod {}
`,
);
writeFile(
'button.module.ts',
`
import {NgModule} from '@angular/core';
import {MyButton} from './button';
@NgModule({declarations: [MyButton], exports: [MyButton]})
export class ButtonModule {}
`,
);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-comp', template: '<my-button>Hello</my-button>', standalone: false})
export class MyComp {}
`,
);
writeFile(
'button.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-button', template: '<ng-content></ng-content>', standalone: false})
export class MyButton {}
`,
);
await runMigration('convert-to-standalone');
const myCompContent = tree.readContent('comp.ts');
expect(myCompContent).toContain(`import { MyButton } from './button';`);
expect(stripWhitespace(myCompContent)).toContain(
stripWhitespace(`
@Component({
selector: 'my-comp',
template: '<my-button>Hello</my-button>',
imports: [MyButton]
})
`),
);
expect(stripWhitespace(tree.readContent('button.ts'))).toContain(
stripWhitespace(`
@Component({
selector: 'my-button',
template: '<ng-content></ng-content>'
})
`),
);
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(`
@NgModule({imports: [ButtonModule, MyComp], exports: [MyComp]})
`),
);
expect(stripWhitespace(tree.readContent('button.module.ts'))).toContain(
stripWhitespace(`
@NgModule({imports: [MyButton], exports: [MyButton]})
`),
);
});
it('should refer to dependen | {
"end_byte": 23121,
"start_byte": 15999,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_migration_spec.ts"
} |
angular/packages/core/schematics/test/standalone_migration_spec.ts_23125_30967 | by their module if they have been excluded from the migration', async () => {
writeFile(
'./should-migrate/module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import {ButtonModule} from '../do-not-migrate/button.module';
@NgModule({imports: [ButtonModule], declarations: [MyComp], exports: [MyComp]})
export class Mod {}
`,
);
writeFile(
'./do-not-migrate/button.module.ts',
`
import {NgModule} from '@angular/core';
import {MyButton} from './button';
@NgModule({declarations: [MyButton], exports: [MyButton]})
export class ButtonModule {}
`,
);
writeFile(
'./should-migrate/comp.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-comp', template: '<my-button>Hello</my-button>', standalone: false})
export class MyComp {}
`,
);
writeFile(
'./do-not-migrate/button.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-button', template: '<ng-content></ng-content>', standalone: false})
export class MyButton {}
`,
);
await runMigration('convert-to-standalone', './should-migrate');
const myCompContent = tree.readContent('./should-migrate/comp.ts');
expect(myCompContent).toContain(
`import { ButtonModule } from '../do-not-migrate/button.module';`,
);
expect(stripWhitespace(myCompContent)).toContain(
stripWhitespace(`
@Component({
selector: 'my-comp',
template: '<my-button>Hello</my-button>',
imports: [ButtonModule]
})
`),
);
expect(stripWhitespace(tree.readContent('./should-migrate/module.ts'))).toContain(
stripWhitespace(`@NgModule({imports: [ButtonModule, MyComp], exports: [MyComp]})`),
);
expect(tree.readContent('./do-not-migrate/button.ts')).toContain('standalone: false');
expect(stripWhitespace(tree.readContent('./do-not-migrate/button.module.ts'))).toContain(
stripWhitespace(`@NgModule({declarations: [MyButton], exports: [MyButton]})`),
);
});
it('should add imports to dependencies within the same module', async () => {
writeFile(
'module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import {MyButton} from './button';
import {MyTooltip} from './tooltip';
@NgModule({declarations: [MyComp, MyButton, MyTooltip], exports: [MyComp]})
export class Mod {}
`,
);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-comp', template: '<my-button tooltip="Click me">Hello</my-button>', standalone: false})
export class MyComp {}
`,
);
writeFile(
'button.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-button', template: '<ng-content></ng-content>', standalone: false})
export class MyButton {}
`,
);
writeFile(
'tooltip.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[tooltip]', standalone: false})
export class MyTooltip {}
`,
);
await runMigration('convert-to-standalone');
const myCompContent = tree.readContent('comp.ts');
expect(myCompContent).toContain(`import { MyButton } from './button';`);
expect(myCompContent).toContain(`import { MyTooltip } from './tooltip';`);
expect(stripWhitespace(myCompContent)).toContain(
stripWhitespace(`
@Component({
selector: 'my-comp',
template: '<my-button tooltip="Click me">Hello</my-button>',
imports: [MyButton, MyTooltip]
})
`),
);
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(`@NgModule({imports: [MyComp, MyButton, MyTooltip], exports: [MyComp]})`),
);
expect(stripWhitespace(tree.readContent('button.ts'))).toContain(
stripWhitespace(`@Component({selector: 'my-button', template: '<ng-content></ng-content>'})`),
);
expect(stripWhitespace(tree.readContent('tooltip.ts'))).toContain(
stripWhitespace(`@Directive({selector: '[tooltip]'})`),
);
});
it('should add imports to external dependencies', async () => {
writeFile(
'module.ts',
`
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {MyComp, MyOtherComp} from './comp';
@NgModule({imports: [CommonModule], declarations: [MyComp, MyOtherComp], exports: [MyComp]})
export class Mod {}
`,
);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
@Component({
selector: 'my-comp',
template: \`
<div *ngFor="let message of messages">
<span *ngIf="message">{{message}}</span>
</div>
\`,
standalone: false
})
export class MyComp {
messages = ['hello', 'hi'];
}
@Component({
selector: 'my-other-comp',
template: '<div *ngIf="isShown"></div>',
standalone: false
})
export class MyOtherComp {
isShown = true;
}
`,
);
await runMigration('convert-to-standalone');
const myCompContent = tree.readContent('comp.ts');
expect(myCompContent).toContain(`import { NgFor, NgIf } from '@angular/common';`);
expect(stripWhitespace(myCompContent)).toContain(
stripWhitespace(`
@Component({
selector: 'my-comp',
template: \`
<div *ngFor="let message of messages">
<span *ngIf="message">{{message}}</span>
</div>
\`,
imports: [NgFor, NgIf]
})
`),
);
expect(stripWhitespace(myCompContent)).toContain(
stripWhitespace(`
@Component({
selector: 'my-other-comp',
template: '<div *ngIf="isShown"></div>',
imports: [NgIf]
})
`),
);
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(
`@NgModule({imports: [CommonModule, MyComp, MyOtherComp], exports: [MyComp]})`,
),
);
});
it('should add imports to pipes that are used in the template', async () => {
writeFile(
'module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import {MyPipe} from './pipe';
@NgModule({declarations: [MyComp, MyPipe], exports: [MyComp]})
export class Mod {}
`,
);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-comp', template: '{{"hello" | myPipe}}', standalone: false})
export class MyComp {}
`,
);
writeFile(
'pipe.ts',
`
import {Pipe} from '@angular/core';
@Pipe({name: 'myPipe', standalone: false})
export class MyPipe {
transform() {}
}
`,
);
await runMigration('convert-to-standalone');
const myCompContent = tree.readContent('comp.ts');
expect(myCompContent).toContain(`import { MyPipe } from './pipe';`);
expect(stripWhitespace(myCompContent)).toContain(
stripWhitespace(`
@Component({
selector: 'my-comp',
template: '{{"hello" | myPipe}}',
imports: [MyPipe]
})
`),
);
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(`@NgModule({imports: [MyComp, MyPipe], exports: [MyComp]})`),
);
expect(stripWhitespace(tree.readContent('pipe.ts'))).toContain(
stripWhitespace(`@Pipe({name: 'myPipe'})`),
);
});
it('should migrate tests wit | {
"end_byte": 30967,
"start_byte": 23125,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_migration_spec.ts"
} |
angular/packages/core/schematics/test/standalone_migration_spec.ts_30971_39410 | inline NgModule', async () => {
writeFile(
'app.spec.ts',
`
import {NgModule, Component} from '@angular/core';
import {TestBed} from '@angular/core/testing';
describe('bootstrapping an app', () => {
it('should work', () => {
@Component({selector: 'hello', template: 'Hello', standalone: false})
class Hello {}
@Component({template: '<hello></hello>', standalone: false})
class App {}
@NgModule({declarations: [App, Hello], exports: [App, Hello]})
class Mod {}
TestBed.configureTestingModule({imports: [Mod]});
const fixture = TestBed.createComponent(App);
expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>');
});
});
`,
);
await runMigration('convert-to-standalone');
const content = stripWhitespace(tree.readContent('app.spec.ts'));
expect(content).toContain(
stripWhitespace(`
@Component({selector: 'hello', template: 'Hello'})
class Hello {}
`),
);
expect(content).toContain(
stripWhitespace(`
@Component({template: '<hello></hello>', imports: [Hello]})
class App {}
`),
);
expect(content).toContain(
stripWhitespace(`
@NgModule({imports: [App, Hello], exports: [App, Hello]})
class Mod {}
`),
);
});
it('should migrate tests where the declaration is already standalone', async () => {
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'comp', template: '', standalone: true})
export class MyComp {}
`,
);
writeFile(
'app.spec.ts',
`
import {TestBed} from '@angular/core/testing';
import {MyComp} from './comp';
describe('bootstrapping an app', () => {
it('should work', () => {
TestBed.configureTestingModule({declarations: [MyComp]});
expect(() => TestBed.createComponent(MyComp)).not.toThrow();
});
});
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('app.spec.ts'))).toContain(
stripWhitespace(`
import {TestBed} from '@angular/core/testing';
import {MyComp} from './comp';
describe('bootstrapping an app', () => {
it('should work', () => {
TestBed.configureTestingModule({imports: [MyComp]});
expect(() => TestBed.createComponent(MyComp)).not.toThrow();
});
});
`),
);
});
it('should import the module that declares a template dependency', async () => {
writeFile(
'./should-migrate/module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import {ButtonModule} from '../do-not-migrate/button.module';
@NgModule({imports: [ButtonModule], declarations: [MyComp]})
export class Mod {}
`,
);
writeFile(
'./should-migrate/comp.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-comp', template: '<my-button>Hello</my-button>', standalone: false})
export class MyComp {}
`,
);
writeFile(
'./do-not-migrate/button.module.ts',
`
import {NgModule, forwardRef} from '@angular/core';
import {MyButton} from './button';
@NgModule({
imports: [forwardRef(() => ButtonModule)],
exports: [forwardRef(() => ButtonModule)]
})
export class ExporterModule {}
@NgModule({declarations: [MyButton], exports: [MyButton]})
export class ButtonModule {}
`,
);
writeFile(
'./do-not-migrate/button.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-button', template: '<ng-content></ng-content>', standalone: false})
export class MyButton {}
`,
);
await runMigration('convert-to-standalone', './should-migrate');
const myCompContent = tree.readContent('./should-migrate/comp.ts');
expect(myCompContent).toContain(
`import { ButtonModule } from '../do-not-migrate/button.module';`,
);
expect(myCompContent).toContain('imports: [ButtonModule]');
});
it('should not reference internal modules', async () => {
writeFile(
'./should-migrate/module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import {ɵButtonModule} from '../do-not-migrate/button.module';
@NgModule({imports: [ɵButtonModule], declarations: [MyComp]})
export class Mod {}
`,
);
writeFile(
'./should-migrate/comp.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-comp', template: '<my-button>Hello</my-button>', standalone: false})
export class MyComp {}
`,
);
writeFile(
'./do-not-migrate/button.module.ts',
`
import {NgModule, forwardRef} from '@angular/core';
import {MyButton} from './button';
@NgModule({
imports: [forwardRef(() => ɵButtonModule)],
exports: [forwardRef(() => ɵButtonModule)]
})
export class ExporterModule {}
@NgModule({declarations: [MyButton], exports: [MyButton]})
export class ɵButtonModule {}
`,
);
writeFile(
'./do-not-migrate/button.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-button', template: '<ng-content></ng-content>', standalone: false})
export class MyButton {}
`,
);
await runMigration('convert-to-standalone', './should-migrate');
const myCompContent = tree.readContent('./should-migrate/comp.ts');
expect(myCompContent).toContain(
`import { ExporterModule } from '../do-not-migrate/button.module';`,
);
expect(myCompContent).toContain('imports: [ExporterModule]');
});
it('should migrate tests with a component declared through TestBed', async () => {
writeFile(
'app.spec.ts',
`
import {NgModule, Component} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {ButtonModule} from './button.module';
import {MatCardModule} from '@angular/material/card';
describe('bootstrapping an app', () => {
it('should work', () => {
TestBed.configureTestingModule({
declarations: [App, Hello],
imports: [ButtonModule, MatCardModule]
});
const fixture = TestBed.createComponent(App);
expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>');
});
it('should work in a different way', () => {
TestBed.configureTestingModule({declarations: [App, Hello], imports: [MatCardModule]});
const fixture = TestBed.createComponent(App);
expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>');
});
});
@Component({selector: 'hello', template: 'Hello', standalone: false})
class Hello {}
@Component({template: '<hello></hello>', standalone: false})
class App {}
`,
);
await runMigration('convert-to-standalone');
const content = stripWhitespace(tree.readContent('app.spec.ts'));
expect(content).toContain(
stripWhitespace(`
@Component({
selector: 'hello',
template: 'Hello',
imports: [ButtonModule, MatCardModule]
})
class Hello {}
`),
);
expect(content).toContain(
stripWhitespace(`
@Component({
template: '<hello></hello>',
imports: [ButtonModule, MatCardModule]
})
class App {}
`),
);
expect(content).toContain(
stripWhitespace(`
it('should work', () => {
TestBed.configureTestingModule({
imports: [ButtonModule, MatCardModule, App, Hello]
});
const fixture = TestBed.createComponent(App);
expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>');
});
`),
);
expect(content).toContain(
stripWhitespace(`
it('should work in a different way', () => {
TestBed.configureTestingModule({imports: [MatCardModule, App, Hello]});
const fixture = TestBed.createComponent(App);
expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>');
});
`),
);
});
it('should not add ModuleWithProv | {
"end_byte": 39410,
"start_byte": 30971,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_migration_spec.ts"
} |
angular/packages/core/schematics/test/standalone_migration_spec.ts_39414_49330 | s imports to the `imports` in a test', async () => {
writeFile(
'app.spec.ts',
`
import {NgModule, Component} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {MatCardModule} from '@angular/material/card';
describe('bootstrapping an app', () => {
it('should work', () => {
TestBed.configureTestingModule({
declarations: [App],
imports: [MatCardModule.forRoot({})]
});
const fixture = TestBed.createComponent(App);
expect(fixture.nativeElement.innerHTML).toBe('hello');
});
});
@Component({template: 'hello', standalone: false})
class App {}
`,
);
await runMigration('convert-to-standalone');
const content = stripWhitespace(tree.readContent('app.spec.ts'));
expect(content).toContain(
stripWhitespace(`
@Component({template: 'hello'})
class App {}
`),
);
expect(content).toContain(
stripWhitespace(`
it('should work', () => {
TestBed.configureTestingModule({
imports: [MatCardModule.forRoot({}), App]
});
const fixture = TestBed.createComponent(App);
expect(fixture.nativeElement.innerHTML).toBe('hello');
});
`),
);
});
it('should not change testing objects with no declarations', async () => {
const initialContent = `
import {NgModule, Component} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {ButtonModule} from './button.module';
import {MatCardModule} from '@angular/material/card';
describe('bootstrapping an app', () => {
it('should work', () => {
TestBed.configureTestingModule({
imports: [ButtonModule, MatCardModule]
});
const fixture = TestBed.createComponent(App);
expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>');
});
});
@Component({template: 'hello', standalone: false})
class App {}
`;
writeFile('app.spec.ts', initialContent);
await runMigration('convert-to-standalone');
expect(tree.readContent('app.spec.ts')).toBe(initialContent);
});
it('should migrate tests with a component declared through Catalyst', async () => {
writeFile(
'app.spec.ts',
`
import {NgModule, Component} from '@angular/core';
import {bootstrap, setupModule} from 'some_internal_path/angular/testing/catalyst';
import {ButtonModule} from './button.module';
import {MatCardModule} from '@angular/material/card';
describe('bootstrapping an app', () => {
it('should work', () => {
setupModule({
declarations: [App, Hello],
imports: [ButtonModule, MatCardModule]
});
const fixture = bootstrap(App);
expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>');
});
it('should work in a different way', () => {
setupModule({declarations: [App, Hello], imports: [MatCardModule]});
const fixture = bootstrap(App);
expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>');
});
});
@Component({selector: 'hello', template: 'Hello', standalone: false})
class Hello {}
@Component({template: '<hello></hello>', standalone: false})
class App {}
`,
);
await runMigration('convert-to-standalone');
const content = stripWhitespace(tree.readContent('app.spec.ts'));
expect(content).toContain(
stripWhitespace(`
@Component({
selector: 'hello',
template: 'Hello',
imports: [ButtonModule, MatCardModule]
})
class Hello {}
`),
);
expect(content).toContain(
stripWhitespace(`
@Component({
template: '<hello></hello>',
imports: [ButtonModule, MatCardModule]
})
class App {}
`),
);
expect(content).toContain(
stripWhitespace(`
it('should work', () => {
setupModule({
imports: [ButtonModule, MatCardModule, App, Hello]
});
const fixture = bootstrap(App);
expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>');
});
`),
);
expect(content).toContain(
stripWhitespace(`
it('should work in a different way', () => {
setupModule({imports: [MatCardModule, App, Hello]});
const fixture = bootstrap(App);
expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>');
});
`),
);
});
it('should not copy over the NoopAnimationsModule into the imports of a test component', async () => {
writeFile(
'app.spec.ts',
`
import {NgModule, Component} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {MatCardModule} from '@angular/material/card';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
describe('bootstrapping an app', () => {
it('should work', () => {
TestBed.configureTestingModule({
imports: [MatCardModule, NoopAnimationsModule],
declarations: [App]
});
const fixture = TestBed.createComponent(App);
expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>');
});
});
@Component({template: 'hello'})
class App {}
`,
);
await runMigration('convert-to-standalone');
const content = stripWhitespace(tree.readContent('app.spec.ts'));
expect(content).toContain(
stripWhitespace(`
TestBed.configureTestingModule({
imports: [MatCardModule, NoopAnimationsModule, App]
});
`),
);
expect(content).toContain(
stripWhitespace(`
@Component({template: 'hello', imports: [MatCardModule]})
class App {}
`),
);
});
it('should not copy over the BrowserAnimationsModule into the imports of a test component', async () => {
writeFile(
'app.spec.ts',
`
import {NgModule, Component} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {MatCardModule} from '@angular/material/card';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
describe('bootstrapping an app', () => {
it('should work', () => {
TestBed.configureTestingModule({
imports: [MatCardModule, BrowserAnimationsModule],
declarations: [App]
});
const fixture = TestBed.createComponent(App);
expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>');
});
});
@Component({template: 'hello', standalone: false})
class App {}
`,
);
await runMigration('convert-to-standalone');
const content = stripWhitespace(tree.readContent('app.spec.ts'));
expect(content).toContain(
stripWhitespace(`
TestBed.configureTestingModule({
imports: [MatCardModule, BrowserAnimationsModule, App]
});
`),
);
expect(content).toContain(
stripWhitespace(`
@Component({template: 'hello', imports: [MatCardModule]})
class App {}
`),
);
});
it('should not move declarations that are not being migrated out of the declarations array', async () => {
const appComponentContent = `
import {Component} from '@angular/core';
@Component({selector: 'app', template: '', standalone: false})
export class AppComponent {}
`;
const appModuleContent = `
import {NgModule} from '@angular/core';
import {AppComponent} from './app.component';
@NgModule({declarations: [AppComponent], bootstrap: [AppComponent]})
export class AppModule {}
`;
writeFile('app.component.ts', appComponentContent);
writeFile('app.module.ts', appModuleContent);
writeFile(
'app.spec.ts',
`
import {Component} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {ButtonModule} from './button.module';
import {MatCardModule} from '@angular/material/card';
import {AppComponent} from './app.component';
describe('bootstrapping an app', () => {
it('should work', () => {
TestBed.configureTestingModule({
declarations: [AppComponent, TestComp],
imports: [ButtonModule, MatCardModule]
});
const fixture = TestBed.createComponent(App);
expect(fixture.nativeElement.innerHTML).toBe('');
});
});
@Component({template: '', standalone: false})
class TestComp {}
`,
);
await runMigration('convert-to-standalone');
const testContent = stripWhitespace(tree.readContent('app.spec.ts'));
expect(tree.readContent('app.module.ts')).toBe(appModuleContent);
expect(tree.readContent('app.component.ts')).toBe(appComponentContent);
expect(testContent).toContain(
stripWhitespace(`
it('should work', () => {
TestBed.configureTestingModule({
declarations: [AppComponent],
imports: [ButtonModule, MatCardModule, TestComp]
});
const fixture = TestBed.createComponent(App);
expect(fixture.nativeElement.innerHTML).toBe('');
});
`),
);
expect(testContent).toContain(
stripWhitespace(`
@Component({
template: '',
imports: [ButtonModule, MatCardModule]
})
class TestComp {}
`),
);
});
it('should not migrate `configure | {
"end_byte": 49330,
"start_byte": 39414,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_migration_spec.ts"
} |
angular/packages/core/schematics/test/standalone_migration_spec.ts_49334_57316 | ingModule` with a non-array expression in the `declarations` field', async () => {
const initialContent = `
import {NgModule, Component} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {ButtonModule} from './button.module';
import {MatCardModule} from '@angular/material/card';
function setup(declarations: any[], imports: any[]) {
TestBed.configureTestingModule({
declarations: declarations,
imports,
});
return TestBed.createComponent(App);
}
describe('bootstrapping an app', () => {
it('should work', () => {
const fixture = setup([App, Hello], [ButtonModule, MatCardModule]);
expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>');
});
it('should work in a different way', () => {
const fixture = setup([App, Hello], [MatCardModule]);
expect(fixture.nativeElement.innerHTML).toBe('<hello>Hello</hello>');
});
});
@Component({selector: 'hello', template: 'Hello'})
class Hello {}
@Component({template: '<hello></hello>'})
class App {}
`;
writeFile('app.spec.ts', initialContent);
await runMigration('convert-to-standalone');
expect(tree.readContent('app.spec.ts')).toBe(initialContent);
});
it('should not migrate modules with a `bootstrap` array', async () => {
const initialModule = `
import {NgModule, Component} from '@angular/core';
@Component({selector: 'root-comp', template: 'hello'})
export class RootComp {}
@NgModule({declarations: [RootComp], bootstrap: [RootComp]})
export class Mod {}
`;
writeFile('module.ts', initialModule);
await runMigration('convert-to-standalone');
expect(tree.readContent('module.ts')).toBe(initialModule);
});
it('should migrate a module with an empty `bootstrap` array', async () => {
writeFile(
'module.ts',
`
import {NgModule, Component} from '@angular/core';
@Component({selector: 'root-comp', template: 'hello', standalone: false})
export class RootComp {}
@NgModule({declarations: [RootComp], bootstrap: []})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('module.ts'))).toBe(
stripWhitespace(`
import {NgModule, Component} from '@angular/core';
@Component({selector: 'root-comp', template: 'hello'})
export class RootComp {}
@NgModule({imports: [RootComp], bootstrap: []})
export class Mod {}
`),
);
});
it('should migrate declarations that are not being bootstrapped in a root module', async () => {
writeFile(
'dir.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[foo]', standalone: false})
export class MyDir {}
`,
);
writeFile(
'module.ts',
`
import {NgModule, Component} from '@angular/core';
import {MyDir} from './dir';
@Component({selector: 'root-comp', template: 'hello', standalone: false})
export class RootComp {}
@NgModule({declarations: [RootComp, MyDir], bootstrap: [RootComp]})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('dir.ts'))).toBe(
stripWhitespace(`
import {Directive} from '@angular/core';
@Directive({selector: '[foo]'})
export class MyDir {}
`),
);
expect(stripWhitespace(tree.readContent('module.ts'))).toBe(
stripWhitespace(`
import {NgModule, Component} from '@angular/core';
import {MyDir} from './dir';
@Component({selector: 'root-comp', template: 'hello', standalone: false})
export class RootComp {}
@NgModule({imports: [MyDir], declarations: [RootComp], bootstrap: [RootComp]})
export class Mod {}
`),
);
});
it('should generate a forwardRef for forward reference within the same file', async () => {
writeFile(
'decls.ts',
`
import {Component, Directive} from '@angular/core';
@Component({
selector: 'comp',
template: '<div my-dir></div>',
standalone: false
})
export class MyComp {}
@Directive({selector: '[my-dir]', standalone: false})
export class MyDir {}
`,
);
writeFile(
'module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp, MyDir} from './decls';
@NgModule({declarations: [MyComp, MyDir]})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('decls.ts'))).toEqual(
stripWhitespace(`
import {Component, Directive, forwardRef} from '@angular/core';
@Component({
selector: 'comp',
template: '<div my-dir></div>',
imports: [forwardRef(() => MyDir)]
})
export class MyComp {}
@Directive({selector: '[my-dir]'})
export class MyDir {}
`),
);
});
it('should not generate a forwardRef for a self import', async () => {
writeFile(
'decls.ts',
`
import {Component} from '@angular/core';
@Component({
selector: 'comp',
template: '<comp/>',
standalone: false,
})
export class MyComp {}
`,
);
writeFile(
'module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './decls';
@NgModule({declarations: [MyComp]})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('decls.ts'))).toEqual(
stripWhitespace(`
import {Component} from '@angular/core';
@Component({
selector: 'comp',
template: '<comp/>',
})
export class MyComp {}
`),
);
});
it('should not generate a forwardRef when adding an imported module dependency', async () => {
writeFile(
'./comp.ts',
`
import {Component, NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';
@Component({
selector: 'comp',
template: '<div routerLink="/"></div>',
standalone: false
})
export class MyComp {}
@NgModule({imports: [RouterModule], declarations: [MyComp]})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('comp.ts'))).toEqual(
stripWhitespace(`
import {Component, NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';
@Component({
selector: 'comp',
template: '<div routerLink="/"></div>',
imports: [RouterModule]
})
export class MyComp {}
@NgModule({imports: [RouterModule, MyComp]})
export class Mod {}
`),
);
});
it('should not duplicate doc strings', async () => {
writeFile(
'module.ts',
`
import {NgModule, Directive} from '@angular/core';
/** Directive used for testing. */
@Directive({selector: '[dir]', standalone: false})
export class MyDir {}
/** Module used for testing. */
@NgModule({declarations: [MyDir]})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('module.ts'))).toBe(
stripWhitespace(`
import {NgModule, Directive} from '@angular/core';
/** Directive used for testing. */
@Directive({selector: '[dir]'})
export class MyDir {}
/** Module used for testing. */
@NgModule({imports: [MyDir]})
export class Mod {}
`),
);
});
it('should use the generated alia | {
"end_byte": 57316,
"start_byte": 49334,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_migration_spec.ts"
} |
angular/packages/core/schematics/test/standalone_migration_spec.ts_57320_65728 | a conflicting symbol already exists', async () => {
writeFile(
'module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import {MyButton} from './button';
@NgModule({declarations: [MyComp, MyButton], exports: [MyComp]})
export class Mod {}
`,
);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
import {MyButton} from '@external/button';
MyButton.sayHello();
@Component({selector: 'my-comp', template: '<my-button>Hello</my-button>', standalone: false})
export class MyComp {}
`,
);
writeFile(
'button.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-button', template: '<ng-content></ng-content>', standalone: false})
export class MyButton {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('comp.ts'))).toBe(
stripWhitespace(`
import {Component} from '@angular/core';
import {MyButton} from '@external/button';
import {MyButton as MyButton_1} from './button';
MyButton.sayHello();
@Component({
selector: 'my-comp', template: '<my-button>Hello</my-button>',
imports: [MyButton_1]
})
export class MyComp {}
`),
);
});
it('should preserve the trailing comma when adding an `imports` array', async () => {
writeFile(
'module.ts',
`
import {NgModule, Directive} from '@angular/core';
@Directive({selector: '[dir]', standalone: false})
export class MyDir {}
@NgModule({
declarations: [MyDir],
exports: [MyDir],
})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(`
@NgModule({
imports: [MyDir],
exports: [MyDir],
})
`),
);
});
it('should preserve the trailing comma when adding to an existing `imports` array', async () => {
writeFile(
'module.ts',
`
import {NgModule, Directive} from '@angular/core';
import {CommonModule} from '@angular/common';
import {RouterModule} from '@angular/router';
@Directive({selector: '[dir]', standalone: false})
export class MyDir {}
@NgModule({
imports: [
CommonModule,
RouterModule,
],
declarations: [MyDir],
exports: [MyDir],
})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(`
@NgModule({
imports: [
CommonModule,
RouterModule,
MyDir,
],
exports: [MyDir],
})
`),
);
});
it('should preserve the trailing comma when marking a directive as standalone', async () => {
writeFile(
'module.ts',
`
import {NgModule, Directive} from '@angular/core';
@Directive({
selector: '[dir]',
exportAs: 'dir',
standalone: false,
})
export class MyDir {}
@NgModule({declarations: [MyDir]})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(`
@Directive({
selector: '[dir]',
exportAs: 'dir',
})
`),
);
});
it('should add a trailing comma when generating an imports array in a component', async () => {
writeFile(
'module.ts',
`
import {NgModule, Directive, Component} from '@angular/core';
@Directive({selector: '[dir-one]', standalone: false})
export class DirOne {}
@Directive({selector: '[dir-two]', standalone: false})
export class DirTwo {}
@Directive({selector: '[dir-three]', standalone: false})
export class DirThree {}
@Component({
selector: 'my-comp',
template: '<div dir-one dir-two dir-three></div>',
standalone: false,
})
export class MyComp {}
@NgModule({declarations: [DirOne, DirTwo, DirThree, MyComp]})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
expect(stripWhitespace(tree.readContent('module.ts'))).toContain(
stripWhitespace(`
@Component({
selector: 'my-comp',
template: '<div dir-one dir-two dir-three></div>',
imports: [
DirOne,
DirTwo,
DirThree,
],
})
`),
);
});
it('should handle a directive that is explicitly standalone: false', async () => {
writeFile(
'module.ts',
`
import {NgModule, Directive} from '@angular/core';
@Directive({selector: '[dir]', standalone: false})
export class MyDir {}
@NgModule({declarations: [MyDir], exports: [MyDir]})
export class Mod {}
`,
);
await runMigration('convert-to-standalone');
const result = tree.readContent('module.ts');
expect(stripWhitespace(result)).toContain(stripWhitespace(`@Directive({selector: '[dir]'})`));
expect(stripWhitespace(result)).toContain(
stripWhitespace(`@NgModule({imports: [MyDir], exports: [MyDir]})`),
);
});
it('should remove a module that only has imports and exports', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import {ButtonModule} from './button.module';
@NgModule({imports: [ButtonModule], declarations: [MyComp], exports: [ButtonModule, MyComp]})
export class AppModule {}
`,
);
writeFile(
'button.module.ts',
`
import {NgModule} from '@angular/core';
import {MyButton} from './button';
@NgModule({imports: [MyButton], exports: [MyButton]})
export class ButtonModule {}
`,
);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-comp', template: '<my-button>Hello</my-button>', standalone: false})
export class MyComp {}
`,
);
writeFile(
'button.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-button', template: '<ng-content></ng-content>', standalone: true})
export class MyButton {}
`,
);
await runMigration('prune-ng-modules');
const appModule = tree.readContent('app.module.ts');
expect(tree.exists('button.module.ts')).toBe(false);
expect(appModule).not.toContain('ButtonModule');
expect(stripWhitespace(appModule)).toContain(
stripWhitespace(`
@NgModule({imports: [], declarations: [MyComp], exports: [MyComp]})
export class AppModule {}
`),
);
});
it('should not remove a module that has declarations', async () => {
const initialAppModule = `
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import {ButtonModule} from './button.module';
@NgModule({declarations: [MyComp]})
export class AppModule {}
`;
writeFile('app.module.ts', initialAppModule);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-comp', template: 'Hello', standalone: false})
export class MyComp {}
`,
);
await runMigration('prune-ng-modules');
expect(tree.readContent('app.module.ts')).toBe(initialAppModule);
});
it('should not remove a module that bootstraps a component', async () => {
const initialAppModule = `
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import {ButtonModule} from './button.module';
@NgModule({bootstrap: [MyComp]})
export class AppModule {}
`;
writeFile('app.module.ts', initialAppModule);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-comp', template: 'Hello', standalone: false})
export class MyComp {}
`,
);
await runMigration('prune-ng-modules');
expect(tree.readContent('app.module.ts')).toBe(initialAppModule);
});
it('should not remove a module th | {
"end_byte": 65728,
"start_byte": 57320,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_migration_spec.ts"
} |
angular/packages/core/schematics/test/standalone_migration_spec.ts_65732_74079 | as providers', async () => {
const initialAppModule = `
import {NgModule, InjectionToken} from '@angular/core';
const token = new InjectionToken('token');
@NgModule({providers: [{provide: token, useValue: 123}]})
export class AppModule {}
`;
writeFile('app.module.ts', initialAppModule);
await runMigration('prune-ng-modules');
expect(tree.readContent('app.module.ts')).toBe(initialAppModule);
});
it('should not remove a module that imports a ModuleWithProviders', async () => {
const initialAppModule = `
import {NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';
@NgModule({imports: [RouterModule.forRoot([])]})
export class RoutingModule {}
`;
writeFile('app.module.ts', initialAppModule);
await runMigration('prune-ng-modules');
expect(tree.readContent('app.module.ts')).toBe(initialAppModule);
});
it('should not remove a module that has class members', async () => {
const initialAppModule = `
import {NgModule} from '@angular/core';
import {ButtonModule} from './button.module';
@NgModule()
export class AppModule {
sum(a: number, b: number) {
return a + b;
}
}
`;
writeFile('app.module.ts', initialAppModule);
await runMigration('prune-ng-modules');
expect(tree.readContent('app.module.ts')).toBe(initialAppModule);
});
it('should remove a module that only has an empty constructor', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {ButtonModule} from './button.module';
@NgModule()
export class AppModule {
constructor() {
}
}
`,
);
await runMigration('prune-ng-modules');
expect(tree.exists('app.module.ts')).toBe(false);
});
it('should remove a module with no arguments passed into NgModule', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
@NgModule()
export class AppModule {}
`,
);
await runMigration('prune-ng-modules');
expect(tree.exists('app.module.ts')).toBe(false);
});
it('should remove a module file where there is unexported code', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
const ONE = 1;
const TWO = 2;
console.log(ONE + TWO);
@NgModule()
export class AppModule {}
`,
);
await runMigration('prune-ng-modules');
expect(tree.exists('app.module.ts')).toBe(false);
});
it('should remove a module that passes empty arrays into `declarations`, `providers` and `bootstrap`', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {ButtonModule} from './button.module';
@NgModule({declarations: [], providers: [], bootstrap: []})
export class AppModule {}
`,
);
await runMigration('prune-ng-modules');
expect(tree.exists('app.module.ts')).toBe(false);
});
it('should remove a chain of modules that all depend on each other', async () => {
writeFile(
'a.module.ts',
`
import {NgModule} from '@angular/core';
@NgModule({})
export class ModuleA {}
`,
);
writeFile(
'b.module.ts',
`
import {NgModule} from '@angular/core';
import {ModuleA} from './a.module';
@NgModule({imports: [ModuleA]})
export class ModuleB {}
`,
);
writeFile(
'c.module.ts',
`
import {NgModule} from '@angular/core';
import {ModuleB} from './b.module';
@NgModule({imports: [ModuleB]})
export class ModuleC {}
`,
);
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {MyDir} from './dir';
import {ModuleC} from './c.module';
@NgModule({imports: [ModuleC], declarations: [MyDir]})
export class AppModule {}
`,
);
writeFile(
'dir.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[myDir]'})
export class MyDir {}
`,
);
await runMigration('prune-ng-modules');
const appModule = tree.readContent('app.module.ts');
expect(tree.exists('a.module.ts')).toBe(false);
expect(tree.exists('b.module.ts')).toBe(false);
expect(tree.exists('c.module.ts')).toBe(false);
expect(appModule).not.toContain('ModuleC');
expect(stripWhitespace(appModule)).toContain(
stripWhitespace(`
@NgModule({imports: [], declarations: [MyDir]})
export class AppModule {}
`),
);
});
it('should not remove a chain of modules if a module in the chain cannot be removed because it has providers', async () => {
const moduleAContent = `
import {NgModule, InjectionToken} from '@angular/core';
export const token = new InjectionToken<any>('token');
@NgModule({providers: [{provide: token, useValue: 123}]})
export class ModuleA {}
`;
const moduleBContent = `
import {NgModule} from '@angular/core';
import {ModuleA} from './a.module';
@NgModule({imports: [ModuleA]})
export class ModuleB {}
`;
const moduleCContent = `
import {NgModule} from '@angular/core';
import {ModuleB} from './b.module';
@NgModule({imports: [ModuleB]})
export class ModuleC {}
`;
const appModuleContent = `
import {NgModule} from '@angular/core';
import {MyDir} from './dir';
import {ModuleC} from './c.module';
@NgModule({imports: [ModuleC], declarations: [MyDir]})
export class AppModule {}
`;
writeFile('a.module.ts', moduleAContent);
writeFile('b.module.ts', moduleBContent);
writeFile('c.module.ts', moduleCContent);
writeFile('app.module.ts', appModuleContent);
writeFile(
'dir.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[myDir]'})
export class MyDir {}
`,
);
await runMigration('prune-ng-modules');
expect(tree.readContent('a.module.ts')).toBe(moduleAContent);
expect(tree.readContent('b.module.ts')).toBe(moduleBContent);
expect(tree.readContent('c.module.ts')).toBe(moduleCContent);
expect(tree.readContent('app.module.ts')).toBe(appModuleContent);
});
it('should not remove a chain of modules if a module in the chain cannot be removed because it is importing a ModuleWithProviders', async () => {
const moduleAContent = `
import {NgModule} from '@angular/core';
@NgModule({imports: [RouterModule.forRoot([{path: '/foo'}])]})
export class ModuleA {}
`;
const moduleBContent = `
import {NgModule} from '@angular/core';
import {ModuleA} from './a.module';
@NgModule({imports: [ModuleA]})
export class ModuleB {}
`;
const moduleCContent = `
import {NgModule} from '@angular/core';
import {ModuleB} from './b.module';
@NgModule({imports: [ModuleB]})
export class ModuleC {}
`;
const appModuleContent = `
import {NgModule} from '@angular/core';
import {MyDir} from './dir';
import {ModuleC} from './c.module';
@NgModule({imports: [ModuleC], declarations: [MyDir]})
export class AppModule {}
`;
writeFile('a.module.ts', moduleAContent);
writeFile('b.module.ts', moduleBContent);
writeFile('c.module.ts', moduleCContent);
writeFile('app.module.ts', appModuleContent);
writeFile(
'dir.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[myDir]'})
export class MyDir {}
`,
);
await runMigration('prune-ng-modules');
expect(tree.readContent('a.module.ts')).toBe(moduleAContent);
expect(tree.readContent('b.module.ts')).toBe(moduleBContent);
expect(tree.readContent('c.module.ts')).toBe(moduleCContent);
expect(tree.readContent('app.module.ts')).toBe(appModuleContent);
});
it('should not remove the module | {
"end_byte": 74079,
"start_byte": 65732,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_migration_spec.ts"
} |
angular/packages/core/schematics/test/standalone_migration_spec.ts_74083_81335 | if it contains other exported code', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import {sum, ButtonModule, multiply} from './button.module';
@NgModule({imports: [ButtonModule], declarations: [MyComp], exports: [ButtonModule, MyComp]})
export class AppModule {}
console.log(sum(1, 2), multiply(3, 4));
`,
);
writeFile(
'button.module.ts',
`
import {NgModule} from '@angular/core';
import {MyButton} from './button';
export function sum(a: number, b: number) {
return a + b;
}
@NgModule({imports: [MyButton], exports: [MyButton]})
export class ButtonModule {}
export function multiply(a: number, b: number) {
return a * b;
}
`,
);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-comp', template: '<my-button>Hello</my-button>'})
export class MyComp {}
`,
);
writeFile(
'button.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-button', template: '<ng-content></ng-content>', standalone: true})
export class MyButton {}
`,
);
await runMigration('prune-ng-modules');
expect(stripWhitespace(tree.readContent('button.module.ts'))).toBe(
stripWhitespace(`
import {NgModule} from '@angular/core';
import {MyButton} from './button';
export function sum(a: number, b: number) {
return a + b;
}
export function multiply(a: number, b: number) {
return a * b;
}
`),
);
expect(stripWhitespace(tree.readContent('app.module.ts'))).toBe(
stripWhitespace(`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import {sum, multiply} from './button.module';
@NgModule({imports: [], declarations: [MyComp], exports: [MyComp]})
export class AppModule {}
console.log(sum(1, 2), multiply(3, 4));
`),
);
});
it('should delete a file that contains multiple modules that are being deleted', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import {ButtonModule, TooltipModule} from './shared-modules';
@NgModule({
imports: [ButtonModule, TooltipModule],
declarations: [MyComp],
exports: [ButtonModule, MyComp, TooltipModule]
})
export class AppModule {}
`,
);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-comp', template: ''})
export class MyComp {}
`,
);
writeFile(
'shared-modules.ts',
`
import {NgModule} from '@angular/core';
import {MyButton} from './button';
import {MyTooltip} from './tooltip';
@NgModule({imports: [MyButton], exports: [MyButton]})
export class ButtonModule {}
@NgModule({imports: [MyTooltip], exports: [MyTooltip]})
export class TooltipModule {}
`,
);
writeFile(
'button.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[my-button]' standalone: true})
export class MyButton {}
`,
);
writeFile(
'tooltip.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[my-tooltip]' standalone: true})
export class MyTooltip {}
`,
);
await runMigration('prune-ng-modules');
const appModule = tree.readContent('app.module.ts');
expect(tree.exists('shared-modules.ts')).toBe(false);
expect(appModule).not.toContain('ButtonModule');
expect(appModule).not.toContain('TooltipModule');
expect(stripWhitespace(appModule)).toContain(
stripWhitespace(`
@NgModule({
imports: [],
declarations: [MyComp],
exports: [MyComp]
})
export class AppModule {}
`),
);
});
it('should preserve an import that has one NgModule that is being deleted, in addition to a named import', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import Foo, {ButtonModule} from './button.module';
@NgModule({imports: [ButtonModule], declarations: [MyComp], exports: [ButtonModule, MyComp]})
export class AppModule {}
`,
);
writeFile(
'button.module.ts',
`
import {NgModule} from '@angular/core';
import {MyButton} from './button';
@NgModule({imports: [MyButton], exports: [MyButton]})
export class ButtonModule {}
`,
);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-comp', template: '<my-button>Hello</my-button>'})
export class MyComp {}
`,
);
writeFile(
'button.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-button', template: '<ng-content></ng-content>', standalone: true})
export class MyButton {}
`,
);
await runMigration('prune-ng-modules');
expect(tree.exists('button.module.ts')).toBe(false);
expect(tree.readContent('app.module.ts')).toContain(`import Foo from './button.module';`);
});
it('should remove module references from export expressions', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
@NgModule({imports: [MyComp]})
export class AppModule {}
`,
);
writeFile(
'button.module.ts',
`
import {NgModule} from '@angular/core';
import {MyButton} from './button';
@NgModule({imports: [MyButton], exports: [MyButton]})
export class ButtonModule {}
`,
);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
import {MyButton} from './button';
@Component({
selector: 'my-comp',
template: '<my-button>Hello</my-button>',
standalone: true,
imports: [MyButton]
})
export class MyComp {}
`,
);
writeFile(
'button.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-button', template: '<ng-content></ng-content>', standalone: true})
export class MyButton {}
`,
);
writeFile(
'index.ts',
`
export {AppModule} from './app.module';
export {MyComp} from './comp';
export {ButtonModule} from './button.module';
export {MyButton} from './button';
`,
);
await runMigration('prune-ng-modules');
expect(tree.exists('app.module.ts')).toBe(false);
expect(tree.exists('button.module.ts')).toBe(false);
expect(stripWhitespace(tree.readContent('index.ts'))).toBe(
stripWhitespace(`
export {MyComp} from './comp';
export {MyButton} from './button';
`),
);
});
it('should remove barrel export i | {
"end_byte": 81335,
"start_byte": 74083,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_migration_spec.ts"
} |
angular/packages/core/schematics/test/standalone_migration_spec.ts_81339_90039 | e corresponding file is deleted', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
@NgModule({imports: [MyComp]})
export class AppModule {}
`,
);
writeFile(
'button.module.ts',
`
import {NgModule} from '@angular/core';
import {MyButton} from './button';
@NgModule({imports: [MyButton], exports: [MyButton]})
export class ButtonModule {}
`,
);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
import {MyButton} from './button';
@Component({
selector: 'my-comp',
template: '<my-button>Hello</my-button>',
standalone: true,
imports: [MyButton]
})
export class MyComp {}
`,
);
writeFile(
'button.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-button', template: '<ng-content></ng-content>', standalone: true})
export class MyButton {}
`,
);
writeFile(
'index.ts',
`
export * from './app.module';
export {MyComp} from './comp';
export {ButtonModule} from './button.module';
`,
);
await runMigration('prune-ng-modules');
expect(tree.exists('app.module.ts')).toBe(false);
expect(tree.exists('button.module.ts')).toBe(false);
expect(stripWhitespace(tree.readContent('index.ts'))).toBe(
stripWhitespace(`
export {MyComp} from './comp';
`),
);
});
it('should remove barrel files referring to other barrel files that were deleted', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {MyDir} from './dir';
@NgModule({imports: [MyDir]})
export class AppModule {}
`,
);
writeFile(
'dir.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[dir]', standalone: true})
export class MyDir {}
`,
);
writeFile('index.ts', `export * from './app.module';`);
writeFile('index-2.ts', `export * from './index';`);
writeFile('index-3.ts', `export * from './index-2';`);
await runMigration('prune-ng-modules');
expect(tree.exists('index.ts')).toBe(false);
expect(tree.exists('index-2.ts')).toBe(false);
expect(tree.exists('index-3.ts')).toBe(false);
});
it('should not delete dependent barrel files if they have some barrel exports that will not be removed', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {MyDir} from './dir';
@NgModule({imports: [MyDir]})
export class AppModule {}
`,
);
writeFile(
'dir.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[dir]', standalone: true})
export class MyDir {}
`,
);
writeFile(
'utils.ts',
`
export function sum(a: number, b: number) { return a + b; }
`,
);
writeFile('index.ts', `export * from './app.module';`);
writeFile(
'index-2.ts',
`
export * from './index';
export * from './utils';
`,
);
writeFile('index-3.ts', `export * from './index-2';`);
await runMigration('prune-ng-modules');
expect(tree.exists('index.ts')).toBe(false);
expect(stripWhitespace(tree.readContent('index-2.ts'))).toBe(
stripWhitespace(`export * from './utils';`),
);
expect(stripWhitespace(tree.readContent('index-3.ts'))).toBe(
stripWhitespace(`export * from './index-2';`),
);
});
it('should add a comment to locations that cannot be removed automatically', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
import {ButtonModule} from './button.module';
console.log(ButtonModule);
if (typeof ButtonModule !== 'undefined') {
console.log('Exists!');
}
export const FOO = ButtonModule;
@NgModule({imports: [ButtonModule], declarations: [MyComp], exports: [ButtonModule, MyComp]})
export class AppModule {}
`,
);
writeFile(
'button.module.ts',
`
import {NgModule} from '@angular/core';
@NgModule()
export class ButtonModule {}
`,
);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
@Component({selector: 'my-comp', template: 'Hello'})
export class MyComp {}
`,
);
await runMigration('prune-ng-modules');
expect(tree.exists('button.module.ts')).toBe(false);
expect(stripWhitespace(tree.readContent('app.module.ts'))).toBe(
stripWhitespace(`
import {NgModule} from '@angular/core';
import {MyComp} from './comp';
console.log( /* TODO(standalone-migration): clean up removed NgModule reference manually. */ ButtonModule);
if (typeof /* TODO(standalone-migration): clean up removed NgModule reference manually. */ ButtonModule !== 'undefined') {
console.log('Exists!');
}
export const FOO = /* TODO(standalone-migration): clean up removed NgModule reference manually. */ ButtonModule;
@NgModule({imports: [], declarations: [MyComp], exports: [MyComp]})
export class AppModule {}
`),
);
});
it('should preserve the trailing comma when deleting a module', async () => {
const initialAppModule = `
import {NgModule, InjectionToken} from '@angular/core';
import {CommonModule} from '@angular/common';
import {RouterModule} from '@angular/router';
const token = new InjectionToken('token');
@NgModule()
export class ToDelete {}
@NgModule({
imports: [
CommonModule,
ToDelete,
RouterModule,
],
providers: [{provide: token, useValue: 123}],
})
export class AppModule {}
`;
writeFile('app.module.ts', initialAppModule);
await runMigration('prune-ng-modules');
expect(stripWhitespace(tree.readContent('app.module.ts'))).toContain(
stripWhitespace(`
@NgModule({
imports: [
CommonModule,
RouterModule,
],
providers: [{provide: token, useValue: 123}],
})
`),
);
});
it('should replace any leftover NgModule classes in imports arrays with the exports used in the template', async () => {
writeFile(
'button.module.ts',
`
import {NgModule, Directive} from '@angular/core';
import {MyDir, MyButton} from './used';
import {Unused} from './unused';
@NgModule({imports: [MyButton, MyDir, Unused], exports: [MyButton, MyDir, Unused]})
export class ButtonModule {}
`,
);
// Declared in the module, but not used.
writeFile(
'unused.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[unused]', standalone: true})
export class Unused {}
`,
);
writeFile(
'used.ts',
`
import {Directive, Component} from '@angular/core';
@Directive({selector: '[my-dir]', standalone: true})
export class MyDir {}
@Component({selector: 'my-button', template: '<ng-content/>', standalone: true})
export class MyButton {}
`,
);
writeFile(
'unrelated.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[unrelated]', standalone: true})
export class Unrelated {}
`,
);
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
import {ButtonModule} from './button.module';
import {Unrelated} from './unrelated';
@Component({
selector: 'my-comp',
template: '<my-button my-dir unrelated>Hello</my-button>',
imports: [ButtonModule, Unrelated],
standalone: true,
})
export class MyComp {}
`,
);
await runMigration('prune-ng-modules');
expect(tree.exists('button.module.ts')).toBe(false);
expect(stripWhitespace(tree.readContent('comp.ts'))).toBe(
stripWhitespace(`
import {Component} from '@angular/core';
import {Unrelated} from './unrelated';
import {MyButton, MyDir} from './used';
@Component({
selector: 'my-comp',
template: '<my-button my-dir unrelated>Hello</my-button>',
imports: [MyButton, MyDir, Unrelated],
standalone: true,
})
export class MyComp {}
`),
);
});
it('should switch a platformBrows | {
"end_byte": 90039,
"start_byte": 81339,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_migration_spec.ts"
} |
angular/packages/core/schematics/test/standalone_migration_spec.ts_90043_98758 | .bootstrapModule call to bootstrapApplication', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
@Component({template: 'hello', standalone: false})
export class AppComponent {}
@NgModule({declarations: [AppComponent], bootstrap: [AppComponent]})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
bootstrapApplication(AppComponent).catch(e => console.error(e));
`),
);
expect(stripWhitespace(tree.readContent('./app/app.module.ts'))).toBe(
stripWhitespace(`
import {NgModule, Component} from '@angular/core';
@Component({template: 'hello'})
export class AppComponent {}
`),
);
});
it('should switch a platformBrowserDynamic().bootstrapModule call to bootstrapApplication', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
platformBrowserDynamic().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
@Component({template: 'hello', standalone: false})
export class AppComponent {}
@NgModule({declarations: [AppComponent], bootstrap: [AppComponent]})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {bootstrapApplication} from '@angular/platform-browser';
bootstrapApplication(AppComponent).catch(e => console.error(e));
`),
);
expect(stripWhitespace(tree.readContent('./app/app.module.ts'))).toBe(
stripWhitespace(`
import {NgModule, Component} from '@angular/core';
@Component({template: 'hello'})
export class AppComponent {}
`),
);
});
it('should switch a PlatformRef.bootstrapModule call to bootstrapApplication', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {PlatformRef} from '@angular/core';
const foo: PlatformRef = null!;
foo.bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
@Component({template: 'hello', standalone: false})
export class AppComponent {}
@NgModule({declarations: [AppComponent], bootstrap: [AppComponent]})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {PlatformRef} from '@angular/core';
import {bootstrapApplication} from '@angular/platform-browser';
const foo: PlatformRef = null!;
bootstrapApplication(AppComponent).catch(e => console.error(e));
`),
);
expect(stripWhitespace(tree.readContent('./app/app.module.ts'))).toBe(
stripWhitespace(`
import {NgModule, Component} from '@angular/core';
@Component({template: 'hello'})
export class AppComponent {}
`),
);
});
it('should convert the root module declarations to standalone', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.component.ts',
`
import {Component} from '@angular/core';
@Component({template: '<div *ngIf="show" dir>hello</div>', standalone: false})
export class AppComponent {
show = true;
}
`,
);
writeFile(
'./app/dir.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[dir]', standalone: false})
export class Dir {}
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {AppComponent} from './app.component';
import {Dir} from './dir';
@NgModule({
imports: [CommonModule],
declarations: [AppComponent, Dir],
bootstrap: [AppComponent]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(tree.exists('./app/app.module.ts')).toBe(false);
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {CommonModule} from '@angular/common';
import {AppComponent} from './app/app.component';
import {importProvidersFrom} from '@angular/core';
bootstrapApplication(AppComponent, {
providers: [importProvidersFrom(CommonModule)]
}).catch(e => console.error(e));
`),
);
expect(stripWhitespace(tree.readContent('./app/app.component.ts'))).toBe(
stripWhitespace(`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
import {Dir} from './dir';
@Component({
template: '<div *ngIf="show" dir>hello</div>',
imports: [NgIf, Dir]
})
export class AppComponent {
show = true;
}
`),
);
expect(stripWhitespace(tree.readContent('./app/dir.ts'))).toBe(
stripWhitespace(`
import {Directive} from '@angular/core';
@Directive({selector: '[dir]'})
export class Dir {}
`),
);
});
it('should migrate the root component tests when converting to standalone', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.component.ts',
`
import {Component} from '@angular/core';
@Component({template: 'hello', standalone: false})
export class AppComponent {}
`,
);
writeFile(
'./app/app.component.spec.ts',
`
import {TestBed} from '@angular/core/testing';
import {AppComponent} from './app.component';
describe('bootstrapping an app', () => {
it('should work', () => {
TestBed.configureTestingModule({declarations: [AppComponent]});
const fixture = TestBed.createComponent(AppComponent);
expect(fixture.nativeElement.innerHTML).toBe('hello');
});
});
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule} from '@angular/core';
import {AppComponent} from './app.component';
@NgModule({declarations: [AppComponent], bootstrap: [AppComponent]})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('./app/app.component.ts'))).toBe(
stripWhitespace(`
import {Component} from '@angular/core';
@Component({template: 'hello'})
export class AppComponent {}
`),
);
expect(stripWhitespace(tree.readContent('./app/app.component.spec.ts'))).toBe(
stripWhitespace(`
import {TestBed} from '@angular/core/testing';
import {AppComponent} from './app.component';
describe('bootstrapping an app', () => {
it('should work', () => {
TestBed.configureTestingModule({imports: [AppComponent]});
const fixture = TestBed.createComponent(AppComponent);
expect(fixture.nativeElement.innerHTML).toBe('hello');
});
});
`),
);
});
it('should copy providers and the | {
"end_byte": 98758,
"start_byte": 90043,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_migration_spec.ts"
} |
angular/packages/core/schematics/test/standalone_migration_spec.ts_98762_106866 | bols they depend on to the main file', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component, InjectionToken} from '@angular/core';
import {externalToken} from './externals/token';
import {externalToken as aliasedExternalToken} from './externals/other-token';
import {ExternalInterface} from '@external/interfaces';
import {InternalInterface} from './interfaces/internal-interface';
const internalToken = new InjectionToken<string>('internalToken');
export const exportedToken = new InjectionToken<InternalInterface>('exportedToken');
export class ExportedClass {}
export function exportedFactory(value: InternalInterface) {
return value.foo;
}
const unexportedExtraProviders = [
{provide: aliasedExternalToken, useFactory: (value: ExternalInterface) => value.foo}
];
export const exportedExtraProviders = [
{provide: exportedToken, useClass: ExportedClass}
];
@Component({template: 'hello', standalone: false})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [
{provide: internalToken, useValue: 'hello'},
{provide: externalToken, useValue: 123, multi: true},
{provide: externalToken, useFactory: exportedFactory, multi: true},
...unexportedExtraProviders,
...exportedExtraProviders
]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
// Note that this leaves a couple of unused imports from `app.module`.
// The schematic optimizes for safety, rather than avoiding unused imports.
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {exportedToken, exportedExtraProviders, ExportedClass, exportedFactory, AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {InjectionToken} from '@angular/core';
import {InternalInterface} from './app/interfaces/internal-interface';
import {externalToken} from './app/externals/token';
import {externalToken as aliasedExternalToken} from './app/externals/other-token';
import {ExternalInterface} from '@external/interfaces';
const internalToken = new InjectionToken<string>('internalToken');
const unexportedExtraProviders = [
{provide: aliasedExternalToken, useFactory: (value: ExternalInterface) => value.foo}
];
bootstrapApplication(AppComponent, {
providers: [
{provide: internalToken, useValue: 'hello'},
{provide: externalToken, useValue: 123, multi: true},
{provide: externalToken, useFactory: exportedFactory, multi: true},
...unexportedExtraProviders,
...exportedExtraProviders
]
}).catch(e => console.error(e));
`),
);
expect(stripWhitespace(tree.readContent('./app/app.module.ts'))).toBe(
stripWhitespace(`
import {NgModule, Component, InjectionToken} from '@angular/core';
import {externalToken} from './externals/token';
import {externalToken as aliasedExternalToken} from './externals/other-token';
import {ExternalInterface} from '@external/interfaces';
import {InternalInterface} from './interfaces/internal-interface';
const internalToken = new InjectionToken<string>('internalToken');
export const exportedToken = new InjectionToken<InternalInterface>('exportedToken');
export class ExportedClass {}
export function exportedFactory(value: InternalInterface) {
return value.foo;
}
const unexportedExtraProviders = [
{provide: aliasedExternalToken, useFactory: (value: ExternalInterface) => value.foo}
];
export const exportedExtraProviders = [
{provide: exportedToken, useClass: ExportedClass}
];
@Component({template: 'hello'})
export class AppComponent {}
`),
);
});
it('should not copy over non-declaration references to the main file', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component, InjectionToken} from '@angular/core';
export const token = new InjectionToken<string>('token');
console.log(token);
@Component({template: 'hello', standalone: false})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [{provide: token, useValue: 'hello'}]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {token, AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {InjectionToken} from '@angular/core';
bootstrapApplication(AppComponent, {
providers: [{ provide: token, useValue: 'hello' }]
}).catch(e => console.error(e));
`),
);
expect(stripWhitespace(tree.readContent('./app/app.module.ts'))).toBe(
stripWhitespace(`
import {NgModule, Component, InjectionToken} from '@angular/core';
export const token = new InjectionToken<string>('token');
console.log(token);
@Component({template: 'hello'})
export class AppComponent {}
`),
);
});
it('should update dynamic imports from the `providers` that are copied to the main file', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {ROUTES} from '@angular/router';
@Component({template: 'hello', standalone: false})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [{
provide: ROUTES,
useValue: [
{path: 'internal-comp', loadComponent: () => import('../routes/internal-comp').then(c => c.InternalComp)},
{path: 'external-comp', loadComponent: () => import('@external/external-comp').then(c => c.ExternalComp)}
]
}]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {ROUTES} from '@angular/router';
bootstrapApplication(AppComponent, {
providers: [{
provide: ROUTES,
useValue: [
{path: 'internal-comp', loadComponent: () => import("./routes/internal-comp").then(c => c.InternalComp)},
{path: 'external-comp', loadComponent: () => import('@external/external-comp').then(c => c.ExternalComp)}
]
}]
}).catch(e => console.error(e));
`),
);
});
it('should copy modules from the | {
"end_byte": 106866,
"start_byte": 98762,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_migration_spec.ts"
} |
angular/packages/core/schematics/test/standalone_migration_spec.ts_106870_115081 | orts` array to the `providers` and wrap them in `importProvidersFrom`', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'token.ts',
`
import {InjectionToken} from '@angular/core';
export const token = new InjectionToken<string>('token');
`,
);
writeFile(
'./modules/internal.module.ts',
`
import {NgModule} from '@angular/core';
import {token} from '../token';
@NgModule({providers: [{provide: token, useValue: 'InternalModule'}]})
export class InternalModule {}
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {CommonModule} from '@angular/common';
import {InternalModule} from '../modules/internal.module';
import {token} from '../token';
@Component({template: 'hello', standalone: true})
export class AppComponent {}
@NgModule({providers: [{provide: token, useValue: 'SameFileModule'}]})
export class SameFileModule {}
@NgModule({
imports: [CommonModule, InternalModule, SameFileModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {SameFileModule, AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {CommonModule} from '@angular/common';
import {InternalModule} from './modules/internal.module';
import {NgModule, importProvidersFrom} from '@angular/core';
import {token} from './token';
bootstrapApplication(AppComponent, {
providers: [importProvidersFrom(CommonModule, InternalModule, SameFileModule)]
}).catch(e => console.error(e));
`),
);
});
it('should switch RouterModule.forRoot calls with one argument to provideRouter', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {RouterModule} from '@angular/router';
@Component({template: 'hello', standalone: false})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [
RouterModule.forRoot([
{path: 'internal-comp', loadComponent: () => import("./routes/internal-comp").then(c => c.InternalComp) },
{path: 'external-comp', loadComponent: () => import('@external/external-comp').then(c => c.ExternalComp) }
])
]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {provideRouter} from '@angular/router';
bootstrapApplication(AppComponent, {
providers: [provideRouter([
{path: 'internal-comp', loadComponent: () => import("./app/routes/internal-comp").then(c => c.InternalComp)},
{path: 'external-comp', loadComponent: () => import('@external/external-comp').then(c => c.ExternalComp)}
])]
}).catch(e => console.error(e));
`),
);
});
it('should migrate a RouterModule.forRoot call with an empty config', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {RouterModule} from '@angular/router';
import {APP_ROUTES} from './routes';
@Component({template: 'hello', standalone: false})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [RouterModule.forRoot(APP_ROUTES, {})]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {provideRouter} from '@angular/router';
import {APP_ROUTES} from './app/routes';
bootstrapApplication(AppComponent, {
providers: [provideRouter(APP_ROUTES)]
}).catch(e => console.error(e));
`),
);
});
it('should migrate a router config with a preloadingStrategy to withPreloading', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {RouterModule} from '@angular/router';
import {of} from 'rxjs';
@Component({template: 'hello', standalone: false})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [RouterModule.forRoot([], {
preloadingStrategy: () => of(true)
})]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {withPreloading, provideRouter} from '@angular/router';
import {of} from 'rxjs';
bootstrapApplication(AppComponent, {
providers: [provideRouter([], withPreloading(() => of(true)))]
}).catch(e => console.error(e));
`),
);
});
it('should migrate a router config with enableTracing to withDebugTracing', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {RouterModule} from '@angular/router';
@Component({template: 'hello', standalone: false})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [RouterModule.forRoot([], {
enableTracing: true
})]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {withDebugTracing, provideRouter} from '@angular/router';
bootstrapApplication(AppComponent, {
providers: [provideRouter([], withDebugTracing())]
}).catch(e => console.error(e));
`),
);
});
it('should migrate a router confi | {
"end_byte": 115081,
"start_byte": 106870,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_migration_spec.ts"
} |
angular/packages/core/schematics/test/standalone_migration_spec.ts_115085_124118 | th `initialNavigation: "enabledBlocking"` to withEnabledBlockingInitialNavigation', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {RouterModule} from '@angular/router';
@Component({template: 'hello', standalone: false})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [RouterModule.forRoot([], {
initialNavigation: 'enabledBlocking'
})]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {withEnabledBlockingInitialNavigation, provideRouter} from '@angular/router';
bootstrapApplication(AppComponent, {
providers: [provideRouter([], withEnabledBlockingInitialNavigation())]
}).catch(e => console.error(e));
`),
);
});
it('should migrate a router config with `initialNavigation: "enabled"` to withEnabledBlockingInitialNavigation', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {RouterModule} from '@angular/router';
@Component({template: 'hello', standalone: false})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [RouterModule.forRoot([], {
initialNavigation: 'enabled'
})]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {withEnabledBlockingInitialNavigation, provideRouter} from '@angular/router';
bootstrapApplication(AppComponent, {
providers: [provideRouter([], withEnabledBlockingInitialNavigation())]
}).catch(e => console.error(e));
`),
);
});
it('should migrate a router config with `initialNavigation: "disabled"` to withDisabledInitialNavigation', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {RouterModule} from '@angular/router';
@Component({template: 'hello', standalone: false})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [RouterModule.forRoot([], {
initialNavigation: 'disabled'
})]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {withDisabledInitialNavigation, provideRouter} from '@angular/router';
bootstrapApplication(AppComponent, {
providers: [provideRouter([], withDisabledInitialNavigation())]
}).catch(e => console.error(e));
`),
);
});
it('should migrate a router config with useHash to withHashLocation', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {RouterModule} from '@angular/router';
@Component({template: 'hello', standalone: false})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [RouterModule.forRoot([], {
useHash: true
})]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {withHashLocation, provideRouter} from '@angular/router';
bootstrapApplication(AppComponent, {
providers: [provideRouter([], withHashLocation())]
}).catch(e => console.error(e));
`),
);
});
it('should migrate a router config with errorHandler to withNavigationErrorHandler', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {RouterModule} from '@angular/router';
@Component({template: 'hello', standalone: false})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [RouterModule.forRoot([], {
errorHandler: () => {}
})]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {withNavigationErrorHandler, provideRouter} from '@angular/router';
bootstrapApplication(AppComponent, {
providers: [provideRouter([], withNavigationErrorHandler(() => {}))]
}).catch(e => console.error(e));
`),
);
});
it('should combine the anchorScrolling and scrollPositionRestoration of a router config into withInMemoryScrolling', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {RouterModule} from '@angular/router';
@Component({template: 'hello', standalone: false})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [RouterModule.forRoot([], {
anchorScrolling: 'enabled',
scrollPositionRestoration: 'top'
})]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {withInMemoryScrolling, provideRouter} from '@angular/router';
bootstrapApplication(AppComponent, {
providers: [provideRouter([], withInMemoryScrolling({
anchorScrolling: 'enabled',
scrollPositionRestoration: 'top'
}))]
}).catch(e => console.error(e));
`),
);
});
it('should copy properties that d | {
"end_byte": 124118,
"start_byte": 115085,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_migration_spec.ts"
} |
angular/packages/core/schematics/test/standalone_migration_spec.ts_124122_132707 | t map to a feature into withRouterConfig', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {RouterModule} from '@angular/router';
@Component({template: 'hello'})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [RouterModule.forRoot([], {
canceledNavigationResolution: 'replace',
useHash: true,
paramsInheritanceStrategy: 'always'
})]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {withHashLocation, withRouterConfig, provideRouter} from '@angular/router';
bootstrapApplication(AppComponent, {
providers: [provideRouter([], withHashLocation(), withRouterConfig({
canceledNavigationResolution: 'replace',
paramsInheritanceStrategy: 'always'
}))]
}).catch(e => console.error(e));
`),
);
});
it('should preserve a RouterModule.forRoot where the config cannot be statically analyzed', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {RouterModule} from '@angular/router';
@Component({template: 'hello'})
export class AppComponent {}
const extraOptions = {useHash: true};
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [RouterModule.forRoot([], {
enableTracing: true,
...extraOptions
})]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {RouterModule} from '@angular/router';
import {importProvidersFrom} from '@angular/core';
const extraOptions = {useHash: true};
bootstrapApplication(AppComponent, {
providers: [importProvidersFrom(RouterModule.forRoot([], {
enableTracing: true,
...extraOptions
}))]
}).catch(e => console.error(e));
`),
);
});
it('should convert BrowserAnimationsModule references to provideAnimations', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
@Component({template: 'hello'})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [BrowserAnimationsModule]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {provideAnimations} from '@angular/platform-browser/animations';
bootstrapApplication(AppComponent, {
providers: [provideAnimations()]
}).catch(e => console.error(e));
`),
);
});
it('should preserve BrowserAnimationsModule.withConfig calls', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
@Component({template: 'hello'})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [BrowserAnimationsModule.withConfig({disableAnimations: true})]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {importProvidersFrom} from '@angular/core';
bootstrapApplication(AppComponent, {
providers: [importProvidersFrom(BrowserAnimationsModule.withConfig({disableAnimations: true}))]
}).catch(e => console.error(e));
`),
);
});
it('should convert NoopAnimationsModule references to provideNoopAnimations', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
@Component({template: 'hello'})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [NoopAnimationsModule]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {provideNoopAnimations} from '@angular/platform-browser/animations';
bootstrapApplication(AppComponent, {
providers: [provideNoopAnimations()]
}).catch(e => console.error(e));
`),
);
});
it('should convert HttpClientModule references to provideHttpClient(withInterceptorsFromDi())', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {HttpClientModule} from '@angular/common/http';
@Component({template: 'hello'})
export class AppComponent {}
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [HttpClientModule]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {withInterceptorsFromDi, provideHttpClient} from '@angular/common/http';
bootstrapApplication(AppComponent, {
providers: [provideHttpClient(withInterceptorsFromDi())]
}).catch(e => console.error(e));
`),
);
});
it('should omit standalone direct | {
"end_byte": 132707,
"start_byte": 124122,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_migration_spec.ts"
} |
angular/packages/core/schematics/test/standalone_migration_spec.ts_132711_139310 | from the imports array from the importProvidersFrom call', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component, Directive} from '@angular/core';
import {CommonModule} from '@angular/common';
@Directive({selector: '[dir]', standalone: true})
export class Dir {}
@Component({template: '<span dir></span>', standalone: false})
export class AppComponent {}
@NgModule({imports: [Dir, CommonModule], declarations: [AppComponent], bootstrap: [AppComponent]})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {CommonModule} from '@angular/common';
import {importProvidersFrom} from '@angular/core';
bootstrapApplication(AppComponent, {
providers: [importProvidersFrom(CommonModule)]
}).catch(e => console.error(e));
`),
);
expect(stripWhitespace(tree.readContent('./app/app.module.ts'))).toContain(
stripWhitespace(`
@Component({template: '<span dir></span>', imports: [Dir]})
export class AppComponent {}
`),
);
});
it('should be able to migrate a bootstrapModule call where the root component does not belong to the bootstrapped component', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/root.module.ts',
`
import {NgModule, Component, InjectionToken} from '@angular/core';
const token = new InjectionToken<string>('token');
@Component({selector: 'root-comp', template: '', standalone: true})
export class Root {}
@NgModule({
imports: [Root],
exports: [Root],
providers: [{provide: token, useValue: 'hello'}]
})
export class RootModule {}
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {RootModule, Root} from './root.module';
@NgModule({
imports: [RootModule],
bootstrap: [Root]
})
export class AppModule {}
`,
);
await runMigration('standalone-bootstrap');
expect(tree.exists('./app/app.module.ts')).toBe(false);
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {RootModule, Root} from './app/root.module';
import {importProvidersFrom} from '@angular/core';
bootstrapApplication(Root, {
providers: [importProvidersFrom(RootModule)]
}).catch(e => console.error(e));
`),
);
});
it('should add Protractor support if any tests are detected', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
@Component({selector: 'app', template: 'hello'})
export class AppComponent {}
@NgModule({declarations: [AppComponent], bootstrap: [AppComponent]})
export class AppModule {}
`,
);
writeFile(
'./app/app.e2e.spec.ts',
`
import {browser, by, element} from 'protractor';
describe('app', () => {
beforeAll(async () => {
await browser.get(browser.params.testUrl);
});
it('should work', async () => {
const rootSelector = element(by.css('app'));
expect(await rootSelector.isPresent()).toBe(true);
});
});
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, provideProtractorTestingSupport, bootstrapApplication} from '@angular/platform-browser';
bootstrapApplication(AppComponent, {
providers: [provideProtractorTestingSupport()]
}).catch(e => console.error(e));
`),
);
});
it('should add Protractor support if any tests with deep imports are detected', async () => {
writeFile(
'main.ts',
`
import {AppModule} from './app/app.module';
import {platformBrowser} from '@angular/platform-browser';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
`,
);
writeFile(
'./app/app.module.ts',
`
import {NgModule, Component} from '@angular/core';
@Component({selector: 'app', template: 'hello'})
export class AppComponent {}
@NgModule({declarations: [AppComponent], bootstrap: [AppComponent]})
export class AppModule {}
`,
);
writeFile(
'./app/app.e2e.spec.ts',
`
import {browser, by, element} from 'protractor/some/deep-import';
describe('app', () => {
beforeAll(async () => {
await browser.get(browser.params.testUrl);
});
it('should work', async () => {
const rootSelector = element(by.css('app'));
expect(await rootSelector.isPresent()).toBe(true);
});
});
`,
);
await runMigration('standalone-bootstrap');
expect(stripWhitespace(tree.readContent('main.ts'))).toBe(
stripWhitespace(`
import {AppComponent} from './app/app.module';
import {platformBrowser, provideProtractorTestingSupport, bootstrapApplication} from '@angular/platform-browser';
bootstrapApplication(AppComponent, {
providers: [provideProtractorTestingSupport()]
}).catch(e => console.error(e));
`),
);
});
});
| {
"end_byte": 139310,
"start_byte": 132711,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_migration_spec.ts"
} |
angular/packages/core/schematics/test/output_migration_spec.ts_0_2128 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {getSystemPath, normalize, virtualFs} from '@angular-devkit/core';
import {TempScopedNodeJsSyncHost} from '@angular-devkit/core/node/testing';
import {HostTree} from '@angular-devkit/schematics';
import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing';
import {runfiles} from '@bazel/runfiles';
import shx from 'shelljs';
describe('output migration', () => {
let runner: SchematicTestRunner;
let host: TempScopedNodeJsSyncHost;
let tree: UnitTestTree;
let tmpDirPath: string;
let previousWorkingDir: string;
function writeFile(filePath: string, contents: string) {
host.sync.write(normalize(filePath), virtualFs.stringToFileBuffer(contents));
}
function runMigration(options?: {path?: string}) {
return runner.runSchematic('output-migration', options, tree);
}
beforeEach(() => {
runner = new SchematicTestRunner('test', runfiles.resolvePackageRelative('../collection.json'));
host = new TempScopedNodeJsSyncHost();
tree = new UnitTestTree(new HostTree(host));
writeFile('/tsconfig.json', '{}');
writeFile(
'/angular.json',
JSON.stringify({
version: 1,
projects: {t: {root: '', architect: {build: {options: {tsConfig: './tsconfig.json'}}}}},
}),
);
previousWorkingDir = shx.pwd();
tmpDirPath = getSystemPath(host.root);
shx.cd(tmpDirPath);
});
afterEach(() => {
shx.cd(previousWorkingDir);
shx.rm('-r', tmpDirPath);
});
it('should work', async () => {
writeFile(
'/index.ts',
`
import {Directive, Output, EventEmitter} from '@angular/core';
@Directive({})
export class SomeDirective {
@Output() out = new EventEmitter<string>();
}`,
);
await runMigration();
const content = tree.readContent('/index.ts').replace(/\s+/g, ' ');
expect(content).toContain('readonly out = output<string>();');
});
});
| {
"end_byte": 2128,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/output_migration_spec.ts"
} |
angular/packages/core/schematics/test/helpers.ts_0_504 | /**
* @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 {dedent as dedentFn} from '../utils/tsurge/testing/dedent';
/**
* Template string function that can be used to dedent the resulting
* string literal. The smallest common indentation will be omitted.
* Additionally, whitespace in empty lines is removed.
*/
export const dedent = dedentFn;
| {
"end_byte": 504,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/helpers.ts"
} |
angular/packages/core/schematics/test/standalone_routes_spec.ts_0_8297 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {getSystemPath, normalize, virtualFs} from '@angular-devkit/core';
import {TempScopedNodeJsSyncHost} from '@angular-devkit/core/node/testing';
import {HostTree} from '@angular-devkit/schematics';
import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing';
import {runfiles} from '@bazel/runfiles';
import shx from 'shelljs';
describe('route lazy loading migration', () => {
let runner: SchematicTestRunner;
let host: TempScopedNodeJsSyncHost;
let tree: UnitTestTree;
let tmpDirPath: string;
let previousWorkingDir: string;
function writeFile(filePath: string, contents: string) {
host.sync.write(normalize(filePath), virtualFs.stringToFileBuffer(contents));
}
function runMigration(mode: string, path = './') {
return runner.runSchematic('route-lazy-loading', {mode, path}, tree);
}
function stripWhitespace(content: string) {
return content.replace(/\s+/g, '');
}
beforeEach(() => {
runner = new SchematicTestRunner('test', runfiles.resolvePackageRelative('../collection.json'));
host = new TempScopedNodeJsSyncHost();
tree = new UnitTestTree(new HostTree(host));
writeFile(
'/tsconfig.json',
JSON.stringify({
compilerOptions: {
lib: ['es2015'],
strictNullChecks: true,
},
}),
);
writeFile(
'/angular.json',
JSON.stringify({
version: 1,
projects: {t: {root: '', architect: {build: {options: {tsConfig: './tsconfig.json'}}}}},
}),
);
writeFile(
'/node_modules/@angular/router/index.d.ts',
`
export declare interface Route {
path?: string;
component?: any;
loadComponent?: () => any | Promise<any> ;
children?: Route[];
}
export declare type Routes = Route[];
`,
);
previousWorkingDir = shx.pwd();
tmpDirPath = getSystemPath(host.root);
// Switch into the temporary directory path. This allows us to run
// the schematic against our custom unit test tree.
shx.cd(tmpDirPath);
});
afterEach(() => {
shx.cd(previousWorkingDir);
shx.rm('-r', tmpDirPath);
});
it('should throw an error if no files match the passed-in path', async () => {
let error: string | null = null;
writeFile('dir.ts', `const hello = 'world';`);
try {
await runMigration('route-lazy-loading', './foo');
} catch (e: any) {
error = e.message;
}
expect(error).toMatch(/Could not find any files to migrate under the path .*\/foo\./);
});
it('should throw an error if a path outside of the project is passed in', async () => {
let error: string | null = null;
writeFile('dir.ts', `const hello = 'world';`);
try {
await runMigration('route-lazy-loading', '../foo');
} catch (e: any) {
error = e.message;
}
expect(error).toBe('Cannot run route lazy loading migration outside of the current project.');
});
it('should throw an error if the passed in path is a file', async () => {
let error: string | null = null;
writeFile('dir.ts', '');
try {
await runMigration('route-lazy-loading', './dir.ts');
} catch (e: any) {
error = e.message;
}
expect(error).toMatch(
/Migration path .*\/dir\.ts has to be a directory\. Cannot run the route lazy loading migration/,
);
});
it('should throw an error if the component is in the same file as the routes declaration', async () => {
writeFile(
'app.module.ts',
`
import {NgModule, Component} from '@angular/core';
import {RouterModule} from '@angular/router';
@Component({template: 'hello', standalone: true})
export class TestComponent {}
@NgModule({
imports: [RouterModule.forRoot([{path: 'test', component: TestComponent}])],
})
export class AppModule {}
`,
);
let error: string | undefined;
try {
await runMigration('route-lazy-loading');
} catch (e: any) {
error = e.message;
}
expect(error).toMatch(/Could not find any files to migrate under the path .*\/\./);
});
it('should not migrate already lazy loaded standalone components', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';
@NgModule({
imports: [RouterModule.forRoot([{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}])],
})
export class AppModule {}
`,
);
writeFile(
'test.ts',
`
import {Component} from '@angular/core';
@Component({template: 'hello', standalone: true})
export class TestComponent {}
`,
);
let error: string | undefined;
try {
await runMigration('route-lazy-loading');
} catch (e: any) {
error = e.message;
}
expect(error).toMatch(/Could not find any files to migrate under the path .*\/\./);
});
it('should migrate standalone components in a different file from the routes declaration', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';
import {TestComponent} from './test';
@NgModule({
imports: [RouterModule.forRoot([{path: 'test', component: TestComponent}])],
})
export class AppModule {}
`,
);
writeFile(
'test.ts',
`
import {Component} from '@angular/core';
@Component({template: 'hello', standalone: true})
export class TestComponent {}
`,
);
await runMigration('route-lazy-loading');
expect(stripWhitespace(tree.readContent('app.module.ts'))).toContain(
stripWhitespace(`
import {NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';
@NgModule({
imports: [RouterModule.forRoot([{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}])],
})
export class AppModule {}
`),
);
});
it('should support provideRouter, RouterModule.forRoot, RouterModule.forChild', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {RouterModule, provideRouter} from '@angular/router';
import {TestComponent} from './test';
const routes = [{path: 'test', component: TestComponent}];
const routes2 = [{path: 'test', component: TestComponent}];
@NgModule({
imports: [
RouterModule.forRoot([{path: 'test', component: TestComponent}]),
RouterModule.forChild([{path: 'test', component: TestComponent}]),
],
providers: [
provideRouter(routes),
provideRouter(routes),
provideRouter(routes2)
],
})
export class AppModule {}
`,
);
writeFile(
'test.ts',
`
import {Component} from '@angular/core';
@Component({template: 'hello', standalone: true})
export class TestComponent {}
`,
);
await runMigration('route-lazy-loading');
expect(stripWhitespace(tree.readContent('app.module.ts'))).toContain(
stripWhitespace(`
import {NgModule} from '@angular/core';
import {RouterModule, provideRouter} from '@angular/router';
const routes = [{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}];
const routes2 = [{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}];
@NgModule({
imports: [
RouterModule.forRoot([{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}]),
RouterModule.forChild([{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}]),
],
providers: [
provideRouter(routes),
provideRouter(routes),
provideRouter(routes2)
],
})
export class AppModule {}
`),
);
}); | {
"end_byte": 8297,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_routes_spec.ts"
} |
angular/packages/core/schematics/test/standalone_routes_spec.ts_8301_15128 | it('should support provideRoutes', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {provideRoutes} from '@angular/router';
import {TestComponent} from './test';
const routes = [{path: 'test', component: TestComponent}];
@NgModule({
providers: [provideRoutes(routes)],
})
export class AppModule {}
`,
);
writeFile(
'test.ts',
`
import {Component} from '@angular/core';
@Component({template: 'hello', standalone: true})
export class TestComponent {}
`,
);
await runMigration('route-lazy-loading');
expect(stripWhitespace(tree.readContent('app.module.ts'))).toContain(
stripWhitespace(`
import {NgModule} from '@angular/core';
import {provideRoutes} from '@angular/router';
const routes = [{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}];
@NgModule({
providers: [provideRoutes(routes)],
})
export class AppModule {}
`),
);
});
it('should skip not standalone components', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {provideRoutes} from '@angular/router';
import {TestComponent} from './test';
import {NotStandaloneComponent} from './not-standalone';
const routes = [
{path: 'test', component: TestComponent},
{path: 'test1', component: NotStandaloneComponent},
];
@NgModule({
providers: [provideRoutes(routes)],
})
export class AppModule {}
`,
);
writeFile(
'test.ts',
`
import {Component} from '@angular/core';
@Component({template: 'hello', standalone: true})
export class TestComponent {}
`,
);
writeFile(
'not-standalone.ts',
`
import {Component, NgModule} from '@angular/core';
@Component({template: 'hello'})
export class NotStandaloneComponent {}
@NgModule({declarations: [NotStandaloneComponent], exports: [NotStandaloneComponent]})
export class NotStandaloneModule {}
`,
);
await runMigration('route-lazy-loading');
expect(stripWhitespace(tree.readContent('app.module.ts'))).toContain(
stripWhitespace(`
import {NgModule} from '@angular/core';
import {provideRoutes} from '@angular/router';
import {NotStandaloneComponent} from './not-standalone';
const routes = [
{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)},
{path: 'test1', component: NotStandaloneComponent},
];
@NgModule({
providers: [provideRoutes(routes)],
})
export class AppModule {}
`),
);
});
it('should support Router.resetConfig', async () => {
writeFile(
'app.module.ts',
`
import {Component} from '@angular/core';
import {Router} from '@angular/router';
import {TestComponent} from './test';
const routes = [{path: 'test', component: TestComponent}];
@Component({})
export class AppComponent {
constructor(private router: Router) {}
someMethod() {
this.router.resetConfig(routes);
}
}
`,
);
writeFile(
'test.ts',
`
import {Component} from '@angular/core';
@Component({template: 'hello', standalone: true})
export class TestComponent {}
`,
);
await runMigration('route-lazy-loading');
expect(stripWhitespace(tree.readContent('app.module.ts'))).toContain(
stripWhitespace(`
import {Component} from '@angular/core';
import {Router} from '@angular/router';
const routes = [{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}];
@Component({})
export class AppComponent {
constructor(private router: Router) {}
someMethod() {
this.router.resetConfig(routes);
}
}
`),
);
});
it('should support migrating default exported components', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {provideRouter} from '@angular/router';
import TestComponent from './test';
const routes = [{path: 'test', component: TestComponent}];
@NgModule({
providers: [provideRouter(routes)],
})
export class AppModule {}
`,
);
writeFile(
'test.ts',
`
import {Component} from '@angular/core';
@Component({template: 'hello', standalone: true})
export default class TestComponent {}
`,
);
await runMigration('route-lazy-loading');
expect(stripWhitespace(tree.readContent('app.module.ts'))).toContain(
stripWhitespace(`
import {NgModule} from '@angular/core';
import {provideRouter} from '@angular/router';
const routes = [{path: 'test', loadComponent: () => import('./test')}];
@NgModule({
providers: [provideRouter(routes)],
})
export class AppModule {}
`),
);
});
it('should migrate multiple components', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';
import {routes} from './routes';
@NgModule({
imports: [RouterModule.forRoot(routes],
})
export class AppModule {}
`,
);
writeFile(
'routes.ts',
`
import {Routes, Route} from '@angular/router';
import {TestComponent} from './test';
import {Test1Component} from './cmp1';
export const routes: Routes = [
{path: 'test', component: TestComponent},
{path: 'test1', component: Test1Component},
];
`,
);
writeFile(
'test.ts',
`
import {Component} from '@angular/core';
@Component({template: 'hello', standalone: true})
export class TestComponent {}
`,
);
writeFile(
'cmp1.ts',
`
import {Component} from '@angular/core';
@Component({template: 'hello', standalone: true})
export class Test1Component {}
`,
);
await runMigration('route-lazy-loading');
expect(stripWhitespace(tree.readContent('routes.ts'))).toContain(
stripWhitespace(`
import {Routes, Route} from '@angular/router';
export const routes: Routes = [
{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)},
{path: 'test1', loadComponent: () => import('./cmp1').then(m => m.Test1Component)},
];
`),
);
}); | {
"end_byte": 15128,
"start_byte": 8301,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_routes_spec.ts"
} |
angular/packages/core/schematics/test/standalone_routes_spec.ts_15132_22767 | it('should migrate nested children components', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';
import {routes} from './routes';
@NgModule({ imports: [RouterModule.forRoot(routes] })
export class AppModule {}
`,
);
writeFile(
'routes.ts',
`
import {Routes} from '@angular/router';
import {TestComponent} from './test';
import {Test1Component} from './cmp1';
export const routes: Routes = [
{path: 'test', component: TestComponent},
{path: 'test1', component: Test1Component},
{
path:'nested',
children: [
{
path: 'test',
component: TestComponent,
children: [
{path: 'test', component: TestComponent},
{path: 'test1', component: Test1Component},
{
path: 'nested1',
children: [
{path: 'test', component: TestComponent},
],
},
],
},
{path: 'test', component: TestComponent},
]
},
];
`,
);
writeFile(
'test.ts',
`
import {Component} from '@angular/core';
@Component({template: 'hello', standalone: true})
export class TestComponent {}
`,
);
writeFile(
'cmp1.ts',
`
import {Component} from '@angular/core';
@Component({template: 'hello', standalone: true})
export class Test1Component {}
`,
);
await runMigration('route-lazy-loading');
expect(stripWhitespace(tree.readContent('routes.ts'))).toContain(
stripWhitespace(`
import {Routes} from '@angular/router';
export const routes: Routes = [
{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)},
{path: 'test1', loadComponent: () => import('./cmp1').then(m => m.Test1Component)},
{
path:'nested',
children: [
{
path: 'test',
loadComponent: () => import('./test').then(m => m.TestComponent),
children: [
{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)},
{path: 'test1', loadComponent: () => import('./cmp1').then(m => m.Test1Component)},
{
path: 'nested1',
children: [
{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)},
],
},
],
},
{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)},
]
},
];
`),
);
});
it('should migrate routes if the routes file in is another file with type', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';
import {routes} from './routes';
@NgModule({
imports: [RouterModule.forRoot(routes],
})
export class AppModule {}
`,
);
writeFile(
'routes.ts',
`
import {Routes, Route} from '@angular/router';
import {TestComponent} from './test';
import {Test2 as Test2Alias} from './test2';
export const routes: Routes = [{path: 'test', component: TestComponent}];
export const routes1: Route[] = [{path: 'test', component: Test2Alias}];
`,
);
writeFile(
'test.ts',
`
import {Component} from '@angular/core';
@Component({template: 'hello', standalone: true})
export class TestComponent {}
`,
);
writeFile(
'test2.ts',
`
import {Component} from '@angular/core';
@Component({template: 'hello', standalone: true})
export class Test2 {}
`,
);
await runMigration('route-lazy-loading');
expect(stripWhitespace(tree.readContent('routes.ts'))).toContain(
stripWhitespace(`
import {Routes, Route} from '@angular/router';
export const routes: Routes = [{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}];
export const routes1: Route[] = [{path: 'test', loadComponent: () => import('./test2').then(m => m.Test2)}];
`),
);
});
it('should migrate routes array if the Routes type is aliased', async () => {
writeFile(
'routes.ts',
`
import {Routes as Routes1, Route as Route1} from '@angular/router';
import {TestComponent} from './test';
export const routes: Routes1 = [{path: 'test', component: TestComponent}];
export const routes1: Route1[] = [{path: 'test', component: TestComponent}];
`,
);
writeFile(
'test.ts',
`
import {Component} from '@angular/core';
@Component({template: 'hello', standalone: true})
export class TestComponent {}
`,
);
await runMigration('route-lazy-loading');
expect(stripWhitespace(tree.readContent('routes.ts'))).toContain(
stripWhitespace(`
import {Routes as Routes1, Route as Route1} from '@angular/router';
export const routes: Routes1 = [{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}];
export const routes1: Route1[] = [{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}];
`),
);
});
it('should not migrate routes if the routes array doesnt have type and is not referenced', async () => {
writeFile(
'routes.ts',
`
import {TestComponent} from './test';
export const routes = [{path: 'test', component: TestComponent}];
`,
);
writeFile(
'test.ts',
`
import {Component} from '@angular/core';
@Component({template: 'hello', standalone: true})
export class TestComponent {}
`,
);
let error: string | null = null;
try {
await runMigration('route-lazy-loading');
} catch (e: any) {
error = e.message;
}
expect(error).toMatch(/Could not find any files to migrate under the path/);
});
xit('should migrate routes if the routes file in is another file without type', async () => {
writeFile(
'app.module.ts',
`
import {NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';
import {routes} from './routes';
@NgModule({
imports: [RouterModule.forRoot(routes],
})
export class AppModule {}
`,
);
writeFile(
'routes.ts',
`
import {TestComponent} from './test';
export const routes = [{path: 'test', component: TestComponent}];
`,
);
writeFile(
'test.ts',
`
import {Component} from '@angular/core';
@Component({template: 'hello', standalone: true})
export class TestComponent {}
`,
);
await runMigration('route-lazy-loading');
expect(stripWhitespace(tree.readContent('routes.ts'))).toContain(
stripWhitespace(`
export const routes = [{path: 'test', loadComponent: () => import('./test').then(m => m.TestComponent)}];
`),
);
});
// TODO: support multiple imports of components
// ex import * as Components from './components';
// export const MenuRoutes: Routes = [
// {
// path: 'menu',
// component: Components.MenuListComponent
// },
// ];
}); | {
"end_byte": 22767,
"start_byte": 15132,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/standalone_routes_spec.ts"
} |
angular/packages/core/schematics/test/project_tsconfig_paths_spec.ts_0_3061 | /**
* @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 {HostTree} from '@angular-devkit/schematics';
import {UnitTestTree} from '@angular-devkit/schematics/testing';
import {getProjectTsConfigPaths} from '../utils/project_tsconfig_paths';
describe('project tsconfig paths', () => {
let testTree: UnitTestTree;
beforeEach(() => {
testTree = new UnitTestTree(new HostTree());
});
it('should detect build tsconfig path inside of angular.json file', async () => {
testTree.create('/my-custom-config.json', '');
testTree.create(
'/angular.json',
JSON.stringify({
version: 1,
projects: {
my_name: {root: '', architect: {build: {options: {tsConfig: './my-custom-config.json'}}}},
},
}),
);
expect((await getProjectTsConfigPaths(testTree)).buildPaths).toEqual(['my-custom-config.json']);
});
it('should be able to read workspace configuration which is using jsconc-parser features', async () => {
testTree.create('/my-build-config.json', '');
testTree.create(
'/angular.json',
`{
"version": 1,
// Comments are supported in the workspace configurations.
"projects": {
"with_tests": {
"root": "",
"targets": {
"build": {
"options": {
"tsConfig": "./my-build-config.json",
}
}
}
}
},
}`,
);
expect((await getProjectTsConfigPaths(testTree)).buildPaths).toEqual(['my-build-config.json']);
});
it('should detect test tsconfig path inside of angular.json file', async () => {
testTree.create('/my-test-config.json', '');
testTree.create(
'/angular.json',
JSON.stringify({
version: 1,
projects: {
my_name: {root: '', architect: {test: {options: {tsConfig: './my-test-config.json'}}}},
},
}),
);
expect((await getProjectTsConfigPaths(testTree)).testPaths).toEqual(['my-test-config.json']);
});
it('should detect test tsconfig path inside of .angular.json file', async () => {
testTree.create('/my-test-config.json', '');
testTree.create(
'/.angular.json',
JSON.stringify({
version: 1,
projects: {
with_tests: {root: '', architect: {test: {options: {tsConfig: './my-test-config.json'}}}},
},
}),
);
expect((await getProjectTsConfigPaths(testTree)).testPaths).toEqual(['my-test-config.json']);
});
it('should not return duplicate tsconfig files', async () => {
testTree.create('/tsconfig.json', '');
testTree.create(
'/.angular.json',
JSON.stringify({
version: 1,
projects: {app: {root: '', architect: {build: {options: {tsConfig: 'tsconfig.json'}}}}},
}),
);
expect((await getProjectTsConfigPaths(testTree)).buildPaths).toEqual(['tsconfig.json']);
});
});
| {
"end_byte": 3061,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/project_tsconfig_paths_spec.ts"
} |
angular/packages/core/schematics/test/pending_tasks_spec.ts_0_2988 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {getSystemPath, normalize, virtualFs} from '@angular-devkit/core';
import {TempScopedNodeJsSyncHost} from '@angular-devkit/core/node/testing';
import {HostTree} from '@angular-devkit/schematics';
import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing';
import {runfiles} from '@bazel/runfiles';
import shx from 'shelljs';
describe('experimental pending tasks migration', () => {
let runner: SchematicTestRunner;
let host: TempScopedNodeJsSyncHost;
let tree: UnitTestTree;
let tmpDirPath: string;
function writeFile(filePath: string, contents: string) {
host.sync.write(normalize(filePath), virtualFs.stringToFileBuffer(contents));
}
function runMigration() {
return runner.runSchematic('pending-tasks', {}, tree);
}
beforeEach(() => {
runner = new SchematicTestRunner('test', runfiles.resolvePackageRelative('../migrations.json'));
host = new TempScopedNodeJsSyncHost();
tree = new UnitTestTree(new HostTree(host));
writeFile(
'/tsconfig.json',
JSON.stringify({
compilerOptions: {
lib: ['es2015'],
strictNullChecks: true,
},
}),
);
writeFile(
'/angular.json',
JSON.stringify({
version: 1,
projects: {t: {root: '', architect: {build: {options: {tsConfig: './tsconfig.json'}}}}},
}),
);
tmpDirPath = getSystemPath(host.root);
// Switch into the temporary directory path. This allows us to run
// the schematic against our custom unit test tree.
shx.cd(tmpDirPath);
});
it('should update ExperimentalPendingTasks', async () => {
writeFile(
'/index.ts',
`
import {ExperimentalPendingTasks, Directive} from '@angular/core';
@Directive({
selector: '[someDirective]'
})
export class SomeDirective {
x = inject(ExperimentalPendingTasks);
}`,
);
await runMigration();
const content = tree.readContent('/index.ts').replace(/\s+/g, ' ');
expect(content).toContain("import {PendingTasks, Directive} from '@angular/core';");
expect(content).toContain('x = inject(PendingTasks);');
});
it('should update import alias', async () => {
writeFile(
'/index.ts',
`
import {ExperimentalPendingTasks as Y, Directive} from '@angular/core';
@Directive({
selector: '[someDirective]'
})
export class SomeDirective {
x = inject(Y);
}`,
);
await runMigration();
const content = tree.readContent('/index.ts').replace(/\s+/g, ' ');
expect(content).toContain("import {PendingTasks as Y, Directive} from '@angular/core';");
expect(content).toContain('x = inject(Y);');
});
});
| {
"end_byte": 2988,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/pending_tasks_spec.ts"
} |
angular/packages/core/schematics/test/provide_initializer_spec.ts_0_9078 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {getSystemPath, normalize, virtualFs} from '@angular-devkit/core';
import {TempScopedNodeJsSyncHost} from '@angular-devkit/core/node/testing';
import {HostTree} from '@angular-devkit/schematics';
import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing';
import {runfiles} from '@bazel/runfiles';
import shx from 'shelljs';
describe('Provide initializer migration', () => {
it('should transform APP_INITIALIZER + useValue into provideAppInitializer', async () => {
const content = await migrateCode(`
import { APP_INITIALIZER } from '@angular/core';
const providers = [{
provide: APP_INITIALIZER,
useValue: () => { console.log('hello'); },
multi: true,
}];
`);
expect(content).toContain(`import { provideAppInitializer } from '@angular/core';`);
expect(content).toContain(
`const providers = [provideAppInitializer(() => { console.log('hello'); })]`,
);
expect(content).not.toContain('APP_INITIALIZER');
});
it('should not remove other imported symbols by mistake', async () => {
const content = await migrateCode(`
import { APP_INITIALIZER, input } from '@angular/core';
const providers = [{
provide: APP_INITIALIZER,
useValue: () => { console.log('hello'); },
multi: true,
}];
`);
expect(content).toContain(`import { input, provideAppInitializer } from '@angular/core';`);
});
it('should reuse provideAppInitializer if already imported', async () => {
const content = await migrateCode(`
import { APP_INITIALIZER, input, provideAppInitializer } from '@angular/core';
const providers = [{
provide: APP_INITIALIZER,
useValue: () => { console.log('hello'); },
multi: true,
}];
`);
expect(content).toContain(`import { input, provideAppInitializer } from '@angular/core';`);
});
it('should transform APP_INITIALIZER + useValue async function into provideAppInitializer', async () => {
const content = await migrateCode(`
import { APP_INITIALIZER } from '@angular/core';
const providers = [{
provide: APP_INITIALIZER,
useValue: async () => { await Promise.resolve(); return 42; },
multi: true,
}];
`);
expect(content).toContain(
`const providers = [provideAppInitializer(async () => { await Promise.resolve(); return 42; })]`,
);
});
it('should transform APP_INITIALIZER + useValue symbol into provideAppInitializer', async () => {
const content = await migrateCode(`
import { APP_INITIALIZER } from '@angular/core';
function initializerFn() {}
const providers = [{
provide: APP_INITIALIZER,
useValue: initializerFn,
multi: true,
}];
`);
expect(content).toContain(`const providers = [provideAppInitializer(initializerFn)];`);
});
it('should transform APP_INITIALIZER + useFactory into provideAppInitializer', async () => {
const content = await migrateCode(`
import { APP_INITIALIZER } from '@angular/core';
const providers = [{
provide: APP_INITIALIZER,
useFactory: () => {
const service = inject(Service);
return () => service.init();
},
multi: true,
}];
`);
expect(content).toContain(`const providers = [provideAppInitializer(() => { return (() => {
const service = inject(Service);
return () => service.init();
})(); })];`);
});
it('should transform APP_INITIALIZER + useExisting into provideAppInitializer', async () => {
const content = await migrateCode(`
import { APP_INITIALIZER } from '@angular/core';
const providers = [{
provide: APP_INITIALIZER,
useExisting: MY_INITIALIZER,
multi: true,
}];
`);
expect(content).toContain(`import { inject, provideAppInitializer } from '@angular/core';`);
expect(content).toContain(
`const providers = [provideAppInitializer(() => inject(MY_INITIALIZER)())]`,
);
});
it('should transform APP_INITIALIZER + deps into provideAppInitializer', async () => {
const content = await migrateCode(`
import { APP_INITIALIZER } from '@angular/core';
const providers = [{
provide: APP_INITIALIZER,
useFactory: (a: ServiceA, b: ServiceB) => {
return () => a.init();
},
deps: [ServiceA, ServiceB],
multi: true,
}];
`);
expect(content).toContain(`import { inject, provideAppInitializer } from '@angular/core';`);
expect(content).toContain(
`const providers = [provideAppInitializer(() => { return ((a: ServiceA, b: ServiceB) => {
return () => a.init();
})(inject(ServiceA), inject(ServiceB)); })];`,
);
});
it('should not transform APP_INITIALIZER if multi is not set to true', async () => {
const content = await migrateCode(`
import { APP_INITIALIZER } from '@angular/core';
const providers = [{
provide: APP_INITIALIZER,
useValue: [initializer],
}];
`);
expect(content).toBe(`
import { APP_INITIALIZER } from '@angular/core';
const providers = [{
provide: APP_INITIALIZER,
useValue: [initializer],
}];
`);
});
it('should not transform APP_INITIALIZER if it is not imported from @angular/core', async () => {
const content = await migrateCode(`
import { APP_INITIALIZER } from '@not-angular/core';
const providers = [{
provide: APP_INITIALIZER,
useValue: () => { console.log('hello'); },
multi: true,
}];
`);
expect(content).toBe(`
import { APP_INITIALIZER } from '@not-angular/core';
const providers = [{
provide: APP_INITIALIZER,
useValue: () => { console.log('hello'); },
multi: true,
}];
`);
});
it('should transform ENVIRONMENT_INITIALIZER + useValue into provideEnvironmentInitializer', async () => {
const content = await migrateCode(`
import { ENVIRONMENT_INITIALIZER } from '@angular/core';
const providers = [{
provide: ENVIRONMENT_INITIALIZER,
useValue: () => { console.log('hello'); },
multi: true,
}];
`);
expect(content).toContain(`import { provideEnvironmentInitializer } from '@angular/core';`);
expect(content).toContain(
`const providers = [provideEnvironmentInitializer(() => { console.log('hello'); })]`,
);
expect(content).not.toContain('ENVIRONMENT_INITIALIZER');
});
it('should transform PLATFORM_INITIALIZER + useValue into providePlatformInitializer', async () => {
const content = await migrateCode(`
import { PLATFORM_INITIALIZER } from '@angular/core';
const providers = [{
provide: PLATFORM_INITIALIZER,
useValue: () => { console.log('hello'); },
multi: true,
}];
`);
expect(content).toContain(`import { providePlatformInitializer } from '@angular/core';`);
expect(content).toContain(
`const providers = [providePlatformInitializer(() => { console.log('hello'); })]`,
);
expect(content).not.toContain('PLATFORM_INITIALIZER');
});
});
async function migrateCode(content: string) {
const {readFile, writeFile, runMigration} = setUpMigration();
writeFile('/index.ts', content);
await runMigration();
return readFile('/index.ts');
}
function setUpMigration() {
const host = new TempScopedNodeJsSyncHost();
const tree = new UnitTestTree(new HostTree(host));
const runner = new SchematicTestRunner(
'test',
runfiles.resolvePackageRelative('../migrations.json'),
);
function writeFile(filePath: string, content: string) {
host.sync.write(normalize(filePath), virtualFs.stringToFileBuffer(content));
}
writeFile(
'/tsconfig.json',
JSON.stringify({
compilerOptions: {
lib: ['es2015'],
strictNullChecks: true,
},
}),
);
writeFile(
'/angular.json',
JSON.stringify({
version: 1,
projects: {t: {root: '', architect: {build: {options: {tsConfig: './tsconfig.json'}}}}},
}),
);
const previousWorkingDir = shx.pwd();
const tmpDirPath = getSystemPath(host.root);
// Switch into the temporary directory path. This allows us to run
// the schematic against our custom unit test tree.
shx.cd(tmpDirPath);
// Get back to current directory after test.
cleanupFns.push(() => shx.cd(previousWorkingDir));
return {
readFile(filePath: string) {
return tree.readContent(filePath);
},
writeFile,
async runMigration() {
return await runner.runSchematic('provide-initializer', {}, tree);
},
};
}
let cleanupFns: Array<() => void> = [];
afterEach(() => {
for (const cleanupFn of cleanupFns) {
cleanupFn();
}
cleanupFns = [];
});
| {
"end_byte": 9078,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/provide_initializer_spec.ts"
} |
angular/packages/core/schematics/test/control_flow_migration_spec.ts_0_4817 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {getSystemPath, logging, normalize, virtualFs} from '@angular-devkit/core';
import {TempScopedNodeJsSyncHost} from '@angular-devkit/core/node/testing';
import {HostTree} from '@angular-devkit/schematics';
import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing';
import {runfiles} from '@bazel/runfiles';
import shx from 'shelljs';
describe('control flow migration', () => {
let runner: SchematicTestRunner;
let host: TempScopedNodeJsSyncHost;
let tree: UnitTestTree;
let tmpDirPath: string;
let previousWorkingDir: string;
let errorOutput: string[] = [];
let warnOutput: string[] = [];
function writeFile(filePath: string, contents: string) {
host.sync.write(normalize(filePath), virtualFs.stringToFileBuffer(contents));
}
function runMigration(path: string | undefined = undefined, format: boolean = true) {
return runner.runSchematic('control-flow-migration', {path, format}, tree);
}
beforeEach(() => {
runner = new SchematicTestRunner('test', runfiles.resolvePackageRelative('../collection.json'));
host = new TempScopedNodeJsSyncHost();
tree = new UnitTestTree(new HostTree(host));
errorOutput = [];
warnOutput = [];
runner.logger.subscribe((e: logging.LogEntry) => {
if (e.level === 'error') {
errorOutput.push(e.message);
} else if (e.level === 'warn') {
warnOutput.push(e.message);
}
});
writeFile('/tsconfig.json', '{}');
writeFile(
'/angular.json',
JSON.stringify({
version: 1,
projects: {t: {root: '', architect: {build: {options: {tsConfig: './tsconfig.json'}}}}},
}),
);
previousWorkingDir = shx.pwd();
tmpDirPath = getSystemPath(host.root);
// Switch into the temporary directory path. This allows us to run
// the schematic against our custom unit test tree.
shx.cd(tmpDirPath);
});
afterEach(() => {
shx.cd(previousWorkingDir);
shx.rm('-r', tmpDirPath);
});
describe('path', () => {
it('should throw an error if no files match the passed-in path', async () => {
let error: string | null = null;
writeFile(
'dir.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[dir]'})
export class MyDir {}
`,
);
try {
await runMigration('./foo');
} catch (e: any) {
error = e.message;
}
expect(error).toMatch(
/Could not find any files to migrate under the path .*\/foo\. Cannot run the control flow migration/,
);
});
it('should throw an error if a path outside of the project is passed in', async () => {
let error: string | null = null;
writeFile(
'dir.ts',
`
import {Directive} from '@angular/core';
@Directive({selector: '[dir]'})
export class MyDir {}
`,
);
try {
await runMigration('../foo');
} catch (e: any) {
error = e.message;
}
expect(error).toBe('Cannot run control flow migration outside of the current project.');
});
it('should only migrate the paths that were passed in', async () => {
writeFile(
'comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
imports: [NgIf, NgFor,NgSwitch,NgSwitchCase ,NgSwitchDefault],
template: \`<div><span *ngIf="toggle">This should be hidden</span></div>\`
})
class Comp {
toggle = false;
}
`,
);
writeFile(
'skip.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
imports: [NgIf],
template: \`<div *ngIf="show">Show me</div>\`
})
class Comp {
show = false;
}
`,
);
await runMigration('./comp.ts');
const migratedContent = tree.readContent('/comp.ts');
const skippedContent = tree.readContent('/skip.ts');
expect(migratedContent).toContain(
'template: `<div>@if (toggle) {<span>This should be hidden</span>}</div>`',
);
expect(migratedContent).toContain('imports: []');
expect(migratedContent).not.toContain(`import {NgIf} from '@angular/common';`);
expect(skippedContent).toContain('template: `<div *ngIf="show">Show me</div>`');
expect(skippedContent).toContain('imports: [NgIf]');
expect(skippedContent).toContain(`import {NgIf} from '@angular/common';`);
});
}); | {
"end_byte": 4817,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts"
} |
angular/packages/core/schematics/test/control_flow_migration_spec.ts_4821_12756 | describe('ngIf', () => {
it('should migrate an inline template', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
imports: [NgIf],
template: \`<div><span *ngIf="toggle">This should be hidden</span></div>\`
})
class Comp {
toggle = false;
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<div>@if (toggle) {<span>This should be hidden</span>}</div>`',
);
});
it('should migrate an empty case', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {ngSwitch, ngSwitchCase} from '@angular/common';
@Component({
template: \`<div [ngSwitch]="testOpts">` +
`<p *ngSwitchCase="">Option 1</p>` +
`<p *ngSwitchCase="2">Option 2</p>` +
`</div>\`
})
class Comp {
testOpts = "1";
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
`template: \`<div>@switch (testOpts) { @case ('') { <p>Option 1</p> } @case (2) { <p>Option 2</p> }}</div>`,
);
});
it('should migrate multiple inline templates in the same file', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
imports: [NgIf],
template: \`<div><span *ngIf="toggle">This should be hidden</span></div>\`
})
class Comp {
toggle = false;
}
@Component({
template: \`<article *ngIf="show === 5">An Article</article>\`
})
class OtherComp {
show = 5
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<div>@if (toggle) {<span>This should be hidden</span>}</div>`',
);
expect(content).toContain('template: `@if (show === 5) {<article>An Article</article>}`');
});
it('should migrate an external template', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[`<div>`, `<span *ngIf="show">Content here</span>`, `</div>`].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[`<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` }`, `</div>`].join('\n'),
);
});
it('should migrate a template referenced by multiple components', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {}
`,
);
writeFile(
'/other-comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class OtherComp {}
`,
);
writeFile(
'/comp.html',
[`<div>`, `<span *ngIf="show">Content here</span>`, `</div>`].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[`<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` }`, `</div>`].join('\n'),
);
});
it('should migrate an if case with no star', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[`<div>`, `<span ngIf="show">Content here</span>`, `</div>`].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[`<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` }`, `</div>`].join('\n'),
);
});
it('should migrate an if case as a binding', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[`<div>`, `<span [ngIf]="show">Content here</span>`, `</div>`].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[`<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` }`, `</div>`].join('\n'),
);
});
it('should migrate an if case as a binding with let variables', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<ng-template [ngIf]="data$ | async" let-data="ngIf">`,
` {{ data }}`,
`</ng-template>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe([`@if (data$ | async; as data) {`, ` {{ data }}`, `}`].join('\n'));
});
it('should migrate an if case as a binding with let variable with no value', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<ng-template [ngIf]="viewModel$ | async" let-vm>`,
` {{vm | json}}`,
`</ng-template>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[`@if (viewModel$ | async; as vm) {`, ` {{vm | json}}`, `}`].join('\n'),
);
});
it('should migrate an if else case as bindings', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf,NgIfElse} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<ng-template [ngIf]="show" [ngIfElse]="tmplName"><span>Content here</span></ng-template>`,
`</div>`,
`<ng-template #tmplName><p>Stuff</p></ng-template>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (show) {`,
` <span>Content here</span>`,
` } @else {`,
` <p>Stuff</p>`,
` }`,
`</div>\n`,
].join('\n'),
);
}); | {
"end_byte": 12756,
"start_byte": 4821,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts"
} |
angular/packages/core/schematics/test/control_flow_migration_spec.ts_12762_19998 | it('should migrate an if then else case as bindings', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf,NgIfElse} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<ng-template [ngIf]="show" [ngIfElse]="elseTmpl" [ngIfThenElse]="thenTmpl">Ignore Me</ng-template>`,
`</div>`,
`<ng-template #elseTmpl><p>Stuff</p></ng-template>`,
`<ng-template #thenTmpl><span>Content here</span></ng-template>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (show) {`,
` <span>Content here</span>`,
` } @else {`,
` <p>Stuff</p>`,
` }`,
`</div>\n`,
].join('\n'),
);
});
it('should migrate an if else case with condition that has `then` in the string', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf,NgIfElse} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[`<div *ngIf="!(isAuthenticated$ | async) && !reauthRequired">`, ` Hello!`, `</div>`].join(
'\n',
),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`@if (!(isAuthenticated$ | async) && !reauthRequired) {`,
` <div>`,
` Hello!`,
` </div>`,
`}`,
].join('\n'),
);
});
it('should migrate an if case on a container', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<ng-container *ngIf="show"><span>Content here</span></ng-container>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[`<div>`, ` @if (show) {`, ` <span>Content here</span>`, ` }`, `</div>`].join('\n'),
);
});
it('should migrate an if case on an empty container', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<ng-container`,
` *ngIf="true; then template"`,
`></ng-container>`,
`<ng-template #template>`,
` Hello!`,
`</ng-template> `,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe([`@if (true) {`, ` Hello!`, `}\n`].join('\n'));
});
it('should migrate an if case with an ng-template with i18n', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<ng-template *ngIf="show" i18n="@@something"><span>Content here</span></ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (show) {`,
` <ng-container i18n="@@something"><span>Content here</span></ng-container>`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should migrate an if case with an ng-template with empty i18n', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<ng-template *ngIf="show" i18n><span>Content here</span></ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (show) {`,
` <ng-container i18n><span>Content here</span></ng-container>`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should migrate an if case with an ng-container with i18n', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<ng-container *ngIf="show" i18n="@@something"><span>Content here</span></ng-container>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (show) {`,
` <ng-container i18n="@@something"><span>Content here</span></ng-container>`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should migrate a bound if case on an ng-template with i18n', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<ng-template`,
` [ngIf]="data$ | async"`,
` let-data="ngIf"`,
` i18n="@@i18n-label">`,
` {{ data }}`,
`</ng-template>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`@if (data$ | async; as data) {`,
` <ng-container i18n="@@i18n-label">`,
` {{ data }}`,
`</ng-container>`,
`}`,
].join('\n'),
);
}); | {
"end_byte": 19998,
"start_byte": 12762,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts"
} |
angular/packages/core/schematics/test/control_flow_migration_spec.ts_20004_27544 | it('should migrate an if case with an ng-container with empty i18n', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<ng-container *ngIf="show" i18n><span>Content here</span></ng-container>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (show) {`,
` <ng-container i18n><span>Content here</span></ng-container>`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should migrate a bound NgIfElse case with ng-templates and remove all unnecessary attributes', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<ng-template`,
` [ngIf]="fooTemplate"`,
` [ngIfElse]="barTemplate"`,
` [ngTemplateOutlet]="fooTemplate"`,
`></ng-template>`,
`<ng-template #fooTemplate>Foo</ng-template>`,
`<ng-template #barTemplate>Bar</ng-template>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`@if (fooTemplate) {`,
` <ng-template`,
` [ngTemplateOutlet]="fooTemplate"`,
` ></ng-template>`,
`} @else {`,
` Bar`,
`}`,
`<ng-template #fooTemplate>Foo</ng-template>\n`,
].join('\n'),
);
});
it('should migrate a bound NgIfThenElse case with ng-templates with i18n', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<ng-template [ngIf]="show" [ngIfThenElse]="thenTmpl" [ngIfElse]="elseTmpl">ignored</ng-template>`,
`</div>`,
`<ng-template #thenTmpl i18n="@@something"><span>Content here</span></ng-template>`,
`<ng-template #elseTmpl i18n="@@somethingElse"><p>other</p></ng-template>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (show) {`,
` <ng-container i18n="@@something"><span>Content here</span></ng-container>`,
` } @else {`,
` <ng-container i18n="@@somethingElse"><p>other</p></ng-container>`,
` }`,
`</div>\n`,
].join('\n'),
);
});
it('should migrate a bound NgIfElse case with ng-templates with i18n', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<ng-template [ngIf]="show" [ngIfElse]="elseTmpl" i18n="@@something"><span>Content here</span></ng-template>`,
`</div>`,
`<ng-template #elseTmpl i18n="@@somethingElse"><p>other</p></ng-template>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (show) {`,
` <ng-container i18n="@@something"><span>Content here</span></ng-container>`,
` } @else {`,
` <ng-container i18n="@@somethingElse"><p>other</p></ng-container>`,
` }`,
`</div>\n`,
].join('\n'),
);
});
it('should migrate an NgIfElse case with ng-templates with multiple i18n attributes', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<ng-template *ngIf="false; else barTempl" i18n="@@foo">`,
` Foo`,
`</ng-template>`,
`<ng-template i18n="@@bar" #barTempl> Bar </ng-template>`,
`<a *ngIf="true" i18n="@@bam">Bam</a>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`@if (false) {`,
` <ng-container i18n="@@foo">`,
` Foo`,
`</ng-container>`,
`} @else {`,
` <ng-container i18n="@@bar"> Bar </ng-container>`,
`}`,
`@if (true) {`,
` <a i18n="@@bam">Bam</a>`,
`}`,
].join('\n'),
);
});
it('should migrate an if else case', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<span *ngIf="show; else elseBlock">Content here</span>`,
`<ng-template #elseBlock>Else Content</ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (show) {`,
` <span>Content here</span>`,
` } @else {`,
` Else Content`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should migrate an if else case with no semicolon before else', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<span *ngIf="show else elseBlock">Content here</span>`,
`<ng-template #elseBlock>Else Content</ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (show) {`,
` <span>Content here</span>`,
` } @else {`,
` Else Content`,
` }`,
`</div>`,
].join('\n'),
);
}); | {
"end_byte": 27544,
"start_byte": 20004,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts"
} |
angular/packages/core/schematics/test/control_flow_migration_spec.ts_27550_34580 | it('should migrate an if then else case with no semicolons', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<span *ngIf="show then thenTmpl else elseTmpl"></span>`,
`<ng-template #thenTmpl><span>Content here</span></ng-template>`,
`<ng-template #elseTmpl>Else Content</ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (show) {`,
` <span>Content here</span>`,
` } @else {`,
` Else Content`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should migrate an if else case with a colon after else', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<span *ngIf="show; else: elseTmpl">Content here</span>`,
`<ng-template #elseTmpl>Else Content</ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`<div>`,
` @if (show) {`,
` <span>Content here</span>`,
` } @else {`,
` Else Content`,
` }`,
`</div>`,
].join('\n');
expect(actual).toBe(expected);
});
it('should migrate an if else case with no space after ;', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<span *ngIf="show;else elseBlock">Content here</span>`,
`<ng-template #elseBlock>Else Content</ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (show) {`,
` <span>Content here</span>`,
` } @else {`,
` Else Content`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should migrate an if then else case with no spaces before ;', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<span *ngIf="show;then thenBlock;else elseBlock">Ignored</span>`,
`<ng-template #thenBlock><div>THEN Stuff</div></ng-template>`,
`<ng-template #elseBlock>Else Content</ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (show) {`,
` <div>THEN Stuff</div>`,
` } @else {`,
` Else Content`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should migrate an if else case when the template is above the block', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<ng-template #elseBlock>Else Content</ng-template>`,
`<span *ngIf="show; else elseBlock">Content here</span>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (show) {`,
` <span>Content here</span>`,
` } @else {`,
` Else Content`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should migrate an if then else case', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<span *ngIf="show; then thenBlock; else elseBlock">Ignored</span>`,
`<ng-template #thenBlock><div>THEN Stuff</div></ng-template>`,
`<ng-template #elseBlock>Else Content</ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (show) {`,
` <div>THEN Stuff</div>`,
` } @else {`,
` Else Content`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should migrate an if then else case with templates in odd places', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<ng-template #elseBlock>Else Content</ng-template>`,
`<span *ngIf="show; then thenBlock; else elseBlock">Ignored</span>`,
`<ng-template #thenBlock><div>THEN Stuff</div></ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (show) {`,
` <div>THEN Stuff</div>`,
` } @else {`,
` Else Content`,
` }`,
`</div>`,
].join('\n'),
);
}); | {
"end_byte": 34580,
"start_byte": 27550,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts"
} |
angular/packages/core/schematics/test/control_flow_migration_spec.ts_34586_41918 | it('should migrate a complex if then else case on ng-containers', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<ng-container>`,
` <ng-container`,
` *ngIf="loading; then loadingTmpl; else showTmpl"`,
` >`,
` </ng-container>`,
`<ng-template #showTmpl>`,
` <ng-container`,
` *ngIf="selected; else emptyTmpl"`,
` >`,
` <div></div>`,
` </ng-container>`,
`</ng-template>`,
`<ng-template #emptyTmpl>`,
` Empty`,
`</ng-template>`,
`</ng-container>`,
`<ng-template #loadingTmpl>`,
` <p>Loading</p>`,
`</ng-template>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<ng-container>`,
` @if (loading) {`,
` <p>Loading</p>`,
` } @else {`,
` @if (selected) {`,
` <div></div>`,
` } @else {`,
` Empty`,
` }`,
` }`,
`</ng-container>\n`,
].join('\n'),
);
});
it('should migrate but not remove ng-templates when referenced elsewhere', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<span *ngIf="show; then thenBlock; else elseBlock">Ignored</span>`,
`<ng-template #thenBlock><div>THEN Stuff</div></ng-template>`,
`<ng-template #elseBlock>Else Content</ng-template>`,
`</div>`,
`<ng-container *ngTemplateOutlet="elseBlock"></ng-container>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (show) {`,
` <div>THEN Stuff</div>`,
` } @else {`,
` Else Content`,
` }`,
` <ng-template #elseBlock>Else Content</ng-template>`,
`</div>`,
`<ng-container *ngTemplateOutlet="elseBlock"></ng-container>`,
].join('\n'),
);
});
it('should not remove ng-templates used by other directives', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<ng-template #blockUsedElsewhere><div>Block</div></ng-template>`,
`<ng-container *ngTemplateOutlet="blockUsedElsewhere"></ng-container>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<ng-template #blockUsedElsewhere><div>Block</div></ng-template>`,
`<ng-container *ngTemplateOutlet="blockUsedElsewhere"></ng-container>`,
].join('\n'),
);
});
it('should migrate if with alias', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
user$ = of({ name: 'Jane' }})
}
`,
);
writeFile('/comp.html', `<div *ngIf="user$ | async as user">{{ user.name }}</div>`);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(`@if (user$ | async; as user) {<div>{{ user.name }}</div>}`);
});
it('should migrate if/else with alias', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
user$ = of({ name: 'Jane' }})
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<div *ngIf="user$ | async as user; else noUserBlock">{{ user.name }}</div>`,
`<ng-template #noUserBlock>No user</ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (user$ | async; as user) {`,
` <div>{{ user.name }}</div>`,
` } @else {`,
` No user`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should migrate if/else with semicolon at end', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
user$ = of({ name: 'Jane' }})
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<div *ngIf="user$ | async as user; else noUserBlock;">{{ user.name }}</div>`,
`<ng-template #noUserBlock>No user</ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (user$ | async; as user) {`,
` <div>{{ user.name }}</div>`,
` } @else {`,
` No user`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should migrate if/else with let variable', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
user$ = of({ name: 'Jane' }})
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<div *ngIf="user of users; else noUserBlock; let tooltipContent;">{{ user.name }}</div>`,
`<ng-template #noUserBlock>No user</ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (user of users; as tooltipContent) {`,
` <div>{{ user.name }}</div>`,
` } @else {`,
` No user`,
` }`,
`</div>`,
].join('\n'),
);
}); | {
"end_byte": 41918,
"start_byte": 34586,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts"
} |
angular/packages/core/schematics/test/control_flow_migration_spec.ts_41924_45386 | it('should migrate if/else with let variable in wrong place with no semicolons', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
user$ = of({ name: 'Jane' }})
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<div *ngIf="user of users; let tooltipContent else noUserBlock">{{ user.name }}</div>`,
`<ng-template #noUserBlock>No user</ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (user of users; as tooltipContent) {`,
` <div>{{ user.name }}</div>`,
` } @else {`,
` No user`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should migrate if/then/else with alias', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
user$ = of({ name: 'Jane' }})
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<ng-container *ngIf="user$ | async as user; then userBlock; else noUserBlock">Ignored</ng-container>`,
`<ng-template #userBlock>User</ng-template>`,
`<ng-template #noUserBlock>No user</ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (user$ | async; as user) {`,
` User`,
` } @else {`,
` No user`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should migrate a nested class', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
function foo() {
@Component({
imports: [NgIf],
template: \`<div><span *ngIf="toggle">This should be hidden</span></div>\`
})
class Comp {
toggle = false;
}
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<div>@if (toggle) {<span>This should be hidden</span>}</div>`',
);
});
it('should migrate a nested class', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
function foo() {
@Component({
imports: [NgIf],
template: \`<div><span *ngIf="toggle">This should be hidden</span></div>\`
})
class Comp {
toggle = false;
}
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<div>@if (toggle) {<span>This should be hidden</span>}</div>`',
);
});
}); | {
"end_byte": 45386,
"start_byte": 41924,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts"
} |
angular/packages/core/schematics/test/control_flow_migration_spec.ts_45390_52078 | describe('ngFor', () => {
it('should migrate an inline template', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let item of items">{{item.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (item of items; track item) {<li>{{item.text}}</li>}</ul>`',
);
});
it('should migrate multiple inline templates in the same file', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
const items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let item of items">{{item.text}}</li></ul>\`
})
class Comp {
items: Item[] = s;
}
@Component({
imports: [NgFor],
template: \`<article><div *ngFor="let item of items">{{item.text}}</div></article>\`
})
class OtherComp {
items: Item[] = s;
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (item of items; track item) {<li>{{item.text}}</li>}</ul>`',
);
expect(content).toContain(
'template: `<article>@for (item of items; track item) {<div>{{item.text}}</div>}</article>`',
);
});
it('should migrate an external template', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
interface Item {
id: number;
text: string;
}
const items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
@Component({
templateUrl: './comp.html'
})
class Comp {
items: Item[] = s;
}
`,
);
writeFile(
'/comp.html',
[`<ul>`, `<li *ngFor="let item of items">{{item.text}}</li>`, `</ul>`].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<ul>`,
` @for (item of items; track item) {`,
` <li>{{item.text}}</li>`,
` }`,
`</ul>`,
].join('\n'),
);
});
it('should migrate a template referenced by multiple components', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
interface Item {
id: number;
text: string;
}
const items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
@Component({
templateUrl: './comp.html'
})
class Comp {
items: Item[] = s;
}
`,
);
writeFile(
'/other-comp.ts',
`
import {Component} from '@angular/core';
interface Item {
id: number;
text: string;
}
const items: Item[] = [{id: 3, text: 'things'},{id: 4, text: 'yup'}];
@Component({
templateUrl: './comp.html'
})
class OtherComp {
items: Item[] = s;
}
`,
);
writeFile(
'/comp.html',
[`<ul>`, `<li *ngFor="let item of items">{{item.text}}</li>`, `</ul>`].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<ul>`,
` @for (item of items; track item) {`,
` <li>{{item.text}}</li>`,
` }`,
`</ul>`,
].join('\n'),
);
});
it('should migrate with a trackBy function', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of items; trackBy: trackMeFn;">{{itm.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of items; track trackMeFn($index, itm)) {<li>{{itm.text}}</li>}</ul>`',
);
});
it('should migrate with an index alias', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of items; let index = index">{{itm.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of items; track itm; let index = $index) {<li>{{itm.text}}</li>}</ul>`',
);
});
it('should migrate with a comma-separated index alias', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of items, let index = index">{{itm.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of items; track itm; let index = $index) {<li>{{itm.text}}</li>}</ul>`',
);
}); | {
"end_byte": 52078,
"start_byte": 45390,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts"
} |
angular/packages/core/schematics/test/control_flow_migration_spec.ts_52084_59180 | it('should migrate with an old style alias', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<tbody>`,
` <tr *ngFor="let row of field(); let y = index; trackBy: trackByIndex">`,
` <td`,
` *ngFor="let cell of row; let x = index; trackBy: trackByIndex"`,
` ></td>`,
` </tr>`,
`</tbody>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`<tbody>`,
` @for (row of field(); track trackByIndex(y, row); let y = $index) {`,
` <tr>`,
` @for (cell of row; track trackByIndex(x, cell); let x = $index) {`,
` <td`,
` ></td>`,
` }`,
` </tr>`,
` }`,
`</tbody>`,
].join('\n');
expect(actual).toBe(expected);
});
it('should migrate an index alias after an expression containing commas', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of foo({a: 1, b: 2}, [1, 2]), let index = index">{{itm.text}}</li></ul>\`
})
class Comp {}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of foo({a: 1, b: 2}, [1, 2]); track itm; let index = $index) {<li>{{itm.text}}</li>}</ul>`',
);
});
it('should migrate with an index alias with no spaces', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of items; let index=index">{{itm.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of items; track itm; let index = $index) {<li>{{itm.text}}</li>}</ul>`',
);
});
it('should migrate with alias declared with as', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of items; index as myIndex">{{itm.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of items; track itm; let myIndex = $index) {<li>{{itm.text}}</li>}</ul>`',
);
});
it('should migrate with alias declared with a comma-separated `as` expression', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of items, index as myIndex">{{itm.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of items; track itm; let myIndex = $index) {<li>{{itm.text}}</li>}</ul>`',
);
});
it('should not generate aliased variables declared via the `as` syntax with the same name as the original', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<div *ngFor="let item of items; index as $index;">{{$index}}</div>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'}, {id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `@for (item of items; track item) {<div>{{$index}}</div>}`',
);
});
it('should not generate aliased variables declared via the `let` syntax with the same name as the original', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<div *ngFor="let item of items; let $index = index">{{$index}}</div>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'}, {id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `@for (item of items; track item) {<div>{{$index}}</div>}`',
);
});
it('should migrate with a trackBy function and an aliased index', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of items; trackBy: trackMeFn; index as i">{{itm.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of items; track trackMeFn(i, itm); let i = $index) {<li>{{itm.text}}</li>}</ul>`',
);
}); | {
"end_byte": 59180,
"start_byte": 52084,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts"
} |
angular/packages/core/schematics/test/control_flow_migration_spec.ts_59186_66122 | it('should migrate with multiple aliases', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of items; let count = count; let first = first; let last = last; let ev = even; let od = odd;">{{itm.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of items; track itm; let count = $count; let first = $first; let last = $last; let ev = $even; let od = $odd) {<li>{{itm.text}}</li>}</ul>`',
);
});
it('should remove unneeded ng-containers', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ng-container *ngFor="let item of items"><p>{{item.text}}</p></ng-container>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `@for (item of items; track item) {<p>{{item.text}}</p>}`',
);
});
it('should leave ng-containers with additional attributes', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ng-container *ngFor="let item of items" [bindMe]="stuff"><p>{{item.text}}</p></ng-container>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `@for (item of items; track item) {<ng-container [bindMe]="stuff"><p>{{item.text}}</p></ng-container>}`',
);
});
it('should migrate a nested class', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
function foo() {
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let item of items">{{item.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (item of items; track item) {<li>{{item.text}}</li>}</ul>`',
);
});
it('should migrate a nested class', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
function foo() {
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let item of items">{{item.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (item of items; track item) {<li>{{item.text}}</li>}</ul>`',
);
});
it('should migrate an ngFor with quoted semicolon in expression', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of '1;2;3'">{{itm}}</li></ul>\`
})
class Comp {}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
"template: `<ul>@for (itm of '1;2;3'; track itm) {<li>{{itm}}</li>}</ul>`",
);
});
it('should migrate an ngFor with quoted semicolon in expression', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of '1,2,3'">{{itm}}</li></ul>\`
})
class Comp {}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
"template: `<ul>@for (itm of '1,2,3'; track itm) {<li>{{itm}}</li>}</ul>`",
);
});
it('should migrate ngForTemplate', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<ng-container *ngFor="let item of things; template: itemTemplate"></ng-container>`,
`<ng-container *ngFor="let item of items; template: itemTemplate"></ng-container>`,
`<ng-template #itemTemplate let-item>`,
` <p>Stuff</p>`,
`</ng-template>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`@for (item of things; track item) {`,
` <ng-container *ngTemplateOutlet="itemTemplate; context: {$implicit: item}"></ng-container>`,
`}`,
`@for (item of items; track item) {`,
` <ng-container *ngTemplateOutlet="itemTemplate; context: {$implicit: item}"></ng-container>`,
`}`,
`<ng-template #itemTemplate let-item>`,
` <p>Stuff</p>`,
`</ng-template>`,
].join('\n');
expect(actual).toBe(expected);
}); | {
"end_byte": 66122,
"start_byte": 59186,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts"
} |
angular/packages/core/schematics/test/control_flow_migration_spec.ts_66128_67167 | it('should migrate ngForTemplate when template is only used once', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<ng-container *ngFor="let item of items; template: itemTemplate"></ng-container>`,
`<ng-template #itemTemplate let-item>`,
` <p>Stuff</p>`,
`</ng-template>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [`@for (item of items; track item) {`, ` <p>Stuff</p>`, `}\n`].join('\n');
expect(actual).toBe(expected);
});
}); | {
"end_byte": 67167,
"start_byte": 66128,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts"
} |
angular/packages/core/schematics/test/control_flow_migration_spec.ts_67171_74974 | describe('ngForOf', () => {
it('should migrate a basic ngForOf', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor,NgForOf],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<tbody>`,
` <ng-template ngFor let-rowData [ngForOf]="things">`,
` <tr><td>{{rowData}}</td></tr>`,
` </ng-template>`,
`</tbody>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`<tbody>`,
` @for (rowData of things; track rowData) {`,
` <tr><td>{{rowData}}</td></tr>`,
` }`,
`</tbody>`,
].join('\n');
expect(actual).toBe(expected);
});
it('should migrate ngForOf with an alias', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor,NgForOf],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<tbody>`,
` <ng-template ngFor let-rowData let-rowIndex="index" [ngForOf]="things">`,
` <tr><td>{{rowIndex}}</td><td>{{rowData}}</td></tr>`,
` </ng-template>`,
`</tbody>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`<tbody>`,
` @for (rowData of things; track rowData; let rowIndex = $index) {`,
` <tr><td>{{rowIndex}}</td><td>{{rowData}}</td></tr>`,
` }`,
`</tbody>`,
].join('\n');
expect(actual).toBe(expected);
});
it('should migrate ngForOf with track by', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor,NgForOf],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<tbody>`,
` <ng-template ngFor let-rowData [ngForOf]="things" [ngForTrackBy]="trackMe">`,
` <tr><td>{{rowData}}</td></tr>`,
` </ng-template>`,
`</tbody>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`<tbody>`,
` @for (rowData of things; track trackMe($index, rowData)) {`,
` <tr><td>{{rowData}}</td></tr>`,
` }`,
`</tbody>`,
].join('\n');
expect(actual).toBe(expected);
});
it('should migrate ngForOf with track by and alias', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor,NgForOf],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<tbody>`,
` <ng-template ngFor let-rowData let-rowIndex="index" [ngForOf]="things" [ngForTrackBy]="trackMe">`,
` <tr><td>{{rowIndex}}</td><td>{{rowData}}</td></tr>`,
` </ng-template>`,
`</tbody>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`<tbody>`,
` @for (rowData of things; track trackMe(rowIndex, rowData); let rowIndex = $index) {`,
` <tr><td>{{rowIndex}}</td><td>{{rowData}}</td></tr>`,
` }`,
`</tbody>`,
].join('\n');
expect(actual).toBe(expected);
});
it('should migrate ngFor with a long ternary and trackby', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor,NgForOf],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<div`,
` *ngFor="`,
` let item of section === 'manage'`,
` ? filteredPermissions?.manage`,
` : section === 'customFields'`,
` ? filteredPermissions?.customFields`,
` : section === 'createAndDelete'`,
` ? filteredPermissions?.createAndDelete`,
` : filteredPermissions?.team;`,
` trackBy: trackById`,
` "`,
`>`,
` {{ item }}`,
`</div>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`@for (`,
` item of section === 'manage'`,
` ? filteredPermissions?.manage`,
` : section === 'customFields'`,
` ? filteredPermissions?.customFields`,
` : section === 'createAndDelete'`,
` ? filteredPermissions?.createAndDelete`,
` : filteredPermissions?.team; track trackById($index,`,
` item)) {`,
` <div`,
` >`,
` {{ item }}`,
` </div>`,
`}`,
].join('\n');
expect(actual).toBe(expected);
});
it('should migrate ngForOf with track by and multiple aliases', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor,NgForOf],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<tbody>`,
` <ng-template ngFor let-rowData let-rowIndex="index" let-rCount="count" [ngForOf]="things" [ngForTrackBy]="trackMe">`,
` <tr><td>{{rowIndex}}</td><td>{{rowData}}</td></tr>`,
` </ng-template>`,
`</tbody>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`<tbody>`,
` @for (rowData of things; track trackMe(rowIndex, rowData); let rowIndex = $index; let rCount = $count) {`,
` <tr><td>{{rowIndex}}</td><td>{{rowData}}</td></tr>`,
` }`,
`</tbody>`,
].join('\n');
expect(actual).toBe(expected);
});
}); | {
"end_byte": 74974,
"start_byte": 67171,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/test/control_flow_migration_spec.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.